repo_name
stringlengths 7
111
| __id__
int64 16.6k
19,705B
| blob_id
stringlengths 40
40
| directory_id
stringlengths 40
40
| path
stringlengths 5
151
| content_id
stringlengths 40
40
| detected_licenses
list | license_type
stringclasses 2
values | repo_url
stringlengths 26
130
| snapshot_id
stringlengths 40
40
| revision_id
stringlengths 40
40
| branch_name
stringlengths 4
42
| visit_date
timestamp[ns] | revision_date
timestamp[ns] | committer_date
timestamp[ns] | github_id
int64 14.6k
687M
⌀ | star_events_count
int64 0
209k
| fork_events_count
int64 0
110k
| gha_license_id
stringclasses 12
values | gha_fork
bool 2
classes | gha_event_created_at
timestamp[ns] | gha_created_at
timestamp[ns] | gha_updated_at
timestamp[ns] | gha_pushed_at
timestamp[ns] | gha_size
int64 0
10.2M
⌀ | gha_stargazers_count
int32 0
178k
⌀ | gha_forks_count
int32 0
88.9k
⌀ | gha_open_issues_count
int32 0
2.72k
⌀ | gha_language
stringlengths 1
16
⌀ | gha_archived
bool 1
class | gha_disabled
bool 1
class | content
stringlengths 10
2.95M
| src_encoding
stringclasses 5
values | language
stringclasses 1
value | is_vendor
bool 2
classes | is_generated
bool 2
classes | length_bytes
int64 10
2.95M
| extension
stringclasses 19
values | num_repo_files
int64 1
202k
| filename
stringlengths 4
112
| num_lang_files
int64 1
202k
| alphanum_fraction
float64 0.26
0.89
| alpha_fraction
float64 0.2
0.89
| hex_fraction
float64 0
0.09
| num_lines
int32 1
93.6k
| avg_line_length
float64 4.57
103
| max_line_length
int64 7
931
|
---|---|---|---|---|---|---|---|---|---|---|---|---|---|---|---|---|---|---|---|---|---|---|---|---|---|---|---|---|---|---|---|---|---|---|---|---|---|---|---|---|---|---|---|---|---|---|
VVILD/sendd | 3,040,836,862,992 | d9b1aa106f0b7e351967a11e31b262b7ece88e32 | 99fb1fa5262bc8a701ca4407d833b0134c62d5e0 | /core/utils/track_request_test.py | d8a22819af4b3c867629f0df466768faaa1f663b | []
| no_license | https://github.com/VVILD/sendd | 0dd2f83e9acb30cd1b7b523bf6e4df06db0c6442 | 96d6dc3a84e826c59a506a93d2cb16d5c684d10a | refs/heads/master | 2021-03-19T12:13:51.916905 | 2015-12-07T13:46:45 | 2015-12-07T13:46:45 | 33,768,401 | 0 | 0 | null | null | null | null | null | null | null | null | null | null | null | null | null | __author__ = 'vatsalshah'
#!/usr/bin/env python
"""
This example shows how to track shipments.
"""
import logging
from ..fedex.config import FedexConfig
from ..fedex.services.track_service import FedexTrackRequest
# Set this to the INFO level to see the response from Fedex printed in stdout.
logging.basicConfig(level=logging.INFO)
# Change these values to match your testing account/meter number.
CONFIG_OBJ = FedexConfig(key='jFdC6SAqFS9vz7gY',
password='6bxCaeVdszjUo2iHw5R3tbrBu',
account_number='677853204',
meter_number='108284345',
use_test_server=False)
# NOTE: TRACKING IS VERY ERRATIC ON THE TEST SERVERS. YOU MAY NEED TO USE
# PRODUCTION KEYS/PASSWORDS/ACCOUNT #.
# We're using the FedexConfig object from example_config.py in this dir.
track = FedexTrackRequest(CONFIG_OBJ)
track.TrackPackageIdentifier.Type = 'TRACKING_NUMBER_OR_DOORTAG'
track.TrackPackageIdentifier.Value = '781617896139'
track.IncludeDetailedScans = False
# Fires off the request, sets the 'response' attribute on the object.
track.send_request()
# track.request
# See the response printed out.
print track.response
# Look through the matches (there should only be one for a tracking number
# query), and show a few details about each shipment.
# print "== Results =="
# for match in track.response.TrackDetails:
# print "Tracking #:", match.TrackingNumber
# print "Status:", match.StatusDescription
# print "Estimated Delivery:", match.EstimatedDeliveryTimestamp | UTF-8 | Python | false | false | 1,566 | py | 109 | track_request_test.py | 76 | 0.722861 | 0.699234 | 0 | 43 | 35.44186 | 78 |
RandomGamer123/TheBrainOfTWOWCentral | 13,202,729,478,487 | 42aed4169ae6cc10f81dd314d58f82074c0cdac1 | 9dc0ff36610128728af64003f9d9f18ea5089cd3 | /Commands/idtime.py | dbbcc58b13a438ebd81afda1c67094e385cc1609 | [
"MIT"
]
| permissive | https://github.com/RandomGamer123/TheBrainOfTWOWCentral | 46bd5efba383438fb0939511006b485386678525 | f29e7268b97c77309f52821525b5776ef11707b2 | refs/heads/master | 2022-12-12T18:35:53.796133 | 2020-09-03T00:02:32 | 2020-09-03T00:02:32 | 292,417,015 | 0 | 0 | null | true | 2020-09-02T23:32:38 | 2020-09-02T23:32:37 | 2020-08-31T21:35:46 | 2020-08-31T21:35:43 | 39,111 | 0 | 0 | 0 | null | false | false | import discord, datetime
def HELP(PREFIX):
return {
"COOLDOWN": 1,
"MAIN": "Finds the time corresponding to a Discord snowflake (ID).",
"FORMAT": "[id] (id2) (mode)",
"CHANNEL": 0,
"USAGE": f"""Using `{PREFIX}idtime` will return the time corresponding to the provided Discord
snowflake. "message" or "user" can replace numeric IDs to use the ID of your message or your account
respectively. Two IDs can be included instead of one to calculate the difference in time between
them. A mode (timestamp, unix) can be specified at the end to display the resulting time in.
""".replace("\n", "").replace("\t", ""),
"CATEGORY" : "Utility"
}
PERMS = 0 # Non-members
ALIASES = []
REQ = []
async def MAIN(message, args, level, perms, SERVER):
if level == 1:
await message.channel.send("Include the ID you would like to find the time of.")
else:
snowflake_list = []
format_list = []
unix_list = []
if level > 1:
mode = "n/a"
for elem in args[1:]:
try:
snowflake_list.append(int(elem))
except ValueError:
if elem == "message":
snowflake_list.append(message.id)
elif elem == "user":
snowflake_list.append(message.author.id)
else:
mode = elem
break
if mode not in ["timestamp", "unix"]:
mode = "timestamp"
else:
snowflake_list = [int(args[1])]
mode = "timestamp"
output = ""
snowflake_list = snowflake_list[:2]
for snowflake in snowflake_list:
if snowflake > 18446744073709551615 or snowflake < 0:
snowflake_list.remove(snowflake)
continue
snowflaketime = bin(snowflake)[2:].zfill(64)
snowflaketime = snowflaketime[:42]
snowflaketime = (int(snowflaketime, 2) + 1420070400000)/1000
unix_list.append(snowflaketime)
if mode == "timestamp":
ft = str(datetime.datetime.fromtimestamp(snowflaketime))
if ft.endswith("000"):
ft = ft[:-3]
else:
ft = ft + ".000"
format_list.append(ft + " UTC")
elif mode == "unix":
format_list.append(str(snowflaketime))
for i in range(len(snowflake_list)):
output += (str(snowflake_list[i]) + " → **" + format_list[i] + "**")
output += "\n"
if len(snowflake_list) > 1:
ds = abs(unix_list[0] - unix_list[1])
diff = []
for increment in [86400, 3600, 60]:
diff.append(round(ds - ds % increment) // increment)
ds = ds % increment
diff.append(round(ds, 3))
diff[0] = str(diff[0])
diff[1] = str(diff[1]).zfill(2)
diff[2] = str(diff[2]).zfill(2)
sec = str(diff[3]).split(".")
diff[3] = sec[0].zfill(2) + "." + sec[1].ljust(3, '0')
output += "Difference: **" + (":".join(diff)).lstrip("0:") + "**"
elif len(snowflake_list) == 0:
await message.channel.send("Invalid ID.")
return
await message.channel.send(output)
return | UTF-8 | Python | false | false | 2,760 | py | 45 | idtime.py | 43 | 0.628716 | 0.595359 | 0 | 85 | 31.458824 | 103 |
micheledallatorre/soaring_club | 18,554,258,760,900 | 981d4e77600b55281369d1f2e72fc74d6caa4e3a | b7aced6770c732b8695faf44810c68c1c70aee5a | /soaring_club/apps/aircraftlogger/views.py | b3a17a0c15d89e37b2b02fdbdf17516f518a60a4 | []
| no_license | https://github.com/micheledallatorre/soaring_club | 9088834acef4205d71844c30f5815b4af424c360 | c481cc5f761598c8f305eeccb731443527c9c652 | refs/heads/master | 2021-01-16T23:15:29.501904 | 2016-06-16T15:45:47 | 2016-06-16T15:45:47 | 61,134,627 | 0 | 0 | null | true | 2016-06-14T15:33:23 | 2016-06-14T15:33:22 | 2016-06-14T15:18:02 | 2012-07-15T23:40:45 | 1,640 | 0 | 0 | 0 | null | null | null | from django.http import HttpResponse, Http404
from django.db.models import Q #@UnusedImport
from django.shortcuts import render
from django.shortcuts import redirect
from django.shortcuts import get_object_or_404
from django.contrib.auth.decorators import login_required
from django.utils.translation import ugettext_lazy as _
from django.core.paginator import Paginator, InvalidPage, EmptyPage
from django.core.exceptions import ObjectDoesNotExist #@UnusedImport
from django.conf import settings #@UnusedImport
from django.views.generic import View
from django.views.generic.edit import FormMixin
from django.utils import simplejson as json
from django.template.loader import get_template
from django.template import TemplateDoesNotExist
import decimal
import towerlog
from django.utils.log import getLogger
from forms import * #@UnusedWildImport
from models import * #@UnusedWildImport
logger = getLogger('app')
class JSONResponseMixin(object):
def render_to_response(self, context):
"Returns a JSON response containing 'context' as payload"
return self.get_json_response(self.convert_context_to_json(context))
def get_json_response(self, content, **httpresponse_kwargs):
"Construct an `HttpResponse` object."
return HttpResponse(content,
content_type='application/json',
**httpresponse_kwargs)
def convert_context_to_json(self, context):
"Convert the context dictionary into a JSON object"
# Note: This is *EXTREMELY* naive; in reality, you'll need
# to do much more complex handling to ensure that arbitrary
# objects -- such as Django model instances or querysets
# -- can be serialized as JSON.
return json.dumps(context)
class JSONFormView(FormMixin, View, JSONResponseMixin):
success_message = ''
def form_valid(self, form, request):
form.save()
return self.success(_(self.success_message))
def form_invalid(self, form):
response = SimpleResponse()
response.setError(_("Validation failed."))
response.setData(form.errors)
return self.render_to_response(response.json())
def success(self, message):
response = SimpleResponse()
response.setSuccess(message)
return self.render_to_response(response.json())
def get(self, request, *args, **kwargs):
raise Http404
def post(self, request, *args, **kwargs):
form = self.get_form(self.get_form_class()) #@UnusedVariable
class SimpleResponse(object):
"""
The simplest form of our ajax response
"""
def __init__(self, error=False, message=None):
self.error = error
self.message = message
self.data = {}
def setError(self, message):
self.error = True
self.message = message
def setSuccess(self, message):
self.error = False
self.message = message
def setData(self,data={}):
self.data = data.copy()
def json(self):
return {'error': self.error,
'message': self.message,
'data':self.data
}
def get_planes_from_flarm(flarm_id, date=None):
"""
Get the planes with a particolar flarm installed. If date is specified
select only planes that don't removed flarm until that date
"""
planes = Plane.objects.filter( Q(installation__flarmid__iexact=flarm_id))
if planes and date:
planes.filter(Q(installation__date_added__lte=date),
Q(installation__date_removed__gte=date) |
Q(installation__date_removed__isnull=True)
)
return planes
def get_current_member(request, stuff_allowed=True):
"""
Get the current logged member or if the user is staff the member choosed
via cookie
"""
member = None
if request.user.is_authenticated():
if request.session.get('member', False) and stuff_allowed and request.user.is_staff:
member = request.session['member']
#Is there a better solution to check if user has an associated member?
elif request.user.member.count():
member = request.user.member.get()
return member
def index(request):
"""
Main page.
Show login botton or memebr status after login.
"""
membercredit = tow_cents = tmg_cents = tow_good_status = tmg_good_status = None
member = get_current_member(request)
balance = []
if member:
membercredit = member.membercredit_or_none
for cls, dsc in CREDIT_CLASSES:
b = member.balance(cls)
if b:
balance.append((dsc,b,b>0))
tow_cents = member.tow_cents_balance()
if tow_cents > 0:
tow_good_status = True
tmg_cents = member.tmg_cents_balance()
if tmg_cents > 0:
tmg_good_status = True
logged = request.user
else:
logged = False
return render(request, 'index.html', {'logged' : logged,
'member' : member,
'membercredit' : membercredit,
'balance' : balance,
'tow_cents' : tow_cents,
'tow_good_status' : tow_good_status,
'tmg_cents' : tmg_cents,
'tmg_good_status' : tmg_good_status,
})
def display_meta(request):
values = request.META.items()
values.sort()
html = []
for k, v in values:
html.append('<tr><td>%s</td><td>%s</td></tr>' % (k, v))
return HttpResponse('<table>%s</table>' % '\n'.join(html))
def logs(request):
"""
This view show flights logged in one Tower Station log file and permit to add them to Flights object
"""
if request.method == 'POST':
#A form has been submitted
if request.POST.has_key('file_log'):
log_selection = TowerLogForm(request.POST)
if log_selection.is_valid():
tower_log = get_object_or_404(TowerLog,
id=log_selection.cleaned_data['file_log'])
nome = tower_log.log_file.name
nmea = towerlog.TowerLog()
nmea.process_file(tower_log.log_file)
logs = sorted(list(nmea.generate_log_book()), key=lambda record: record[2])
for log in logs:
planes = get_planes_from_flarm(log[1])
log.append(planes)
return render(request, 'logs.html', {
'log_selection': log_selection,
'nome': nome,
'logs': logs})
else:
if request.POST.has_key('flights'):
flights = request.POST.getlist('flights')
flights = [ fly.split(',') for fly in flights ]
debug_print('to flights.html--->',flights)
return render(request, 'flights.html',
{
'flights': flights,
})
log_selection = TowerLogForm()
return render(request, 'logs.html', {'log_selection': log_selection})
def member_flights(role, member, request, paginator=None):
flights_missing = flights_durations = first_date = flights_page = flights_from = flights_to = None
flights_list = []
form_range_flights = DateRangeForm()
form_year = YearChooseForm()
if member:
if request.method == 'POST' and request.POST.has_key('from_date'):
form_range_flights = DateRangeForm(request.POST)
if form_range_flights.is_valid():
flights_from = form_range_flights.cleaned_data['from_date']
flights_to = form_range_flights.cleaned_data['to_date']
try:
first_date = member.first_flight_date(role, flights_from, flights_to)
flights_list = member.active_flights(role, flights_from, flights_to)
flights_missing = member.flights_missing_time_landing(role, flights_from, flights_to).count()
flights_durations = member.flights_durations(role, flights_from, flights_to)
except (AttributeError, TypeError):
pass
# Make sure page request is an int. If not, deliver first page.
page = request.GET.get('page')
try:
page = int(page)
except (ValueError, TypeError):
if page != 'all':
page = 1
# If page request (9999) is out of range, deliver last page of results.
if page == 'all':
flights_page = flights_list
is_paginated = True,
paginator = Paginator(flights_list, flights_list.count())
page = 1
else:
is_paginated = True,
paginator = Paginator(flights_list, 50) # Show 25 contacts per page
try:
flights_page = paginator.page(page)
except (EmptyPage, InvalidPage):
flights_page = paginator.page(paginator.num_pages)
return {'role': role,
'flights': flights_page,
'is_paginated': is_paginated,
'paginator': paginator,
'member' : member,
'flights_no': flights_list.count(),
'flights_durations': flights_durations,
'flights_missing': flights_missing,
'first_date': first_date,
'hits' : flights_list.count(),
'page': page,
'pages': paginator.num_pages,
'results_per_page': paginator.per_page,
'next' : flights_page.next_page_number(),
'previous' : flights_page.previous_page_number(),
'has_next' : flights_page.has_next(),
'has_previous' : flights_page.has_previous(),
'form_range_flights' : form_range_flights,
'form_year' : form_year,
}
@login_required
def flights(request, role='pilot'):
member = get_current_member(request)
return render(request, 'flights.html', member_flights(role, member, request))
@login_required
def flights_bills(request):
"""
List flights_bills
"""
first_date = bills_from = bills_to = None
bills_list = []
member = get_current_member(request)
form_range_flightbills = DateRangeForm()
if member:
if request.method == 'POST' and request.POST.has_key('from_date'):
form_range_flightbills = DateRangeForm(request.POST)
if form_range_flightbills.is_valid():
bills_from = form_range_flightbills.cleaned_data['from_date']
bills_to = form_range_flightbills.cleaned_data['to_date']
try:
first_date = member.first_flightbill_date(bills_from, bills_to)
bills_list = member.active_flightbills(bills_from, bills_to)
debits = {}
for cls, dsc in CREDIT_CLASSES:
debits[dsc] = member.debit(cls, bills_from, bills_to)
except (AttributeError, TypeError):
pass
return render(request,
'flights_bills.html',
{
'member' : member,
'hits' : bills_list.count(),
'first_date': first_date,
'bills_list': bills_list,
'debits' : debits,
'form_range_flightbills' : form_range_flightbills,
}
)
@login_required
def update_flight_landing(request, flight_id):
"""
Allow user or staff to update landing information for single flight
TODO: allow staff to update all info
"""
member = get_current_member(request, stuff_allowed=False)
if member:
flight = get_object_or_404(Flight, pk=flight_id)
if flight in member.pilot.all() or request.user.is_staff:
form_saved = None
if request.method == 'POST':
form = FlightLandingForm(request.POST)
if form.is_valid():
flight.landing = form.cleaned_data['landing']
flight.landing_field = form.cleaned_data['landing_field']
flight.save()
form_saved = True
return render(request, 'flight_update_landing.html', {'form_saved':form_saved, 'flight':flight, 'form':form})
else:
context = {'flight_id': flight.id}
if flight.landing:
context['landing'] = flight.landing
if flight.landing_field:
context['landing_field'] = flight.landing_field
form = FlightLandingForm()
return render(request, 'flight_update_landing.html', {'form_saved':form_saved, 'flight':flight, 'form':form})
else:
return redirect('/flights/')
else:
return redirect('/')
@login_required
def receipts(request):
return render(request, 'receipts.html', member_receipts(get_current_member(request)) )
@login_required
def update_receipt_note(request, receipt_id):
if request.user.is_authenticated():
if request.user.member.count():
member = request.user.member.get()
receipt = get_object_or_404(Receipt, pk=receipt_id)
if receipt in member.receipt_payer.all() or request.user.is_staff:
if request.method == 'POST':
form_saved = None
form = ReceiptNoteForm(request.POST)
if form.is_valid():
note = form.cleaned_data['note']
receipt.note = note
receipt.updated_by = request.user
receipt.save()
form_saved = True
return render(request, 'receipt_update_note.html', {'form_saved':form_saved, 'receipt':receipt, 'form':form})
else:
context = {'note': receipt.note}
form = ReceiptNoteForm(context)
return render(request, 'receipt_update_note.html', {'receipt':receipt, 'form':form})
else:
return redirect('/receipts/')
else:
return redirect('/')
class ReceiptRangeView(JSONFormView):
form_class = ReceiptRangeForm
success_message="FATTO!!"
@login_required
def reports(request, action=None, template=None):
"""
This view render the 'Report' tab. The URL that is responding to is /reports/action.
action can be 'debits' for retrieving cents balance, 'receipts' for get a list of
receipts in an interval, 'member' to impersonate a member for viewing flights etc..,
'clearance' to retrieve a list of pilots permitted to flight.
"""
#TODO: change word debits in balance
if request.user.is_authenticated():
if request.user.is_staff:
logged = request.user
form_range_receipts = ReceiptRangeForm()
form_member = MemberChooseForm()
form_debits_filter = DebitsForm(initial={'status_filter' : 'Active'})
context = {'logged' : logged,
'form_debits_filter': form_debits_filter,
'form_range_receipts': form_range_receipts,
'form_member': form_member,
'club_limit':settings.MAX_DAYS_FROM_LAST_FLIGHT_CLUB.days,
'private_limit':settings.MAX_DAYS_FROM_LAST_FLIGHT_PRIVATE.days,
}
if request.method == 'POST':
if action == 'debits':
#Form for filter debits
form_debits_filter = DebitsForm(request.POST)
#Retrieve data only if request is for results template
if not request.is_ajax() or template == "debits_table":
# tourism, glider tow, motorglider, etc... may be there is a better method to do this...
if form_debits_filter.is_valid():
#Check what button was pressed and apply related filter to members
if form_debits_filter.cleaned_data['status_filter'] == 'Active':
report = debits_report(~Q(type__type__exact='inactive'))
elif form_debits_filter.cleaned_data['status_filter'] == 'Registered':
report = debits_report(Q(type__type__exact='registered'))
else:
report = debits_report()
#Filter report with a credit lesser than settings.MIN_CREDIT in any type of balance:
if form_debits_filter.cleaned_data['only_negative']:
new_report = []
for r in report:
for dsc, d in r['debits']:
if d < settings.MIN_CREDIT:
new_report += [r]
break
report = new_report
totals = []
#Compute totals for every credit classes
for cls,dsc in CREDIT_CLASSES:
totals += ((dsc, sum([dict(r['debits'])[dsc] for r in report]),),)
context.update({
'debits': report,
'totals': totals,
})
else:
if request.is_ajax():
template = 'blank'
elif action == 'receipts':
#refresh form with POST data
form_range_receipts = ReceiptRangeForm(request.POST)
#Retrieve data only if request is for results template
if not request.is_ajax() or template == "receipts_table":
if form_range_receipts.is_valid():
reference_from = form_range_receipts.cleaned_data['reference_from']
reference_to = form_range_receipts.cleaned_data['reference_to']
receipt_from = Receipt.objects.get(reference=reference_from)
receipt_to = Receipt.objects.get(reference=reference_to)
try:
from_int = int(reference_from)
to_int = int(reference_to)
except ValueError:
from_int = to_int = None
receipts = []
if from_int and to_int:
for ref in range(from_int,to_int+1):
try:
r = Receipt.objects.get(reference=str(ref))
except ObjectDoesNotExist:
r = None
if r:
receipts.append(r)
if not receipts:
receipts = Receipt.objects.filter(date__lte=receipt_to.date, date__gte=receipt_from.date)
total = 0
for receipt in receipts:
total += receipt.total
context.update({
'total':total,
'receipts':receipts,
'from':receipt_from.date,
'to':receipt_to.date,
})
else:
if request.is_ajax():
template = 'blank'
elif action == 'member':
#refresh form with POST data
form_member = MemberChooseForm(request.POST)
#Check if request is for results or for refreshing form
#Retrieve data only if request is for results template
if not request.is_ajax() or template == "member_table":
if form_member.is_valid():
member = form_member.cleaned_data['member']
request.session['member'] = member
context.update({'member':member})
else:
#form is invalid, clear results
if request.is_ajax():
template = 'blank'
elif action == 'clearance':
#There's no need to update form but for avoid data retrieve when call is for form only
#check is done
#Retrieve data only if request is for results template
logger.debug("clearance action with path=%s is_ajax=%s template=%s" % (request.get_full_path(),request.is_ajax(), template))
if not request.is_ajax() or template == "clearance_table":
logger.debug("clearance report")
report = clearance_report()
context.update({
'clearance': report,
})
#Update form values
context.update({
'form_debits_filter': form_debits_filter,
'form_range_receipts': form_range_receipts,
'form_member': form_member,
})
if template is None:
template='reports.html'
else:
try:
template += '.html'
get_template(template)
except TemplateDoesNotExist:
template='reports.html'
logger.debug(" with request=%s context=%s template=%s" % (request.get_full_path(), context, template))
return render(request, template, context)
return redirect('/')
def set_member(request, member_id):
member = Member.objects.get(pk=member_id)
request.session['member'] = member
return redirect('/')
def member_receipts(member):
receipts = total = tow_cents = tmg_cents = first_date = None
if member:
try:
receipts = member.active_receipts()
tow_cents = member.tow_cents_aquired()
tmg_cents = member.tmg_cents_aquired()
total = Receipt.objects.user_total(member.id)
first_date = member.first_receipt_date()
_credits = []
for cls, dsc in CREDIT_CLASSES:
_credits += ( (dsc, member.credit(cls)), )
except (AttributeError, TypeError):
pass
return {
'total':total,
'tow_cents':tow_cents,
'tmg_cents':tmg_cents,
'credits':_credits,
'first_date':first_date,
'receipts': receipts,
'member': member,
}
@login_required
def flights_sheet_submit(request, form, formset, head, flights):
logged = request.user
if logged.is_staff:
return render(request, 'flights_sheet.html', {'form':form, 'formset': formset})
else:
return redirect('/')
@login_required
def flights_sheet(request):
logged = request.user
saved = False
if logged.is_staff:
if request.method == 'POST':
form = FlightsSheet(request.POST)
formset = FlightsSheetItemSet(request.POST)
if form.is_valid() and formset.is_valid():
head = form.cleaned_data
flights = formset.cleaned_data
flight = flights[0]
#Set the scale for conversion if unit of tow is minutes
if head['counter_unit'] == 'minutes':
scale = decimal.Decimal(str(100.0/60.0))
else:
scale = 1
#Cerca il socio fittizio che corrisponde al CUS
payer = Member.objects.get(last_name__exact='CUS')
#il riscaldamento se c'e' viene contaggiato come volo di servizio
#ed imputato a cus. Il volo inizia e termina con l'orario di decollo del primo volo.
if head['warmup_cost']:
tow_flight = Flight(date=head['date'],
takeoff=flight['takeoff'],
takeoff_field='LIDT',
landing=flight['takeoff'],
landing_field='LIDT',
pilot=head['pilot'],
copilot=None,
plane=head['tow'],
porpouse='riscaldamento')
tow_flight.save()
bill = FlightBill(flight = tow_flight,
tow_flight = None,
payer = payer,
cost = head['warmup_cost']*scale,
cost_class = 'service')
bill.save()
for flight in flights:
if flight:
glider_flight = Flight(date=head['date'],
takeoff=flight['takeoff'],
takeoff_field='LIDT',
landing=flight['landing_glider'],
landing_field='LIDT',
pilot=flight['pilot'],
copilot=flight['instructor'],
plane=flight['glider'],
porpouse=flight['porpouse'])
glider_flight.save()
if 'scheda' in flight['porpouse']:
porpouse = 'traino scuola'
else:
porpouse = 'traino'
tow_flight = Flight(date=head['date'],
takeoff=flight['takeoff'],
takeoff_field='LIDT',
landing=flight['landing'],
landing_field='LIDT',
pilot=head['pilot'],
copilot=None,
plane=head['tow'],
porpouse=porpouse)
tow_flight.save()
bill = FlightBill(flight = tow_flight,
tow_flight = glider_flight,
payer = flight['pilot'],
cost = flight['tow_cost']*scale,
cost_class = 'towing')
bill.save()
saved = True
return render(request, 'flights_sheet.html', {'form':form, 'formset': formset, 'saved':saved})
else:
form = FlightsSheet()
formset = FlightsSheetItemSet()
return render(request, 'flights_sheet.html', {'form':form, 'formset': formset, 'saved':saved})
else:
return redirect('/')
# def update_flight(request, object_id):
# return update_object(request, object_id=object_id, model=Flight, extra_context={'flight':get_object_or_404(Flight, pk=object_id)})
def flarm_db(request, flarm_id=None, date=None):
if flarm_id and date:
planes = get_planes_from_flarm(flarm_id, date)
return render(request, 'flarms.html', {'planes':planes})
elif flarm_id:
planes = get_planes_from_flarm(flarm_id)
return render(request, 'flarms.html', {'planes':planes})
else:
planes = Plane.objects.filter(installation__id__isnull=False)
return render(request, 'flarms.html', {'planes':planes})
| UTF-8 | Python | false | false | 29,282 | py | 76 | views.py | 30 | 0.497302 | 0.495697 | 0 | 653 | 43.839204 | 144 |
swapsha96/jwst | 4,312,147,200,263 | ae9d42c732757d011c37b124336f049eb434df35 | 9f67986758d23aa25c5110150177e43ae710b543 | /jwst/datamodels/traps.py | 797a165ef7f3d9eaebb552a94acd75a427655ddc | [
"BSD-2-Clause"
]
| permissive | https://github.com/swapsha96/jwst | b589d6b2a7c17270accd666b9fe598f525bfde74 | ad260a6e65c9b98269273ccb3c7292256abea5ae | refs/heads/master | 2021-01-21T14:24:49.130271 | 2017-06-24T12:27:46 | 2017-06-24T12:27:46 | null | 0 | 0 | null | null | null | null | null | null | null | null | null | null | null | null | null | from __future__ import absolute_import, unicode_literals, division, print_function
from . import model_base
__all__ = ['TrapsModel']
class TrapsModel(model_base.DataModel):
"""
A data model for trap capture and decay.
Parameters
----------
init : any
Any of the initializers supported by `~jwst.datamodels.DataModel`.
traps_table : numpy array
A table with three columns for trap-capture parameters and one
column for the trap-decay timescale. Each row of the table is
for a different trap family.
"""
schema_url = "traps.schema.yaml"
def __init__(self, init=None, traps_table=None, **kwargs):
super(TrapsModel, self).__init__(init=init, **kwargs)
if traps_table is not None:
self.traps_table = traps_table
| UTF-8 | Python | false | false | 813 | py | 16 | traps.py | 7 | 0.643296 | 0.643296 | 0 | 29 | 27.034483 | 82 |
seanbehan/screenshotes | 5,497,558,151,128 | 7f033cebb3cb35898bcfca2bfcef6323eeb7df03 | 2e29a58c7f43e08d58dabe6c0eac1dfedb389775 | /library.py | e6d26762c7e27f0b40dd05b6b480bb249ffab93f | []
| no_license | https://github.com/seanbehan/screenshotes | 2963b44ee09547c39ee0a8d667b8fec2dbaa5b69 | 6efc4fb95496e133d5a96842abaa874de8018d54 | refs/heads/master | 2020-05-20T23:53:55.323281 | 2015-07-19T01:46:11 | 2015-07-19T01:46:11 | 37,335,505 | 1 | 0 | null | null | null | null | null | null | null | null | null | null | null | null | null | from selenium import webdriver
from selenium.webdriver.common.desired_capabilities import DesiredCapabilities
from hashlib import md5
from collections import OrderedDict
import os, datetime, urlparse
import requests
from os import environ as env
from uuid import uuid4
def _url(url):
if url.startswith('http'):
return url
try:
_https = 'https://%s' % url
requests.head(_https)
return _https
except:
pass
return 'http://%s' % url
def take_screenshot(opts):
url = _url(opts['url'])
width, height = opts['width'], opts['height']
background = opts['background']
data = OrderedDict()
dcap = dict(DesiredCapabilities.PHANTOMJS)
dcap["phantomjs.page.settings.userAgent"] = (
"Mozilla/5.0 (X11; Linux x86_64) AppleWebKit/53 "
"(KHTML, like Gecko) Chrome/15.0.87"
)
dcap['init.service_args'] = ('--web-security=false', '--ignore-ssl-errors=true', '--ssl-protocol=any')
driver = webdriver.PhantomJS(desired_capabilities=dcap,service_args=['--ignore-ssl-errors=true', '--ssl-protocol=any', '--web-security=false'])
driver.get(url)
driver.set_page_load_timeout(10)
driver.set_window_size(width, height)
data["title"] = driver.title
data["url"] = driver.current_url
data["screenshot"] = {}
file_name = "%s.png" % str(uuid4()) # md5(url).hexdigest()
file_path = "static/screenshots/%s" % file_name
full_url = "%s/%s" % (env.get("DOMAIN", 'http://localhost:5555'), file_path)
if background:
driver.execute_script("""(function() {
var style = document.createElement('style'), text = document.createTextNode('body { background: %s }');
style.setAttribute('type', 'text/css');
style.appendChild(text);
document.head.insertBefore(style, document.head.firstChild);
})();""" % background)
driver.save_screenshot(file_path)
driver.quit()
data["screenshot"]["url"] = full_url
data["screenshot"]["taken_at"] = str(datetime.datetime.now())
data["screenshot"]["size"] = os.path.getsize(str(file_path))
return data
| UTF-8 | Python | false | false | 2,134 | py | 7 | library.py | 2 | 0.639644 | 0.627929 | 0 | 62 | 33.419355 | 147 |
sarath1plaza/Quiz | 3,049,426,799,199 | 43cd5d7d2c52b186ac4bdc27b40495897c553d23 | 582c97e75dcceb4f590fcfc33a09984a19cb1b45 | /restapi/migrations/0002_auto_20191114_1811.py | b48141bc11804f69a9b47a756381cf27e27c655f | []
| no_license | https://github.com/sarath1plaza/Quiz | 9f605b3d6cee5fa90602d404d18602e82c6cafe0 | 57d7b0a0d90bb7aa0b6abe6fcd0ee35406d4ed8a | refs/heads/master | 2022-03-15T07:32:11.498762 | 2019-11-15T18:23:34 | 2019-11-15T18:23:34 | null | 0 | 0 | null | null | null | null | null | null | null | null | null | null | null | null | null | # Generated by Django 2.2.5 on 2019-11-14 18:11
from django.db import migrations
class Migration(migrations.Migration):
dependencies = [
('restapi', '0001_initial'),
]
operations = [
migrations.RenameModel(
old_name='logclass',
new_name='registartion',
),
]
| UTF-8 | Python | false | false | 327 | py | 10 | 0002_auto_20191114_1811.py | 8 | 0.58104 | 0.522936 | 0 | 17 | 18.235294 | 47 |
Cloudxtreme/MyProject | 18,897,856,126,021 | 8e824b9eb64afeb7ee6e8d79a67165c16b5fa4d4 | 3b786d3854e830a4b46ee55851ca186becbfa650 | /SystemTesting/pylib/vmware/kvm/api/default_setup_impl.py | eae559ffa2fcff11a7905c340ed5c55c7ae40926 | []
| no_license | https://github.com/Cloudxtreme/MyProject | d81f8d38684333c22084b88141b712c78b140777 | 5b55817c050b637e2747084290f6206d2e622938 | refs/heads/master | 2021-05-31T10:26:42.951835 | 2015-12-10T09:57:04 | 2015-12-10T09:57:04 | null | 0 | 0 | null | null | null | null | null | null | null | null | null | null | null | null | null | import lib.kvm as kvm
import lib.hypervisor as hypervisor
import vmware.interfaces.setup_interface as setup_interface
import vmware.common.global_config as global_config
pylogger = global_config.pylogger
kvm_objs = {}
REQUIRED_OVS_PKGS = ["openvswitch", "kmod-openvswitch"]
class DefaultSetupImpl(setup_interface.SetupInterface):
# TODO(salmanm): This should be sourced from the user input yaml.
DEFAULT_KVM_TEMPLATE = "template_kvm_debian"
@classmethod
def setup_3rd_party_library(cls, client_object=None):
"""
Method to initilize mh qe/lib.
@return kvm_obj: obj of the kvm host with client_object.ip
"""
global kvm_objs
if client_object.ip in kvm_objs:
return kvm_objs[client_object.ip]
kvm.Kvm.default_vm_template = cls.DEFAULT_KVM_TEMPLATE
pylogger.debug("setup_3rd_party_library for %s %s %s " %
(client_object.ip, client_object.username,
client_object.password))
host_keys_file = global_config.get_host_keys_file()
pylogger.debug("Loading ssh known_hosts key from %r" % host_keys_file)
kvm_obj = hypervisor.Hypervisor.get_hypervisor(
client_object.ip, user=client_object.username,
passwd=client_object.password, known_hosts_file=host_keys_file)
kvm_obj.connect(user=client_object.username,
passwd=client_object.password,
sync_br_external_ids=False,
expected_ovs_pkgs=REQUIRED_OVS_PKGS, no_verify=True)
kvm_objs[client_object.ip] = kvm_obj
return kvm_obj
| UTF-8 | Python | false | false | 1,648 | py | 2,856 | default_setup_impl.py | 1,843 | 0.646238 | 0.645024 | 0 | 39 | 41.25641 | 78 |
lihongqiang/cv-models | 14,869,176,792,072 | 0c2c16cf97c88e3450f8b3a34a1877cc03a467ae | 4903eee3b4987833f9bb27d56b56927d38267824 | /highwaynet.py | 5c96716a0a91411d3d59412d0d44cc177626c252 | []
| no_license | https://github.com/lihongqiang/cv-models | 213fefc7cb5c16183f36769ff1cf5012d04e3200 | c40bfef7dc79981ebcb6f4a677170fefe026fad2 | refs/heads/master | 2021-01-21T06:39:49.335429 | 2017-03-02T08:33:35 | 2017-03-02T08:33:35 | 83,269,085 | 1 | 1 | null | null | null | null | null | null | null | null | null | null | null | null | null | #!/usr/bin/env python2
# -*- coding: utf-8 -*-
"""
Created on Mon Feb 27 18:16:27 2017
@author: lhq
"""
#%%
import tflearn
import tensorflow as tf
X, Y, X_test, Y_test = tflearn.datasets.mnist.load_data(one_hot=True)
#%%
with tf.Graph().as_default():
input_data = tflearn.input_data(shape=[None, 28*28])
layer1 = tflearn.fully_connected(input_data, 64, activation='elu',
regularizer='L2', weight_decay=0.001)
dense = layer1
for i in range(10):
dense = tflearn.highway(dense, 64, activation='elu',
regularizer='L2', weight_decay=0.001,
transform_dropout=0.8)
softmax = tflearn.fully_connected(dense, 10, activation='softmax')
sgd = tflearn.optimizers.SGD(learning_rate=0.1, lr_decay=0.96, decay_step=1000)
topk = tflearn.metrics.top_k(3)
regression = tflearn.regression(softmax, loss='categorical_crossentropy',
optimizer=sgd, metric=topk)
model = tflearn.DNN(regression, tensorboard_verbose=0)
model.fit(X, Y, n_epoch=20, validation_set=(X_test, Y_test),
show_metric=True, run_id='high_dense_model') | UTF-8 | Python | false | false | 1,228 | py | 6 | highwaynet.py | 5 | 0.59202 | 0.54886 | 0 | 37 | 32.216216 | 83 |
ataola/a2python | 481,036,363,245 | 3378fb8ac56ac076538aae51b899ffbe4931c77d | a222c1f3028b49abefa0708b8f71784ca467cb3c | /code/demo/06-word-count.py | 62e0fd87113895f1ebfe8b73803219971eb5868e | [
"MIT"
]
| permissive | https://github.com/ataola/a2python | 6fd015a0e0f3a09ada825257bb55b85affa6ac98 | 3b098d5004ee5b4e101feb76a5c210c03ad8fa94 | refs/heads/master | 2023-04-12T20:09:36.058650 | 2023-03-20T03:01:29 | 2023-03-20T03:01:29 | 242,354,710 | 0 | 0 | null | null | null | null | null | null | null | null | null | null | null | null | null | #!/usr/bin/env python
# -*- coding: UTF-8 -*-
import pathlib
file_name = "01-address-book.md"
# 取得脚本所在目录
current_path = pathlib.PurePath(__file__).parent
# 和脚本同目录下的文件绝对路径
file = current_path.joinpath(file_name)
# 打开文件
with open(file, encoding='utf-8') as f:
# 读取文件
content = f.read()
words = content.rstrip()
number = len(words) # 统计字数
print(number)
| UTF-8 | Python | false | false | 460 | py | 52 | 06-word-count.py | 41 | 0.622449 | 0.612245 | 0 | 18 | 19.777778 | 48 |
KayMutale/pythoncourse | 6,193,342,863,457 | 55d57de648b2923c2dead5f80a74dac25fe6eb6a | 46c76c7ca1d9d030606f2e3e95a2a9e6bbad2789 | /game.py | a9c78cf27a0b99786c6468a6220b60bf8be66ec2 | []
| no_license | https://github.com/KayMutale/pythoncourse | be9ff713cffc73c1b9b3c1dd2bdd6d293637ce1e | 985a747ff17133aa533b7a049f83b37fc0fed80e | refs/heads/master | 2023-04-13T07:58:00.993724 | 2021-04-16T14:19:41 | 2021-04-16T14:19:41 | null | 0 | 0 | null | null | null | null | null | null | null | null | null | null | null | null | null | #!/usr/bin/env python
from random import randint
score = {}
def dice():
return randint(1,6)
def setplayers(*players):
for player in players:
score[player] = 0
def turn():
winner = None
winning_roll = 0
for player in score:
raw_input('%s press key for dice roll' % player)
roll = dice()
print roll
if roll > winning_roll:
winning_roll = roll
winner = player
score[winner] += 1
print "%s scores" % winner
def show_scores():
print "SCORES"
for player in score:
print player, score[player]
| UTF-8 | Python | false | false | 610 | py | 257 | game.py | 223 | 0.568852 | 0.560656 | 0 | 29 | 19.862069 | 56 |
imfangli/vimrc | 7,112,465,887,171 | 17b93f4d88d9afcc524705598144bc568badaebd | 5db3009eb36afe7110ed5402be3a9e570c58c540 | /my_plugins/YouCompleteMe/third_party/ycmd/ycmd/tests/java/get_completions_test.py | 7c7c7e7b2ea6466c57ed96721c0bcdd8eb87ad7c | [
"MIT",
"GPL-3.0-only",
"GPL-1.0-or-later"
]
| permissive | https://github.com/imfangli/vimrc | ced2c6caece1cf19421c6ea7deb017bec4ca3a27 | d2d14e7d083d70cc8627ddccb5b99c53c3c38be3 | refs/heads/master | 2022-02-01T00:34:31.855421 | 2022-01-22T15:57:28 | 2022-01-22T15:57:28 | 211,766,038 | 2 | 0 | MIT | true | 2019-09-30T03:15:03 | 2019-09-30T03:15:02 | 2019-09-30T02:50:54 | 2019-09-20T05:44:36 | 16,570 | 0 | 0 | 0 | null | false | false | # encoding: utf-8
#
# Copyright (C) 2017-2019 ycmd contributors
#
# This file is part of ycmd.
#
# ycmd is free software: you can redistribute it and/or modify
# it under the terms of the GNU General Public License as published by
# the Free Software Foundation, either version 3 of the License, or
# (at your option) any later version.
#
# ycmd is distributed in the hope that it will be useful,
# but WITHOUT ANY WARRANTY; without even the implied warranty of
# MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the
# GNU General Public License for more details.
#
# You should have received a copy of the GNU General Public License
# along with ycmd. If not, see <http://www.gnu.org/licenses/>.
from __future__ import print_function
from __future__ import absolute_import
from __future__ import unicode_literals
from __future__ import division
# Not installing aliases from python-future; it's unreliable and slow.
from builtins import * # noqa
from hamcrest import ( assert_that,
contains,
contains_inanyorder,
empty,
matches_regexp,
has_entries,
has_item )
from nose.tools import eq_
from pprint import pformat
import requests
from ycmd import handlers
from ycmd.tests.java import DEFAULT_PROJECT_DIR, PathToTestFile, SharedYcmd
from ycmd.tests.test_utils import ( CombineRequest,
ChunkMatcher,
CompletionEntryMatcher,
LocationMatcher,
WithRetry )
from ycmd.utils import ReadFile
from mock import patch
def ProjectPath( *args ):
return PathToTestFile( DEFAULT_PROJECT_DIR,
'src',
'com',
'test',
*args )
@WithRetry
def RunTest( app, test ):
"""
Method to run a simple completion test and verify the result
test is a dictionary containing:
'request': kwargs for BuildRequest
'expect': {
'response': server response code (e.g. httplib.OK)
'data': matcher for the server response json
}
"""
contents = ReadFile( test[ 'request' ][ 'filepath' ] )
app.post_json( '/event_notification',
CombineRequest( test[ 'request' ], {
'event_name': 'FileReadyToParse',
'contents': contents,
} ),
expect_errors = True )
# We ignore errors here and we check the response code ourself.
# This is to allow testing of requests returning errors.
response = app.post_json( '/completions',
CombineRequest( test[ 'request' ], {
'contents': contents
} ),
expect_errors = True )
print( 'completer response: {0}'.format( pformat( response.json ) ) )
eq_( response.status_code, test[ 'expect' ][ 'response' ] )
assert_that( response.json, test[ 'expect' ][ 'data' ] )
PUBLIC_OBJECT_METHODS = [
CompletionEntryMatcher( 'equals', 'Object', { 'kind': 'Method' } ),
CompletionEntryMatcher( 'getClass', 'Object', { 'kind': 'Method' } ),
CompletionEntryMatcher( 'hashCode', 'Object', { 'kind': 'Method' } ),
CompletionEntryMatcher( 'notify', 'Object', { 'kind': 'Method' } ),
CompletionEntryMatcher( 'notifyAll', 'Object', { 'kind': 'Method' } ),
CompletionEntryMatcher( 'toString', 'Object', { 'kind': 'Method' } ),
CompletionEntryMatcher( 'wait', 'Object', {
'menu_text': matches_regexp( 'wait\\(long .*, int .*\\) : void' ),
'kind': 'Method',
} ),
CompletionEntryMatcher( 'wait', 'Object', {
'menu_text': matches_regexp( 'wait\\(long .*\\) : void' ),
'kind': 'Method',
} ),
CompletionEntryMatcher( 'wait', 'Object', {
'menu_text': 'wait() : void',
'kind': 'Method',
} ),
]
# The zealots that designed java made everything inherit from Object (except,
# possibly Object, or Class, or whichever one they used to break the Smalltalk
# infinite recursion problem). Anyway, that means that we get a lot of noise
# suggestions from the Object Class interface. This allows us to write:
#
# contains_inanyorder( *WithObjectMethods( CompletionEntryMatcher( ... ) ) )
#
# and focus on what we care about.
def WithObjectMethods( *args ):
return list( PUBLIC_OBJECT_METHODS ) + list( args )
@SharedYcmd
def GetCompletions_NoQuery_test( app ):
RunTest( app, {
'description': 'semantic completion works for builtin types (no query)',
'request': {
'filetype' : 'java',
'filepath' : ProjectPath( 'TestFactory.java' ),
'line_num' : 27,
'column_num': 12,
},
'expect': {
'response': requests.codes.ok,
'data': has_entries( {
'completions': contains_inanyorder(
*WithObjectMethods(
CompletionEntryMatcher( 'test', 'TestFactory.Bar', {
'kind': 'Field'
} ),
CompletionEntryMatcher( 'testString', 'TestFactory.Bar', {
'kind': 'Field'
} )
)
),
'errors': empty(),
} )
},
} )
@SharedYcmd
def GetCompletions_WithQuery_test( app ):
RunTest( app, {
'description': 'semantic completion works for builtin types (with query)',
'request': {
'filetype' : 'java',
'filepath' : ProjectPath( 'TestFactory.java' ),
'line_num' : 27,
'column_num': 15,
},
'expect': {
'response': requests.codes.ok,
'data': has_entries( {
'completions': contains_inanyorder(
CompletionEntryMatcher( 'test', 'TestFactory.Bar', {
'kind': 'Field'
} ),
CompletionEntryMatcher( 'testString', 'TestFactory.Bar', {
'kind': 'Field'
} )
),
'errors': empty(),
} )
},
} )
@SharedYcmd
def GetCompletions_DetailFromCache_test( app ):
for i in range( 0, 2 ):
RunTest( app, {
'description': 'completion works when the elements come from the cache',
'request': {
'filetype' : 'java',
'filepath' : ProjectPath( 'TestLauncher.java' ),
'line_num' : 32,
'column_num': 15,
},
'expect': {
'response': requests.codes.ok,
'data': has_entries( {
'completion_start_column': 11,
'completions': has_item(
CompletionEntryMatcher( 'doSomethingVaguelyUseful',
'AbstractTestWidget', {
'kind': 'Method',
'menu_text':
'doSomethingVaguelyUseful() : void',
} )
),
'errors': empty(),
} )
},
} )
@SharedYcmd
def GetCompletions_Package_test( app ):
RunTest( app, {
'description': 'completion works for package statements',
'request': {
'filetype' : 'java',
'filepath' : ProjectPath( 'wobble', 'Wibble.java' ),
'line_num' : 1,
'column_num': 18,
},
'expect': {
'response': requests.codes.ok,
'data': has_entries( {
'completion_start_column': 9,
'completions': contains(
CompletionEntryMatcher( 'com.test.wobble', None, {
'kind': 'Module'
} ),
),
'errors': empty(),
} )
},
} )
@SharedYcmd
def GetCompletions_Import_Class_test( app ):
RunTest( app, {
'description': 'completion works for import statements with a single class',
'request': {
'filetype' : 'java',
'filepath' : ProjectPath( 'TestLauncher.java' ),
'line_num' : 3,
'column_num': 34,
},
'expect': {
'response': requests.codes.ok,
'data': has_entries( {
'completion_start_column': 34,
'completions': contains(
CompletionEntryMatcher( 'Tset;', None, {
'menu_text': 'Tset - com.youcompleteme.testing',
'kind': 'Class',
} )
),
'errors': empty(),
} )
},
} )
@SharedYcmd
def GetCompletions_Import_Classes_test( app ):
filepath = ProjectPath( 'TestLauncher.java' )
RunTest( app, {
'description': 'completion works for imports with multiple classes',
'request': {
'filetype' : 'java',
'filepath' : filepath,
'line_num' : 4,
'column_num': 52,
},
'expect': {
'response': requests.codes.ok,
'data': has_entries( {
'completion_start_column': 52,
'completions': contains(
CompletionEntryMatcher( 'A;', None, {
'menu_text': 'A - com.test.wobble',
'kind': 'Class',
} ),
CompletionEntryMatcher( 'A_Very_Long_Class_Here;', None, {
'menu_text': 'A_Very_Long_Class_Here - com.test.wobble',
'kind': 'Class',
} ),
CompletionEntryMatcher( 'Waggle;', None, {
'menu_text': 'Waggle - com.test.wobble',
'kind': 'Interface',
} ),
CompletionEntryMatcher( 'Wibble;', None, {
'menu_text': 'Wibble - com.test.wobble',
'kind': 'Enum',
} ),
),
'errors': empty(),
} )
},
} )
@SharedYcmd
def GetCompletions_Import_ModuleAndClass_test( app ):
filepath = ProjectPath( 'TestLauncher.java' )
RunTest( app, {
'description': 'completion works for imports of classes and modules',
'request': {
'filetype' : 'java',
'filepath' : filepath,
'line_num' : 3,
'column_num': 26,
},
'expect': {
'response': requests.codes.ok,
'data': has_entries( {
'completion_start_column': 26,
'completions': contains(
CompletionEntryMatcher( 'testing.*;', None, {
'menu_text': 'com.youcompleteme.testing',
'kind': 'Module',
} ),
CompletionEntryMatcher( 'Test;', None, {
'menu_text': 'Test - com.youcompleteme',
'kind': 'Class',
} ),
),
'errors': empty(),
} )
},
} )
@SharedYcmd
def GetCompletions_WithFixIt_test( app ):
filepath = ProjectPath( 'TestFactory.java' )
RunTest( app, {
'description': 'semantic completion with when additional textEdit',
'request': {
'filetype' : 'java',
'filepath' : filepath,
'line_num' : 19,
'column_num': 25,
},
'expect': {
'response': requests.codes.ok,
'data': has_entries( {
'completion_start_column': 22,
'completions': contains_inanyorder(
CompletionEntryMatcher( 'CUTHBERT', 'com.test.wobble.Wibble',
{
'kind': 'EnumMember',
'extra_data': has_entries( {
'fixits': contains( has_entries( {
'chunks': contains(
ChunkMatcher( 'Wibble',
LocationMatcher( filepath, 19, 15 ),
LocationMatcher( filepath, 19, 21 ) ),
# OK, so it inserts the import
ChunkMatcher( '\n\nimport com.test.wobble.Wibble;\n\n',
LocationMatcher( filepath, 1, 18 ),
LocationMatcher( filepath, 3, 1 ) ),
),
} ) ),
} ),
} ),
),
'errors': empty(),
} )
},
} )
@SharedYcmd
def GetCompletions_RejectMultiLineInsertion_test( app ):
filepath = ProjectPath( 'TestLauncher.java' )
RunTest( app, {
'description': 'completion item discarded when not valid',
'request': {
'filetype' : 'java',
'filepath' : filepath,
'line_num' : 28,
'column_num' : 16,
'force_semantic': True
},
'expect': {
'response': requests.codes.ok,
'data': has_entries( {
'completion_start_column': 16,
'completions': contains(
CompletionEntryMatcher( 'TestLauncher', 'com.test.TestLauncher', {
'kind': 'Constructor'
} )
# Note: There would be a suggestion here for the _real_ thing we want,
# which is a TestLauncher.Launchable, but this would generate the code
# for an anonymous inner class via a completion TextEdit (not
# AdditionalTextEdit) which we don't support.
),
'errors': empty(),
} )
},
} )
@SharedYcmd
def GetCompletions_UnicodeIdentifier_test( app ):
filepath = PathToTestFile( DEFAULT_PROJECT_DIR,
'src',
'com',
'youcompleteme',
'Test.java' )
RunTest( app, {
'description': 'Completion works for unicode identifier',
'request': {
'filetype' : 'java',
'filepath' : filepath,
'line_num' : 16,
'column_num' : 35,
'force_semantic': True
},
'expect': {
'response': requests.codes.ok,
'data': has_entries( {
'completion_start_column': 35,
'completions': contains_inanyorder( *WithObjectMethods(
CompletionEntryMatcher( 'a_test', 'Test.TéstClass', {
'kind': 'Field',
'detailed_info': 'a_test : int\n\n',
} ),
CompletionEntryMatcher( 'åtest', 'Test.TéstClass', {
'kind': 'Field',
'detailed_info': 'åtest : boolean\n\n',
} ),
CompletionEntryMatcher( 'testywesty', 'Test.TéstClass', {
'kind': 'Field',
} ),
) ),
'errors': empty(),
} )
},
} )
@SharedYcmd
def GetCompletions_ResolveFailed_test( app ):
filepath = PathToTestFile( DEFAULT_PROJECT_DIR,
'src',
'com',
'youcompleteme',
'Test.java' )
from ycmd.completers.language_server import language_server_protocol as lsapi
def BrokenResolveCompletion( request_id, completion ):
return lsapi.BuildRequest( request_id, 'completionItem/FAIL', completion )
with patch( 'ycmd.completers.language_server.language_server_protocol.'
'ResolveCompletion',
side_effect = BrokenResolveCompletion ):
RunTest( app, {
'description': 'Completion works for unicode identifier',
'request': {
'filetype' : 'java',
'filepath' : filepath,
'line_num' : 16,
'column_num' : 35,
'force_semantic': True
},
'expect': {
'response': requests.codes.ok,
'data': has_entries( {
'completion_start_column': 35,
'completions': contains_inanyorder( *WithObjectMethods(
CompletionEntryMatcher( 'a_test', 'Test.TéstClass', {
'kind': 'Field',
'detailed_info': 'a_test : int\n\n',
} ),
CompletionEntryMatcher( 'åtest', 'Test.TéstClass', {
'kind': 'Field',
'detailed_info': 'åtest : boolean\n\n',
} ),
CompletionEntryMatcher( 'testywesty', 'Test.TéstClass', {
'kind': 'Field',
} ),
) ),
'errors': empty(),
} )
},
} )
@SharedYcmd
def GetCompletions_ServerNotInitialized_test( app ):
filepath = PathToTestFile( 'simple_eclipse_project',
'src',
'com',
'test',
'AbstractTestWidget.java' )
completer = handlers._server_state.GetFiletypeCompleter( [ 'java' ] )
with patch.object( completer, '_ServerIsInitialized', return_value = False ):
RunTest( app, {
'description': 'Completion works for unicode identifier',
'request': {
'filetype' : 'java',
'filepath' : filepath,
'line_num' : 16,
'column_num' : 35,
'force_semantic': True
},
'expect': {
'response': requests.codes.ok,
'data': has_entries( {
'errors': empty(),
'completions': empty(),
'completion_start_column': 6
} ),
}
} )
@SharedYcmd
def GetCompletions_MoreThan100FilteredResolve_test( app ):
RunTest( app, {
'description': 'More that 100 match, but filtered set is fewer as this '
'depends on max_num_candidates',
'request': {
'filetype' : 'java',
'filepath' : ProjectPath( 'TestLauncher.java' ),
'line_num' : 4,
'column_num': 15,
},
'expect': {
'response': requests.codes.ok,
'data': has_entries( {
'completions': has_item(
CompletionEntryMatcher( 'com.youcompleteme.*;', None, {
'kind': 'Module',
'detailed_info': 'com.youcompleteme\n\n',
} ),
),
'completion_start_column': 8,
'errors': empty(),
} )
},
} )
@SharedYcmd
def GetCompletions_MoreThan100ForceSemantic_test( app ):
RunTest( app, {
'description': 'When forcing we pass the query, which reduces candidates',
'request': {
'filetype' : 'java',
'filepath' : ProjectPath( 'TestLauncher.java' ),
'line_num' : 4,
'column_num': 15,
'force_semantic': True
},
'expect': {
'response': requests.codes.ok,
'data': has_entries( {
'completions': contains(
CompletionEntryMatcher( 'com.youcompleteme.*;', None, {
'kind': 'Module',
'detailed_info': 'com.youcompleteme\n\n',
} ),
CompletionEntryMatcher( 'com.youcompleteme.testing.*;', None, {
'kind': 'Module',
'detailed_info': 'com.youcompleteme.testing\n\n',
} ),
),
'completion_start_column': 8,
'errors': empty(),
} )
},
} )
@SharedYcmd
def GetCompletions_ForceAtTopLevel_NoImport_test( app ):
RunTest( app, {
'description': 'When forcing semantic completion, pass the query to server',
'request': {
'filetype' : 'java',
'filepath' : ProjectPath( 'TestWidgetImpl.java' ),
'line_num' : 30,
'column_num': 20,
'force_semantic': True,
},
'expect': {
'response': requests.codes.ok,
'data': has_entries( {
'completions': contains(
CompletionEntryMatcher( 'TestFactory', None, {
'kind': 'Class',
'menu_text': 'TestFactory - com.test',
} ),
),
'completion_start_column': 12,
'errors': empty(),
} )
},
} )
@SharedYcmd
def GetCompletions_NoForceAtTopLevel_NoImport_test( app ):
RunTest( app, {
'description': 'When not forcing semantic completion, use no context',
'request': {
'filetype' : 'java',
'filepath' : ProjectPath( 'TestWidgetImpl.java' ),
'line_num' : 30,
'column_num': 20,
'force_semantic': False,
},
'expect': {
'response': requests.codes.ok,
'data': has_entries( {
'completions': contains(
CompletionEntryMatcher( 'TestFactory', '[ID]', {} ),
),
'completion_start_column': 12,
'errors': empty(),
} )
},
} )
@SharedYcmd
def GetCompletions_ForceAtTopLevel_WithImport_test( app ):
filepath = ProjectPath( 'TestWidgetImpl.java' )
RunTest( app, {
'description': 'Top level completions have import FixIts',
'request': {
'filetype' : 'java',
'filepath' : filepath,
'line_num' : 34,
'column_num': 16,
'force_semantic': True,
},
'expect': {
'response': requests.codes.ok,
'data': has_entries( {
'completions': has_item(
CompletionEntryMatcher( 'InputStreamReader', None, {
'kind': 'Class',
'menu_text': 'InputStreamReader - java.io',
'extra_data': has_entries( {
'fixits': contains( has_entries( {
'chunks': contains(
ChunkMatcher( '\n\nimport java.io.InputStreamReader;\n\n',
LocationMatcher( filepath, 1, 18 ),
LocationMatcher( filepath, 3, 1 ) ),
),
} ) ),
} ),
} ),
),
'completion_start_column': 12,
'errors': empty(),
} )
},
} )
@SharedYcmd
def GetCompletions_UseServerTriggers_test( app ):
filepath = ProjectPath( 'TestWidgetImpl.java' )
RunTest( app, {
'description': 'We use the semantic triggers from the server (@ here)',
'request': {
'filetype' : 'java',
'filepath' : filepath,
'line_num' : 24,
'column_num': 7,
'force_semantic': False,
},
'expect': {
'response': requests.codes.ok,
'data': has_entries( {
'completion_start_column': 4,
'completions': has_item(
CompletionEntryMatcher( 'Override', None, {
'kind': 'Interface',
'menu_text': 'Override - java.lang',
} )
)
} )
}
} )
| UTF-8 | Python | true | false | 21,233 | py | 882 | get_completions_test.py | 452 | 0.527635 | 0.521415 | 0 | 695 | 29.536691 | 80 |
rictts/Gestao-de-Turmas | 8,615,704,402,957 | 5b2ab3035538c2e069bba55da5db81da7d299fc3 | 19d0b52cc1bf768e91ea48e9e14cd3429c3544bf | /BD_disciplina.py | 6bd6d3fc3c7d34ecf95a8718e9c67a91e5c40ef1 | []
| no_license | https://github.com/rictts/Gestao-de-Turmas | a42aca104be539ee275af316be2b5fd9a38fb7ec | b67b57d931a4fe07db8a29b16fe6c0318c543ea0 | refs/heads/main | 2023-05-05T16:32:23.545229 | 2021-05-28T12:59:32 | 2021-05-28T12:59:32 | 367,845,137 | 0 | 0 | null | false | 2021-05-28T12:59:33 | 2021-05-16T10:11:43 | 2021-05-28T12:58:27 | 2021-05-28T12:59:32 | 31 | 0 | 0 | 0 | Python | false | false |
import os
import sqlite3
dbName = "Turmas.db"
global conn
conn = sqlite3.connect(dbName)
def insert_disciplina(disciplina):
print("Insere na Base de dados:",disciplina)
sql = """INSERT INTO disciplina(Nome_Disciplina) VALUES (?);"""
c = conn.cursor()
dados = (disciplina)
c.execute(sql, (dados,))
conn.commit()
def select_disciplina():
lista_disciplina = list()
print("BD Disciplina-Select ")
sql = """SELECT * from disciplina;"""
c = conn.cursor()
resultado = c.execute(sql)
for linha in resultado:
lista_disciplina.append(linha)
return lista_disciplina
def delete_disciplina(disciplina):
print("Apaga na Base de dados:",disciplina)
sql = """DELETE FROM disciplina WHERE Nome_Disciplina = ?;"""
c = conn.cursor()
dados = (disciplina)
c.execute(sql, (dados,))
conn.commit()
| UTF-8 | Python | false | false | 924 | py | 16 | BD_disciplina.py | 14 | 0.61039 | 0.608225 | 0 | 43 | 19.302326 | 67 |
bookwyrm-social/bookwyrm | 9,878,424,790,447 | bc83b422416bd2e1adf0acf822312dc852392df1 | 8fa191cd4a67431a04eff62d35122ee83cc7b0af | /bookwyrm/migrations/0089_user_show_suggested_users.py | 047bb974ce670b02cdbc737a13fc24a2f5a17a10 | [
"LicenseRef-scancode-warranty-disclaimer"
]
| no_license | https://github.com/bookwyrm-social/bookwyrm | 24678676a7a58dba96641194dfae3fffbf01574d | 0f8da5b738047f3c34d60d93f59bdedd8f797224 | refs/heads/main | 2023-08-20T21:45:30.957277 | 2023-08-19T23:41:50 | 2023-08-19T23:41:50 | 236,415,735 | 1,398 | 216 | NOASSERTION | false | 2023-09-08T20:43:06 | 2020-01-27T03:51:54 | 2023-09-08T18:02:43 | 2023-09-08T20:43:06 | 60,885 | 1,908 | 224 | 338 | Python | false | false | # Generated by Django 3.2.4 on 2021-09-08 16:28
from django.db import migrations, models
class Migration(migrations.Migration):
dependencies = [
("bookwyrm", "0088_auto_20210905_2233"),
]
operations = [
migrations.AddField(
model_name="user",
name="show_suggested_users",
field=models.BooleanField(default=True),
),
]
| UTF-8 | Python | false | false | 399 | py | 889 | 0089_user_show_suggested_users.py | 492 | 0.596491 | 0.518797 | 0 | 18 | 21.166667 | 52 |
sabareeshs/codenames | 12,446,815,234,734 | 258548b759ad097a49f578addb4e0c11d0ee7dd7 | 5190df8d0da29a78111e4c74cedde5ea48cf0b5f | /gameplay/urls.py | 3e4ba06181964a5c8f240eb675a1fd3de14d1465 | []
| no_license | https://github.com/sabareeshs/codenames | 7aa2a44bcac7f8c7e7f153301e016d6dad69b187 | 39db5269f41ae7dfb4e13d8445d66ca35547eec9 | refs/heads/master | 2022-08-29T03:37:42.488840 | 2020-05-30T06:59:53 | 2020-05-30T06:59:53 | 265,723,481 | 0 | 0 | null | null | null | null | null | null | null | null | null | null | null | null | null | from django.conf.urls import url
from gameplay import views
urlpatterns = [
url(r'^$', views.index, name='gameplay_index'),
url(r'^create_board/$', views.create_board, name='create_board'),
url(r'^(?P<board_id>[0-9a-f]{8}\-[0-9a-f]{4}\-4[0-9a-f]{3}\-[89ab][0-9a-f]{3}\-[0-9a-f]{12})/delete/$', views.delete, name='delete'),
url(r'^(?P<board_id>[0-9a-f]{8}\-[0-9a-f]{4}\-4[0-9a-f]{3}\-[89ab][0-9a-f]{3}\-[0-9a-f]{12})/num_clues/$', views.num_clues, name='num_clues'),
url(r'^(?P<board_id>[0-9a-f]{8}\-[0-9a-f]{4}\-4[0-9a-f]{3}\-[89ab][0-9a-f]{3}\-[0-9a-f]{12})/(?P<player>[\_a-z]+)/$', views.board, name='board'),
url(r'^(?P<board_id>[0-9a-f]{8}\-[0-9a-f]{4}\-4[0-9a-f]{3}\-[89ab][0-9a-f]{3}\-[0-9a-f]{12})/(?P<player>[\_a-z]+)/end_turn/$', views.end_turn, name='end_turn'),
url(r'^(?P<board_id>[0-9a-f]{8}\-[0-9a-f]{4}\-4[0-9a-f]{3}\-[89ab][0-9a-f]{3}\-[0-9a-f]{12})/card/(?P<word>[\sa-z\-]+)/(?P<player>[\_a-z]+)/$', views.card_click, name='card_click'),
]
| UTF-8 | Python | false | false | 966 | py | 16 | urls.py | 5 | 0.546584 | 0.44824 | 0 | 12 | 79.5 | 182 |
ushitora/vizdoom_experiments | 8,684,423,909,956 | b0507e71f68c6cb07ef7602f27c6d3e8426be213 | 68f6e727e8f95391d6381669c72857f8bc4ac142 | /source/a3c_demo/a3c_demo.py | 62c4f7626635c3f97714f86b29f7bb971ac676ff | []
| no_license | https://github.com/ushitora/vizdoom_experiments | db6b6279ce0b248c1e933340d518ce90189be37d | fcc6febcbd9039b0f0f0aea1d472b2226b5395e5 | refs/heads/master | 2020-04-28T09:40:56.209848 | 2019-03-12T10:00:28 | 2019-03-12T10:00:28 | 175,175,368 | 0 | 0 | null | null | null | null | null | null | null | null | null | null | null | null | null |
# coding: utf-8
# In[ ]:
#!/usr/bin/python
from __future__ import print_function
import math
import time,random,threading,datetime
import tensorflow as tf
from time import sleep
import numpy as np
from vizdoom import *
import skimage.color, skimage.transform
from tqdm import tqdm
import h5py
from tensorflow.python import debug as tf_debug
from tqdm import tqdm
from PIL import Image
CONFIG_FILE_PATH = "./config/custom_config.cfg"
MODEL_PATH = "./model_v03/model_v03.ckpt"
DEMO_PATH = "./demodata_cig2017_v0-2.h5"
LOG_DIR = "./logs_v03"
RECORDS_DIR = "./records_v03/"
N_FOLDER = 3
RESOLUTION = (120,180,3)
N_ADV = 10
TIME_LEARN = datetime.timedelta(hours=24)
N_WORKERS = 10
WORKER_STEPS = 200000
N_PRE_STEP = 20000
N_ACTION = 6
GAMMA = 0.99
BOTS_NUM = 10
EPS_START = 0.5
EPS_END = 0.0
EPS_STEPS = WORKER_STEPS*N_WORKERS
REWARDS = {'living':-0.01, 'health_loss':-1, 'medkit':50, 'ammo':0.0, 'frag':500, 'dist':3e-2, 'suicide':-500}
LEARNING_RATE = 5e-3
RMSProbDecaly = 0.99
ISNPY = False
TEST_FREQ_PRELEARNING = 50
COEFF_L_P = 1.0
COEFF_L_V = 0.01
COEFF_ENT = 1.0
# In[ ]:
# --スレッドになるクラスです -------
class Worker_thread:
# スレッドは学習環境environmentを持ちます
def __init__(self, thread_name, parameter_server):
self.environment = Environment(thread_name, parameter_server,False)
print(thread_name," Initialized")
def run(self):
while True:
if not self.environment.finished:
self.environment.run()
else:
sleep(1.0)
# In[ ]:
class Environment(object):
def __init__(self,name, parameter_server,record=False):
self.game = DoomGame()
self.game.load_config(CONFIG_FILE_PATH)
self.game.set_window_visible(False)
self.game.set_mode(Mode.PLAYER)
# self.game.set_screen_format(ScreenFormat.GRAY8)
self.game.set_screen_format(ScreenFormat.CRCGCB)
self.game.set_screen_resolution(ScreenResolution.RES_640X480)
self.game.init()
health = self.game.get_game_variable(GameVariable.HEALTH)
ammo = self.game.get_game_variable(GameVariable.SELECTED_WEAPON_AMMO)
frag = self.game.get_game_variable(GameVariable.FRAGCOUNT)
pos_x = self.game.get_game_variable(GameVariable.POSITION_X)
pos_y = self.game.get_game_variable(GameVariable.POSITION_Y)
self.reward_gen = RewardGenerater(health,ammo,frag,pos_x,pos_y)
self.network = Network_local(name, parameter_server)
self.agent = Agent(name,self.network)
self.local_step = 0
self.finished = False
self.name = name
self.record = record
self.parameter_server = parameter_server
self.frame_record = []
self.loss_policy = []
self.loss_value = []
self.entropy = []
def start_episode(self):
self.game.new_episode()
for i in range(BOTS_NUM):
self.game.send_game_command("addbot")
def preprocess(self,img):
if len(img.shape) == 3:
img = img.transpose(1,2,0)
img = skimage.transform.resize(img, RESOLUTION,mode='constant')
img = img.astype(np.float32)
return img
def get_reward(self):
health = self.game.get_game_variable(GameVariable.HEALTH)
ammo = self.game.get_game_variable(GameVariable.SELECTED_WEAPON_AMMO)
frag = self.game.get_game_variable(GameVariable.FRAGCOUNT)
pos_x = self.game.get_game_variable(GameVariable.POSITION_X)
pos_y = self.game.get_game_variable(GameVariable.POSITION_Y)
r,r_detail = self.reward_gen.get_reward(health,ammo,frag,pos_x,pos_y)
return r
def run(self):
global frames,runout
self.start_episode()
train_episode = 0
step = 0
# for step in range(WORKER_STEPS):
while True:
# if step % 1000 == 0:
# buff = self.name + ":" + str(step) + "step is passed"
# print(buff)
#Copy params from global
self.agent.network.pull_parameter_server()
if not self.game.is_episode_finished():
if step%N_ADV==0 and not step==0:
self.reward_gen.update_origin(self.game.get_game_variable(GameVariable.POSITION_X), self.game.get_game_variable(GameVariable.POSITION_Y))
s1 = self.preprocess(self.game.get_state().screen_buffer)
action = self.agent.act(s1)
self.game.make_action(action,5)
reward = self.get_reward()
isterminal = self.game.is_episode_finished()
s2 = self.preprocess(self.game.get_state().screen_buffer) if not isterminal else None
if self.record==True:
self.parameter_server.write_summary(frames,np.array([s1]),np.array([action]),np.array([[reward]]))
l_p,l_v,ent = self.parameter_server.calc_loss(frames,np.array([s1]),np.array([action]),np.array([[reward]]))
self.loss_policy.append(l_p[0][0])
self.loss_value.append(l_v[0][0])
self.entropy.append(ent[0][0])
self.frame_record.append(frames)
# if step==0:
# print("async")
# print(s1.shape)
# print(action)
# print(reward)
self.agent.advantage_push_network(s1,action,reward,s2,isterminal)
if self.game.is_player_dead():
self.game.respawn_player()
self.reward_gen.respawn_pos(self.game.get_game_variable(GameVariable.HEALTH), self.game.get_game_variable(GameVariable.SELECTED_WEAPON_AMMO), self.game.get_game_variable(GameVariable.POSITION_X), self.game.get_game_variable(GameVariable.POSITION_Y))
else:
train_episode += 1
self.start_episode()
self.reward_gen.new_episode(health = self.game.get_game_variable(GameVariable.HEALTH), ammo = self.game.get_game_variable(GameVariable.SELECTED_WEAPON_AMMO), posx = self.game.get_game_variable(GameVariable.POSITION_X), posy = self.game.get_game_variable(GameVariable.POSITION_Y))
self.local_step += 1
frames += 1
step += 1
if runout == True:
break
print(self.name," finished")
self.finished = True
# In[ ]:
class DemoEnvironment(object):
def __init__(self,name, parameter_server, test_env):
self.game = DoomGame()
self.game.load_config(CONFIG_FILE_PATH)
self.game.set_window_visible(False)
self.game.set_mode(Mode.PLAYER)
# self.game.set_screen_format(ScreenFormat.GRAY8)
self.game.set_screen_format(ScreenFormat.CRCGCB)
self.game.set_screen_resolution(ScreenResolution.RES_640X480)
self.game.init()
health = self.game.get_game_variable(GameVariable.HEALTH)
ammo = self.game.get_game_variable(GameVariable.SELECTED_WEAPON_AMMO)
frag = self.game.get_game_variable(GameVariable.FRAGCOUNT)
pos_x = self.game.get_game_variable(GameVariable.POSITION_X)
pos_y = self.game.get_game_variable(GameVariable.POSITION_Y)
self.reward_gen = RewardGenerater(health,ammo,frag,pos_x,pos_y)
self.network = Network_local(name, parameter_server)
self.agent = Agent(name,self.network)
self.test_env = test_env
self.pre_death = 0
self.parameter_server = parameter_server
self.replay_buff = []
self.loss_policy = []
self.loss_value = []
self.entropy = []
self.frame_record = []
def load_demonstration(self):
if ISNPY:
pass
else:
hdf5file = h5py.File(DEMO_PATH,"r")
folder = "demodata_"+str(0)
state1 = hdf5file[folder+"/state1"].value
state2 = hdf5file[folder+"/state2"].value
actions_row = hdf5file[folder+"/actions"].value
isterminals = hdf5file[folder+"/isterminals"].value
health = hdf5file[folder+"/healths"].value
ammo = hdf5file[folder+"/ammos"].value
posx = hdf5file[folder+"/posxs"].value
posy = hdf5file[folder+"/posys"].value
death = hdf5file[folder+"/deaths"].value
frag = hdf5file[folder+"/frags"].value
for i in range(1,N_FOLDER):
folder = "demodata_" +str(i)
state1 = np.concatenate((state1,hdf5file[folder+"/state1"].value),axis=0)
state2 = np.concatenate((state2,hdf5file[folder+"/state2"].value),axis=0)
actions_row = np.concatenate((actions_row,hdf5file[folder+"/actions"].value),axis=0)
isterminals = np.concatenate((isterminals,hdf5file[folder+"/isterminals"].value),axis=0)
health = np.concatenate((health,hdf5file[folder+"/healths"].value),axis=0)
ammo = np.concatenate((ammo,hdf5file[folder+"/ammos"].value),axis=0)
posx = np.concatenate((posx,hdf5file[folder+"/posxs"].value),axis=0)
posy = np.concatenate((posy,hdf5file[folder+"/posys"].value),axis=0)
death = np.concatenate((death,hdf5file[folder+"/deaths"].value),axis=0)
frag = np.concatenate((frag,hdf5file[folder+"/frags"].value),axis=0)
n_transit, n_step, _ = actions_row.shape
print(actions_row.shape)
actions = np.zeros(shape=[n_transit,n_step,N_ACTION])
for i in range(n_transit):
for j in range(n_step):
actions[i][j][actions_row[i][j]] = 1
is_dead = False
is_finished = False
pre_health = 100
pre_ammo = 15
pre_frag = 0
pre_death = 0
pre_posx = 0.0
pre_posy = 0.0
for i in range(n_transit):
pre_posx = posx[i][0]
pre_posy = posy[i][0]
replay_sequence = []
R = 0
for j in range(N_ADV):
if not is_finished:
if is_dead :
pre_posx = posx[i][j]
pre_posy = posy[i][j]
pre_health = 100
pre_ammo = 15
is_dead = False
m_frag = frag[i][j] - pre_frag
m_death = death[i][j] - pre_death
m_health = health[i][j] - pre_health
m_ammo = ammo[i][j] - pre_ammo
m_posx = posx[i][j] - pre_posx
m_posy = posy[i][j] - pre_posy
if m_death >= 1:
is_dead = True
if isterminals[i][j] == True:
is_finished = True
r_d = self.reward_gen.calc_reward(m_frag,m_death,m_health,m_ammo,m_posx,m_posy)
r = sum(r_d.values())
replay_sequence.append((state1[i][j],actions[i][j],state2[i][j],r,isterminals[i][j]))
pre_frag = frag[i][j]
pre_death = death[i][j]
pre_health = health[i][j]
pre_ammo = ammo[i][j]
# if j==7:
# print("---------------------------------")
# print("state[%d][%d]:"%(i,j))
# print("\t%4.2f, %4.2f, %4.2f, %4.2f, %4.2f, %4.2f"%(m_frag,m_death,m_health,m_ammo,m_posx,m_posy))
# print("\t%4.2f, %4.2f, %4.2f, %4.2f, %4.2f, %4.2f"%(r_d['frag'],r_d['medkit'],r_d['health_loss'],r_d['ammo'],r_d['dist'],r_d['suicide']))
else:
replay_sequence.append((None,None,None,None,True))
is_finished = False
self.replay_buff.append(replay_sequence)
replay_sequence = []
def pre_learning(self):
global frames
num_replay = len(self.replay_buff)
for step in tqdm(range(N_PRE_STEP)):
self.agent.network.pull_parameter_server()
replay_idx = random.randint(0,num_replay-1)
if frames%TEST_FREQ_PRELEARNING == 0:
self.test_env.run()
for i in range(N_ADV):
s1 = self.replay_buff[replay_idx][i][0]
action = self.replay_buff[replay_idx][i][1]
s2 = self.replay_buff[replay_idx][i][2]
reward = self.replay_buff[replay_idx][i][3]
isterminal = self.replay_buff[replay_idx][i][4]
if not(type(s1)==type(None)):
self.agent.advantage_push_network(s1,action,reward,s2,isterminal)
s1 = self.replay_buff[replay_idx][0][0]
action = self.replay_buff[replay_idx][0][1]
reward = self.replay_buff[replay_idx][0][3]
# print("-----------%d---------------"%step)
# print("-----------------GLOBAL-----------------")
# self.parameter_server.test_func(s1,action,reward)
# print("-----------------LOCAL-----------------")
# self.agent.network.test_func(s1,action,reward)
l_p,l_v,ent = self.parameter_server.calc_loss(frames,np.array([s1]),np.array([action]),np.array([reward]))
self.loss_policy.append(l_p[0][0])
self.loss_value.append(l_v[0][0])
self.entropy.append(ent[0][0])
self.frame_record.append(frames)
frames+=1
# In[ ]:
class TestEnvironment(object):
def __init__(self,name, parameter_server):
self.game = DoomGame()
self.game.load_config(CONFIG_FILE_PATH)
self.game.set_window_visible(False)
self.game.set_mode(Mode.PLAYER)
# self.game.set_screen_format(ScreenFormat.GRAY8)
self.game.set_screen_format(ScreenFormat.CRCGCB)
self.game.set_screen_resolution(ScreenResolution.RES_640X480)
self.game.init()
health = self.game.get_game_variable(GameVariable.HEALTH)
ammo = self.game.get_game_variable(GameVariable.SELECTED_WEAPON_AMMO)
frag = self.game.get_game_variable(GameVariable.FRAGCOUNT)
pos_x = self.game.get_game_variable(GameVariable.POSITION_X)
pos_y = self.game.get_game_variable(GameVariable.POSITION_Y)
self.reward_gen = RewardGenerater(health,ammo,frag,pos_x,pos_y)
self.network = Network_local(name, parameter_server)
self.agent = Agent(name,self.network)
self.pre_death = 0
self.record_reward = []
self.record_frag = []
self.record_death = []
def start_episode(self):
self.game.new_episode()
for i in range(BOTS_NUM):
self.game.send_game_command("addbot")
def preprocess(self,img):
if len(img.shape) == 3:
img = img.transpose(1,2,0)
img = skimage.transform.resize(img, RESOLUTION,mode='constant')
img = img.astype(np.float32)
return img
def get_reward(self):
health = self.game.get_game_variable(GameVariable.HEALTH)
ammo = self.game.get_game_variable(GameVariable.SELECTED_WEAPON_AMMO)
frag = self.game.get_game_variable(GameVariable.FRAGCOUNT)
pos_x = self.game.get_game_variable(GameVariable.POSITION_X)
pos_y = self.game.get_game_variable(GameVariable.POSITION_Y)
r,r_detail = self.reward_gen.get_reward(health,ammo,frag,pos_x,pos_y)
return r
def run(self):
global frames
health = self.game.get_game_variable(GameVariable.HEALTH)
ammo = self.game.get_game_variable(GameVariable.SELECTED_WEAPON_AMMO)
frag = self.game.get_game_variable(GameVariable.FRAGCOUNT)
pos_x = self.game.get_game_variable(GameVariable.POSITION_X)
pos_y = self.game.get_game_variable(GameVariable.POSITION_Y)
self.reward_gen = RewardGenerater(health,ammo,0,pos_x,pos_y)
self.start_episode()
#Copy params from global
self.agent.network.pull_parameter_server()
step = 0
while not self.game.is_episode_finished():
if step%N_ADV==0 and not step==0:
self.reward_gen.update_origin(self.game.get_game_variable(GameVariable.POSITION_X), self.game.get_game_variable(GameVariable.POSITION_Y))
s1 = self.preprocess(self.game.get_state().screen_buffer)
action = self.agent.test_act(s1)
self.game.make_action(action,1)
reward = self.get_reward()
isterminal = self.game.is_episode_finished()
if self.game.is_player_dead():
self.game.respawn_player()
self.reward_gen.respawn_pos(self.game.get_game_variable(GameVariable.HEALTH), self.game.get_game_variable(GameVariable.SELECTED_WEAPON_AMMO), self.game.get_game_variable(GameVariable.POSITION_X), self.game.get_game_variable(GameVariable.POSITION_Y))
step += 1
print("----------TEST at %d step-------------"%(frames))
ret_frag = self.game.get_game_variable(GameVariable.FRAGCOUNT)
ret_death = self.game.get_game_variable(GameVariable.DEATHCOUNT)-self.pre_death
ret_reward = self.reward_gen.total_reward
print("FRAG:",ret_frag,"DEATH:",ret_death)
print("REWARD",ret_reward)
print("DETAIL:",self.reward_gen.total_reward_detail)
return ret_reward,ret_frag,ret_death
# self.record_frag.append(self.game.get_game_variable(GameVariable.FRAGCOUNT))
# self.record_death.append(self.game.get_game_variable(GameVariable.DEATHCOUNT)-self.pre_death)
# self.record_reward.append(self.reward_gen.total_reward)
self.pre_death = self.game.get_game_variable(GameVariable.DEATHCOUNT)
def run_gif(self):
global frames
health = self.game.get_game_variable(GameVariable.HEALTH)
ammo = self.game.get_game_variable(GameVariable.SELECTED_WEAPON_AMMO)
frag = self.game.get_game_variable(GameVariable.FRAGCOUNT)
pos_x = self.game.get_game_variable(GameVariable.POSITION_X)
pos_y = self.game.get_game_variable(GameVariable.POSITION_Y)
self.reward_gen = RewardGenerater(health,ammo,0,pos_x,pos_y)
self.start_episode()
#Copy params from global
self.agent.network.pull_parameter_server()
step = 0
gif_img = []
while not self.game.is_episode_finished():
if step%N_ADV==0 and not step==0:
self.reward_gen.update_origin(self.game.get_game_variable(GameVariable.POSITION_X), self.game.get_game_variable(GameVariable.POSITION_Y))
s1 = self.preprocess(self.game.get_state().screen_buffer)
if step%5==0:
gif_img.append(s1)
action = self.agent.test_act(s1)
self.game.make_action(action,1)
reward = self.get_reward()
isterminal = self.game.is_episode_finished()
if self.game.is_player_dead():
self.game.respawn_player()
self.reward_gen.respawn_pos(self.game.get_game_variable(GameVariable.HEALTH), self.game.get_game_variable(GameVariable.SELECTED_WEAPON_AMMO), self.game.get_game_variable(GameVariable.POSITION_X), self.game.get_game_variable(GameVariable.POSITION_Y))
step += 1
save_img = []
for i in range(len(gif_img)):
save_img.append(Image.fromarray(np.uint8(gif_img[i]*255)))
save_img[0].save('test.gif',save_all=True,append_images=save_img[1:])
print("----------TEST at %d step-------------"%(frames))
print("FRAG:",self.game.get_game_variable(GameVariable.FRAGCOUNT),"DEATH:",self.game.get_game_variable(GameVariable.DEATHCOUNT)-self.pre_death)
print("REWARD",self.reward_gen.total_reward)
print("DETAIL:",self.reward_gen.total_reward_detail)
self.record_frag.append(self.game.get_game_variable(GameVariable.FRAGCOUNT))
self.record_death.append(self.game.get_game_variable(GameVariable.DEATHCOUNT)-self.pre_death)
self.record_reward.append(self.reward_gen.total_reward)
self.pre_death = self.game.get_game_variable(GameVariable.DEATHCOUNT)
# In[ ]:
class RewardGenerater(object):
def __init__(self,health,ammo,frag,pos_x,pos_y):
# Reward
self.rewards = REWARDS
self.dist_unit = 6.0
self.origin_x = pos_x
self.origin_y = pos_y
self.pre_health = health
self.pre_ammo = ammo
self.pre_frag = frag
self.total_reward = 0.0
self.total_reward_detail = {'living':0.0, 'health_loss':0.0, 'medkit':0.0, 'ammo':0.0, 'frag':0.0, 'dist':0.0, 'suicide': 0.0}
def get_reward(self,health,ammo,frag,pos_x,pos_y):
if abs(health) > 10000:
health = 100.0
if self.origin_x == 0 and self.origin_y == 0:
self.origin_x = pos_x
self.origin_y = pos_y
self.reward_detail = self.calc_reward(frag-self.pre_frag,0.0, health-self.pre_health, ammo-self.pre_ammo, pos_x-self.origin_x, pos_y-self.origin_y)
self.reward = sum(self.reward_detail.values())
for k,v in self.reward_detail.items():
self.total_reward_detail[k] += v
self.total_reward = sum(self.total_reward_detail.values())
self.pre_frag = frag
self.pre_health = health
self.pre_ammo = ammo
return (self.reward, self.reward_detail)
def calc_reward(self,m_frag,m_death,m_health,m_ammo,m_posx,m_posy):
ret_detail = {}
ret_detail['living'] = self.rewards['living']
if m_frag >= 0:
ret_detail['frag'] = (m_frag)*self.rewards['frag']
ret_detail['suicide'] = 0.0
else:
ret_detail['suicide'] = (m_frag*-1)*(self.rewards['suicide'])
ret_detail['frag'] = 0.0
ret_detail['dist'] = int((math.sqrt((m_posx)**2 + (m_posy)**2))/self.dist_unit) * (self.rewards['dist'] * self.dist_unit)
if m_health > 0:
ret_detail['medkit'] = self.rewards['medkit']
ret_detail['health_loss'] = 0.0
else:
ret_detail['medkit'] = 0.0
ret_detail['health_loss'] = (m_health)*self.rewards['health_loss'] * (-1)
ret_detail['ammo'] = (m_ammo)*self.rewards['ammo'] if m_ammo>0 else 0.0
return ret_detail
def respawn_pos(self,health,ammo,posx, posy):
self.origin_x = posx
self.origin_y = posy
self.pre_health = health
self.pre_ammo = ammo
def new_episode(self,health,ammo,posx,posy):
self.respawn_pos(health,ammo,posx,posy)
self.pre_frag = 0
self.total_reward = 0
self.total_reward_detail={'living':0.0, 'health_loss':0.0, 'medkit':0.0, 'ammo':0.0, 'frag':0.0, 'dist':0.0, 'suicide': 0.0}
def update_origin(self,pos_x, pos_y):
self.origin_x = pos_x
self.origin_y = pos_y
# In[ ]:
class NetworkSetting:
def state():
name = "STATE"
shape = [None,RESOLUTION[0],RESOLUTION[1],RESOLUTION[2]]
return tf.placeholder(tf.float32,shape=shape,name=name)
def conv1(pre_layer):
num_outputs = 8
kernel_size = [6,6]
stride = 3
padding = 'SAME'
activation = tf.nn.relu
weights_init = tf.contrib.layers.xavier_initializer_conv2d()
bias_init = tf.constant_initializer(0.1)
return tf.contrib.layers.conv2d(pre_layer,kernel_size=kernel_size,num_outputs=num_outputs, stride=stride,padding=padding,activation_fn=activation, weights_initializer=weights_init, biases_initializer=bias_init)
def maxpool1(pre_layer):
return tf.nn.max_pool(pre_layer,[1,3,3,1],[1,2,2,1],'SAME')
def conv2(pre_layer):
num_outputs = 16
kernel_size = [3,3]
stride = 2
padding = 'SAME'
activation = tf.nn.relu
weights_init = tf.contrib.layers.xavier_initializer_conv2d()
bias_init = tf.constant_initializer(0.1)
return tf.contrib.layers.conv2d(pre_layer,kernel_size=kernel_size,num_outputs=num_outputs, stride=stride,padding=padding,activation_fn=activation, weights_initializer=weights_init,biases_initializer=bias_init)
def maxpool2(pre_layer):
return tf.nn.max_pool(pre_layer,[1,3,3,1],[1,2,2,1],'SAME')
def reshape(pre_layer):
return tf.contrib.layers.flatten(pre_layer)
def fc1(pre_layer):
num_outputs = 512
activation_fn = tf.nn.relu
weights_init = tf.contrib.layers.xavier_initializer()
bias_init = tf.constant_initializer(0.1)
return tf.contrib.layers.fully_connected(pre_layer,num_outputs=num_outputs,activation_fn=activation_fn, weights_initializer=weights_init, biases_initializer=bias_init)
def policy(pre_layer):
num_outputs=6
activation_fn = tf.nn.softmax
weights_init = tf.contrib.layers.xavier_initializer()
bias_init = tf.constant_initializer(0.1)
return tf.contrib.layers.fully_connected(pre_layer,num_outputs=num_outputs,activation_fn=activation_fn, weights_initializer=weights_init, biases_initializer=bias_init)
def value(pre_layer):
num_outputs = 1
activation_fn = None
weights_init = tf.contrib.layers.xavier_initializer()
bias_init = tf.constant_initializer(0.1)
return tf.contrib.layers.fully_connected(pre_layer,num_outputs=num_outputs,activation_fn=activation_fn, weights_initializer=weights_init, biases_initializer=bias_init)
# In[ ]:
# --グローバルなTensorFlowのDeep Neural Networkのクラスです -------
class ParameterServer:
def __init__(self):
with tf.variable_scope("parameter_server"): # スレッド名で重み変数に名前を与え、識別します(Name Space)
self._build_model() # ニューラルネットワークの形を決定
with tf.variable_scope("summary"):
self._build_summary()
self.weights_params = tf.get_collection(tf.GraphKeys.TRAINABLE_VARIABLES, scope="parameter_server")
self.optimizer = tf.train.RMSPropOptimizer(LEARNING_RATE, RMSProbDecaly) # loss関数を最小化していくoptimizerの定義です
# with tf.device("/cpu:0"):
# self.saver = tf.train.Saver()
self.saver = tf.train.Saver()
# print("-------GLOBAL-------")
# for w in self.weights_params:
# print(w)
def _build_model(self):
self.state = NetworkSetting.state()
self.conv1 = NetworkSetting.conv1(self.state)
self.maxpool1 = NetworkSetting.maxpool1(self.conv1)
self.conv2 = NetworkSetting.conv2(self.maxpool1)
self.maxpool2 = NetworkSetting.maxpool2(self.conv2)
reshape = NetworkSetting.reshape(self.maxpool2)
fc1 = NetworkSetting.fc1(reshape)
with tf.variable_scope("policy"):
self.policy = NetworkSetting.policy(fc1)
with tf.variable_scope("value"):
self.value = NetworkSetting.value(fc1)
print("---------MODEL SHAPE-------------")
print(self.state.get_shape())
print(self.conv1.get_shape())
print(self.conv2.get_shape())
print(reshape.get_shape())
print(fc1.get_shape())
print(self.policy.get_shape())
print(self.value.get_shape())
def _build_summary(self):
self.a_t = tf.placeholder(tf.float32, shape=(None, N_ACTION))
self.r_t = tf.placeholder(tf.float32, shape=(None,1))
self.reward = tf.placeholder(tf.float32,shape=(None,1))
self.frag = tf.placeholder(tf.int64,shape=(None,1))
self.death = tf.placeholder(tf.int64,shape=(None,1))
log_prob = tf.log(tf.reduce_sum(self.policy * self.a_t, axis=1, keep_dims=True)+1e-10)
advantage = self.r_t - self.value
self.test1 = log_prob
self.test2 = advantage
self.loss_policy = -log_prob * tf.stop_gradient(advantage)
self.loss_value = COEFF_L_V* tf.square(advantage)
self.entropy = COEFF_ENT * tf.reduce_sum(self.policy * tf.log(self.policy + 1e-10), axis=1, keep_dims=True)
print(self.loss_policy.get_shape())
print(self.loss_value.get_shape())
# with tf.device("/cpu:0"):
summary_lp = tf.summary.scalar('loss_policy',self.loss_policy[0][0])
summary_lv = tf.summary.scalar('loss_value', self.loss_value[0][0])
summary_ent = tf.summary.scalar('entropy', self.entropy[0][0])
self.merged_scalar = tf.summary.merge([summary_lp,summary_lv,summary_ent])
state_shape = self.state.get_shape()
conv1_shape = self.conv1.get_shape()
conv2_shape = self.conv2.get_shape()
summary_state = tf.summary.image('state',tf.reshape(self.state,[-1, state_shape[1], state_shape[2], state_shape[3]]),1)
summary_conv1 = tf.summary.image('conv1',tf.reshape(self.conv1,[-1, conv1_shape[1], conv1_shape[2], 1]),1)
summary_conv2 = tf.summary.image('conv2',tf.reshape(self.conv2,[-1, conv2_shape[1], conv2_shape[2], 1]),1)
self.merged_image = tf.summary.merge([summary_state,summary_conv1,summary_conv2])
summary_reward = tf.summary.scalar('reward',self.reward[0][0])
summary_frag = tf.summary.scalar('frag',self.frag[0][0])
summary_death = tf.summary.scalar('death',self.death[0][0])
self.merged_testscore = tf.summary.merge([summary_reward,summary_frag,summary_death])
self.writer = tf.summary.FileWriter(LOG_DIR,SESS.graph)
def test_func(self,s1,a,r):
s1 = np.array([s1])
a = np.array([a])
r = np.array([r])
temp=SESS.run([self.value,self.test1,self.test2,self.loss_policy,self.loss_value,self.entropy],feed_dict={self.state:s1, self.a_t:a, self.r_t:r})
print("\tvalue:%f\n\ttest1:%f\n\ttest2:%f\n\tloss_policy:%f\n\tloss_value:%f"%(temp[0],temp[1],temp[2],temp[3],temp[4]))
def calc_loss(self,step,s1,a,r):
loss_p,loss_v,entropy = SESS.run([self.loss_policy,self.loss_value,self.entropy],feed_dict={self.state:s1,self.a_t:a,self.r_t:r})
return loss_p,loss_v,entropy
def write_summary(self,step,s1,a,r):
m_s,m_i = SESS.run([self.merged_scalar,self.merged_image],feed_dict={self.state:s1,self.a_t:a,self.r_t:r})
self.writer.add_summary(m_s,step)
if step%1000 == 0:
self.writer.add_summary(m_i,step)
def write_records(self,step,r,f,d):
r = np.array([[r]])
f = np.array([[f]])
d = np.array([[d]])
m = SESS.run(self.merged_testscore,feed_dict={self.reward:r,self.frag:f,self.death:d})
self.writer.add_summary(m,step)
def save_model(self):
self.saver.save(SESS, MODEL_PATH)
# In[ ]:
class Agent(object):
def __init__(self,name,network):
self.name = name
self.network = network
self.memory = []
def act(self,s1):
global frames
if frames>=EPS_STEPS:
eps = EPS_END
else:
eps = EPS_START + frames*(EPS_END - EPS_START) / EPS_STEPS
if random.random() < eps:
action = np.zeros((N_ACTION,))
action[np.random.randint(0,6)] = 1
return action.tolist()
else:
s1 = np.array([s1])
action_prob = self.network.predict_policy(s1)[0]
action = np.zeros((N_ACTION,))
action[np.random.choice(N_ACTION,p=action_prob)] = 1
# action[np.argmax(action_prob)] = 1
return action.tolist()
def test_act(self,s1):
s1 = np.array([s1])
action_prob = self.network.predict_policy(s1)[0]
action = np.zeros((N_ACTION,))
action[np.random.choice(N_ACTION,p=action_prob)] = 1
# action[np.argmax(action_prob)] = 1
return action.tolist()
def advantage_push_network(self,s1,action,reward,s2,isterminal):
self.memory.append((s1,action,reward,s2))
if isterminal:
for i in range(len(self.memory)-1,-1,-1):
s1,a,r,s2 = self.memory[i]
if i==len(self.memory)-1:
self.R = 0
else:
self.R = r + GAMMA*self.R
self.network.train_push(s1,a,self.R,s2,isterminal)
self.memory = []
self.R = 0
self.network.update_parameter_server()
if len(self.memory)>=N_ADV:
for i in range(N_ADV-1,-1,-1):
s1,a,r,s2 = self.memory[i]
if i==N_ADV-1:
self.R = self.network.predict_value(np.array([s1]))[0][0]
else:
self.R = r + GAMMA*self.R
self.network.train_push(s1,a,self.R,s2,isterminal)
self.memory = []
self.R = 0
self.network.update_parameter_server()
# In[ ]:
class Network_local(object):
def __init__(self,name,parameter_server):
self.name = name
with tf.variable_scope(self.name):
self._model()
self._build_graph(parameter_server)
self.s1 = np.empty(shape=(100,RESOLUTION[0],RESOLUTION[1],RESOLUTION[2]),dtype=np.float32)
self.s2 = np.empty(shape=(100,RESOLUTION[0],RESOLUTION[1],RESOLUTION[2]),dtype=np.float32)
self.reward = np.empty(shape=(100,1),dtype=np.float32)
self.action = np.empty(shape=(100,N_ACTION),dtype=np.float32)
self.isterminal = np.empty(shape=(100,1),dtype=np.int8)
self.queue_pointer = 0
# print("-----LOCAL weights---")
# for w in self.weights_params:
# print(w)
# print("-----LOCAL grads---")
# for w in self.grads:
# print(w)
def _model(self): # Kerasでネットワークの形を定義します
self.state = NetworkSetting.state()
self.conv1 = NetworkSetting.conv1(self.state)
self.maxpool1 = NetworkSetting.maxpool1(self.conv1)
self.conv2 = NetworkSetting.conv2(self.maxpool1)
self.maxpool2 = NetworkSetting.maxpool2(self.conv2)
reshape = NetworkSetting.reshape(self.maxpool2)
fc1 = NetworkSetting.fc1(reshape)
with tf.variable_scope("policy"):
self.policy = NetworkSetting.policy(fc1)
with tf.variable_scope("value"):
self.value = NetworkSetting.value(fc1)
def _build_graph(self,parameter_server):
self.a_t = tf.placeholder(tf.float32, shape=(None, N_ACTION))
self.r_t = tf.placeholder(tf.float32, shape=(None,1))
log_prob = tf.log(tf.reduce_sum(self.policy * self.a_t, axis=1, keep_dims=True)+1e-10)
advantage = self.r_t - self.value
self.test1 = log_prob
self.test2 = advantage
loss_policy = -log_prob * tf.stop_gradient(advantage)
loss_value = COEFF_L_V * tf.square(advantage)
entropy = COEFF_ENT * tf.reduce_sum(self.policy * tf.log(self.policy + 1e-10), axis=1, keep_dims=True)
self.loss_total = tf.reduce_mean(loss_policy + loss_value + entropy)
self.test3 = loss_policy
self.test4 = loss_value
self.test5 = entropy
self.weights_params = tf.get_collection(tf.GraphKeys.TRAINABLE_VARIABLES, scope=self.name)
self.grads = tf.gradients(self.loss_total, self.weights_params)
# for i in self.grads:
# print(i)
# for i in self.weights_params:
# print(i)
self.update_global_weight_params = parameter_server.optimizer.apply_gradients(zip(self.grads, parameter_server.weights_params))
self.pull_global_weight_params = [l_p.assign(g_p) for l_p,g_p in zip(self.weights_params,parameter_server.weights_params)]
self.push_local_weight_params = [g_p.assign(l_p) for g_p,l_p in zip(parameter_server.weights_params,self.weights_params)]
def test_func(self,s1,a,r):
s1 = np.array([s1])
a = np.array([a])
r = np.array([r])
# temp=SESS.run([self.value,self.test1,self.test2,self.test3,self.test4,self.test5],feed_dict={self.state:s1, self.a_t:a, self.r_t:r})
# print("\tvalue:%f\n\ttest1:%f\n\ttest2:%f\n\tloss_policy:%f\n\tloss_value:%f"%(temp[0],temp[1],temp[2],temp[3],temp[4]))
temp = SESS.run([self.grads],feed_dict={self.state:s1, self.a_t:a, self.r_t:r})
# print(temp)
def pull_parameter_server(self):
SESS.run(self.pull_global_weight_params)
def push_parameter_server(self):
SESS.run(self.push_local_weight_params)
def show_weights(self):
hoge = SESS.run(self.weights_params)
for i in range(len(hoge)):
print(hoge[i])
def update_parameter_server(self):
if self.queue_pointer > 0:
s1 = self.s1[0:self.queue_pointer]
s2 = self.s2[0:self.queue_pointer]
r = self.reward[0:self.queue_pointer]
a = self.action[0:self.queue_pointer]
# print(self.name,s1.shape)
# print(self.queue_pointer)
feed_dict = {self.state: s1,self.a_t:a, self.r_t:r}
SESS.run(self.update_global_weight_params,feed_dict)
self.queue_pointer = 0
def predict_value(self,s):
v = SESS.run(self.value,feed_dict={self.state:s})
return v
def predict_policy(self,s):
feed_dict = {self.state:s}
prob = SESS.run(self.policy, feed_dict)
return prob
def train_push(self,s,a,r,s_,isterminal):
self.s1[self.queue_pointer] = s
self.s2[self.queue_pointer] = s_
self.action[self.queue_pointer] = a
self.reward[self.queue_pointer] = r
self.isterminal[self.queue_pointer] = isterminal
self.queue_pointer += 1
# In[ ]:
# -- main ここからメイン関数です------------------------------
# M0.global変数の定義と、セッションの開始です
frames = 0 # 全スレッドで共有して使用する総ステップ数
pre_frames = 0
isLearned = False # 学習が終了したことを示すフラグ
runout = False
SESS = tf.Session(config=tf.ConfigProto(log_device_placement=False)) # TensorFlowのセッション開始
# SESS = tf_debug.LocalCLIDebugWrapperSession(SESS)
# スレッドを作成します
with tf.device("/cpu:0"):
parameter_server = ParameterServer() # 全スレッドで共有するパラメータを持つエンティティです
with tf.device("/gpu:0"):
threads = [] # 並列して走るスレッド
for i in range(N_WORKERS):
thread_name = "local_thread"+str(i+1)
threads.append(Worker_thread(thread_name=thread_name, parameter_server=parameter_server))
test_env = TestEnvironment("test_env",parameter_server)
prelearning_env = DemoEnvironment("pre_learning",parameter_server,test_env)
# TensorFlowでマルチスレッドを実行します
SESS.run(tf.global_variables_initializer()) # TensorFlowを使う場合、最初に変数初期化をして、実行します
threads[0].environment.record=True
print("loading_demonstration")
prelearning_env.load_demonstration()
start_time = datetime.datetime.now()
print("pre learning")
prelearning_env.pre_learning()
# np.save(RECORDS_DIR+"pre_reward.npy",np.array(test_env.record_reward))
# np.save(RECORDS_DIR+"pre_frag.npy",np.array(test_env.record_frag))
# np.save(RECORDS_DIR+"pre_death.npy",np.array(test_env.record_death))
# np.save(RECORDS_DIR+"pre_loss_policy.npy",prelearning_env.loss_policy)
# np.save(RECORDS_DIR+"pre_loss_value.npy",prelearning_env.loss_value)
# np.save(RECORDS_DIR+"pre_entropy.npy",prelearning_env.entropy)
# np.save(RECORDS_DIR+"pre_frame.npy",prelearning_env.frame_record)
test_env.record_reward = []
test_env.record_frag = []
test_env.record_death = []
frames = 0
sleep(3.0)
start_time_async = datetime.datetime.now()
running_threads = []
for worker in threads:
job = lambda: worker.run() # この辺は、マルチスレッドを走らせる作法だと思って良い
t = threading.Thread(target=job)
t.start()
test_frame = 0
while True:
if frames >= test_frame and frames<test_frame+1000:
r,f,d = test_env.run()
parameter_server.write_records(frames,r,f,d)
test_frame += 1000
elif frames >= test_frame+1000:
print("TEST at %d~%d step cant be finished"%(test_frame, test_frame+1000-1))
test_frame += 1000
else:
pass
if datetime.datetime.now() > start_time_async+TIME_LEARN:
runout=True
isLearned = True
for worker in threads:
if not worker.environment.finished:
isLearned = False
if isLearned:
break
print("*****************************\nTIME to LEARNING:%.3f [sec]\n*****************************"%(datetime.datetime.now()-start_time).seconds)
# np.save(RECORDS_DIR+"reward.npy",np.array(test_env.record_reward))
# np.save(RECORDS_DIR+"frag.npy",np.array(test_env.record_frag))
# np.save(RECORDS_DIR+"death.npy",np.array(test_env.record_death))
# np.save(RECORDS_DIR+"loss_policy.npy",threads[0].environment.loss_policy)
# np.save(RECORDS_DIR+"loss_value.npy",threads[0].environment.loss_value)
# np.save(RECORDS_DIR+"entropy.npy",threads[0].environment.entropy)
# np.save(RECORDS_DIR+"frame.npy",threads[0].environment.frame_record)
parameter_server.save_model()
print("Learning phase is finished")
for i in range(3):
test_env.run()
test_env.run_gif()
| UTF-8 | Python | false | false | 44,392 | py | 82 | a3c_demo.py | 43 | 0.559416 | 0.543301 | 0 | 1,115 | 38.289686 | 424 |
shingo-kagami/raspi_videoplayer | 9,998,683,912,039 | 160b234dad992159156f5e5e1bbb0c012a444c50 | f1a6734b8349c2dded5b1aeccd7400067d25cf88 | /playlist.py | fe53bd1ff7fac0bd9b6e6338c0d849488c4c7305 | [
"BSD-2-Clause"
]
| permissive | https://github.com/shingo-kagami/raspi_videoplayer | 64f4ca5dafd867ddec0ffe6e7b68bf8cc648a3df | 875697c880edc5a19f8f5c69a065d88fc531f14b | refs/heads/master | 2020-12-03T17:52:18.945897 | 2019-12-27T07:41:39 | 2019-12-27T07:41:39 | 231,417,396 | 1 | 0 | null | null | null | null | null | null | null | null | null | null | null | null | null | # vids = [
#'/home/pi/Videos/aaa.mp4',
#'/home/pi/Videos/bbb.mp4',
#]
| UTF-8 | Python | false | false | 72 | py | 3 | playlist.py | 2 | 0.555556 | 0.527778 | 0 | 4 | 16.75 | 28 |
Arxcis/bitwise_sudoku | 8,727,373,571,654 | f8e7a4339a773931eb26950cd8d744b3dcba7ee5 | 7072a881d818ed031e45b34034107900d110d762 | /file.py | 77319791990297c7569550dcae2c04860cad542b | []
| no_license | https://github.com/Arxcis/bitwise_sudoku | 9e6885512b5d0f35a1962ae258bea875e8629cbf | 6100184aa25b0982a91442413db066379ab9c009 | refs/heads/master | 2017-05-08T15:41:33.529454 | 2017-02-17T12:19:56 | 2017-02-17T12:19:56 | 82,253,938 | 0 | 0 | null | null | null | null | null | null | null | null | null | null | null | null | null | #!/usr/local/bin/python3
#-*-coding:utf-8-*-
# File : file.py
# Exercise: Sudoku solver
# Author : Jonas Solsvik
# Email : jonas.solsvik@gmail.com
# Date : 16.02.17
# License : Free as in pizza
import pickle
toggle_bits = 0x1ff
top_bit = 0x200
single_bits = {
0 : 0x0,
1 : 0x1,
2 : 0x2,
3 : 0x4,
4 : 0x8,
5 : 0x10,
6 : 0x20,
7 : 0x40,
8 : 0x80,
9 : 0x100,
}
#
# Filepaths
#
filepath = "bit.hash"
filepath_intmap = "int.map"
filepath_bitmap = "bit.bmap"
filepath_bitgrid = "bit.grid"
filepath_solution = "solution.map"
#
# Bithash
#
def dump_bithash(bithash):
with open(filepath, 'wb') as file:
pickle.dump(bithash, file, protocol=2)
def load_bithash():
with open(filepath, 'rb') as file:
bithash = pickle.load(file)
return bithash
#
# Bitmap
#
def load_bitmap(path=""):
with open(filepath_bitmap, 'rb') as bitfile:
bitmap = pickle.load(bitfile)
return bitmap
def dump_bitmap(bitmap):
with open(filepath_bitmap, 'wb') as bitfile:
pickle.dump(bitmap, bitfile, protocol=2)
def save_solution(bitmap):
bithash = load_bithash()
with open(filepath_solution, 'a') as savefile:
for r in range(9):
for c in range(9):
savefile.write(str(bithash[bitmap[r][c]][0])+ " ")
savefile.write("\n")
savefile.write("\n")
def convert_intmap_to_bitmap(file=False,path=filepath_intmap):
bitmap = []
intmap = []
with open(path) as intfile:
file_contents = intfile.readlines()
for i in range(9):
line = file_contents[i].rstrip()
line = line.split(" ")
intmap.append([int(line[i]) for i in range(9)])
bitmap = [[((single_bits[intmap[i][j]] | top_bit) ^ toggle_bits) if single_bits[intmap[i][j]] > 0 else (0x0 | top_bit) for j in range(9)] for i in range(9) ]
if file:
with open(filepath_bitmap, 'wb') as bitfile:
pickle.dump(bitmap, bitfile, protocol=2)
return bitmap
def load_all_grids():
with open(filepath_bitgrid, "r") as gridfile:
box = gridfile.readline().rstrip()
col = gridfile.readline().rstrip()
row = gridfile.readline().rstrip()
box = box.split(" ")
col = col.split(" ")
row = row.split(" ")
box = [int(box[i]) for i in range(9)]
col = [int(col[i]) for i in range(9)]
row = [int(row[i]) for i in range(9)]
return box, col, row
| UTF-8 | Python | false | false | 2,463 | py | 4 | file.py | 3 | 0.583435 | 0.556638 | 0 | 122 | 19.188525 | 161 |
razinkovaleksey/chromedriver78extentionerror | 15,676,630,665,065 | 24159410e1c035219e386c6c600183f34f4d3c17 | 75dbbf709bb5ca431d2cca5e633216fb086e10b9 | /run.py | 2ca487eecef2b4a3fca204a11919350a033549d8 | []
| no_license | https://github.com/razinkovaleksey/chromedriver78extentionerror | 5154e0264c688c4466406adf1d1cd0cd6e42a26c | 30f4247e07fa153f542838c34914e5d59bb6df16 | refs/heads/master | 2020-08-30T21:08:21.141935 | 2019-10-30T09:38:27 | 2019-10-30T09:38:27 | 218,489,852 | 0 | 0 | null | null | null | null | null | null | null | null | null | null | null | null | null | import importlib
from selenium.webdriver.chrome.options import Options
wd = importlib.import_module('selenium.webdriver')
chrome = getattr(wd, 'Chrome')
chrome_options = Options()
chrome_options.add_extension('plugin.crx')
driver = chrome(options=chrome_options, service_args=["--verbose", "--log-path=qc1.log"])
| UTF-8 | Python | false | false | 328 | py | 1 | run.py | 1 | 0.731707 | 0.728659 | 0 | 11 | 27.818182 | 89 |
pedromneto97/ProjetoSOS | 5,463,198,416,612 | bb14655abcb4fdbf4b4eaa03a9424cc296a04f75 | cfbe46ac439cbcee24862fada33766587dc2c102 | /ESP32-Server/server.py | c5e0fbd32beb66550152c973f23b74f5499543d8 | []
| no_license | https://github.com/pedromneto97/ProjetoSOS | 9701ef32a1b18181ea8008c19a58bfd2942f02c3 | 3893069f39796d56fbccab1f2b105d8207071608 | refs/heads/master | 2020-03-09T13:18:37.561467 | 2018-11-19T23:52:38 | 2018-11-19T23:52:38 | 128,807,707 | 6 | 1 | null | false | 2018-11-19T23:52:39 | 2018-04-09T17:14:08 | 2018-11-19T23:50:12 | 2018-11-19T23:52:39 | 113 | 1 | 0 | 2 | Python | false | null | import socket
from gc import collect
from time import sleep_ms
import ujson
from machine import reset
from tipo import Tipo
# Classe do server
class Server:
# Construtor
def __init__(self, sta):
self.station = sta
def endereco(self):
confs = self.station.ifconfig() # Recebe as configurações de endereço
aux = confs[0].split('.') # Sepera o endereço IP por ponto
# Monta o 192.168.1.25
ip = str(aux[0]) + '.' + str(aux[1]) + '.' + str(aux[2]) + '.' + str(100)
# Define as configurações de IP, só alterando o IP do server
self.station.ifconfig((ip, confs[1], confs[2], confs[3]))
# Seta as variáveis como nada
del confs
del aux
return (ip, 5000)
# Servidor
def servidor(self, device, cadastro=False):
# Cria o socket
server = socket.socket(socket.AF_INET, socket.SOCK_STREAM)
if cadastro:
end = self.endereco()
server.bind(end) # Da bind no endereço
server.listen(1) # Começa a ouvir
print("Endereço: " + end[0])
print("Esperando:\n")
# Laço das mensagens do cliente
while True:
conn, addr = server.accept() # Recebe a conecção e o endereço
print('Conectado por: ' + str(addr))
msg = conn.recv(2048) # Recebe a mensagen
l = ujson.loads(msg.decode('utf-8'))
if l['id'] not in device.cadastrados.keys():
conn.close()
server.close()
return l['id']
conn.close()
else:
try:
end = self.endereco()
server.bind(end) # Da bind no endereço
server.listen(28) # Começa a ouvir
print("Endereço: " + str(end))
print("Esperando:\n")
# Laço das mensagens do cliente
while True:
conn, addr = server.accept() # Recebe a conecção e o endereço
print('Conectado por: ' + str(addr))
device.avisa()
msg = conn.recv(2048) # Recebe a mensagen
l = ujson.loads(msg.decode('utf-8'))
if l['id'] not in device.cadastrados.keys():
conn.close()
device.desliga_aviso()
continue
if l['tipo'] in device.lista.keys():
flag = True
for item in device.lista[l['tipo']]:
if item['id'] == l['id']:
item['chamadas'] += 1
l['chamadas'] = item['chamadas']
l['horas'] = item['horas']
l['minutos'] = item['minutos']
flag = False
break
if flag:
device.lista[l['tipo']].append({
'id': l['id'],
'horas': l['horas'],
'minutos': l['minutos'],
'chamadas': l['chamadas']
})
device.altera_tamanho(l['tipo'], True)
device.ordenar()
del flag
else:
device.desliga_aviso()
conn.close()
continue
device.reinicia_inativo()
ind = next(i for i, valor in enumerate(device.lista[l['tipo']]) if valor['id'] == l['id'])
if device.iterador['tipo'] != l['tipo'] or device.iterador['iterador'] != ind:
anterior = device.anterior()
device.iterador['tipo'] = l['tipo']
device.iterador['iterador'] = ind
device.escreve_oled(tipo=l['tipo'], nome=device.cadastrados[l['id']]['nome'],
quarto=device.cadastrados[l['id']]['quarto'], hora=l['horas'],
minuto=l['minutos'], chamadas=int(l['chamadas']), posicao=True,
anterior=anterior)
else:
device.escreve_oled(tipo=l['tipo'], nome=device.cadastrados[l['id']]['nome'],
quarto=device.cadastrados[l['id']]['quarto'], hora=l['horas'],
minuto=l['minutos'], chamadas=int(l['chamadas']), posicao=True)
sleep_ms(300)
device.desliga_aviso()
collect()
conn.close() # Fecha a conexão
except:
if len(device.lista[Tipo.EMERGENCIA]) > 0 or len(device.lista[Tipo.AJUDA]) > 0 or len(
device.lista[Tipo.BATERIA]) > 0:
try:
f = open('estado.json', 'w')
f.write(ujson.dumps(device.lista))
f.close()
except:
print("Erro ao salvar estado")
reset()
| UTF-8 | Python | false | false | 5,406 | py | 10 | server.py | 9 | 0.424113 | 0.415939 | 0 | 119 | 44.235294 | 110 |
M-Kub/PyScraping | 15,659,450,765,061 | e5c7127c6bb8464cf481abc2dfd7bb0862d86fa1 | 856d89ab37dc378d8aaad84ac5e0f58638fb8ace | /imaspi.py | b853bc15a87d8f3be8fed97de08e1b687a685368 | []
| no_license | https://github.com/M-Kub/PyScraping | 9c5a1dff6a706386853fe14562e52982d139c724 | 7567b9a6fba40cf1cba09fdf02c6e67080ed81c3 | refs/heads/master | 2020-08-24T04:19:38.099784 | 2019-11-18T10:52:22 | 2019-11-18T10:52:22 | 216,761,050 | 0 | 0 | null | null | null | null | null | null | null | null | null | null | null | null | null | from urllib.request import urlopen
from bs4 import BeautifulSoup
import re
html = urlopen('https://cdn1.spiegel.de')
bs = BeautifulSoup(html, 'html.parser')
images = bs.find_all('img',
{'src': re.compile('/images/image.*.jpg')})
for image in images:
print(image['src'])
print(len(images))
| UTF-8 | Python | false | false | 300 | py | 6 | imaspi.py | 6 | 0.696667 | 0.69 | 0 | 13 | 22.076923 | 47 |
maiyeu97/nguyenduyhoang-fundermental-c4e14 | 962,072,681,190 | ffd4d5678a4619048e914b7db88adec6227654e7 | ff349a301c6c261bbaed6b207a29413be1efb9ef | /fundamental/session01/hinh_tam_giac.py | 03ce64384af16a878b413780f74530119931098f | []
| no_license | https://github.com/maiyeu97/nguyenduyhoang-fundermental-c4e14 | 955c48dc195df6edf071fb8797931768a84a52fc | 4ab42e9a36b841215a8da20ca2933375f4f1598e | refs/heads/master | 2020-03-15T23:42:32.624930 | 2018-05-07T02:58:25 | 2018-05-07T02:58:25 | 112,141,401 | 0 | 0 | null | null | null | null | null | null | null | null | null | null | null | null | null | from turtle import *
color("red")
shape("arrow")
# speed(-1)
for i in range(20):
forward(200)
left(120)
mainloop()
| UTF-8 | Python | false | false | 123 | py | 85 | hinh_tam_giac.py | 69 | 0.634146 | 0.560976 | 0 | 8 | 14.375 | 20 |
babamba/sideAppServer | 352,187,351,227 | 9ed597e205df21b28180a10f5aa9b0d63ea98a9b | 7958401b2fb438f6bbc518e6b536cc8ec28bd559 | /TodaySalary/users/migrations/0008_user_push_token.py | 1cc821b6e86fc9b6914f6d96dd0d02b50a640875 | [
"MIT"
]
| permissive | https://github.com/babamba/sideAppServer | db49a209802b90cbbade70aaa23d0cce1f4c2208 | 607d61cbea9d05fe902b9f8e772bbd9f7baca28c | refs/heads/master | 2022-12-13T12:52:15.944602 | 2019-03-31T03:07:49 | 2019-03-31T03:07:49 | 174,468,137 | 0 | 0 | MIT | false | 2022-12-09T15:04:51 | 2019-03-08T04:19:03 | 2019-03-31T03:08:00 | 2022-12-09T15:04:50 | 8,042 | 0 | 0 | 31 | JavaScript | false | false | # Generated by Django 2.0.9 on 2019-03-26 17:31
from django.db import migrations, models
class Migration(migrations.Migration):
dependencies = [
('users', '0007_auto_20190311_1641'),
]
operations = [
migrations.AddField(
model_name='user',
name='push_token',
field=models.TextField(default=''),
),
]
| UTF-8 | Python | false | false | 381 | py | 41 | 0008_user_push_token.py | 35 | 0.574803 | 0.493438 | 0 | 18 | 20.166667 | 47 |
thauptfeld/CAT | 18,803,366,841,289 | 138aae520cde5f235fd5dda882b46e788b82f493 | 6b1ec5a21b99b6741b8b2b58ae59aa3411daa9b6 | /CAT_pack/contigs.py | df9ec319a704f04a2a8d8704d0d1d857e774646a | [
"MIT"
]
| permissive | https://github.com/thauptfeld/CAT | bf0bf7d653a1386ac3ae01df1dfeebca0e0d4020 | e41ebd66a059b67b43c8e141002f37b3df755509 | refs/heads/master | 2023-05-04T12:29:28.844113 | 2021-06-01T11:18:19 | 2021-06-01T11:18:19 | null | 0 | 0 | null | null | null | null | null | null | null | null | null | null | null | null | null | #!/usr/bin/env python3
import argparse
import decimal
import sys
import about
import check
import shared
import tax
def parse_arguments():
parser = argparse.ArgumentParser(
prog='CAT contigs',
description='Run Contig Annotation Tool (CAT).',
usage='CAT contigs -c -d -t [options] [-h / --help]',
add_help=False)
required = parser.add_argument_group('Required arguments')
shared.add_argument(required, 'contigs_fasta', True)
shared.add_argument(required, 'database_folder', True)
shared.add_argument(required, 'taxonomy_folder', True)
optional = parser.add_argument_group('Optional arguments')
shared.add_argument(optional, 'r', False, default=decimal.Decimal(10))
shared.add_argument(optional, 'f', False, default=decimal.Decimal(0.5))
shared.add_argument(optional, 'out_prefix', False, default='./out.CAT')
shared.add_argument(optional, 'proteins_fasta', False)
shared.add_argument(optional, 'alignment_file', False)
shared.add_argument(optional, 'path_to_prodigal', False,
default='prodigal')
shared.add_argument(optional, 'path_to_diamond', False, default='diamond')
shared.add_argument(optional, 'no_stars', False)
shared.add_argument(optional, 'force', False)
shared.add_argument(optional, 'quiet', False)
shared.add_argument(optional, 'verbose', False)
shared.add_argument(optional, 'no_log', False)
shared.add_argument(optional, 'help', False)
shared.add_argument(optional, 'IkwId', False)
specific = parser.add_argument_group('DIAMOND specific optional arguments')
shared.add_all_diamond_arguments(specific)
(args, extra_args) = parser.parse_known_args()
extra_args = [arg for (i, arg) in enumerate(extra_args) if
(i, arg) != (0, 'contigs')]
if len(extra_args) > 0:
sys.exit('error: too much arguments supplied:\n{0}'.format(
'\n'.join(extra_args)))
# Check experimental features.
if not args.IkwId:
if args.top < 50:
sys.exit('error: --top can only be set lower than 50 in '
'combination with the --I_know_what_Im_doing flag. See '
'README.md as to why this is the case.')
# Add extra arguments.
shared.expand_arguments(args)
return args
def run():
args = parse_arguments()
message = '# CAT v{0}.'.format(about.__version__)
shared.give_user_feedback(message, args.log_file, args.quiet,
show_time=False)
# Check at which state to start.
step_list = []
if not args.proteins_fasta and not args.alignment_file:
message = (
'\n'
'CAT is running. Protein prediction, alignment, and contig '
'classification are carried out.')
shared.give_user_feedback(message, args.log_file, args.quiet,
show_time=False)
step_list.append('predict_proteins')
step_list.append('align')
elif args.proteins_fasta and not args.alignment_file:
message = (
'\n'
'CAT is running. Since a predicted protein fasta is supplied, '
'only alignment and contig classification are carried out.')
shared.give_user_feedback(message, args.log_file, args.quiet,
show_time=False)
step_list.append('align')
elif args.proteins_fasta and args.alignment_file:
message = (
'\n'
'CAT is running. Since a predicted protein fasta and '
'alignment file are supplied, only contig classification is '
'carried out.')
shared.give_user_feedback(message, args.log_file, args.quiet,
show_time=False)
elif not args.proteins_fasta and args.alignment_file:
message = (
'if you want CAT to directly do the classification, you '
'should not only supply an alignment table but also a '
'predicted protein fasta file with argument '
'[-p / --proteins].')
shared.give_user_feedback(message, args.log_file, args.quiet,
error=True)
sys.exit(1)
step_list.append('classify')
# Print variables.
message = (
'Rarw!\n\n'
'Supplied command: {0}\n\n'
'Contigs fasta: {1}\n'
'Taxonomy folder: {2}\n'
'Database folder: {3}\n'
'Parameter r: {4}\n'
'Parameter f: {5}\n'
'Log file: {6}\n\n'
'-----------------\n'.format(
' '.join(sys.argv),
args.contigs_fasta,
args.taxonomy_folder,
args.database_folder,
int(args.r),
float(args.f),
args.log_file))
shared.give_user_feedback(message, args.log_file, args.quiet,
show_time=False)
# Check binaries, output files, taxonomy folder and database folder, and
# set variables.
message = 'Doing some pre-flight checks first.'
shared.give_user_feedback(message, args.log_file, args.quiet,
show_time=False)
errors = []
errors.append(
check.check_out_prefix(args.out_prefix, args.log_file, args.quiet))
if 'predict_proteins' in step_list:
errors.append(
check.check_prodigal_binaries(
args.path_to_prodigal, args.log_file, args.quiet))
setattr(args,
'proteins_fasta',
'{0}.predicted_proteins.faa'.format(args.out_prefix))
setattr(args,
'proteins_gff',
'{0}.predicted_proteins.gff'.format(args.out_prefix))
if not args.force:
errors.append(
check.check_output_file(
args.proteins_fasta, args.log_file, args.quiet))
errors.append(
check.check_output_file(
args.proteins_gff, args.log_file, args.quiet))
if 'align' in step_list:
errors.append(
check.check_diamond_binaries(
args.path_to_diamond, args.log_file, args.quiet))
setattr(args,
'alignment_file',
'{0}.alignment.diamond'.format(args.out_prefix))
if not args.force:
errors.append(
check.check_output_file(
args.alignment_file, args.log_file, args.quiet))
errors.append(
check.check_folders_for_run(
args.taxonomy_folder,
args.nodes_dmp,
args.names_dmp,
args.database_folder,
args.diamond_database,
args.fastaid2LCAtaxid_file,
args.taxids_with_multiple_offspring_file,
step_list,
args.log_file,
args.quiet))
setattr(args,
'contig2classification_output_file',
'{0}.contig2classification.txt'.format(args.out_prefix))
setattr(args,
'ORF2LCA_output_file',
'{0}.ORF2LCA.txt'.format(args.out_prefix))
if not args.force:
errors.append(
check.check_output_file(
args.contig2classification_output_file,
args.log_file,
args.quiet))
errors.append(
check.check_output_file(
args.ORF2LCA_output_file, args.log_file, args.quiet))
if 'predict_proteins' not in step_list:
errors.append(
check.check_fasta(
args.proteins_fasta, args.log_file, args.quiet))
if 'align' in step_list:
errors.append(
check.check_top(args.top, args.r, args.log_file, args.quiet))
# Print all variables.
shared.print_variables(args, step_list)
if True in errors:
sys.exit(1)
message = 'Ready to fly!\n\n-----------------\n'
shared.give_user_feedback(message, args.log_file, args.quiet,
show_time=False)
# Start CAT.
contig_names = shared.import_contig_names(
args.contigs_fasta, args.log_file, args.quiet)
if 'predict_proteins' in step_list:
shared.run_prodigal(
args.path_to_prodigal,
args.contigs_fasta,
args.proteins_fasta,
args.proteins_gff,
args.log_file,
args.quiet)
contig2ORFs = shared.import_ORFs(
args.proteins_fasta, args.log_file, args.quiet)
check.check_whether_ORFs_are_based_on_contigs(
contig_names, contig2ORFs, args.log_file, args.quiet)
if 'align' in step_list:
shared.run_diamond(args)
(ORF2hits,
all_hits) = shared.parse_tabular_alignment(
args.alignment_file,
args.one_minus_r,
args.log_file,
args.quiet)
(taxid2parent,
taxid2rank) = tax.import_nodes(
args.nodes_dmp, args.log_file, args.quiet)
fastaid2LCAtaxid = tax.import_fastaid2LCAtaxid(
args.fastaid2LCAtaxid_file, all_hits, args.log_file, args.quiet)
taxids_with_multiple_offspring = tax.import_taxids_with_multiple_offspring(
args.taxids_with_multiple_offspring_file,
args.log_file,
args.quiet)
message = 'CAT is spinning! Files {0} and {1} are created.'.format(
args.contig2classification_output_file, args.ORF2LCA_output_file)
shared.give_user_feedback(message, args.log_file, args.quiet)
n_classified_contigs = 0
with open(args.contig2classification_output_file, 'w') as outf1, open(args.ORF2LCA_output_file, 'w') as outf2:
outf1.write(
'# contig\tclassification\treason\tlineage\tlineage scores\n')
outf2.write('# ORF\tnumber of hits\tlineage\ttop bit-score\n')
for contig in sorted(contig_names):
if contig not in contig2ORFs:
outf1.write('{0}\tno taxid assigned\tno ORFs found\n'.format(
contig))
continue
LCAs_ORFs = []
for ORF in contig2ORFs[contig]:
if ORF not in ORF2hits:
outf2.write('{0}\tORF has no hit to database\n'.format(
ORF))
continue
n_hits = len(ORF2hits[ORF])
(taxid,
top_bitscore) = tax.find_LCA_for_ORF(
ORF2hits[ORF], fastaid2LCAtaxid, taxid2parent)
if taxid.startswith('no taxid found'):
outf2.write('{0}\t{1}\t{2}\t{3}\n'.format(
ORF, n_hits, taxid, top_bitscore))
else:
lineage = tax.find_lineage(taxid, taxid2parent)
if not args.no_stars:
lineage = tax.star_lineage(
lineage, taxids_with_multiple_offspring)
outf2.write('{0}\t{1}\t{2}\t{3}\n'.format(
ORF, n_hits, ';'.join(lineage[::-1]), top_bitscore))
LCAs_ORFs.append((taxid, top_bitscore),)
if len(LCAs_ORFs) == 0:
outf1.write('{0}\tno taxid assigned\t'
'no hits to database\n'.format(contig))
continue
(lineages,
lineages_scores,
based_on_n_ORFs) = tax.find_weighted_LCA(
LCAs_ORFs, taxid2parent, args.f)
if lineages == 'no ORFs with taxids found.':
outf1.write('{0}\tno taxid assigned\t'
'hits not found in taxonomy files\n'.format(contig))
continue
if lineages == 'no lineage whitelisted.':
outf1.write(
'{0}\tno taxid assigned\t'
'no lineage reached minimum bit-score support\n'
''.format(contig))
continue
# The contig has a valid classification.
n_classified_contigs += 1
for (i, lineage) in enumerate(lineages):
if not args.no_stars:
lineage = tax.star_lineage(
lineage, taxids_with_multiple_offspring)
scores = ['{0:.2f}'.format(score) for
score in lineages_scores[i]]
if len(lineages) == 1:
# There is only one classification.
outf1.write(
'{0}\t'
'taxid assigned\t'
'based on {1}/{2} ORFs\t'
'{3}\t'
'{4}\n'.format(
contig,
based_on_n_ORFs,
len(contig2ORFs[contig]),
';'.join(lineage[::-1]),
';'.join(scores[::-1])))
else:
# There are multiple classifications.
outf1.write(
'{0}\t'
'taxid assigned ({1}/{2})\t'
'based on {3}/{4} ORFs\t'
'{5}\t'
'{6}\n'.format(
contig,
i + 1,
len(lineages),
based_on_n_ORFs,
len(contig2ORFs[contig]),
';'.join(lineage[::-1]),
';'.join(scores[::-1])))
message = ('\n-----------------\n\n'
'{0} CAT is done! {1:,d}/{2:,d} contigs have taxonomy assigned.'
''.format(
shared.timestamp(),
n_classified_contigs,
len(contig_names)))
shared.give_user_feedback(message, args.log_file, args.quiet,
show_time=False)
if args.f < 0.5:
message = ('\nWARNING: since f is set to smaller than 0.5, one contig '
'may have multiple classifications.')
shared.give_user_feedback(message, args.log_file, args.quiet,
show_time=False)
return
if __name__ == '__main__':
sys.exit('Run \'CAT contigs\' to run Contig Annotation Tool (CAT).')
| UTF-8 | Python | false | false | 14,781 | py | 12 | contigs.py | 10 | 0.512956 | 0.505108 | 0 | 401 | 35.860349 | 114 |
JetBrains/intellij-community | 11,003,706,217,897 | 4a4e9c07f643f46ceadb10d7d06f7feb71a302f9 | eb9f655206c43c12b497c667ba56a0d358b6bc3a | /python/helpers/typeshed/stdlib/turtle.pyi | 13197c336e5ed549b65cec3c966e9fd223c72c31 | [
"Apache-2.0",
"MIT"
]
| permissive | https://github.com/JetBrains/intellij-community | 2ed226e200ecc17c037dcddd4a006de56cd43941 | 05dbd4575d01a213f3f4d69aa4968473f2536142 | refs/heads/master | 2023-09-03T17:06:37.560889 | 2023-09-03T11:51:00 | 2023-09-03T12:12:27 | 2,489,216 | 16,288 | 6,635 | Apache-2.0 | false | 2023-09-12T07:41:58 | 2011-09-30T13:33:05 | 2023-09-12T03:37:30 | 2023-09-12T06:46:46 | 4,523,919 | 15,754 | 4,972 | 237 | null | false | false | from _typeshed import Self
from collections.abc import Callable, Sequence
from tkinter import Canvas, Frame, Misc, PhotoImage, Scrollbar
from typing import Any, ClassVar, Union, overload
from typing_extensions import TypeAlias
__all__ = [
"ScrolledCanvas",
"TurtleScreen",
"Screen",
"RawTurtle",
"Turtle",
"RawPen",
"Pen",
"Shape",
"Vec2D",
"addshape",
"bgcolor",
"bgpic",
"bye",
"clearscreen",
"colormode",
"delay",
"exitonclick",
"getcanvas",
"getshapes",
"listen",
"mainloop",
"mode",
"numinput",
"onkey",
"onkeypress",
"onkeyrelease",
"onscreenclick",
"ontimer",
"register_shape",
"resetscreen",
"screensize",
"setup",
"setworldcoordinates",
"textinput",
"title",
"tracer",
"turtles",
"update",
"window_height",
"window_width",
"back",
"backward",
"begin_fill",
"begin_poly",
"bk",
"circle",
"clear",
"clearstamp",
"clearstamps",
"clone",
"color",
"degrees",
"distance",
"dot",
"down",
"end_fill",
"end_poly",
"fd",
"fillcolor",
"filling",
"forward",
"get_poly",
"getpen",
"getscreen",
"get_shapepoly",
"getturtle",
"goto",
"heading",
"hideturtle",
"home",
"ht",
"isdown",
"isvisible",
"left",
"lt",
"onclick",
"ondrag",
"onrelease",
"pd",
"pen",
"pencolor",
"pendown",
"pensize",
"penup",
"pos",
"position",
"pu",
"radians",
"right",
"reset",
"resizemode",
"rt",
"seth",
"setheading",
"setpos",
"setposition",
"settiltangle",
"setundobuffer",
"setx",
"sety",
"shape",
"shapesize",
"shapetransform",
"shearfactor",
"showturtle",
"speed",
"st",
"stamp",
"tilt",
"tiltangle",
"towards",
"turtlesize",
"undo",
"undobufferentries",
"up",
"width",
"write",
"xcor",
"ycor",
"write_docstringdict",
"done",
"Terminator",
]
# Note: '_Color' is the alias we use for arguments and _AnyColor is the
# alias we use for return types. Really, these two aliases should be the
# same, but as per the "no union returns" typeshed policy, we'll return
# Any instead.
_Color: TypeAlias = Union[str, tuple[float, float, float]]
_AnyColor: TypeAlias = Any
# TODO: Replace this with a TypedDict once it becomes standardized.
_PenState: TypeAlias = dict[str, Any]
_Speed: TypeAlias = str | float
_PolygonCoords: TypeAlias = Sequence[tuple[float, float]]
class Vec2D(tuple[float, float]):
def __new__(cls: type[Self], x: float, y: float) -> Self: ...
def __add__(self, other: tuple[float, float]) -> Vec2D: ... # type: ignore[override]
@overload # type: ignore[override]
def __mul__(self, other: Vec2D) -> float: ...
@overload
def __mul__(self, other: float) -> Vec2D: ...
def __rmul__(self, other: float) -> Vec2D: ... # type: ignore[override]
def __sub__(self, other: tuple[float, float]) -> Vec2D: ...
def __neg__(self) -> Vec2D: ...
def __abs__(self) -> float: ...
def rotate(self, angle: float) -> Vec2D: ...
# Does not actually inherit from Canvas, but dynamically gets all methods of Canvas
class ScrolledCanvas(Canvas, Frame): # type: ignore[misc]
bg: str
hscroll: Scrollbar
vscroll: Scrollbar
def __init__(
self, master: Misc | None, width: int = ..., height: int = ..., canvwidth: int = ..., canvheight: int = ...
) -> None: ...
canvwidth: int
canvheight: int
def reset(self, canvwidth: int | None = ..., canvheight: int | None = ..., bg: str | None = ...) -> None: ...
class TurtleScreenBase:
cv: Canvas
canvwidth: int
canvheight: int
xscale: float
yscale: float
def __init__(self, cv: Canvas) -> None: ...
def mainloop(self) -> None: ...
def textinput(self, title: str, prompt: str) -> str | None: ...
def numinput(
self, title: str, prompt: str, default: float | None = ..., minval: float | None = ..., maxval: float | None = ...
) -> float | None: ...
class Terminator(Exception): ...
class TurtleGraphicsError(Exception): ...
class Shape:
def __init__(self, type_: str, data: _PolygonCoords | PhotoImage | None = ...) -> None: ...
def addcomponent(self, poly: _PolygonCoords, fill: _Color, outline: _Color | None = ...) -> None: ...
class TurtleScreen(TurtleScreenBase):
def __init__(self, cv: Canvas, mode: str = ..., colormode: float = ..., delay: int = ...) -> None: ...
def clear(self) -> None: ...
@overload
def mode(self, mode: None = ...) -> str: ...
@overload
def mode(self, mode: str) -> None: ...
def setworldcoordinates(self, llx: float, lly: float, urx: float, ury: float) -> None: ...
def register_shape(self, name: str, shape: _PolygonCoords | Shape | None = ...) -> None: ...
@overload
def colormode(self, cmode: None = ...) -> float: ...
@overload
def colormode(self, cmode: float) -> None: ...
def reset(self) -> None: ...
def turtles(self) -> list[Turtle]: ...
@overload
def bgcolor(self) -> _AnyColor: ...
@overload
def bgcolor(self, color: _Color) -> None: ...
@overload
def bgcolor(self, r: float, g: float, b: float) -> None: ...
@overload
def tracer(self, n: None = ...) -> int: ...
@overload
def tracer(self, n: int, delay: int | None = ...) -> None: ...
@overload
def delay(self, delay: None = ...) -> int: ...
@overload
def delay(self, delay: int) -> None: ...
def update(self) -> None: ...
def window_width(self) -> int: ...
def window_height(self) -> int: ...
def getcanvas(self) -> Canvas: ...
def getshapes(self) -> list[str]: ...
def onclick(self, fun: Callable[[float, float], object], btn: int = ..., add: Any | None = ...) -> None: ...
def onkey(self, fun: Callable[[], object], key: str) -> None: ...
def listen(self, xdummy: float | None = ..., ydummy: float | None = ...) -> None: ...
def ontimer(self, fun: Callable[[], object], t: int = ...) -> None: ...
@overload
def bgpic(self, picname: None = ...) -> str: ...
@overload
def bgpic(self, picname: str) -> None: ...
@overload
def screensize(self, canvwidth: None = ..., canvheight: None = ..., bg: None = ...) -> tuple[int, int]: ...
# Looks like if self.cv is not a ScrolledCanvas, this could return a tuple as well
@overload
def screensize(self, canvwidth: int, canvheight: int, bg: _Color | None = ...) -> None: ...
onscreenclick = onclick
resetscreen = reset
clearscreen = clear
addshape = register_shape
def onkeypress(self, fun: Callable[[], object], key: str | None = ...) -> None: ...
onkeyrelease = onkey
class TNavigator:
START_ORIENTATION: dict[str, Vec2D]
DEFAULT_MODE: str
DEFAULT_ANGLEOFFSET: int
DEFAULT_ANGLEORIENT: int
def __init__(self, mode: str = ...) -> None: ...
def reset(self) -> None: ...
def degrees(self, fullcircle: float = ...) -> None: ...
def radians(self) -> None: ...
def forward(self, distance: float) -> None: ...
def back(self, distance: float) -> None: ...
def right(self, angle: float) -> None: ...
def left(self, angle: float) -> None: ...
def pos(self) -> Vec2D: ...
def xcor(self) -> float: ...
def ycor(self) -> float: ...
@overload
def goto(self, x: tuple[float, float], y: None = ...) -> None: ...
@overload
def goto(self, x: float, y: float) -> None: ...
def home(self) -> None: ...
def setx(self, x: float) -> None: ...
def sety(self, y: float) -> None: ...
@overload
def distance(self, x: TNavigator | tuple[float, float], y: None = ...) -> float: ...
@overload
def distance(self, x: float, y: float) -> float: ...
@overload
def towards(self, x: TNavigator | tuple[float, float], y: None = ...) -> float: ...
@overload
def towards(self, x: float, y: float) -> float: ...
def heading(self) -> float: ...
def setheading(self, to_angle: float) -> None: ...
def circle(self, radius: float, extent: float | None = ..., steps: int | None = ...) -> None: ...
fd = forward
bk = back
backward = back
rt = right
lt = left
position = pos
setpos = goto
setposition = goto
seth = setheading
class TPen:
def __init__(self, resizemode: str = ...) -> None: ...
@overload
def resizemode(self, rmode: None = ...) -> str: ...
@overload
def resizemode(self, rmode: str) -> None: ...
@overload
def pensize(self, width: None = ...) -> int: ...
@overload
def pensize(self, width: int) -> None: ...
def penup(self) -> None: ...
def pendown(self) -> None: ...
def isdown(self) -> bool: ...
@overload
def speed(self, speed: None = ...) -> int: ...
@overload
def speed(self, speed: _Speed) -> None: ...
@overload
def pencolor(self) -> _AnyColor: ...
@overload
def pencolor(self, color: _Color) -> None: ...
@overload
def pencolor(self, r: float, g: float, b: float) -> None: ...
@overload
def fillcolor(self) -> _AnyColor: ...
@overload
def fillcolor(self, color: _Color) -> None: ...
@overload
def fillcolor(self, r: float, g: float, b: float) -> None: ...
@overload
def color(self) -> tuple[_AnyColor, _AnyColor]: ...
@overload
def color(self, color: _Color) -> None: ...
@overload
def color(self, r: float, g: float, b: float) -> None: ...
@overload
def color(self, color1: _Color, color2: _Color) -> None: ...
def showturtle(self) -> None: ...
def hideturtle(self) -> None: ...
def isvisible(self) -> bool: ...
# Note: signatures 1 and 2 overlap unsafely when no arguments are provided
@overload
def pen(self) -> _PenState: ... # type: ignore[misc]
@overload
def pen(
self,
pen: _PenState | None = ...,
*,
shown: bool = ...,
pendown: bool = ...,
pencolor: _Color = ...,
fillcolor: _Color = ...,
pensize: int = ...,
speed: int = ...,
resizemode: str = ...,
stretchfactor: tuple[float, float] = ...,
outline: int = ...,
tilt: float = ...,
) -> None: ...
width = pensize
up = penup
pu = penup
pd = pendown
down = pendown
st = showturtle
ht = hideturtle
class RawTurtle(TPen, TNavigator):
screen: TurtleScreen
screens: ClassVar[list[TurtleScreen]]
def __init__(
self, canvas: Canvas | TurtleScreen | None = ..., shape: str = ..., undobuffersize: int = ..., visible: bool = ...
) -> None: ...
def reset(self) -> None: ...
def setundobuffer(self, size: int | None) -> None: ...
def undobufferentries(self) -> int: ...
def clear(self) -> None: ...
def clone(self: Self) -> Self: ...
@overload
def shape(self, name: None = ...) -> str: ...
@overload
def shape(self, name: str) -> None: ...
# Unsafely overlaps when no arguments are provided
@overload
def shapesize(self) -> tuple[float, float, float]: ... # type: ignore[misc]
@overload
def shapesize(
self, stretch_wid: float | None = ..., stretch_len: float | None = ..., outline: float | None = ...
) -> None: ...
@overload
def shearfactor(self, shear: None = ...) -> float: ...
@overload
def shearfactor(self, shear: float) -> None: ...
# Unsafely overlaps when no arguments are provided
@overload
def shapetransform(self) -> tuple[float, float, float, float]: ... # type: ignore[misc]
@overload
def shapetransform(
self, t11: float | None = ..., t12: float | None = ..., t21: float | None = ..., t22: float | None = ...
) -> None: ...
def get_shapepoly(self) -> _PolygonCoords | None: ...
def settiltangle(self, angle: float) -> None: ...
@overload
def tiltangle(self, angle: None = ...) -> float: ...
@overload
def tiltangle(self, angle: float) -> None: ...
def tilt(self, angle: float) -> None: ...
# Can return either 'int' or Tuple[int, ...] based on if the stamp is
# a compound stamp or not. So, as per the "no Union return" policy,
# we return Any.
def stamp(self) -> Any: ...
def clearstamp(self, stampid: int | tuple[int, ...]) -> None: ...
def clearstamps(self, n: int | None = ...) -> None: ...
def filling(self) -> bool: ...
def begin_fill(self) -> None: ...
def end_fill(self) -> None: ...
def dot(self, size: int | None = ..., *color: _Color) -> None: ...
def write(self, arg: object, move: bool = ..., align: str = ..., font: tuple[str, int, str] = ...) -> None: ...
def begin_poly(self) -> None: ...
def end_poly(self) -> None: ...
def get_poly(self) -> _PolygonCoords | None: ...
def getscreen(self) -> TurtleScreen: ...
def getturtle(self: Self) -> Self: ...
getpen = getturtle
def onclick(self, fun: Callable[[float, float], object], btn: int = ..., add: bool | None = ...) -> None: ...
def onrelease(self, fun: Callable[[float, float], object], btn: int = ..., add: bool | None = ...) -> None: ...
def ondrag(self, fun: Callable[[float, float], object], btn: int = ..., add: bool | None = ...) -> None: ...
def undo(self) -> None: ...
turtlesize = shapesize
class _Screen(TurtleScreen):
def __init__(self) -> None: ...
# Note int and float are interpreted differently, hence the Union instead of just float
def setup(
self,
width: int | float = ..., # noqa: Y041
height: int | float = ..., # noqa: Y041
startx: int | None = ...,
starty: int | None = ...,
) -> None: ...
def title(self, titlestring: str) -> None: ...
def bye(self) -> None: ...
def exitonclick(self) -> None: ...
class Turtle(RawTurtle):
def __init__(self, shape: str = ..., undobuffersize: int = ..., visible: bool = ...) -> None: ...
RawPen = RawTurtle
Pen = Turtle
def write_docstringdict(filename: str = ...) -> None: ...
# Note: it's somewhat unfortunate that we have to copy the function signatures.
# It would be nice if we could partially reduce the redundancy by doing something
# like the following:
#
# _screen: Screen
# clear = _screen.clear
#
# However, it seems pytype does not support this type of syntax in pyi files.
# Functions copied from TurtleScreenBase:
# Note: mainloop() was always present in the global scope, but was added to
# TurtleScreenBase in Python 3.0
def mainloop() -> None: ...
def textinput(title: str, prompt: str) -> str | None: ...
def numinput(
title: str, prompt: str, default: float | None = ..., minval: float | None = ..., maxval: float | None = ...
) -> float | None: ...
# Functions copied from TurtleScreen:
def clear() -> None: ...
@overload
def mode(mode: None = ...) -> str: ...
@overload
def mode(mode: str) -> None: ...
def setworldcoordinates(llx: float, lly: float, urx: float, ury: float) -> None: ...
def register_shape(name: str, shape: _PolygonCoords | Shape | None = ...) -> None: ...
@overload
def colormode(cmode: None = ...) -> float: ...
@overload
def colormode(cmode: float) -> None: ...
def reset() -> None: ...
def turtles() -> list[Turtle]: ...
@overload
def bgcolor() -> _AnyColor: ...
@overload
def bgcolor(color: _Color) -> None: ...
@overload
def bgcolor(r: float, g: float, b: float) -> None: ...
@overload
def tracer(n: None = ...) -> int: ...
@overload
def tracer(n: int, delay: int | None = ...) -> None: ...
@overload
def delay(delay: None = ...) -> int: ...
@overload
def delay(delay: int) -> None: ...
def update() -> None: ...
def window_width() -> int: ...
def window_height() -> int: ...
def getcanvas() -> Canvas: ...
def getshapes() -> list[str]: ...
def onclick(fun: Callable[[float, float], object], btn: int = ..., add: Any | None = ...) -> None: ...
def onkey(fun: Callable[[], object], key: str) -> None: ...
def listen(xdummy: float | None = ..., ydummy: float | None = ...) -> None: ...
def ontimer(fun: Callable[[], object], t: int = ...) -> None: ...
@overload
def bgpic(picname: None = ...) -> str: ...
@overload
def bgpic(picname: str) -> None: ...
@overload
def screensize(canvwidth: None = ..., canvheight: None = ..., bg: None = ...) -> tuple[int, int]: ...
@overload
def screensize(canvwidth: int, canvheight: int, bg: _Color | None = ...) -> None: ...
onscreenclick = onclick
resetscreen = reset
clearscreen = clear
addshape = register_shape
def onkeypress(fun: Callable[[], object], key: str | None = ...) -> None: ...
onkeyrelease = onkey
# Functions copied from _Screen:
def setup(width: float = ..., height: float = ..., startx: int | None = ..., starty: int | None = ...) -> None: ...
def title(titlestring: str) -> None: ...
def bye() -> None: ...
def exitonclick() -> None: ...
def Screen() -> _Screen: ...
# Functions copied from TNavigator:
def degrees(fullcircle: float = ...) -> None: ...
def radians() -> None: ...
def forward(distance: float) -> None: ...
def back(distance: float) -> None: ...
def right(angle: float) -> None: ...
def left(angle: float) -> None: ...
def pos() -> Vec2D: ...
def xcor() -> float: ...
def ycor() -> float: ...
@overload
def goto(x: tuple[float, float], y: None = ...) -> None: ...
@overload
def goto(x: float, y: float) -> None: ...
def home() -> None: ...
def setx(x: float) -> None: ...
def sety(y: float) -> None: ...
@overload
def distance(x: TNavigator | tuple[float, float], y: None = ...) -> float: ...
@overload
def distance(x: float, y: float) -> float: ...
@overload
def towards(x: TNavigator | tuple[float, float], y: None = ...) -> float: ...
@overload
def towards(x: float, y: float) -> float: ...
def heading() -> float: ...
def setheading(to_angle: float) -> None: ...
def circle(radius: float, extent: float | None = ..., steps: int | None = ...) -> None: ...
fd = forward
bk = back
backward = back
rt = right
lt = left
position = pos
setpos = goto
setposition = goto
seth = setheading
# Functions copied from TPen:
@overload
def resizemode(rmode: None = ...) -> str: ...
@overload
def resizemode(rmode: str) -> None: ...
@overload
def pensize(width: None = ...) -> int: ...
@overload
def pensize(width: int) -> None: ...
def penup() -> None: ...
def pendown() -> None: ...
def isdown() -> bool: ...
@overload
def speed(speed: None = ...) -> int: ...
@overload
def speed(speed: _Speed) -> None: ...
@overload
def pencolor() -> _AnyColor: ...
@overload
def pencolor(color: _Color) -> None: ...
@overload
def pencolor(r: float, g: float, b: float) -> None: ...
@overload
def fillcolor() -> _AnyColor: ...
@overload
def fillcolor(color: _Color) -> None: ...
@overload
def fillcolor(r: float, g: float, b: float) -> None: ...
@overload
def color() -> tuple[_AnyColor, _AnyColor]: ...
@overload
def color(color: _Color) -> None: ...
@overload
def color(r: float, g: float, b: float) -> None: ...
@overload
def color(color1: _Color, color2: _Color) -> None: ...
def showturtle() -> None: ...
def hideturtle() -> None: ...
def isvisible() -> bool: ...
# Note: signatures 1 and 2 overlap unsafely when no arguments are provided
@overload
def pen() -> _PenState: ... # type: ignore[misc]
@overload
def pen(
pen: _PenState | None = ...,
*,
shown: bool = ...,
pendown: bool = ...,
pencolor: _Color = ...,
fillcolor: _Color = ...,
pensize: int = ...,
speed: int = ...,
resizemode: str = ...,
stretchfactor: tuple[float, float] = ...,
outline: int = ...,
tilt: float = ...,
) -> None: ...
width = pensize
up = penup
pu = penup
pd = pendown
down = pendown
st = showturtle
ht = hideturtle
# Functions copied from RawTurtle:
def setundobuffer(size: int | None) -> None: ...
def undobufferentries() -> int: ...
@overload
def shape(name: None = ...) -> str: ...
@overload
def shape(name: str) -> None: ...
# Unsafely overlaps when no arguments are provided
@overload
def shapesize() -> tuple[float, float, float]: ... # type: ignore[misc]
@overload
def shapesize(stretch_wid: float | None = ..., stretch_len: float | None = ..., outline: float | None = ...) -> None: ...
@overload
def shearfactor(shear: None = ...) -> float: ...
@overload
def shearfactor(shear: float) -> None: ...
# Unsafely overlaps when no arguments are provided
@overload
def shapetransform() -> tuple[float, float, float, float]: ... # type: ignore[misc]
@overload
def shapetransform(
t11: float | None = ..., t12: float | None = ..., t21: float | None = ..., t22: float | None = ...
) -> None: ...
def get_shapepoly() -> _PolygonCoords | None: ...
def settiltangle(angle: float) -> None: ...
@overload
def tiltangle(angle: None = ...) -> float: ...
@overload
def tiltangle(angle: float) -> None: ...
def tilt(angle: float) -> None: ...
# Can return either 'int' or Tuple[int, ...] based on if the stamp is
# a compound stamp or not. So, as per the "no Union return" policy,
# we return Any.
def stamp() -> Any: ...
def clearstamp(stampid: int | tuple[int, ...]) -> None: ...
def clearstamps(n: int | None = ...) -> None: ...
def filling() -> bool: ...
def begin_fill() -> None: ...
def end_fill() -> None: ...
def dot(size: int | None = ..., *color: _Color) -> None: ...
def write(arg: object, move: bool = ..., align: str = ..., font: tuple[str, int, str] = ...) -> None: ...
def begin_poly() -> None: ...
def end_poly() -> None: ...
def get_poly() -> _PolygonCoords | None: ...
def getscreen() -> TurtleScreen: ...
def getturtle() -> Turtle: ...
getpen = getturtle
def onrelease(fun: Callable[[float, float], object], btn: int = ..., add: Any | None = ...) -> None: ...
def ondrag(fun: Callable[[float, float], object], btn: int = ..., add: Any | None = ...) -> None: ...
def undo() -> None: ...
turtlesize = shapesize
# Functions copied from RawTurtle with a few tweaks:
def clone() -> Turtle: ...
# Extra functions present only in the global scope:
done = mainloop
| UTF-8 | Python | false | false | 21,990 | pyi | 127,182 | turtle.pyi | 70,394 | 0.574488 | 0.572487 | 0 | 695 | 30.640288 | 122 |
Kacper99/spotifydl | 13,743,895,362,718 | 1076a57e73bfd06f04ce693a687033f018c9d671 | 29c4ddb536572aea3cec856355fa4b2edd2b2c3b | /spotifydl.py | 335d625aa2095708e539b4fb2250d6e687a584e9 | []
| no_license | https://github.com/Kacper99/spotifydl | 614fe48590fca4c2dbdcaa30175aa84fbe55f78d | 87489b8056e5b128e69bfb220501319253ff1329 | refs/heads/master | 2022-11-07T11:54:07.051296 | 2020-06-26T20:17:41 | 2020-06-26T20:17:41 | 275,000,335 | 0 | 0 | null | null | null | null | null | null | null | null | null | null | null | null | null | import spotipy
import spotipy.oauth2 as oauth2
import argparse
import os
import multiprocessing
from downloader import Downloader
from itertools import product
save_dir = '/'
def get_args():
parser = argparse.ArgumentParser('Download your spotify playlist through youtubedl')
parser.add_argument('--id', help='Spotify client ID')
parser.add_argument('--secret', help='Spotify client secret')
parser.add_argument('-c', action='store_true',
help='If you want to pass the username and playlist ID using command line use this')
parser.add_argument('--username', help='Username of the authors playlist')
parser.add_argument('--playlist_uri', help='URI of the playlist')
parser.add_argument('--dir', help='Save destination directory')
return parser.parse_args()
def generate_token(id, secret):
credentials = oauth2.SpotifyClientCredentials(
client_id=id,
client_secret=secret)
return credentials.get_access_token(as_dict=False)
def get_playlist_tracks(S, username, playlist_id):
results = S.user_playlist_tracks(username, playlist_id)
tracks = results['items']
while results['next']:
results = S.next(results)
tracks.extend(results['items'])
return tracks
def get_track_names(S, username, playlist_id):
tracks = get_playlist_tracks(S, username, playlist_id)
print('Found {} tracks'.format(len(tracks)))
song_names = []
for track in tracks:
track = track['track']
song_name = track['name']
artists = ', '.join([artist['name'] for artist in track['artists']])
song_names.append((song_name, artists))
return song_names
if __name__ == '__main__':
args = get_args()
token = generate_token(args.id, args.secret)
spotify = spotipy.Spotify(auth=token)
songs = None
if args.c is False:
args.username = input('Spotify Username (e.g. johndoe123):\n')
args.playlist_uri = input('Spotify playlist URI (e.g. spotify:playlist:xxxxxxxxxxxxxxxxxxxxxx):\n')
args.dir = input('Save directory (e.g. ~/Desktop/Summer Tunes 2020):\n')
songs = get_track_names(spotify, args.username, args.playlist_uri)
dl = Downloader(args.dir)
pool = multiprocessing.Pool(5)
pool.map(dl.download_song, songs)
| UTF-8 | Python | false | false | 2,304 | py | 4 | spotifydl.py | 2 | 0.671441 | 0.666667 | 0 | 68 | 32.882353 | 108 |
jik0730/csed331-algorithms | 12,008,728,579,512 | b23c76378f9b2872f6fc1ec314bac37f71fc7130 | f8d649847f592ec492566050d9e0cff27ec3ffff | /assn8/p1.py | 1f961a7b09855f9344c0def3f85730f5a6bc4863 | []
| no_license | https://github.com/jik0730/csed331-algorithms | 35044808ccdcabb02a3077fff9a30dd3f6ac9166 | 9cf6b519e9beba71ee05228e50c60ffe732d9b3f | refs/heads/master | 2021-01-01T06:52:35.188802 | 2017-07-18T01:23:04 | 2017-07-18T01:23:04 | 97,537,313 | 0 | 0 | null | null | null | null | null | null | null | null | null | null | null | null | null | import sys
import itertools
def main():
numOfTests = int(sys.stdin.readline())
while numOfTests:
n, m = map(int, sys.stdin.readline().split())
graph = makeGraph(n, m)
route_distance = TSP(graph)
if route_distance == float('inf'):
print -1
else:
print route_distance
numOfTests -= 1
"""
Description: Make adjacency matrix graph representation
"""
def makeGraph(numV, numE):
graph = [float('inf')]*numV
for i in range(numV):
graph[i] = [float('inf')]*numV
while numE:
u, v, c = map(int, sys.stdin.readline().split())
graph[u][v] = c
graph[v][u] = c
numE -= 1
return graph
"""
Description: TSP algorithm by dynamic programming
"""
def TSP(graph):
n = len(graph)
C = {(frozenset([0]), 0): 0}
for s in range(2, n+1):
for S in [frozenset(subset) for subset in itertools.combinations(range(n), s)]:
if 0 not in S:
continue
C[(S, 0)] = float('inf')
for j in S - frozenset([0]):
C[(S, j)] = min([C[S-frozenset([j]),i]+graph[i][j] for i in S-frozenset([j])])
print C
return min([C[frozenset(range(n)),j]+graph[j][0] for j in range(n)])
if __name__ == '__main__':
main() | UTF-8 | Python | false | false | 1,303 | py | 25 | p1.py | 24 | 0.534152 | 0.524942 | 0 | 51 | 24.568627 | 94 |
Melodyh20809/leetcode | 12,051,678,274,516 | d1e30d23d36a6af07c3e9d5b6f1b905e4734ce88 | 67b025788ba0319347c9eed0c49ce826921ad22c | /0724 pivotIndex.py | 5ee0f7547affac35fa0264cbf6ca138897fc9aa9 | []
| no_license | https://github.com/Melodyh20809/leetcode | d68b76f32b7acc21a4cbed40b2fdfa507cac6151 | 50a57dee36efd2d5ef311c66f3a75bd479b0a798 | refs/heads/master | 2020-12-20T19:18:49.908879 | 2020-10-03T14:38:28 | 2020-10-03T14:38:28 | 236,185,085 | 1 | 0 | null | null | null | null | null | null | null | null | null | null | null | null | null | class Solution:
def pivotIndex(self, nums):
if not nums:
return -1
if len(nums)==1:
return 0
l=0
r=sum(nums[1:])
for i in range(len(nums)-1):
if l==r:
return i
l=l+nums[i]
r=r-nums[i+1]
if l==r:
return len(nums)-1
return -1
x=Solution()
result=x.pivotIndex([1])
print(result) | UTF-8 | Python | false | false | 423 | py | 159 | 0724 pivotIndex.py | 159 | 0.439716 | 0.416076 | 0 | 19 | 21.315789 | 36 |
fatima72/raniai | 5,231,270,179,865 | dee136b78c09591ea8246a8889031fc124914dc8 | 1fee4378f4451984fdddf0323f13b96b13af1215 | /08-07/setmatrixzero.py | af44ea4b7e21756eb93598c74dc848f8988d238b | []
| no_license | https://github.com/fatima72/raniai | d67cc79cf9f64fbd920a25fe474495fbb5189f84 | 18ad4e8ccf43074e9732deae69d684cb6d266d21 | refs/heads/master | 2023-06-12T22:59:17.736468 | 2021-07-09T16:02:21 | 2021-07-09T16:02:21 | 383,495,989 | 0 | 0 | null | null | null | null | null | null | null | null | null | null | null | null | null | """
Given an m x n integer matrix matrix, if an element is 0, set its entire row and column to 0's, and return the matrix.
"""
m,n = list(map(int,input().split()))
matrix = []
zero_column = []
for _ in range(m):
column = list(map(int,input().split()))
for j in range(n):
if(column[j]==0):
column = [0]*n
zero_column.append(j)
break
matrix.append(column)
for j in zero_column:
for i in range(m):
matrix[i][j] = 0
print(matrix)
| UTF-8 | Python | false | false | 537 | py | 26 | setmatrixzero.py | 26 | 0.52514 | 0.515829 | 0 | 24 | 20.833333 | 118 |
NeverC12307/ImbalanceClassification | 10,969,346,516,392 | d6f15a152f204c386702cb33de3ffdb2c657d40a | 6a0263f8bbe1cb538a8e3bbfb6e094eb938a1396 | /other_people/AdaC2Classifier.py | 96456c26d27263ce1753584220d8de97cc0f3da0 | []
| no_license | https://github.com/NeverC12307/ImbalanceClassification | 812d4e8cab8c48c0435e155c68d3d1736b4094de | 754d89bccfeeb563de1d18b20c7ce2ae452c0908 | refs/heads/master | 2023-04-10T09:52:55.102927 | 2021-04-07T12:54:51 | 2021-04-07T12:54:51 | null | 0 | 0 | null | null | null | null | null | null | null | null | null | null | null | null | null | # 描述:来自论文 Cost-Sensitive Boosting for Classification of Imbalanced Data, Yanmin Sun
import numpy as np
from sklearn import metrics
from sklearn.tree import DecisionTreeClassifier
from data.read_data import get_data, shuffle_data
class AdaC2Classifier:
"""
代价敏感分类器
"""
def __init__(self, T, C):
"""
:param T: 迭代次数
:param C: 代价项字典,如 {1: 0.1, 0: 1},前面的 1 和 0 表示类别,后面的 0.1 和 1 表示分错样本付出的代价
"""
self.T = T # 总迭代次数
self.C = C
self.all_h = [] # 所有基分类器
self.all_alpha = [-1 for i in range(T)] # 所有 α
def fit(self, X, Y):
"""
训练模型
:param X: 样本
:param Y: 标签
"""
C = self.C
M = len(Y)
# 初始化样本权重
D = [1 / M for j in range(M)]
# 开始迭代
for t in range(self.T):
# 训练基分类器
clf = DecisionTreeClassifier(class_weight=C)
clf.fit(X, Y, sample_weight=D)
y_pred = clf.predict(X)
self.all_h.append(clf)
# 计算阿尔法
alpha = self.get_alpha(D, C, Y, y_pred)
self.all_alpha[t] = alpha
# 计算归一化因子
Z = self.get_normalization_factor(D, C, alpha, Y, y_pred)
# 更新权重
D = self.get_new_weights(D, C, alpha, Y, y_pred, Z) # 更新权重
def get_new_weights(self, D, C, alpha, Y, y_pred, Z):
"""
更新权重
:param D: 老权重
:param C: 代价项
:param alpha:
:param Y: 标签
:param y_pred:老预测标签
:param Z: 归一化因子
:return:
"""
M = len(Y)
# 新的权重
new_D = [-1 for i in range(M)]
for i in range(M):
if Y[i] == 0:
y = -1
else:
y = 1
if y_pred[i] == 0:
h = -1
else:
h = 1
new_D[i] = C[Y[i]] * D[i] * np.exp(-alpha * y * h) / Z
return new_D
def predict(self, X):
"""
预测样本
:param X:样本
:return: 标签
"""
all_y_pred = []
for i in range(self.T):
y_pred = self.all_h[i].predict(X)
all_y_pred.append(y_pred)
Y = []
for i, x in enumerate(X):
sum = 0
for j in range(self.T):
if all_y_pred[j][i] == 0:
h = -1
else:
h = 1
sum += self.all_alpha[j] * h
Y.append(np.sign(sum))
Y = np.array(Y, dtype=np.int8)
Y[Y == -1] = 0
return Y
def get_alpha(self, D, C, Y, y_pred):
"""
计算阿尔法
:param D:权重
:param C:代价项
:param Y:真实标签
:param y_pred:预测标签
:return:阿尔法
"""
# 样本数量
M = len(Y)
# 先求分子分母
sum_up = 0 # 分子
sum_down = 0 # 分母
for i in range(M):
if Y[i] == y_pred[i]:
sum_up += C[Y[i]] * D[i]
else:
sum_down += C[Y[i]] * D[i]
# 如果分母为0
if sum_down == 0:
sum_down = 0.1
alpha = np.log(sum_up / sum_down) / 2
return alpha
def get_normalization_factor(self, D, C, alpha, Y, y_pred):
"""
计算归一化因子
:param D:样本权重
:param C:代价项
:param alpha:
:param Y:真实标签
:param y_pred:预测标签
:return:归一化因子
"""
# 样本数量
M = len(Y)
Z = 0
for i in range(M):
if Y[i] == 0:
y = -1
else:
y = 1
if y_pred[i] == 0:
h = -1
else:
h = 1
Z += C[Y[i]] * D[i] * np.exp(-alpha * y * h)
return Z
if __name__ == '__main__':
# 获取原始数据
x, y = get_data([0, 6], -1, "1到5/yeast.dat")
x, y = shuffle_data(x, y)
x = np.array(x)
y = np.array(y, dtype=np.int8)
# y[y == 0] = -1
# 代价项
C = {1: 0.1, 0: 1}
x_train = x[:-100]
y_train = y[:-100]
x_val = x[-100:]
y_val = y[-100:]
clf = AdaC2Classifier(20, C)
clf.fit(x_train, y_train)
y_pred = clf.predict(x_val)
print("预测结果:")
print(y_pred)
print("原本标签:")
print(y_val)
val_acc = metrics.accuracy_score(y_val, y_pred)
val_precision = metrics.precision_score(y_val, y_pred)
val_recall = metrics.recall_score(y_val, y_pred)
val_f1 = metrics.f1_score(y_val, y_pred)
print("val_acc:%.2f val_precision:%.2f val_recall:%.2f val_f1:%.2f" %
(val_acc, val_precision, val_recall, val_f1))
| UTF-8 | Python | false | false | 5,050 | py | 38 | AdaC2Classifier.py | 20 | 0.424613 | 0.407811 | 0 | 209 | 20.92823 | 83 |
a77654135/ScrapyProject | 7,026,566,546,182 | 288eea3a71c57f830c766ba91d8c61a24e32c144 | 574ef9a69c4c5d9bef7331bde567e17b56ff7446 | /ScrapyProject/items/btbaItem.py | fe9644513b1138838c47a0de04cbe066e5383033 | []
| no_license | https://github.com/a77654135/ScrapyProject | 370ef835e8bd09c197c98dfdd97ac84511b3e278 | 59ed19ce4c9df1bbfd3f57ae9e765b5c66983f6d | refs/heads/master | 2018-10-04T22:42:17.732679 | 2018-06-08T03:06:11 | 2018-06-08T03:06:11 | 124,848,339 | 0 | 0 | null | null | null | null | null | null | null | null | null | null | null | null | null | # -*- coding: utf-8 -*-
"""
-------------------------------------------------
File Name: btbaItem
Author : talus
date: 2018/4/8 0008
Description :
-------------------------------------------------
"""
import sys
import scrapy
class BtbaItem(scrapy.Item):
category = scrapy.Field()
name = scrapy.Field()
cover = scrapy.Field()
desc = scrapy.Field()
year = scrapy.Field()
country = scrapy.Field()
type = scrapy.Field()
grade = scrapy.Field()
state = scrapy.Field()
detail_url = scrapy.Field()
download_list = scrapy.Field() | UTF-8 | Python | false | false | 603 | py | 35 | btbaItem.py | 28 | 0.490818 | 0.472454 | 0 | 26 | 22.076923 | 49 |
VijayKr0810/VijayProject | 13,632,226,232,886 | 8362385b7931aaf77c31f6ecd57db51d80f31e23 | 156287b4f229c117667fe2d2c365903b8aaf83c5 | /io_simulator/struct_check.py | 2a43cb25d3d2303c1fdb16539a1d2c63bb6587f9 | []
| no_license | https://github.com/VijayKr0810/VijayProject | 8e854682b648ef3ec732c2ff9c206c9e07e804c0 | 6b0776188df0890e6e33a8da8b8d8f92cff190d6 | refs/heads/master | 2020-08-31T15:12:32.266282 | 2019-10-31T10:09:16 | 2019-10-31T10:09:16 | 218,719,131 | 0 | 0 | null | null | null | null | null | null | null | null | null | null | null | null | null | import ctypes,struct
import ctypes
from ctypes import *
from datetime import datetime
curr_time = datetime.now()
print curr_time.year
print curr_time.month
print curr_time.day
print curr_time.hour
print curr_time.minute
print curr_time.second
print curr_time.microsecond/1000
| UTF-8 | Python | false | false | 328 | py | 10 | struct_check.py | 6 | 0.685976 | 0.67378 | 0 | 14 | 18.857143 | 32 |
finleysg/gamer-api | 16,801,912,091,784 | e33a7cb00da26e821ae7bdeedba0ea601073a01a | 9feb104f5542cca535b791a1eff769f484892ae2 | /core/migrations/0009_auto_20180422_0942.py | acba467071253b314d3054ef648040fa804810c1 | []
| no_license | https://github.com/finleysg/gamer-api | 013b7e02853890b3243ea5961d14c44e5e4ec717 | 9123fe7a59a509ebaa5c065e6ef10fe449fe6cf0 | refs/heads/master | 2020-02-28T01:19:10.836226 | 2018-07-03T18:59:31 | 2018-07-03T18:59:31 | 86,816,000 | 0 | 0 | null | false | 2020-08-17T02:57:22 | 2017-03-31T12:18:43 | 2020-08-17T02:56:58 | 2020-08-17T02:57:21 | 72 | 0 | 0 | 3 | Python | false | false | # Generated by Django 2.0.4 on 2018-04-22 14:42
from django.db import migrations, models
class Migration(migrations.Migration):
dependencies = [
('core', '0008_auto_20180422_0923'),
]
operations = [
migrations.RemoveField(
model_name='gang',
name='owner',
),
migrations.RemoveField(
model_name='gangmember',
name='gang',
),
migrations.RemoveField(
model_name='gangmember',
name='member',
),
migrations.AddField(
model_name='member',
name='friends',
field=models.ManyToManyField(blank=True, related_name='_member_friends_+', to='core.Member'),
),
migrations.DeleteModel(
name='Gang',
),
migrations.DeleteModel(
name='GangMember',
),
]
| UTF-8 | Python | false | false | 891 | py | 62 | 0009_auto_20180422_0942.py | 50 | 0.52413 | 0.489338 | 0 | 36 | 23.75 | 105 |
AronForero/Chameleon-Project-Back | 7,576,322,341,488 | 4ce44e66f4ce3c81ac2ab615d224d0139b6a6048 | 24eba2468a74f84ccaf92f0c78eaa8c6c6f5507c | /forum/views.py | 1dbcb60d1b99108fdbd3efcca695012fc7f82967 | []
| no_license | https://github.com/AronForero/Chameleon-Project-Back | 34692d391c3feb238208ee0e7bff837fc728fde9 | ce8c3309aa5e7125ff2eae657572897c94e3bb22 | refs/heads/develop | 2023-08-21T19:54:07.010381 | 2021-04-14T05:16:17 | 2021-04-14T05:16:17 | 262,084,897 | 0 | 1 | null | false | 2021-09-10T18:39:09 | 2020-05-07T15:14:32 | 2021-04-14T05:16:48 | 2021-09-10T18:39:09 | 141 | 0 | 1 | 2 | Python | false | false | """This file handles the logic that will be executed when the endpoint are called"""
from django.shortcuts import render
import datetime
from django.shortcuts import get_object_or_404
from rest_framework import status, viewsets
from rest_framework.response import Response
from rest_framework.permissions import AllowAny, IsAuthenticated
from .models import Topic,State, Replies
from .serializers import TopicSerializer, StateSerializer, RepliesSerializer
# Create your views here.
class TopicViewSet(viewsets.ModelViewSet):
"""
This class will handle all the logic for the Topics
"""
permission_classes = (IsAuthenticated,)
queryset = Topic.objects.filter(trashed=False)
serializer_class = TopicSerializer
class StateViewSet(viewsets.ModelViewSet):
"""
This class will handle all the logic for the State
"""
permission_classes = (IsAuthenticated,)
queryset = State.objects.filter(trashed=False)
serializer_class = StateSerializer
class RepliesViewSet(viewsets.ModelViewSet):
"""
This class will handle all the logic for the Replies
"""
permission_classes = (IsAuthenticated,)
queryset = Replies.objects.filter(trashed=False)
serializer_class = RepliesSerializer
| UTF-8 | Python | false | false | 1,243 | py | 10 | views.py | 9 | 0.760257 | 0.757844 | 0 | 38 | 31.710526 | 84 |
soitun/commcare-hq | 2,190,433,337,589 | f184db30b09a4c54fb9ec9af4ea637111ffe3b13 | 136b315c9573cbbd6d613e45c34c6e79e98c8b25 | /corehq/apps/hqcase/tests/test_case_api_permissions.py | 825168bbccd00508eb03bcda9e020d1de7e3e27c | [
"BSD-3-Clause"
]
| permissive | https://github.com/soitun/commcare-hq | 088074835dd9cb1507a3d57523e5065ae4533fd8 | 5ee0ecadc08ecd1691ee0a26f8907ae0728af28e | refs/heads/master | 2023-08-23T08:06:09.694400 | 2023-05-12T10:18:24 | 2023-05-12T10:18:24 | 124,774,234 | 0 | 0 | BSD-3-Clause | true | 2023-05-15T22:20:21 | 2018-03-11T16:08:49 | 2022-05-12T08:54:19 | 2023-05-15T22:20:21 | 789,886 | 0 | 0 | 13 | Python | false | false | import uuid
from contextlib import contextmanager
from django.http import QueryDict
from django.test import TestCase
from django.urls import reverse
from casexml.apps.case.mock import CaseBlock
from corehq import privileges
from corehq.apps.case_search.models import CaseSearchConfig
from corehq.apps.commtrack.tests.util import bootstrap_domain
from corehq.apps.es.case_search import case_search_adapter
from corehq.apps.es.client import manager
from corehq.apps.es.forms import form_adapter
from corehq.apps.es.tests.utils import case_search_es_setup, es_test
from corehq.apps.es.users import user_adapter
from corehq.apps.hqcase.api.get_list import get_list
from corehq.apps.locations.tests.util import setup_locations_and_types
from corehq.apps.users.models import HqPermissions, UserRole, WebUser
from corehq.form_processor.tests.utils import FormProcessorTestUtils
from corehq.util.es.testing import sync_users_to_es
from corehq.util.test_utils import (
disable_quickcache,
flag_enabled,
privilege_enabled,
)
@es_test(requires=[
case_search_adapter,
form_adapter,
user_adapter,
], setup_class=True)
@disable_quickcache
@privilege_enabled(privileges.API_ACCESS)
@flag_enabled('CASE_API_V0_6')
@flag_enabled('API_THROTTLE_WHITELIST')
class TestCaseAPIPermissions(TestCase):
domain = 'test-case-api-permissions'
@classmethod
def setUpClass(cls):
super().setUpClass()
cls.domain_obj = bootstrap_domain(cls.domain)
CaseSearchConfig.objects.create(pk=cls.domain, enabled=True)
location_types, locations = setup_locations_and_types(
cls.domain,
location_types=['country'],
stock_tracking_types=[],
locations=[('USA', []), ('RSA', [])],
)
cls.user_location = locations['RSA']
names_locations = [
('Joe', locations['USA']),
('Cyril', locations['RSA']),
]
case_blocks = get_case_blocks(names_locations)
case_search_es_setup(cls.domain, case_blocks)
cls.case_ids = [cb.case_id for cb in case_blocks]
@classmethod
def tearDownClass(cls):
FormProcessorTestUtils.delete_all_cases()
cls.domain_obj.delete()
super().tearDownClass()
def test_case_api_list_happy_path(self):
permissions = {
'edit_data': True,
'access_api': True,
}
with get_web_user(
self.domain,
self.user_location,
permissions,
self.client,
):
url = reverse('case_api', args=(self.domain,))
response = self.client.get(url)
self.assertEqual(response.status_code, 200)
json = response.json()
self.assertEqual(json['matching_records'], 2) # AssertionError: 0 != 2
def test_case_api_list_requires_access_all_locations(self):
permissions = {
'edit_data': True,
'access_api': True,
'access_all_locations': False,
}
with get_web_user(
self.domain,
self.user_location,
permissions,
self.client,
):
url = reverse('case_api', args=(self.domain,))
response = self.client.get(url)
self.assertEqual(response.status_code, 403)
def test_case_api_bulk_fetch_happy_path(self):
permissions = {
'edit_data': True,
'access_api': True,
}
with get_web_user(
self.domain,
self.user_location,
permissions,
self.client,
):
url = reverse('case_api_bulk_fetch', args=(self.domain,))
response = self.client.post(
url,
{'case_ids': self.case_ids},
content_type='application/json',
)
self.assertEqual(response.status_code, 200)
json = response.json()
self.assertEqual(json['matching_records'], 2) # AssertionError: 0 != 2
def test_case_api_bulk_fetch_requires_access_all_locations(self):
permissions = {
'edit_data': True,
'access_api': True,
'access_all_locations': False,
}
with get_web_user(
self.domain,
self.user_location,
permissions,
self.client,
):
url = reverse('case_api_bulk_fetch', args=(self.domain,))
response = self.client.post(
url,
{'case_ids': self.case_ids},
content_type='application/json',
)
self.assertEqual(response.status_code, 403)
def test_get_list_access_all_locations(self):
permissions = {
'edit_data': True,
'access_api': True,
'access_all_locations': True,
}
with get_web_user(
self.domain,
self.user_location,
permissions,
self.client,
) as web_user:
result = get_list(self.domain, web_user, params=QueryDict())
self.assertEqual(result['matching_records'], 2) # AssertionError: 0 != 2
self.assertEqual(
{c['case_name'] for c in result['cases']},
{'Joe', 'Cyril'},
)
def test_get_list_location_restricted(self):
permissions = {
'edit_data': True,
'access_api': True,
'access_all_locations': False,
}
with sync_users_to_es():
with get_web_user(
self.domain,
self.user_location,
permissions,
self.client,
) as web_user:
result = get_list(self.domain, web_user, params=QueryDict())
self.assertEqual(result['matching_records'], 1) # AssertionError: 0 != 1
self.assertEqual(result['cases'][0]['case_name'], 'Cyril')
@contextmanager
def get_web_user(domain, location, permissions, client):
username = 'admin@example.com'
password = '************'
role = UserRole.create(
domain,
'edit-data',
permissions=HqPermissions(**permissions),
)
web_user = WebUser.create(
domain,
username,
password,
created_by=None,
created_via=None,
role_id=role.get_id,
)
web_user.set_location(domain, location)
manager.index_refresh(user_adapter.index_name)
client.login(username=username, password=password)
try:
yield web_user
finally:
web_user.delete(domain, deleted_by=None)
role.delete()
def get_case_blocks(names_locations):
return [
CaseBlock(
case_id=str(uuid.uuid4()),
case_type='person',
case_name=name,
owner_id=location.location_id,
) for name, location in names_locations
]
| UTF-8 | Python | false | false | 6,950 | py | 42 | test_case_api_permissions.py | 36 | 0.576115 | 0.572086 | 0 | 218 | 30.880734 | 89 |
MAyaCohenCS/PrivacyAttackSimulator | 18,889,266,201,443 | 920aaf79ffdb49a79b02fbd321209085d3645691 | ac70c3bc0be40815ce1a954803b23b7779dfd849 | /simulator.py | 3f671b326a4aad48dee08866c5fbb40c3fc3c27d | []
| no_license | https://github.com/MAyaCohenCS/PrivacyAttackSimulator | 494f8713757b97af726854cdc0a66c6bdbcacdb2 | c7da1e0d638ddbd97bac7d981b6b6cd902b101c3 | refs/heads/master | 2020-12-28T04:11:17.508672 | 2020-02-24T09:08:32 | 2020-02-24T09:08:32 | 238,177,311 | 0 | 0 | null | null | null | null | null | null | null | null | null | null | null | null | null | import attacks_lib
import private_mechanisms_lib
import data_utils
import matplotlib.pyplot as plt
import numpy as np
ATTACKS = [attacks_lib.LP_reconstructor]
BASELINES = [private_mechanisms_lib.No_privacy,
private_mechanisms_lib.Random_Answers]
MECHANISMS = [private_mechanisms_lib.Round_to_R_multiplication,
private_mechanisms_lib.Epsilon_gausian_noise]
COMPARATORS = [data_utils.census_citizenship_DB_DC, data_utils.intro_grades_DB_DC]
QUERY_CONST_FACTOR = 2
REPETITIONS = 50
EPSILON_SAMPLE_STEP_SIZE = 1
def draw_graphics(dc_class):
graphics_file_name = 'simulation_results/graphics_data/' + str(dc_class.__name__) + ".csv"
graphics_file = open(graphics_file_name, "r")
epsilon_range =[int(s) for s in graphics_file.readline()[:-1].split(',')]
baselines = graphics_file.readline()[:-1].split(',')
results = graphics_file.readline()[:-1].split(',')
fig = plt.figure()
ax = plt.subplot(211)
for data_series in baselines:
ax.plot(epsilon_range, [float(graphics_file.readline()[:-1])]*len(epsilon_range), label=data_series.strip())
for data_series in results:
ax.plot(epsilon_range, [float(s) for s in graphics_file.readline()[:-1].split(',')], '.-', label=data_series.strip())
ax.set(xlabel='Security parameter', ylabel='Reconstruction rate',
title= dc_class().get_data_name()+' Reconstruction rates by security parameter')
ax.grid()
from matplotlib.font_manager import FontProperties
#
fontP = FontProperties()
fontP.set_size('small')
chartBox = ax.get_position()
ax.set_position([chartBox.x0, chartBox.y0 * 0.7, chartBox.width, chartBox.height * 1.5])
ax.legend(loc='upper center', bbox_to_anchor=(0.5, -0.17), shadow=True)
ax.axis(ymax= 1.03, ymin=-0.03)
fig.savefig("simulation_results/graphics_data/"+str(dc_class.__name__)+" results.png")
# plt.show()
def simulate (dc_class, a_class, pm_class, epsilon_range, DC, query_limit, graphics_file):
# log simulations
log_file = open('simulation_results/' + str(dc_class.__name__) + '/' + str(a_class.__name__) + "_vs_" + str(
pm_class.__name__) + ".csv", "w")
log_file.write("epsilon: ,repetitions\n")
# collects data for graphics
results = np.zeros((len(epsilon_range), REPETITIONS))
for e in range(len(epsilon_range)):
log_file.write(str(epsilon_range[e]) + ": ")
for r in range(REPETITIONS):
A = a_class(DC.size, DC.get_data_bounds())
PM = pm_class(epsilon_range[e], DC.data, DC.get_data_bounds())
for _ in range(query_limit):
A.learn_from_response(PM.respond_query(A.generate_query()))
attack_success_rate = DC.score(A.predict_origin())
log_file.write(',' + str(attack_success_rate))
results[e, r] = attack_success_rate
log_file.write('\n')
log_file.flush()
log_file.close()
graphics_file.write(str(np.median(results, axis=1).tolist()).strip('[]') + '\n')
graphics_file.flush()
def build_simulation():
# set a separate environment for each DB
for dc_class in COMPARATORS:
DC = dc_class()
epsilon_range = np.arange(1,DC.size,EPSILON_SAMPLE_STEP_SIZE)
query_limit = int(QUERY_CONST_FACTOR * DC.size)
#collect graphics data
graphics_file_name = 'simulation_results/graphics_data/' + str(dc_class.__name__) + ".csv"
graphics_file = open(graphics_file_name, "w")
graphics_file.write(str(epsilon_range.tolist()).strip('[]')+'\n')
graphics_file.flush()
legend = [str(A_class.__name__) + " vs. " + str(PM_class.__name__) for A_class in ATTACKS for PM_class in BASELINES]
graphics_file.write(', '.join(legend)+ '\n')
graphics_file.flush()
legend = [str(A_class.__name__) + " vs. " + str(PM_class.__name__) for A_class in ATTACKS for PM_class in MECHANISMS]
graphics_file.write(', '.join(legend)+ '\n')
graphics_file.flush()
#pick a pair <A, PM> for the simulation
for a_class in ATTACKS:
for bln_class in BASELINES:
simulate(dc_class, a_class, bln_class, [0], DC, query_limit, graphics_file)
for pm_class in MECHANISMS:
simulate(dc_class, a_class, pm_class, epsilon_range, DC, query_limit, graphics_file)
graphics_file.close()
def main():
#build_simulation()
for dc_class in COMPARATORS:
draw_graphics(dc_class)
if __name__ == "__main__":
main()
| UTF-8 | Python | false | false | 4,559 | py | 17 | simulator.py | 4 | 0.623382 | 0.616363 | 0 | 131 | 33.770992 | 125 |
YunShiTiger/ProxyPool | 12,575,664,269,594 | eea60ed60843c9fa5f09fb0ffc53ca1a78ae6b0c | af76168df443fd7a231646ec4a956603a1581152 | /DB/MongodbClient.py | c7e83d723453c2a8daefcb132ef8f9011ed984a9 | [
"MIT"
]
| permissive | https://github.com/YunShiTiger/ProxyPool | 86a30609564df12ade8eb2b5fd3ef1b830eb28e7 | 9aab5ea8be34ec4331ff3ececd3780c7dd074eba | refs/heads/master | 2020-04-06T22:26:29.958534 | 2018-11-16T05:35:14 | 2018-11-16T05:35:18 | null | 0 | 0 | null | null | null | null | null | null | null | null | null | null | null | null | null | # coding: utf-8
from pymongo import MongoClient
class MongodbClient(object):
def __init__(self, name, host, port, **kwargs):
self.name = name
self.client = MongoClient(host, port, **kwargs)
self.db = self.client.proxy
def changeTable(self, name):
self.name = name
def get(self, query):
data = self.db[self.name].find_one(query)
return data
def put(self, query, data):
if self.db[self.name].find_one(query):
return None
else:
self.db[self.name].insert(data)
# unuseful function
# def pop(self):
# data = list(self.db[self.name].aggregate([{'$sample': {'size': 1}}]))
# if data:
# data = data[0]
# value = data['proxy']
# self.delete(value)
# return {'proxy': value, 'value': data['num']}
# return None
def aggregate(self, operation_list):
data = list(self.db[self.name].aggregate(operation_list))
return data
def delete(self, query):
self.db[self.name].remove(query)
def getAll(self):
data = self.db[self.name].find()
result = { item['proxy']: item for item in data }
return result
def clean(self):
self.client.drop_database('proxy')
def delete_all(self):
self.db[self.name].remove()
def update(self, query, data):
self.db[self.name].update(query, data)
def exists(self, query):
result = False
data = self.get(query)
if data:
result = True
return result
def getNumber(self):
return self.db[self.name].count()
if __name__ == "__main__":
db = MongodbClient('first', 'localhost', 27017)
# db.put('127.0.0.1:1')
# db2 = MongodbClient('second', 'localhost', 27017)
# db2.put('127.0.0.1:2')
# print(db.pop())
| UTF-8 | Python | false | false | 1,880 | py | 11 | MongodbClient.py | 8 | 0.554787 | 0.539362 | 0 | 73 | 24.753425 | 79 |
schmitzl/AI_project | 3,118,146,270,257 | f8cf69a9fcf829292e9aeb9a1f720cbf039a366f | 3f8d59509632239bdd38c2fb823557311dceafe8 | /Documents/test.py | 0cda6cd68259a92638f804bf0e7f353b4a55c339 | []
| no_license | https://github.com/schmitzl/AI_project | e43a50ba26650457edfdf5fd85b6cf8408c44de7 | 41a4b0b6edc310e689b4cc43bf671e5074f19735 | refs/heads/master | 2021-05-03T14:57:51.914552 | 2016-10-27T13:04:34 | 2016-10-27T13:04:34 | 42,666,822 | 0 | 0 | null | null | null | null | null | null | null | null | null | null | null | null | null | """
------- README ------
How to perform feature extraction / get a dictionairy and create bag of words from
it using scikit-learn python libraries.
Most stuff taken from http://scikit-learn.org/stable/modules/feature_extraction.html#the-bag-of-words-representation. I also added some more commentary coz their explanation is rather poor imo.
Installation instructions here: http://scikit-learn.org/stable/install.html
"""
# this is a comment
print "hello world"
# fooling around
measurements = [{'city': 'Dubai', 'temperature': 33.},
{'city': 'London', 'temperature': 12.},
{'city': 'San Fransisco', 'temperature': 18.}]
print measurements
from sklearn.feature_extraction import DictVectorizer
vec = DictVectorizer()
f = vec.fit_transform(measurements).toarray()
[x,y] = f.shape
print x
print y
"""
output:
3
4
"""
# start here
corpus = ['This is the first document.',
'This is the second second document.',
'And the third one.',
'Is this the first document?']
from sklearn.feature_extraction.text import CountVectorizer
vectorizer = CountVectorizer(min_df=1)
vectorizer
CountVectorizer(analyzer='word',binary=False,decode_error='strict',dtype='numpy.int64',encoding='utf-8',input='content',lowercase=True,max_df=1.0,max_features=None, min_df=1,ngram_range=(1, 1), preprocessor=None, stop_words=None,strip_accents=None, token_pattern='(?u)\\b\\w\\w+\\b',tokenizer=None, vocabulary=None)
# Extracts features and creates some dictionairy
# internaly (i need to find where it stores it)
# it also creates a BoW representation
# for every input training document.
xx = vectorizer.fit_transform(corpus)
xx.toarray()
print xx
# xx is an array where each row is basically a Bag of Words for every one of the above "documents".
# The interesting (or maybe not so interesting) part, is that the dictionairy is formed internally
# from the 'corpus' . Notice that this fucntion automatically removes duplicate words. In this simple 'corpus' we
# have 4 documents that contains 20 words in total. However, only 9 of these words are unique, thus
# we end up with an array 4x9 . The output is not really handy to be honest but ill see how to make it
# look better.
"""
xx real output:
(0, 8) 1
(0, 3) 1
(0, 6) 1
(0, 2) 1
(0, 1) 1
(1, 8) 1
(1, 3) 1
(1, 6) 1
(1, 1) 1
(1, 5) 2
(2, 6) 1
(2, 0) 1
(2, 7) 1
(2, 4) 1
(3, 8) 1
(3, 3) 1
(3, 6) 1
(3, 2) 1
(3, 1) 1
which is basically this:
xx output:
[0, 1, 1, 1, 0, 0, 1, 0, 1], # bag 1
[0, 1, 0, 1, 0, 2, 1, 0, 1], # bag 2
[1, 0, 0, 0, 1, 0, 1, 1, 0], # bag 3
[0, 1, 1, 1, 0, 0, 1, 0, 1] # bag 4
Once we get to this point with all of our trainig samples it would be cool to have another matrix
with stored in string type the label of each of these bags (using the same index)
something like this:
xx=
[0, 1, 1, 1, 0, 0, 1, 0, 1], # bag 1
[0, 1, 0, 1, 0, 2, 1, 0, 1], # bag 2
[1, 0, 0, 0, 1, 0, 1, 1, 0], # bag 3
[0, 1, 1, 1, 0, 0, 1, 0, 1] # bag 4
yy=
['positive'], #refers to bag 1
['negative'], #refers to bag 2
['positive'], #refers to bag 3
['negative'], #refers to bag 4
"""
# Suppose that we have some test samples, documents/lyrics.
# We need to get a bag of words for each of these samples too.
k=vectorizer.transform(['Something completely new.']).toarray()
l=vectorizer.transform(['This is Something completely new.']).toarray()
print k
print l
"""
real outputs:
[[0 0 0 0 0 0 0 0 0]]
[[0 0 0 1 0 0 0 0 1]]
First is k , second is l. Notice that each of these new documents have been trasformed into a bag of words.
As expected 'k' is zeros as it doesnt contain any words from the dictionairy we learn earlier, so
basically it contains 9 x zeros --> ( size(vocabulary) x occurences in each bin).
On the other hand 'l' contains two 1s (bin 3 & 8 [bin_range = 0-8]), ('This', 'is') found in the
dictionairy, rest = zeros (no occurences in the dict).
Note:
For the classification part we are also going to need the labels of the test data in another matrix.
Same fashion as the training set.
We only going to use test labels in order to check if the predicted labels match to test labels. We CANNOT use them
to train the system , otherwise it would be considered cheat, and appart from that it would score 100% accuracy
so we dont want this.
"""
| UTF-8 | Python | false | false | 4,348 | py | 20 | test.py | 9 | 0.674333 | 0.630405 | 0 | 170 | 24.511765 | 315 |
Abhi1997/crawler | 11,244,224,413,485 | 23b8410254ec8cbf9cb4b836368f350fec7a8221 | 8a3afaf51a617516268a8067575491be92b1a259 | /ExtractAll.py | 9fc37f93c31c65fca8773373af8ad1ad82658995 | []
| no_license | https://github.com/Abhi1997/crawler | 427564c028b5aafd162ef200be9c2dc337c7e22a | 660702e7e42445d323f40dcd62208c4585e8da76 | refs/heads/master | 2018-09-27T16:26:48.547705 | 2018-07-16T05:28:19 | 2018-07-16T05:28:19 | 135,258,602 | 0 | 0 | null | null | null | null | null | null | null | null | null | null | null | null | null | import requests
import bs4
import csv
import re
def name(x):
url = 'https://www.drugs.com' + x
req = requests.get(url)
soup = bs4.BeautifulSoup(req.text, 'lxml')
for a in soup.body.b:
return a
def dosage(y):
url = 'https://www.drugs.com' + y
req = requests.get(url)
soup = bs4.BeautifulSoup(req.text, 'lxml')
for a in soup.findAll('p', limit=2):
if re.search(r'Dosage form:', a.text, re.M | re.I): # using regular expression for obtain dosage
replace = re.sub(r'Ingredients:', " Ingredients:", a.text)
replace = re.sub(r'Labeler:', " Labeler:", replace)
find = re.search(r'Dosage form: (.*) Ingredients: (.*?) Labeler', replace, re.M | re.I)
return find.group(1)
elif re.search(r'Name: ', a.text, re.M | re.I):
replace = re.sub(r'Form:', " Form:", a.text)
replace= re.sub(r'Ingredients:', " Ingredients:", a.text)
replace = re.sub(r'Date:', " Date:", replace)
find = re.search(r'Form: (.*) Ingredients: (.*?) Date', replace, re.M | re.I)
return find.group(1)
def ingd(y):
url = 'https://www.drugs.com' + y
req = requests.get(url)
soup = bs4.BeautifulSoup(req.text, 'lxml')
for a in soup.findAll('p', limit=2):
if re.search(r'Dosage form:', a.text, re.M | re.I): # using regular expression for obtain ingrediants
replace = re.sub(r'Ingredients:', " Ingredients:", a.text)
replace = re.sub(r'Labeler:', " Labeler:", replace)
find = re.search(r'Dosage form: (.*) Ingredients: (.*?) Labeler', replace, re.M | re.I)
return find.group(2)
elif re.search(r'Name: ', a.text, re.M | re.I):
replace = re.sub(r'Form:', " Form:", a.text)
replace= re.sub(r'Ingredients:', " Ingredients:", a.text)
replace = re.sub(r'Date:', " Date:", replace)
find = re.search(r'Form: (.*) Ingredients: (.*?) Date', replace, re.M | re.I)
return find.group(2)
def purpose(y):
t = "none"
url = 'https://www.drugs.com' + y
req = requests.get(url)
soup = bs4.BeautifulSoup(req.text, 'lxml')
if soup.findAll('tr', attrs={'class': 'First Toprule'}):
for a in soup.findAll('tr', attrs={'class': 'First Toprule'}):
for p in a.select('td'):
print('')
return p.text
elif soup.findAll('tr', attrs={'class': 'Botrule Last'}):
for x in soup.findAll('tr', attrs={'class': 'First Toprule'}):
for y in x.select('td'):
print('')
return y.text
elif soup.findAll('div', attrs={'class': 'Section'}):
for a in soup.findAll('div', attrs={'class': 'Section'}, limit=4):
for b in a.select('.First'):
t = [b.text] # 78 page is not working
return t
def uses(z):
t = "none"
url = 'https://www.drugs.com' + z
req = requests.get(url)
soup = bs4.BeautifulSoup(req.text, 'lxml')
if soup.findAll('div', attrs={'class': 'Section'}):
for a in soup.findAll('div', attrs={'class': 'Section'}, limit=5):
if a.findAll('ul', attrs={'class': 'Disc'}):
for c in a.findAll('ul', attrs={'class': 'Disc'}):
for d in c.select('li'):
t = [d.text]
return t
elif a.findAll('ul'): # Added this for the page who doesn't have '.First' class
for c in a.findAll('ul'):
for d in c.select('li'):
t = [d.text]
return t
elif a.findAll('ul', attrs={'class': 'Square'}):
for c in a.findAll('ul', attrs={'class': 'Square'}):
for d in c.select('li'):
t = [d.text]
return t
if soup.findAll('div', attrs={'class': 'Section'}):
for a in soup.findAll('div', attrs={'class': 'Section'}, limit=4):
for b in a.select('.First'):
t = [b.text]
return t
def flex():
with open('Otc_Extract_1_10.csv', 'a', newline='')as csvfile:
file_obj = open('OTC_FOR_A.csv', 'r')
writer = csv.writer(csvfile)
writer.writerow(['NAME', 'LINKS', 'DOSAGE', 'INGREDIENT', 'PURPOSE', 'USES'])
for r in csv.reader(file_obj):
r = list(csv.reader(file_obj))
for a in range(1, 10):
print(a)
writer.writerow([name(r[a][1]), 'www.drugs.com' + r[a][1], dosage(r[a][1]), ingd(r[a][1]), purpose(r[a][1]), uses(r[a][1])]) # here r[m][n] we
# have [m] as row and [n] as column
flex()
| UTF-8 | Python | false | false | 4,749 | py | 8 | ExtractAll.py | 7 | 0.508107 | 0.502 | 0 | 123 | 37.609756 | 159 |
denskif/CRM_test | 18,459,769,441,886 | 84d3c00653cfe2a08cd8a3550c570e2c09b129ca | 4f00b1285305bdc70d1e2a0fa8259bf8cca95598 | /CRMSuit_2_Company.py | d9d034f78000fec219ad05ff2b3d96ce4c7d5b66 | []
| no_license | https://github.com/denskif/CRM_test | 266a554564cbdffcb98a6d1ff30eac295943adf0 | 991fb2e7929e5315cb633230aa0c1cbdbc98e05c | refs/heads/master | 2019-11-28T16:50:27.173951 | 2017-09-27T16:37:05 | 2017-09-27T16:37:05 | 100,393,024 | 0 | 0 | null | null | null | null | null | null | null | null | null | null | null | null | null | #-*- coding: UTF -8 -*-
import unittest, time, sys
from datetime import datetime
import Shop_side as Shop
import CRM_side_Company as CRM
import CRM_side_Home as CRM_Home
from selenium import webdriver
from selenium.webdriver.support.wait import WebDriverWait
from selenium.webdriver.common.keys import Keys
from selenium.common.exceptions import NoSuchElementException
from selenium.webdriver.common.by import By
from selenium.webdriver.support import expected_conditions as EC
# -------------------------------------------- Test Cases --------------------------------------------------------
class TestCase(unittest.TestCase):
def setUp(self):
#self.driver = webdriver.Remote(command_executor='http://192.168.6.51:4444/wd/hub', desired_capabilities={'platform': 'LINUX', 'browserName': 'firefox', 'javascriptEnabled': True})
self.driver = webdriver.Firefox(executable_path='..//CRM_test/driver/geckodriver')
self.driver.implicitly_wait(10)
self.driver.maximize_window()
OpenCRM = CRM_Home.GoToCRM(self.driver)
Form = OpenCRM.OpenCRM()
HomePage = Form.LogIn('alex@bunke.com.ua', '11111111')
HomePage.GoToCompany()
def tearDown(self):
self.driver.quit()
# Curent and Expand position
def testNumber1(self):
Company = CRM.MainList(self.driver)
Worker = Company.Get_First_worker()
time.sleep(2)
self.assertTrue(Worker)
Company.Push_Button_Curtail()
try:
Worker
except NoSuchElementException:
return False
Company.Push_Button_Expand()
self.assertTrue(Worker)
#Create department
def testNumber2(self):
Company = CRM.MainList(self.driver)
Company.Create_Position('Department', 'Test Department5')
#Create position
def testNumber3(self):
Company = CRM.MainList(self.driver)
Company.Create_Position('Position', 'Test Position5')
# Create worker
def testNumber4(self):
Company = CRM.MainList(self.driver)
Company.Create_Position('Worker', 'Test')
Company.Record_date_worker('Worker', 'Testing', 'test@com', 'Test Department5', 'Test Position5', '111111', u'Наличные деньги')
#Company.Push_Button_Expand()
worker = Company.Get_worker_to_name('Worker Testing')
self.assertTrue(worker)
# Rename department
def testNumber5(self):
Company = CRM.MainList(self.driver)
Company.Change_Department('Test Department5', 'Test Department6')
Rename = Company.Find_department('Test Department6')
assert Rename.text == 'Test Department6'
# Rename position
def testNumber6(self):
Company = CRM.MainList(self.driver)
Company.Change_Position('Test Position5', 'Test Position6')
Rename = Company.Find_Position('Test Position6')
assert Rename.text == 'Test Position6'
def testNumber7(self):
Company = CRM.MainList(self.driver)
Detal = Company.Open_deteils_worker(u'Прац Тестовий')
Detal.Change_Stane_Worker('Not Work')
Detal.Buttom_save()
Detal.info_frame('yes')
Workers = Company.Get_Mass_unworking_workers()
mas = []
for Worker in Workers:
mas.append(Worker.text)
assert u'Прац Тестовий' in mas
def testNumber8(self):
name = u'Працівникc Тестовийc'
Pre_details = name.split(' ')
New_details = [Pre_details[1] + u'оч', Pre_details[0] + u'оч', 'test@com.ua', '0998877665']
Company = CRM.MainList(self.driver)
Detal = Company.Open_deteils_worker(name)
Detal.Change_Personal_Deteil(New_details[0], New_details[1], New_details[2], New_details[3])
Detal.Buttom_save()
Detal.info_frame('yes')
Workers = Company.Get_Mass_working_worker()
new_details = ' '.join(New_details)
mas = []
for Worker in Workers:
mas.append(Worker.text)
assert new_details in mas
def testNumber9(self):
Company = CRM.MainList(self.driver)
Company.Create_Position('Worker', 'Babushkin')
Company.Record_date_worker('Worker', 'Babushkin', 'test@com', 'Test Department6', 'Test Position6', '111111', u'Наличные деньги')
Detal = Company.Open_deteils_worker('Worker Babushkin')
Formuls = Detal.Go_to_Formuls_salary()
Formuls.Add_formul_salary('fix', '5000')
def testNumder10(self):
Company = CRM.MainList(self.driver)
Detal = Company.Open_deteils_worker('Worker Babushkin')
Formuls = Detal.Go_to_Formuls_salary()
Formuls.Change_formuk_salary()
if __name__ == '__main__':
unittest.main(verbosity=2)
| UTF-8 | Python | false | false | 4,790 | py | 7 | CRMSuit_2_Company.py | 7 | 0.638329 | 0.620734 | 0 | 124 | 37.040323 | 188 |
BYU-AUVSI/GroundStation | 4,836,133,216,565 | ebb0fb8c509c87bd08aa5d6e226c7bdea1c328a4 | 5214f6ef55b5ab5f1e2beb847d690c377827265f | /src/ground_station/marble_map.py | 279bd1f3ebd44763f1578ed32ba48ed1061fb5ac | []
| no_license | https://github.com/BYU-AUVSI/GroundStation | 021d45c319cf0dc5e5edb3e3d1906bf5ed9e0bc8 | 79ada62392ebaf592ee787305e634e7a41871f69 | refs/heads/master | 2017-12-07T10:35:45.218850 | 2017-06-21T01:56:00 | 2017-06-21T01:56:00 | 79,607,833 | 0 | 2 | null | null | null | null | null | null | null | null | null | null | null | null | null | from PyKDE4.marble import *
from PyQt4.QtCore import *
from PyQt4.QtGui import *
import os.path
from math import ceil, floor, sqrt, sin, asin, cos, acos, radians, degrees, fmod, pi
import map_info_parser
import rospy
from std_msgs.msg import String, Float32MultiArray
from rosflight_msgs.msg import State, GPS, RCRaw
from ros_plane.msg import Current_Path, Waypoint
from Signals import WP_Handler
from .Geo import Geobase
import json, re, time
'''
For changing color of current waypoint to green:
Use the QTimer (as shown in the layer tutorial) to call the marble.update method
at every set interval [[in fact, do it like map_widget's Plane() class, but in this
MarbleMap() class]],
and have PaintLayer have an internal state-subscriber-like class whose data member
of current waypoint is always updating.
'''
class GPSSubscriber():
def __init__(self):
# subscribing to fcu_common/GPS to get plane latitude and longitude
self.lat = 0.0 # in degrees
self.lon = 0.0
self.altitude = 0.0
rospy.Subscriber("/gps/data", GPS, self.callback)
#rospy.Subscriber("/waypoint_path", FW_Waypoint, self.callback_waypoints)
def callback(self, gps):
self.lat = gps.latitude
self.lon = -1.0*gps.longitude
self.altitude = gps.altitude
class MissionSubscriber():
def __init__(self):
self.mission_data = ""
rospy.Subscriber("missions", String, self.callback)
def callback(self, mission_json):
json_data = mission_json.data
json_data = re.sub(r"u'",r'"',json_data)
json_data = re.sub(r"'",r'"',json_data)
json_data = re.sub(r"True",r'"True"',json_data)
json_data = re.sub(r"False",r'"False"',json_data)
data = json.loads(json_data)[0]
self.mission_data = data
class ObstaclesSubscriber():
def __init__(self):
self.stationaryObstacles = []
self.movingObstacles = []
rospy.Subscriber("/obstacles", String, self.json_callback)
def json_callback(self, obstacles_json):
json_data = str(obstacles_json.data)
json_data = re.sub(r"u'",r'"',json_data)
json_data = re.sub(r"'",r'"',json_data)
data = json.loads(json_data)
moving_obstacles = data["moving_obstacles"]
stationary_obstacles = data["stationary_obstacles"]
self.movingObstacles = []
for obstacle in moving_obstacles:
lat = float(obstacle["latitude"])
lon = float(obstacle["longitude"])
radius = float(obstacle["sphere_radius"])
height = float(obstacle["altitude_msl"])
self.movingObstacles.append((lat, lon, radius, height))
self.stationaryObstacles = []
for obstacle in stationary_obstacles:
lat = float(obstacle["latitude"])
lon = float(obstacle["longitude"])
radius = float(obstacle["cylinder_radius"])
height = float(obstacle["cylinder_height"])
self.stationaryObstacles.append((lat, lon, radius, height))
class StateSubscriber(): # Using GPS state output to avoid conversions for display
def __init__(self):
self.lat = 0.0
self.lon = 0.0
self.psi = 0.0
rospy.Subscriber("/gps_state", State, self.callback)
def callback(self, state):
self.lat = state.position[0]
self.lon = state.position[1]
self.psi = fmod(state.chi, 2*pi)
class MiscSubscriber():
def __init__(self):
rospy.Subscriber("/current_path", Current_Path, self.callback_curPath)
rospy.Subscriber("/rc_raw", RCRaw, self.callback_RC)
rospy.Subscriber("/waypoint_path", Waypoint, self.callback_waypoints)
rospy.Subscriber("/gps/data", GPS, self.callback_GPS)
self.autopilotEnabled = False
self.curPath = Current_Path()
self.waypoints = []
self.curPath.flag = False
self.numSat = 0
def callback_curPath(self, cp):
self.curPath = cp
def callback_RC(self, rcRaw):
self.autopilotEnabled = (rcRaw.values[4] < 1700)
def callback_waypoints(self, waypoint):
self.waypoints.append(waypoint)
def callback_GPS(self, gps_data):
self.numSat = gps_data.NumSat
# Class for allowing the widget to paint to the marble map
class PaintLayer(Marble.LayerInterface, QObject):
def __init__(self, marble):
QObject.__init__(self)
self.marble = marble
self._home_map = self.marble._home_map
# This list must be kept in sync with the plane's on-board waypoint queue
self.load_wp_from_file()
self.gpsSubscriber = GPSSubscriber()
self.obsSubscriber = ObstaclesSubscriber()
self.missionSubscriber = MissionSubscriber()
self.stateSubscriber = StateSubscriber()
self.miscSubscriber = MiscSubscriber()
self.use_interop_boundaries = True # <<<<< Assign to True to use interop server for boundaries
#self.R = 6371000.0 # Radius of earth in meters
self.R = 6370027.0 # Radius of the earth in meters at the competition
self.h = 20
self.w = 20
# For signal handling
self.marble.WPH.wp_inserted.connect(self.add_waypoint)
self.marble.WPH.wp_removed.connect(self.remove_waypoint)
self.marble.WPH.home_changed.connect(self.change_home)
self.timeSinceStart = time.time()
def load_wp_from_file(self):
if self.marble.wp_state == 'MainWP':
self.waypoints = map_info_parser.get_main_waypoints(self._home_map)
elif self.marble.wp_state == 'SearchWP':
self.waypoints = map_info_parser.get_search_waypoints(self._home_map)
else:
self.waypoints = []
def add_waypoint(self, lat, lon, alt, pos):
self.waypoints.insert(pos, (lat, lon, alt))
def remove_waypoint(self, pos):
del self.waypoints[pos]
def change_home(self, new_home):
self._home_map = new_home
#self.latlon = self.marble.latlon
#self.R_prime = cos(radians(self.latlon[0]))*self.R
def dnToLat(self, dn):
return self.marble.GIS.plane_latlon[0] + degrees(asin(dn/self.R))
def dnToLat_HP(self, dn): # uses home pt instead of plane lat, lon
return self.marble.latlon[0] + degrees(asin(dn/self.R))
def deToLon(self, de):
return self.marble.GIS.plane_latlon[1] + degrees(asin(de/(cos(radians(self.marble.GIS.plane_latlon[0]))*self.R)))
def deToLon_HP(self, de): # uses home pt instead of plane lat, lon
return self.marble.latlon[1] + degrees(asin(de/(cos(radians(self.marble.latlon[0]))*self.R)))
def renderPosition(self): # So that Marble knows where to paint
return ['SURFACE']
def render(self, painter, viewPort, renderPos, layer):
painter.m_index = 0 # should provide a surface paint
painter.setRenderHint(QPainter.Antialiasing, True)
#self._home_map = self.marble._home_map
self.drawWaypoints(painter)
# Don't draw these if it's too zoomed out
if (self.marble.zoom() > 2700):
self.drawStationaryObstacles(painter)
self.drawMovingObstacles(painter)
if self.marble.view_full_path:
self.drawFullCurrentPath(painter)
if self.use_interop_boundaries:
self.drawMissionDetails(painter)
if self.marble.GIS.received_msg:
self.drawCurPath(painter)
self.drawPlane(painter) # Plane on top of all other items in drawing
return True
def rotate_x(self, x, y, a):
return x * cos(a) + y * sin(a)
def rotate_y(self, x, y, a):
return -1 * x * sin(a) + y * cos(a)
def drawFullCurrentPath(self, painter):
# receive list of curr_path objects from wp_window (with marble obj as bridge)
painter.setPen(QPen(QBrush(Qt.green), 3.5, Qt.SolidLine, Qt.RoundCap))
curpath_line = Marble.GeoDataLineString()
for pathNEPoint in self.marble.current_path_NE_list: # list of (North, East) tuples for rendering
pt_lon = self.deToLon_HP(pathNEPoint[1])
pt_lat = self.dnToLat_HP(pathNEPoint[0])
pt = Marble.GeoDataCoordinates(pt_lon, pt_lat, 0.0, Marble.GeoDataCoordinates.Degree)
curpath_line.append(pt)
painter.drawPolyline(curpath_line)
def drawCurPath(self, painter):
painter.setPen(QPen(QBrush(Qt.red), 3.5, Qt.SolidLine, Qt.RoundCap))
curPath = self.miscSubscriber.curPath
if curPath.flag == True:
r = curPath.r
q = curPath.q
scale = 200
pt_1 = [r[1],r[0]]
pt_2 = [r[1]+scale*q[1],r[0]+scale*q[0]]
line_1 = Marble.GeoDataLineString()
line_1.append(Marble.GeoDataCoordinates(self.deToLon(pt_1[0]), self.dnToLat(pt_1[1]), 0.0, Marble.GeoDataCoordinates.Degree))
line_1.append(Marble.GeoDataCoordinates(self.deToLon(pt_2[0]), self.dnToLat(pt_2[1]), 0.0, Marble.GeoDataCoordinates.Degree))
painter.drawPolyline(line_1)
else:
c = curPath.c
R = curPath.rho
referenceDistance = self.marble.distanceFromZoom(self.marble.zoom())*1000
location = Marble.GeoDataCoordinates(self.deToLon(c[1]), self.dnToLat(c[0]), 0.0, Marble.GeoDataCoordinates.Degree)
pixelRadius = ceil(6.8*67*R/referenceDistance)
painter.drawEllipse(location, pixelRadius, pixelRadius)
def drawPlane(self, painter):
autopilotEnabled = self.miscSubscriber.autopilotEnabled
if autopilotEnabled:
painter.setPen(QPen(QBrush(Qt.black), 3.5, Qt.SolidLine, Qt.RoundCap))
else:
painter.setPen(QPen(QBrush(Qt.red), 3.5, Qt.SolidLine, Qt.RoundCap))
#de = self.stateSubscriber.pe
lat = self.stateSubscriber.lat # dnToLat
#dn = self.stateSubscriber.pn
lon = self.stateSubscriber.lon # deToLon
psi = self.stateSubscriber.psi
# Draw Plane Lines with pts 1-7
referenceDistance = self.marble.distanceFromZoom(self.marble.zoom())
scaled_h = 6.5e-5*self.h*referenceDistance
scaled_w = 6.5e-5*self.w*referenceDistance
#pt_1 = [de + self.rotate_x(0, scaled_h/2, psi), dn + self.rotate_y(0, scaled_h/2, psi)]
pt_1 = [lon + self.rotate_x(0, scaled_h/2, psi), lat + self.rotate_y(0, scaled_h/2, psi)]
#pt_2 = [de + self.rotate_x(0, -scaled_h/2, psi), dn + self.rotate_y(0, -scaled_h/2, psi)]
pt_2 = [lon + self.rotate_x(0, -scaled_h/2, psi), lat + self.rotate_y(0, -scaled_h/2, psi)]
line_1 = Marble.GeoDataLineString()
#line_1.append(Marble.GeoDataCoordinates(self.deToLon(pt_1[0]), self.dnToLat(pt_1[1]), 0.0, Marble.GeoDataCoordinates.Degree))
line_1.append(Marble.GeoDataCoordinates(pt_1[0], pt_1[1], 0.0, Marble.GeoDataCoordinates.Degree))
#line_1.append(Marble.GeoDataCoordinates(self.deToLon(pt_2[0]), self.dnToLat(pt_2[1]), 0.0, Marble.GeoDataCoordinates.Degree))
line_1.append(Marble.GeoDataCoordinates(pt_2[0], pt_2[1], 0.0, Marble.GeoDataCoordinates.Degree))
#pt_3 = [de, dn]
pt_3 = [lon, lat]
#pt_4 = [de + self.rotate_x(-scaled_w/2, -scaled_h/4, psi), dn + self.rotate_y(-scaled_w/2, -scaled_h/4, psi)]
pt_4 = [lon + self.rotate_x(-scaled_w/2, -scaled_h/4, psi), lat + self.rotate_y(-scaled_w/2, -scaled_h/4, psi)]
#pt_5 = [de + self.rotate_x(scaled_w/2, -scaled_h/4, psi), dn + self.rotate_y(scaled_w/2, -scaled_h/4, psi)]
pt_5 = [lon + self.rotate_x(scaled_w/2, -scaled_h/4, psi), lat + self.rotate_y(scaled_w/2, -scaled_h/4, psi)]
line_2 = Marble.GeoDataLineString()
#line_2.append(Marble.GeoDataCoordinates(self.deToLon(pt_3[0]), self.dnToLat(pt_3[1]), 0.0, Marble.GeoDataCoordinates.Degree))
line_2.append(Marble.GeoDataCoordinates(pt_3[0], pt_3[1], 0.0, Marble.GeoDataCoordinates.Degree))
#line_2.append(Marble.GeoDataCoordinates(self.deToLon(pt_4[0]), self.dnToLat(pt_4[1]), 0.0, Marble.GeoDataCoordinates.Degree))
line_2.append(Marble.GeoDataCoordinates(pt_4[0], pt_4[1], 0.0, Marble.GeoDataCoordinates.Degree))
line_3 = Marble.GeoDataLineString()
#line_3.append(Marble.GeoDataCoordinates(self.deToLon(pt_3[0]), self.dnToLat(pt_3[1]), 0.0, Marble.GeoDataCoordinates.Degree))
line_3.append(Marble.GeoDataCoordinates(pt_3[0], pt_3[1], 0.0, Marble.GeoDataCoordinates.Degree))
#line_3.append(Marble.GeoDataCoordinates(self.deToLon(pt_5[0]), self.dnToLat(pt_5[1]), 0.0, Marble.GeoDataCoordinates.Degree))
line_3.append(Marble.GeoDataCoordinates(pt_5[0], pt_5[1], 0.0, Marble.GeoDataCoordinates.Degree))
#pt_6 = [de + self.rotate_x(-scaled_w/4, -2*scaled_h/5, psi), dn + self.rotate_y(-scaled_w/4, -2*scaled_h/5, psi)]
pt_6 = [lon + self.rotate_x(-scaled_w/4, -2*scaled_h/5, psi), lat + self.rotate_y(-scaled_w/4, -2*scaled_h/5, psi)]
#pt_7 = [de + self.rotate_x(scaled_w/4, -2*scaled_h/5, psi), dn + self.rotate_y(scaled_w/4, -2*scaled_h/5, psi)]
pt_7 = [lon + self.rotate_x(scaled_w/4, -2*scaled_h/5, psi), lat + self.rotate_y(scaled_w/4, -2*scaled_h/5, psi)]
line_4 = Marble.GeoDataLineString()
#line_4.append(Marble.GeoDataCoordinates(self.deToLon(pt_6[0]), self.dnToLat(pt_6[1]), 0.0, Marble.GeoDataCoordinates.Degree))
line_4.append(Marble.GeoDataCoordinates(pt_6[0], pt_6[1], 0.0, Marble.GeoDataCoordinates.Degree))
#line_4.append(Marble.GeoDataCoordinates(self.deToLon(pt_7[0]), self.dnToLat(pt_7[1]), 0.0, Marble.GeoDataCoordinates.Degree))
line_4.append(Marble.GeoDataCoordinates(pt_7[0], pt_7[1], 0.0, Marble.GeoDataCoordinates.Degree))
painter.drawPolyline(line_1)
painter.drawPolyline(line_2)
painter.drawPolyline(line_3)
painter.drawPolyline(line_4)
def drawMissionDetails(self, painter):
mission_data = self.missionSubscriber.mission_data
if len(mission_data) == 0:
return
painter.setPen(QPen(QBrush(Qt.blue), 4.5, Qt.SolidLine, Qt.RoundCap))
# Draw boundaries
for zone in mission_data['fly_zones']:
line = Marble.GeoDataLineString()
for point in zone['boundary_pts']:
lat = point['latitude']
lon = point['longitude']
order = int(point['order'])
location = Marble.GeoDataCoordinates(lon, lat, 0.0, Marble.GeoDataCoordinates.Degree)
line.append(location)
line.append(line[0]) # Close the polygon by adding the first point again
painter.drawPolyline(line)
def drawWaypoints(self, painter):
painter.setPen(QPen(QBrush(Qt.blue), 4.5, Qt.SolidLine, Qt.RoundCap))
#waypoints = self.miscSubscriber.waypoints # GETTING FROM PLANE [[[[[[[[[[[[[[[[[[[[]]]]]]]]]]]]]]]]]]]]
# Draw waypoints according to latlong degrees for current map
for waypoint in self.waypoints:
#location = Marble.GeoDataCoordinates(self.deToLon(waypoint.w[1]), self.dnToLat(waypoint.w[0]), 0.0, Marble.GeoDataCoordinates.Degree)
location = Marble.GeoDataCoordinates(waypoint[1], waypoint[0], 0.0, Marble.GeoDataCoordinates.Degree)
painter.drawEllipse(location, 5, 5)
def metersToFeet(self, meters):
return meters*3.28084
def drawStationaryObstacles(self, painter):
# height and radius are both in feet
UAV_height = self.metersToFeet(self.gpsSubscriber.altitude)
referenceDistance = self.marble.distanceFromZoom(self.marble.zoom())*1000
# Draw obstacles according to latlong degrees and height relative to the UAV
for (latitude, longitude, radius, height) in self.obsSubscriber.stationaryObstacles:
pixelDiameter = ceil(2*67*radius/referenceDistance)
heightDiff = height-UAV_height
location = Marble.GeoDataCoordinates(longitude, latitude, height, Marble.GeoDataCoordinates.Degree)
painter.setPen(QPen(QBrush(Qt.red), pixelDiameter/2, Qt.SolidLine, Qt.RoundCap))
if (heightDiff < 0):
painter.setPen(QPen(QBrush(Qt.darkGreen), pixelDiameter/2, Qt.SolidLine, Qt.RoundCap))
painter.drawEllipse(location, pixelDiameter/2, pixelDiameter/2)
painter.setPen(QPen(QBrush(Qt.black), 1, Qt.SolidLine, Qt.RoundCap))
painter.drawText(location, str(floor(heightDiff)))
def drawMovingObstacles(self, painter):
UAV_height = self.metersToFeet(self.gpsSubscriber.altitude)
referenceDistance = self.marble.distanceFromZoom(self.marble.zoom())*1000
# Draw obstacles according to latlong degrees and height relative to the UAV
for (latitude, longitude, radius, height) in self.obsSubscriber.movingObstacles:
heightDiff = height-UAV_height
location = Marble.GeoDataCoordinates(longitude, latitude, height, Marble.GeoDataCoordinates.Degree)
# Draw maximum radius of sphere in grey
pixelDiameter = ceil(2*67*radius/referenceDistance)
painter.setPen(QPen(QBrush(Qt.darkGreen), pixelDiameter/2, Qt.SolidLine, Qt.RoundCap))
painter.drawEllipse(location, pixelDiameter/2, pixelDiameter/2)
# Draw radius of sphere at current height in red (if applicable)
# Calculate radius of sphere at current height
if abs(heightDiff) < radius:
localRadius = sqrt(radius*radius - heightDiff*heightDiff)
pixelDiameter = ceil(2*67*localRadius/referenceDistance)
painter.setPen(QPen(QBrush(Qt.red), pixelDiameter/2, Qt.SolidLine, Qt.RoundCap))
painter.drawEllipse(location, pixelDiameter/2, pixelDiameter/2)
painter.setPen(QPen(QBrush(Qt.black), 1, Qt.SolidLine, Qt.RoundCap))
painter.drawText(location, str(floor(heightDiff))+ "("+str(floor(radius))+")")
class GPSInitSubscriber():
def __init__(self):
#self.home_lat = 0.0 # in degrees
#self.home_lon = 0.0
#self.home_alt = 0.0
self.plane_latlon = [0.0, 0.0, 0.0] # lat, lon, alt
self.received_msg = False
self.GB = Geobase(self.plane_latlon[0], self.plane_latlon[1])
self.gi_sub = rospy.Subscriber("/gps_init", Float32MultiArray, self.callback)
def callback(self, gps_array):
self.plane_latlon[0] = gps_array.data[0]
self.plane_latlon[1] = gps_array.data[1]
self.plane_latlon[2] = gps_array.data[2]
self.GB = Geobase(self.plane_latlon[0], self.plane_latlon[1])
#self.home_lat = gps_array.data[0]
#self.home_lon = gps_array.data[1]
#self.home_alt = gps_arrag.data[2]
self.received_msg = True
self.gi_sub.unregister()
class MarbleMap(Marble.MarbleWidget):
def __init__(self, parent=None): # Parent line VERY important
super(MarbleMap, self).__init__() # MarbleWidget constructor
# Check if Google Maps files exist
googleMapsPath = os.path.expanduser("~/.local/share/marble/maps/earth/google-maps-satellite/")
if os.path.exists(googleMapsPath):
self.setMapThemeId("earth/google-maps-satellite/google-maps-satellite.dgml")
else: # Default to open street map
self.setMapThemeId("earth/openstreetmap/openstreetmap.dgml") # street view
self.setProjection(Marble.Mercator)
self.setShowOverviewMap(False)
self.WPH = WP_Handler()
self.wp_opts = {'None':{'title_substr':'Empty Mode','folder_name':'','is_rrt':False},
'MainWP':{'title_substr':'Main Waypoints','folder_name':'main_wps','is_rrt':False},
'PathWP':{'title_substr':'Path Waypoints','folder_name':'path_wps','is_rrt':False},
'SearchWP':{'title_substr':'Search Waypoints','folder_name':'search_wps','is_rrt':False},
'RRT_PathWP':{'title_substr':'RRT Path Waypoints','folder_name':'rrt_path_wps','is_rrt':True,'parent':'PathWP','needs_render':True},
'RRT_SearchWP':{'title_substr':'RRT Search Waypoints','folder_name':'rrt_search_wps','is_rrt':True,'parent':'SearchWP','needs_render':True},
'DropWP':{'title_substr':'Bottle Drop Waypoints','folder_name':'drop_wps','is_rrt':False},
'HikerWP':{'title_substr':'Hiker Waypoints','folder_name':'hiker_wps','is_rrt':False}}
self.wp_state = 'None' # can be 'None','MainWP','PathWP','SearchWP',
# 'DropWP','TargetWP','HikerWP'
# For waypoint conversion
self._home_map = map_info_parser.get_default()
self.latlon = map_info_parser.get_latlon(self._home_map)
self.GB = Geobase(self.latlon[0], self.latlon[1]) # For full current path drawer
self.GIS = GPSInitSubscriber()
self._map_coords = map_info_parser.get_gps_dict()
def_latlonzoom = self._map_coords[self._home_map]
self._home_pt = Marble.GeoDataCoordinates(def_latlonzoom[1], def_latlonzoom[0], 0.0, Marble.GeoDataCoordinates.Degree) # +
self.centerOn(self._home_pt)
self.setZoom(def_latlonzoom[2])
self._mouse_attentive = False
paintlayer = PaintLayer(self)
self.addLayer(paintlayer)
self.seconds_tests = [2.0/3600, 5.0/3600, 15.0/3600, 30.0/3600, 60.0/3600]
self.num_s_tests = len(self.seconds_tests)
self.view_full_path = False
self.current_path_NE_list = []
def mousePressEvent(self, QMouseEvent): # only use if popup window is open===============
if self._mouse_attentive:
q_mouse_pos = QMouseEvent.pos()
q_mouse_x = q_mouse_pos.x()
q_mouse_y = q_mouse_pos.y()
frame_geom = self.frameGeometry().getCoords()
w_width = frame_geom[2] - frame_geom[0]
w_height = frame_geom[3] - frame_geom[1]
lat = self.centerLatitude()
lon = self.centerLongitude()
# Can check 2, 5, 15, 30 60 seconds, use first one that has a pixel difference from
# center greater than 15 px with screenCoordinates()
x = 0.0
y = 0.0
i = 0
found = False
while not found and i < self.num_s_tests:
coord_tuple = self.screenCoordinates(lon + self.seconds_tests[i],
lat + self.seconds_tests[i])
found = coord_tuple[0] # Check if too far
if (abs(coord_tuple[1] - w_width/2) < 10): # Check if too close
found = False
if found:
x = abs(coord_tuple[1] - w_width/2)
y = abs(coord_tuple[2] - w_height/2)
else:
i += 1
if found: # Compute latlon from pixel
x_offset = q_mouse_x - w_width / 2 # number of pixels to the east of center
y_offset = w_height / 2 - q_mouse_y # number of pixels to the north of center
clicked_lon = lon + x_offset*self.seconds_tests[i]/x
clicked_lat = lat + y_offset*self.seconds_tests[i]/y
self.WPH.emit_clicked(clicked_lat, clicked_lon)
else: # Do nothing ===========================
print 'Not found. Zoom in!'
def path_viewer_toggle(self, state_integer):
if state_integer == 2: # checkbox checked
self.view_full_path = True
else: # checkbox unchecked
self.view_full_path = False
def change_home(self, map_name):
self._home_map = map_name
latlonzoom = self._map_coords[self._home_map]
self._home_pt = Marble.GeoDataCoordinates(latlonzoom[1], latlonzoom[0], 0.0, Marble.GeoDataCoordinates.Degree)
self.latlon = map_info_parser.get_latlon(self._home_map)
self.GB = Geobase(self.latlon[0], self.latlon[1])
self.centerOn(self._home_pt)
self.setZoom(latlonzoom[2])
self.update()
self.WPH.emit_home_change(self._home_map)
def get_home(self):
return self._home_pt
| UTF-8 | Python | false | false | 24,251 | py | 54 | marble_map.py | 22 | 0.623315 | 0.603893 | 0 | 498 | 47.696787 | 164 |
holi87/Selenium3 | 7,971,459,342,921 | 8716917312092e09df5ce2db5057b2c9c1df81b2 | bd757c63a76b1e1fcce1aef14669c237bdc2fb6e | /test_kraje_i_geostrefy.py | dc1f07587fce42dc8579ffa95e77344e5f365cbc | []
| no_license | https://github.com/holi87/Selenium3 | 3dad049a2ae19ef4c1e98c55cdfc90842925cc8b | 75cbe53a4b1fc45ecd012c0d41e25033cd3da13d | refs/heads/master | 2021-01-20T22:02:09.959004 | 2017-09-28T18:40:46 | 2017-09-28T18:40:46 | 101,796,049 | 0 | 0 | null | null | null | null | null | null | null | null | null | null | null | null | null | import pytest
from selenium import webdriver
from selenium.webdriver.support.wait import WebDriverWait
from selenium.webdriver.support import expected_conditions as ec
@pytest.fixture
def driver(request):
wd = webdriver.Chrome()
request.addfinalizer(wd.quit)
return wd
# task 9 - part 1
def test_countries(driver):
login_to_admin_page(driver)
driver.get("http://localhost:8080/litecart/admin/?app=countries&doc=countries")
wait(driver).until(ec.title_contains("Countries | My Store"))
lista_krajow = []
kraje_stref = []
for row in driver.find_elements_by_class_name("row"):
lista_krajow.append(row.find_element_by_xpath(".//a").text)
if row.find_element_by_xpath(".//td[6]").text != str(0): # making list of urls where zones > 0 to use later
kraje_stref.append(row.find_element_by_xpath(".//a").get_attribute("href"))
assert lista_krajow == sorted(lista_krajow)
# here starting b) part - checking pages of countries with more zones than 0
for i in range(len(kraje_stref)):
driver.get(kraje_stref[i])
lista_stref = []
dlugosc_tablicy = len(driver.find_elements_by_xpath("//table[@id='table-zones']/*/tr"))
for j in range(2, dlugosc_tablicy):
lista_stref.append(driver.find_element_by_xpath("//*[@id='table-zones']/tbody/tr[%s]/td[3]" % j).text)
assert lista_stref == sorted(lista_stref)
# task 9 - part 2
def test_geozones(driver):
login_to_admin_page(driver)
driver.get("http://localhost:8080/litecart/admin/?app=geo_zones&doc=geo_zones")
wait(driver).until(ec.title_contains("Geo Zones | My Store"))
for i in range(len(driver.find_elements_by_class_name("row"))):
tmp = driver.find_elements_by_class_name("row")
tmp[i].find_element_by_xpath(".//a").click()
# this if is for EU
if driver.find_element_by_name("name").get_attribute("value") == "European Union":
print("\nIn European Union are countries not zones!")
# this part will check if countries are sorted alphabetically
lista_panstw = driver.find_elements_by_xpath("//td[2]/select/option[@selected]")
for j in range(len(lista_panstw)):
lista_panstw[j] = lista_panstw[j].text
assert lista_panstw == sorted(lista_panstw)
else:
lista_stref = driver.find_elements_by_xpath("//td[3]/select/option[@selected]")
for j in range(len(lista_stref)):
lista_stref[j] = lista_stref[j].text
assert lista_stref == sorted(lista_stref)
driver.execute_script("history.go(-1);")
def login_to_admin_page(driver):
driver.get("http://localhost:8080/litecart/admin/")
driver.find_element_by_xpath("//input[@name='username']").send_keys("admin")
driver.find_element_by_name("password").send_keys("admin")
driver.find_element_by_name("login").click()
wait(driver).until(ec.title_is("My Store"))
def wait(driver):
waiter = WebDriverWait(driver, 10)
return waiter
__author__ = "Grzegorz Holak"
| UTF-8 | Python | false | false | 3,091 | py | 12 | test_kraje_i_geostrefy.py | 11 | 0.646716 | 0.637981 | 0 | 77 | 39.142857 | 117 |
Kokemomo/Kokemomo | 9,405,978,421,042 | 4c016697169a5b069a42e1afed59d84c924f9323 | 6c1ff800e79c8a5498c83e2708fdb3f9bd836821 | /kokemomo/plugins/admin/model/km_user_admin.py | 09edb3e54b74b932b00f8213c535ca9733de67d9 | [
"MIT"
]
| permissive | https://github.com/Kokemomo/Kokemomo | 45759c1aad38bd55819331e4e9a77ba8be2dcf68 | 614504dc49b2f509b25c9ec2229f4438db73bab7 | refs/heads/master | 2020-12-25T22:47:54.786463 | 2019-05-11T05:33:41 | 2019-05-11T05:33:41 | 23,455,240 | 5 | 2 | MIT | false | 2019-05-11T05:33:42 | 2014-08-29T06:48:37 | 2017-09-12T10:44:58 | 2019-05-11T05:33:41 | 4,754 | 2 | 3 | 14 | Python | false | false | #!/usr/bin/env python
# -*- coding:utf-8 -*-
from kokemomo.plugins.engine.model.km_user_table import KMUser
from kokemomo.plugins.engine.model.km_group_table import KMGroup
from kokemomo.plugins.engine.model.km_role_table import KMRole
class KMUserAdmin:
@classmethod
def save_user(cls, data):
id = data.get_request_parameter("id")
delete = data.get_request_parameter("delete", default=None)
if delete is None:
user = KMUser.get(id)
user.set_data(data)
user.save()
else:
KMUser.delete_by_id(id)
@classmethod
def save_group(cls, data):
id = data.get_request_parameter("id")
delete = data.get_request_parameter("delete", default=None)
if delete is None:
group = KMGroup.get(id)
group.set_data(data)
group.save()
else:
KMGroup.delete_by_id(id)
@classmethod
def save_role(cls, data):
id = data.get_request_parameter("id")
delete = data.get_request_parameter("delete", default=None)
if delete is None:
role = KMRole.get(id)
role.set_data(data)
role.save()
else:
KMRole.delete_by_id(id)
| UTF-8 | Python | false | false | 1,250 | py | 112 | km_user_admin.py | 74 | 0.5888 | 0.588 | 0 | 40 | 30.225 | 67 |
mxttbennett/Civic-Connect | 2,113,123,930,999 | 91f3a60432c61f16982422164eb29a2f35200a7b | 2f64dafa3445a4b7da74c8df317afd6c581bd150 | /cc/models.py | c73d9dfbf00c9a47600d3fdacc58134b024b9a3d | []
| no_license | https://github.com/mxttbennett/Civic-Connect | 38baeff5b55a4429e6ef43b96b22c84a11f32ac0 | 9545392ec8c703574ce9e2477d1440b2fb0c8719 | refs/heads/master | 2023-03-22T00:55:30.740777 | 2021-03-08T07:08:42 | 2021-03-08T07:08:42 | 345,561,206 | 0 | 0 | null | null | null | null | null | null | null | null | null | null | null | null | null | from django.db import models
class Issue(models.Model):
user_id = models.CharField(max_length=200, default="admin")
issue_name = models.CharField(max_length=200)
issue_text = models.CharField(max_length=3000)
is_approved = models.BooleanField(default=True)
class SiteUser(models.Model):
user_id = models.CharField(max_length=200, unique=True)
user_first_name = models.CharField(max_length=50)
user_last_name = models.CharField(max_length=50)
user_street_add = models.CharField(max_length=150)
user_city_add = models.CharField(max_length=150)
user_state_add = models.CharField(max_length=30)
user_zip = models.CharField(max_length=6)
user_email = models.CharField(max_length=50)
user_phone = models.CharField(max_length=50)
class UserIssue(models.Model):
user_id = models.CharField(max_length=200)
issue_name = models.CharField(max_length=200)
# is_bookmarked = models.BooleanField(default=False)
def __str__(self):
return self.issue_name
class UserTemplate(models.Model):
user_id = models.CharField(max_length=200)
issue_name = models.CharField(max_length=200)
issue_text = models.CharField(max_length=3000)
is_approved = models.BooleanField(default=False) | UTF-8 | Python | false | false | 1,261 | py | 18 | models.py | 11 | 0.716098 | 0.679619 | 0 | 32 | 38.4375 | 63 |
Wps-8th-Wadiz/Wadiz | 1,906,965,527,580 | 7ba04a9dd75256ccd9cb84cafbb34fddb92e369b | 0d2eb2a50b2631532a24dddb0a7b4ea81d8aebf1 | /app/members/urls/apis.py | 679dee59f53689114524d59bbeef5b7806c70a93 | []
| no_license | https://github.com/Wps-8th-Wadiz/Wadiz | 0a71643ad8a096631f0b6bdb0bd797914bc5d7f5 | 40023762ee1576d36adf9aae79e571f5bbe881ac | refs/heads/master | 2022-12-27T01:47:52.523693 | 2019-05-29T16:12:12 | 2019-05-29T16:12:12 | 143,415,865 | 0 | 3 | null | false | 2022-12-08T02:54:55 | 2018-08-03T10:51:54 | 2019-05-29T16:12:22 | 2022-12-08T02:54:55 | 5,526 | 0 | 2 | 17 | Python | false | false | from django.urls import path
from .. import apis
app_name = 'user'
urlpatterns = [
path('', apis.UserList.as_view()),
path('signin/', apis.AuthToken.as_view()),
path('detail/<int:pk>/', apis.UserDetail.as_view()),
path('signup/', apis.UserList.as_view(), name='signup'),
path('activate/<str:uidb64>/<str:token>/', apis.UserActivate.as_view(), name='activate'),
path('change-info/', apis.UserDetail.as_view()),
path('myinfo/', apis.UserInfo.as_view()),
]
| UTF-8 | Python | false | false | 485 | py | 32 | apis.py | 23 | 0.637113 | 0.63299 | 0 | 15 | 31.333333 | 93 |
hgpaula85/SeleniumProjects | 12,506,944,790,249 | 6e58c448c245d907bf626b88545be4faff53043a | ac59a4444b7fedf696e622e027a419db95e86f11 | /PyTestPack/test_case_demo_2.py | d248c5fd7c9f22e915b6b106728a173f976212e9 | []
| no_license | https://github.com/hgpaula85/SeleniumProjects | 9490166cb6bd8217551e13b6b54b51cbd7a7f294 | 2477241bb6c98f39bbc01f3c720843a02bb56815 | refs/heads/master | 2021-01-13T05:22:02.779933 | 2020-01-30T09:12:47 | 2020-01-30T09:12:47 | 81,366,904 | 0 | 0 | null | null | null | null | null | null | null | null | null | null | null | null | null | import pytest
@pytest.yield_fixture()
def set_up():
print("\nRun demo 2 set up")
yield
print("\nRun demo 2 tear down")
print("-" * 50)
def test_demo_2_test_01(set_up):
print("Running demo 2 test 01")
def test_demo_2_test_02(set_up):
print("Running demo 2 test 01")
| UTF-8 | Python | false | false | 296 | py | 35 | test_case_demo_2.py | 34 | 0.618243 | 0.564189 | 0 | 18 | 15.444444 | 35 |
xiaorancs/business-exit-risk-forecast | 11,888,469,498,081 | 688a3eca38e283684de2b27bdffdfbffd65fd913 | a3943ff15380cc7da674f4c9ac90fb197c995c5c | /stack/remove_onefeatures.py | bc7b5b8c995e54c4c92677c6676a470d4f14065f | [
"BSD-2-Clause"
]
| permissive | https://github.com/xiaorancs/business-exit-risk-forecast | 7849b395c2a571ec7f1afb45a1cd1efd89b5a7bc | 2d8fbfa3a90883e486884b84717e08b86f1daa8d | refs/heads/master | 2018-12-10T11:00:47.399696 | 2018-10-12T06:32:03 | 2018-10-12T06:32:03 | 113,841,805 | 20 | 3 | null | null | null | null | null | null | null | null | null | null | null | null | null |
# coding: utf-8
# In[1]:
import pandas as pd
import numpy as np
# 重新审视数据,对年和月进行分割,对不听的类别的特征添加更过的one-hot编码
# ont-hot
# 1. HY
# 2. ETYPE
# 3. ALEREO
# 4. WXCODE
# 5. 年和月(日期)
#
#
# > 可以确定的one-hot编码:
# + HY
# + ETYPE
# + CHANGE_FIRST_ALTERNO
# + CHANGE_END_ALTERNO
# + CHANGE_ALTERNO_MUCNID
# + RIGHT_FIRST_TYPECODE
# + RIGHT_END_TYPECODE
# + RIGHT_TYPECODE_MUCHID
#
# 删除只有一个特征的脏特征。
#
#
# 对所有的有关时间还能的特征,分成年和月两个维度,
#
# timeType = ['RGYEAR','FIRST_CHANGE_TIME','END_CHANGE_TIME','BRANCH_FIRST_YEAR','BRANCH_END_YEAR',
# 'BRANCH_FIRST_CLOSE_YEAR','TZ_QY_FIRST_TIME','TZ_QY_END_TIME','TZ_FIRST_CLOSE_TIME',
# 'RIGHT_FIRST_ASK_TIME', 'RIGHT_FIRST_FB_TIME','RIGHT_END_ASK_TIME', 'RIGHT_END_FB_TIME',
# 'PROJECT_FIRST_TIME', 'PROJECT_END_TIME', 'LAWSUIT_FIRST_TIME', 'LAWSUIT_END_TIME',
# 'BREAKFAITH_FIRST_FIRST_TIME', 'BREAKFAITH_FIRST_END_TIME','BREAKFAITH_END_FIRST_TIME',
# 'RECRUIT_FIRST_TIME', 'RECRUIT_END_TIME']
#
# 继续添加特征,
# 增加注册资本 / 2018.01 - RGYEAR。
# 增加注册资本注册RATE / 2018.01 - RGYEAR。
# In[2]:
# 所有时间类型的特征
timeType = ['RGYEAR','FIRST_CHANGE_TIME','END_CHANGE_TIME','BRANCH_FIRST_YEAR','BRANCH_END_YEAR',
'BRANCH_FIRST_CLOSE_YEAR','TZ_QY_FIRST_TIME','TZ_QY_END_TIME','TZ_FIRST_CLOSE_TIME',
'RIGHT_FIRST_ASK_TIME', 'RIGHT_FIRST_FB_TIME','RIGHT_END_ASK_TIME', 'RIGHT_END_FB_TIME',
'PROJECT_FIRST_TIME', 'PROJECT_END_TIME', 'LAWSUIT_FIRST_TIME', 'LAWSUIT_END_TIME',
'BREAKFAITH_FIRST_FIRST_TIME', 'BREAKFAITH_FIRST_END_TIME','BREAKFAITH_END_FIRST_TIME',
'RECRUIT_FIRST_TIME', 'RECRUIT_END_TIME','QUALIFICATION_FIRST_FIRST_TIME',
'QUALIFICATION_FIRST_END_TIME','QUALIFICATION_END_FIRST_TIME' ]
# 所有进行one-hot的编码的数据,对注册时间和变成时间得到的年和月进行one-hot编码
# one-hot的特征。
onehot = ['HY','ETYPE','CHANGE_FIRST_ALTERNO','CHANGE_END_ALTERNO','CHANGE_ALTERNO_MUCNID',
'RIGHT_FIRST_TYPECODE','RIGHT_END_TYPECODE','RIGHT_TYPECODE_MUCHID','BREAKFAITH_FIRST_END_TIME_MONTH',
'BREAKFAITH_FIRST_FIRST_TIME_MONTH','END_CHANGE_TIME_MONTH','FIRST_CHANGE_TIME_MONTH',
'LAWSUIT_END_TIME_MONTH','LAWSUIT_END_TIME_YEAR','LAWSUIT_FIRST_TIME_MONTH','LAWSUIT_FIRST_TIME_YEAR',
'PROJECT_END_TIME_MONTH','PROJECT_END_TIME_YEAR','PROJECT_FIRST_TIME_MONTH','PROJECT_FIRST_TIME_YEAR',
'QUALIFICATION_END_FIRST_TIME_MONTH','QUALIFICATION_FIRST_END_TIME_MONTH','QUALIFICATION_FIRST_FIRST_TIME_MONTH',
'RECRUIT_END_TIME_MONTH','RECRUIT_END_TIME_YEAR','RECRUIT_FIRST_TIME_MONTH','RECRUIT_FIRST_TIME_YEAR',
'RIGHT_END_ASK_TIME_MONTH','RIGHT_END_FB_TIME_MONTH','RIGHT_FIRST_ASK_TIME_MONTH','RIGHT_FIRST_FB_TIME_MONTH']
def time2int(x):
'''
将时间转化为整数,加入训练
2018-01 - x
'''
y = int(x[:x.find('-')])
m = int(x[x.find('-')+1:])
s = 12*(2018-y) + (1-m)
return s
def removeOneValueFeature(df_all):
'''
删除只有一个值的特征,没有用处,而且占用空间,
设置直接读取的特征文件。
'''
features = list(df_all.columns)
for f in features:
if len(set(df_all[f])) == 1:
df_all.drop(f,axis=1,inplace=True)
# 设置时间日期
for t in timeType:
df_all[t] = df_all[t].apply(time2int)
df_all['XEID'] = df_all['EID'].map(lambda x: int(x[1:]))
return df_all
def runRemove(inputfile,outputfile):
'''
输入输出文件,文件名主义其格式的不同。
'''
df_all = pd.read_csv(inputfile)
df_all = removeOneValueFeature(df_all)
df_all.to_csv(outputfile,index=False,index_label=False)
del df_all
return outputfile
# 运行
inputfile = ['../data/alldata/df_data1234567890.csv','../data/alldata/df_data1234567890_plus.csv']
outputfile = ['../data/alldata/df_data_all.csv','../data/alldata/df_data_plus_all.csv']
for i in range(2):
print(i," start ",inputfile[i])
runRemove(inputfile[i],outputfile[i])
print(i," end ",inputfile[i])
| UTF-8 | Python | false | false | 4,309 | py | 34 | remove_onefeatures.py | 28 | 0.638882 | 0.62335 | 0 | 113 | 33.168142 | 123 |
legendofdoug/Log_Puller | 9,268,539,431,837 | 44648b044c29053e56804b2cdc58705d7fdca3ac | 10bffb03a8fade5e4f09a2cab02f5c4cf4df9540 | /misc_tools.py | b7fd6669c805cabe0827596f575c6e88d45a3443 | []
| no_license | https://github.com/legendofdoug/Log_Puller | f97a339b32df4bb505a52ac9c39563fedfbb8b4c | b01bb47921e7b5d104bdd093937577dba88d9629 | refs/heads/master | 2022-12-09T05:27:23.054186 | 2020-08-28T21:53:29 | 2020-08-28T21:53:29 | 275,969,168 | 0 | 0 | null | null | null | null | null | null | null | null | null | null | null | null | null | import socket
import argparse, os
from subprocess import call
from config import *
import os
import getpass
"""This file is no llonger used, but is being kept just in case I need it."""
# function below is from https://stackoverflow.com/questions/166506/finding-local-ip-addresses-using-pythons-stdlib
def get_ip():
s = socket.socket(socket.AF_INET, socket.SOCK_DGRAM)
try:
# doesn't even have to be reachable
s.connect(('10.255.255.255', 1))
IP = s.getsockname()[0]
except Exception:
IP = '127.0.0.1'
finally:
s.close()
return IP
def pxe_user_selection(): #will only be used if we see a pxe that doesn't use root
answer = str.lower(input("Is pxe username root? "))
if answer == "yes" or answer == "y" or answer == "true":
pxe_user = "root"
else:
pxe_user = getpass.getuser("What is the username you want to use? ")
return pxe_user
| UTF-8 | Python | false | false | 932 | py | 9 | misc_tools.py | 8 | 0.646996 | 0.620172 | 0 | 29 | 30.965517 | 115 |
harshad-deo/TorchVI | 1,090,921,741,124 | 3d0a8d94a0e3494e1bc91f797ce4d650e68620a1 | 02f3b2a84ea1fc0ff243fd5f4dc39c9f44e68657 | /abinitio/03_linear_regression.py | 7091b0913a5e1f2f7478a5c709db6e7aafaf6240 | [
"Apache-2.0"
]
| permissive | https://github.com/harshad-deo/TorchVI | fb2095c826424c8160e3447399c71414b3830756 | f66d1486201368c9906869477ba7ae254d2e7191 | refs/heads/main | 2023-02-25T10:20:05.907847 | 2021-01-20T15:34:31 | 2021-01-20T15:34:31 | 317,140,695 | 1 | 0 | null | null | null | null | null | null | null | null | null | null | null | null | null | import math
import numpy as np
import torch
from torch import optim, distributions
from tqdm import tqdm
class Model:
def __init__(self, reg_prior_mu, reg_prior_sd, noise_prior_scale):
self.mu_0 = torch.randn(1)
self.mu_1 = torch.randn(1)
self.mu_2 = torch.randn(1)
self.omega_0 = torch.randn(1)
self.omega_1 = torch.randn(1)
self.omega_2 = torch.randn(1)
self.mu_0.requires_grad = True
self.mu_1.requires_grad = True
self.mu_2.requires_grad = True
self.omega_0.requires_grad = True
self.omega_1.requires_grad = True
self.omega_2.requires_grad = True
self.norm_prior = distributions.Normal(loc=reg_prior_mu, scale=reg_prior_sd)
self.half_norm_prior = distributions.HalfNormal(scale=noise_prior_scale)
def __call__(self, xs, ys):
eta_0 = torch.randn(1)
eta_1 = torch.randn(1)
eta_2 = torch.randn(1)
zeta_0 = self.mu_0 + eta_0 * self.omega_0.exp()
zeta_1 = self.mu_1 + eta_1 * self.omega_1.exp()
zeta_2 = self.mu_2 + eta_2 * self.omega_2.exp()
y_mu = zeta_0 + zeta_1 * xs
theta_2 = zeta_2.exp()
dist = distributions.Normal(loc=y_mu, scale=theta_2)
data_lp = dist.log_prob(ys).sum()
theta_lp = self.norm_prior.log_prob(zeta_0)
theta_lp += self.norm_prior.log_prob(zeta_1)
theta_lp += self.half_norm_prior.log_prob(theta_2)
jac = zeta_2
return data_lp + theta_lp + jac + self.omega_0 + self.omega_1 + self.omega_2
def parameters(self):
return [self.mu_0, self.mu_1, self.mu_2, self.omega_0, self.omega_1, self.omega_2]
def __repr__(self):
mu_rep = f'{[self.mu_0, self.mu_1, self.mu_2]}'
omega_rep = f'{[self.omega_0, self.omega_1, self.omega_2]}'
return f'mu: {mu_rep}, omega: {omega_rep}'
def fit(reg_prior_mu, reg_prior_sd, noise_prior_scale, xs, ys, num_epochs):
model = Model(reg_prior_mu, reg_prior_sd, noise_prior_scale)
optimizer = optim.Adam(model.parameters(), lr=7e-2)
losses = np.zeros(num_epochs)
for i in tqdm(range(num_epochs)):
optimizer.zero_grad()
loss = -model(xs, ys)
losses[i] = loss.item()
loss.backward()
optimizer.step()
losses = np.log(losses)
return model, losses
if __name__ == "__main__":
import matplotlib.pyplot as plt
from utils.fix_seed import fix_seed
fix_seed(42)
num_samples = 100
slope = -0.8
intercept = 0.3
noise_scale = 0.5
xmin = -5
xmax = 5
xs = xmin + (xmax - xmin) * torch.rand(num_samples)
ys = intercept + slope * xs + noise_scale * torch.randn(num_samples)
num_epochs = 5000
model, losses = fit(0, 1, 1, xs, ys, num_epochs)
fig, axs = plt.subplots(2, 2)
mu_0 = model.mu_0.item()
mu_1 = model.mu_1.item()
mu_2 = model.mu_2.item()
sd_0 = math.exp(model.omega_0.item())
sd_1 = math.exp(model.omega_1.item())
sd_2 = math.exp(model.omega_2.item())
samples_theta_0 = np.random.normal(loc=mu_0, scale=sd_0, size=num_samples * 10)
samples_theta_1 = np.random.normal(loc=mu_1, scale=sd_1, size=num_samples * 10)
samples_theta_2 = np.exp(np.random.normal(loc=mu_2, scale=sd_2, size=num_samples * 10))
ax = axs[0][0]
ax.plot(losses)
ax.set_xlabel('Epoch')
ax.set_ylabel('Log Loss')
ax = axs[0][1]
ax.hist(samples_theta_0)
ax.set_xlabel('$\\theta_0$')
ax.set_ylabel('$p(\\theta_0)$')
ax = axs[1][0]
ax.hist(samples_theta_1)
ax.set_xlabel('$\\theta_1$')
ax.set_ylabel('$p(\\theta_1)$')
ax = axs[1][1]
ax.hist(samples_theta_2)
ax.set_xlabel('$\\theta_2$')
ax.set_ylabel('$p(\\theta_2)$')
plt.show()
print('ho gaya')
| UTF-8 | Python | false | false | 3,786 | py | 59 | 03_linear_regression.py | 35 | 0.584258 | 0.550449 | 0 | 132 | 27.681818 | 91 |
paulmagnus/CSPy | 4,578,435,146,120 | 58302ebe9743c9eb451a676047928c97400d99d4 | 672c7054ad3954ad0cbb9feaf1a18b2d48b8da83 | /Games-2017/28/Game.py | 8ccf8f633f9fb3b3e28ea9c2074c6590a2ffad06 | []
| no_license | https://github.com/paulmagnus/CSPy | 5197d78309ab85d1e8cc979ed5c17782ff4249e1 | e5d96a65fc84481b85072cfb55dea9a0666634b5 | refs/heads/master | 2020-03-07T23:08:35.445403 | 2018-04-02T13:46:38 | 2018-04-02T13:46:38 | 127,773,207 | 0 | 0 | null | null | null | null | null | null | null | null | null | null | null | null | null | """
*****************************************************************************
FILE: Game.py
AUTHOR: Olivia Maddox
PARTNER: N/A
ASSIGNMENT: Project 6
DATE: 04/07/17
DESCRIPTION: This program builds a Hamilton-themed Monopoly game. It involves
graphics and several classes including a die, a deck, a set of Chance cards,
players, pawns, board spaces and a game board. The board is the game's manager
and controls the ending of the game. The game ends when a player runs out of
money, making the winner the player who has money left over.
*****************************************************************************
"""
import random
from cs110graphics import *
class Die(EventHandler):
""" Create a six-sided die """
SIDES = 6
POSITIONS = [None,
[(0, 0), None, None, None, None, None],
[(-.25, .25), (.25, -.25), None, None, None, None],
[(-.25, .25), (0, 0), (.25, -.25), None, None, None],
[(-.25, -.25), (-.25, .25), (.25, -.25),
(.25, .25), None, None],
[(-.25, -.25), (-.25, .25), (.25, -.25),
(.25, .25), (0, 0), None],
[(-.25, -.25), (-.25, .25), (.25, -.25),
(.25, .25), (-.25, 0), (.25, 0)]]
def __init__(self, board, width=25, center=(291, 291), bgcolor='white',
fgcolor='black'):
# Make die the event handler
EventHandler.__init__(self)
# Initialize die attributes for creating die"
self._value = 1
self._square = Rectangle(width, width, center)
self._square.setFillColor(bgcolor)
self._square.setDepth(20)
self._center = center
self._active = True
self._board = board
self._width = width
self._pips = []
for _ in range(Die.SIDES):
pip = Circle(width / 15, center)
pip.setFillColor(fgcolor)
pip.addHandler(self)
pip.setDepth(20)
self._pips.append(pip)
self._square.addHandler(self)
def addTo(self, win):
"""Add die and pips to window"""
win.add(self._square)
for pip in self._pips:
win.add(pip)
def roll(self):
""" Change the die's current value to a random number between 1 and 6"""
if not self._active:
return
self._value = random.randrange(Die.SIDES) + 1
self._active = False
self._update()
def getValue(self):
""" Return this die's current value """
return self._value
def _update(self):
""" Private method. Make the appearance of the die match the die's
value """
positions = Die.POSITIONS[self._value]
cx, cy = self._center
for i in range(len(positions)):
if positions[i] is None:
self._pips[i].setDepth(25)
else:
self._pips[i].setDepth(15)
dx, dy = positions[i]
self._pips[i].moveTo((cx + dx * self._width,
cy + dy * self._width))
def deactivate(self):
""" Deactivate die """
self._active = False
def activate(self):
""" Activate die """
self._active = True
def handleMouseRelease(self, event):
""" When die is clicked, roll and report to board """
self.roll()
self._board.reportDieRoll()
class Deck:
"""A class for building a deck of cards. This class is not graphical"""
def __init__(self, win, board):
"""Creates a deck of 9 Chance cards."""
# Initializes deck list
self._board = board
self._deck = []
self._discard = []
# Sets deck activity to false
self._deckActive = False
# Lists out possible card numbers
nums = ["1", "2", "3", "4", "5", "6", "7", "8", "9"]
# Adds each card to the deck
for num in nums:
card = Card(num, num + ".png", "back.png", self)
self._deck.append(card)
# Adds each card to the window
for c in self._deck:
c.addTo(win)
def empty(self):
"""Returns True if the deck no longer contains any cards. Otherwise
false is returned."""
# Returns Boolean statement if length of deck is 0
return len(self._deck) == 0
def deal(self):
"""Deals a card. A card is removed from the top of the deck and
returned."""
# CITE: Tucker Ward
# DETAILS: The function "pop" removes a list's last item and returns it
card = self._deck.pop()
self._discard.append(card)
return card
def shuffle(self):
"""All cards currently in the deck are randomly ordered. """
# Initializes a new deck for shuffled cards
shuffled = []
# Appends cards from a random position in the deck to shuffled deck
for _ in range(9):
shuffled.append(self._deck.pop(random.randrange(len(self._deck))))
# Sets the deck equal to the shuffled deck
self._deck = shuffled
def activateChance(self):
""" Activate chance cards """
self._deckActive = True
def deactivateChance(self):
""" Deactivate chance cards """
self._deckActive = False
def getDeckActive(self):
""" Return bool statement regarding deck activity """
return self._deckActive
def executeChanceCard(self, num):
""" Send message to board to execute chance card """
self._board.executeChanceCard(num)
class Card(EventHandler):
"""A class used for building graphical Chance cards"""
def __init__(self, num, faceFileName, backFileName, deck):
"""Creates a Chance card with the given number."""
# Set up Card as the EventHandler
EventHandler.__init__(self)
# Initialize attributes
self._deck = deck
self._num = num
# Create image objects for card sides
faceurl = "https://cs.hamilton.edu/~omaddox/images/" + faceFileName
self._face = Image(faceurl, (600, 590), width=114, height=160)
backurl = "https://cs.hamilton.edu/~omaddox/images/" + backFileName
self._back = Image(backurl, (600, 590), width=114, height=160)
self._back.addHandler(self)
# Rotate card front and back
self._face.rotate(45)
self._back.rotate(45)
# Assign card attributes
self._depth = 10
self._size = (150, 210)
self._center = (650, 600)
# List card sides and set which one is showing
self._sides = [self._back, self._face]
self._show = 0
def addTo(self, win):
"""Add the card to the given graphics window."""
win.add(self._face)
win.add(self._back)
def removeFrom(self, win):
"""Remove the card from the given graphics window. """
win.remove(self._face)
win.remove(self._face)
def flip(self):
"""Flip the card over. This visually flips the card over as well."""
# Switch card side to faced up or down. Update card.
self._show = (self._show + 1) % 2
self._update()
def move(self, dx, dy):
"""Move a card by dx and dy."""
self._face.move(dx, dy)
self._back.move(dx, dy)
def setDepth(self, depth):
"""Set the depth of graphical objects representing the card to depth"""
self._depth = depth
self._update()
def handleMouseRelease(self, event):
"""Handle mouse release event from the button"""
# Deal card, flip card and move it to pile if deck isn't empty
if self._deck.empty() != True:
card = self._deck.deal()
card.flip()
card.move(90, 0)
# Send card num to the deck to execute chance card
if self._deck.getDeckActive() is True:
self._deck.executeChanceCard(card.getNum())
def _update(self):
"""Recieve calls from other functions, and adjust image depths to
represent which card side should be showing"""
# Locate the correct side from card sides list and adjust the depth
for i in range(len(self._sides)):
if i == self._show:
self._sides[i].setDepth(self._depth)
else:
self._sides[i].setDepth(self._depth + 1)
def getNum(self):
""" Returns num value """
return self._num
class Player:
""" A class used the players in the game """
def __init__(self, board, player, value):
self._board = board
self._player = player
self._money = value
self._props = []
colors = ["black", "white"]
self._color = colors[player]
# Create pawn piece for corresponding player
self._pawn = Pawn(self._board, self._color, self._player)
# Create text to display each player's money
self._monText = Text(("Player {} money left: ${}".
format(self._player + 1, self._money)),
(1000, 30 + player * 225), 14)
# Create text to display each player's properties
self._propText = Text(("Properties: {}".format(self._props)),
(1000, 50 + player * 225), 14)
# Create color indicator to match player with its pawn color
self._tellColor = Rectangle(30, 30, (1130, 20 + player * 225))
self._tellColor.setFillColor(self._color)
# Initialize jail statements as false
self._isInJail = False
self._isJustFreed = False
def addTo(self, win):
""" Add pawn, money text and color indicator to window """
self._pawn.addTo(win)
win.add(self._monText)
win.add(self._propText)
win.add(self._tellColor)
def moveTo(self, position):
""" Move pawn to given position """
self._pawn.moveTo(position)
def setPosition(self, pos):
""" Set pawn position to given position """
self._pawn.setPosition(pos)
def addMoney(self, value):
""" Add money to current value """
self._money += value
self._monText.setTextString("Player {} money left: ${}".
format(self._player + 1, self._money))
def loseMoney(self, value):
""" Subtract money from current value """
self._money -= value
self._monText.setTextString("Player {} money left: ${}".
format(self._player + 1, self._money))
# If player's money is less than or equal to 0, game ends and they lose
if self._money <= 0:
self._board.gameOver()
def propOwn(self, prop):
""" method docstring """
for prp in self._props:
if prp == prop:
return True
return False
def addProperty(self, prop):
""" Append property to player's property list """
self._props.append(prop)
self._propText.setTextString(("Properties: {}".format(self._props)))
def getPawn(self):
""" Return pawn """
return self._pawn
def activate(self):
""" Activate pawn to allow moving """
self._pawn.activate()
def deactivate(self):
""" Deactivate pawn to prohibit moving """
self._pawn.deactivate()
def passedGo(self):
""" Add 200 when player has passed Go """
self.addMoney(200)
def goToJail(self):
""" Player is sent to jail """
self._board.goToJail()
def setJustFreed(self, val):
""" Set value to either true or false """
self._isJustFreed = val
def getJustFreed(self):
""" Return bool statement regarding player's release from jail """
return self._isJustFreed
def getPosition(self):
""" Return pawn position """
return self._pawn.getPosition()
def isInJail(self):
""" Return bool statement of whether player is in jail or not """
return self._isInJail
def stuckInJail(self):
""" Player is stuck in jail. Returns true. """
self._isInJail = True
def outOfJail(self):
""" Player is out of jail. Returns false. """
self._isInJail = False
def getMoney(self):
""" Return a player's money"""
return self._money
class Pawn(EventHandler):
""" A class dedicated to each player's pawn """
def __init__(self, board, color, ident):
# Set pawn as event handler
EventHandler.__init__(self)
# Initialize attributes
self._color = color
self._board = board
# Set identifying number for this pawn
self._ident = ident
# Establish current logical position on the board
self._position = 0
# Create pawn
self._square = Rectangle(30, 30, (829, 824))
self._square.setFillColor(color)
self._square.addHandler(self)
# Set pawn to inactive
self._pawnActive = False
def activate(self):
""" Set pawn to active. Create a green thick border to show activity."""
self._pawnActive = True
self._square.setBorderColor('green')
self._square.setBorderWidth(5)
def deactivate(self):
"""Set pawn to inactive. Create a black border to show inactivity """
self._pawnActive = False
self._square.setBorderColor('black')
self._square.setBorderWidth(1)
def handleMouseRelease(self, event):
""" Tell board that the active pawn was clicked """
if not self._pawnActive:
return
self._board.reportPawnClick(self._ident)
def addTo(self, win):
""" Add pawn piece to window """
win.add(self._square)
def getPosition(self):
""" Return pawn position """
return self._position
def moveTo(self, position):
""" Move pawn to given position """
self._square.moveTo(position)
def setPosition(self, pos):
""" Set pawn position to given position """
self._position = pos
def move(self, dx, dy):
""" Move pawn by dx and dy """
self._square.move(dx, dy)
class BoardSpace:
""" A class dedicated to the spaces on the board and their corresponding
kind"""
def __init__(self, board, center, kind):
self._board = board
self._center = center
self._kind = kind
def getCenter(self):
""" Return the board space's center """
return self._center
def getKind(self):
""" Return the board space's kind """
return self._kind
def implementAction(self):
""" Implement action for the space's designated kind """
# Chance:
if self._kind == "Chance":
self._board.activateChance()
# Properties:
if self._kind == "Prop":
self._board.landedOnProp(self._center)
# Utilities:
if self._kind == "Utility":
self._board.landedOnProp(self._center)
# Go:
if self._kind == "Go":
self._board.passedGo()
self._board.changeTurn()
# Tax:
if self._kind == "Tax":
self._board.taxes()
# Free parking
if self._kind == "Park":
self._board.changeTurn()
# Just visiting jail
if self._kind == "Visit":
self._board.changeTurn()
# Go to jail
if self._kind == "ToJail":
self._board.goToJail()
self._board.changeTurn()
class Board:
""" This class is the game's controller site. Creates board spaces. Keeps
track of pawn movement and changing turns. Implements actions from board
space class. Controls game ending. """
def __init__(self, win):
# Set image as game board
self._board = Image("https://cs.hamilton.edu/~omaddox/images/yes.png",
(585, 450), 1170, 900)
# Add board and die to the window
win.add(self._board)
self._die = Die(self)
self._die.addTo(win)
self._win = win
# Initialize pawn movement to false
self._pawnMoved = False
# Set up space positions and kinds
self._positions = [((831, 832), "Go"), ((714, 876), "Prop"),
((625, 874), "Prop"), ((541, 871), "Chance"),
((447, 873), "Prop"), ((357, 874), "Prop"),
((272, 877), "Tax"), ((182, 878), "Prop"),
((25, 872), "Visit"), ((24, 716), "Chance"),
((21, 628), "Prop"), ((18, 535), "Prop"),
((20, 448), "Utility"), ((20, 362), "Prop"),
((20, 271), "Prop"), ((20, 187), "Prop"),
((21, 62), "Park"), ((179, 23), "Prop"),
((269, 20), "Prop"), ((360, 22), "Chance"),
((446, 21), "Utility"), ((537, 16), "Prop"),
((625, 21), "Utility"), ((712, 20), "Prop"),
((869, 23), "ToJail"), ((873, 175), "Prop"),
((873, 270), "Utility"), ((873, 354), "Prop"),
((873, 445), "Prop"), ((874, 533), "Prop"),
((873, 626), "Tax"), ((871, 716), "Prop"),
((86, 810), "Jail")]
# Set up properties with price and statement if bought and center
self._props = [(1, "Bundy", 60, False, (714, 876)),
(2, "Dunham", 60, False, (625, 874)),
(4, "North", 100, False, (447, 873)),
(5, "South", 100, False, (357, 874)),
(7, "Wertimer", 120, False, (182, 878)),
(10, "Keehn", 140, False, (21, 628)),
(11, "Major", 140, False, (18, 535)),
(12, "McEwen", 200, False, (20, 448)),
(13, "Minor", 180, False, (20, 362)),
(14, "Babbitt", 180, False, (20, 271)),
(15, "Milbank", 200, False, (20, 187)),
(17, "Carnegie", 220, False, (179, 23)),
(18, "Macintosh", 220, False, (269, 20)),
(20, "Commons", 200, False, (446, 21)),
(21, "Root", 260, False, (537, 16)),
(22, "Diner", 200, False, (625, 21)),
(23, "Kirkland", 260, False, (712, 20)),
(25, "Morris", 300, False, (873, 175)),
(26, "Opus", 200, False, (873, 270)),
(27, "Ferguson", 300, False, (873, 354)),
(28, "Rogers", 320, False, (873, 445)),
(29, "Farmhouse", 350, False, (874, 533)),
(31, "Co-op", 400, False, (871, 716))]
# Set up property rent
self._rent = [(1, 10), (2, 10), (4, 17), (5, 17), (7, 20), (10, 23),
(11, 23), (12, 33), (13, 30), (14, 30), (15, 33),
(17, 37), (18, 37), (20, 33), (21, 43), (22, 33),
(23, 47), (25, 50), (26, 33), (27, 50), (28, 53),
(29, 58), (31, 67)]
# Set up board spaces
self._spaces = []
for i in range(len(self._positions)):
space = BoardSpace(self, self._positions[i][0],
self._positions[i][1])
self._spaces.append(space)
# Set up players
self._players = []
for player in range(int(input("How many players? (1-2)"))):
thisPlayer = Player(self, player, 1500)
thisPlayer.addTo(win)
self._players.append(thisPlayer)
self._updatePawnLocations()
# Set current player
self._current = len(self._players) - 1
self.changeTurn()
# Create and shuffle deck
self._deck = Deck(win, self)
self._deck.shuffle()
def reportPawnClick(self, ident):
""" Report to board that current player has been clicked """
if self._pawnMoved:
return
if ident == self._current:
self._pawnMoved = True
thePawn = self._players[ident].getPawn()
pos = thePawn.getPosition()
# If current player is in jail, change turns unless die value is 6
if self._players[ident].isInJail():
if self._die.getValue() != 6:
self.changeTurn()
# If player in jail rolls a 6, they are released from jail
else:
self._players[ident].outOfJail()
self.changeTurn()
self._players[ident].setJustFreed(True)
# Current player is out of jail, value of freedom reinitializes
else:
if self._players[ident].getJustFreed():
pos += 8
self._players[ident].setJustFreed(False)
pos += self._die.getValue()
# Call passed go
if pos > (len(self._positions) - 1):
self.passedGo()
# Create pathway for pawns around the board.
pos = pos % (len(self._positions) - 1)
thePawn.setPosition(pos)
self._updatePawnLocations()
# Get player position to tell board space to implement action
playerPos = self._players[self._current].getPosition()
self._spaces[playerPos].implementAction()
def landedOnProp(self, center):
""" Player either has choice to buy if untaken, or has to pay rent if
taken """
# Ask player if they want to buy untaken property
if self.propTaken(center) is False:
if input("Do you want to buy this property? Yes or No:") == "Yes":
self.buyProperty()
else:
self.changeTurn()
# Check if bought property is landed on by owner
else:
for i in range(len(self._props)):
if self._props[i][4] == center:
# If true, change turn
if self._players[self._current].propOwn(self._props[i][1]):
self.changeTurn()
# if false, player pay rent
else:
self.payRent()
def propTaken(self, center):
""" Check whether the property has been bought or not """
pos = 0
for i in range(len(self._positions)):
if self._positions[i][0] == center:
pos = i
# Return bool statement of whether property has been bought
for j in range(len(self._props)):
if self._props[j][0] == pos:
return self._props[j][3]
def buyProperty(self):
""" Player buys property. Spends money and takes away availability """
for i in range(len(self._props)):
if self._props[i][0] == self._players[self._current].getPosition():
# Player loses money when buying
self._players[self._current].loseMoney(self._props[i][2])
self._players[self._current].addProperty(self._props[i][1])
# Change property availability from False to True
self._props[i][3] = True
self.changeTurn()
def payRent(self):
""" Player pays rent when landing on other player's properties """
for i in range(len(self._rent)):
if self._rent[i][0] == self._players[self._current].getPosition():
# Gives owner money and loses own money
self.givePlayMon(self._rent[i][1], self._players[self._current])
self.changeTurn()
def passedGo(self):
""" Current player passes go """
self._players[self._current].passedGo()
def goToJail(self):
""" Current player goes to jail """
self._players[self._current].stuckInJail()
self._players[self._current].setPosition(32)
self._updatePawnLocations()
self.changeTurn()
def reportDieRoll(self):
""" Reports whether the die has been rolled and pawn has moved """
self._pawnMoved = False
def changeTurn(self):
""" Switch turn of players. Activate die."""
# Deactivate current player and activate other player
self._players[self._current].deactivate()
self._current = (self._current + 1) % len(self._players)
self._players[self._current].activate()
self._die.activate()
def givePlayMon(self, value, player):
""" Give other player money, current player loses own money """
if self._players[0] != player:
self._players[0].addMoney(value)
player.loseMoney(value)
else:
player.addMoney(value)
self._players[0].loseMoney(value)
def _updatePawnLocations(self):
""" Move the two pawns to their correct locations on the window """
offsets = [(-2, 0), (2, 0), (0, -2), (0, 2)]
for i in range(len(self._players)):
self._pawn = self._players[i].getPawn()
pos = self._pawn.getPosition()
self._pawn.moveTo(self._spaces[pos].getCenter())
self._pawn.move(offsets[i][0] * 10, offsets[i][1] * 10)
def taxes(self):
""" Take money away from player and change turns"""
self._players[self._current].loseMoney(200)
self.changeTurn()
def activateChance(self):
""" Activate chance cards """
self._deck.activateChance()
def executeChanceCard(self, num):
""" Execute the chance card and its each specific function"""
if num == "1":
# Pay each player $100
self.givePlayMon(100, self._players[self._current])
self.changeTurn()
self._deck.deactivateChance()
if num == "2":
# Advance to go
self._players[self._current].setPosition(0)
self._updatePawnLocations()
self.passedGo()
self.changeTurn()
self._deck.deactivateChance()
if num == "3":
# Go to jail
self.goToJail()
self._deck.deactivateChance()
if num == "4":
# Pay bank $150
self._players[self._current].loseMoney(150)
self.changeTurn()
self._deck.deactivateChance()
if num == "5":
# Advance to free parking
self._players[self._current].setPosition(16)
self._updatePawnLocations()
self.changeTurn()
self._deck.deactivateChance()
if num == "6":
# Move back 3 spaces
currentPos = self._players[self._current].getPosition()
self._players[self._current].setPosition(currentPos - 3)
self._updatePawnLocations()
self.changeTurn()
self._deck.deactivateChance()
if num == "7":
# Move forward 4 spaces
currentPos = self._players[self._current].getPosition()
self._players[self._current].setPosition(currentPos + 4)
self._updatePawnLocations()
self.changeTurn()
self._deck.deactivateChance()
if num == "8":
# Collect $150
self._players[self._current].addMoney(150)
self.changeTurn()
self._deck.deactivateChance()
if num == "9":
# Move to opus
self._players[self._current].setPosition(26)
self._updatePawnLocations()
self.changeTurn()
self._deck.deactivateChance()
def gameOver(self):
""" End game """
# Deactivate players and die
for i in range(len(self._players)):
self._players[i].deactivate()
self._die.deactivate()
# Print and add game-over text to window
gameOverText = Text("Game over!", (500, 230), 48)
self._win.add(gameOverText)
# Calculate winner
for i in range(len(self._players)):
if self._players[i].getMoney() > 0:
winner = i + 1
winnerText = Text("Player {} wins!".format(winner), (500, 270), 32)
self._win.add(winnerText)
def play(win):
""" function docstring """
_ = Board(win)
StartGraphicsSystem(play, width=1170, height=900)
| UTF-8 | Python | false | false | 30,996 | py | 179 | Game.py | 152 | 0.483933 | 0.456381 | 0 | 971 | 30.92173 | 80 |
novayo/LeetCode | 2,138,893,740,721 | 41a5999dba31548a6506b1174dd777a70a637a05 | 2f63688febd21dc3ae6b19abfa79ad313c820154 | /0158_Read_N_Characters_Given_Read4_II_-_Call_multiple_times/try_2.py | a4c2dd4e8324887b41c77bbd258c20c2e4d12a53 | []
| no_license | https://github.com/novayo/LeetCode | cadd03587ee4ed6e35f60294070165afc1539ac8 | 54d0b3c237e0ffed8782915d6b75b7c6a0fe0de7 | refs/heads/master | 2023-08-14T00:35:15.528520 | 2023-07-30T05:56:05 | 2023-07-30T05:56:05 | 200,248,146 | 8 | 1 | null | false | 2022-11-19T04:37:54 | 2019-08-02T14:24:19 | 2022-11-02T09:01:22 | 2022-11-19T04:37:54 | 1,851 | 5 | 1 | 0 | Python | false | false | # The read4 API is already defined for you.
# def read4(buf4: List[str]) -> int:
class Solution:
def __init__(self):
self.rest = []
def read(self, buf: List[str], n: int) -> int:
while len(self.rest) < n:
tmp = [''] * 4
num = read4(tmp)
if num == 0:
break
self.rest.extend(tmp[:num])
if len(self.rest) < n:
n = len(self.rest)
buf[:n] = self.rest[:n]
self.rest = self.rest[n:]
return n
| UTF-8 | Python | false | false | 537 | py | 2,665 | try_2.py | 1,754 | 0.44879 | 0.437616 | 0 | 20 | 25.8 | 50 |
ukchiji/team-project-3-matron | 8,091,718,411,467 | 86611b4ac4af3f8940359db4bc3d5a1f77f91d42 | 2686ef5f9fbe941796f4c773c72cc03be813b68c | /selenium_test/test_IE/test_basics.py | c70d191a006c949ed49511c50c83eba7711cd595 | [
"MIT"
]
| permissive | https://github.com/ukchiji/team-project-3-matron | 25b4f46a7c4b232fc78dcc9220110129aa465052 | 53e4298ac8ff2866f187783a2e7d74cae578d4d5 | refs/heads/master | 2023-04-12T22:48:17.371003 | 2020-04-11T01:27:28 | 2020-04-11T01:27:28 | null | 0 | 0 | null | null | null | null | null | null | null | null | null | null | null | null | null | import unittest
from selenium import webdriver
import time
from selenium.webdriver.common.action_chains import ActionChains
import os
from testutils import EasyDriver
class seleniumtest(EasyDriver):
def test_Heroku(self):
self.driver.maximize_window()
self.driver.get("https://floating-shore-56001.herokuapp.com/")
time.sleep(1)
print("\nTitle of the page is: " + self.driver.title)
self.driver.close()
def test_get_element(self):
self.driver.get("https://floating-shore-56001.herokuapp.com/")
button = self.driver.find_element_by_id('edit_floor')
button.click()
time.sleep(3)
self.driver.close()
if __name__ == '__main__':
unittest.main()
| UTF-8 | Python | false | false | 758 | py | 25 | test_basics.py | 18 | 0.646438 | 0.630607 | 0 | 26 | 28.115385 | 70 |
garaemon/gcal-watcher | 4,801,773,484,710 | 395003288a3b12ea21d1598d9c46207c048edb40 | e8ca9de4562353e77daee9fda8b05993480dc60a | /gcal_watcher/command.py | b24f6c2eb5b76cc14882159124ff97361c52a3c0 | []
| no_license | https://github.com/garaemon/gcal-watcher | 547d04c3bae334b36950c172b0895f0326c32cb1 | da380235e3c41ee8a96d6cc4bdbaf5907a180758 | refs/heads/master | 2021-05-10T13:35:24.801393 | 2018-02-03T07:25:40 | 2018-02-03T07:25:40 | 118,480,214 | 0 | 0 | null | null | null | null | null | null | null | null | null | null | null | null | null | import datetime
import json
from threading import Thread
import requests
class CommandException(Exception):
pass
class Command(object):
REQUIRED_FIELDS = ['method', 'url']
def __init__(self, json_object, event_date):
Command.verify_fields(json_object)
self.is_started = False
self.method = json_object['method']
self.url = Command.replace_vars(json_object['url'], event_date)
self.params = dict()
self.json_object = json_object
self.event_date = event_date
if 'params' in json_object:
for key in json_object['params']:
self.params[key] = Command.replace_vars(json_object['params'][key], event_date)
def invoke(self):
print('invoked!', self.json_object)
self.thread = Thread(target=self.invoke_thread)
self.thread.daemon = True
self.thread.run()
self.is_started = True
def invoke_thread(self):
try:
if self.method.upper() == 'GET':
res = requests.get(self.url)
elif self.method.upper() == 'POST':
res = requests.post(
self.url, json.dumps(self.params), headers={
'Content-Type': 'application/json'
})
except Exception as e:
print('Failed to execute command', self.json_object)
print('Done')
def __eq__(self, other):
return (self.method == other.method and self.url == other.url and
self.params == other.params)
@classmethod
def verify_fields(cls, obj):
for field in cls.REQUIRED_FIELDS:
if field not in obj:
raise CommandException('no {} is specified'.format(field))
return True
@classmethod
def replace_vars(_cls, string, today, yesterday=None, tomorrow=None):
yesterday = yesterday or today + datetime.timedelta(days=-1)
tomorrow = tomorrow or today + datetime.timedelta(days=1)
replace_rules = {
'${today.year}': '%04d' % today.year,
'${today.month}': '%02d' % today.month,
'${today.day}': '%02d' % today.day,
'${yesterday.year}': '%04d' % yesterday.year,
'${yesterday.month}': '%02d' % yesterday.month,
'${yesterday.day}': '%02d' % yesterday.day,
'${tomorrow.year}': '%04d' % tomorrow.year,
'${tomorrow.month}': '%02d' % tomorrow.month,
'${tomorrow.day}': '%02d' % tomorrow.day,
}
for from_string, to_string in replace_rules.items():
string = string.replace(from_string, to_string)
return string
def main():
command = Command({
'method': 'GET',
'url': 'http://localhost:8000',
}, datetime.datetime.now())
command.invoke()
if __name__ == '__main__':
main()
#
# {"method": "POST",
# "url": "http://localhost:5000/record",
# "params": {
# "station_id": "TBS",
# "start_date": "${today.year}-${today.month}-${today.day}-22-00",
# "artist": "Foo",
# "album": "Foo-album",
# "title": "Foo-${today.year}-${today.month}-${today.day}"
# }
# }
| UTF-8 | Python | false | false | 3,168 | py | 10 | command.py | 8 | 0.553346 | 0.543245 | 0 | 99 | 31 | 95 |
cubedro/raiden | 7,662,221,666,865 | 4dc97ed4a54528565198265e9a1b2fd6266e9015 | 4b70ceb354c84d2281fa32a606883cfe407f311d | /raiden/tests/test_service.py | 860daf1f202f2f45a47677ef115cbfb5c1d0e7b1 | [
"MIT"
]
| permissive | https://github.com/cubedro/raiden | 0254673f8bd9e227b870452c4d477dfbcb583f7f | eed6e2d88d3caa755b2aa51d1ca5f8295b5ab670 | refs/heads/master | 2021-01-12T13:27:33.059247 | 2016-03-03T14:31:18 | 2016-03-11T17:32:17 | null | 0 | 0 | null | null | null | null | null | null | null | null | null | null | null | null | null | from raiden.messages import Ping, Ack, decode
from raiden.app import create_network
from raiden.transport import UnreliableTransport, UDPTransport
from raiden.raiden_protocol import RaidenProtocol
from .utils import setup_messages_cb
import gevent
def test_ping():
apps = create_network(num_nodes=2, num_assets=0, channels_per_node=0)
a0, a1 = apps
messages = setup_messages_cb()
p = Ping(nonce=0)
a0.raiden.sign(p)
a0.raiden.protocol.send(a1.raiden.address, p)
gevent.sleep(0.1)
assert len(messages) == 2 # Ping, Ack
assert decode(messages[0]) == p
a = decode(messages[1])
assert isinstance(a, Ack)
assert a.echo == p.hash
def test_ping_dropped_message():
apps = create_network(num_nodes=2, num_assets=0, channels_per_node=0,
transport_class=UnreliableTransport)
a0, a1 = apps
# mock transport with packet loss, every 3nd is lost, starting with first message
UnreliableTransport.droprate = 3
RaidenProtocol.try_interval = 0.1 # for fast tests
RaidenProtocol.repeat_messages = True
messages = setup_messages_cb()
UnreliableTransport.network.counter = 0
p = Ping(nonce=0)
a0.raiden.sign(p)
a0.raiden.protocol.send(a1.raiden.address, p)
gevent.sleep(1)
assert len(messages) == 3 # Ping(dropped), Ping, Ack
for i in [0, 1]:
assert decode(messages[i]) == p
for i in [2]:
a = decode(messages[i])
assert isinstance(a, Ack)
assert a.echo == p.hash
# try failing Ack
messages = setup_messages_cb()
assert not messages
UnreliableTransport.network.counter = 2 # first message sent, 2nd dropped
p = Ping(nonce=0)
a0.raiden.sign(p)
a0.raiden.protocol.send(a1.raiden.address, p)
gevent.sleep(1)
for m in messages:
print decode(m)
assert len(messages) == 4 # Ping, Ack(dropped), Ping, Ack
for i in [0, 2]:
assert decode(messages[i]) == p
for i in [1, 3]:
a = decode(messages[i])
assert isinstance(a, Ack)
assert a.echo == p.hash
RaidenProtocol.repeat_messages = False
def test_ping_udp():
apps = create_network(num_nodes=2, num_assets=0, channels_per_node=0,
transport_class=UDPTransport)
a0, a1 = apps
messages = setup_messages_cb()
p = Ping(nonce=0)
a0.raiden.sign(p)
a0.raiden.protocol.send(a1.raiden.address, p)
gevent.sleep(0.1)
assert len(messages) == 2 # Ping, Ack
assert decode(messages[0]) == p
a = decode(messages[1])
assert isinstance(a, Ack)
assert a.echo == p.hash
| UTF-8 | Python | false | false | 2,609 | py | 17 | test_service.py | 15 | 0.644308 | 0.621694 | 0 | 87 | 28.988506 | 85 |
pulumi/pulumi-azure-native | 14,267,881,393,696 | 9a2dbf1df6711d101e57fd7e62a4167f3a2e67b9 | b049a961f100444dde14599bab06a0a4224d869b | /sdk/python/pulumi_azure_native/desktopvirtualization/__init__.py | 4cff60e757ad5f60f7795da7f0a7abb842681113 | [
"BSD-3-Clause",
"Apache-2.0"
]
| permissive | https://github.com/pulumi/pulumi-azure-native | b390c88beef8381f9a71ab2bed5571e0dd848e65 | 4c499abe17ec6696ce28477dde1157372896364e | refs/heads/master | 2023-08-30T08:19:41.564780 | 2023-08-28T19:29:04 | 2023-08-28T19:29:04 | 172,386,632 | 107 | 29 | Apache-2.0 | false | 2023-09-14T13:17:00 | 2019-02-24T20:30:21 | 2023-09-11T17:08:08 | 2023-09-14T13:16:52 | 2,507,628 | 104 | 26 | 377 | Python | false | false | # coding=utf-8
# *** WARNING: this file was generated by pulumi. ***
# *** Do not edit by hand unless you're certain you know what you are doing! ***
from .. import _utilities
import typing
# Export this package's modules as members:
from ._enums import *
from .application import *
from .application_group import *
from .get_application import *
from .get_application_group import *
from .get_host_pool import *
from .get_msix_package import *
from .get_private_endpoint_connection_by_host_pool import *
from .get_private_endpoint_connection_by_workspace import *
from .get_scaling_plan import *
from .get_scaling_plan_personal_schedule import *
from .get_scaling_plan_pooled_schedule import *
from .get_workspace import *
from .host_pool import *
from .msix_package import *
from .private_endpoint_connection_by_host_pool import *
from .private_endpoint_connection_by_workspace import *
from .scaling_plan import *
from .scaling_plan_personal_schedule import *
from .scaling_plan_pooled_schedule import *
from .workspace import *
from ._inputs import *
from . import outputs
# Make subpackages available:
if typing.TYPE_CHECKING:
import pulumi_azure_native.desktopvirtualization.v20210201preview as __v20210201preview
v20210201preview = __v20210201preview
import pulumi_azure_native.desktopvirtualization.v20220210preview as __v20220210preview
v20220210preview = __v20220210preview
import pulumi_azure_native.desktopvirtualization.v20220401preview as __v20220401preview
v20220401preview = __v20220401preview
import pulumi_azure_native.desktopvirtualization.v20220909 as __v20220909
v20220909 = __v20220909
import pulumi_azure_native.desktopvirtualization.v20221014preview as __v20221014preview
v20221014preview = __v20221014preview
import pulumi_azure_native.desktopvirtualization.v20230707preview as __v20230707preview
v20230707preview = __v20230707preview
else:
v20210201preview = _utilities.lazy_import('pulumi_azure_native.desktopvirtualization.v20210201preview')
v20220210preview = _utilities.lazy_import('pulumi_azure_native.desktopvirtualization.v20220210preview')
v20220401preview = _utilities.lazy_import('pulumi_azure_native.desktopvirtualization.v20220401preview')
v20220909 = _utilities.lazy_import('pulumi_azure_native.desktopvirtualization.v20220909')
v20221014preview = _utilities.lazy_import('pulumi_azure_native.desktopvirtualization.v20221014preview')
v20230707preview = _utilities.lazy_import('pulumi_azure_native.desktopvirtualization.v20230707preview')
| UTF-8 | Python | false | false | 2,551 | py | 13,948 | __init__.py | 5,665 | 0.792238 | 0.678949 | 0 | 52 | 48.038462 | 107 |
harshpv07/InternRESTAPI | 11,536,282,172,819 | 695a855272bd654c11aa7aebf5e8b668928a39aa | dda8b38073a7e0bed87a0fa9b948f188384cb1fe | /venv/lib/python3.7/sre_parse.py | da55ab08d648534a54f78219228f25e92202c832 | []
| no_license | https://github.com/harshpv07/InternRESTAPI | fcb6e0a4f9c6e80484855649821d27971344fd8e | 57d3bcc7ca41925d79ea00227e57a96d53dd22b3 | refs/heads/master | 2021-06-20T13:55:21.593685 | 2019-05-25T11:25:09 | 2019-05-25T11:25:09 | 188,557,165 | 0 | 0 | null | false | 2021-03-19T22:41:14 | 2019-05-25T11:20:24 | 2019-05-25T11:25:12 | 2021-03-19T22:41:14 | 15,511 | 0 | 0 | 1 | Python | false | false | /home/harsh/anaconda3/lib/python3.7/sre_parse.py | UTF-8 | Python | false | false | 48 | py | 48 | sre_parse.py | 46 | 0.8125 | 0.75 | 0 | 1 | 48 | 48 |
nguyennhut401/quangly_vanban | 12,275,016,570,802 | e1ec988f00032f54baf6b4932b5a7c988249d04c | 53c6d31da97e7c1a6bc72cc4440361689a5c1f53 | /the_docs/models.py | 5d73e029548aa12ae201f94368843d429d1c0ee5 | [
"MIT"
]
| permissive | https://github.com/nguyennhut401/quangly_vanban | ab8e7832b5df8f7cedaf7a0e9e56071c4e30a446 | 39a485156b567654ceece1fac28f043a58886006 | refs/heads/master | 2019-01-26T22:00:04.855791 | 2017-08-01T13:01:10 | 2017-08-01T13:01:10 | 98,044,891 | 0 | 0 | null | null | null | null | null | null | null | null | null | null | null | null | null | # -*- coding: utf-8 -*-
from __future__ import unicode_literals
from django.db import models
from slugify import slugify
import hashlib
from .library import UnicodeHtmlToUnicode, RemoveHTML
import pdb
# Create your models here.
class Dictionary(models.Model):
"""Model Dictionary"""
name = models.CharField(max_length = 50)
description = models.CharField(max_length = 250, null = True, blank = True)
is_type = models.BooleanField(default = False)
parent = models.ForeignKey('self', on_delete = models.CASCADE, related_name = 'Dictionary_child', null = True, blank = True)
creation_time = models.DateTimeField(auto_now_add = True)
modification_time = models.DateTimeField(auto_now = True, blank = True)
def __unicode__(self):
return self.name
class VanBan(models.Model):
"""Model VanBan"""
name = models.CharField(max_length = 250)
permalink = models.TextField(unique =True, blank = True, primary_key = True)
wordFile = models.FileField(null = True, blank = True)
content = models.TextField()
content_unicode = models.TextField(blank = True, editable = False)
documentType = models.ForeignKey(Dictionary, on_delete = models.CASCADE, related_name = 'Dictionary_VanBan')
creation_time = models.DateTimeField(auto_now_add = True)
modification_time = models.DateTimeField(auto_now = True, blank = True)
def delete(self, *args, **kwargs):
self.wordFile.delete()
super(VanBan, self).delete(*args, **kwargs)
def save(self, *args, **kwargs):
# pdb.set_trace()
if not self.pk:
hashString = hashlib.sha256(slugify(self.name) + "-" + slugify(self.documentType.name))
self.permalink = hashString.hexdigest()
self.content = UnicodeHtmlToUnicode(self.content)
stringClear = RemoveHTML(self.content).replace('\r', '').replace('\n','')
stringClear = ' '.join(stringClear.split())
self.content_unicode = stringClear
super(VanBan, self).save(*args, **kwargs)
def __unicode__(self):
return self.name
class DieuKhoan(models.Model):
"""Model DieuKhoan"""
name = models.CharField(max_length = 250)
permalink = models.TextField(unique = True, blank = True, primary_key = True)
content = models.TextField()
content_unicode = models.TextField(blank = True, editable = False)
wordFile = models.FileField(null = True, blank = True)
DieuKhoanCha = models.ForeignKey('self', on_delete = models.CASCADE, related_name = 'dieukhoan_con', null = True, blank = True)
VanBan = models.ForeignKey(VanBan, on_delete = models.CASCADE, related_name = 'dieukhoan', null = True, blank = True)
creation_time = models.DateTimeField(auto_now_add = True)
modification_time = models.DateTimeField(auto_now = True, blank = True)
def save(self, *args, **kwargs):
# pdb.set_trace()
if not self.pk:
hashString = hashlib.sha256(slugify(self.name))
self.permalink = hashString.hexdigest()
self.content = UnicodeHtmlToUnicode(self.content)
stringClear = RemoveHTML(self.content).replace('\r', '').replace('\n','')
stringClear = ' '.join(stringClear.split())
self.content_unicode = stringClear
super(DieuKhoan, self).save(*args, **kwargs) # Call the "real" save() method.
def __unicode__(self):
return "{0}-{1}".format(self.DieuKhoanCha, self.name) | UTF-8 | Python | false | false | 3,192 | py | 16 | models.py | 13 | 0.715539 | 0.709273 | 0 | 81 | 38.419753 | 128 |
nicolasbon38/Werewolf_game_discord_bot | 17,806,934,415,400 | 39a2cb8512c11af2bd417fa656fc29abe4201411 | 4d57da4b95251a6a9af861a855b0b1ca4b50b7fe | /state_witch.py | 50be5ea79f37a9d4ea0f82265cb43e57423d815a | []
| no_license | https://github.com/nicolasbon38/Werewolf_game_discord_bot | f351c8328dcefde14593978c8bfad1e0b40dbe7b | fadbd4e56bc0c5ee5f14aa8e483a7775a5026b82 | refs/heads/master | 2022-11-29T19:57:37.899112 | 2020-07-15T20:00:57 | 2020-07-15T20:00:57 | 278,888,823 | 1 | 0 | null | null | null | null | null | null | null | null | null | null | null | null | null | class State_witch:
def __init__(self):
self.life_potion = True
self.death_potion = True | UTF-8 | Python | false | false | 107 | py | 8 | state_witch.py | 7 | 0.588785 | 0.588785 | 0 | 4 | 26 | 32 |
ErikBjare/quantifiedme | 16,149,077,060,200 | e52f3736c23ea39aa935a2eed68264f1db64894a | 0a9abbab28fa1a082f93b8749b1ac4ab04f43809 | /src/quantifiedme/load/activitywatch_fake.py | ffb4169d785b8279fc08550a5672e3004f35fc82 | []
| no_license | https://github.com/ErikBjare/quantifiedme | 297a2e28d1a653f0edc751328c92db212013786a | 1a187f5cf0855bc2168cb000873718df4825d3c7 | refs/heads/master | 2023-05-28T08:34:40.007693 | 2023-05-23T17:51:18 | 2023-05-23T17:51:18 | 134,724,751 | 25 | 1 | null | false | 2023-03-23T10:08:07 | 2018-05-24T14:11:10 | 2023-03-07T15:32:40 | 2023-03-23T10:07:22 | 6,136 | 21 | 2 | 3 | Python | false | false | import random
from typing import Iterable
from datetime import datetime, timedelta
import numpy as np
from aw_core import Event
fakedata_weights = [
(100, None),
(2, {"title": "Uncategorized"}),
(5, {"title": "ActivityWatch"}),
(4, {"title": "Thankful"}),
(3, {"title": "QuantifiedMe"}),
(3, {"title": "FMAA01 - Analysis in One Variable"}),
(3, {"title": "EDAN95 - Applied Machine Learning"}),
(2, {"title": "Stack Overflow"}),
(2, {"title": "phone: Brilliant"}),
(2, {"url": "youtube.com", "title": "YouTube"}),
(1, {"url": "reddit.com"}),
(1, {"url": "facebook.com"}),
(1, {"title": "Plex"}),
(1, {"title": "Spotify"}),
(1, {"title": "Fallout 4"}),
]
# TODO: Merge/replace with aw-fakedata
def create_fake_events(start: datetime, end: datetime) -> Iterable[Event]:
assert start.tzinfo
assert end.tzinfo
# First set RNG seeds to make the notebook reproducible
random.seed(0)
np.random.seed(0)
# Ensures events don't start a few ms in the past
start += timedelta(seconds=1)
pareto_alpha = 0.5
pareto_mode = 5
time_passed = timedelta()
while start + time_passed < end:
duration = timedelta(seconds=np.random.pareto(pareto_alpha) * pareto_mode)
duration = min([timedelta(hours=1), duration])
timestamp = start + time_passed
time_passed += duration
if start + time_passed > end:
break
data = random.choices(
[d[1] for d in fakedata_weights], [d[0] for d in fakedata_weights]
)[0]
if data:
yield Event(timestamp=timestamp, duration=duration, data=data)
| UTF-8 | Python | false | false | 1,661 | py | 39 | activitywatch_fake.py | 27 | 0.596026 | 0.576761 | 0 | 54 | 29.759259 | 82 |
chukyjack/ace_it_dataconsole | 11,596,411,728,879 | 9f2fa505dd9ea48326a704499c7b1d1f461afbff | 5ebd67d6574f03b4481694f610e899672a9fff71 | /ace_it/schedule/migrations/0003_schedule_is_confirmed.py | 344a4f5f38fa95b061a023adaefe908187a0a300 | []
| no_license | https://github.com/chukyjack/ace_it_dataconsole | 1d1f12e0e04b8b2e9ce47736a44614f98a9aa0cd | 57605d9c47121d67a7a28e5b5cd46e88c656109a | refs/heads/ace_it_backend | 2022-12-13T00:53:17.052007 | 2020-10-20T06:15:40 | 2020-10-20T06:15:40 | 210,095,730 | 0 | 0 | null | false | 2022-12-08T01:24:03 | 2019-09-22T05:31:21 | 2020-10-20T06:16:55 | 2022-12-08T01:24:02 | 152,373 | 0 | 0 | 16 | SCSS | false | false | # Generated by Django 2.2 on 2020-01-20 04:41
from django.db import migrations, models
class Migration(migrations.Migration):
dependencies = [
('schedule', '0002_auto_20191009_0612'),
]
operations = [
migrations.AddField(
model_name='schedule',
name='is_confirmed',
field=models.BooleanField(default=False),
),
]
| UTF-8 | Python | false | false | 394 | py | 299 | 0003_schedule_is_confirmed.py | 206 | 0.596447 | 0.520305 | 0 | 18 | 20.888889 | 53 |
shibom/google_py_exercise | 9,216,999,837,143 | 1e0b777a4816e0701196b0a4740f298d493dd921 | 772c687c823f8a588d76fa2a55a2594be5755f64 | /alice_counter.py | 51ad64a7f48bfe197ef089610c2e5562e96305f9 | []
| no_license | https://github.com/shibom/google_py_exercise | 183cf5bdbc9c26bcdaa7e59c4d26367277911b3e | d312c7ee5519d946269c57e125801499e56ccf6c | refs/heads/master | 2021-01-01T05:14:44.354126 | 2015-07-24T00:36:15 | 2015-07-24T00:36:15 | 39,601,638 | 0 | 0 | null | null | null | null | null | null | null | null | null | null | null | null | null | #!/bin/env python
from collections import Counter
import pylab
from pylab import *
import matplotlib.pyplot as plt
infile = open("alice.txt", 'r')
all_lines = infile.readlines()
num_words = 0
word_count = Counter()
words = {}
for lines in all_lines:
lines = lines.split()
for word in lines:
word_count[word.lower()] += 1
for word, count in word_count.iteritems():
words.update({(word, count)})
#words = sorted(words, key=words.get)
for_hist = words.values()
fig = plt.figure()
ax = fig.add_subplot(111)
ax.hist(for_hist, 1000)
ax.set_xlim(0,400)
plt.show()
pylab.show()
infile.close()
| UTF-8 | Python | false | false | 616 | py | 13 | alice_counter.py | 12 | 0.673701 | 0.652597 | 0 | 29 | 20.241379 | 42 |
nurulsucisawaliah/python-project-chapter-6 | 644,245,096,293 | 1d3afef9f1bc082f45e57595ee36c154015fdef2 | 00522b2228ead8a634d9b2095c1e67f67f81d9ea | /statistik/bagian A.py | fb6f0b715a56fa66a9aad7123fb2992de2d0dd5a | []
| no_license | https://github.com/nurulsucisawaliah/python-project-chapter-6 | 94a2c4ef2deac599c050cb01359a07fa4c45aab3 | a830ae05ba0439e69838cf063ef807804597b50c | refs/heads/main | 2023-01-08T12:06:58.991579 | 2020-11-09T16:23:15 | 2020-11-09T16:23:15 | null | 0 | 0 | null | null | null | null | null | null | null | null | null | null | null | null | null | def sum(*n):
i=0
for x in n:
i=i+x
print(i)
| UTF-8 | Python | false | false | 69 | py | 8 | bagian A.py | 8 | 0.362319 | 0.347826 | 0 | 5 | 11.8 | 15 |
ioncann0ns/ad2dispatch | 5,360,119,232,026 | 8aa06bfd03d59d0695b495e9dad761bd0f383c04 | ee569d3f3d7629225e741d04774a54936b328474 | /pages/views.py | b48c2dedf4a8bd878f6f0bff47f5eebb8ef4072d | [
"Apache-2.0"
]
| permissive | https://github.com/ioncann0ns/ad2dispatch | b6e0bd52e1559620f4b13e9b1fe4b88dc8e7b4d2 | 0fcce967466c5abc00dc71480a92b31fabb06cf2 | refs/heads/master | 2016-08-10T21:11:55.281679 | 2016-04-19T02:34:26 | 2016-04-19T02:34:26 | 42,753,900 | 0 | 0 | null | null | null | null | null | null | null | null | null | null | null | null | null | import markdown
from django.http import Http404
from django.shortcuts import render
from .models import Page
def page(request, page_title=None, sub_page=None):
try:
# Get page data
if page_title is None:
selected_page = Page.objects.filter(parent_page=None).order_by('order').first()
selected_page.loc = 'page:' + selected_page.title
elif sub_page is not None:
selected_page = Page.objects.get(title=sub_page)
selected_page.loc = 'page:' + page_title + ':' + selected_page.title
else:
selected_page = Page.objects.get(title=page_title)
selected_page.loc = 'page:' + selected_page.title
# Parse Markdown if not Raw
if not selected_page.raw:
try:
selected_page.content = markdown.markdown(selected_page.content)
except AttributeError:
pass
# TODO: Needs DRY'd up
top_pages = Page.objects.filter(parent_page=None).order_by('order')
# Builds navigation list, and adds helpful attributes
for tpage in top_pages:
tpage.loc = 'page:' + tpage.title
if tpage.title != 'Home':
tpage.path = '/' + tpage.title
else:
tpage.path = '/'
# Needs DRY'd up end
if page_title is not None:
sub_pages = Page.objects.filter(parent_page=Page.objects.get(title=page_title)).order_by('order')
# Builds sub-nav list, and adds helpful attributes
for sub_page in sub_pages:
sub_page.loc = 'page:' + page_title + ':' + sub_page.title
sub_page.path = '/' + page_title + '/' + sub_page.title
else:
sub_pages = None
except Page.DoesNotExist:
raise Http404("Page does not exist.")
context = {
'page': selected_page,
'top_pages': top_pages, # TODO: DRY
'sub_pages': sub_pages,
'loc': selected_page.loc,
}
return render(request, 'pages/page.html', context)
| UTF-8 | Python | false | false | 2,069 | py | 17 | views.py | 12 | 0.570807 | 0.567907 | 0 | 56 | 35.946429 | 109 |
cuthai/ML_Assignment5 | 11,553,462,057,261 | 68be2345b17e93da7028da7a4b83af9d2dd083e9 | 4e852b51e571f1db6d12ebcda6cb22fdbd40749c | /neural_network/output_layer.py | 7cd00493b69367b9cd549d303e97bb5833534bef | []
| no_license | https://github.com/cuthai/ML_Assignment5 | 2afcd4a31e8d44cb5789f601ea9dd41d81362c95 | cf2ff6381524fbc3ec41cbf1b06cf839b388fb1a | refs/heads/master | 2023-01-10T23:58:29.425180 | 2020-11-15T03:49:27 | 2020-11-15T03:49:27 | 307,850,702 | 0 | 0 | null | null | null | null | null | null | null | null | null | null | null | null | null | import numpy as np
import math
class OutputLayer:
"""
Class OutputLayer
This class receives the inputs and perform classification using a softmax function. The max of the function is used
for prediction
"""
def __init__(self, dimensions, classes, class_names, input_count, step_size, convergence_threshold):
# Data Variables
self.dimensions = dimensions
self.classes = classes
self.class_names = class_names
# Layer Variables
self.input_count = input_count
# Tune Variables
self.step_size = step_size
self.convergence_threshold = convergence_threshold
# Initialize weights
self.weights = np.random.uniform(low=-.01, high=.01, size=(self.classes, self.input_count + 1))
def fit(self, data):
"""
Fit function
This function calculates entropy, updates weights, and backpropagation. The function used is a softmax
"""
# Assign X and Y
x = data[:-1].astype(float)
y = data[-1]
# Calculate softmax function
output = np.matmul(x[:, None].T, self.weights.T)
likelihood = (np.exp(output) / np.sum(np.exp(output), axis=1)[:, None])
# Initial delta variables, all set to 0
weights_delta = np.zeros((self.weights.shape[0], self.weights.shape[1]))
entropy = 0
# Initial backpropagation
backpropagation = np.zeros(self.input_count)
# For each class, we will calculate the changes to delta
for index in range(self.classes):
# Determine target
current_class = self.class_names[index]
if current_class == y:
actual = 1
else:
actual = 0
# Calculate the difference between softmax and target
difference = (actual - likelihood[:, index])
# Add up for backpropagation
for input_index in range(self.input_count):
backpropagation[input_index] += sum(difference * self.weights[index, input_index + 1])
# Update the deltas for this class
weights_delta[index, :] = x * difference
# Calculate entropy
entropy -= actual * math.log(likelihood[:, index])
print(entropy)
# Check for convergence
if entropy < self.convergence_threshold:
return True, 0
# If not converged, update weights and return backpropagation
else:
self.weights = self.weights + (self.step_size * weights_delta)
return False, backpropagation
def predict(self, data):
"""
Predict function
Return class based on the highest softmax class
"""
# Assign X
x = data[:-1].astype(float)
# Softmax function
output = np.matmul(x[:, None].T, self.weights.T)
likelihood = (np.exp(output) / np.sum(np.exp(output), axis=1)[:, None])
prediction_index = np.argmax(likelihood, axis=1).astype('O')[0]
# Retrieve prediction class name
prediction = self.class_names[prediction_index]
return prediction
| UTF-8 | Python | false | false | 3,178 | py | 37 | output_layer.py | 8 | 0.594399 | 0.588106 | 0 | 100 | 30.78 | 119 |
timpierce/superlists | 5,497,558,166,820 | b78d3f3153f7ffa9d1b3f4e948efc363fcd5a0c7 | 29e4a512fabcb9ae3782974c5dd792bd6877dfba | /deploy_tools/fabfile.py | 03213b938ad1ed2e8007048517545334f3fcdcb8 | []
| no_license | https://github.com/timpierce/superlists | fc0d5269e104a8623880869e1ef9b1fa42b97891 | 6b3dcacec7dc3fcabae818da4cdb45dce6741c4f | refs/heads/master | 2021-08-22T15:26:49.445216 | 2018-12-10T19:21:41 | 2018-12-10T19:21:41 | 160,975,881 | 0 | 0 | null | false | 2021-06-10T21:02:33 | 2018-12-08T20:26:55 | 2018-12-10T19:22:06 | 2021-06-10T21:02:32 | 27 | 0 | 0 | 2 | Python | false | false | import random
from fabric.contrib.files import append, exists
from fabric.api import cd, env, local, run
REPO_URL = 'https://github.com/timpierce/superlists.git '
def deploy():
pass | UTF-8 | Python | true | false | 188 | py | 5 | fabfile.py | 3 | 0.744681 | 0.744681 | 0 | 9 | 20 | 57 |
heitorlessa/serverless-encryption-workshop | 1,099,511,634,625 | 16a6c544bfb103f62bf3298edd8c122ec37ed079 | 15568b26730d7de7baaf8a3b025744ebd371f050 | /lab2/config_sample/dynamo/encryption_service.py | be61c95c88024f27a75ac1831972bb7d7b22e1f6 | [
"Apache-2.0"
]
| permissive | https://github.com/heitorlessa/serverless-encryption-workshop | ff119d909bdce6ba37cb0ab913cc018dde61c141 | b2a42034aef02dc27463a857eccec9307a50ee3f | refs/heads/master | 2021-01-19T07:06:58.708323 | 2016-10-12T13:00:10 | 2016-10-12T13:00:10 | 64,591,597 | 2 | 0 | null | null | null | null | null | null | null | null | null | null | null | null | null | #-------------------------------------------------------------------------
# Name: Encryption microservice for Lambda
# Purpose: Demonstrate use of KMS Encrypt endpoint, configuration handling via DynamoDB local
# Author: Heitor Lessa
#-------------------------------------------------------------------------
import boto3
import logging
import base64
import json
import botocore
from boto3.dynamodb.conditions import Key, Attr
# Basic Logging definition
logger = logging.getLogger()
logger.setLevel(logging.INFO)
kms = boto3.client('kms')
s3 = boto3.client('s3')
dynamodb = boto3.resource(
'dynamodb', region_name='eu-west-1', endpoint_url='http://localhost:8000')
class Crypter(object):
"""Crypter provides easy encryption through KMS Encrypt endpoint"""
def __init__(self, KMSkey):
self.key = KMSkey
# Leverage KMS Encrypt and base64-encode encrypted blob
# More info on Encrypt API:
# https://docs.aws.amazon.com/kms/latest/APIReference/API_Encrypt.html
def encrypt(self, message):
ret = kms.encrypt(KeyId=self.key, Plaintext=message)
encrypted_data = base64.encodestring(ret.get('CiphertextBlob'))
return encrypted_data
def get_config(context):
try:
table = dynamodb.Table(context.function_name)
response = table.query(
KeyConditionExpression=Key('stage').eq(
context.function_version.lower())
)
if not response['Count'] > 0:
raise Exception()
config = response['Items'][0]
except Exception, e:
raise Exception("Does {0} config exist?".format(
context.function_version.lower()))
return config
def lambda_handler(event, context):
# Basic input validation to avoid unnecessary KMS calls
# More info on KMS Costs: https://aws.amazon.com/kms/pricing/
try:
message = event["data"]
except:
error = {
"status": 400,
"error": "Invalid parameters - Please ensure required parameters are present"
}
raise Exception(json.dumps(error))
try:
logging.info("[+] Loading config from S3")
logging.info("[*] Function Version: " + context.function_version)
logging.info("[*] Function Name: " + context.function_name)
config = get_config(context)
except Exception as e:
error = {
"status": 500,
"error": "Error occurred while trying to obtain configuration - Message: {0}".format(e)
}
raise Exception(json.dumps(error))
crypter = Crypter(config['key'])
try:
encrypted_message = crypter.encrypt(message)
except botocore.exceptions.ClientError as e:
error = {
"status": 400,
"error": "Double check region and KMS Key ID - Message: {0}".format(e)
}
raise Exception(json.dumps(error))
except Exception as e:
error = {
"status": 500,
"error": "Error occurred while trying to encrypt data - Message: {0}".format(e)
}
raise Exception(json.dumps(error))
return {
'data': encrypted_message
}
| UTF-8 | Python | false | false | 3,177 | py | 25 | encryption_service.py | 9 | 0.595845 | 0.584199 | 0 | 108 | 28.416667 | 99 |
haitham88/currency_exchange_rate | 7,988,639,216,284 | 6b88bed62393d8d22bf05f84691c5cc06afc09be | cf584b351b02845a9b69cce6dc055339fc9a1d30 | /app/utils/response.py | 5c6c995e9b6555e65e485ad76bbf25cef41eee82 | []
| no_license | https://github.com/haitham88/currency_exchange_rate | 8bd810764c656e403938551eb9565345457be55a | 1fb1d318a5f909f95ad81f6993bf5a3517262a4d | refs/heads/master | 2023-01-29T19:37:21.756667 | 2020-12-11T12:07:40 | 2020-12-11T12:07:40 | 320,328,374 | 0 | 0 | null | null | null | null | null | null | null | null | null | null | null | null | null |
class Response(object):
status: bool
status_code: int
data: dict | UTF-8 | Python | false | false | 81 | py | 17 | response.py | 15 | 0.617284 | 0.617284 | 0 | 4 | 19 | 23 |
thanyachanok/-1 | 9,526,237,484,509 | 1ff4c32b64c544f1f5a1ce96da5cabde03d36caa | 30a9765fc0a1804e7809e51f4dd4c4055bc6e489 | /รองเท้า.py | 4fef9a16f35bcb9b941c8815285ced5585be545d | []
| no_license | https://github.com/thanyachanok/-1 | 6eddeb908833a904281422ca0f972750c3acbe1a | ae852d577880ddd8c4ffdef919e159947f8d2271 | refs/heads/master | 2022-09-01T13:45:24.447905 | 2020-05-27T14:53:53 | 2020-05-27T14:53:53 | 267,347,787 | 0 | 0 | null | null | null | null | null | null | null | null | null | null | null | null | null | a = []
x=0
while True :
print ('--------------\n ร้าน MiDream \n-------------- ')
print ('1)Nike ลด 20% [n]\n2)Adidas ลด 30% [a]\n3)converse ลด 50% [c]\n สิ้นสุดการเลือกรายการ [x]\n home [y]')
brand = input ('Please select brand : ')
brand = brand.lower()
while brand =='n' :
print ('\n>>>>>>>>>>>>>>Nike<<<<<<<<<<<<<<<\n1.Nike Epic React ราคา 4,500 [1]\n2.Nike Zoom fly ราคา 5,000 [2] \n3.Nike Zoom Pegasus ราคา 5,500 [3]\n4.Backhome [0]')
nike = (input ('Please select Nike : '))
nike = nike.lower()
if nike== '1':
n01 = ('Nike Epic React:4,500:900:3,600')
a.append(n01)
x+=3600
print ('\n-----------รายการได้ถูกเก็บไว้ในตะกร้าแล้ว----------------\n')
elif nike== '2':
n02 = ('Nike Zoom fly:5,000:1,000:4,000')
a.append(n02)
x+=4000
print ('\n-----------รายการได้ถูกเก็บไว้ในตะกร้าแล้ว----------------\n')
elif nike== '3' :
n03 = ('Nike Zoom Pegasus:5,500:1,100:4,400')
a.append(n03)
x+=4400
print ('\n-----------รายการได้ถูกเก็บไว้ในตะกร้าแล้ว----------------\n')
elif nike== '0':
break
while brand == 'a' :
print ('>>>>>>>>>>>>>>>Adidas<<<<<<<<<<<<<<<\n1)PUSHA T OZWEEGO ราคา 5,300 [1]\n2)ADDVANTAGE BASE ราคา 2,000 [2]\n3)NITE JOGGER ราคา 4,900 [3]\n4.Backhome [0]')
addie = (input ('Please select Adidas : '))
addie = addie.lower()
if addie == '1' :
a01 = ('PUSHA T OZWEEGO:5,300:1,590:3,710')
a.append(a01)
x+=3710
print ('\n-----------รายการได้ถูกเก็บไว้ในตะกร้าแล้ว----------------\n')
elif addie == '2' :
a02 = ('ADDVANTAGE BASE:2,000:600:1,400')
a.append(a02)
x+=1400
print ('\n-----------รายการได้ถูกเก็บไว้ในตะกร้าแล้ว----------------\n')
elif addie == '3' :
a03 = ('NITE JOGGER:4,900:1,470:3,430')
a.append(a03)
x+=3430
print ('\n-----------รายการได้ถูกเก็บไว้ในตะกร้าแล้ว----------------\n')
elif addie== '0':
break
while brand == 'c':
print('>>>>>>>>>>Converse<<<<<<<<<<<<<<<\n1)converse jack purcell ราคา 2,000 [1]\n2)converse all star ราคา 5,000 [2]\n3)converse chuck taylor ราคา 4,000 [3]\n4.Backhome [0]')
converse = (input ('Please select converse : '))
converse = converse.lower()
if converse =='1' :
c01=('converse jack purcell:2,000:1,000:1,000')
a.append(c01)
x+=1000
print ('\n-----------รายการได้ถูกเก็บไว้ในตะกร้าแล้ว----------------\n')
elif converse == '2' :
c02 = ('converse all star:5,000:2,500:2,500')
a.append(c02)
x+=2500
print ('\n-----------รายการได้ถูกเก็บไว้ในตะกร้าแล้ว----------------\n')
elif converse == '3' :
c03 = ('converse chuck taylor:4,000:2,000:2,000')
a.append(c03)
x+=2000
print ('\n-----------รายการได้ถูกเก็บไว้ในตะกร้าแล้ว----------------\n')
elif converse == '0':
break
if brand == 'x' :
print (' สินค้าและจำนวนเงินที่ต้องจ่าย')
print ('{0:_<120}'.format(""))
print ('{0:' '<35}{1:' '<35}{2:' '<35}{3:' '<35}'.format('รุ่น','ราคา','ส่วนลด','จ่ายจริง'))
print ('{0:_<120}'.format(""))
count = 0
for d in a :
e = d.split(':')
count +=1
print(count,end=")")
print('{0[0]:<32}{0[1]:<35}{0[2]:<36}{0[3]:<36}'.format(e))
print ('{0:_<120}'.format(""))
print('รวมเป็นเงิน %d'%x)
print ('{0:_<120}'.format(""))
a.clear()
x=0
if brand=='y':
print('a')
| UTF-8 | Python | false | false | 4,879 | py | 1 | รองเท้า.py | 1 | 0.40955 | 0.33399 | 0 | 89 | 43.606742 | 182 |
enda1111/deep-learning | 14,370,960,613,213 | f6731c128edfa58506e4ef8ea2ab85343323e6c9 | 71791e19d6f420324b2426369f7ca008ee5ddac8 | /nn/__init__.py | 66a1182454fec1a55b557f1bf10d52c37a7e24d0 | []
| no_license | https://github.com/enda1111/deep-learning | ebba94b2942586baa0d79666d389bc0b24d9619b | 778cbdec7815d1617df4adcf47c57705da71b65e | refs/heads/master | 2021-01-24T10:37:22.860780 | 2016-10-10T14:39:02 | 2016-10-10T14:39:02 | 70,310,141 | 0 | 0 | null | null | null | null | null | null | null | null | null | null | null | null | null | from . import trainer
Trainer = trainer.Trainer
| UTF-8 | Python | false | false | 49 | py | 7 | __init__.py | 7 | 0.77551 | 0.77551 | 0 | 3 | 15.333333 | 25 |
tonymontaro/Algorithmic-Problem-Solving | 8,057,358,658,229 | a0af33944a8a604bdbeccb6052c6933f126db792 | 187b62e1b808fa92b04912c211301a5695a2d1fe | /Hackerrank/algorithms - practice/sorting/07-quicksort-1-partition.py | 51153b2ce1a5871493dfb6e6e404d97e18893057 | []
| no_license | https://github.com/tonymontaro/Algorithmic-Problem-Solving | fda498ee841a88e9e43ad624136e86b4e101e587 | 290e4c3af79ff5477b31a314a08eb24f3690890b | refs/heads/master | 2021-06-07T04:49:22.786439 | 2020-11-24T10:49:00 | 2020-11-24T10:49:00 | 122,983,998 | 0 | 1 | null | null | null | null | null | null | null | null | null | null | null | null | null | n, l, left, right = input(), [i for i in input().strip().split()], [], []
el, equal = int(l[0]), [l[0]]
for i in range(1, len(l)):
if int(l[i]) == el:
equal.append(l[i])
elif int(l[i]) > el:
right.append(l[i])
else:
left.append(l[i])
print(' '.join(left + equal + right))
| UTF-8 | Python | false | false | 310 | py | 188 | 07-quicksort-1-partition.py | 95 | 0.493548 | 0.483871 | 0 | 12 | 24.833333 | 73 |
MeanTuple/hello_world | 10,136,122,845,392 | 179f0d18f71fd5e29711fb773f29c27ce3728260 | d33c1f5c659129c7708540bd62c6ae00937d5c78 | /hw.py | 4657b4ed1a0e3dd8e8fadd037870e2e5ffeea8d7 | []
| no_license | https://github.com/MeanTuple/hello_world | 22edb9c251eeed5048d35541c5015eade80d5281 | e3931147fc0d652fa9d430c2f1bd5b0c7c115b51 | refs/heads/master | 2021-04-06T00:16:29.037815 | 2018-04-22T05:14:38 | 2018-04-22T05:14:38 | null | 0 | 0 | null | null | null | null | null | null | null | null | null | null | null | null | null | print "Hello,world!" #python 2.7
print("Hello,world!") #python 3.6
| UTF-8 | Python | false | false | 67 | py | 1 | hw.py | 1 | 0.686567 | 0.626866 | 0 | 2 | 32.5 | 33 |
meloun/ew_aplikace | 4,148,938,431,066 | 97cb8f4f4d22a56486a7e49144a377ac7929bc52 | dc99adb79f15b3889a7ef6139cfe5dfc614889b8 | /Aplikace_1_0/Source/libs/test/odr.py | eeb3f66e23f8eea260b1110f6560e6d92ac5a345 | []
| no_license | https://github.com/meloun/ew_aplikace | 95d1e4063a149a10bb3a96f372691b5110c26b7b | f890c020ad8d3d224f796dab3f1f222c1f6ba0eb | refs/heads/master | 2023-04-28T06:43:12.252105 | 2023-04-18T19:59:36 | 2023-04-18T19:59:36 | 2,674,595 | 0 | 2 | null | null | null | null | null | null | null | null | null | null | null | null | null | '''
Created on 2.12.2013
@author: Meloun
'''
mystr = "0100"
print mystr
print hex(int(mystr)) | UTF-8 | Python | false | false | 101 | py | 160 | odr.py | 113 | 0.623762 | 0.514851 | 0 | 8 | 10.875 | 21 |
acaciawater/gw4e | 2,422,361,569,435 | a762227eec2107a4142f4dfe369ec99d58d3d5b4 | 473734eb1f5efc4261856a93bed3aab78d2ca28e | /maps/migrations/0034_documentgroup_open.py | 93df419cc865149e29e6e831ad2c3cc96063b422 | []
| no_license | https://github.com/acaciawater/gw4e | 922e35b40d502a6eec7bfac4fefd8836518bb8ea | 2ea0cce334b87df69aa7aa2651fc7e8f43295b07 | refs/heads/master | 2021-06-21T04:03:23.685705 | 2021-01-04T14:08:56 | 2021-01-04T14:08:56 | 163,511,033 | 0 | 0 | null | null | null | null | null | null | null | null | null | null | null | null | null | # Generated by Django 2.2.12 on 2020-04-15 19:22
from django.db import migrations, models
class Migration(migrations.Migration):
dependencies = [
('maps', '0033_delete_userconfig'),
]
operations = [
migrations.AddField(
model_name='documentgroup',
name='open',
field=models.BooleanField(default=False),
),
]
| UTF-8 | Python | false | false | 389 | py | 99 | 0034_documentgroup_open.py | 76 | 0.59383 | 0.542416 | 0 | 18 | 20.611111 | 53 |
AnthonyMChong/leetcodepractice | 7,859,790,156,317 | c49a1ca25716fdbc1ec20e8c1e160e1141adda98 | bcf93f61800fb0152603326da81b161f01d440dd | /monotonic-array/monotonic-array.py | 82d64bb5cd8e95feec3d1ec187b74fcda676b697 | []
| no_license | https://github.com/AnthonyMChong/leetcodepractice | ae313ffdf169340a41968ca511e3d7abf35fdefc | 0094d2a8241a5c52d38b96a6d79965ca7ca727af | refs/heads/master | 2020-04-26T02:43:05.485726 | 2019-08-22T01:56:28 | 2019-08-22T01:56:28 | 173,243,018 | 0 | 0 | null | null | null | null | null | null | null | null | null | null | null | null | null | def ismonotonic ( inlist ): # will use mode flag to check 0 monotone -1 if dec , 1 if inc
monoflag = 0
preVal = None
for checklist in inlist:
if preVal == None:
preVal = checklist
elif (checklist > preVal) :
if (monoflag < 0):
return False
monoflag = 1
elif (checklist < preVal) :
if (monoflag > 0):
return False
monoflag = -1
preVal = checklist
return True
mylist = [ 1, 1, 2, 2, 5, 6, 6, 7, 11 , 1]
mylist = mylist[::-1]
print mylist
print ismonotonic(mylist) | UTF-8 | Python | false | false | 603 | py | 35 | monotonic-array.py | 30 | 0.525705 | 0.492537 | 0 | 22 | 26.454545 | 89 |
Lee-Geon-Yeong/SW_Expert_Academy | 3,109,556,343,725 | c9253556655275cb7d8c144b2d434a6866f6d4aa | fc3096160a9df7c3c9a11f1eb9e51fd3790e5890 | /D1/6240_repeatation.py | 9eaa4733c4b0ec3b30e84e2c76e56bd75ffe463a | []
| no_license | https://github.com/Lee-Geon-Yeong/SW_Expert_Academy | dc14d11be5adf8a86c5107214b07acc49e089561 | 2a3cb6a2f10de92a93f44e93bc806e618a5b79c4 | refs/heads/master | 2023-06-30T11:12:00.333653 | 2021-08-09T14:23:42 | 2021-08-09T14:23:42 | 325,823,891 | 0 | 0 | null | null | null | null | null | null | null | null | null | null | null | null | null | arr = 0
for i in range(1,101) :
if i % 3 == 0 :
arr += i
print("1부터 100사이의 숫자 중 3의 배수의 총합: %d" % arr)
| UTF-8 | Python | false | false | 142 | py | 52 | 6240_repeatation.py | 51 | 0.491228 | 0.385965 | 0 | 5 | 21.8 | 44 |
hanbinchoi/Python_practice | 8,864,812,509,827 | 67119415c1e11f86067ef53cc585927eb1802b1a | 32489d1fc435558b0fb9245a7ec8f1d55ef28643 | /entry.py | 7c2991df81f66b67242de1b251a0cfc7fdff6a1c | []
| no_license | https://github.com/hanbinchoi/Python_practice | d51232bb2916c43030a90403d9ccbd69152681e1 | 7615be210117859565fb61589c5d3ea9e883ee11 | refs/heads/master | 2020-05-30T04:15:25.500650 | 2020-03-30T10:13:31 | 2020-03-30T10:13:31 | 189,532,442 | 0 | 0 | null | null | null | null | null | null | null | null | null | null | null | null | null | from tkinter import *
win=Tk()
def click():
print(entry.get())
entry=Entry(win,show='*')
entry.pack(fill=X)
btn=Button(win,text='view',command=click)
btn.pack(fill=X)
win.mainloop()
| UTF-8 | Python | false | false | 190 | py | 76 | entry.py | 75 | 0.678947 | 0.678947 | 0 | 13 | 13.615385 | 41 |
noilpa/3DMID-URX | 15,582,141,350,128 | 31f3d9fc65082a56c4cef3f47a42ae23335dc976 | cfe2e076420bd9e2622c7770ce0ccd727a018c72 | /3dMid.py | bb3a6ffd9ad39241f902e34e1539285fc8a974aa | []
| no_license | https://github.com/noilpa/3DMID-URX | 0c1e6891d994c8f76bfcf7a140892d21bc8f4df2 | 5f70a478d87f0452fb5fea30b82841e485c1c30b | refs/heads/master | 2021-04-26T22:11:13.626019 | 2018-05-28T13:07:37 | 2018-05-28T13:07:37 | 124,035,207 | 0 | 0 | null | null | null | null | null | null | null | null | null | null | null | null | null | import reader as rd
import math
import urx
import math3d as m3d
from math3d import Vector
from math3d import Orientation
import time
from utils import *
# -----------=====TRASH=====-----------
# def initialize_robot(rob, file_path):
#
# tcp = (0, 0, 0.066, 0, 0, 0)
# rob.set_tcp(tcp)
# # my_csys = rob.new_csys_from_xpy()
# # print(my_csys)
#
# # my_csys = m3d.Transform(
# # 7.21748314e-01, -6.92100474e-01, -8.73532598e-03,
# # 6.92132446e-01, 7.21769916e-01, 9.30157231e-04,
# # 5.66113324e-03, -6.71734195e-03, 9.99961414e-01,
# # -0.50301, -0.27713, -0.21144
# # )
# # rob.set_csys(my_csys)
# obj_list = rd.read_file(file_path)
# pose_processing(rob, obj_list)
#
# | 3-axis
# ________ ___v__
# / 1 /| 1-axis x| cube | <---- 2-axis
# /________ / | ___|______|___
# | | | | |
# | 2 | 3| | table |
# | | / | |
# |________|/
#
# ___#___
# значение индикатора в нулевом положении / \
# | 000 |
# \_______/
# #
# #
# #
# ____Y____
#
#
#
# Z Z
# ^ ^
# | |
# | |
# |______ X |________ Y
# \ | \ ^
# \ V \ |
# \ Y \ X /
#
# LEFT(clock) RIGHT(counter clock)
'''
| get_three_points_from_robot -> 3 points
| get_plane_from_three_points -> plane
| stand_perpendicular
| check_cross_direction
| origin = intersection_of_three_planes
shift_point(origin, cube_edge)
| new_csys = new_from_xyp(x_vec, y_vec, origin)
|
| 3dMid - work
|
V
'''
class Controller:
ROBOT = None
TOOL_AXIS = None
AXIS_DIRECTION = None
COM_PORT = None
INDICATOR_ORIGIN = None
MODEL_HEIGHT = None
FILE = None
def __init__(self, robot, com_port, indicator, tcp, points_filepath, axis='x'):
"""
==========FIRST OF ALL USE IT==========
@robot - Robot object or ip to robot
@axis - indicator direction, one of string values: x, y, -x, -y
@com_port - Serial object or com number
@indicator - default indicator value
"""
if isinstance(robot, urx.Robot):
self.ROBOT = robot
else:
self.ROBOT = urx.Robot(robot)
if isinstance(com_port, serial.Serial):
self.COM_PORT = com_port
elif com_port is None:
pass
else:
self.COM_PORT = serial.Serial(com_port,
baudrate=9600,
bytesize=serial.EIGHTBITS,
stopbits=serial.STOPBITS_ONE,
parity=serial.PARITY_NONE)
self.FILE = rd.read_file(points_filepath)
if axis.startswith('-'):
self.AXIS_DIRECTION = -1
self.TOOL_AXIS = axis[1:]
else:
self.AXIS_DIRECTION = 1
self.TOOL_AXIS = axis
self.ROBOT.set_tcp(tcp)
# default indicator value
self.INDICATOR_ORIGIN = indicator
def __get_three_points_from_robot(self):
input('Set first point on plane and press Enter')
p1 = self.__correct_point()
input('Set second point on plane and press Enter')
p2 = self.__correct_point()
input('Set third point on plane and press Enter')
p3 = self.__correct_point()
return [p1, p2, p3]
def __get_indicator_data(self):
if self.COM_PORT.is_open:
try:
self.COM_PORT.write(b'1\r\n')
time.sleep(0.2)
indicator = self.COM_PORT.read_all().decode('utf-8')[3:]
print(indicator)
data = float(indicator)
return data
except Exception as e:
print(e)
return None
else:
raise Exception('Serial port is unreachable')
def __stand_perpendicular(self, plane):
# TODO: rework this method without moving robot
# point = self.ROBOT.getl()
vector = Vector(plane[:3])
self.set_tool_orientation(orient_from_vector(vector))
# pose = point[:3] + rx_ry_rz_from_vector(vector)
# self.ROBOT.movel(pose, vel=0.1)
def __check_cross_direction(self, vector: Vector):
# TODO: dot product of tool vector and plane vector must be > 0 => codirected
v = vector.normalized
self.__stand_perpendicular(vector)
# tool = self.ROBOT.get_orientation()
if np.dot(v, tool) < 0:
return inverse_vector(v)
else:
return v
def __correct_point(self):
epsilon = 0.00005
pose = [0, 0, 0]
ind_data = self.__get_indicator_data() / 1000
delta = self.INDICATOR_ORIGIN - ind_data
if abs(delta) > epsilon:
pose[axis_to_number_dict[self.TOOL_AXIS]] = self.AXIS_DIRECTION * delta
self.ROBOT.translate_tool(pose)
point = self.ROBOT.getl()[:3]
return point
def __move_to_start(self, pose_to, radius):
pose_from = self.ROBOT.getl()
x_via = (pose_from[0] + pose_to[0]) / 2
y_via = (pose_from[1] + pose_to[1]) / 2
a = radius ** 2 - x_via ** 2 - y_via ** 2
if a > 0:
z_via = math.sqrt(a)
else:
z_via = -math.sqrt(-a)
pose_via = (x_via, y_via, z_via, pose_to[3], pose_to[4], pose_to[5])
# self.ROBOT.movec(pose_via, pose_to)
self.ROBOT.movep(pose_to, vel=2)
def __new_csys_from_planes(self):
"""
first plane define Z axis
second plane define X axis
third plane define Y axis
Z directed outside plane
X and Y axis directed inside plane
"""
planes = []
for i in range(3):
p1, p2, p3 = self.__get_three_points_from_robot()
planes.append(get_plane_from_three_points(p1, p2, p3))
self.__check_cross_direction(planes[i])
orig = intersection_of_three_planes(planes[0], planes[1], planes[2])
orig[2] -= self.MODEL_HEIGHT
vec_x = m3d.Vector(planes[1][:3])
vec_y = m3d.Vector(planes[2][:3])
csys = m3d.Transform.new_from_xyp(vec_x, vec_y, orig)
self.ROBOT.set_csys(csys)
def pose_processing(self):
vectors = self.FILE.copy()
del vectors['sphere']
sphere = self.FILE['sphere']
start_pose = (0, 0, (float(sphere['radius']) + float(sphere['center'][2])), math.pi, 0, 0)
try:
self.ROBOT.movel(start_pose, vel=2)
except urx.RobotException:
pass
input('Press any key to start...')
for key in vectors:
x1, y1, z1 = [float(i) for i in vectors[key]['start']]
x2, y2, z2 = [float(i) for i in vectors[key]['stop']]
vx, vy, vz = [float(i) for i in vectors[key]['direction']]
vec_z = m3d.Vector(vx, vy, vz)
orient = orient_from_vector(-vec_z)
pose_1 = (x1, y1, z1, orient.rotation_vector[0], orient.rotation_vector[1], orient.rotation_vector[2])
pose_2 = (x2, y2, z2, orient.rotation_vector[0], orient.rotation_vector[1], orient.rotation_vector[2])
try:
self.__move_to_start(pose_2, sphere['radius'])
except urx.RobotException:
pass
# move to stop
try:
self.ROBOT.movel(pose_1, vel=2)
except urx.RobotException:
pass
# do_something_useful()
time.sleep(1)
# move back to start
try:
self.ROBOT.movel(pose_2, vel=2)
except urx.RobotException:
pass
self.ROBOT.movel(start_pose, vel=2)
def new_rob_csys(self, mode):
modes = {
'points': self.ROBOT.new_csys_from_xpy,
'planes': self.__new_csys_from_planes
}
if mode not in modes.keys():
raise NameError('wrong mode')
else:
modes[mode]()
def set_tool_orientation(self, vector: Vector):
self.ROBOT.set_orientation(orient_from_vector(vector))
def init_stage(c: Controller, points=[]):
"""
Prepare for pose_processing()
:param c:
:param points: [ [[p1], [p2], [p3]], [[p1], [p2], [p3]], [[p1], [p2], [p3]] ]
:return: new csys
"""
if len(points) == 0:
for i in range(3):
points.append(c.__get_three_points_from_robot())
planes = []
for i, p in enumerate(points):
planes.append(get_plane_from_three_points(p[0], p[1], p[2]))
print(planes)
if __name__ == '__main__':
# rob = urx.Robot('192.168.0.105')
rob = urx.Robot('192.168.88.21')
# edge = 112.71
y = 50 / 1000
x = 0
z = 34.3 / 1000
com = None # 'COM3'
co = Controller(robot=rob,
com_port=com,
indicator=0,
tcp=[x, y, z, 0, 0, 0],
points_filepath='./points.txt',
axis='z')
# co.ROBOT.new_csys_from_xpy()
px = m3d.Vector([-0.43486041640101686, -0.13881540123664282, -0.21053820546042168])
p0 = m3d.Vector([-0.5198672251276444, -0.21984341325034076, -0.2118583353420153])
py = m3d.Vector([-0.5981675648960634, -0.13921634276409914, -0.21199963026601087])
new_csys = m3d.Transform.new_from_xyp(px - p0, py - p0, p0)
co.ROBOT.set_csys(new_csys)
co.pose_processing()
| UTF-8 | Python | false | false | 10,273 | py | 6 | 3dMid.py | 4 | 0.478121 | 0.432116 | 0 | 320 | 30.990625 | 114 |
leandrosilvaf/sisemp | 1,159,641,188,195 | c9d41713f0035e8e605aa02b35fab93c0ac9d084 | ff2832113399d5fddbb2b52afd9cd9c9c665059f | /sisemp/emprestimo/models.py | c20950405b4e95be0b8630d59cf747f661811835 | []
| no_license | https://github.com/leandrosilvaf/sisemp | ed015d2e396c4326aa3f4488e8692a0229b14e55 | f5097d410ad274f6945d406a531d1ea150d120a2 | refs/heads/master | 2020-05-20T08:22:02.811398 | 2019-05-09T22:58:38 | 2019-05-09T22:58:38 | 184,151,221 | 0 | 0 | null | null | null | null | null | null | null | null | null | null | null | null | null | # -*- coding: utf-8 -*-
#
# Copyright (c) 2010 Wille Marcel Lima Malheiro and contributors
#
# This file is part of VaiVem.
#
# VaiVem is free software under terms of the GNU Affero General Public
# License version 3 (AGPLv3) as published by the Free
# Software Foundation. See the file README for copying conditions.
#
import datetime
from django.db import models
from django.contrib.auth.models import User
class Usuario(models.Model):
class Meta:
ordering = ('nome',)
CATEGORIAS_CAHL = (
('Estudante',(
('agrimensura', 'Engenharia de Agrimensura e Cartográfica'),
('transporte', 'Tecnologia em Transporte Terrestre'),
('civil', 'Engenharia Civil'),
('ambiental', 'Engenharia Ambiental'),
('geografia', 'Geografia'),
('interdisciplinar', 'Bacharelado Interdisciplinar'),
)
),
('professor', 'Professor'),
('tecnico', 'Técnico Administrativo'),
)
nome = models.CharField(max_length=100)
matricula = models.IntegerField(max_length=9, primary_key=True)
categoria = models.CharField(max_length=50, choices=CATEGORIAS_CAHL)
email = models.EmailField(max_length=75)
telefone = models.CharField(max_length=15)
endereco = models.TextField('Endereço', max_length=200)
suspensao = models.DateField('Suspenso até', default=datetime.date(2010, 9, 7), null=True)
disponivel = models.BooleanField(default=True)
observacoes = models.TextField('Observações', max_length=300, blank=True)
atualizacao_cadastral = models.DateField('Última atualização de cadastro', auto_now_add=True)
def __unicode__(self):
return self.nome
class Equipamento(models.Model):
class Meta:
ordering = ('nome','tombo',)
CATEG_EQUIPOS = (
('topografico', 'Topográfico'),
('audio', 'Áudio'),
('video', 'Vídeo'),
('foto', 'Fotografia'),
('info', 'Informática'),
('museu', 'Museologia')
)
tombo = models.IntegerField(max_length=10, primary_key=True)
nome = models.CharField(max_length=200)
numeroserie = models.CharField('Número de Série', max_length=30, null=True)
categoria = models.CharField(max_length=50, choices=CATEG_EQUIPOS)
disponivel = models.BooleanField(default=True)
observacoes = models.TextField('Observações', max_length=300, blank=True)
ultimo_inventario = models.DateField('Data do último inventário', null=True)
def __unicode__(self):
return u'%s - %s' % (self.tombo, self.nome)
class Emprestimo(models.Model):
id = models.AutoField(primary_key=True)
itens = models.ManyToManyField('Equipamento', limit_choices_to = {'disponivel':True})
usuario = models.ForeignKey('Usuario', limit_choices_to = {'suspensao__lte':datetime.date.today(), 'atualizacao_cadastral__gte':datetime.date(2019,7,20)})
data_emprestimo = models.DateTimeField('Data de Empréstimo', auto_now_add=True)
prazo_devolucao = models.DateTimeField('Prazo para Devolução', null=True)
data_devolucao = models.DateTimeField('Data de Devolução', null=True)
devolvido = models.BooleanField(default=False)
funcionario_emprestimo = models.ForeignKey(User, related_name="%(class)s_emprestimo", null=True)
funcionario_devolucao = models.ForeignKey(User, related_name="%(class)s_devolucao", null=True)
def __unicode__(self):
return str(self.id)
| UTF-8 | Python | false | false | 3,456 | py | 15 | models.py | 5 | 0.672786 | 0.6588 | 0 | 86 | 38.906977 | 158 |
simran137/Pharmacy_Management_System | 9,251,359,564,373 | c3742a64c37de1f2c077e8b7574375cd7f257f58 | ee2b94e52f5e06aafcf152a4d5a79db8cc5a2c81 | /pharmacy/items/migrations/0014_auto_20190507_0614.py | d903d95cefd7a9e9defb8f415788c8ed522b3722 | []
| no_license | https://github.com/simran137/Pharmacy_Management_System | 4c0938db641ada4617762f88fc34e444e5c50838 | 404f5bba4562479420ae9d089fbfc6e8563e503e | refs/heads/master | 2020-06-22T01:45:53.831050 | 2019-07-18T14:21:39 | 2019-07-18T14:21:39 | 197,603,033 | 0 | 0 | null | null | null | null | null | null | null | null | null | null | null | null | null | # Generated by Django 2.2.1 on 2019-05-07 06:14
from django.db import migrations, models
class Migration(migrations.Migration):
dependencies = [
('items', '0013_remove_item_concentration'),
]
operations = [
migrations.AlterField(
model_name='item',
name='type',
field=models.CharField(choices=[('tablet', 'tablet'), ('capsule', 'capsule'), ('injection', 'injection'), ('pouch', 'pouch'), ('bottle', 'bottle'), ('cream', 'cream'), ('gel', 'gel'), ('other', 'other')], max_length=15),
),
]
| UTF-8 | Python | false | false | 569 | py | 31 | 0014_auto_20190507_0614.py | 31 | 0.572935 | 0.536028 | 0 | 18 | 30.611111 | 232 |
lnsongxf/PythonExamples | 5,016,521,802,719 | 94161a7c4d4b8b2b3ac6d221af8f58ca3280d1f9 | b2c6f3bddd8f8a3e820b5db19b6a77efdeaec548 | /Code/Miscellaneous/DictOfDataFrames.py | dab096f69015fda766ac406be8b7abd2560b4101 | [
"Apache-2.0"
]
| permissive | https://github.com/lnsongxf/PythonExamples | 99883936547803ab0eb8a19fb407840f43d3f1e7 | a20a866f0f1dcf6ca429e5114baac1e40cf1da42 | refs/heads/master | 2020-04-08T00:39:10.191362 | 2015-07-19T13:58:00 | 2015-07-19T13:58:00 | null | 0 | 0 | null | null | null | null | null | null | null | null | null | null | null | null | null | # ==============================================================================
# purpose: create a dict of Python DataFrames from a DataFrame
# author: tirthankar chakravarty
# created: 13/5/15
# revised:
# comments:
#==============================================================================
import pandas as pd
import numpy.random as npr
dfM = pd.DataFrame({
"group_var": npr.random_integers(low = 0, high = 10, size = 100),
"data_var": npr.normal(size = 100)
})
dfMG = dict(list(dfM.groupby('group_var')))
| UTF-8 | Python | false | false | 530 | py | 47 | DictOfDataFrames.py | 32 | 0.473585 | 0.44717 | 0 | 18 | 28.333333 | 80 |
jedsada-io/100-days-of-code-tracker | 10,136,122,820,440 | 1727791468a244f79b6242494156f9d35c11f78e | 0d19a212dffb471ca3cf9feb6110958332fb236f | /Python-t/Jedsada12thOct/TkinterTemplate.py | 699898d759ba686192e787dd62a8b1eeacef06a6 | []
| no_license | https://github.com/jedsada-io/100-days-of-code-tracker | 1c1b24845817e7ed53c1b4c90797d2887e98a4a4 | 3da399bef3670a9f9816e27ad0485ec4291e9aca | refs/heads/main | 2023-04-14T04:53:22.152051 | 2021-11-21T20:02:56 | 2021-11-21T20:02:56 | 331,627,166 | 1 | 0 | null | null | null | null | null | null | null | null | null | null | null | null | null | import tkinter as tk
class Application(tk.Frame):
def __init__(self, master):
"""Inheriting from Tkinter"""
super(Application, self).__init__(master)
self.grid() # Calling the grid method from Tkinter
#### Customise!!!
self.create_widgets() # Calling a method
def create_widgets(self):
'''Method to create all content on the screen'''
### First Name Area
self.firstname_lbl = tk.Label(self, text='first name: ', font='arial12')
self.firstname_lbl.grid(row=0, column=0, pady=10)
self.first_entry_field = tk.Entry(self)
self.first_entry_field.grid(row = 0, column = 1, pady=10)
### Last Name Area
self.lastname_lbl = tk.Label(self, text='last name: ', font='arial12')
self.lastname_lbl.grid(row=1, column=0, pady=10)
self.last_entry_field = tk.Entry(self)
self.last_entry_field.grid(row = 1, column = 1, pady=10)
self.combine_bttn = tk.Button(self, text = "Combine", command=self.combine)
self.combine_bttn.grid(row = 2, column = 0)
self.delete_bttn = tk.Button(self, text = "Delete", command=self.delete)
self.delete_bttn.grid(row = 2, column = 1)
self.text_box = tk.Text(self, width = 25, height = 3, wrap = tk.WORD)
self.text_box.grid(row = 3, column = 0, columnspan=4, pady=20)
def combine(self):
first_text = self.first_entry_field.get()
second_text = self.last_entry_field.get()
if len(first_text) > 1 and len(second_text) > 1:
full_name = 'Hello, ' + first_text + ' '+ second_text
self.text_box.delete(0.0, tk.END)
self.text_box.insert(0.0, full_name)
def delete(self):
self.text_box.delete(0.0, tk.END)
root = tk.Tk()
root.title("My App")
root.geometry("400x400")
root = Application(root)
root.mainloop() # Keeps the window running
| UTF-8 | Python | false | false | 1,807 | py | 83 | TkinterTemplate.py | 64 | 0.639889 | 0.614404 | 0 | 59 | 29.59322 | 79 |
LiuSilva/studying_python | 6,777,458,396,075 | cdcefaa8278ab704b988d3970ba47c4e2e5a4352 | 98986e8ffd03fe9ea6064396349870c5496f6c7e | /30_days_of_python/templates.py | 7015da2ccbb585b4b2188837304c5a1e29595d90 | []
| no_license | https://github.com/LiuSilva/studying_python | 097e045d0b118289a863752f8b1223ec57067283 | bab97f8f511fb6681a6a1fc4a32ad78055366740 | refs/heads/master | 2021-01-01T05:58:33.683207 | 2018-06-08T23:04:31 | 2018-06-08T23:04:31 | 97,322,964 | 0 | 0 | null | null | null | null | null | null | null | null | null | null | null | null | null | import os
def get_template_path(path):
file_path = os.path.join(os.getcwd(), path)
if not os.path.isfile(file_path):
raise Exception("Arquivo não existe.\n %s" % (file_path))
return file_path
def get_template(path):
file_path = get_template_path(path)
return open(file_path).read()
def render_context(template_string, context):
## os ** faz com que o format receba um dicionario
## e coloque os atributos nos lugares que estao
## marcados na string.. como uma substituicao
return template_string.format(**context)
file_ = 'templates/email_message.txt'
file_html = 'templates/email_message.html'
template = get_template(file_)
template_html = get_template(file_html)
context = {
'name': 'Python',
'date': 'November 9th, 2017',
'total': '0,00'
}
print(render_context(template, context))
print(render_context(template_html, context)) | UTF-8 | Python | false | false | 852 | py | 276 | templates.py | 270 | 0.720329 | 0.710928 | 0 | 31 | 26.483871 | 59 |
MaxYandexLyceum/kapuchino | 16,501,264,357,809 | 52bf5f5605ac1bcba79f42117289aa5a77f39f75 | 0df0c0537a372e16e2bfbd984ef50654cb977f71 | /espresso-master/main.py | 9b25bae21e4ede9b3089844a82549fc28462c9ae | []
| no_license | https://github.com/MaxYandexLyceum/kapuchino | 2b81ce421b9565642e8ba59873acb0320ee5eed9 | fad29cd9f4dc6399c68c317632cfe7a20fa67f33 | refs/heads/master | 2023-03-09T20:23:43.999572 | 2021-02-21T20:11:45 | 2021-02-21T20:11:45 | 340,994,453 | 0 | 0 | null | null | null | null | null | null | null | null | null | null | null | null | null | from PyQt5.QtWidgets import QApplication, QWidget, QPushButton, QVBoxLayout
import sqlite3
import sys
import PyQt5
from PyQt5 import uic
from PyQt5.QtGui import QStandardItemModel
from PyQt5.QtWidgets import QApplication, QMessageBox, QPushButton, QInputDialog, QWidget, QVBoxLayout, QLabel, \
QLineEdit, QComboBox
from PyQt5.QtWidgets import QMainWindow, QTableWidgetItem
class MyWidget(QMainWindow):
def __init__(self):
super().__init__()
uic.loadUi("main.ui", self)
self.pushButton.clicked.connect(self.add)
self.do()
self.pushButton_3.clicked.connect(self.do)
def add(self):
self.dialog = Dialog()
self.dialog.setWindowTitle("Форма")
self.dialog.show()
def do(self):
self.con = sqlite3.connect("coffee.db")
cur = self.con.cursor()
result = cur.execute("SELECT * FROM coffee").fetchall()
self.tableWidget.setRowCount(len(result))
self.tableWidget.setColumnCount(len(result[0]))
self.titles = [description[0] for description in cur.description]
self.tableWidget.setHorizontalHeaderLabels(self.titles)
for i, elem in enumerate(result):
for j, val in enumerate(elem):
self.tableWidget.setItem(i, j, QTableWidgetItem(str(val)))
class Dialog(QWidget):
def __init__(self):
super().__init__()
uic.loadUi("addEditCoffeeForm.ui", self)
self.pushButton5.clicked.connect(self.base)
def base(self):
nazvanie = self.lineEdit.text()
prozharka = self.lineEdit_2.text()
molotiy_vzernah = self.comboBox.currentText()
vkus = self.lineEdit_3.text()
cena = self.lineEdit_4.text()
obyom = self.lineEdit_5.text()
self.con = sqlite3.connect("coffee.db")
cur = self.con.cursor()
f = True
result0 = cur.execute("SELECT * FROM coffee").fetchall()
for i in result0:
if nazvanie in i:
f = False
if f:
cur.execute(
"INSERT INTO coffee (name, stepen, molotyilivzernah, opisanie, cena, obyom) VALUES (?, ?, ?, ?, ?, ?)", (nazvanie, prozharka, molotiy_vzernah, vkus, cena, obyom))
self.con.commit()
cur.close()
else:
cur.execute(
"UPDATE coffee set stepen = ?, molotyilivzernah = ?, opisanie = ?, cena = ?, obyom = ? WHERE name = ?",
(prozharka, molotiy_vzernah, vkus, cena, obyom, nazvanie))
self.con.commit()
cur.close()
if __name__ == '__main__':
app = QApplication(sys.argv)
ex = MyWidget()
ex.show()
sys.exit(app.exec())
| UTF-8 | Python | false | false | 2,685 | py | 1 | main.py | 1 | 0.60709 | 0.6 | 0 | 77 | 33.805195 | 178 |
1071179133/boamp | 1,958,505,135,715 | cd73ad2fe6fa9572f02b59823a06376db03978f6 | f2cc9b7b855914fe15a58273e8de1f7b44d98f24 | /super_admin/urls.py | 5cc383725544da1d475ab85b331a64ab381ffb6a | []
| no_license | https://github.com/1071179133/boamp | b001cb4be52f6ea61f033948630192a7a6793248 | f8df644c91ca236cfa4c8b2ecec618236d76ad31 | refs/heads/master | 2020-05-03T01:25:15.911960 | 2019-03-29T08:16:48 | 2019-03-29T08:16:48 | 178,336,779 | 4 | 3 | null | false | 2019-10-22T22:28:06 | 2019-03-29T05:13:40 | 2019-04-01T15:14:51 | 2019-10-22T22:28:05 | 2,773 | 2 | 1 | 2 | JavaScript | false | false | from django.contrib import admin
from django.urls import path,re_path
from super_admin import views
urlpatterns = [
path('index/', views.index,name="table_index"),
re_path('(?P<app_name>\w+)/(?P<table_name>\w+)/add/', views.table_obj_add,name="table_objs_add"),
re_path('(?P<app_name>\w+)/(?P<table_name>\w+)/(?P<obj_id>\d+)/change/', views.table_obj_change,name="table_objs_change"),
re_path('(?P<app_name>\w+)/(?P<table_name>\w+)/(?P<obj_id>\d+)/delete/', views.table_obj_delete,name="obj_delete"),
re_path('(\w+)/(\w+)/', views.display_table_obj,name="table_objs"),
path('pg_num/',views.pg_num,name="pg_num"),
]
| UTF-8 | Python | false | false | 640 | py | 64 | urls.py | 39 | 0.632813 | 0.632813 | 0 | 12 | 52.333333 | 126 |
LH1151418000/meiduo2 | 3,100,966,420,609 | 639cc8de3af04c23f4af45de6fd03f90732f5c0b | 5fc1132efc80b0c15bd507afe453090f4b390e1e | /meiduo_mall/celery_tasks/sms/tasks.py | c8cf935122306aa2d04c224c25387007a7e9cb39 | []
| no_license | https://github.com/LH1151418000/meiduo2 | c9c302fee61fbaaf2f026b79b693751a50d35974 | f557bd15a62eb482cef40cee4383308659992d6c | refs/heads/main | 2023-01-19T19:59:22.843823 | 2020-12-03T03:09:08 | 2020-12-03T03:09:08 | 317,078,617 | 0 | 0 | null | null | null | null | null | null | null | null | null | null | null | null | null | from ronglian_sms_sdk import SmsSDK
from celery_tasks.main import celery_app
# 创建发送短信任务
@celery_app.task(name="sms_send")
def sms_send(mobile, sms_code):
sms = SmsSDK('8aaf0708723b53c901724954cb8c03f7', '01413ea023b7420dafe75c5ece801c51',
'8aaf070872499534017258fb6de10960')
sms.sendMessage('1', mobile, (sms_code, 5))
return sms
| UTF-8 | Python | false | false | 377 | py | 6 | tasks.py | 6 | 0.725762 | 0.531856 | 0 | 11 | 31.818182 | 88 |
stcstores/stcadmin | 17,532,056,520,313 | 9e4cdfb9f48cf86bbc1a9ab54a99ce414246d1c1 | 446fc0b792dafeca16cd817d09e644d7d621d51c | /shipping/tests/test_models/test_ShippingPrice_model.py | ab97d1b891c77a9017a1d69b213e13c90e20fa6a | []
| no_license | https://github.com/stcstores/stcadmin | 083ac83261872d401088c30d5454c986416c0dbb | ba51d4e304b1aeb296fa2fe16611c892fcdbd471 | refs/heads/master | 2023-08-29T23:13:44.652923 | 2023-08-29T13:33:01 | 2023-08-29T13:33:01 | 78,753,311 | 0 | 0 | null | false | 2023-09-14T09:08:28 | 2017-01-12T14:25:26 | 2022-01-05T10:21:06 | 2023-09-14T09:08:26 | 9,560 | 0 | 0 | 2 | Python | false | false | import pytest
from django.db import IntegrityError
from shipping import models
@pytest.fixture
def shipping_service(shipping_service_factory):
return shipping_service_factory.create()
@pytest.fixture
def country(country_factory):
return country_factory.create()
@pytest.fixture
def region(region_factory):
return region_factory.create()
@pytest.fixture
def new_shipping_price(shipping_service, country):
shipping_price = models.ShippingPrice(
shipping_service=shipping_service, country=country
)
shipping_price.save()
return shipping_price
@pytest.mark.django_db
def test_sets_shipping_service(new_shipping_price, shipping_service):
assert new_shipping_price.shipping_service == shipping_service
@pytest.mark.django_db
def test_sets_country(new_shipping_price, country):
assert new_shipping_price.country == country
@pytest.fixture
def test_sets_region(new_shipping_price):
assert new_shipping_price.region is None
@pytest.mark.django_db
def test_sets_item_price(new_shipping_price):
assert new_shipping_price.item_price == 0
@pytest.mark.django_db
def test_sets_price_per_kg(new_shipping_price):
assert new_shipping_price.price_per_kg == 0
@pytest.mark.django_db
def test_sets_price_per_g(new_shipping_price):
assert new_shipping_price.price_per_g == 0
@pytest.mark.django_db
def test_sets_item_surcharge(new_shipping_price):
assert new_shipping_price.item_surcharge == 0
@pytest.mark.django_db
def test_sets_fuel_surcharge(new_shipping_price):
assert new_shipping_price.fuel_surcharge == 0
@pytest.mark.django_db
def test_sets_covid_surcharge(new_shipping_price):
assert new_shipping_price.covid_surcharge == 0
@pytest.mark.django_db
def test_sets_active(new_shipping_price):
assert new_shipping_price.active is False
@pytest.mark.django_db
def test_can_create_with_region(shipping_service, region):
shipping_price = models.ShippingPrice(
shipping_service=shipping_service, region=region
)
shipping_price.save()
assert shipping_price.region == region
@pytest.mark.django_db
def test__str__method_with_country(shipping_price_factory, country):
shipping_price = shipping_price_factory.create(country=country, region=None)
assert (
str(shipping_price)
== f"{shipping_price.shipping_service} - {shipping_price.country}"
)
@pytest.mark.django_db
def test__str__method_with_region(shipping_price_factory, region):
shipping_price = shipping_price_factory.create(country=None, region=region)
assert str(shipping_price) == f"{shipping_price.shipping_service} - {region}"
@pytest.mark.django_db
def test_fixed_price(shipping_price_factory):
price = 560
shipping_price = shipping_price_factory.create(item_price=price, price_per_kg=0)
assert shipping_price.price(970) == price
@pytest.mark.django_db
def test_kg_price(shipping_price_factory):
shipping_price = shipping_price_factory.create(item_price=120, price_per_kg=80)
assert shipping_price.price(1500) == 280
@pytest.mark.django_db
def test_g_price(shipping_price_factory):
shipping_price = shipping_price_factory.create(
item_price=120, price_per_kg=0, price_per_g=0.08
)
assert shipping_price.price(1500) == 240
@pytest.mark.django_db
def test_weight_band_price(shipping_price_factory, weight_band_factory):
shipping_price = shipping_price_factory.create(item_price=0, price_per_kg=0)
weight_band_factory.create(
min_weight=0, max_weight=200, price=220, shipping_price=shipping_price
)
correct_weight_band = weight_band_factory.create(
min_weight=201, max_weight=500, price=530, shipping_price=shipping_price
)
weight_band_factory.create(
min_weight=501, max_weight=700, price=780, shipping_price=shipping_price
)
assert shipping_price.price(350) == correct_weight_band.price
@pytest.mark.django_db
def test_weight_band_with_kg_price(shipping_price_factory, weight_band_factory):
shipping_price = shipping_price_factory.create(item_price=0, price_per_kg=80)
weight_band_factory.create(
min_weight=100, max_weight=2000, price=220, shipping_price=shipping_price
)
assert shipping_price.price(1500) == 380
@pytest.mark.django_db
def test_weight_band_with_g_price(shipping_price_factory, weight_band_factory):
shipping_price = shipping_price_factory.create(
item_price=0, price_per_kg=0, price_per_g=0.08
)
weight_band_factory.create(
min_weight=100, max_weight=2000, price=220, shipping_price=shipping_price
)
assert shipping_price.price(1500) == 340
@pytest.mark.django_db
def test_item_surcharge(shipping_price_factory):
shipping_price = shipping_price_factory.create(item_price=600, item_surcharge=70)
assert shipping_price.price(1500) == 670
@pytest.mark.django_db
def test_fuel_surcharge(shipping_price_factory):
shipping_price = shipping_price_factory.create(item_price=600, fuel_surcharge=10)
assert shipping_price.price(1500) == 660
@pytest.mark.django_db
def test_covid_surcharge(shipping_price_factory):
shipping_price = shipping_price_factory.create(item_price=600, covid_surcharge=70)
assert shipping_price.price(1500) == 670
@pytest.mark.django_db
def test_surcharges(shipping_price_factory):
shipping_price = shipping_price_factory.create(
item_price=600, item_surcharge=70, fuel_surcharge=10, covid_surcharge=70
)
assert shipping_price.price(1500) == 800
@pytest.mark.django_db
def test_shipping_service_and_country_are_unique_together(
shipping_service, country, shipping_price_factory
):
shipping_price_factory.create(shipping_service=shipping_service, country=country)
with pytest.raises(IntegrityError):
shipping_price_factory.create(
shipping_service=shipping_service, country=country
)
@pytest.mark.django_db
def test_shipping_service_and_region_are_unique_together(
region, shipping_service, country, shipping_price_factory
):
shipping_price_factory.create(
shipping_service=shipping_service, country=None, region=region
)
with pytest.raises(IntegrityError):
shipping_price_factory.create(
shipping_service=shipping_service, country=None, region=region
)
@pytest.mark.django_db
def test_shipping_service_cannot_have_both_country_and_region(
shipping_price_factory, country, region
):
with pytest.raises(IntegrityError):
shipping_price_factory.create(country=country, region=region)
@pytest.mark.django_db
def test_country_and_region_cannot_both_be_null(shipping_price_factory):
with pytest.raises(IntegrityError):
shipping_price_factory.create(country=None, region=None)
@pytest.mark.django_db
def test_find_shipping_price(
shipping_price_factory, country_factory, shipping_service_factory
):
shipping_service = shipping_service_factory.create()
country = country_factory.create()
price = shipping_price_factory.create(
shipping_service=shipping_service, country=country, region=None
)
returned = models.ShippingPrice.objects.find_shipping_price(
country=country, shipping_service=shipping_service
)
assert returned == price
@pytest.mark.django_db
def test_find_shipping_price_by_region(
shipping_price_factory, country_factory, shipping_service_factory
):
shipping_service = shipping_service_factory.create()
country = country_factory.create()
price = shipping_price_factory.create(
shipping_service=shipping_service, country=None, region=country.region
)
returned = models.ShippingPrice.objects.find_shipping_price(
country=country, shipping_service=shipping_service
)
assert returned == price
@pytest.mark.django_db
def test_find_shipping_price_without_match(shipping_service_factory, country_factory):
shipping_service = shipping_service_factory.create()
country = country_factory.create()
with pytest.raises(models.ShippingPrice.DoesNotExist):
models.ShippingPrice.objects.find_shipping_price(
country=country, shipping_service=shipping_service
)
| UTF-8 | Python | false | false | 8,180 | py | 577 | test_ShippingPrice_model.py | 432 | 0.733374 | 0.713447 | 0 | 262 | 30.221374 | 86 |
BGCX261/zora-na-pruzi-hg-to-git | 781,684,088,059 | 7e922d2a2ad7b14fbf5f747783390795468f4e96 | fb0e99751068fa293312f60fedf8b6d0b9eae293 | /zora_na_pruzi/stroj/svg/vytvořím_svg_příklad.py | faef8fe4863df038f6fd24c080979c93744cfed1 | []
| no_license | https://github.com/BGCX261/zora-na-pruzi-hg-to-git | d9628a07e3effa6eeb15b9b5ff6d75932a6deaff | 34a331e17ba87c0de34e7f0c5b43642d5b175215 | refs/heads/master | 2021-01-19T16:52:06.478359 | 2013-08-07T19:58:42 | 2013-08-07T19:58:42 | 41,600,435 | 0 | 0 | null | null | null | null | null | null | null | null | null | null | null | null | null | #!/usr/bin/env python3
# Copyright (c) 2012 Домоглед <domogled@domogled.eu>
# @author Петр Болф <petr.bolf@domogled.eu>
'''
Hen je program, který ...
'''
print('Jak udělám SVG soubor')
from zora_na_pruzi.strojmir.xml.svg import E
def davaj_svg():
svg = E.SVG()
svg.titulek = 'TITULEK'
svg.popisek = 'popisuji svg'
kruh = E.G().kružnice(střed = (45, 50), poloměr = 40)
svg.append(kruh)
css_kruhu = kruh.css_dle_třídy('KOLO', element = True)
css_kruhu.fill(0xFFFF00).stroke(0x1100CC).stroke_width(4, 'px')
return svg
if __name__ == '__main__':
svg = davaj_svg()
print(svg)
uložím_do_souboru = 'testuji.svg'
import os
svg.CSS >> '{}.{}'.format(os.path.splitext(uložím_do_souboru)[0], 'css')
svg >> uložím_do_souboru
import webbrowser
webbrowser.open(uložím_do_souboru)
| UTF-8 | Python | false | false | 882 | py | 296 | vytvořím_svg_příklad.py | 238 | 0.623529 | 0.598824 | 0 | 36 | 22.611111 | 77 |
abdiswork/Data-Science | 14,156,212,234,621 | 02a19c86354244e97309812f058d099ac6af9426 | 981e8942e0f914f51c5744422615c3b966816a77 | /career-track/Python for Data Professional/Part1/practice-loop.py | 054d477bdabb0ed88202468bffc805bfa675fd46 | []
| no_license | https://github.com/abdiswork/Data-Science | a7d883089f67e3ada2b30ec3dba64d93aceb7998 | a2f0d02f609742c8d1c486827dab168897742db4 | refs/heads/main | 2023-08-29T19:03:46.600065 | 2021-11-04T08:05:52 | 2021-11-04T08:05:52 | 423,764,012 | 0 | 0 | null | null | null | null | null | null | null | null | null | null | null | null | null | list_cash_flow = [
2500000, 5000000, -1000000, -2500000, 5000000, 10000000,
-5000000, 7500000, 10000000, -1500000, 25000000, -2500000
]
total_pengeluaran, total_pemasukan = 0, 0
for dana in list_cash_flow:
if dana > 0:
total_pemasukan += dana
else:
total_pengeluaran += dana
total_pengeluaran *= -1
print(total_pengeluaran)
print(total_pemasukan) | UTF-8 | Python | false | false | 371 | py | 59 | practice-loop.py | 57 | 0.695418 | 0.450135 | 0 | 13 | 27.615385 | 57 |
Mort6s/DP-MFSC | 1,365,799,638,823 | d5be4f8ff4c60c87a0dab456f263ba608cd19dd9 | df8563dca06dd41a5e9a4ddbf44b631e78c72313 | /Main.py | a38d7d13f5e440fa7cf7201f4add2a88e6f9c49f | []
| no_license | https://github.com/Mort6s/DP-MFSC | b62560a0df48cd037570f860d61bc6c04c6a9eae | e6a67de138d93986536cda97469b84776abe469b | refs/heads/master | 2020-07-29T20:33:17.208758 | 2019-09-21T11:21:09 | 2019-09-21T11:21:09 | 209,948,763 | 0 | 0 | null | null | null | null | null | null | null | null | null | null | null | null | null | # -*- coding: utf-8 -*-
"""
Created on Thu Jul 13 21:33:24 2017
@author: 84664
"""
from __future__ import division
import sys
sys.path.append('conf')
import dp_conf as conf
import PreMining as PM
import Mining as M
import numpy as np
import ConsolidatedFrequency as CF
import utility
import datetime
import os
def getNoisyConFrequency():
print "*****Read Data********************"
Dataset = []
Dataset = PM.read(conf.dataset, conf.tlen, conf.scale)
print "*****Read sucessfully*************"
print "*****Start Mining Phase***********"
height = conf.lUp - conf.lLeft + 1
dbSets = M.randomly_partition_database(Dataset, height)
each_epsilon = conf.epsilon2 / height
CandidateSets = {}
new_CandidateSets = {}
FS = {}
FS_sup = {}
FSlist = []
FSlist_sup = []
print "len(dbSets)" + str(len(dbSets))
i = 0
for k in range(conf.lLeft, conf.lUp + 1):
if k == conf.lLeft :
CandidateSets[k] = M.getcandidate(conf.alphabet, k)
else:
CandidateSets[k] = M.generate_candidate(FS[k - 1], conf.alphabet)
#print "len of dbset:" + str( len(dbSets) )
new_CandidateSets[k] = M.SamplingbasedCandidatePruning(k, CandidateSets[k], dbSets[i], conf.epsilon1, conf.theta)
i += 1
#print new_CandidateSets[k]
(FS[k], FS_sup[k])= M.discover_frequent_sequence1(k,new_CandidateSets[k], each_epsilon, Dataset, conf.theta)
#(FS[k], FS_sup[k]) = M.discoverFrequentSequences(k, Dataset, new_CandidateSets[k], each_epsilon, conf.theta, conf.l_max, conf.l_max)
FSlist += FS[k]
FSlist_sup += FS_sup[k]
print "************* End Mining Phase ****************"
fp = open(conf.dataset_noisy, 'w')
print len(FSlist)
print len(FSlist_sup)
for i in range(len(FSlist)):
fp.write(str(FSlist[i]) + ":" + str(FSlist_sup[i]) + '\n')
fp.close()
print"Caculate the consolidated frequencies"
CF.calculateConsolidatedFrequency(conf.dataset_noisy, conf.lLeft, conf.lUp, conf.delta, conf.TopNfile_noisy, conf.topN)
print "End Caculate the consolidate frquencies"
def getTrueConFrequency():
print "*****getTrueConFrequency**********"
print "*****Read Data********************"
Dataset = []
Dataset = PM.read(conf.dataset, conf.tlen, conf.scale)
print "len of dataset:" + str(len(Dataset))
print "*****Read sucessfully*************"
print "*****Start Mining Phase***********"
#dbSets = M.randomly_partition_database(Dataset, conf.lUp)
CandidateSets = {}
FS = {}
FS_sup = {}
FSlist = []
FSlist_sup = []
for k in range(1, conf.lUp + 1):
print "k=" + str(k)
if k == 1 :
CandidateSets[k] = M.getcandidate(conf.alphabet, k)
else:
CandidateSets[k] = M.generate_candidate(FS[k - 1], conf.alphabet)
#CandidateSets[k] = M.SamplingbasedCandidatePruning(k, CandidateSets[k], dbSets[k - 1], conf.theta, conf.l_max)
(FS[k], FS_sup[k])= M.discover_frequent_sequence2(CandidateSets[k], Dataset, conf.theta)
FSlist += FS[k]
FSlist_sup += FS_sup[k]
print "************* End Mining Phase ****************"
fp = open(conf.dataset_true, 'w')
print len(FSlist)
print len(FSlist_sup)
for i in range(len(FSlist)):
fp.write(str(FSlist[i]) + ":" + str(FSlist_sup[i]) + '\n')
fp.close()
print"Caculate the consolidated frequencies"
CF.calculateConsolidatedFrequency(conf.dataset_true, conf.lLeft, conf.lUp, conf.delta, conf.TopNfile_true, conf.topN)
print "End Caculate the consolidate frquencies"
begin = datetime.datetime.now()
getNoisyConFrequency()
if os.path.isfile(conf.TopNfile_true) == False :
getTrueConFrequency()
utility.Accuracy(conf.TopNfile_true, conf.TopNfile_noisy, conf.topN)
utility.RE(conf.TopNfile_true, conf.TopNfile_noisy, conf.topN)
utility.ARE(conf.TopNfile_true, conf.TopNfile_noisy, conf.topN)
utility.FNR(conf.TopNfile_true, conf.TopNfile_noisy, conf.topN)
end = datetime.datetime.now()
print "Total running time:" + str(end - begin)
'''
f = open(conf.dataset_true)
lines = f.readlines()
utility.Recall(len(lines), conf.TopNfile_true, conf.TopNfile_noisy, conf.topN)
'''
| UTF-8 | Python | false | false | 4,271 | py | 18 | Main.py | 8 | 0.616483 | 0.608991 | 0 | 122 | 34 | 141 |
tdaylan/PyAutoFit | 1,769,526,527,417 | e05baf37fabb5e0c57de8225d9a00dd86b47254e | eac06815e958fe429e3c697c2837aee0aad048b0 | /setup.py | f053e8a1ec7483938323f79776369076e0c259c0 | [
"MIT"
]
| permissive | https://github.com/tdaylan/PyAutoFit | 7c76c6e49f73423781a23d8c6ea374ae9a302303 | 58242a4ce83c03dd58624336822988d52a440ba4 | refs/heads/master | 2020-04-09T00:04:40.486821 | 2018-11-20T14:52:51 | 2018-11-20T14:52:51 | 159,852,436 | 1 | 0 | null | true | 2018-11-30T16:49:05 | 2018-11-30T16:49:04 | 2018-11-20T14:53:24 | 2018-11-20T14:54:10 | 105 | 0 | 0 | 0 | null | false | null | from codecs import open
from os.path import abspath, dirname, join
from subprocess import call
from setuptools import Command, find_packages, setup
from autofit import __version__
this_dir = abspath(dirname(__file__))
with open(join(this_dir, 'README.md'), encoding='utf-8') as file:
long_description = file.read()
class RunTests(Command):
"""Run all tests."""
description = 'run tests'
user_options = []
def initialize_options(self):
pass
def finalize_options(self):
pass
def run(self):
"""Run all tests!"""
errno = call(['py.test', '--cov=autolens', '--cov-report=term-missing'])
raise SystemExit(errno)
setup(
name='autofit',
version=__version__,
description='Classy non-linear optimisation',
long_description=long_description,
long_description_content_type='text/markdown',
url='https://github.com/rhayes777/AutoFit',
author='James Nightingale and Richard Hayes',
author_email='richard@rghsoftware.co.uk',
include_package_data=True,
license='MIT License',
classifiers=[
'Intended Audience :: Science/Research',
'Topic :: Scientific/Engineering :: Physics',
'License :: OSI Approved :: MIT License',
'Natural Language :: English',
'Operating System :: OS Independent',
'Programming Language :: Python :: 3',
'Programming Language :: Python :: 3.2',
'Programming Language :: Python :: 3.3',
'Programming Language :: Python :: 3.4',
'Programming Language :: Python :: 3.5',
'Programming Language :: Python :: 3.6',
'Programming Language :: Python :: 3.7'
],
keywords='cli',
packages=find_packages(exclude=['docs', 'tests*']),
install_requires=[
'GetDist',
'scipy',
'numpy',
'pymultinest',
'matplotlib'
],
extras_require={
'test': ['coverage', 'pytest', 'pytest-cov'],
},
cmdclass={'test': RunTests},
)
| UTF-8 | Python | false | false | 2,001 | py | 30 | setup.py | 12 | 0.609695 | 0.601199 | 0 | 69 | 28 | 80 |
zhanglianghui/PyFun | 7,310,034,357,557 | 853e98117ec035249e3e42e529e6a723ffd772aa | 31132e2fdd17c4412547e8b9e3e172d5983af455 | /leetcode/binary-tree-level-sum.py | fc0f9b6282f0d90fe767386936dccedb55661474 | []
| no_license | https://github.com/zhanglianghui/PyFun | 0e3c65067253f60a624577a5e857d0e98c7aad52 | 99285e5654980d6d405bf640870e8f0281057fbc | refs/heads/master | 2020-03-28T15:07:28.741868 | 2018-10-11T02:28:32 | 2018-10-11T02:28:32 | 148,558,696 | 0 | 0 | null | null | null | null | null | null | null | null | null | null | null | null | null | from queue import Queue
from tree_sample import Tree_Sample
class TreeNode:
def __init__(self, val):
self.val = val
self.left, self.right = None, None
class Solution:
"""
@param root: the root of the binary tree
@param level: the depth of the target level
@return: An integer
"""
def levelSum1(self, root, level):
"""
广度优先遍历
:param root:
:param level:
:return:
"""
result = 0
if root is None:
return result
q = Queue()
q.put(root)
l = 0
while not q.empty():
l += 1
n = q.qsize()
for i in range(n):
cur = q.get()
if level == l:
result += cur.val
if cur.left is not None:
q.put(cur.left)
if cur.right is not None:
q.put(cur.right)
return result
def levelSum(self, root, level):
"""
深度优先遍历
:param root:
:param level:
:return:
"""
items = []
self.dfs(root, 1, items, level)
return sum(items)
def dfs(self, root, depth, items, level):
if root is None:
return
if depth == level:
items.append(root.val)
return
self.dfs(root.left, depth + 1, items, level)
self.dfs(root.right, depth + 1, items, level)
# print(Solution().levelSum1(Tree_Sample, 2))
print(Solution().levelSum(Tree_Sample, 3))
| UTF-8 | Python | false | false | 1,587 | py | 25 | binary-tree-level-sum.py | 24 | 0.479207 | 0.472809 | 0 | 69 | 21.652174 | 53 |
ShahrOZe69/AmazonScraper | 15,822,659,557,533 | 2a4818eb85533f867ec23ae94800fcedb3bafa0d | f3257b637f3d99b030a08153584822a21bb0ac38 | /AmazonScraperV2/AmazonScraper.py | 4068fc2349667241c0d1ef7658e8b4e52e29907b | []
| no_license | https://github.com/ShahrOZe69/AmazonScraper | 7bb3c4bea89ad909e06e8ba424084cd57b8c3224 | e1ea0cc1eeb45e0f8fed16e6ef3ddf1a558cb6f7 | refs/heads/main | 2023-04-25T21:07:46.581173 | 2021-05-26T06:33:16 | 2021-05-26T06:33:16 | 370,930,074 | 0 | 0 | null | null | null | null | null | null | null | null | null | null | null | null | null | from requests_html import HTMLSession
import requests_html
from bs4 import BeautifulSoup
import random
from file_reader import read_from_xlsx
import time
import pandas as pd
from pprint import pprint
from ProxySnatcher import getFreshProxies
"""INITIAL WORK"""
asins = read_from_xlsx('ASINs.xlsx')['ASIN/ISBN']
useragent_list= open('user_agents.txt','r',encoding='utf-8').read().splitlines()
proxies_list = open('http_proxies.txt','r',encoding='utf-8').read().splitlines()
items = [['span',{'id':'productTitle'}],['span',{'class':'a-icon-alt'}],['a',{'data-hook':'review-title'}]]
names = ['Title','Rating','Top Review']
CHUNK_SIZE=100
def getNewProxy():
proxy = random.choice(proxies_list)
proxies={'http':f'http://{proxy}'}
return proxies
def getNewHeaders():
useragent = random.choice(useragent_list)
HEADERS={'user-agent':useragent}
return HEADERS
def checkResponse(r):
if "To discuss automated access to Amazon data please contact" in r.html.text or "Sorry, we just need to make sure you're not a robot" in r.html.text or r.status_code != 200:
return False
return True
def getItems(soup):
result={}
for i,n in zip(items,names):
item = soup.find(*i)
if item is not None:
result[n]=item.get_text(strip=True)
return result
"""SCRAPING"""
def Scrape(s_index):
getFreshProxies()
session = HTMLSession()
count=0
data=[]
for asin in asins[s_index:s_index+CHUNK_SIZE]:
noOfTries=0
succesful=False
URL = f'https://www.amazon.com/dp/{asin}'
while not succesful:
try:
response = session.get(URL,headers=getNewHeaders(),proxies=getNewProxy())
response.html.render(timeout=10)
except Exception as e:
print(e)
continue
if checkResponse(response):
soup = BeautifulSoup(response.html.html,features='lxml')
count+=1
dat = getItems(soup)
print(dat,count)
data.append(dat)
if count%10==0:
df= pd.DataFrame(data)
df.to_csv("result1.csv",index=False)
succesful = True
else:
print("BAD RESPONSE")
noOfTries+=1
if noOfTries==20:
print("NEED NEW FUEL")
time.sleep(random.randint(100,200))
getFreshProxies()
print("STARTING")
proxies_list = open('http_proxies.txt','r',encoding='utf-8').read().splitlines()
try:
print("closing response")
response.close()
time.sleep(10)
print('closing session')
response.session.close()
time.sleep(10)
except Exception as e:
print("ERROR WHILE CLOSING SESSIONS AND RESPONSE \n\n",e)
session = HTMLSession()
noOfTries=0
response.close()
response.session.close()
Scrape(0)
| UTF-8 | Python | false | false | 2,715 | py | 7 | AmazonScraper.py | 4 | 0.65267 | 0.640147 | 0 | 97 | 25.927835 | 175 |
Aasthaengg/IBMdataset | 4,887,672,804,235 | 9fe357079f9dd840ee068f3f59bf511bf38f3ab0 | ca7aa979e7059467e158830b76673f5b77a0f5a3 | /Python_codes/p03289/s584214867.py | 0dbd797c6750c353a41ac212d98cbaa7f4841fb3 | []
| no_license | https://github.com/Aasthaengg/IBMdataset | 7abb6cbcc4fb03ef5ca68ac64ba460c4a64f8901 | f33f1c5c3b16d0ea8d1f5a7d479ad288bb3f48d8 | refs/heads/main | 2023-04-22T10:22:44.763102 | 2021-05-13T17:27:22 | 2021-05-13T17:27:22 | 367,112,348 | 0 | 0 | null | null | null | null | null | null | null | null | null | null | null | null | null | S = input().rstrip()
cnt = 0
for s in S[2:-1]:
if s == "C":
cnt += 1
else:
if not s.islower():
print("WA")
exit()
if cnt == 1 and S[0] == "A" and S[1].islower() and S[-1].islower():
print("AC")
else:
print("WA") | UTF-8 | Python | false | false | 267 | py | 202,060 | s584214867.py | 202,055 | 0.430712 | 0.400749 | 0 | 13 | 19.615385 | 67 |
alikanet/pyUtils | 9,131,100,512,548 | a77b8e014d7f1b7da0e4abaa1c0851a675e7394e | 25d1f3a7aeda1a1cd4b9bd38325c7470f080ba82 | /encryptDialog.py | 22ce95e082194bc1d66dc1b1ad6e257b7d634750 | []
| no_license | https://github.com/alikanet/pyUtils | 6026c3d59291bf6605af1a3cad1a2b0b6cfcf6ed | 5f122de19ef77954c3c5d5e4d2362899130962cd | refs/heads/master | 2022-07-29T14:49:40.034743 | 2020-05-18T07:10:16 | 2020-05-18T07:10:16 | 255,798,305 | 0 | 0 | null | null | null | null | null | null | null | null | null | null | null | null | null | from PyQt5 import QtCore, QtGui, QtWidgets
class Ui_encryptDlg(object):
def setupUi(self, encryptDlg):
encryptDlg.setObjectName("encryptDlg")
encryptDlg.resize(660, 129)
self.buttonBox = QtWidgets.QDialogButtonBox(encryptDlg)
self.buttonBox.setGeometry(QtCore.QRect(560, 90, 81, 41))
self.buttonBox.setOrientation(QtCore.Qt.Vertical)
self.buttonBox.setStandardButtons(QtWidgets.QDialogButtonBox.Ok)
self.buttonBox.setObjectName("buttonBox")
self.txtInput = QtWidgets.QLineEdit(encryptDlg)
self.txtInput.setGeometry(QtCore.QRect(80, 20, 411, 21))
self.txtInput.setObjectName("txtInput")
self.txtOutput = QtWidgets.QLineEdit(encryptDlg)
self.txtOutput.setGeometry(QtCore.QRect(80, 60, 411, 21))
self.txtOutput.setObjectName("txtOutput")
self.label = QtWidgets.QLabel(encryptDlg)
self.label.setGeometry(QtCore.QRect(20, 60, 51, 16))
self.label.setObjectName("label")
self.label_2 = QtWidgets.QLabel(encryptDlg)
self.label_2.setGeometry(QtCore.QRect(20, 20, 41, 16))
self.label_2.setObjectName("label_2")
self.btnEncrypt = QtWidgets.QPushButton(encryptDlg)
self.btnEncrypt.setGeometry(QtCore.QRect(496, 16, 80, 32))
self.btnEncrypt.setObjectName("btnEncrypt")
self.btnDecrypt = QtWidgets.QPushButton(encryptDlg)
self.btnDecrypt.setGeometry(QtCore.QRect(566, 16, 80, 32))
self.btnDecrypt.setObjectName("btnDecrypt")
self.drpType = QtWidgets.QComboBox(encryptDlg)
self.drpType.setGeometry(QtCore.QRect(500, 58, 141, 26))
self.drpType.setObjectName("drpType")
self.retranslateUi(encryptDlg)
self.buttonBox.accepted.connect(encryptDlg.accept)
self.buttonBox.rejected.connect(encryptDlg.reject)
self.btnDecrypt.clicked.connect(encryptDlg.exec)
self.btnEncrypt.clicked.connect(encryptDlg.exec)
self.drpType.currentTextChanged['QString'].connect(encryptDlg.exec)
QtCore.QMetaObject.connectSlotsByName(encryptDlg)
def retranslateUi(self, encryptDlg):
_translate = QtCore.QCoreApplication.translate
encryptDlg.setWindowTitle(_translate("encryptDlg", "Encryption"))
self.label.setText(_translate("encryptDlg", "Output"))
self.label_2.setText(_translate("encryptDlg", "Input"))
self.btnEncrypt.setText(_translate("encryptDlg", "Encrypt"))
self.btnDecrypt.setText(_translate("encryptDlg", "Decrypt"))
# if __name__ == "__main__":
# import sys
# app = QtWidgets.QApplication(sys.argv)
# encryptDlg = QtWidgets.QDialog()
# ui = Ui_encryptDlg()
# ui.setupUi(encryptDlg)
# encryptDlg.show()
# sys.exit(app.exec_())
| UTF-8 | Python | false | false | 2,765 | py | 20 | encryptDialog.py | 10 | 0.689693 | 0.659675 | 0 | 59 | 45.864407 | 75 |
stvnfrnk/kangaroo | 962,072,676,169 | 1619c1f67d83c595667bc609c23528efad4bfb3e | d02f268ba00d685293ee7667844f690ec9a7f27f | /codewars/python3/get_the_middle_character.py | f6463ba780f85e595076dcf77820827f52f5961e | []
| no_license | https://github.com/stvnfrnk/kangaroo | e0560c0f510869921abbe87090b9b99e0dabd43b | 5734c982c7edeb5906a3c28befe27f3bd685df9a | refs/heads/master | 2018-02-08T19:46:05.595908 | 2017-10-23T16:44:10 | 2017-10-23T16:44:10 | 80,402,630 | 0 | 0 | null | null | null | null | null | null | null | null | null | null | null | null | null | #!/Users/stevenfranke/anaconda/bin/python3
'''
Your job is to return the middle character of the word.
If the word's length is odd, return the middle character.
If the word's length is even, return the middle 2 characters.
'''
def get_middle(s):
if type(s) == str:
if len(s) % 2 != 0:
mid = int(len(s) / 2)
print(str(s[mid]))
elif len(s) % 2 == 0:
mid1 = int(len(s) / 2 - 0.5)
mid2 = int(len(s) / 2 + 0.5)
str(s[mid1]) + str(s[mid2])
get_middle("testword")
### SMART SOLUTIONS ###
def get_middle(s):
return s[(len(s)-1)/2:len(s)/2+1]
def get_middle(s):
i = (len(s) - 1) // 2
return s[i:-i] or s
| UTF-8 | Python | false | false | 698 | py | 7 | get_the_middle_character.py | 6 | 0.537249 | 0.504298 | 0 | 33 | 20.121212 | 61 |
Altercg/Pyqt5 | 7,000,796,694,900 | 4164b655e6919e3fdb78e4fa95600bc3ca349b33 | 19d622c873a6b23393022daeb22f854dccf7684c | /tableview.py | 10547dc3a208c8673a6b5430499106fa4b1299c5 | []
| no_license | https://github.com/Altercg/Pyqt5 | c85c21c348061f4fda7c73adfa0b7834e1d5fa85 | c1e1c7754a73e59d3c1d0378698b521eeae22bb4 | refs/heads/master | 2022-04-22T16:02:31.749472 | 2020-04-16T13:01:24 | 2020-04-16T13:01:24 | 254,829,321 | 0 | 0 | null | null | null | null | null | null | null | null | null | null | null | null | null | '''
显示二维表数据(QTableView控件)
数据源 Model
需要创建QTableView实例和一个数据源(Model),然后将两者关联
MVC:Model Viewer Controller MVC的目的是将后端的数据和前端页面的耦合度降低
QTableView的子类,扩展的表格控件(QTableWidget)
每一个Cell(单元格)是一个QTableWidgetItem
tablewidget = QTableWidget()
tablewidget.setRowCount(4) # 设置行数
tablewidget.setColumnCount(3) # 设置列数
textItem = QTableWidgetItem('小明')
tableWidget.setItem(0,0,textItem) # cell里面加文本
combox.setStyleSheet('QComboBox{margin:3px};') # QSS,设置combox控件样式
tableWidget.setCellWidget(0,1,combox) #cell里面加combox
findItems(text,QtCore.Qt.MatchExactly) # 数据定位,Qt.MatchStartsWith以此开头,Qt.MatchExactly精确定位,返回列表
item.setBackground(QBrush(QColor(0,255,0))) # 设置背景色
item.setForeground(QBrush(QColor(255,0,0))) # 设置字体色
newItem.setFont(QFont('Times',14,QFont.Black)) # 设置字体样式
tableWidget.verticalScrollBar().setSliderPosition(row)
# setSliderPosition(row) # 找到满足的单元格,定位单元格所在的行
# verticalScrollBar() #获得滚动条
sortItems(columnIndex,orderType)# 单元格排序 1.指定哪一列,2.升序or降序
# Qt.DescendingOrder 降序
# Qt.AscendingOrder 升序
setTextAlignment(Qt.AlignRight | Qt.AlignBottom) # 分本对齐方式 Qt.AlignRight Qt.AlignBottom
setSpan(行,列,合并多少行数,要合并的列数) # 合并单元格,1表示不合并
tableWidget.setRowHeight(0, 80) # 第1行的高度为80
tableWidget.setColumnWidth(2, 120) # 设置cell的尺寸
newItem = QTableWidgetItem(QIcon('./images/bao1.png'),'背包')# 图片和文本添加到一个单元格中
setIconSize(QSize(width,height)) # 改变单元格图片的尺寸
# 在cell显示上下文菜单
self.tableWidget.setContextMenuPolicy(Qt.CustomContextMenu) # 设置允许显示上下文菜单
信号:self.tableWidget.customContextMenuRequested.connect(self.generateMenu)
def generateMenu(self,pos): # pos的相当于屏幕的坐标系
self.tableWidget.selectionModel().selection().indexes() # 获取所选择的行
menu = QMenu() # 创建菜单项
item1 = menu.addAction("菜单项1") # 添加菜单项
screenPos = self.tableWidget.mapToGlobal(pos) #转为相对于菜单的
action = menu.exec(screenPos) # 不点击就不会动
tablewidget.setEditTriggers(QAbstractItemView.NoEditTriggers) # 禁止编辑
tablewidget.setSelectionBehavior(QAbstractItemView.SelectRows) # 整行选择
tablewidget.resizeColumnsToContents()# 根据内容调整列和行
tablewidget.resizeRowsToContents()
tablewidget.horizontalHeader().setVisible(False) # 水平头隐藏
# tablewidget.verticalHeader().setVisible(False)
tablewidget.setVerticalHeaderLabels(["a","b"]) # 设置水平头的名称
tablewidget.setShowGrid(False) # 隐藏表格线
显示列表数据(QListView控件)
listview = QListView()
listModel = QStringListModel()
self.list = ["列表项1","列表项2", "列表项3"]
listModel.setStringList(self.list)
listview.setModel(listModel)
信号:listview.clicked.connect(self.clicked)
def clicked(self,item):
QMessageBox.information(self,"QListView","您选择了:" + self.list[item.row()])
QListView的子类,扩展的列表控件(QListWidget)
self.listwidget = QListWidget()
self.listwidget.addItem("item1")
信号:self.listwidget.itemClicked.connect(self.clicked)
def clicked(self,Index):
self.listwidget.item(self.listwidget.row(Index)).text()) # 先获得点击的行数的文本,再传入获得文本
'''
from PyQt5.QtWidgets import *
from PyQt5.QtGui import *
import sys
class TableView(QWidget):
def __init__(self, arg=None):
super(TableView, self).__init__(arg)
self.setWindowTitle("QTableView表格视图控件演示")
self.resize(500, 300);
self.model = QStandardItemModel(4, 3) # 设置二维表
self.model.setHorizontalHeaderLabels(['id', '姓名', '年龄']) # 设置列
# 关联QTableView控件和Model
self.tableview = QTableView()
self.tableview.setModel(self.model)
# 添加数据
item11 = QStandardItem('10')
item12 = QStandardItem('雷神')
item13 = QStandardItem('2000')
self.model.setItem(0, 0, item11)
self.model.setItem(0, 1, item12)
self.model.setItem(0, 2, item13)
item31 = QStandardItem('30')
item32 = QStandardItem('死亡女神')
item33 = QStandardItem('3000')
self.model.setItem(2, 0, item31)
self.model.setItem(2, 1, item32)
self.model.setItem(2, 2, item33)
layout = QVBoxLayout()
layout.addWidget(self.tableview)
self.setLayout(layout)
if __name__ == '__main__':
app = QApplication(sys.argv)
table = TableView()
table.show()
sys.exit(app.exec_()) | UTF-8 | Python | false | false | 5,199 | py | 14 | tableview.py | 13 | 0.689904 | 0.667288 | 0 | 122 | 34.163934 | 97 |
kyouko-taiga/yaffel-py | 12,747,462,961,337 | e2b1cf73100f75080da510de5c28a40fd31bcf78 | 6bd914f982930b20ebe36753959e2061ba1bffbf | /yaffel/exceptions.py | 0d63745e9c5da51d16788f707b9daf7a994bb61a | [
"Apache-2.0"
]
| permissive | https://github.com/kyouko-taiga/yaffel-py | 7d214855f2f277088b93216d0d0ff94664c32b29 | e663c2dd61a147a238c9d8c6524eb228dda79994 | refs/heads/master | 2016-08-04T07:47:12.951070 | 2015-04-09T13:54:29 | 2015-04-09T13:54:29 | 20,404,076 | 0 | 0 | null | null | null | null | null | null | null | null | null | null | null | null | null | # This source file is part of yaffel-py
# Main Developer : Dimitri Racordon (kyouko.taiga@gmail.com)
#
# Copyright 2014 Dimitri Racordon
#
# Licensed under the Apache License, Version 2.0 (the "License");
# you may not use this file except in compliance with the License.
# You may obtain a copy of the License at
#
# http://www.apache.org/licenses/LICENSE-2.0
#
# Unless required by applicable law or agreed to in writing, software
# distributed under the License is distributed on an "AS IS" BASIS,
# WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
# See the License for the specific language governing permissions and
# limitations under the License.
__all__ = ['EvaluationError', 'InvalidExpressionError', 'UnboundValueError']
class EvaluationError(Exception):
def __init__(self, message):
Exception.__init__(self, message)
class InvalidExpressionError(EvaluationError):
def __init__(self, message):
Exception.__init__(self, message)
class UnboundValueError(EvaluationError):
def __init__(self, message):
super().__init__(message)
| UTF-8 | Python | false | false | 1,102 | py | 7 | exceptions.py | 6 | 0.729583 | 0.722323 | 0 | 30 | 35.733333 | 76 |
Lee8150951/Python-Learning | 7,859,790,179,925 | c3aefa38c2c66c8f1bf9f52caa0ff8856f226011 | 88c868ef54bfac6a654d68a593ef0c10a8ec877c | /day07/02-Parameter.py | 2a2b295a18749662b1179244567943a0100cfcde | []
| no_license | https://github.com/Lee8150951/Python-Learning | 83ea946760dbcc3853b7362f6c35cf0edf8c8d7e | 79b85116d10f3b4abfab5e9ec13839d66651d0ab | refs/heads/master | 2023-02-02T10:31:42.715788 | 2020-12-20T07:06:24 | 2020-12-20T07:06:24 | 320,474,416 | 1 | 0 | null | null | null | null | null | null | null | null | null | null | null | null | null | # P122练习
# 练习8-3
def make_shirt_1(size, string):
print(f"Size:\"{size}\";String:\"{string}\"")
make_shirt_1(string = 'Python', size = 'L')
# 练习8-4
def make_shirt_2(string = 'Python'):
print(f"I love {string}")
make_shirt_2()
make_shirt_2("JavaScript")
# 练习8-5
def describe_city(city = 'Shanghai', country = 'China'):
print(f"{city.title()} is in {country.title()}.")
describe_city()
describe_city('New York', 'the U.S.A')
describe_city('Tokyo', 'Japan') | UTF-8 | Python | false | false | 481 | py | 37 | 02-Parameter.py | 35 | 0.634409 | 0.604301 | 0 | 16 | 28.125 | 56 |
melvinlim/bjcount | 19,327,352,841,019 | 65ffe117e6a5d40a9f50dffb807557872cb14db5 | cde3651297a58b7ab081735813dc68a5d7551a76 | /settings.py | 3706a96a5ca0bc4f4fd652a06841838bc6858b79 | []
| no_license | https://github.com/melvinlim/bjcount | 35dc75bee8da36f5faf43ac01558e2f697458da9 | ce74644147e9781e4f42dee6b5b9a96a21c1a90c | refs/heads/master | 2021-08-24T07:47:33.280848 | 2017-12-08T18:14:44 | 2017-12-08T18:14:44 | 112,386,872 | 0 | 0 | null | null | null | null | null | null | null | null | null | null | null | null | null | class Settings(object):
def __init__(self,canSitOut=False,alwaysTakeInsurance=False,modifiedStrategy=False,simplifiedStrategy=False,allowSurrender=False,allowDouble=True):
self.canSitOut=canSitOut
self.alwaysTakeInsurance=alwaysTakeInsurance
self.modifiedStrategy=modifiedStrategy
self.simplifiedStrategy=simplifiedStrategy
self.allowSurrender=allowSurrender
self.allowDouble=allowDouble
| UTF-8 | Python | false | false | 401 | py | 8 | settings.py | 8 | 0.857855 | 0.857855 | 0 | 8 | 49.125 | 148 |
duanegtr/tl-cogs | 15,556,371,583,678 | 01117fe89293b683f3145825d89b600bc0fb82bf | 1bd4719cd26fa9fcd008caea225018d3c18e4edb | /welcomer/__init__.py | 205e5e7c64a9a20b43ed1f0316cb87551cfee84b | [
"MIT"
]
| permissive | https://github.com/duanegtr/tl-cogs | 37fc5be8a8d99b39f77e0a7e80f40337627bb612 | ffde1452a75ad42b4f6511b612ce486e96fcd6de | refs/heads/master | 2023-09-04T15:28:42.238702 | 2021-11-05T22:48:02 | 2021-11-05T22:48:02 | 291,639,185 | 3 | 4 | MIT | true | 2021-04-25T05:54:36 | 2020-08-31T06:57:17 | 2021-04-19T08:41:24 | 2021-04-25T05:54:35 | 1,749 | 2 | 4 | 0 | Python | false | false | from .welcomer import Welcomer
async def setup(bot):
cog = Welcomer(bot=bot)
await cog.crtoken()
await cog.load_menu_module()
bot.add_cog(cog) | UTF-8 | Python | false | false | 159 | py | 114 | __init__.py | 81 | 0.679245 | 0.679245 | 0 | 7 | 21.857143 | 32 |
fagan2888/Geoquery-project | 14,207,751,816,894 | 3163998a6950ca33322ff0dc6b694741509fd2b0 | 0634b0057d18627b20756f6a4ebdbe672d40938b | /source/test.py | a4c416f46c7c91ad906930f57f88e3b359ac36aa | []
| no_license | https://github.com/fagan2888/Geoquery-project | 5fc99f6a3eb3eb45d7410fd0af74200ad9569f42 | 399dcb45de35f6bbcaa609ff19f91fcde6e8b920 | refs/heads/master | 2022-04-23T02:53:10.245617 | 2020-04-12T11:17:29 | 2020-04-12T11:17:29 | null | 0 | 0 | null | null | null | null | null | null | null | null | null | null | null | null | null | # from reportlab.pdfgen import canvas
# from reportlab.lib.pagesizes import A4, letter
# import os
# import webbrowser
# import seaborn as sns
# from folium.plugins import FastMarkerCluster
# import folium
#
#
#
# def mapa(df):
# latlong = df[['lat', 'lng']]
# mi = folium.Map(location=latlong, zoom_start=16, control_scale=True)
# folium.Marker(location=latlong,
# popup='This seems to be a good area to place your bar',
# icon=folium.Icon(color='blue', icon='glyphicon glyphicon-star-empty'), ).add_to(mi)
# folium.Circle(location=latlong, radius=500, color='blue', fill=True, fill_color='blue').add_to(mi)
# minimap = FastMarkerCluster(latlong).add_to(mi)
# mi.add_child(minimap)
# mi.save('../pdf/my_bar.html')
# return webbrowser.open('file://' + os.path.realpath('my_bar.html'))
#
#
# mapa(top500)
#PDF creator structure
# def shortpdf (name):
# ancho, alto=A4 # ancho y alto de la pagina, en dinA4, es una tupla en puntos (un punto=1/72 pulgadas)
# archivo ='path'.format(yea)
# # c=canvas.Canvas('path'.format(yea), pagesize=A4) # genera el archivo pdf vacio, con tamaño dinA4
# # c.setStrokeColorRGB(0.7, 0.7, 0.7)
# # c.setStrokeColorRGB(0.7, 0.7, 0.7)
# # c.setFont("{}-Bold".format(font), 24)
# # c.drawString(150, alto-50, "text") # escribe con margen de 50 puntos
# # c.setFont('{}-BoldOblique'.format(font), 10)
# # c.drawString(20, 20, "text")
# # c.drawRightString(ancho-30, 20, name)
# # c.setFont("{}-Bold".format(font), 20)
# # c.drawCentredString(round(ancho/2), alto-80, "text".format(yea))
# # c.drawImage("path.jpg", 0, alto-100, width=100, height=100)
# asd = c.drawImage("path.png", ancho-100, alto-100, width=75, height=75)
# x=0
# y=alto-100
# c.setLineWidth(3)
# c.setStrokeGray(0)
# # c.line(x, y, ancho, y)
# # c.setFont('Times-Roman', 12)
# # c.drawString(100, alto-155, " text ")
# # c.drawString(100, alto-168, " text")
# # c.drawImage(path3, 70, alto - 440, width=450, height=250)
# # c.drawString(100, alto-480, " text")
# # c.drawImage(path4, 70, alto - 750, width=450, height=250)
# # c.setLineWidth(1)
# #c.line(0, 50, ancho, 50)
# # c.setFont('{}-Bold'.format(font), 10)
# # c.drawCentredString(round(ancho/2), 20, "1/1")
# c.showPage()
# c.save()
# return asd
#
# a = shortpdf ('alejandro') | UTF-8 | Python | false | false | 2,456 | py | 1 | test.py | 1 | 0.608961 | 0.553971 | 0 | 77 | 30.896104 | 114 |
Subsets and Splits
No community queries yet
The top public SQL queries from the community will appear here once available.