blob_id
stringlengths
40
40
directory_id
stringlengths
40
40
path
stringlengths
3
288
content_id
stringlengths
40
40
detected_licenses
listlengths
0
112
license_type
stringclasses
2 values
repo_name
stringlengths
5
115
snapshot_id
stringlengths
40
40
revision_id
stringlengths
40
40
branch_name
stringclasses
684 values
visit_date
timestamp[us]date
2015-08-06 10:31:46
2023-09-06 10:44:38
revision_date
timestamp[us]date
1970-01-01 02:38:32
2037-05-03 13:00:00
committer_date
timestamp[us]date
1970-01-01 02:38:32
2023-09-06 01:08:06
github_id
int64
4.92k
681M
star_events_count
int64
0
209k
fork_events_count
int64
0
110k
gha_license_id
stringclasses
22 values
gha_event_created_at
timestamp[us]date
2012-06-04 01:52:49
2023-09-14 21:59:50
gha_created_at
timestamp[us]date
2008-05-22 07:58:19
2023-08-21 12:35:19
gha_language
stringclasses
147 values
src_encoding
stringclasses
25 values
language
stringclasses
1 value
is_vendor
bool
2 classes
is_generated
bool
2 classes
length_bytes
int64
128
12.7k
extension
stringclasses
142 values
content
stringlengths
128
8.19k
authors
listlengths
1
1
author_id
stringlengths
1
132
b7bbd0cff4f44ec86ea0f1751469f76ffbf8a50f
24c84c5b93cd816976d370a99982f45e0d18a184
/BitManipulation/XRaiseToPowerN.py
59807df6c254cb11dc951ae81be87470bc2be99a
[]
no_license
purushottamkaushik/DataStructuresUsingPython
4ef1cf33f1af3fd25105a45be4f179069e327628
e016fe052c5600dcfbfcede986d173b401ed23fc
refs/heads/master
2023-03-12T13:25:18.186446
2021-02-28T18:21:37
2021-02-28T18:21:37
343,180,450
0
0
null
null
null
null
UTF-8
Python
false
false
775
py
class Solution1: def myPow(self, x,n): return x ** (n) # Time limit Exceeded Solution # # class Solution: # def myPow(self, x: float, n: int) -> float: # # if n < 0: # n = -n # x = 1 / x # # val = 1 # for j in range(1, n + 1): # val *= x # return val class Solution: def fastPow(self, x, n): if n == 0: return 1.0 A = self.fastPow(x, n / 2) if n % 2 == 0: return A * A else: return A * A * x def myPow(self, x: float, n: int) -> float: if n < 0: x = 1 / x n = -n return self.fastPow(x, n) s = Solution() print(s.myPow(2,10))
[ "purushottamkaushik96@gmail.com" ]
purushottamkaushik96@gmail.com
3f2ebca3033b0e9b6e0594a4e024b17269235a58
44064ed79f173ddca96174913910c1610992b7cb
/Second_Processing_app/temboo/Library/Zendesk/Users/CreateManyUsers.py
7f4fbc8aa21e3fc4e42b3c6633ea77278bf1c34c
[]
no_license
dattasaurabh82/Final_thesis
440fb5e29ebc28dd64fe59ecd87f01494ed6d4e5
8edaea62f5987db026adfffb6b52b59b119f6375
refs/heads/master
2021-01-20T22:25:48.999100
2014-10-14T18:58:00
2014-10-14T18:58:00
null
0
0
null
null
null
null
UTF-8
Python
false
false
3,051
py
# -*- coding: utf-8 -*- ############################################################################### # # CreateManyUsers # Creates many new users at one time. # # Python version 2.6 # ############################################################################### from temboo.core.choreography import Choreography from temboo.core.choreography import InputSet from temboo.core.choreography import ResultSet from temboo.core.choreography import ChoreographyExecution import json class CreateManyUsers(Choreography): def __init__(self, temboo_session): """ Create a new instance of the CreateManyUsers Choreo. A TembooSession object, containing a valid set of Temboo credentials, must be supplied. """ Choreography.__init__(self, temboo_session, '/Library/Zendesk/Users/CreateManyUsers') def new_input_set(self): return CreateManyUsersInputSet() def _make_result_set(self, result, path): return CreateManyUsersResultSet(result, path) def _make_execution(self, session, exec_id, path): return CreateManyUsersChoreographyExecution(session, exec_id, path) class CreateManyUsersInputSet(InputSet): """ An InputSet with methods appropriate for specifying the inputs to the CreateManyUsers Choreo. The InputSet object is used to specify input parameters when executing this Choreo. """ def set_Email(self, value): """ Set the value of the Email input for this Choreo. ((required, string) The email address you use to login to your Zendesk account.) """ InputSet._set_input(self, 'Email', value) def set_Password(self, value): """ Set the value of the Password input for this Choreo. ((required, password) Your Zendesk password.) """ InputSet._set_input(self, 'Password', value) def set_Server(self, value): """ Set the value of the Server input for this Choreo. ((required, string) Your Zendesk domain and subdomain (e.g., temboocare.zendesk.com).) """ InputSet._set_input(self, 'Server', value) def set_Users(self, value): """ Set the value of the Users input for this Choreo. ((required, json) A JSON-formatted string containing an array of user properties you wish to set.) """ InputSet._set_input(self, 'Users', value) class CreateManyUsersResultSet(ResultSet): """ A ResultSet with methods tailored to the values returned by the CreateManyUsers Choreo. The ResultSet object is used to retrieve the results of a Choreo execution. """ def getJSONFromString(self, str): return json.loads(str) def get_Response(self): """ Retrieve the value for the "Response" output from this Choreo execution. ((json) ) """ return self._output.get('Response', None) class CreateManyUsersChoreographyExecution(ChoreographyExecution): def _make_result_set(self, response, path): return CreateManyUsersResultSet(response, path)
[ "dattasaurabh82@gmail.com" ]
dattasaurabh82@gmail.com
c9d1642bef0822ea1d0d53275ff38258fec6c343
a7cb6aa4605e6cb8387858e270e051b5cb5c95b6
/nagaram/anagrams.py
04c657f2aba07d717599c1bea0f9488d5486f23e
[ "BSD-3-Clause" ]
permissive
a-tal/nagaram
6a41322762d5746b14c13e46b116b6b5f6fdd2e9
2edcb0ef8cb569ebd1c398be826472b4831d6110
refs/heads/master
2020-06-08T05:00:45.766688
2018-03-10T18:18:12
2018-03-10T18:18:12
8,365,790
1
2
BSD-3-Clause
2018-03-10T18:18:31
2013-02-22T20:59:43
Python
UTF-8
Python
false
false
1,632
py
"""Anagram finding functions.""" from nagaram.scrabble import blank_tiles, word_list, word_score def _letter_map(word): """Creates a map of letter use in a word. Args: word: a string to create a letter map from Returns: a dictionary of {letter: integer count of letter in word} """ lmap = {} for letter in word: try: lmap[letter] += 1 except KeyError: lmap[letter] = 1 return lmap def anagrams_in_word(word, sowpods=False, start="", end=""): """Finds anagrams in word. Args: word: the string to base our search off of sowpods: boolean to declare TWL or SOWPODS words file start: a string of starting characters to find anagrams based on end: a string of ending characters to find anagrams based on Yields: a tuple of (word, score) that can be made with the input_word """ input_letters, blanks, questions = blank_tiles(word) for tile in start + end: input_letters.append(tile) for word in word_list(sowpods, start, end): lmap = _letter_map(input_letters) used_blanks = 0 for letter in word: if letter in lmap: lmap[letter] -= 1 if lmap[letter] < 0: used_blanks += 1 if used_blanks > (blanks + questions): break else: used_blanks += 1 if used_blanks > (blanks + questions): break else: yield (word, word_score(word, input_letters, questions))
[ "github@talsma.ca" ]
github@talsma.ca
1ac752b254b2f46452b83ae611dadec6e8478300
9e0105505f4746d5872090885df6064ad772b3e5
/utils/modules.py
12888a8c8e2c06fb3dc18dd68c7e1eeed327cf99
[]
no_license
wwwbq/PyTorch_YOLOv1
568afa4f8f508dabd9bcb35404a634985bf4a8ae
2e86c64577e24193b117582c07a4941c2eeba8cc
refs/heads/main
2023-08-08T00:08:42.466820
2021-09-13T06:25:09
2021-09-13T06:25:09
null
0
0
null
null
null
null
UTF-8
Python
false
false
918
py
import torch import torch.nn as nn import torch.nn.functional as F class Conv(nn.Module): def __init__(self, c1, c2, k, s=1, p=0, d=1, g=1, act=True): super(Conv, self).__init__() self.convs = nn.Sequential( nn.Conv2d(c1, c2, k, stride=s, padding=p, dilation=d, groups=g), nn.BatchNorm2d(c2), nn.LeakyReLU(0.1, inplace=True) if act else nn.Identity() ) def forward(self, x): return self.convs(x) class SPP(nn.Module): """ Spatial Pyramid Pooling """ def __init__(self): super(SPP, self).__init__() def forward(self, x): x_1 = torch.nn.functional.max_pool2d(x, 5, stride=1, padding=2) x_2 = torch.nn.functional.max_pool2d(x, 9, stride=1, padding=4) x_3 = torch.nn.functional.max_pool2d(x, 13, stride=1, padding=6) x = torch.cat([x, x_1, x_2, x_3], dim=1) return x
[ "1394571815@qq.com" ]
1394571815@qq.com
cf1bd1863d3f53e5ecd17372f8353719846f99e0
3d19e1a316de4d6d96471c64332fff7acfaf1308
/Users/M/michiko3/my_scraper_-_michiko.py
051a46dfb17a94145b5b97a6695f80da14f2f70c
[]
no_license
BerilBBJ/scraperwiki-scraper-vault
4e98837ac3b1cc3a3edb01b8954ed00f341c8fcc
65ea6a943cc348a9caf3782b900b36446f7e137d
refs/heads/master
2021-12-02T23:55:58.481210
2013-09-30T17:02:59
2013-09-30T17:02:59
null
0
0
null
null
null
null
UTF-8
Python
false
false
3,276
py
import scraperwiki from bs4 import BeautifulSoup html = scraperwiki.scrape("http://usatoday30.usatoday.com/money/economy/housing/2009-02-11-decline-housing-foreclosure_N.htm") soup = BeautifulSoup(html) print soup.prettify() print soup.find_all("table") print len(soup.find_all("table")) tables = soup.find_all("table", {"border" : "0", "cellspacing": "1", "cellpadding": "2"}) print len(tables) print tables for table in tables: for row in table.find_all('tr'): for cell in row.find_all("td"): print cell.get_text().strip() rows = tables[1].find_all('tr') for row in rows: for cell in row.find_all("td"): print cell.get_text().strip() for row in rows: cells = row.find_all("td") print "there are", len(cells), "in this row" print "zero", cells[0] for row in rows: cells = row.find_all("td") print "there are", len(cells), "cells in this row" if len(cells) > 5: print "rank", cells[0].get_text().strip() print "state", cells[1].get_text().strip() print 'total_filings', cells[2].get_text().strip() print '1_per_x' , cells[3].get_text().strip() for row in rows: cells = row.find_all("td") if len(cells) > 5: data = { 'rank' : cells[0].get_text().strip(), 'state' : cells[1].get_text().strip(), 'total_filings' : cells[2].get_text().strip(), '1_per_x' : cells[3].get_text().strip(), 'change_dec_jan' : cells[4].get_text().strip(), 'change_jan08' : cells[5].get_text().strip() } scraperwiki.sqlite.save(unique_keys=['state'],data=data)import scraperwiki from bs4 import BeautifulSoup html = scraperwiki.scrape("http://usatoday30.usatoday.com/money/economy/housing/2009-02-11-decline-housing-foreclosure_N.htm") soup = BeautifulSoup(html) print soup.prettify() print soup.find_all("table") print len(soup.find_all("table")) tables = soup.find_all("table", {"border" : "0", "cellspacing": "1", "cellpadding": "2"}) print len(tables) print tables for table in tables: for row in table.find_all('tr'): for cell in row.find_all("td"): print cell.get_text().strip() rows = tables[1].find_all('tr') for row in rows: for cell in row.find_all("td"): print cell.get_text().strip() for row in rows: cells = row.find_all("td") print "there are", len(cells), "in this row" print "zero", cells[0] for row in rows: cells = row.find_all("td") print "there are", len(cells), "cells in this row" if len(cells) > 5: print "rank", cells[0].get_text().strip() print "state", cells[1].get_text().strip() print 'total_filings', cells[2].get_text().strip() print '1_per_x' , cells[3].get_text().strip() for row in rows: cells = row.find_all("td") if len(cells) > 5: data = { 'rank' : cells[0].get_text().strip(), 'state' : cells[1].get_text().strip(), 'total_filings' : cells[2].get_text().strip(), '1_per_x' : cells[3].get_text().strip(), 'change_dec_jan' : cells[4].get_text().strip(), 'change_jan08' : cells[5].get_text().strip() } scraperwiki.sqlite.save(unique_keys=['state'],data=data)
[ "pallih@kaninka.net" ]
pallih@kaninka.net
6074ebb5ed259550f2ca5a4e5800871b45257c7e
87f94560837a93963b1610457f27cd9adc34e538
/2018/3/main.py
4aa7d0bcf7fb488e7c4caffb3bb5c404e64271d0
[]
no_license
Coul33t/AdventOfCode
3f511a71f48fcff3738a6e905e711a68f32fad62
f1443888cde4043f21d286449f2660f1c722e571
refs/heads/master
2020-04-09T09:38:05.351225
2018-12-04T15:09:09
2018-12-04T15:09:09
160,240,608
0
0
null
null
null
null
UTF-8
Python
false
false
1,557
py
import pdb import re def rect_overlaps(rect1, rect2): # 1 = top left x # 2 = top left y # 3 = width # 4 = height # top_right.x = rect[1] + rect[3] # bottom_left.x = rect[1] # top_right.y = rect[2] # bottom_left.y = rect[2] + rect[4] return not (rect1[1] + rect1[3] < rect2[1] or rect1[1] > rect2[1] + rect2[3] or rect1[2] > rect2[2] + rect2[4] or rect1[2] + rect1[4] < rect2[2]) def overlapping2(data): overlaps_matrix = [[0 for y in range(len(data))] for x in range(len(data))] for i in range(len(data)): for j in range(len(data)): if i != j and rect_overlaps(data[i], data[j]): overlaps_matrix[i][j] += 1 if sum(overlaps_matrix[i]) == 0: return data[i][0] def overlapping(data): max_width = max([x[1] + x[3] for x in data]) max_height = max([x[2] + x[4] for x in data]) canvas = [[0 for y in range(max_width)] for x in range(max_height)] for claim in data: for x in range(claim[2], claim[2] + claim[4]): for y in range(claim[1], claim[1] + claim[3]): canvas[x][y] += 1 return sum(sum(i > 1 for i in row) for row in canvas) if __name__ == '__main__': with open ('input.txt', 'r') as input_file: data = input_file.read().split('\n') for i in range(len(data)): data[i] = [int(x) for x in re.findall(r'(\d+)', data[i])] print(overlapping(data)) print(overlapping2(data))
[ "Coulis1990@gmail.com" ]
Coulis1990@gmail.com
ab9e2100dc7cda13e45967def14d034a68096bb4
9680ba23fd13b4bc0fc3ce0c9f02bb88c6da73e4
/Bernd Klein (520) ile Python/p_20708x.py
4d2b0d69e9c9930d9ace4529711b5a71b43f8e75
[]
no_license
mnihatyavas/Python-uygulamalar
694091545a24f50a40a2ef63a3d96354a57c8859
688e0dbde24b5605e045c8ec2a9c772ab5f0f244
refs/heads/master
2020-08-23T19:12:42.897039
2020-04-24T22:45:22
2020-04-24T22:45:22
216,670,169
0
0
null
null
null
null
ISO-8859-9
Python
false
false
7,413
py
# coding:iso-8859-9 Türkçe # p_20708x.py: Orijinal Grafik sınıfı ve metodlarının alt-örneği. class Graph(object): def __init__(self, graph_dict=None): """ initializes a graph object If no dictionary or None is given, an empty dictionary will be used """ if graph_dict == None: graph_dict = {} self.__graph_dict = graph_dict def vertices(self): """ returns the vertices of a graph """ return list(self.__graph_dict.keys()) def edges(self): """ returns the edges of a graph """ return self.__generate_edges() def add_vertex(self, vertex): """ If the vertex "vertex" is not in self.__graph_dict, a key "vertex" with an empty list as a value is added to the dictionary. Otherwise nothing has to be done. """ if vertex not in self.__graph_dict: self.__graph_dict[vertex] = [] def add_edge(self, edge): """ assumes that edge is of type set, tuple or list; between two vertices can be multiple edges! """ edge = set(edge) vertex1 = edge.pop() if edge: # not a loop vertex2 = edge.pop() else: # a loop vertex2 = vertex1 if vertex1 in self.__graph_dict: self.__graph_dict[vertex1].append(vertex2) else: self.__graph_dict[vertex1] = [vertex2] def __generate_edges(self): """ A static method generating the edges of the graph "graph". Edges are represented as sets with one (a loop back to the vertex) or two vertices """ edges = [] for vertex in self.__graph_dict: for neighbour in self.__graph_dict[vertex]: if {neighbour, vertex} not in edges: edges.append({vertex, neighbour}) return edges def __str__(self): res = "vertices: " for k in self.__graph_dict: res += str(k) + " " res += "\nedges: " for edge in self.__generate_edges(): res += str(edge) + " " return res def find_isolated_vertices(self): """ returns a list of isolated vertices. """ graph = self.__graph_dict isolated = [] for vertex in graph: print(isolated, vertex) if not graph[vertex]: isolated += [vertex] return isolated def find_path(self, start_vertex, end_vertex, path=[]): """ find a path from start_vertex to end_vertex in graph """ graph = self.__graph_dict path = path + [start_vertex] if start_vertex == end_vertex: return path if start_vertex not in graph: return None for vertex in graph[start_vertex]: if vertex not in path: extended_path = self.find_path(vertex, end_vertex, path) if extended_path: return extended_path return None def find_all_paths(self, start_vertex, end_vertex, path=[]): """ find all paths from start_vertex to end_vertex in graph """ graph = self.__graph_dict path = path + [start_vertex] if start_vertex == end_vertex: return [path] if start_vertex not in graph: return [] paths = [] for vertex in graph[start_vertex]: if vertex not in path: extended_paths = self.find_all_paths(vertex, end_vertex, path) for p in extended_paths: paths.append(p) return paths def is_connected(self, vertices_encountered = None, start_vertex=None): """ determines if the graph is connected """ if vertices_encountered is None: vertices_encountered = set() gdict = self.__graph_dict vertices = list(gdict.keys()) # "list" necessary in Python 3 if not start_vertex: # chosse a vertex from graph as a starting point start_vertex = vertices[0] vertices_encountered.add(start_vertex) if len(vertices_encountered) != len(vertices): for vertex in gdict[start_vertex]: if vertex not in vertices_encountered: if self.is_connected(vertices_encountered, vertex): return True else: return True return False def vertex_degree(self, vertex): """ The degree of a vertex is the number of edges connecting it, i.e. the number of adjacent vertices. Loops are counted double, i.e. every occurence of vertex in the list of adjacent vertices. """ adj_vertices = self.__graph_dict[vertex] degree = len(adj_vertices) + adj_vertices.count(vertex) return degree def degree_sequence(self): """ calculates the degree sequence """ seq = [] for vertex in self.__graph_dict:seq.append(self.vertex_degree(vertex)) seq.sort(reverse=True) return tuple(seq) @staticmethod def is_degree_sequence(sequence): """ Method returns True, if the sequence "sequence" is a degree sequence, i.e. a non-increasing sequence. Otherwise False is returned. """ # check if the sequence sequence is non-increasing: return all( x>=y for x, y in zip(sequence, sequence[1:])) def delta(self): """ the minimum degree of the vertices """ min = 100000000 for vertex in self.__graph_dict: vertex_degree = self.vertex_degree(vertex) if vertex_degree < min: min = vertex_degree return min def Delta(self): """ the maximum degree of the vertices """ max = 0 for vertex in self.__graph_dict: vertex_degree = self.vertex_degree(vertex) if vertex_degree > max: max = vertex_degree return max def density(self): """ method to calculate the density of a graph """ g = self.__graph_dict V = len(g.keys()) E = len(self.edges()) return 2.0 * E / (V *(V - 1)) def diameter(self): """ calculates the diameter of the graph """ v = self.vertices() pairs = [ (v[i],v[j]) for i in range(len(v)) for j in range(i+1, len(v)-1)] smallest_paths = [] for (s,e) in pairs: paths = self.find_all_paths(s,e) smallest = sorted(paths, key=len)[0] smallest_paths.append(smallest) smallest_paths.sort(key=len) # longest path is at the end of list, # i.e. diameter corresponds to the length of this path diameter = len(smallest_paths[-1]) - 1 return diameter @staticmethod def erdoes_gallai(dsequence): """ Checks if the condition of the Erdoes-Gallai inequality is fullfilled """ if sum(dsequence) % 2: # sum of sequence is odd return False if Graph.is_degree_sequence(dsequence): for k in range(1,len(dsequence) + 1): left = sum(dsequence[:k]) right = k * (k-1) + sum([min(x,k) for x in dsequence[k:]]) if left > right:return False else: # sequence is increasing return False return True
[ "noreply@github.com" ]
mnihatyavas.noreply@github.com
0e45c65d4c67c931afc4e85b7410cb8b62d4c595
9adc45c39030d1109849c211afd294b4d33f660c
/example/scripts/upload_video_to_s3_and_sync.py
321e2e91ad4f767a025163b98ac0c20532904674
[ "MIT" ]
permissive
jf-parent/brome
f12e728b984061e3c329f30d59f9d615ffe0a1f2
784f45d96b83b703dd2181cb59ca8ea777c2510e
refs/heads/release
2020-12-28T14:45:53.428910
2017-05-05T12:32:44
2017-05-05T12:32:44
38,472,866
3
0
null
2017-05-05T12:32:45
2015-07-03T05:02:09
Python
UTF-8
Python
false
false
2,713
py
#! /usr/bin/env python import os import boto3 import yaml from brome.core.utils import DbSessionContext from brome.model.testinstance import Testinstance from brome.model.testcrash import Testcrash from brome.model.testresult import Testresult HERE = os.path.abspath(os.path.dirname(__file__)) ROOT = os.path.join(HERE, '..') s3 = boto3.resource('s3') brome_config_path = os.path.join(ROOT, "config", "brome.yml") with open(brome_config_path) as fd: config = yaml.load(fd) DB_NAME = config['database']['mongo_database_name'] BUCKET_NAME = config['database']['s3_bucket_name'] ROOT_TB_RESULTS = config['project']['test_batch_result_path'] with DbSessionContext(DB_NAME) as session: # fetch test instance that has their video in local test_instance_list = session.query(Testinstance)\ .filter(Testinstance.video_location == 'local')\ .filter(Testinstance.video_capture_path != '')\ .all() for test_instance in test_instance_list: # upload the video to s3 file_path = os.path.join( ROOT_TB_RESULTS, test_instance.video_capture_path ) try: data = open(file_path, 'rb') except FileNotFoundError: print('{file_path} not found'.format(file_path=file_path)) continue print('[*]Uploading {file_path} to s3...'.format(file_path=file_path)) s3.Bucket(BUCKET_NAME).put_object( Key=test_instance.video_capture_path, Body=data ) remote_file_name = \ 'https://s3-us-west-2.amazonaws.com/{bucket}/{path}' \ .format( bucket=BUCKET_NAME, path=test_instance.video_capture_path ) # set the video_location to s3 test_instance.video_location = 's3' test_instance.video_capture_path = remote_file_name session.save(test_instance, safe=True) # Test Crash test_crash_list = session.query(Testcrash)\ .filter(Testcrash.test_instance_id == test_instance.mongo_id)\ .all() for test_crash in test_crash_list: test_crash.video_capture_path = remote_file_name test_crash.video_location = 's3' session.save(test_crash, safe=True) # Test Result test_result_list = session.query(Testresult)\ .filter(Testresult.test_instance_id == test_instance.mongo_id)\ .all() for test_result in test_result_list: test_result.video_capture_path = remote_file_name test_result.video_location = 's3' session.save(test_result, safe=True) os.remove(file_path) print('Done')
[ "parent.j.f@gmail.com" ]
parent.j.f@gmail.com
ea52af8e78e10745bd9ade47d2ab923070e1488d
41ad3529ff9b6357d57468641b21d4ac02a6c0b5
/DJI_wxPython.py
446cff5dda74c28d7be7f1d217ff7ced444f789c
[]
no_license
gitpNser/learndata
9153a3c305cf07904d5006059489c72c2388cee0
a5059ae3346a17b833132e9295a0e73482b4a386
refs/heads/master
2020-06-13T11:25:56.676610
2019-11-28T14:47:43
2019-11-28T14:47:43
194,638,488
0
0
null
null
null
null
UTF-8
Python
false
false
6,694
py
# -*- coding: utf-8 -*- """ Created on Wed Aug 14 13:51:41 2019 wxPython plot @author: pNser copy Dazhuang @NJU """ import datetime as dt import myfinance as finance import matplotlib.pyplot as plt import pandas as pd import _thread as thread import wx #不明白这行的目的 ID_EVENT_REFRESH = 9999 #定义一个wx.Frame的子类 class StockFrame(wx.Frame): #定义选择框的初始状态 option_list = {'open':True,'close':True,'high':False,'low':False,'volume':False} def __init__(self,title): wx.Frame.__init__(self,None,title=title,size=(430,600)) #创建状态栏 self.CreateStatusBar() #创建菜单栏,菜单栏文字 menuBar = wx.MenuBar() filemenu = wx.Menu() menuBar.Append(filemenu,"&File") #增加“Refresh”菜单以及在状态栏说明文字,绑定方法 menuRefresh = filemenu.Append(ID_EVENT_REFRESH,"&Refresh","Refresh the price") self.Bind(wx.EVT_MENU,self.OnRefresh,menuRefresh) #增加“Quit”菜单以及在状态栏说明文字,绑定方法 menuQuit = filemenu.Append(wx.ID_EXIT,"&Quit","Terminate the program") self.Bind(wx.EVT_MENU,self.OnQuit,menuQuit) #菜单栏子项设置完成后完成菜单栏设定 self.SetMenuBar(menuBar) #创建panel panel = wx.Panel(self) #创建股票代码(code)文本框sizer,水平放置 codeSizer = wx.BoxSizer(wx.HORIZONTAL) #静态文字标签,在codesizer中加入标签位置下对齐 labelText = wx.StaticText(panel,label="Stock Code:") codeSizer.Add(labelText,0,wx.ALIGN_BOTTOM) #TODO: need a better way yo put a spacer here than this: #codeSizer.Add((10,10)) #文本框,初始值“BA”,出发回车键响应 codeText = wx.TextCtrl(panel,value="BA",style=wx.TE_PROCESS_ENTER) #绑定回车键方法到Event上 self.Bind(wx.EVT_TEXT_ENTER,self.OnTextSubmitted,codeText) #codesizer中增加文本框位置 codeSizer.Add(codeText) #创建optionsizer,水平放置 optionSizer = wx.BoxSizer(wx.HORIZONTAL) #增加check event的方法,并在optionsizer中增加checkbox位置 for key, value in self.option_list.items(): checkBox = wx.CheckBox(panel,label=key.title()) checkBox.SetValue(value) self.Bind(wx.EVT_CHECKBOX,self.OnChecked) optionSizer.Add(checkBox) #增加列表,report类型 self.list = wx.ListCtrl(panel,wx.NewId(),style=wx.LC_REPORT) #执行createHeaer程序 self.createHeader() #增加list显示内容,对列表内双击事件绑定方法 pos = self.list.InsertItem(0,"__") self.list.SetItem(pos,1,"loading...") self.list.SetItem(pos,2,"__") self.Bind(wx.EVT_LIST_ITEM_ACTIVATED,self.OnDoubleClick,self.list) #增加ctrlsizer ctrlSizer = wx.BoxSizer(wx.HORIZONTAL) ctrlSizer.Add((10,10)) #增加退出按钮及刷新按钮,分别绑定方法及放置位置 buttonQuit = wx.Button(panel,-1,"Quit") self.Bind(wx.EVT_BUTTON,self.OnQuit,buttonQuit) ctrlSizer.Add(buttonQuit,1) buttonRefresh = wx.Button(panel,-1,"Refresh") self.Bind(wx.EVT_BUTTON,self.OnRefresh,buttonRefresh) ctrlSizer.Add(buttonRefresh,1,wx.LEFT|wx.BOTTOM) #设置一个总的sizer,垂直方式,然后将其他子sizer放入 sizer = wx.BoxSizer(wx.VERTICAL) sizer.Add(codeSizer,0,wx.ALL,5) sizer.Add(optionSizer,0,wx.ALL,5) sizer.Add(self.list,-1,wx.ALL | wx.EXPAND,5) sizer.Add(ctrlSizer,0,wx.ALIGN_BOTTOM) #最终整理sizer panel.SetSizerAndFit(sizer) self.Center() #start to load data right after the window omes up self.OnRefresh(None) #创建list表头 def createHeader(self): self.list.InsertColumn(0,"Symbol") self.list.InsertColumn(1,"Name") self.list.InsertColumn(2,"Last Trade") #list里面增加数据 def setData(self,data): self.list.ClearAll() self.createHeader() pos = 0 for row in data: pos = self.list.InsertItem(pos+1,row['code']) self.list.SetItem(pos,1,row['name']) self.list.SetColumnWidth(1,-1) self.list.SetItem(pos,2,str(row['price'])) if pos%2 == 0: #set new look and feel for odd lines self.list.SetItemBackgroundColour(pos,(134,225,249)) #画图 def PlotData(self,code): quotes = finance.get_quotes_historical(code) fields = ['date','open','close','high','low','volume'] dates = [] for i in range(0,len(quotes)): x = dt.datetime.utcfromtimestamp(int(quotes[i]['date'])) y = dt.datetime.strftime(x,'%Y-%m-%d') dates.append(y) quotesdf = pd.DataFrame(quotes,index=dates,columns=fields) #remove unchecked fileds fileds_to_drop = ['date'] for key, value in self.option_list.items(): if not value: fileds_to_drop.append(key) quotesdf = quotesdf.drop(fileds_to_drop,axis=1) quotesdf.plot() plt.show() #响应列表双击方法 def OnDoubleClick(self,event): self.PlotData(event.GetText()) #响应文本框输入回车方法 def OnTextSubmitted(self,event): self.PlotData(event.GetString()) #获取复选框数据 def OnChecked(self,event): checkBox = event.GetEventObject() text = checkBox.GetLabel().lower() self.option_list[text] = checkBox.GetValue() #响应退出按钮/菜单方法 def OnQuit(self,event): self.Close() self.Destroy() #响应刷新按钮/菜单方法 def OnRefresh(self,event): thread.start_new_thread(self.retrieve_quotes,()) #获取 DJI数据 def retrieve_quotes(self): data = finance.get_dji_list() if data: self.setData(data) else: wx.MessageBox('Download failed.','Message', wx.OK | wx.ICON_INFORMATION) if __name__ == '__main__': app = wx.App(False) #创建StockFrame实例,名称为"Dow Jons Industrial Average(^DJI)" top = StockFrame("Dow Jons Industrial Average(^DJI)") top.Show(True) app.MainLoop()
[ "gitknt@outlook.com" ]
gitknt@outlook.com
faea3e50e4e9b59dd76834845389c8df6f3fdee6
597b82737635e845fd5360e191f323669af1b2ae
/08_full_django/products/apps/products/views.py
d46ee65e2d2a815b3a101e18a5a2d6fa8c0eec5e
[]
no_license
twknab/learning-python
1bd10497fbbe181a26f2070c147cb2fed6955178
75b76b2a607439aa2d8db675738adf8d3b8644df
refs/heads/master
2021-08-08T08:50:04.337490
2017-11-10T00:28:45
2017-11-10T00:28:45
89,213,845
0
1
null
null
null
null
UTF-8
Python
false
false
1,362
py
from django.shortcuts import render from models import Product # Create 3 Different Products: """ Note: You can see our object creation has been placed outside of our `index()` method. This is because if we placed these creation events inside of our index method, we'd have the same product created on every refresh. """ Product.objects.create(name="Kool Aid",description="A powdered sugary drink.",price="1.00",cost="0.50",category="Beverage") Product.objects.create(name="Lentil Burger",description="Lentils, onions and shallots pressed into a patty.",price="8.00",cost="3.50",category="Food") Product.objects.create(name="French Fries",description="Organic potatos fried to a crisp and seasoned to perfection.",price="2.00",cost="1.00",category="Food") def index(request): """Loads homepage.""" print "Loading homepage..." print "Building instance off of `Product` model..." # Stores all products: products = Product.objects.all() # Loop through products and print information: print "///////////// P R O D U C T S /////////////" for product in products: print "- {} | {} | ${} (consumer cost)/ea | ${}/ea (business cost)".format(product.name, product.description, product.price, product.cost) print "/////////////////////////////////////////////////" return render(request, "products/index.html")
[ "natureminded@users.noreply.github.com" ]
natureminded@users.noreply.github.com
571a517e58b1431ce8c60ae03fc91e324600403c
78c3082e9082b5b50435805723ae00a58ca88e30
/03.AI알고리즘 소스코드/venv/Lib/site-packages/caffe2/python/operator_test/jsd_ops_test.py
4a2b327ddeba63f3df666180047c9e0f4b3ed672
[]
no_license
jinStar-kimmy/algorithm
26c1bc456d5319578110f3d56f8bd19122356603
59ae8afd8d133f59a6b8d8cee76790fd9dfe1ff7
refs/heads/master
2023-08-28T13:16:45.690232
2021-10-20T08:23:46
2021-10-20T08:23:46
419,217,105
0
1
null
null
null
null
UTF-8
Python
false
false
1,085
py
from caffe2.python import core import caffe2.python.hypothesis_test_util as hu import caffe2.python.serialized_test.serialized_test_util as serial import hypothesis.strategies as st import numpy as np def entropy(p): q = 1. - p return -p * np.log(p) - q * np.log(q) def jsd(p, q): return [entropy(p / 2. + q / 2.) - entropy(p) / 2. - entropy(q) / 2.] def jsd_grad(go, o, pq_list): p, q = pq_list m = (p + q) / 2. return [np.log(p * (1 - m) / (1 - p) / m) / 2. * go, None] class TestJSDOps(serial.SerializedTestCase): @serial.given(n=st.integers(10, 100), **hu.gcs_cpu_only) def test_bernoulli_jsd(self, n, gc, dc): p = np.random.rand(n).astype(np.float32) q = np.random.rand(n).astype(np.float32) op = core.CreateOperator("BernoulliJSD", ["p", "q"], ["l"]) self.assertReferenceChecks( device_option=gc, op=op, inputs=[p, q], reference=jsd, output_to_grad='l', grad_reference=jsd_grad, )
[ "gudwls3126@gmail.com" ]
gudwls3126@gmail.com
2f97ef1ba97ac1029b7fbfb48d23a450ad5975a0
242086b8c6a39cbc7af3bd7f2fd9b78a66567024
/python/PP4E-Examples-1.4/Examples/PP4E/Preview/tkinter102.py
9ef018e04625b9629f7cbf85be5ab4f1d125109d
[]
no_license
chuzui/algorithm
7537d0aa051ac4cbe9f6a7ca9a3037204803a650
c3006b24c4896c1242d3ceab43ace995c94f10c8
refs/heads/master
2021-01-10T13:05:30.902020
2015-09-27T14:39:02
2015-09-27T14:39:02
8,404,397
4
4
null
null
null
null
UTF-8
Python
false
false
412
py
from tkinter import * from tkinter.messagebox import showinfo class MyGui(Frame): def __init__(self, parent=None): Frame.__init__(self, parent) button = Button(self, text='press', command=self.reply) button.pack() def reply(self): showinfo(title='popup', message='Button pressed!') if __name__ == '__main__': window = MyGui() window.pack() window.mainloop()
[ "zui" ]
zui
f314aa92ae0309c5fc33503ef23d53144f73e8d1
ca7aa979e7059467e158830b76673f5b77a0f5a3
/Python_codes/p03618/s585911965.py
3cb657424c1ff0a4d384f5df252781e21eb2b757
[]
no_license
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
UTF-8
Python
false
false
321
py
import sys sys.setrecursionlimit(10**7) #input = sys.stdin.readline from collections import Counter def main(): a = input() n = len(a) base = n * (n - 1) // 2 counter = Counter(a) def f(): for c in counter.values(): yield c * (c - 1) // 2 print(base - sum(f()) + 1) main()
[ "66529651+Aastha2104@users.noreply.github.com" ]
66529651+Aastha2104@users.noreply.github.com
70e4f58dfd4f4803a9edb317dac94031b38f62ac
ac4eca2377cafd58b3da6c7bdae8e3eea9606e52
/101-200/129.Sum Root to Leaf Numbers.py
3fcb3828eb0d11e950cc8329f5bf86e95237e258
[]
no_license
iscas-ljc/leetcode-medium
bf71a8d9a93af07d6863c67b10c824f6855c520c
21b962825b1a386c60b319cbf94c0aecfa546008
refs/heads/master
2021-09-05T09:42:01.100811
2018-01-26T06:14:46
2018-01-26T06:14:46
111,070,794
1
0
null
null
null
null
UTF-8
Python
false
false
356
py
class Solution(object): def sumNumbers(self, root): self.result=0 self.sum(root,0) return self.result def sum(self,root,tile_now): if root: self.sum(root.left,tile_now*10+root.val) self.sum(root.right,tile_now*10+root.val) if not root.left and not root.right: self.result+=tile_now*10+root.val
[ "861218470@qq.com" ]
861218470@qq.com
09c4d515d0e34930231eb3884a4c97df7a64efc9
3cef23043a4bf3bc2a37d952e51b1a9faeb76d0b
/setup.py
0d6ff2da2b231576e669a8f68795badbaf0a0b64
[ "MIT" ]
permissive
hiroaki-yamamoto/django-nghelp
794bc103ecf5bb652363e3a1df530afa971ac46a
e15dc408a4a9205d23f9d68b6d10d7b9648dbd2e
refs/heads/master
2020-07-29T21:41:23.972244
2018-01-15T04:30:49
2018-01-15T04:30:49
73,657,569
2
0
null
null
null
null
UTF-8
Python
false
false
1,198
py
#!/usr/bin/env python # coding=utf-8 """Setup script.""" import sys from setuptools import setup, find_packages dependencies = ("django>=1.11", "jinja2") name = "django-nghelp" desc = "AngularJS Frontend Helper for Django" license = "MIT" url = "https://github.com/hiroaki-yamamoto/django-nghelp.git" keywords = "django AngularJS" version = "[VERSION]" author = "Hiroaki Yamamoto" author_email = "hiroaki@hysoftware.net" if sys.version_info < (2, 7): raise RuntimeError("Not supported on earlier then python 2.7.") try: with open('README.rst') as readme: long_desc = readme.read() except Exception: long_desc = None setup( name=name, version=version, description=desc, long_description=long_desc, packages=find_packages(exclude=["tests"]), include_package_data=True, install_requires=dependencies, zip_safe=False, author=author, author_email=author_email, license=license, keywords=keywords, url=url, classifiers=[ "Development Status :: 7 - Inactive", "License :: OSI Approved :: MIT License", "Programming Language :: Python :: 2.7", "Programming Language :: Python :: 3.5" ] )
[ "hiroaki@hysoftware.net" ]
hiroaki@hysoftware.net
cfc948a7d33be8ee11ef65a155425af6c2ca5b4b
9b5597492e57313712c0a842ef887940f92636cd
/judge/sessions/2018Individual/jillzhoujinjing@gmail.com/PB_02.py
c4f369a67b553603b661bba7006a5bf67a02439f
[]
no_license
onionhoney/codesprint
ae02be9e3c2354bb921dc0721ad3819539a580fa
fcece4daf908aec41de7bba94c07b44c2aa98c67
refs/heads/master
2020-03-11T11:29:57.052236
2019-05-02T22:04:53
2019-05-02T22:04:53
129,971,104
0
0
null
null
null
null
UTF-8
Python
false
false
951
py
import sys def find_one(data,min_p,max_p): index = int((min_p+max_p)/2) dif = max_p - min_p if dif == 0: return max_p if dif == 1: if data[max_p] == 1: return max_p elif data[min_p] == 1: return min_p if data[index] == 2: return find_one(data,min_p,index) elif data[index] == 0: return find_one(data,index, max_p) else: return index first_line = 1 cur_case = 0 cur_case_line = 0 all_data = {} for line in sys.stdin: if first_line: first_line = 0 else: cur_case_line +=1 if cur_case not in all_data: all_data[cur_case] = [list(map(int,line.strip('\n').split(' ')))] else: all_data[cur_case].append(list(map(int,line.strip('\n').split(' ')))) if cur_case_line == 3: result = "" for i in range(3): data = all_data[cur_case][i] if i < 2: result += str(find_one(data,0,99)) + ' ' else: result += str(find_one(data,0,99)) print(result) cur_case += 1 cur_case_line = 0
[ "root@codesprintla.com" ]
root@codesprintla.com
4da5b58f9a136d6c3af1a22f37d1afcfd4426cfa
ece0d321e48f182832252b23db1df0c21b78f20c
/engine/2.80/scripts/addons/presets/pov/lamp/05_(4000K)_100W_Metal_Halide.py
2a0ba8c12164925c6a8d0a9b11741a6f94a1b5f1
[ "Unlicense", "GPL-3.0-only", "Font-exception-2.0", "GPL-3.0-or-later", "Apache-2.0", "LicenseRef-scancode-public-domain", "LicenseRef-scancode-unknown-license-reference", "LicenseRef-scancode-public-domain-disclaimer", "Bitstream-Vera", "LicenseRef-scancode-blender-2010", "LGPL-2.1-or-later", "GPL-2.0-or-later", "GPL-2.0-only", "LGPL-2.0-only", "PSF-2.0", "LicenseRef-scancode-free-unknown", "LicenseRef-scancode-proprietary-license", "GPL-1.0-or-later", "BSD-2-Clause" ]
permissive
byteinc/Phasor
47d4e48a52fa562dfa1a2dbe493f8ec9e94625b9
f7d23a489c2b4bcc3c1961ac955926484ff8b8d9
refs/heads/master
2022-10-25T17:05:01.585032
2019-03-16T19:24:22
2019-03-16T19:24:22
175,723,233
3
1
Unlicense
2022-10-21T07:02:37
2019-03-15T00:58:08
Python
UTF-8
Python
false
false
603
py
#After 1962 #Common uses: outdoor lighting where good color rendering is needed, television/film lighting, sports fields, car headlights, flood lights, heavy flashlights, green house applications import bpy bpy.context.object.data.type = 'SPOT' lampdata = bpy.context.object.data lampdata.show_cone = True lampdata.spot_size = 0.6 lampdata.spot_blend = 0.9 lampdata.color = (0.9490196108818054, 0.9882352948188782, 1.0) lampdata.energy = 20.98293#9000lm/21.446(=lux)*0.004*6.25(distance) *2 for distance is the point of half strength lampdata.distance = 0.025 lampdata.falloff_type = 'INVERSE_SQUARE'
[ "admin@irradiate.net" ]
admin@irradiate.net
a05114189934ab4ce9304762f6164d71185d9253
b08437d7346ace7b8282e0fd7f292c6eb64b0b0d
/columbus/people.py
67aeeba949705935adf341a8e3fd70edd696bd3c
[]
no_license
opengovernment/municipal-scrapers-us
d3b3df303d8999882d3a05f1bec831ba705e8e2b
54c28c0fa1319d712674c559e3df3d79a975768f
refs/heads/master
2021-01-14T13:17:07.931879
2014-01-10T00:55:48
2014-01-10T00:55:48
15,881,694
1
0
null
null
null
null
UTF-8
Python
false
false
1,598
py
# Copyright (c) Sunlight Labs, 2013, under the terms of the BSD-3 clause # license. # # Contributors: # # - Paul Tagliamonte <paultag@sunlightfoundation.com> from pupa.scrape import Scraper, Legislator, Committee from collections import defaultdict import lxml.html HOMEPAGE = "http://council.columbus.gov/" class ColumbusPersonScraper(Scraper): def lxmlize(self, url): entry = self.urlopen(url) page = lxml.html.fromstring(entry) page.make_links_absolute(url) return page def get_people(self): yield self.cbus_scrape_people() def scrape_homepage(self, folk): url = folk.attrib['href'] page = self.lxmlize(url) image = page.xpath( "//img[contains(@src, 'uploadedImages/City_Council/Members/')]" )[0].attrib['src'] name = page.xpath("//div[@id='ctl00_ctl00_Body_body_cntCommon']/h3") name, = name bio = "\n\n".join([x.text_content() for x in page.xpath( "//div[@id='ctl00_ctl00_Body_body_cntCommon']/p" )]) leg = Legislator(name=name.text, post_id='member', biography=bio, image=image) leg.add_source(url) return leg def cbus_scrape_people(self): page = self.lxmlize(HOMEPAGE) folks = page.xpath("//div[@class='col-left']/div[2]//" "div[@class='gutter_text'][1]//" "ul[@class='gutterlist']/li//a") for folk in folks: yield self.scrape_homepage(folk)
[ "tag@pault.ag" ]
tag@pault.ag
9066c600056c28e78bbb7f6076635f0797b62764
85a32fc66050b5590f6a54774bbb4b88291894ab
/python/strings/merge-the-tools/python2.py
9062ca3d05ac46255135508ccf8df8779f673d34
[]
no_license
charlesartbr/hackerrank-python
59a01330a3a6c2a3889e725d4a29a45d3483fb01
bbe7c6e2bfed38132f511881487cda3d5977c89d
refs/heads/master
2022-04-29T07:40:20.244416
2022-03-19T14:26:33
2022-03-19T14:26:33
188,117,284
46
37
null
2022-03-19T14:26:34
2019-05-22T21:38:18
Python
UTF-8
Python
false
false
318
py
def merge_the_tools(string, k): n = len(string) for i in xrange(0, n, k): u = [] for j in string[i:i+k]: if not j in u: u.append(j) print ''.join(u) if __name__ == '__main__': string, k = raw_input(), int(raw_input()) merge_the_tools(string, k)
[ "e-mail@charles.art.br" ]
e-mail@charles.art.br
2811d0bfb278246fdc5e3e4c58809850f9b47c87
ba0cbdae81c171bd4be7b12c0594de72bd6d625a
/MyToontown/py2/otp/speedchat/SCElement.pyc.py
8c609d912b2c1b4d4c2d607f57a05e84e233b5b4
[]
no_license
sweep41/Toontown-2016
65985f198fa32a832e762fa9c59e59606d6a40a3
7732fb2c27001264e6dd652c057b3dc41f9c8a7d
refs/heads/master
2021-01-23T16:04:45.264205
2017-06-04T02:47:34
2017-06-04T02:47:34
93,279,679
0
0
null
null
null
null
UTF-8
Python
false
false
6,083
py
# 2013.08.22 22:15:47 Pacific Daylight Time # Embedded file name: otp.speedchat.SCElement from pandac.PandaModules import * from direct.gui.DirectGui import * from direct.task import Task from SCConstants import * from SCObject import SCObject from direct.showbase.PythonUtil import boolEqual from otp.otpbase import OTPGlobals class SCElement(SCObject, NodePath): __module__ = __name__ font = OTPGlobals.getInterfaceFont() SerialNum = 0 def __init__(self, parentMenu = None): SCObject.__init__(self) self.SerialNum = SCElement.SerialNum SCElement.SerialNum += 1 node = hidden.attachNewNode('SCElement%s' % self.SerialNum) NodePath.__init__(self, node) self.FinalizeTaskName = 'SCElement%s_Finalize' % self.SerialNum self.parentMenu = parentMenu self.__active = 0 self.__viewable = 1 self.lastWidth = 0 self.lastHeight = 0 self.setDimensions(0, 0) self.padX = 0.25 self.padZ = 0.1 def destroy(self): if self.isActive(): self.exitActive() SCObject.destroy(self) if hasattr(self, 'button'): self.button.destroy() del self.button self.parentMenu = None self.detachNode() return def setParentMenu(self, parentMenu): self.parentMenu = parentMenu def getParentMenu(self): return self.parentMenu def getDisplayText(self): self.notify.error('getDisplayText is pure virtual, derived class must override') def onMouseEnter(self, event): if self.parentMenu is not None: self.parentMenu.memberGainedInputFocus(self) return def onMouseLeave(self, event): if self.parentMenu is not None: self.parentMenu.memberLostInputFocus(self) return def onMouseClick(self, event): pass def enterActive(self): self.__active = 1 def exitActive(self): self.__active = 0 def isActive(self): return self.__active def hasStickyFocus(self): return 0 def setViewable(self, viewable): if not boolEqual(self.__viewable, viewable): self.__viewable = viewable if self.parentMenu is not None: self.parentMenu.memberViewabilityChanged(self) return def isViewable(self): return self.__viewable def getMinDimensions(self): text = TextNode('SCTemp') text.setFont(SCElement.font) dText = self.getDisplayText() text.setText(dText) bounds = text.getCardActual() width = abs(bounds[1] - bounds[0]) + self.padX height = abs(bounds[3] - bounds[2]) + 2.0 * self.padZ return (width, height) def setDimensions(self, width, height): self.width = float(width) self.height = float(height) if (self.lastWidth, self.lastHeight) != (self.width, self.height): self.invalidate() def invalidate(self): SCObject.invalidate(self) parentMenu = self.getParentMenu() if parentMenu is not None: if not parentMenu.isFinalizing(): parentMenu.invalidate() return def enterVisible(self): SCObject.enterVisible(self) self.privScheduleFinalize() def exitVisible(self): SCObject.exitVisible(self) self.privCancelFinalize() def privScheduleFinalize(self): def finalizeElement(task, self = self): if self.parentMenu is not None: if self.parentMenu.isDirty(): return Task.done self.finalize() return Task.done taskMgr.remove(self.FinalizeTaskName) taskMgr.add(finalizeElement, self.FinalizeTaskName, priority=SCElementFinalizePriority) def privCancelFinalize(self): taskMgr.remove(self.FinalizeTaskName) def finalize(self, dbArgs = {}): if not self.isDirty(): return SCObject.finalize(self) if hasattr(self, 'button'): self.button.destroy() del self.button halfHeight = self.height / 2.0 textX = 0 if dbArgs.has_key('text_align'): if dbArgs['text_align'] == TextNode.ACenter: textX = self.width / 2.0 args = {'text': self.getDisplayText(), 'frameColor': (0, 0, 0, 0), 'rolloverColor': self.getColorScheme().getRolloverColor() + (1,), 'pressedColor': self.getColorScheme().getPressedColor() + (1,), 'text_font': OTPGlobals.getInterfaceFont(), 'text_align': TextNode.ALeft, 'text_fg': self.getColorScheme().getTextColor() + (1,), 'text_pos': (textX, -0.25 - halfHeight, 0), 'relief': DGG.FLAT, 'pressEffect': 0} args.update(dbArgs) rolloverColor = args['rolloverColor'] pressedColor = args['pressedColor'] del args['rolloverColor'] del args['pressedColor'] btn = DirectButton(parent=self, frameSize=(0, self.width, -self.height, 0), **args) btn.frameStyle[DGG.BUTTON_ROLLOVER_STATE].setColor(*rolloverColor) btn.frameStyle[DGG.BUTTON_DEPRESSED_STATE].setColor(*pressedColor) btn.updateFrameStyle() btn.bind(DGG.ENTER, self.onMouseEnter) btn.bind(DGG.EXIT, self.onMouseLeave) btn.bind(DGG.B1PRESS, self.onMouseClick) self.button = btn self.lastWidth = self.width self.lastHeight = self.height self.validate() def __str__(self): return '%s: %s' % (self.__class__.__name__, self.getDisplayText()) # okay decompyling C:\Users\Maverick\Documents\Visual Studio 2010\Projects\Unfreezer\py2\otp\speedchat\SCElement.pyc # decompiled 1 files: 1 okay, 0 failed, 0 verify failed # 2013.08.22 22:15:47 Pacific Daylight Time
[ "sweep14@gmail.com" ]
sweep14@gmail.com
b5d4d113d19205f7d6853527b3a819ef30f6852e
e52f3d13abccbfdfc037ae447137759d02fef75f
/python_work/ch10/practice/10-9 silent cAd.py
6c63722dd8156520a7af6d091fb279957d89495d
[]
no_license
WeiS49/Python-Crash-Course
7b8bc10dff58a06b0ef42dfa686ff72d4020547d
2a3c11c28429e49fa48018b252dacb4129587950
refs/heads/master
2023-01-06T19:23:39.577634
2020-11-06T06:12:03
2020-11-06T06:12:03
302,330,894
0
0
null
null
null
null
UTF-8
Python
false
false
294
py
filename1 = 'dogs.txt' filename2 = 'catss.txt' try: with open(filename1) as f1: dogs = f1.read() except FileNotFoundError: pass else: print(dogs) try: with open(filename2) as f2: cats = f2.read() except FileNotFoundError: pass else: print(cats)
[ "swh_1C3@outlook.com" ]
swh_1C3@outlook.com
ed6879070f3634f296250c79bf584b9f6cc4aefb
72786214749df0fc3d2eb471f25b80839b866896
/python_algo_lab/linear_search.py
3ff565dd7f403b0179ed48181a7dc31a1799aa50
[]
no_license
itsvinayak/labs
4f5245fd8a1554e7bbd042a2f4d15ac408a13276
15f54ca1672f684a14c22ac0194f9457eafc97f6
refs/heads/master
2020-09-16T05:19:17.406156
2020-04-08T05:22:59
2020-04-08T05:22:59
223,665,257
0
0
null
null
null
null
UTF-8
Python
false
false
352
py
def linear_search(array, left, right, item): if left == right: return -1 if array[left] == item: return left + 1 return linear_search(array, left + 1, right, item) if __name__ == "__main__": array = [1, 3, 9, 22, 5, 0, 3, 3, 4, 90] item = 22 right = len(array) print(linear_search(array, 0, right, item))
[ "itssvinayak@gmail.com" ]
itssvinayak@gmail.com
cead79d631ff3bbb21c62d18f19d5f993f9bef46
ea89417f702100a5541263e7342f3e9ad76c5423
/hmc/algorithm/utils/lib_utils_system.py
c2202116205fc6cb1bb27a984a42f5894f328225
[ "MIT" ]
permissive
c-hydro/fp-hmc
130b887a27072b7c967fca27f0568d68a3c06143
30bd5d0a3e4921410990968bb3a4eaf601b5b804
refs/heads/main
2023-06-11T12:22:07.480759
2022-12-07T12:20:51
2022-12-07T12:20:51
216,776,851
0
0
MIT
2022-12-02T12:10:25
2019-10-22T09:39:05
Python
UTF-8
Python
false
false
2,819
py
""" Library Features: Name: lib_utils_system Author(s): Fabio Delogu (fabio.delogu@cimafoundation.org) Date: '20200401' Version: '3.0.0' """ ####################################################################################### # Library import logging import os import pandas as pd import shutil from os.path import exists from hmc.algorithm.default.lib_default_args import logger_name # Logging log_stream = logging.getLogger(logger_name) # Debug # import matplotlib.pylab as plt ####################################################################################### # ------------------------------------------------------------------------------------- # Method to split full path in root and filename def split_path(file_path): file_root, file_name = os.path.split(file_path) return file_root, file_name # ------------------------------------------------------------------------------------- # ------------------------------------------------------------------------------------- # Method to create folder (and check if folder exists) def create_folder(path_name=None, path_delimiter=None): if path_name: if path_delimiter: path_name_tmp = path_name.split(path_delimiter)[0] else: path_name_tmp = path_name if not exists(path_name_tmp): os.makedirs(path_name_tmp) # ------------------------------------------------------------------------------------- # ------------------------------------------------------------------------------------- # Method to delete folder (and check if folder exists) def delete_folder(path_name): # Check folder status if os.path.exists(path_name): # Remove folder (file only-read too) shutil.rmtree(path_name, ignore_errors=True) # ------------------------------------------------------------------------------------- # ------------------------------------------------------------------------------------- # Method to delete file def delete_file(file_path, file_delete=True): if file_delete: if os.path.isfile(file_path): os.remove(file_path) # ------------------------------------------------------------------------------------- # ------------------------------------------------------------------------------------- # Method to copy file from source to destination def copy_file(file_path_src, file_path_dest): if os.path.exists(file_path_src): if not file_path_src == file_path_dest: if os.path.exists(file_path_dest): os.remove(file_path_dest) shutil.copy2(file_path_src, file_path_dest) else: log_stream.warning(' ===> Copy file failed! Source not available!') # -------------------------------------------------------------------------------------
[ "fabio.delogu@cimafoundation.org" ]
fabio.delogu@cimafoundation.org
f1e5599f0ea8c38d38ebc0353bab439d1b5250a3
e6f1578ae2eff1b14a0734d8ebf9cbfaf13a7338
/steem/tests/test_steem.py
101488980cd4acf91af38304bdd16248a7e9894d
[ "MIT" ]
permissive
clayop/python-steem
d672be71f5662658bad141a835c2155af1e1ffb5
ad1298d81a8116d000fe21cf1528cfa444c0e38d
refs/heads/master
2021-01-11T21:09:15.789961
2017-02-16T01:51:19
2017-02-16T01:51:19
79,258,712
0
0
null
2017-01-17T18:36:08
2017-01-17T18:36:08
null
UTF-8
Python
false
false
3,508
py
import unittest from steem.steem import ( Steem, MissingKeyError, InsufficientAuthorityError ) from steem.post import ( Post, VotingInvalidOnArchivedPost ) identifier = "@xeroc/piston" testaccount = "xeroc" wif = "5KkUHuJEFhN1RCS3GLV7UMeQ5P1k5Vu31jRgivJei8dBtAcXYMV" steem = Steem(nobroadcast=True, wif=wif) class Testcases(unittest.TestCase): def __init__(self, *args, **kwargs): super(Testcases, self).__init__(*args, **kwargs) self.post = Post(steem, identifier) def test_getOpeningPost(self): self.post._getOpeningPost() def test_reply(self): try: self.post.reply(body="foobar", title="", author=testaccount, meta=None) except InsufficientAuthorityError: pass except MissingKeyError: pass def test_upvote(self): try: self.post.upvote(voter=testaccount) except VotingInvalidOnArchivedPost: pass except InsufficientAuthorityError: pass except MissingKeyError: pass def test_downvote(self, weight=-100, voter=testaccount): try: self.post.downvote(voter=testaccount) except VotingInvalidOnArchivedPost: pass except InsufficientAuthorityError: pass except MissingKeyError: pass def test_edit(self): try: steem.edit(identifier, "Foobar") except InsufficientAuthorityError: pass except MissingKeyError: pass def test_post(self): try: steem.post("title", "body", meta={"foo": "bar"}, author=testaccount) except InsufficientAuthorityError: pass except MissingKeyError: pass def test_create_account(self): try: steem.create_account("xeroc-create", creator=testaccount, password="foobar foo bar hello world", storekeys=False ) except InsufficientAuthorityError: pass except MissingKeyError: pass def test_transfer(self): try: steem.transfer("fabian", 10, "STEEM", account=testaccount) except InsufficientAuthorityError: pass except MissingKeyError: pass def test_withdraw_vesting(self): try: steem.withdraw_vesting(10, account=testaccount) except InsufficientAuthorityError: pass except MissingKeyError: pass def test_transfer_to_vesting(self): try: steem.transfer_to_vesting(10, to=testaccount, account=testaccount) except InsufficientAuthorityError: pass except MissingKeyError: pass def test_get_replies(self): steem.get_replies(author=testaccount) def test_get_posts(self): steem.get_posts() def test_get_categories(self): steem.get_categories(sort="trending") def test_get_balances(self): steem.get_balances(testaccount) def test_getPost(self): self.assertEqual(Post(steem, "@xeroc/piston").url, "/piston/@xeroc/piston") self.assertEqual(Post(steem, {"author": "@xeroc", "permlink": "piston"}).url, "/piston/@xeroc/piston") if __name__ == '__main__': unittest.main()
[ "mail@xeroc.org" ]
mail@xeroc.org
64958beb389d7d629f311e4dd7a2be1ee78700b3
8a029afcaee3080728be4648c96865d5847d3247
/dnnseg/bin/csv_to_zs.py
aa845946c363e52e15e0ba430e5d9e548ee97eb0
[]
no_license
coryshain/dnnseg
623d8c3583a996e496e77123a3296c8731f40613
30eed4b031adb3fcef80f98c6f037fd993aa36ca
refs/heads/master
2021-06-11T00:47:25.975714
2021-02-22T14:18:51
2021-02-22T14:18:51
143,957,434
10
7
null
2020-12-12T01:34:11
2018-08-08T03:41:41
Python
UTF-8
Python
false
false
1,351
py
import pandas as pd import sys import os import argparse from dnnseg.data import segment_table_to_csv def check_path(path): if os.path.basename(path).startswith('embeddings_pred') and path.endswith('.csv'): return True return False if __name__ == '__main__': argparser = argparse.ArgumentParser(''' Convert CSV segment tables into a format acceptable for the Zerospeech 2015 TDE eval. ''') argparser.add_argument('paths', nargs='+', help='Paths to CSV files or directories to recursively search for CSV segment table files.') argparser.add_argument('-v', '--verbose', action='store_true', help='Write progress report to standard error.') args = argparser.parse_args() csvs = set() for path in args.paths: if check_path(path): csvs.add(path) else: for root, _, files in os.walk(path): for f in files: p = os.path.join(root, f) if check_path(p): csvs.add(p) csvs = sorted(list(csvs)) for csv in csvs: if args.verbose: sys.stderr.write('Converting file %s...\n' % csv) df = pd.read_csv(csv, sep=' ') out = segment_table_to_csv(df, verbose=args.verbose) with open(csv[:-4] + '.classes', 'w') as f: f.write(out)
[ "cory.shain@gmail.com" ]
cory.shain@gmail.com
6654efa5ed917fd3dad0f2bd8dc8c8d4adb389aa
f305f84ea6f721c2391300f0a60e21d2ce14f2a5
/22_专题/邻位交换(adjacent swap)/minAdjacentSwap.py
5fd74ce9c63a814cda310f86986f1290e369323b
[]
no_license
981377660LMT/algorithm-study
f2ada3e6959338ae1bc21934a84f7314a8ecff82
7e79e26bb8f641868561b186e34c1127ed63c9e0
refs/heads/master
2023-09-01T18:26:16.525579
2023-09-01T12:21:58
2023-09-01T12:21:58
385,861,235
225
24
null
null
null
null
UTF-8
Python
false
false
1,733
py
from typing import MutableSequence from collections import defaultdict, deque from sortedcontainers import SortedList def minAdjacentSwap1(nums1: MutableSequence[int], nums2: MutableSequence[int]) -> int: """ 求使两个数组相等的最少邻位交换次数 映射+求逆序对 时间复杂度`O(nlogn)` 如果无法做到则输出 -1 """ def countInversionPair(nums: MutableSequence[int]) -> int: """计算逆序对的个数 时间复杂度`O(nlogn)`""" res = 0 sl = SortedList() for num in reversed(nums): pos = sl.bisect_left(num) res += pos sl.add(num) return res # 含有重复元素的映射 例如nums [1,3,2,1,4] 表示已经排序的数组 [0,1,2,3,4] # 那么nums1 [1,1,3,4,2] 就 映射到 [0,3,1,4,2] mapping = defaultdict(deque) for index, num in enumerate(nums2): mapping[num].append(index) for index, num in enumerate(nums1): if not mapping[num]: return -1 mapped = mapping[num].popleft() nums1[index] = mapped res = countInversionPair(nums1) return res def minAdjacentSwap2(nums1: MutableSequence[int], nums2: MutableSequence[int]) -> int: """求使两个数组相等的最少邻位交换次数 对每个数,贪心找到对应的最近位置交换 时间复杂度`O(n^2)` 如果无法做到则输出 -1 """ res = 0 for num in nums1: index = nums2.index(num) # 最左边的第一个位置 if index == -1: return -1 res += index nums2.pop(index) # 已经被换到最左边了,所以减1 return res
[ "lmt2818088@gmail.com" ]
lmt2818088@gmail.com
a6b76bd42fb9759cfcf2ab24708ea976b1f32dea
876de904572c611b8cbad21f50877cdc812f2946
/校招/程序员面试金典_08.11. 硬币_动态规划_数学推导.py
4f0da7d68805a5a34aa80b20e883a371d0147ad4
[ "MIT" ]
permissive
QDylan/Learning-
66a33de0e15f26672fb63c0b393866721def27ae
f09e0aa3de081883b4a7ebfe4d31b5f86f24b64f
refs/heads/master
2023-02-08T02:34:26.616116
2020-12-25T05:02:32
2020-12-25T05:02:32
263,805,536
0
0
null
null
null
null
UTF-8
Python
false
false
1,807
py
# -*- coding: utf-8 -*- """ @Time : 2020/5/19 11:52 @Author : QDY @FileName: 程序员面试金典_08.11. 硬币_动态规划_数学推导.py 硬币。给定数量不限的硬币,币值为25分、10分、5分和1分,编写代码计算n分有几种表示法。(结果可能会很大,你需要将结果模上1000000007) 示例1: 输入: n = 5 输出:2 解释: 有两种方式可以凑成总金额: 5=5 5=1+1+1+1+1 示例2: 输入: n = 10 输出:4 解释: 有四种方式可以凑成总金额: 10=10 10=5+5 10=5+1+1+1+1+1 10=1+1+1+1+1+1+1+1+1+1 """ class Solution: def waysToChange(self, n: int) -> int: # # 1.动态规划 完全背包问题 # # dp[i] = 金额为i时有几种表示法 # # dp[i] = sum(dp[i-coins[j]]),j=0~4 # dp = [1]*(n+1) # 1.dp # for c in [5,10,25]: # for i in range(c,n+1): # dp[i] += dp[i-c] # return dp[-1] % 1000000007 # 2.数学推导 (速度快,应用于len(coins)=4) res = 0 for i in range(n//25+1): # 选用多少个25分硬币 rest = n-25*i # 剩余的金额r # r = r1*10 + a, a = r2*5 + b, a<10, b<5 # 假设选了x个10分硬币(有r1+1种选取法),则剩余的金额为 # r' = r-10*x = 10*r1-10*x+a = 10*(r1-x)+ 5*r2 + b # 这时,10*(r1-x)全由5分硬币组成-> r' = (2(r1-x)+r2)*5+b # 即r'有2r1+r2-2x+1种组成方案 # 对 (2r1+r2-2x+1), x从0->r1求和得 # sum = (2r1+r2+1)*(r1+1)-2(0+r1)*(r1+1)/2 = (r1+r2+1)*(r1+1) rest1, rest2 = rest//10, rest % 10//5 res += (rest1+1)*(rest1+rest2+1) return res % 1000000007
[ "qdy960411@outlook.com" ]
qdy960411@outlook.com
fea9164721f5b30483782a20953571c70a3e5445
5456502f97627278cbd6e16d002d50f1de3da7bb
/chrome/test/chromeos/autotest/files/client/deps/page_cycler_dep/common.py
6e20002004cd79d7c23eb14889b0cbb24282c71a
[ "BSD-3-Clause" ]
permissive
TrellixVulnTeam/Chromium_7C66
72d108a413909eb3bd36c73a6c2f98de1573b6e5
c8649ab2a0f5a747369ed50351209a42f59672ee
refs/heads/master
2023-03-16T12:51:40.231959
2017-12-20T10:38:26
2017-12-20T10:38:26
null
0
0
null
null
null
null
UTF-8
Python
false
false
484
py
# Copyright (c) 2012 The Chromium Authors. All rights reserved. # Use of this source code is governed by a BSD-style license that can be # found in the LICENSE file. import os, sys dirname = os.path.dirname(sys.modules[__name__].__file__) client_dir = os.path.abspath(os.path.join(dirname, "../../")) sys.path.insert(0, client_dir) import setup_modules sys.path.pop(0) setup_modules.setup(base_path=client_dir, root_module_name="autotest_lib.client")
[ "lixiaodonglove7@aliyun.com" ]
lixiaodonglove7@aliyun.com
f4234d8bcd1e3006a4816853a9195259c292e1ad
487fdbff5f51c67f401d108691291a64acc16f94
/day05.py
ea905b22ccf49f9e7e7f3d0242f81878304af93e
[ "MIT" ]
permissive
Yalfoosh/Advent-of-Code-2019
66f8f5d897cd67eaa561789332b033bb8aaa608e
d09be66a14f05b1ae086cdefd22dc414bc45d562
refs/heads/master
2020-09-26T23:01:54.199679
2019-12-11T20:07:33
2019-12-11T20:07:33
226,362,077
0
0
null
null
null
null
UTF-8
Python
false
false
2,353
py
from copy import deepcopy import re input_splitter = re.compile(r",\s*") parameter_count_dict =\ { 1: 3, 2: 3, 3: 1, 4: 1, 5: 2, 6: 2, 7: 3, 8: 3, 99: 1 } def load(path: str = "input/05.txt"): with open(path) as file: return [int(x) for x in input_splitter.split(file.read().strip())] def int_to_flag_vector(value, max_size=3): to_return = list() for _ in range(max_size): to_return.append(value % 10) value //= 10 return to_return def execute(memory, position: int, program_input, **kwargs): command_code = memory[position] flags = [0, 0, 0] if command_code > 99: flags = int_to_flag_vector(command_code // 100) command_code = command_code % 100 if command_code == 99: return len(memory) parameters = memory[position + 1: position + 1 + parameter_count_dict[command_code]] for pi in range(min(2, len(parameters))): if flags[pi] == 0 and command_code != 3: parameters[pi] = memory[parameters[pi]] if command_code == 1: memory[parameters[2]] = parameters[0] + parameters[1] elif command_code == 2: memory[parameters[2]] = parameters[0] * parameters[1] elif command_code == 3: memory[parameters[0]] = program_input elif command_code == 4: prefix = kwargs.get("prefix", None) prefix = "" if prefix is None else "[{}]\t".format(str(prefix)) print(f"{prefix}{parameters[0]}") elif command_code == 5: if parameters[0] != 0: return parameters[1] elif command_code == 6: if parameters[0] == 0: return parameters[1] elif command_code == 7: memory[parameters[2]] = 1 if (parameters[0] < parameters[1]) else 0 elif command_code == 8: memory[parameters[2]] = 1 if (parameters[0] == parameters[1]) else 0 else: return len(memory) return position + len(parameters) + 1 # Prep original_instructions = load() # First first_input = 1 instructions = deepcopy(original_instructions) i = 0 while i < len(instructions): i = execute(instructions, i, first_input, prefix=1) # Second second_input = 5 instructions = deepcopy(original_instructions) i = 0 while i < len(instructions): i = execute(instructions, i, second_input, prefix=2)
[ "suflajmob@gmail.com" ]
suflajmob@gmail.com
7f93a40d800f6f3ebe0d7340f2b8d405f789ae15
7b54edc142d01a7385f22f9e127f4790bd88f92b
/info/utils/common.py
8c5b49ee0121b2afd02e40193b0bca6cad980950
[]
no_license
amourbrus/newsWebFlask
20b73b39da3739133ea235b92b88e09639fbcfd8
359ec394ce2eacd3dde330d83f490efc0f354b5d
refs/heads/master
2020-03-21T10:16:19.084405
2018-07-12T15:04:54
2018-07-12T15:04:54
138,442,128
0
0
null
null
null
null
UTF-8
Python
false
false
622
py
import functools from flask import g from flask import session from info.models import User def index_class(index): if index == 0: return "first" elif index == 1: return "second" elif index == 2: return "third" else: return "" def user_login_data(f): @functools.wraps(f) def wrapper(*args,**kwargs): user_id = session.get("user_id") # 默认值 user = None if user_id: # 根据id查询当前用户 user = User.query.get(user_id) g.user = user return f(*args,**kwargs) return wrapper
[ "2338336776@qq.com" ]
2338336776@qq.com
8819e864d5603b9e54a6f258e6a7c04e9483aff8
71d4fafdf7261a7da96404f294feed13f6c771a0
/mainwebsiteenv/lib/python2.7/site-packages/phonenumbers/data/region_TC.py
45cf24186cb81296740b4d9674973cb859470f7f
[]
no_license
avravikiran/mainwebsite
53f80108caf6fb536ba598967d417395aa2d9604
65bb5e85618aed89bfc1ee2719bd86d0ba0c8acd
refs/heads/master
2021-09-17T02:26:09.689217
2018-06-26T16:09:57
2018-06-26T16:09:57
null
0
0
null
null
null
null
UTF-8
Python
false
false
1,413
py
"""Auto-generated file, do not edit by hand. TC metadata""" from ..phonemetadata import NumberFormat, PhoneNumberDesc, PhoneMetadata PHONE_METADATA_TC = PhoneMetadata(id='TC', country_code=1, international_prefix='011', general_desc=PhoneNumberDesc(national_number_pattern='[5689]\\d{9}', possible_length=(10,), possible_length_local_only=(7,)), fixed_line=PhoneNumberDesc(national_number_pattern='649(?:712|9(?:4\\d|50))\\d{4}', example_number='6497121234', possible_length=(10,), possible_length_local_only=(7,)), mobile=PhoneNumberDesc(national_number_pattern='649(?:2(?:3[129]|4[1-7])|3(?:3[1-389]|4[1-8])|4[34][1-3])\\d{4}', example_number='6492311234', possible_length=(10,), possible_length_local_only=(7,)), toll_free=PhoneNumberDesc(national_number_pattern='8(?:00|33|44|55|66|77|88)[2-9]\\d{6}', example_number='8002345678', possible_length=(10,)), premium_rate=PhoneNumberDesc(national_number_pattern='900[2-9]\\d{6}', example_number='9002345678', possible_length=(10,)), personal_number=PhoneNumberDesc(national_number_pattern='5(?:00|22|33|44|66|77|88)[2-9]\\d{6}', example_number='5002345678', possible_length=(10,)), voip=PhoneNumberDesc(national_number_pattern='64971[01]\\d{4}', example_number='6497101234', possible_length=(10,), possible_length_local_only=(7,)), national_prefix='1', national_prefix_for_parsing='1', leading_digits='649')
[ "me15btech11039@iith.ac.in.com" ]
me15btech11039@iith.ac.in.com
a4b2d7963db02f8c672477e5f95f24874ba73fdb
9e988c0dfbea15cd23a3de860cb0c88c3dcdbd97
/sdBs/AllRun/pg_1605+123/sdB_pg_1605+123_lc.py
0bb502fdc840c769372947da5add7de5f4ec3f0b
[]
no_license
tboudreaux/SummerSTScICode
73b2e5839b10c0bf733808f4316d34be91c5a3bd
4dd1ffbb09e0a599257d21872f9d62b5420028b0
refs/heads/master
2021-01-20T18:07:44.723496
2016-08-08T16:49:53
2016-08-08T16:49:53
65,221,159
0
0
null
null
null
null
UTF-8
Python
false
false
345
py
from gPhoton.gAperture import gAperture def main(): gAperture(band="NUV", skypos=[242.076542,12.200892], stepsz=30., csvfile="/data2/fleming/GPHOTON_OUTPU/LIGHTCURVES/sdBs/sdB_pg_1605+123/sdB_pg_1605+123_lc.csv", maxgap=1000., overwrite=True, radius=0.00555556, annulus=[0.005972227,0.0103888972], verbose=3) if __name__ == "__main__": main()
[ "thomas@boudreauxmail.com" ]
thomas@boudreauxmail.com
fbaa8321206abbc95d0c0afcb5d6add91cba179d
30d02ec6dd309dced011d266ca40bace293fb23e
/20210125/min_cost_climbing_stairs.py
364d94212e31ff42f3ac84aab24719ebdbb696b9
[]
no_license
jyeoniii/algorithm
b72f5e9f7fe63098c251bcc1585787ba39ca750c
7d80e27aec8fbac936911ee78a92c47b00daa3ba
refs/heads/master
2023-04-15T01:39:41.149528
2021-04-22T13:55:58
2021-04-22T13:55:58
316,533,879
0
0
null
null
null
null
UTF-8
Python
false
false
355
py
# https://leetcode.com/problems/min-cost-climbing-stairs/ from typing import List class Solution: def minCostClimbingStairs(self, cost: List[int]) -> int: dp = [0] * len(cost) dp[0], dp[1] = cost[0], cost[1] for i in range(2, len(cost)): dp[i] = min(dp[i-2], dp[i-1]) + cost[i] return min(dp[-1], dp[-2])
[ "jaykim9438@gmail.com" ]
jaykim9438@gmail.com
10063675a5f60fefde1348935aca932ecf817962
1ba58b17f33122abf4236e9e430a51d375e0eb53
/km72/Lesiuk_Andrew/3/task7.py
5193e638cd6293de20a4c88f3e2230d7f4a8f580
[]
no_license
igortereshchenko/amis_python
c4f8d86b88ab036d08ff0ce35c9b42ebeabecc42
c6f0f2a70c82d5f269b3078eb296f82271b5bb10
refs/heads/master
2021-10-22T16:21:19.990650
2017-11-01T07:26:54
2017-11-01T07:26:54
104,785,028
0
139
null
2020-04-21T21:27:09
2017-09-25T18:11:42
Python
UTF-8
Python
false
false
466
py
print('Програма визначає скільки показуватиме годинник') while True: N=int(input('Введіть скільки часу пройшло після півночі\n')) if N<0: print('Час маэ бути додатнім') else: break t = N//1440 print('Кількість днів:', t) print('Кількість годин:', t//60) print('Кількість хвилин:', t%60)
[ "noreply@github.com" ]
igortereshchenko.noreply@github.com
a664baac4f20445be3d45180f262f6795c2cb852
41b4702e359e3352116eeecf2bdf59cb13c71cf2
/full_model_walker_param/rand_param_envs/rand_param_envs/gym/error.py
3cbf07f1aebc146761fed6c16430dfa2594c62c8
[]
no_license
CaralHsi/Multi-Task-Batch-RL
b0aad53291c1713fd2d89fa4fff4a85c98427d4d
69d29164ab7d82ec5e06a929ed3b96462db21853
refs/heads/master
2022-12-22T19:23:45.341092
2020-10-01T00:05:36
2020-10-01T00:05:36
null
0
0
null
null
null
null
UTF-8
Python
false
false
3,413
py
import sys class Error(Exception): pass # Local errors class Unregistered(Error): """Raised when the user requests an item from the registry that does not actually exist. """ pass class UnregisteredEnv(Unregistered): """Raised when the user requests an env from the registry that does not actually exist. """ pass class UnregisteredBenchmark(Unregistered): """Raised when the user requests an env from the registry that does not actually exist. """ pass class DeprecatedEnv(Error): """Raised when the user requests an env from the registry with an older version number than the latest env with the same name. """ pass class UnseedableEnv(Error): """Raised when the user tries to seed an env that does not support seeding. """ pass class DependencyNotInstalled(Error): pass class UnsupportedMode(Exception): """Raised when the user requests a rendering mode not supported by the environment. """ pass class ResetNeeded(Exception): """When the monitor is active, raised when the user tries to step an environment that's already done. """ pass class ResetNotAllowed(Exception): """When the monitor is active, raised when the user tries to step an environment that's not yet done. """ pass class InvalidAction(Exception): """Raised when the user performs an action not contained within the action space """ pass # API errors class APIError(Error): def __init__(self, message=None, http_body=None, http_status=None, json_body=None, headers=None): super(APIError, self).__init__(message) if http_body and hasattr(http_body, 'decode'): try: http_body = http_body.decode('utf-8') except: http_body = ('<Could not decode body as utf-8. ' 'Please report to gym@openai.com>') self._message = message self.http_body = http_body self.http_status = http_status self.json_body = json_body self.headers = headers or {} self.request_id = self.headers.get('request-id', None) def __unicode__(self): if self.request_id is not None: msg = self._message or "<empty message>" return u"Request {0}: {1}".format(self.request_id, msg) else: return self._message if sys.version_info > (3, 0): def __str__(self): return self.__unicode__() else: def __str__(self): return unicode(self).encode('utf-8') class APIConnectionError(APIError): pass class InvalidRequestError(APIError): def __init__(self, message, param, http_body=None, http_status=None, json_body=None, headers=None): super(InvalidRequestError, self).__init__( message, http_body, http_status, json_body, headers) self.param = param class AuthenticationError(APIError): pass class RateLimitError(APIError): pass # Video errors class VideoRecorderError(Error): pass class InvalidFrame(Error): pass # Wrapper errors class DoubleWrapperError(Error): pass class WrapAfterConfigureError(Error): pass
[ "jil021@eng.ucsd.edu" ]
jil021@eng.ucsd.edu
58e7e2647dbe0a4e0415a8e2ee79e7efd343560e
facb8b9155a569b09ba66aefc22564a5bf9cd319
/wp2/era5_scripts/01_netCDF_extraction/erafive902TG/606-tideGauge.py
2cf848516a1ff591f435d0ff9083a5bb228a8912
[]
no_license
moinabyssinia/modeling-global-storm-surges
13e69faa8f45a1244a964c5de4e2a5a6c95b2128
6e385b2a5f0867df8ceabd155e17ba876779c1bd
refs/heads/master
2023-06-09T00:40:39.319465
2021-06-25T21:00:44
2021-06-25T21:00:44
229,080,191
0
0
null
null
null
null
UTF-8
Python
false
false
4,595
py
# -*- coding: utf-8 -*- """ Created on Mon Jun 01 10:00:00 2020 ERA5 netCDF extraction script @author: Michael Tadesse """ import time as tt import os import pandas as pd from d_define_grid import Coordinate, findPixels, findindx from c_read_netcdf import readnetcdf from f_era5_subsetV2 import subsetter def extract_data(delta= 1): """ This is the master function that calls subsequent functions to extract uwnd, vwnd, slp for the specified tide gauges delta: distance (in degrees) from the tide gauge """ print('Delta = {}'.format(delta), '\n') #defining the folders for predictors nc_path = {'slp' : "/lustre/fs0/home/mtadesse/era_five/slp",\ "wnd_u": "/lustre/fs0/home/mtadesse/era_five/wnd_u",\ 'wnd_v' : "/lustre/fs0/home/mtadesse/era_five/wnd_v"} surge_path = "/lustre/fs0/home/mtadesse/obs_surge" csv_path = "/lustre/fs0/home/mtadesse/erafive_localized" #cd to the obs_surge dir to get TG information os.chdir(surge_path) tg_list = os.listdir() ################################# #looping through the predictor folders ################################# for pf in nc_path.keys(): print(pf, '\n') os.chdir(nc_path[pf]) #################################### #looping through the years of the chosen predictor #################################### for py in os.listdir(): os.chdir(nc_path[pf]) #back to the predictor folder print(py, '\n') #get netcdf components - give predicor name and predictor file nc_file = readnetcdf(pf, py) lon, lat, time, pred = nc_file[0], nc_file[1], nc_file[2], \ nc_file[3] x = 606 y = 607 #looping through individual tide gauges for t in range(x, y): #the name of the tide gauge - for saving purposes # tg = tg_list[t].split('.mat.mat.csv')[0] tg = tg_list[t] #extract lon and lat data from surge csv file print("tide gauge", tg, '\n') os.chdir(surge_path) if os.stat(tg).st_size == 0: print('\n', "This tide gauge has no surge data!", '\n') continue surge = pd.read_csv(tg, header = None) #surge_with_date = add_date(surge) #define tide gauge coordinate(lon, lat) tg_cord = Coordinate(float(surge.iloc[1,4]), float(surge.iloc[1,5])) print(tg_cord) #find closest grid points and their indices close_grids = findPixels(tg_cord, delta, lon, lat) ind_grids = findindx(close_grids, lon, lat) ind_grids.columns = ['lon', 'lat'] #loop through preds# #subset predictor on selected grid size print("subsetting \n") pred_new = subsetter(pred, ind_grids, time) #create directories to save pred_new os.chdir(csv_path) #tide gauge directory tg_name = tg.split('.csv')[0] try: os.makedirs(tg_name) os.chdir(tg_name) #cd to it after creating it except FileExistsError: #directory already exists os.chdir(tg_name) #predictor directory pred_name = pf try: os.makedirs(pred_name) os.chdir(pred_name) #cd to it after creating it except FileExistsError: #directory already exists os.chdir(pred_name) #time for saving file print("saving as csv") yr_name = py.split('_')[-1] save_name = '_'.join([tg_name, pred_name, yr_name])\ + ".csv" pred_new.to_csv(save_name) #return to the predictor directory os.chdir(nc_path[pf]) #run script extract_data(delta= 1)
[ "michaelg.tadesse@gmail.com" ]
michaelg.tadesse@gmail.com
59a4a14b9d124e2ebce3cf2bee85efcd5d00fa6b
ca7aa979e7059467e158830b76673f5b77a0f5a3
/Python_codes/p03722/s588134158.py
2ca94082b4c983d18464cd5ca89025e819443681
[]
no_license
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
UTF-8
Python
false
false
1,902
py
from collections import defaultdict, deque, Counter from heapq import heappush, heappop, heapify import math import bisect import random from itertools import permutations, accumulate, combinations, product import sys from copy import deepcopy import string from bisect import bisect_left, bisect_right from math import factorial, ceil, floor from operator import mul from functools import reduce sys.setrecursionlimit(2147483647) INF = 10 ** 20 def LI(): return list(map(int, sys.stdin.buffer.readline().split())) def I(): return int(sys.stdin.buffer.readline()) def LS(): return sys.stdin.buffer.readline().rstrip().decode('utf-8').split() def S(): return sys.stdin.buffer.readline().rstrip().decode('utf-8') def IR(n): return [I() for i in range(n)] def LIR(n): return [LI() for i in range(n)] def SR(n): return [S() for i in range(n)] def LSR(n): return [LS() for i in range(n)] def SRL(n): return [list(S()) for i in range(n)] mod = 1000000007 n, m = LI() G = [[] for _ in range(n)] for a, b, c in LIR(m): G[a - 1] += [(b - 1, c)] # 負の閉路がなかったら高々n-1回で更新は終わるはずn回目に更新が起こったとしたら負の閉路がある。 def bellman_ford(G, s=0): n = len(G) dist = [-INF] * n dist[s] = 0 v_nows = {s} for _ in range(n): v_changeds = set() for u in v_nows: for v, c in G[u]: if dist[u] + c > dist[v]: dist[v] = dist[u] + c v_changeds.add(v) v_nows = v_changeds if not v_changeds: return dist[n - 1] for i in v_nows: dist[i] = INF dq = deque(v_nows) while dq: u = dq.popleft() if u == n - 1: return "inf" for v, c in G[u]: if dist[v] != INF: dist[v] = INF dq += [v] return dist[n - 1] print(bellman_ford(G))
[ "66529651+Aastha2104@users.noreply.github.com" ]
66529651+Aastha2104@users.noreply.github.com
a44dda549816cfa2bb70f000b27b7c4ae8270f22
049584769071069cd4ebb83a4a519093ba57eb87
/src/billing/migrations/0023_auto_20150620_1546.py
173e44e8784fa6c344130f8c12801a8d85ca02f4
[]
no_license
kij8323/mysite_server_version
4c1c29b0d0b6eb5d91907d44105a347a0ff58a54
d58ddd79626772d8b71e539f00cdf45763ab2a00
refs/heads/master
2016-09-05T23:34:14.584462
2015-12-21T12:45:39
2015-12-21T12:45:39
38,934,170
0
0
null
null
null
null
UTF-8
Python
false
false
869
py
# -*- coding: utf-8 -*- from __future__ import unicode_literals from django.db import models, migrations import datetime from django.utils.timezone import utc class Migration(migrations.Migration): dependencies = [ ('billing', '0022_auto_20150620_1545'), ] operations = [ migrations.AlterField( model_name='membership', name='date_end', field=models.DateTimeField(default=datetime.datetime(2015, 6, 20, 15, 46, 54, 250929, tzinfo=utc), verbose_name=b'End Date'), preserve_default=True, ), migrations.AlterField( model_name='membership', name='date_start', field=models.DateTimeField(default=datetime.datetime(2015, 6, 20, 15, 46, 54, 250955, tzinfo=utc), verbose_name=b'Start Date'), preserve_default=True, ), ]
[ "shenanping2008@Hotmail.com" ]
shenanping2008@Hotmail.com
21696ee9099e81ed55415a70fe21f018e45ad988
3be1ddf42236a1b33ec74ed3bfdd0f8918513733
/coding-challenges/week05/day3/apartment/class_bed.py
808418561319a7ae9f5d0a65e2ca972b02df1795
[]
no_license
aabhishek-chaurasia-au17/MyCoding_Challenge
84ef926b550b3f511f1c642fe35f4303c8abb949
419d02ad8740a2c00403fd30c661074266d2ba8f
refs/heads/main
2023-08-29T09:52:36.796504
2021-11-07T07:32:09
2021-11-07T07:32:09
359,842,173
1
0
null
null
null
null
UTF-8
Python
false
false
1,250
py
""" 1. The Bed Object has the following attributes: length: length of the bed in feet breadth: breadth of the bed in feet year_made: Year in which the bed was made has_headboard: True or False depending on whether the bed has a headboard or not has_posts: True or False depending on whether the bed has sideposts or not material: material is wood, steel, plywood and so on. 2. The Bed Object does not support any following methods """ class Bed(): # Beds class made with followings attributes def __init__(self,length,breadth,year_made,has_headboard,has_posts,material): self.length = f"The length of the bed in feet is : {length} feet " self.breadth = f"The breadth of the bed in feet is {breadth} feet " self.year_made = f"The bed is made in the year of : {year_made} " self.has_headboard = f"This bed has headboard : {has_headboard} " self.has_posts = f"This bed has posts : {has_posts} " self.material = f"The materials that use to make the bed is : {material}" my_bed = Bed(10,5,2015,True,False,'Wood') # for checking just uncomment below lines print(my_bed.length) print(my_bed.breadth) print(my_bed.year_made) print(my_bed.has_headboard) print(my_bed.has_posts) print(my_bed.material)
[ "abhishekc838@gmail.com" ]
abhishekc838@gmail.com
1295ed4099b439863d64290c637f977703fbdfa8
59c746c28bff4afcc99a13b4ddd9aa42365f3348
/dashboard/forms.py
fc8e64f55aa24a9c972d5f06f17d354cc0fa2fd2
[]
no_license
lucassimon/django-sendgrid
c228fe6f5bc871181c82c18c20837080fe6bb47f
4e34fc0f7072ebcf06ee91764e220f0aa94904e6
refs/heads/master
2021-01-20T08:01:04.948950
2017-07-07T13:33:12
2017-07-07T13:33:12
90,080,629
0
0
null
null
null
null
UTF-8
Python
false
false
956
py
# -*- coding:utf-8 -*- from __future__ import unicode_literals # Stdlib imports # Core Django imports from django import forms from django.utils.translation import ugettext as _ # Third-party app imports # Realative imports of the 'app-name' package from .models import Scheduling class DashboardCustomerServiceForm(forms.Form): start_date = forms.DateField() end_date = forms.DateField() class Meta: fields = '__all__' help_texts = { 'start_date': _( _(u'Data Inicial.') ), 'end_date': _( _(u'Data Final.') ), } widgets = { 'start_date': forms.DateInput( attrs={ 'class': 'form-control', }, ), 'end_date': forms.DateInput( attrs={ 'class': 'form-control', }, ), }
[ "lucassrod@gmail.com" ]
lucassrod@gmail.com
2f1c8c27aa6df64d188f2e053ca56184acd42928
952243fed6885563cb9631e3bea6f367cb19a30c
/calendars/views.py
21013fbaf8c3647d2d467a3eccd72cdc131acdd1
[]
no_license
Kang-kyunghun/batch_calendar
8380d8ccad958341e9e0050f7a4b710ab0daa973
76570bfd3816001c3be7714554100cf7d57948c9
refs/heads/main
2023-08-01T11:51:27.045435
2021-04-25T07:48:48
2021-04-25T07:48:48
406,577,277
0
0
null
null
null
null
UTF-8
Python
false
false
5,743
py
import json import requests import progressbar from time import sleep from pprint import pprint from datetime import datetime, timedelta from dateutil.relativedelta import relativedelta from django.http import HttpResponse, JsonResponse from django.views import View from django.shortcuts import render, get_object_or_404 from .models import Batch, Calendar token = "ya29.a0AfH6SMBtPkM8F-eKJD4liR4GwxJwL_IiBya-Z7vpkmdtXQ8dY3x3gOBSDSh3xAHM-Dr2u5gjkAF8vpHuVz61U3s0ky-vOH5CBSVpGkGbguy96P9LEL_Q8d_d1JX5qIeGDhjpyTitY7_puCahTJXq3QLr_uxaYStYZsFU9XVpGtw" class BatchesView(View): def get(self, request): batch_list = Batch.objects.all() output = ', '.join([batch.name for batch in batch_list]) context = {'batch_list' : batch_list} return render(request, 'batches/index.html', context) class CalendarsView(View): def get(self, request): calendar_list = Calendar.objects.all() output = ', '.join([calendar.name for calendar in calendar_list]) context = {'calendar_list' : calendar_list} return render(request, 'calendars/index.html', context) class CalendarView(View): def get(self, request, calendar_id): calendar = get_object_or_404(Calendar, pk = calendar_id) return render(request, 'calendars/detail.html', {'calendar' : calendar}) class GoogleCalendarsView(View): def get(self, request): google_calendar_list = requests.get('https://www.googleapis.com/calendar/v3/users/me/calendarList?access_token=' + token) calendars = google_calendar_list.json()['items'] batch_calendars = [calendar for calendar in calendars] output = ', '.join([calendar['summary'] for calendar in batch_calendars]) return JsonResponse({'result':batch_calendars}, status=200) class GoogleCalendarEventsView(View): def get(self, request, calendar_id): event_list = requests.get(f'https://www.googleapis.com/calendar/v3/calendars/{calendar_id}/events?showDeleted=False&singleEvents=True&access_token=' + token) print("CURRENT_CALENDAR : ", event_list.json()['summary']) events = [ { 'id' : event['id'], 'name' : event.get('summary', None), 'start_time' : event['start']['dateTime'] if 'start' in event else None, 'end_time' : event['end']['dateTime'] if 'end' in event else None } for event in event_list.json()['items'] ] return JsonResponse({'events' : events, 'number_of_events' : len(events)}, status=200) def post(self, request, calendar_id): payload = json.loads(request.body) referenced_calendar_id = payload['referenced_calendar_id'] week_added = payload['week_added'] referenced_event_list = requests.get(f'https://www.googleapis.com/calendar/v3/calendars/{referenced_calendar_id}/events?showDeleted=False&singleEvents=True&access_token=' + token) print('CURRENT_CALENDAR : ', referenced_event_list.json()['summary']) events = referenced_event_list.json()['items'] for event in events: print('CURRENT_EVENT: ', event['summary']) print('DATE_TIME: ', event['start']['dateTime'][:10]) if datetime.strptime(event['start']['dateTime'], '%Y-%m-%dT%H:%M:%SZ') < datetime(2021, 2, 8): body = { 'summary' : event['summary'].replace('[16기]',''), 'start' : { 'dateTime' : (datetime.strptime(event['start']['dateTime'],'%Y-%m-%dT%H:%M:%SZ') + relativedelta(weeks=week_added)).strftime('%Y-%m-%dT%H:%M:%SZ') }, 'end' : { 'dateTime' : (datetime.strptime(event['end']['dateTime'],'%Y-%m-%dT%H:%M:%SZ') + relativedelta(weeks=week_added)).strftime('%Y-%m-%dT%H:%M:%SZ') }, } else: body = { 'summary' : event['summary'].replace('[16기]',''), 'start' : { 'dateTime' : (datetime.strptime(event['start']['dateTime'],'%Y-%m-%dT%H:%M:%SZ') + relativedelta(weeks=week_added-1)).strftime('%Y-%m-%dT%H:%M:%SZ') }, 'end' : { 'dateTime' : (datetime.strptime(event['end']['dateTime'],'%Y-%m-%dT%H:%M:%SZ') + relativedelta(weeks=week_added-1)).strftime('%Y-%m-%dT%H:%M:%SZ') }, } # if '[16기]' in event['summary']: # body['summary'] = event['summary'].replace('[16기]', '') # # if '[Back]' in event['summary']: # body['summary'] = event['summary'].replace('[Back]', 'Session - Back |') # # if '[Front]' in event['summary']: # body['summary'] = event['summary'].replace('[Front]', 'Session - Front |') # # if 'Code Kata' in event['summary']: # body['summary'] = event['summary'].replace(event['summary'][-3]+'주차', 'week'+event['summary'][-3]) # # if '1:1 면담' in event['summary']: # continue a = requests.post(f'https://www.googleapis.com/calendar/v3/calendars/{calendar_id}/events?access_token=' + token, json=body) return JsonResponse({'result' : 'ok'}, status=200) def delete(self, request, calendar_id): event_list = requests.get(f'https://www.googleapis.com/calendar/v3/calendars/{calendar_id}/events?showDeleted=False&singleEvents=True&access_token=' + token).json()['items'] for event in event_list: print(event['summary']) event_id = event['id'] a = requests.delete(f"https://www.googleapis.com/calendar/v3/calendars/{calendar_id}/events/{event_id}?access_token=" + token) return JsonResponse({'messae': 'ok'})
[ "lsheon93@gmail.com" ]
lsheon93@gmail.com
11f5989b5de10bec420830d71d06778129715373
b68c92fe89b701297f76054b0f284df5466eb698
/Other/Daily/InsertIntoSortedCircularList.py
ce812f2208b6741a286fbcf4ddf906fefa62ae38
[]
no_license
makrandp/python-practice
32381a8c589f9b499ab6bde8184a847b066112f8
60218fd79248bf8138158811e6e1b03261fb38fa
refs/heads/master
2023-03-27T18:11:56.066535
2021-03-28T04:02:00
2021-03-28T04:02:00
null
0
0
null
null
null
null
UTF-8
Python
false
false
2,278
py
''' Given a node from a Circular Linked List which is sorted in ascending order, write a function to insert a value insertVal into the list such that it remains a sorted circular list. The given node can be a reference to any single node in the list, and may not be necessarily the smallest value in the circular list. If there are multiple suitable places for insertion, you may choose any place to insert the new value. After the insertion, the circular list should remain sorted. If the list is empty (i.e., given node is null), you should create a new single circular list and return the reference to that single node. Otherwise, you should return the original given node. ''' """ # Definition for a Node. class Node: def __init__(self, val=None, next=None): self.val = val self.next = next """ from typing import List class Solution: def insert(self, head: 'Node', insertVal: int) -> 'Node': # Handling null if head == None: n = Node(insertVal) n.next = n return n # Handling a size one if head.next == head: n = Node(insertVal, head) head.next = n return n n = head while True: if n.next.val < n.val: # We've reached the end # Time to decide if we are going to insert here or just after if n.val <= insertVal: # Our insert val is greater than or equal to the maximum value # We will insert here break elif insertVal <= n.next.val: # We will insert at the bottom break if n.val <= insertVal and n.next.val >= insertVal: break n = n.next # If we've ever reached the head, again, we have a circular array with all the same numbers if n == head: break # Inserting print(n.val) pointNext = n.next node = Node(insertVal, pointNext) n.next = node return head
[ "awalexweber99@gmail.com" ]
awalexweber99@gmail.com
2e810e00ffe4dad728bcd1f47ef0855f39af6474
bffd93e3ba15915c5b929ac75303d2e124db6a24
/app/api_v1_2/domain/app_infos.py
7c5e8d4ec0d38e006312737af67c1cf3271c5fca
[]
no_license
themycode/MobileToolPlatform
fe7140ede1069495fd077364e7b932f3e7e8299d
1569f06dcd9f3b9a4a699e47cf6724d90f8a84c8
refs/heads/master
2021-10-26T15:05:44.859610
2019-04-13T10:38:27
2019-04-13T10:38:27
null
0
0
null
null
null
null
UTF-8
Python
false
false
399
py
#!/usr/bin/env python # -*- coding: utf-8 -*- """ @version: v1.0 @author: jayzhen @license: Apache Licence @email: jayzhen_testing@163.com @software: PyCharm """ class App(object): def __init__(self): self.uid = None self.pid = None self.cpu = None self.mem = None self.gfx = None self.net = None self.bat = None self.fps = None
[ "jayzhen_testing@163.com" ]
jayzhen_testing@163.com
376168fe008d4a2ec6337a3ab692cb9eca743790
296a60e4ca32f326dde269fd6eec5a5e0c8f743c
/site_app/migrations/0004_post.py
9998a41892458ea6a4abda1fa20d0d3a08ba1e7a
[]
no_license
Najafova/company_introduction_landingpage1
758790ae4a1565f65b2714db000c2dac7c3128b1
bb3d212a2057605f90fa5881804acaecfaf61788
refs/heads/master
2022-12-01T09:46:36.251346
2020-03-19T14:33:11
2020-03-19T14:33:11
248,525,225
0
0
null
2022-11-22T03:38:32
2020-03-19T14:32:56
JavaScript
UTF-8
Python
false
false
845
py
# Generated by Django 2.1.7 on 2019-02-18 07:44 import ckeditor.fields from django.db import migrations, models class Migration(migrations.Migration): dependencies = [ ('site_app', '0003_team_image'), ] operations = [ migrations.CreateModel( name='Post', fields=[ ('id', models.AutoField(auto_created=True, primary_key=True, serialize=False, verbose_name='ID')), ('title', models.CharField(blank=True, max_length=255, null=True)), ('description', ckeditor.fields.RichTextField(blank=True, null=True)), ('body', models.TextField(blank=True, null=True)), ('order', models.IntegerField(blank=True, null=True)), ('slug', models.SlugField(blank=True, default='')), ], ), ]
[ "gulnarnecefova1996@gmail.com" ]
gulnarnecefova1996@gmail.com
3f1f6c50edaa6b7434171b31a68951df9f9c29e8
3cdb4faf34d8375d6aee08bcc523adadcb0c46e2
/web/env/lib/python3.6/site-packages/django/conf/locale/th/formats.py
d7394eb69c315129df90d1aeeee0ca61a9a79231
[ "MIT", "GPL-3.0-only" ]
permissive
rizwansoaib/face-attendence
bc185d4de627ce5adab1cda7da466cb7a5fddcbe
59300441b52d32f3ecb5095085ef9d448aef63af
refs/heads/master
2020-04-25T23:47:47.303642
2019-09-12T14:26:17
2019-09-12T14:26:17
173,157,284
45
12
MIT
2020-02-11T23:47:55
2019-02-28T17:33:14
Python
UTF-8
Python
false
false
1,072
py
# This file is distributed under the same license as the Django package. # # The *_FORMAT strings use the Django date format syntax, # see https://docs.djangoproject.com/en/dev/ref/templates/builtins/#date DATE_FORMAT = 'j F Y' TIME_FORMAT = 'G:i' DATETIME_FORMAT = 'j F Y, G:i' YEAR_MONTH_FORMAT = 'F Y' MONTH_DAY_FORMAT = 'j F' SHORT_DATE_FORMAT = 'j M Y' SHORT_DATETIME_FORMAT = 'j M Y, G:i' FIRST_DAY_OF_WEEK = 0 # Sunday # The *_INPUT_FORMATS strings use the Python strftime format syntax, # see https://docs.python.org/library/datetime.html#strftime-strptime-behavior DATE_INPUT_FORMATS = [ '%d/%m/%Y', # 25/10/2006 '%d %b %Y', # 25 ต.ค. 2006 '%d %B %Y', # 25 ตุลาคม 2006 ] TIME_INPUT_FORMATS = [ '%H:%M:%S', # 14:30:59 '%H:%M:%S.%f', # 14:30:59.000200 '%H:%M', # 14:30 ] DATETIME_INPUT_FORMATS = [ '%d/%m/%Y %H:%M:%S', # 25/10/2006 14:30:59 '%d/%m/%Y %H:%M:%S.%f', # 25/10/2006 14:30:59.000200 '%d/%m/%Y %H:%M', # 25/10/2006 14:30 ] DECIMAL_SEPARATOR = '.' THOUSAND_SEPARATOR = ',' NUMBER_GROUPING = 3
[ "rizwansoaib@gmail.com" ]
rizwansoaib@gmail.com
9ed93ded054e5409a3857b0612a1e109381b47cb
771fc415b752721b89d418a510eb3e6a447a075c
/sitl_config/usv/vrx_gazebo/nodes/quat2rpy.py
59a0a59de70be5baa82f09ba62ad55eae7cc6657
[ "MIT" ]
permissive
robin-shaun/XTDrone
ebf8948ed44bf8fc796263a18aef8a985ac00e12
6ee0a3033b5eed8fcfddc9b3bfee7a4fb26c79db
refs/heads/master
2023-09-02T10:49:03.888060
2023-07-16T13:02:07
2023-07-16T13:02:07
248,799,809
815
182
null
2020-09-17T12:50:46
2020-03-20T16:16:52
Python
UTF-8
Python
false
false
3,454
py
#!/usr/bin/env python ''' Node to convert from quaternions to rpy in various ROS messages ''' import rospy import tf from geometry_msgs.msg import Vector3 from geometry_msgs.msg import Pose from geometry_msgs.msg import PoseArray from sensor_msgs.msg import Imu from gazebo_msgs.msg import ModelStates from nav_msgs.msg import Odometry class Node(): def __init__(self,pose_index=None,model_name=None, input_msg_type='Pose'): self.pubmsg = None self.pub = None self.pose_index = pose_index self.model_name = model_name self.input_msg_type = input_msg_type def callback(self,data): #rospy.loginfo("callback") if (not (pose_index==None)): data = data[pose_index] elif self.model_name is not None: try: index = data.name.index(model_name) except ValueError: rospy.logwarn_throttle(10.0, 'Model state {} not found'.format(model_name)) return data = data.pose[index] elif ( (self.input_msg_type == 'Pose') or (self.input_msg_type == 'Imu')): pass elif self.input_msg_type == 'Odometry': data = data.pose.pose else: rospy.logerr("Don't know what to do with message type %s"% self.input_msg_type) sys.exit() q = (data.orientation.x, data.orientation.y, data.orientation.z, data.orientation.w) euler = tf.transformations.euler_from_quaternion(q) self.pubmsg.x = euler[0] self.pubmsg.y = euler[1] self.pubmsg.z = euler[2] rospy.logdebug("publishing rpy: %.2f, %.2f, %.2f" %(euler[0],euler[1],euler[2])) self.pub.publish(self.pubmsg) if __name__ == '__main__': rospy.init_node('quat2rpy', anonymous=True) # ROS Parameters in_topic = 'in_topic' out_topic = 'out_topic' pose_index = rospy.get_param('~pose_index',None) model_name = rospy.get_param('~model_name',None) inmsgtype = rospy.get_param('~input_msg_type','Pose') # Initiate node object node=Node(pose_index, model_name, input_msg_type=inmsgtype) node.pubmsg = Vector3() # Setup publisher node.pub = rospy.Publisher(out_topic,Vector3,queue_size=10) # Subscriber if (not(model_name == None)): inmsgtype = 'ModelStates[%s]'% model_name rospy.Subscriber(in_topic,ModelStates,node.callback) elif (not (pose_index == None)): inmsgtype = 'PoseArray[%d]'%pose_index # Setup subscriber rospy.Subscriber(in_topic,PoseArray,node.callback) else: if inmsgtype == 'Pose': # Setup subscriber rospy.Subscriber(in_topic,Pose,node.callback) elif inmsgtype == 'Imu': rospy.Subscriber(in_topic,Imu,node.callback) elif inmsgtype == 'Odometry': rospy.Subscriber(in_topic,Odometry,node.callback) else: rospy.logerr("I don't know how to deal with message type <%s>"% inmsgtype) sys.exit() rospy.loginfo("Subscribing to %s, looking for %s messages."% (in_topic,inmsgtype)) rospy.loginfo("Publishing to %s, sending Vector3 messages"% (out_topic)) try: rospy.spin() except rospy.ROSInterruptException: pass
[ "robin_shaun@foxmail.com" ]
robin_shaun@foxmail.com
9b6478662fe7153eccd5d4eb415af97ac57aec2b
f674baa2f4ca0ac0ab856bd2ae3df6317278faf8
/message/migrations/0001_initial.py
d07d4ae40786a92748a0dcb91691844b265dca88
[]
no_license
youichiro/nutfes-staff-app
3d6e869cbc3f35c78f7ef1230fae3e075de4d445
f3aed87b0fc27f99591f135aa2b73f54029c5560
refs/heads/master
2020-03-26T18:48:54.117252
2018-09-16T03:06:38
2018-09-16T03:06:38
145,232,347
0
0
null
null
null
null
UTF-8
Python
false
false
1,681
py
# Generated by Django 2.0.7 on 2018-08-25 09:42 from django.conf import settings from django.db import migrations, models import django.db.models.deletion class Migration(migrations.Migration): initial = True dependencies = [ migrations.swappable_dependency(settings.AUTH_USER_MODEL), ] operations = [ migrations.CreateModel( name='Message', fields=[ ('id', models.AutoField(primary_key=True, serialize=False)), ('text', models.TextField(max_length=1000)), ('importance', models.CharField(max_length=10)), ('created_at', models.DateTimeField(auto_now_add=True)), ('updated_at', models.DateTimeField(auto_now=True)), ('user', models.ForeignKey(on_delete=django.db.models.deletion.PROTECT, to=settings.AUTH_USER_MODEL)), ], options={ 'db_table': 'messages', }, ), migrations.CreateModel( name='Reply', fields=[ ('id', models.AutoField(primary_key=True, serialize=False)), ('text', models.TextField(max_length=1000)), ('created_at', models.DateTimeField(auto_now_add=True)), ('updated_at', models.DateTimeField(auto_now=True)), ('message', models.ForeignKey(on_delete=django.db.models.deletion.PROTECT, to='message.Message')), ('user', models.ForeignKey(on_delete=django.db.models.deletion.PROTECT, to=settings.AUTH_USER_MODEL)), ], options={ 'db_table': 'replies', }, ), ]
[ "cinnamon416@gmail.com" ]
cinnamon416@gmail.com
6d5cfbd9dfb220db9c0d966b0284b9e5bddfc680
a5c4ea16042a8078e360c32636c00e3163ac99a8
/ImagenetBundle/chapter09-squeezenet/pyimagesearch/nn/mxconv/mxsqueezenet.py
d176140b5694953ac7b3adf83c600d3e497b6c13
[]
no_license
lykhahaha/Mine
3b74571b116f72ee17721038ca4c58796610cedd
1439e7b161a7cd612b0d6fa4403b4c8c61648060
refs/heads/master
2020-07-15T05:16:13.808047
2019-06-01T07:30:01
2019-06-01T07:30:01
null
0
0
null
null
null
null
UTF-8
Python
false
false
3,000
py
imprt mxnet as mx class MxSqueezeNet: @staticmethod def squeeze(data, num_filter): # the first part of FIRE module consists of a number of 1x1 filter squuezes conv_1x1 = mx.sym.Convolution(data=data, kernel=(1, 1), num_filter=num_filter) act_1x1 = mx.sym.LeakyReLU(data=conv_1x1, act_type='elu') return act_1x1 @staticmethod def fire(data, num_squeeze_filter, num_expand_filter): # construct 1x1 squeeze followed by 1x1 expand squeeze_1x1 = MxSqueezeNet.squeeze(data, num_squeeze_filter) expand_1x1 = mx.sym.Convolution(data=squeeze_1x1, kernel=(1, 1), num_filter=num_expand_filter) relu_expand_1x1 = mx.sym.LeakyReLU(data=expand_1x1, act_type='elu') # construct 3x3 expand exapnd_3x3 = mx.sym.Convolution(data=squeeze_1x1, kernel=(3, 3), pad=(1, 1), num_filter=num_expand_filter) relu_expand_3x3 = mx.sym.LeakyReLU(data=exapnd_3x3, act_type='elu') # the output is concatenated along channels dimension output = mx.sym.Concat(relu_expand_1x1, relu_expand_3x3, dim=1) return output @staticmethod def build(classes): # data input data = mx.sym.Variable('data') # Block #1: Conv -> ReLU -> Pool conv_1 = mx.sym.Convolution(data=data, kernel=(7, 7), stride=(2, 2), num_filter=96) act_1 = mx.sym.LeakyReLU(data=conv_1, act_type='elu') pool_1 = mx.sym.Pooling(data=act_1, kernel=(3, 3), pool_type='max', stride=(2, 2)) # Block #2-4: (FIRE * 3) -> Pool fire_2 = MxSqueezeNet.fire(pool_1, num_squeeze_filter=16, num_expand_filter=64) fire_3 = MxSqueezeNet.fire(fire_2, num_squeeze_filter=16, num_expand_filter=64) fire_4 = MxSqueezeNet.fire(fire_3, num_squeeze_filter=32, num_expand_filter=128) pool_4 = mx.sym.Pooling(data=fire_4, kernel=(3, 3), pool_type='max', stride=(2, 2)) # Block #5-8 : (FIRE) * 4 -> Pool fire_5 = MxSqueezeNet.fire(pool_4, num_squeeze_filter=32, num_expand_filter=128) fire_6 = MxSqueezeNet.fire(fire_2, num_squeeze_filter=48, num_expand_filter=192) fire_7 = MxSqueezeNet.fire(fire_3, num_squeeze_filter=48, num_expand_filter=192) fire_8 = MxSqueezeNet.fire(fire_3, num_squeeze_filter=64, num_expand_filter=256) pool_8 = mx.sym.Pooling(data=fire_8, kernel=(3, 3), pool_type='max', stride=(2, 2)) # Last block: FIRE -> Dropout -> Conv -> ACT -> Pool fire_9 = MxSqueezeNet.fire(pool_8, num_squeeze_filter=64, num_expand_filter=256) do_9 = mx.sym.Dropout(data=fire_9, p=0.5) conv_10 = mx.sym.Convolution(data=do_9, kernel=(1, 1), num_filter=classes) act_10 = mx.sym.LeakyReLU(data=conv_10, act_type='elu') pool_10 = mx.sym.Pooling(data=act_10, kernel=(13, 13), pool_type='avg') # softmax classifier flatten = mx.sym.Flatten(data=pool_10) model = mx.sym.SoftmaxOutput(data=flatten, name='softmax') return model
[ "ITITIU15033@student.hcmiu.edu.vn" ]
ITITIU15033@student.hcmiu.edu.vn
1e38e86a6fe23e2fdf32b69d62392265587fe770
e55480007fde8acea46fe8eeb3ee7193c25ba113
/tests/test_ds/test_array_queue.py
8d7bfd6083cf5899b1b3906928cf2765f343ec77
[]
no_license
Annihilation7/Ds-and-Al
80301bf543ec2eb4b3a9810f5fc25b0386847fd3
a0bc5f5ef4a92c0e7a736dcff77df61d46b57409
refs/heads/master
2020-09-24T05:04:41.250051
2020-02-15T10:31:10
2020-02-15T10:31:10
225,669,366
1
0
null
null
null
null
UTF-8
Python
false
false
525
py
import unittest from src.ds.array_queue import ArrayQueue class Test_ArrayQueue(unittest.TestCase): def setUp(self) -> None: self.processer = ArrayQueue() def test_all(self): elems = [i for i in range(10)] for index, elem in enumerate(elems): if index != 0 and index % 3 == 0: self.processer.dequeue() self.processer.printQueue() continue self.processer.enqueue(elem) if __name__ == '__main__': unittest.main()
[ "763366463@qq.com" ]
763366463@qq.com
9e623f48c4ded2745ca63c8797f9d295299357eb
c05357142b9f112d401a77f9610079be3500675d
/danceschool/core/cms_apps.py
2f38fcd1bd17a22fd9ef29cfae7349cd05395ef0
[ "BSD-3-Clause" ]
permissive
NorthIsUp/django-danceschool
b3df9a9373c08e51fcaa88751e325b6423f36bac
71661830e87e45a3df949b026f446c481c8e8415
refs/heads/master
2021-01-02T22:42:17.608615
2017-08-04T17:27:37
2017-08-04T17:27:37
99,373,397
1
0
null
2017-08-04T19:21:50
2017-08-04T19:21:50
null
UTF-8
Python
false
false
601
py
from cms.app_base import CMSApp from cms.apphook_pool import apphook_pool from django.utils.translation import ugettext_lazy as _ class RegistrationApphook(CMSApp): name = _("Registration Apphook") def get_urls(self, page=None, language=None, **kwargs): return ["danceschool.core.urls_registration"] class AccountsApphook(CMSApp): name = _("Accounts Apphook") def get_urls(self, page=None, language=None, **kwargs): return ["danceschool.core.urls_accounts"] apphook_pool.register(RegistrationApphook) apphook_pool.register(AccountsApphook)
[ "lee.c.tucker@gmail.com" ]
lee.c.tucker@gmail.com
e7f97d55c16386e8fb5a231694dc710e02577ecf
68528d13d49029074ad4a312c8c16c585f755914
/scripts/average_filter.py
8d3e8dc0e8ee6af46051aae803dbf24caff97490
[ "MIT" ]
permissive
ShotaAk/pimouse_controller
8132b3d95d6387aa5fae98b60d205f3179eaa62a
a7bbbd7109e582245cab0eaa017246fd44104474
refs/heads/master
2020-03-19T04:54:40.153634
2018-06-03T12:37:47
2018-06-03T12:37:47
135,881,207
1
0
null
null
null
null
UTF-8
Python
false
false
865
py
#!/usr/bin/env python #encoding: utf8 import numpy as np import math # 移動平均フィルタ # 平均値を計算するための個数は引数sizeで指定する class AverageFilter(): def __init__(self, size): if size <= 0: size = 1 self._buffer = np.zeros(size, dtype=np.float32) self._buffer_size = size self._current_index = 0 self._filtered_value = 0 self._offset_value = 0 def update(self, value): self._buffer[self._current_index] = value self._current_index += 1 if self._current_index >= self._buffer_size: self._current_index = 0 self._filtered_value = np.average(self._buffer) def get_value(self): return self._filtered_value - self._offset_value def offset(self): self._offset_value = self._filtered_value
[ "macakasit@gmail.com" ]
macakasit@gmail.com
e6502be55f11f703cab1033ac7cf94a0df500f3c
ab97407d4f3c91142f2bed8e5c5415fbc9be8ac6
/python/Add Two Numbers.py
62baca112887e5abe3a9077ca8d65e68032a533c
[]
no_license
Lendfating/LeetCode
d328c68578d10d6cdba0c4dcb3359ddf085546e1
4cc492e04a7003839f07df93070fa9c19726a1c5
refs/heads/master
2020-12-30T09:26:20.461654
2015-02-01T08:41:46
2015-02-01T08:41:46
26,170,626
1
0
null
null
null
null
UTF-8
Python
false
false
1,625
py
#!/usr/bin/python # -*- coding: utf-8 -*- """ # soluction """ # Definition for singly-linked list. # class ListNode: # def __init__(self, x): # self.val = x # self.next = None class Solution: # @return a ListNode def addTwoNumbers(self, l1, l2): if l1 is None: return l2 dump = ListNode(0) p, p1, p2, carry = dump, l1, l2, 0 while p1 is not None and p2 is not None: carry, p.next = (p1.val+p2.val+carry)/10, ListNode((p1.val+p2.val+carry)%10) p, p1, p2 = p.next, p1.next, p2.next if p1 is not None: while p1 is not None and carry != 0: carry, p.next = (p1.val+carry)/10, ListNode((p1.val+carry)%10) p, p1 = p.next, p1.next p.next = p1 elif p2 is not None: while p2 is not None and carry != 0: carry, p.next = (p2.val+carry)/10, ListNode((p2.val+carry)%10) p, p2 = p.next, p2.next p.next = p2 if carry != 0: p.next = ListNode(carry) return dump.next # @return a ListNode def addTwoNumbers1(self, l1, l2): dump = ListNode(0) p, p1, p2, sum = dump, l1, l2, 0 while p1 is not None or p2 is not None or sum!=0: sum += (p1.val if p1 is not None else 0) + (p2.val if p2 is not None else 0) p.next = ListNode(sum%10) sum /= 10 p = p.next p1 = p1.next if p1 is not None else None p2 = p2.next if p2 is not None else None return dump.next if __name__ == '__main__': pass
[ "lizhen19900409@126.com" ]
lizhen19900409@126.com
c119089df301b537c5f9324aa655dd8ff843e348
08db28fa3836c36433aa105883a762396d4883c6
/spider/learning/day_04/07_requests_get.py
67509a6a7a53277ba40f23333df8b8ff888dea59
[]
no_license
xieyipeng/FaceRecognition
1127aaff0dd121319a8652abcfe8a59a7beaaf43
dede5b181d6b70b87ccf00052df8056a912eff0f
refs/heads/master
2022-09-19T07:02:33.624410
2020-06-02T03:03:58
2020-06-02T03:03:58
246,464,586
2
0
null
null
null
null
UTF-8
Python
false
false
635
py
import requests # 参数自动转译 # url = 'https://www.baidu.com/s?ie=UTF-8&wd=美女' url = 'http://www.baidu.com/s' params = { "wd": "美女", "ie": "utf-8" } headers = { 'User-Agent': 'Mozilla/5.0 (Windows NT 10.0; Win64; x64) AppleWebKit/537.36 (KHTML, like Gecko) Chrome/79.0.3945.117 Safari/537.36' } # response = requests.get(url, headers=headers) response = requests.get(url, headers=headers, params=params) data = response.content.decode('utf-8') with open('07requests_get.html', 'w', encoding='utf-8')as f: f.write(data) # 发送post请求 添加参数 # requests.post(url,data=(参数{}),json=(参数))
[ "3239202719@qq.com" ]
3239202719@qq.com
53c144744fd35855616f66ff8a7662edfe04d507
ec126ba7180f687d310a56f100d38f717ac1702a
/calc final.py
de96e14d474516de570ed2ef6a5efd68bdf5558d
[]
no_license
Sahil4UI/PythonJan3-4AfternoonRegular2021
0cb0f14b964125510f253a38a1b9af30024e6e68
36f83d326489c28841d2e197eb840579bc64411f
refs/heads/main
2023-03-04T21:31:56.407760
2021-02-17T10:26:51
2021-02-17T10:26:51
327,277,855
0
0
null
null
null
null
UTF-8
Python
false
false
222
py
def Calc(x,y,opr): return eval(x+opr+y) a = (input("Enter first Number : ")) b =(input("Enter second Number : ")) choice = (input("enter operation you wanna perform : ")) res = Calc(a,b,choice) print(res)
[ "noreply@github.com" ]
Sahil4UI.noreply@github.com
ad2f3075e13d53f508a2cae75716305a2f71c736
9e5452e9a8079125d2f89aedca7ca5b675171fee
/src/cargos/edible_oil.py
811d51f8f88240b59b1455c6d220d6ae97149448
[]
no_license
RadarCZ/firs
c16f8b2faf3c770c873bab948adc0bd850156dd5
da1d614c0a92b91978ff212015ed9d00c9f37607
refs/heads/master
2023-08-13T09:05:32.939857
2021-09-24T18:10:28
2021-09-24T18:10:28
null
0
0
null
null
null
null
UTF-8
Python
false
false
883
py
from cargo import Cargo cargo = Cargo( id="edible_oil", type_name="string(STR_CARGO_NAME_EDIBLE_OIL)", unit_name="string(STR_CARGO_NAME_EDIBLE_OIL)", type_abbreviation="string(STR_CID_EDIBLE_OIL)", sprite="NEW_CARGO_SPRITE", weight="1.0", is_freight="1", cargo_classes="bitmask(CC_PIECE_GOODS, CC_LIQUID)", cargo_label="EOIL", # apart from TOWNGROWTH_PASSENGERS and TOWNGROWTH_MAIL, FIRS does not set any town growth effects; this has the intended effect of disabling food / water requirements for towns in desert and above snowline town_growth_effect="TOWNGROWTH_NONE", town_growth_multiplier="1.0", units_of_cargo="TTD_STR_LITERS", items_of_cargo="string(STR_CARGO_UNIT_EDIBLE_OIL)", penalty_lowerbound="20", single_penalty_length="128", price_factor=116, capacity_multiplier="1", icon_indices=(0, 3), )
[ "andy@teamrubber.com" ]
andy@teamrubber.com
635d68f5ec22d6be70e09af9a059a4673c87a2b6
63b0fed007d152fe5e96640b844081c07ca20a11
/ABC/ABC001~ABC099/ABC062/a.py
b0e83e1c338410207e43b30673b420f1ce8d2f2d
[]
no_license
Nikkuniku/AtcoderProgramming
8ff54541c8e65d0c93ce42f3a98aec061adf2f05
fbaf7b40084c52e35c803b6b03346f2a06fb5367
refs/heads/master
2023-08-21T10:20:43.520468
2023-08-12T09:53:07
2023-08-12T09:53:07
254,373,698
0
0
null
null
null
null
UTF-8
Python
false
false
133
py
x, y = map(int, input().split()) g = [-1, 0, 2, 0, 1, 0, 1, 0, 0, 1, 0, 1, 0] ans = 'No' if g[x] == g[y]: ans = 'Yes' print(ans)
[ "ymdysk911@gmail.com" ]
ymdysk911@gmail.com
266edd864291ce9f0e8dd6c6dbe2b32c284924c9
fcc63d65284593a9ad45e28dd8c49445aa4a8d30
/manage.py
08f78aa46edb9f464700090ac1a4214dc028624c
[]
no_license
Hardworking-tester/API_SAMPLE
0b33a2ee52e4d316775a09c9c897275b26e027c9
867f0b289a01fea72081fd74fbf24b2edcfe1d2d
refs/heads/master
2021-01-23T12:32:36.585842
2017-06-23T02:31:39
2017-06-23T02:31:39
93,167,406
0
0
null
null
null
null
UTF-8
Python
false
false
612
py
# encoding:utf-8 # author:wwg from app import create_app,db from flask_script import Manager, Shell,Server from app.models import FunctionModelsDb from flask_migrate import Migrate,MigrateCommand app = create_app() manager = Manager(app) manager.add_command("runserver", Server(use_debugger=True)) # migrate=Migrate(app,db) # def make_shell_context(): # return dict(app=app, db=db, FunctionModels=FunctionModels, CaseInformation=CaseInformation) # manager.add_command("shell", Shell(make_context=make_shell_context)) # manager.add_command('db', MigrateCommand) if __name__ == '__main__': manager.run()
[ "373391120@qq.com" ]
373391120@qq.com
86cfcd2cb4cf1f59e0ea551e9420e1a9e389eaf1
a9e3f3ad54ade49c19973707d2beb49f64490efd
/Part-03-Understanding-Software-Crafting-Your-Own-Tools/models/edx-platform/common/djangoapps/student/signals/receivers.py
6af93ee1068cae5f32c12f1ee11ca6af02f5bfa3
[ "MIT", "AGPL-3.0-only", "AGPL-3.0-or-later" ]
permissive
luque/better-ways-of-thinking-about-software
8c3dda94e119f0f96edbfe5ba60ca6ec3f5f625d
5809eaca7079a15ee56b0b7fcfea425337046c97
refs/heads/master
2021-11-24T15:10:09.785252
2021-11-22T12:14:34
2021-11-22T12:14:34
163,850,454
3
1
MIT
2021-11-22T12:12:31
2019-01-02T14:21:30
JavaScript
UTF-8
Python
false
false
3,432
py
""" Signal receivers for the "student" application. """ # pylint: disable=unused-argument from django.conf import settings from django.contrib.auth import get_user_model from django.db import IntegrityError from django.db.models.signals import post_save, pre_save from django.dispatch import receiver from edx_name_affirmation.signals import VERIFIED_NAME_APPROVED from lms.djangoapps.courseware.toggles import courseware_mfe_progress_milestones_are_active from common.djangoapps.student.helpers import EMAIL_EXISTS_MSG_FMT, USERNAME_EXISTS_MSG_FMT, AccountValidationError from common.djangoapps.student.models import ( CourseEnrollment, CourseEnrollmentCelebration, PendingNameChange, is_email_retired, is_username_retired ) from common.djangoapps.student.models_api import confirm_name_change @receiver(pre_save, sender=get_user_model()) def on_user_updated(sender, instance, **kwargs): """ Check for retired usernames. """ # Check only at User creation time and when not raw. if not instance.id and not kwargs['raw']: prefix_to_check = getattr(settings, 'RETIRED_USERNAME_PREFIX', None) if prefix_to_check: # Check for username that's too close to retired username format. if instance.username.startswith(prefix_to_check): raise AccountValidationError( USERNAME_EXISTS_MSG_FMT.format(username=instance.username), field="username" ) # Check for a retired username. if is_username_retired(instance.username): raise AccountValidationError( USERNAME_EXISTS_MSG_FMT.format(username=instance.username), field="username" ) # Check for a retired email. if is_email_retired(instance.email): raise AccountValidationError( EMAIL_EXISTS_MSG_FMT.format(email=instance.email), field="email" ) @receiver(post_save, sender=CourseEnrollment) def create_course_enrollment_celebration(sender, instance, created, **kwargs): """ Creates celebration rows when enrollments are created This is how we distinguish between new enrollments that we want to celebrate and old ones that existed before we introduced a given celebration. """ if not created: return # The UI for celebrations is only supported on the MFE right now, so don't turn on # celebrations unless this enrollment's course is MFE-enabled and has milestones enabled. if not courseware_mfe_progress_milestones_are_active(instance.course_id): return try: CourseEnrollmentCelebration.objects.create( enrollment=instance, celebrate_first_section=True, ) except IntegrityError: # A celebration object was already created. Shouldn't happen, but ignore it if it does. pass @receiver(VERIFIED_NAME_APPROVED) def listen_for_verified_name_approved(sender, user_id, profile_name, **kwargs): """ If the user has a pending name change that corresponds to an approved verified name, confirm it. """ user = get_user_model().objects.get(id=user_id) try: pending_name_change = PendingNameChange.objects.get(user=user, new_name=profile_name) confirm_name_change(user, pending_name_change) except PendingNameChange.DoesNotExist: pass
[ "rafael.luque@osoco.es" ]
rafael.luque@osoco.es
0b9fc00ced102d9e7d221b9e3f42f3e11458e8d5
56f5b2ea36a2258b8ca21e2a3af9a5c7a9df3c6e
/CMGTools/H2TauTau/prod/25aug_corrMC/up/mc/GluGluToHToTauTau_M-95_8TeV-powheg-pythia6/Summer12_DR53X-PU_S10_START53_V7C-v1/AODSIM/PAT_CMG_V5_16_0_1377467473/HTT_24Jul_newTES_manzoni_Up_Jobs/Job_9/run_cfg.py
c4c5df9677f7f4e810c52603360e671cef3b0002
[]
no_license
rmanzoni/HTT
18e6b583f04c0a6ca10142d9da3dd4c850cddabc
a03b227073b2d4d8a2abe95367c014694588bf98
refs/heads/master
2016-09-06T05:55:52.602604
2014-02-20T16:35:34
2014-02-20T16:35:34
null
0
0
null
null
null
null
UTF-8
Python
false
false
1,500
py
import FWCore.ParameterSet.Config as cms import os,sys sys.path.append('/afs/cern.ch/user/m/manzoni/summer13/CMGTools/CMSSW_5_3_9/src/CMGTools/H2TauTau/prod/25aug_corrMC/up/mc/GluGluToHToTauTau_M-95_8TeV-powheg-pythia6/Summer12_DR53X-PU_S10_START53_V7C-v1/AODSIM/PAT_CMG_V5_16_0_1377467473/HTT_24Jul_newTES_manzoni_Up_Jobs') from base_cfg import * process.source = cms.Source("PoolSource", noEventSort = cms.untracked.bool(True), inputCommands = cms.untracked.vstring('keep *', 'drop cmgStructuredPFJets_cmgStructuredPFJetSel__PAT'), duplicateCheckMode = cms.untracked.string('noDuplicateCheck'), fileNames = cms.untracked.vstring('/store/cmst3/group/cmgtools/CMG/GluGluToHToTauTau_M-95_8TeV-powheg-pythia6/Summer12_DR53X-PU_S10_START53_V7C-v1/AODSIM/PAT_CMG_V5_16_0/cmgTuple_46_1_8HB.root', '/store/cmst3/group/cmgtools/CMG/GluGluToHToTauTau_M-95_8TeV-powheg-pythia6/Summer12_DR53X-PU_S10_START53_V7C-v1/AODSIM/PAT_CMG_V5_16_0/cmgTuple_47_1_hDi.root', '/store/cmst3/group/cmgtools/CMG/GluGluToHToTauTau_M-95_8TeV-powheg-pythia6/Summer12_DR53X-PU_S10_START53_V7C-v1/AODSIM/PAT_CMG_V5_16_0/cmgTuple_48_1_dzl.root', '/store/cmst3/group/cmgtools/CMG/GluGluToHToTauTau_M-95_8TeV-powheg-pythia6/Summer12_DR53X-PU_S10_START53_V7C-v1/AODSIM/PAT_CMG_V5_16_0/cmgTuple_49_1_0TO.root', '/store/cmst3/group/cmgtools/CMG/GluGluToHToTauTau_M-95_8TeV-powheg-pythia6/Summer12_DR53X-PU_S10_START53_V7C-v1/AODSIM/PAT_CMG_V5_16_0/cmgTuple_4_1_ork.root') )
[ "riccardo.manzoni@cern.ch" ]
riccardo.manzoni@cern.ch
3c620fa7634959754cb7c5f09e025d6e39b6b3dd
8afb5afd38548c631f6f9536846039ef6cb297b9
/MY_REPOS/PYTHON_PRAC/learn-python3/oop_advance/orm.py
f59b23a9e893ff71ab7c6301d8df304de7161bfc
[ "MIT" ]
permissive
bgoonz/UsefulResourceRepo2.0
d87588ffd668bb498f7787b896cc7b20d83ce0ad
2cb4b45dd14a230aa0e800042e893f8dfb23beda
refs/heads/master
2023-03-17T01:22:05.254751
2022-08-11T03:18:22
2022-08-11T03:18:22
382,628,698
10
12
MIT
2022-10-10T14:13:54
2021-07-03T13:58:52
null
UTF-8
Python
false
false
2,262
py
#!/usr/bin/env python3 # -*- coding: utf-8 -*- " Simple ORM using metaclass " class Field(object): def __init__(self, name, column_type): self.name = name self.column_type = column_type def __str__(self): return "<%s:%s>" % (self.__class__.__name__, self.name) class StringField(Field): def __init__(self, name): super(StringField, self).__init__(name, "varchar(100)") class IntegerField(Field): def __init__(self, name): super(IntegerField, self).__init__(name, "bigint") class ModelMetaclass(type): def __new__(cls, name, bases, attrs): if name == "Model": return type.__new__(cls, name, bases, attrs) print("Found model: %s" % name) mappings = dict() for k, v in attrs.items(): if isinstance(v, Field): print("Found mapping: %s ==> %s" % (k, v)) mappings[k] = v for k in mappings.keys(): attrs.pop(k) attrs["__mappings__"] = mappings # 保存属性和列的映射关系 attrs["__table__"] = name # 假设表名和类名一致 return type.__new__(cls, name, bases, attrs) class Model(dict, metaclass=ModelMetaclass): def __init__(self, **kw): super(Model, self).__init__(**kw) def __getattr__(self, key): try: return self[key] except KeyError: raise AttributeError(r"'Model' object has no attribute '%s'" % key) def __setattr__(self, key, value): self[key] = value def save(self): fields = [] params = [] args = [] for k, v in self.__mappings__.items(): fields.append(v.name) params.append("?") args.append(getattr(self, k, None)) sql = "insert into %s (%s) values (%s)" % ( self.__table__, ",".join(fields), ",".join(params), ) print("SQL: %s" % sql) print("ARGS: %s" % str(args)) # testing code: class User(Model): id = IntegerField("id") name = StringField("username") email = StringField("email") password = StringField("password") u = User(id=12345, name="Michael", email="test@orm.org", password="my-pwd") u.save()
[ "bryan.guner@gmail.com" ]
bryan.guner@gmail.com
df3e9efc8ee499934b9e1b00f6d263afcf93c57b
3f2d1c68d07dd6677bc19c559b1960ca5fef6346
/knn/get_data.py
f8f4a916bc28894a39badcdf63732a71756173c4
[]
no_license
213584adghj/ml
6ffcf732377dabda129990e3a89468e18dd2700c
f73080e13c4a1c6babe0229bdb939eb3a7f988b6
refs/heads/master
2021-03-13T23:22:41.981534
2020-03-12T01:59:21
2020-03-12T01:59:21
246,720,376
0
0
null
null
null
null
UTF-8
Python
false
false
2,102
py
# -*- coding: utf-8 -*- import numpy as np import sys from sklearn.model_selection import train_test_split sys.path.append('...') from conf import knn as kn import os import re class data(object): def __init__(self): self.base_data_path = self.get_path() self.all_data_x, self.all_data_y = self.get_all_data() self.x_train, self.x_test, self.y_train, self.y_test = self.split_all_data() self.save_train_path() self.save_test_path() def get_path(self): path = os.getcwd() path = path.rstrip('\src\knn') path = path + kn.CONFIG['data']['base_data_file'] return path def get_all_data(self): dataMat = [] labelMat = [] path = self.base_data_path fr = open(path, 'r') for line in fr.readlines(): curLine = line.strip().split('\t') dataMat.append(np.array(curLine[0:len(curLine) - 1], dtype=float)) labelMat.append(int(re.sub("\D", "", curLine[-1]))) return np.array(dataMat), np.array(labelMat, dtype=int) def split_all_data(self): test_size = 1 - kn.CONFIG['data']['parameter']['characteristic_amount'] x_train, x_test, y_train, y_test = train_test_split(self.all_data_x, self.all_data_y, test_size=test_size, random_state=0) return x_train, x_test, y_train, y_test def save_train_path(self): path = os.getcwd() path = path.rstrip('\\src\\knn') p = path + kn.CONFIG['data']['train_data_path']['x'] q = path + kn.CONFIG['data']['train_data_path']['y'] np.savetxt(p, self.x_train, fmt='%s', newline='\n') np.savetxt(q, self.y_train, fmt='%s', newline='\n') def save_test_path(self): path = os.getcwd() path = path.rstrip('\\src\\knn') p = path + kn.CONFIG['data']['test_data_path']['x'] q = path + kn.CONFIG['data']['test_data_path']['y'] np.savetxt(p, self.x_test, fmt='%s', newline='\n') np.savetxt(q, self.y_test, fmt='%s', newline='\n')
[ "you@example.com" ]
you@example.com
3d74f3713ebc51593b0995dfa896d8ac0e3b2557
53fab060fa262e5d5026e0807d93c75fb81e67b9
/backup/user_348/ch120_2020_03_28_13_43_27_150252.py
8ca957e5746b650c5766458db3710c75e345506e
[]
no_license
gabriellaec/desoft-analise-exercicios
b77c6999424c5ce7e44086a12589a0ad43d6adca
01940ab0897aa6005764fc220b900e4d6161d36b
refs/heads/main
2023-01-31T17:19:42.050628
2020-12-16T05:21:31
2020-12-16T05:21:31
306,735,108
0
0
null
null
null
null
UTF-8
Python
false
false
782
py
from random import randint dinheiro = 100 print(dinheiro) jogo = True a = randint(1,36) while jogo: valor = float(input('aposte um valor:')) while valor > 0: aposta = input('numero ou paridade:') if aposta == 'n': numero = int(input('Escolha um numero:')) if numero == a: dinheiro = dinheiro + 35*valor else: dinheiro = dinheiro - 10 elif aposta == 'p': escolha = input('c ou i:') if a%2 == 0 and escolha == 'p': dinheiro = dinheiro + valor elif a%2 != 0 and escolha == 'i': dinheiro = dinheiro + valor else: dinheiro = dinheiro - valor else: jogo = False print(dinheiro)
[ "you@example.com" ]
you@example.com
b801eba554c6416ecd4abdfc6ece4a5c3fb09be3
aeee9575513324e329331b7cd1b28d157c297330
/server.py
0dcfd2b4567febb2fddb04507b0cb96cca101069
[]
no_license
martolini/ktntcpchat
0e80f0d00fc8d3c6c23cd9086c56622be5c58b58
887b060c94877bd773c2b1566d7a801632c21a56
refs/heads/master
2020-12-24T13:27:55.609069
2014-03-19T20:07:32
2014-03-19T20:07:32
null
0
0
null
null
null
null
UTF-8
Python
false
false
4,111
py
''' KTN-project 2013 / 2014 Very simple server implementation that should serve as a basis for implementing the chat server ''' import SocketServer, json import re from threading import Lock from datetime import datetime ''' The RequestHandler class for our server. It is instantiated once per connection to the server, and must override the handle() method to implement communication to the client. ''' class ClientHandler(SocketServer.BaseRequestHandler): def __init__(self, *args, **kwargs): SocketServer.BaseRequestHandler.__init__(self, *args, **kwargs) self.username = None self.loggedin = False def username_is_valid(self): return re.match('^[0-9a-zA-Z_]+$', self.username) def username_is_taken(self): return self.username in self.server.connections.keys() def handle_login(self, data): self.username = data['username'] if self.username_is_valid() and not self.username_is_taken(): self.server.connections[self.username] = self.connection self.connection.sendall(json.dumps({'response': 'login', 'username': self.username, 'messages': self.server.messages})) self.loggedin = True return if not self.username_is_valid(): error = 'Invalid username!' elif self.username_is_taken(): error = 'Name already taken!' self.connection.sendall(json.dumps({'response': 'login', 'username': self.username, 'error': error})) def handle(self): # Get a reference to the socket object self.connection = self.request # Get the remote ip adress of the socket self.ip = self.client_address[0] # Get the remote port number of the socket self.port = self.client_address[1] print 'Client connected @' + self.ip + ':' + str(self.port) while True: data = self.connection.recv(1024).strip() if data: data = json.loads(data) if data['request'] == 'login': self.handle_login(data) elif data['request'] == 'logout': message = {'response': 'logout', 'username': self.username} if not self.loggedin: message['error'] = "Not logged in!" self.connection.sendall(json.dumps(message)) del self.server.connections[self.username] break elif data['request'] == 'message': if not self.loggedin: message = json.dumps({'response': 'message', 'error': 'You are not logged in!'}) self.connection.sendall(message) else: message = json.dumps({'response': 'message', 'message': "<%s> said @ %s: %s" % (self.username, datetime.now().strftime("%H:%M"), data['message'])}) self.server.messages.append(message) for conn in self.server.connections.values(): conn.sendall(message) else: print 'WHAAAAAT' else: print 'Connection with %s lost' % self.ip del self.server.connections[self.username] break # Check if the data exists # (recv could have returned due to a disconnect) ''' This will make all Request handlers being called in its own thread. Very important, otherwise only one client will be served at a time ''' class ThreadedTCPServer(SocketServer.ThreadingMixIn, SocketServer.TCPServer): def __init__(self, *args, **kwargs): SocketServer.TCPServer.__init__(self, *args, **kwargs) self.connections = {} self.messages = [] if __name__ == "__main__": HOST = 'localhost' PORT = 9999 # Create the server, binding to localhost on port 9999 server = ThreadedTCPServer((HOST, PORT), ClientHandler) # Activate the server; this will keep running until you # interrupt the program with Ctrl-C server.serve_forever()
[ "msroed@gmail.com" ]
msroed@gmail.com
6ee1be19681e1d0b0a92b6188c6b7d23f9e185c6
f538e3974b8d9718a3cd24c1dea77023789c9315
/DjangoUbuntu/images_env/images/home/urls.py
779918c3280b79f78139b92224f69383058c32fe
[]
no_license
doremonkinhcan87/BlogImage
de1eab86505befb595844ed15168d1eb7d352121
c25dbe8c0a54c3294d3c8353cc9baf0a748a3707
refs/heads/master
2016-08-11T10:18:19.654850
2016-01-27T09:07:13
2016-01-27T09:07:13
49,034,669
0
0
null
null
null
null
UTF-8
Python
false
false
173
py
from django.conf.urls import url from django.contrib import admin from home import views as home_views urlpatterns = [ url( r'^$', home_views.index, name='index'), ]
[ "dautienthuy@gmail.com" ]
dautienthuy@gmail.com
e4ca26f30e0569af1913ec828b403f78fcf1dc99
01196cb36e60d2f4e0bd04fb8a230c82512c6d1d
/EmployeeManagmentSystem/poll/models.py
8bc144c4f484787a486066cd9c5fed83d93a8363
[]
no_license
dipayandutta/django
ba69b7834bd95d4564e44155504f770b780f3ebd
3139a7b720911a4f876fb6ef9d086c39f83e3762
refs/heads/master
2022-04-27T18:56:18.129939
2022-03-23T14:05:22
2022-03-23T14:05:22
132,355,123
0
0
null
null
null
null
UTF-8
Python
false
false
776
py
from django.db import models from django.contrib.auth.models import User # Create your models here. class Question(models.Model): title = models.TextField(null=True,blank=True) status = models.CharField(default='inactive',max_length=10) created_by = models.ForeignKey(User,null=True,blank=True,on_delete=models.CASCADE) create_at = models.DateTimeField(null=True,blank=True) updated_at = models.DateTimeField(null=True,blank=True) def __str__(self): return self.title class Choice(models.Model): question = models.ForeignKey('poll.Question',on_delete=models.CASCADE) text = models.TextField(null=True,blank=True) create_at = models.DateTimeField(auto_now_add=True) updated_at = models.DateTimeField(auto_now=True) def __str__(self): return self.text
[ "inbox.dipayan@gmail.com" ]
inbox.dipayan@gmail.com
261ecd163dcc1512445518a9868ef7263a49e1b9
48832d27da16256ee62c364add45f21b968ee669
/res_bw/scripts/common/lib/lib2to3/fixes/fix_xreadlines.py
39a696f2250018e3185cba4d70fb28000233131b
[]
no_license
webiumsk/WOT-0.9.15.1
0752d5bbd7c6fafdd7f714af939ae7bcf654faf7
17ca3550fef25e430534d079876a14fbbcccb9b4
refs/heads/master
2021-01-20T18:24:10.349144
2016-08-04T18:08:34
2016-08-04T18:08:34
64,955,694
0
0
null
null
null
null
WINDOWS-1250
Python
false
false
1,002
py
# 2016.08.04 20:00:20 Střední Evropa (letní čas) # Embedded file name: scripts/common/Lib/lib2to3/fixes/fix_xreadlines.py """Fix "for x in f.xreadlines()" -> "for x in f". This fixer will also convert g(f.xreadlines) into g(f.__iter__).""" from .. import fixer_base from ..fixer_util import Name class FixXreadlines(fixer_base.BaseFix): BM_compatible = True PATTERN = "\n power< call=any+ trailer< '.' 'xreadlines' > trailer< '(' ')' > >\n |\n power< any+ trailer< '.' no_call='xreadlines' > >\n " def transform(self, node, results): no_call = results.get('no_call') if no_call: no_call.replace(Name(u'__iter__', prefix=no_call.prefix)) else: node.replace([ x.clone() for x in results['call'] ]) # okay decompyling c:\Users\PC\wotsources\files\originals\res_bw\scripts\common\lib\lib2to3\fixes\fix_xreadlines.pyc # decompiled 1 files: 1 okay, 0 failed, 0 verify failed # 2016.08.04 20:00:20 Střední Evropa (letní čas)
[ "info@webium.sk" ]
info@webium.sk
a6f5c05679a178711e1a3abdd53c281dcbd83546
ffa651d0a81ce5629ab760fbd18d4e18f2b3f3ed
/venv/lib/python3.9/site-packages/pip/_vendor/html5lib/filters/whitespace.py
8f71ebfa7e095f19288caa7d380f8abd8badb31b
[]
no_license
superew/TestUI-Setel
b02d4c18a3301b57eaecb7ff60ccce7b9e1e7813
5cd48475fc6622ed289d15c109428f55d3d5d6f6
refs/heads/master
2023-08-02T11:16:34.646927
2021-09-30T17:21:43
2021-09-30T17:21:43
410,351,545
0
0
null
null
null
null
UTF-8
Python
false
false
1,062
py
from __future__ import absolute_import, division, unicode_literals import re from . import base from ..constants import rcdataElements, spaceCharacters spaceCharacters = "".join(spaceCharacters) SPACES_REGEX = re.compile("[%s]+" % spaceCharacters) class Filter(base.Filter): """Collapses whitespace except in pre, textarea, and script elements""" spacePreserveElements = frozenset(["pre", "textarea"] + list(rcdataElements)) def __iter__(self): preserve = 0 for token in base.Filter.__iter__(self): type = token["type"] if type == "StartTag" \ and (preserve or token["name"] in self.spacePreserveElements): preserve += 1 elif type == "EndTag" and preserve: preserve -= 1 elif not preserve and type == "SpaceCharacters" and token["data"]: # Test on token["data"] above to not introduce spaces where there were not token["data"] = " " elif not preserve and type == "Characters": token["data"] = collapse_spaces(token["data"]) yield token def collapse_spaces(text): return SPACES_REGEX.sub(' ', text)
[ "blackan.andrew@gmail.com" ]
blackan.andrew@gmail.com
51007ea1a328bbe0321cff96a9091326b6171efb
9d268f0cedc3089dd95b6b22cc1a0191f43dac00
/basket/admin.py
1024e6ec91575d300e8585758be8b9fcef2c5bd2
[]
no_license
Dmitry-Kiselev/store
a5c5b3ade4baa8fa7b600e10feeae352e318340a
193788ac5c00e699863c0194661085e7be08bdf7
refs/heads/master
2022-12-13T19:12:39.553834
2017-06-15T11:38:14
2017-06-15T11:38:14
91,546,511
0
0
null
2022-12-07T23:57:51
2017-05-17T07:28:09
Python
UTF-8
Python
false
false
344
py
from django.contrib import admin from .models import Basket, Line class LineInlineAdmin(admin.TabularInline): model = Line @admin.register(Line) class LineAdmin(admin.ModelAdmin): list_display = ['product'] @admin.register(Basket) class BasketAdmin(admin.ModelAdmin): list_display = ['user'] inlines = [LineInlineAdmin, ]
[ "kdem27@gmail.com" ]
kdem27@gmail.com
305dc36192283483c72fd39e44335055375b1dc7
b91578b96ffe63639d3efc70d4737b92091cd0b1
/backend/unpp_api/apps/common/management/commands/clean_commonfile_orphans.py
29cbb451ddc386beafc2e0e3e0cea4ed46135ef6
[ "Apache-2.0" ]
permissive
unicef/un-partner-portal
876b6ec394909ed2f72777493623413e9cecbfdc
73afa193a5f6d626928cae0025c72a17f0ef8f61
refs/heads/develop
2023-02-06T21:08:22.037975
2019-05-20T07:35:29
2019-05-20T07:35:29
96,332,233
6
1
Apache-2.0
2023-01-25T23:21:41
2017-07-05T15:07:44
JavaScript
UTF-8
Python
false
false
1,077
py
from __future__ import absolute_import from datetime import datetime from dateutil.relativedelta import relativedelta from django.core.management.base import BaseCommand from common.models import CommonFile class Command(BaseCommand): help = 'Cleans up files that have no existing references.' def add_arguments(self, parser): parser.add_argument( '--all', action='store_true', dest='all', default=False, help='Do not exclude recent files' ) def handle(self, *args, **options): common_files = CommonFile.objects.all() if not options.get('all'): common_files = common_files.filter(created_lte=datetime.now() - relativedelta(weeks=1)) self.stdout.write('Start checking current files') cf: CommonFile for cf in common_files.iterator(): if not cf.has_existing_reference: self.stdout.write(f'{cf} has no references, removing...') cf.delete() self.stdout.write('Finish files scan')
[ "maciej.jaworski@tivix.com" ]
maciej.jaworski@tivix.com
b600795d48e3d62be0154d5ee0d1f86cef382183
506cb452b371218df26fac6a1b41c46d19ce83fd
/integer_reverse.py
fbbbe7b8011994a47699d09eb49c54cddc44a97c
[]
no_license
shhhhhigne/guessing-game
135cfcaaccad8aa6ba9e1267007d3222eab3bec8
5e9b137b8717061990d4b320bff4b630b3da103c
refs/heads/master
2021-04-29T02:48:32.459926
2017-01-04T20:56:05
2017-01-04T20:56:05
78,052,049
0
0
null
null
null
null
UTF-8
Python
false
false
234
py
def reverse_integer(): user_input = int(raw_input("Input number: ")) while user_input is not 0: n = user_input % 10 print n user_input = (user_input - n)/10 #print user_input reverse_integer()
[ "no-reply@hackbrightacademy.com" ]
no-reply@hackbrightacademy.com
5c5b9d46206ac9713596e8e8bf604697810ef3e7
e9fe65ef3aa2d2d0c5e676fee8ac21acd2b82218
/nestedList_3_3.py
1ca2fa4c5e6b7ef1263562d3342caa61b9f5b55d
[]
no_license
MayowaFunmi/Algorithm-Problem-Solutions
5d3f54199fa381ca778bf8e932fdf599d5a42a77
77124d0212c1c8a09af64b445d9b1207444710b9
refs/heads/master
2022-12-27T22:07:10.883196
2020-10-11T00:34:12
2020-10-11T00:34:12
303,010,447
0
0
null
null
null
null
UTF-8
Python
false
false
317
py
list = [["yes", 5.87], ["me", 2.29], ["them", 4.55], ["him", 0.34], ["she", 2.29], ["our", 4.55]] score = [] for i in list: score.append(i[1]) score.sort() print(score) names = [] for name, mark in list: if mark == score[-2]: names.append(name) names.sort() for i in names: print(i)
[ "akinade.mayowa@gmail.com" ]
akinade.mayowa@gmail.com
a02e4f7a7ac588561c425e85fede489e9ac79fa5
af93b3909f86ab2d310a8fa81c9357d87fdd8a64
/begginer/8.cas/zadatak6.py
b1aa0bb49f735766be9270a393eccc4fb04ecf1b
[]
no_license
BiljanaPavlovic/pajton-kurs
8cf15d443c9cca38f627e44d764106ef0cc5cd98
93092e6e945b33116ca65796570462edccfcbcb0
refs/heads/master
2021-05-24T14:09:57.536994
2020-08-02T15:00:12
2020-08-02T15:00:12
253,597,402
0
0
null
null
null
null
UTF-8
Python
false
false
139
py
proizvod=1 for i in range(4,51): if i%6==0: proizvod=proizvod*i #proizvod*=i print(f"proizvod je {proizvod}")
[ "zabiljanupavlovic@gmail.com" ]
zabiljanupavlovic@gmail.com
627bba94d0d7c441615c4d735a19a9d7bf5af2a5
35250c1ccc3a1e2ef160f1dab088c9abe0381f9f
/2020/0412/1032.py
ad26688eeefed21f33aea4e895b2f8c31e30e300
[]
no_license
entrekid/daily_algorithm
838ab50bd35c1bb5efd8848b9696c848473f17ad
a6df9784cec95148b6c91d804600c4ed75f33f3e
refs/heads/master
2023-02-07T11:21:58.816085
2021-01-02T17:58:38
2021-01-02T17:58:38
252,633,404
0
0
null
null
null
null
UTF-8
Python
false
false
371
py
import sys input = sys.stdin.readline N = int(input()) all = [input().rstrip() for _ in range(N)] ans = all[0] length = len(ans) ret = "" for index in range(length): base = ans[index] for jter in range(1, N): if all[jter][index] == base: continue else: ret += "?" break else: ret += base print(ret)
[ "dat.sci.seol@gmail.com" ]
dat.sci.seol@gmail.com
b26aa47f86d46143f9e4617cf1f3a9cd1d1ee085
6cecdc007a3aafe0c0d0160053811a1197aca519
/apps/hq/urls.py
dfd7a56494e809ecc98888792013d8fb67b130fe
[]
no_license
commtrack/temp-aquatest
91d678c927cc4b2dce6f709afe7faf2768b58157
3b10d179552b1e9d6a0e4ad5e91a92a05dba19c7
refs/heads/master
2016-08-04T18:06:47.582196
2010-09-29T13:20:13
2010-09-29T13:20:13
null
0
0
null
null
null
null
UTF-8
Python
false
false
633
py
from django.conf.urls.defaults import * import hq.views as views import settings urlpatterns = patterns('', url(r'^$', 'hq.views.dashboard', name="homepage"), (r'^serverup.txt$', 'hq.views.server_up'), (r'^change_password/?$', 'hq.views.password_change'), (r'^no_permissions/?$', 'hq.views.no_permissions'), url(r'^reporters/add/?$', views.add_reporter, name="add-reporter"), url(r'^reporters/(?P<pk>\d+)/?$', views.edit_reporter, name="view-reporter"), (r'^stats/?$', 'hq.views.reporter_stats'), (r'', include('hq.reporter.api_.urls')), )
[ "allen.machary@gmail.com" ]
allen.machary@gmail.com
e722b56c0586dbb8980d79f634b53921923bc0e4
ad6c519f356c0c49eb004084b12b5f08e3cd2e9e
/contrib/compile_less.py
0f21f7dd011811897c55b5aeecc5ff29cd6b0aaa
[ "MIT" ]
permissive
csilvers/kake
1a773e7c2232ea243be256bb5e6bd92e0189db9d
51465b12d267a629dd61778918d83a2a134ec3b2
refs/heads/master
2021-05-05T23:07:40.425063
2019-01-23T23:35:48
2019-01-23T23:35:48
116,594,798
0
0
MIT
2019-01-23T23:19:17
2018-01-07T19:59:09
Python
UTF-8
Python
false
false
2,249
py
# TODO(colin): fix these lint errors (http://pep8.readthedocs.io/en/release-1.7.x/intro.html#error-codes) # pep8-disable:E131 """A Compile object (see compile_rule.py): foo.less -> foo.less.css.""" from __future__ import absolute_import import json from kake.lib import compile_rule from kake.lib import computed_inputs _LESS_COMPILATION_FAILURE_RESPONSE = """ body * { display: none !important; } body { background: #bbb !important; margin: 20px !important; color: #900 !important; font-family: Menlo, Consolas, Monaco, monospace !important; font-weight: bold !important; white-space: pre !important; } body:before { content: %s } """ class CompileLess(compile_rule.CompileBase): def version(self): """Update every time build() changes in a way that affects output.""" return 3 def build(self, outfile_name, infile_names, _, context): # As the lone other_input, the lessc compiler is the last infile. (retcode, stdout, stderr) = self.try_call_with_output( [self.abspath(infile_names[-1]), '--no-color', '--source-map', # writes to <outfile>.map '--source-map-rootpath=/', '--source-map-basepath=%s' % self.abspath(''), self.abspath(infile_names[0]), self.abspath(outfile_name)]) if retcode: message = 'Compiling Less file %s failed:\n%s\n' % ( infile_names[0], stderr) raise compile_rule.GracefulCompileFailure( message, _LESS_COMPILATION_FAILURE_RESPONSE % # Use \A instead of \n in CSS strings: # http://stackoverflow.com/a/9063069 json.dumps(message).replace("\\n", " \\A ")) # Less files have an include-structure, which means that whenever an # included file changes, we need to rebuild. Hence we need to use a # computed input. compile_rule.register_compile( 'COMPILED LESS', 'genfiles/compiled_less/en/{{path}}.less.css', computed_inputs.ComputedIncludeInputs( '{{path}}.less', r'^@import\s*"([^"]*)"', other_inputs=['genfiles/node_modules/.bin/lessc']), CompileLess())
[ "csilvers@khanacademy.org" ]
csilvers@khanacademy.org
3477905774ed5edf89834341f37552f9d7ae3118
21e27d3db70f99de096969553b689c58cd09c42b
/updatelineno_of_paleoword.py
218e5ee0aea4cf63e9fb07e7d980e88fb6b4b706
[]
no_license
suhailvs/django-qurantorah
e520b0030422f8a4311763628daebbbbd392c34c
151b9abf3428654b6c490d3df392c0d163c79c6e
refs/heads/master
2021-06-15T02:11:14.688457
2020-03-15T07:31:33
2020-03-15T07:31:33
159,264,131
0
0
null
2021-03-18T21:11:04
2018-11-27T02:31:00
Python
UTF-8
Python
false
false
1,063
py
import json from torah.models import Word,Line """ USAGE ===== ./manage.py shell >>> import updatelineno_of_paleoword >>> updatelineno_of_paleoword.save_word_to_db() """ def save_word_to_db(): chap='genesis,exodus,leviticus,numbers,deuteronomy' n_lines, n_word, n_letters= 0,0,0 for title in chap.split(','): paleo_data = json.loads(open('torah/json/paleo/%s.json'%title).read()) for i,chapter in enumerate(paleo_data['text']): # data_word = [] # data_line = [] n_lines+=len(chapter) for j,line in enumerate(chapter): n_word+=len(line.split(' ')) for word in line.split(' '): w, created = Word.objects.get_or_create(name = word) l = Line.objects.get(title = title, chapter = i+1, line = j+1) w.lines.add(l) #if not Word.objects.filter(name=word): #data_word.append(Word(name=word)) n_letters+=len(word) # data_line.append(Line(title = title, chapter = i+1, line = j+1)) # Word.objects.bulk_create(data_word) # Line.objects.bulk_create(data_line) print(n_lines,n_word,n_letters)
[ "suhailvs@gmail.com" ]
suhailvs@gmail.com
74c8e9860eae167b136c05285e22a67e2c9a8de8
920b9cb23d3883dcc93b1682adfee83099fee826
/itsm/role/utils.py
17cfe9461e59ce1f7ab21362402eb584388b0f6c
[ "MIT", "LGPL-2.1-or-later", "LGPL-3.0-only" ]
permissive
TencentBlueKing/bk-itsm
f817fb166248d3059857b57d03e8b5ec1b78ff5b
2d708bd0d869d391456e0fb8d644af3b9f031acf
refs/heads/master
2023-08-31T23:42:32.275836
2023-08-22T08:17:54
2023-08-22T08:17:54
391,839,825
100
86
MIT
2023-09-14T08:24:54
2021-08-02T06:35:16
Python
UTF-8
Python
false
false
1,710
py
# -*- coding: utf-8 -*- """ Tencent is pleased to support the open source community by making BK-ITSM 蓝鲸流程服务 available. Copyright (C) 2021 THL A29 Limited, a Tencent company. All rights reserved. BK-ITSM 蓝鲸流程服务 is licensed under the MIT License. License for BK-ITSM 蓝鲸流程服务: -------------------------------------------------------------------- Permission is hereby granted, free of charge, to any person obtaining a copy of this software and associated documentation files (the "Software"), to deal in the Software without restriction, including without limitation the rights to use, copy, modify, merge, publish, distribute, sublicense, and/or sell copies of the Software, and to permit persons to whom the Software is furnished to do so, subject to the following conditions: The above copyright notice and this permission notice shall be included in all copies or substantial portions of the Software. THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, EXPRESS OR IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF MERCHANTABILITY, FITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT. IN NO EVENT SHALL THE AUTHORS OR COPYRIGHT HOLDERS BE LIABLE FOR ANY CLAIM, DAMAGES OR OTHER LIABILITY, WHETHER IN AN ACTION OF CONTRACT, TORT OR OTHERWISE, ARISING FROM, OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE USE OR OTHER DEALINGS IN THE SOFTWARE. """ from django.utils.translation import ugettext as _ def translate_constant_2(constant): temp_constant = [] for item in constant: # py2->py3: 'str' object has no attribute 'decode' temp_constant.append((item[0], _(item[1]))) constant = temp_constant return constant
[ "1758504262@qq.com" ]
1758504262@qq.com
24f7f8a2e67f6628493069a129b394a4ff11d1d4
2f0d56cdcc4db54f9484b3942db88d79a4215408
/.history/Python_Learning/lesson13_20200329114830.py
ba04f40090cb55cf629dc5824f55791317a02c91
[]
no_license
xiangxing98/xiangxing98.github.io
8571c8ee8509c0bccbb6c2f3740494eedc53e418
23618666363ecc6d4acd1a8662ea366ddf2e6155
refs/heads/master
2021-11-17T19:00:16.347567
2021-11-14T08:35:01
2021-11-14T08:35:01
33,877,060
7
1
null
2017-07-01T16:42:49
2015-04-13T15:35:01
HTML
UTF-8
Python
false
false
429
py
# -*- encoding: utf-8 -*- # !/usr/bin/env python ''' @File : lesson13.py @Time : 2020/03/29 11:43:27 @Author : Stone_Hou @Version : 1.0 @Contact : xiangxing985529@163.com @License : (C)Copyright 2010-2020, Stone_Hou @Desc : None ''' # here put the import lib # Practice #01 print('He said,"I\'m yours!"') # He said, "I'm yours!" # Practice #02 print('\\\\_v_//') \\_v_// # Practice #03 # Practice #04
[ "xiangxing985529@163.com" ]
xiangxing985529@163.com
e1ac78e0b777110562d318e87c495e8dbe70df4d
8096e140f0fd38b9492e0fcf307990b1a5bfc3dd
/Python/pick6/pick6.py
25239e92262858f2921b73fe2ff362a129aeeefd
[]
no_license
perennialAutodidact/PDXCodeGuild_Projects
0cacd44499c0bdc0c157555fe5466df6d8eb09b6
28a8258eba41e1fe6c135f54b230436ea7d28678
refs/heads/master
2022-11-15T22:26:45.775550
2020-07-07T17:13:01
2020-07-07T17:13:01
null
0
0
null
null
null
null
UTF-8
Python
false
false
1,465
py
import random def pick6(): nums = [] i = 0 while i < 6: num = random.randint(1,99) nums.append(num) i += 1 return nums def check_ticket(ticket, goal): matches = [] for index, num in enumerate(ticket): if num == goal[index]: matches.append(num) else: matches.append(0) return matches def collect_winnings(matches): scores = {0:0, 1:4, 2:7, 3:100, 4:50000, 5:1000000, 6:25000000} # number of matches vs dollar rewards i = 0 # number of matches for num in matches: if num > 0: i += 1 reward = scores[i] return reward def get_roi(investment, earnings): roi = (earnings - investment)/investment return roi def main(): plays = int(input("\nWelcome to Pick 6. Enter the number of times you'd like to play: ")) winning_ticket = pick6() ticket_price = 2 balance = 0 earnings = 0 i = 0 while i < plays: balance -= ticket_price ticket = pick6() matches = check_ticket(ticket, winning_ticket) reward = collect_winnings(matches) if reward: balance += reward earnings += reward i += 1 investment = ticket_price * plays roi = get_roi(investment, earnings) print(f"Your final balance is ${balance}. You won ${earnings}. The return on your investment of ${investment} was {roi}") main()
[ "keegood8@gmail.com" ]
keegood8@gmail.com
a1f99b984843bb214cc729eb084b6f32c4a7f041
b7f91e2cbc1deea0b33f4293336876568e0b263d
/parctice/training_code/Armour_plate_detection_training/rpn_s/train.py
b1b9d79fc873a59f700e74ebc2b830009f5e909b
[]
no_license
wonggw/Robomaster_NTU_2018
196776d3b0a3b581a0c0db9618c1a9f59634ceb9
cac54d22b6ac3f3a94790ed056660cdccb78558d
refs/heads/master
2020-03-25T01:52:58.963643
2018-08-01T03:34:37
2018-08-01T03:34:37
143,262,046
0
0
null
2018-08-02T07:57:47
2018-08-02T07:57:47
null
UTF-8
Python
false
false
2,161
py
import numpy as np import netpart import data_reader import model as M import tensorflow as tf import cv2 import time import myconvertmod as cvt import os if not os.path.exists('./model/'): os.mkdir('./model/') reader = data_reader.reader(height=240,width=320,scale_range=[0.05,1.2], lower_bound=3,upper_bound=5,index_multiplier=2) def draw(img,c,b,multip,name): c = c[0] b = b[0] row,col,_ = b.shape # print(b.shape,c.shape) # print(row,col) for i in range(row): for j in range(col): # print(i,j) if c[i][j][0]>-0.5: x = int(b[i][j][0])+j*multip+multip//2 y = int(b[i][j][1])+i*multip+multip//2 w = int(b[i][j][2]) h = int(b[i][j][3]) cv2.rectangle(img,(x-w//2,y-h//2),(x+w//2,y+h//2),(0,255,0),2) cv2.imshow(name,img) cv2.waitKey(1) def draw2(img,c,b,multip,name): c = c[0] b = b[0] row,col,_ = b.shape c = c.reshape([-1]) ind = c.argsort()[-5:][::-1] for aaa in ind: # print(aaa) i = aaa//col j = aaa%col x = int(b[i][j][0])+j*multip+multip//2 y = int(b[i][j][1])+i*multip+multip//2 w = int(b[i][j][2]) h = int(b[i][j][3]) cv2.rectangle(img,(x-w//2,y-h//2),(x+w//2,y+h//2),(0,255,0),2) cv2.imshow(name,img) cv2.waitKey(1) b0,b1,c0,c1 = netpart.model_out netout = [[b0,c0],[b1,c1]] t1 = time.time() MAX_ITER = 500000 with tf.Session() as sess: saver = tf.train.Saver() M.loadSess('./model/',sess) for i in range(MAX_ITER): img, train_dic = reader.get_img() for k in train_dic: ls,_,b,c = sess.run([netpart.loss_functions[k], netpart.train_steps[k]] + netout[k], feed_dict={netpart.inpholder:[img], netpart.b_labholder:[train_dic[k][1]], netpart.c_labholder:[train_dic[k][0]]}) if i%10==0: t2 = time.time() remain_time = float(MAX_ITER - i) / float(i+1) * (t2-t1) h,m,s = cvt.sec2hms(remain_time) print('Iter:\t%d\tLoss:\t%.6f\tK:%d\tETA:%d:%d:%d'%(i,ls,k,h,m,s)) if i%100==0: if k==0: multip = 8 elif k==1: multip = 32 # multip = 8 if k==0 else 32 draw(img.copy(),[train_dic[k][0]],[train_dic[k][1]],multip,'lab') draw2(img.copy(),c,b,multip,'pred') if i%2000==0 and i>0: saver.save(sess,'./model/MSRPN_%d.ckpt'%i)
[ "cy960823@outlook.com" ]
cy960823@outlook.com
379fd53a5f423321a7a8eb0065c23cc0be712f0c
563bdb036cb8cbfbd55fe05888c3ff6ec121b660
/documenter2docset/documenter.py
e79a80bd15e0a601ca8531819ca511e3b1a8f5df
[]
no_license
jlumpe/documenter2docset
8858697f8b26f465b166d373bdd093239fb00901
ce5ef6572e51b783529c04a2794af67552867d3d
refs/heads/master
2020-04-13T16:52:03.980076
2018-12-28T20:27:19
2018-12-28T20:27:19
163,332,319
0
0
null
null
null
null
UTF-8
Python
false
false
586
py
"""Work with documentation generated by Documenter.jl.""" import ast def read_search_index(fh): """Read search_index.js. Can't part strictly as JSON (even after removing the variable assignment at the beginning because it isn't formatted correctly (comma after last element of array). Use ast.literal_eval instead because it should match Python dict/list literal syntax. """ start = 'var documenterSearchIndex = ' if fh.read(len(start)) != start: raise ValueError('Failed to parse search index') rest = fh.read() data = ast.literal_eval(rest) return data['docs']
[ "mjlumpe@gmail.com" ]
mjlumpe@gmail.com
c9ad645885da2ff6ead3ccefeee3ae71e844d592
f7038be35e310a21958cd4e6bb9baadaf3c69943
/python/shred/mango/mango/settings.py
48564b45e78084e8f244583ee9facc75bd312419
[]
no_license
code-machina/awesome-tutorials
d0208fadc06bae0c1865d50a8b1c74d2737dae13
6c813a1e9c343f8f99c2f6d5be804a829ec149ed
refs/heads/master
2023-01-12T06:52:35.474881
2019-01-31T09:09:46
2019-01-31T09:09:46
160,049,994
1
0
null
2023-01-07T07:52:20
2018-12-02T13:25:58
JavaScript
UTF-8
Python
false
false
3,684
py
""" Django settings for mango project. Generated by 'django-admin startproject' using Django 1.8.2. For more information on this file, see https://docs.djangoproject.com/en/1.8/topics/settings/ For the full list of settings and their values, see https://docs.djangoproject.com/en/1.8/ref/settings/ """ # Build paths inside the project like this: os.path.join(BASE_DIR, ...) import os BASE_DIR = os.path.dirname(os.path.dirname(os.path.abspath(__file__))) # Quick-start development settings - unsuitable for production # See https://docs.djangoproject.com/en/1.8/howto/deployment/checklist/ # SECURITY WARNING: keep the secret key used in production secret! SECRET_KEY = 'pehq^ro26o4wb^6x)hog5m^*v%=!8yb^@d(1haun#v(dgqyb9g' # SECURITY WARNING: don't run with debug turned on in production! DEBUG = True ALLOWED_HOSTS = [] # Application definition INSTALLED_APPS = ( 'django.contrib.admin', 'django.contrib.auth', 'django.contrib.contenttypes', 'django.contrib.sessions', 'django.contrib.messages', 'django.contrib.staticfiles', 'lemon', 'djcelery', ) MIDDLEWARE_CLASSES = ( 'django.contrib.sessions.middleware.SessionMiddleware', 'django.middleware.common.CommonMiddleware', 'django.middleware.csrf.CsrfViewMiddleware', 'django.contrib.auth.middleware.AuthenticationMiddleware', 'django.contrib.auth.middleware.SessionAuthenticationMiddleware', 'django.contrib.messages.middleware.MessageMiddleware', 'django.middleware.clickjacking.XFrameOptionsMiddleware', 'django.middleware.security.SecurityMiddleware', ) ROOT_URLCONF = 'mango.urls' TEMPLATES = [ { 'BACKEND': 'django.template.backends.django.DjangoTemplates', 'DIRS': [ os.path.join(BASE_DIR, 'templates'), ], 'APP_DIRS': True, 'OPTIONS': { 'context_processors': [ 'django.template.context_processors.debug', 'django.template.context_processors.request', 'django.template.context_processors.media', 'django.template.context_processors.static', 'django.contrib.auth.context_processors.auth', 'django.contrib.messages.context_processors.messages', ], }, }, ] WSGI_APPLICATION = 'mango.wsgi.application' # Database # https://docs.djangoproject.com/en/1.8/ref/settings/#databases DATABASES = { 'default': { 'ENGINE': 'django.db.backends.sqlite3', 'NAME': os.path.join(BASE_DIR, 'db.sqlite3'), } } # Internationalization # https://docs.djangoproject.com/en/1.8/topics/i18n/ LANGUAGE_CODE = 'en-us' TIME_ZONE = 'UTC' USE_I18N = True USE_L10N = True USE_TZ = True # Static files (CSS, JavaScript, Images) # https://docs.djangoproject.com/en/1.8/howto/static-files/ STATICFILES_DIRS = ( os.path.join(BASE_DIR, "static"), ) STATIC_ROOT = '/static/' STATIC_URL = '/static/' CELERY_BROKER_URL = 'redis://localhost:6379' # CELERY_RESULT_BACKEND = 'redis://localhost:6379' CELERY_ACCEPT_CONTENT = ['application/json'] CELERY_TASK_SERIALIZER = 'json' CELERY_RESULT_SERIALIZER = 'json' CELERY_TIMEZONE = 'Asia/Seoul' CELERY_RESULT_BACKEND = 'db+sqlite:///db.sqlite' from datetime import timedelta from celery.schedules import crontab # from datetime import timedelta # TODO: 여기서 YML 파일을 로드하여 동적으로 스케줄을 구성한다. CELERYBEAT_SCHEDULE = { 'add-every-30-seconds': { 'task': 'tasks.task_sample_add', 'schedule': timedelta(seconds=1), 'args': (16, 16) }, } CELERYBEAT_SCHEDULER = 'djcelery.schedulers.DatabaseScheduler' import djcelery djcelery.setup_loader()
[ "gbkim1988@gmail.com" ]
gbkim1988@gmail.com
28fd248312ad2493793bbb3f26584351c889655e
54d8a05e0238e96eb43e4893bacba024e490bf11
/python-projects/algo_and_ds/shortest_cell_path_using_bfs_pramp_interview.py
20d9c4271b29075a2acbe3379700acf8700381c3
[]
no_license
infinite-Joy/programming-languages
6ce05aa03afd7edeb0847c2cc952af72ad2db21e
0dd3fdb679a0052d6d274d19040eadd06ae69cf6
refs/heads/master
2023-05-29T10:34:44.075626
2022-07-18T13:53:02
2022-07-18T13:53:02
30,753,185
3
5
null
2023-05-22T21:54:46
2015-02-13T11:14:25
Jupyter Notebook
UTF-8
Python
false
false
1,621
py
from collections import deque def next_cell(grid, row, col, visited): # the list is in top, left, bottom, right nrow = [-1, 0, 1, 0] ncol = [0, -1, 0, 1] for rr, cc in zip(nrow, ncol): updated_row = row + rr updated_col = col + cc if 0 <= updated_row < len(grid) and 0 <= updated_col < len(grid[0]): if (updated_row, updated_col) not in visited and grid[updated_row][updated_col] == 1: yield updated_row, updated_col def shortestCellPath(grid, sr, sc, tr, tc): if len(grid) == 1 and not grid[0]: return -1 queue = deque([((sr, sc), 0)]) # 0,0; level=0 visited = set((sr, sc)) while queue: (row, col), level = queue.popleft() # 0, 0 level = 0 if row == tr and col == tc: return level for nrow, ncol in next_cell(grid, row, col, visited): queue.append(((nrow, ncol), level + 1)) visited.add((nrow, ncol)) return -1 grid = [[1, 1, 1, 1], [0, 0, 0, 1], [1, 1, 1, 1]] print(shortestCellPath(grid, 0, 0, 2, 0)) grid = [[1, 1, 1, 1], [0, 0, 0, 1], [1, 0, 1, 1]] print(shortestCellPath(grid, 0, 0, 2, 0)) """ edge case [[]] input: grid = [[1, 1, 1, 1], [0, 0, 0, 1], [1, 1, 1, 1]] sr = 0, sc = 0, tr = 2, tc = 0 output: 8 (The lines below represent this grid:) 1111 0001 1111 using a bfs should give the shortest path time complexity m*n space complexity m*n queue while queue is present: take the present row , col and the current level if target is found: return the level iterate on the adj rows and cols that are not already visited: append to the queue with level + 1 add the row , col to the visited return -1 """
[ "joydeepubuntu@gmail.com" ]
joydeepubuntu@gmail.com
47684ef9baf25752da28cc56054c26aabdfa5f87
84f0c73b9147e293a91161d3bd00fdfb8758a1e2
/django/test1/test1/settings.py
e7105747f60d717d10860b8345297a7f6fe8ce78
[]
no_license
TrellixVulnTeam/allPythonPractice_R8XZ
73305067dfc7cfc22ae1a8283f7cb1397e41974b
45f0885f6526807f1150c6b9e65d50ddf0f37d9f
refs/heads/master
2023-03-15T19:19:14.020828
2019-07-25T16:18:24
2019-07-25T16:18:24
null
0
0
null
null
null
null
UTF-8
Python
false
false
2,852
py
""" Django settings for test1 project. Generated by 'django-admin startproject' using Django 1.8.2. For more information on this file, see https://docs.djangoproject.com/en/1.8/topics/settings/ For the full list of settings and their values, see https://docs.djangoproject.com/en/1.8/ref/settings/ """ # Build paths inside the project like this: os.path.join(BASE_DIR, ...) import os # 项目目录的绝对路径 BASE_DIR = os.path.dirname(os.path.dirname(os.path.abspath(__file__))) # Quick-start development settings - unsuitable for production # See https://docs.djangoproject.com/en/1.8/howto/deployment/checklist/ # SECURITY WARNING: keep the secret key used in production secret! SECRET_KEY = '-yiw=bcb^yy5ao!%n20(eb&=#ez74krb1!-+-e6j1)4swb-3=^' # SECURITY WARNING: don't run with debug turned on in production! DEBUG = True ALLOWED_HOSTS = [] # Application definition INSTALLED_APPS = ( 'django.contrib.admin', 'django.contrib.auth', 'django.contrib.contenttypes', 'django.contrib.sessions', 'django.contrib.messages', 'django.contrib.staticfiles', 'booktest', # 进行应用注册 ) MIDDLEWARE_CLASSES = ( 'django.contrib.sessions.middleware.SessionMiddleware', 'django.middleware.common.CommonMiddleware', 'django.middleware.csrf.CsrfViewMiddleware', 'django.contrib.auth.middleware.AuthenticationMiddleware', 'django.contrib.auth.middleware.SessionAuthenticationMiddleware', 'django.contrib.messages.middleware.MessageMiddleware', 'django.middleware.clickjacking.XFrameOptionsMiddleware', 'django.middleware.security.SecurityMiddleware', ) ROOT_URLCONF = 'test1.urls' TEMPLATES = [ { 'BACKEND': 'django.template.backends.django.DjangoTemplates', 'DIRS': [os.path.join(BASE_DIR, 'templates')], # 配置模板目录 'APP_DIRS': True, 'OPTIONS': { 'context_processors': [ 'django.template.context_processors.debug', 'django.template.context_processors.request', 'django.contrib.auth.context_processors.auth', 'django.contrib.messages.context_processors.messages', ], }, }, ] WSGI_APPLICATION = 'test1.wsgi.application' # Database # https://docs.djangoproject.com/en/1.8/ref/settings/#databases DATABASES = { 'default': { 'ENGINE': 'django.db.backends.sqlite3', 'NAME': os.path.join(BASE_DIR, 'db.sqlite3'), } } # Internationalization # https://docs.djangoproject.com/en/1.8/topics/i18n/ # LANGUAGE_CODE = 'en-us' LANGUAGE_CODE = 'zh-hans' # 使用中文 # TIME_ZONE = 'UTC' TIME_ZONE = 'Asia/Shanghai' #使用中国时间 USE_I18N = True USE_L10N = True USE_TZ = True # Static files (CSS, JavaScript, Images) # https://docs.djangoproject.com/en/1.8/howto/static-files/ STATIC_URL = '/static/'
[ "focusdroid@126.com" ]
focusdroid@126.com
172e7821ecc773081c07cf4efa28191b5d77b8e9
a3b0e7acb6e0d7e73f5e369a17f367ac7caf83fb
/python/free_Code_CAmp/scientific_computing_for_everybody/ch_3/playground.py
6f990236ce5c0b0436b2382899a7d87f0b97507e
[]
no_license
jadedocelot/Bin2rong
f9d35731ca7df50cfba36141d249db2858121826
314b509f7b3b3a6a5d6ce589dbc57a2c6212b3d7
refs/heads/master
2023-03-24T14:03:32.374633
2021-03-19T00:05:24
2021-03-19T00:05:24
285,387,043
0
0
null
null
null
null
UTF-8
Python
false
false
601
py
import time # A import random x = (random.range(1,100)) while x < 100: x = x + 20 time.sleep(0.19) print(x) x = x +12 time.sleep(0.23) print(x) x = x + 4 time.sleep(0.38) print(x) x = x + 70 time.sleep(0.60) print(x) break print("End of code") def winScore(): userName = input("Enter in you: ") print("Great job \n",userName) user_score = x if x < 100: print("\nYour score is :", x) print("\nyou lose!\n") else: print("\nYour score is:", x) print("\nYou have scored higher than 100, you win!\n") winScore()
[ "eabelortega@gmail.com" ]
eabelortega@gmail.com
580ca49442935c52d5d05ec0a2f0dde826ee4536
f9e4c2e9cd4a95dc228b384e2e8abadc9f1b0bda
/clubs/views.py
d9f78a81a32d48a5082518ede439e6e26525355d
[]
no_license
sanchitbareja/fratevents
227adddd77c9a0055ccd74d5e0bf6f771790f8d3
f50c8ccb40b8c9124b40e70d90c9190ef27a2fb7
refs/heads/master
2016-09-06T15:36:45.443412
2013-02-16T21:13:36
2013-02-16T21:13:36
null
0
0
null
null
null
null
UTF-8
Python
false
false
1,200
py
# Create your views here. from django.template import Context, RequestContext from django.http import HttpResponse from django.shortcuts import render_to_response from django.template.loader import render_to_string from django import forms from django.http import HttpResponseRedirect from clubs.models import Club import os, time, simplejson from datetime import datetime, date #return json of everything in database def getClubInfoJSON(request): results = {'success':False} try: if(request.method == u'POST'): POST = request.POST print POST['clubID'] club = Club.objects.get(id=POST['clubID']) print club results['id'] = club.id results['name'] = club.name print "debug 1" results['description'] = club.description print "debug 2" results['typeOfOrganization'] = club.typeOfOrganization print "debug 3" results['founded'] = club.founded print "debug 4" results['urlPersonal'] = club.urlPersonal print "debug 7" results['image'] = club.image print "debug 9" results['success'] = True print "debug 9" except: pass print results json_results = simplejson.dumps(results) return HttpResponse(json_results, mimetype='application/json')
[ "sanchitbareja@gmail.com" ]
sanchitbareja@gmail.com
77b0263d6f72098ae8615af9a9bca10d2fe3356e
d1752d73dd7dd8a7c0ea5ce3741f18b9c9073af7
/solutions/Day17_MoreExceptions/Day17_MoreExceptions.py
eedced4a6bfe57d7cedc22b72ec585dd28954258
[ "MIT" ]
permissive
arsho/Hackerrank_30_Days_of_Code_Solutions
58ee9277854d67e967e07d62ddbfd155beefd35b
840e5cbe8025b4488a97d1a51313c19c4e7e91ed
refs/heads/master
2020-05-04T15:26:49.304023
2019-04-03T14:31:29
2019-04-03T14:31:29
179,241,241
2
1
null
null
null
null
UTF-8
Python
false
false
528
py
''' Title : Day 17: More Exceptions Domain : Tutorials Author : Ahmedur Rahman Shovon Created : 03 April 2019 ''' #Write your code here class Calculator(object): def power(self, n, p): if n < 0 or p < 0: raise ValueError("n and p should be non-negative") return n**p myCalculator=Calculator() T=int(input()) for i in range(T): n,p = map(int, input().split()) try: ans=myCalculator.power(n,p) print(ans) except Exception as e: print(e)
[ "shovon.sylhet@gmail.com" ]
shovon.sylhet@gmail.com
6e20ec43fbcfeb13a9b90f75a1e1d161c23035d5
27eeee7dc09efc8911ba32e25fc18e2ea79b7843
/skedulord/job.py
2c622d0771f9e4e2a9298ff8841c1d6ebc14b299
[ "MIT" ]
permissive
koaning/skedulord
fe9253e341dbd8442688508954c032fe74a5ad46
78dc0e630743a059573c34efdd52104586b2c4de
refs/heads/main
2022-06-03T18:04:00.279729
2022-05-21T12:35:26
2022-05-21T12:35:26
215,561,785
65
4
MIT
2022-05-01T12:29:48
2019-10-16T13:58:06
Python
UTF-8
Python
false
false
2,412
py
import io import json import time import uuid import pathlib import subprocess import datetime as dt from skedulord.common import job_name_path, log_heartbeat from pathlib import Path class JobRunner: """ Object in charge of running a job and logging it. """ def __init__(self, name, cmd, retry=3, wait=60): self.name = name self.cmd = cmd self.retry = retry self.wait = wait self.start_time = str(dt.datetime.now())[:19].replace(" ", "T") self.logpath = Path(job_name_path(name)) / f"{self.start_time}.txt" pathlib.Path(self.logpath).parent.mkdir(parents=True, exist_ok=True) pathlib.Path(self.logpath).touch() self.file = self.logpath.open("a") def _attempt_cmd(self, command, name, run_id): tries = 1 stop = False while not stop: info = {"name": name, "command": command, "run_id": run_id, "attempt": tries, "timestamp": str(dt.datetime.now())} self.file.writelines([json.dumps(info), "\n"]) output = subprocess.run( command.split(" "), cwd=str(pathlib.Path().cwd()), stdout=subprocess.PIPE, stderr=subprocess.STDOUT, encoding="utf-8", universal_newlines=True, ) for line in output.stdout.split("\n"): self.file.writelines([line, "\n"]) if output.returncode == 0: stop = True else: tries += 1 if tries > self.retry: stop = True else: time.sleep(self.wait) return "fail" if tries > self.retry else "success" def run(self): """ Run and log a command. """ run_id = str(uuid.uuid4())[:8] start_time = self.start_time status = self._attempt_cmd(command=self.cmd, name=self.name, run_id=run_id) endtime = str(dt.datetime.now())[:19] job_name_path(self.name).mkdir(parents=True, exist_ok=True) logpath = str(job_name_path(self.name) / f"{start_time}.txt") log_heartbeat( run_id=run_id, name=self.name, command=self.cmd, status=status, tic=start_time.replace("T", " "), toc=endtime, logpath=logpath )
[ "vincentwarmerdam@gmail.com" ]
vincentwarmerdam@gmail.com
3071abc122ec82db2b2ba1766208aef9f85ec69c
64546da2b39cf96a490a0b73ce09166e2b704da2
/backend/course/models.py
e6616fc039c250373458eec7bec5f2d3a47329fa
[]
no_license
crowdbotics-apps/for-later-19794
3c547dfef97bd6631929ba3a09954d8edb6bd0de
501d0f3fd4d58775c964e08e1fe75d69bf759520
refs/heads/master
2022-12-06T07:56:19.275934
2020-08-26T15:34:01
2020-08-26T15:34:01
290,533,035
0
0
null
null
null
null
UTF-8
Python
false
false
2,850
py
from django.conf import settings from django.db import models class Recording(models.Model): "Generated Model" event = models.ForeignKey( "course.Event", on_delete=models.CASCADE, related_name="recording_event", ) media = models.URLField() user = models.ForeignKey( "users.User", on_delete=models.CASCADE, related_name="recording_user", ) published = models.DateTimeField() class Module(models.Model): "Generated Model" course = models.ForeignKey( "course.Course", on_delete=models.CASCADE, related_name="module_course", ) title = models.CharField(max_length=256,) description = models.TextField() class Category(models.Model): "Generated Model" name = models.CharField(max_length=256,) class PaymentMethod(models.Model): "Generated Model" user = models.ForeignKey( "users.User", on_delete=models.CASCADE, related_name="paymentmethod_user", ) primary = models.BooleanField() token = models.CharField(max_length=256,) class SubscriptionType(models.Model): "Generated Model" name = models.CharField(max_length=256,) class Event(models.Model): "Generated Model" name = models.CharField(max_length=256,) user = models.ForeignKey( "users.User", on_delete=models.CASCADE, related_name="event_user", ) date = models.DateTimeField() class Enrollment(models.Model): "Generated Model" user = models.ForeignKey( "users.User", on_delete=models.CASCADE, related_name="enrollment_user", ) course = models.ForeignKey( "course.Course", on_delete=models.CASCADE, related_name="enrollment_course", ) class Subscription(models.Model): "Generated Model" subscription_type = models.ForeignKey( "course.SubscriptionType", on_delete=models.CASCADE, related_name="subscription_subscription_type", ) user = models.ForeignKey( "users.User", on_delete=models.CASCADE, related_name="subscription_user", ) class Course(models.Model): "Generated Model" author = models.ForeignKey( "users.User", on_delete=models.CASCADE, related_name="course_author", ) title = models.CharField(null=True, blank=True, max_length=256,) description = models.TextField(null=True, blank=True,) categories = models.ManyToManyField( "course.Category", blank=True, related_name="course_categories", ) class Lesson(models.Model): "Generated Model" module = models.ForeignKey( "course.Module", on_delete=models.CASCADE, related_name="lesson_module", ) title = models.CharField(max_length=256,) description = models.TextField() media = models.URLField() class Group(models.Model): "Generated Model" name = models.CharField(max_length=256,) # Create your models here.
[ "team@crowdbotics.com" ]
team@crowdbotics.com
e7b886977f81669168fde729b360287c320f19a2
b885eaf4df374d41c5a790e7635726a4a45413ca
/LeetCode/Session3/ClosestBSTValue.py
08a5eac84d8b1f8292686d15c2ebb4215e9c68ff
[ "MIT" ]
permissive
shobhitmishra/CodingProblems
2a5de0850478c3c2889ddac40c4ed73e652cf65f
0fc8c5037eef95b3ec9826b3a6e48885fc86659e
refs/heads/master
2021-01-17T23:22:42.442018
2020-04-17T18:25:24
2020-04-17T18:25:24
84,218,320
0
0
null
null
null
null
UTF-8
Python
false
false
925
py
import sys class TreeNode: def __init__(self, x): self.val = x self.left = None self.right = None class Solution: def closestValue(self, root: TreeNode, target: float) -> int: self.minDiffValue = root.val self.closestValueHelper(root, target) return self.minDiffValue def closestValueHelper(self, node: TreeNode, target: float): if not node: return currentDiff = abs(node.val - target) if currentDiff < abs(self.minDiffValue - target): self.minDiffValue = node.val if target < node.val: self.closestValueHelper(node.left, target) else: self.closestValueHelper(node.right, target) ob = Solution() root = TreeNode(4) root.left = TreeNode(2) root.left.left = TreeNode(1) root.left.right = TreeNode(3) root.right = TreeNode(5) print(ob.closestValue(root, 3.14))
[ "shmishra@microsoft.com" ]
shmishra@microsoft.com
8f523c223becca901b73198037ee041f2607b3cf
1f08436bab6cd03bcfb257e8e49405cbc265195a
/12_File/Sample/io_ex10.py
69cc54f04c4f232c4450593d34e968477c1e7d3d
[]
no_license
kuchunbk/PythonBasic
e3ba6322f256d577e37deff09c814c3a374b93b2
a87135d7a98be8830d30acd750d84bcbf777280b
refs/heads/master
2020-03-10T04:28:42.947308
2018-04-17T04:25:51
2018-04-17T04:25:51
129,192,997
0
0
null
null
null
null
UTF-8
Python
false
false
491
py
'''Question: Write a Python program to count the frequency of words in a file. ''' # Python code: from collections import Counter def word_count(fname): with open(fname) as f: return Counter(f.read().split()) print("Number of words in the file :",word_count("test.txt")) '''Output sample: Number of words in the file : Counter({'this': 7, 'Append': 5, 'text.': 5, 'text.Append': 2, 'Welcome': 1, 'to ': 1, 'w3resource.com.': 1}) '''
[ "kuchunbk@gmail.com" ]
kuchunbk@gmail.com
a6da60cb6269f0ba182ed3e312c8156f7620dea8
e1386d15b6e67c2e4e301bfb6d2fdfa817ac082d
/tests/unit_tests/handlers/test_delivery_utility_handlers.py
2610ffaf7d85d9443a29d004dceb09a4dcdee112
[ "MIT" ]
permissive
arteria-project/arteria-delivery
002272f5371a77968fad15061ec6aa00068fab14
46830f5b891dabb3a1352719842d1a9706641032
refs/heads/master
2023-09-04T07:53:12.783287
2023-08-04T13:26:41
2023-08-04T13:26:41
71,244,793
0
8
MIT
2023-08-09T14:52:04
2016-10-18T12:15:20
Python
UTF-8
Python
false
false
653
py
import json from tornado.testing import * from tornado.web import Application from delivery.app import routes from delivery import __version__ as checksum_version from tests.test_utils import DummyConfig class TestUtilityHandlers(AsyncHTTPTestCase): API_BASE = "/api/1.0" def get_app(self): return Application( routes( config=DummyConfig())) def test_version(self): response = self.fetch(self.API_BASE + "/version") expected_result = {"version": checksum_version} self.assertEqual(response.code, 200) self.assertEqual(json.loads(response.body), expected_result)
[ "johan.dahlberg@medsci.uu.se" ]
johan.dahlberg@medsci.uu.se
4ab772d063000b2f73af815811ee2b7718613d44
57fa7d6820ca63d14f6568adb9185b8a8ea47589
/ViewClass/ViewClass/settings.py
26d3ce9d89c07c63796efac306a53f7eadde218c
[]
no_license
kunjabijukchhe/Web-Development
0dd0a5f415adb863f96c1552d90b6b7a282b6945
e9bd5c5cc4b0f12f2f1714986c612494be9ab8ea
refs/heads/master
2020-09-23T04:43:39.118376
2020-07-21T08:21:30
2020-07-21T08:21:30
225,405,104
0
0
null
null
null
null
UTF-8
Python
false
false
3,174
py
""" Django settings for ViewClass project. Generated by 'django-admin startproject' using Django 2.2.3. For more information on this file, see https://docs.djangoproject.com/en/2.2/topics/settings/ For the full list of settings and their values, see https://docs.djangoproject.com/en/2.2/ref/settings/ """ import os # Build paths inside the project like this: os.path.join(BASE_DIR, ...) BASE_DIR = os.path.dirname(os.path.dirname(os.path.abspath(__file__))) TEMPLATE_DIR=os.path.join(BASE_DIR,'templates') # Quick-start development settings - unsuitable for production # See https://docs.djangoproject.com/en/2.2/howto/deployment/checklist/ # SECURITY WARNING: keep the secret key used in production secret! SECRET_KEY = '761kx+tbqwnwrojw3&vzx11$1!%6f+yrh&8yb5v^q%!ky=3if=' # SECURITY WARNING: don't run with debug turned on in production! DEBUG = True ALLOWED_HOSTS = [] # Application definition INSTALLED_APPS = [ 'django.contrib.admin', 'django.contrib.auth', 'django.contrib.contenttypes', 'django.contrib.sessions', 'django.contrib.messages', 'django.contrib.staticfiles', 'reviseApp', ] MIDDLEWARE = [ 'django.middleware.security.SecurityMiddleware', 'django.contrib.sessions.middleware.SessionMiddleware', 'django.middleware.common.CommonMiddleware', 'django.middleware.csrf.CsrfViewMiddleware', 'django.contrib.auth.middleware.AuthenticationMiddleware', 'django.contrib.messages.middleware.MessageMiddleware', 'django.middleware.clickjacking.XFrameOptionsMiddleware', ] ROOT_URLCONF = 'ViewClass.urls' TEMPLATES = [ { 'BACKEND': 'django.template.backends.django.DjangoTemplates', 'DIRS': [TEMPLATE_DIR,], 'APP_DIRS': True, 'OPTIONS': { 'context_processors': [ 'django.template.context_processors.debug', 'django.template.context_processors.request', 'django.contrib.auth.context_processors.auth', 'django.contrib.messages.context_processors.messages', ], }, }, ] WSGI_APPLICATION = 'ViewClass.wsgi.application' # Database # https://docs.djangoproject.com/en/2.2/ref/settings/#databases DATABASES = { 'default': { 'ENGINE': 'django.db.backends.sqlite3', 'NAME': os.path.join(BASE_DIR, 'db.sqlite3'), } } # Password validation # https://docs.djangoproject.com/en/2.2/ref/settings/#auth-password-validators AUTH_PASSWORD_VALIDATORS = [ { 'NAME': 'django.contrib.auth.password_validation.UserAttributeSimilarityValidator', }, { 'NAME': 'django.contrib.auth.password_validation.MinimumLengthValidator', }, { 'NAME': 'django.contrib.auth.password_validation.CommonPasswordValidator', }, { 'NAME': 'django.contrib.auth.password_validation.NumericPasswordValidator', }, ] # Internationalization # https://docs.djangoproject.com/en/2.2/topics/i18n/ LANGUAGE_CODE = 'en-us' TIME_ZONE = 'UTC' USE_I18N = True USE_L10N = True USE_TZ = True # Static files (CSS, JavaScript, Images) # https://docs.djangoproject.com/en/2.2/howto/static-files/ STATIC_URL = '/static/'
[ "bijukchhekunja@gamil.com" ]
bijukchhekunja@gamil.com
353478d1c692ca136b3015ce5ce4e0220ef2efe4
49f23f530d0cda7aadbb27be9c5bdefaa794d27f
/server/common_models/__init__.py
4b63cc4511ffc6f06c746a09ef3301a5c735fe58
[ "MIT" ]
permissive
Soopro/totoro
198f3a51ae94d7466136ee766be98cb559c991f1
6be1af50496340ded9879a6450c8208ac9f97e72
refs/heads/master
2020-05-14T09:22:21.942621
2019-08-03T20:55:23
2019-08-03T20:55:23
181,738,167
0
1
MIT
2019-10-29T13:43:24
2019-04-16T17:42:16
Python
UTF-8
Python
false
false
191
py
# coding=utf-8 from __future__ import absolute_import from .user import * from .media import * from .book import * from .category import * from .configuration import * from .notify import *
[ "redy.ru@gmail.com" ]
redy.ru@gmail.com
1ab5eea08126195608143cbf70088bb0be88adc8
ae844174eff5d14b8627ef8b32e66713f03772c8
/Notes/Lec19/testing with nose.py
86c5c3fa2283cf61d402cbbe75c779e3211c39b5
[]
no_license
tayloa/CSCI1100_Fall2015
1bd6250894083086437c7defceddacf73315b83b
4ca1e6261e3c5d5372d3a097cb6c8601a2a8c1c6
refs/heads/master
2021-01-22T22:43:55.301293
2017-05-30T04:52:21
2017-05-30T04:52:21
92,784,700
0
1
null
null
null
null
UTF-8
Python
false
false
184
py
import nose from search import * def tetst_st1_1(): assert str1([4,1,3,2]) == (1,2) def tetst_st1_1(): assert str1([1,2,3,4]) == def tetst_st1_1(): assert str1([1,2,3,1])
[ "halfnote1004@gmail.com" ]
halfnote1004@gmail.com
7ccab5bc4ae69ea234e05faaef3b39949464da00
7000895fad6f4c23084122ef27b3292d5e57df9f
/tests/core/test_TransactionMetadata.py
be05089d68a8de1c9fc5e458eb05f7072f56148b
[ "MIT" ]
permissive
jack3343/xrd-core
1302cefe2a231895a53fcef73e558cdbc1196884
48a6d890d62485c627060b017eadf85602268caf
refs/heads/master
2022-12-15T07:36:16.618507
2020-08-27T09:21:36
2020-08-27T09:21:36
290,652,706
0
0
null
null
null
null
UTF-8
Python
false
false
5,229
py
# coding=utf-8 # Distributed under the MIT software license, see the accompanying # file LICENSE or http://www.opensource.org/licenses/mit-license.php. from unittest import TestCase from mock import MagicMock from xrd.core import config from xrd.core.TransactionMetadata import TransactionMetadata from xrd.core.misc import logger, db from xrd.core.State import State from xrd.core.txs.TransferTransaction import TransferTransaction from xrd.core.Block import Block from tests.misc.helper import set_xrd_dir, get_alice_xmss, get_some_address logger.initialize_default() class TestTransactionMetadata(TestCase): def setUp(self): with set_xrd_dir('no_data'): self.state = State() self.m_db = MagicMock(name='mock DB', autospec=db.DB) def test_rollback_tx_metadata(self): alice_xmss = get_alice_xmss() tx1 = TransferTransaction.create(addrs_to=[get_some_address(1), get_some_address(2)], amounts=[1, 2], message_data=None, fee=0, xmss_pk=alice_xmss.pk) block = Block.create(dev_config=config.dev, block_number=5, prev_headerhash=b'', prev_timestamp=10, transactions=[tx1], miner_address=b'', seed_height=0, seed_hash=None) TransactionMetadata.update_tx_metadata(self.state, block=block, batch=None) tx_metadata = TransactionMetadata.get_tx_metadata(self.state, tx1.txhash) self.assertEqual(tx_metadata[0].to_json(), tx1.to_json()) TransactionMetadata.rollback_tx_metadata(self.state, block, None) self.assertIsNone(TransactionMetadata.get_tx_metadata(self.state, tx1.txhash)) def test_update_tx_metadata(self): alice_xmss = get_alice_xmss() tx = TransferTransaction.create(addrs_to=[get_some_address(1), get_some_address(2)], amounts=[1, 2], message_data=None, fee=0, xmss_pk=alice_xmss.pk) block_number = 5 TransactionMetadata.put_tx_metadata(self.state, tx, block_number, 10000, None) tx_metadata = TransactionMetadata.get_tx_metadata(self.state, tx.txhash) self.assertEqual(tx_metadata[0].to_json(), tx.to_json()) self.assertEqual(tx_metadata[1], block_number) def test_remove_tx_metadata(self): self.assertIsNone(TransactionMetadata.get_tx_metadata(self.state, b'test1')) alice_xmss = get_alice_xmss() tx = TransferTransaction.create(addrs_to=[get_some_address(1), get_some_address(2)], amounts=[1, 2], message_data=None, fee=0, xmss_pk=alice_xmss.pk) block_number = 5 TransactionMetadata.put_tx_metadata(self.state, tx, block_number, 10000, None) tx_metadata = TransactionMetadata.get_tx_metadata(self.state, tx.txhash) self.assertEqual(tx_metadata[0].to_json(), tx.to_json()) self.assertEqual(tx_metadata[1], block_number) TransactionMetadata.remove_tx_metadata(self.state, tx, None) self.assertIsNone(TransactionMetadata.get_tx_metadata(self.state, tx.txhash)) def test_put_tx_metadata(self): self.assertIsNone(TransactionMetadata.get_tx_metadata(self.state, b'test1')) alice_xmss = get_alice_xmss() tx = TransferTransaction.create(addrs_to=[get_some_address(1), get_some_address(2)], amounts=[1, 2], message_data=None, fee=0, xmss_pk=alice_xmss.pk) block_number = 5 TransactionMetadata.put_tx_metadata(self.state, tx, block_number, 10000, None) tx_metadata = TransactionMetadata.get_tx_metadata(self.state, tx.txhash) self.assertEqual(tx_metadata[0].to_json(), tx.to_json()) self.assertEqual(tx_metadata[1], block_number) def test_get_tx_metadata(self): self.assertIsNone(TransactionMetadata.get_tx_metadata(self.state, b'test1')) alice_xmss = get_alice_xmss() tx = TransferTransaction.create(addrs_to=[get_some_address(1), get_some_address(2)], amounts=[1, 2], message_data=None, fee=0, xmss_pk=alice_xmss.pk) block_number = 5 timestamp = 10000 TransactionMetadata.put_tx_metadata(self.state, tx, block_number, timestamp, None) tx_metadata = TransactionMetadata.get_tx_metadata(self.state, tx.txhash) self.assertEqual(tx_metadata[0].to_json(), tx.to_json()) self.assertEqual(tx_metadata[1], block_number)
[ "70303530+jack3343@users.noreply.github.com" ]
70303530+jack3343@users.noreply.github.com
0b4fbe315a453bb13ddfe9bc6c4cee6d06ad3d86
27b86f422246a78704e0e84983b2630533a47db6
/exploration/tools/diff_dxf_files.py
28162397f11ab0d070fc9d40ac52f5a90195c50b
[ "MIT" ]
permissive
mozman/ezdxf
7512decd600896960660f0f580cab815bf0d7a51
ba6ab0264dcb6833173042a37b1b5ae878d75113
refs/heads/master
2023-09-01T11:55:13.462105
2023-08-15T11:50:05
2023-08-15T12:00:04
79,697,117
750
194
MIT
2023-09-14T09:40:41
2017-01-22T05:55:55
Python
UTF-8
Python
false
false
1,658
py
# Copyright (c) 2023, Manfred Moitzi # License: MIT License from typing import Optional, Iterable from ezdxf.lldxf.tags import Tags from ezdxf.lldxf.tagger import tag_compiler from ezdxf.tools.rawloader import raw_structure_loader from ezdxf.tools.difftags import diff_tags, print_diff, OpCode FILE1 = r"C:\Users\mozman\Desktop\Outbox\906_polylines.dxf" FILE2 = r"C:\Users\mozman\Desktop\Outbox\906_copy.dxf" def get_handle(tags: Tags): try: return tags.get_handle() except ValueError: return "0" def cmp_section(sec1, sec2): for e1 in sec1: handle = get_handle(e1) if handle is None or handle == "0": continue e2 = entity_tags(sec2, handle) if e2 is None: print(f"entity handle #{handle} not found in second file") continue e1 = Tags(tag_compiler(iter(e1))) a, b = e2, e1 diff = list(diff_tags(a, b, ndigits=6)) has_diff = any(op.opcode != OpCode.equal for op in diff) if has_diff: print("-"*79) print(f"comparing {e1.dxftype()}(#{handle})") print_diff(a, b, diff) def cmp_dxf_files(filename1: str, filename2: str): doc1 = raw_structure_loader(filename1) doc2 = raw_structure_loader(filename2) for section in ["TABLES", "BLOCKS", "ENTITIES", "OBJECTS"]: cmp_section(doc1[section], doc2[section]) def entity_tags(entities: Iterable[Tags], handle: str) -> Optional[Tags]: for e in entities: if get_handle(e) == handle: return Tags(tag_compiler(iter(e))) return None if __name__ == "__main__": cmp_dxf_files(FILE1, FILE2)
[ "me@mozman.at" ]
me@mozman.at
656f52ac462cf2a6b5c44a4cfb10a5417245ad90
de24f83a5e3768a2638ebcf13cbe717e75740168
/moodledata/vpl_data/9/usersdata/82/5635/submittedfiles/crianca.py
a715f37838ff16a13db79b479c9046f643398dd8
[]
no_license
rafaelperazzo/programacao-web
95643423a35c44613b0f64bed05bd34780fe2436
170dd5440afb9ee68a973f3de13a99aa4c735d79
refs/heads/master
2021-01-12T14:06:25.773146
2017-12-22T16:05:45
2017-12-22T16:05:45
69,566,344
0
0
null
null
null
null
UTF-8
Python
false
false
237
py
# -*- coding: utf-8 -*- from __future__ import division #ENTRADA P1 = input ('Digite o valor de P1:') C1 = input ('Digite o valor de C1:') P2 = input ('Digite o valor de P2:') C2 = input ('Digite o valor de C2:') #PROCESSAMNETO E SAIDA
[ "rafael.mota@ufca.edu.br" ]
rafael.mota@ufca.edu.br
26893bbbc95fc0c9dadd5b947bef410efc052c39
40b0af3099e8c2d0ce30d8ecce842ea8122be8b2
/BASIC SYNTAX, CONDITIONAL STATEMENTS AND LOOPS/number_between_1_100.py
6e45b2c407889b183c8950d48ab3ad6b8688ba39
[]
no_license
milenpenev/Fundamentals
6c1b1f5e26c4bf4622b1de6a4cc9a3b6a1f7a44b
7754d1e4fba9e8f24b723f434f01f252c137eb60
refs/heads/main
2023-04-08T12:58:23.899238
2021-04-03T07:42:48
2021-04-03T07:42:48
350,467,280
0
0
null
null
null
null
UTF-8
Python
false
false
136
py
number = float(input()) while number < 1 or number > 100: number = float(input()) print(f"The number {number} is between 1 and 100")
[ "milennpenev@gmail.com" ]
milennpenev@gmail.com
6988bd8c6b1fe3ef303ee68b28980a98319aebca
69ed8c9140be238fe3499dfbd27ab4a3fcfcbec8
/webempresa/blog/views.py
bccc7d66a0fe0be9734e9a26fefacd9dfe9ad3d8
[]
no_license
Garavirod/CoffeeWeb
b8b1f3fa2373b2e45dbc393589edd18c17964f8c
e2250a416d0f2bceb3a68617133ae212d835a26c
refs/heads/master
2022-12-18T23:40:26.337613
2019-08-01T19:18:38
2019-08-01T19:18:38
187,440,808
0
0
null
null
null
null
UTF-8
Python
false
false
839
py
from django.shortcuts import render, get_object_or_404 from .models import Post, Category # Create your views here. def blog(request): posts = Post.objects.all() return render(request,"blog/blog.html",{'posts':posts}) def category(request,category_id): #el 'get' nos permite obtener un único registro filtrado ppor una serie de campos por el parametro # category = Category.objects.get(id=category_id) # Los paraámetros serán el modelo y el identificador de la categoría #Buscamos a la inversa todas la entradas que tengan asignada esta categoría category = get_object_or_404(Category,id=category_id) #Nos muestra el error 404 según el modelo posts = Post.objects.filter(categories=category) #Filatra los datos por categoría return render(request,"blog/category.html",{'category':category})
[ "rodrigogarciaavila26@gmail.com" ]
rodrigogarciaavila26@gmail.com