hexsha
stringlengths
40
40
size
int64
7
1.04M
ext
stringclasses
10 values
lang
stringclasses
1 value
max_stars_repo_path
stringlengths
4
247
max_stars_repo_name
stringlengths
4
125
max_stars_repo_head_hexsha
stringlengths
40
78
max_stars_repo_licenses
listlengths
1
10
max_stars_count
int64
1
368k
max_stars_repo_stars_event_min_datetime
stringlengths
24
24
max_stars_repo_stars_event_max_datetime
stringlengths
24
24
max_issues_repo_path
stringlengths
4
247
max_issues_repo_name
stringlengths
4
125
max_issues_repo_head_hexsha
stringlengths
40
78
max_issues_repo_licenses
listlengths
1
10
max_issues_count
int64
1
116k
max_issues_repo_issues_event_min_datetime
stringlengths
24
24
max_issues_repo_issues_event_max_datetime
stringlengths
24
24
max_forks_repo_path
stringlengths
4
247
max_forks_repo_name
stringlengths
4
125
max_forks_repo_head_hexsha
stringlengths
40
78
max_forks_repo_licenses
listlengths
1
10
max_forks_count
int64
1
105k
max_forks_repo_forks_event_min_datetime
stringlengths
24
24
max_forks_repo_forks_event_max_datetime
stringlengths
24
24
content
stringlengths
1
1.04M
avg_line_length
float64
1.77
618k
max_line_length
int64
1
1.02M
alphanum_fraction
float64
0
1
original_content
stringlengths
7
1.04M
filtered:remove_function_no_docstring
int64
-102
942k
filtered:remove_class_no_docstring
int64
-354
977k
filtered:remove_delete_markers
int64
0
60.1k
892ddbf9761a9ac75a73aa7d4771197be4dee5a9
10,730
py
Python
internalScripts/analysis-scripts/GeneratePhenotypeROCCurve.py
kbase/probabilistic_annotation
2454925ca98c80c73bda327a0eff8aed94c5a48d
[ "MIT" ]
null
null
null
internalScripts/analysis-scripts/GeneratePhenotypeROCCurve.py
kbase/probabilistic_annotation
2454925ca98c80c73bda327a0eff8aed94c5a48d
[ "MIT" ]
null
null
null
internalScripts/analysis-scripts/GeneratePhenotypeROCCurve.py
kbase/probabilistic_annotation
2454925ca98c80c73bda327a0eff8aed94c5a48d
[ "MIT" ]
null
null
null
#!/usr/bin/python -u import argparse import sys import re import os import traceback from operator import itemgetter, attrgetter from biokbase.probabilistic_annotation.Client import _read_inifile from biokbase.workspaceService.Client import * desc = ''' Given a JSON object calculate the false positive, negative rates. Optionally omit everything that isn't in the specified media. ''' separator ='///' rolesToRxnsFileName = 'roles_to_reactions' if __name__ == "__main__": parser = argparse.ArgumentParser(prog='GeneratePhenotypeROCCurve.py', description=desc) parser.add_argument('genome', help='ID of genome to analyze', action='store', default=None) parser.add_argument('model', help='ID of integrated gap filled model to analyze', action='store', default=None) parser.add_argument('phenosimset', help='ID of PhenotypeSimulationSet object to analyze', action='store', default=None) parser.add_argument('workspace', help='ID of workspace containing objects to analyze', action='store', default=None) parser.add_argument('--solution', help='index number of solution in integrated gap filled model', action='store', default='0') parser.add_argument('--phenosimsetws', help='workspace containing PhenotypeSimulationSet object (same as workspace if not specified)', action='store', default=None) parser.add_argument('--media', help='limit analysis to only this media condition', action='store', dest='media', default=None) parser.add_argument('--probanno', help='ID of ProbAnno object for genome', action='store', dest='probanno', default=None) parser.add_argument('--probannows', help='workspace containing ProbAnno object (same as workspace if not specified)', action='store', dest='probannows', default=None) parser.add_argument('--rxnprobs', help='ID of RxnProbs object for genome', action='store', dest='rxnprobs', default=None) parser.add_argument('--rxnprobsws', help='workspace containing RxnProbs object (same as workspace if not specified)', action='store', dest='rxnprobsws', default=None) parser.add_argument('--script-dir', help='path to directory with analysis scripts', action='store', dest='scriptDir', default='.') parser.add_argument('--fba-url', help='url for fba modeling service', action='store', dest='fbaurl', default='http://bio-data-1.mcs.anl.gov/services/fba') parser.add_argument('--ws-url', help='url for workspace service', action='store', dest='wsurl', default='http://kbase.us/services/workspace/') args = parser.parse_args() if args.probanno is None: args.probanno = args.genome + '.probanno' if args.probannows is None: args.probannows = args.workspace if args.rxnprobs is None: args.rxnprobs = args.genome + '.rxnprobs' if args.rxnprobsws is None: args.rxnprobsws = args.workspace if args.phenosimsetws is None: args.phenosimsetws = args.workspace # Create the clients for the services we need. authdata = _read_inifile() token = authdata['token'] wsClient = workspaceService(args.wsurl) # Build roles to reactions dictionary. step = 1 print "+++ Step %d: Build reactions to roles dictionary +++" %(step) if not os.path.exists(rolesToRxnsFileName): os.system("all_roles_used_in_models | roles_to_complexes | get_relationship_HasStep -to id >%s" %(rolesToRxnsFileName)) rolesToReactions = dict() reactionsToRoles = dict() # Each line of the file has four fields: (1) role, (2) hypothetical flag, (3) complex id, (4) reaction id rolesToRxnsFile = open(rolesToRxnsFileName, 'r') for line in rolesToRxnsFile: fields = line.strip('\r\n').split('\t') reaction = fields[3] if reaction not in reactionsToRoles: reactionsToRoles[reaction] = list() reactionsToRoles[reaction].append(fields[0]) rolesToRxnsFile.close() print " %d reactions in reactions to roles dictionary" %(len(reactionsToRoles)) # Analyze the gap fill results for the specified model. step += 1 print "+++ Step %d: Run AnalyzeGapfillResults.py for model '%s/%s' +++" %(step, args.workspace, args.model) rxnprobs = args.rxnprobs resultsFileName = args.model + '.results' os.system("%s/AnalyzeGapfillResults.py -m %s -w %s --rxnprobs %s --url %s >%s" \ %(args.scriptDir, args.model, args.workspace, rxnprobs, args.fbaurl, resultsFileName)) genesToReactions = dict() resultsFile = open(resultsFileName, 'r') resultsFile.readline() # Throw away header line for line in resultsFile: fields = line.strip('\r\n').split('\t') if fields[0] == args.solution: if fields[5] == '0': # Only keep reactions that are not a reversibility change if fields[6]: # Only keep reactions that have a GPR rxnid = re.sub(r'rxn0*(\d+)', r'kb|rxn.\1', fields[1]) geneList = re.findall('fig\|\d+\.\d+\.peg\.\d+', fields[6]) for index in range(len(geneList)): if geneList[index] not in genesToReactions: genesToReactions[geneList[index]] = dict() genesToReactions[geneList[index]][rxnid] = 0.0 resultsFile.close() print " %d genes in genes to reactions dictionary" %(len(genesToReactions)) # Get the ProbAnno object from the workspace. step += 1 probanno = args.probanno print "+++ Step %d: Get ProbAnno object '%s/%s'" %(step, args.probannows, probanno) paObject = wsClient.get_object( { 'id': probanno, 'workspace': args.probannows, 'type': 'ProbAnno', 'auth': token } ) probAnno = paObject['data'] print " %d genes in ProbAnno roleset probabilities dictionary" %(len(probAnno['roleset_probabilities'])) # Need to go through rolesets dictionary # If an entry has more than one role, split into parts # Then run the array and combine any duplicate roles by adding probs # Parse the roleset probabilities from the ProbAnno object. step += 1 print "+++ Step %d: Parse rolesets into roles and adjust probabilities for duplicates +++" %(step) rolesetProbabilities = dict() for gene in probAnno['roleset_probabilities']: geneRoleList = probAnno['roleset_probabilities'][gene] geneRoleDict = dict() for index in range(len(geneRoleList)): prob = geneRoleList[index][1] # Probability for this roleset # Split multiple roles in roleset for this gene roleList = geneRoleList[index][0].split(separator) # If role occurs more than once, add up the probabilities for j in range(len(roleList)): if roleList[j] in geneRoleDict: geneRoleDict[roleList[j]] += prob else: geneRoleDict[roleList[j]] = prob rolesetProbabilities[gene] = geneRoleDict print " %d genes in parsed roleset probabilities dictionary" %(len(rolesetProbabilities)) # for each reaction in the reactions dictionary, find the roles in the rolesToReactions dictionary # then find the roles in the probanno object for the gene step += 1 print "+++ Step %d: Find maximum probability of reaction given gene +++" %(step) probsFile = open(args.model+'.probs', 'w') numProbs = 0 for gene in genesToReactions: if gene in rolesetProbabilities: geneRoleDict = rolesetProbabilities[gene] for reaction in genesToReactions[gene]: if reaction not in reactionsToRoles: print 'Why is reaction %s not in the reactionToRoles dictionary?' %(reaction) roleList = reactionsToRoles[reaction] for index in range(0,len(roleList)): for role in geneRoleDict: if role == roleList[index]: probsFile.write('P(%s | %s) = %f\n' %(reaction, gene, geneRoleDict[role])) genesToReactions[gene][reaction] = max(geneRoleDict[role], genesToReactions[gene][reaction]) numProbs += 1 else: print 'Gene %s not found in ProbAnno object' %(gene) probsFile.close() print " %d reaction probabilities set in genesToReactions dictionary" %(numProbs) # Get the PhenotypeSimulationSet object. step += 1 print "+++ Step %d: Get phenotype simulation set %s/%s +++" %(step, args.phenosimsetws, args.phenosimset) pssObject = wsClient.get_object( { 'id': args.phenosimset, 'workspace': args.phenosimsetws, 'type': 'PhenotypeSimulationSet', 'auth': token } ) phenoSimSet = pssObject['data'] # Make sure the model matches in the phenotype simulation set. if phenoSimSet['model'] != args.model or phenoSimSet['model_workspace'] != args.workspace: print 'Specified model %s/%s does not match model %s/%s in phenotype simulation set' \ %(args.workspace, args.model, phenoSimSet['model_workspace'], phenoSimSet['model']) print " %d simulations in phenotype simulation set" %(len(phenoSimSet['phenotypeSimulations'])) # Go through the list of simulations, for each gene and see if the gene is in the genesToReactions # dictionary. If so, mark it as known and include the probability. Otherwise, mark it as unknown # and set the probability to 0.5. In both cases, set a flag indicating if the simulation was # correct or incorrect. step += 1 print "+++ Step %d: Analyze phenotype simulation set results +++" %(step) numKnown = 0 resultList = list() for sim in phenoSimSet['phenotypeSimulations']: if sim[3] == 'CP' or sim[3] == 'CN': right = 1 else: right = 0 geneList = sim[0][0] for gene in geneList: if gene in genesToReactions: for reaction in genesToReactions[gene]: resultList.append( (gene, reaction, genesToReactions[gene][reaction], right ) ) numKnown += 1 else: resultList.append( (gene, 'unknown', 0.5, right) ) print " %d genes had reactions with known probabilities" %(numKnown) step += 1 print "+++ Step %d: Save analysis to file +++" %(step) resultList.sort(key=itemgetter(2), reverse=True) resultFile = open(args.phenosimset+'.results.csv', 'w') resultFile.write('prob,true,reaction\n') for index in range(len(resultList)): resultFile.write('%f,%d,%s\n' %(resultList[index][2], resultList[index][3], resultList[index][1])) print " Saved analysis to %s" %(resultFile.name) resultFile.close() exit(0)
54.191919
170
0.656198
#!/usr/bin/python -u import argparse import sys import re import os import traceback from operator import itemgetter, attrgetter from biokbase.probabilistic_annotation.Client import _read_inifile from biokbase.workspaceService.Client import * desc = ''' Given a JSON object calculate the false positive, negative rates. Optionally omit everything that isn't in the specified media. ''' separator ='///' rolesToRxnsFileName = 'roles_to_reactions' if __name__ == "__main__": parser = argparse.ArgumentParser(prog='GeneratePhenotypeROCCurve.py', description=desc) parser.add_argument('genome', help='ID of genome to analyze', action='store', default=None) parser.add_argument('model', help='ID of integrated gap filled model to analyze', action='store', default=None) parser.add_argument('phenosimset', help='ID of PhenotypeSimulationSet object to analyze', action='store', default=None) parser.add_argument('workspace', help='ID of workspace containing objects to analyze', action='store', default=None) parser.add_argument('--solution', help='index number of solution in integrated gap filled model', action='store', default='0') parser.add_argument('--phenosimsetws', help='workspace containing PhenotypeSimulationSet object (same as workspace if not specified)', action='store', default=None) parser.add_argument('--media', help='limit analysis to only this media condition', action='store', dest='media', default=None) parser.add_argument('--probanno', help='ID of ProbAnno object for genome', action='store', dest='probanno', default=None) parser.add_argument('--probannows', help='workspace containing ProbAnno object (same as workspace if not specified)', action='store', dest='probannows', default=None) parser.add_argument('--rxnprobs', help='ID of RxnProbs object for genome', action='store', dest='rxnprobs', default=None) parser.add_argument('--rxnprobsws', help='workspace containing RxnProbs object (same as workspace if not specified)', action='store', dest='rxnprobsws', default=None) parser.add_argument('--script-dir', help='path to directory with analysis scripts', action='store', dest='scriptDir', default='.') parser.add_argument('--fba-url', help='url for fba modeling service', action='store', dest='fbaurl', default='http://bio-data-1.mcs.anl.gov/services/fba') parser.add_argument('--ws-url', help='url for workspace service', action='store', dest='wsurl', default='http://kbase.us/services/workspace/') args = parser.parse_args() if args.probanno is None: args.probanno = args.genome + '.probanno' if args.probannows is None: args.probannows = args.workspace if args.rxnprobs is None: args.rxnprobs = args.genome + '.rxnprobs' if args.rxnprobsws is None: args.rxnprobsws = args.workspace if args.phenosimsetws is None: args.phenosimsetws = args.workspace # Create the clients for the services we need. authdata = _read_inifile() token = authdata['token'] wsClient = workspaceService(args.wsurl) # Build roles to reactions dictionary. step = 1 print "+++ Step %d: Build reactions to roles dictionary +++" %(step) if not os.path.exists(rolesToRxnsFileName): os.system("all_roles_used_in_models | roles_to_complexes | get_relationship_HasStep -to id >%s" %(rolesToRxnsFileName)) rolesToReactions = dict() reactionsToRoles = dict() # Each line of the file has four fields: (1) role, (2) hypothetical flag, (3) complex id, (4) reaction id rolesToRxnsFile = open(rolesToRxnsFileName, 'r') for line in rolesToRxnsFile: fields = line.strip('\r\n').split('\t') reaction = fields[3] if reaction not in reactionsToRoles: reactionsToRoles[reaction] = list() reactionsToRoles[reaction].append(fields[0]) rolesToRxnsFile.close() print " %d reactions in reactions to roles dictionary" %(len(reactionsToRoles)) # Analyze the gap fill results for the specified model. step += 1 print "+++ Step %d: Run AnalyzeGapfillResults.py for model '%s/%s' +++" %(step, args.workspace, args.model) rxnprobs = args.rxnprobs resultsFileName = args.model + '.results' os.system("%s/AnalyzeGapfillResults.py -m %s -w %s --rxnprobs %s --url %s >%s" \ %(args.scriptDir, args.model, args.workspace, rxnprobs, args.fbaurl, resultsFileName)) genesToReactions = dict() resultsFile = open(resultsFileName, 'r') resultsFile.readline() # Throw away header line for line in resultsFile: fields = line.strip('\r\n').split('\t') if fields[0] == args.solution: if fields[5] == '0': # Only keep reactions that are not a reversibility change if fields[6]: # Only keep reactions that have a GPR rxnid = re.sub(r'rxn0*(\d+)', r'kb|rxn.\1', fields[1]) geneList = re.findall('fig\|\d+\.\d+\.peg\.\d+', fields[6]) for index in range(len(geneList)): if geneList[index] not in genesToReactions: genesToReactions[geneList[index]] = dict() genesToReactions[geneList[index]][rxnid] = 0.0 resultsFile.close() print " %d genes in genes to reactions dictionary" %(len(genesToReactions)) # Get the ProbAnno object from the workspace. step += 1 probanno = args.probanno print "+++ Step %d: Get ProbAnno object '%s/%s'" %(step, args.probannows, probanno) paObject = wsClient.get_object( { 'id': probanno, 'workspace': args.probannows, 'type': 'ProbAnno', 'auth': token } ) probAnno = paObject['data'] print " %d genes in ProbAnno roleset probabilities dictionary" %(len(probAnno['roleset_probabilities'])) # Need to go through rolesets dictionary # If an entry has more than one role, split into parts # Then run the array and combine any duplicate roles by adding probs # Parse the roleset probabilities from the ProbAnno object. step += 1 print "+++ Step %d: Parse rolesets into roles and adjust probabilities for duplicates +++" %(step) rolesetProbabilities = dict() for gene in probAnno['roleset_probabilities']: geneRoleList = probAnno['roleset_probabilities'][gene] geneRoleDict = dict() for index in range(len(geneRoleList)): prob = geneRoleList[index][1] # Probability for this roleset # Split multiple roles in roleset for this gene roleList = geneRoleList[index][0].split(separator) # If role occurs more than once, add up the probabilities for j in range(len(roleList)): if roleList[j] in geneRoleDict: geneRoleDict[roleList[j]] += prob else: geneRoleDict[roleList[j]] = prob rolesetProbabilities[gene] = geneRoleDict print " %d genes in parsed roleset probabilities dictionary" %(len(rolesetProbabilities)) # for each reaction in the reactions dictionary, find the roles in the rolesToReactions dictionary # then find the roles in the probanno object for the gene step += 1 print "+++ Step %d: Find maximum probability of reaction given gene +++" %(step) probsFile = open(args.model+'.probs', 'w') numProbs = 0 for gene in genesToReactions: if gene in rolesetProbabilities: geneRoleDict = rolesetProbabilities[gene] for reaction in genesToReactions[gene]: if reaction not in reactionsToRoles: print 'Why is reaction %s not in the reactionToRoles dictionary?' %(reaction) roleList = reactionsToRoles[reaction] for index in range(0,len(roleList)): for role in geneRoleDict: if role == roleList[index]: probsFile.write('P(%s | %s) = %f\n' %(reaction, gene, geneRoleDict[role])) genesToReactions[gene][reaction] = max(geneRoleDict[role], genesToReactions[gene][reaction]) numProbs += 1 else: print 'Gene %s not found in ProbAnno object' %(gene) probsFile.close() print " %d reaction probabilities set in genesToReactions dictionary" %(numProbs) # Get the PhenotypeSimulationSet object. step += 1 print "+++ Step %d: Get phenotype simulation set %s/%s +++" %(step, args.phenosimsetws, args.phenosimset) pssObject = wsClient.get_object( { 'id': args.phenosimset, 'workspace': args.phenosimsetws, 'type': 'PhenotypeSimulationSet', 'auth': token } ) phenoSimSet = pssObject['data'] # Make sure the model matches in the phenotype simulation set. if phenoSimSet['model'] != args.model or phenoSimSet['model_workspace'] != args.workspace: print 'Specified model %s/%s does not match model %s/%s in phenotype simulation set' \ %(args.workspace, args.model, phenoSimSet['model_workspace'], phenoSimSet['model']) print " %d simulations in phenotype simulation set" %(len(phenoSimSet['phenotypeSimulations'])) # Go through the list of simulations, for each gene and see if the gene is in the genesToReactions # dictionary. If so, mark it as known and include the probability. Otherwise, mark it as unknown # and set the probability to 0.5. In both cases, set a flag indicating if the simulation was # correct or incorrect. step += 1 print "+++ Step %d: Analyze phenotype simulation set results +++" %(step) numKnown = 0 resultList = list() for sim in phenoSimSet['phenotypeSimulations']: if sim[3] == 'CP' or sim[3] == 'CN': right = 1 else: right = 0 geneList = sim[0][0] for gene in geneList: if gene in genesToReactions: for reaction in genesToReactions[gene]: resultList.append( (gene, reaction, genesToReactions[gene][reaction], right ) ) numKnown += 1 else: resultList.append( (gene, 'unknown', 0.5, right) ) print " %d genes had reactions with known probabilities" %(numKnown) step += 1 print "+++ Step %d: Save analysis to file +++" %(step) resultList.sort(key=itemgetter(2), reverse=True) resultFile = open(args.phenosimset+'.results.csv', 'w') resultFile.write('prob,true,reaction\n') for index in range(len(resultList)): resultFile.write('%f,%d,%s\n' %(resultList[index][2], resultList[index][3], resultList[index][1])) print " Saved analysis to %s" %(resultFile.name) resultFile.close() exit(0)
0
0
0
fd0f329ab7fc7ffe7339fd4bccaa6df4c6149391
836
py
Python
modules/sentiment.py
jsamar1/wtfthisarticle
e0ed4ff0e70822339d9b8c6bed49ac165f2f97a2
[ "MIT" ]
null
null
null
modules/sentiment.py
jsamar1/wtfthisarticle
e0ed4ff0e70822339d9b8c6bed49ac165f2f97a2
[ "MIT" ]
7
2021-03-18T21:01:21.000Z
2022-03-11T23:28:59.000Z
modules/sentiment.py
jsamar1/wtfthisarticle
e0ed4ff0e70822339d9b8c6bed49ac165f2f97a2
[ "MIT" ]
1
2018-09-30T10:09:53.000Z
2018-09-30T10:09:53.000Z
# Imports the Google Cloud client library from google.cloud import language from google.cloud.language import enums from google.cloud.language import types import json import re
27.866667
78
0.696172
# Imports the Google Cloud client library from google.cloud import language from google.cloud.language import enums from google.cloud.language import types import json import re def analyze(text): # Instantiates a client client = language.LanguageServiceClient() # The text to analyze document = types.Document( content=text, type=enums.Document.Type.PLAIN_TEXT) # Detects the sentiment of the text sentiment = client.analyze_sentiment(document=document).document_sentiment # print('Text: {}'.format(text)) # print('Sentiment: {}, {}'.format(sentiment.score, sentiment.magnitude)) sentiment = { 'score' : sentiment.score, 'magnitude' : sentiment.magnitude } with open('modules/json/sentiment.json', 'w') as outfile: json.dump(sentiment, outfile)
634
0
23
13fa97be4cc3d64f3acac671d8fd28e7569d6f67
64
py
Python
Dangerous/Golismero/thirdparty_libs/requests_ntlm/__init__.py
JeyZeta/Dangerous-
824ea6b571eda98bb855f176361e9b35dfda578e
[ "MIT" ]
null
null
null
Dangerous/Golismero/thirdparty_libs/requests_ntlm/__init__.py
JeyZeta/Dangerous-
824ea6b571eda98bb855f176361e9b35dfda578e
[ "MIT" ]
null
null
null
Dangerous/Golismero/thirdparty_libs/requests_ntlm/__init__.py
JeyZeta/Dangerous-
824ea6b571eda98bb855f176361e9b35dfda578e
[ "MIT" ]
1
2018-07-04T18:35:16.000Z
2018-07-04T18:35:16.000Z
from requests_ntlm import HttpNtlmAuth __all__ = [HttpNtlmAuth]
21.333333
38
0.84375
from requests_ntlm import HttpNtlmAuth __all__ = [HttpNtlmAuth]
0
0
0
b9440083d88705c3693e34c4cc54c50c8df8fe7f
634
py
Python
liliput/migrations/0002_verify_and_count.py
strassan/www.kaifeck.de
b54698e8e57eaedbc4cb4ea3335fc719df92108f
[ "MIT" ]
2
2020-07-29T17:35:31.000Z
2021-06-06T11:37:49.000Z
liliput/migrations/0002_verify_and_count.py
strassan/www.kaifeck.de
b54698e8e57eaedbc4cb4ea3335fc719df92108f
[ "MIT" ]
4
2020-10-28T19:06:02.000Z
2021-01-11T16:06:46.000Z
liliput/migrations/0002_verify_and_count.py
strassan/www.kaifeck.de
b54698e8e57eaedbc4cb4ea3335fc719df92108f
[ "MIT" ]
null
null
null
# Generated by Django 3.0.7 on 2020-06-30 14:42 from django.db import migrations, models
24.384615
65
0.585174
# Generated by Django 3.0.7 on 2020-06-30 14:42 from django.db import migrations, models class Migration(migrations.Migration): dependencies = [ ('liliput', '0001_initial'), ] operations = [ migrations.AddField( model_name='shortlink', name='number_of_requests', field=models.IntegerField(default=0, editable=False), preserve_default=False, ), migrations.AddField( model_name='shortlink', name='verified', field=models.BooleanField(default=False), preserve_default=False, ), ]
0
520
23
c361e3d7e233b7a9094e7596ce0361df9cd3aa9d
946
py
Python
src/gamesbyexample/tutorialguess1.py
RedStarfish/PythonStdioGames
0fa4d42f1a0c2dde403e70cdd47e7a9e81430efe
[ "MIT" ]
null
null
null
src/gamesbyexample/tutorialguess1.py
RedStarfish/PythonStdioGames
0fa4d42f1a0c2dde403e70cdd47e7a9e81430efe
[ "MIT" ]
null
null
null
src/gamesbyexample/tutorialguess1.py
RedStarfish/PythonStdioGames
0fa4d42f1a0c2dde403e70cdd47e7a9e81430efe
[ "MIT" ]
null
null
null
"""Tutorial: Guess the Number, by Al Sweigart al@inventwithpython.com Part 1 of a tutorial to make a "Guess the Number" game, bit by bit.""" # Try copying the code in this program on your own and running the # program before moving on to part 2. (You don't have to copy the # comments.) # Everything after a # is a "comment" and is ignored by the computer. # You can use comments to write notes and reminders in your code. # This program really only has three lines of actual code. # Programs start executing instructions at the top of the file # and go down. # The print() function displays text on the screen. Notice that # the ' single quotes are not printed: print('Hello! What is your name?') # The input() function lets the player type text in and press Enter. The # text is stored in a variable named playerName: playerName = input() # This displays the name that the player typed in: print('It is good to meet you, ' + playerName)
36.384615
72
0.739958
"""Tutorial: Guess the Number, by Al Sweigart al@inventwithpython.com Part 1 of a tutorial to make a "Guess the Number" game, bit by bit.""" # Try copying the code in this program on your own and running the # program before moving on to part 2. (You don't have to copy the # comments.) # Everything after a # is a "comment" and is ignored by the computer. # You can use comments to write notes and reminders in your code. # This program really only has three lines of actual code. # Programs start executing instructions at the top of the file # and go down. # The print() function displays text on the screen. Notice that # the ' single quotes are not printed: print('Hello! What is your name?') # The input() function lets the player type text in and press Enter. The # text is stored in a variable named playerName: playerName = input() # This displays the name that the player typed in: print('It is good to meet you, ' + playerName)
0
0
0
0af06fb53569af078a78e8ae77d7643b0412ff90
251
py
Python
tests/fixtures/auth.py
reiem/python-economic-rest
0d2df7fef8ea6a567f9a651e4f70ac4045180b79
[ "BSD-3-Clause" ]
null
null
null
tests/fixtures/auth.py
reiem/python-economic-rest
0d2df7fef8ea6a567f9a651e4f70ac4045180b79
[ "BSD-3-Clause" ]
null
null
null
tests/fixtures/auth.py
reiem/python-economic-rest
0d2df7fef8ea6a567f9a651e4f70ac4045180b79
[ "BSD-3-Clause" ]
null
null
null
from economic.auth import Authentication import pytest from _pytest.fixtures import SubRequest @pytest.fixture
20.916667
40
0.752988
from economic.auth import Authentication import pytest from _pytest.fixtures import SubRequest @pytest.fixture def auth(request: SubRequest): return Authentication( request.config.option.app_id, request.config.option.token )
116
0
22
f5ce58a0e4e3e74a06b00a176dd1ef7357320590
4,710
py
Python
ptranking/ltr_adhoc/listwise/lambdarank.py
ii-research-ranking/ptranking
2794e6e086bcd87ce177f40194339e9b825e9f4c
[ "MIT" ]
64
2018-09-19T17:04:04.000Z
2020-04-30T07:54:04.000Z
ptranking/ltr_adhoc/listwise/lambdarank.py
ii-research-ranking/ptranking
2794e6e086bcd87ce177f40194339e9b825e9f4c
[ "MIT" ]
4
2018-09-27T06:59:02.000Z
2020-01-05T12:35:12.000Z
ptranking/ltr_adhoc/listwise/lambdarank.py
ii-research-ranking/ptranking
2794e6e086bcd87ce177f40194339e9b825e9f4c
[ "MIT" ]
11
2018-09-28T07:17:51.000Z
2020-03-12T06:28:35.000Z
#!/usr/bin/env python # -*- coding: utf-8 -*- """Description Christopher J.C. Burges, Robert Ragno, and Quoc Viet Le. 2006. Learning to Rank with Nonsmooth Cost Functions. In Proceedings of NIPS conference. 193–200. """ import torch import torch.nn.functional as F from ptranking.data.data_utils import LABEL_TYPE from ptranking.metric.metric_utils import get_delta_ndcg from ptranking.base.adhoc_ranker import AdhocNeuralRanker from ptranking.ltr_adhoc.eval.parameter import ModelParameter from ptranking.ltr_adhoc.util.lambda_utils import get_pairwise_comp_probs class LambdaRank(AdhocNeuralRanker): ''' Christopher J.C. Burges, Robert Ragno, and Quoc Viet Le. 2006. Learning to Rank with Nonsmooth Cost Functions. In Proceedings of NIPS conference. 193–200. ''' def custom_loss_function(self, batch_preds, batch_std_labels, **kwargs): ''' @param batch_preds: [batch, ranking_size] each row represents the relevance predictions for documents associated with the same query @param batch_std_labels: [batch, ranking_size] each row represents the standard relevance grades for documents associated with the same query @param kwargs: @return: ''' assert 'label_type' in kwargs and LABEL_TYPE.MultiLabel == kwargs['label_type'] label_type = kwargs['label_type'] assert 'presort' in kwargs and kwargs['presort'] is True # aiming for direct usage of ideal ranking # sort documents according to the predicted relevance batch_descending_preds, batch_pred_desc_inds = torch.sort(batch_preds, dim=1, descending=True) # reorder batch_stds correspondingly so as to make it consistent. # BTW, batch_stds[batch_preds_sorted_inds] only works with 1-D tensor batch_predict_rankings = torch.gather(batch_std_labels, dim=1, index=batch_pred_desc_inds) batch_p_ij, batch_std_p_ij = get_pairwise_comp_probs(batch_preds=batch_descending_preds, batch_std_labels=batch_predict_rankings, sigma=self.sigma) batch_delta_ndcg = get_delta_ndcg(batch_ideal_rankings=batch_std_labels, batch_predict_rankings=batch_predict_rankings, label_type=label_type, device=self.device) _batch_loss = F.binary_cross_entropy(input=torch.triu(batch_p_ij, diagonal=1), target=torch.triu(batch_std_p_ij, diagonal=1), weight=torch.triu(batch_delta_ndcg, diagonal=1), reduction='none') batch_loss = torch.sum(torch.sum(_batch_loss, dim=(2, 1))) self.optimizer.zero_grad() batch_loss.backward() self.optimizer.step() return batch_loss ###### Parameter of LambdaRank ###### class LambdaRankParameter(ModelParameter): ''' Parameter class for LambdaRank ''' def default_para_dict(self): """ Default parameter setting for LambdaRank :return: """ self.lambda_para_dict = dict(model_id=self.model_id, sigma=1.0) return self.lambda_para_dict def to_para_string(self, log=False, given_para_dict=None): """ String identifier of parameters :param log: :param given_para_dict: a given dict, which is used for maximum setting w.r.t. grid-search :return: """ # using specified para-dict or inner para-dict lambda_para_dict = given_para_dict if given_para_dict is not None else self.lambda_para_dict s1, s2 = (':', '\n') if log else ('_', '_') lambdarank_para_str = s1.join(['Sigma', '{:,g}'.format(lambda_para_dict['sigma'])]) return lambdarank_para_str def grid_search(self): """ Iterator of parameter settings for LambdaRank """ if self.use_json: choice_sigma = self.json_dict['sigma'] else: choice_sigma = [5.0, 1.0] if self.debug else [1.0] # 1.0, 10.0, 50.0, 100.0 for sigma in choice_sigma: self.lambda_para_dict = dict(model_id=self.model_id, sigma=sigma) yield self.lambda_para_dict
44.018692
149
0.661146
#!/usr/bin/env python # -*- coding: utf-8 -*- """Description Christopher J.C. Burges, Robert Ragno, and Quoc Viet Le. 2006. Learning to Rank with Nonsmooth Cost Functions. In Proceedings of NIPS conference. 193–200. """ import torch import torch.nn.functional as F from ptranking.data.data_utils import LABEL_TYPE from ptranking.metric.metric_utils import get_delta_ndcg from ptranking.base.adhoc_ranker import AdhocNeuralRanker from ptranking.ltr_adhoc.eval.parameter import ModelParameter from ptranking.ltr_adhoc.util.lambda_utils import get_pairwise_comp_probs class LambdaRank(AdhocNeuralRanker): ''' Christopher J.C. Burges, Robert Ragno, and Quoc Viet Le. 2006. Learning to Rank with Nonsmooth Cost Functions. In Proceedings of NIPS conference. 193–200. ''' def __init__(self, sf_para_dict=None, model_para_dict=None, gpu=False, device=None): super(LambdaRank, self).__init__(id='LambdaRank', sf_para_dict=sf_para_dict, gpu=gpu, device=device) self.sigma = model_para_dict['sigma'] def custom_loss_function(self, batch_preds, batch_std_labels, **kwargs): ''' @param batch_preds: [batch, ranking_size] each row represents the relevance predictions for documents associated with the same query @param batch_std_labels: [batch, ranking_size] each row represents the standard relevance grades for documents associated with the same query @param kwargs: @return: ''' assert 'label_type' in kwargs and LABEL_TYPE.MultiLabel == kwargs['label_type'] label_type = kwargs['label_type'] assert 'presort' in kwargs and kwargs['presort'] is True # aiming for direct usage of ideal ranking # sort documents according to the predicted relevance batch_descending_preds, batch_pred_desc_inds = torch.sort(batch_preds, dim=1, descending=True) # reorder batch_stds correspondingly so as to make it consistent. # BTW, batch_stds[batch_preds_sorted_inds] only works with 1-D tensor batch_predict_rankings = torch.gather(batch_std_labels, dim=1, index=batch_pred_desc_inds) batch_p_ij, batch_std_p_ij = get_pairwise_comp_probs(batch_preds=batch_descending_preds, batch_std_labels=batch_predict_rankings, sigma=self.sigma) batch_delta_ndcg = get_delta_ndcg(batch_ideal_rankings=batch_std_labels, batch_predict_rankings=batch_predict_rankings, label_type=label_type, device=self.device) _batch_loss = F.binary_cross_entropy(input=torch.triu(batch_p_ij, diagonal=1), target=torch.triu(batch_std_p_ij, diagonal=1), weight=torch.triu(batch_delta_ndcg, diagonal=1), reduction='none') batch_loss = torch.sum(torch.sum(_batch_loss, dim=(2, 1))) self.optimizer.zero_grad() batch_loss.backward() self.optimizer.step() return batch_loss ###### Parameter of LambdaRank ###### class LambdaRankParameter(ModelParameter): ''' Parameter class for LambdaRank ''' def __init__(self, debug=False, para_json=None): super(LambdaRankParameter, self).__init__(model_id='LambdaRank', para_json=para_json) self.debug = debug def default_para_dict(self): """ Default parameter setting for LambdaRank :return: """ self.lambda_para_dict = dict(model_id=self.model_id, sigma=1.0) return self.lambda_para_dict def to_para_string(self, log=False, given_para_dict=None): """ String identifier of parameters :param log: :param given_para_dict: a given dict, which is used for maximum setting w.r.t. grid-search :return: """ # using specified para-dict or inner para-dict lambda_para_dict = given_para_dict if given_para_dict is not None else self.lambda_para_dict s1, s2 = (':', '\n') if log else ('_', '_') lambdarank_para_str = s1.join(['Sigma', '{:,g}'.format(lambda_para_dict['sigma'])]) return lambdarank_para_str def grid_search(self): """ Iterator of parameter settings for LambdaRank """ if self.use_json: choice_sigma = self.json_dict['sigma'] else: choice_sigma = [5.0, 1.0] if self.debug else [1.0] # 1.0, 10.0, 50.0, 100.0 for sigma in choice_sigma: self.lambda_para_dict = dict(model_id=self.model_id, sigma=sigma) yield self.lambda_para_dict
366
0
52
78d1e28cfc697d589decfb83ba1a7618a037e58a
1,928
py
Python
dash_extra_components/TableOfContents.py
plotly/dash-extra-components
947b13e045806b4f158d77d84bd5ade938fce96e
[ "MIT" ]
12
2019-01-03T21:13:59.000Z
2021-08-10T22:55:52.000Z
dash_extra_components/TableOfContents.py
plotly/dash-extra-components
947b13e045806b4f158d77d84bd5ade938fce96e
[ "MIT" ]
7
2018-12-20T22:08:23.000Z
2021-05-07T23:54:50.000Z
dash_extra_components/TableOfContents.py
plotly/dash-extra-components
947b13e045806b4f158d77d84bd5ade938fce96e
[ "MIT" ]
1
2021-06-18T19:12:40.000Z
2021-06-18T19:12:40.000Z
# AUTO GENERATED FILE - DO NOT EDIT from dash.development.base_component import Component, _explicitize_args class TableOfContents(Component): """A TableOfContents component. Build a table of contents list with links to the headers tag. Keyword arguments: - id (string; optional): Unique identifier for the component. - className (string; optional): className for the top ul component. - content_selector (string; optional): Selector to search for building the toc. - headings (list; optional): Headings tag name to search. The table of contents will be leveled according to the order of the headings prop. - table_of_contents (list; optional): The table of content in object form. - style (dict; optional): Style of the parent <ul> - setProps (boolean | number | string | dict | list; optional)""" @_explicitize_args
49.435897
222
0.695539
# AUTO GENERATED FILE - DO NOT EDIT from dash.development.base_component import Component, _explicitize_args class TableOfContents(Component): """A TableOfContents component. Build a table of contents list with links to the headers tag. Keyword arguments: - id (string; optional): Unique identifier for the component. - className (string; optional): className for the top ul component. - content_selector (string; optional): Selector to search for building the toc. - headings (list; optional): Headings tag name to search. The table of contents will be leveled according to the order of the headings prop. - table_of_contents (list; optional): The table of content in object form. - style (dict; optional): Style of the parent <ul> - setProps (boolean | number | string | dict | list; optional)""" @_explicitize_args def __init__(self, id=Component.UNDEFINED, className=Component.UNDEFINED, content_selector=Component.UNDEFINED, headings=Component.UNDEFINED, table_of_contents=Component.UNDEFINED, style=Component.UNDEFINED, **kwargs): self._prop_names = ['id', 'className', 'content_selector', 'headings', 'table_of_contents', 'style', 'setProps'] self._type = 'TableOfContents' self._namespace = 'dash_extra_components' self._valid_wildcard_attributes = [] self.available_properties = ['id', 'className', 'content_selector', 'headings', 'table_of_contents', 'style', 'setProps'] self.available_wildcard_properties = [] _explicit_args = kwargs.pop('_explicit_args') _locals = locals() _locals.update(kwargs) # For wildcard attrs args = {k: _locals[k] for k in _explicit_args if k != 'children'} for k in []: if k not in args: raise TypeError( 'Required argument `' + k + '` was not specified.') super(TableOfContents, self).__init__(**args)
1,072
0
26
feb7dbf6b94b36b4b780077450bb6fc7721e7421
1,191
py
Python
tests/integration/models/test_front.py
Lordshinjo/asyncpraw
d94d89a992d9b5b300439ea6884a9df1d95511e2
[ "BSD-2-Clause" ]
72
2020-07-14T02:02:21.000Z
2022-03-15T13:10:02.000Z
tests/integration/models/test_front.py
Lordshinjo/asyncpraw
d94d89a992d9b5b300439ea6884a9df1d95511e2
[ "BSD-2-Clause" ]
68
2020-07-16T05:29:43.000Z
2022-03-14T12:04:56.000Z
tests/integration/models/test_front.py
Lordshinjo/asyncpraw
d94d89a992d9b5b300439ea6884a9df1d95511e2
[ "BSD-2-Clause" ]
19
2020-07-22T15:34:30.000Z
2022-03-27T20:28:46.000Z
"""Test asyncpraw.models.front.""" from .. import IntegrationTest
34.028571
82
0.648195
"""Test asyncpraw.models.front.""" from .. import IntegrationTest class TestFront(IntegrationTest): async def test_best(self): with self.use_cassette(): submissions = await self.async_list(self.reddit.front.best()) assert len(submissions) == 100 async def test_controversial(self): with self.use_cassette(): submissions = await self.async_list(self.reddit.front.controversial()) assert len(submissions) == 100 async def test_gilded(self): with self.use_cassette(): submissions = await self.async_list(self.reddit.front.gilded()) assert len(submissions) == 100 async def test_hot(self): with self.use_cassette(): submissions = await self.async_list(self.reddit.front.hot()) assert len(submissions) == 100 async def test_new(self): with self.use_cassette(): submissions = await self.async_list(self.reddit.front.new()) assert len(submissions) == 100 async def test_top(self): with self.use_cassette(): submissions = await self.async_list(self.reddit.front.top()) assert len(submissions) == 100
928
12
184
eeae97e3e1918c205fa4325233b0d7d25463308e
3,303
py
Python
app/routes.py
kasztp/Scrabble
6d97044a539a76271f8540709efa332a92362c84
[ "MIT" ]
1
2020-11-18T20:05:43.000Z
2020-11-18T20:05:43.000Z
app/routes.py
kasztp/Scrabble
6d97044a539a76271f8540709efa332a92362c84
[ "MIT" ]
1
2021-12-11T15:43:27.000Z
2021-12-11T15:48:51.000Z
app/routes.py
kasztp/Scrabble
6d97044a539a76271f8540709efa332a92362c84
[ "MIT" ]
4
2020-04-01T16:53:12.000Z
2021-01-14T10:19:02.000Z
from flask import render_template, flash, redirect, request, url_for from app import app from .forms import ConfigForm from .scrabble_logic import Scrabble tile_draw = [] grouped = {} hasblank = 0 @app.route('/') @app.route('/index') @app.route('/table') @app.route('/config', methods=['GET', 'POST'])
39.795181
92
0.536482
from flask import render_template, flash, redirect, request, url_for from app import app from .forms import ConfigForm from .scrabble_logic import Scrabble tile_draw = [] grouped = {} hasblank = 0 @app.route('/') def root(): return render_template('index.html', title='Home', scores=grouped, tiles='tiles', blanks='blanks') @app.route('/index') def index(): return render_template('index.html', title='Home', scores=grouped, tiles=tile_draw, blanks=hasblank*(chr(160) + ' ')) @app.route('/table') def table(): mytable = Scrabble.build_table() return render_template('table.html', title='Table', column_names=mytable.columns.values, row_data=list(mytable.values.tolist()), link_column='A', zip=zip) @app.route('/config', methods=['GET', 'POST']) def config(): form = ConfigForm() if form.validate_on_submit(): flash(f'Configuration: Language {form.language.data},' f'Max Word Length {form.max_word_length.data},' f'Calculate for Maximum Length Only={form.max_word_length.data}') if request.method == 'POST': language = request.form['language'] max_word_length = int(request.form['max_word_length']) game = Scrabble(language) global tile_draw tile_draw = [] if form.own_tileset.data: global hasblank hasblank = form.own_tileset.data.count('BLANK') if hasblank >= 1: print('Removing BLANK tiles...') form.own_tileset.data = form.own_tileset.data.replace('BLANK', '') if language == 'HU': hasdigraph = 0 digraph_count = 0 digraphs = [] for digraph in ('cs', 'gy', 'sz', 'zs', 'ty', 'ly', 'ny'): if digraph in form.own_tileset.data: digraph_count += form.own_tileset.data.count(digraph) for _ in range(digraph_count): hasdigraph += 1 digraphs += digraph form.own_tileset.data.replace(digraph, '') for character in form.own_tileset.data: tile_draw += [character] tile_draw += digraphs else: for character in form.own_tileset.data: tile_draw += [character] game.hand.update_hand(tile_draw, hasblank) else: tile_draw = game.hand.held_tiles print('Tiles drawn: {}'.format(tile_draw)) flash('Tiles: {}'.format(tile_draw)) valid_words = game.word_check(tile_draw, max_word_length, form.only_max.data) global grouped grouped = {} if valid_words != 'NONE': scores = game.score_calc(valid_words) grouped = game.group_by_score(scores) else: grouped = {0: 'Number of valid words found'} return redirect(url_for('index')) return render_template('config.html', title='Configuration', form=form)
2,904
0
88
cc8939a085c9bc31314eff4ab8366df0f9f57fe8
3,091
py
Python
elkconfdparser/parser.py
iaroslavscript/elk-confd-parser
6930afa981468ddf24c80a33feba5e10ca870b9d
[ "MIT" ]
null
null
null
elkconfdparser/parser.py
iaroslavscript/elk-confd-parser
6930afa981468ddf24c80a33feba5e10ca870b9d
[ "MIT" ]
18
2021-07-29T18:24:28.000Z
2021-08-01T07:44:16.000Z
elkconfdparser/parser.py
iaroslavscript/elk-confd-parser
6930afa981468ddf24c80a33feba5e10ca870b9d
[ "MIT" ]
null
null
null
import enum from elkconfdparser import errors
25.758333
97
0.527337
import enum from elkconfdparser import errors class _BlockType(enum.Enum): NONE = enum.auto() COMMENT = enum.auto() STRING = enum.auto() VARIABLE = enum.auto() IGNORED = enum.auto() class _ParserAction(enum.IntFlag): NONE = 0 IGNORE_SYMBOL = enum.auto() DROP_VALUE = enum.auto() ESCAPE_NEXT = enum.auto() def parse(text, start=0, end=None): if end is None: end = len(text)-1 result = _parse(text, start, end)[0] return result def _parse(text, start, end): # noqa: C901 # FIXME block = _BlockType.NONE root = {} current = [] stack = [] action = _ParserAction.NONE delta = 0 i = start while i <= end: delta = 0 action &= ~_ParserAction.IGNORE_SYMBOL c = text[i] if c == "\n": action |= _ParserAction.DROP_VALUE elif block == _BlockType.COMMENT: action |= _ParserAction.IGNORE_SYMBOL elif block == _BlockType.STRING: if action & _ParserAction.ESCAPE_NEXT: action &= ~_ParserAction.ESCAPE_NEXT else: if c == '"': action |= _ParserAction.DROP_VALUE elif c == "\\": action |= _ParserAction.ESCAPE_NEXT | _ParserAction.IGNORE_SYMBOL elif c == '"': action |= _ParserAction.IGNORE_SYMBOL block = _BlockType.STRING elif c == "#": action |= _ParserAction.IGNORE_SYMBOL block = _BlockType.COMMENT elif c.isspace() or c in "=>,{}[]": action |= _ParserAction.DROP_VALUE elif c.isidentifier(): block = _BlockType.VARIABLE else: action |= _ParserAction.IGNORE_SYMBOL if not (action & _ParserAction.DROP_VALUE): if not (action & _ParserAction.IGNORE_SYMBOL): current.append(c) else: if current: stack.insert(0, ''.join(current)) current.clear() _drop_stack(root, stack) action &= ~_ParserAction.DROP_VALUE block = _BlockType.NONE if block != _BlockType.COMMENT and block != _BlockType.STRING: if c == '[': # Today I have no time to fix it block = _BlockType.IGNORED # so for now list types are silently ignored elif c == ']': # block = _BlockType.NONE # stack.insert(0, None) # _drop_stack(root, stack) elif c == '{': data, delta = _parse(text, i+1, end) stack.insert(0, data) _drop_stack(root, stack) elif c == '}': return root, i i = max(i, delta) + 1 return root, i def _drop_stack(root, stack): if len(stack) > 1: root.setdefault(stack.pop(), []).append(stack.pop()) if len(stack): raise errors.StackNotEmptyException('Unknown operands left on stack after assigment')
2,673
251
115
1f8b2985369841e17a42d01d25ee774e67366b41
754
py
Python
Rasp_Pi_2018/should_i_water/send_mail_task.py
BitKnitting/should_I_water
8d849671892b7bbc9e947e0ba041c4c3527b6bbd
[ "MIT" ]
2
2018-05-20T00:26:31.000Z
2018-06-13T16:22:48.000Z
Rasp_Pi_2018/should_i_water/send_mail_task.py
BitKnitting/should_I_water
8d849671892b7bbc9e947e0ba041c4c3527b6bbd
[ "MIT" ]
null
null
null
Rasp_Pi_2018/should_i_water/send_mail_task.py
BitKnitting/should_I_water
8d849671892b7bbc9e947e0ba041c4c3527b6bbd
[ "MIT" ]
null
null
null
#!/usr/bin/env python3 import os import sys LIB_PATH = os.environ['LADYBUG_LIB_PATH'] sys.path.append(LIB_PATH) from build_message_lib import BuildMessage from plot_weather_lib import PlotWeather from send_message_lib import SendMessage # TODO: Error checking needs improvement. # plot_weather() returns True (could create a PNG) or False (PNG of weather # could not be created). Yet, build message assumes multiplart MIME with the # Weather PNG in place. p = PlotWeather() b = BuildMessage() # send margaret a message. False means send detailed data. m = b.build_message('Margaret',False) s = SendMessage() s.send_message('happyday.mjohnson@gmail.com',m) m = b.build_message('Thor',True) # Send summary info s.send_message('thor_johnson@msn.com',m)
34.272727
77
0.777188
#!/usr/bin/env python3 import os import sys LIB_PATH = os.environ['LADYBUG_LIB_PATH'] sys.path.append(LIB_PATH) from build_message_lib import BuildMessage from plot_weather_lib import PlotWeather from send_message_lib import SendMessage # TODO: Error checking needs improvement. # plot_weather() returns True (could create a PNG) or False (PNG of weather # could not be created). Yet, build message assumes multiplart MIME with the # Weather PNG in place. p = PlotWeather() b = BuildMessage() # send margaret a message. False means send detailed data. m = b.build_message('Margaret',False) s = SendMessage() s.send_message('happyday.mjohnson@gmail.com',m) m = b.build_message('Thor',True) # Send summary info s.send_message('thor_johnson@msn.com',m)
0
0
0
a938390837c72c215ad582ed7f13afb2eb5ac461
9,644
py
Python
autocompletion.py
giladbarnea/autocompletion
2e67ba64951754c34348756d5790714f04725ed7
[ "MIT" ]
1
2020-10-23T05:22:04.000Z
2020-10-23T05:22:04.000Z
autocompletion.py
giladbarnea/autocompletion
2e67ba64951754c34348756d5790714f04725ed7
[ "MIT" ]
null
null
null
autocompletion.py
giladbarnea/autocompletion
2e67ba64951754c34348756d5790714f04725ed7
[ "MIT" ]
null
null
null
''':' autocomplete() { if [ $# != 2 ] then echo "USAGE: autocomplete <command> <config-path>" return 1 fi local COMMAND="$1" local CONFIG_PATH="$(readlink -f "$2")" eval " _complete_$COMMAND() { local THIS_FILE=\"\$(readlink -f \"\${BASH_SOURCE[0]}\")\" COMPREPLY=( \$(python \"\$THIS_FILE\" \"$CONFIG_PATH\" \"\$COMP_LINE\" \"\$COMP_POINT\" \"\$COMP_CWORD\") ); # Some special behaviour (like displaying path autocompletion only from the last slash on) # must be done in bash on-demand, so the first line is reserved for compopt. for FLAG in \$(echo \"\${COMPREPLY[0]}\" | tr ',' '\\n') do if [ \"\$FLAG\" = \".\" ] then continue fi compopt -o \"\$FLAG\" done COMPREPLY=( \"\${COMPREPLY[@]:1}\" ) } complete -F _complete_$COMMAND $COMMAND " } return ''' import collections import os import shlex import sys import traceback import types completers = {} completer_prefix = 'complete_' completers['value'] = complete_value completers['path'] = complete_path if __name__ == '__main__': sys.exit(main(sys.argv))
35.586716
120
0.579013
''':' autocomplete() { if [ $# != 2 ] then echo "USAGE: autocomplete <command> <config-path>" return 1 fi local COMMAND="$1" local CONFIG_PATH="$(readlink -f "$2")" eval " _complete_$COMMAND() { local THIS_FILE=\"\$(readlink -f \"\${BASH_SOURCE[0]}\")\" COMPREPLY=( \$(python \"\$THIS_FILE\" \"$CONFIG_PATH\" \"\$COMP_LINE\" \"\$COMP_POINT\" \"\$COMP_CWORD\") ); # Some special behaviour (like displaying path autocompletion only from the last slash on) # must be done in bash on-demand, so the first line is reserved for compopt. for FLAG in \$(echo \"\${COMPREPLY[0]}\" | tr ',' '\\n') do if [ \"\$FLAG\" = \".\" ] then continue fi compopt -o \"\$FLAG\" done COMPREPLY=( \"\${COMPREPLY[@]:1}\" ) } complete -F _complete_$COMMAND $COMMAND " } return ''' import collections import os import shlex import sys import traceback import types completers = {} completer_prefix = 'complete_' class Autocompleter(object): def __init__(self, config_path, line, cursor, index): self.line = line self.cursor = cursor self.index = index # Parse the current state. self.words = split(self.line) # Bash considers '=' a delimiter, but we consider it part of a word, so fix the index. # '=' in the end ('--flag=' => '--flag', '=') requires -1. # '=' in the middle ('--flag=value' => '--flag', '=', 'value') requires -2. for word in self.words: if word.endswith('='): self.index -= 1 elif '=' in word: self.index -= 2 # Find the current prefix (we can't just use self.words[index] because the cursor may be positioned # in the middle of that word, so slice the remainder of the line first). before = split(self.line[:self.cursor]) if self.index < len(before): self.prefix = before[self.index] else: self.prefix = '' # Import config as a module and collect its completers. self.module = import_module(config_path) for key, value in vars(self.module).items(): if key.startswith(completer_prefix): name = key[len(completer_prefix):] completers[name] = value # Parse config's comments for the autocompletion specifications. self.subcommands = collections.OrderedDict() with open(config_path) as reader: for line in reader: line = line.strip() if not line: continue if not line.startswith('#'): break line = line[1:].strip() if not line: continue subcommand = Subcommand(self, line) self.subcommands[subcommand.name] = subcommand # Some special behaviour (like displaying path autocompletion only from the last slash on) # must be done in bash on-demand, so the first line is reserved for compopt. self.compopt = ['.'] def autocomplete(self): # Index 0 is the command, so there's nothing to do. if self.index == 0: return [] # Index 1 is the subcommand, so autocomplete all the subcommands starting with the prefix. if self.index == 1: return [subcommand for subcommand in self.subcommands if subcommand.startswith(self.prefix)] # Otherwise, it's a flag or an argument of a subcommand, so delegate autocompletion to it. subcommand = self.words[1] if subcommand not in self.subcommands: return [] options = self.subcommands[subcommand].autocomplete() return [option for option in options if option and option.startswith(self.prefix)] class Subcommand(object): def __init__(self, autocompleter, config): self.autocompleter = autocompleter self.words = config.split() self.name = self.words[0] self.flags = {} self.arguments = [] for word in self.words[1:]: if word.startswith('-'): flag = Flag(self, word) self.flags[flag.name] = flag else: argument = Argument(self, word) self.arguments.append(argument) def autocomplete(self): # '-' means it's a flag. if self.autocompleter.prefix.startswith('-'): # If the flag contains '=', it means we've reached its value, so delegate autocompletion to it. if '=' in self.autocompleter.prefix: name = self.autocompleter.prefix.split('=', 1)[0] if name not in self.flags: return [] return self.flags[name].autocomplete() # Otherwise, autocomplete all the flags that match. return [flag.match() for flag in self.flags.values()] # Otherwise, it's an argument, so delegate autocompletion to it. self.argument_index = 0 for n, word in enumerate(self.autocompleter.words): if n == self.autocompleter.index: break if not word.startswith('-'): self.argument_index += 1 self.argument_index -= 2 # Don't count the command and subcommand. if self.argument_index >= len(self.arguments): return [] return self.arguments[self.argument_index].autocomplete() class Flag(object): def __init__(self, subcommand, config): self.subcommand = subcommand if '=' in config: self.name, self.value = config.split('=', 1) else: self.name, self.value = config, None def autocomplete(self): completer = completers.get(self.value.strip('<>')) if not completer: return [] # Flag values are autocompleted separately, so discard the '--flag=' prefix. self.subcommand.autocompleter.prefix = self.subcommand.autocompleter.prefix[len(self.name)+1:] return completer(self, self.subcommand.autocompleter.prefix) def match(self): # If the flag doesn't start with the prefix there's no game. if not self.name.startswith(self.subcommand.autocompleter.prefix): return None # Otherwise, check that the flag hasn't appeared already. for word in self.subcommand.autocompleter.words: if not word.startswith('-'): continue # Flags followed by values are stripped so that only their name is considered. if '=' in word: word = word.split('=', 1)[0] if self.name == word: return None if self.value: self.subcommand.autocompleter.compopt.append('nospace') # Don't put a space after '='. return self.name + '=' return self.name class Argument(object): def __init__(self, subcommand, config): self.subcommand = subcommand self.name = config def autocomplete(self): completer = completers.get(self.name.strip('<>')) if not completer: return [] return completer(self, self.subcommand.autocompleter.prefix) def complete_value(arg, prefix): return [] completers['value'] = complete_value def complete_path(arg, prefix): arg.subcommand.autocompleter.compopt.append('filenames') # Display paths from the last slash on. directory, prefix = os.path.split(prefix) return [os.path.join(directory, entry) for entry in os.listdir(directory or '.') if entry.startswith(prefix)] completers['path'] = complete_path def echo(message, *args): # Anything printed to stdout is interpreted as autocompletion options, so print messages to stderr. sys.stderr.write(os.linesep + message % args + os.linesep) sys.stderr.flush() def import_module(path): # There's no cross version method to import a module from path, so do it manually. path = os.path.abspath(path) file = os.path.basename(path) name = os.path.splitext(file)[0] with open(path) as reader: data = reader.read() code = compile(data, file, 'exec') module = types.ModuleType(name) module.__file__ = path module.__name__ = name exec(code, vars(module)) return module def split(line): # shlex doesn't like unclosed quotes, so if that's the case we close them ourselves. try: return shlex.split(line) except ValueError: pass # Try closing with ". try: return shlex.split(line + '"') except ValueError: pass # Try closing with '. try: return shlex.split(line + "'") except ValueError: pass raise ValueError('invalid line: %r' % text) def main(argv): if len(argv) != 5: echo('USAGE: %s <config-path> <line> <cursor> <index>' % argv[0]) return +1 try: autocompleter = Autocompleter( config_path = argv[1], line = argv[2], cursor = int(argv[3]), index = int(argv[4]), ) options = autocompleter.autocomplete() print(','.join(autocompleter.compopt)) print(os.linesep.join(options)) except Exception as error: echo('ERROR: %s' % error) traceback.print_exc() return -1 if __name__ == '__main__': sys.exit(main(sys.argv))
7,858
11
485
860cbfb88ef007ae90c1c2fb1f851645620e3633
63
py
Python
habitica/__init__.py
clckwrkbdgr/habitica
2fbbdf1da8de5803b8132f2d51817ffc671364b2
[ "MIT" ]
1
2020-05-10T09:20:08.000Z
2020-05-10T09:20:08.000Z
habitica/__init__.py
clckwrkbdgr/habitica
2fbbdf1da8de5803b8132f2d51817ffc671364b2
[ "MIT" ]
null
null
null
habitica/__init__.py
clckwrkbdgr/habitica
2fbbdf1da8de5803b8132f2d51817ffc671364b2
[ "MIT" ]
null
null
null
from . import api, cli, extra, core from .core import Habitica
21
35
0.746032
from . import api, cli, extra, core from .core import Habitica
0
0
0
6b9b3ccccc7e73c7edc904ee8464ac9829c22050
220
py
Python
haravan/resources/blog.py
vivekpatel111/HaravanAPI
bec18d43b485c966e1396ce990c7b0fd40c96de0
[ "MIT" ]
null
null
null
haravan/resources/blog.py
vivekpatel111/HaravanAPI
bec18d43b485c966e1396ce990c7b0fd40c96de0
[ "MIT" ]
null
null
null
haravan/resources/blog.py
vivekpatel111/HaravanAPI
bec18d43b485c966e1396ce990c7b0fd40c96de0
[ "MIT" ]
1
2019-03-08T06:28:48.000Z
2019-03-08T06:28:48.000Z
from ..base import HaravanResource from haravan import mixins import haravan
22
62
0.768182
from ..base import HaravanResource from haravan import mixins import haravan class Blog(HaravanResource, mixins.Metafields, mixins.Events): def articles(self): return haravan.Article.find(blog_id=self.id)
51
41
50
bb0cca9978a14262fdad4a5cb740fe6cfea8d3e5
576
py
Python
abc229/abc229_d.py
Vermee81/practice-coding-contests
78aada60fa75f208ee0eef337b33b27b1c260d18
[ "MIT" ]
null
null
null
abc229/abc229_d.py
Vermee81/practice-coding-contests
78aada60fa75f208ee0eef337b33b27b1c260d18
[ "MIT" ]
null
null
null
abc229/abc229_d.py
Vermee81/practice-coding-contests
78aada60fa75f208ee0eef337b33b27b1c260d18
[ "MIT" ]
null
null
null
# https://atcoder.jp/contests/abc229/tasks/abc229_d S = input() K = int(input()) ans = 0 tail_idx = 0 cum_dot = [0] * (len(S) + 1) for i in range(len(S)): if S[i] == '.': cum_dot[i + 1] = cum_dot[i] + 1 else: cum_dot[i + 1] = cum_dot[i] for head_idx in range(len(S)): while tail_idx <= len(S) - 1 and can_swap_to_x(head_idx, tail_idx + 1): tail_idx += 1 ans = max(ans, tail_idx - head_idx) print(ans)
20.571429
75
0.581597
# https://atcoder.jp/contests/abc229/tasks/abc229_d S = input() K = int(input()) ans = 0 tail_idx = 0 cum_dot = [0] * (len(S) + 1) for i in range(len(S)): if S[i] == '.': cum_dot[i + 1] = cum_dot[i] + 1 else: cum_dot[i + 1] = cum_dot[i] def can_swap_to_x(start: int, end: int) -> bool: if cum_dot[end] - cum_dot[start] > K: return False return True for head_idx in range(len(S)): while tail_idx <= len(S) - 1 and can_swap_to_x(head_idx, tail_idx + 1): tail_idx += 1 ans = max(ans, tail_idx - head_idx) print(ans)
106
0
23
0fadf45c92b0a0910501554f2fdcc4259660a3ab
3,513
py
Python
c7n/resources/shield.py
fadiguezel/cloud-custodian
147fffcf9a109ffd4248a746775b55def5a727c5
[ "Apache-2.0" ]
null
null
null
c7n/resources/shield.py
fadiguezel/cloud-custodian
147fffcf9a109ffd4248a746775b55def5a727c5
[ "Apache-2.0" ]
1
2021-02-24T04:42:37.000Z
2021-02-24T04:42:37.000Z
c7n/resources/shield.py
fadiguezel/cloud-custodian
147fffcf9a109ffd4248a746775b55def5a727c5
[ "Apache-2.0" ]
1
2021-01-26T10:03:21.000Z
2021-01-26T10:03:21.000Z
# Copyright 2015-2017 Capital One Services, LLC # # Licensed under the Apache License, Version 2.0 (the "License"); # you may not use this file except in compliance with the License. # You may obtain a copy of the License at # # http://www.apache.org/licenses/LICENSE-2.0 # # Unless required by applicable law or agreed to in writing, software # distributed under the License is distributed on an "AS IS" BASIS, # WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. # See the License for the specific language governing permissions and # limitations under the License. from __future__ import absolute_import, division, print_function, unicode_literals from botocore.exceptions import ClientError from c7n.actions import BaseAction from c7n.filters import Filter from c7n.manager import resources from c7n.query import QueryResourceManager from c7n.utils import local_session, type_schema @resources.register('shield-protection') @resources.register('shield-attack') class SetShieldProtection(BaseAction): """Enable shield protection on applicable resource. """ permissions = ('shield:CreateProtection', 'shield:ListProtections',) schema = type_schema( 'set-shield', state={'type': 'boolean'})
34.441176
83
0.652149
# Copyright 2015-2017 Capital One Services, LLC # # Licensed under the Apache License, Version 2.0 (the "License"); # you may not use this file except in compliance with the License. # You may obtain a copy of the License at # # http://www.apache.org/licenses/LICENSE-2.0 # # Unless required by applicable law or agreed to in writing, software # distributed under the License is distributed on an "AS IS" BASIS, # WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. # See the License for the specific language governing permissions and # limitations under the License. from __future__ import absolute_import, division, print_function, unicode_literals from botocore.exceptions import ClientError from c7n.actions import BaseAction from c7n.filters import Filter from c7n.manager import resources from c7n.query import QueryResourceManager from c7n.utils import local_session, type_schema @resources.register('shield-protection') class ShieldProtection(QueryResourceManager): class resource_type(object): service = 'shield' enum_spec = ('list_protections', 'Protections', None) id = 'Id' name = 'Name' dimension = None filter_name = None @resources.register('shield-attack') class ShieldAttack(QueryResourceManager): class resource_type(object): service = 'shield' enum_spec = ('list_attacks', 'Attacks', None) detail_spec = ('describe_attack', 'AttackId', 'AttackId', 'Attack') id = 'AttackId' date = 'StartTime' dimension = None filter_name = 'ResourceArns' filter_type = 'list' class IsShieldProtected(Filter): permissions = ('shield:ListProtections',) schema = type_schema('shield-enabled', state={'type': 'boolean'}) def process(self, resources, event=None): client = local_session(self.manager.session_factory).client( 'shield', region_name='us-east-1') protections = client.list_protections().get('Protections', ()) protected_resources = {p['ResourceArn'] for p in protections} state = self.data.get('state', False) results = [] for r in resources: arn = self.manager.get_arn(r) r['c7n:ShieldProtected'] = shielded = arn in protected_resources if shielded and state: results.append(r) elif not shielded and not state: results.append(r) return results class SetShieldProtection(BaseAction): """Enable shield protection on applicable resource. """ permissions = ('shield:CreateProtection', 'shield:ListProtections',) schema = type_schema( 'set-shield', state={'type': 'boolean'}) def process(self, resources): client = local_session(self.manager.session_factory).client( 'shield', region_name='us-east-1') model = self.manager.get_model() protections = client.list_protections().get('Protections', ()) protected_resources = {p['ResourceArn'] for p in protections} for r in resources: arn = self.manager.get_arn(r) if arn in protected_resources: continue try: client.create_protection( Name=r[model.name], ResourceArn=arn) except ClientError as e: if e.response['Error']['Code'] == 'ResourceAlreadyExistsException': continue raise
1,417
747
94
ebc7816cbcf82d03551d822b1195efe4648cf28f
1,309
py
Python
07-Forms/newDjangoProject/newDjangoProject/todo_app/views.py
M0673N/Python-Web-Basics
cecc27f7a12f990756edcc8885290eb3b2e487b7
[ "MIT" ]
null
null
null
07-Forms/newDjangoProject/newDjangoProject/todo_app/views.py
M0673N/Python-Web-Basics
cecc27f7a12f990756edcc8885290eb3b2e487b7
[ "MIT" ]
null
null
null
07-Forms/newDjangoProject/newDjangoProject/todo_app/views.py
M0673N/Python-Web-Basics
cecc27f7a12f990756edcc8885290eb3b2e487b7
[ "MIT" ]
null
null
null
from django.shortcuts import render, redirect from newDjangoProject.todo_app.forms import TodoForm from newDjangoProject.todo_app.models import Todo
26.714286
65
0.637128
from django.shortcuts import render, redirect from newDjangoProject.todo_app.forms import TodoForm from newDjangoProject.todo_app.models import Todo def index(request): todos = Todo.objects.all() context = {'todos': todos} return render(request, 'index.html', context=context) def create(request): if request.method == 'GET': form = TodoForm() context = {'form': form} return render(request, 'create.html', context=context) form = TodoForm(request.POST) if form.is_valid(): todo = Todo(**form.cleaned_data) todo.save() return redirect('index') return render(request, 'create.html', context={'form': form}) def edit(request, pk): if request.method == 'GET': form = TodoForm() context = {'pk': pk, 'form': form} return render(request, 'edit.html', context=context) form = TodoForm(request.POST) if form.is_valid(): todo = Todo.objects.get(pk=pk) todo.title = form.cleaned_data['title'] todo.description = form.cleaned_data['description'] todo.save() return redirect('index') return render(request, 'edit.html', context={'form': form}) def delete(request, pk): todo = Todo.objects.get(pk=pk) todo.delete() return redirect('index')
1,063
0
92
9e2765f3e4657262b967d2c8984a56f0d3a891f1
883
py
Python
exercicios/aula18-ex084.py
anildoferreira/CursoPython-PyCharm
56c3962d6cc7d43482a9649a482619adba780d81
[ "MIT" ]
null
null
null
exercicios/aula18-ex084.py
anildoferreira/CursoPython-PyCharm
56c3962d6cc7d43482a9649a482619adba780d81
[ "MIT" ]
null
null
null
exercicios/aula18-ex084.py
anildoferreira/CursoPython-PyCharm
56c3962d6cc7d43482a9649a482619adba780d81
[ "MIT" ]
null
null
null
temp = [] princ = [] c = maior = menor = 0 continuar = ' ' while continuar not in 'Nn': c += 1 print(f'{c}º PESSOA') print('-' * 10) temp.append(str(input(f'Digite o seu nome: '))) temp.append(float(input(f'Digite o seu peso: '))) if c == 1: maior = menor = temp[1] else: if temp[1] > maior: maior = temp[1] if temp[1] < menor: menor = temp[1] princ.append(temp[:]) temp.clear() while True: continuar = str(input('Quer continuar? [S/N]:')) if continuar in 'NnSs': break print('Tente novamente!', end=' ') print(f'Foram cadastradas {c} pessoas.') print(f'O maior peso foi de {maior}',end=' ') for p in princ: if p[1] == maior: print(p[0]) print(f'O menor peso foi de {menor}',end=' ') for p in princ: if p[1] == menor: print(p[0])
22.641026
56
0.520951
temp = [] princ = [] c = maior = menor = 0 continuar = ' ' while continuar not in 'Nn': c += 1 print(f'{c}º PESSOA') print('-' * 10) temp.append(str(input(f'Digite o seu nome: '))) temp.append(float(input(f'Digite o seu peso: '))) if c == 1: maior = menor = temp[1] else: if temp[1] > maior: maior = temp[1] if temp[1] < menor: menor = temp[1] princ.append(temp[:]) temp.clear() while True: continuar = str(input('Quer continuar? [S/N]:')) if continuar in 'NnSs': break print('Tente novamente!', end=' ') print(f'Foram cadastradas {c} pessoas.') print(f'O maior peso foi de {maior}',end=' ') for p in princ: if p[1] == maior: print(p[0]) print(f'O menor peso foi de {menor}',end=' ') for p in princ: if p[1] == menor: print(p[0])
0
0
0
e05b3d75e3b753188335b9edf04c6ef40364090b
20,463
py
Python
core/botCore.py
iwannadapdap/Simple-Binance-Trader
905e205803c0e8f5b5af27e5a32c563944362424
[ "MIT" ]
null
null
null
core/botCore.py
iwannadapdap/Simple-Binance-Trader
905e205803c0e8f5b5af27e5a32c563944362424
[ "MIT" ]
null
null
null
core/botCore.py
iwannadapdap/Simple-Binance-Trader
905e205803c0e8f5b5af27e5a32c563944362424
[ "MIT" ]
null
null
null
#! /usr/bin/env python3 import os import sys import time import json import os.path import hashlib import logging import threading from decimal import Decimal from flask_socketio import SocketIO from flask import Flask, render_template, url_for, request from binance_api import api_master_rest_caller from binance_api import api_master_socket_caller from . import trader MULTI_DEPTH_INDICATORS = ['ema', 'sma', 'rma', 'order'] # Initilize globals. ## Setup flask app/socket APP = Flask(__name__) SOCKET_IO = SocketIO(APP) ## Initilize base core object. core_object = None started_updater = False ## Initilize IP/port pair globals. host_ip = '' host_port = '' ## Set traders cache file name. CAHCE_FILES = 'traders.json' @APP.context_processor @APP.route('/', methods=['GET']) @APP.route('/rest-api/v1/trader_update', methods=['POST']) @APP.route('/rest-api/v1/get_trader_charting', methods=['GET']) @APP.route('/rest-api/v1/get_trader_indicators', methods=['GET']) @APP.route('/rest-api/v1/get_trader_candles', methods=['GET']) @APP.route('/rest-api/v1/test', methods=['GET'])
39.126195
203
0.620779
#! /usr/bin/env python3 import os import sys import time import json import os.path import hashlib import logging import threading from decimal import Decimal from flask_socketio import SocketIO from flask import Flask, render_template, url_for, request from binance_api import api_master_rest_caller from binance_api import api_master_socket_caller from . import trader MULTI_DEPTH_INDICATORS = ['ema', 'sma', 'rma', 'order'] # Initilize globals. ## Setup flask app/socket APP = Flask(__name__) SOCKET_IO = SocketIO(APP) ## Initilize base core object. core_object = None started_updater = False ## Initilize IP/port pair globals. host_ip = '' host_port = '' ## Set traders cache file name. CAHCE_FILES = 'traders.json' @APP.context_processor def override_url_for(): return(dict(url_for=dated_url_for)) def dated_url_for(endpoint, **values): # Override to prevent cached assets being used. if endpoint == 'static': filename = values.get('filename', None) if filename: file_path = os.path.join(APP.root_path, endpoint, filename) values['q'] = int(os.stat(file_path).st_mtime) return url_for(endpoint, **values) @APP.route('/', methods=['GET']) def control_panel(): # Base control panel configuration. global started_updater ## Web updater used for live updating. if not(started_updater): started_updater = True web_updater_thread = threading.Thread(target=web_updater) web_updater_thread.start() ## Set socket ip/port. start_up_data = { 'host':{'IP': host_ip, 'Port': host_port}, 'market_symbols': core_object.trading_markets } return(render_template('main_page.html', data=start_up_data)) @APP.route('/rest-api/v1/trader_update', methods=['POST']) def update_trader(): # Base API for managing trader interaction. data = request.get_json() ## Check if specified bot exists. current_trader = api_error_check(data) if current_trader == None: ## No trader therefore return false. return(json.dumps({'call':False, 'message':'INVALID_TRADER'})) elif data['action'] == 'start': ## Updating trader status to running. if current_trader.state_data['runtime_state'] == 'FORCE_PAUSE': current_trader.state_data['runtime_state'] = 'RUN' elif data['action'] == 'pause': ## Updating trader status to paused. if current_trader.state_data['runtime_state'] == 'RUN': current_trader.state_data['runtime_state'] = 'FORCE_PAUSE' else: ## If action was not found return false return(json.dumps({'call':False, 'message':'INVALID_ACTION'})) return(json.dumps({'call':True})) @APP.route('/rest-api/v1/get_trader_charting', methods=['GET']) def get_trader_charting(): # Endpoint to pass trader indicator data. market = request.args.get('market') limit = int(request.args.get('limit')) data = {'market':market} ## Check if specified bot exists. current_trader = api_error_check(data) if current_trader == None: ## No trader therefore return false. return(json.dumps({'call':False, 'message':'INVALID_TRADER'})) candle_data = core_object.get_trader_candles(current_trader.print_pair)[:limit] indicator_data = core_object.get_trader_indicators(current_trader.print_pair) short_indicator_data = shorten_indicators(indicator_data, candle_data[-1][0]) return(json.dumps({'call':True, 'data':{'market':market, 'indicators':short_indicator_data, 'candles':candle_data}})) @APP.route('/rest-api/v1/get_trader_indicators', methods=['GET']) def get_trader_indicators(): # Endpoint to pass trader indicator data. market = request.args.get('market') limit = int(request.args.get('limit')) data = {'market':market} ## Check if specified bot exists. current_trader = api_error_check(data) if current_trader == None: ## No trader therefore return false. return(json.dumps({'call':False, 'message':'INVALID_TRADER'})) indicator_data = core_object.get_trader_indicators(current_trader.print_pair) return(json.dumps({'call':True, 'data':{'market':market, 'indicators':indicator_data}})) @APP.route('/rest-api/v1/get_trader_candles', methods=['GET']) def get_trader_candles(): # Endpoint to pass trader candles. market = request.args.get('market') limit = int(request.args.get('limit')) data = {'market':market} ## Check if specified bot exists. current_trader = api_error_check(data) if current_trader == None: ## No trader therefore return false. return(json.dumps({'call':False, 'message':'INVALID_TRADER'})) candle_data = core_object.get_trader_candles(current_trader.print_pair)[:limit] return(json.dumps({'call':True, 'data':{'market':market, 'candles':candle_data}})) @APP.route('/rest-api/v1/test', methods=['GET']) def test_rest_call(): # API endpoint test return(json.dumps({'call':True, 'message':'HELLO WORLD!'})) def shorten_indicators(indicators, end_time): base_indicators = {} for ind in indicators: if ind in MULTI_DEPTH_INDICATORS: base_indicators.update({ind:{}}) for sub_ind in indicators[ind]: base_indicators[ind].update({sub_ind:[ [val[0] if ind != 'order' else val[0]*1000,val[1]] for val in indicators[ind][sub_ind] if (val[0] if ind != 'order' else val[0]*1000) > end_time ]}) else: base_indicators.update({ind:[ [val[0],val[1]] for val in indicators[ind] if val[0] > end_time]}) return(base_indicators) def api_error_check(data): ## Check if specified bot exists. current_trader = None for trader in core_object.trader_objects: if trader.print_pair == data['market']: current_trader = trader break return(current_trader) def web_updater(): # Web updater use to update live via socket. lastHash = None while True: if core_object.coreState == 'RUN': ## Get trader data and hash it to find out if there have been any changes. traderData = core_object.get_trader_data() currHash = hashlib.md5(str(traderData).encode()) if lastHash != currHash: ## Update any new changes via socket. lastHash = currHash total_bulk_data = [] for trader in traderData: bulk_data = {} bulk_data.update({'market':trader['market']}) bulk_data.update({'trade_recorder':trader['trade_recorder']}) bulk_data.update({'wallet_pair':trader['wallet_pair']}) bulk_data.update(trader['custom_conditions']) bulk_data.update(trader['market_activity']) bulk_data.update(trader['market_prices']) bulk_data.update(trader['state_data']) total_bulk_data.append(bulk_data) SOCKET_IO.emit('current_traders_data', {'data':total_bulk_data}) time.sleep(.8) class BotCore(): def __init__(self, settings, logs_dir, cache_dir): # Initilization for the bot core managment object. logging.info('[BotCore] Initilizing the BotCore object.') ## Setup binance REST and socket API. self.rest_api = api_master_rest_caller.Binance_REST(settings['public_key'], settings['private_key']) self.socket_api = api_master_socket_caller.Binance_SOCK() ## Setup the logs/cache dir locations. self.logs_dir = logs_dir self.cache_dir = cache_dir ## Setup run type, market type, and update bnb balance. self.run_type = settings['run_type'] self.market_type = settings['market_type'] self.update_bnb_balance = settings['update_bnb_balance'] ## Setup max candle/depth setting. self.max_candles = settings['max_candles'] self.max_depth = settings['max_depth'] ## Get base quote pair (This prevents multiple different pairs from conflicting.) pair_one = settings['trading_markets'][0] self.quote_asset = pair_one[:pair_one.index('-')] self.base_currency = settings['trading_currency'] self.candle_Interval = settings['trader_interval'] ## Initilize base trader settings. self.trader_objects = [] self.trading_markets = settings['trading_markets'] ## Initilize core state self.coreState = 'READY' def start(self): # Start the core object. logging.info('[BotCore] Starting the BotCore object.') self.coreState = 'SETUP' ## check markets found_markets = [] not_supported = [] #breakpoint() for market in self.rest_api.get_exchangeInfo()['symbols']: fmtMarket = '{0}-{1}'.format(market['quoteAsset'], market['baseAsset']) # If the current market is not in the trading markets list then skip. if not fmtMarket in self.trading_markets: continue found_markets.append(fmtMarket) if (self.market_type == 'MARGIN' and market['isMarginTradingAllowed'] == False) or (self.market_type == 'SPOT' and market['isSpotTradingAllowed'] == False): not_supported.append(fmtMarket) continue # This is used to setup min quantity. if float(market['filters'][2]['minQty']) < 1.0: minQuantBase = (Decimal(market['filters'][2]['minQty'])).as_tuple() lS = abs(int(len(minQuantBase.digits)+minQuantBase.exponent))+1 else: lS = 0 # This is used to set up the price precision for the market. tickSizeBase = (Decimal(market['filters'][0]['tickSize'])).as_tuple() tS = abs(int(len(tickSizeBase.digits)+tickSizeBase.exponent))+1 # This is used to get the markets minimal notation. mN = float(market['filters'][3]['minNotional']) # Put all rules into a json object to pass to the trader. market_rules = {'LOT_SIZE':lS, 'TICK_SIZE':tS, 'MINIMUM_NOTATION':mN} # Initilize trader objecta dn also set-up its inital required data. traderObject = trader.BaseTrader(market['quoteAsset'], market['baseAsset'], self.rest_api, socket_api=self.socket_api) traderObject.setup_initial_values(self.market_type, self.run_type, market_rules) self.trader_objects.append(traderObject) ## Show markets that dont exist on the binance exchange. if len(self.trading_markets) != len(found_markets): no_market_text = '' for market in [market for market in self.trading_markets if market not in found_markets]: no_market_text+=str(market)+', ' logging.warning('Following pairs dont exist: {}'.format(no_market_text[:-2])) ## Show markets that dont support the market type. if len(not_supported) > 0: not_support_text = '' for market in not_supported: not_support_text += ' '+str(market) logging.warning('[BotCore] Following market pairs are not supported for {}: {}'.format(self.market_type, not_support_text)) valid_tading_markets = [market for market in found_markets if market not in not_supported] ## setup the binance socket. for market in valid_tading_markets: self.socket_api.set_candle_stream(symbol=market, interval=self.candle_Interval) self.socket_api.set_manual_depth_stream(symbol=market, update_speed='1000ms') #breakpoint() if self.run_type == 'REAL': self.socket_api.set_userDataStream(self.rest_api, self.market_type) self.socket_api.BASE_CANDLE_LIMIT = self.max_candles self.socket_api.BASE_DEPTH_LIMIT = self.max_depth self.socket_api.build_query() self.socket_api.set_live_and_historic_combo(self.rest_api) self.socket_api.start() # Load the wallets. if self.run_type == 'REAL': user_info = self.rest_api.get_account(self.market_type) #iwan: todo: check if this request is successfull. #one case is request is ahead of time, and binance return error 'code':-1021 'msg':"Timestamp for this request was 1000ms ahead of the server's time. if self.market_type == 'SPOT': wallet_balances = user_info['balances'] elif self.market_type == 'MARGIN': wallet_balances = user_info['userAssets'] current_tokens = {} for balance in wallet_balances: total_balance = (float(balance['free']) + float(balance['locked'])) if total_balance > 0: current_tokens.update({balance['asset']:[ float(balance['free']), float(balance['locked'])]}) else: current_tokens = {self.quote_asset:[float(self.base_currency), 0.0]} # Load cached data cached_traders_data = None if os.path.exists(self.cache_dir+CAHCE_FILES): with open(self.cache_dir+CAHCE_FILES, 'r') as f: cached_traders_data = json.load(f)['data'] ## Setup the trader objects and start them. logging.info('[BotCore] Starting the trader objects.') #breakpoint() for trader_ in self.trader_objects: currSymbol = "{0}{1}".format(trader_.base_asset, trader_.quote_asset) # Update trader with cached data (to resume trades/keep records of trades.) if cached_traders_data != '' and cached_traders_data: for cached_trader in cached_traders_data: m_split = cached_trader['market'].split('-') if (m_split[1]+m_split[0]) == currSymbol: trader_.configuration = cached_trader['configuration'] trader_.custom_conditional_data = cached_trader['custom_conditions'] trader_.market_activity = cached_trader['market_activity'] trader_.trade_recorder = cached_trader['trade_recorder'] trader_.state_data = cached_trader['state_data'] wallet_pair = {} if trader_.quote_asset in current_tokens: wallet_pair.update({trader_.quote_asset:current_tokens[trader_.quote_asset]}) if trader_.base_asset in current_tokens: wallet_pair.update({trader_.base_asset:current_tokens[trader_.base_asset]}) trader_.start(self.base_currency, wallet_pair) logging.debug('[BotCore] Starting trader manager') TM_thread = threading.Thread(target=self._trader_manager) TM_thread.start() if self.update_bnb_balance: logging.debug('[BotCore] Starting BNB manager') BNB_thread = threading.Thread(target=self._bnb_manager) BNB_thread.start() logging.debug('[BotCore] Starting connection manager thread.') CM_thread = threading.Thread(target=self._connection_manager) CM_thread.start() logging.debug('[BotCore] Starting file manager thread.') FM_thread = threading.Thread(target=self._file_manager) FM_thread.start() logging.info('[BotCore] BotCore successfully started.') self.coreState = 'RUN' def _trader_manager(self): ''' ''' while self.coreState != 'STOP': pass def _bnb_manager(self): ''' This will manage BNB balance and update if there is low BNB in account. ''' last_wallet_update_time = 0 while self.coreState != 'STOP': socket_buffer_global = self.socket_api.socketBuffer # If outbound postion is seen then wallet has updated. if 'outboundAccountPosition' in socket_buffer_global: if last_wallet_update_time != socket_buffer_global['outboundAccountPosition']['E']: last_wallet_update_time = socket_buffer_global['outboundAccountPosition']['E'] for wallet in socket_buffer_global['outboundAccountPosition']['B']: if wallet['a'] == 'BNB': if float(wallet['f']) < 0.01: bnb_order = self.rest_api.place_order(self.market_type, symbol='BNBBTC', side='BUY', type='MARKET', quantity=0.1) time.sleep(2) def _file_manager(self): ''' This section is responsible for activly updating the traders cache files. ''' while self.coreState != 'STOP': time.sleep(15) traders_data = self.get_trader_data() if os.path.exists(self.cache_dir): file_path = '{0}{1}'.format(self.cache_dir,CAHCE_FILES) with open(file_path, 'w') as f: json.dump({'lastUpdateTime':time.time() ,'data':traders_data}, f) def _connection_manager(self): ''' This section is responsible for re-testing connectiongs in the event of a disconnect. ''' update_time = 0 retryCounter = 1 time.sleep(20) while self.coreState != 'STOP': time.sleep(1) if self.coreState != 'RUN': continue if self.socket_api.last_data_recv_time != update_time: update_time = self.socket_api.last_data_recv_time else: if (update_time + (15*retryCounter)) < time.time(): retryCounter += 1 try: print(self.rest_api.test_ping()) except Exception as e: logging.warning('[BotCore] Connection issue: {0}.'.format(e)) continue logging.info('[BotCore] Connection issue resolved.') if not(self.socket_api.socketRunning): logging.info('[BotCore] Attempting socket restart.') self.socket_api.start() def get_trader_data(self): ''' This can be called to return data for each of the active traders. ''' rData = [ _trader.get_trader_data() for _trader in self.trader_objects ] return(rData) def get_trader_indicators(self, market): ''' This can be called to return the indicators that are used by the traders (Will be used to display web UI activity.) ''' for _trader in self.trader_objects: if _trader.print_pair == market: indicator_data = _trader.indicators indicator_data.update({'order':{'buy':[], 'sell':[]}}) indicator_data['order']['buy'] = [ [order[0],order[1]] for order in _trader.trade_recorder if order[4] == 'BUY'] indicator_data['order']['sell'] = [ [order[0],order[1]] for order in _trader.trade_recorder if order[4] == 'SELL'] return(indicator_data) def get_trader_candles(self, market): ''' This can be called to return the candle data for the traders (Will be used to display web UI activity.) ''' for _trader in self.trader_objects: if _trader.print_pair == market: sock_symbol = str(_trader.base_asset)+str(_trader.quote_asset) return(self.socket_api.get_live_candles(sock_symbol)) def start(settings, logs_dir, cache_dir): global core_object, host_ip, host_port if core_object == None: core_object = BotCore(settings, logs_dir, cache_dir) core_object.start() logging.info('[BotCore] Starting traders in {0} mode, market type is {1}.'.format(settings['run_type'], settings['market_type'])) log = logging.getLogger('werkzeug') log.setLevel(logging.ERROR) host_ip = settings['host_ip'] host_port = settings['host_port'] SOCKET_IO.run(APP, host=settings['host_ip'], port=settings['host_port'], debug=True, use_reloader=False)
15,008
4,041
292
12c2373f5be85698acee1ae90c41ce2fe8b0ed68
1,641
py
Python
frontend/test/test_SignUpRequest.py
CMPUT404-wi21-project/CMPUT404-project-socialdistribution
b88ca3608e16a1bae72cd7c8cfc212db74d1b2c0
[ "W3C-20150513" ]
1
2021-04-08T22:02:44.000Z
2021-04-08T22:02:44.000Z
frontend/test/test_SignUpRequest.py
CMPUT404-wi21-project/CMPUT404-project-socialdistribution
b88ca3608e16a1bae72cd7c8cfc212db74d1b2c0
[ "W3C-20150513" ]
79
2021-02-06T22:55:52.000Z
2021-04-15T20:24:56.000Z
frontend/test/test_SignUpRequest.py
CMPUT404-wi21-project/CMPUT404-project-socialdistribution
b88ca3608e16a1bae72cd7c8cfc212db74d1b2c0
[ "W3C-20150513" ]
4
2021-02-14T15:13:15.000Z
2021-04-17T06:21:11.000Z
from selenium import webdriver from test_utils import * from time import sleep import random if __name__ == "__main__": try: test_SignUpRequest() print("test_SignUpRequest passed") except: print("test_SignUpRequest Failed")
37.295455
96
0.730652
from selenium import webdriver from test_utils import * from time import sleep import random def test_SignUpRequest(): driver = getFrontEndWebDriver() sleep(1) driver.find_element_by_xpath(".//div[@role='tab' and contains(@id,'Register')]").click() username_input = driver.find_element_by_xpath(frontend_username_xpath) password_input = driver.find_element_by_xpath(frontend_password_xpath) display_name_input = driver.find_element_by_xpath(".//input[@placeholder='Display Name']") register_button = driver.find_element_by_xpath(frontend_loginButton_xpath) # Frontend_test_user1 is an existing user username_input.send_keys("Frontend_test_user1") password_input.send_keys("123") display_name_input.send_keys("Frontend_test_user1") register_button.click() register_button.click() sleep(1) alert = driver.find_element_by_xpath(".//div[@class='ant-alert-message']") # test duplicate username assert(alert.text == 'username: Username "Frontend_test_user1" is already taken.') username_input.send_keys("Frontend_test_user1_new"+str(random.randint(1000,3000))) register_button.click() sleep(1) # test sign up request is sent alert = driver.find_element_by_xpath(".//div[@class='ant-alert-message']") assert(alert.text == "Successfully Registered! : Please await admin approval before Login!") # please delete or approve the sign up request later driver.close() if __name__ == "__main__": try: test_SignUpRequest() print("test_SignUpRequest passed") except: print("test_SignUpRequest Failed")
1,357
0
23
7a635939146e08bb91f77fd1ef12cbe7ecea88c9
224
py
Python
Flask/APIFlask/schemas/book.py
JhonatasMenezes/Projetos_Python
f1989a8cb1c428fdae98da770f8db149b8b8587d
[ "MIT" ]
3
2021-07-15T22:58:00.000Z
2022-02-18T17:42:00.000Z
Flask/APIFlask/schemas/book.py
JhonatasMenezes/Projetos_Python
f1989a8cb1c428fdae98da770f8db149b8b8587d
[ "MIT" ]
1
2021-10-01T17:52:49.000Z
2021-10-01T17:52:49.000Z
Flask/APIFlask/schemas/book.py
JhonatasMenezes/Projetos_Python
f1989a8cb1c428fdae98da770f8db149b8b8587d
[ "MIT" ]
null
null
null
from marshmallow import EXCLUDE from ma import ma from models.book import BookModel
24.888889
42
0.723214
from marshmallow import EXCLUDE from ma import ma from models.book import BookModel class BookSchema(ma.SQLAlchemyAutoSchema): class Beta: model = BookModel load_instance = True unknown = EXCLUDE
0
118
23
6b795fa3b8cecd2854b0c676c4b54bf5e6a30cf3
601
py
Python
07_hidden_dir/Resources/script.py
ssmrabet/Darkly
089ac7ac19fd1f08a61c81e63becbea65e2f3b4f
[ "MIT" ]
null
null
null
07_hidden_dir/Resources/script.py
ssmrabet/Darkly
089ac7ac19fd1f08a61c81e63becbea65e2f3b4f
[ "MIT" ]
null
null
null
07_hidden_dir/Resources/script.py
ssmrabet/Darkly
089ac7ac19fd1f08a61c81e63becbea65e2f3b4f
[ "MIT" ]
null
null
null
import requests import bs4 as bs if __name__ == "__main__": url = "http://192.168.1.40/.hidden/" scrapping_recursive(url)
23.115385
44
0.625624
import requests import bs4 as bs def scrapping_recursive(url): r = requests.get(url) s = bs.BeautifulSoup(r.text, 'html.parser') if (s is not None): links = s.find_all("a") #f = open("result.txt", "a+") for link in links: final_link = link.get('href') if (final_link == "README"): r = requests.get(url + final_link) line = r.text.encode('utf-8').strip() print(line) #f.write(line + "\n"); elif (final_link != "../"): scrapping_recursive(url + final_link) #f.close() if __name__ == "__main__": url = "http://192.168.1.40/.hidden/" scrapping_recursive(url)
453
0
23
0e7a9cfca5eead38c216a3c2821ac65326cfec71
6,193
py
Python
Sketches/MPS/BugReports/FixTests/Kamaelia/Kamaelia/Apps/MH/Profiling.py
sparkslabs/kamaelia_orig
24b5f855a63421a1f7c6c7a35a7f4629ed955316
[ "Apache-2.0" ]
12
2015-10-20T10:22:01.000Z
2021-07-19T10:09:44.000Z
Sketches/MPS/BugReports/FixTests/Kamaelia/Kamaelia/Apps/MH/Profiling.py
sparkslabs/kamaelia_orig
24b5f855a63421a1f7c6c7a35a7f4629ed955316
[ "Apache-2.0" ]
2
2015-10-20T10:22:55.000Z
2017-02-13T11:05:25.000Z
Sketches/MPS/BugReports/FixTests/Kamaelia/Kamaelia/Apps/MH/Profiling.py
sparkslabs/kamaelia_orig
24b5f855a63421a1f7c6c7a35a7f4629ed955316
[ "Apache-2.0" ]
6
2015-03-09T12:51:59.000Z
2020-03-01T13:06:21.000Z
#!/usr/bin/env python # -*- coding: utf-8 -*- # Copyright 2010 British Broadcasting Corporation and Kamaelia Contributors(1) # # (1) Kamaelia Contributors are listed in the AUTHORS file and at # http://www.kamaelia.org/AUTHORS - please extend this file, # not this notice. # # Licensed under the Apache License, Version 2.0 (the "License"); # you may not use this file except in compliance with the License. # You may obtain a copy of the License at # # http://www.apache.org/licenses/LICENSE-2.0 # # Unless required by applicable law or agreed to in writing, software # distributed under the License is distributed on an "AS IS" BASIS, # WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. # See the License for the specific language governing permissions and # limitations under the License. from Axon.Component import component from Axon.ThreadedComponent import threadedcomponent from Axon.Ipc import producerFinished, shutdownMicroprocess from Kamaelia.Util.PipelineComponent import pipeline import time from Axon.Scheduler import _ACTIVE class Profiler(threadedcomponent): """\ Profiler([samplingrate][,outputrate]) -> new Profiler component. Basic code profiler for Axon/Kamaelia systems. Measures the amount of time different microproceses are running. Keyword arguments: - samplingrate -- samples of state taken per second (default=1.0) - outputrate -- times statistics are output per second (default=1.0) """ Inboxes = { "inbox" : "", "control" : "", } Outboxes = { "outbox" : "Raw profiling data", "signal" : "", } if __name__=="__main__": from Kamaelia.Util.Console import ConsoleEchoer BusyComponent().activate() pipeline( FormattedProfiler(10.0,1.0), ConsoleEchoer(), ).run()
37.083832
145
0.51316
#!/usr/bin/env python # -*- coding: utf-8 -*- # Copyright 2010 British Broadcasting Corporation and Kamaelia Contributors(1) # # (1) Kamaelia Contributors are listed in the AUTHORS file and at # http://www.kamaelia.org/AUTHORS - please extend this file, # not this notice. # # Licensed under the Apache License, Version 2.0 (the "License"); # you may not use this file except in compliance with the License. # You may obtain a copy of the License at # # http://www.apache.org/licenses/LICENSE-2.0 # # Unless required by applicable law or agreed to in writing, software # distributed under the License is distributed on an "AS IS" BASIS, # WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. # See the License for the specific language governing permissions and # limitations under the License. from Axon.Component import component from Axon.ThreadedComponent import threadedcomponent from Axon.Ipc import producerFinished, shutdownMicroprocess from Kamaelia.Util.PipelineComponent import pipeline import time from Axon.Scheduler import _ACTIVE class Profiler(threadedcomponent): """\ Profiler([samplingrate][,outputrate]) -> new Profiler component. Basic code profiler for Axon/Kamaelia systems. Measures the amount of time different microproceses are running. Keyword arguments: - samplingrate -- samples of state taken per second (default=1.0) - outputrate -- times statistics are output per second (default=1.0) """ Inboxes = { "inbox" : "", "control" : "", } Outboxes = { "outbox" : "Raw profiling data", "signal" : "", } def __init__(self, samplingrate=1.0, outputrate=1.0): super(Profiler,self).__init__() self.samplestep = 1.0 / samplingrate self.outputstep = 1.0 / outputrate def shutdown(self): while self.dataReady("control"): msg = self.recv("control") self.send(msg,"signal") if isinstance(msg, (shutdownMicroprocess, producerFinished)): return True return False def main(self): microprocesses = {} now = time.time() nextsample = now nextoutput = now cycles=0 scheduler = self.scheduler latest=0 while not self.shutdown(): nexttime = min(nextsample,nextoutput) time.sleep(nexttime-now) now=time.time() if now >= nextsample: nextsample = now+self.samplestep cycles+=1 latest+=1 for mprocess in scheduler.listAllThreads(): name=mprocess.name running,active,shortactive,_,_2 = microprocesses.get(name, (0,0,0,None,-1)) running+=1 # if not scheduler.isThreadPaused(mprocess): if scheduler.threads[mprocess] == _ACTIVE: active+=1 shortactive+=1 try: lineno = mprocess._microprocess__thread.gi_frame.f_locals['pc'].gi_frame.f_lineno except: lineno = -1 microprocesses[name] = running,active,shortactive,latest,lineno if now >= nextoutput: nextoutput = now+self.outputstep outmsg = [] # print "-----Run----Active--%Usage--LineNo--Name-----------------" todel=[] for name,(running,active,shortactive,mru,lineno) in microprocesses.iteritems(): outmsg.append( { "running" : running, "active" : active, "%usage" : 100.0*shortactive/cycles, "lineno" : lineno, "name" : name, "done" : mru!=latest } ) if mru!=latest: todel.append(name) name += " [DONE]" else: microprocesses[name] = (running,active,0,mru,lineno) # print "%8d %8d %6.2f %6d %s" % (running,active,100.0*shortactive/cycles,lineno,name) # print "------------------------------------------" cycles=0 for name in todel: del microprocesses[name] self.send(outmsg, "outbox") class ProfilerOutputFormatter(component): def shutdown(self): while self.dataReady("control"): msg = self.recv("control") self.send(msg,"signal") if isinstance(msg, (shutdownMicroprocess, producerFinished)): return True return False def main(self): while not self.shutdown(): while self.dataReady("inbox"): profile = self.recv("inbox") output = "-----Run----Active--%Usage--LineNo--Name-----------------\n" for mp in profile: flags = [] if mp["done"]: flags.append("[DONE]") output += "%8d %8d %6.2f %6d %s %s\n" % (mp["running"],mp["active"],mp["%usage"],mp["lineno"],mp["name"]," ".join(flags)) output += "---------------------------------------------------------\n" self.send(output,"outbox") yield 1 self.pause() def FormattedProfiler(*largs,**kargs): return pipeline( Profiler(*largs,**kargs), ProfilerOutputFormatter() ) if __name__=="__main__": from Kamaelia.Util.Console import ConsoleEchoer class BusyComponent(component): def main(self): while 1: yield 1 BusyComponent().activate() pipeline( FormattedProfiler(10.0,1.0), ConsoleEchoer(), ).run()
4,017
30
241
0ff91e3fafb80c50fca16bcdb41b0cd40242dff6
1,373
py
Python
hummingbot/cli/utils/symbol_splitter.py
mitakash/hummingbot
58c2bc421f5da9cef472fea473f9b5273466b11c
[ "Apache-2.0" ]
null
null
null
hummingbot/cli/utils/symbol_splitter.py
mitakash/hummingbot
58c2bc421f5da9cef472fea473f9b5273466b11c
[ "Apache-2.0" ]
null
null
null
hummingbot/cli/utils/symbol_splitter.py
mitakash/hummingbot
58c2bc421f5da9cef472fea473f9b5273466b11c
[ "Apache-2.0" ]
null
null
null
import re from typing import Tuple BINANCE_SYMBOL_SPLITTER = re.compile(r"^(\w+)(BTC|ETH|BNB|XRP|USDT|USDC|TUSD|PAX)$")
30.511111
118
0.589221
import re from typing import Tuple BINANCE_SYMBOL_SPLITTER = re.compile(r"^(\w+)(BTC|ETH|BNB|XRP|USDT|USDC|TUSD|PAX)$") class SymbolSplitter: def __init__(self, market: str, symbol: str): self._symbol: Tuple[str, str] = self.split(market, symbol) @property def base_asset(self): return self._symbol[0] @property def quote_asset(self): return self._symbol[1] @staticmethod def split(market, symbol) -> Tuple[str, str]: """ Takes an exchange pair and return :param market: lowercase market e.g. binance :param symbol: uppercase exchange pair e.g. ETHUSDT :return: tuple: (base_asset, quote_asset) """ try: if market == "binance": m = BINANCE_SYMBOL_SPLITTER.match(symbol) result: Tuple = (m.group(1), m.group(2)) elif market in ["ddex", "radar_relay", "coinbase_pro"]: result: Tuple = tuple(symbol.split('-')) else: raise ValueError("Market %s not supported" % (market,)) except Exception: raise ValueError("Error parsing %s symbol. Symbol %s is not a valid %s symbol" % (market, symbol, market)) if len(result) != 2: raise ValueError("Symbol %s does not match %s's format" % (symbol, market)) return result
154
1,071
23
fffd4b71438fcbfa4a73dc716b4d928f5fe5b3c0
2,290
py
Python
code/analyze_type_precision.py
MrZhengXin/OptiPrompt
ec3654ecdcb6b7fb7d35b0e7f5c56687ff757f76
[ "MIT" ]
null
null
null
code/analyze_type_precision.py
MrZhengXin/OptiPrompt
ec3654ecdcb6b7fb7d35b0e7f5c56687ff757f76
[ "MIT" ]
null
null
null
code/analyze_type_precision.py
MrZhengXin/OptiPrompt
ec3654ecdcb6b7fb7d35b0e7f5c56687ff757f76
[ "MIT" ]
null
null
null
import json import os print("relation", "raw_p", "few_p", "p inc", "raw_type_p", "few_type_p", "t inc", sep='\t') relations = ['P1001', 'P101', 'P103', 'P106', 'P108', 'P127', 'P1303', 'P131', 'P136', 'P1376', 'P138', 'P140', 'P1412', 'P159', 'P17', 'P176', 'P178', 'P19', 'P190', 'P20', 'P264', 'P27', 'P276', 'P279', 'P30', 'P31', 'P36', 'P361', 'P364', 'P37', 'P39', 'P407', 'P413', 'P449', 'P463', 'P47', 'P495', 'P527', 'P530', 'P740', 'P937'] fewshot_dir_path = 'case_based_10_train' raw_dir_path = 'lama' with open('data/type_file/bert.json', 'r') as f: relation_token = json.load(f) for relation in relations: with open(os.path.join(fewshot_dir_path, relation, relation + '_predictions.jsonl'), 'r') as f: fewshot_prediction_list = f.readlines() fewshot_prediction_list = [json.loads(pred) for pred in fewshot_prediction_list] with open(os.path.join(raw_dir_path, relation, relation + '_predictions.jsonl'), 'r') as f: raw_prediction_list = f.readlines() raw_prediction_list = [json.loads(pred) for pred in raw_prediction_list] type_token_set = set(relation_token[relation]) raw_p = get_precision(raw_prediction_list) few_p = get_precision(fewshot_prediction_list) p_inc = few_p - raw_p raw_type_p = get_type_precision(raw_prediction_list, type_token_set) few_type_p = get_type_precision(fewshot_prediction_list, type_token_set) t_inc = few_type_p - raw_type_p print( relation, raw_p, few_p, p_inc, raw_type_p, few_type_p, t_inc, sep='\t' )
39.482759
334
0.662882
import json import os print("relation", "raw_p", "few_p", "p inc", "raw_type_p", "few_type_p", "t inc", sep='\t') relations = ['P1001', 'P101', 'P103', 'P106', 'P108', 'P127', 'P1303', 'P131', 'P136', 'P1376', 'P138', 'P140', 'P1412', 'P159', 'P17', 'P176', 'P178', 'P19', 'P190', 'P20', 'P264', 'P27', 'P276', 'P279', 'P30', 'P31', 'P36', 'P361', 'P364', 'P37', 'P39', 'P407', 'P413', 'P449', 'P463', 'P47', 'P495', 'P527', 'P530', 'P740', 'P937'] fewshot_dir_path = 'case_based_10_train' raw_dir_path = 'lama' with open('data/type_file/bert.json', 'r') as f: relation_token = json.load(f) def get_type_precision(prediction_list, type_token_set): type_correct_cnt = 0 total = len(prediction_list) for prediction in prediction_list: top_word = prediction['topk'][0]['token'] type_correct_cnt += 1 if top_word in type_token_set else 0 type_presicion = 100.0 * type_correct_cnt / total return type_presicion def get_precision(prediction_list): correct_cnt = 0 total = len(prediction_list) for prediction in prediction_list: top_word = prediction['topk'][0]['token'] answer = prediction['obj_label'] correct_cnt += 1 if top_word == answer else 0 presicion = 100.0 * correct_cnt / total return presicion for relation in relations: with open(os.path.join(fewshot_dir_path, relation, relation + '_predictions.jsonl'), 'r') as f: fewshot_prediction_list = f.readlines() fewshot_prediction_list = [json.loads(pred) for pred in fewshot_prediction_list] with open(os.path.join(raw_dir_path, relation, relation + '_predictions.jsonl'), 'r') as f: raw_prediction_list = f.readlines() raw_prediction_list = [json.loads(pred) for pred in raw_prediction_list] type_token_set = set(relation_token[relation]) raw_p = get_precision(raw_prediction_list) few_p = get_precision(fewshot_prediction_list) p_inc = few_p - raw_p raw_type_p = get_type_precision(raw_prediction_list, type_token_set) few_type_p = get_type_precision(fewshot_prediction_list, type_token_set) t_inc = few_type_p - raw_type_p print( relation, raw_p, few_p, p_inc, raw_type_p, few_type_p, t_inc, sep='\t' )
645
0
46
22ea2f0346f2cc607b6a5343c004181e08422137
2,229
py
Python
utils.py
nrichards17/diabetes-pytorch
80ba7e366e5850657cdd29dd8f81adf81408c56f
[ "MIT" ]
null
null
null
utils.py
nrichards17/diabetes-pytorch
80ba7e366e5850657cdd29dd8f81adf81408c56f
[ "MIT" ]
null
null
null
utils.py
nrichards17/diabetes-pytorch
80ba7e366e5850657cdd29dd8f81adf81408c56f
[ "MIT" ]
null
null
null
import json import os import logging import pandas as pd import torch def set_logger(log_path): """Set the logger to log info in terminal and file `log_path`. In general, it is useful to have a logger so that every output to the terminal is saved in a permanent file. Here we save it to `model_dir/train.log`. Example: ``` logging.info("Starting training...") ``` Args: log_path: (string) where to log """ logger = logging.getLogger() logger.setLevel(logging.INFO) if not logger.handlers: # Logging to a file file_handler = logging.FileHandler(log_path) file_handler.setFormatter(logging.Formatter('%(asctime)s:%(levelname)s: %(message)s')) logger.addHandler(file_handler) # Logging to console stream_handler = logging.StreamHandler() stream_handler.setFormatter(logging.Formatter('%(asctime)s:%(levelname)s: %(message)s')) logger.addHandler(stream_handler) def save_metric_histories(train_hist, valid_hist, results_path): """ both lists of dicts, keys are metric names """ train_hist_df = pd.DataFrame(train_hist) valid_hist_df = pd.DataFrame(valid_hist) TRAIN_HIST_FILE = os.path.join(results_path, 'train_hist.csv') VALID_HIST_FILE = os.path.join(results_path, 'valid_hist.csv') train_hist_df.to_csv(TRAIN_HIST_FILE, index=False) valid_hist_df.to_csv(VALID_HIST_FILE, index=False)
28.576923
96
0.662629
import json import os import logging import pandas as pd import torch class Params(dict): def save(self, json_path): with open(json_path, 'w') as f: json.dump(self, f, indent=4) def load(self, json_path): with open(json_path) as f: params = json.load(f) self.update(params) class Features(dict): def save(self, json_path): with open(json_path, 'w') as f: json.dump(self, f, indent=4) def load(self, json_path): with open(json_path) as f: params = json.load(f) self.update(params) def set_logger(log_path): """Set the logger to log info in terminal and file `log_path`. In general, it is useful to have a logger so that every output to the terminal is saved in a permanent file. Here we save it to `model_dir/train.log`. Example: ``` logging.info("Starting training...") ``` Args: log_path: (string) where to log """ logger = logging.getLogger() logger.setLevel(logging.INFO) if not logger.handlers: # Logging to a file file_handler = logging.FileHandler(log_path) file_handler.setFormatter(logging.Formatter('%(asctime)s:%(levelname)s: %(message)s')) logger.addHandler(file_handler) # Logging to console stream_handler = logging.StreamHandler() stream_handler.setFormatter(logging.Formatter('%(asctime)s:%(levelname)s: %(message)s')) logger.addHandler(stream_handler) def save_metric_histories(train_hist, valid_hist, results_path): """ both lists of dicts, keys are metric names """ train_hist_df = pd.DataFrame(train_hist) valid_hist_df = pd.DataFrame(valid_hist) TRAIN_HIST_FILE = os.path.join(results_path, 'train_hist.csv') VALID_HIST_FILE = os.path.join(results_path, 'valid_hist.csv') train_hist_df.to_csv(TRAIN_HIST_FILE, index=False) valid_hist_df.to_csv(VALID_HIST_FILE, index=False) def save_model(model, results_path): MODEL_FILE = os.path.join(results_path, 'model.pt') torch.save(model, MODEL_FILE) def load_model(path): assert os.path.exists(path), f'File {path} does not exist.' return torch.load(path)
581
-2
198
54d538a4ca0dd49fa6ee3492bdccefda46e1cbaa
1,500
py
Python
tests/tests_test_workflow/test_integ_workflow/integ_test/test_integ_test_start_properties_opensearch_dashboards.py
rishabh6788/opensearch-build
f03a5848397a2758ea29a4edc0bb6b221c0fc2e3
[ "Apache-2.0" ]
null
null
null
tests/tests_test_workflow/test_integ_workflow/integ_test/test_integ_test_start_properties_opensearch_dashboards.py
rishabh6788/opensearch-build
f03a5848397a2758ea29a4edc0bb6b221c0fc2e3
[ "Apache-2.0" ]
null
null
null
tests/tests_test_workflow/test_integ_workflow/integ_test/test_integ_test_start_properties_opensearch_dashboards.py
rishabh6788/opensearch-build
f03a5848397a2758ea29a4edc0bb6b221c0fc2e3
[ "Apache-2.0" ]
null
null
null
# SPDX-License-Identifier: Apache-2.0 # # The OpenSearch Contributors require contributions made to # this file be licensed under the Apache-2.0 license or a # compatible open source license. import unittest from unittest.mock import MagicMock, Mock, patch from test_workflow.integ_test.integ_test_start_properties_opensearch_dashboards import IntegTestStartPropertiesOpenSearchDashboards
45.454545
131
0.796
# SPDX-License-Identifier: Apache-2.0 # # The OpenSearch Contributors require contributions made to # this file be licensed under the Apache-2.0 license or a # compatible open source license. import unittest from unittest.mock import MagicMock, Mock, patch from test_workflow.integ_test.integ_test_start_properties_opensearch_dashboards import IntegTestStartPropertiesOpenSearchDashboards class TestIntegTestStartPropertiesOpenSearchDashboards(unittest.TestCase): @patch("test_workflow.integ_test.integ_test_start_properties.BundleManifest") @patch("test_workflow.integ_test.integ_test_start_properties.BuildManifest") @patch("test_workflow.integ_test.integ_test_start_properties_opensearch_dashboards.DependencyInstallerOpenSearchDashboards") def test(self, mock_installer: Mock, mock_build: Mock, mock_bundle: Mock) -> None: path = "test-path" mock_bundle_object = MagicMock() mock_bundle.from_urlpath.return_value = mock_bundle_object mock_build_object = MagicMock() mock_build.from_urlpath.return_value = mock_build_object IntegTestStartPropertiesOpenSearchDashboards(path) mock_bundle.from_urlpath.assert_called_once_with("/".join([path.rstrip("/"), "dist/opensearch-dashboards/manifest.yml"])) mock_build.from_urlpath.assert_called_once_with("/".join([path.rstrip("/"), "builds/opensearch-dashboards/manifest.yml"])) mock_installer.assert_called_with(path, mock_build_object, mock_bundle_object)
713
372
23
5d40ae920735fb7e5b921b8c8a69c1c85db58c7a
907
py
Python
Python/main.py
edeutsch/USI
7fadea3cc1e23cea8b33a210b05bf67ebc0a4b38
[ "Apache-2.0" ]
null
null
null
Python/main.py
edeutsch/USI
7fadea3cc1e23cea8b33a210b05bf67ebc0a4b38
[ "Apache-2.0" ]
1
2018-08-31T16:59:03.000Z
2018-08-31T16:59:03.000Z
Python/main.py
edeutsch/USI
7fadea3cc1e23cea8b33a210b05bf67ebc0a4b38
[ "Apache-2.0" ]
1
2018-08-06T17:46:37.000Z
2018-08-06T17:46:37.000Z
from Spectrum import Spectrum from UniversalSpectrumIdentifier import UniversalSpectrumIdentifier # USI created usi = UniversalSpectrumIdentifier("asdf:PXD000561::Adult_Frontalcortex_bRP_Elite_85_f09:scan:17555:VLHPLEGAVVIIFK/2") # usi = UniversalSpectrumIdentifier("mzspec:PXD002437:00261_A06_P001564_B00E_A00_R1:scan:10951:PEPT[Phospho]IDELVISK/2") # usi = UniversalSpectrumIdentifier("mzspec:PXD005712::20152002_RG_150218_Saita_Ctrl_3XXXXX:scan:5748:AVAAVAATGPASAPGPGGGR/2") usi.parse(verbose=False) # if the USI is okay then create a spectrum class to fetch from the online database if usi.valid: # spectrum class just takes in a USI spectrum = Spectrum(usi) # fetches the USI from the PeptideAtlas database or whatever database is specified resp = spectrum.fetch('PeptideAtlas') print(resp.code) if resp.code == 'OK': spectrum.show()
43.190476
127
0.76516
from Spectrum import Spectrum from UniversalSpectrumIdentifier import UniversalSpectrumIdentifier # USI created usi = UniversalSpectrumIdentifier("asdf:PXD000561::Adult_Frontalcortex_bRP_Elite_85_f09:scan:17555:VLHPLEGAVVIIFK/2") # usi = UniversalSpectrumIdentifier("mzspec:PXD002437:00261_A06_P001564_B00E_A00_R1:scan:10951:PEPT[Phospho]IDELVISK/2") # usi = UniversalSpectrumIdentifier("mzspec:PXD005712::20152002_RG_150218_Saita_Ctrl_3XXXXX:scan:5748:AVAAVAATGPASAPGPGGGR/2") usi.parse(verbose=False) # if the USI is okay then create a spectrum class to fetch from the online database if usi.valid: # spectrum class just takes in a USI spectrum = Spectrum(usi) # fetches the USI from the PeptideAtlas database or whatever database is specified resp = spectrum.fetch('PeptideAtlas') print(resp.code) if resp.code == 'OK': spectrum.show()
0
0
0
78b70ffad5c6ae171231f8e98d808c39a15557be
2,854
py
Python
src/vtra/plot/create_crop_maps.py
GFDRR/vietnam-transport
71f6fc8cb7f1ca7bccb9a29d544869b442e68bfc
[ "MIT" ]
3
2018-07-09T12:15:46.000Z
2020-12-03T07:02:23.000Z
src/vtra/plot/create_crop_maps.py
GFDRR/vietnam-transport
71f6fc8cb7f1ca7bccb9a29d544869b442e68bfc
[ "MIT" ]
1
2019-05-09T21:57:20.000Z
2019-05-09T21:57:20.000Z
src/vtra/plot/create_crop_maps.py
GFDRR/vietnam-transport
71f6fc8cb7f1ca7bccb9a29d544869b442e68bfc
[ "MIT" ]
2
2018-07-23T12:49:21.000Z
2021-06-03T11:00:44.000Z
"""Crop maps """ # pylint: disable=C0103 import os import sys import cartopy.crs as ccrs import cartopy.io.shapereader as shpreader import matplotlib as mpl import matplotlib.pyplot as plt import numpy as np from vtra.utils import * mpl.style.use('ggplot') mpl.rcParams['font.size'] = 11. mpl.rcParams['axes.labelsize'] = 14. mpl.rcParams['xtick.labelsize'] = 11. mpl.rcParams['ytick.labelsize'] = 11. mpl.rcParams['savefig.pad_inches'] = 0.05 if __name__ == '__main__': main()
38.567568
126
0.565172
"""Crop maps """ # pylint: disable=C0103 import os import sys import cartopy.crs as ccrs import cartopy.io.shapereader as shpreader import matplotlib as mpl import matplotlib.pyplot as plt import numpy as np from vtra.utils import * mpl.style.use('ggplot') mpl.rcParams['font.size'] = 11. mpl.rcParams['axes.labelsize'] = 14. mpl.rcParams['xtick.labelsize'] = 11. mpl.rcParams['ytick.labelsize'] = 11. mpl.rcParams['savefig.pad_inches'] = 0.05 def main(): config = load_config() crop_cols = ['rice', 'cash', 'cass', 'teas', 'maiz', 'rubb', 'swpo', 'acof', 'rcof', 'pepp'] title_cols = ['Rice', 'Cashew', 'Cassava', 'Teas', 'Maize', 'Rubber', 'Sweet Potatoes', 'Coffee Arabica', 'Coffee Robusta', 'Pepper'] crop_file_path = os.path.join(config['paths']['data'], 'Agriculture_crops', 'crop_data') for file in os.listdir(crop_file_path): if file.endswith('.tif'): crop_file = os.path.join(crop_file_path, file) crop_name = [cr for cr in crop_cols if cr in file.lower().strip()] if crop_name: crop_name = crop_name[0] crop_title = title_cols[crop_cols.index(crop_name)] ax = get_axes() plot_basemap(ax, config['paths']['data']) scale_bar(ax, location=(0.8, 0.05)) plot_basemap_labels(ax, config['paths']['data']) proj_lat_lon = ccrs.PlateCarree() # Create color map colors = plt.get_cmap('YlGn') #colors.colors[0] = (1, 1, 1, 0) # Read in raster data data, lat_lon_extent = get_data(crop_file) data[data <= 0] = np.nan max_val = np.nanmax(data) norm = mpl.colors.Normalize(vmin=0, vmax=max_val) # Plot population data im = ax.imshow(data, extent=lat_lon_extent, transform=proj_lat_lon, cmap=colors, norm=norm, zorder=5) # Add colorbar cbar = plt.colorbar(im, ax=ax, fraction=0.1, shrink=0.87, pad=0.01, drawedges=False, orientation='horizontal', norm=mpl.colors.Normalize(vmin=0, vmax=max_val), ticks=list(np.linspace(0, max_val, 3))) cbar.set_clim(vmin=0, vmax=max_val) cbar.outline.set_color("none") cbar.ax.yaxis.set_tick_params(color='black') cbar.ax.set_xlabel('Crop Annual Production(tons)', fontsize=12, color='black') plt.title(crop_title, fontsize=14) output_file = os.path.join( config['paths']['figures'], '{}_production.png'.format(crop_name)) save_fig(output_file) plt.close() if __name__ == '__main__': main()
2,344
0
23
0369ac970383309c0f70c4043c5bd0ee8c516bbb
1,113
py
Python
src/plot-figure-7.py
lorenzocorneo/surrounded-by-the-clouds
536375943f8a6c23b31d6528403624d586ce1270
[ "MIT" ]
2
2021-03-25T15:56:07.000Z
2021-10-10T13:02:52.000Z
src/plot-figure-7.py
lorenzocorneo/surrounded-by-the-clouds
536375943f8a6c23b31d6528403624d586ce1270
[ "MIT" ]
null
null
null
src/plot-figure-7.py
lorenzocorneo/surrounded-by-the-clouds
536375943f8a6c23b31d6528403624d586ce1270
[ "MIT" ]
null
null
null
from collections import defaultdict import matplotlib.pyplot as plt from boxes import generate_legend_handles, group_boxplot from commons import WIDTH_IN with open("data/hops.csv") as f: ret = defaultdict(list) for l in f.readlines()[1:]: split = l.rstrip("\n").split(",") # is datacenter? if split[-1] == "1": continue # Hops, ASes ret[split[0]].append((int(split[5]), int(split[6]))) grp = [ (continent, [("Hops", [x[0] for x in xs]), ("ASes", [x[1] for x in xs])]) for continent, xs in ret.items() ] fig, ax = plt.subplots(figsize=(WIDTH_IN, 1.2)) ax, positions, props = group_boxplot(grp, ax, showfliers=False) ax.set_yticks(range(0, 26, 5)) ax.set_ylabel("Path length") ax.legend( handles=generate_legend_handles(props), handlelength=1, labelspacing=0.06, columnspacing=0.5, handletextpad=0.3, ncol=6, fontsize="small", loc="upper right", fancybox=False, edgecolor="k", ) plt.grid(axis="y") plt.subplots_adjust(top=0.99, bottom=0.17, left=0.14, right=0.99) plt.savefig("figures/figure-7.pdf")
25.295455
77
0.638814
from collections import defaultdict import matplotlib.pyplot as plt from boxes import generate_legend_handles, group_boxplot from commons import WIDTH_IN with open("data/hops.csv") as f: ret = defaultdict(list) for l in f.readlines()[1:]: split = l.rstrip("\n").split(",") # is datacenter? if split[-1] == "1": continue # Hops, ASes ret[split[0]].append((int(split[5]), int(split[6]))) grp = [ (continent, [("Hops", [x[0] for x in xs]), ("ASes", [x[1] for x in xs])]) for continent, xs in ret.items() ] fig, ax = plt.subplots(figsize=(WIDTH_IN, 1.2)) ax, positions, props = group_boxplot(grp, ax, showfliers=False) ax.set_yticks(range(0, 26, 5)) ax.set_ylabel("Path length") ax.legend( handles=generate_legend_handles(props), handlelength=1, labelspacing=0.06, columnspacing=0.5, handletextpad=0.3, ncol=6, fontsize="small", loc="upper right", fancybox=False, edgecolor="k", ) plt.grid(axis="y") plt.subplots_adjust(top=0.99, bottom=0.17, left=0.14, right=0.99) plt.savefig("figures/figure-7.pdf")
0
0
0
55b3ede38b9889f29e3a15bff2b46b25815cfeec
740
py
Python
DataAnalysis/SearchTools/WordSearches.py
AdamSwenson/TwitterProject
8c5dc7a57eac611b555058736d609f2f204cb836
[ "MIT" ]
null
null
null
DataAnalysis/SearchTools/WordSearches.py
AdamSwenson/TwitterProject
8c5dc7a57eac611b555058736d609f2f204cb836
[ "MIT" ]
6
2020-03-24T17:34:24.000Z
2021-12-13T20:14:34.000Z
DataAnalysis/SearchTools/WordSearches.py
AdamSwenson/TwitterProject
8c5dc7a57eac611b555058736d609f2f204cb836
[ "MIT" ]
null
null
null
""" Created by adam on 5/31/18 """ __author__ = 'adam' import sqlite3 import environment def get_all_words_in_tweet(tweetId, db): """ Returns all the words used in the tweet Example: words = get_all_words_in_tweet(331546674315014144, db=environment.TWEET_DB_NO_STOP) words = [x[2] for x in words] Result: words = ['thought', 'crying', 'like', 'crazy', 'im', 'tired', 'pain','inevitability', 'rely', 'life', 'spoonie'] """ conn = sqlite3.connect(db) query = "SELECT * FROM word_map WHERE tweet_id = ?" param = (tweetId, ) with conn: r = conn.execute(query, param) return r.fetchall() if __name__ == '__main__': pass
21.764706
91
0.589189
""" Created by adam on 5/31/18 """ __author__ = 'adam' import sqlite3 import environment def get_all_words_in_tweet(tweetId, db): """ Returns all the words used in the tweet Example: words = get_all_words_in_tweet(331546674315014144, db=environment.TWEET_DB_NO_STOP) words = [x[2] for x in words] Result: words = ['thought', 'crying', 'like', 'crazy', 'im', 'tired', 'pain','inevitability', 'rely', 'life', 'spoonie'] """ conn = sqlite3.connect(db) query = "SELECT * FROM word_map WHERE tweet_id = ?" param = (tweetId, ) with conn: r = conn.execute(query, param) return r.fetchall() if __name__ == '__main__': pass
0
0
0
f65859568809091cac6c05f41f4c989b4ab25104
1,318
py
Python
Source/SourceGaussian.py
srio/BeamlineComponents
0fd107365f2ff3ec413df5ec6f4694a7903cbb94
[ "MIT" ]
null
null
null
Source/SourceGaussian.py
srio/BeamlineComponents
0fd107365f2ff3ec413df5ec6f4694a7903cbb94
[ "MIT" ]
2
2016-11-04T15:10:30.000Z
2016-11-04T15:15:59.000Z
Source/SourceGaussian.py
srio/BeamlineComponents
0fd107365f2ff3ec413df5ec6f4694a7903cbb94
[ "MIT" ]
null
null
null
""" Represents an optical Gaussian source. """
25.843137
79
0.685888
""" Represents an optical Gaussian source. """ class SourceGaussian(object): def __init__(self, sigma_x, sigma_y, sigma_x_prime, sigma_y_prime, energy): self._sigma_x = sigma_x self._sigma_y = sigma_y self._sigma_x_prime = sigma_x_prime self._sigma_y_prime = sigma_y_prime self._energy = energy def setAveragePhotonEnergy(self, average_photon_energy): self.__average_photon_energy = average_photon_energy def averagePhotonEnergy(self): return self.__average_photon_energy def setPulseEnergy(self, pulse_energy): self.__pulse_energy = pulse_energy def pulseEnergy(self): return self.__pulse_energy def setRepititionRate(self, repitition_rate): self.__repitition_rate = repitition_rate def repititionRate(self): return self.__repitition_rate def setPolarization(self, polarization): self.__polarization = polarization def polarization(self): return self.__polarization def sigmaX(self): return self._sigma_x def sigmaY(self): return self._sigma_y def sigmaXPrime(self): return self._sigma_x_prime def sigmaYPrime(self): return self._sigma_y_prime def energy(self): return self._energy
842
8
421
60487050897e32dddf4b8bc06326498770016f4e
2,165
py
Python
data/transcoder_evaluation_gfg/python/SUBSET_SUM_DIVISIBLE_M.py
mxl1n/CodeGen
e5101dd5c5e9c3720c70c80f78b18f13e118335a
[ "MIT" ]
241
2021-07-20T08:35:20.000Z
2022-03-31T02:39:08.000Z
data/transcoder_evaluation_gfg/python/SUBSET_SUM_DIVISIBLE_M.py
mxl1n/CodeGen
e5101dd5c5e9c3720c70c80f78b18f13e118335a
[ "MIT" ]
49
2021-07-22T23:18:42.000Z
2022-03-24T09:15:26.000Z
data/transcoder_evaluation_gfg/python/SUBSET_SUM_DIVISIBLE_M.py
mxl1n/CodeGen
e5101dd5c5e9c3720c70c80f78b18f13e118335a
[ "MIT" ]
71
2021-07-21T05:17:52.000Z
2022-03-29T23:49:28.000Z
# Copyright (c) 2019-present, Facebook, Inc. # All rights reserved. # # This source code is licensed under the license found in the # LICENSE file in the root directory of this source tree. # #TOFILL if __name__ == '__main__': param = [ ([2, 5, 7, 12, 13, 13, 15, 18, 20, 21, 22, 26, 27, 41, 41, 50, 53, 57, 58, 58, 61, 62, 62, 64, 70, 75, 78, 79, 81, 81, 81, 83, 86, 91, 93, 95, 97, 99, 99],36,35,), ([8, 16, 62, -24, 14, -4, 2, 50, -64, -76, 78, 66, -64, 18],12,11,), ([0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1],32,27,), ([50, 20, 79, 42, 85, 24, 20, 76, 36, 88, 40, 5, 24, 85, 7, 19, 43, 51, 94, 13, 53, 93, 92, 43, 97, 38, 80, 48, 52, 47, 77, 56, 41, 80, 32, 34, 77, 14, 70, 3],29,27,), ([-96, -94, -72, -58, -48, -36, -28, -26, -10, -10, -8, -8, -6, 2, 14, 30, 30, 54, 58, 60, 64, 68, 78, 84, 96, 98],16,18,), ([1, 0, 1, 1, 0, 0, 1, 1, 1, 0, 0],7,8,), ([2, 7, 8, 15, 18, 23, 24, 25, 27, 35, 40, 42, 43, 46, 48, 50, 53, 64, 66, 69, 70, 71, 72, 77, 78, 80, 81, 81, 81, 82, 82, 82, 84, 87, 97, 98],23,32,), ([46, 54, 24, -10],3,3,), ([0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1],21,34,), ([39, 21, 38, 6, 38, 44, 96, 1, 16, 1, 28, 4, 55, 8],12,11,) ] n_success = 0 for i, parameters_set in enumerate(param): if f_filled(*parameters_set) == f_gold(*parameters_set): n_success+=1 print("#Results: %i, %i" % (n_success, len(param)))
48.111111
171
0.439261
# Copyright (c) 2019-present, Facebook, Inc. # All rights reserved. # # This source code is licensed under the license found in the # LICENSE file in the root directory of this source tree. # def f_gold ( arr , n , m ) : if ( n > m ) : return True DP = [ False for i in range ( m ) ] for i in range ( n ) : if ( DP [ 0 ] ) : return True temp = [ False for i in range ( m ) ] for j in range ( m ) : if ( DP [ j ] == True ) : if ( DP [ ( j + arr [ i ] ) % m ] == False ) : temp [ ( j + arr [ i ] ) % m ] = True for j in range ( m ) : if ( temp [ j ] ) : DP [ j ] = True DP [ arr [ i ] % m ] = True return DP [ 0 ] #TOFILL if __name__ == '__main__': param = [ ([2, 5, 7, 12, 13, 13, 15, 18, 20, 21, 22, 26, 27, 41, 41, 50, 53, 57, 58, 58, 61, 62, 62, 64, 70, 75, 78, 79, 81, 81, 81, 83, 86, 91, 93, 95, 97, 99, 99],36,35,), ([8, 16, 62, -24, 14, -4, 2, 50, -64, -76, 78, 66, -64, 18],12,11,), ([0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1],32,27,), ([50, 20, 79, 42, 85, 24, 20, 76, 36, 88, 40, 5, 24, 85, 7, 19, 43, 51, 94, 13, 53, 93, 92, 43, 97, 38, 80, 48, 52, 47, 77, 56, 41, 80, 32, 34, 77, 14, 70, 3],29,27,), ([-96, -94, -72, -58, -48, -36, -28, -26, -10, -10, -8, -8, -6, 2, 14, 30, 30, 54, 58, 60, 64, 68, 78, 84, 96, 98],16,18,), ([1, 0, 1, 1, 0, 0, 1, 1, 1, 0, 0],7,8,), ([2, 7, 8, 15, 18, 23, 24, 25, 27, 35, 40, 42, 43, 46, 48, 50, 53, 64, 66, 69, 70, 71, 72, 77, 78, 80, 81, 81, 81, 82, 82, 82, 84, 87, 97, 98],23,32,), ([46, 54, 24, -10],3,3,), ([0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1],21,34,), ([39, 21, 38, 6, 38, 44, 96, 1, 16, 1, 28, 4, 55, 8],12,11,) ] n_success = 0 for i, parameters_set in enumerate(param): if f_filled(*parameters_set) == f_gold(*parameters_set): n_success+=1 print("#Results: %i, %i" % (n_success, len(param)))
550
0
22
5a67f959ffbb10d127fdebfd245b28d5f2ba7a70
11,801
py
Python
python/aocrecs/logic/events.py
Rotzbua/aocrecs.com
2f03ece75e7367a99e5f36874727cd5bb90508f7
[ "MIT" ]
7
2019-10-08T09:04:48.000Z
2021-02-06T00:05:53.000Z
python/aocrecs/logic/events.py
happyleavesaoc/aocrecs.com
2f03ece75e7367a99e5f36874727cd5bb90508f7
[ "MIT" ]
10
2020-01-18T22:14:09.000Z
2021-07-31T21:43:05.000Z
python/aocrecs/logic/events.py
happyleavesaoc/aocrecs.com
2f03ece75e7367a99e5f36874727cd5bb90508f7
[ "MIT" ]
5
2020-05-08T11:35:14.000Z
2022-01-16T12:41:57.000Z
"""Events.""" import asyncio import networkx from aocrecs.cache import cached from aocrecs.util import by_key def get_sides(matches, participants): """Get users per side given matches.""" users = {} for match in matches: users.update({ p['user_id']: dict( id=p['user_id'], name=p['user_name'] or p['name'], platform_id=p['platform_id'] ) for p in match['players'] }) return [ dict(p, users=[users[u] for u in p['user_ids'] if u]) for p in compute_participants(matches, participants) ] async def get_series(database, series_id): """Get a series.""" series_query = """ select series.id, series.played, series_metadata.name, rounds.tournament_id, tournaments.id as tournament_id, tournaments.name as tournament_name, events.id as event_id, events.name as event_name from series join rounds on series.round_id=rounds.id join series_metadata on series.id=series_metadata.series_id join tournaments on rounds.tournament_id=tournaments.id join events on tournaments.event_id=events.id where series.id=:id """ participants_query = 'select series_id, name, score, winner from participants where series_id=:id' matches_query = 'select id, series_id from matches where series_id=:id' values = {'id': series_id} series, participants, matches = await asyncio.gather( database.fetch_one(series_query, values=values), database.fetch_all(participants_query, values=values), database.fetch_all(matches_query, values=values) ) return dict( series, participants=list(map(dict, participants)), match_ids=list(map(lambda m: m['id'], matches)), tournament=dict( id=series['tournament_id'], name=series['tournament_name'], event=dict( id=series['event_id'], name=series['event_name'] ) ) ) @cached(ttl=86400) async def get_event(database, event_id): """Get an event.""" events_query = 'select id, name, year from events where id=:event_id' tournaments_query = 'select id, event_id, name from tournaments where event_id=:event_id' series_query = """ select series.id, series.played, series_metadata.name, rounds.tournament_id from series join rounds on series.round_id=rounds.id join tournaments on rounds.tournament_id=tournaments.id join series_metadata on series.id=series_metadata.series_id where tournaments.event_id=:event_id order by series.id """ participants_query = """ select series_id, participants.name, score, winner from participants join series on participants.series_id=series.id join rounds on series.round_id=rounds.id join tournaments on rounds.tournament_id=tournaments.id where tournaments.event_id=:event_id """ maps_query = """ select map_name, avg(matches.duration)::interval(0) as avg_duration, count(distinct match_id) as matches, max(players.dataset_id) as dataset_id, round(count(distinct match_id)/(select count(*) from matches where event_id=:event_id)::numeric, 2) as played_percent, mode() within group (order by civilizations.id) as most_played_civ_id, mode() within group (order by civilizations.name) as most_played_civ_name from players join civilizations on civilizations.dataset_id=players.dataset_id and civilizations.id = players.civilization_id join matches on players.match_id=matches.id where event_id=:event_id group by map_name order by count(distinct match_id) desc """ players_query = """ select max(players.name) as name, max(players.platform_id) as platform_id, max(user_id) as user_id, max(people.id) as person_id, max(people.name) as person_name, max(people.country) as country, count(*) as matches, round(sum(players.winner::int)/count(*)::numeric, 2) as win_percent, max(matches.dataset_id) as dataset_id, avg(matches.duration)::interval(0) as avg_duration, mode() within group (order by civilizations.id) as most_played_civ_id, mode() within group (order by civilizations.name) as most_played_civ_name, mode() within group (order by matches.map_name) as most_played_map from players join civilizations on civilizations.dataset_id=players.dataset_id and civilizations.id = players.civilization_id join matches on players.match_id=matches.id left join users on players.platform_id=users.platform_id and players.user_id=users.id left join people on users.person_id=people.id where event_id=:event_id group by case when people.id is not null then people.id::varchar else players.name end order by count(*) desc, sum(players.winner::int)/count(*)::numeric desc """ civilizations_query = """ select civilizations.id, civilizations.name, avg(matches.duration)::interval(0) as avg_duration, count(distinct match_id) as matches, max(players.dataset_id) as dataset_id, count(*) as matches, round(sum(players.winner::int)/count(*)::numeric, 2) as win_percent, mode() within group (order by matches.map_name) as most_played_map from players join civilizations on civilizations.dataset_id=players.dataset_id and civilizations.id = players.civilization_id join matches on players.match_id=matches.id where event_id=:event_id group by civilizations.id, civilizations.name order by count(distinct match_id) desc ; """ event, tournaments, series, maps, civilizations, players, participants = await asyncio.gather( database.fetch_one(events_query, values={'event_id': event_id}), database.fetch_all(tournaments_query, values={'event_id': event_id}), database.fetch_all(series_query, values={'event_id': event_id}), database.fetch_all(maps_query, values={'event_id': event_id}), database.fetch_all(civilizations_query, values={'event_id': event_id}), database.fetch_all(players_query, values={'event_id': event_id}), database.fetch_all(participants_query, values={'event_id': event_id}) ) series_data = by_key(series, 'tournament_id') participant_data = by_key(participants, 'series_id') return dict( event, maps=[ dict( map=dict( name=m['map_name'] ), average_duration=m['avg_duration'], match_count=m['matches'], played_percent=m['played_percent'], most_played_civilization=dict( id=m['most_played_civ_id'], name=m['most_played_civ_name'], dataset_id=m['dataset_id'] ) ) for m in maps ], civilizations=[ dict( civilization=dict( id=c['id'], name=c['name'], dataset_id=c['dataset_id'] ), average_duration=c['avg_duration'], match_count=c['matches'], win_percent=c['win_percent'], most_played_map=c['most_played_map'] ) for c in civilizations ], players=[ dict( player=dict( name=player['name'], user=dict( id=player['user_id'], name=player['name'], platform_id=player['platform_id'], person=dict( id=player['person_id'], country=player['country'], name=player['person_name'] ) if player['person_id'] else None ) if player['user_id'] else None ), match_count=player['matches'], win_percent=player['win_percent'], average_duration=player['avg_duration'], most_played_map=player['most_played_map'], most_played_civilization=dict( id=player['most_played_civ_id'], name=player['most_played_civ_name'], dataset_id=player['dataset_id'] ) ) for player in players ], tournaments=[dict( tournament, series=[dict( series_, participants=participant_data[series_['id']], ) for series_ in series_data[tournament['id']]] ) for tournament in tournaments] ) @cached(warm=True, ttl=86400) async def get_events(database): """Get events.""" events_query = 'select id, name, year from events order by year, name' events = await database.fetch_all(events_query) return [dict(e) for e in events] def compute_participants(matches, challonge_data): """Compute series participants. Iterate all matches and players to create a graph. Apply connected components algorithm to resolve distinct participant groups over all matches. Sort participant groups by number of wins to correlate with Challonge participant data (which also includes number of wins). Note that edge cases exist that are not covered. For example, teams sometimes field a 1v1 player for a single match. If neither player in the 1v1 match takes part in any other matches, the players can't be placed in a participant group and their win is not counted. There are two consequences: 1. Not counting a win may make the number of wins between participants even, in which case we don't know which participant group won the series. 2. Not grouping a player means the participant player list will be incomplete. """ graph = networkx.DiGraph() win_id = 0 platform_ids = [] name_to_user = {} for match in matches: # Record a win win_id += 1 graph.add_node(win_id, type='win') # Record platform ID platform_ids.append(match['platform_id']) # Add node for each player for player in match['players']: name_to_user[player['name']] = player['user_id'] graph.add_node(player['name'], type='player') # Can happen for incomplete matches if match['winning_team'] is None: continue # Connect winning players to recorded win for player in match['winning_team']['players']: graph.add_edge(player['name'], win_id) # Connect all players on the same team for team in match['teams']: for i in team['players']: for j in team['players']: graph.add_edge(i['name'], j['name']) mgz_data = [{ 'wins': len([node for node in g if graph.nodes[node]['type'] == 'win']), 'players': [node for node in g if graph.nodes[node]['type'] == 'player'] } for g in networkx.weakly_connected_components(graph)] return [{ 'user_ids': [name_to_user[n] for n in mgz['players']], 'winner': challonge['winner'], 'name': challonge['name'], 'score': challonge['score'], 'platform_id': platform_ids[0] } for mgz, challonge in zip( sorted(mgz_data, key=lambda k: -1 * k['wins']), sorted(challonge_data, key=lambda k: -1 * k['score'] if k['score'] else 0) )]
41.847518
149
0.614185
"""Events.""" import asyncio import networkx from aocrecs.cache import cached from aocrecs.util import by_key def get_sides(matches, participants): """Get users per side given matches.""" users = {} for match in matches: users.update({ p['user_id']: dict( id=p['user_id'], name=p['user_name'] or p['name'], platform_id=p['platform_id'] ) for p in match['players'] }) return [ dict(p, users=[users[u] for u in p['user_ids'] if u]) for p in compute_participants(matches, participants) ] async def get_series(database, series_id): """Get a series.""" series_query = """ select series.id, series.played, series_metadata.name, rounds.tournament_id, tournaments.id as tournament_id, tournaments.name as tournament_name, events.id as event_id, events.name as event_name from series join rounds on series.round_id=rounds.id join series_metadata on series.id=series_metadata.series_id join tournaments on rounds.tournament_id=tournaments.id join events on tournaments.event_id=events.id where series.id=:id """ participants_query = 'select series_id, name, score, winner from participants where series_id=:id' matches_query = 'select id, series_id from matches where series_id=:id' values = {'id': series_id} series, participants, matches = await asyncio.gather( database.fetch_one(series_query, values=values), database.fetch_all(participants_query, values=values), database.fetch_all(matches_query, values=values) ) return dict( series, participants=list(map(dict, participants)), match_ids=list(map(lambda m: m['id'], matches)), tournament=dict( id=series['tournament_id'], name=series['tournament_name'], event=dict( id=series['event_id'], name=series['event_name'] ) ) ) @cached(ttl=86400) async def get_event(database, event_id): """Get an event.""" events_query = 'select id, name, year from events where id=:event_id' tournaments_query = 'select id, event_id, name from tournaments where event_id=:event_id' series_query = """ select series.id, series.played, series_metadata.name, rounds.tournament_id from series join rounds on series.round_id=rounds.id join tournaments on rounds.tournament_id=tournaments.id join series_metadata on series.id=series_metadata.series_id where tournaments.event_id=:event_id order by series.id """ participants_query = """ select series_id, participants.name, score, winner from participants join series on participants.series_id=series.id join rounds on series.round_id=rounds.id join tournaments on rounds.tournament_id=tournaments.id where tournaments.event_id=:event_id """ maps_query = """ select map_name, avg(matches.duration)::interval(0) as avg_duration, count(distinct match_id) as matches, max(players.dataset_id) as dataset_id, round(count(distinct match_id)/(select count(*) from matches where event_id=:event_id)::numeric, 2) as played_percent, mode() within group (order by civilizations.id) as most_played_civ_id, mode() within group (order by civilizations.name) as most_played_civ_name from players join civilizations on civilizations.dataset_id=players.dataset_id and civilizations.id = players.civilization_id join matches on players.match_id=matches.id where event_id=:event_id group by map_name order by count(distinct match_id) desc """ players_query = """ select max(players.name) as name, max(players.platform_id) as platform_id, max(user_id) as user_id, max(people.id) as person_id, max(people.name) as person_name, max(people.country) as country, count(*) as matches, round(sum(players.winner::int)/count(*)::numeric, 2) as win_percent, max(matches.dataset_id) as dataset_id, avg(matches.duration)::interval(0) as avg_duration, mode() within group (order by civilizations.id) as most_played_civ_id, mode() within group (order by civilizations.name) as most_played_civ_name, mode() within group (order by matches.map_name) as most_played_map from players join civilizations on civilizations.dataset_id=players.dataset_id and civilizations.id = players.civilization_id join matches on players.match_id=matches.id left join users on players.platform_id=users.platform_id and players.user_id=users.id left join people on users.person_id=people.id where event_id=:event_id group by case when people.id is not null then people.id::varchar else players.name end order by count(*) desc, sum(players.winner::int)/count(*)::numeric desc """ civilizations_query = """ select civilizations.id, civilizations.name, avg(matches.duration)::interval(0) as avg_duration, count(distinct match_id) as matches, max(players.dataset_id) as dataset_id, count(*) as matches, round(sum(players.winner::int)/count(*)::numeric, 2) as win_percent, mode() within group (order by matches.map_name) as most_played_map from players join civilizations on civilizations.dataset_id=players.dataset_id and civilizations.id = players.civilization_id join matches on players.match_id=matches.id where event_id=:event_id group by civilizations.id, civilizations.name order by count(distinct match_id) desc ; """ event, tournaments, series, maps, civilizations, players, participants = await asyncio.gather( database.fetch_one(events_query, values={'event_id': event_id}), database.fetch_all(tournaments_query, values={'event_id': event_id}), database.fetch_all(series_query, values={'event_id': event_id}), database.fetch_all(maps_query, values={'event_id': event_id}), database.fetch_all(civilizations_query, values={'event_id': event_id}), database.fetch_all(players_query, values={'event_id': event_id}), database.fetch_all(participants_query, values={'event_id': event_id}) ) series_data = by_key(series, 'tournament_id') participant_data = by_key(participants, 'series_id') return dict( event, maps=[ dict( map=dict( name=m['map_name'] ), average_duration=m['avg_duration'], match_count=m['matches'], played_percent=m['played_percent'], most_played_civilization=dict( id=m['most_played_civ_id'], name=m['most_played_civ_name'], dataset_id=m['dataset_id'] ) ) for m in maps ], civilizations=[ dict( civilization=dict( id=c['id'], name=c['name'], dataset_id=c['dataset_id'] ), average_duration=c['avg_duration'], match_count=c['matches'], win_percent=c['win_percent'], most_played_map=c['most_played_map'] ) for c in civilizations ], players=[ dict( player=dict( name=player['name'], user=dict( id=player['user_id'], name=player['name'], platform_id=player['platform_id'], person=dict( id=player['person_id'], country=player['country'], name=player['person_name'] ) if player['person_id'] else None ) if player['user_id'] else None ), match_count=player['matches'], win_percent=player['win_percent'], average_duration=player['avg_duration'], most_played_map=player['most_played_map'], most_played_civilization=dict( id=player['most_played_civ_id'], name=player['most_played_civ_name'], dataset_id=player['dataset_id'] ) ) for player in players ], tournaments=[dict( tournament, series=[dict( series_, participants=participant_data[series_['id']], ) for series_ in series_data[tournament['id']]] ) for tournament in tournaments] ) @cached(warm=True, ttl=86400) async def get_events(database): """Get events.""" events_query = 'select id, name, year from events order by year, name' events = await database.fetch_all(events_query) return [dict(e) for e in events] def compute_participants(matches, challonge_data): """Compute series participants. Iterate all matches and players to create a graph. Apply connected components algorithm to resolve distinct participant groups over all matches. Sort participant groups by number of wins to correlate with Challonge participant data (which also includes number of wins). Note that edge cases exist that are not covered. For example, teams sometimes field a 1v1 player for a single match. If neither player in the 1v1 match takes part in any other matches, the players can't be placed in a participant group and their win is not counted. There are two consequences: 1. Not counting a win may make the number of wins between participants even, in which case we don't know which participant group won the series. 2. Not grouping a player means the participant player list will be incomplete. """ graph = networkx.DiGraph() win_id = 0 platform_ids = [] name_to_user = {} for match in matches: # Record a win win_id += 1 graph.add_node(win_id, type='win') # Record platform ID platform_ids.append(match['platform_id']) # Add node for each player for player in match['players']: name_to_user[player['name']] = player['user_id'] graph.add_node(player['name'], type='player') # Can happen for incomplete matches if match['winning_team'] is None: continue # Connect winning players to recorded win for player in match['winning_team']['players']: graph.add_edge(player['name'], win_id) # Connect all players on the same team for team in match['teams']: for i in team['players']: for j in team['players']: graph.add_edge(i['name'], j['name']) mgz_data = [{ 'wins': len([node for node in g if graph.nodes[node]['type'] == 'win']), 'players': [node for node in g if graph.nodes[node]['type'] == 'player'] } for g in networkx.weakly_connected_components(graph)] return [{ 'user_ids': [name_to_user[n] for n in mgz['players']], 'winner': challonge['winner'], 'name': challonge['name'], 'score': challonge['score'], 'platform_id': platform_ids[0] } for mgz, challonge in zip( sorted(mgz_data, key=lambda k: -1 * k['wins']), sorted(challonge_data, key=lambda k: -1 * k['score'] if k['score'] else 0) )]
0
0
0
1e4aa6c0af4512f3bea0466bf347d6d2bb5d4aa6
225
py
Python
lib/uModBus/defconvert.py
mbrizuelaarg/isp_node_v3
0656c8fed380ed7db8970113aae63a2d155e3420
[ "MIT" ]
null
null
null
lib/uModBus/defconvert.py
mbrizuelaarg/isp_node_v3
0656c8fed380ed7db8970113aae63a2d155e3420
[ "MIT" ]
null
null
null
lib/uModBus/defconvert.py
mbrizuelaarg/isp_node_v3
0656c8fed380ed7db8970113aae63a2d155e3420
[ "MIT" ]
null
null
null
# Coneversiones de unidades import struct import binascii
22.5
60
0.675556
# Coneversiones de unidades import struct import binascii def float_to_hex(f): return hex(struct.unpack('<I', struct.pack('<f', f))[0]) def double_to_hex(f): return hex(struct.unpack('<Q', struct.pack('<d', f))[0])
121
0
46
d6406d3649d44ec3b677763c0ad156e48067ec63
3,959
py
Python
MiniPlayerViewWidget.py
neoaggelos/qcmus
b584b3de55efe24a2fab35f7b29eeef6148428f4
[ "MIT" ]
3
2018-05-29T07:02:03.000Z
2021-10-30T16:25:56.000Z
MiniPlayerViewWidget.py
neoaggelos/qcmus
b584b3de55efe24a2fab35f7b29eeef6148428f4
[ "MIT" ]
null
null
null
MiniPlayerViewWidget.py
neoaggelos/qcmus
b584b3de55efe24a2fab35f7b29eeef6148428f4
[ "MIT" ]
null
null
null
# MiniPlayerViewWidget.py from PyQt5.QtCore import * from PyQt5.QtWidgets import * from PyQt5.QtGui import * import sys, subprocess, time, threading, datetime, os, mutagen from _prefs import miniplayer_coversize, cmus_remote_cmd, player_coversize coversize = miniplayer_coversize
35.348214
120
0.610255
# MiniPlayerViewWidget.py from PyQt5.QtCore import * from PyQt5.QtWidgets import * from PyQt5.QtGui import * import sys, subprocess, time, threading, datetime, os, mutagen from _prefs import miniplayer_coversize, cmus_remote_cmd, player_coversize coversize = miniplayer_coversize class MiniPlayerViewWidget(QWidget): def __init__(self, parent): super().__init__() self.parent = parent # layout self.setLayout(QHBoxLayout()) self.layout().setContentsMargins(0,0,20,0) self.layout().setSpacing(20) self.layout().setAlignment(Qt.AlignLeft) # album art self.albumart_label = QLabel() self.albumart_label.setAlignment(Qt.AlignCenter) self.albumart_label.setFixedSize(QSize(coversize, coversize)) #self.albumart_label.setStyleSheet('QLabel { border: 1px solid black; }') self.layout().addWidget(self.albumart_label) self.layout().setAlignment(self.albumart_label, Qt.AlignLeft) songinfo_layout = QVBoxLayout() songinfo_layout.setSpacing(1) self.layout().addLayout(songinfo_layout) self.layout().setAlignment(songinfo_layout, Qt.AlignLeft) def create_label(text, bold, scale): if bold: text = '<b>{}</b>'.format(text) label = QLabel(text) font = label.font() font.setPointSize(font.pointSize() * scale) label.setFont(font) songinfo_layout.addWidget(label) return label self.title_label = create_label('', True, 1.4) self.artist_label = create_label('', False, 1.0) # buttons self.layout().addStretch(1) buttons_layout = QHBoxLayout() self.layout().addLayout(buttons_layout) self.layout().setAlignment(buttons_layout, Qt.AlignRight) def create_button(icon, scale, callback): icon = QIcon.fromTheme(icon) button = QPushButton(icon, '') button.setFixedSize(button.sizeHint() * scale) button.clicked.connect(callback) buttons_layout.addWidget(button) return button self.prev_button = create_button('media-skip-backward', 1.0, self.prevButtonPressed) self.play_button = create_button(self.playButtonIcon(), 1.3, self.playButtonPressed) self.next_button = create_button('media-skip-forward', 1.0, self.nextButtonPressed) self.refresh(True) def refresh(self, force=False): self.play_button.setIcon(QIcon.fromTheme(self.playButtonIcon())) if self.parent.cmus.has_changed or force: self.title_label.setText(self.parent.cmus.title) self.artist_label.setText(self.parent.cmus.artist) if self.parent.cmus.albumart != []: pix = QPixmap() pix.loadFromData(self.parent.cmus.albumart.data, self.parent.cmus.albumart.mime) self.albumart_label.setPixmap(pix.scaled(coversize, coversize, transformMode = Qt.SmoothTransformation)) else: self.albumart_label.clear() def playButtonIcon(self): name = 'media-playback-start' if self.parent.cmus.status == 'playing': name = 'media-playback-pause' return name def playButtonPressed(self): subprocess.call([cmus_remote_cmd, "-u"]) def nextButtonPressed(self): subprocess.call([cmus_remote_cmd, "-n"]) def prevButtonPressed(self): subprocess.call([cmus_remote_cmd, "-r"]) def mouseReleaseEvent(self, event): if event.button() == Qt.LeftButton: self.parent.centralWidget().setCurrentWidget(self.parent.nowplaying_tab) event.accept()
3,421
15
239
1073dbfbefe70f8b5ce421cb36d8c129550ec237
1,420
py
Python
src/flake8_absolute_import/core.py
bskinn/flake8-absolute-import
18c97a5da14717ad4ed079eaec526826be7bf16c
[ "MIT" ]
10
2019-09-06T21:51:43.000Z
2022-03-26T12:27:16.000Z
src/flake8_absolute_import/core.py
bskinn/flake8-absolute-import
18c97a5da14717ad4ed079eaec526826be7bf16c
[ "MIT" ]
12
2019-09-06T19:15:52.000Z
2021-12-05T02:05:10.000Z
src/flake8_absolute_import/core.py
bskinn/flake8-absolute-import
18c97a5da14717ad4ed079eaec526826be7bf16c
[ "MIT" ]
1
2020-06-13T20:23:42.000Z
2020-06-13T20:23:42.000Z
r"""*Main implementation file for* ``flake8-absolute-import``. flake8 plugin to require absolute imports **Author** Brian Skinn (bskinn@alum.mit.edu) **File Created** 6 Sep 2019 **Copyright** \(c) Brian Skinn 2019-2021 **Source Repository** http://github.com/bskinn/flake8-absolute-import **License** The MIT License; see |license_txt|_ for full license terms **Members** """ import ast from flake8_absolute_import.version import __version__ ABS101 = "ABS101 Relative import found" class Visitor(ast.NodeVisitor): """NodeVisitor to report relative imports.""" def __init__(self): """Create a Visitor with empty errors list.""" self.errors = [] def visit_ImportFrom(self, node): # noqa: N802 """Implement check for relative import.""" if node.level > 0: self.errors.append((node.lineno, node.col_offset, ABS101)) self.generic_visit(node) class Plugin: """Core plugin class for flake8-absolute-import.""" name = "flake8-absolute-import" version = __version__ def __init__(self, tree): """Create plugin instance from the provided AST.""" self._tree = tree def run(self): """Traverse the AST and collect the errors.""" visitor = Visitor() visitor.visit(self._tree) for line, col, msg in visitor.errors: yield line, col, msg, type(self)
22.1875
70
0.647887
r"""*Main implementation file for* ``flake8-absolute-import``. flake8 plugin to require absolute imports **Author** Brian Skinn (bskinn@alum.mit.edu) **File Created** 6 Sep 2019 **Copyright** \(c) Brian Skinn 2019-2021 **Source Repository** http://github.com/bskinn/flake8-absolute-import **License** The MIT License; see |license_txt|_ for full license terms **Members** """ import ast from flake8_absolute_import.version import __version__ ABS101 = "ABS101 Relative import found" class Visitor(ast.NodeVisitor): """NodeVisitor to report relative imports.""" def __init__(self): """Create a Visitor with empty errors list.""" self.errors = [] def visit_ImportFrom(self, node): # noqa: N802 """Implement check for relative import.""" if node.level > 0: self.errors.append((node.lineno, node.col_offset, ABS101)) self.generic_visit(node) class Plugin: """Core plugin class for flake8-absolute-import.""" name = "flake8-absolute-import" version = __version__ def __init__(self, tree): """Create plugin instance from the provided AST.""" self._tree = tree def run(self): """Traverse the AST and collect the errors.""" visitor = Visitor() visitor.visit(self._tree) for line, col, msg in visitor.errors: yield line, col, msg, type(self)
0
0
0
885c791a63037ad680d9dcaab6b342c198504176
732
py
Python
urls.py
yoramk2/halolib
c05bc9f9c37d09700c5a42dcd3b9a74c0c5c0c29
[ "MIT" ]
2
2020-07-22T13:28:47.000Z
2021-02-08T04:38:06.000Z
urls.py
yoramk2/halolib
c05bc9f9c37d09700c5a42dcd3b9a74c0c5c0c29
[ "MIT" ]
2
2021-06-10T20:59:03.000Z
2021-11-15T17:47:59.000Z
urls.py
yoramk2/halolib
c05bc9f9c37d09700c5a42dcd3b9a74c0c5c0c29
[ "MIT" ]
1
2021-02-08T04:38:09.000Z
2021-02-08T04:38:09.000Z
from django.conf.urls import * # Uncomment the next two lines to enable the admin: from django.contrib import admin admin.autodiscover() # from django.conf import settings urlpatterns = [ # Example: url(r'^', include('halolib.halolib.urls')), #url(r'^(?P<url>.*)$', proxy),#, ProxyLink.as_view(), name='proxy'), # Uncomment the admin/doc line below to enable admin documentation: #url(r'^admin/doc/', include('django.contrib.admindocs.urls')), # Uncomment the next line to enable the admin: #url(r'^admin/', include(admin.site.urls)), #url(r'^api-token-auth/', include('rest_framework.authtoken.views.obtain_auth_token')), ] #+ static(settings.STATIC_URL, document_root=settings.STATIC_ROOT)
30.5
91
0.698087
from django.conf.urls import * # Uncomment the next two lines to enable the admin: from django.contrib import admin admin.autodiscover() # from django.conf import settings urlpatterns = [ # Example: url(r'^', include('halolib.halolib.urls')), #url(r'^(?P<url>.*)$', proxy),#, ProxyLink.as_view(), name='proxy'), # Uncomment the admin/doc line below to enable admin documentation: #url(r'^admin/doc/', include('django.contrib.admindocs.urls')), # Uncomment the next line to enable the admin: #url(r'^admin/', include(admin.site.urls)), #url(r'^api-token-auth/', include('rest_framework.authtoken.views.obtain_auth_token')), ] #+ static(settings.STATIC_URL, document_root=settings.STATIC_ROOT)
0
0
0
45df360af4bd2108103929d449a6b5f49a957b14
13,766
py
Python
web/kathe.py
avuko/kathe
d7f80965484fb83f47e4f7cb78c424ff8722a319
[ "BSD-3-Clause" ]
21
2018-03-23T13:44:09.000Z
2022-01-19T01:16:06.000Z
web/kathe.py
avuko/kathe
d7f80965484fb83f47e4f7cb78c424ff8722a319
[ "BSD-3-Clause" ]
11
2019-07-29T12:57:41.000Z
2022-01-22T09:27:41.000Z
web/kathe.py
avuko/kathe
d7f80965484fb83f47e4f7cb78c424ff8722a319
[ "BSD-3-Clause" ]
5
2018-12-11T01:23:14.000Z
2021-09-16T06:16:21.000Z
#!/usr/bin/env python3 # -*- coding: utf-8 -*- """ This module is meant to be used together with the web app. For the stand alone CLI implementation, see parent directory. """ from datetime import datetime import ast import os import re import unicodedata import logging import defaults logger = logging.getLogger() try: import redis except ImportError: print('pip install redis') exit(1) try: import ssdeep except ImportError: """ if you get errors during the installation process, install these: sudo apt-get install python3 python-dev python3-dev build-essential libssl-dev libffi-dev libxml2-dev libxslt1-dev zlib1g-dev python-pip libfuzzy-dev """ print('pip install ssdeep') exit(1) # To start with, set all to None. inputname = None inputssdeep = None inputsha256 = None # set the DB number and host to the default value REDIS_DB = defaults.REDIS_DB REDIS_HOST = defaults.REDIS_HOST REDIS_PASS = defaults.REDIS_PASS # Connect to redis. # Also, convert all responses to strings, not bytes r = redis.StrictRedis(REDIS_HOST, 6379, db=REDIS_DB, password=REDIS_PASS, charset="utf-8", decode_responses=True) def remove_control_characters(s): """Some input (like filenames) has some really nasty control chars. This trick removes those (https://stackoverflow.com/a/19016117)""" return "".join(ch for ch in s if unicodedata.category(ch)[0] != "C") def replace_badchars(inputstring): """Stringing together '.replace' seems the fastest way to do this: https://stackoverflow.com/a/27086669. As the input is json, the "," does not nead special treatment """ blacklist = {':': '', '\\': '', '"': '', '\'': '', '|': '', ' ': '', '/': ''} for k in blacklist: inputstring = inputstring.replace(k, blacklist[k]) return inputstring def clean_context(contextstring): """Remove all troublesome characters from the context option. We need to do this to make splitting the strings by other tools reliable.""" clean_contextstring = replace_badchars(contextstring) # make string splitable on pipe symbol and turn to lowercase clean_contextstring = clean_contextstring.encode('utf-8', 'ignore') clean_contextstring = clean_contextstring.decode('utf-8', 'ignore') clean_contextstring = clean_contextstring.replace(',', '|').lower() clean_contextstring = remove_control_characters(clean_contextstring) return clean_contextstring def clean_name(filename): """Remove pathname from the input and characters which could cause issues with stringparsing. """ # XXX in the case of directories, we'd want dirnames etc. cleanname = os.path.basename(filename) cleanname = replace_badchars(cleanname) cleanname = cleanname.encode('utf-8', 'ignore').decode('utf-8', 'ignore') cleanname = remove_control_characters(cleanname) # this turns a comma seperated list into the actual context list cleanname = cleanname.replace(',', '|').lower() return (cleanname) # The below two functions (preprocess_ssdeep and get_all_7_char_rolling_window) # originally come from Brian Wallace: # https://www.virusbulletin.com/virusbulletin/2015/11/\ # optimizing-ssdeep-use-scale def get_all_7_char_rolling_window(bs, h): """return a set containing the 7 character length strings (rolling window) of the ssdeep string for both block sizes, with the block size prepended. Ssdeep only does a compare if at least 7 characters match between strings. These are the keys which hold the sibling values.""" return set((str(bs) + ":" + h[i:i + 7]) for i in range(len(h) - 6)) def preprocess_ssdeep(h): """The ssdeep string is split into block_size, ssdeep, ssdeep_double_block. Before returning a set of all the rolling_window for size and double size, all the repeated character sequences of more than 3 are reduced to max 3. This is something the ssdeep algoritm does internally too. """ h_rolling_window = set() block_size, h = h.split(":", 1) block_size = int(block_size) # Reduce any sequence of the same char greater than 3 to 3 for c in set(list(h)): while c * 4 in h: h = h.replace(c * 4, c * 3) block_data, double_block_data = h.split(":") h_rolling_window.update(get_all_7_char_rolling_window(block_size, block_data)) h_rolling_window.update(get_all_7_char_rolling_window(block_size * 2, double_block_data)) return h_rolling_window def get_ssdeep_sets(rolling_window_ssdeep, inputssdeep): """ create a set of ssdeep hashes matching filesssdeep from the rolling_window set, which does not contain inputssdeep hash itself. Using '.discard' to silently return without inputssdeep.""" siblings_set = r.smembers(rolling_window_ssdeep) siblings_set.discard(inputssdeep) return siblings_set def add_ssdeep_to_rolling_window(rolling_window_ssdeep, inputssdeep): """This function adds the inputssdeep hash to all the matching rolling_windows.""" r.sadd(rolling_window_ssdeep, inputssdeep) def add_info(inputname, inputsha256, inputssdeep, inputcontext): """The four info fields contain a set (read: unique) of information about the added entity. This way sha256/inputname/inputssdeep are linked and retrievable.""" inputcontext = clean_context(inputcontext) splitcontext = inputcontext.split('|') inputsha256 = inputsha256.lower() r.sadd('info:inputname:{}'.format(inputname), 'sha256:{}:ssdeep:{}:context:{}'.format(inputsha256, inputssdeep, inputcontext)) r.sadd('info:ssdeep:{}'.format(inputssdeep), 'sha256:{}:context:{}:inputname:{}'.format(inputsha256, inputcontext, inputname)) r.sadd('info:sha256:{}'.format(inputsha256), 'ssdeep:{}:context:{}:inputname:{}'.format(inputssdeep, inputcontext, inputname)) r.sadd("hashes:ssdeep", '{}'.format(inputssdeep)) r.sadd("names:inputname", '{}'.format(inputname)) # pull all most significant contexts from an ssdeep and, if they are # different, add the combined names to splitcontext for inclusion in # "names:context". # Because the ssdeeps are similar, this will make different naming # schemes explicit. for contexts in r.smembers('info:ssdeep:{}'.format(inputssdeep)): context = contexts.split(':')[3].split('|')[0] if context != splitcontext[0]: context = '/'.join(sorted([context, splitcontext[0]])) splitcontext.append(context) for singlecontext in splitcontext: # add unique key to set with 'incr 1' to keep track of occurance # and create a ranked set. Rank may chance over time, but that # is not a problem when updates do not happen inbetween calls r.zincrby("names:context", '{}'.format(singlecontext), amount=1) info_string = 'sha256:{}:ssdeep:{}:inputname:{}:inputcontext:{}' r.sadd('info:context:{}'.format(singlecontext), info_string.format(inputsha256, inputssdeep, inputname, inputcontext)) # timestamp is used for caching of query results. It is updated after # every addition so it never goes stale. # keep a log of timestamps r.sadd("timestamplog", r.get("timestamp")) logger.debug(timestamp()) r.set("timestamp", timestamp()) logger.debug(r.get("timestamp")) def get_allsha256_for_ssdeep(ssdeep): """function which retrieves a string of unique sha256 hashes for an ssdeep hash. Theoretically a single ssdeep hash could match multiple different inputs, if the differences are insignificant.""" allsha256s = [allsha256.split(':')[1] for allsha256 in r.smembers('info:ssdeep:{}'.format(ssdeep))] allsha256s = str.join(':', set(allsha256s)) logger.debug(f"=== DEBUG === : allsha256s: {allsha256s}") return allsha256s def get_allcontext_for_ssdeep(ssdeep): """function which retrieves a string of unique context strings for an ssdeep hash. Theoretically a single ssdeep hash could match multiple different contexts, based on how they are added to the dataset.""" allcontexts = [allcontext.split(':')[3] for allcontext in r.smembers('info:ssdeep:{}'.format(ssdeep))] allcontexts = str.join(':', set(allcontexts)) logger.debug(f"=== DEBUG === : allcontexts: {allcontexts}") return allcontexts def return_results(inputname, inputsha256, inputssdeep, inputcontext): """The results should be in json. But the json.dumps function cannot deal with python sets, so we turn them into lists. additionally we retrieve other files with the same sha256 and, last but not least, it siblings (partially matching ssdeep hashes).""" info = dict() info['inputname'] = inputname info['sha256'] = inputsha256.lower() info['ssdeep'] = inputssdeep info['context'] = inputcontext info['other_inputnames'] = [inputnames.split(':')[-1] for inputnames in r.smembers('info:sha256:{}'.format(inputsha256)) if inputnames.split(':')[-1] not in inputname] info['siblings'] = list(r.zrangebyscore(inputssdeep, min=0, max='+inf', withscores=True)) return(info) def new_hash(inputsha256): """ To speed things up, we take a different path if the file is already known. return True if new, False if the hash is already known.""" inputsha256 = inputsha256.lower() if r.sismember("hashes:sha256", '{}'.format(inputsha256)): new = False else: new = True return new def rest_add(info_object): """This function should receive a list of dictionaries. Each dictionary must consist of: {"inputname": <>, "sha256": <>, "ssdeep": <>, "contexts": ["<>", "<>", "<>"]} The most important context must be the first in the list.""" logger.debug(f"=== DEBUG === : ingesting info_object: {info_object}") # sanity check for rest_info in info_object: inputname = clean_name(rest_info['inputname']) if check_sha256(rest_info['sha256']): input_sha256 = rest_info['sha256'].lower() else: return False if check_ssdeep(rest_info['ssdeep']): input_ssdeep = rest_info['ssdeep'] else: return False if len(rest_info['contexts']) == 0: return False contexts = list(map(lambda x: clean_context(x), rest_info['contexts'])) input_contexts = ','.join(contexts) add_ssdeep_to_db(inputname, input_sha256, input_ssdeep, input_contexts) return True
40.369501
86
0.645576
#!/usr/bin/env python3 # -*- coding: utf-8 -*- """ This module is meant to be used together with the web app. For the stand alone CLI implementation, see parent directory. """ from datetime import datetime import ast import os import re import unicodedata import logging import defaults logger = logging.getLogger() try: import redis except ImportError: print('pip install redis') exit(1) try: import ssdeep except ImportError: """ if you get errors during the installation process, install these: sudo apt-get install python3 python-dev python3-dev build-essential libssl-dev libffi-dev libxml2-dev libxslt1-dev zlib1g-dev python-pip libfuzzy-dev """ print('pip install ssdeep') exit(1) # To start with, set all to None. inputname = None inputssdeep = None inputsha256 = None # set the DB number and host to the default value REDIS_DB = defaults.REDIS_DB REDIS_HOST = defaults.REDIS_HOST REDIS_PASS = defaults.REDIS_PASS # Connect to redis. # Also, convert all responses to strings, not bytes r = redis.StrictRedis(REDIS_HOST, 6379, db=REDIS_DB, password=REDIS_PASS, charset="utf-8", decode_responses=True) def timestamp(): ts = int(datetime.now().strftime("%s") + str(datetime.now().microsecond).zfill(6)) return ts def check_sha256(sha256_string): sha256check = re.compile(r"^[a-f0-9]{64}(:.+)?$", re.IGNORECASE) result = bool(sha256check.match(sha256_string)) return result def check_ssdeep(ssdeep_string): ssdeepcheck = re.compile(r"^[0-9]*\:[a-z0-9+/]*\:[a-z0-9+/]*$", re.IGNORECASE) result = bool(ssdeepcheck.match(ssdeep_string)) return result def remove_control_characters(s): """Some input (like filenames) has some really nasty control chars. This trick removes those (https://stackoverflow.com/a/19016117)""" return "".join(ch for ch in s if unicodedata.category(ch)[0] != "C") def replace_badchars(inputstring): """Stringing together '.replace' seems the fastest way to do this: https://stackoverflow.com/a/27086669. As the input is json, the "," does not nead special treatment """ blacklist = {':': '', '\\': '', '"': '', '\'': '', '|': '', ' ': '', '/': ''} for k in blacklist: inputstring = inputstring.replace(k, blacklist[k]) return inputstring def clean_context(contextstring): """Remove all troublesome characters from the context option. We need to do this to make splitting the strings by other tools reliable.""" clean_contextstring = replace_badchars(contextstring) # make string splitable on pipe symbol and turn to lowercase clean_contextstring = clean_contextstring.encode('utf-8', 'ignore') clean_contextstring = clean_contextstring.decode('utf-8', 'ignore') clean_contextstring = clean_contextstring.replace(',', '|').lower() clean_contextstring = remove_control_characters(clean_contextstring) return clean_contextstring def clean_name(filename): """Remove pathname from the input and characters which could cause issues with stringparsing. """ # XXX in the case of directories, we'd want dirnames etc. cleanname = os.path.basename(filename) cleanname = replace_badchars(cleanname) cleanname = cleanname.encode('utf-8', 'ignore').decode('utf-8', 'ignore') cleanname = remove_control_characters(cleanname) # this turns a comma seperated list into the actual context list cleanname = cleanname.replace(',', '|').lower() return (cleanname) # The below two functions (preprocess_ssdeep and get_all_7_char_rolling_window) # originally come from Brian Wallace: # https://www.virusbulletin.com/virusbulletin/2015/11/\ # optimizing-ssdeep-use-scale def get_all_7_char_rolling_window(bs, h): """return a set containing the 7 character length strings (rolling window) of the ssdeep string for both block sizes, with the block size prepended. Ssdeep only does a compare if at least 7 characters match between strings. These are the keys which hold the sibling values.""" return set((str(bs) + ":" + h[i:i + 7]) for i in range(len(h) - 6)) def preprocess_ssdeep(h): """The ssdeep string is split into block_size, ssdeep, ssdeep_double_block. Before returning a set of all the rolling_window for size and double size, all the repeated character sequences of more than 3 are reduced to max 3. This is something the ssdeep algoritm does internally too. """ h_rolling_window = set() block_size, h = h.split(":", 1) block_size = int(block_size) # Reduce any sequence of the same char greater than 3 to 3 for c in set(list(h)): while c * 4 in h: h = h.replace(c * 4, c * 3) block_data, double_block_data = h.split(":") h_rolling_window.update(get_all_7_char_rolling_window(block_size, block_data)) h_rolling_window.update(get_all_7_char_rolling_window(block_size * 2, double_block_data)) return h_rolling_window def get_ssdeep_sets(rolling_window_ssdeep, inputssdeep): """ create a set of ssdeep hashes matching filesssdeep from the rolling_window set, which does not contain inputssdeep hash itself. Using '.discard' to silently return without inputssdeep.""" siblings_set = r.smembers(rolling_window_ssdeep) siblings_set.discard(inputssdeep) return siblings_set def add_ssdeep_to_rolling_window(rolling_window_ssdeep, inputssdeep): """This function adds the inputssdeep hash to all the matching rolling_windows.""" r.sadd(rolling_window_ssdeep, inputssdeep) def add_info(inputname, inputsha256, inputssdeep, inputcontext): """The four info fields contain a set (read: unique) of information about the added entity. This way sha256/inputname/inputssdeep are linked and retrievable.""" inputcontext = clean_context(inputcontext) splitcontext = inputcontext.split('|') inputsha256 = inputsha256.lower() r.sadd('info:inputname:{}'.format(inputname), 'sha256:{}:ssdeep:{}:context:{}'.format(inputsha256, inputssdeep, inputcontext)) r.sadd('info:ssdeep:{}'.format(inputssdeep), 'sha256:{}:context:{}:inputname:{}'.format(inputsha256, inputcontext, inputname)) r.sadd('info:sha256:{}'.format(inputsha256), 'ssdeep:{}:context:{}:inputname:{}'.format(inputssdeep, inputcontext, inputname)) r.sadd("hashes:ssdeep", '{}'.format(inputssdeep)) r.sadd("names:inputname", '{}'.format(inputname)) # pull all most significant contexts from an ssdeep and, if they are # different, add the combined names to splitcontext for inclusion in # "names:context". # Because the ssdeeps are similar, this will make different naming # schemes explicit. for contexts in r.smembers('info:ssdeep:{}'.format(inputssdeep)): context = contexts.split(':')[3].split('|')[0] if context != splitcontext[0]: context = '/'.join(sorted([context, splitcontext[0]])) splitcontext.append(context) for singlecontext in splitcontext: # add unique key to set with 'incr 1' to keep track of occurance # and create a ranked set. Rank may chance over time, but that # is not a problem when updates do not happen inbetween calls r.zincrby("names:context", '{}'.format(singlecontext), amount=1) info_string = 'sha256:{}:ssdeep:{}:inputname:{}:inputcontext:{}' r.sadd('info:context:{}'.format(singlecontext), info_string.format(inputsha256, inputssdeep, inputname, inputcontext)) # timestamp is used for caching of query results. It is updated after # every addition so it never goes stale. # keep a log of timestamps r.sadd("timestamplog", r.get("timestamp")) logger.debug(timestamp()) r.set("timestamp", timestamp()) logger.debug(r.get("timestamp")) def get_allsha256_for_ssdeep(ssdeep): """function which retrieves a string of unique sha256 hashes for an ssdeep hash. Theoretically a single ssdeep hash could match multiple different inputs, if the differences are insignificant.""" allsha256s = [allsha256.split(':')[1] for allsha256 in r.smembers('info:ssdeep:{}'.format(ssdeep))] allsha256s = str.join(':', set(allsha256s)) logger.debug(f"=== DEBUG === : allsha256s: {allsha256s}") return allsha256s def get_allcontext_for_ssdeep(ssdeep): """function which retrieves a string of unique context strings for an ssdeep hash. Theoretically a single ssdeep hash could match multiple different contexts, based on how they are added to the dataset.""" allcontexts = [allcontext.split(':')[3] for allcontext in r.smembers('info:ssdeep:{}'.format(ssdeep))] allcontexts = str.join(':', set(allcontexts)) logger.debug(f"=== DEBUG === : allcontexts: {allcontexts}") return allcontexts def return_results(inputname, inputsha256, inputssdeep, inputcontext): """The results should be in json. But the json.dumps function cannot deal with python sets, so we turn them into lists. additionally we retrieve other files with the same sha256 and, last but not least, it siblings (partially matching ssdeep hashes).""" info = dict() info['inputname'] = inputname info['sha256'] = inputsha256.lower() info['ssdeep'] = inputssdeep info['context'] = inputcontext info['other_inputnames'] = [inputnames.split(':')[-1] for inputnames in r.smembers('info:sha256:{}'.format(inputsha256)) if inputnames.split(':')[-1] not in inputname] info['siblings'] = list(r.zrangebyscore(inputssdeep, min=0, max='+inf', withscores=True)) return(info) def new_hash(inputsha256): """ To speed things up, we take a different path if the file is already known. return True if new, False if the hash is already known.""" inputsha256 = inputsha256.lower() if r.sismember("hashes:sha256", '{}'.format(inputsha256)): new = False else: new = True return new def zrange_to_json(zrange_input): my_list = [] for kv in zrange_input: key_object = ast.literal_eval(kv[0]) for k in key_object: key_object[k]['count'] = int(kv[1]) jsonlist = [k, key_object[k]] my_list.append(jsonlist) return my_list def add_ssdeep_to_db(inputname, inputsha256, inputssdeep, inputcontext): inputsha256 = inputsha256.lower() # If the file is new, add all information if new_hash(inputsha256): inputname = clean_name(inputname) r.sadd("hashes:sha256", '{}'.format(inputsha256)) add_info(inputname, inputsha256, inputssdeep, inputcontext) ssdeep_compare = preprocess_ssdeep(inputssdeep) for rolling_window_ssdeep in ssdeep_compare: ssdeep_sets = get_ssdeep_sets(rolling_window_ssdeep, inputssdeep) add_ssdeep_to_rolling_window(rolling_window_ssdeep, inputssdeep) for sibling_ssdeep in ssdeep_sets: # Add sibling_ssdeep to the inputssdeep # XXX maybe add zscore check to optimise away the compare st = '{},{},{}' r.zadd(inputssdeep, float(ssdeep.compare(sibling_ssdeep, inputssdeep)), st.format(sibling_ssdeep, get_allsha256_for_ssdeep(sibling_ssdeep), get_allcontext_for_ssdeep(sibling_ssdeep))) # Add inputssdeep to sibling_ssdeep r.zadd(sibling_ssdeep, float(ssdeep.compare(inputssdeep, sibling_ssdeep)), st.format(inputssdeep, inputsha256, inputcontext.replace(',', '|'))) # or else, add only the new info else: inputname = clean_name(inputname) inputsha256 = inputsha256.lower() add_info(inputname, inputsha256, inputssdeep, inputcontext) def rest_add(info_object): """This function should receive a list of dictionaries. Each dictionary must consist of: {"inputname": <>, "sha256": <>, "ssdeep": <>, "contexts": ["<>", "<>", "<>"]} The most important context must be the first in the list.""" logger.debug(f"=== DEBUG === : ingesting info_object: {info_object}") # sanity check for rest_info in info_object: inputname = clean_name(rest_info['inputname']) if check_sha256(rest_info['sha256']): input_sha256 = rest_info['sha256'].lower() else: return False if check_ssdeep(rest_info['ssdeep']): input_ssdeep = rest_info['ssdeep'] else: return False if len(rest_info['contexts']) == 0: return False contexts = list(map(lambda x: clean_context(x), rest_info['contexts'])) input_contexts = ','.join(contexts) add_ssdeep_to_db(inputname, input_sha256, input_ssdeep, input_contexts) return True def incremental_add_to_zset(zset_name, zset_members): for zset_member in zset_members: r.zincrby(zset_name, zset_member, amount=1)
2,446
0
138
2c88d2e79259cfe90133daf6b9c7d0e294c455db
877
py
Python
main.py
mdarman187/website-blocker
c0191e9679f128aa95f7d5a5aff65f0a755b9ce3
[ "BSD-2-Clause" ]
1
2021-05-06T11:53:51.000Z
2021-05-06T11:53:51.000Z
main.py
mdarman187/website-blocker
c0191e9679f128aa95f7d5a5aff65f0a755b9ce3
[ "BSD-2-Clause" ]
null
null
null
main.py
mdarman187/website-blocker
c0191e9679f128aa95f7d5a5aff65f0a755b9ce3
[ "BSD-2-Clause" ]
1
2021-05-09T15:31:14.000Z
2021-05-09T15:31:14.000Z
import time from datetime import datetime as dt hp = r"C:\Windows\System32\drivers\hosts" #provide the proper host path according to yor system redirect = "127.0.0.1" web = ["www.youtube.com","www.facebook.com"] #add the website links in the list while True: if dt(dt.now().year, dt.now().month, dt.now().day,9) < dt.now() < dt(dt.now().year, dt.now().month, dt.now().day,18): print("Sorry you are not allowed...") with open(hp,'r+') as file: content = file.read() for site in web: if site in content: pass else: file.write(redirect+" "+site+"\n") else: with open(hp,'r+') as file: content = file.readlines() file.seek(0) for line in content: if not any(site in line for site in web): file.write(line) file.truncate() print("Access Granted....") time.sleep(5)
31.321429
119
0.600912
import time from datetime import datetime as dt hp = r"C:\Windows\System32\drivers\hosts" #provide the proper host path according to yor system redirect = "127.0.0.1" web = ["www.youtube.com","www.facebook.com"] #add the website links in the list while True: if dt(dt.now().year, dt.now().month, dt.now().day,9) < dt.now() < dt(dt.now().year, dt.now().month, dt.now().day,18): print("Sorry you are not allowed...") with open(hp,'r+') as file: content = file.read() for site in web: if site in content: pass else: file.write(redirect+" "+site+"\n") else: with open(hp,'r+') as file: content = file.readlines() file.seek(0) for line in content: if not any(site in line for site in web): file.write(line) file.truncate() print("Access Granted....") time.sleep(5)
0
0
0
a7745a192cb1bb04a777308a559458f888187067
7,501
py
Python
sedldata/migrate/versions/c2f1fafd2225_fix_bad_casting.py
OpenDataServices/sedldata
c7f3b13969bb9c9a494a5fadf1456cc85e9bf2cc
[ "BSD-3-Clause" ]
null
null
null
sedldata/migrate/versions/c2f1fafd2225_fix_bad_casting.py
OpenDataServices/sedldata
c7f3b13969bb9c9a494a5fadf1456cc85e9bf2cc
[ "BSD-3-Clause" ]
null
null
null
sedldata/migrate/versions/c2f1fafd2225_fix_bad_casting.py
OpenDataServices/sedldata
c7f3b13969bb9c9a494a5fadf1456cc85e9bf2cc
[ "BSD-3-Clause" ]
1
2019-01-20T19:39:11.000Z
2019-01-20T19:39:11.000Z
"""Fix bad casting Revision ID: c2f1fafd2225 Revises: bff84c33d64d Create Date: 2019-01-10 15:41:34.358222 """ from alembic import op import sqlalchemy as sa from sqlalchemy.dialects import postgresql # revision identifiers, used by Alembic. revision = 'c2f1fafd2225' down_revision = 'bff84c33d64d' branch_labels = None depends_on = None
39.898936
163
0.710039
"""Fix bad casting Revision ID: c2f1fafd2225 Revises: bff84c33d64d Create Date: 2019-01-10 15:41:34.358222 """ from alembic import op import sqlalchemy as sa from sqlalchemy.dialects import postgresql # revision identifiers, used by Alembic. revision = 'c2f1fafd2225' down_revision = 'bff84c33d64d' branch_labels = None depends_on = None def upgrade(): create_view_statements = ''' CREATE EXTENSION if not exists plpgsql; CREATE OR REPLACE FUNCTION convert_to_numeric(v_input text) RETURNS INTEGER AS $$ DECLARE v_num_value NUMERIC DEFAULT NULL; BEGIN BEGIN v_num_value := v_input::NUMERIC; EXCEPTION WHEN OTHERS THEN RETURN NULL; END; RETURN v_num_value; END; $$ LANGUAGE plpgsql; drop view collection_summary; drop view deal_summary; drop view offer_summary; create view offer_summary as select deal_table_id, count(*) offer_count, sum(case when offer.offer->'csuStandardMark' is not null AND (offer.offer->'csuStandardMark'->>'awarded')::bool then 1 else 0 end) csu_standard_mark_awarded, sum(coalesce(convert_to_numeric(offer.offer->>'investmentTarget'), 0)) investment_target, sum(coalesce(convert_to_numeric(offer.offer->>'minimumInvestmentTarget'), 0)) minimum_investment_target, sum(coalesce(convert_to_numeric(offer.offer->>'maximumInvestmentTarget'), 0)) maximum_investment_target from offer group by 1; drop view project_summary; create view project_summary as select project.deal_table_id, count(*) as project_count, sum(coalesce(convert_to_numeric(project->>'estimatedValue'), 0)) project_estimated_value, sum(coalesce(convert_to_numeric(project->>'raisedValue'), 0)) project_raised_value, sum(asset_count) asset_count, sum(asset_value) asset_value, sum(asset_purchase_price) asset_purchase_price, sum(asset_quantity) asset_quantity from project left join (select deal_table_id, count(*) as asset_count, sum(case when jsonb_typeof(asset.value->'totalValue') = 'number' then (asset.value->>'totalValue')::numeric else 0 end) asset_value, sum(case when jsonb_typeof(asset.value->'purcahasePrice') = 'number' then (asset.value->>'purcahasePrice')::numeric else 0 end) asset_purchase_price, sum(case when jsonb_typeof(asset.value->'quantity') = 'number' then (asset.value->>'quantity')::numeric else 0 end) asset_quantity from project, jsonb_array_elements(project->'assets') as asset group by 1 ) assets on assets.deal_table_id = project.deal_table_id group by 1; drop view grant_summary; create view grant_summary as select deal_table_id, count(*) grant_count, sum(case when ("grant"->>'isMatchFunding')::bool then 1 else 0 end) is_match_funding, sum(coalesce(convert_to_numeric("grant"."grant"->>'amountRequested'), 0)) grant_amount_requested, sum(coalesce(convert_to_numeric("grant"."grant"->>'amountCommitted'), 0)) grant_amount_committed, sum(coalesce(convert_to_numeric("grant"."grant"->>'amountDisbursed'), 0)) grant_amount_disbursed from "grant" group by 1; drop view equity_summary; create view equity_summary as select deal_table_id, count(*) equity_count, sum(coalesce(convert_to_numeric("equity"."equity"->>'value'), 0)) equity_value, sum(coalesce(convert_to_numeric("equity"."equity"->>'estimatedValue'), 0)) equity_estimated_value from "equity" group by 1; create view deal_summary as select id deal_table_id, deal_id, collection, deal->'recipientOrganization'->>'name' as recipient_organization_name, deal->'recipientOrganization'->>'id' as recipient_organization_id, deal->'arrangingOrganization'->>'name' as arraging_organization_name, deal->'arrangingOrganization'->>'id' as arraging_organization_id, deal->>'status' as status, deal->>'currency' currency, coalesce(convert_to_numeric(deal->>'estimatedValue')::numeric, 0) as estimated_value, coalesce(convert_to_numeric(deal->>'value')::numeric, 0) as value, coalesce(offer_count, 0) as offer_count, coalesce(csu_standard_mark_awarded, 0) as csu_standard_mark_awarded, coalesce(investment_target, 0) as investment_target, coalesce(minimum_investment_target, 0) as minimum_investment_target, coalesce(maximum_investment_target, 0) as maximum_investment_target, coalesce(project_estimated_value, 0) as project_estimated_value, coalesce(project_raised_value, 0) as project_raised_value, coalesce(project_count, 0) as project_count, coalesce(asset_purchase_price, 0) as asset_purchase_price, coalesce(asset_quantity, 0) as asset_quantity, coalesce(asset_count, 0) as asset_count, coalesce(asset_value, 0) as asset_value, coalesce(grant_count, 0) as grant_count, coalesce(is_match_funding, 0) as is_match_funding, coalesce(grant_amount_committed, 0) as grant_amount_committed, coalesce(grant_amount_disbursed, 0) as grant_amount_disbursed, coalesce(grant_amount_requested, 0) as grant_amount_requested, coalesce(equity_count, 0) as equity_count, coalesce(equity_value, 0) as equity_value, coalesce(equity_estimated_value, 0) as equity_estimated_value, coalesce(credit_count, 0) as credit_count, coalesce(credit_estimated_value, 0) as credit_estimated_value, deal from deal left join offer_summary os on os.deal_table_id = deal.id left join project_summary ps on ps.deal_table_id = deal.id left join grant_summary gs on gs.deal_table_id = deal.id left join equity_summary es on es.deal_table_id = deal.id left join credit_summary cs on cs.deal_table_id = deal.id; create view collection_summary as select collection, count(*) deal_count, sum(estimated_value) as estimated_value, sum(value) as value, sum(offer_count) as offer_count, sum(csu_standard_mark_awarded) as csu_standard_mark_awarded, sum(investment_target) as investment_target, sum(minimum_investment_target) as minimum_investment_target, sum(maximum_investment_target) as maximum_investment_target, sum(project_estimated_value) as project_estimated_value, sum(project_raised_value) as project_raised_value, sum(project_count) as project_count, sum(asset_purchase_price) as asset_purchase_price, sum(asset_quantity) as asset_quantity, sum(asset_count) as asset_count, sum(asset_value) as asset_value, sum(grant_count) as grant_count, sum(is_match_funding) as is_match_funding, sum(grant_amount_committed) as grant_amount_committed, sum(grant_amount_disbursed) as grant_amount_disbursed, sum(grant_amount_requested) as grant_amount_requested, sum(equity_count) as equity_count, sum(equity_value) as equity_value, sum(equity_estimated_value) as equity_estimated_value, sum(credit_count) as credit_count, sum(credit_estimated_value) as credit_estimated_value from deal_summary group by 1; ''' op.execute(create_view_statements) # ### end Alembic commands ### def downgrade(): pass
7,112
0
46
f20b9ad554df7baf34a36e8ad592de4e2452bc61
1,226
py
Python
src/HafrenHaver/pexels_pager.py
InnovAnon-Inc/HafrenHaver
5283ae3817c500f2365d1c8108dd3270aceb28fa
[ "Unlicense" ]
2
2020-11-09T19:30:26.000Z
2020-12-29T21:38:40.000Z
src/HafrenHaver/pexels_pager.py
InnovAnon-Inc/HafrenHaver
5283ae3817c500f2365d1c8108dd3270aceb28fa
[ "Unlicense" ]
null
null
null
src/HafrenHaver/pexels_pager.py
InnovAnon-Inc/HafrenHaver
5283ae3817c500f2365d1c8108dd3270aceb28fa
[ "Unlicense" ]
null
null
null
#! /usr/bin/env python3 from pager import Pager from pexels_results import PexelsResults if __name__ == "__main__": import requests main () quit ()
25.541667
53
0.563622
#! /usr/bin/env python3 from pager import Pager from pexels_results import PexelsResults class PexelsPager (Pager): def __init__ (self, session=None, *args, **kwargs): results = PexelsResults (session, *args, **kwargs) Pager.__init__ (self, results, *args, **kwargs) def req (self, **kwargs): rets = Pager.req (self, **kwargs) for ret in rets: vtotal, vtotal_hits, res, vcreds = ret vcreds = set (vcreds) vcreds.add (res['photographer']) res = res['url'] ret = vtotal, vtotal_hits, res, vcreds yield ret if __name__ == "__main__": import requests def main (): type1 = False with requests.Session () as s: if type1: r = PixabayPager (s) else: r = PexelsPager (s) if type1: p = r.req ( qs=('test',)) else: p = r.req (queries=('test',)) print (p) print () for h in p: print (h) print () if type1: p = r.req ( qs=('test',)) else: p = r.req (queries=('test',)) print (len (tuple (p))) print ("time : %s" % (r.get_time (),)) print ("limit : %s" % (r.get_limit (),)) print ("remaining: %s" % (r.get_remaining (),)) print ("reset : %s" % (r.get_reset (),)) main () quit ()
973
5
95
d1b3a101bc62092128d8f6f3b3d8380a8a37832c
641
py
Python
schemaregistry/storage/error.py
reducingwip/schemaregistry
30f0377b70253c642404f152c4eb531406ecfd5a
[ "MIT" ]
null
null
null
schemaregistry/storage/error.py
reducingwip/schemaregistry
30f0377b70253c642404f152c4eb531406ecfd5a
[ "MIT" ]
null
null
null
schemaregistry/storage/error.py
reducingwip/schemaregistry
30f0377b70253c642404f152c4eb531406ecfd5a
[ "MIT" ]
null
null
null
""" error.py ~~~~~~~~ This module contains errors to be thrown by storage modules :copyright: (c) by 2016 James Moore :license: BSD, see LICENSE for more details """ class SchemaExistsError(Exception): """ Thrown when a schema already exists """ pass class SchemaDoesNotExistError(Exception): """ Thrown when a schema does not exist """ pass class SchemaHasNoVersionsError(Exception): """ Thrown when a schema does not have any versions """ pass class SchemaVersionDoesNotExistError(Exception): """ Thrown when a schema version does not exist """ pass
19.424242
63
0.650546
""" error.py ~~~~~~~~ This module contains errors to be thrown by storage modules :copyright: (c) by 2016 James Moore :license: BSD, see LICENSE for more details """ class SchemaExistsError(Exception): """ Thrown when a schema already exists """ pass class SchemaDoesNotExistError(Exception): """ Thrown when a schema does not exist """ pass class SchemaHasNoVersionsError(Exception): """ Thrown when a schema does not have any versions """ pass class SchemaVersionDoesNotExistError(Exception): """ Thrown when a schema version does not exist """ pass
0
0
0
6d3ab87a1c16bb84c009a754914c611e25536fb3
512
py
Python
backend/apps/blackswan/migrations/0011_auto_20190716_1943.py
arshul/blackswan
1a651214e14e738ebac320c775e05ece61a2a1f8
[ "MIT" ]
2
2019-09-10T21:58:19.000Z
2019-10-20T18:46:23.000Z
backend/apps/blackswan/migrations/0011_auto_20190716_1943.py
arshul/blackswan
1a651214e14e738ebac320c775e05ece61a2a1f8
[ "MIT" ]
46
2019-05-14T03:26:00.000Z
2020-06-05T20:48:16.000Z
backend/apps/blackswan/migrations/0011_auto_20190716_1943.py
arshul/blackswan
1a651214e14e738ebac320c775e05ece61a2a1f8
[ "MIT" ]
5
2019-10-02T16:46:32.000Z
2020-02-18T05:53:37.000Z
# Generated by Django 2.1.1 on 2019-07-16 19:43 from django.db import migrations
21.333333
47
0.5625
# Generated by Django 2.1.1 on 2019-07-16 19:43 from django.db import migrations class Migration(migrations.Migration): dependencies = [ ('blackswan', '0010_user_full_name'), ] operations = [ migrations.RenameField( model_name='project', old_name='title', new_name='repo', ), migrations.RenameField( model_name='workflowexecution', old_name='username_pr', new_name='actor', ), ]
0
406
23
0f572b130d1694f5c837089a20bc12b0396745a6
1,307
py
Python
097_Interleaving_String.py
adwardlee/leetcode_solutions
f386869161181e153e29165d8fff06492bb192f3
[ "MIT" ]
null
null
null
097_Interleaving_String.py
adwardlee/leetcode_solutions
f386869161181e153e29165d8fff06492bb192f3
[ "MIT" ]
null
null
null
097_Interleaving_String.py
adwardlee/leetcode_solutions
f386869161181e153e29165d8fff06492bb192f3
[ "MIT" ]
null
null
null
''' Given strings s1, s2, and s3, find whether s3 is formed by an interleaving of s1 and s2. An interleaving of two strings s and t is a configuration where they are divided into non-empty substrings such that: s = s1 + s2 + ... + sn t = t1 + t2 + ... + tm |n - m| <= 1 The interleaving is s1 + t1 + s2 + t2 + s3 + t3 + ... or t1 + s1 + t2 + s2 + t3 + s3 + ... Note: a + b is the concatenation of strings a and b. Example 1: Input: s1 = "aabcc", s2 = "dbbca", s3 = "aadbbcbcac" Output: true Example 2: Input: s1 = "aabcc", s2 = "dbbca", s3 = "aadbbbaccc" Output: false Example 3: Input: s1 = "", s2 = "", s3 = "" Output: true '''
29.044444
117
0.505738
''' Given strings s1, s2, and s3, find whether s3 is formed by an interleaving of s1 and s2. An interleaving of two strings s and t is a configuration where they are divided into non-empty substrings such that: s = s1 + s2 + ... + sn t = t1 + t2 + ... + tm |n - m| <= 1 The interleaving is s1 + t1 + s2 + t2 + s3 + t3 + ... or t1 + s1 + t2 + s2 + t3 + s3 + ... Note: a + b is the concatenation of strings a and b. Example 1: Input: s1 = "aabcc", s2 = "dbbca", s3 = "aadbbcbcac" Output: true Example 2: Input: s1 = "aabcc", s2 = "dbbca", s3 = "aadbbbaccc" Output: false Example 3: Input: s1 = "", s2 = "", s3 = "" Output: true ''' class Solution: def isInterleave(self, s1: str, s2: str, s3: str) -> bool: l1 = len(s1) l2 = len(s2) l3 = len(s3) if l1 + l2 != l3: return False dp = [[1 for i in range(l1+1)] for j in range(l2+1)] for i in range(1, l1+1): dp[0][i] = dp[0][i-1] and (s1[i-1] == s3[i-1]) for i in range(1, l2+1): dp[i][0] = dp[i - 1][0] and (s2[i-1] == s3[i-1]) for i in range(1, l2+1): for j in range(1, l1+1): dp[i][j] = (dp[i-1][j] and (s2[i-1] == s3[i + j - 1])) or (dp[i][j-1] and (s1[j-1] == s3[i + j - 1])) return dp[-1][-1]
625
-6
48
7a67be7f805caf6e90c3c75aaa16a3abda76ba3a
487
py
Python
for.py
PMinThant/My-Python
fbcd6906e442c0d7b42a93c366ec608de9fb402e
[ "MIT" ]
null
null
null
for.py
PMinThant/My-Python
fbcd6906e442c0d7b42a93c366ec608de9fb402e
[ "MIT" ]
null
null
null
for.py
PMinThant/My-Python
fbcd6906e442c0d7b42a93c366ec608de9fb402e
[ "MIT" ]
null
null
null
for var_x in range(1,6): print(var_x) var_i = ["Apple","Banana","Pieapple","Orange","Lime"] for var_x in var_i: print(var_x) food_info={"Food_1":"Apple","Food_2":"Banana","Food_3":"Pieapple","Food_4":"Mango","Food_5":"Orange","Food_6":"Lime"} index_num1 = range(len(dict.keys(food_info))) key_list =list(dict.keys(food_info)) print("Food Name"+"\t"+"Food List") for var_x in index_num1: print(key_list[var_x]+"\t\t"+food_info[key_list[var_x]])
30.4375
118
0.64271
for var_x in range(1,6): print(var_x) var_i = ["Apple","Banana","Pieapple","Orange","Lime"] for var_x in var_i: print(var_x) food_info={"Food_1":"Apple","Food_2":"Banana","Food_3":"Pieapple","Food_4":"Mango","Food_5":"Orange","Food_6":"Lime"} index_num1 = range(len(dict.keys(food_info))) key_list =list(dict.keys(food_info)) print("Food Name"+"\t"+"Food List") for var_x in index_num1: print(key_list[var_x]+"\t\t"+food_info[key_list[var_x]])
0
0
0
247cf1f7a45b192ebd2e976ae9aad0f33c3fa562
989
py
Python
Server/app/schema/mutations/quickmemo/new.py
Team-SeeTo/SeeTo-Backend
19990cd6f4895e773eaa504f7b7a07ddbb5856e5
[ "Apache-2.0" ]
4
2018-06-18T06:50:12.000Z
2018-11-15T00:08:24.000Z
Server/app/schema/mutations/quickmemo/new.py
Team-SeeTo/SeeTo-Backend
19990cd6f4895e773eaa504f7b7a07ddbb5856e5
[ "Apache-2.0" ]
null
null
null
Server/app/schema/mutations/quickmemo/new.py
Team-SeeTo/SeeTo-Backend
19990cd6f4895e773eaa504f7b7a07ddbb5856e5
[ "Apache-2.0" ]
null
null
null
import graphene from flask_graphql_auth import mutation_jwt_required, get_jwt_identity, AuthInfoField from app.models import User, QuickMemo from app.schema.unions import ResponseUnion from app.schema.fields import ResponseMessageField
30.90625
101
0.661274
import graphene from flask_graphql_auth import mutation_jwt_required, get_jwt_identity, AuthInfoField from app.models import User, QuickMemo from app.schema.unions import ResponseUnion from app.schema.fields import ResponseMessageField class NewQuickMemoMutation(graphene.Mutation): class Arguments(object): token = graphene.String() title = graphene.String() body = graphene.String() result = graphene.Field(ResponseUnion) @classmethod @mutation_jwt_required def mutate(cls, _, info, title, body): user = User.objects(email=get_jwt_identity()) new_memo = QuickMemo(title=title, body=body) new_memo.save() user.update_one(push__quick_memo=new_memo) # TODO: User Log 남기는 기능은 함수로 따로 빼자 return NewQuickMemoMutation(result=ResponseMessageField(is_success=True, message="Quick memo upload success"))
484
270
23
448a9870dfde912c7a758d249170aff35f96d60b
97
py
Python
my/media/movies.py
aluhrs13/HPI
e750666e30e8987f3a4c46755857dc85dd64446c
[ "MIT" ]
1,026
2020-03-16T16:53:29.000Z
2022-03-29T16:03:38.000Z
my/media/movies.py
aluhrs13/HPI
e750666e30e8987f3a4c46755857dc85dd64446c
[ "MIT" ]
102
2020-03-18T22:53:29.000Z
2022-03-22T00:34:46.000Z
my/media/movies.py
aluhrs13/HPI
e750666e30e8987f3a4c46755857dc85dd64446c
[ "MIT" ]
50
2020-03-17T21:00:34.000Z
2022-03-28T08:37:13.000Z
from .imdb import get_movies # TODO extract items from org mode? perhaps not very high priority
24.25
66
0.793814
from .imdb import get_movies # TODO extract items from org mode? perhaps not very high priority
0
0
0
bd832959fc599907901c316c690667a4d2b13c90
9,505
py
Python
ai/STA/Strategy/graphless_offense.py
RoboCupULaval/StrategyAI
ccddde144f2c0a67113d2e5ffe7c75ed9d4a3d19
[ "MIT" ]
13
2018-03-14T10:20:10.000Z
2021-12-10T05:36:47.000Z
ai/STA/Strategy/graphless_offense.py
RoboCupULaval/StrategyIA
ccddde144f2c0a67113d2e5ffe7c75ed9d4a3d19
[ "MIT" ]
200
2016-04-29T23:13:01.000Z
2018-03-13T14:36:39.000Z
ai/STA/Strategy/graphless_offense.py
RoboCupULaval/StrategyIA
ccddde144f2c0a67113d2e5ffe7c75ed9d4a3d19
[ "MIT" ]
45
2015-07-04T18:57:39.000Z
2018-01-11T16:11:13.000Z
# Under MIT license, see LICENSE.txt import numpy as np from Util.geometry import wrap_to_pi from Util.role import Role from ai.Algorithm.evaluation_module import closest_players_to_point_except, ball_going_toward_player from ai.GameDomainObjects import Player from ai.STA.Strategy.graphless_strategy import GraphlessStrategy from ai.STA.Tactic.go_kick import GoKick from ai.STA.Tactic.goalkeeper import GoalKeeper from ai.STA.Tactic.position_for_pass import PositionForPass from ai.STA.Tactic.receive_pass import ReceivePass from ai.STA.Tactic.stay_away_from_ball import StayAwayFromBall from ai.STA.Tactic.tactic_constants import Flags from ai.states.game_state import GameState MAX_DISTANCE_TO_SWITCH_TO_RECEIVE_PASS = 1500
53.398876
156
0.604945
# Under MIT license, see LICENSE.txt import numpy as np from Util.geometry import wrap_to_pi from Util.role import Role from ai.Algorithm.evaluation_module import closest_players_to_point_except, ball_going_toward_player from ai.GameDomainObjects import Player from ai.STA.Strategy.graphless_strategy import GraphlessStrategy from ai.STA.Tactic.go_kick import GoKick from ai.STA.Tactic.goalkeeper import GoalKeeper from ai.STA.Tactic.position_for_pass import PositionForPass from ai.STA.Tactic.receive_pass import ReceivePass from ai.STA.Tactic.stay_away_from_ball import StayAwayFromBall from ai.STA.Tactic.tactic_constants import Flags from ai.states.game_state import GameState MAX_DISTANCE_TO_SWITCH_TO_RECEIVE_PASS = 1500 class GraphlessOffense(GraphlessStrategy): MOVING_BALL_VELOCITY = 50 # mm/s DANGER_BALL_VELOCITY = 600 # mm/s def __init__(self, p_game_state: GameState): super().__init__(p_game_state) self.robots_in_formation = [p for r, p in self.assigned_roles.items() if r != Role.GOALKEEPER] for role, player in self.assigned_roles.items(): if role is Role.GOALKEEPER: self.roles_to_tactics[role] = GoalKeeper(self.game_state, player) else: self.roles_to_tactics[role] = PositionForPass(self.game_state, player, auto_position=True, robots_in_formation=self.robots_in_formation) self.next_state = self.go_get_ball self.current_pass_receiver = None def go_get_ball(self): for role, player in self.assigned_roles.items(): if role == Role.GOALKEEPER: continue tactic = self.roles_to_tactics[role] if isinstance(tactic, GoKick): if not self.is_closest_not_goalkeeper(player): self.logger.info(f"Robot {player.id} was not closest. Returning to PositionForPass") self.roles_to_tactics[role] = PositionForPass(self.game_state, player, auto_position=True, robots_in_formation=self.robots_in_formation) elif tactic.status_flag == Flags.PASS_TO_PLAYER and self._will_probably_kick_soon(player): self.logger.info(f"Robot {player.id} is passing to Robot {tactic.current_player_target.id}") self._assign_target_to_receive_pass(tactic.current_player_target, passing_robot=player) self.logger.info("Switching to receive_pass") self.next_state = self.receive_pass return # We dont want to override self.current_pass_receiver elif self.is_closest_not_goalkeeper(player): self.logger.info(f"Robot {player.id} is closest! Switching to GoKick") self.roles_to_tactics[role] = GoKick(self.game_state, player, auto_update_target=True, can_kick_in_goal=True) # Robots must not stay in receive pass if they are not receiving a pass elif isinstance(tactic, ReceivePass): self.roles_to_tactics[role] = PositionForPass(self.game_state, player, auto_position=True, robots_in_formation=self.robots_in_formation) elif ball_going_toward_player(self.game_state, player): self.logger.info(f"Ball is going toward Robot {player.id}!") if self._ball_going_toward_goal(): self.logger.info(f"Robot {player.id} is blocking the ball from entering goal. Switching its tactic to stay away.") self.roles_to_tactics[role] = StayAwayFromBall(self.game_state, player) else: self._assign_target_to_receive_pass(player, passing_robot=None) self.logger.info("Switching to receive_pass") self.next_state = self.receive_pass def receive_pass(self): for role, player in self.assigned_roles.items(): if role == Role.GOALKEEPER: continue tactic = self.roles_to_tactics[role] if isinstance(tactic, GoKick): gokick_target = tactic.current_player_target if gokick_target is not None: if gokick_target != self.current_pass_receiver: self.logger.info( f"Robot {player.id} changed its target! Last target: Robot {self.current_pass_receiver.id} -- New target : {gokick_target.id}") self.logger.info(f"Switching Robot {self.current_pass_receiver.id} tactic to PositionForPass") last_receiver_role = self.game_state.get_role_by_player_id(self.current_pass_receiver.id) self.roles_to_tactics[last_receiver_role] = PositionForPass(self.game_state, self.current_pass_receiver, auto_position=True, robots_in_formation=self.robots_in_formation) self._assign_target_to_receive_pass(gokick_target, player) if tactic.status_flag == Flags.SUCCESS: self.logger.info(f"Robot {player.id} has kicked!") receiver_role = self.game_state.get_role_by_player_id(self.current_pass_receiver.id) receiver_tactic = self.roles_to_tactics[receiver_role] assert isinstance(receiver_tactic, ReceivePass) receiver_tactic.passing_robot_has_kicked = True elif isinstance(tactic, ReceivePass) and tactic.status_flag == Flags.SUCCESS: self.logger.info(f"Robot {player.id} has received ball!") self.logger.info("Switching to go_get_ball") self.next_state = self.go_get_ball if all(not isinstance(self.roles_to_tactics[role], GoKick) for role, _ in self.assigned_roles.items()): self.next_state = self.go_get_ball def _assign_target_to_receive_pass(self, target: Player, passing_robot): self.logger.info(f"Switching Robot {target.id} tactic to ReceivePass") role = self.game_state.get_role_by_player_id(target.id) self.roles_to_tactics[role] = ReceivePass(self.game_state, target, passing_robot=passing_robot) self.current_pass_receiver = target @classmethod def required_roles(cls): return [Role.GOALKEEPER, Role.FIRST_ATTACK, Role.MIDDLE] @classmethod def optional_roles(cls): return [Role.FIRST_DEFENCE, Role.SECOND_ATTACK, Role.SECOND_DEFENCE] def is_closest_not_goalkeeper(self, player: Player): ban_players = self.game_state.ban_players if player in ban_players: return False closests = closest_players_to_point_except(self.game_state.ball.position, except_roles=[Role.GOALKEEPER], except_players=ban_players) return len(closests) > 0 and closests[0].player == player def _will_probably_kick_soon(self, player: Player): tactic = self.roles_to_tactics[self.game_state.get_role_by_player_id(player.id)] assert isinstance(tactic, GoKick) player_to_ball_distance = (self.game_state.ball_position - player.position).norm is_close_to_ball = player_to_ball_distance < MAX_DISTANCE_TO_SWITCH_TO_RECEIVE_PASS if is_close_to_ball: self.logger.info("Go Kick is close to ball") ball_to_receiver_unit = (tactic.current_player_target.position - self.game_state.ball_position).unit is_approaching_ball = player.velocity.position.unit.dot(ball_to_receiver_unit) > 0.5 if is_approaching_ball: self.logger.info("Go Kick is approaching the ball") return is_close_to_ball or is_approaching_ball def _ball_going_toward_goal(self): angle_p1 = wrap_to_pi((self.game_state.field.their_goal_line.p1 - self.game_state.ball.position).angle + np.pi) angle_p2 = wrap_to_pi((self.game_state.field.their_goal_line.p2 - self.game_state.ball.position).angle + np.pi) lower_angle = angle_p1 - 5 * np.pi / 180.0 upper_angle = angle_p2 + 5 * np.pi / 180.0 ball_velocity_angle = wrap_to_pi(self.game_state.ball.velocity.angle + np.pi) ball_speed = self.game_state.ball.velocity.norm return (ball_speed > self.DANGER_BALL_VELOCITY and self.game_state.ball.velocity.x < 0) or \ (ball_speed > self.MOVING_BALL_VELOCITY and lower_angle <= ball_velocity_angle <= upper_angle)
8,375
376
23
c44b7120c318e903bf67ddb2e46c2955ce7565b7
7,777
py
Python
Tests/Methods/Slot/test_HoleM53_meth.py
IrakozeFD/pyleecan
5a93bd98755d880176c1ce8ac90f36ca1b907055
[ "Apache-2.0" ]
2
2020-08-28T14:54:55.000Z
2021-03-13T19:34:45.000Z
Tests/Methods/Slot/test_HoleM53_meth.py
IrakozeFD/pyleecan
5a93bd98755d880176c1ce8ac90f36ca1b907055
[ "Apache-2.0" ]
null
null
null
Tests/Methods/Slot/test_HoleM53_meth.py
IrakozeFD/pyleecan
5a93bd98755d880176c1ce8ac90f36ca1b907055
[ "Apache-2.0" ]
null
null
null
# -*- coding: utf-8 -*- import pytest from pyleecan.Classes.Segment import Segment from pyleecan.Classes.SurfLine import SurfLine from pyleecan.Classes.LamHole import LamHole from pyleecan.Classes.HoleM53 import HoleM53 from pyleecan.Classes.Magnet import Magnet from numpy import exp, arcsin, ndarray, pi from pyleecan.Methods.Slot.HoleM53 import Slot53InterError # For AlmostEqual DELTA = 1e-6 HoleM53_test = list() HoleM53_test_error = list() # Two hole test_obj = LamHole(is_internal=True, Rext=80.2e-3, Rint=0) test_obj.hole = list() test_obj.hole.append( HoleM53( Zh=8, H0=0.02, H1=0.001, H2=0.01, H3=0.003, W1=0.005, W2=0, W3=0.01, W4=0.78 ) ) HoleM53_test.append( { "test_obj": test_obj, "S_exp": 3.63836e-4, "SM_exp": 0.0002, "Rmin": 5.8879558e-2, "Rmax": 7.92e-2, "W5": 7.78324e-3, } ) # One hole test_obj = LamHole(is_internal=True, Rext=80.2e-3, Rint=0) test_obj.hole = list() test_obj.hole.append( HoleM53(Zh=8, H0=0.02, H1=0.001, H2=0.01, H3=0.003, W1=0, W2=0, W3=0.01, W4=0.78) ) HoleM53_test.append( { "test_obj": test_obj, "S_exp": 3.73158e-4, "SM_exp": 0.0002, "Rmin": 5.8523556e-2, "Rmax": 7.92e-2, "W5": 8.317707e-3, } ) # Error test test_obj = LamHole(is_internal=True, Rext=80.2e-3, Rint=0) test_obj.hole = list() test_obj.hole.append( HoleM53(Zh=8, H0=0.02, H1=0.001, H2=0.01, H3=0.003, W1=0, W2=0, W3=0.01, W4=0.78) ) HoleM53_test_error.append( { "test_obj": test_obj, "S_exp": 3.73158e-4, "SM_exp": 0.0002, "Rmin": 5.8523556e-2, "Rmax": 7.92e-2, "W5": 8.317707e-3, } ) @pytest.mark.METHODS class Test_HoleM53_meth(object): """pytest for holeB53 methods""" @pytest.mark.parametrize("test_dict", HoleM53_test) def test_comp_surface(self, test_dict): """Check that the computation of the surface is correct""" test_obj = test_dict["test_obj"] result = test_obj.hole[0].comp_surface() a = result b = test_dict["S_exp"] msg = "Return " + str(a) + " expected " + str(b) assert abs((a - b) / a - 0) < DELTA, msg @pytest.mark.parametrize("test_dict", HoleM53_test) def test_comp_surface_mag(self, test_dict): """Check that the computation of the magnet surface is correct""" test_obj = test_dict["test_obj"] result = test_obj.hole[0].comp_surface_magnets() a = result b = test_dict["SM_exp"] msg = "Return " + str(a) + " expected " + str(b) assert abs((a - b) / a - 0) < DELTA, msg @pytest.mark.parametrize("test_dict", HoleM53_test) def test_comp_radius(self, test_dict): """Check that the computation of the radius is correct""" test_obj = test_dict["test_obj"] result = test_obj.hole[0].comp_radius() a = result[0] b = test_dict["Rmin"] msg = "Return " + str(a) + " expected " + str(b) assert abs((a - b) / a - 0) < DELTA, msg a = result[1] b = test_dict["Rmax"] msg = "Return " + str(a) + " expected " + str(b) assert abs((a - b) / a - 0) < DELTA, msg @pytest.mark.parametrize("test_dict", HoleM53_test) def test_comp_W5(self, test_dict): """Check that the computation of W5 iscorrect""" test_obj = test_dict["test_obj"] a = test_obj.hole[0].comp_W5() b = test_dict["W5"] msg = "Return " + str(a) + " expected " + str(b) assert abs((a - b) / a - 0) < DELTA, msg # Test that Z11 = Zlist[0] test_obj2 = LamHole(is_internal=True, Rext=80.2e-3, Rint=0) test_obj2.hole = list() test_obj2.hole.append( HoleM53( Zh=8, H0=0.00000000000000000000002, H1=0.00000001, H2=0.01, H3=0.003, W1=0, W2=0, W3=0.01, W4=2.28, ) ) a = test_obj2.hole[0].comp_W5() assert -0.0014380265690122837 == a @pytest.mark.parametrize("test_dict", HoleM53_test) def test_build_geometry(self, test_dict): """Check that the build geometry method works""" # is_simplified to True and magnetization Parallel test_obj = test_dict["test_obj"] test_obj.hole[0].magnet_0 = Magnet(type_magnetization=1) test_obj.hole[0].magnet_1 = Magnet(type_magnetization=1) a = test_obj.hole[0].build_geometry(is_simplified=True) assert a[1].label == "HoleMagnet_Stator_Parallel_N_R0_T0_S0" assert a[1].line_list[0] is not None assert a[1].line_list[1] is not None with pytest.raises(IndexError) as context: a[1].line_list[2] if test_obj.hole[0].W1 > 0: assert a[4].label == "HoleMagnet_Stator_Parallel_N_R0_T1_S0" assert a[4].line_list[0] is not None assert a[4].line_list[1] is not None with pytest.raises(IndexError) as context: a[4].line_list[2] else: assert a[3].label == "HoleMagnet_Stator_Parallel_N_R0_T1_S0" assert a[3].line_list[0] is not None assert a[3].line_list[1] is not None with pytest.raises(IndexError) as context: a[3].line_list[2] @pytest.mark.parametrize("test_dict", HoleM53_test_error) def test_build_geometry_Z11_Z1_not_foundable(self, test_dict): """Check that the build geometry error works""" test_obj = test_dict["test_obj"] test_obj.hole[0] = HoleM53( Zh=8, H0=0.02, H1=0.001, H2=0.01, H3=0.003, W1=0.765149757, W2=0.32542, W3=0.0564, W4=0.324, ) # Z11 with pytest.raises(Slot53InterError) as context: test_obj.hole[0].build_geometry() test_obj.hole[0] = HoleM53( Zh=8, H0=50.02, H1=10.0054456451, H2=40.56456456401, H3=0.968464003, W1=10.0, W2=0.14540, W3=1.01546654654, W4=0.05144, ) # Z1 with pytest.raises(Slot53InterError) as context: test_obj.hole[0].build_geometry() @pytest.mark.parametrize("test_dict", HoleM53_test_error) def test_build_geometry_Z11_Z1(self, test_dict): """Check nothing it's just for the coverage""" test_obj = test_dict["test_obj"] test_obj.hole[0] = HoleM53( Zh=8, H0=0.02, H1=0.001, H2=0.01, H3=0.003, W1=0.005, W2=0, W3=0.01, W4=0.78 ) lst_pattern = test_obj.hole[0].build_geometry() # Z11 = Zlist[0] test_obj.hole[0] = HoleM53( Zh=8, H0=0.00000000000000000000002, H1=0.00000001, H2=0.01, H3=0.003, W1=0, W2=0, W3=0.01, W4=2.28, ) lst1 = test_obj.hole[0].build_geometry() # Z1 = Zlist[0] test_obj.hole[0] = HoleM53( Zh=8, H0=0.00000000000000000000002, H1=0.00000001, H2=0.01, H3=0.003, W1=0, W2=0, W3=0.01, W4=4.78, ) lst2 = test_obj.hole[0].build_geometry() assert len(lst1) != len(lst_pattern) assert len(lst2) != len(lst_pattern) def test_comp_surface_magnet_id(self): """check that id is 0""" hole = HoleM53( Zh=8, H0=0.02, H1=0.001, H2=0.01, H3=0.003, W1=0.005, W2=0, W3=0.01, W4=0.78 ) assert hole.comp_surface_magnet_id(2) == 0
29.683206
88
0.557284
# -*- coding: utf-8 -*- import pytest from pyleecan.Classes.Segment import Segment from pyleecan.Classes.SurfLine import SurfLine from pyleecan.Classes.LamHole import LamHole from pyleecan.Classes.HoleM53 import HoleM53 from pyleecan.Classes.Magnet import Magnet from numpy import exp, arcsin, ndarray, pi from pyleecan.Methods.Slot.HoleM53 import Slot53InterError # For AlmostEqual DELTA = 1e-6 HoleM53_test = list() HoleM53_test_error = list() # Two hole test_obj = LamHole(is_internal=True, Rext=80.2e-3, Rint=0) test_obj.hole = list() test_obj.hole.append( HoleM53( Zh=8, H0=0.02, H1=0.001, H2=0.01, H3=0.003, W1=0.005, W2=0, W3=0.01, W4=0.78 ) ) HoleM53_test.append( { "test_obj": test_obj, "S_exp": 3.63836e-4, "SM_exp": 0.0002, "Rmin": 5.8879558e-2, "Rmax": 7.92e-2, "W5": 7.78324e-3, } ) # One hole test_obj = LamHole(is_internal=True, Rext=80.2e-3, Rint=0) test_obj.hole = list() test_obj.hole.append( HoleM53(Zh=8, H0=0.02, H1=0.001, H2=0.01, H3=0.003, W1=0, W2=0, W3=0.01, W4=0.78) ) HoleM53_test.append( { "test_obj": test_obj, "S_exp": 3.73158e-4, "SM_exp": 0.0002, "Rmin": 5.8523556e-2, "Rmax": 7.92e-2, "W5": 8.317707e-3, } ) # Error test test_obj = LamHole(is_internal=True, Rext=80.2e-3, Rint=0) test_obj.hole = list() test_obj.hole.append( HoleM53(Zh=8, H0=0.02, H1=0.001, H2=0.01, H3=0.003, W1=0, W2=0, W3=0.01, W4=0.78) ) HoleM53_test_error.append( { "test_obj": test_obj, "S_exp": 3.73158e-4, "SM_exp": 0.0002, "Rmin": 5.8523556e-2, "Rmax": 7.92e-2, "W5": 8.317707e-3, } ) @pytest.mark.METHODS class Test_HoleM53_meth(object): """pytest for holeB53 methods""" @pytest.mark.parametrize("test_dict", HoleM53_test) def test_comp_surface(self, test_dict): """Check that the computation of the surface is correct""" test_obj = test_dict["test_obj"] result = test_obj.hole[0].comp_surface() a = result b = test_dict["S_exp"] msg = "Return " + str(a) + " expected " + str(b) assert abs((a - b) / a - 0) < DELTA, msg @pytest.mark.parametrize("test_dict", HoleM53_test) def test_comp_surface_mag(self, test_dict): """Check that the computation of the magnet surface is correct""" test_obj = test_dict["test_obj"] result = test_obj.hole[0].comp_surface_magnets() a = result b = test_dict["SM_exp"] msg = "Return " + str(a) + " expected " + str(b) assert abs((a - b) / a - 0) < DELTA, msg @pytest.mark.parametrize("test_dict", HoleM53_test) def test_comp_radius(self, test_dict): """Check that the computation of the radius is correct""" test_obj = test_dict["test_obj"] result = test_obj.hole[0].comp_radius() a = result[0] b = test_dict["Rmin"] msg = "Return " + str(a) + " expected " + str(b) assert abs((a - b) / a - 0) < DELTA, msg a = result[1] b = test_dict["Rmax"] msg = "Return " + str(a) + " expected " + str(b) assert abs((a - b) / a - 0) < DELTA, msg @pytest.mark.parametrize("test_dict", HoleM53_test) def test_comp_W5(self, test_dict): """Check that the computation of W5 iscorrect""" test_obj = test_dict["test_obj"] a = test_obj.hole[0].comp_W5() b = test_dict["W5"] msg = "Return " + str(a) + " expected " + str(b) assert abs((a - b) / a - 0) < DELTA, msg # Test that Z11 = Zlist[0] test_obj2 = LamHole(is_internal=True, Rext=80.2e-3, Rint=0) test_obj2.hole = list() test_obj2.hole.append( HoleM53( Zh=8, H0=0.00000000000000000000002, H1=0.00000001, H2=0.01, H3=0.003, W1=0, W2=0, W3=0.01, W4=2.28, ) ) a = test_obj2.hole[0].comp_W5() assert -0.0014380265690122837 == a @pytest.mark.parametrize("test_dict", HoleM53_test) def test_build_geometry(self, test_dict): """Check that the build geometry method works""" # is_simplified to True and magnetization Parallel test_obj = test_dict["test_obj"] test_obj.hole[0].magnet_0 = Magnet(type_magnetization=1) test_obj.hole[0].magnet_1 = Magnet(type_magnetization=1) a = test_obj.hole[0].build_geometry(is_simplified=True) assert a[1].label == "HoleMagnet_Stator_Parallel_N_R0_T0_S0" assert a[1].line_list[0] is not None assert a[1].line_list[1] is not None with pytest.raises(IndexError) as context: a[1].line_list[2] if test_obj.hole[0].W1 > 0: assert a[4].label == "HoleMagnet_Stator_Parallel_N_R0_T1_S0" assert a[4].line_list[0] is not None assert a[4].line_list[1] is not None with pytest.raises(IndexError) as context: a[4].line_list[2] else: assert a[3].label == "HoleMagnet_Stator_Parallel_N_R0_T1_S0" assert a[3].line_list[0] is not None assert a[3].line_list[1] is not None with pytest.raises(IndexError) as context: a[3].line_list[2] @pytest.mark.parametrize("test_dict", HoleM53_test_error) def test_build_geometry_Z11_Z1_not_foundable(self, test_dict): """Check that the build geometry error works""" test_obj = test_dict["test_obj"] test_obj.hole[0] = HoleM53( Zh=8, H0=0.02, H1=0.001, H2=0.01, H3=0.003, W1=0.765149757, W2=0.32542, W3=0.0564, W4=0.324, ) # Z11 with pytest.raises(Slot53InterError) as context: test_obj.hole[0].build_geometry() test_obj.hole[0] = HoleM53( Zh=8, H0=50.02, H1=10.0054456451, H2=40.56456456401, H3=0.968464003, W1=10.0, W2=0.14540, W3=1.01546654654, W4=0.05144, ) # Z1 with pytest.raises(Slot53InterError) as context: test_obj.hole[0].build_geometry() @pytest.mark.parametrize("test_dict", HoleM53_test_error) def test_build_geometry_Z11_Z1(self, test_dict): """Check nothing it's just for the coverage""" test_obj = test_dict["test_obj"] test_obj.hole[0] = HoleM53( Zh=8, H0=0.02, H1=0.001, H2=0.01, H3=0.003, W1=0.005, W2=0, W3=0.01, W4=0.78 ) lst_pattern = test_obj.hole[0].build_geometry() # Z11 = Zlist[0] test_obj.hole[0] = HoleM53( Zh=8, H0=0.00000000000000000000002, H1=0.00000001, H2=0.01, H3=0.003, W1=0, W2=0, W3=0.01, W4=2.28, ) lst1 = test_obj.hole[0].build_geometry() # Z1 = Zlist[0] test_obj.hole[0] = HoleM53( Zh=8, H0=0.00000000000000000000002, H1=0.00000001, H2=0.01, H3=0.003, W1=0, W2=0, W3=0.01, W4=4.78, ) lst2 = test_obj.hole[0].build_geometry() assert len(lst1) != len(lst_pattern) assert len(lst2) != len(lst_pattern) def test_comp_surface_magnet_id(self): """check that id is 0""" hole = HoleM53( Zh=8, H0=0.02, H1=0.001, H2=0.01, H3=0.003, W1=0.005, W2=0, W3=0.01, W4=0.78 ) assert hole.comp_surface_magnet_id(2) == 0
0
0
0
57393cfb77555e6eedd1e1f644547de5412d9e00
81
py
Python
mmdet/ops/box_iou_rotated/__init__.py
JarvisUSTC/DARDet
debbf476e9750030db67f030a40cf8d4f03e46ee
[ "Apache-2.0" ]
23
2021-09-22T14:05:49.000Z
2022-02-15T09:45:23.000Z
mmdet/ops/box_iou_rotated/__init__.py
JarvisUSTC/DARDet
debbf476e9750030db67f030a40cf8d4f03e46ee
[ "Apache-2.0" ]
13
2021-10-09T07:08:17.000Z
2022-01-06T05:53:45.000Z
mmdet/ops/box_iou_rotated/__init__.py
JarvisUSTC/DARDet
debbf476e9750030db67f030a40cf8d4f03e46ee
[ "Apache-2.0" ]
6
2021-11-15T03:16:51.000Z
2022-03-20T08:55:19.000Z
from .box_iou_rotated_cuda import box_iou_rotated __all__ = ['box_iou_rotated']
20.25
49
0.82716
from .box_iou_rotated_cuda import box_iou_rotated __all__ = ['box_iou_rotated']
0
0
0
2d94622d5e13f03b2513ee75ca6a50d0f1931939
341
py
Python
vcsver/util.py
janneronkko/vcsver
77020e296a8239ee142213642504c03b9064653f
[ "MIT" ]
1
2020-12-23T19:22:51.000Z
2020-12-23T19:22:51.000Z
vcsver/util.py
janneronkko/vcsver
77020e296a8239ee142213642504c03b9064653f
[ "MIT" ]
null
null
null
vcsver/util.py
janneronkko/vcsver
77020e296a8239ee142213642504c03b9064653f
[ "MIT" ]
null
null
null
import typing
24.357143
60
0.478006
import typing def parse_pkg_info_file(path: str) -> typing.Dict[str, str]: with open(path, 'rt') as pkg_info_file: return { key.strip(): value.strip() for key, value in ( line.split(':', 1) for line in pkg_info_file if ':' in line ) }
303
0
23
1e85fd4f4ea8db04a18b0e7537753f2dffeb788d
2,912
py
Python
spotseeker_server/auth/oauth.py
uw-it-aca/spotseeker_server
1d8a5bf98b76fdcb807ed4cd32f939bb7e9aa66c
[ "Apache-2.0" ]
5
2015-03-12T00:36:33.000Z
2022-02-24T16:41:25.000Z
spotseeker_server/auth/oauth.py
uw-it-aca/spotseeker_server
1d8a5bf98b76fdcb807ed4cd32f939bb7e9aa66c
[ "Apache-2.0" ]
133
2016-02-03T23:54:45.000Z
2022-03-30T21:33:58.000Z
spotseeker_server/auth/oauth.py
uw-it-aca/spotseeker_server
1d8a5bf98b76fdcb807ed4cd32f939bb7e9aa66c
[ "Apache-2.0" ]
6
2015-01-07T23:21:15.000Z
2017-12-07T08:26:33.000Z
# Copyright 2021 UW-IT, University of Washington # SPDX-License-Identifier: Apache-2.0 """ This module uses oauth to allow applications and users access. Supports 2-legged oauth for application requests, and for trusted applications accessing user-restricted methods. Supports 3-legged oauth for non-trusted applications that want to access user methods. To use this module, add this to your settings.py: SPOTSEEKER_AUTH_MODULE = spotseeker_server.auth.oauth """ from django.http import HttpResponse from oauth_provider.utils import get_oauth_request, verify_oauth_request from oauth_provider.store import store, InvalidConsumerError, InvalidTokenError from spotseeker_server.models import TrustedOAuthClient import logging
34.666667
79
0.668613
# Copyright 2021 UW-IT, University of Washington # SPDX-License-Identifier: Apache-2.0 """ This module uses oauth to allow applications and users access. Supports 2-legged oauth for application requests, and for trusted applications accessing user-restricted methods. Supports 3-legged oauth for non-trusted applications that want to access user methods. To use this module, add this to your settings.py: SPOTSEEKER_AUTH_MODULE = spotseeker_server.auth.oauth """ from django.http import HttpResponse from oauth_provider.utils import get_oauth_request, verify_oauth_request from oauth_provider.store import store, InvalidConsumerError, InvalidTokenError from spotseeker_server.models import TrustedOAuthClient import logging def authenticate_application(*args, **kwargs): request = args[1] try: oauth_request = get_oauth_request(request) consumer = store.get_consumer( request, oauth_request, oauth_request["oauth_consumer_key"] ) verify_oauth_request(request, oauth_request, consumer) request.META["SS_OAUTH_CONSUMER_NAME"] = consumer.name request.META["SS_OAUTH_CONSUMER_PK"] = consumer.pk return except Exception as e: response = HttpResponse("Error authorizing application: %s" % e) response.status_code = 401 return response def authenticate_user(*args, **kwargs): request = args[1] try: oauth_request = get_oauth_request(request) consumer = store.get_consumer( request, oauth_request, oauth_request["oauth_consumer_key"] ) verify_oauth_request(request, oauth_request, consumer) # Allow a trusted client to either give us a user via header, or do the # 3-legged oauth user = None try: trusted_client = TrustedOAuthClient.objects.get(consumer=consumer) if trusted_client and trusted_client.is_trusted: user = request.META["HTTP_X_OAUTH_USER"] logging.info( "user is a trusted client and was set to {}".format(user) ) except Exception as e: pass if not user: access_token = store.get_access_token( request, oauth_request, consumer, oauth_request[u"oauth_token"] ) user = store.get_user_for_access_token( request, oauth_request, access_token ).username logging.info( "user was not a trusted client and was set to {}".format(user) ) request.META["SS_OAUTH_CONSUMER_NAME"] = consumer.name request.META["SS_OAUTH_CONSUMER_PK"] = consumer.pk request.META["SS_OAUTH_USER"] = user return except Exception as e: response = HttpResponse("Error authorizing user: %s" % e) response.status_code = 401 return response
2,134
0
46
c19d9ada1c4db136f3439e7b6dffa4c5b94a5de8
2,824
py
Python
examples/DPUCADF8H/tf_resnet/utils.py
Carles-Figuerola/Vitis-AI
fc043ea4aca1f9fe4e18962e6a6ae397812bb34b
[ "Apache-2.0" ]
1
2020-12-18T14:49:19.000Z
2020-12-18T14:49:19.000Z
examples/DPUCADF8H/tf_resnet/utils.py
cy333/Vitis-AI
611b82cfc32ea2fe04491432bf8feed1f378c9de
[ "Apache-2.0" ]
null
null
null
examples/DPUCADF8H/tf_resnet/utils.py
cy333/Vitis-AI
611b82cfc32ea2fe04491432bf8feed1f378c9de
[ "Apache-2.0" ]
null
null
null
#!/usr/bin/env python # Copyright 2019 Xilinx Inc. # # Licensed under the Apache License, Version 2.0 (the "License"); # you may not use this file except in compliance with the License. # You may obtain a copy of the License at # # http://www.apache.org/licenses/LICENSE-2.0 # # Unless required by applicable law or agreed to in writing, software # distributed under the License is distributed on an "AS IS" BASIS, # WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. # See the License for the specific language governing permissions and # limitations under the License. from functools import partial import os import os.path as osp from vai.dpuv1.rt.xdnn_io import loadImageBlobFromFileScriptBase IMAGEROOT = osp.join(os.environ['HOME'], 'CK-TOOLS/dataset-imagenet-ilsvrc2012-val-min') IMAGELIST = osp.join(os.environ['HOME'], 'CK-TOOLS/dataset-imagenet-ilsvrc2012-val-min/val.txt') INPUT_NODES = 'input' ### Preprocessing formulas ### Available transformations: ['resize', 'resize2mindim', 'resize2maxdim', 'crop_letterbox', ### 'crop_center', 'plot', 'pxlscale', 'meansub', 'chtranspose', 'chswap'] CMD_SEQ = { 'resnet50_v1_tf':[ ('meansub', [103.94, 116.78, 123.68]), ('chswap',(2,1,0)), ('resize', [256, 256]), ('crop_center', [224, 224]), ], 'inception_v1_tf':[ ('pxlscale', 1/255.), ('meansub', 0.5), ('pxlscale', 2), ('resize', [256, 256]), ('crop_center', [224, 224]), ], 'inception_v3_tf':[ ('pxlscale', 1/255.), ('meansub', 0.5), ('pxlscale', 2), ('resize', [342, 342]), ('crop_center', [299, 299]), ], } for name in CMD_SEQ: globals()['input_fn_{}'.format(name)] = get_input_fn(name)
36.675325
127
0.651204
#!/usr/bin/env python # Copyright 2019 Xilinx Inc. # # Licensed under the Apache License, Version 2.0 (the "License"); # you may not use this file except in compliance with the License. # You may obtain a copy of the License at # # http://www.apache.org/licenses/LICENSE-2.0 # # Unless required by applicable law or agreed to in writing, software # distributed under the License is distributed on an "AS IS" BASIS, # WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. # See the License for the specific language governing permissions and # limitations under the License. from functools import partial import os import os.path as osp from vai.dpuv1.rt.xdnn_io import loadImageBlobFromFileScriptBase IMAGEROOT = osp.join(os.environ['HOME'], 'CK-TOOLS/dataset-imagenet-ilsvrc2012-val-min') IMAGELIST = osp.join(os.environ['HOME'], 'CK-TOOLS/dataset-imagenet-ilsvrc2012-val-min/val.txt') INPUT_NODES = 'input' ### Preprocessing formulas ### Available transformations: ['resize', 'resize2mindim', 'resize2maxdim', 'crop_letterbox', ### 'crop_center', 'plot', 'pxlscale', 'meansub', 'chtranspose', 'chswap'] CMD_SEQ = { 'resnet50_v1_tf':[ ('meansub', [103.94, 116.78, 123.68]), ('chswap',(2,1,0)), ('resize', [256, 256]), ('crop_center', [224, 224]), ], 'inception_v1_tf':[ ('pxlscale', 1/255.), ('meansub', 0.5), ('pxlscale', 2), ('resize', [256, 256]), ('crop_center', [224, 224]), ], 'inception_v3_tf':[ ('pxlscale', 1/255.), ('meansub', 0.5), ('pxlscale', 2), ('resize', [342, 342]), ('crop_center', [299, 299]), ], } def load_image(iter, image_list = None, pre_process_function = None, input_nodes = 'data', get_shapes = False, batch_size = 1): images = [] shapes = [] labels = [] for i in range(batch_size): image_name, label = image_list[iter * batch_size + i].split(' ') print((image_name)) image, shape = loadImageBlobFromFileScriptBase(image_name, pre_process_function) images.append(image) shapes.append(shape) if get_shapes: return {input_nodes: images}, shapes else: return {input_nodes: images} def get_input_fn(pre_processing_function_name, imageroot = IMAGEROOT, imagelist = IMAGELIST, input_nodes = INPUT_NODES): cmd_seq = CMD_SEQ[pre_processing_function_name] with open(imagelist) as fin: lines = fin.readlines() image_list = list(map(lambda x:os.path.join(imageroot, x.strip()), lines)) return partial(load_image, image_list = image_list, pre_process_function = cmd_seq, input_nodes = input_nodes) for name in CMD_SEQ: globals()['input_fn_{}'.format(name)] = get_input_fn(name)
960
0
46
1ca477dab2a4289e5804db7eecd473adf8fe8b7d
8,923
py
Python
examples/20_mnist_ddp.py
todd-deshane/aihwkit
07269e29731f9a6482d25326400437f6bef2fc94
[ "Apache-2.0" ]
133
2020-09-17T20:36:08.000Z
2022-03-21T12:15:40.000Z
examples/20_mnist_ddp.py
todd-deshane/aihwkit
07269e29731f9a6482d25326400437f6bef2fc94
[ "Apache-2.0" ]
140
2020-09-21T12:16:55.000Z
2022-03-31T18:07:37.000Z
examples/20_mnist_ddp.py
todd-deshane/aihwkit
07269e29731f9a6482d25326400437f6bef2fc94
[ "Apache-2.0" ]
53
2020-09-17T15:53:31.000Z
2022-03-30T12:22:04.000Z
# -*- coding: utf-8 -*- # (C) Copyright 2020, 2021 IBM. All Rights Reserved. # # This code is licensed under the Apache License, Version 2.0. You may # obtain a copy of this license in the LICENSE.txt file in the root directory # of this source tree or at http://www.apache.org/licenses/LICENSE-2.0. # # Any modifications or derivative works of this code must retain this # copyright notice, and modified files need to carry a notice indicating # that they have been altered from the originals. """aihwkit example 20: MNIST training with PyTorch Distributed Data Parallel (DDP). MNIST training example based on the paper: https://www.frontiersin.org/articles/10.3389/fnins.2016.00333/full Uses learning rates of η = 0.01, 0.005, and 0.0025 for epochs 0–10, 11–20, and 21–30, respectively. """ # pylint: disable=invalid-name # pylint: disable=too-many-locals import os from time import time # Imports from PyTorch. import torch from torch import nn import torch.distributed as dist import torch.multiprocessing as mp from torch.nn.parallel import DistributedDataParallel as DDP from torch.optim.lr_scheduler import StepLR from torchvision import datasets, transforms # Imports from aihwkit. from aihwkit.nn import AnalogLinear, AnalogLinearMapped, AnalogSequential from aihwkit.optim import AnalogSGD from aihwkit.simulator.configs import InferenceRPUConfig # Check device DEVICE = torch.device('cuda' if torch.cuda.is_available() else 'cpu') # Path where the datasets will be stored. PATH_DATASET = os.path.join('data', 'DATASET') # Network definition. INPUT_SIZE = 784 HIDDEN_SIZES = [256, 128] OUTPUT_SIZE = 10 # Training parameters. EPOCHS = 30 BATCH_SIZE = 64 def init_process(rank, size, fn, backend='nccl'): """ Initialize the distributed environment. """ print("init process: ", rank) os.environ['MASTER_ADDR'] = 'localhost' os.environ['MASTER_PORT'] = '29411' dist.init_process_group(backend, rank=rank, world_size=size) fn() def cleanup(): """ Destroy distributed processes once they are complete. """ dist.destroy_process_group() def load_images(): """Load images for train from the torchvision datasets.""" rank = dist.get_rank() size = dist.get_world_size() transform = transforms.Compose([transforms.ToTensor()]) # Load the images. train_set = datasets.MNIST(PATH_DATASET, download=True, train=True, transform=transform) val_set = datasets.MNIST(PATH_DATASET, download=True, train=False, transform=transform) train_sampler = torch.utils.data.DistributedSampler(train_set, num_replicas=size, rank=rank, shuffle=True, seed=42) train_data = torch.utils.data.DataLoader(train_set, batch_size=BATCH_SIZE, shuffle=False, num_workers=size, sampler=train_sampler, pin_memory=True) validation_data = torch.utils.data.DataLoader(val_set, batch_size=BATCH_SIZE, shuffle=True, num_workers=size, pin_memory=True) return train_data, validation_data def create_analog_network(input_size, hidden_sizes, output_size): """Create the neural network using analog and digital layers. Args: input_size (int): size of the Tensor at the input. hidden_sizes (list): list of sizes of the hidden layers (2 layers). output_size (int): size of the Tensor at the output. Returns: nn.Module: created analog model """ model = AnalogSequential( AnalogLinear(input_size, hidden_sizes[0], True, rpu_config=InferenceRPUConfig()), nn.Sigmoid(), AnalogLinear(hidden_sizes[0], hidden_sizes[1], True, rpu_config=InferenceRPUConfig()), nn.Sigmoid(), AnalogLinearMapped(hidden_sizes[1], output_size, True, rpu_config=InferenceRPUConfig()), nn.LogSoftmax(dim=1) ) return model def create_sgd_optimizer(model): """Create the analog-aware optimizer. Args: model (nn.Module): model to be trained. Returns: nn.Module: optimizer """ optimizer = AnalogSGD(model.parameters(), lr=0.05) optimizer.regroup_param_groups(model) return optimizer def train(model, train_set): """Train the network. Args: model (nn.Module): model to be trained. train_set (DataLoader): dataset of elements to use as input for training. """ rank = dist.get_rank() size = dist.get_world_size() device = torch.device('cuda', rank) classifier = nn.NLLLoss() optimizer = create_sgd_optimizer(model) scheduler = StepLR(optimizer, step_size=10, gamma=0.5) time_init = time() total_time = [torch.zeros(1, dtype=torch.float).to(device) for _ in range(size)] for epoch_number in range(EPOCHS): total_loss = torch.zeros(1, dtype=torch.float).to(device) total_images = torch.zeros(1, dtype=torch.int).to(device) for images, labels in train_set: images = images.to(device) labels = labels.to(device) # Flatten MNIST images into a 784 vector. images = images.view(images.shape[0], -1) optimizer.zero_grad() # Add training Tensor to the model (input). output = model(images) loss = classifier(output, labels) # Run training (backward propagation). loss.backward() # Optimize weights. optimizer.step() total_images += labels.size(0) total_loss += loss.item() * labels.size(0) dist.all_reduce(total_loss, op=dist.ReduceOp.SUM) dist.all_reduce(total_images, op=dist.ReduceOp.SUM) if rank == 0: train_loss = total_loss.item() / total_images.item() print('Epoch {} - Training loss: {:.16f}'.format(epoch_number, train_loss)) # Decay learning rate if needed. scheduler.step() dist.all_gather(total_time, torch.tensor(time()-time_init).to(device)) if rank == 0: avg_train_time = torch.mean(torch.cat(total_time, 0)) print('\nAverage Training Time (s) = {}'.format(avg_train_time)) def test_evaluation(model, val_set): """Test trained network Args: model (nn.Model): Trained model to be evaluated val_set (DataLoader): Validation set to perform the evaluation """ rank = dist.get_rank() size = dist.get_world_size() device = torch.device('cuda', rank) # Setup counter of images predicted to 0. predicted_ok = 0 total_images = 0 # make list to collect test ccuracies for each gpu acc_list = [torch.zeros(1, dtype=torch.float).to(device) for _ in range(size)] model.eval() for images, labels in val_set: # Predict image. images = images.to(device) labels = labels.to(device) images = images.view(images.shape[0], -1) pred = model(images) _, predicted = torch.max(pred.data, 1) total_images += labels.size(0) predicted_ok += (predicted == labels).sum().item() dist.all_gather(acc_list, torch.tensor(predicted_ok/total_images).to(device)) if rank == 0: acc = torch.mean(torch.cat(acc_list, 0)) print('\nNumber Of Images Tested = {}'.format(total_images)) print('Model Accuracy = {}'.format(acc)) def main(): """Train a PyTorch analog model with the MNIST dataset.""" rank = dist.get_rank() device = torch.device('cuda', rank) # Load datasets. train_dataset, validation_dataset = load_images() # Prepare the model. model = create_analog_network(INPUT_SIZE, HIDDEN_SIZES, OUTPUT_SIZE) if rank == 0: print(model) model.prepare_for_ddp() model.to(device) # enable parallel training model = DDP(model, device_ids=[rank], output_device=rank) # Train the model. train(model, train_dataset) # Evaluate the trained model. test_evaluation(model, validation_dataset) cleanup() if __name__ == '__main__': # Execute only if run as the entry point into the program world_size = 2 print("Device count: ", world_size) processes = [] ctx = mp.get_context("spawn") for world_rank in range(world_size): print("Process: ", world_rank) p = ctx.Process(target=init_process, args=(world_rank, world_size, main)) p.start() processes.append(p) for p in processes: p.join()
31.199301
96
0.631402
# -*- coding: utf-8 -*- # (C) Copyright 2020, 2021 IBM. All Rights Reserved. # # This code is licensed under the Apache License, Version 2.0. You may # obtain a copy of this license in the LICENSE.txt file in the root directory # of this source tree or at http://www.apache.org/licenses/LICENSE-2.0. # # Any modifications or derivative works of this code must retain this # copyright notice, and modified files need to carry a notice indicating # that they have been altered from the originals. """aihwkit example 20: MNIST training with PyTorch Distributed Data Parallel (DDP). MNIST training example based on the paper: https://www.frontiersin.org/articles/10.3389/fnins.2016.00333/full Uses learning rates of η = 0.01, 0.005, and 0.0025 for epochs 0–10, 11–20, and 21–30, respectively. """ # pylint: disable=invalid-name # pylint: disable=too-many-locals import os from time import time # Imports from PyTorch. import torch from torch import nn import torch.distributed as dist import torch.multiprocessing as mp from torch.nn.parallel import DistributedDataParallel as DDP from torch.optim.lr_scheduler import StepLR from torchvision import datasets, transforms # Imports from aihwkit. from aihwkit.nn import AnalogLinear, AnalogLinearMapped, AnalogSequential from aihwkit.optim import AnalogSGD from aihwkit.simulator.configs import InferenceRPUConfig # Check device DEVICE = torch.device('cuda' if torch.cuda.is_available() else 'cpu') # Path where the datasets will be stored. PATH_DATASET = os.path.join('data', 'DATASET') # Network definition. INPUT_SIZE = 784 HIDDEN_SIZES = [256, 128] OUTPUT_SIZE = 10 # Training parameters. EPOCHS = 30 BATCH_SIZE = 64 def init_process(rank, size, fn, backend='nccl'): """ Initialize the distributed environment. """ print("init process: ", rank) os.environ['MASTER_ADDR'] = 'localhost' os.environ['MASTER_PORT'] = '29411' dist.init_process_group(backend, rank=rank, world_size=size) fn() def cleanup(): """ Destroy distributed processes once they are complete. """ dist.destroy_process_group() def load_images(): """Load images for train from the torchvision datasets.""" rank = dist.get_rank() size = dist.get_world_size() transform = transforms.Compose([transforms.ToTensor()]) # Load the images. train_set = datasets.MNIST(PATH_DATASET, download=True, train=True, transform=transform) val_set = datasets.MNIST(PATH_DATASET, download=True, train=False, transform=transform) train_sampler = torch.utils.data.DistributedSampler(train_set, num_replicas=size, rank=rank, shuffle=True, seed=42) train_data = torch.utils.data.DataLoader(train_set, batch_size=BATCH_SIZE, shuffle=False, num_workers=size, sampler=train_sampler, pin_memory=True) validation_data = torch.utils.data.DataLoader(val_set, batch_size=BATCH_SIZE, shuffle=True, num_workers=size, pin_memory=True) return train_data, validation_data def create_analog_network(input_size, hidden_sizes, output_size): """Create the neural network using analog and digital layers. Args: input_size (int): size of the Tensor at the input. hidden_sizes (list): list of sizes of the hidden layers (2 layers). output_size (int): size of the Tensor at the output. Returns: nn.Module: created analog model """ model = AnalogSequential( AnalogLinear(input_size, hidden_sizes[0], True, rpu_config=InferenceRPUConfig()), nn.Sigmoid(), AnalogLinear(hidden_sizes[0], hidden_sizes[1], True, rpu_config=InferenceRPUConfig()), nn.Sigmoid(), AnalogLinearMapped(hidden_sizes[1], output_size, True, rpu_config=InferenceRPUConfig()), nn.LogSoftmax(dim=1) ) return model def create_sgd_optimizer(model): """Create the analog-aware optimizer. Args: model (nn.Module): model to be trained. Returns: nn.Module: optimizer """ optimizer = AnalogSGD(model.parameters(), lr=0.05) optimizer.regroup_param_groups(model) return optimizer def train(model, train_set): """Train the network. Args: model (nn.Module): model to be trained. train_set (DataLoader): dataset of elements to use as input for training. """ rank = dist.get_rank() size = dist.get_world_size() device = torch.device('cuda', rank) classifier = nn.NLLLoss() optimizer = create_sgd_optimizer(model) scheduler = StepLR(optimizer, step_size=10, gamma=0.5) time_init = time() total_time = [torch.zeros(1, dtype=torch.float).to(device) for _ in range(size)] for epoch_number in range(EPOCHS): total_loss = torch.zeros(1, dtype=torch.float).to(device) total_images = torch.zeros(1, dtype=torch.int).to(device) for images, labels in train_set: images = images.to(device) labels = labels.to(device) # Flatten MNIST images into a 784 vector. images = images.view(images.shape[0], -1) optimizer.zero_grad() # Add training Tensor to the model (input). output = model(images) loss = classifier(output, labels) # Run training (backward propagation). loss.backward() # Optimize weights. optimizer.step() total_images += labels.size(0) total_loss += loss.item() * labels.size(0) dist.all_reduce(total_loss, op=dist.ReduceOp.SUM) dist.all_reduce(total_images, op=dist.ReduceOp.SUM) if rank == 0: train_loss = total_loss.item() / total_images.item() print('Epoch {} - Training loss: {:.16f}'.format(epoch_number, train_loss)) # Decay learning rate if needed. scheduler.step() dist.all_gather(total_time, torch.tensor(time()-time_init).to(device)) if rank == 0: avg_train_time = torch.mean(torch.cat(total_time, 0)) print('\nAverage Training Time (s) = {}'.format(avg_train_time)) def test_evaluation(model, val_set): """Test trained network Args: model (nn.Model): Trained model to be evaluated val_set (DataLoader): Validation set to perform the evaluation """ rank = dist.get_rank() size = dist.get_world_size() device = torch.device('cuda', rank) # Setup counter of images predicted to 0. predicted_ok = 0 total_images = 0 # make list to collect test ccuracies for each gpu acc_list = [torch.zeros(1, dtype=torch.float).to(device) for _ in range(size)] model.eval() for images, labels in val_set: # Predict image. images = images.to(device) labels = labels.to(device) images = images.view(images.shape[0], -1) pred = model(images) _, predicted = torch.max(pred.data, 1) total_images += labels.size(0) predicted_ok += (predicted == labels).sum().item() dist.all_gather(acc_list, torch.tensor(predicted_ok/total_images).to(device)) if rank == 0: acc = torch.mean(torch.cat(acc_list, 0)) print('\nNumber Of Images Tested = {}'.format(total_images)) print('Model Accuracy = {}'.format(acc)) def main(): """Train a PyTorch analog model with the MNIST dataset.""" rank = dist.get_rank() device = torch.device('cuda', rank) # Load datasets. train_dataset, validation_dataset = load_images() # Prepare the model. model = create_analog_network(INPUT_SIZE, HIDDEN_SIZES, OUTPUT_SIZE) if rank == 0: print(model) model.prepare_for_ddp() model.to(device) # enable parallel training model = DDP(model, device_ids=[rank], output_device=rank) # Train the model. train(model, train_dataset) # Evaluate the trained model. test_evaluation(model, validation_dataset) cleanup() if __name__ == '__main__': # Execute only if run as the entry point into the program world_size = 2 print("Device count: ", world_size) processes = [] ctx = mp.get_context("spawn") for world_rank in range(world_size): print("Process: ", world_rank) p = ctx.Process(target=init_process, args=(world_rank, world_size, main)) p.start() processes.append(p) for p in processes: p.join()
0
0
0
23f32a0c11babe495ce710c08005cd357fd003c8
295
py
Python
bitmovin_api_sdk/models/rate_distortion_level_for_quantization.py
jaythecaesarean/bitmovin-api-sdk-python
48166511fcb9082041c552ace55a9b66cc59b794
[ "MIT" ]
11
2019-07-03T10:41:16.000Z
2022-02-25T21:48:06.000Z
bitmovin_api_sdk/models/rate_distortion_level_for_quantization.py
jaythecaesarean/bitmovin-api-sdk-python
48166511fcb9082041c552ace55a9b66cc59b794
[ "MIT" ]
8
2019-11-23T00:01:25.000Z
2021-04-29T12:30:31.000Z
bitmovin_api_sdk/models/rate_distortion_level_for_quantization.py
jaythecaesarean/bitmovin-api-sdk-python
48166511fcb9082041c552ace55a9b66cc59b794
[ "MIT" ]
13
2020-01-02T14:58:18.000Z
2022-03-26T12:10:30.000Z
# coding: utf-8 from enum import Enum from six import string_types, iteritems from bitmovin_api_sdk.common.poscheck import poscheck_model
24.583333
59
0.79661
# coding: utf-8 from enum import Enum from six import string_types, iteritems from bitmovin_api_sdk.common.poscheck import poscheck_model class RateDistortionLevelForQuantization(Enum): DISABLED = "DISABLED" LEVELS = "LEVELS" LEVELS_AND_CODING_GROUPS = "LEVELS_AND_CODING_GROUPS"
0
132
23
da952d5df89a3a8565908d0e2b88228f1f82071c
609
py
Python
ppr-api/src/database/postgres_functions/sim_number.py
cameron-freshworks/ppr
01d6f5d300c791aebad5e58bb4601e9be2ccfc46
[ "Apache-2.0" ]
null
null
null
ppr-api/src/database/postgres_functions/sim_number.py
cameron-freshworks/ppr
01d6f5d300c791aebad5e58bb4601e9be2ccfc46
[ "Apache-2.0" ]
null
null
null
ppr-api/src/database/postgres_functions/sim_number.py
cameron-freshworks/ppr
01d6f5d300c791aebad5e58bb4601e9be2ccfc46
[ "Apache-2.0" ]
null
null
null
"""Maintain db function searchkey_first_name here.""" from alembic_utils.pg_function import PGFunction sim_number = PGFunction( schema="public", signature="sim_number(actual_name character varying)", definition=""" RETURNS numeric LANGUAGE plpgsql AS $function$ DECLARE v_name VARCHAR(60); v_sim_number DECIMAL; BEGIN v_name := regexp_replace(actual_name, '(.)\1{1,}', '\1', 'g'); if length((SELECT public.searchkey_last_name(v_name))) <= 3 then v_sim_number := .65 ; else v_sim_number := .46 ; end if; return v_sim_number; END ; $function$; """ )
21
69
0.673235
"""Maintain db function searchkey_first_name here.""" from alembic_utils.pg_function import PGFunction sim_number = PGFunction( schema="public", signature="sim_number(actual_name character varying)", definition=""" RETURNS numeric LANGUAGE plpgsql AS $function$ DECLARE v_name VARCHAR(60); v_sim_number DECIMAL; BEGIN v_name := regexp_replace(actual_name, '(.)\1{1,}', '\1', 'g'); if length((SELECT public.searchkey_last_name(v_name))) <= 3 then v_sim_number := .65 ; else v_sim_number := .46 ; end if; return v_sim_number; END ; $function$; """ )
0
0
0
ed3b192957fb52fcf051e34f1c02df774bbee1c4
24,801
py
Python
tests/sentry/utils/test_snuba.py
FelixSchwarz/sentry
7c92c4fa2b6b9f214764f48c82594acae1549e52
[ "BSD-3-Clause" ]
null
null
null
tests/sentry/utils/test_snuba.py
FelixSchwarz/sentry
7c92c4fa2b6b9f214764f48c82594acae1549e52
[ "BSD-3-Clause" ]
null
null
null
tests/sentry/utils/test_snuba.py
FelixSchwarz/sentry
7c92c4fa2b6b9f214764f48c82594acae1549e52
[ "BSD-3-Clause" ]
null
null
null
from __future__ import absolute_import from datetime import datetime from mock import patch import pytest import pytz from sentry.models import GroupRelease, Release from sentry.testutils import TestCase, SnubaTestCase from sentry.testutils.helpers.datetime import iso_format, before_now from sentry.utils.snuba import ( _prepare_query_params, get_snuba_translators, zerofill, get_json_type, get_snuba_column_name, detect_dataset, transform_aliases_and_query, Dataset, SnubaQueryParams, UnqualifiedQueryError, ) class TransformAliasesAndQueryTransactionsTest(TestCase): """ This test mocks snuba.raw_query because there is currently no way to insert data into the transactions dataset during tests. """ @patch("sentry.utils.snuba.raw_query") @patch("sentry.utils.snuba.raw_query") @patch("sentry.utils.snuba.raw_query") @patch("sentry.utils.snuba.raw_query") @patch("sentry.utils.snuba.raw_query") @patch("sentry.utils.snuba.raw_query") @patch("sentry.utils.snuba.raw_query") @patch("sentry.utils.snuba.raw_query")
39.056693
100
0.570703
from __future__ import absolute_import from datetime import datetime from mock import patch import pytest import pytz from sentry.models import GroupRelease, Release from sentry.testutils import TestCase, SnubaTestCase from sentry.testutils.helpers.datetime import iso_format, before_now from sentry.utils.snuba import ( _prepare_query_params, get_snuba_translators, zerofill, get_json_type, get_snuba_column_name, detect_dataset, transform_aliases_and_query, Dataset, SnubaQueryParams, UnqualifiedQueryError, ) class SnubaUtilsTest(TestCase): def setUp(self): self.now = datetime.utcnow().replace( hour=0, minute=0, second=0, microsecond=0, tzinfo=pytz.UTC ) self.proj1 = self.create_project() self.proj1env1 = self.create_environment(project=self.proj1, name="prod") self.proj1group1 = self.create_group(self.proj1) self.proj1group2 = self.create_group(self.proj1) self.release1 = Release.objects.create( organization_id=self.organization.id, version="1" * 10, date_added=self.now ) self.release1.add_project(self.proj1) self.release2 = Release.objects.create( organization_id=self.organization.id, version="2" * 10, date_added=self.now ) self.release2.add_project(self.proj1) self.group1release1 = GroupRelease.objects.create( project_id=self.proj1.id, group_id=self.proj1group1.id, release_id=self.release1.id ) self.group1release2 = GroupRelease.objects.create( project_id=self.proj1.id, group_id=self.proj1group1.id, release_id=self.release2.id ) self.group2release1 = GroupRelease.objects.create( project_id=self.proj1.id, group_id=self.proj1group2.id, release_id=self.release1.id ) def test_translation(self): # Case 1: No translation filter_keys = {"sdk": ["python", "js"]} forward, reverse = get_snuba_translators(filter_keys) assert forward(filter_keys) == filter_keys result = [{"sdk": "python", "count": 123}, {"sdk": "js", "count": 234}] assert all(reverse(row) == row for row in result) # Case 2: Environment ID -> Name and back filter_keys = {"environment": [self.proj1env1.id]} forward, reverse = get_snuba_translators(filter_keys) assert forward(filter_keys) == {"environment": [self.proj1env1.name]} row = {"environment": self.proj1env1.name, "count": 123} assert reverse(row) == {"environment": self.proj1env1.id, "count": 123} # Case 3, both Environment and Release filter_keys = { "environment": [self.proj1env1.id], "tags[sentry:release]": [self.release1.id], } forward, reverse = get_snuba_translators(filter_keys) assert forward(filter_keys) == { "environment": [self.proj1env1.name], "tags[sentry:release]": [self.release1.version], } row = { "environment": self.proj1env1.name, "tags[sentry:release]": self.release1.version, "count": 123, } assert reverse(row) == { "environment": self.proj1env1.id, "tags[sentry:release]": self.release1.id, "count": 123, } # Case 4: 2 Groups, many-to-many mapping of Groups # to Releases. Reverse translation depends on multiple # fields. filter_keys = { "issue": [self.proj1group1.id, self.proj1group2.id], "tags[sentry:release]": [ self.group1release1.id, self.group1release2.id, self.group2release1.id, ], } forward, reverse = get_snuba_translators(filter_keys, is_grouprelease=True) assert forward(filter_keys) == { "issue": [self.proj1group1.id, self.proj1group2.id], "tags[sentry:release]": [ self.release1.version, self.release2.version, self.release1.version, # Duplicated because 2 GroupReleases refer to it ], } result = [ { "issue": self.proj1group1.id, "tags[sentry:release]": self.release1.version, "count": 1, }, { "issue": self.proj1group1.id, "tags[sentry:release]": self.release2.version, "count": 2, }, { "issue": self.proj1group2.id, "tags[sentry:release]": self.release1.version, "count": 3, }, ] result = [reverse(r) for r in result] assert result == [ { "issue": self.proj1group1.id, "tags[sentry:release]": self.group1release1.id, "count": 1, }, { "issue": self.proj1group1.id, "tags[sentry:release]": self.group1release2.id, "count": 2, }, { "issue": self.proj1group2.id, "tags[sentry:release]": self.group2release1.id, "count": 3, }, ] def test_zerofill(self): results = zerofill( {}, datetime(2019, 1, 2, 0, 0), datetime(2019, 1, 9, 23, 59, 59), 86400, "time" ) results_desc = zerofill( {}, datetime(2019, 1, 2, 0, 0), datetime(2019, 1, 9, 23, 59, 59), 86400, "-time" ) assert results == list(reversed(results_desc)) # Bucket for the 2, 3, 4, 5, 6, 7, 8, 9 assert len(results) == 8 assert results[0]["time"] == 1546387200 assert results[7]["time"] == 1546992000 def test_get_json_type(self): assert get_json_type("UInt8") == "boolean" assert get_json_type("UInt16") == "integer" assert get_json_type("UInt32") == "integer" assert get_json_type("UInt64") == "integer" assert get_json_type("Float32") == "number" assert get_json_type("Float64") == "number" assert get_json_type("Nullable(Float64)") == "number" assert get_json_type("Array(String)") == "array" assert get_json_type("Char") == "string" assert get_json_type("unknown") == "string" assert get_json_type("") == "string" def test_get_snuba_column_name(self): assert get_snuba_column_name("project_id") == "project_id" assert get_snuba_column_name("start") == "start" assert get_snuba_column_name("'thing'") == "'thing'" assert get_snuba_column_name("id") == "event_id" assert get_snuba_column_name("geo.region") == "geo_region" # This is odd behavior but captures what we do currently. assert get_snuba_column_name("tags[sentry:user]") == "tags[tags[sentry:user]]" assert get_snuba_column_name("organization") == "tags[organization]" class TransformAliasesAndQueryTest(SnubaTestCase, TestCase): def setUp(self): super(TransformAliasesAndQueryTest, self).setUp() self.environment = self.create_environment(self.project, name="prod") self.release = self.create_release(self.project, version="first-release") self.store_event( data={ "message": "oh no", "release": "first-release", "environment": "prod", "platform": "python", "user": {"id": "99", "email": "bruce@example.com", "username": "brucew"}, "timestamp": iso_format(before_now(minutes=1)), }, project_id=self.project.id, ) def test_field_aliasing_in_selected_columns(self): result = transform_aliases_and_query( selected_columns=["project.id", "user.email", "release"], filter_keys={"project_id": [self.project.id]}, ) data = result["data"] assert len(data) == 1 assert data[0]["project.id"] == self.project.id assert data[0]["user.email"] == "bruce@example.com" assert data[0]["release"] == "first-release" def test_field_aliasing_in_aggregate_functions_and_groupby(self): result = transform_aliases_and_query( selected_columns=["project.id"], aggregations=[["uniq", "user.email", "uniq_email"]], filter_keys={"project_id": [self.project.id]}, groupby=["project.id"], ) data = result["data"] assert len(data) == 1 assert data[0]["project.id"] == self.project.id assert data[0]["uniq_email"] == 1 def test_field_aliasing_in_conditions(self): result = transform_aliases_and_query( selected_columns=["project.id", "user.email"], conditions=[["user.email", "=", "bruce@example.com"]], filter_keys={"project_id": [self.project.id]}, ) data = result["data"] assert len(data) == 1 assert data[0]["project.id"] == self.project.id assert data[0]["user.email"] == "bruce@example.com" def test_autoconversion_of_time_column(self): result = transform_aliases_and_query( aggregations=[["count", "", "count"]], filter_keys={"project_id": [self.project.id]}, start=before_now(minutes=5), end=before_now(), groupby=["time"], orderby=["time"], rollup=3600, ) data = result["data"] assert isinstance(data[-1]["time"], int) assert data[-1]["count"] == 1 def test_conversion_of_release_filter_key(self): result = transform_aliases_and_query( selected_columns=["id", "message"], filter_keys={ "release": [self.create_release(self.project).id], "project_id": [self.project.id], }, ) assert len(result["data"]) == 0 result = transform_aliases_and_query( selected_columns=["id", "message"], filter_keys={"release": [self.release.id], "project_id": [self.project.id]}, ) assert len(result["data"]) == 1 def test_conversion_of_environment_filter_key(self): result = transform_aliases_and_query( selected_columns=["id", "message"], filter_keys={ "environment": [self.create_environment(self.project).id], "project_id": [self.project.id], }, ) assert len(result["data"]) == 0 result = transform_aliases_and_query( selected_columns=["id", "message"], filter_keys={"environment": [self.environment.id], "project_id": [self.project.id]}, ) assert len(result["data"]) == 1 class TransformAliasesAndQueryTransactionsTest(TestCase): """ This test mocks snuba.raw_query because there is currently no way to insert data into the transactions dataset during tests. """ @patch("sentry.utils.snuba.raw_query") def test_selected_columns_aliasing_in_function(self, mock_query): mock_query.return_value = { "meta": [{"name": "transaction"}, {"name": "duration"}], "data": [{"transaction": "api.do_things", "duration": 200}], } transform_aliases_and_query( selected_columns=["transaction", "transaction.duration"], aggregations=[ ["argMax", ["id", "transaction.duration"], "longest"], ["uniq", "transaction", "uniq_transaction"], ], filter_keys={"project_id": [self.project.id]}, ) mock_query.assert_called_with( selected_columns=["transaction_name", "duration"], aggregations=[ ["argMax", ["event_id", "duration"], "longest"], ["uniq", "transaction_name", "uniq_transaction"], ], filter_keys={"project_id": [self.project.id]}, dataset=Dataset.Transactions, arrayjoin=None, end=None, start=None, conditions=None, groupby=None, having=None, orderby=None, ) @patch("sentry.utils.snuba.raw_query") def test_selected_columns_opaque_string(self, mock_query): mock_query.return_value = { "meta": [{"name": "transaction"}, {"name": "p95"}], "data": [{"transaction": "api.do_things", "p95": 200}], } transform_aliases_and_query( selected_columns=["transaction"], aggregations=[ ["quantileTiming(0.95)(duration)", "", "p95"], ["uniq", "transaction", "uniq_transaction"], ], filter_keys={"project_id": [self.project.id]}, ) mock_query.assert_called_with( selected_columns=["transaction_name"], aggregations=[ ["quantileTiming(0.95)(duration)", "", "p95"], ["uniq", "transaction_name", "uniq_transaction"], ], filter_keys={"project_id": [self.project.id]}, dataset=Dataset.Transactions, arrayjoin=None, end=None, start=None, conditions=None, groupby=None, having=None, orderby=None, ) @patch("sentry.utils.snuba.raw_query") def test_orderby_aliasing(self, mock_query): mock_query.return_value = { "meta": [{"name": "transaction_name"}, {"name": "duration"}], "data": [{"transaction_name": "api.do_things", "duration": 200}], } transform_aliases_and_query( selected_columns=["transaction", "transaction.duration"], filter_keys={"project_id": [self.project.id]}, orderby=["timestamp"], ) mock_query.assert_called_with( selected_columns=["transaction_name", "duration"], filter_keys={"project_id": [self.project.id]}, dataset=Dataset.Transactions, orderby=["finish_ts"], aggregations=None, arrayjoin=None, end=None, start=None, conditions=None, groupby=None, having=None, ) @patch("sentry.utils.snuba.raw_query") def test_conditions_order_and_groupby_aliasing(self, mock_query): mock_query.return_value = { "meta": [{"name": "transaction_name"}, {"name": "duration"}], "data": [{"transaction_name": "api.do_things", "duration": 200}], } transform_aliases_and_query( selected_columns=["transaction", "transaction.duration"], conditions=[ ["transaction.duration", "=", 200], ["time", ">", "2019-09-23"], ["http.method", "=", "GET"], ], aggregations=[["count", "", "count"]], groupby=["transaction.op"], orderby=["-timestamp", "-count"], filter_keys={"project_id": [self.project.id]}, ) mock_query.assert_called_with( selected_columns=["transaction_name", "duration"], conditions=[ ["duration", "=", 200], ["bucketed_end", ">", "2019-09-23"], ["tags[http.method]", "=", "GET"], ], aggregations=[["count", "", "count"]], filter_keys={"project_id": [self.project.id]}, groupby=["transaction_op"], orderby=["-finish_ts", "-count"], dataset=Dataset.Transactions, arrayjoin=None, end=None, start=None, having=None, ) @patch("sentry.utils.snuba.raw_query") def test_conditions_nested_function_aliasing(self, mock_query): mock_query.return_value = { "meta": [{"name": "transaction_name"}], "data": [{"transaction_name": "api.do_things"}], } transform_aliases_and_query( selected_columns=["transaction"], conditions=[ ["event.type", "=", "transaction"], ["match", [["ifNull", ["tags[user_email]", ""]], "'(?i)^.*\@sentry\.io$'"]], [["positionCaseInsensitive", ["message", "'recent-searches'"]], "!=", 0], ], aggregations=[["count", "", "count"]], filter_keys={"project_id": [self.project.id]}, ) mock_query.assert_called_with( selected_columns=["transaction_name"], conditions=[ ["match", [["ifNull", ["tags[user_email]", ""]], "'(?i)^.*\@sentry\.io$'"]], [["positionCaseInsensitive", ["transaction_name", "'recent-searches'"]], "!=", 0], ], aggregations=[["count", "", "count"]], filter_keys={"project_id": [self.project.id]}, dataset=Dataset.Transactions, groupby=None, orderby=None, arrayjoin=None, end=None, start=None, having=None, ) @patch("sentry.utils.snuba.raw_query") def test_condition_removal(self, mock_query): mock_query.return_value = { "meta": [{"name": "transaction_name"}, {"name": "duration"}], "data": [{"transaction_name": "api.do_things", "duration": 200}], } transform_aliases_and_query( selected_columns=["transaction", "transaction.duration"], conditions=[["event.type", "=", "transaction"], ["duration", ">", 200]], groupby=["transaction.op"], filter_keys={"project_id": [self.project.id]}, ) mock_query.assert_called_with( selected_columns=["transaction_name", "duration"], conditions=[["duration", ">", 200]], filter_keys={"project_id": [self.project.id]}, groupby=["transaction_op"], dataset=Dataset.Transactions, aggregations=None, arrayjoin=None, end=None, start=None, having=None, orderby=None, ) @patch("sentry.utils.snuba.raw_query") def test_condition_not_remove_type_csp(self, mock_query): mock_query.return_value = { "meta": [{"name": "transaction_name"}, {"name": "duration"}], "data": [{"transaction_name": "api.do_things", "duration": 200}], } transform_aliases_and_query( selected_columns=["transaction", "transaction.duration"], conditions=[ ["event.type", "=", "transaction"], ["type", "=", "csp"], ["duration", ">", 200], ], groupby=["transaction.op"], filter_keys={"project_id": [self.project.id]}, ) mock_query.assert_called_with( selected_columns=["transaction_name", "duration"], conditions=[["tags[type]", "=", "csp"], ["duration", ">", 200]], filter_keys={"project_id": [self.project.id]}, groupby=["transaction_op"], dataset=Dataset.Transactions, aggregations=None, arrayjoin=None, end=None, start=None, having=None, orderby=None, ) @patch("sentry.utils.snuba.raw_query") def test_condition_transform(self, mock_query): mock_query.return_value = { "meta": [{"name": "transaction_name"}, {"name": "duration"}], "data": [{"transaction_name": "api.do_things", "duration": 200}], } transform_aliases_and_query( selected_columns=["transaction", "transaction.duration"], conditions=[["http_method", "=", "GET"]], groupby=["transaction.op"], filter_keys={"project_id": [self.project.id]}, ) mock_query.assert_called_with( selected_columns=["transaction_name", "duration"], conditions=[["tags[http_method]", "=", "GET"]], filter_keys={"project_id": [self.project.id]}, groupby=["transaction_op"], dataset=Dataset.Transactions, aggregations=None, arrayjoin=None, end=None, start=None, having=None, orderby=None, ) class DetectDatasetTest(TestCase): def test_dataset_key(self): query = {"dataset": Dataset.Events, "conditions": [["event.type", "=", "transaction"]]} assert detect_dataset(query) == Dataset.Events def test_event_type_condition(self): query = {"conditions": [["event.type", "=", "transaction"]]} assert detect_dataset(query) == Dataset.Transactions query = {"conditions": [["event.type", "=", "error"]]} assert detect_dataset(query) == Dataset.Events query = {"conditions": [["event.type", "=", "transaction"]]} assert detect_dataset(query) == Dataset.Transactions query = {"conditions": [["event.type", "=", "error"]]} assert detect_dataset(query) == Dataset.Events query = {"conditions": [["type", "!=", "transactions"]]} assert detect_dataset(query) == Dataset.Events def test_conditions(self): query = {"conditions": [["transaction", "=", "api.do_thing"]]} assert detect_dataset(query) == Dataset.Events query = {"conditions": [["transaction.duration", ">", "3"]]} assert detect_dataset(query) == Dataset.Transactions # Internal aliases are treated as tags query = {"conditions": [["duration", ">", "3"]]} assert detect_dataset(query) == Dataset.Events def test_conditions_aliased(self): query = {"conditions": [["duration", ">", "3"]]} assert detect_dataset(query, aliased_conditions=True) == Dataset.Transactions # Not an internal alias query = {"conditions": [["transaction.duration", ">", "3"]]} assert detect_dataset(query, aliased_conditions=True) == Dataset.Events def test_selected_columns(self): query = {"selected_columns": ["id", "message"]} assert detect_dataset(query) == Dataset.Events query = {"selected_columns": ["id", "transaction", "transaction.duration"]} assert detect_dataset(query) == Dataset.Transactions def test_aggregations(self): query = {"aggregations": [["argMax", ["id", "timestamp"], "latest_event"]]} assert detect_dataset(query) == Dataset.Events query = {"aggregations": [["argMax", ["id", "duration"], "longest"]]} assert detect_dataset(query) == Dataset.Events query = {"aggregations": [["quantileTiming(0.95)", "transaction.duration", "p95_duration"]]} assert detect_dataset(query) == Dataset.Transactions query = {"aggregations": [["uniq", "transaction.op", "uniq_transaction_op"]]} assert detect_dataset(query) == Dataset.Transactions class PrepareQueryParamsTest(TestCase): def test_events_dataset_with_project_id(self): query_params = SnubaQueryParams( dataset=Dataset.Events, filter_keys={"project_id": [self.project.id]} ) kwargs, _, _ = _prepare_query_params(query_params) assert kwargs["project"] == [self.project.id] def test_transactions_dataset_with_project_id(self): query_params = SnubaQueryParams( dataset=Dataset.Transactions, filter_keys={"project_id": [self.project.id]} ) kwargs, _, _ = _prepare_query_params(query_params) assert kwargs["project"] == [self.project.id] def test_outcomes_dataset_with_org_id(self): query_params = SnubaQueryParams( dataset=Dataset.Outcomes, filter_keys={"org_id": [self.organization.id]} ) kwargs, _, _ = _prepare_query_params(query_params) assert kwargs["organization"] == self.organization.id def test_outcomes_dataset_with_key_id(self): key = self.create_project_key(project=self.project) query_params = SnubaQueryParams(dataset=Dataset.Outcomes, filter_keys={"key_id": [key.id]}) kwargs, _, _ = _prepare_query_params(query_params) assert kwargs["organization"] == self.organization.id def test_outcomes_dataset_with_no_org_id_given(self): query_params = SnubaQueryParams(dataset=Dataset.Outcomes) with pytest.raises(UnqualifiedQueryError): _prepare_query_params(query_params) def test_invalid_dataset_provided(self): query_params = SnubaQueryParams(dataset="invalid_dataset") with pytest.raises(UnqualifiedQueryError): _prepare_query_params(query_params)
22,658
80
944
fa132a8030c21b8f2d0d0428523ec55f885b4421
3,712
py
Python
src/utoolbox/filters/perona_malik.py
liuyenting/utoolbox-legacy
dfcb24701ca25a37a223cc3c14b4433e6c296bfd
[ "Apache-2.0" ]
2
2020-09-03T06:22:14.000Z
2020-10-04T10:14:56.000Z
src/utoolbox/filters/perona_malik.py
liuyenting/utoolbox-legacy
dfcb24701ca25a37a223cc3c14b4433e6c296bfd
[ "Apache-2.0" ]
null
null
null
src/utoolbox/filters/perona_malik.py
liuyenting/utoolbox-legacy
dfcb24701ca25a37a223cc3c14b4433e6c296bfd
[ "Apache-2.0" ]
null
null
null
""" Perona-Malik anisotropic smoothing filter [Sergeevich]_. .. [Sergeevich] Employing the Perona - Malik anisotropic filter for the problem of landing site detection: https://github.com/Galarius/pm-ocl """ import logging from math import ceil import os import cupy as cp import numpy as np from utoolbox.parallel import RawKernelFile __all__ = ["PeronaMalik2D", "PeronaMalik3D"] logger = logging.getLogger(__name__) class PeronaMalik2D(object): """ Perona-Malik anisotropic smoothing filter in 2D. Args: threshold (float, optional): Conduction function threshold. niter (float, optiona): Number of iterations. tile_width (int, optional): Tile size during kernel launch. """ def __call__(self, x, in_place=True): """ Args: x (cp.ndarray): Input data. in_place (bool, optional): Write result into provided array. """ ny, nx = x.shape grid_sz = (int(ceil(nx / self._tile_width)), int(ceil(ny / self._tile_width))) in_buf = x if in_place else cp.copy(x) out_buf = cp.empty_like(in_buf) for _ in range(self._niter): self._kernels["perona_malik_2d_kernel"]( grid_sz, (self._tile_width,) * 2, (out_buf, in_buf, np.float32(self._threshold), nx, ny), ) in_buf, out_buf = out_buf, in_buf return in_buf class PeronaMalik3D(object): """ Perona-Malik anisotropic smoothing filter in 3D. Args: threshold (float, optional): Conduction function threshold. niter (float, optiona): Number of iterations. tile_width (int, optional): Tile size during kernel launch. """ def __call__(self, x, in_place=True): """ Args: x (cp.ndarray): Input data. in_place (bool, optional): Write result into provided array. """ nz, ny, nx = x.shape grid_sz = ( int(ceil(nx / self._tile_width)), int(ceil(ny / self._tile_width)), int(ceil(nz / self._tile_width)), ) in_buf = x if in_place else cp.copy(x) out_buf = cp.empty_like(in_buf) for _ in range(self._niter): self._kernels["perona_malik_3d_kernel"]( grid_sz, (self._tile_width,) * 3, (out_buf, in_buf, np.float32(self._threshold), nx, ny, nz), ) in_buf, out_buf = out_buf, in_buf return in_buf if __name__ == "__main__": from imageio import volread, volwrite from utoolbox.exposure.rescale_intensity import RescaleIntensity in_data = volread("mito.tif") _, _, nc = in_data.shape pm = PeronaMalik3D(threshold=10, niter=16) in_data = in_data.astype(np.float32) in_data = cp.asarray(in_data) out_data = pm(in_data) ri = RescaleIntensity() out_data = ri(out_data, out_range=np.uint16) out_data = cp.asnumpy(out_data) out_data = out_data.astype(np.uint16) volwrite("result.tif", out_data)
30.42623
141
0.627155
""" Perona-Malik anisotropic smoothing filter [Sergeevich]_. .. [Sergeevich] Employing the Perona - Malik anisotropic filter for the problem of landing site detection: https://github.com/Galarius/pm-ocl """ import logging from math import ceil import os import cupy as cp import numpy as np from utoolbox.parallel import RawKernelFile __all__ = ["PeronaMalik2D", "PeronaMalik3D"] logger = logging.getLogger(__name__) class PeronaMalik2D(object): """ Perona-Malik anisotropic smoothing filter in 2D. Args: threshold (float, optional): Conduction function threshold. niter (float, optiona): Number of iterations. tile_width (int, optional): Tile size during kernel launch. """ def __init__(self, threshold=30.0, niter=16, tile_width=16): cu_file = os.path.join(os.path.dirname(__file__), "perona_malik.cu") self._kernels = RawKernelFile(cu_file, tile_width=tile_width) self._tile_width = tile_width self._threshold, self._niter = np.float32(threshold), niter def __call__(self, x, in_place=True): """ Args: x (cp.ndarray): Input data. in_place (bool, optional): Write result into provided array. """ ny, nx = x.shape grid_sz = (int(ceil(nx / self._tile_width)), int(ceil(ny / self._tile_width))) in_buf = x if in_place else cp.copy(x) out_buf = cp.empty_like(in_buf) for _ in range(self._niter): self._kernels["perona_malik_2d_kernel"]( grid_sz, (self._tile_width,) * 2, (out_buf, in_buf, np.float32(self._threshold), nx, ny), ) in_buf, out_buf = out_buf, in_buf return in_buf class PeronaMalik3D(object): """ Perona-Malik anisotropic smoothing filter in 3D. Args: threshold (float, optional): Conduction function threshold. niter (float, optiona): Number of iterations. tile_width (int, optional): Tile size during kernel launch. """ def __init__(self, threshold=30.0, niter=16, tile_width=8): cu_file = os.path.join(os.path.dirname(__file__), "perona_malik.cu") self._kernels = RawKernelFile(cu_file, tile_width=tile_width) self._tile_width = tile_width self._threshold, self._niter = np.float32(threshold), niter def __call__(self, x, in_place=True): """ Args: x (cp.ndarray): Input data. in_place (bool, optional): Write result into provided array. """ nz, ny, nx = x.shape grid_sz = ( int(ceil(nx / self._tile_width)), int(ceil(ny / self._tile_width)), int(ceil(nz / self._tile_width)), ) in_buf = x if in_place else cp.copy(x) out_buf = cp.empty_like(in_buf) for _ in range(self._niter): self._kernels["perona_malik_3d_kernel"]( grid_sz, (self._tile_width,) * 3, (out_buf, in_buf, np.float32(self._threshold), nx, ny, nz), ) in_buf, out_buf = out_buf, in_buf return in_buf if __name__ == "__main__": from imageio import volread, volwrite from utoolbox.exposure.rescale_intensity import RescaleIntensity in_data = volread("mito.tif") _, _, nc = in_data.shape pm = PeronaMalik3D(threshold=10, niter=16) in_data = in_data.astype(np.float32) in_data = cp.asarray(in_data) out_data = pm(in_data) ri = RescaleIntensity() out_data = ri(out_data, out_range=np.uint16) out_data = cp.asnumpy(out_data) out_data = out_data.astype(np.uint16) volwrite("result.tif", out_data)
585
0
54
3c4d27d48356baf985b7fec6b617c3526b7bce2b
1,902
py
Python
DeepAgent/interfaces/ibaseBuffer.py
LANNDS18/DeepAgent_Atari
d9e984f5eba35b845b3bbb2a06dc7975159dbf43
[ "MIT" ]
3
2022-02-28T15:44:16.000Z
2022-03-02T17:00:59.000Z
DeepAgent/interfaces/ibaseBuffer.py
LANNDS18/DeepAgent_DemonAttack
ce86a8365ac31833cd5824a68d81892871d81182
[ "MIT" ]
null
null
null
DeepAgent/interfaces/ibaseBuffer.py
LANNDS18/DeepAgent_DemonAttack
ce86a8365ac31833cd5824a68d81892871d81182
[ "MIT" ]
null
null
null
from collections import namedtuple Transition = namedtuple("Transition", ("state", "action", "reward", "done", "new_state")) class BaseBuffer: """ Base class for replay buffer. """ def __init__(self, size, batch_size=32, n_step=0): """ Initialize replay buffer. Args: size: Buffer maximum size. batch_size: Size of the batch that should be used in get_sample() implementation. n_step: The reward after n_step after applying discount factor """ assert size > 0, f'Buffer size should be > 0, got {size}' assert batch_size > 0, f'Buffer batch size should be > 0, got {batch_size}' assert ( batch_size <= size ), f'Buffer batch size `{batch_size}` should be <= size `{size}`' self.size = size self.batch_size = batch_size self.n_step = n_step self.current_size = 0 def append(self, *args): """ Add experience to buffer. Args: *args: Items to store, types are implementation specific. """ raise NotImplementedError( f'append() should be implemented by {self.__class__.__name__} subclasses' ) def get_sample_indices(self): """ Random sample indices from stored experience. :return: List of batch_size indices. """ raise NotImplementedError( f'get_sample_indices() should be implemented by {self.__class__.__name__} subclasses' ) def get_sample(self, indices): """ Sample from stored experience. Args: *indices: The indices of getting samo Returns: Sample as numpy array. """ raise NotImplementedError( f'get_sample() should be implemented by {self.__class__.__name__} subclasses' )
31.7
97
0.585174
from collections import namedtuple Transition = namedtuple("Transition", ("state", "action", "reward", "done", "new_state")) class BaseBuffer: """ Base class for replay buffer. """ def __init__(self, size, batch_size=32, n_step=0): """ Initialize replay buffer. Args: size: Buffer maximum size. batch_size: Size of the batch that should be used in get_sample() implementation. n_step: The reward after n_step after applying discount factor """ assert size > 0, f'Buffer size should be > 0, got {size}' assert batch_size > 0, f'Buffer batch size should be > 0, got {batch_size}' assert ( batch_size <= size ), f'Buffer batch size `{batch_size}` should be <= size `{size}`' self.size = size self.batch_size = batch_size self.n_step = n_step self.current_size = 0 def append(self, *args): """ Add experience to buffer. Args: *args: Items to store, types are implementation specific. """ raise NotImplementedError( f'append() should be implemented by {self.__class__.__name__} subclasses' ) def get_sample_indices(self): """ Random sample indices from stored experience. :return: List of batch_size indices. """ raise NotImplementedError( f'get_sample_indices() should be implemented by {self.__class__.__name__} subclasses' ) def get_sample(self, indices): """ Sample from stored experience. Args: *indices: The indices of getting samo Returns: Sample as numpy array. """ raise NotImplementedError( f'get_sample() should be implemented by {self.__class__.__name__} subclasses' )
0
0
0
792a0df8a0a05daebef053e1d6c299973259af08
254
py
Python
office365/onedrive/sharepointIds.py
wreiner/Office365-REST-Python-Client
476bbce4f5928a140b4f5d33475d0ac9b0783530
[ "MIT" ]
544
2016-08-04T17:10:16.000Z
2022-03-31T07:17:20.000Z
office365/onedrive/sharepointIds.py
wreiner/Office365-REST-Python-Client
476bbce4f5928a140b4f5d33475d0ac9b0783530
[ "MIT" ]
438
2016-10-11T12:24:22.000Z
2022-03-31T19:30:35.000Z
office365/onedrive/sharepointIds.py
wreiner/Office365-REST-Python-Client
476bbce4f5928a140b4f5d33475d0ac9b0783530
[ "MIT" ]
202
2016-08-22T19:29:40.000Z
2022-03-30T20:26:15.000Z
from office365.runtime.client_value import ClientValue class SharePointIds(ClientValue): """The SharePointIds resource groups the various identifiers for an item stored in a SharePoint site or OneDrive for Business into a single structure. """
36.285714
116
0.795276
from office365.runtime.client_value import ClientValue class SharePointIds(ClientValue): """The SharePointIds resource groups the various identifiers for an item stored in a SharePoint site or OneDrive for Business into a single structure. """
0
0
0
3da4e40bc237552e858407e97b5b4238a39df90c
1,945
py
Python
passgenerate/passgenerate.py
eaybek/passgenerate
b08896efa6127ef597521c6067e09f6921032acf
[ "MIT" ]
null
null
null
passgenerate/passgenerate.py
eaybek/passgenerate
b08896efa6127ef597521c6067e09f6921032acf
[ "MIT" ]
null
null
null
passgenerate/passgenerate.py
eaybek/passgenerate
b08896efa6127ef597521c6067e09f6921032acf
[ "MIT" ]
null
null
null
import random
26.643836
58
0.617995
import random def generate( times=5, passlength=32, include=[], exclude=[], include_numbers=True, include_big_letters=True, include_little_letters=True, include_special_chars1=False, include_special_chars2=False, include_special_chars3=False, include_special_chars4=False, ): if times == 0: return [] included_chars = [] special_chars1 = range(32, 48) numbers = range(48, 58) special_chars2 = range(58, 65) big_letters = range(65, 91) special_chars3 = range(91, 97) little_letters = range(97, 123) special_chars4 = range(123, 127) if include_special_chars1: included_chars += [chr(i) for i in special_chars1] if include_numbers: included_chars += [chr(i) for i in numbers] if include_special_chars2: included_chars += [chr(i) for i in special_chars2] if include_big_letters: included_chars += [chr(i) for i in big_letters] if include_special_chars3: included_chars += [chr(i) for i in special_chars3] if include_little_letters: included_chars += [chr(i) for i in little_letters] if include_special_chars4: included_chars += [chr(i) for i in special_chars4] included_chars += [i for i in include] for i in exclude: if i in included_chars: included_chars.remove(i) ic_size = len(included_chars) password = "" for i in range(0, passlength): password += included_chars[ random.randint(0, ic_size - 1) ] return [ password, *generate( times - 1, passlength, include, exclude, include_numbers, include_big_letters, include_little_letters, include_special_chars1, include_special_chars2, include_special_chars3, include_special_chars4, ), ]
1,907
0
23
5aed65375fea66e5d3e5e1b637854272be09ff01
1,998
py
Python
uci.py
zeFresk/deep-position-analysis
f3f24e4587cf623e8b7d19a8e5682c7b6d0efaf4
[ "MIT" ]
20
2018-12-12T12:50:16.000Z
2021-09-29T14:39:23.000Z
uci.py
ScallyBag/deep-position-analysis
f3f24e4587cf623e8b7d19a8e5682c7b6d0efaf4
[ "MIT" ]
6
2019-07-22T18:22:25.000Z
2021-07-01T09:49:30.000Z
uci.py
ScallyBag/deep-position-analysis
f3f24e4587cf623e8b7d19a8e5682c7b6d0efaf4
[ "MIT" ]
1
2021-09-29T14:39:09.000Z
2021-09-29T14:39:09.000Z
import chess.uci import sys import os ########################################### ########## UCI config functions ########### ########################################### def write_config(opt, file): """Export options dictionnary to config file.""" for key, value in opt.items(): if key.lower() == "multipv": continue file.write("{:s} = {:s}\n".format(str(key), str(value))) def update_options_from_config(opt, file): """Read a config and update dictionnary opt""" data = file.readlines() for line in data: key, val = line.split('=') opt[key.strip()] = val.strip() #remove whitespace return opt def default_options(engine): """Returns a dictionnary containing all engine options at their default value""" Options = engine.options ret = dict() for e in Options: ret[Options[e].name] = Options[e].default return ret def load_options(engine, config): """ Load engine uci options from config, if no config exists will create one. Returns a tuple : (config , boolean containing whereas or not we used a default config)""" if config == "<autodiscover>": #no config provided engine_name = engine.name.split()[0] # first string in name config = engine_name + ".cfg" if not os.path.isfile(config): # no existing config file print("\n!Warning: No config file for {:s} detected, creating one. Default values used.\n".format(engine_name)) f = open(config, "w") opt = default_options(engine) write_config(opt, f) # exporting config to file return (opt, True) if os.path.isfile(config): # custom or default config exists opt = default_options(engine) f = open(config, "r") update_options_from_config(opt, f) return (opt, False) else: #no config found sys.stderr.write("!!Error: config {:s} doesn't exists ! Exiting...\n") sys.exit(-2)
31.21875
123
0.588088
import chess.uci import sys import os ########################################### ########## UCI config functions ########### ########################################### def write_config(opt, file): """Export options dictionnary to config file.""" for key, value in opt.items(): if key.lower() == "multipv": continue file.write("{:s} = {:s}\n".format(str(key), str(value))) def update_options_from_config(opt, file): """Read a config and update dictionnary opt""" data = file.readlines() for line in data: key, val = line.split('=') opt[key.strip()] = val.strip() #remove whitespace return opt def default_options(engine): """Returns a dictionnary containing all engine options at their default value""" Options = engine.options ret = dict() for e in Options: ret[Options[e].name] = Options[e].default return ret def load_options(engine, config): """ Load engine uci options from config, if no config exists will create one. Returns a tuple : (config , boolean containing whereas or not we used a default config)""" if config == "<autodiscover>": #no config provided engine_name = engine.name.split()[0] # first string in name config = engine_name + ".cfg" if not os.path.isfile(config): # no existing config file print("\n!Warning: No config file for {:s} detected, creating one. Default values used.\n".format(engine_name)) f = open(config, "w") opt = default_options(engine) write_config(opt, f) # exporting config to file return (opt, True) if os.path.isfile(config): # custom or default config exists opt = default_options(engine) f = open(config, "r") update_options_from_config(opt, f) return (opt, False) else: #no config found sys.stderr.write("!!Error: config {:s} doesn't exists ! Exiting...\n") sys.exit(-2)
0
0
0
0157b26dfb05673b29e289dfb9935a9a1efc3039
1,284
py
Python
abstract_factory/__init__.py
tolunaykatirci/design-patterns
e7013b003199b7400d825c992b77a800e440ad5a
[ "Apache-2.0" ]
null
null
null
abstract_factory/__init__.py
tolunaykatirci/design-patterns
e7013b003199b7400d825c992b77a800e440ad5a
[ "Apache-2.0" ]
null
null
null
abstract_factory/__init__.py
tolunaykatirci/design-patterns
e7013b003199b7400d825c992b77a800e440ad5a
[ "Apache-2.0" ]
null
null
null
from abstract_factory.factories.furniture_factory import FurnitureFactory from abstract_factory.factories.modern_furniture_factory import ModernFurnitureFactory from abstract_factory.factories.victorian_furniture_factory import VictorianFurnitureFactory ''' Abstract Factory is a creational design pattern that lets you produce families of related objects without specifying their concrete classes. Chair, Sofa, Coffee Table X Modern, Victorian ''' def client_code(factory: FurnitureFactory) -> None: """ The client code works with factories and products only through abstract types: FurnitureFactory and abstract furniture Chair, Sofa and Coffee Table. This lets you pass any factory or product subclass to the client code without breaking it. """ chair = factory.create_chair() sofa = factory.create_sofa() print(f"{chair.chair_feature_1()}") print(f"{sofa.sofa_feature_2()}") if __name__ == "__main__": """ The client code can work with any concrete factory class. """ print("Client: Testing client code with the ModernFurnitureFactory:") client_code(ModernFurnitureFactory()) print('\n') print("Client: Testing client code with the VictorianFurnitureFactory:") client_code(VictorianFurnitureFactory())
34.702703
94
0.767134
from abstract_factory.factories.furniture_factory import FurnitureFactory from abstract_factory.factories.modern_furniture_factory import ModernFurnitureFactory from abstract_factory.factories.victorian_furniture_factory import VictorianFurnitureFactory ''' Abstract Factory is a creational design pattern that lets you produce families of related objects without specifying their concrete classes. Chair, Sofa, Coffee Table X Modern, Victorian ''' def client_code(factory: FurnitureFactory) -> None: """ The client code works with factories and products only through abstract types: FurnitureFactory and abstract furniture Chair, Sofa and Coffee Table. This lets you pass any factory or product subclass to the client code without breaking it. """ chair = factory.create_chair() sofa = factory.create_sofa() print(f"{chair.chair_feature_1()}") print(f"{sofa.sofa_feature_2()}") if __name__ == "__main__": """ The client code can work with any concrete factory class. """ print("Client: Testing client code with the ModernFurnitureFactory:") client_code(ModernFurnitureFactory()) print('\n') print("Client: Testing client code with the VictorianFurnitureFactory:") client_code(VictorianFurnitureFactory())
0
0
0
ede2b9d349c94c7787fbfa393de8b4efe911a0ba
617
py
Python
django_vend/stores/views.py
remarkablerocket/django-vend
c07809a7f1748d98ed78c115dcf22de1e0875f94
[ "BSD-3-Clause" ]
null
null
null
django_vend/stores/views.py
remarkablerocket/django-vend
c07809a7f1748d98ed78c115dcf22de1e0875f94
[ "BSD-3-Clause" ]
null
null
null
django_vend/stores/views.py
remarkablerocket/django-vend
c07809a7f1748d98ed78c115dcf22de1e0875f94
[ "BSD-3-Clause" ]
null
null
null
from django.shortcuts import render from django.views.generic import ListView, DetailView from django_vend.core.views import (VendAuthSingleObjectSyncMixin, VendAuthCollectionSyncMixin) from .models import VendOutlet, VendRegister
25.708333
66
0.779579
from django.shortcuts import render from django.views.generic import ListView, DetailView from django_vend.core.views import (VendAuthSingleObjectSyncMixin, VendAuthCollectionSyncMixin) from .models import VendOutlet, VendRegister class RegisterList(VendAuthCollectionSyncMixin, ListView): model = VendRegister class RegisterDetail(VendAuthSingleObjectSyncMixin, DetailView): model = VendRegister class OutletList(VendAuthCollectionSyncMixin, ListView): model = VendOutlet class OutletDetail(VendAuthSingleObjectSyncMixin, DetailView): model = VendOutlet
0
252
92
bc705f5a48abf88fe4dd6878918563245bb06910
1,210
py
Python
Noise_Reduction/TSNR.py
cooperbarth/Joint-Audio-Correction-Kit
511a8ee249ca8cd0695afee11f15ad38b1a9452e
[ "MIT" ]
6
2019-06-13T06:07:34.000Z
2021-09-17T22:14:12.000Z
Noise_Reduction/TSNR.py
cooperbarth/Joint-Audio-Correction-Kit
511a8ee249ca8cd0695afee11f15ad38b1a9452e
[ "MIT" ]
2
2019-03-22T01:06:33.000Z
2019-06-20T04:17:24.000Z
Noise_Reduction/TSNR.py
cooperbarth/Joint-Audio-Correction-Kit
511a8ee249ca8cd0695afee11f15ad38b1a9452e
[ "MIT" ]
1
2019-11-13T22:44:53.000Z
2019-11-13T22:44:53.000Z
import numpy as np def TSNR(noisy_stft, signal_gains, noise_estimation): """ Reconstructs the signal by re-adding phase components to the magnitude estimate :param noisy_stft: stft of original noisy signal :param signal_gains: gains of each stft frame returned by DD :param noise_estimation: noise estimation average based on first n frames of noisy signal :return: signal_output: stft of signal after TSNR modification TSNR_gains: ndarray containing gain for each bin in signal_output """ num_frames = noisy_stft.shape[1] signal_output = np.zeros(noisy_stft.shape, dtype=complex) TSNR_gains = [] for frame_number in range(num_frames): noisy_frame = np.abs(noisy_stft[:, frame_number]) #Calculating SNR_prior for current frame numerator = (signal_gains[:, frame_number] * noisy_frame) ** 2 prior_SNR = numerator / noise_estimation #Calculating TSNR filter_gain for current frame TSNR_gain = np.divide(prior_SNR, prior_SNR + 1) TSNR_gains.append(TSNR_gain) signal_output[:, frame_number] = TSNR_gain * noisy_stft[:, frame_number] return signal_output, np.asarray(TSNR_gains).T
39.032258
93
0.71405
import numpy as np def TSNR(noisy_stft, signal_gains, noise_estimation): """ Reconstructs the signal by re-adding phase components to the magnitude estimate :param noisy_stft: stft of original noisy signal :param signal_gains: gains of each stft frame returned by DD :param noise_estimation: noise estimation average based on first n frames of noisy signal :return: signal_output: stft of signal after TSNR modification TSNR_gains: ndarray containing gain for each bin in signal_output """ num_frames = noisy_stft.shape[1] signal_output = np.zeros(noisy_stft.shape, dtype=complex) TSNR_gains = [] for frame_number in range(num_frames): noisy_frame = np.abs(noisy_stft[:, frame_number]) #Calculating SNR_prior for current frame numerator = (signal_gains[:, frame_number] * noisy_frame) ** 2 prior_SNR = numerator / noise_estimation #Calculating TSNR filter_gain for current frame TSNR_gain = np.divide(prior_SNR, prior_SNR + 1) TSNR_gains.append(TSNR_gain) signal_output[:, frame_number] = TSNR_gain * noisy_stft[:, frame_number] return signal_output, np.asarray(TSNR_gains).T
0
0
0
897c27db77012c8ae94c2d760b68e0b8dbc97aec
4,160
py
Python
screen.py
logoner/py_adventure
312cb9ae44a9061d92b36d338e63c15f62718457
[ "CC0-1.0" ]
null
null
null
screen.py
logoner/py_adventure
312cb9ae44a9061d92b36d338e63c15f62718457
[ "CC0-1.0" ]
null
null
null
screen.py
logoner/py_adventure
312cb9ae44a9061d92b36d338e63c15f62718457
[ "CC0-1.0" ]
null
null
null
# py_adventure screen scrypt import config import os
101.463415
151
0.108173
# py_adventure screen scrypt import config import os def display_interface(location, meeting, menu): # config.location_number, enemy_meeting, displayed_menu # строку "Вы оказались в необычном месте." нужно заменить на параметр location_descriptor(location) в котором описание места. screen = ['*****************************************************Инфо.*Локация*****************************************************', '* location_descriptor(' + str(location) + ') *', '* ' + meeting[1] + ' *', '* ' + meeting[2] + ' *', '*******************************************************Инфо.*Перс******************************************************', '* Пройдено километров: ' + str(location) + ' *', '***********************************************************************************************************************', '*08********************************************************************************************************************', '*09********************************************************************************************************************', '*10********************************************************************************************************************', '*11********************************************************************************************************************', '*12********************************************************************************************************************', '*13********************************************************************************************************************', '*14********************************************************************************************************************', '*15********************************************************************************************************************', '*16********************************************************************************************************************', '*17********************************************************************************************************************', '*18********************************************************************************************************************', '*19********************************************************************************************************************', '*20********************************************************************************************************************', '*21********************************************************************************************************************', '******************************************************Ваши действия****************************************************', '* ' + menu[0] + ' *', '* ' + menu[1] + ' *', '* ' + menu[2] + ' *', '* ' + menu[3] + ' *', '* *', '* Вы выбираете: *', '***********************************************************************************************************************',] os.system('cls') # For Windows for line in screen: print(line)
4,217
0
24
90d2721fb801ab6fff85d03a472b3766fe0c3540
6,330
py
Python
EGAT/feature_generator/distance_and_angle_generator.py
sailfish009/EGAT
a03d6cbeb3e6d8f75edd608370256326d8fcb05b
[ "MIT" ]
11
2020-11-06T08:37:39.000Z
2021-01-22T08:46:37.000Z
EGAT/feature_generator/distance_and_angle_generator.py
MaxCodeXTC/EGAT
9f6f88bf2fe08965e9c7092e0f7717120e09b0e3
[ "MIT" ]
1
2021-08-14T08:26:56.000Z
2021-08-19T21:08:06.000Z
EGAT/feature_generator/distance_and_angle_generator.py
MaxCodeXTC/EGAT
9f6f88bf2fe08965e9c7092e0f7717120e09b0e3
[ "MIT" ]
5
2020-11-09T04:15:42.000Z
2021-01-19T05:53:26.000Z
# coding: utf-8 # In[1]: import numpy as np from time import time import gzip import warnings import pickle warnings.filterwarnings("ignore") from Bio.PDB import * import Bio from config import DefaultConfig configs = DefaultConfig() parser = PDBParser() THIRD_ATOM = 'N' # 'O' # In[2]: # In[3]: from Bio import pairwise2 from Bio.pairwise2 import format_alignment from Bio import SeqUtils protein_letters_3to1 = SeqUtils.IUPACData.protein_letters_3to1 ppb = PPBuilder() # dist_matrix_map, angle_matrix_map
33.670213
112
0.599684
# coding: utf-8 # In[1]: import numpy as np from time import time import gzip import warnings import pickle warnings.filterwarnings("ignore") from Bio.PDB import * import Bio from config import DefaultConfig configs = DefaultConfig() parser = PDBParser() THIRD_ATOM = 'N' # 'O' # In[2]: def residue_distance(res1, res2): distance = [] cnt = 0 for atom1 in res1: for atom2 in res2: distance += [abs(atom1 - atom2)] cnt += 1 distance = np.array(distance) dist_mean = distance.mean() dist_std = distance.std() if 'CA' in res1 and 'CA' in res2: dist_ca = abs(res1['CA'] - res2['CA']) else: dist_ca = dist_mean return dist_mean, dist_std, dist_ca def residue_relative_angle(res1, res2): if 'CA' in res1 and THIRD_ATOM in res1 and 'C' in res1: v1 = res1['CA'].get_vector().get_array() v2 = res1[THIRD_ATOM].get_vector().get_array() v3 = res1['C'].get_vector().get_array() normal1 = np.cross((v2 - v1), (v3 - v1)) else: k = list(res1) if len(k) == 1: normal1 = k[0].get_vector().get_array() else: raise normal1 = normal1 / np.linalg.norm(normal1) if 'CA' in res2 and THIRD_ATOM in res2 and 'C' in res2: v1 = res2['CA'].get_vector().get_array() v2 = res2[THIRD_ATOM].get_vector().get_array() v3 = res2['C'].get_vector().get_array() normal2 = np.cross((v2 - v1), (v3 - v1)) else: k = list(res2) if len(k) == 1: normal2 = k[0].get_vector().get_array() else: raise normal2 = normal2 / np.linalg.norm(normal2) return np.arccos(np.clip(np.dot(normal1, normal2), -1.0, 1.0)) def get_dist_and_angle_matrix(residues): size = len(residues) dist_mat = np.zeros([size, size, 3]) angle_mat = np.zeros([size, size]) for i in range(size): for j in range(i + 1, size): dist_mean, dist_std, dist_ca = residue_distance(residues[i], residues[j]) angle = residue_relative_angle(residues[i], residues[j]) dist_mat[i, j, 0] = dist_mean dist_mat[i, j, 1] = dist_std dist_mat[i, j, 2] = dist_ca dist_mat[j, i, 0] = dist_mean dist_mat[j, i, 1] = dist_std dist_mat[j, i, 2] = dist_ca angle_mat[i, j] = angle angle_mat[j, i] = angle return dist_mat, angle_mat # In[3]: from Bio import pairwise2 from Bio.pairwise2 import format_alignment from Bio import SeqUtils protein_letters_3to1 = SeqUtils.IUPACData.protein_letters_3to1 ppb = PPBuilder() def generate_distance_and_angle_matrix(root_dir): t0 = time() dist_matrix_map = {} # key: idx, value: {'protein_id':<complexName>_<chains>, 'dist_matrix':dist_matrix} angle_matrix_map = {} # key: idx, value: {'protein_id':<complexName>_<chains>, 'angle_matrix':angle_matrix} with open(root_dir + '/inputs/protein_list.txt', 'r') as f: protein_list = f.readlines() protein_list = [x.strip() for x in protein_list] for idx, protein_name in enumerate(protein_list): complex_name, chains = protein_name.upper().split('_') try: path = root_dir + '/inputs/pdb_files/' + protein_name + '.pdb' structure = parser.get_structure(complex_name, path) except: path = root_dir + '/inputs/pdb_files/' + protein_name.lower() + '.pdb' structure = parser.get_structure(complex_name, path) model = structure[0] # every structure object has only one model object in DeepPPISP's dataset pep_pdb = '' residues = [] for chain_id in chains: for residue in model[chain_id].get_residues(): residues += [residue] peptides = ppb.build_peptides(model[chain_id]) pep_pdb += ''.join([str(pep.get_sequence()) for pep in peptides]) pep_seq_from_res_list = '' i = 0 total_res = 0 temp = 0 residues2 = [] original_total_res = len(residues) while i < original_total_res: res = residues[i] res_name = res.get_resname() if res_name[0] + res_name[1:].lower() not in protein_letters_3to1: temp += 1 else: pep_seq_from_res_list += protein_letters_3to1[res_name[0] + res_name[1:].lower()] residues2 += [residues[i]] total_res += 1 if total_res == configs.max_sequence_length: break i += 1 if pep_pdb[:configs.max_sequence_length] != pep_seq_from_res_list and False: # for debug only print('Extraction of residue-information from PDB file filed for protein:', protein_name) # print('Pairwise Alignment:') alignments = pairwise2.align.globalxx(pep_pdb[:configs.max_sequence_length], pep_seq_from_res_list) print(format_alignment(*alignments[0])) print('len(residues2):', len(residues2), ', len(pep_pdb):', len(pep_pdb), ', len(pep_seq_from_res_list):', len(pep_seq_from_res_list), '\n') # print(format_alignment(*alignments[0])) # print('...') raise Exception else: t1 = time() print(idx, ':', protein_name, len(pep_seq_from_res_list)) fasta_string = '>{}\n'.format(protein_name) + pep_seq_from_res_list with open(root_dir + '/inputs/fasta_files/{}.fasta'.format(protein_name), 'w') as f: f.write(fasta_string) dist_mat, angle_mat = get_dist_and_angle_matrix(residues2[:configs.max_sequence_length]) dist_matrix_map[idx] = {'protein_id': protein_name, 'dist_matrix': dist_mat} angle_matrix_map[idx] = {'protein_id': protein_name, 'angle_matrix': angle_mat} print(idx, 'done.', time()-t1) pickle.dump(dist_matrix_map, gzip.open(root_dir + '/inputs/ppisp_dist_matrix_map.pkl.gz', 'wb')) pickle.dump(angle_matrix_map, gzip.open(root_dir + '/inputs/ppisp_angle_matrix_map.pkl.gz', 'wb')) print('Total time for Distance and Angle matrices generation:', time() - t0) # dist_matrix_map, angle_matrix_map
5,704
0
92
569d38194b1b31a4c8eebb0a5e9a0b3fc694bf4d
2,222
py
Python
Day-04_Giant-Squid/puzzle_2.py
richardangell/advent-of-code-2021
48397e980fd6d4d43234df89e47bf22581c0611e
[ "BSD-3-Clause" ]
null
null
null
Day-04_Giant-Squid/puzzle_2.py
richardangell/advent-of-code-2021
48397e980fd6d4d43234df89e47bf22581c0611e
[ "BSD-3-Clause" ]
null
null
null
Day-04_Giant-Squid/puzzle_2.py
richardangell/advent-of-code-2021
48397e980fd6d4d43234df89e47bf22581c0611e
[ "BSD-3-Clause" ]
null
null
null
import numpy as np from numpy.typing import ArrayLike import sys from puzzle_1 import load_input sys.path.append("..") import helpers # noqa def calculate_last_winning_score( draw_numbers: list[int], boards: list[ArrayLike], blank_boards: list[ArrayLike] ) -> tuple[int, int, int]: """Function to calculate the winning score from the board which would win last. The score is given by sum of all unmarked numbers on that board multiplied by the number that was just called for the winning board. """ boards_in_play = [i for i in range(len(boards))] remove_board = [] for drawn_number in draw_numbers: for board_no in boards_in_play: board = boards[board_no] blank_board = blank_boards[board_no] drawn_number_found = board == drawn_number if drawn_number_found.sum() > 0: blank_board = blank_board + drawn_number_found blank_board = np.clip(blank_board, a_min=None, a_max=1) blank_boards[board_no] = blank_board unmarked_board = (1 - blank_board) * board # check for winning board if (blank_board.sum(axis=0) == 5).any() or ( blank_board.sum(axis=1) == 5 ).any(): # if the board wins, store the board number and remove it # outside of the loop if len(boards_in_play) > 1: remove_board.append(board_no) else: unmarked_board = (1 - blank_board) * board unmarked_board_score = unmarked_board.sum() return ( unmarked_board_score * drawn_number, unmarked_board_score, drawn_number, ) if remove_board is not []: for board_to_remove in remove_board: boards_in_play.remove(board_to_remove) remove_board = [] if __name__ == "__main__": input = load_input("input_1.txt") result = calculate_last_winning_score(*input) print(result)
27.097561
83
0.565257
import numpy as np from numpy.typing import ArrayLike import sys from puzzle_1 import load_input sys.path.append("..") import helpers # noqa def calculate_last_winning_score( draw_numbers: list[int], boards: list[ArrayLike], blank_boards: list[ArrayLike] ) -> tuple[int, int, int]: """Function to calculate the winning score from the board which would win last. The score is given by sum of all unmarked numbers on that board multiplied by the number that was just called for the winning board. """ boards_in_play = [i for i in range(len(boards))] remove_board = [] for drawn_number in draw_numbers: for board_no in boards_in_play: board = boards[board_no] blank_board = blank_boards[board_no] drawn_number_found = board == drawn_number if drawn_number_found.sum() > 0: blank_board = blank_board + drawn_number_found blank_board = np.clip(blank_board, a_min=None, a_max=1) blank_boards[board_no] = blank_board unmarked_board = (1 - blank_board) * board # check for winning board if (blank_board.sum(axis=0) == 5).any() or ( blank_board.sum(axis=1) == 5 ).any(): # if the board wins, store the board number and remove it # outside of the loop if len(boards_in_play) > 1: remove_board.append(board_no) else: unmarked_board = (1 - blank_board) * board unmarked_board_score = unmarked_board.sum() return ( unmarked_board_score * drawn_number, unmarked_board_score, drawn_number, ) if remove_board is not []: for board_to_remove in remove_board: boards_in_play.remove(board_to_remove) remove_board = [] if __name__ == "__main__": input = load_input("input_1.txt") result = calculate_last_winning_score(*input) print(result)
0
0
0
e0aae4b1cbbabd84c6ef45d5488c32b230ae2b94
8,642
py
Python
qiskit_machine_learning/neural_networks/neural_network.py
FrankFeenix/qiskit-machine-learning
ec800bc8a58b32f3052ff399d54f19a74417fc7d
[ "Apache-2.0" ]
null
null
null
qiskit_machine_learning/neural_networks/neural_network.py
FrankFeenix/qiskit-machine-learning
ec800bc8a58b32f3052ff399d54f19a74417fc7d
[ "Apache-2.0" ]
null
null
null
qiskit_machine_learning/neural_networks/neural_network.py
FrankFeenix/qiskit-machine-learning
ec800bc8a58b32f3052ff399d54f19a74417fc7d
[ "Apache-2.0" ]
1
2021-06-15T16:41:39.000Z
2021-06-15T16:41:39.000Z
# This code is part of Qiskit. # # (C) Copyright IBM 2020, 2021. # # This code is licensed under the Apache License, Version 2.0. You may # obtain a copy of this license in the LICENSE.txt file in the root directory # of this source tree or at http://www.apache.org/licenses/LICENSE-2.0. # # Any modifications or derivative works of this code must retain this # copyright notice, and modified files need to carry a notice indicating # that they have been altered from the originals. """A Neural Network abstract class for all (quantum) neural networks within Qiskit's machine learning module.""" from abc import ABC, abstractmethod from typing import Tuple, Union, List, Optional import numpy as np try: from sparse import SparseArray except ImportError: class SparseArray: # type: ignore """Empty SparseArray class Replacement if sparse.SparseArray is not present. """ pass from ..exceptions import QiskitMachineLearningError class NeuralNetwork(ABC): """Abstract Neural Network class providing forward and backward pass and handling batched inputs. This is to be implemented by other (quantum) neural networks. """ def __init__( self, num_inputs: int, num_weights: int, sparse: bool, output_shape: Union[int, Tuple[int, ...]], ) -> None: """Initializes the Neural Network. Args: num_inputs: The number of input features. num_weights: The number of trainable weights. sparse: Determines whether the output is a sparse array or not. output_shape: The shape of the output. Raises: QiskitMachineLearningError: Invalid parameter values. """ if num_inputs < 0: raise QiskitMachineLearningError(f"Number of inputs cannot be negative: {num_inputs}!") self._num_inputs = num_inputs if num_weights < 0: raise QiskitMachineLearningError( f"Number of weights cannot be negative: {num_weights}!" ) self._num_weights = num_weights self._sparse = sparse if isinstance(output_shape, int): output_shape = (output_shape,) if not np.all([s > 0 for s in output_shape]): raise QiskitMachineLearningError( f"Invalid output shape, all components must be > 0, but got: {output_shape}." ) self._output_shape = output_shape self._input_gradients = False @property def num_inputs(self) -> int: """Returns the number of input features.""" return self._num_inputs @property def num_weights(self) -> int: """Returns the number of trainable weights.""" return self._num_weights @property def sparse(self) -> bool: """Returns whether the output is sparse or not.""" return self._sparse @property def output_shape(self) -> Tuple[int, ...]: """Returns the output shape.""" return self._output_shape @property def input_gradients(self) -> bool: """Returns whether gradients with respect to input data are computed by this neural network in the ``backward`` method or not. By default such gradients are not computed.""" return self._input_gradients @input_gradients.setter def input_gradients(self, input_gradients: bool) -> None: """Turn on/off computation of gradients with respect to input data.""" self._input_gradients = input_gradients def forward( self, input_data: Optional[Union[List[float], np.ndarray, float]], weights: Optional[Union[List[float], np.ndarray, float]], ) -> Union[np.ndarray, SparseArray]: """Forward pass of the network. Args: input_data: input data of the shape (num_inputs). In case of a single scalar input it is directly cast to and interpreted like a one-element array. weights: trainable weights of the shape (num_weights). In case of a single scalar weight it is directly cast to and interpreted like a one-element array. Returns: The result of the neural network of the shape (output_shape). """ input_, shape = self._validate_input(input_data) weights_ = self._validate_weights(weights) output_data = self._forward(input_, weights_) return self._validate_forward_output(output_data, shape) @abstractmethod def backward( self, input_data: Optional[Union[List[float], np.ndarray, float]], weights: Optional[Union[List[float], np.ndarray, float]], ) -> Tuple[Optional[Union[np.ndarray, SparseArray]], Optional[Union[np.ndarray, SparseArray]],]: """Backward pass of the network. Args: input_data: input data of the shape (num_inputs). In case of a single scalar input it is directly cast to and interpreted like a one-element array. weights: trainable weights of the shape (num_weights). In case of a single scalar weight it is directly cast to and interpreted like a one-element array. Returns: The result of the neural network of the backward pass, i.e., a tuple with the gradients for input and weights of shape (output_shape, num_input) and (output_shape, num_weights), respectively. """ input_, shape = self._validate_input(input_data) weights_ = self._validate_weights(weights) input_grad, weight_grad = self._backward(input_, weights_) input_grad_reshaped, weight_grad_reshaped = self._validate_backward_output( input_grad, weight_grad, shape ) return input_grad_reshaped, weight_grad_reshaped @abstractmethod
37.573913
100
0.640361
# This code is part of Qiskit. # # (C) Copyright IBM 2020, 2021. # # This code is licensed under the Apache License, Version 2.0. You may # obtain a copy of this license in the LICENSE.txt file in the root directory # of this source tree or at http://www.apache.org/licenses/LICENSE-2.0. # # Any modifications or derivative works of this code must retain this # copyright notice, and modified files need to carry a notice indicating # that they have been altered from the originals. """A Neural Network abstract class for all (quantum) neural networks within Qiskit's machine learning module.""" from abc import ABC, abstractmethod from typing import Tuple, Union, List, Optional import numpy as np try: from sparse import SparseArray except ImportError: class SparseArray: # type: ignore """Empty SparseArray class Replacement if sparse.SparseArray is not present. """ pass from ..exceptions import QiskitMachineLearningError class NeuralNetwork(ABC): """Abstract Neural Network class providing forward and backward pass and handling batched inputs. This is to be implemented by other (quantum) neural networks. """ def __init__( self, num_inputs: int, num_weights: int, sparse: bool, output_shape: Union[int, Tuple[int, ...]], ) -> None: """Initializes the Neural Network. Args: num_inputs: The number of input features. num_weights: The number of trainable weights. sparse: Determines whether the output is a sparse array or not. output_shape: The shape of the output. Raises: QiskitMachineLearningError: Invalid parameter values. """ if num_inputs < 0: raise QiskitMachineLearningError(f"Number of inputs cannot be negative: {num_inputs}!") self._num_inputs = num_inputs if num_weights < 0: raise QiskitMachineLearningError( f"Number of weights cannot be negative: {num_weights}!" ) self._num_weights = num_weights self._sparse = sparse if isinstance(output_shape, int): output_shape = (output_shape,) if not np.all([s > 0 for s in output_shape]): raise QiskitMachineLearningError( f"Invalid output shape, all components must be > 0, but got: {output_shape}." ) self._output_shape = output_shape self._input_gradients = False @property def num_inputs(self) -> int: """Returns the number of input features.""" return self._num_inputs @property def num_weights(self) -> int: """Returns the number of trainable weights.""" return self._num_weights @property def sparse(self) -> bool: """Returns whether the output is sparse or not.""" return self._sparse @property def output_shape(self) -> Tuple[int, ...]: """Returns the output shape.""" return self._output_shape @property def input_gradients(self) -> bool: """Returns whether gradients with respect to input data are computed by this neural network in the ``backward`` method or not. By default such gradients are not computed.""" return self._input_gradients @input_gradients.setter def input_gradients(self, input_gradients: bool) -> None: """Turn on/off computation of gradients with respect to input data.""" self._input_gradients = input_gradients def _validate_input( self, input_data: Optional[Union[List[float], np.ndarray, float]] ) -> Tuple[Union[np.ndarray, None], Union[Tuple[int, ...], None]]: if input_data is None: return None, None input_ = np.array(input_data) shape = input_.shape if len(shape) == 0: # there's a single value in the input. input_ = input_.reshape((1, 1)) return input_, shape if shape[-1] != self._num_inputs: raise QiskitMachineLearningError( f"Input data has incorrect shape, last dimension " f"is not equal to the number of inputs: " f"{self._num_inputs}, but got: {shape[-1]}." ) if len(shape) == 1: # add an empty dimension for samples (batch dimension) input_ = input_.reshape((1, -1)) elif len(shape) > 2: # flatten lower dimensions, keep num_inputs as a last dimension input_ = input_.reshape((np.product(input_.shape[:-1]), -1)) return input_, shape def _validate_weights( self, weights: Optional[Union[List[float], np.ndarray, float]] ) -> Union[np.ndarray, None]: if weights is None: return None weights_ = np.array(weights) return weights_.reshape(self._num_weights) def _validate_forward_output( self, output_data: np.ndarray, original_shape: Tuple[int, ...] ) -> np.ndarray: if original_shape and len(original_shape) >= 2: output_data = output_data.reshape((*original_shape[:-1], *self._output_shape)) return output_data def _validate_backward_output( self, input_grad: np.ndarray, weight_grad: np.ndarray, original_shape: Tuple[int, ...], ) -> Tuple[Union[np.ndarray, SparseArray], Union[np.ndarray, SparseArray]]: if input_grad is not None and original_shape and len(original_shape) >= 2: input_grad = input_grad.reshape( (*original_shape[:-1], *self._output_shape, self._num_inputs) ) if weight_grad is not None and original_shape and len(original_shape) >= 2: weight_grad = weight_grad.reshape( (*original_shape[:-1], *self._output_shape, self._num_weights) ) return input_grad, weight_grad def forward( self, input_data: Optional[Union[List[float], np.ndarray, float]], weights: Optional[Union[List[float], np.ndarray, float]], ) -> Union[np.ndarray, SparseArray]: """Forward pass of the network. Args: input_data: input data of the shape (num_inputs). In case of a single scalar input it is directly cast to and interpreted like a one-element array. weights: trainable weights of the shape (num_weights). In case of a single scalar weight it is directly cast to and interpreted like a one-element array. Returns: The result of the neural network of the shape (output_shape). """ input_, shape = self._validate_input(input_data) weights_ = self._validate_weights(weights) output_data = self._forward(input_, weights_) return self._validate_forward_output(output_data, shape) @abstractmethod def _forward( self, input_data: Optional[np.ndarray], weights: Optional[np.ndarray] ) -> Union[np.ndarray, SparseArray]: raise NotImplementedError def backward( self, input_data: Optional[Union[List[float], np.ndarray, float]], weights: Optional[Union[List[float], np.ndarray, float]], ) -> Tuple[Optional[Union[np.ndarray, SparseArray]], Optional[Union[np.ndarray, SparseArray]],]: """Backward pass of the network. Args: input_data: input data of the shape (num_inputs). In case of a single scalar input it is directly cast to and interpreted like a one-element array. weights: trainable weights of the shape (num_weights). In case of a single scalar weight it is directly cast to and interpreted like a one-element array. Returns: The result of the neural network of the backward pass, i.e., a tuple with the gradients for input and weights of shape (output_shape, num_input) and (output_shape, num_weights), respectively. """ input_, shape = self._validate_input(input_data) weights_ = self._validate_weights(weights) input_grad, weight_grad = self._backward(input_, weights_) input_grad_reshaped, weight_grad_reshaped = self._validate_backward_output( input_grad, weight_grad, shape ) return input_grad_reshaped, weight_grad_reshaped @abstractmethod def _backward( self, input_data: Optional[np.ndarray], weights: Optional[np.ndarray] ) -> Tuple[Optional[Union[np.ndarray, SparseArray]], Optional[Union[np.ndarray, SparseArray]],]: raise NotImplementedError
2,631
0
160
8fd5aaa621aee3a0c3eab511248713236b6221a9
4,822
py
Python
docker2shell.py
Vayel/publik
8b8da0bd8f8aa99fdcda55300e9f04aea9101a62
[ "MIT" ]
null
null
null
docker2shell.py
Vayel/publik
8b8da0bd8f8aa99fdcda55300e9f04aea9101a62
[ "MIT" ]
null
null
null
docker2shell.py
Vayel/publik
8b8da0bd8f8aa99fdcda55300e9f04aea9101a62
[ "MIT" ]
null
null
null
#!/usr/bin/env python import os import re import shutil import glob # This script converts from the docker version to a shell install version # Useful for installation without docker # Manual installation # - Init a database using ../postgresql/docker-entrypoint-initdb.d/init-database.sh # - Add db, smtp and rabbitmq to /etc/hosts # - Excute ./docker2shell.py # - Open schellinstall folder # - Update database connexion in config files (*.py) # - Create env file and load data in bash session for envsub # - Update NGINX ports in *.template # - Update SMTP config (config.py and wcs.settings.py) # - Turn debug off if needed in config files (*.py) # - Execute install.sh # - Start app with start-xxx.sh apps = ["base", "hobo", "authentic", "combo", "fargo", "passerelle", "wcs"] project_path = os.getcwd() bare_path = os.path.join(project_path, "shellinstall") if not os.path.exists(bare_path): os.makedirs(bare_path) else: [os.remove(f) for f in glob.glob(bare_path+"/*")] replace_dict = { "FROM" : "# FROM", "MAINTAINER" : "# MAINTAINER", "VOLUME" : "# VOLUME", "EXPOSE" : "# EXPOSE", "ENTRYPOINT\s\[\"(?P<script>[A-Za-z\-\.]*)\"\]" : "./\g<script>", "CMD" : "# CMD", "RUN " : "", "COPY" : "cp", "ENV\s(?P<name>[A-Z]*)\s*(?P<value>[a-z]*)" : "export \g<name>=\g<value>", "/root" : "/usr/bin" } do_not_copy = ["Dockerfile", "LICENSE", "README.md", \ ".git", "nginx.template", "start.sh", "stop.sh"] startgru = "" stopgru = "" configuregru = "" envextractor = re.compile("(envsubst.*)") for app in apps: app_path = os.path.join(project_path, app) if "Dockerfile" in os.listdir(app) : print("Converting {} docker image...".format(app)) # Rename nginx template using app name nginx_path = os.path.join(app_path, "nginx.template") if os.path.isfile(nginx_path): nginx_new_name = "nginx-"+app+".template" replace_dict.update({"nginx.template" : nginx_new_name}) shutil.copyfile(nginx_path, os.path.join(bare_path, nginx_new_name)) # Convert docker entrypoint into startup script entrypoint_path = os.path.join(app_path, "start.sh") if os.path.isfile(entrypoint_path): startappscript = "start-"+app+".sh" replace_dict.update({"start.sh" : startappscript}) # delete the 'exec' command in the script with open(entrypoint_path) as f: newContent = f.read().replace('exec "$@"', '') newContent = envextractor.sub('# moved to configure.sh \\1', newContent) configuregru += "\n".join([ a + "\n" for a in envextractor.findall(newContent)]) with open(os.path.join(bare_path, startappscript), "w+") as f: f.write(newContent) startgru += "./" + startappscript + "\n" # Convert docker stop script entrypoint_path = os.path.join(app_path, "stop.sh") if os.path.isfile(entrypoint_path): stopappscript = "stop-"+app+".sh" replace_dict.update({"stop.sh" : stopappscript}) shutil.copyfile(entrypoint_path, os.path.join(bare_path, stopappscript)) stopgru += "./" + stopappscript + "\n" # Convert dockerfile file_replace(replace_dict, \ os.path.join(app_path, "Dockerfile"), \ os.path.join(bare_path, "install.sh"), app) # Copy other files files = [f for f in os.listdir(app) if f not in do_not_copy] for file in files: file_path = os.path.join(app_path, file) if os.path.isfile(os.path.join(bare_path, file)): print("Error, file %s already exists", file) shutil.copy(file_path, bare_path) print("{} docker image converted".format(app)) with open(os.path.join(bare_path, "start-all.sh"), "w") as f: f.write(startgru) with open(os.path.join(bare_path, "stop-all.sh"), "w") as f: f.write(stopgru) with open(os.path.join(bare_path, "configure.sh"), "w") as f: f.write(configuregru)
34.442857
96
0.592493
#!/usr/bin/env python import os import re import shutil import glob # This script converts from the docker version to a shell install version # Useful for installation without docker # Manual installation # - Init a database using ../postgresql/docker-entrypoint-initdb.d/init-database.sh # - Add db, smtp and rabbitmq to /etc/hosts # - Excute ./docker2shell.py # - Open schellinstall folder # - Update database connexion in config files (*.py) # - Create env file and load data in bash session for envsub # - Update NGINX ports in *.template # - Update SMTP config (config.py and wcs.settings.py) # - Turn debug off if needed in config files (*.py) # - Execute install.sh # - Start app with start-xxx.sh def file_replace(replace_dict, source, dest=None, title=None): fin = open(source, 'r') if dest: fout = open(dest, 'a') else: fd, name = mkstemp() fout = open(name, 'w') if title: fout.write("\n\n################\n") fout.write("# " + title + "\n") fout.write("################\n\n") for line in fin: out = line for pattern,replace in replace_dict.iteritems(): out = re.sub(pattern, replace, out) fout.write(out) try: fout.writelines(fin.readlines()) except Exception as E: raise E fin.close() fout.close() if not dest: shutil.move(name, source) apps = ["base", "hobo", "authentic", "combo", "fargo", "passerelle", "wcs"] project_path = os.getcwd() bare_path = os.path.join(project_path, "shellinstall") if not os.path.exists(bare_path): os.makedirs(bare_path) else: [os.remove(f) for f in glob.glob(bare_path+"/*")] replace_dict = { "FROM" : "# FROM", "MAINTAINER" : "# MAINTAINER", "VOLUME" : "# VOLUME", "EXPOSE" : "# EXPOSE", "ENTRYPOINT\s\[\"(?P<script>[A-Za-z\-\.]*)\"\]" : "./\g<script>", "CMD" : "# CMD", "RUN " : "", "COPY" : "cp", "ENV\s(?P<name>[A-Z]*)\s*(?P<value>[a-z]*)" : "export \g<name>=\g<value>", "/root" : "/usr/bin" } do_not_copy = ["Dockerfile", "LICENSE", "README.md", \ ".git", "nginx.template", "start.sh", "stop.sh"] startgru = "" stopgru = "" configuregru = "" envextractor = re.compile("(envsubst.*)") for app in apps: app_path = os.path.join(project_path, app) if "Dockerfile" in os.listdir(app) : print("Converting {} docker image...".format(app)) # Rename nginx template using app name nginx_path = os.path.join(app_path, "nginx.template") if os.path.isfile(nginx_path): nginx_new_name = "nginx-"+app+".template" replace_dict.update({"nginx.template" : nginx_new_name}) shutil.copyfile(nginx_path, os.path.join(bare_path, nginx_new_name)) # Convert docker entrypoint into startup script entrypoint_path = os.path.join(app_path, "start.sh") if os.path.isfile(entrypoint_path): startappscript = "start-"+app+".sh" replace_dict.update({"start.sh" : startappscript}) # delete the 'exec' command in the script with open(entrypoint_path) as f: newContent = f.read().replace('exec "$@"', '') newContent = envextractor.sub('# moved to configure.sh \\1', newContent) configuregru += "\n".join([ a + "\n" for a in envextractor.findall(newContent)]) with open(os.path.join(bare_path, startappscript), "w+") as f: f.write(newContent) startgru += "./" + startappscript + "\n" # Convert docker stop script entrypoint_path = os.path.join(app_path, "stop.sh") if os.path.isfile(entrypoint_path): stopappscript = "stop-"+app+".sh" replace_dict.update({"stop.sh" : stopappscript}) shutil.copyfile(entrypoint_path, os.path.join(bare_path, stopappscript)) stopgru += "./" + stopappscript + "\n" # Convert dockerfile file_replace(replace_dict, \ os.path.join(app_path, "Dockerfile"), \ os.path.join(bare_path, "install.sh"), app) # Copy other files files = [f for f in os.listdir(app) if f not in do_not_copy] for file in files: file_path = os.path.join(app_path, file) if os.path.isfile(os.path.join(bare_path, file)): print("Error, file %s already exists", file) shutil.copy(file_path, bare_path) print("{} docker image converted".format(app)) with open(os.path.join(bare_path, "start-all.sh"), "w") as f: f.write(startgru) with open(os.path.join(bare_path, "stop-all.sh"), "w") as f: f.write(stopgru) with open(os.path.join(bare_path, "configure.sh"), "w") as f: f.write(configuregru)
675
0
24
6284f4c4e9787b2a2c648b7e2f1218b645b002e2
330
py
Python
jotleaf/test_localsettings.py
reverie/jotleaf.com
86311b546bb5bae7ba826f5576ea82ac515e8b7d
[ "MIT" ]
1
2020-10-25T15:10:43.000Z
2020-10-25T15:10:43.000Z
jotleaf/test_localsettings.py
reverie/jotleaf.com
86311b546bb5bae7ba826f5576ea82ac515e8b7d
[ "MIT" ]
null
null
null
jotleaf/test_localsettings.py
reverie/jotleaf.com
86311b546bb5bae7ba826f5576ea82ac515e8b7d
[ "MIT" ]
null
null
null
from root_dir import root_dir DEBUG = True LOG_DIRECTORY = root_dir('..', 'dev_logs') EMAIL_BACKEND = 'django.core.mail.backends.locmem.EmailBackend' EMAIL_PORT = 1025 YWOT_HOST = 'localhost:8001' PUSHER_APP_ID = '...' PUSHER_KEY = '...' PUSHER_SECRET = '...' MIXPANEL_ID = "..." STATIC_URL = '/static/' SENTRY_DSN = None
15.714286
63
0.69697
from root_dir import root_dir DEBUG = True LOG_DIRECTORY = root_dir('..', 'dev_logs') EMAIL_BACKEND = 'django.core.mail.backends.locmem.EmailBackend' EMAIL_PORT = 1025 YWOT_HOST = 'localhost:8001' PUSHER_APP_ID = '...' PUSHER_KEY = '...' PUSHER_SECRET = '...' MIXPANEL_ID = "..." STATIC_URL = '/static/' SENTRY_DSN = None
0
0
0
f05122174cbeb25e8dcc8f8551911789fe0a1b12
1,190
py
Python
lplangid/tokenizer.py
stephantul/lplangid
11dc6d1b0283ffe3a96159da6b68854ae698280b
[ "MIT" ]
3
2021-09-22T07:35:58.000Z
2021-10-02T20:23:52.000Z
lplangid/tokenizer.py
stephantul/lplangid
11dc6d1b0283ffe3a96159da6b68854ae698280b
[ "MIT" ]
3
2021-09-22T07:51:02.000Z
2021-09-30T20:24:04.000Z
lplangid/tokenizer.py
stephantul/lplangid
11dc6d1b0283ffe3a96159da6b68854ae698280b
[ "MIT" ]
3
2021-09-22T07:36:01.000Z
2021-10-02T20:23:55.000Z
import re import string from typing import List def tokenize_fast(input_text: str) -> List[str]: """Returns a very naive whitespace and punctuation based tokenization. This helps for most but not all languages, should only be used if you don't know the language yet, or if you have a lot of data and can sacrifice a lot of output quality for the sake of speed. """ return strip_most_punctuation(remove_html_tags(input_text)).split() def remove_html_tags(input_text: str) -> str: """Removes all text enclosed by angle brackets.""" html_regex = re.compile("<.*?>") return re.sub(html_regex, "", input_text) def strip_most_punctuation(input_text: str) -> str: """Removes most punctuation except for particular characters inside a word. E.g., "The dog." becomes "The dog" but "U.S.A." becomes "U.S.A". """ chars = [c for c in input_text] for i in range(len(chars)): if chars[i] in string.punctuation: if ((chars[i] in "'./?&=:") and 0 < i < len(chars) - 1 and not chars[i-1].isspace() and not chars[i+1].isspace()): continue chars[i] = ' ' return ''.join(chars)
35
106
0.642857
import re import string from typing import List def tokenize_fast(input_text: str) -> List[str]: """Returns a very naive whitespace and punctuation based tokenization. This helps for most but not all languages, should only be used if you don't know the language yet, or if you have a lot of data and can sacrifice a lot of output quality for the sake of speed. """ return strip_most_punctuation(remove_html_tags(input_text)).split() def remove_html_tags(input_text: str) -> str: """Removes all text enclosed by angle brackets.""" html_regex = re.compile("<.*?>") return re.sub(html_regex, "", input_text) def strip_most_punctuation(input_text: str) -> str: """Removes most punctuation except for particular characters inside a word. E.g., "The dog." becomes "The dog" but "U.S.A." becomes "U.S.A". """ chars = [c for c in input_text] for i in range(len(chars)): if chars[i] in string.punctuation: if ((chars[i] in "'./?&=:") and 0 < i < len(chars) - 1 and not chars[i-1].isspace() and not chars[i+1].isspace()): continue chars[i] = ' ' return ''.join(chars)
0
0
0
244b09637d99df431294fd2b8181aae392e105de
2,035
py
Python
project-euler/601/euler_601_v1.py
zoffixznet/project-euler
39921379385ae2521354c7266a541c46785e85a2
[ "MIT" ]
null
null
null
project-euler/601/euler_601_v1.py
zoffixznet/project-euler
39921379385ae2521354c7266a541c46785e85a2
[ "MIT" ]
null
null
null
project-euler/601/euler_601_v1.py
zoffixznet/project-euler
39921379385ae2521354c7266a541c46785e85a2
[ "MIT" ]
null
null
null
# The Expat License # # Copyright (c) 2017, Shlomi Fish # # 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. import sys from functools import reduce from six import print_ if sys.version_info > (3,): long = int xrange = range if __name__ == "__main__": main()
27.133333
79
0.655037
# The Expat License # # Copyright (c) 2017, Shlomi Fish # # 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. import sys from functools import reduce from six import print_ if sys.version_info > (3,): long = int xrange = range def gcd(*numbers): from fractions import gcd return reduce(gcd, numbers) def lcm(*numbers): return reduce((lambda a, b: (a*b) // gcd(a, b)), numbers, 1) def calc_P(s, N): my_lcm = lcm(*list(range(1, s+1))) i = my_lcm ret = 0 while i < 1: i += my_lcm t = s + 1 while i < N-1: if (((i+t) % t) != 0): ret += 1 i += my_lcm return ret def print_P(s, N): ret = calc_P(s, N) print_("calc_P(s=%d, N=%d) = %d" % (s, N, ret)) return ret def main(): print_P(3, 14) print_P(6, 10**6) print_P(2, 4**2) mysum = 0 p = long(4) for i in xrange(1, 32): mysum += print_P(long(i), p) print_("mysum(%d) = %d" % (i, mysum)) p *= 4 if __name__ == "__main__": main()
635
0
115
e0e05b806c74b1fcaf1ba79e312e6b56d299af1e
884
py
Python
auto-blog/delete.py
alpeshjamgade/auto-blog
656929acdacdb9bbfe0c0aa37b478963f96a0b1f
[ "MIT" ]
null
null
null
auto-blog/delete.py
alpeshjamgade/auto-blog
656929acdacdb9bbfe0c0aa37b478963f96a0b1f
[ "MIT" ]
null
null
null
auto-blog/delete.py
alpeshjamgade/auto-blog
656929acdacdb9bbfe0c0aa37b478963f96a0b1f
[ "MIT" ]
null
null
null
import requests from requests.structures import CaseInsensitiveDict import json BLOG_ID = "2352119848425464545" BASE_URL = "https://www.googleapis.com/blogger/v3/blogs/" if __name__ == "__main__": main()
26
180
0.745475
import requests from requests.structures import CaseInsensitiveDict import json BLOG_ID = "2352119848425464545" BASE_URL = "https://www.googleapis.com/blogger/v3/blogs/" def delete_post(post_id): endpoint = "https://www.googleapis.com/blogger/v3/blogs/2352119848425464545/posts/{post_id}".format( post_id=post_id ) headers = CaseInsensitiveDict() headers["Accept"] = "application/json" headers[ "Authorization" ] = "Bearer ya29.a0AfH6SMD5Is4DETibo7RxWpOnEUFaZviwtE57DuZZxoR0H0Caw9dmy_EvPeUo6z8A5Zotj0EbmEXghkAu4zMbFFlP090u3zNSPZ-exMKcgXsS7ydYj1CVUKUmodb9Ydgbrg6XFtNal4muejtJ4c5Khg_xeRYm" resp = requests.delete(endpoint, headers=headers) return resp.text def main(): post_id = input("Enter the post_id of a post you want to delete: ") resp = delete_post(post_id) print(resp) if __name__ == "__main__": main()
625
0
46
ac2c4fbc88dd909c10b15938d1091b8b904be397
2,227
py
Python
app.py
amrrs/real-time-live-streamlit-dashboard-python
72347d9de864218944aa3d7ad93a10133defc49b
[ "MIT" ]
5
2022-01-21T11:57:51.000Z
2022-03-20T01:46:15.000Z
app.py
amrrs/real-time-live-streamlit-dashboard-python
72347d9de864218944aa3d7ad93a10133defc49b
[ "MIT" ]
null
null
null
app.py
amrrs/real-time-live-streamlit-dashboard-python
72347d9de864218944aa3d7ad93a10133defc49b
[ "MIT" ]
2
2022-02-18T14:38:38.000Z
2022-03-14T06:28:12.000Z
import streamlit as st # web development import numpy as np # np mean, np random import pandas as pd # read csv, df manipulation import time # to simulate a real time data, time loop import plotly.express as px # interactive charts # read csv from a github repo df = pd.read_csv("https://raw.githubusercontent.com/Lexie88rus/bank-marketing-analysis/master/bank.csv") st.set_page_config( page_title = 'Real-Time Data Science Dashboard', page_icon = '✅', layout = 'wide' ) # dashboard title st.title("Real-Time / Live Data Science Dashboard") # top-level filters job_filter = st.selectbox("Select the Job", pd.unique(df['job'])) # creating a single-element container. placeholder = st.empty() # dataframe filter df = df[df['job']==job_filter] # near real-time / live feed simulation for seconds in range(200): #while True: df['age_new'] = df['age'] * np.random.choice(range(1,5)) df['balance_new'] = df['balance'] * np.random.choice(range(1,5)) # creating KPIs avg_age = np.mean(df['age_new']) count_married = int(df[(df["marital"]=='married')]['marital'].count() + np.random.choice(range(1,30))) balance = np.mean(df['balance_new']) with placeholder.container(): # create three columns kpi1, kpi2, kpi3 = st.columns(3) # fill in those three columns with respective metrics or KPIs kpi1.metric(label="Age ⏳", value=round(avg_age), delta= round(avg_age) - 10) kpi2.metric(label="Married Count 💍", value= int(count_married), delta= - 10 + count_married) kpi3.metric(label="A/C Balance $", value= f"$ {round(balance,2)} ", delta= - round(balance/count_married) * 100) # create two columns for charts fig_col1, fig_col2 = st.columns(2) with fig_col1: st.markdown("### First Chart") fig = px.density_heatmap(data_frame=df, y = 'age_new', x = 'marital') st.write(fig) with fig_col2: st.markdown("### Second Chart") fig2 = px.histogram(data_frame = df, x = 'age_new') st.write(fig2) st.markdown("### Detailed Data View") st.dataframe(df) time.sleep(1) #placeholder.empty()
29.693333
120
0.63718
import streamlit as st # web development import numpy as np # np mean, np random import pandas as pd # read csv, df manipulation import time # to simulate a real time data, time loop import plotly.express as px # interactive charts # read csv from a github repo df = pd.read_csv("https://raw.githubusercontent.com/Lexie88rus/bank-marketing-analysis/master/bank.csv") st.set_page_config( page_title = 'Real-Time Data Science Dashboard', page_icon = '✅', layout = 'wide' ) # dashboard title st.title("Real-Time / Live Data Science Dashboard") # top-level filters job_filter = st.selectbox("Select the Job", pd.unique(df['job'])) # creating a single-element container. placeholder = st.empty() # dataframe filter df = df[df['job']==job_filter] # near real-time / live feed simulation for seconds in range(200): #while True: df['age_new'] = df['age'] * np.random.choice(range(1,5)) df['balance_new'] = df['balance'] * np.random.choice(range(1,5)) # creating KPIs avg_age = np.mean(df['age_new']) count_married = int(df[(df["marital"]=='married')]['marital'].count() + np.random.choice(range(1,30))) balance = np.mean(df['balance_new']) with placeholder.container(): # create three columns kpi1, kpi2, kpi3 = st.columns(3) # fill in those three columns with respective metrics or KPIs kpi1.metric(label="Age ⏳", value=round(avg_age), delta= round(avg_age) - 10) kpi2.metric(label="Married Count 💍", value= int(count_married), delta= - 10 + count_married) kpi3.metric(label="A/C Balance $", value= f"$ {round(balance,2)} ", delta= - round(balance/count_married) * 100) # create two columns for charts fig_col1, fig_col2 = st.columns(2) with fig_col1: st.markdown("### First Chart") fig = px.density_heatmap(data_frame=df, y = 'age_new', x = 'marital') st.write(fig) with fig_col2: st.markdown("### Second Chart") fig2 = px.histogram(data_frame = df, x = 'age_new') st.write(fig2) st.markdown("### Detailed Data View") st.dataframe(df) time.sleep(1) #placeholder.empty()
0
0
0
24b11a228e261e489b2172e72feaa5017619873e
2,421
py
Python
venv/Lib/site-packages/arcade/examples/test2.py
JohnWJackson/arcadePython
b69058b0241d332a81a7d7319f70ae9237bdca94
[ "MIT" ]
null
null
null
venv/Lib/site-packages/arcade/examples/test2.py
JohnWJackson/arcadePython
b69058b0241d332a81a7d7319f70ae9237bdca94
[ "MIT" ]
null
null
null
venv/Lib/site-packages/arcade/examples/test2.py
JohnWJackson/arcadePython
b69058b0241d332a81a7d7319f70ae9237bdca94
[ "MIT" ]
1
2020-11-06T18:46:35.000Z
2020-11-06T18:46:35.000Z
""" Earth moon sun """ import arcade SCREEN_WIDTH = 600 SCREEN_HEIGHT = 600 class MyGame(arcade.Window): """ Main application class. """ def on_draw(self): """ Render the screen. """ # This command has to happen before we start drawing arcade.start_render() self.earth_shape_list.draw() self.moon_shape_list.draw() def update(self, delta_time): """ Movement and game logic """ self.earth_angle += 1 self.moon_angle += 5 earth_center_x, earth_center_y = arcade.rotate_point( self.sun_x + self.earth_dist, self.sun_y, self.sun_x, self.sun_y, self.earth_angle) self.moon_shape_list.center_x = earth_center_x self.moon_shape_list.center_y = earth_center_y self.earth_shape_list.angle = self.earth_angle self.moon_shape_list.angle = self.moon_angle if __name__ == "__main__": main()
31.038462
103
0.624122
""" Earth moon sun """ import arcade SCREEN_WIDTH = 600 SCREEN_HEIGHT = 600 class MyGame(arcade.Window): """ Main application class. """ def __init__(self): # Call the parent class initializer super().__init__(SCREEN_WIDTH, SCREEN_HEIGHT, "Earth Moon Sun") self.sun_x = SCREEN_WIDTH / 2 self.sun_y = SCREEN_HEIGHT / 2 self.earth_dist = 180 self.moon_dist = 40 self.sun_dia = 20 self.earth_dia = 10 self.moon_dia = 5 self.moon_shape_list = arcade.ShapeElementList() moon = arcade.create_ellipse_filled(self.moon_dist, 0, self.moon_dia, self.moon_dia, arcade.color.WHITE) self.moon_shape_list.append(moon) self.moon_angle = 0 self.earth_angle = 0 self.earth_shape_list = arcade.ShapeElementList() sun = arcade.create_ellipse_filled(0, 0, self.sun_dia, self.sun_dia, arcade.color.YELLOW) earth = arcade.create_ellipse_filled(self.earth_dist, 0, self.earth_dia, self.earth_dia, arcade.color.BRIGHT_GREEN) self.earth_shape_list.append(sun) self.earth_shape_list.append(earth) self.earth_shape_list.center_x = self.sun_x self.earth_shape_list.center_y = self.sun_y self.moon_shape_list.center_x = self.sun_x + self.earth_dist self.moon_shape_list.center_y = self.sun_y arcade.set_background_color(arcade.color.DARK_MIDNIGHT_BLUE) def on_draw(self): """ Render the screen. """ # This command has to happen before we start drawing arcade.start_render() self.earth_shape_list.draw() self.moon_shape_list.draw() def update(self, delta_time): """ Movement and game logic """ self.earth_angle += 1 self.moon_angle += 5 earth_center_x, earth_center_y = arcade.rotate_point( self.sun_x + self.earth_dist, self.sun_y, self.sun_x, self.sun_y, self.earth_angle) self.moon_shape_list.center_x = earth_center_x self.moon_shape_list.center_y = earth_center_y self.earth_shape_list.angle = self.earth_angle self.moon_shape_list.angle = self.moon_angle def main(): window = MyGame() arcade.run() if __name__ == "__main__": main()
1,422
0
50
4288e59835e07bac230630007cd7f939850fbd5e
2,247
py
Python
mytest_export_py.py
wangping984/Ultra-Fast-Lane-Detection
b7559c1469d832bf5afe5d158dd3ad63b4df9d9c
[ "MIT" ]
null
null
null
mytest_export_py.py
wangping984/Ultra-Fast-Lane-Detection
b7559c1469d832bf5afe5d158dd3ad63b4df9d9c
[ "MIT" ]
null
null
null
mytest_export_py.py
wangping984/Ultra-Fast-Lane-Detection
b7559c1469d832bf5afe5d158dd3ad63b4df9d9c
[ "MIT" ]
null
null
null
# %% [markdown] # 分析test.py文件 # %% import torch from model.model import parsingNet import torchvision.transforms as transforms from torch.utils.data import DataLoader from torchvision.io import read_image from PIL import Image import cv2 import scipy.special torch.backends.cudnn.benchmark = True cls_num_per_lane = 18 net = parsingNet(pretrained = False, backbone='18',cls_dim = (200+1,cls_num_per_lane,4), use_aux=False).cpu() modlePath = 'culane_18.pth' state_dict = torch.load(modlePath, map_location = 'cpu')['model'] # %% net.load_state_dict(state_dict, strict = False) net.eval() # %% img_transforms = transforms.Compose([ transforms.Resize((288, 800)), transforms.ToTensor(), transforms.Normalize((0.485, 0.456, 0.406), (0.229, 0.224, 0.225)), ]) cap = cv2.VideoCapture("20190408035014_020328AA.MP4") _,img = cap.read() img = cv2.cvtColor(img, cv2.COLOR_BGR2RGB) img2 = Image.fromarray(img) x = img_transforms(img2) x = x.unsqueeze(0).cpu()+1 # %% img_path = "mytest.jpg" image = Image.open(img_path) img = img_transforms(image) img = img.cpu() img = img.unsqueeze(0).cpu()+1 with torch.no_grad(): out = net(img) # %% [markdown] # 下面参照demo.py处理输出数据 # %% out_j = out[0].data.cpu().numpy() # 下面让18行row ankor上下颠倒排列 out_j = out_j[:, ::-1, :] # softmax的参数axis=0,表示只对201个gridding做softmax运算 # out_j1[:-1, :, :]表示第一维度gridding数量减1,去掉最后一个 prob = scipy.special.softmax(out_j[:-1, :, :], axis=0) # %% import numpy as np idx = np.arange(200) + 1 idx1 = idx.reshape(-1, 1, 1) loc = np.sum(prob * idx1, axis=0) out_j = np.argmax(out_j, axis=0) loc[out_j == 200] = 0 out_j = loc # %% vis = cv2.imread(img_path) col_sample = np.linspace(0, 800 - 1, 200) col_sample_w = col_sample[1] - col_sample[0] img_w, img_h = 1640, 590 row_anchor = [121, 131, 141, 150, 160, 170, 180, 189, 199, 209, 219, 228, 238, 248, 258, 267, 277, 287] for i in range(out_j.shape[1]): if np.sum(out_j[:, i] != 0) > 2: for k in range(out_j.shape[0]): if out_j[k, i] > 0: ppp = (int(out_j[k, i] * col_sample_w * img_w / 800) - 1, int(img_h * (row_anchor[cls_num_per_lane-1-k]/288)) - 1 ) cv2.circle(vis,ppp,5,(0,255,0),-1) # %% cv2.imwrite('out4.jpg', vis)
24.966667
131
0.653761
# %% [markdown] # 分析test.py文件 # %% import torch from model.model import parsingNet import torchvision.transforms as transforms from torch.utils.data import DataLoader from torchvision.io import read_image from PIL import Image import cv2 import scipy.special torch.backends.cudnn.benchmark = True cls_num_per_lane = 18 net = parsingNet(pretrained = False, backbone='18',cls_dim = (200+1,cls_num_per_lane,4), use_aux=False).cpu() modlePath = 'culane_18.pth' state_dict = torch.load(modlePath, map_location = 'cpu')['model'] # %% net.load_state_dict(state_dict, strict = False) net.eval() # %% img_transforms = transforms.Compose([ transforms.Resize((288, 800)), transforms.ToTensor(), transforms.Normalize((0.485, 0.456, 0.406), (0.229, 0.224, 0.225)), ]) cap = cv2.VideoCapture("20190408035014_020328AA.MP4") _,img = cap.read() img = cv2.cvtColor(img, cv2.COLOR_BGR2RGB) img2 = Image.fromarray(img) x = img_transforms(img2) x = x.unsqueeze(0).cpu()+1 # %% img_path = "mytest.jpg" image = Image.open(img_path) img = img_transforms(image) img = img.cpu() img = img.unsqueeze(0).cpu()+1 with torch.no_grad(): out = net(img) # %% [markdown] # 下面参照demo.py处理输出数据 # %% out_j = out[0].data.cpu().numpy() # 下面让18行row ankor上下颠倒排列 out_j = out_j[:, ::-1, :] # softmax的参数axis=0,表示只对201个gridding做softmax运算 # out_j1[:-1, :, :]表示第一维度gridding数量减1,去掉最后一个 prob = scipy.special.softmax(out_j[:-1, :, :], axis=0) # %% import numpy as np idx = np.arange(200) + 1 idx1 = idx.reshape(-1, 1, 1) loc = np.sum(prob * idx1, axis=0) out_j = np.argmax(out_j, axis=0) loc[out_j == 200] = 0 out_j = loc # %% vis = cv2.imread(img_path) col_sample = np.linspace(0, 800 - 1, 200) col_sample_w = col_sample[1] - col_sample[0] img_w, img_h = 1640, 590 row_anchor = [121, 131, 141, 150, 160, 170, 180, 189, 199, 209, 219, 228, 238, 248, 258, 267, 277, 287] for i in range(out_j.shape[1]): if np.sum(out_j[:, i] != 0) > 2: for k in range(out_j.shape[0]): if out_j[k, i] > 0: ppp = (int(out_j[k, i] * col_sample_w * img_w / 800) - 1, int(img_h * (row_anchor[cls_num_per_lane-1-k]/288)) - 1 ) cv2.circle(vis,ppp,5,(0,255,0),-1) # %% cv2.imwrite('out4.jpg', vis)
0
0
0
84eec7287516857ac3fe21ded84f7686a66988d3
131
py
Python
venv/lib/python3.7/site-packages/crispy_forms_materialize/__init__.py
fullstack-overkill/Api
77cb5b8209be3b34bb2f7ea7b3ec979cc46a3b55
[ "MIT" ]
null
null
null
venv/lib/python3.7/site-packages/crispy_forms_materialize/__init__.py
fullstack-overkill/Api
77cb5b8209be3b34bb2f7ea7b3ec979cc46a3b55
[ "MIT" ]
4
2020-06-05T21:11:56.000Z
2021-09-08T01:02:17.000Z
venv/lib/python3.7/site-packages/crispy_forms_materialize/__init__.py
fullstack-overkill/Api
77cb5b8209be3b34bb2f7ea7b3ec979cc46a3b55
[ "MIT" ]
null
null
null
# -*- coding: utf-8 -*- """ Django application to add 'django-crispy-forms' layout objects for Materialize """ __version__ = '0.2'
21.833333
78
0.679389
# -*- coding: utf-8 -*- """ Django application to add 'django-crispy-forms' layout objects for Materialize """ __version__ = '0.2'
0
0
0
6d4307cc55255c7f8c96605174ff284f8569c1df
25,124
py
Python
server/models/match.py
nikolastojsin/donkey-kong-drs-projekat
f7f837a7195aa731badb25d280c06317e9ada7d1
[ "MIT" ]
null
null
null
server/models/match.py
nikolastojsin/donkey-kong-drs-projekat
f7f837a7195aa731badb25d280c06317e9ada7d1
[ "MIT" ]
null
null
null
server/models/match.py
nikolastojsin/donkey-kong-drs-projekat
f7f837a7195aa731badb25d280c06317e9ada7d1
[ "MIT" ]
null
null
null
import json import multiprocessing as mp import random import threading import time import numpy as np from threading import Thread, Lock from common.constants import * from common.enums.climb_state import ClimbState from common.enums.collision_control_methods import CCMethods from common.enums.direction import Direction from common.enums.layout import Layouts from common.enums.layout_block import LayoutBlock from common.enums.player import Player from common.enums.server_message import ServerMessage from common.layout_builder import get_level_layout from server.donkey_kong_server import Server from server.models.collision.pipe_message import Message from server.models.game_objects.barrel import Barrel from server.models.game_objects.coin import Coin from server.models.game_objects.gorilla import Gorilla from server.models.game_objects.princess import Princess from server.models.networking.client import Client class Match: """ Starts object threads """ """ Sets the scene layout, notifies players to load the scene """ """ Sends a message to all players in the match """ """ Sends a message to the opponent """ """ Adds a player to the match """ """ Removes the player from the match and ends the match if favor of his opponent """ """ Checks if a player can move in the desired direction. """ """ Sets the layout of the current level """ """ Resets player lives """ """ Checks if a player should fall. Notifies both players to move the avatar of the falling player down. """ """ Checks if both players are dead """ """ Handles barrel movement, removing and collision with players """ """ Handles collision with princess, starts next level upon collision """ """ Handles collision with gorilla """ """ Handles gorilla movement and barrel throwing """ """ Handles coin drawing and removal """ """ Sets coin position """ """ Sends coin effect messages """ """ Notifies both players to move the gorilla """ """ Notifies both players to draw a barrel """ """ Thread safe check if threads should terminate """ """ Checks if both players are dead """ """ Notifies both players to move the player avatar left """ """ Notifies both players to move the player avatar right """ """ Notifies both players to move the player avatar up """ """ Notifies both players to move the player avatar down """ """ Stops running threads, closes all pipes to collision control and notifies players that the match ended """ """ Creates a pipe between collision control and this match """ """ Sets starting positions for players, princess, gorilla and gorilla movement boundaries """ """ Sets the current layout of the scene """ """ Resets player positions to their starting ones fot that scene """ """ Thread safe deleting of all barrels """
47.855238
139
0.607427
import json import multiprocessing as mp import random import threading import time import numpy as np from threading import Thread, Lock from common.constants import * from common.enums.climb_state import ClimbState from common.enums.collision_control_methods import CCMethods from common.enums.direction import Direction from common.enums.layout import Layouts from common.enums.layout_block import LayoutBlock from common.enums.player import Player from common.enums.server_message import ServerMessage from common.layout_builder import get_level_layout from server.donkey_kong_server import Server from server.models.collision.pipe_message import Message from server.models.game_objects.barrel import Barrel from server.models.game_objects.coin import Coin from server.models.game_objects.gorilla import Gorilla from server.models.game_objects.princess import Princess from server.models.networking.client import Client class Match: def __init__(self, parent: 'Server'): self.__parent__ = parent self.players = [] self.princess = Princess() self.princess_reached = False self.gorilla = Gorilla() self.coin = Coin() self.current_scene = 1 self.kill_thread = False self.kill_thread_lock = Lock() self.barrels_lock = Lock() self.ending = False self.cc_endpoint = self.__add_cc_endpoint() self.level_layout = None self.barrel_speed = 0.03 self.barrels = np.array([Barrel(i) for i in range(BARREL_POOL_SIZE)]) self.players_falling_thread = Thread(target=self.__players_falling_thread_do_work) self.barrels_fall_thread = Thread(target=self.__barrels_fall_thread_do_work) self.check_end_match_thread = Thread(target=self.__check_end_match_thread_do_work) self.princess_collision_thread = Thread(target=self.__princess_collision_thread_do_work) self.gorilla_thread = Thread(target=self.__gorilla_thread_do_work) self.gorilla_collision_thread = Thread(target=self.__gorilla_collision_thread_do_work) self.coin_thread = Thread(target=self.__coin_thread_do_work) """ Starts object threads """ def start_threads(self): self.players_falling_thread.start() self.barrels_fall_thread.start() self.princess_collision_thread.start() self.gorilla_thread.start() self.gorilla_collision_thread.start() self.check_end_match_thread.start() self.coin_thread.start() """ Sets the scene layout, notifies players to load the scene """ def load_scene(self): if self.current_scene == 1: self.set_level_layout(Layouts.FirstLevel) elif self.current_scene == 2: self.set_level_layout(Layouts.SecondLevel) elif self.current_scene == 3: self.set_level_layout(Layouts.ThirdLevel) elif self.current_scene == 4: self.set_level_layout(Layouts.FourthLevel) elif self.current_scene == 5: self.set_level_layout(Layouts.FifthLevel) self.barrel_speed /= BARREL_SPEED_MULTIPLIER message = json.dumps( { "command": ServerMessage.LOAD_GAME_SCENE.value, "layout": self.current_scene, "player": Player.PLAYER_1.value, "my_lives": self.players[0].lives, "opponent_lives": self.players[1].lives }) self.players[0].send(message) message = json.dumps( { "command": ServerMessage.LOAD_GAME_SCENE.value, "layout": self.current_scene, "player": Player.PLAYER_2.value, "my_lives": self.players[1].lives, "opponent_lives": self.players[0].lives }) self.players[1].send(message) self.__reset_barrels() self.princess_reached = False self.players[0].ready = False self.players[1].ready = False self.players[0].highest_y = 600 self.players[1].highest_y = 600 """ Sends a message to all players in the match """ def send_to_all(self, msg): for player in self.players: player.send(msg) """ Sends a message to the opponent """ def send_to_opponent(self, msg, player: Client): for p in self.players: if p != player: p.send(msg) """ Adds a player to the match """ def add_player(self, player: Client): self.players.append(player) """ Removes the player from the match and ends the match if favor of his opponent """ def player_disconnected(self, player: 'Client'): self.players.remove(player) self.__end() """ Checks if a player can move in the desired direction. """ def move(self, player: Client, direction: Direction): player.latest_direction = direction if direction == Direction.LEFT: self.cc_endpoint.send(Message(CCMethods.END_OF_SCREEN_L, player.x)) msg = self.cc_endpoint.recv() self.__move_left(player, msg) elif direction == Direction.RIGHT: self.cc_endpoint.send(Message(CCMethods.END_OF_SCREEN_R, player.x)) msg = self.cc_endpoint.recv() self.__move_right(player, msg) elif direction == Direction.UP: self.cc_endpoint.send(Message(CCMethods.CLIMB_UP, player.x, player.y, self.level_layout)) msg = self.cc_endpoint.recv() self.__move_up(player, msg) elif direction == Direction.DOWN: self.cc_endpoint.send(Message(CCMethods.CLIMB_DOWN, player.x, player.y, self.level_layout)) msg = self.cc_endpoint.recv() self.__move_down(player, msg) """ Sets the layout of the current level """ def set_level_layout(self, layout: Layouts): self.level_layout = get_level_layout(layout.value) self.__set_starting_pos() """ Resets player lives """ def reset_lives(self): for player in self.players: player.lives = PLAYER_LIVES """ Checks if a player should fall. Notifies both players to move the avatar of the falling player down. """ def __players_falling_thread_do_work(self): thread_endpoint = self.__add_cc_endpoint() while not self.__check_thread_kill(): if self.players[0].ready is True and self.players[1].ready is True: for player in self.players: if player.x is not None and player.y is not None and ( player.latest_direction == Direction.LEFT or player.latest_direction == Direction.RIGHT): thread_endpoint.send(Message(CCMethods.FALLING, player.x, player.y, player.latest_direction, self.level_layout)) msg = thread_endpoint.recv() if msg.args[0]: player.falling = True message = json.dumps({ "command": ServerMessage.FALL.value }) player.send(message) message = json.dumps({ "command": ServerMessage.FALL_OPPONENT.value }) self.send_to_opponent(message, player) player.y += 5 else: player.falling = False time.sleep(0.02) thread_endpoint.send(Message(CCMethods.KILL_PROCESS)) thread_endpoint.close() """ Checks if both players are dead """ def __check_end_match_thread_do_work(self): while self.__check_thread_kill() is False and self.__check_end_match() is False: time.sleep(0.1) self.__end() """ Handles barrel movement, removing and collision with players """ def __barrels_fall_thread_do_work(self): thread_endpoint = self.__add_cc_endpoint() while not self.__check_thread_kill(): if not self.princess_reached and self.players[0].ready and self.players[1].ready: for index, barrel in enumerate(self.barrels): if barrel.drawn: thread_endpoint.send(Message(CCMethods.END_OF_SCREEN_V, barrel.y)) msg = thread_endpoint.recv() # barrel reached end of screen, remove it if msg.args[0]: message = json.dumps({ "command": ServerMessage.REMOVE_BARREL.value, "index": index }) self.send_to_all(message) barrel.drawn = False # barrel has not reached end of screen, fall else: move_barrel = True for player in self.players: if barrel.x is not None and barrel.y is not None and player.x is not None and player.y is not None: thread_endpoint.send(Message(CCMethods.BARREL_COLLISION, barrel.x, barrel.y, player.x, player.y)) msg = thread_endpoint.recv() if msg.args[0]: self.__reset_player_pos(player) player.lose_life() message = json.dumps({ "command": ServerMessage.HIT.value, "index": index, "lives": player.lives }) player.send(message) message = json.dumps( { "command": ServerMessage.OPPONENT_HIT.value, "index": index, "lives": player.lives }) self.send_to_opponent(message, player) barrel.drawn = False move_barrel = False if move_barrel: message = json.dumps({ "command": ServerMessage.MOVE_BARREL.value, "index": index }) self.send_to_all(message) barrel.y += 5 time.sleep(self.barrel_speed) thread_endpoint.send(Message(CCMethods.KILL_PROCESS)) thread_endpoint.close() """ Handles collision with princess, starts next level upon collision """ def __princess_collision_thread_do_work(self): thread_endpoint = self.__add_cc_endpoint() while not self.__check_thread_kill(): if self.princess_reached is False and self.players[0].ready is True and self.players[1].ready is True: for player in self.players: if player.x is not None and player.y is not None: thread_endpoint.send(Message(CCMethods.PRINCESS_COLLISION, self.princess.x, self.princess.y, player.x, player.y)) msg = thread_endpoint.recv() if msg.args[0]: self.princess_reached = True self.__set_current_scene() self.load_scene() time.sleep(0.03) thread_endpoint.send(Message(CCMethods.KILL_PROCESS)) thread_endpoint.close() """ Handles collision with gorilla """ def __gorilla_collision_thread_do_work(self): thread_endpoint = self.__add_cc_endpoint() while not self.__check_thread_kill(): if self.princess_reached is False and self.players[0].ready is True and self.players[1].ready is True: for player in self.players: if player.x is not None and player.y is not None: thread_endpoint.send(Message(CCMethods.GORILLA_COLLISION, self.gorilla.x, self.gorilla.y, player.x, player.y)) msg = thread_endpoint.recv() if msg.args[0]: self.__reset_player_pos(player) player.lose_life() message = json.dumps({ "command": ServerMessage.GORILLA_HIT.value, "lives": player.lives }) player.send(message) message = json.dumps({ "command": ServerMessage.GORILLA_HIT_OPPONENT.value, "lives": player.lives }) self.send_to_opponent(message, player) thread_endpoint.send(Message(CCMethods.KILL_PROCESS)) thread_endpoint.close() """ Handles gorilla movement and barrel throwing """ def __gorilla_thread_do_work(self): count = 0 while not self.__check_thread_kill(): if not self.princess_reached and self.players[0].ready is True and self.players[1].ready is True: if count == GORILLA_BARREL_THROW_DELAY: self.__gorilla_throw_barrel() count = 0 time.sleep(0.8) else: self.__gorilla_move() time.sleep(0.2) count += 1 """ Handles coin drawing and removal """ def __coin_thread_do_work(self): thread_endpoint = self.__add_cc_endpoint() while not self.__check_thread_kill(): if self.princess_reached is False and self.players[0].ready is True and self.players[1].ready is True: if self.coin.drawn is False: time.sleep(10) self.__coin_set_position() self.coin.drawn = True message = json.dumps({ "command": ServerMessage.DRAW_COIN.value, "x": self.coin.x, "y": self.coin.y }) self.send_to_all(message) else: for player in self.players: if player.x is not None and player.y is not None: thread_endpoint.send(Message(CCMethods.COIN_COLLISION, self.coin.x, self.coin.y, player.x, player.y)) msg = thread_endpoint.recv() if msg.args[0]: self.coin.drawn = False message = json.dumps({ "command": ServerMessage.REMOVE_COIN.value }) self.send_to_all(message) self.__coin_add_effect(player) thread_endpoint.send(Message(CCMethods.KILL_PROCESS)) thread_endpoint.close() """ Sets coin position """ def __coin_set_position(self): rows = int(SCENE_HEIGHT / SCENE_GRID_BLOCK_HEIGHT) columns = int(SCENE_WIDTH / SCENE_GRID_BLOCK_WIDTH) while True: row = np.random.randint(0, rows) column = np.random.randint(0, columns) if self.level_layout[row][column] == LayoutBlock.Platform: break self.coin.x = column * SCENE_GRID_BLOCK_WIDTH self.coin.y = (row - 1) * SCENE_GRID_BLOCK_HEIGHT """ Sends coin effect messages """ def __coin_add_effect(self, player: Client): effect = np.random.randint(0, 2) if effect == 0: if player.lives == PLAYER_LIVES: return player.lives += 1 message = json.dumps({ "command": ServerMessage.EFFECT_GAIN_LIFE.value, "lives": player.lives }) player.send(message) message = json.dumps({ "command": ServerMessage.EFFECT_GAIN_LIFE_OPPONENT.value, "lives": player.lives }) self.send_to_opponent(message, player) elif effect == 1: player.lives -= 1 message = json.dumps({ "command": ServerMessage.EFFECT_LOSE_LIFE.value, "lives": player.lives }) player.send(message) message = json.dumps({ "command": ServerMessage.EFFECT_LOSE_LIFE_OPPONENT.value, "lives": player.lives }) self.send_to_opponent(message, player) """ Notifies both players to move the gorilla """ def __gorilla_move(self): random_direction = random.choice([Direction.LEFT, Direction.RIGHT]) x = int(self.gorilla.x / SCENE_GRID_BLOCK_WIDTH) if random_direction == Direction.LEFT: if not x <= self.gorilla.bound_start: move_direction = Direction.LEFT else: move_direction = Direction.RIGHT else: if not x >= self.gorilla.bound_end: move_direction = Direction.RIGHT else: move_direction = Direction.LEFT if move_direction == Direction.LEFT: self.gorilla.x -= 40 elif move_direction == Direction.RIGHT: self.gorilla.x += 40 message = json.dumps({ "command": ServerMessage.GORILLA_MOVE.value, "direction": move_direction.value }) self.send_to_all(message) """ Notifies both players to draw a barrel """ def __gorilla_throw_barrel(self): for barrel in self.barrels: if not barrel.drawn: barrel.drawn = True barrel.set_coordinates(self.gorilla.x + 14, self.gorilla.y + 40) message = json.dumps( { "command": ServerMessage.GORILLA_THROW_BARREL.value, "x": barrel.x, "y": barrel.y, "index": barrel.index }) self.send_to_all(message) break """ Thread safe check if threads should terminate """ def __check_thread_kill(self): self.kill_thread_lock.acquire() ret_val = self.kill_thread self.kill_thread_lock.release() return ret_val """ Checks if both players are dead """ def __check_end_match(self) -> bool: if self.players[0].lives <= 0 and self.players[1].lives <= 0: return True return False """ Notifies both players to move the player avatar left """ def __move_left(self, player: Client, msg: Message): # player is not at the edge of the screen if not msg.args[0]: player.x -= 5 message = json.dumps({ "command": ServerMessage.MOVE.value, "direction": Direction.LEFT.value }) player.send(message) message = json.dumps({ "command": ServerMessage.MOVE_OPPONENT.value, "direction": Direction.LEFT.value }) self.send_to_opponent(message, player) # player is at the edge of the screen else: message = json.dumps({ "command": ServerMessage.STOP.value }) player.send(message) message = json.dumps({ "command": ServerMessage.STOP_OPPONENT.value }) self.send_to_opponent(message, player) """ Notifies both players to move the player avatar right """ def __move_right(self, player: Client, msg: Message): # player is not at the edge of the screen if not msg.args[0]: player.x += 5 message = json.dumps({ "command": ServerMessage.MOVE.value, "direction": Direction.RIGHT.value }) player.send(message) message = json.dumps({ "command": ServerMessage.MOVE_OPPONENT.value, "direction": Direction.RIGHT.value }) self.send_to_opponent(message, player) # player is at the edge of the screen else: message = json.dumps({ "command": ServerMessage.STOP.value }) player.send(message) message = json.dumps({ "command": ServerMessage.STOP_OPPONENT.value }) self.send_to_opponent(message, player) """ Notifies both players to move the player avatar up """ def __move_up(self, player: Client, msg: Message): if msg.args[0] == ClimbState.CLIMB or msg.args[0] == ClimbState.FINISH: player.y -= 5 player.climbing = True if msg.args[0] == ClimbState.NONE and player.climbing is True: player.add_point() message = json.dumps({ "command": ServerMessage.SET_POINTS.value, "points": player.points }) player.send(message) message = json.dumps({ "command": ServerMessage.SET_POINTS_OPPONENT.value, "points": player.points }) self.send_to_opponent(message, player) player.climbing = False message = json.dumps({ "command": ServerMessage.CLIMB_UP.value, "climb_state": msg.args[0].value }) player.send(message) message = json.dumps({ "command": ServerMessage.CLIMB_UP_OPPONENT.value, "climb_state": msg.args[0].value }) self.send_to_opponent(message, player) """ Notifies both players to move the player avatar down """ def __move_down(self, player: Client, msg: Message): if msg.args[0] == ClimbState.CLIMB or msg.args[0] == ClimbState.FINISH: player.y += 5 message = json.dumps({ "command": ServerMessage.CLIMB_DOWN.value, "climb_state": msg.args[0].value }) player.send(message) message = json.dumps({ "command": ServerMessage.CLIMB_DOWN_OPPONENT.value, "climb_state": msg.args[0].value }) self.send_to_opponent(message, player) """ Stops running threads, closes all pipes to collision control and notifies players that the match ended """ def __end(self): self.kill_thread_lock.acquire() self.kill_thread = True self.kill_thread_lock.release() self.ending = True message = json.dumps({ "command": ServerMessage.MATCH_ENDED.value }) self.send_to_all(message) if self.barrels_fall_thread.isAlive() and threading.current_thread() != self.barrels_fall_thread: self.barrels_fall_thread.join() if self.players_falling_thread.isAlive() and threading.current_thread() != self.players_falling_thread: self.players_falling_thread.join() if self.princess_collision_thread.isAlive() and threading.current_thread() != self.princess_collision_thread: self.princess_collision_thread.join() if self.gorilla_thread.isAlive() and threading.current_thread() != self.gorilla_thread: self.gorilla_thread.join() if self.gorilla_collision_thread.isAlive() and threading.current_thread() != self.gorilla_collision_thread: self.gorilla_collision_thread.join() if self.check_end_match_thread.isAlive() and threading.current_thread() != self.check_end_match_thread: self.check_end_match_thread.join() if self.coin_thread.isAlive() and threading.current_thread() != self.coin_thread: self.coin_thread.join() for player in self.players: player.points = 0 self.cc_endpoint.send(Message(CCMethods.KILL_PROCESS)) if self.__parent__.matches.__contains__(self): self.__parent__.matches.remove(self) """ Creates a pipe between collision control and this match """ def __add_cc_endpoint(self) -> 'mp.Connection': parent, child = mp.Pipe() self.__parent__.cc_endpoint.send(Message(CCMethods.ADD_ENDPOINT, child)) return parent """ Sets starting positions for players, princess, gorilla and gorilla movement boundaries """ def __set_starting_pos(self): rows = int(SCENE_HEIGHT / SCENE_GRID_BLOCK_HEIGHT) columns = int(SCENE_WIDTH / SCENE_GRID_BLOCK_WIDTH) gorilla_x = 0 gorilla_y = 0 for row in range(rows): for column in range(columns): if self.level_layout[row][column] == LayoutBlock.Player_1: self.players[0].starting_x = column * SCENE_GRID_BLOCK_WIDTH self.players[0].starting_y = row * SCENE_GRID_BLOCK_HEIGHT + 5 elif self.level_layout[row][column] == LayoutBlock.Player_2: self.players[1].starting_x = column * SCENE_GRID_BLOCK_WIDTH + 13 self.players[1].starting_y = row * SCENE_GRID_BLOCK_HEIGHT + 5 elif self.level_layout[row][column] == LayoutBlock.Princess: self.princess.x = column * SCENE_GRID_BLOCK_WIDTH self.princess.y = row * SCENE_GRID_BLOCK_HEIGHT elif self.level_layout[row][column] == LayoutBlock.Gorilla: self.gorilla.x = column * SCENE_GRID_BLOCK_WIDTH self.gorilla.y = row * SCENE_GRID_BLOCK_HEIGHT - 15 gorilla_x = column gorilla_y = row for i in range(gorilla_x, 0, -1): if self.level_layout[gorilla_y + 1][i] is None: self.gorilla.bound_start = i + 1 break for i in range(gorilla_x, columns): if self.level_layout[gorilla_y + 1][i] is None: self.gorilla.bound_end = i - 1 break """ Sets the current layout of the scene """ def __set_current_scene(self): if self.current_scene == 5: self.current_scene = 1 else: self.current_scene += 1 """ Resets player positions to their starting ones fot that scene """ def __reset_player_pos(self, player: Client): player.x = player.starting_x player.y = player.starting_y """ Thread safe deleting of all barrels """ def __reset_barrels(self): self.barrels_lock.acquire() for barrel in self.barrels: barrel.drawn = False self.barrels_lock.release()
21,372
0
858
1a8755e5e7b5dfa739b4ec592ba01c44219647aa
15,585
py
Python
tests/test_workflow.py
SergiuIliev/up42-py
132682cf6c9d12ab68972f187ab82a998ee36e11
[ "MIT" ]
null
null
null
tests/test_workflow.py
SergiuIliev/up42-py
132682cf6c9d12ab68972f187ab82a998ee36e11
[ "MIT" ]
null
null
null
tests/test_workflow.py
SergiuIliev/up42-py
132682cf6c9d12ab68972f187ab82a998ee36e11
[ "MIT" ]
null
null
null
from pathlib import Path import json import pytest import requests_mock import shapely # pylint: disable=unused-import,wrong-import-order from .context import Workflow from .fixtures import auth_mock, auth_live, workflow_mock, workflow_live, job_mock import up42 json_workflow_tasks = { "data": [ { "id": "c0d04ec3-98d7-4183-902f-5bcb2a176d89", "name": "sobloo-s2-l1c-aoiclipped:1", "block": { "name": "sobloo-s2-l1c-aoiclipped", "parameters": { "nodata": {"type": "number",}, "time": { "type": "dateRange", "default": "2018-01-01T00:00:00+00:00/2020-12-31T23:59:59+00:00", }, }, }, }, { "id": "af626c54-156e-4f13-a743-55efd27de533", "name": "tiling:1", "block": { "name": "tiling", "parameters": { "nodata": { "type": "number", "default": None, "required": False, "description": "Value representing..", }, "tile_width": { "type": "number", "default": 768, "required": True, "description": "Width of a tile in pixels", }, }, }, }, ], "error": {}, } @pytest.mark.live @pytest.mark.live @pytest.mark.skip # TODO: Resolve @pytest.mark.live @pytest.mark.live @pytest.mark.live @pytest.mark.live @pytest.mark.skip @pytest.mark.live # TODO: Resolve # def test_update_name(workflow_mock, caplog): # new_name = "new_workflow_name" # with requests_mock.Mocker() as m: # url_update_name = ( # f"{workflow_mock.auth._endpoint()}/projects/{workflow_mock.auth.project_id}/workflows/" # f"{workflow_mock.workflow_id}" # ) # json_new_properties = {"data": {}, "error": {}} # m.post( # url=url_update_name, # json=json_new_properties, # ) # # workflow_mock.update_name(name=new_name) # assert f"Updated workflow name: {new_name}" in caplog.text @pytest.mark.skip # TODO: Resolve
34.943946
101
0.60924
from pathlib import Path import json import pytest import requests_mock import shapely # pylint: disable=unused-import,wrong-import-order from .context import Workflow from .fixtures import auth_mock, auth_live, workflow_mock, workflow_live, job_mock import up42 json_workflow_tasks = { "data": [ { "id": "c0d04ec3-98d7-4183-902f-5bcb2a176d89", "name": "sobloo-s2-l1c-aoiclipped:1", "block": { "name": "sobloo-s2-l1c-aoiclipped", "parameters": { "nodata": {"type": "number",}, "time": { "type": "dateRange", "default": "2018-01-01T00:00:00+00:00/2020-12-31T23:59:59+00:00", }, }, }, }, { "id": "af626c54-156e-4f13-a743-55efd27de533", "name": "tiling:1", "block": { "name": "tiling", "parameters": { "nodata": { "type": "number", "default": None, "required": False, "description": "Value representing..", }, "tile_width": { "type": "number", "default": 768, "required": True, "description": "Width of a tile in pixels", }, }, }, }, ], "error": {}, } def test_workflow_get_info(workflow_mock): del workflow_mock.info with requests_mock.Mocker() as m: url_workflow_info = ( f"{workflow_mock.auth._endpoint()}/projects/" f"{workflow_mock.project_id}/workflows/" f"{workflow_mock.workflow_id}" ) m.get(url=url_workflow_info, json={"data": {"xyz": 789}, "error": {}}) info = workflow_mock._get_info() assert isinstance(workflow_mock, Workflow) assert info["xyz"] == 789 assert workflow_mock.info["xyz"] == 789 def test_get_compatible_blocks(workflow_mock): url_workflow_tasks = ( f"{workflow_mock.auth._endpoint()}/projects/{workflow_mock.auth.project_id}/workflows/" f"{workflow_mock.workflow_id}/tasks" ) with requests_mock.Mocker() as m: m.get(url=url_workflow_tasks, json=json_workflow_tasks) url_compatible_blocks = ( f"{workflow_mock.auth._endpoint()}/projects/{workflow_mock.project_id}/" f"workflows/{workflow_mock.workflow_id}/" f"compatible-blocks?parentTaskName=tiling:1" ) json_compatible_blocks = { "data": { "blocks": [ {"blockId": "aaa123", "name": "aaa", "versionTag": "2.0"}, {"blockId": "bbb123", "name": "bbb", "versionTag": "2.0"}, ], "error": {}, } } m.get(url=url_compatible_blocks, json=json_compatible_blocks) compatible_blocks = workflow_mock.get_compatible_blocks() assert isinstance(compatible_blocks, dict) assert "aaa" in list(compatible_blocks.keys()) @pytest.mark.live def test_get_compatible_blocks_live(workflow_live): compatible_blocks = workflow_live.get_compatible_blocks() assert isinstance(compatible_blocks, dict) assert "tiling" in list(compatible_blocks.keys()) def test_get_workflow_tasks_normal_and_basic(workflow_mock): url_workflow_tasks = ( f"{workflow_mock.auth._endpoint()}/projects/{workflow_mock.auth.project_id}/workflows/" f"{workflow_mock.workflow_id}/tasks" ) with requests_mock.Mocker() as m: m.get(url=url_workflow_tasks, json=json_workflow_tasks) tasks = workflow_mock.get_workflow_tasks(basic=False) assert len(tasks) == 2 assert tasks[0] == { "id": "c0d04ec3-98d7-4183-902f-5bcb2a176d89", "name": "sobloo-s2-l1c-aoiclipped:1", "block": { "name": "sobloo-s2-l1c-aoiclipped", "parameters": { "nodata": {"type": "number"}, "time": { "type": "dateRange", "default": "2018-01-01T00:00:00+00:00/2020-12-31T23:59:59+00:00", }, }, }, } with requests_mock.Mocker() as m: m.get(url=url_workflow_tasks, json=json_workflow_tasks) tasks = workflow_mock.get_workflow_tasks(basic=True) assert len(tasks) == 2 assert tasks["sobloo-s2-l1c-aoiclipped:1"] == "c0d04ec3-98d7-4183-902f-5bcb2a176d89" @pytest.mark.live def test_get_workflow_tasks_live(workflow_live): workflow_tasks = workflow_live.get_workflow_tasks(basic=True) assert isinstance(workflow_tasks, dict) assert "sobloo-s2-l1c-aoiclipped:1" in list(workflow_tasks.keys()) def test_construct_full_workflow_tasks_dict(workflow_mock): input_tasks = [ "a2daaab4-196d-4226-a018-a810444dcad1", "4ed70368-d4e1-4462-bef6-14e768049471", ] with requests_mock.Mocker() as m: url_get_blocks = f"{workflow_mock.auth._endpoint()}/blocks" m.get( url=url_get_blocks, json={ "data": [ {"id": "4ed70368-d4e1-4462-bef6-14e768049471", "name": "tiling"}, { "id": "c0d04ec3-98d7-4183-902f-5bcb2a176d89", "name": "sharpening", }, { "id": "a2daaab4-196d-4226-a018-a810444dcad1", "name": "sobloo-s2-l1c-aoiclipped", }, ], "error": {}, }, ) full_workflow_tasks_dict = workflow_mock._construct_full_workflow_tasks_dict( input_tasks=input_tasks ) assert isinstance(full_workflow_tasks_dict, list) assert full_workflow_tasks_dict[0]["name"] == "sobloo-s2-l1c-aoiclipped:1" assert full_workflow_tasks_dict[0]["parentName"] is None assert full_workflow_tasks_dict[1]["name"] == "tiling:1" assert full_workflow_tasks_dict[1]["parentName"] == "sobloo-s2-l1c-aoiclipped:1" assert ( full_workflow_tasks_dict[1]["blockId"] == "4ed70368-d4e1-4462-bef6-14e768049471" ) @pytest.mark.skip # TODO: Resolve def test_add_workflow_tasks_full(workflow_mock, caplog): input_tasks_full = [ { "name": "sobloo-s2-l1c-aoiclipped:1", "parentName": None, "blockId": "a2daaab4-196d-4226-a018-a810444dcad1", }, { "name": "sharpening:1", "parentName": "sobloo-s2-l1c-aoiclipped", "blockId": "4ed70368-d4e1-4462-bef6-14e768049471", }, ] job_url = ( f"{workflow_mock.auth._endpoint()}/projects/{workflow_mock.project_id}/workflows/" f"{workflow_mock.workflow_id}/tasks/" ) with requests_mock.Mocker() as m: m.post(url=job_url, status_code=200) workflow_mock.add_workflow_tasks(input_tasks_full) assert f"Added tasks to workflow: {input_tasks_full}" in caplog.text @pytest.mark.live def test_add_workflow_tasks_simple_not_existing_block_id_raises_live(workflow_live): input_tasks_simple = ["12345"] with pytest.raises(Exception): workflow_live.add_workflow_tasks(input_tasks_simple) def test_get_parameter_info(workflow_mock): url_workflow_tasks = ( f"{workflow_mock.auth._endpoint()}/projects/{workflow_mock.auth.project_id}/workflows/" f"{workflow_mock.workflow_id}/tasks" ) with requests_mock.Mocker() as m: m.get(url=url_workflow_tasks, json=json_workflow_tasks) parameter_info = workflow_mock.get_parameters_info() assert isinstance(parameter_info, dict) assert all( x in list(parameter_info.keys()) for x in ["tiling:1", "sobloo-s2-l1c-aoiclipped:1"] ) assert all( x in list(parameter_info["tiling:1"].keys()) for x in ["nodata", "tile_width"] ) @pytest.mark.live def test_get_parameter_info_live(workflow_live): parameter_info = workflow_live.get_parameters_info() assert isinstance(parameter_info, dict) assert all( x in list(parameter_info.keys()) for x in ["tiling:1", "sobloo-s2-l1c-aoiclipped:1"] ) assert all( x in list(parameter_info["tiling:1"].keys()) for x in ["nodata", "tile_width", "match_extents"] ) def test_get_default_parameters(workflow_mock): url_workflow_tasks = ( f"{workflow_mock.auth._endpoint()}/projects/{workflow_mock.auth.project_id}/workflows/" f"{workflow_mock.workflow_id}/tasks" ) with requests_mock.Mocker() as m: m.get(url=url_workflow_tasks, json=json_workflow_tasks) default_parameters = workflow_mock._get_default_parameters() assert isinstance(default_parameters, dict) assert all( x in list(default_parameters.keys()) for x in ["tiling:1", "sobloo-s2-l1c-aoiclipped:1"] ) assert default_parameters["tiling:1"] == {"tile_width": 768} assert default_parameters["sobloo-s2-l1c-aoiclipped:1"] == { "time": "2018-01-01T00:00:00+00:00/2020-12-31T23:59:59+00:00" } def test_construct_parameter(workflow_mock): url_workflow_tasks = ( f"{workflow_mock.auth._endpoint()}/projects/{workflow_mock.auth.project_id}/workflows/" f"{workflow_mock.workflow_id}/tasks" ) with requests_mock.Mocker() as m: m.get(url=url_workflow_tasks, json=json_workflow_tasks) parameters = workflow_mock.construct_parameters( geometry=shapely.geometry.point.Point(1, 3), geometry_operation="bbox", start_date="2014-01-01", end_date="2016-12-31", limit=1, ) assert isinstance(parameters, dict) assert parameters == { "sobloo-s2-l1c-aoiclipped:1": { "time": "2014-01-01T00:00:00Z/2016-12-31T00:00:00Z", "limit": 1, "bbox": [0.99999, 2.99999, 1.00001, 3.00001], }, "tiling:1": {"tile_width": 768}, } def test_construct_parameter_scene_ids(workflow_mock): url_workflow_tasks = ( f"{workflow_mock.auth._endpoint()}/projects/{workflow_mock.auth.project_id}/workflows/" f"{workflow_mock.workflow_id}/tasks" ) with requests_mock.Mocker() as m: m.get(url=url_workflow_tasks, json=json_workflow_tasks) parameters = workflow_mock.construct_parameters( geometry=shapely.geometry.point.Point(1, 3), geometry_operation="bbox", scene_ids=["s2_123223"], ) assert isinstance(parameters, dict) assert parameters == { "sobloo-s2-l1c-aoiclipped:1": { "ids": ["s2_123223"], "limit": 1, "bbox": [0.99999, 2.99999, 1.00001, 3.00001], }, "tiling:1": {"tile_width": 768}, } def test_construct_parameter_order_ids(workflow_mock): url_workflow_tasks = ( f"{workflow_mock.auth._endpoint()}/projects/{workflow_mock.auth.project_id}/workflows/" f"{workflow_mock.workflow_id}/tasks" ) with requests_mock.Mocker() as m: m.get(url=url_workflow_tasks, json=json_workflow_tasks) parameters = workflow_mock.construct_parameters(order_ids=["8472712912"]) assert isinstance(parameters, dict) assert parameters == { "sobloo-s2-l1c-aoiclipped:1": {"order_ids": ["8472712912"]}, "tiling:1": {"tile_width": 768}, } def test_create_and_run_job(workflow_mock, job_mock): with requests_mock.Mocker() as m: job_url = ( f"{workflow_mock.auth._endpoint()}/projects/{workflow_mock.project_id}/" f"workflows/{workflow_mock.workflow_id}/jobs?name=_py" ) m.post(url=job_url, json={"data": {"id": job_mock.job_id}}) input_parameters_json = ( Path(__file__).resolve().parent / "mock_data/input_params_simple.json" ) m.get( url=f"{job_mock.auth._endpoint()}/projects/{job_mock.project_id}/" f"jobs/{job_mock.job_id}", json={"data": {}}, ) jb = workflow_mock.create_and_run_job(input_parameters_json) assert isinstance(jb, up42.Job) assert jb.job_id == job_mock.job_id @pytest.mark.live def test_create_and_run_job_live(workflow_live): input_parameters_json = ( Path(__file__).resolve().parent / "mock_data/input_params_simple.json" ) jb = workflow_live.create_and_run_job(input_parameters_json, track_status=True) assert isinstance(jb, up42.Job) with open(input_parameters_json) as src: assert jb.info["inputs"] == json.load(src) assert jb.info["mode"] == "DEFAULT" assert jb.get_status() == "SUCCEEDED" @pytest.mark.live def test_create_and_run_job_test_query_live(workflow_live): input_parameters_json = ( Path(__file__).resolve().parent / "mock_data/input_params_simple.json" ) jb = workflow_live.create_and_run_job( input_parameters_json, test_query=True, track_status=True ) assert isinstance(jb, up42.Job) with open(input_parameters_json) as src: job_info_params = json.load(src) job_info_params.update({"config": {"mode": "DRY_RUN"}}) assert jb.info["inputs"] == job_info_params assert jb.info["mode"] == "DRY_RUN" assert jb.get_status() == "SUCCEEDED" def test_get_jobs(workflow_mock): job_id = "87c285b4-d69b-42a4-bdc5-6fe6d0ddcbbd" with requests_mock.Mocker() as m: url_jobs = ( f"{workflow_mock.auth._endpoint()}/projects/{workflow_mock.project_id}/jobs" ) json_jobs = { "data": [{"id": job_id, "status": "SUCCEEDED", "inputs": {}, "error": {},}] } m.get(url=url_jobs, json=json_jobs) url_job_info = ( f"{workflow_mock.auth._endpoint()}/projects/" f"{workflow_mock.project_id}/jobs/{job_id}" ) m.get(url=url_job_info, json={"data": {"xyz": 789}, "error": {}}) jobs = workflow_mock.get_jobs() assert isinstance(jobs, list) assert isinstance(jobs[0], up42.Job) assert jobs[0].job_id == job_id @pytest.mark.skip @pytest.mark.live def test_get_jobs_live(workflow_live): # Too many jobs in test project jobs = workflow_live.get_jobs() assert isinstance(jobs, list) assert isinstance(jobs[0], up42.Job) # TODO: Resolve # def test_update_name(workflow_mock, caplog): # new_name = "new_workflow_name" # with requests_mock.Mocker() as m: # url_update_name = ( # f"{workflow_mock.auth._endpoint()}/projects/{workflow_mock.auth.project_id}/workflows/" # f"{workflow_mock.workflow_id}" # ) # json_new_properties = {"data": {}, "error": {}} # m.post( # url=url_update_name, # json=json_new_properties, # ) # # workflow_mock.update_name(name=new_name) # assert f"Updated workflow name: {new_name}" in caplog.text @pytest.mark.skip # TODO: Resolve def test_delete(workflow_mock, caplog): with requests_mock.Mocker() as m: delete_url = ( f"{workflow_mock.auth._endpoint()}/projects/{workflow_mock.project_id}/workflows/" f"{workflow_mock.workflow_id}" ) m.delete(url=delete_url) workflow_mock.delete() assert f"Successfully deleted workflow: {workflow_mock.workflow_id}" in caplog.text
12,713
0
451
009f418f44c5d85a6d3e9d6e673290c3f794646f
451
py
Python
redsys/languages.py
brunovila/python-redsys
f7e6dfd692e4ad5f887baf59e283d4406700f2ab
[ "MIT" ]
13
2017-04-27T08:16:38.000Z
2021-06-15T12:12:51.000Z
redsys/languages.py
brunovila/python-redsys
f7e6dfd692e4ad5f887baf59e283d4406700f2ab
[ "MIT" ]
12
2017-08-17T11:52:50.000Z
2021-09-12T17:18:23.000Z
redsys/languages.py
brunovila/python-redsys
f7e6dfd692e4ad5f887baf59e283d4406700f2ab
[ "MIT" ]
18
2017-03-16T17:36:01.000Z
2021-11-01T00:29:44.000Z
# -*- coding: utf-8 -*- CUSTOMER = '000' SPANISH = '001' ENGLISH = '002' CATALAN = '003' FRENCH = '004' GERMAN = '005' DUTCH = '006' ITALIAN = '007' SWEDISH = '008' PORTUGUESE = '009' VALENCIAN = '010' POLISH = '011' GALICIAN = '012' EUSKERA = '013' LANGUAGES = [ CUSTOMER, SPANISH, ENGLISH, CATALAN, FRENCH, GERMAN, DUTCH, ITALIAN, SWEDISH, PORTUGUESE, VALENCIAN, POLISH, GALICIAN, EUSKERA ]
13.264706
23
0.578714
# -*- coding: utf-8 -*- CUSTOMER = '000' SPANISH = '001' ENGLISH = '002' CATALAN = '003' FRENCH = '004' GERMAN = '005' DUTCH = '006' ITALIAN = '007' SWEDISH = '008' PORTUGUESE = '009' VALENCIAN = '010' POLISH = '011' GALICIAN = '012' EUSKERA = '013' LANGUAGES = [ CUSTOMER, SPANISH, ENGLISH, CATALAN, FRENCH, GERMAN, DUTCH, ITALIAN, SWEDISH, PORTUGUESE, VALENCIAN, POLISH, GALICIAN, EUSKERA ]
0
0
0
ad4da63243211d9ff16d05cfe6062d9d6bd2770e
1,321
py
Python
tests/tests_vipps.py
almazkun/vipps-python
107e065d551f0aff908f6685afc8d26d89d82176
[ "MIT" ]
2
2021-04-05T04:11:39.000Z
2021-04-08T12:56:15.000Z
tests/tests_vipps.py
asmexcaliburwoods/vipps-python
bd205e2a0a6c096bde09906baed4139b92a5b56a
[ "MIT" ]
null
null
null
tests/tests_vipps.py
asmexcaliburwoods/vipps-python
bd205e2a0a6c096bde09906baed4139b92a5b56a
[ "MIT" ]
2
2021-04-05T04:11:44.000Z
2021-05-20T13:44:47.000Z
import os import unittest from vipps import VippsEcomApi, VippsSignupApi import env VIPPS_CLIENT_ID = env.VIPPS_CLIENT_ID VIPPS_CLIENT_SECRET = env.VIPPS_CLIENT_SECRET VIPPS_SUBSCRIPTION_KEY = env.VIPPS_SUBSCRIPTION_KEY VIPPS_MERCHANT_SERIAL_NUMBER = env.VIPPS_MERCHANT_SERIAL_NUMBER VIPPS_SERVER = env.VIPPS_SERVER VIPPS_CALLBACK_PREFIX = env.VIPPS_CALLBACK_PREFIX VIPPS_FALLBACK_URL = env.VIPPS_FALLBACK_URL
31.452381
65
0.719909
import os import unittest from vipps import VippsEcomApi, VippsSignupApi import env VIPPS_CLIENT_ID = env.VIPPS_CLIENT_ID VIPPS_CLIENT_SECRET = env.VIPPS_CLIENT_SECRET VIPPS_SUBSCRIPTION_KEY = env.VIPPS_SUBSCRIPTION_KEY VIPPS_MERCHANT_SERIAL_NUMBER = env.VIPPS_MERCHANT_SERIAL_NUMBER VIPPS_SERVER = env.VIPPS_SERVER VIPPS_CALLBACK_PREFIX = env.VIPPS_CALLBACK_PREFIX VIPPS_FALLBACK_URL = env.VIPPS_FALLBACK_URL class TestVippsEcomApi(unittest.TestCase): def setUp(self): self.client = VippsEcomApi( client_id=VIPPS_CLIENT_ID, client_secret=VIPPS_CLIENT_SECRET, vipps_subscription_key=VIPPS_SUBSCRIPTION_KEY, merchant_serial_number=VIPPS_MERCHANT_SERIAL_NUMBER, vipps_server=VIPPS_SERVER, callback_prefix=VIPPS_CALLBACK_PREFIX, fall_back=VIPPS_FALLBACK_URL, ) self.order_id = "acme-shop-123-order123abc" self.amount = 151 self.transaction_text = "One pair of Vipps socks" def test_initiate(self): initiate = self.client.init_payment( order_id=self.order_id, amount=self.amount, transaction_text=self.transaction_text, ) self.assertTrue(initiate.get("orderId") == self.order_id) self.assertTrue(initiate.get("url"))
809
21
76
4bf76a83a9f3978f8a59f0e184e23fca4032779f
455
py
Python
task_1/__init__.py
Quinlys/-Yakymiv_Igor--tasks
4992ca5fd050ed35f060b5b22ed05133be5c1d5a
[ "MIT" ]
null
null
null
task_1/__init__.py
Quinlys/-Yakymiv_Igor--tasks
4992ca5fd050ed35f060b5b22ed05133be5c1d5a
[ "MIT" ]
null
null
null
task_1/__init__.py
Quinlys/-Yakymiv_Igor--tasks
4992ca5fd050ed35f060b5b22ed05133be5c1d5a
[ "MIT" ]
null
null
null
# -*- coding: utf-8 -*-
25.277778
59
0.424176
# -*- coding: utf-8 -*- def fill_spiral_matrix(n): result = [] x, y, dx, dy = 0, 0, 1, 0 arr = [[0] * n for i in range(n)] for i in range(1, n**2+1): arr[x][y] = i nx, ny = x+dx, y+dy if 0 <= nx < n and 0 <= ny < n and not arr[nx][ny]: x, y = nx, ny else: dx, dy = -dy, dx x, y = x+dx, y+dy for x in list(zip(*arr)): result.append(list(x)) return result
408
0
22
4dc424f27991bfbf38e953e9b306af71d998143b
7,711
py
Python
preprocessing/preprocessing/BubbleExtractorCombined_V1.py
gitter-manish/deploy-ml-model
90c792f2c58316ca133f31758890c92fbf0f72c0
[ "MIT" ]
null
null
null
preprocessing/preprocessing/BubbleExtractorCombined_V1.py
gitter-manish/deploy-ml-model
90c792f2c58316ca133f31758890c92fbf0f72c0
[ "MIT" ]
null
null
null
preprocessing/preprocessing/BubbleExtractorCombined_V1.py
gitter-manish/deploy-ml-model
90c792f2c58316ca133f31758890c92fbf0f72c0
[ "MIT" ]
null
null
null
import cv2 as cv import numpy as np import pandas as pd import time import os start_time = time.time() lengi = 0 df = pd.DataFrame(columns=['document_id', 'set_id', 'student_id', 'answer_keys']) xForQuads = [(344, 552), (620, 828), (897, 1106), (1174, 1382)] yForQuads = [(897, 1115), (1115, 1333), (1333, 1550), (1550, 1767), (1767, 1984)] setCords = [480, 840, 856, 944] studentCords = [480, 840, 970, 1378] thresholdForWhitePixels = 0.195 for entry in os.scandir('/home/manish/Desktop/JhunAlignedWithBlob'): if entry.path.endswith('.jpg') and entry.is_file(): src = entry.path start = src.find('image')+5 end = src.find('.jpg') docId = src[start:end] imageOriginal = cv.imread(src, -1) imageThresh = image_thresholding(imageOriginal) imageSet = imageThresh[setCords[0]:setCords[1], setCords[2]:setCords[3]] imageStudent = imageThresh[studentCords[0]:studentCords[1], studentCords[2]:studentCords[3]] data = [docId, getIds(imageSet, 2), getIds(imageStudent, 9), getAnswerKeys(imageThresh)] df.loc[len(df.index)] = data lengi += 1 print(f'Done processing image {lengi}: {docId}') # if lengi == 1: # break # break # break # print(df.head()) df['set_id'] = df['set_id'].apply('="{}"'.format) df['student_id'] = df['student_id'].apply('="{}"'.format) df['answer_keys'] = df['answer_keys'].apply('="{}"'.format) df.to_csv('/home/manish/Desktop/bubble_processed3_V3.csv', index=False) print(f'Total time taken: {(time.time() - start_time) / float(60)} minutes.')
45.358824
150
0.474517
import cv2 as cv import numpy as np import pandas as pd import time import os start_time = time.time() lengi = 0 df = pd.DataFrame(columns=['document_id', 'set_id', 'student_id', 'answer_keys']) xForQuads = [(344, 552), (620, 828), (897, 1106), (1174, 1382)] yForQuads = [(897, 1115), (1115, 1333), (1333, 1550), (1550, 1767), (1767, 1984)] setCords = [480, 840, 856, 944] studentCords = [480, 840, 970, 1378] thresholdForWhitePixels = 0.195 def getAnswerKeys(img): imageOriginal = img allScore = [] answer_keys = '' for vert in xForQuads: for hor in yForQuads: image = imageOriginal[hor[0]:hor[1], vert[0]:vert[1]] # <<<<<<<<<<<<<<<<---------------- Preprocessing and removing channels ---------->>>>>>>>>> h, w = image.shape[1], image.shape[0] image = image[20:h-10, :] rows = np.array_split(image, 5, axis=0) #<<<<<<<<<<<<<----------------- Split into image into 5 rows ------------------------>>>>>>>>>>> r, a, b, c = 1, 0.25, 0.5, 1 localKernel = np.array([[a, a, a, a, a, a], [a, b, b, b, b, a], [a, b, c, c, b, a], [a, b, c, c, b, a], [a, b, b, b, b, a], [a, a, a, a, a, a]], dtype='float16') for row in rows: cols = np.array_split(row, 4, axis=1) #<<<<<<<<<<<<<<<<-------------------- Splits each row into 4 Cells tempList = [] empty = True for col in cols: col = cv.resize(col, (36, 36), interpolation=cv.INTER_LINEAR) hCol, wCol = col.shape[1], col.shape[0] center = [int(hCol / 2), int(wCol / 2)] lowerH, upperH, lowerW, upperW = center[0] - 18, center[0] + 18, center[1] - 18, center[0] + 18 col = col[lowerH:upperH, lowerW:upperW] ################################ Internal division of a cell in 6x6 ######################### colMatrix = np.zeros((6, 6), dtype='float16') colRowGrids = np.array_split(col, 6, axis=0) #<<<<<<---------------- Splits each cell into 6 rows i = 0 for colRowGrid in colRowGrids: totalNzcValue = 36 colGrids = np.array_split(colRowGrid, 6, axis=1) #<<<<<<---------------- Splits each cell row into 6 smaller cells of size 6x6 j = 0 if totalNzcValue != 0: for colGrid in colGrids: nzc = np.count_nonzero(colGrid) colMatrix[i][j] = float(nzc/totalNzcValue) j += 1 i += 1 aggVal = np.round(np.sum(colMatrix*localKernel)/np.sum(localKernel), 4) allScore.append(aggVal) tempList.append(aggVal) for index in range(len(tempList)): if tempList[index] > thresholdForWhitePixels: empty = False answer_keys += str(index + 1) if empty == True: answer_keys += str('x') answer_keys += '#' return answer_keys def getIds(image, num): allScore = [] reqString = '' r, a, b, c = 1, 0.25, 0.5, 1 localKernel = np.array([[a, a, a, a, a, a], [a, b, b, b, b, a], [a, b, c, c, b, a], [a, b, c, c, b, a], [a, b, b, b, b, a], [a, a, a, a, a, a]], dtype='float16') rows = np.array_split(image, num, axis=1) # <<<<<<<<<<<<<----------------- Split into image into 5 rows ------------------------>>>>>>>>>>> for row in rows: row = cv.resize(row, (44, 360), interpolation=cv.INTER_AREA) cols = np.array_split(row, 10, axis=0) # <<<<<<<<<<<<<<<<-------------------- Splits each row into 4 Cells # cv.imshow('col', row) tempList = [] empty = True for col in cols: col = cv.resize(col, (36, 36), interpolation=cv.INTER_LINEAR) hCol, wCol = col.shape[1], col.shape[0] center = [int(hCol / 2), int(wCol / 2)] lowerH, upperH, lowerW, upperW = center[0] - 18, center[0] + 18, center[1] - 18, center[0] + 18 col = col[lowerH:upperH, lowerW:upperW] ################################ Internal division of a cell in 6x6 ######################### colMatrix = np.zeros((6, 6), dtype='float16') colRowGrids = np.array_split(col, 6, axis=0) # <<<<<<---------------- Splits each cell into 6 rows i = 0 for colRowGrid in colRowGrids: totalNzcValue = 36 colGrids = np.array_split(colRowGrid, 6, axis=1) # <<<<<<---------------- Splits each cell row into 6 smaller cells of size 6x6 j = 0 if totalNzcValue != 0: for colGrid in colGrids: nzc = np.count_nonzero(colGrid) colMatrix[i][j] = float(nzc / totalNzcValue) j += 1 i += 1 aggVal = np.round(np.sum(colMatrix * localKernel) / np.sum(localKernel), 4) allScore.append(aggVal) tempList.append(aggVal) blank = True for index in range(len(tempList)): if tempList[index] > thresholdForWhitePixels: blank = False reqString += str(index) if blank == True: reqString += '$' if reqString == '': if num == 9: reqString = '$$$$$$$$$' else: reqString = '$$' return reqString def image_thresholding(imageOriginal): imageOriginal = imageOriginal.copy() imageHSV = cv.cvtColor(imageOriginal, cv.COLOR_BGR2HSV) lBound = (0, 0, 135) uBound = (255, 255, 255) mask = cv.inRange(imageHSV, lBound, uBound) imageWithoutChannels = cv.bitwise_and(imageOriginal, imageOriginal, mask=mask) imageGray = cv.cvtColor(imageWithoutChannels, cv.COLOR_BGR2GRAY) _, imageThresh = cv.threshold(imageGray, 80, 255, cv.THRESH_BINARY_INV) return imageThresh for entry in os.scandir('/home/manish/Desktop/JhunAlignedWithBlob'): if entry.path.endswith('.jpg') and entry.is_file(): src = entry.path start = src.find('image')+5 end = src.find('.jpg') docId = src[start:end] imageOriginal = cv.imread(src, -1) imageThresh = image_thresholding(imageOriginal) imageSet = imageThresh[setCords[0]:setCords[1], setCords[2]:setCords[3]] imageStudent = imageThresh[studentCords[0]:studentCords[1], studentCords[2]:studentCords[3]] data = [docId, getIds(imageSet, 2), getIds(imageStudent, 9), getAnswerKeys(imageThresh)] df.loc[len(df.index)] = data lengi += 1 print(f'Done processing image {lengi}: {docId}') # if lengi == 1: # break # break # break # print(df.head()) df['set_id'] = df['set_id'].apply('="{}"'.format) df['student_id'] = df['student_id'].apply('="{}"'.format) df['answer_keys'] = df['answer_keys'].apply('="{}"'.format) df.to_csv('/home/manish/Desktop/bubble_processed3_V3.csv', index=False) print(f'Total time taken: {(time.time() - start_time) / float(60)} minutes.')
6,047
0
69
7e544ac2398c762a2eb06014b20d482e0428f1b8
3,848
py
Python
porosityMethods.py
mbandreeta/supervisionedPorosity
96a8cab628df19d173791729b34fa3ed6e55ed80
[ "MIT" ]
null
null
null
porosityMethods.py
mbandreeta/supervisionedPorosity
96a8cab628df19d173791729b34fa3ed6e55ed80
[ "MIT" ]
null
null
null
porosityMethods.py
mbandreeta/supervisionedPorosity
96a8cab628df19d173791729b34fa3ed6e55ed80
[ "MIT" ]
null
null
null
import skimage import tqdm import numpy as np from imageProcessing import *
35.962617
140
0.690229
import skimage import tqdm import numpy as np from imageProcessing import * def segmentSolidPhase(segmented,f,threshold): from scipy.ndimage import binary_dilation w=1; d = binary_dilation(segmented==1); d = d-((segmented==1)*1) positions = np.where(d>0); for idx in (range(positions[0].size)): [i,j,k] = [positions[0][idx],positions[1][idx],positions[2][idx]]; if f[i,j,k] >= threshold: segmented[i,j,k] = 1; def segmentVoidPhase(segmented,f,threshold): from scipy.ndimage import binary_dilation w=1; d = binary_dilation(segmented==0); d = d-((segmented==0)*1) positions = np.where(d>0); for idx in (range(positions[0].size)): [i,j,k] = [positions[0][idx],positions[1][idx],positions[2][idx]]; if f[i,j,k] <= threshold: segmented[i,j,k] = 0; def radiusMap(porosity_matrix,unit): from scipy.ndimage import median_filter macropores = (porosity_matrix==1)*1; intermediate = porosity_matrix.copy(); intermediate[macropores==1]=0; v = intermediate* (unit**3) *(3.0/(4.0*np.pi)); r_eq = np.cbrt(v) surface = (r_eq**2)*np.pi ; from scipy.ndimage.morphology import distance_transform_edt as bwt dt = bwt(macropores) map_radius = r_eq+ (dt*unit); aux = (dt<np.sqrt(2))*dt * (unit**2); surface_contact = aux*intermediate; map_surface = surface_contact+surface; return map_radius,map_surface; def interactiveCorrectionNaive(Esolid,Evoid,filtered,mask,porosity_estimated=0,tolerance=2): porosity=0; error = np.abs(porosity_estimated-porosity)*100.0/porosity_estimated; step=10; segmented = filtered.copy(); print("PorosityEntered","PorosityCalculated","LowThreshold","UpThreshold"," Error%") while(error>tolerance): segmented = filtered.copy();#filtered.copy(); segmented = ((segmented - Evoid)/(Esolid-Evoid)); segmented[filtered>=Esolid]=1; # solid region segmented[filtered<=Evoid]=0; porosity_matrix=(1-segmented)*mask; porosity = 100.0*(np.sum(porosity_matrix)/np.sum(mask)); nerror = np.abs(porosity_estimated-porosity)*100.0/porosity_estimated; if(nerror<error): error = nerror; else: step = step/2; error = nerror; print(" %5.1f %5.1f %5.2f %5.2f %5.1f" %(porosity_estimated,porosity,Evoid,Esolid,error)) if(porosity>porosity_estimated): Esolid=Esolid-step; else: Esolid=Esolid+step; print(" %5.1f %5.1f %5.2f %5.2f %5.1f" %(porosity_estimated,porosity,Evoid,Esolid,error)) return porosity_matrix; def run_porosity(img,resolution,porosity_estimated,resize=True,plot=False,pos=100): from scipy.ndimage import median_filter print("Applying filter."); # import SimpleITK as sitk # if(resize): # sitk_image = resample_image(sitk.GetImageFromArray(img)) # img = sitk.GetArrayFromImage(sitk_image); # resolution = resolution*2; filtered = histogram_normalization(img) filtered = median_filter(filtered,1); print("Creating mask."); mask,obs = createMask(filtered); print("Threshold Adjustment"); otsu01 = skimage.filters.threshold_otsu(filtered); aux = filtered.copy(); aux = aux[aux<otsu01]; y,x = skimage.exposure.histogram(aux); Evoid = np.argmax(y); #Evoid = 0; #skimage.filters.threshold_otsu(filtered); y,x = skimage.exposure.histogram(filtered[mask==1]); Esolid = np.argmax(y); #print(Esolid,Evoid) porosity_matrix = interactiveCorrectionNaive(Esolid,Evoid,filtered,mask,porosity_estimated) segmented =(1-porosity_matrix)*mask; #map_radius,map_surface = radiusMap(porosity_matrix,resolution) print("Average sample porosity:", np.sum(porosity_matrix)/np.sum(mask)) if(plot): showData(img,filtered,segmented,pos) #showDataColor(porosity_matrix,map_radius,map_surface,pos) return porosity_matrix,resolution
3,634
0
125
666da4bf7ea8cb6e53488d2bb095018500fea12d
354
py
Python
myUniversePython/analyser.py
saygindogu/universe
e7de1e897ab0d1d0551e0bd1d91c32ac670ae13a
[ "MIT" ]
null
null
null
myUniversePython/analyser.py
saygindogu/universe
e7de1e897ab0d1d0551e0bd1d91c32ac670ae13a
[ "MIT" ]
null
null
null
myUniversePython/analyser.py
saygindogu/universe
e7de1e897ab0d1d0551e0bd1d91c32ac670ae13a
[ "MIT" ]
null
null
null
# Import the necessary packages and modules import matplotlib.pyplot as plt import numpy as np f = open('history.txt', 'r') for line in f: if line.startswith('='): tokens = line.split('\t') # Prepare the data x = np.linspace(0, 10, 100) # Plot the data plt.plot(x, x, label='linear') # Add a legend plt.legend() # Show the plot plt.show()
15.391304
43
0.663842
# Import the necessary packages and modules import matplotlib.pyplot as plt import numpy as np f = open('history.txt', 'r') for line in f: if line.startswith('='): tokens = line.split('\t') # Prepare the data x = np.linspace(0, 10, 100) # Plot the data plt.plot(x, x, label='linear') # Add a legend plt.legend() # Show the plot plt.show()
0
0
0
17fd905bf344238092df2c2454e797b7c916eb09
4,612
py
Python
remix_bot/slap_msgs.py
uhwot/telegram-remix-bo
6ae9b7ff6cf758454d668784050f036d8d63627b
[ "MIT" ]
null
null
null
remix_bot/slap_msgs.py
uhwot/telegram-remix-bo
6ae9b7ff6cf758454d668784050f036d8d63627b
[ "MIT" ]
1
2020-10-22T19:14:32.000Z
2020-10-28T08:46:20.000Z
remix_bot/slap_msgs.py
uhwot/telegram-remix-bot
6ae9b7ff6cf758454d668784050f036d8d63627b
[ "MIT" ]
null
null
null
SLAP_TEMPLATES = ( "{user1} {hits} {user2} with a {item}.", "{user1} {hits} {user2} in the face with a {item}.", "{user1} {hits} {user2} around a bit with a {item}.", "{user1} {throws} a {item} at {user2}.", "{user1} grabs a {item} and {throws} it at {user2}'s face.", "{user1} launches a {item} in {user2}'s general direction.", "{user1} starts slapping {user2} silly with a {item}.", "{user1} pins {user2} down and repeatedly {hits} them with a {item}.", "{user1} grabs up a {item} and {hits} {user2} with it.", "{user1} ties {user2} to a chair and {throws} a {item} at them.", "{user1} gave a friendly push to help {user2} learn to swim in lava.", "{user1} {hits} {user2} with a diamond sword.", "{user1} used Splash! But nothing happened...", ) SLAP_SELF = ( "{user1} {hits} themselves with a {item} in their confusion!", "{user1} {hits} themselves in the face with a {item}... what an idiot.", "{user1} {hits} themselves around a bit with a {item}... but why?", "{user1} hits their head against a wall... for some reason.", "{user1} launches themselves into space without a spacesuit... because they thought there was oxygen.", "{user1} {hits} themselves with a {item} after looking at Windows 8's UI. They lost all hope of humanity.", "{user1} is confused. They hurt themselves in their confusion.", ) SLAP_BASIC = ( "{user1} was squished too much.", "{user1} fell from a high place.", "{user1} suffocated in a wall.", "{user1} was struck by lightning.", "{user1} was squished by a falling anvil.", ) ITEMS = ( "cast iron skillet", "large trout", "baseball bat", "cricket bat", "wooden cane", "dildo", "printer", "shovel", "CRT monitor", "physics textbook", "toaster", "portrait of Richard Stallman", "television", "five ton truck", "roll of duct tape", "book", "laptop", "old television", "sack of rocks", "rainbow trout", "rubber chicken", "spiked bat", "fire extinguisher", "heavy rock", "block of dirt", "beehive", "piece of rotten meat", "bear", "ton of bricks", ) THROW = ("throws", "flings", "chucks", "hurls") HIT = ("hits", "whacks", "slaps", "smacks", "bashes") RUN_STRINGS = ( "Where do you think you're going?", "Huh? what? did they get away?", "ZZzzZZzz... Huh? what? oh, just them again, nevermind.", "Get back here!", "Not so fast...", "Look out for the wall!", "Don't leave me alone with them!!", "You run, you die.", "Jokes on you, I'm everywhere", "You're gonna regret that...", "You could also try /kickme, I hear that's fun.", "Go bother someone else, no-one here cares.", "You can run, but you can't hide.", "Is that all you've got?", "I'm behind you...", "You've got company!", "We can do this the easy way, or the hard way.", "You just don't get it, do you?", "Yeah, you better run!", "Please, remind me how much I care?", "I'd run faster if I were you.", "That's definitely the droid we're looking for.", "May the odds be ever in your favour.", "Famous last words.", "And they disappeared forever, never to be seen again.", '"Oh, look at me! I\'m so cool, I can run from a bot!" - this person', "Yeah yeah, just tap /kickme already.", "Here, take this ring and head to Mordor while you're at it.", "Legend has it, they're still running...", "Unlike Harry Potter, your parents can't protect you from me.", "Fear leads to anger. Anger leads to hate. Hate leads to suffering. If you keep running in fear, you might " "be the next Vader.", "Multiple calculations later, I have decided my interest in your shenanigans is exactly 0.", "Legend has it, they're still running.", "Keep it up, not sure we want you here anyway.", "You're a wiza- Oh. Wait. You're not Harry, keep moving.", "NO RUNNING IN THE HALLWAYS!", "Hasta la vista, baby.", "Who let the dogs out?", "It's funny, because no one cares.", "Ah, what a waste. I liked that one.", "Frankly, my dear, I don't give a damn.", "My milkshake brings all the boys to yard... So run faster!", "You can't HANDLE the truth!", "A long time ago, in a galaxy far far away... Someone would've cared about that. Not anymore though.", "Hey, look at them! They're running from the inevitable banhammer... Cute.", "Han shot first. So will I.", "What are you running after, a white rabbit?", "As The Doctor would say... RUN!", )
37.803279
112
0.614918
SLAP_TEMPLATES = ( "{user1} {hits} {user2} with a {item}.", "{user1} {hits} {user2} in the face with a {item}.", "{user1} {hits} {user2} around a bit with a {item}.", "{user1} {throws} a {item} at {user2}.", "{user1} grabs a {item} and {throws} it at {user2}'s face.", "{user1} launches a {item} in {user2}'s general direction.", "{user1} starts slapping {user2} silly with a {item}.", "{user1} pins {user2} down and repeatedly {hits} them with a {item}.", "{user1} grabs up a {item} and {hits} {user2} with it.", "{user1} ties {user2} to a chair and {throws} a {item} at them.", "{user1} gave a friendly push to help {user2} learn to swim in lava.", "{user1} {hits} {user2} with a diamond sword.", "{user1} used Splash! But nothing happened...", ) SLAP_SELF = ( "{user1} {hits} themselves with a {item} in their confusion!", "{user1} {hits} themselves in the face with a {item}... what an idiot.", "{user1} {hits} themselves around a bit with a {item}... but why?", "{user1} hits their head against a wall... for some reason.", "{user1} launches themselves into space without a spacesuit... because they thought there was oxygen.", "{user1} {hits} themselves with a {item} after looking at Windows 8's UI. They lost all hope of humanity.", "{user1} is confused. They hurt themselves in their confusion.", ) SLAP_BASIC = ( "{user1} was squished too much.", "{user1} fell from a high place.", "{user1} suffocated in a wall.", "{user1} was struck by lightning.", "{user1} was squished by a falling anvil.", ) ITEMS = ( "cast iron skillet", "large trout", "baseball bat", "cricket bat", "wooden cane", "dildo", "printer", "shovel", "CRT monitor", "physics textbook", "toaster", "portrait of Richard Stallman", "television", "five ton truck", "roll of duct tape", "book", "laptop", "old television", "sack of rocks", "rainbow trout", "rubber chicken", "spiked bat", "fire extinguisher", "heavy rock", "block of dirt", "beehive", "piece of rotten meat", "bear", "ton of bricks", ) THROW = ("throws", "flings", "chucks", "hurls") HIT = ("hits", "whacks", "slaps", "smacks", "bashes") RUN_STRINGS = ( "Where do you think you're going?", "Huh? what? did they get away?", "ZZzzZZzz... Huh? what? oh, just them again, nevermind.", "Get back here!", "Not so fast...", "Look out for the wall!", "Don't leave me alone with them!!", "You run, you die.", "Jokes on you, I'm everywhere", "You're gonna regret that...", "You could also try /kickme, I hear that's fun.", "Go bother someone else, no-one here cares.", "You can run, but you can't hide.", "Is that all you've got?", "I'm behind you...", "You've got company!", "We can do this the easy way, or the hard way.", "You just don't get it, do you?", "Yeah, you better run!", "Please, remind me how much I care?", "I'd run faster if I were you.", "That's definitely the droid we're looking for.", "May the odds be ever in your favour.", "Famous last words.", "And they disappeared forever, never to be seen again.", '"Oh, look at me! I\'m so cool, I can run from a bot!" - this person', "Yeah yeah, just tap /kickme already.", "Here, take this ring and head to Mordor while you're at it.", "Legend has it, they're still running...", "Unlike Harry Potter, your parents can't protect you from me.", "Fear leads to anger. Anger leads to hate. Hate leads to suffering. If you keep running in fear, you might " "be the next Vader.", "Multiple calculations later, I have decided my interest in your shenanigans is exactly 0.", "Legend has it, they're still running.", "Keep it up, not sure we want you here anyway.", "You're a wiza- Oh. Wait. You're not Harry, keep moving.", "NO RUNNING IN THE HALLWAYS!", "Hasta la vista, baby.", "Who let the dogs out?", "It's funny, because no one cares.", "Ah, what a waste. I liked that one.", "Frankly, my dear, I don't give a damn.", "My milkshake brings all the boys to yard... So run faster!", "You can't HANDLE the truth!", "A long time ago, in a galaxy far far away... Someone would've cared about that. Not anymore though.", "Hey, look at them! They're running from the inevitable banhammer... Cute.", "Han shot first. So will I.", "What are you running after, a white rabbit?", "As The Doctor would say... RUN!", )
0
0
0
0c7093ad3dc6e521bebc114441fff78b91e63857
14,175
py
Python
OrchardWatch-ML/growth_model/server.py
david-fisher/320-F19-Track-I
cddff29ad9f79a794928eb29d44bc9f53f46f3fd
[ "BSD-3-Clause" ]
8
2019-09-04T14:18:30.000Z
2020-02-04T18:06:50.000Z
OrchardWatch-ML/growth_model/server.py
david-fisher/320-F19-Track-I
cddff29ad9f79a794928eb29d44bc9f53f46f3fd
[ "BSD-3-Clause" ]
103
2019-09-19T18:15:25.000Z
2020-05-05T01:39:40.000Z
OrchardWatch-ML/growth_model/server.py
david-fisher/320-F19-Track-I
cddff29ad9f79a794928eb29d44bc9f53f46f3fd
[ "BSD-3-Clause" ]
2
2020-01-17T18:46:46.000Z
2020-05-04T15:53:34.000Z
import os import argparse from flask import request from flask_api import FlaskAPI, status, exceptions from werkzeug.utils import secure_filename import io import numpy as np from PIL import Image import cv2 from datetime import datetime import re import math import apriltag from flask_cors import CORS from logzero import logger import boto3 DB_CLUSTER = "database320" DB_NAME = "db320" ARN = "arn:aws:rds:us-east-2:007372221023:cluster:database320" SECRET_ARN = "arn:aws:secretsmanager:us-east-2:007372221023:secret:rds-db-credentials/cluster-BZEL6PSDLGVBVJB6BIDZGZQ4MI/admin320-fsoCse" REGION_NAME = "us-east-2" IMG_FORMAT = ".jpg" # changing this is not handled very gracefully at the moment, probably UPLOAD_FOLDER = "/temp/uploads" ALLOWED_EXTENSIONS = {"png", "jpg", "jpeg"} def ret(error_message=None, **kwargs): """ Make return JSON object :param error_message: sets "error" field to given message string :param kwargs: fields to set on the return JSON """ r = {} if error_message is not None: r["error"] = error_message r.update(kwargs) return r # Params: l1 and l2 are color image matrices # Returns: 1 if aligned, 0 otherwise, -1 on error def get_matching_s3_objects( s3, bucket, prefix="", suffix="", max_keys_per_request=100, ): """ List objects in an S3 bucket. :param s3: boto.client("s3") client :param bucket: Name of the S3 bucket. :param prefix: Only fetch objects whose key starts with this prefix (optional). :param suffix: Only fetch objects whose keys end with this suffix (optional). :param max_keys_per_request: number of objects to list down """ kwargs = {"Bucket": bucket} # If the prefix is a single string (not a tuple of strings), we can # do the filtering directly in the S3 API. if isinstance(prefix, str): kwargs["Prefix"] = prefix else: kwargs["Prefix"] = str(prefix) kwargs["MaxKeys"] = max_keys_per_request while True: # The S3 API response is a large blob of metadata. # 'Contents' contains information about the listed objects. resp = s3.list_objects_v2(**kwargs) try: contents = resp["Contents"] except KeyError: return for obj in contents: key = obj["Key"] if key.startswith(prefix) and key.endswith(suffix): yield obj # The S3 API is paginated, returning up to 1000 keys at a time. # Pass the continuation token into the next response, until we # reach the final page (when this field is missing). try: kwargs["ContinuationToken"] = resp["NextContinuationToken"] except KeyError: break if __name__ == "__main__": parser = argparse.ArgumentParser() parser.add_argument("-p", "--port", action="store", default="8000") args = parser.parse_args() port = int(args.port) app = create_app() app.run(host="0.0.0.0", port=port)
35.977157
216
0.634215
import os import argparse from flask import request from flask_api import FlaskAPI, status, exceptions from werkzeug.utils import secure_filename import io import numpy as np from PIL import Image import cv2 from datetime import datetime import re import math import apriltag from flask_cors import CORS from logzero import logger import boto3 DB_CLUSTER = "database320" DB_NAME = "db320" ARN = "arn:aws:rds:us-east-2:007372221023:cluster:database320" SECRET_ARN = "arn:aws:secretsmanager:us-east-2:007372221023:secret:rds-db-credentials/cluster-BZEL6PSDLGVBVJB6BIDZGZQ4MI/admin320-fsoCse" REGION_NAME = "us-east-2" IMG_FORMAT = ".jpg" # changing this is not handled very gracefully at the moment, probably UPLOAD_FOLDER = "/temp/uploads" ALLOWED_EXTENSIONS = {"png", "jpg", "jpeg"} def allowed_file(filename): return "." in filename and filename.rsplit(".", 1)[1].lower() in ALLOWED_EXTENSIONS def create_app(config=None): app = FlaskAPI(__name__) app.config.update(dict(DEBUG=False)) app.config.update(config or {}) CORS(app) @app.route("/tree", methods=["POST"]) def get_num_clusters(): logger.warning("POST /tree") image = request.files["image"] return "", status.HTTP_501_NOT_IMPLEMENTED @app.route("/cluster", methods=["POST"]) @app.route("/cluster/<int:cluster_num>", methods=["POST"]) def label_apples(cluster_num=None): logger.info("POST /cluster/{}".format(cluster_num if cluster_num is not None else "")) if "cluster_img" not in request.files: logger.error("missing_cluster_img") return ret(error_message="missing_cluster_img"), status.HTTP_400_BAD_REQUEST input_image = request.files["cluster_img"] if input_image and allowed_file(input_image.filename): filename = secure_filename(input_image.filename) os.makedirs(UPLOAD_FOLDER, exist_ok=True) filename = os.path.join(UPLOAD_FOLDER, filename) input_image.save(filename) else: logger.error("invalid_cluster_img") return ret(error_message="invalid_cluster_img"), status.HTTP_400_BAD_REQUEST # input_image = np.fromstring(input_image.read(), np.uint8) # decode image input_image = cv2.imread(filename) os.remove(filename) # input_image = cv2.cvtColor(input_image, cv2.COLOR_BGR2RGB) s3 = boto3.client("s3", region_name=REGION_NAME) # STEP 1: Check if cluster_num is valid if cluster_num is not None: if not is_valid_cluster_num(cluster_num): logger.error("invalid_cluster_img") return ret(error_message="invalid_cluster_num"), status.HTTP_400_BAD_REQUEST # STEP 2: ALIGNMENT CHECK # get most recent img from /clusters/cluster_num most_recent_image = get_last_picture(s3, cluster_num) if most_recent_image is not None: aligned = check_alignment(input_image, most_recent_image) else: # TODO: check for good tag positioning aligned = 1 if aligned == -1: logger.error("error, tag not present in input img") return ret(error_message="no_tag"), status.HTTP_400_BAD_REQUEST elif aligned == 0: logger.error("input image not aligned") return ret(error_message="not_aligned"), status.HTTP_400_BAD_REQUEST else: logger.info("successfully aligned") else: tag = detect_tag(input_image) if not tag: # just check if the tag is there logger.error("error, tag not present in input img") return ret(error_message="no_tag"), status.HTTP_400_BAD_REQUEST # rds = boto3.client("rds-data", region_name=REGION_NAME) # cluster_ids = rds.execute_statement( # secretArn=SECRET_ARN, # database=DB_NAME, # resourceArn=ARN, # sql="SELECT cluster_id FROM Cluster", # ) # print(cluster_ids) # TODO: Do this as above, via database # This is really gross and inefficient, and I apologize. See above comment. existing_clusters = list( get_matching_s3_objects(s3, "orchardwatchphotos", prefix="clusters") ) if existing_clusters: get_cluster_id = lambda key: int(re.findall("clusters/(\d*)/", key)[0]) highest_cluster = sorted(existing_clusters, key=lambda o: get_cluster_id(o["Key"]))[-1] highest_cluster_id = get_cluster_id(highest_cluster["Key"]) else: highest_cluster_id = 0 cluster_num = int(highest_cluster_id) + 1 # No race conditions here, no sir. # STEP 3: if alignment check result == 1: name picture to 'cluster_num_date_time' date = datetime.date(datetime.now()) time = datetime.time(datetime.now()) key = str(date) + "_" + str(time) + IMG_FORMAT # STEP 4: send to S3 to be stored in /clusters/cluster_num store_in_s3(s3, input_image, cluster_num, key) # TODO: Measure the apple, and appropriately store the data in DB # Get the measurements for the apple # measurements = measure_image(input_image, most_recent_image) # num_apples = len(measurements) # Instantiate an rds # rds = boto3.client("rds-data", region_name=REGION_NAME) # Create a ClusterImage record # time = time[:8] # time_stamp = str(date) + " " + str(time) # file_url = key # sql_parameters = [ # {'name':'cluster_id', 'value':{'varchar': str(cluster_num)}}, # {'name':'time_stamp', 'value':{'timestamp': time_stamp}}, # {'name':'file_url', 'value':{'varchar': file_url}}, # ] # rds.execute_statement( # secretArn=SECRET_ARN, # database=DB_NAME, # resourceArn=ARN, # sql="INSERT INTO ClusterImage (cluster_id, time_stamp, file_url) VALUES (:cluster_id, :time_stamp, :file_url)", # parameters=sql_parameters # ) # Get cluster_image_id # sql_parameters = [ # {'name':'cluster_id', 'value':{'varchar': str(cluster_num)}}, # {'name':'time_stamp', 'value':{'timestamp': time_stamp}}, # ] # cluster_image_id = int(rds.execute_statement( # secretArn=SECRET_ARN, # database=DB_NAME, # resourceArn=ARN, # sql="SELECT cluster_image_id FROM ClusterImage WHERE cluster_id = :cluster_id AND time_stamp=:time_stamp", # parameters=sql_parameters # )) # Create a ClusterDataPoint record # TODO: Figure out how to handle the rest of the data in the schema that is not provided during image upload # TODO: Get all assumptions cleared up # Create a FruitDataPoint per fruitlet # Assume fruit_id to be the index of the measurement # Assume model_id to be 0 # stem_color = 'green' # for fruit_id in range(num_apples): # sql_parameters = [ # {'name':'fruit_id', 'value':{'varchar': str(cluster_num)}}, # {'name':'cluster_image_id', 'value':{'cluster_image_id': cluster_image_id}}, # {'name':'model_id', 'value':{'model_id': 0}}, # {'name':'time_stamp', 'value':{'timestamp': time_stamp}}, # {'name':'measurement', 'value':{'measurement': measurements[fruit_id]}}, # {'name':'stem_color', 'value':{'stem_color': stem_color}}, # ] # rds.execute_statement( # secretArn=SECRET_ARN, # database=DB_NAME, # resourceArn=ARN, # sql="INSERT INTO FruitDataPoint (fruit_id, cluster_image_id, model_id, time_stamp, measurement, stem_color) VALUES (:fruit_id, :cluster_image_id, :model_id, :time_stamp, :measurement, :stem_color)", # parameters=sql_parameters # ) logger.info("Success!") return ret(cluster_num=cluster_num), status.HTTP_201_CREATED if cluster_num is None else status.HTTP_200_OK # technically this can be consolidated into label_apples, but # I put it separately for readability @app.route("/cluster/<int:cluster_num>", methods=["GET"]) def get_cluster_data(cluster_num): logger.info("GET /cluster/{}".format(cluster_num)) # well, get the data. return "", status.HTTP_501_NOT_IMPLEMENTED @app.route("/", methods=["GET"]) def hello(): return "Hi from the server!", status.HTTP_200_OK return app def ret(error_message=None, **kwargs): """ Make return JSON object :param error_message: sets "error" field to given message string :param kwargs: fields to set on the return JSON """ r = {} if error_message is not None: r["error"] = error_message r.update(kwargs) return r def measure_image(input_image, most_recent_image): # Returns: list of doubles corresponding to relative growth rate per apple return dummy_measurement() def dummy_measurement(): return [5.2, 3.1, 2.5] def is_valid_cluster_num(cluster_num): N_VALID_CLUSTERS = 10000 # checks input to see if cluster_num is valid return isinstance(cluster_num, int) and 0 < cluster_num <= N_VALID_CLUSTERS def make_s3_cluster_name(cluster_num): bucket_name = "orchardwatchphotos" folder_key = "clusters/{}".format(cluster_num) return bucket_name, folder_key def make_s3_datapoint_name(cluster_num, subkey): bucket_name, folder_key = make_s3_cluster_name(cluster_num) folder_key += "/" + str(subkey) return bucket_name, folder_key def get_last_picture(s3, cluster_num): bucket_name, folder_key = make_s3_cluster_name(cluster_num) cluster_photos = list(get_matching_s3_objects(s3, bucket_name, prefix=folder_key)) if not cluster_photos: return None s = boto3.resource("s3") latest = sorted(cluster_photos, key=lambda o: o["Key"])[-1] data = s.Object(bucket_name, latest["Key"]).get()["Body"].read() img = Image.open(io.BytesIO(data)) img = np.asarray(img) # buffer = BytesIO() # s3.download_fileobj(bucket_name, key, buffer) # buffer.seek(0) return img def store_in_s3(s3, image, cluster_num, subkey): # store image in correct folder in s3 bucket_name, key = make_s3_datapoint_name(cluster_num, subkey) bin_img = io.BytesIO(cv2.imencode(IMG_FORMAT, image)[1].tobytes()) s3.upload_fileobj(bin_img, bucket_name, key) def compute_homography_distance(m1, m2): diffs = [] result = 0 for i in range(len(m1)): for j in range(len(m1[i])): diffs.append(m1[i][j] - m2[i][j]) for d in diffs: result = result + math.pow(d, 2) result = math.sqrt(result) return result def detect_tag(image): img_bw = cv2.cvtColor(image, cv2.COLOR_RGB2GRAY) # convert to grayscale for apriltag library (thresh, img_bw) = cv2.threshold( img_bw, 128, 255, cv2.THRESH_BINARY | cv2.THRESH_OTSU ) # threshold detector = apriltag.Detector() tag_info = detector.detect(img_bw) return tag_info # Params: l1 and l2 are color image matrices # Returns: 1 if aligned, 0 otherwise, -1 on error def check_alignment(l1, l2): # Threshold for alignment # VVV MAKE THIS NUMBER LARGER IF YOU NEED TO FAKE IT FOR THE DEMO sim_thresh = 1 # # Read in image (l1 and l2 will most likely be paths leading to images loaded # # application and S3 bucket) # img1 = cv2.imread(l1, cv2.IMREAD_COLOR) # img2 = cv2.imread(l2, cv2.IMREAD_COLOR) # Convert to RGB # img1 = cv2.cvtColor(img1, cv2.COLOR_BGR2RGB) # img2 = cv2.cvtColor(img1, cv2.COLOR_BGR2RGB) img1 = l1 img2 = l2 r_1 = detect_tag(img1) r_2 = detect_tag(img2) # Ensure an AprilTag can be detected if not r_1 or not r_2: return -1 # Check similarity by checking threshold metric = compute_homography_distance(r_1[0].homography, r_2[0].homography) if metric <= sim_thresh: return 1 else: return 0 def get_matching_s3_objects( s3, bucket, prefix="", suffix="", max_keys_per_request=100, ): """ List objects in an S3 bucket. :param s3: boto.client("s3") client :param bucket: Name of the S3 bucket. :param prefix: Only fetch objects whose key starts with this prefix (optional). :param suffix: Only fetch objects whose keys end with this suffix (optional). :param max_keys_per_request: number of objects to list down """ kwargs = {"Bucket": bucket} # If the prefix is a single string (not a tuple of strings), we can # do the filtering directly in the S3 API. if isinstance(prefix, str): kwargs["Prefix"] = prefix else: kwargs["Prefix"] = str(prefix) kwargs["MaxKeys"] = max_keys_per_request while True: # The S3 API response is a large blob of metadata. # 'Contents' contains information about the listed objects. resp = s3.list_objects_v2(**kwargs) try: contents = resp["Contents"] except KeyError: return for obj in contents: key = obj["Key"] if key.startswith(prefix) and key.endswith(suffix): yield obj # The S3 API is paginated, returning up to 1000 keys at a time. # Pass the continuation token into the next response, until we # reach the final page (when this field is missing). try: kwargs["ContinuationToken"] = resp["NextContinuationToken"] except KeyError: break if __name__ == "__main__": parser = argparse.ArgumentParser() parser.add_argument("-p", "--port", action="store", default="8000") args = parser.parse_args() port = int(args.port) app = create_app() app.run(host="0.0.0.0", port=port)
10,871
0
275
202920f8de2be9a2ad13e317799f56b62fff1ef6
10,034
py
Python
program.py
kokuraxc/lift_simulation
7ef7a292ccb19fbe3b1146240df4a0cdeef46fad
[ "MIT" ]
null
null
null
program.py
kokuraxc/lift_simulation
7ef7a292ccb19fbe3b1146240df4a0cdeef46fad
[ "MIT" ]
null
null
null
program.py
kokuraxc/lift_simulation
7ef7a292ccb19fbe3b1146240df4a0cdeef46fad
[ "MIT" ]
null
null
null
import threading import time import logging import math class Cart: """ need to implement the move method with threading so that it won't interfere with other functions """ # the original implmentation, with the bug. # get all the passengers who want to go the "direction" if __name__ == '__main__': stop_threads = False planner = Planner(5, 1) """ while True: try: lvl_from = int(input()) lvl_to = int(input()) except: planner.stopAll() break Person(lvl_from, lvl_to, planner) """ time.sleep(1) Person(3, 4, planner) time.sleep(1) Person(2, 0, planner)
46.669767
219
0.632749
import threading import time import logging import math class Planner: def __init__(self, total_storeys, total_carts_number): self.levels = [Level(i) for i in range(total_storeys)] self.carts = [Cart(i, self) for i in range(total_carts_number)] def passenger_calls_cart(self, level, direction): # TODO turn the light on this level on self.levels[level].direction_indicator[direction] = True # TODO call the cart to come # This part is the most import logic part # it decides which cart to send to the Level if there are more than one cart # for now, assume there is only one cart # pass the planner object to cart method self.carts[0].call_to_level(level, direction) pass def stopAll(self): for c in self.carts: c.stop() class Cart: """ need to implement the move method with threading so that it won't interfere with other functions """ def __init__(self, index, planner): self.id = index self.planner = planner self.max_capacity = 15 self.speed = 0.1 # randomly choose this speed, doesn't necessarily reflect actual speed self.moving_direction = 0 # 1: upwards, -1: downwards, 0: rest self.current_location = 0 self.pressed_levels = [] # levels pressed by passengers on board self.calling_levels = [] # levels passed from the planner self.passengers = [] self.cur_destination = None # start moving the cart when it's initialized # of course, it will remain at the same place if there is no passengers self.stop_thread = False self.running_thread = threading.Thread(target=self.move) self.running_thread.start() def call_to_level(self, level, direction): if (level, direction) not in self.calling_levels: self.calling_levels.append((level, direction)) def stop(self): self.stop_thread = True def move(self): while True: if self.stop_thread: break time.sleep(self.speed) self.current_location += self.speed * self.moving_direction # fix the float number not precise to 0.1 error if abs(self.current_location - math.ceil(self.current_location)) < 0.05: self.current_location = math.ceil(self.current_location) elif abs(self.current_location - math.floor(self.current_location)) < 0.05: self.current_location = math.floor(self.current_location) # skip it when the cart is in between levels if self.current_location % 1 != 0: continue # passengers get out self.passengers = [p for p in self.passengers if p.destination_level != self.current_location] # first check if reached cur_destination if self.cur_destination != None and self.current_location == self.cur_destination: if self.cur_destination = None # the original implmentation, with the bug. def move2(self): while True: if self.stop_thread: break time.sleep(self.speed) self.current_location += self.speed * self.moving_direction # fix the float number not precise to 0.1 error if abs(self.current_location - math.ceil(self.current_location)) < 0.05: self.current_location = math.ceil(self.current_location) elif abs(self.current_location - math.floor(self.current_location)) < 0.05: self.current_location = math.floor(self.current_location) if self.current_location in self.pressed_levels or self.current_location in self.calling_levels: print('^^^^ pressed levels:', self.pressed_levels, 'calling levels:', self.calling_levels) if self.moving_direction != 0: print('######') print('current direction:', self.moving_direction, '; current location:', self.current_location) # passengers get out if self.current_location in self.pressed_levels: print('at level', self.current_location) print('before passengers get OUT, passenger count:', len(self.passengers)) self.passengers = [p for p in self.passengers if p.destination_level != self.current_location] print('after passengers get OUT, passenger count:', len(self.passengers)) self.pressed_levels.remove(self.current_location) # passengers get in # cart is not moving if self.current_location in self.calling_levels and len(self.passengers) == 0 and self.moving_direction == 0: new_passengers = self.planner.levels[self.current_location].get_passengers(1) # upwards _direction = 1 if len(new_passengers) == 0: new_passengers = self.planner.levels[self.current_location].get_passengers(-1) # downwards _direction = -1 if len(new_passengers) > 0: for p in new_passengers: p.press_button_destination(self) print('before passengers going', _direction, 'get IN, passenger count:', len(self.passengers)) self.passengers += new_passengers print('after passengers going', _direction, 'get IN, passenger count:', len(self.passengers)) self.planner.levels[self.current_location].direction_indicator[_direction] = False # passengers get in # original direction # cart is moving elif self.current_location in self.calling_levels: new_passengers = self.planner.levels[self.current_location].get_passengers(self.moving_direction) for p in new_passengers: p.press_button_destination(self) print('before passengers going', self.moving_direction, 'get IN, passenger count:', len(self.passengers)) self.passengers += new_passengers print('after passengers going', self.moving_direction, 'get IN, passenger count:', len(self.passengers)) self.planner.levels[self.current_location].direction_indicator[self.moving_direction] = False # passengers get in # original direction # after all other passengers get out if self.current_location in self.calling_levels and len(self.passengers) == 0 and self.moving_direction != 0: self.moving_direction = -self.moving_direction new_passengers = self.planner.levels[self.current_location].get_passengers(self.moving_direction) for p in new_passengers: p.press_button_destination(self) print('before passengers going', self.moving_direction, 'get IN, passenger count:', len(self.passengers)) self.passengers += new_passengers print('after passengers going', self.moving_direction, 'get IN, passenger count:', len(self.passengers)) self.planner.levels[self.current_location].direction_indicator[self.moving_direction] = False if self.current_location in self.calling_levels and self.planner.levels[self.current_location].direction_indicator[1] == False and self.planner.levels[self.current_location].direction_indicator[-1] == False: self.calling_levels.remove(self.current_location) # decide whether to move upwards or downwards all_levels = self.pressed_levels + self.calling_levels all_levels.sort() if len(all_levels) > 0: if self.moving_direction == 1 and self.current_location < all_levels[-1]: pass # keep the same direction: upwards else: self.moving_direction = -1 if self.moving_direction == -1 and self.current_location > all_levels[0]: pass # keep the same direction: downwards else: self.moving_direction = 1 else: self.moving_direction = 0 class Level: def __init__(self, position): self.position = position # direction UP: 1, DOWN: -1; 0 is undefined self.queues = [None, [], []] # index 1: upwards; index -1: downwards; index 0: undefined self.direction_indicator = [None, False, False] def person_come(self, person, direction): self.queues[direction].append(person) # get all the passengers who want to go the "direction" def get_passengers(self, direction): ret = self.queues[direction] self.queues[direction] = [] return ret class Person: def __init__(self, start_level, destination_level, planner): self.start_level = start_level self.destination_level = destination_level self.direction = 1 if destination_level - start_level > 0 else -1 self.planner = planner self.planner.levels[start_level].person_come(self, self.direction) print('New Passenger from', start_level, 'to', destination_level) self.press_button_call_cart() def press_button_call_cart(self): self.planner.passenger_calls_cart(self.start_level, self.direction) def press_button_destination(self, cart): if self.destination_level not in cart.pressed_levels and self.destination_level != cart.current_location: cart.pressed_levels.append(self.destination_level) if __name__ == '__main__': stop_threads = False planner = Planner(5, 1) """ while True: try: lvl_from = int(input()) lvl_to = int(input()) except: planner.stopAll() break Person(lvl_from, lvl_to, planner) """ time.sleep(1) Person(3, 4, planner) time.sleep(1) Person(2, 0, planner)
8,938
-24
441
060754a0900fca850d2f4210065f69b20f828318
1,010
py
Python
PEH_COURSE_NOTES/02_ethical_python/pyport.py
dustin-py/info_sec_notes
c793aa3c837d428d240ce9a97d151541ecf5b825
[ "MIT" ]
1
2020-09-17T05:40:15.000Z
2020-09-17T05:40:15.000Z
PEH_COURSE_NOTES/02_ethical_python/pyport.py
dustin-py/info_sec_notes
c793aa3c837d428d240ce9a97d151541ecf5b825
[ "MIT" ]
null
null
null
PEH_COURSE_NOTES/02_ethical_python/pyport.py
dustin-py/info_sec_notes
c793aa3c837d428d240ce9a97d151541ecf5b825
[ "MIT" ]
2
2020-09-10T01:42:13.000Z
2020-09-14T16:56:30.000Z
#!/bin/python3 """This is a very simple/terrible port scanner for educational purpose""" import sys import socket from datetime import datetime if len(sys.argv) == 2: target = socket.gethostbyname(sys.argv[1]) # translate hostname else: print("Invalid amount of arguments.") print("Syntax: python3 pyport.py <ip>") print("-" * 50) print("Scanning target "+ target) print("Time started: " + str(datetime.now())) print("-" * 50) try: for port in range(50, 85): s = socket.socket(socket.AF_INET, socket.SOCK_STREAM) socket.setdefaulttimeout(1) result = s.connect_ex((target,port)) # returns error indicator if result == 0: print("Port {} is open".format(port)) s.close() except KeyboardInterrupt: print("\nExiting program.") sys.exit() except socket.gaierror: print("Hostname could not be resolved.") sys.exit() except socket.error: print("Could not connect to server.") sys.exit() # command: # python3 scanner.py <ip>
28.055556
73
0.661386
#!/bin/python3 """This is a very simple/terrible port scanner for educational purpose""" import sys import socket from datetime import datetime if len(sys.argv) == 2: target = socket.gethostbyname(sys.argv[1]) # translate hostname else: print("Invalid amount of arguments.") print("Syntax: python3 pyport.py <ip>") print("-" * 50) print("Scanning target "+ target) print("Time started: " + str(datetime.now())) print("-" * 50) try: for port in range(50, 85): s = socket.socket(socket.AF_INET, socket.SOCK_STREAM) socket.setdefaulttimeout(1) result = s.connect_ex((target,port)) # returns error indicator if result == 0: print("Port {} is open".format(port)) s.close() except KeyboardInterrupt: print("\nExiting program.") sys.exit() except socket.gaierror: print("Hostname could not be resolved.") sys.exit() except socket.error: print("Could not connect to server.") sys.exit() # command: # python3 scanner.py <ip>
0
0
0
1022b74220051619e3fbc2df75398be21afd784a
705
py
Python
python/45_bitmap/bitmap.py
shipan3452/algo
0494cc0d8f5daf108daf4358c4531a29279dd380
[ "Apache-2.0" ]
22,028
2018-09-27T05:55:19.000Z
2022-03-30T10:44:46.000Z
python/45_bitmap/bitmap.py
wangjing013/algo
b2c1228ff915287ad7ebeae4355fa26854ea1557
[ "Apache-2.0" ]
164
2018-10-06T15:11:08.000Z
2022-03-28T10:04:34.000Z
python/45_bitmap/bitmap.py
wangjing013/algo
b2c1228ff915287ad7ebeae4355fa26854ea1557
[ "Apache-2.0" ]
7,250
2018-09-30T00:45:25.000Z
2022-03-31T20:15:33.000Z
""" Author: Wenru Dong """ from typing import Optional if __name__ == "__main__": bitmap = Bitmap(10) bitmap.setbit(1) bitmap.setbit(3) bitmap.setbit(6) bitmap.setbit(7) bitmap.setbit(8) for i in range(1, 11): print(bitmap.getbit(i))
23.5
54
0.558865
""" Author: Wenru Dong """ from typing import Optional class Bitmap: def __init__(self, num_bits: int): self._num_bits = num_bits self._bytes = bytearray(num_bits // 8 + 1) def setbit(self, k: int) -> None: if k > self._num_bits or k < 1: return self._bytes[k // 8] |= (1 << k % 8) def getbit(self, k: int) -> Optional[bool]: if k > self._num_bits or k < 1: return return self._bytes[k // 8] & (1 << k % 8) != 0 if __name__ == "__main__": bitmap = Bitmap(10) bitmap.setbit(1) bitmap.setbit(3) bitmap.setbit(6) bitmap.setbit(7) bitmap.setbit(8) for i in range(1, 11): print(bitmap.getbit(i))
325
-8
111
e587999a7e8362a1ea53e0597090bc5e5186a9de
1,110
py
Python
data_show.py
sherlock1987/ConvLab-2
9547cb09bfd7e297e2c609637c9e38f6c94fdbfb
[ "Apache-2.0" ]
1
2020-06-05T08:42:51.000Z
2020-06-05T08:42:51.000Z
data_show.py
sherlock1987/ConvLab-2
9547cb09bfd7e297e2c609637c9e38f6c94fdbfb
[ "Apache-2.0" ]
null
null
null
data_show.py
sherlock1987/ConvLab-2
9547cb09bfd7e297e2c609637c9e38f6c94fdbfb
[ "Apache-2.0" ]
1
2020-06-05T09:15:51.000Z
2020-06-05T09:15:51.000Z
a = [[['Inform', 'Train', 'Choice', 'over 1'], ['Inform', 'Train', 'Choice', '000'], ['Request', 'Train', 'Depart', '?']], [['Inform', 'Train', 'Depart', 'birmingham new street']], [['Request', 'Train', 'Day', '?']], [['Inform', 'Train', 'Day', 'wednesday']], [['Inform', 'Train', 'Arrive', '20:23'], ['Inform', 'Train', 'Day', 'Wednesday'], ['Inform', 'Train', 'Depart', 'birmingham new street'], ['Inform', 'Train', 'Leave', '17:40']], [['Inform', 'Train', 'People', '5']], [['OfferBooked', 'Train', 'Ref', 'A9NHSO9Y']], [['Inform', 'Hotel', 'Internet', 'yes'], ['Inform', 'Hotel', 'Stars', '4']], [['Recommend', 'Hotel', 'Name', 'the cambridge belfry']], [['Inform', 'Hotel', 'Day', 'wednesday'], ['Inform', 'Hotel', 'People', '5'], ['Inform', 'Hotel', 'Stay', '5']], [['Book', 'Booking', 'Ref', '5NAWGJDC']], [['thank', 'general', 'none', 'none']], [['bye', 'general', 'none', 'none']]] print(a) for i in range(len(a)): print() for j in range(len(a[i])): one = a[i][j] left = "_".join(one[:-1]) right = one[-1] whole = ": ".join([left, right]) print(whole)
46.25
177
0.513514
a = [[['Inform', 'Train', 'Choice', 'over 1'], ['Inform', 'Train', 'Choice', '000'], ['Request', 'Train', 'Depart', '?']], [['Inform', 'Train', 'Depart', 'birmingham new street']], [['Request', 'Train', 'Day', '?']], [['Inform', 'Train', 'Day', 'wednesday']], [['Inform', 'Train', 'Arrive', '20:23'], ['Inform', 'Train', 'Day', 'Wednesday'], ['Inform', 'Train', 'Depart', 'birmingham new street'], ['Inform', 'Train', 'Leave', '17:40']], [['Inform', 'Train', 'People', '5']], [['OfferBooked', 'Train', 'Ref', 'A9NHSO9Y']], [['Inform', 'Hotel', 'Internet', 'yes'], ['Inform', 'Hotel', 'Stars', '4']], [['Recommend', 'Hotel', 'Name', 'the cambridge belfry']], [['Inform', 'Hotel', 'Day', 'wednesday'], ['Inform', 'Hotel', 'People', '5'], ['Inform', 'Hotel', 'Stay', '5']], [['Book', 'Booking', 'Ref', '5NAWGJDC']], [['thank', 'general', 'none', 'none']], [['bye', 'general', 'none', 'none']]] print(a) for i in range(len(a)): print() for j in range(len(a[i])): one = a[i][j] left = "_".join(one[:-1]) right = one[-1] whole = ": ".join([left, right]) print(whole)
0
0
0
fc7c412d4a6ededf0a68602a59234bebc3e8681c
7,522
py
Python
sdks/python/apache_beam/io/gcp/datastore_write_it_pipeline.py
dlesco/beam
fcf00b234a66a8d111b201f08ace46e3c3b38b5e
[ "Apache-2.0" ]
4
2018-09-25T16:10:54.000Z
2020-07-13T23:52:12.000Z
sdks/python/apache_beam/io/gcp/datastore_write_it_pipeline.py
dlesco/beam
fcf00b234a66a8d111b201f08ace46e3c3b38b5e
[ "Apache-2.0" ]
41
2018-08-16T23:54:04.000Z
2022-01-24T20:27:19.000Z
sdks/python/apache_beam/io/gcp/datastore_write_it_pipeline.py
dlesco/beam
fcf00b234a66a8d111b201f08ace46e3c3b38b5e
[ "Apache-2.0" ]
2
2019-04-16T15:29:22.000Z
2020-03-30T18:43:34.000Z
# # Licensed to the Apache Software Foundation (ASF) under one or more # contributor license agreements. See the NOTICE file distributed with # this work for additional information regarding copyright ownership. # The ASF licenses this file to You under the Apache License, Version 2.0 # (the "License"); you may not use this file except in compliance with # the License. You may obtain a copy of the License at # # http://www.apache.org/licenses/LICENSE-2.0 # # Unless required by applicable law or agreed to in writing, software # distributed under the License is distributed on an "AS IS" BASIS, # WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. # See the License for the specific language governing permissions and # limitations under the License. # """A job that write Entries into Datastore. The pipelines behave in the steps below. 1. Create and write Entities to Datastore 2. (Optional) If read limit was provided, read it and confirm that the expected Entities were read. 3. Query the written Entities and verify result. 4. Delete Entries. 5. Query the written Entities, verify no results. """ from __future__ import absolute_import import argparse import hashlib import logging import uuid import apache_beam as beam from apache_beam.io.gcp.datastore.v1.datastoreio import DeleteFromDatastore from apache_beam.io.gcp.datastore.v1.datastoreio import ReadFromDatastore from apache_beam.io.gcp.datastore.v1.datastoreio import WriteToDatastore from apache_beam.options.pipeline_options import GoogleCloudOptions from apache_beam.options.pipeline_options import PipelineOptions from apache_beam.options.pipeline_options import SetupOptions from apache_beam.testing.test_pipeline import TestPipeline from apache_beam.testing.util import assert_that from apache_beam.testing.util import equal_to # Protect against environments where apitools library is not available. # pylint: disable=wrong-import-order, wrong-import-position try: from google.cloud.proto.datastore.v1 import entity_pb2 from google.cloud.proto.datastore.v1 import query_pb2 from googledatastore import helper as datastore_helper from googledatastore import PropertyFilter except ImportError: pass # pylint: enable=wrong-import-order, wrong-import-position # pylint: enable=ungrouped-imports def new_pipeline_with_job_name(pipeline_options, job_name, suffix): """Create a pipeline with the given job_name and a suffix.""" gcp_options = pipeline_options.view_as(GoogleCloudOptions) # DirectRunner doesn't have a job name. if job_name: gcp_options.job_name = job_name + suffix return TestPipeline(options=pipeline_options) class EntityWrapper(object): """Create a Cloud Datastore entity from the given string.""" def make_entity(self, content): """Create entity from given string.""" entity = entity_pb2.Entity() if self._namespace is not None: entity.key.partition_id.namespace_id = self._namespace # All entities created will have the same ancestor datastore_helper.add_key_path(entity.key, self._kind, self._ancestor, self._kind, hashlib.sha1(content).hexdigest()) datastore_helper.add_properties(entity, {'content': str(content)}) return entity def make_ancestor_query(kind, namespace, ancestor): """Creates a Cloud Datastore ancestor query.""" ancestor_key = entity_pb2.Key() datastore_helper.add_key_path(ancestor_key, kind, ancestor) if namespace is not None: ancestor_key.partition_id.namespace_id = namespace query = query_pb2.Query() query.kind.add().name = kind datastore_helper.set_property_filter( query.filter, '__key__', PropertyFilter.HAS_ANCESTOR, ancestor_key) return query def run(argv=None): """Main entry point.""" parser = argparse.ArgumentParser() parser.add_argument('--kind', dest='kind', default='writereadtest', help='Datastore Kind') parser.add_argument('--num_entities', dest='num_entities', type=int, required=True, help='Number of entities to write') parser.add_argument('--limit', dest='limit', type=int, help='Limit of number of entities to write') known_args, pipeline_args = parser.parse_known_args(argv) pipeline_options = PipelineOptions(pipeline_args) pipeline_options.view_as(SetupOptions).save_main_session = True gcloud_options = pipeline_options.view_as(GoogleCloudOptions) job_name = gcloud_options.job_name kind = known_args.kind num_entities = known_args.num_entities project = gcloud_options.project # a random ancesor key ancestor = str(uuid.uuid4()) query = make_ancestor_query(kind, None, ancestor) # Pipeline 1: Create and write the specified number of Entities to the # Cloud Datastore. logging.info('Writing %s entities to %s', num_entities, project) p = new_pipeline_with_job_name(pipeline_options, job_name, '-write') # pylint: disable=expression-not-assigned (p | 'Input' >> beam.Create(list(range(known_args.num_entities))) | 'To String' >> beam.Map(str) | 'To Entity' >> beam.Map(EntityWrapper(kind, None, ancestor).make_entity) | 'Write to Datastore' >> WriteToDatastore(project)) p.run() # Optional Pipeline 2: If a read limit was provided, read it and confirm # that the expected entities were read. if known_args.limit is not None: logging.info('Querying a limited set of %s entities and verifying count.', known_args.limit) p = new_pipeline_with_job_name(pipeline_options, job_name, '-verify-limit') query_with_limit = query_pb2.Query() query_with_limit.CopyFrom(query) query_with_limit.limit.value = known_args.limit entities = p | 'read from datastore' >> ReadFromDatastore(project, query_with_limit) assert_that( entities | beam.combiners.Count.Globally(), equal_to([known_args.limit])) p.run() # Pipeline 3: Query the written Entities and verify result. logging.info('Querying entities, asserting they match.') p = new_pipeline_with_job_name(pipeline_options, job_name, '-verify') entities = p | 'read from datastore' >> ReadFromDatastore(project, query) assert_that( entities | beam.combiners.Count.Globally(), equal_to([num_entities])) p.run() # Pipeline 4: Delete Entities. logging.info('Deleting entities.') p = new_pipeline_with_job_name(pipeline_options, job_name, '-delete') entities = p | 'read from datastore' >> ReadFromDatastore(project, query) # pylint: disable=expression-not-assigned (entities | 'To Keys' >> beam.Map(lambda entity: entity.key) | 'Delete keys' >> DeleteFromDatastore(project)) p.run() # Pipeline 5: Query the written Entities, verify no results. logging.info('Querying for the entities to make sure there are none present.') p = new_pipeline_with_job_name(pipeline_options, job_name, '-verify-deleted') entities = p | 'read from datastore' >> ReadFromDatastore(project, query) assert_that( entities | beam.combiners.Count.Globally(), equal_to([0])) p.run() if __name__ == '__main__': logging.getLogger().setLevel(logging.INFO) run()
36.163462
80
0.724807
# # Licensed to the Apache Software Foundation (ASF) under one or more # contributor license agreements. See the NOTICE file distributed with # this work for additional information regarding copyright ownership. # The ASF licenses this file to You under the Apache License, Version 2.0 # (the "License"); you may not use this file except in compliance with # the License. You may obtain a copy of the License at # # http://www.apache.org/licenses/LICENSE-2.0 # # Unless required by applicable law or agreed to in writing, software # distributed under the License is distributed on an "AS IS" BASIS, # WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. # See the License for the specific language governing permissions and # limitations under the License. # """A job that write Entries into Datastore. The pipelines behave in the steps below. 1. Create and write Entities to Datastore 2. (Optional) If read limit was provided, read it and confirm that the expected Entities were read. 3. Query the written Entities and verify result. 4. Delete Entries. 5. Query the written Entities, verify no results. """ from __future__ import absolute_import import argparse import hashlib import logging import uuid import apache_beam as beam from apache_beam.io.gcp.datastore.v1.datastoreio import DeleteFromDatastore from apache_beam.io.gcp.datastore.v1.datastoreio import ReadFromDatastore from apache_beam.io.gcp.datastore.v1.datastoreio import WriteToDatastore from apache_beam.options.pipeline_options import GoogleCloudOptions from apache_beam.options.pipeline_options import PipelineOptions from apache_beam.options.pipeline_options import SetupOptions from apache_beam.testing.test_pipeline import TestPipeline from apache_beam.testing.util import assert_that from apache_beam.testing.util import equal_to # Protect against environments where apitools library is not available. # pylint: disable=wrong-import-order, wrong-import-position try: from google.cloud.proto.datastore.v1 import entity_pb2 from google.cloud.proto.datastore.v1 import query_pb2 from googledatastore import helper as datastore_helper from googledatastore import PropertyFilter except ImportError: pass # pylint: enable=wrong-import-order, wrong-import-position # pylint: enable=ungrouped-imports def new_pipeline_with_job_name(pipeline_options, job_name, suffix): """Create a pipeline with the given job_name and a suffix.""" gcp_options = pipeline_options.view_as(GoogleCloudOptions) # DirectRunner doesn't have a job name. if job_name: gcp_options.job_name = job_name + suffix return TestPipeline(options=pipeline_options) class EntityWrapper(object): """Create a Cloud Datastore entity from the given string.""" def __init__(self, kind, namespace, ancestor): self._kind = kind self._namespace = namespace self._ancestor = ancestor def make_entity(self, content): """Create entity from given string.""" entity = entity_pb2.Entity() if self._namespace is not None: entity.key.partition_id.namespace_id = self._namespace # All entities created will have the same ancestor datastore_helper.add_key_path(entity.key, self._kind, self._ancestor, self._kind, hashlib.sha1(content).hexdigest()) datastore_helper.add_properties(entity, {'content': str(content)}) return entity def make_ancestor_query(kind, namespace, ancestor): """Creates a Cloud Datastore ancestor query.""" ancestor_key = entity_pb2.Key() datastore_helper.add_key_path(ancestor_key, kind, ancestor) if namespace is not None: ancestor_key.partition_id.namespace_id = namespace query = query_pb2.Query() query.kind.add().name = kind datastore_helper.set_property_filter( query.filter, '__key__', PropertyFilter.HAS_ANCESTOR, ancestor_key) return query def run(argv=None): """Main entry point.""" parser = argparse.ArgumentParser() parser.add_argument('--kind', dest='kind', default='writereadtest', help='Datastore Kind') parser.add_argument('--num_entities', dest='num_entities', type=int, required=True, help='Number of entities to write') parser.add_argument('--limit', dest='limit', type=int, help='Limit of number of entities to write') known_args, pipeline_args = parser.parse_known_args(argv) pipeline_options = PipelineOptions(pipeline_args) pipeline_options.view_as(SetupOptions).save_main_session = True gcloud_options = pipeline_options.view_as(GoogleCloudOptions) job_name = gcloud_options.job_name kind = known_args.kind num_entities = known_args.num_entities project = gcloud_options.project # a random ancesor key ancestor = str(uuid.uuid4()) query = make_ancestor_query(kind, None, ancestor) # Pipeline 1: Create and write the specified number of Entities to the # Cloud Datastore. logging.info('Writing %s entities to %s', num_entities, project) p = new_pipeline_with_job_name(pipeline_options, job_name, '-write') # pylint: disable=expression-not-assigned (p | 'Input' >> beam.Create(list(range(known_args.num_entities))) | 'To String' >> beam.Map(str) | 'To Entity' >> beam.Map(EntityWrapper(kind, None, ancestor).make_entity) | 'Write to Datastore' >> WriteToDatastore(project)) p.run() # Optional Pipeline 2: If a read limit was provided, read it and confirm # that the expected entities were read. if known_args.limit is not None: logging.info('Querying a limited set of %s entities and verifying count.', known_args.limit) p = new_pipeline_with_job_name(pipeline_options, job_name, '-verify-limit') query_with_limit = query_pb2.Query() query_with_limit.CopyFrom(query) query_with_limit.limit.value = known_args.limit entities = p | 'read from datastore' >> ReadFromDatastore(project, query_with_limit) assert_that( entities | beam.combiners.Count.Globally(), equal_to([known_args.limit])) p.run() # Pipeline 3: Query the written Entities and verify result. logging.info('Querying entities, asserting they match.') p = new_pipeline_with_job_name(pipeline_options, job_name, '-verify') entities = p | 'read from datastore' >> ReadFromDatastore(project, query) assert_that( entities | beam.combiners.Count.Globally(), equal_to([num_entities])) p.run() # Pipeline 4: Delete Entities. logging.info('Deleting entities.') p = new_pipeline_with_job_name(pipeline_options, job_name, '-delete') entities = p | 'read from datastore' >> ReadFromDatastore(project, query) # pylint: disable=expression-not-assigned (entities | 'To Keys' >> beam.Map(lambda entity: entity.key) | 'Delete keys' >> DeleteFromDatastore(project)) p.run() # Pipeline 5: Query the written Entities, verify no results. logging.info('Querying for the entities to make sure there are none present.') p = new_pipeline_with_job_name(pipeline_options, job_name, '-verify-deleted') entities = p | 'read from datastore' >> ReadFromDatastore(project, query) assert_that( entities | beam.combiners.Count.Globally(), equal_to([0])) p.run() if __name__ == '__main__': logging.getLogger().setLevel(logging.INFO) run()
109
0
25
ec82df66a47bfadb6c53a47eb1ea15809590e667
127
py
Python
Snippets/code-gym-1/highlight.py
ursaMaj0r/python-csc-125
1d0968ad144112e24ae331c75aad58b74041593a
[ "MIT" ]
null
null
null
Snippets/code-gym-1/highlight.py
ursaMaj0r/python-csc-125
1d0968ad144112e24ae331c75aad58b74041593a
[ "MIT" ]
null
null
null
Snippets/code-gym-1/highlight.py
ursaMaj0r/python-csc-125
1d0968ad144112e24ae331c75aad58b74041593a
[ "MIT" ]
null
null
null
# input input_word = input("Enter a word: ") # response print('***') for letter in input_word: print(letter) print('***')
14.111111
36
0.629921
# input input_word = input("Enter a word: ") # response print('***') for letter in input_word: print(letter) print('***')
0
0
0
f1fcb1fb36d49f30f0e0393bfc90d7b785f822e9
18,682
py
Python
python/tinkoff/cloud/stt/v1/stt_pb2.py
Tinkoff/voicekit-examples
fbfe789135bb0b9360f7fb5669b7953616f18502
[ "Apache-2.0" ]
3
2022-02-11T04:34:18.000Z
2022-03-29T19:35:57.000Z
python/tinkoff/cloud/stt/v1/stt_pb2.py
Tinkoff/voicekit-examples
fbfe789135bb0b9360f7fb5669b7953616f18502
[ "Apache-2.0" ]
3
2022-01-27T15:40:38.000Z
2022-03-31T10:03:35.000Z
python/tinkoff/cloud/stt/v1/stt_pb2.py
Tinkoff/voicekit-examples
fbfe789135bb0b9360f7fb5669b7953616f18502
[ "Apache-2.0" ]
5
2022-01-27T15:15:06.000Z
2022-03-24T22:06:18.000Z
# -*- coding: utf-8 -*- # Generated by the protocol buffer compiler. DO NOT EDIT! # source: tinkoff/cloud/stt/v1/stt.proto """Generated protocol buffer code.""" from google.protobuf.internal import enum_type_wrapper from google.protobuf import descriptor as _descriptor from google.protobuf import descriptor_pool as _descriptor_pool from google.protobuf import message as _message from google.protobuf import reflection as _reflection from google.protobuf import symbol_database as _symbol_database # @@protoc_insertion_point(imports) _sym_db = _symbol_database.Default() from google.protobuf import duration_pb2 as google_dot_protobuf_dot_duration__pb2 from google.api import annotations_pb2 as google_dot_api_dot_annotations__pb2 from tinkoff.cloud.longrunning.v1 import longrunning_pb2 as tinkoff_dot_cloud_dot_longrunning_dot_v1_dot_longrunning__pb2 DESCRIPTOR = _descriptor_pool.Default().AddSerializedFile(b'\n\x1etinkoff/cloud/stt/v1/stt.proto\x12\x14tinkoff.cloud.stt.v1\x1a\x1egoogle/protobuf/duration.proto\x1a\x1cgoogle/api/annotations.proto\x1a.tinkoff/cloud/longrunning/v1/longrunning.proto\"D\n\x10RecognitionAudio\x12\x11\n\x07\x63ontent\x18\x01 \x01(\x0cH\x00\x12\r\n\x03uri\x18\x02 \x01(\tH\x00\x42\x0e\n\x0c\x61udio_source\"2\n\x13SpeechContextPhrase\x12\x0c\n\x04text\x18\x01 \x01(\t\x12\r\n\x05score\x18\x02 \x01(\x02\"W\n\rSpeechContext\x12:\n\x07phrases\x18\x03 \x03(\x0b\x32).tinkoff.cloud.stt.v1.SpeechContextPhraseJ\x04\x08\x01\x10\x02J\x04\x08\x02\x10\x03\"\x88\x01\n\x08WordInfo\x12-\n\nstart_time\x18\x01 \x01(\x0b\x32\x19.google.protobuf.Duration\x12+\n\x08\x65nd_time\x18\x02 \x01(\x0b\x32\x19.google.protobuf.Duration\x12\x0c\n\x04word\x18\x03 \x01(\t\x12\x12\n\nconfidence\x18\x04 \x01(\x02\"\xb4\x01\n\x1cVoiceActivityDetectionConfig\x12\x1b\n\x13min_speech_duration\x18\x01 \x01(\x02\x12\x1b\n\x13max_speech_duration\x18\x02 \x01(\x02\x12\"\n\x1asilence_duration_threshold\x18\x03 \x01(\x02\x12\x1e\n\x16silence_prob_threshold\x18\x04 \x01(\x02\x12\x16\n\x0e\x61ggressiveness\x18\x05 \x01(\x02\"\xdb\x04\n\x11RecognitionConfig\x12\x35\n\x08\x65ncoding\x18\x01 \x01(\x0e\x32#.tinkoff.cloud.stt.v1.AudioEncoding\x12\x19\n\x11sample_rate_hertz\x18\x02 \x01(\r\x12\x15\n\rlanguage_code\x18\x03 \x01(\t\x12\x18\n\x10max_alternatives\x18\x04 \x01(\r\x12\x18\n\x10profanity_filter\x18\x05 \x01(\x08\x12<\n\x0fspeech_contexts\x18\x06 \x03(\x0b\x32#.tinkoff.cloud.stt.v1.SpeechContext\x12$\n\x1c\x65nable_automatic_punctuation\x18\x08 \x01(\x08\x12\r\n\x05model\x18\n \x01(\t\x12\x14\n\x0cnum_channels\x18\x0c \x01(\r\x12\x1c\n\x12\x64o_not_perform_vad\x18\r \x01(\x08H\x00\x12H\n\nvad_config\x18\x0e \x01(\x0b\x32\x32.tinkoff.cloud.stt.v1.VoiceActivityDetectionConfigH\x00\x12\x1e\n\x16\x65nable_denormalization\x18\x10 \x01(\x08\x12!\n\x19\x65nable_sentiment_analysis\x18\x11 \x01(\x08\x12$\n\x1c\x65nable_gender_identification\x18\x12 \x01(\x08\x42\x05\n\x03vadJ\x04\x08\x07\x10\x08J\x04\x08\t\x10\nJ\x04\x08\x0b\x10\x0cJ\x04\x08\x0f\x10\x10R\x18\x65nable_word_time_offsetsR\x08metadataR\x0cuse_enhanced\"\x82\x01\n\x10RecognizeRequest\x12\x37\n\x06\x63onfig\x18\x01 \x01(\x0b\x32\'.tinkoff.cloud.stt.v1.RecognitionConfig\x12\x35\n\x05\x61udio\x18\x02 \x01(\x0b\x32&.tinkoff.cloud.stt.v1.RecognitionAudio\"u\n\x1cSpeechRecognitionAlternative\x12\x12\n\ntranscript\x18\x01 \x01(\t\x12\x12\n\nconfidence\x18\x02 \x01(\x02\x12-\n\x05words\x18\x03 \x03(\x0b\x32\x1e.tinkoff.cloud.stt.v1.WordInfo\"^\n\x1dSpeechSentimentAnalysisResult\x12\x1b\n\x13negative_prob_audio\x18\x01 \x01(\x02\x12 \n\x18negative_prob_audio_text\x18\x02 \x01(\x02\"L\n SpeechGenderIdentificationResult\x12\x12\n\nmale_proba\x18\x01 \x01(\x02\x12\x14\n\x0c\x66\x65male_proba\x18\x02 \x01(\x02\"\x86\x03\n\x17SpeechRecognitionResult\x12H\n\x0c\x61lternatives\x18\x01 \x03(\x0b\x32\x32.tinkoff.cloud.stt.v1.SpeechRecognitionAlternative\x12\x0f\n\x07\x63hannel\x18\x02 \x01(\x05\x12-\n\nstart_time\x18\x03 \x01(\x0b\x32\x19.google.protobuf.Duration\x12+\n\x08\x65nd_time\x18\x04 \x01(\x0b\x32\x19.google.protobuf.Duration\x12V\n\x19sentiment_analysis_result\x18\x05 \x01(\x0b\x32\x33.tinkoff.cloud.stt.v1.SpeechSentimentAnalysisResult\x12\\\n\x1cgender_identification_result\x18\x06 \x01(\x0b\x32\x36.tinkoff.cloud.stt.v1.SpeechGenderIdentificationResult\"S\n\x11RecognizeResponse\x12>\n\x07results\x18\x01 \x03(\x0b\x32-.tinkoff.cloud.stt.v1.SpeechRecognitionResult\"H\n\x14InterimResultsConfig\x12\x1e\n\x16\x65nable_interim_results\x18\x01 \x01(\x08\x12\x10\n\x08interval\x18\x02 \x01(\x02\"\x9c\x01\n\x1bLongRunningRecognizeRequest\x12\x37\n\x06\x63onfig\x18\x01 \x01(\x0b\x32\'.tinkoff.cloud.stt.v1.RecognitionConfig\x12\x35\n\x05\x61udio\x18\x02 \x01(\x0b\x32&.tinkoff.cloud.stt.v1.RecognitionAudio\x12\r\n\x05group\x18\x03 \x01(\t\"\xbb\x01\n\x1aStreamingRecognitionConfig\x12\x37\n\x06\x63onfig\x18\x01 \x01(\x0b\x32\'.tinkoff.cloud.stt.v1.RecognitionConfig\x12\x18\n\x10single_utterance\x18\x02 \x01(\x08\x12J\n\x16interim_results_config\x18\x03 \x01(\x0b\x32*.tinkoff.cloud.stt.v1.InterimResultsConfig\"\x97\x01\n\x19StreamingRecognizeRequest\x12L\n\x10streaming_config\x18\x01 \x01(\x0b\x32\x30.tinkoff.cloud.stt.v1.StreamingRecognitionConfigH\x00\x12\x17\n\raudio_content\x18\x02 \x01(\x0cH\x00\x42\x13\n\x11streaming_request\"\x8c\x01\n\x1aStreamingRecognitionResult\x12I\n\x12recognition_result\x18\x01 \x01(\x0b\x32-.tinkoff.cloud.stt.v1.SpeechRecognitionResult\x12\x10\n\x08is_final\x18\x02 \x01(\x08\x12\x11\n\tstability\x18\x03 \x01(\x02\"k\n\x1aStreamingRecognizeResponse\x12\x41\n\x07results\x18\x02 \x03(\x0b\x32\x30.tinkoff.cloud.stt.v1.StreamingRecognitionResultJ\x04\x08\x01\x10\x02J\x04\x08\x03\x10\x04\"\x8f\x01\n\x1eStreamingUnaryRecognizeRequest\x12\x39\n\x06\x63onfig\x18\x01 \x01(\x0b\x32\'.tinkoff.cloud.stt.v1.RecognitionConfigH\x00\x12\x17\n\raudio_content\x18\x02 \x01(\x0cH\x00\x42\x19\n\x17streaming_unary_request*\x91\x02\n\rAudioEncoding\x12\x18\n\x14\x45NCODING_UNSPECIFIED\x10\x00\x12\x0c\n\x08LINEAR16\x10\x01\x12\t\n\x05MULAW\x10\x03\x12\x08\n\x04\x41LAW\x10\x08\x12\x0c\n\x08RAW_OPUS\x10\x0b\x12\x0e\n\nMPEG_AUDIO\x10\x0c\x12\x0c\n\x08\x41\x44TS_AAC\x10\r\x12\x0e\n\nRAW_AAC_LC\x10\x0e\x12\x11\n\rRAW_ER_AAC_LD\x10\x0f\"\x04\x08\x02\x10\x02\"\x04\x08\x04\x10\x04\"\x04\x08\x05\x10\x05\"\x04\x08\x06\x10\x06\"\x04\x08\x07\x10\x07\"\x04\x08\t\x10\t\"\x04\x08\n\x10\n*\x04\x46LAC*\x03\x41MR*\x06\x41MR_WB*\x08OGG_OPUS*\x16SPEEX_WITH_HEADER_BYTE*\tLINEAR32F*\nOGG_VORBIS2\xd0\x04\n\x0cSpeechToText\x12z\n\tRecognize\x12&.tinkoff.cloud.stt.v1.RecognizeRequest\x1a\'.tinkoff.cloud.stt.v1.RecognizeResponse\"\x1c\x82\xd3\xe4\x93\x02\x16\"\x11/v1/stt:recognize:\x01*\x12{\n\x12StreamingRecognize\x12/.tinkoff.cloud.stt.v1.StreamingRecognizeRequest\x1a\x30.tinkoff.cloud.stt.v1.StreamingRecognizeResponse(\x01\x30\x01\x12\x9b\x01\n\x14LongRunningRecognize\x12\x31.tinkoff.cloud.stt.v1.LongRunningRecognizeRequest\x1a\'.tinkoff.cloud.longrunning.v1.Operation\"\'\x82\xd3\xe4\x93\x02!\"\x1c/v1/stt:longrunningrecognize:\x01*\x12\xa8\x01\n\x17StreamingUnaryRecognize\x12\x34.tinkoff.cloud.stt.v1.StreamingUnaryRecognizeRequest\x1a\'.tinkoff.cloud.stt.v1.RecognizeResponse\",\x82\xd3\xe4\x93\x02&\"!/v1/stt:streaming_unary_recognize:\x01*(\x01\x42NZDgithub.com/Tinkoff/voicekit-examples/golang/pkg/tinkoff/cloud/stt/v1\xa2\x02\x05TVKSRb\x06proto3') _AUDIOENCODING = DESCRIPTOR.enum_types_by_name['AudioEncoding'] AudioEncoding = enum_type_wrapper.EnumTypeWrapper(_AUDIOENCODING) ENCODING_UNSPECIFIED = 0 LINEAR16 = 1 MULAW = 3 ALAW = 8 RAW_OPUS = 11 MPEG_AUDIO = 12 ADTS_AAC = 13 RAW_AAC_LC = 14 RAW_ER_AAC_LD = 15 _RECOGNITIONAUDIO = DESCRIPTOR.message_types_by_name['RecognitionAudio'] _SPEECHCONTEXTPHRASE = DESCRIPTOR.message_types_by_name['SpeechContextPhrase'] _SPEECHCONTEXT = DESCRIPTOR.message_types_by_name['SpeechContext'] _WORDINFO = DESCRIPTOR.message_types_by_name['WordInfo'] _VOICEACTIVITYDETECTIONCONFIG = DESCRIPTOR.message_types_by_name['VoiceActivityDetectionConfig'] _RECOGNITIONCONFIG = DESCRIPTOR.message_types_by_name['RecognitionConfig'] _RECOGNIZEREQUEST = DESCRIPTOR.message_types_by_name['RecognizeRequest'] _SPEECHRECOGNITIONALTERNATIVE = DESCRIPTOR.message_types_by_name['SpeechRecognitionAlternative'] _SPEECHSENTIMENTANALYSISRESULT = DESCRIPTOR.message_types_by_name['SpeechSentimentAnalysisResult'] _SPEECHGENDERIDENTIFICATIONRESULT = DESCRIPTOR.message_types_by_name['SpeechGenderIdentificationResult'] _SPEECHRECOGNITIONRESULT = DESCRIPTOR.message_types_by_name['SpeechRecognitionResult'] _RECOGNIZERESPONSE = DESCRIPTOR.message_types_by_name['RecognizeResponse'] _INTERIMRESULTSCONFIG = DESCRIPTOR.message_types_by_name['InterimResultsConfig'] _LONGRUNNINGRECOGNIZEREQUEST = DESCRIPTOR.message_types_by_name['LongRunningRecognizeRequest'] _STREAMINGRECOGNITIONCONFIG = DESCRIPTOR.message_types_by_name['StreamingRecognitionConfig'] _STREAMINGRECOGNIZEREQUEST = DESCRIPTOR.message_types_by_name['StreamingRecognizeRequest'] _STREAMINGRECOGNITIONRESULT = DESCRIPTOR.message_types_by_name['StreamingRecognitionResult'] _STREAMINGRECOGNIZERESPONSE = DESCRIPTOR.message_types_by_name['StreamingRecognizeResponse'] _STREAMINGUNARYRECOGNIZEREQUEST = DESCRIPTOR.message_types_by_name['StreamingUnaryRecognizeRequest'] RecognitionAudio = _reflection.GeneratedProtocolMessageType('RecognitionAudio', (_message.Message,), { 'DESCRIPTOR' : _RECOGNITIONAUDIO, '__module__' : 'tinkoff.cloud.stt.v1.stt_pb2' # @@protoc_insertion_point(class_scope:tinkoff.cloud.stt.v1.RecognitionAudio) }) _sym_db.RegisterMessage(RecognitionAudio) SpeechContextPhrase = _reflection.GeneratedProtocolMessageType('SpeechContextPhrase', (_message.Message,), { 'DESCRIPTOR' : _SPEECHCONTEXTPHRASE, '__module__' : 'tinkoff.cloud.stt.v1.stt_pb2' # @@protoc_insertion_point(class_scope:tinkoff.cloud.stt.v1.SpeechContextPhrase) }) _sym_db.RegisterMessage(SpeechContextPhrase) SpeechContext = _reflection.GeneratedProtocolMessageType('SpeechContext', (_message.Message,), { 'DESCRIPTOR' : _SPEECHCONTEXT, '__module__' : 'tinkoff.cloud.stt.v1.stt_pb2' # @@protoc_insertion_point(class_scope:tinkoff.cloud.stt.v1.SpeechContext) }) _sym_db.RegisterMessage(SpeechContext) WordInfo = _reflection.GeneratedProtocolMessageType('WordInfo', (_message.Message,), { 'DESCRIPTOR' : _WORDINFO, '__module__' : 'tinkoff.cloud.stt.v1.stt_pb2' # @@protoc_insertion_point(class_scope:tinkoff.cloud.stt.v1.WordInfo) }) _sym_db.RegisterMessage(WordInfo) VoiceActivityDetectionConfig = _reflection.GeneratedProtocolMessageType('VoiceActivityDetectionConfig', (_message.Message,), { 'DESCRIPTOR' : _VOICEACTIVITYDETECTIONCONFIG, '__module__' : 'tinkoff.cloud.stt.v1.stt_pb2' # @@protoc_insertion_point(class_scope:tinkoff.cloud.stt.v1.VoiceActivityDetectionConfig) }) _sym_db.RegisterMessage(VoiceActivityDetectionConfig) RecognitionConfig = _reflection.GeneratedProtocolMessageType('RecognitionConfig', (_message.Message,), { 'DESCRIPTOR' : _RECOGNITIONCONFIG, '__module__' : 'tinkoff.cloud.stt.v1.stt_pb2' # @@protoc_insertion_point(class_scope:tinkoff.cloud.stt.v1.RecognitionConfig) }) _sym_db.RegisterMessage(RecognitionConfig) RecognizeRequest = _reflection.GeneratedProtocolMessageType('RecognizeRequest', (_message.Message,), { 'DESCRIPTOR' : _RECOGNIZEREQUEST, '__module__' : 'tinkoff.cloud.stt.v1.stt_pb2' # @@protoc_insertion_point(class_scope:tinkoff.cloud.stt.v1.RecognizeRequest) }) _sym_db.RegisterMessage(RecognizeRequest) SpeechRecognitionAlternative = _reflection.GeneratedProtocolMessageType('SpeechRecognitionAlternative', (_message.Message,), { 'DESCRIPTOR' : _SPEECHRECOGNITIONALTERNATIVE, '__module__' : 'tinkoff.cloud.stt.v1.stt_pb2' # @@protoc_insertion_point(class_scope:tinkoff.cloud.stt.v1.SpeechRecognitionAlternative) }) _sym_db.RegisterMessage(SpeechRecognitionAlternative) SpeechSentimentAnalysisResult = _reflection.GeneratedProtocolMessageType('SpeechSentimentAnalysisResult', (_message.Message,), { 'DESCRIPTOR' : _SPEECHSENTIMENTANALYSISRESULT, '__module__' : 'tinkoff.cloud.stt.v1.stt_pb2' # @@protoc_insertion_point(class_scope:tinkoff.cloud.stt.v1.SpeechSentimentAnalysisResult) }) _sym_db.RegisterMessage(SpeechSentimentAnalysisResult) SpeechGenderIdentificationResult = _reflection.GeneratedProtocolMessageType('SpeechGenderIdentificationResult', (_message.Message,), { 'DESCRIPTOR' : _SPEECHGENDERIDENTIFICATIONRESULT, '__module__' : 'tinkoff.cloud.stt.v1.stt_pb2' # @@protoc_insertion_point(class_scope:tinkoff.cloud.stt.v1.SpeechGenderIdentificationResult) }) _sym_db.RegisterMessage(SpeechGenderIdentificationResult) SpeechRecognitionResult = _reflection.GeneratedProtocolMessageType('SpeechRecognitionResult', (_message.Message,), { 'DESCRIPTOR' : _SPEECHRECOGNITIONRESULT, '__module__' : 'tinkoff.cloud.stt.v1.stt_pb2' # @@protoc_insertion_point(class_scope:tinkoff.cloud.stt.v1.SpeechRecognitionResult) }) _sym_db.RegisterMessage(SpeechRecognitionResult) RecognizeResponse = _reflection.GeneratedProtocolMessageType('RecognizeResponse', (_message.Message,), { 'DESCRIPTOR' : _RECOGNIZERESPONSE, '__module__' : 'tinkoff.cloud.stt.v1.stt_pb2' # @@protoc_insertion_point(class_scope:tinkoff.cloud.stt.v1.RecognizeResponse) }) _sym_db.RegisterMessage(RecognizeResponse) InterimResultsConfig = _reflection.GeneratedProtocolMessageType('InterimResultsConfig', (_message.Message,), { 'DESCRIPTOR' : _INTERIMRESULTSCONFIG, '__module__' : 'tinkoff.cloud.stt.v1.stt_pb2' # @@protoc_insertion_point(class_scope:tinkoff.cloud.stt.v1.InterimResultsConfig) }) _sym_db.RegisterMessage(InterimResultsConfig) LongRunningRecognizeRequest = _reflection.GeneratedProtocolMessageType('LongRunningRecognizeRequest', (_message.Message,), { 'DESCRIPTOR' : _LONGRUNNINGRECOGNIZEREQUEST, '__module__' : 'tinkoff.cloud.stt.v1.stt_pb2' # @@protoc_insertion_point(class_scope:tinkoff.cloud.stt.v1.LongRunningRecognizeRequest) }) _sym_db.RegisterMessage(LongRunningRecognizeRequest) StreamingRecognitionConfig = _reflection.GeneratedProtocolMessageType('StreamingRecognitionConfig', (_message.Message,), { 'DESCRIPTOR' : _STREAMINGRECOGNITIONCONFIG, '__module__' : 'tinkoff.cloud.stt.v1.stt_pb2' # @@protoc_insertion_point(class_scope:tinkoff.cloud.stt.v1.StreamingRecognitionConfig) }) _sym_db.RegisterMessage(StreamingRecognitionConfig) StreamingRecognizeRequest = _reflection.GeneratedProtocolMessageType('StreamingRecognizeRequest', (_message.Message,), { 'DESCRIPTOR' : _STREAMINGRECOGNIZEREQUEST, '__module__' : 'tinkoff.cloud.stt.v1.stt_pb2' # @@protoc_insertion_point(class_scope:tinkoff.cloud.stt.v1.StreamingRecognizeRequest) }) _sym_db.RegisterMessage(StreamingRecognizeRequest) StreamingRecognitionResult = _reflection.GeneratedProtocolMessageType('StreamingRecognitionResult', (_message.Message,), { 'DESCRIPTOR' : _STREAMINGRECOGNITIONRESULT, '__module__' : 'tinkoff.cloud.stt.v1.stt_pb2' # @@protoc_insertion_point(class_scope:tinkoff.cloud.stt.v1.StreamingRecognitionResult) }) _sym_db.RegisterMessage(StreamingRecognitionResult) StreamingRecognizeResponse = _reflection.GeneratedProtocolMessageType('StreamingRecognizeResponse', (_message.Message,), { 'DESCRIPTOR' : _STREAMINGRECOGNIZERESPONSE, '__module__' : 'tinkoff.cloud.stt.v1.stt_pb2' # @@protoc_insertion_point(class_scope:tinkoff.cloud.stt.v1.StreamingRecognizeResponse) }) _sym_db.RegisterMessage(StreamingRecognizeResponse) StreamingUnaryRecognizeRequest = _reflection.GeneratedProtocolMessageType('StreamingUnaryRecognizeRequest', (_message.Message,), { 'DESCRIPTOR' : _STREAMINGUNARYRECOGNIZEREQUEST, '__module__' : 'tinkoff.cloud.stt.v1.stt_pb2' # @@protoc_insertion_point(class_scope:tinkoff.cloud.stt.v1.StreamingUnaryRecognizeRequest) }) _sym_db.RegisterMessage(StreamingUnaryRecognizeRequest) _SPEECHTOTEXT = DESCRIPTOR.services_by_name['SpeechToText'] if _descriptor._USE_C_DESCRIPTORS == False: DESCRIPTOR._options = None DESCRIPTOR._serialized_options = b'ZDgithub.com/Tinkoff/voicekit-examples/golang/pkg/tinkoff/cloud/stt/v1\242\002\005TVKSR' _SPEECHTOTEXT.methods_by_name['Recognize']._options = None _SPEECHTOTEXT.methods_by_name['Recognize']._serialized_options = b'\202\323\344\223\002\026\"\021/v1/stt:recognize:\001*' _SPEECHTOTEXT.methods_by_name['LongRunningRecognize']._options = None _SPEECHTOTEXT.methods_by_name['LongRunningRecognize']._serialized_options = b'\202\323\344\223\002!\"\034/v1/stt:longrunningrecognize:\001*' _SPEECHTOTEXT.methods_by_name['StreamingUnaryRecognize']._options = None _SPEECHTOTEXT.methods_by_name['StreamingUnaryRecognize']._serialized_options = b'\202\323\344\223\002&\"!/v1/stt:streaming_unary_recognize:\001*' _AUDIOENCODING._serialized_start=3185 _AUDIOENCODING._serialized_end=3458 _RECOGNITIONAUDIO._serialized_start=166 _RECOGNITIONAUDIO._serialized_end=234 _SPEECHCONTEXTPHRASE._serialized_start=236 _SPEECHCONTEXTPHRASE._serialized_end=286 _SPEECHCONTEXT._serialized_start=288 _SPEECHCONTEXT._serialized_end=375 _WORDINFO._serialized_start=378 _WORDINFO._serialized_end=514 _VOICEACTIVITYDETECTIONCONFIG._serialized_start=517 _VOICEACTIVITYDETECTIONCONFIG._serialized_end=697 _RECOGNITIONCONFIG._serialized_start=700 _RECOGNITIONCONFIG._serialized_end=1303 _RECOGNIZEREQUEST._serialized_start=1306 _RECOGNIZEREQUEST._serialized_end=1436 _SPEECHRECOGNITIONALTERNATIVE._serialized_start=1438 _SPEECHRECOGNITIONALTERNATIVE._serialized_end=1555 _SPEECHSENTIMENTANALYSISRESULT._serialized_start=1557 _SPEECHSENTIMENTANALYSISRESULT._serialized_end=1651 _SPEECHGENDERIDENTIFICATIONRESULT._serialized_start=1653 _SPEECHGENDERIDENTIFICATIONRESULT._serialized_end=1729 _SPEECHRECOGNITIONRESULT._serialized_start=1732 _SPEECHRECOGNITIONRESULT._serialized_end=2122 _RECOGNIZERESPONSE._serialized_start=2124 _RECOGNIZERESPONSE._serialized_end=2207 _INTERIMRESULTSCONFIG._serialized_start=2209 _INTERIMRESULTSCONFIG._serialized_end=2281 _LONGRUNNINGRECOGNIZEREQUEST._serialized_start=2284 _LONGRUNNINGRECOGNIZEREQUEST._serialized_end=2440 _STREAMINGRECOGNITIONCONFIG._serialized_start=2443 _STREAMINGRECOGNITIONCONFIG._serialized_end=2630 _STREAMINGRECOGNIZEREQUEST._serialized_start=2633 _STREAMINGRECOGNIZEREQUEST._serialized_end=2784 _STREAMINGRECOGNITIONRESULT._serialized_start=2787 _STREAMINGRECOGNITIONRESULT._serialized_end=2927 _STREAMINGRECOGNIZERESPONSE._serialized_start=2929 _STREAMINGRECOGNIZERESPONSE._serialized_end=3036 _STREAMINGUNARYRECOGNIZEREQUEST._serialized_start=3039 _STREAMINGUNARYRECOGNIZEREQUEST._serialized_end=3182 _SPEECHTOTEXT._serialized_start=3461 _SPEECHTOTEXT._serialized_end=4053 # @@protoc_insertion_point(module_scope)
77.198347
6,418
0.827267
# -*- coding: utf-8 -*- # Generated by the protocol buffer compiler. DO NOT EDIT! # source: tinkoff/cloud/stt/v1/stt.proto """Generated protocol buffer code.""" from google.protobuf.internal import enum_type_wrapper from google.protobuf import descriptor as _descriptor from google.protobuf import descriptor_pool as _descriptor_pool from google.protobuf import message as _message from google.protobuf import reflection as _reflection from google.protobuf import symbol_database as _symbol_database # @@protoc_insertion_point(imports) _sym_db = _symbol_database.Default() from google.protobuf import duration_pb2 as google_dot_protobuf_dot_duration__pb2 from google.api import annotations_pb2 as google_dot_api_dot_annotations__pb2 from tinkoff.cloud.longrunning.v1 import longrunning_pb2 as tinkoff_dot_cloud_dot_longrunning_dot_v1_dot_longrunning__pb2 DESCRIPTOR = _descriptor_pool.Default().AddSerializedFile(b'\n\x1etinkoff/cloud/stt/v1/stt.proto\x12\x14tinkoff.cloud.stt.v1\x1a\x1egoogle/protobuf/duration.proto\x1a\x1cgoogle/api/annotations.proto\x1a.tinkoff/cloud/longrunning/v1/longrunning.proto\"D\n\x10RecognitionAudio\x12\x11\n\x07\x63ontent\x18\x01 \x01(\x0cH\x00\x12\r\n\x03uri\x18\x02 \x01(\tH\x00\x42\x0e\n\x0c\x61udio_source\"2\n\x13SpeechContextPhrase\x12\x0c\n\x04text\x18\x01 \x01(\t\x12\r\n\x05score\x18\x02 \x01(\x02\"W\n\rSpeechContext\x12:\n\x07phrases\x18\x03 \x03(\x0b\x32).tinkoff.cloud.stt.v1.SpeechContextPhraseJ\x04\x08\x01\x10\x02J\x04\x08\x02\x10\x03\"\x88\x01\n\x08WordInfo\x12-\n\nstart_time\x18\x01 \x01(\x0b\x32\x19.google.protobuf.Duration\x12+\n\x08\x65nd_time\x18\x02 \x01(\x0b\x32\x19.google.protobuf.Duration\x12\x0c\n\x04word\x18\x03 \x01(\t\x12\x12\n\nconfidence\x18\x04 \x01(\x02\"\xb4\x01\n\x1cVoiceActivityDetectionConfig\x12\x1b\n\x13min_speech_duration\x18\x01 \x01(\x02\x12\x1b\n\x13max_speech_duration\x18\x02 \x01(\x02\x12\"\n\x1asilence_duration_threshold\x18\x03 \x01(\x02\x12\x1e\n\x16silence_prob_threshold\x18\x04 \x01(\x02\x12\x16\n\x0e\x61ggressiveness\x18\x05 \x01(\x02\"\xdb\x04\n\x11RecognitionConfig\x12\x35\n\x08\x65ncoding\x18\x01 \x01(\x0e\x32#.tinkoff.cloud.stt.v1.AudioEncoding\x12\x19\n\x11sample_rate_hertz\x18\x02 \x01(\r\x12\x15\n\rlanguage_code\x18\x03 \x01(\t\x12\x18\n\x10max_alternatives\x18\x04 \x01(\r\x12\x18\n\x10profanity_filter\x18\x05 \x01(\x08\x12<\n\x0fspeech_contexts\x18\x06 \x03(\x0b\x32#.tinkoff.cloud.stt.v1.SpeechContext\x12$\n\x1c\x65nable_automatic_punctuation\x18\x08 \x01(\x08\x12\r\n\x05model\x18\n \x01(\t\x12\x14\n\x0cnum_channels\x18\x0c \x01(\r\x12\x1c\n\x12\x64o_not_perform_vad\x18\r \x01(\x08H\x00\x12H\n\nvad_config\x18\x0e \x01(\x0b\x32\x32.tinkoff.cloud.stt.v1.VoiceActivityDetectionConfigH\x00\x12\x1e\n\x16\x65nable_denormalization\x18\x10 \x01(\x08\x12!\n\x19\x65nable_sentiment_analysis\x18\x11 \x01(\x08\x12$\n\x1c\x65nable_gender_identification\x18\x12 \x01(\x08\x42\x05\n\x03vadJ\x04\x08\x07\x10\x08J\x04\x08\t\x10\nJ\x04\x08\x0b\x10\x0cJ\x04\x08\x0f\x10\x10R\x18\x65nable_word_time_offsetsR\x08metadataR\x0cuse_enhanced\"\x82\x01\n\x10RecognizeRequest\x12\x37\n\x06\x63onfig\x18\x01 \x01(\x0b\x32\'.tinkoff.cloud.stt.v1.RecognitionConfig\x12\x35\n\x05\x61udio\x18\x02 \x01(\x0b\x32&.tinkoff.cloud.stt.v1.RecognitionAudio\"u\n\x1cSpeechRecognitionAlternative\x12\x12\n\ntranscript\x18\x01 \x01(\t\x12\x12\n\nconfidence\x18\x02 \x01(\x02\x12-\n\x05words\x18\x03 \x03(\x0b\x32\x1e.tinkoff.cloud.stt.v1.WordInfo\"^\n\x1dSpeechSentimentAnalysisResult\x12\x1b\n\x13negative_prob_audio\x18\x01 \x01(\x02\x12 \n\x18negative_prob_audio_text\x18\x02 \x01(\x02\"L\n SpeechGenderIdentificationResult\x12\x12\n\nmale_proba\x18\x01 \x01(\x02\x12\x14\n\x0c\x66\x65male_proba\x18\x02 \x01(\x02\"\x86\x03\n\x17SpeechRecognitionResult\x12H\n\x0c\x61lternatives\x18\x01 \x03(\x0b\x32\x32.tinkoff.cloud.stt.v1.SpeechRecognitionAlternative\x12\x0f\n\x07\x63hannel\x18\x02 \x01(\x05\x12-\n\nstart_time\x18\x03 \x01(\x0b\x32\x19.google.protobuf.Duration\x12+\n\x08\x65nd_time\x18\x04 \x01(\x0b\x32\x19.google.protobuf.Duration\x12V\n\x19sentiment_analysis_result\x18\x05 \x01(\x0b\x32\x33.tinkoff.cloud.stt.v1.SpeechSentimentAnalysisResult\x12\\\n\x1cgender_identification_result\x18\x06 \x01(\x0b\x32\x36.tinkoff.cloud.stt.v1.SpeechGenderIdentificationResult\"S\n\x11RecognizeResponse\x12>\n\x07results\x18\x01 \x03(\x0b\x32-.tinkoff.cloud.stt.v1.SpeechRecognitionResult\"H\n\x14InterimResultsConfig\x12\x1e\n\x16\x65nable_interim_results\x18\x01 \x01(\x08\x12\x10\n\x08interval\x18\x02 \x01(\x02\"\x9c\x01\n\x1bLongRunningRecognizeRequest\x12\x37\n\x06\x63onfig\x18\x01 \x01(\x0b\x32\'.tinkoff.cloud.stt.v1.RecognitionConfig\x12\x35\n\x05\x61udio\x18\x02 \x01(\x0b\x32&.tinkoff.cloud.stt.v1.RecognitionAudio\x12\r\n\x05group\x18\x03 \x01(\t\"\xbb\x01\n\x1aStreamingRecognitionConfig\x12\x37\n\x06\x63onfig\x18\x01 \x01(\x0b\x32\'.tinkoff.cloud.stt.v1.RecognitionConfig\x12\x18\n\x10single_utterance\x18\x02 \x01(\x08\x12J\n\x16interim_results_config\x18\x03 \x01(\x0b\x32*.tinkoff.cloud.stt.v1.InterimResultsConfig\"\x97\x01\n\x19StreamingRecognizeRequest\x12L\n\x10streaming_config\x18\x01 \x01(\x0b\x32\x30.tinkoff.cloud.stt.v1.StreamingRecognitionConfigH\x00\x12\x17\n\raudio_content\x18\x02 \x01(\x0cH\x00\x42\x13\n\x11streaming_request\"\x8c\x01\n\x1aStreamingRecognitionResult\x12I\n\x12recognition_result\x18\x01 \x01(\x0b\x32-.tinkoff.cloud.stt.v1.SpeechRecognitionResult\x12\x10\n\x08is_final\x18\x02 \x01(\x08\x12\x11\n\tstability\x18\x03 \x01(\x02\"k\n\x1aStreamingRecognizeResponse\x12\x41\n\x07results\x18\x02 \x03(\x0b\x32\x30.tinkoff.cloud.stt.v1.StreamingRecognitionResultJ\x04\x08\x01\x10\x02J\x04\x08\x03\x10\x04\"\x8f\x01\n\x1eStreamingUnaryRecognizeRequest\x12\x39\n\x06\x63onfig\x18\x01 \x01(\x0b\x32\'.tinkoff.cloud.stt.v1.RecognitionConfigH\x00\x12\x17\n\raudio_content\x18\x02 \x01(\x0cH\x00\x42\x19\n\x17streaming_unary_request*\x91\x02\n\rAudioEncoding\x12\x18\n\x14\x45NCODING_UNSPECIFIED\x10\x00\x12\x0c\n\x08LINEAR16\x10\x01\x12\t\n\x05MULAW\x10\x03\x12\x08\n\x04\x41LAW\x10\x08\x12\x0c\n\x08RAW_OPUS\x10\x0b\x12\x0e\n\nMPEG_AUDIO\x10\x0c\x12\x0c\n\x08\x41\x44TS_AAC\x10\r\x12\x0e\n\nRAW_AAC_LC\x10\x0e\x12\x11\n\rRAW_ER_AAC_LD\x10\x0f\"\x04\x08\x02\x10\x02\"\x04\x08\x04\x10\x04\"\x04\x08\x05\x10\x05\"\x04\x08\x06\x10\x06\"\x04\x08\x07\x10\x07\"\x04\x08\t\x10\t\"\x04\x08\n\x10\n*\x04\x46LAC*\x03\x41MR*\x06\x41MR_WB*\x08OGG_OPUS*\x16SPEEX_WITH_HEADER_BYTE*\tLINEAR32F*\nOGG_VORBIS2\xd0\x04\n\x0cSpeechToText\x12z\n\tRecognize\x12&.tinkoff.cloud.stt.v1.RecognizeRequest\x1a\'.tinkoff.cloud.stt.v1.RecognizeResponse\"\x1c\x82\xd3\xe4\x93\x02\x16\"\x11/v1/stt:recognize:\x01*\x12{\n\x12StreamingRecognize\x12/.tinkoff.cloud.stt.v1.StreamingRecognizeRequest\x1a\x30.tinkoff.cloud.stt.v1.StreamingRecognizeResponse(\x01\x30\x01\x12\x9b\x01\n\x14LongRunningRecognize\x12\x31.tinkoff.cloud.stt.v1.LongRunningRecognizeRequest\x1a\'.tinkoff.cloud.longrunning.v1.Operation\"\'\x82\xd3\xe4\x93\x02!\"\x1c/v1/stt:longrunningrecognize:\x01*\x12\xa8\x01\n\x17StreamingUnaryRecognize\x12\x34.tinkoff.cloud.stt.v1.StreamingUnaryRecognizeRequest\x1a\'.tinkoff.cloud.stt.v1.RecognizeResponse\",\x82\xd3\xe4\x93\x02&\"!/v1/stt:streaming_unary_recognize:\x01*(\x01\x42NZDgithub.com/Tinkoff/voicekit-examples/golang/pkg/tinkoff/cloud/stt/v1\xa2\x02\x05TVKSRb\x06proto3') _AUDIOENCODING = DESCRIPTOR.enum_types_by_name['AudioEncoding'] AudioEncoding = enum_type_wrapper.EnumTypeWrapper(_AUDIOENCODING) ENCODING_UNSPECIFIED = 0 LINEAR16 = 1 MULAW = 3 ALAW = 8 RAW_OPUS = 11 MPEG_AUDIO = 12 ADTS_AAC = 13 RAW_AAC_LC = 14 RAW_ER_AAC_LD = 15 _RECOGNITIONAUDIO = DESCRIPTOR.message_types_by_name['RecognitionAudio'] _SPEECHCONTEXTPHRASE = DESCRIPTOR.message_types_by_name['SpeechContextPhrase'] _SPEECHCONTEXT = DESCRIPTOR.message_types_by_name['SpeechContext'] _WORDINFO = DESCRIPTOR.message_types_by_name['WordInfo'] _VOICEACTIVITYDETECTIONCONFIG = DESCRIPTOR.message_types_by_name['VoiceActivityDetectionConfig'] _RECOGNITIONCONFIG = DESCRIPTOR.message_types_by_name['RecognitionConfig'] _RECOGNIZEREQUEST = DESCRIPTOR.message_types_by_name['RecognizeRequest'] _SPEECHRECOGNITIONALTERNATIVE = DESCRIPTOR.message_types_by_name['SpeechRecognitionAlternative'] _SPEECHSENTIMENTANALYSISRESULT = DESCRIPTOR.message_types_by_name['SpeechSentimentAnalysisResult'] _SPEECHGENDERIDENTIFICATIONRESULT = DESCRIPTOR.message_types_by_name['SpeechGenderIdentificationResult'] _SPEECHRECOGNITIONRESULT = DESCRIPTOR.message_types_by_name['SpeechRecognitionResult'] _RECOGNIZERESPONSE = DESCRIPTOR.message_types_by_name['RecognizeResponse'] _INTERIMRESULTSCONFIG = DESCRIPTOR.message_types_by_name['InterimResultsConfig'] _LONGRUNNINGRECOGNIZEREQUEST = DESCRIPTOR.message_types_by_name['LongRunningRecognizeRequest'] _STREAMINGRECOGNITIONCONFIG = DESCRIPTOR.message_types_by_name['StreamingRecognitionConfig'] _STREAMINGRECOGNIZEREQUEST = DESCRIPTOR.message_types_by_name['StreamingRecognizeRequest'] _STREAMINGRECOGNITIONRESULT = DESCRIPTOR.message_types_by_name['StreamingRecognitionResult'] _STREAMINGRECOGNIZERESPONSE = DESCRIPTOR.message_types_by_name['StreamingRecognizeResponse'] _STREAMINGUNARYRECOGNIZEREQUEST = DESCRIPTOR.message_types_by_name['StreamingUnaryRecognizeRequest'] RecognitionAudio = _reflection.GeneratedProtocolMessageType('RecognitionAudio', (_message.Message,), { 'DESCRIPTOR' : _RECOGNITIONAUDIO, '__module__' : 'tinkoff.cloud.stt.v1.stt_pb2' # @@protoc_insertion_point(class_scope:tinkoff.cloud.stt.v1.RecognitionAudio) }) _sym_db.RegisterMessage(RecognitionAudio) SpeechContextPhrase = _reflection.GeneratedProtocolMessageType('SpeechContextPhrase', (_message.Message,), { 'DESCRIPTOR' : _SPEECHCONTEXTPHRASE, '__module__' : 'tinkoff.cloud.stt.v1.stt_pb2' # @@protoc_insertion_point(class_scope:tinkoff.cloud.stt.v1.SpeechContextPhrase) }) _sym_db.RegisterMessage(SpeechContextPhrase) SpeechContext = _reflection.GeneratedProtocolMessageType('SpeechContext', (_message.Message,), { 'DESCRIPTOR' : _SPEECHCONTEXT, '__module__' : 'tinkoff.cloud.stt.v1.stt_pb2' # @@protoc_insertion_point(class_scope:tinkoff.cloud.stt.v1.SpeechContext) }) _sym_db.RegisterMessage(SpeechContext) WordInfo = _reflection.GeneratedProtocolMessageType('WordInfo', (_message.Message,), { 'DESCRIPTOR' : _WORDINFO, '__module__' : 'tinkoff.cloud.stt.v1.stt_pb2' # @@protoc_insertion_point(class_scope:tinkoff.cloud.stt.v1.WordInfo) }) _sym_db.RegisterMessage(WordInfo) VoiceActivityDetectionConfig = _reflection.GeneratedProtocolMessageType('VoiceActivityDetectionConfig', (_message.Message,), { 'DESCRIPTOR' : _VOICEACTIVITYDETECTIONCONFIG, '__module__' : 'tinkoff.cloud.stt.v1.stt_pb2' # @@protoc_insertion_point(class_scope:tinkoff.cloud.stt.v1.VoiceActivityDetectionConfig) }) _sym_db.RegisterMessage(VoiceActivityDetectionConfig) RecognitionConfig = _reflection.GeneratedProtocolMessageType('RecognitionConfig', (_message.Message,), { 'DESCRIPTOR' : _RECOGNITIONCONFIG, '__module__' : 'tinkoff.cloud.stt.v1.stt_pb2' # @@protoc_insertion_point(class_scope:tinkoff.cloud.stt.v1.RecognitionConfig) }) _sym_db.RegisterMessage(RecognitionConfig) RecognizeRequest = _reflection.GeneratedProtocolMessageType('RecognizeRequest', (_message.Message,), { 'DESCRIPTOR' : _RECOGNIZEREQUEST, '__module__' : 'tinkoff.cloud.stt.v1.stt_pb2' # @@protoc_insertion_point(class_scope:tinkoff.cloud.stt.v1.RecognizeRequest) }) _sym_db.RegisterMessage(RecognizeRequest) SpeechRecognitionAlternative = _reflection.GeneratedProtocolMessageType('SpeechRecognitionAlternative', (_message.Message,), { 'DESCRIPTOR' : _SPEECHRECOGNITIONALTERNATIVE, '__module__' : 'tinkoff.cloud.stt.v1.stt_pb2' # @@protoc_insertion_point(class_scope:tinkoff.cloud.stt.v1.SpeechRecognitionAlternative) }) _sym_db.RegisterMessage(SpeechRecognitionAlternative) SpeechSentimentAnalysisResult = _reflection.GeneratedProtocolMessageType('SpeechSentimentAnalysisResult', (_message.Message,), { 'DESCRIPTOR' : _SPEECHSENTIMENTANALYSISRESULT, '__module__' : 'tinkoff.cloud.stt.v1.stt_pb2' # @@protoc_insertion_point(class_scope:tinkoff.cloud.stt.v1.SpeechSentimentAnalysisResult) }) _sym_db.RegisterMessage(SpeechSentimentAnalysisResult) SpeechGenderIdentificationResult = _reflection.GeneratedProtocolMessageType('SpeechGenderIdentificationResult', (_message.Message,), { 'DESCRIPTOR' : _SPEECHGENDERIDENTIFICATIONRESULT, '__module__' : 'tinkoff.cloud.stt.v1.stt_pb2' # @@protoc_insertion_point(class_scope:tinkoff.cloud.stt.v1.SpeechGenderIdentificationResult) }) _sym_db.RegisterMessage(SpeechGenderIdentificationResult) SpeechRecognitionResult = _reflection.GeneratedProtocolMessageType('SpeechRecognitionResult', (_message.Message,), { 'DESCRIPTOR' : _SPEECHRECOGNITIONRESULT, '__module__' : 'tinkoff.cloud.stt.v1.stt_pb2' # @@protoc_insertion_point(class_scope:tinkoff.cloud.stt.v1.SpeechRecognitionResult) }) _sym_db.RegisterMessage(SpeechRecognitionResult) RecognizeResponse = _reflection.GeneratedProtocolMessageType('RecognizeResponse', (_message.Message,), { 'DESCRIPTOR' : _RECOGNIZERESPONSE, '__module__' : 'tinkoff.cloud.stt.v1.stt_pb2' # @@protoc_insertion_point(class_scope:tinkoff.cloud.stt.v1.RecognizeResponse) }) _sym_db.RegisterMessage(RecognizeResponse) InterimResultsConfig = _reflection.GeneratedProtocolMessageType('InterimResultsConfig', (_message.Message,), { 'DESCRIPTOR' : _INTERIMRESULTSCONFIG, '__module__' : 'tinkoff.cloud.stt.v1.stt_pb2' # @@protoc_insertion_point(class_scope:tinkoff.cloud.stt.v1.InterimResultsConfig) }) _sym_db.RegisterMessage(InterimResultsConfig) LongRunningRecognizeRequest = _reflection.GeneratedProtocolMessageType('LongRunningRecognizeRequest', (_message.Message,), { 'DESCRIPTOR' : _LONGRUNNINGRECOGNIZEREQUEST, '__module__' : 'tinkoff.cloud.stt.v1.stt_pb2' # @@protoc_insertion_point(class_scope:tinkoff.cloud.stt.v1.LongRunningRecognizeRequest) }) _sym_db.RegisterMessage(LongRunningRecognizeRequest) StreamingRecognitionConfig = _reflection.GeneratedProtocolMessageType('StreamingRecognitionConfig', (_message.Message,), { 'DESCRIPTOR' : _STREAMINGRECOGNITIONCONFIG, '__module__' : 'tinkoff.cloud.stt.v1.stt_pb2' # @@protoc_insertion_point(class_scope:tinkoff.cloud.stt.v1.StreamingRecognitionConfig) }) _sym_db.RegisterMessage(StreamingRecognitionConfig) StreamingRecognizeRequest = _reflection.GeneratedProtocolMessageType('StreamingRecognizeRequest', (_message.Message,), { 'DESCRIPTOR' : _STREAMINGRECOGNIZEREQUEST, '__module__' : 'tinkoff.cloud.stt.v1.stt_pb2' # @@protoc_insertion_point(class_scope:tinkoff.cloud.stt.v1.StreamingRecognizeRequest) }) _sym_db.RegisterMessage(StreamingRecognizeRequest) StreamingRecognitionResult = _reflection.GeneratedProtocolMessageType('StreamingRecognitionResult', (_message.Message,), { 'DESCRIPTOR' : _STREAMINGRECOGNITIONRESULT, '__module__' : 'tinkoff.cloud.stt.v1.stt_pb2' # @@protoc_insertion_point(class_scope:tinkoff.cloud.stt.v1.StreamingRecognitionResult) }) _sym_db.RegisterMessage(StreamingRecognitionResult) StreamingRecognizeResponse = _reflection.GeneratedProtocolMessageType('StreamingRecognizeResponse', (_message.Message,), { 'DESCRIPTOR' : _STREAMINGRECOGNIZERESPONSE, '__module__' : 'tinkoff.cloud.stt.v1.stt_pb2' # @@protoc_insertion_point(class_scope:tinkoff.cloud.stt.v1.StreamingRecognizeResponse) }) _sym_db.RegisterMessage(StreamingRecognizeResponse) StreamingUnaryRecognizeRequest = _reflection.GeneratedProtocolMessageType('StreamingUnaryRecognizeRequest', (_message.Message,), { 'DESCRIPTOR' : _STREAMINGUNARYRECOGNIZEREQUEST, '__module__' : 'tinkoff.cloud.stt.v1.stt_pb2' # @@protoc_insertion_point(class_scope:tinkoff.cloud.stt.v1.StreamingUnaryRecognizeRequest) }) _sym_db.RegisterMessage(StreamingUnaryRecognizeRequest) _SPEECHTOTEXT = DESCRIPTOR.services_by_name['SpeechToText'] if _descriptor._USE_C_DESCRIPTORS == False: DESCRIPTOR._options = None DESCRIPTOR._serialized_options = b'ZDgithub.com/Tinkoff/voicekit-examples/golang/pkg/tinkoff/cloud/stt/v1\242\002\005TVKSR' _SPEECHTOTEXT.methods_by_name['Recognize']._options = None _SPEECHTOTEXT.methods_by_name['Recognize']._serialized_options = b'\202\323\344\223\002\026\"\021/v1/stt:recognize:\001*' _SPEECHTOTEXT.methods_by_name['LongRunningRecognize']._options = None _SPEECHTOTEXT.methods_by_name['LongRunningRecognize']._serialized_options = b'\202\323\344\223\002!\"\034/v1/stt:longrunningrecognize:\001*' _SPEECHTOTEXT.methods_by_name['StreamingUnaryRecognize']._options = None _SPEECHTOTEXT.methods_by_name['StreamingUnaryRecognize']._serialized_options = b'\202\323\344\223\002&\"!/v1/stt:streaming_unary_recognize:\001*' _AUDIOENCODING._serialized_start=3185 _AUDIOENCODING._serialized_end=3458 _RECOGNITIONAUDIO._serialized_start=166 _RECOGNITIONAUDIO._serialized_end=234 _SPEECHCONTEXTPHRASE._serialized_start=236 _SPEECHCONTEXTPHRASE._serialized_end=286 _SPEECHCONTEXT._serialized_start=288 _SPEECHCONTEXT._serialized_end=375 _WORDINFO._serialized_start=378 _WORDINFO._serialized_end=514 _VOICEACTIVITYDETECTIONCONFIG._serialized_start=517 _VOICEACTIVITYDETECTIONCONFIG._serialized_end=697 _RECOGNITIONCONFIG._serialized_start=700 _RECOGNITIONCONFIG._serialized_end=1303 _RECOGNIZEREQUEST._serialized_start=1306 _RECOGNIZEREQUEST._serialized_end=1436 _SPEECHRECOGNITIONALTERNATIVE._serialized_start=1438 _SPEECHRECOGNITIONALTERNATIVE._serialized_end=1555 _SPEECHSENTIMENTANALYSISRESULT._serialized_start=1557 _SPEECHSENTIMENTANALYSISRESULT._serialized_end=1651 _SPEECHGENDERIDENTIFICATIONRESULT._serialized_start=1653 _SPEECHGENDERIDENTIFICATIONRESULT._serialized_end=1729 _SPEECHRECOGNITIONRESULT._serialized_start=1732 _SPEECHRECOGNITIONRESULT._serialized_end=2122 _RECOGNIZERESPONSE._serialized_start=2124 _RECOGNIZERESPONSE._serialized_end=2207 _INTERIMRESULTSCONFIG._serialized_start=2209 _INTERIMRESULTSCONFIG._serialized_end=2281 _LONGRUNNINGRECOGNIZEREQUEST._serialized_start=2284 _LONGRUNNINGRECOGNIZEREQUEST._serialized_end=2440 _STREAMINGRECOGNITIONCONFIG._serialized_start=2443 _STREAMINGRECOGNITIONCONFIG._serialized_end=2630 _STREAMINGRECOGNIZEREQUEST._serialized_start=2633 _STREAMINGRECOGNIZEREQUEST._serialized_end=2784 _STREAMINGRECOGNITIONRESULT._serialized_start=2787 _STREAMINGRECOGNITIONRESULT._serialized_end=2927 _STREAMINGRECOGNIZERESPONSE._serialized_start=2929 _STREAMINGRECOGNIZERESPONSE._serialized_end=3036 _STREAMINGUNARYRECOGNIZEREQUEST._serialized_start=3039 _STREAMINGUNARYRECOGNIZEREQUEST._serialized_end=3182 _SPEECHTOTEXT._serialized_start=3461 _SPEECHTOTEXT._serialized_end=4053 # @@protoc_insertion_point(module_scope)
0
0
0
3c1857c084ab7406d5713284152cbbf14f15e691
2,504
py
Python
ml4vision/ml/engines/detection_engine.py
ml4vision/ml4vision-py
5c8da0a0a099d70b390d5875ac08fbabe01372f1
[ "MIT" ]
null
null
null
ml4vision/ml/engines/detection_engine.py
ml4vision/ml4vision-py
5c8da0a0a099d70b390d5875ac08fbabe01372f1
[ "MIT" ]
null
null
null
ml4vision/ml/engines/detection_engine.py
ml4vision/ml4vision-py
5c8da0a0a099d70b390d5875ac08fbabe01372f1
[ "MIT" ]
null
null
null
from .engine import Engine from ..utils.collate import box_collate_fn from ..utils.visualizer import ObjectDetectionVisualizer from ..utils.centernet.parse_detections import parse_detections, parse_batch_detections from ..utils.ap_metrics import APMeter import torch import os import json
34.30137
115
0.653754
from .engine import Engine from ..utils.collate import box_collate_fn from ..utils.visualizer import ObjectDetectionVisualizer from ..utils.centernet.parse_detections import parse_detections, parse_batch_detections from ..utils.ap_metrics import APMeter import torch import os import json class DetectionEngine(Engine): def __init__(self, *args, **kwargs): super().__init__(*args, **kwargs) # set visualizer self.visualizer = ObjectDetectionVisualizer() # set custom collate function self.train_dataset_it.collate_fn = box_collate_fn self.val_dataset_it.collate_fn = box_collate_fn def reset_metrics(self): self.ap_meter = APMeter() def compute_metrics(self, pred, sample): pred_boxes, pred_scores = parse_batch_detections(pred, threshold=0.1) for pred, scores, gt in zip(pred_boxes, pred_scores, sample['boxes']): self.ap_meter.add_detections(pred, scores, gt) def get_metrics(self): ap, ap_dict = self.ap_meter.get_ap() return { 'map': ap, 'working_point': ap_dict } def display(self, pred, sample): image = sample['image'][0] pred_boxes, _ = parse_detections(pred[0], threshold=0.1) gt_boxes = sample['boxes'][0] self.visualizer.display(image, pred_boxes.cpu(), gt_boxes) def forward(self, sample): images = sample['image'].to(self.device) heatmap = sample['heatmap'].to(self.device) scalemap = sample['scalemap'].to(self.device) classmap = sample['classmap'].to(self.device) pred = self.model(images) loss = self.loss_fn(pred, heatmap, scalemap, classmap) return pred, loss def trace_model(self): cfg = self.config # load best checkpoint model = self.model.to(torch.device('cpu')) state = torch.load(os.path.join(cfg.save_location, 'best_val_model.pth'), map_location=torch.device('cpu')) model.load_state_dict(state['model_state_dict'], strict=True) model.eval() traced_model = torch.jit.trace(model, torch.randn(1, 3, 512, 512)) traced_model.save(os.path.join(cfg.save_location, 'best_val_model.pt')) with open(os.path.join(cfg.save_location, 'metrics.json'), 'w') as f: json.dump(state['metrics'], f) with open(os.path.join(cfg.save_location, 'categories.json'), 'w') as f: json.dump(cfg.dataset_info['categories'], f)
1,993
9
212
098ad775b96835b594b952a0d399601e34c38200
118
py
Python
movies_front/wsgi.py
microstack/movies-front
432119a22f08c6a03f90089b2e47296822859957
[ "MIT" ]
null
null
null
movies_front/wsgi.py
microstack/movies-front
432119a22f08c6a03f90089b2e47296822859957
[ "MIT" ]
null
null
null
movies_front/wsgi.py
microstack/movies-front
432119a22f08c6a03f90089b2e47296822859957
[ "MIT" ]
null
null
null
import os from views import app if __name__ == "__main__": host = os.environ.get('HOST') app.run(host=host)
14.75
33
0.661017
import os from views import app if __name__ == "__main__": host = os.environ.get('HOST') app.run(host=host)
0
0
0
f536c2f6ef1a68d088de084db7796591fafa5eb4
1,270
py
Python
Book/chap5/Supporting Materials/MultPlotDemo.py
lorenghoh/pyman
9b4ddd52c5577fc85e2601ae3128f398f0eb673c
[ "CC0-1.0" ]
3
2020-04-30T19:50:11.000Z
2020-10-17T02:07:00.000Z
Book/chap5/Supporting Materials/MultPlotDemo.py
lorenghoh/pyman
9b4ddd52c5577fc85e2601ae3128f398f0eb673c
[ "CC0-1.0" ]
35
2020-04-21T04:25:31.000Z
2021-11-06T22:49:44.000Z
Book/chap5/Supporting Materials/MultPlotDemo.py
lorenghoh/pyman
9b4ddd52c5577fc85e2601ae3128f398f0eb673c
[ "CC0-1.0" ]
11
2020-04-21T04:33:48.000Z
2020-10-23T21:12:12.000Z
# Demonstrates the following: # plotting logarithmic axes # user-defined functions # "where" function, NumPy array conditional import numpy as np import matplotlib.pyplot as plt # Define the sinc function, with output for x=0 defined # as a special case to avoid division by zero # create arrays for plotting x = np.arange(0., 10., 0.1) y = np.exp(x) t = np.linspace(-10., 10., 100) z = s(t) # create a figure window fig = plt.figure(1, figsize=(9,8)) # subplot: linear plot of exponential ax1 = fig.add_subplot(2,2,1) ax1.plot(x, y) ax1.set_xlabel('time (ms)') ax1.set_ylabel('distance (mm)') ax1.set_title('exponential') # subplot: semi-log plot of exponential ax2 = fig.add_subplot(2,2,2) ax2.plot(x, y) ax2.set_yscale('log') ax2.set_xlabel('time (ms)') ax2.set_ylabel('distance (mm)') ax2.set_title('exponential') # subplot: wide subplot of sinc function ax3 = fig.add_subplot(2,1,2) ax3.plot(t, z, 'r') ax3.axhline(color='gray') ax3.axvline(color='gray') ax3.set_xlabel('angle (deg)') ax3.set_ylabel('electric field') ax3.set_title('sinc function') # Adjusts while space around plots to avoid collisions between subplots fig.tight_layout() plt.savefig("MultPlotDemo.pdf") plt.show()
23.518519
71
0.708661
# Demonstrates the following: # plotting logarithmic axes # user-defined functions # "where" function, NumPy array conditional import numpy as np import matplotlib.pyplot as plt # Define the sinc function, with output for x=0 defined # as a special case to avoid division by zero def s(x): a = np.where(x==0., 1., np.sin(x)/x) return a # create arrays for plotting x = np.arange(0., 10., 0.1) y = np.exp(x) t = np.linspace(-10., 10., 100) z = s(t) # create a figure window fig = plt.figure(1, figsize=(9,8)) # subplot: linear plot of exponential ax1 = fig.add_subplot(2,2,1) ax1.plot(x, y) ax1.set_xlabel('time (ms)') ax1.set_ylabel('distance (mm)') ax1.set_title('exponential') # subplot: semi-log plot of exponential ax2 = fig.add_subplot(2,2,2) ax2.plot(x, y) ax2.set_yscale('log') ax2.set_xlabel('time (ms)') ax2.set_ylabel('distance (mm)') ax2.set_title('exponential') # subplot: wide subplot of sinc function ax3 = fig.add_subplot(2,1,2) ax3.plot(t, z, 'r') ax3.axhline(color='gray') ax3.axvline(color='gray') ax3.set_xlabel('angle (deg)') ax3.set_ylabel('electric field') ax3.set_title('sinc function') # Adjusts while space around plots to avoid collisions between subplots fig.tight_layout() plt.savefig("MultPlotDemo.pdf") plt.show()
38
0
22