hexsha stringlengths 40 40 | size int64 5 2.06M | ext stringclasses 11 values | lang stringclasses 1 value | max_stars_repo_path stringlengths 3 251 | max_stars_repo_name stringlengths 4 130 | max_stars_repo_head_hexsha stringlengths 40 78 | max_stars_repo_licenses listlengths 1 10 | max_stars_count int64 1 191k ⌀ | 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 3 251 | max_issues_repo_name stringlengths 4 130 | 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 3 251 | max_forks_repo_name stringlengths 4 130 | 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.05M | avg_line_length float64 1 1.02M | max_line_length int64 3 1.04M | alphanum_fraction float64 0 1 |
|---|---|---|---|---|---|---|---|---|---|---|---|---|---|---|---|---|---|---|---|---|---|---|---|---|---|---|---|---|
f95e41290f52dc02f46f6b46f92ae4c07e63dc68 | 9,528 | py | Python | run.py | magechaP/passwordlocker2.0 | e0ae82aa650c4f1cd285f319ec16de38ba0670ea | [
"Unlicense",
"MIT"
] | null | null | null | run.py | magechaP/passwordlocker2.0 | e0ae82aa650c4f1cd285f319ec16de38ba0670ea | [
"Unlicense",
"MIT"
] | null | null | null | run.py | magechaP/passwordlocker2.0 | e0ae82aa650c4f1cd285f319ec16de38ba0670ea | [
"Unlicense",
"MIT"
] | null | null | null | #!/usr/bin/env python3.6
import random #importing random module
from user import User #importing class User
from credential import Credential #importing class Credential
def create_credential(username,accountname,password):
"""
create_credential function that creates an instance of the class credential
"""
new_credential = Credential(username,accountname,password)
return new_credential
def create_user(name, login_password):
"""
create_user function that creates an instance of the class user
"""
new_user = User(name,login_password)
return new_user
def saveCredential(credential):
"""
saveCredential function to save the credential created by the user
"""
credential.save_credential()
def saveUser(user):
"""
saveUser function to create a user account whenever a user
signs up with password locker
"""
user.save_user()
def deleteCredential(credential):
"""
deleteCredential function that helps user delete an existing credential
"""
credential.delete_credential()
def findCredential(account_name):
"""
findCredential function to search for a credential by accountname and
return all its details
"""
return Credential.find_accountname(account_name)
def credentialExists(account_name):
"""
credentialExists function to check whether a credential exists
and return True or False
"""
return Credential.credential_exists(account_name)
def displayCredentials():
"""
displayCredentials function to display the credentials currently saved
"""
return Credential.display_credentials()
def displayUser():
"""
displayUser function to display user details if user has an account
"""
return User.display_all()
def copyUsername(account_name):
"""
copyUsername function that enables user to copy their user name to their
machine clip board
"""
return Credential.copy_username(account_name)
def copyAccountname(account_name):
"""
copyAccountname function that enables user to copy their
accountname to the machine clipboard
"""
return Credential.copy_accountname(account_name)
def copyPassword(account_name):
"""
copyPassword function that enables user to copy their password
to the machine clipboard
"""
return Credential.copy_password(account_name)
if __name__ == '__main__':
main()
| 46.478049 | 260 | 0.524244 |
f96072c2c69a90c36b742be295db7b6791bf37ec | 1,173 | py | Python | src/Support/Scripts/AlignOperators.py | bobthecow/ManipulateCoda | 5a0e03fb535cfc623070ddd44a9e09d34d313193 | [
"MIT"
] | 5 | 2015-01-05T21:44:18.000Z | 2017-09-08T09:31:44.000Z | src/Support/Scripts/AlignOperators.py | bobthecow/ManipulateCoda | 5a0e03fb535cfc623070ddd44a9e09d34d313193 | [
"MIT"
] | 3 | 2015-01-06T15:21:58.000Z | 2019-04-09T12:03:13.000Z | src/Support/Scripts/AlignOperators.py | bobthecow/ManipulateCoda | 5a0e03fb535cfc623070ddd44a9e09d34d313193 | [
"MIT"
] | null | null | null | '''Line up operators...'''
import cp_actions as cp
import re
def act(controller, bundle, options):
'''
Required action method
'''
context = cp.get_context(controller)
line_ending = cp.get_line_ending(context)
lines, range = cp.lines_and_range(context)
newlines = line_ending.join(balance_operators(lines.split(line_ending)))
cp.insert_text_and_select(context, newlines, range, cp.new_range(range.location, len(newlines)))
| 27.27907 | 146 | 0.546462 |
f9635ddcc69eb4603c2a017bb384ecbb61ddeafe | 1,333 | py | Python | continuous-variables/literature-code-in-python/random_reaction_gen.py | YANGZ001/OrganicChem-LabMate-AI | fb826d85dd852aab987b9bef6856d8da6a4bd9be | [
"MIT"
] | null | null | null | continuous-variables/literature-code-in-python/random_reaction_gen.py | YANGZ001/OrganicChem-LabMate-AI | fb826d85dd852aab987b9bef6856d8da6a4bd9be | [
"MIT"
] | null | null | null | continuous-variables/literature-code-in-python/random_reaction_gen.py | YANGZ001/OrganicChem-LabMate-AI | fb826d85dd852aab987b9bef6856d8da6a4bd9be | [
"MIT"
] | null | null | null | import numpy as np
import pandas as pd
import itertools
'''
Section below creates lists for your reaction parameters. Change names of lists where appropriate
'''
#For bigger lists use np.arange(min_value, max_value, step)
Pyridine = [0.1, 0.2, 0.3] # in mmol
Aldehyde = [0.1, 0.2, 0.3] # in mmol
Isocyanide = [0.1, 0.2, 0.3] # in mmol
Temperature = [10, 20, 40, 60, 80] # in C
Solvent = [0.1, 0.25, 0.5, 1, 1.5] # in mL
Catalyst = [0, 1, 2, 3, 4, 5, 7.5, 10] # in mol%
Time = [5, 10, 15, 30, 60] # in minutes
'''
The following lines create all combos possible for the values listed above and saves as text file. Change names where appropriate.
'''
combinations = list(itertools.product(Pyridine, Aldehyde, Isocyanide, Temperature, Solvent, Catalyst, Time))
df = pd.DataFrame(combinations)
df.to_csv('all_combos716.txt', sep = '\t', header = ['Pyridine', 'Aldehyde', 'Isocyanide', 'Temperature', 'Solvent', 'Catalyst', 'Time'])
'''
Below, 10 random reaction are selected from all possible combinations. The reactions are stored in a text file. Change names of header as appropriate.
'''
random_data = df.sample(n=10, random_state=1)
df_random_data = pd.DataFrame(random_data)
df_random_data.to_csv('train_data716.txt', sep= '\t', header = ['Pyridine', 'Aldehyde', 'Isocyanide', 'Temperature', 'Solvent', 'Catalyst', 'Time'])
| 37.027778 | 150 | 0.701425 |
f96819f7fca3841f9dba660989413c0f8440f951 | 183 | py | Python | agent/tandem/agent/models/connection_state.py | geoffxy/tandem | 81e76f675634f1b42c8c3070c73443f3f68f8624 | [
"Apache-2.0"
] | 732 | 2018-03-11T03:35:17.000Z | 2022-01-06T12:22:03.000Z | agent/tandem/agent/models/connection_state.py | geoffxy/tandem | 81e76f675634f1b42c8c3070c73443f3f68f8624 | [
"Apache-2.0"
] | 21 | 2018-03-11T02:28:22.000Z | 2020-08-30T15:36:40.000Z | plugin/tandem_lib/agent/tandem/agent/models/connection_state.py | typeintandem/vim | e076a9954d73ccb60cd6828e53adf8da76462fc6 | [
"Apache-2.0"
] | 24 | 2018-03-14T05:37:17.000Z | 2022-01-18T14:44:42.000Z | import enum
| 16.636364 | 33 | 0.617486 |
f9686a6e64b3ada450c52aa9db27ba394fa0f073 | 2,241 | py | Python | mechroutines/es/newts/_fs.py | keceli/mechdriver | 978994ba5c77b6df00078b639c4482dacf269440 | [
"Apache-2.0"
] | null | null | null | mechroutines/es/newts/_fs.py | keceli/mechdriver | 978994ba5c77b6df00078b639c4482dacf269440 | [
"Apache-2.0"
] | null | null | null | mechroutines/es/newts/_fs.py | keceli/mechdriver | 978994ba5c77b6df00078b639c4482dacf269440 | [
"Apache-2.0"
] | 8 | 2019-12-18T20:09:46.000Z | 2020-11-14T16:37:28.000Z | """ rpath task function
"""
from mechlib import filesys
from mechlib.filesys import build_fs
from mechlib.filesys import root_locs
def rpath_fs(ts_dct, tsname,
mod_ini_thy_info,
es_keyword_dct,
run_prefix, save_prefix):
""" reaction path filesystem
"""
# Set up coordinate name
rxn_coord = es_keyword_dct.get('rxncoord')
# Get the zma and ts locs
zma_locs = (ts_dct['zma_idx'],)
ts_locs = (int(tsname.split('_')[-1]),)
# Build filesys object down to TS FS
ts_fs = build_fs(
run_prefix, save_prefix, 'TRANSITION STATE',
thy_locs=mod_ini_thy_info[1:],
**root_locs(ts_dct, saddle=True))
ini_ts_run_fs, ini_ts_save_fs = ts_fs
# generate fs
if rxn_coord == 'irc':
# Try and locate a minimum-energy conformer
cnf_fs = build_fs(
run_prefix, save_prefix, 'CONFORMER',
thy_locs=mod_ini_thy_info[1:],
**root_locs(ts_dct, saddle=True, name=tsname))
ini_cnf_run_fs, ini_cnf_save_fs = cnf_fs
ini_loc_info = filesys.mincnf.min_energy_conformer_locators(
ini_cnf_save_fs, mod_ini_thy_info)
ini_min_locs, ini_pfx_save_path = ini_loc_info
if any(ini_min_locs):
# Run IRC from saddle point minimum-energy conformer
ini_pfx_run_path = ini_cnf_run_fs[-1].path(ini_min_locs)
ini_pfx_save_path = ini_cnf_save_fs[-1].path(ini_min_locs)
scn_alg = 'irc-sadpt'
else:
# Run IRC from series of points {Rmax, Rmax-1, ...}
ini_pfx_run_path = ini_ts_run_fs[-1].path(ts_locs)
ini_pfx_save_path = ini_ts_save_fs[-1].path(ts_locs)
scn_alg = 'irc-rmax'
else:
# Run a scan along the requested reaction coordinates
# Have an auto option that just selects the coordinate?
ini_pfx_run_path = ini_ts_run_fs[-1].path(ts_locs)
ini_pfx_save_path = ini_ts_save_fs[-1].path(ts_locs)
scn_alg = 'drp'
# Set up the scan filesystem objects using the predefined prefix
scn_fs = build_fs(
ini_pfx_run_path, ini_pfx_save_path, 'SCAN',
zma_locs=zma_locs)
return scn_alg, scn_fs, cnf_fs, ini_min_locs
| 33.954545 | 70 | 0.646586 |
f968be6f1cca8629346c90e2699c898d9571ac20 | 1,361 | py | Python | computation/listallfiles.py | thirschbuechler/didactic-barnacles | 88d0a2b572aacb2cb45e68bb4f05fa5273224439 | [
"MIT"
] | null | null | null | computation/listallfiles.py | thirschbuechler/didactic-barnacles | 88d0a2b572aacb2cb45e68bb4f05fa5273224439 | [
"MIT"
] | null | null | null | computation/listallfiles.py | thirschbuechler/didactic-barnacles | 88d0a2b572aacb2cb45e68bb4f05fa5273224439 | [
"MIT"
] | null | null | null | # -*- coding: utf-8 -*-
"""
Created on Tue Sep 29 14:38:54 2020
@author: https://stackoverflow.com/questions/18262293/how-to-open-every-file-in-a-folder
"""
import os #os module imported here
location = os.getcwd() # get present working directory location here
counter = 0 #keep a count of all files found
csvfiles = [] #list to store all csv files found at location
filebeginwithhello = [] # list to keep all files that begin with 'hello'
otherfiles = [] #list to keep any other file that do not match the criteria
for file in os.listdir(location):
try:
if file.endswith(".csv"):
print( "csv file found:\t", file)
csvfiles.append(str(file))
counter = counter+1
elif file.endswith(".csv"): #because some files may start with hello and also be a csv file
print( "csv file found:\t", file)
csvfiles.append(str(file))
counter = counter+1
elif file.startswith("hello"):
print( "hello files found: \t", file)
filebeginwithhello.append(file)
counter = counter+1
else:
otherfiles.append(file)
print(file)
counter = counter+1
except Exception as e:
raise e
print("No files found here!")
print("Total files found:\t", counter) | 34.897436 | 100 | 0.603968 |
f96a73f7ebbc6d2b474f86a30e29cb3233db9724 | 5,317 | py | Python | rootfs/api/apps_extra/social_core/actions.py | jianxiaoguo/controller | 8cc1e11601e5725e583f0fa82cdb2c10872ca485 | [
"Apache-2.0"
] | null | null | null | rootfs/api/apps_extra/social_core/actions.py | jianxiaoguo/controller | 8cc1e11601e5725e583f0fa82cdb2c10872ca485 | [
"Apache-2.0"
] | 19 | 2020-07-30T06:31:29.000Z | 2022-03-14T07:33:44.000Z | rootfs/api/apps_extra/social_core/actions.py | jianxiaoguo/controller | 8cc1e11601e5725e583f0fa82cdb2c10872ca485 | [
"Apache-2.0"
] | 9 | 2020-07-30T02:50:12.000Z | 2020-12-11T06:44:19.000Z | from urllib.parse import quote
from social_core.utils import sanitize_redirect, user_is_authenticated, \
user_is_active, partial_pipeline_data, setting_url
| 42.536 | 86 | 0.618018 |
f96c7c015c3ad71d48f4085619b3a3dcae5954cc | 1,667 | py | Python | Part_1/src/manual_split_test/make_paired_cases.py | Bhaskers-Blu-Org2/datascience4managers | 2410182fe6913a8c986d2f28f5db6850cddb75f2 | [
"MIT"
] | 8 | 2019-11-24T08:23:12.000Z | 2021-01-19T02:48:46.000Z | Part_1/src/manual_split_test/make_paired_cases.py | Bhaskers-Blu-Org2/datascience4managers | 2410182fe6913a8c986d2f28f5db6850cddb75f2 | [
"MIT"
] | 1 | 2021-06-02T02:05:15.000Z | 2021-06-02T02:05:15.000Z | Part_1/src/manual_split_test/make_paired_cases.py | microsoft/datascience4managers | 7c332bf23a85f281237c841e1981ab21ed4ca072 | [
"MIT"
] | 9 | 2019-10-29T18:45:36.000Z | 2021-03-27T07:23:13.000Z | #!/usr/bin/python
# Oct 2019 JMA
# make_samples.py Use the splits_aggregator module to create samples
'''
Write a short description of what the program does here.
Usage:
$ ./make_samples.py [-v] [-d ROOT_DIR] [-c pair_cnt]
-v verbose output
-d data directory to read from
-c number of randomly paired cases to generate
'''
import os, sys
import glob
import pprint
import re
import time
from pathlib import Path
import pyarrow
import pandas as pd
import splits_aggregator as sa
### config constants
VERBOSE = False
ROOT_DIR = Path('D:/OneDrive - Microsoft/data/20news')
PAIR_CNT = 1
########################################################################
###############################################################################
def main(input_dir, pair_cnt):
cs = sa.BinaryComparisons(input_dir)
pairs_df = cs.random_pairs(pair_cnt)
if VERBOSE:
print("Pairs: ", pairs_df.shape)
cs.embed_in_excel(pairs_df)
########################################################################
if __name__ == '__main__':
if '-v' in sys.argv:
k = sys.argv.index('-v')
VERBOSE = True
## Inputs
if '-d' in sys.argv:
d = sys.argv.index('-d')
ROOT_DIR = Path(sys.argv[d+1])
# else:
if '-c' in sys.argv:
g = sys.argv.index('-c')
PAIR_CNT= int(sys.argv[g+1])
main(ROOT_DIR, PAIR_CNT)
print(sys.argv, "\nDone in ",
'%5.3f' % time.process_time(),
" secs! At UTC: ",
time.asctime(time.gmtime()), file=sys.stderr) | 24.880597 | 80 | 0.515297 |
f96ca18e0cac4358cc1ae51e86890db7bc505477 | 1,550 | py | Python | src/pySUMOQt/Designer/css_rc.py | pySUMO/pysumo | 889969f94bd45e2b67e25ff46452378351ca5186 | [
"BSD-2-Clause"
] | 7 | 2015-08-21T17:17:35.000Z | 2021-03-02T21:40:00.000Z | src/pySUMOQt/Designer/css_rc.py | pySUMO/pysumo | 889969f94bd45e2b67e25ff46452378351ca5186 | [
"BSD-2-Clause"
] | 2 | 2015-04-14T12:40:37.000Z | 2015-04-14T12:44:03.000Z | src/pySUMOQt/Designer/css_rc.py | pySUMO/pysumo | 889969f94bd45e2b67e25ff46452378351ca5186 | [
"BSD-2-Clause"
] | null | null | null | # -*- coding: utf-8 -*-
# Resource object code
#
# Created: Di. Feb 3 12:11:53 2015
# by: The Resource Compiler for PySide (Qt v4.8.4)
#
# WARNING! All changes made in this file will be lost!
from PySide import QtCore
qt_resource_data = b"\x00\x00\x00\x00\x00\x00\x00\x00\x00\x00\x00\x00\x00\x00\x009QStatusBar::item \x0a{ \x0a\x09border-left: 1px solid #AAAAAA;\x0a} \x0a\x00\x00\x00\x00"
qt_resource_name = b"\x00\x03\x00\x00j\xa3\x00c\x00s\x00s\x00\x0e\x0bq\xe6\xc3\x00M\x00a\x00i\x00n\x00W\x00i\x00n\x00d\x00o\x00w\x00.\x00c\x00s\x00s\x00\x0b\x08\x22\xc1\xc3\x00M\x00e\x00n\x00u\x00b\x00a\x00r\x00.\x00c\x00s\x00s\x00\x10\x05[\x0fC\x00P\x00y\x00S\x00u\x00m\x00o\x00W\x00i\x00d\x00g\x00e\x00t\x00.\x00c\x00s\x00s\x00\x0d\x0d\xd42\xe3\x00S\x00t\x00a\x00t\x00u\x00s\x00b\x00a\x00r\x00.\x00c\x00s\x00s\x00\x0b\x083\x86\xe3\x00T\x00o\x00o\x00l\x00b\x00a\x00r\x00.\x00c\x00s\x00s"
qt_resource_struct = b"\x00\x00\x00\x00\x00\x02\x00\x00\x00\x01\x00\x00\x00\x01\x00\x00\x00\x00\x00\x02\x00\x00\x00\x05\x00\x00\x00\x02\x00\x00\x00J\x00\x00\x00\x00\x00\x01\x00\x00\x00\x08\x00\x00\x00.\x00\x00\x00\x00\x00\x01\x00\x00\x00\x04\x00\x00\x00\x90\x00\x00\x00\x00\x00\x01\x00\x00\x00I\x00\x00\x00\x0c\x00\x00\x00\x00\x00\x01\x00\x00\x00\x00\x00\x00\x00p\x00\x00\x00\x00\x00\x01\x00\x00\x00\x0c"
qInitResources()
| 70.454545 | 488 | 0.75871 |
f96e0469991c8e15ab4a23bec3525036f33b7b33 | 12,081 | py | Python | tests/test_core.py | sobamchan/lineflow | 708a875c090b7df48c9eca3f630915a9c6e5bbd6 | [
"MIT"
] | null | null | null | tests/test_core.py | sobamchan/lineflow | 708a875c090b7df48c9eca3f630915a9c6e5bbd6 | [
"MIT"
] | null | null | null | tests/test_core.py | sobamchan/lineflow | 708a875c090b7df48c9eca3f630915a9c6e5bbd6 | [
"MIT"
] | null | null | null | from unittest import TestCase
from unittest.mock import patch, Mock
import lineflow
from lineflow import Dataset
from lineflow.core import ConcatDataset, ZipDataset
from lineflow.core import RandomAccessConcat, RandomAccessZip
| 35.017391 | 92 | 0.632067 |
f96ed484656fab8971f82e7e48fafd3dcd557e30 | 2,393 | py | Python | aerosandbox/tools/miscellaneous.py | SzymonSzyszko/AeroSandbox | d4084899b665f735c1ec218282b2e4aee08eacff | [
"MIT"
] | null | null | null | aerosandbox/tools/miscellaneous.py | SzymonSzyszko/AeroSandbox | d4084899b665f735c1ec218282b2e4aee08eacff | [
"MIT"
] | null | null | null | aerosandbox/tools/miscellaneous.py | SzymonSzyszko/AeroSandbox | d4084899b665f735c1ec218282b2e4aee08eacff | [
"MIT"
] | null | null | null | import math
import numpy as np
def eng_string(x, format='%.3g', si=True):
'''
Taken from: https://stackoverflow.com/questions/17973278/python-decimal-engineering-notation-for-mili-10e-3-and-micro-10e-6/40691220
Returns float/int value <x> formatted in a simplified engineering format -
using an exponent that is a multiple of 3.
format: printf-style string used to format the value before the exponent.
si: if true, use SI suffix for exponent, e.g. k instead of e3, n instead of
e-9 etc.
E.g. with format='%.2f':
1.23e-08 => 12.30e-9
123 => 123.00
1230.0 => 1.23e3
-1230000.0 => -1.23e6
and with si=True:
1230.0 => 1.23k
-1230000.0 => -1.23M
'''
sign = ''
if x < 0:
x = -x
sign = '-'
exp = int(math.floor(math.log10(x)))
exp3 = exp - (exp % 3)
x3 = x / (10 ** exp3)
if si and exp3 >= -24 and exp3 <= 24 and exp3 != 0:
exp3_text = 'yzafpnum kMGTPEZY'[(exp3 + 24) // 3]
elif exp3 == 0:
exp3_text = ''
else:
exp3_text = 'e%s' % exp3
return ('%s' + format + '%s') % (sign, x3, exp3_text)
remove_nans = lambda x: x[~np.isnan(x)]
import sys
import os
from contextlib import contextmanager
| 28.488095 | 136 | 0.600501 |
f96ffcf56dbd7255308f0925c87a38f826c98376 | 595 | py | Python | web_app/routes/Directory.py | AmyBeisel/BW_Med_Cabinet | 3cce7ff14f2324cdb81a7a1ea313037a6e3eead6 | [
"MIT"
] | null | null | null | web_app/routes/Directory.py | AmyBeisel/BW_Med_Cabinet | 3cce7ff14f2324cdb81a7a1ea313037a6e3eead6 | [
"MIT"
] | null | null | null | web_app/routes/Directory.py | AmyBeisel/BW_Med_Cabinet | 3cce7ff14f2324cdb81a7a1ea313037a6e3eead6 | [
"MIT"
] | null | null | null | # Directory.py
# Import
from flask import Blueprint, render_template
# Make Blueprint for __init__.py
Directory = Blueprint("Directory", __name__)
# App Welcome Page
# Strain JSON Page
# Strain Table Page
| 17.5 | 168 | 0.734454 |
f97211763e2fc9e54ef976a18d06e39b22339ef9 | 567 | py | Python | saleor/product/migrations/0125_auto_20200916_1511.py | fairhopeweb/saleor | 9ac6c22652d46ba65a5b894da5f1ba5bec48c019 | [
"CC-BY-4.0"
] | 15,337 | 2015-01-12T02:11:52.000Z | 2021-10-05T19:19:29.000Z | saleor/product/migrations/0125_auto_20200916_1511.py | fairhopeweb/saleor | 9ac6c22652d46ba65a5b894da5f1ba5bec48c019 | [
"CC-BY-4.0"
] | 7,486 | 2015-02-11T10:52:13.000Z | 2021-10-06T09:37:15.000Z | saleor/product/migrations/0125_auto_20200916_1511.py | aminziadna/saleor | 2e78fb5bcf8b83a6278af02551a104cfa555a1fb | [
"CC-BY-4.0"
] | 5,864 | 2015-01-16T14:52:54.000Z | 2021-10-05T23:01:15.000Z | # Generated by Django 3.1.1 on 2020-09-16 15:11
from django.db import migrations, models
| 24.652174 | 80 | 0.59612 |
f974a1282e8728c135564243668674955a9e7d22 | 943 | py | Python | lintcode/NineChapters/03/binary-tree-level-order-traversal-ii.py | shootsoft/practice | 49f28c2e0240de61d00e4e0291b3c5edd930e345 | [
"Apache-2.0"
] | null | null | null | lintcode/NineChapters/03/binary-tree-level-order-traversal-ii.py | shootsoft/practice | 49f28c2e0240de61d00e4e0291b3c5edd930e345 | [
"Apache-2.0"
] | null | null | null | lintcode/NineChapters/03/binary-tree-level-order-traversal-ii.py | shootsoft/practice | 49f28c2e0240de61d00e4e0291b3c5edd930e345 | [
"Apache-2.0"
] | null | null | null | __author__ = 'yinjun'
"""
Definition of TreeNode:
class TreeNode:
def __init__(self, val):
this.val = val
this.left, this.right = None, None
"""
| 18.86 | 65 | 0.45175 |
f974a73c7d07887b66165d4b3f68128150448a37 | 530 | py | Python | setup.py | Moi-Teaching-Referral-Hospital/ERPNextMTRHModifications | 393cef3294d6b07f2c7ff21899c99a82276be43f | [
"MIT"
] | null | null | null | setup.py | Moi-Teaching-Referral-Hospital/ERPNextMTRHModifications | 393cef3294d6b07f2c7ff21899c99a82276be43f | [
"MIT"
] | 1 | 2021-01-09T20:00:38.000Z | 2021-01-09T20:00:38.000Z | setup.py | Moi-Teaching-Referral-Hospital/mtrh_dev | 367af3922d0fe0c19e35b0edd999dfc42f9a225b | [
"MIT"
] | 2 | 2020-07-28T22:22:04.000Z | 2020-08-16T16:12:56.000Z | # -*- coding: utf-8 -*-
from setuptools import setup, find_packages
with open('requirements.txt') as f:
install_requires = f.read().strip().split('\n')
# get version from __version__ variable in mtrh_dev/__init__.py
from mtrh_dev import __version__ as version
setup(
name='mtrh_dev',
version=version,
description='For all MTRH dev Frappe and ERPNext modifications',
author='MTRH',
author_email='erp@mtrh.go.ke',
packages=find_packages(),
zip_safe=False,
include_package_data=True,
install_requires=install_requires
)
| 25.238095 | 65 | 0.762264 |
f974ccb0279e3323702f280c06f3f6d71a27a8f5 | 23,062 | py | Python | tools/programController.py | brewpi-remix/uno-test | a153a5277bea2a8e58ee479792d6977f0beb853e | [
"MIT"
] | null | null | null | tools/programController.py | brewpi-remix/uno-test | a153a5277bea2a8e58ee479792d6977f0beb853e | [
"MIT"
] | null | null | null | tools/programController.py | brewpi-remix/uno-test | a153a5277bea2a8e58ee479792d6977f0beb853e | [
"MIT"
] | 1 | 2021-07-31T15:23:07.000Z | 2021-07-31T15:23:07.000Z | #!/usr/bin/env python3
import subprocess as sub
import time
import simplejson as json
import os
from sys import stderr
import subprocess
import platform
import sys
import stat
import pwd
import grp
import BrewPiUtil as util
import brewpiVersion
import expandLogMessage
from packaging import version
from MigrateSettings import MigrateSettings
from ConvertBrewPiDevice import ConvertBrewPiDevice
msg_map = {"a": "Arduino"}
| 37.683007 | 146 | 0.588674 |
f975435861ec73bfce0399c6d6ca18e0c1beb891 | 10,086 | py | Python | common/hil_slurm_helpers.py | mghpcc-projects/user_level_slurm_reservations | eae56588bb00abfe043714317a27481e036fcc29 | [
"MIT"
] | null | null | null | common/hil_slurm_helpers.py | mghpcc-projects/user_level_slurm_reservations | eae56588bb00abfe043714317a27481e036fcc29 | [
"MIT"
] | 11 | 2017-09-14T17:21:31.000Z | 2021-06-01T21:48:47.000Z | common/hil_slurm_helpers.py | mghpcc-projects/user_level_slurm_reservations | eae56588bb00abfe043714317a27481e036fcc29 | [
"MIT"
] | 3 | 2017-08-16T13:54:40.000Z | 2018-01-10T19:26:59.000Z | """
MassOpenCloud / Hardware Isolation Layer (MOC/HIL)
Slurm and *NX Subprocess Command Helpers
May 2017, Tim Donahue tpd001@gmail.com
"""
import os
from pwd import getpwnam, getpwuid
from subprocess import Popen, PIPE
from time import time
from hil_slurm_constants import (HIL_RESNAME_PREFIX, HIL_RESNAME_FIELD_SEPARATOR,
HIL_RESERVATION_OPERATIONS, RES_CREATE_FLAGS,
HIL_RESERVE, HIL_RELEASE)
from hil_slurm_settings import SLURM_INSTALL_DIR
from hil_slurm_logging import log_debug, log_info, log_error
def _exec_subprocess_cmd(cmd):
'''
Execute a command in a subprocess and wait for completion
'''
debug = False
p = None
try:
p = Popen(cmd, stdout=PIPE, stderr=PIPE)
(stdout_data, stderr_data) = p.communicate()
except Exception as e:
stdout_data = None
stderr_data ='error: Exception on Popen or communicate'
log_debug('Exception on Popen or communicate')
log_debug('Exception: %s' % e)
if debug:
f = _exec_subprocess_cmd.__name__
log_debug('%s: cmd is %s' % (f, cmd))
log_debug('%s: stdout is %s' % (f, stdout_data))
log_debug('%s: stderr is %s' % (f, stderr_data))
return stdout_data, stderr_data
def _scontrol_show_stdout_to_dict_list(stdout_data, stderr_data, debug=False):
'''
Convert the 'scontrol show' stdout data to a list of dicts
Nearly all params are of the form "keyword=value".
If they all were, a neat functional one-liner would do...
'''
stdout_dict_list = []
if len(stderr_data):
return []
# Split the output and remove the trailing None from the subprocess output
stdout_lines = stdout_data.split(os.linesep)
stdout_lines = filter(None, stdout_lines)
# Convert the output to a list of dicts
for line in stdout_lines:
stdout_line_dict = {}
for kv_pair in line.split(' '):
kv = kv_pair.split('=')
if (len(kv) == 2):
stdout_line_dict[kv[0]] = kv[1]
elif debug:
log_debug('Failed to convert `$s`' % kv_pair)
stdout_dict_list.append(stdout_line_dict)
return stdout_dict_list
def exec_scontrol_cmd(action, entity, entity_id=None, debug=True, **kwargs):
'''
Build an 'scontrol <action> <entity>' command and pass to an executor
Specify single-line output to support stdout postprocessing
'''
cmd = [os.path.join(SLURM_INSTALL_DIR, 'scontrol'), action]
if entity:
cmd.append(entity)
if entity_id:
cmd.append(entity_id)
cmd.append('-o')
if kwargs:
for k, v in kwargs.iteritems():
cmd.append('%s=%s' % (k,v))
if debug:
log_debug('exec_scontrol_cmd(): Command %s' % cmd)
stdout_data, stderr_data = _exec_subprocess_cmd(cmd)
if debug:
log_debug('exec_scontrol_cmd(): Stdout %s' % stdout_data)
log_debug('exec_scontrol_cmd(): Stderr %s' % stderr_data)
return stdout_data, stderr_data
def exec_scontrol_show_cmd(entity, entity_id, debug=False, **kwargs):
'''
Run the 'scontrol show' command on the entity and ID
Convert standard output data to a list of dictionaries, one per line
'''
stdout_data, stderr_data = exec_scontrol_cmd('show', entity, entity_id, debug=debug, **kwargs)
# Check for errors.
# If anything in stderr, return it
# Next, check if stdout includes various error strings - 'scontrol show'
# writes error output to stdout.
# Failure indications:
# Reservation: stdout includes 'not found'
# Job: stdout includes 'Invalid job id'
# Copy stdout to stderr if found.
# If stderr is empty, and stdout does not contain an error string,
# convert stdout to a list of dicts and return that
stdout_dict_list = []
entity_error_dict = {
'reservation': 'not found',
'job': 'Invalid job id'
}
cmd = 'scontrol show ' + entity
if (len(stderr_data) != 0):
log_debug('Command `%s` failed' % cmd)
log_debug(' stderr: %s' % stderr_data)
elif (entity in entity_error_dict) and (entity_error_dict[entity] in stdout_data):
if debug:
log_debug('Command `%s` failed' % cmd)
log_debug(' stderr: %s' % stderr_data)
stderr_data = stdout_data
stdout_data = None
else:
stdout_dict_list = _scontrol_show_stdout_to_dict_list(stdout_data, stderr_data)
return stdout_dict_list, stdout_data, stderr_data
def create_slurm_reservation(name, user, t_start_s, t_end_s, nodes=None,
flags=RES_CREATE_FLAGS, features=None, debug=False):
'''
Create a Slurm reservation via 'scontrol create reservation'
'''
if nodes is None:
nodes = 'ALL'
t_end_arg = {'duration': 'UNLIMITED'} if t_end_s is None else {'endtime': t_end_s}
return exec_scontrol_cmd('create', 'reservation', entity_id=None, debug=debug,
ReservationName=name, starttime=t_start_s,
user=user, nodes=nodes, flags=flags, features=features,
**t_end_arg)
def delete_slurm_reservation(name, debug=False):
'''
Delete a Slurm reservation via 'scontrol delete reservation=<name>'
'''
return exec_scontrol_cmd('delete', None, debug=debug, reservation=name)
def update_slurm_reservation(name, debug=False, **kwargs):
'''
Update a Slurm reservation via 'scontrol update reservation=<name> <kwargs>'
'''
return exec_scontrol_cmd('update', None, reservation=name, debug=debug, **kwargs)
def get_hil_reservation_name(env_dict, restype_s, t_start_s):
'''
Create a reservation name, combining the HIL reservation prefix,
the username, the job ID, and the ToD (YMD_HMS)
Structure:
NamePrefix _ [release|reserve] _ uname _ job_UID _ str(int(time()))
'''
resname = HIL_RESNAME_PREFIX + restype_s + HIL_RESNAME_FIELD_SEPARATOR
resname += env_dict['username'] + HIL_RESNAME_FIELD_SEPARATOR
resname += env_dict['job_uid'] + HIL_RESNAME_FIELD_SEPARATOR
resname += str(int(time()))
return resname
def parse_hil_reservation_name(resname):
'''
Attempt to split a reservation name into HIL reservation name components:
HIL reservation prefix, reservation type, user name, uid, and time
This looks like overkill, except for the presence of other reservations in the
system, with semi-arbitrary names.
'''
prefix = None
restype = None
user = None
uid = None
time_s = None
if resname.startswith(HIL_RESNAME_PREFIX):
resname_partitions = resname.partition(HIL_RESNAME_PREFIX)
prefix = resname_partitions[1]
try:
restype, user, uid, time_s = resname_partitions[2].split(HIL_RESNAME_FIELD_SEPARATOR)
except:
pass
return prefix, restype, user, uid, time_s
def is_hil_reservation(resname, restype_in):
'''
Check if the passed reservation name:
- Starts with the HIL reservation prefix
- Is a HIL reserve or release reservation
- Contains a valid user name and UID
- Optionally, is specifically a reserve or release reservation
- $$$ Could verify nodes have HIL property set
'''
prefix, restype, uname, uid, _ = parse_hil_reservation_name(resname)
if (prefix != HIL_RESNAME_PREFIX):
# log_error('No HIL reservation prefix')
return False
if restype_in:
if (restype != restype_in):
# log_error('Reservation type mismatch')
return False
elif restype not in HIL_RESERVATION_OPERATIONS:
log_error('Unknown reservation type')
return False
try:
pwdbe1 = getpwnam(uname)
pwdbe2 = getpwuid(int(uid))
if pwdbe1 != pwdbe2:
# log_error('Reservation `%s`: User and UID inconsistent' % resname)
return False
except KeyError:
# log_error('Key error')
return False
return True
def get_object_data(what_obj, obj_id, debug=False):
'''
Get a list of dictionaries of information on the object, via
'scontrol show <what_object> <object_id>'
'''
objdata_dict_list, stdout_data, stderr_data = exec_scontrol_show_cmd(what_obj,
obj_id, debug=False)
if (len(stderr_data) != 0):
if debug:
log_debug('Failed to retrieve data for %s `%s`' % (what_obj, obj_id))
log_debug(' %s' % stderr_data)
return objdata_dict_list
def get_partition_data(partition_id):
'''
Get a list of dictionaries of information on the partition(s),
via 'scontrol show partition'
'''
return get_object_data('partition', partition_id, debug=False)
def get_job_data(job_id):
'''
Get a list of dictionaries of information on the job(s),
via 'scontrol show job'
'''
return get_object_data('job', job_id, debug=False)
def get_hil_reservations():
'''
Get a list of all Slurm reservations, return that subset which are HIL reservations
'''
resdata_dict_list = []
resdata_dict_list, stdout_data, stderr_data = exec_scontrol_show_cmd('reservation', None)
for resdata_dict in resdata_dict_list:
if resdata_dict and is_hil_reservation(resdata_dict['ReservationName'], None):
continue
else:
resdata_dict_list.remove(resdata_dict)
return resdata_dict_list
# EOF
| 31.716981 | 98 | 0.65348 |
f976fcf3758aba64e0576f78efb657866db8fe14 | 17,596 | py | Python | tools/contourlet_transform/tools/dfilters.py | yilinshao/CoT-Contourlet-Transformer | 44d36a05f81ec168e3ccd8b9438ddaee6283189e | [
"MIT"
] | 4 | 2021-12-21T07:45:01.000Z | 2021-12-21T09:15:47.000Z | tools/contourlet_transform/tools/dfilters.py | yilinshao/CoT-Contourlet-Transformer | 44d36a05f81ec168e3ccd8b9438ddaee6283189e | [
"MIT"
] | null | null | null | tools/contourlet_transform/tools/dfilters.py | yilinshao/CoT-Contourlet-Transformer | 44d36a05f81ec168e3ccd8b9438ddaee6283189e | [
"MIT"
] | null | null | null | # -*- coding: utf-8 -*-
# PyContourlet
#
# A Python library for the Contourlet Transform.
#
# Copyright (C) 2011 Mazay Jimnez
#
# This program is free software; you can redistribute it and/or modify
# it under the terms of the GNU General Public License as published by
# the Free Software Foundation version 2.
#
# This program is distributed in the hope that it will be useful,
# but WITHOUT ANY WARRANTY; without even the implied warranty of
# MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the
# GNU General Public License for more details.
#
# You should have received a copy of the GNU General Public License along
# with this program; if not, write to the Free Software Foundation, Inc.,
# 51 Franklin Street, Fifth Floor, Boston, MA 02110-1301 USA.
from numpy import *
# from scipy.signal.filter_design import firwin
from .mctrans import *
from .modulate2 import *
from .ldfilter import *
from .ld2quin import *
from .reverse2 import *
from .dmaxflat import *
def dfilters(fname, type):
""" DFILTERS Generate directional 2D filters
Input:
fname: Filter name. Available 'fname' are:
'haar': the Haar filters
'vk': McClellan transformed of the filter from the VK book
'ko': orthogonal filter in the Kovacevic's paper
'kos': smooth 'ko' filter
'lax': 17 x 17 by Lu, Antoniou and Xu
'sk': 9 x 9 by Shah and Kalker
'cd': 7 and 9 McClellan transformed by Cohen and Daubechies
'pkva': ladder filters by Phong et al.
'oqf_362': regular 3 x 6 filter
'dvmlp': regular linear phase biorthogonal filter with 3 dvm
'sinc': ideal filter (*NO perfect recontruction*)
'dmaxflat': diamond maxflat filters obtained from a three stage ladder
type: 'd' or 'r' for decomposition or reconstruction filters
Output:
h0, h1: diamond filter pair (lowpass and highpass)
To test those filters (for the PR condition for the FIR case),
verify that:
convolve(h0, modulate2(h1, 'b')) + convolve(modulate2(h0, 'b'), h1) = 2
(replace + with - for even size filters)
To test for orthogonal filter
convolve(h, reverse2(h)) + modulate2(convolve(h, reverse2(h)), 'b') = 2
"""
# The diamond-shaped filter pair
if fname == "haar":
if str.lower(type[0]) == 'd':
h0 = array([1, 1]) / sqrt(2)
h1 = array([-1, 1]) / sqrt(2)
else:
h0 = array([1, 1]) / sqrt(2)
h1 = array([1, -1]) / sqrt(2)
return h0, h1
elif fname == "vk":
if str.lower(type[0]) == 'd':
h0 = array([1, 2, 1]) / 4.0
h1 = array([-1, -2, 6, -2, -1]) / 4.0
else:
h0 = array([-1, 2, 6, 2, -1]) / 4.0
h1 = array([-1, 2, -1]) / 4.0
# McClellan transfrom to obtain 2D diamond filters
t = array([[0, 1, 0], [1, 0, 1], [0, 1, 0]]) / 4.0 # diamond kernel
h0 = mctrans(h0, t)
h1 = mctrans(h1, t)
return h0, h1
elif fname == "ko": # orthogonal filters in Kovacevic's thesis
a0, a1, a2 = 2, 0.5, 1
h0 = array([[0, -a1, -a0 * a1, 0],
[-a2, -a0 * a2, -a0, 1],
[0, a0 * a1 * a2, -a1 * a2, 0]])
# h1 = qmf2(h0);
h1 = array([[0, -a1 * a2, -a0 * a1 * a2, 0],
[1, a0, -a0 * a2, a2],
[0, -a0 * a1, a1, 0]])
# Normalize filter sum and norm;
norm = sqrt(2) / sum(h0)
h0 = h0 * norm
h1 = h1 * norm
if str.lower(type[0]) == 'r':
# Reverse filters for reconstruction
h0 = h0[::-1, ::-1]
h1 = h1[::-1, ::-1]
return h0, h1
elif fname == "kos": # Smooth orthogonal filters in Kovacevic's thesis
a0, a1, a2 = -sqrt(3), -sqrt(3), 2 + sqrt(3)
h0 = array([[0, -a1, -a0 * a1, 0],
[-a2, -a0 * a2, -a0, 1],
[0, a0 * a1 * a2, -a1 * a2, 0]])
# h1 = qmf2(h0);
h1 = array([[0, -a1 * a2, -a0 * a1 * a2, 0],
[1, a0, -a0 * a2, a2],
[0, -a0 * a1, a1, 0]])
# Normalize filter sum and norm;
norm = sqrt(2) / sum(h0)
h0 = h0 * norm
h1 = h1 * norm
if str.lower(type[0]) == 'r':
# Reverse filters for reconstruction
h0 = h0[::-1, ::-1]
h1 = h1[::-1, ::-1]
return h0, h1
elif fname == "lax": # by Lu, Antoniou and Xu
h = array([[-1.2972901e-5, 1.2316237e-4, -7.5212207e-5, 6.3686104e-5,
9.4800610e-5, -7.5862919e-5, 2.9586164e-4, -1.8430337e-4],
[1.2355540e-4, -1.2780882e-4, -1.9663685e-5, -4.5956538e-5,
-6.5195193e-4, -2.4722942e-4, -2.1538331e-5, -7.0882131e-4],
[-7.5319075e-5, -1.9350810e-5, -7.1947086e-4, 1.2295412e-3,
5.7411214e-4, 4.4705422e-4, 1.9623554e-3, 3.3596717e-4],
[6.3400249e-5, -2.4947178e-4, 4.4905711e-4, -4.1053629e-3,
-2.8588307e-3, 4.3782726e-3, -3.1690509e-3, -3.4371484e-3],
[9.6404973e-5, -4.6116254e-5, 1.2371871e-3, -1.1675575e-2,
1.6173911e-2, -4.1197559e-3, 4.4911165e-3, 1.1635130e-2],
[-7.6955555e-5, -6.5618379e-4, 5.7752252e-4, 1.6211426e-2,
2.1310378e-2, -2.8712621e-3, -4.8422645e-2, -5.9246338e-3],
[2.9802986e-4, -2.1365364e-5, 1.9701350e-3, 4.5047673e-3,
-4.8489158e-2, -3.1809526e-3, -2.9406153e-2, 1.8993868e-1],
[-1.8556637e-4, -7.1279432e-4, 3.3839195e-4, 1.1662001e-2,
-5.9398223e-3, -3.4467920e-3, 1.9006499e-1, 5.7235228e-1]])
h0 = sqrt(2) * vstack((hstack((h, h[:, len(h) - 2::-1])),
hstack((h[len(h) - 2::-1, :],
h[len(h) - 2::-1, len(h) - 2::-1]))))
h1 = modulate2(h0, 'b', None)
return h0, h1
elif fname == "sk": # by Shah and Kalker
h = array([[0.621729, 0.161889, -0.0126949, -0.00542504, 0.00124838],
[0.161889, -0.0353769, -0.0162751, -0.00499353, 0],
[-0.0126949, -0.0162751, 0.00749029, 0, 0],
[-0.00542504, 0.00499353, 0, 0, 0],
[0.00124838, 0, 0, 0, 0]])
h0 = sqrt(2) * vstack((hstack((h[len(h):0:-1, len(h):0:-1],
h[len(h):0:-1, :])),
hstack((h[:, len(h):0:-1], h))))
h1 = modulate2(h0, 'b', None)
return h0, h1
elif fname == "dvmlp":
q = sqrt(2)
b = 0.02
b1 = b * b
h = array([[b / q, 0, -2 * q * b, 0, 3 * q * b, 0, -2 * q * b, 0, b / q],
[0, -1 / (16 * q), 0, 9 / (16 * q), 1 / q, 9 / (16 * q), 0, -1 / (16 * q), 0],
[b / q, 0, -2 * q * b, 0, 3 * q * b, 0, -2 * q * b, 0, b / q]])
g0 = array([[-b1 / q, 0, 4 * b1 * q, 0, -14 * q * b1, 0, 28 * q * b1, 0, -35 * q * b1, 0,
28 * q * b1, 0, -14 * q * b1, 0, 4 * b1 * q, 0, -b1 / q],
[0, b / (8 * q), 0, -13 * b / (8 * q), b / q, 33 * b / (8 * q), -2 * q * b,
-21 * b / (8 * q), 3 * q * b, -21 * b / (8 * q), -2 * q * b, 33 * b / (8 * q),
b / q, -13 * b / (8 * q), 0, b / (8 * q), 0],
[-q * b1, 0, -1 / (256 * q) + 8 * q * b1, 0, 9 / (128 * q) - 28 * q * b1,
-1 / (q * 16), -63 / (256 * q) + 56 * q * b1, 9 / (16 * q),
87 / (64 * q) - 70 * q * b1, 9 / (16 * q), -63 / (256 * q) + 56 * q * b1,
-1 / (q * 16), 9 / (128 * q) - 28 * q * b1, 0, -1 / (256 * q) + 8 * q * b1,
0, -q * b1],
[0, b / (8 * q), 0, -13 * b / (8 * q), b / q, 33 * b / (8 * q), -2 * q * b,
-21 * b / (8 * q), 3 * q * b, -21 * b / (8 * q), -2 * q * b, 33 * b / (8 * q),
b / q, -13 * b / (8 * q), 0, b / (8 * q), 0],
[-b1 / q, 0, 4 * b1 * q, 0, -14 * q * b1, 0, 28 * q * b1, 0, -35 * q * b1,
0, 28 * q * b1, 0, -14 * q * b1, 0, 4 * b1 * q, 0, -b1 / q]])
h1 = modulate2(g0, 'b', None)
h0 = h.copy()
if str.lower(type[0]) == 'r':
h1 = modulate2(h, 'b', None)
h0 = g0.copy()
return h0, h1
elif fname == "cd" or fname == "7-9": # by Cohen and Daubechies
# 1D prototype filters: the '7-9' pair
h0 = array([0.026748757411, -0.016864118443, -0.078223266529,
0.266864118443, 0.602949018236, 0.266864118443,
-0.078223266529, -0.016864118443, 0.026748757411])
g0 = array([-0.045635881557, -0.028771763114, 0.295635881557,
0.557543526229, 0.295635881557, -0.028771763114,
-0.045635881557])
if str.lower(type[0]) == 'd':
h1 = modulate2(g0, 'c', None)
else:
h1 = modulate2(h0, 'c', None)
h0 = g0.copy()
# Use McClellan to obtain 2D filters
t = array([[0, 1, 0], [1, 0, 1], [0, 1, 0]]) / 4.0 # diamond kernel
h0 = sqrt(2) * mctrans(h0, t)
h1 = sqrt(2) * mctrans(h1, t)
return h0, h1
elif fname == "pkva" or fname == "ldtest":
# Filters from the ladder structure
# Allpass filter for the ladder structure network
beta = ldfilter(fname)
# Analysis filters
h0, h1 = ld2quin(beta)
# Normalize norm
h0 = sqrt(2) * h0
h1 = sqrt(2) * h1
# Synthesis filters
if str.lower(type[0]) == 'r':
f0 = modulate2(h1, 'b', None)
f1 = modulate2(h0, 'b', None)
h0 = f0.copy()
h1 = f1.copy()
return h0, h1
# elif fname == "pkva-half4": # Filters from the ladder structure
# # Allpass filter for the ladder structure network
# beta = ldfilterhalf(4)
#
# # Analysis filters
# h0, h1 = ld2quin(beta)
#
# # Normalize norm
# h0 = sqrt(2) * h0
# h1 = sqrt(2) * h1
#
# # Synthesis filters
# if str.lower(type[0]) == 'r':
# f0 = modulate2(h1, 'b', None)
# f1 = modulate2(h0, 'b', None)
# h0 = f0
# h1 = f1
# return h0, h1
#
# elif fname == "pkva-half6": # Filters from the ladder structure
# # Allpass filter for the ladder structure network
# beta = ldfilterhalf(6)
#
# # Analysis filters
# h0, h1 = ld2quin(beta)
#
# # Normalize norm
# h0 = sqrt(2) * h0
# h1 = sqrt(2) * h1
#
# # Synthesis filters
# if srtring.lower(type[0]) == 'r':
# f0 = modulate2(h1, 'b', None)
# f1 = modulate2(h0, 'b', None)
# h0 = f0
# h1 = f1
# return h0, h1
#
# elif fname == "pkva-half8": # Filters from the ladder structure
# # Allpass filter for the ladder structure network
# beta = ldfilterhalf(8)
#
# # Analysis filters
# h0, h1 = ld2quin(beta)
#
# # Normalize norm
# h0 = sqrt(2) * h0
# h1 = sqrt(2) * h1
#
# # Synthesis filters
# if str.lower(type[0]) == 'r':
# f0 = modulate2(h1, 'b', None)
# f1 = modulate2(h0, 'b', None)
# h0 = f0
# h1 = f1
# return h0, h1
# elif fname == "sinc": # The "sinc" case, NO Perfect Reconstruction
# # Ideal low and high pass filters
# flength = 30
#
# h0 = firwin(flength + 1, 0.5)
# h1 = modulate2(h0, 'c', None)
#
# # Use McClellan to obtain 2D filters
# t = array([[0, 1, 0], [1, 0, 1], [0, 1, 0]]) / 4.0 # diamond kernel
# h0 = sqrt(2) * mctrans(h0, t)
# h1 = sqrt(2) * mctrans(h1, t)
# return h0, h1
elif fname == "oqf_362": # Some "home-made" filters!
h0 = sqrt(2) / 64 * array([[sqrt(15), -3, 0],
[0, 5, -sqrt(15)],
[-2 * sqrt(15), 30, 0],
[0, 30, 2 * sqrt(15)],
[sqrt(15), 5, 0],
[0, -3, -sqrt(15)]]).conj().T
h1 = -reverse2(modulate2(h0, 'b', None))
if str.lower(type[0]) == 'r':
# Reverse filters for reconstruction
h0 = h0[::-1, ::-1]
h1 = h1[::-1, ::-1]
return h0, h1
elif fname == "test": # Only for the shape, not for PR
h0 = array([[0, 1, 0], [1, 4, 1], [0, 1, 0]])
h1 = array([[0, -1, 0], [-1, 4, -1], [0, -1, 0]])
return h0, h1
elif fname == "testDVM": # Only for directional vanishing moment
h0 = array([[1, 1], [1, 1]]) / sqrt(2)
h1 = array([[-1, 1], [1, -1]]) / sqrt(2)
return h0, h1
elif fname == "qmf": # by Lu, Antoniou and Xu
# ideal response
# window
m, n = 2, 2
w = empty([5, 5])
w1d = kaiser(4 * m + 1, 2.6)
for n1 in range(-m, m + 1):
for n2 in range(-n, n + 1):
w[n1 + m, n2 + n] = w1d[2 * m + n1 + n2] * w1d[2 * m + n1 - n2]
h = empty([5, 5])
for n1 in range(-m, m + 1):
for n2 in range(-n, n + 1):
h[n1 + m, n2 + n] = .5 * sinc((n1 + n2) / 2.0) * .5 * sinc((n1 - n2) / 2.0)
c = sum(h)
h = sqrt(2) * h / c
h0 = h * w
h1 = modulate2(h0, 'b', None)
return h0, h1
#h0 = modulate2(h,'r');
#h1 = modulate2(h,'b');
elif fname == "qmf2": # by Lu, Antoniou and Xu
# ideal response
# window
h = array([[-.001104, .002494, -0.001744, 0.004895,
-0.000048, -.000311],
[0.008918, -0.002844, -0.025197, -0.017135,
0.003905, -0.000081],
[-0.007587, -0.065904, 0.100431, -0.055878,
0.007023, 0.001504],
[0.001725, 0.184162, 0.632115, 0.099414,
-0.027006, -0.001110],
[-0.017935, -0.000491, 0.191397, -0.001787,
-0.010587, 0.002060],
[.001353, 0.005635, -0.001231, -0.009052,
-0.002668, 0.000596]])
h0 = h / sum(h)
h1 = modulate2(h0, 'b', None)
return h0, h1
#h0 = modulate2(h,'r');
#h1 = modulate2(h,'b');
elif fname == "dmaxflat4":
M1 = 1 / sqrt(2)
M2 = M1
k1 = 1 - sqrt(2)
k3 = k1
k2 = M1
h = array([.25 * k2 * k3, .5 * k2, 1 + .5 * k2 * k3]) * M1
h = hstack((h, h[len(h) - 2::-1]))
g = array([-.125 * k1 * k2 * k3, 0.25 * k1 * k2, (-0.5 * k1 - 0.5 * k3 - 0.375 * k1 * k2 * k3),
1 + .5 * k1 * k2]) * M2
g = hstack((g, g[len(g) - 2::-1]))
B = dmaxflat(4, 0)
h0 = mctrans(h, B)
g0 = mctrans(g, B)
h0 = sqrt(2) * h0 / sum(h0)
g0 = sqrt(2) * g0 / sum(g0)
h1 = modulate2(g0, 'b', None)
if str.lower(type[0]) == 'r':
h1 = modulate2(h0, 'b', None)
h0 = g0.copy()
return h0, h1
elif fname == "dmaxflat5":
M1 = 1 / sqrt(2)
M2 = M1
k1 = 1 - sqrt(2)
k3 = k1
k2 = M1
h = array([.25 * k2 * k3, .5 * k2, 1 + .5 * k2 * k3]) * M1
h = hstack((h, h[len(h) - 2::-1]))
g = array([-.125 * k1 * k2 * k3, 0.25 * k1 * k2,
(-0.5 * k1 - 0.5 * k3 - 0.375 * k1 * k2 * k3), 1 + .5 * k1 * k2]) * M2
g = hstack((g, g[len(g) - 2::-1]))
B = dmaxflat(5, 0)
h0 = mctrans(h, B)
g0 = mctrans(g, B)
h0 = sqrt(2) * h0 / sum(h0)
g0 = sqrt(2) * g0 / sum(g0)
h1 = modulate2(g0, 'b', None)
if str.lower(type[0]) == 'r':
h1 = modulate2(h0, 'b', None)
h0 = g0.copy()
return h0, h1
elif fname == "dmaxflat6":
M1 = 1 / sqrt(2)
M2 = M1
k1 = 1 - sqrt(2)
k3 = k1
k2 = M1
h = array([.25 * k2 * k3, .5 * k2, 1 + .5 * k2 * k3]) * M1
h = hstack((h, h[len(h) - 2::-1]))
g = array([-.125 * k1 * k2 * k3, 0.25 * k1 * k2,
(-0.5 * k1 - 0.5 * k3 - 0.375 * k1 * k2 * k3), 1 + .5 * k1 * k2]) * M2
g = hstack((g, g[len(g) - 2::-1]))
B = dmaxflat(6, 0)
h0 = mctrans(h, B)
g0 = mctrans(g, B)
h0 = sqrt(2) * h0 / sum(h0)
g0 = sqrt(2) * g0 / sum(g0)
h1 = modulate2(g0, 'b', None)
if str.lower(type[0]) == 'r':
h1 = modulate2(h0, 'b', None)
h0 = g0.copy()
return h0, h1
elif fname == "dmaxflat7":
M1 = 1 / sqrt(2)
M2 = M1
k1 = 1 - sqrt(2)
k3 = k1
k2 = M1
h = array([.25 * k2 * k3, .5 * k2, 1 + .5 * k2 * k3]) * M1
h = hstack((h, h[len(h) - 2::-1]))
g = array([-.125 * k1 * k2 * k3, 0.25 * k1 * k2,
(-0.5 * k1 - 0.5 * k3 - 0.375 * k1 * k2 * k3), 1 + .5 * k1 * k2]) * M2
g = hstack((g, g[len(g) - 2::-1]))
B = dmaxflat(7, 0)
h0 = mctrans(h, B)
g0 = mctrans(g, B)
h0 = sqrt(2) * h0 / sum(h0)
g0 = sqrt(2) * g0 / sum(g0)
h1 = modulate2(g0, 'b')
if str.lower(type[0]) == 'r':
h1 = modulate2(h0, 'b')
h0 = g0.copy()
return h0, h1
| 37.759657 | 103 | 0.436065 |
f9773a9cbbac8043bcf3bf565130d13c371454b2 | 96 | py | Python | src/wavestate/iirrational/external/tabulate/__init__.py | wavestate/wavestate-iirrational | 01d6dba8b2131fa2a099a74f17e6540f30cee606 | [
"Apache-2.0"
] | null | null | null | src/wavestate/iirrational/external/tabulate/__init__.py | wavestate/wavestate-iirrational | 01d6dba8b2131fa2a099a74f17e6540f30cee606 | [
"Apache-2.0"
] | null | null | null | src/wavestate/iirrational/external/tabulate/__init__.py | wavestate/wavestate-iirrational | 01d6dba8b2131fa2a099a74f17e6540f30cee606 | [
"Apache-2.0"
] | null | null | null | """
External libraries packaged with for version stability
"""
from .tabulate import tabulate
| 13.714286 | 54 | 0.770833 |
f97830507a9e81ba352de5e77becd93d7de239ce | 1,112 | py | Python | tests/test_statsutils.py | ofek/boltons | 395f690f4a24331c4554e2169ac18a15955a4eab | [
"BSD-3-Clause"
] | 6,058 | 2015-03-18T16:44:39.000Z | 2022-03-28T08:42:16.000Z | tests/test_statsutils.py | ofek/boltons | 395f690f4a24331c4554e2169ac18a15955a4eab | [
"BSD-3-Clause"
] | 289 | 2015-04-09T23:09:24.000Z | 2022-03-30T00:29:33.000Z | tests/test_statsutils.py | ofek/boltons | 395f690f4a24331c4554e2169ac18a15955a4eab | [
"BSD-3-Clause"
] | 407 | 2015-04-09T20:09:15.000Z | 2022-03-30T10:43:22.000Z | # -*- coding: utf-8 -*-
from boltons.statsutils import Stats
| 32.705882 | 115 | 0.615108 |
f979feef783a84ff7f70e9da364235d7c960d2cb | 1,018 | py | Python | funcs.py | pgDora56/shinyintro | 15cc153106ebd88a5f73801f2bf0bef52d37cdab | [
"MIT"
] | null | null | null | funcs.py | pgDora56/shinyintro | 15cc153106ebd88a5f73801f2bf0bef52d37cdab | [
"MIT"
] | null | null | null | funcs.py | pgDora56/shinyintro | 15cc153106ebd88a5f73801f2bf0bef52d37cdab | [
"MIT"
] | null | null | null | import os
import pprint
import json
import random
accept = False
colors = {
"Vo": "#e05ab4",
"Da": "#59afe1",
"Vi": "#e0e05a"
}
with open('idols.json') as f:
idols = (json.load(f))["idols"] # Insert 23 data
| 18.851852 | 72 | 0.54224 |
f97c2537579109b781456eb2fe785026c3ea5e59 | 10,782 | py | Python | UWBsim/interface/plot_widgets.py | kianheus/uwb-simulator | 888cdcae0d4ca101970971afbdf0113ba3bb1480 | [
"MIT"
] | 2 | 2021-08-25T03:27:06.000Z | 2021-09-26T05:08:19.000Z | UWBsim/interface/plot_widgets.py | kianheus/uwb-simulator | 888cdcae0d4ca101970971afbdf0113ba3bb1480 | [
"MIT"
] | null | null | null | UWBsim/interface/plot_widgets.py | kianheus/uwb-simulator | 888cdcae0d4ca101970971afbdf0113ba3bb1480 | [
"MIT"
] | 1 | 2021-07-17T10:59:15.000Z | 2021-07-17T10:59:15.000Z | """Plot Widgets for the UWB Simulation GUI
This file contains several plot widgets that can be used to plot
simulation data in real time and redraw the plots with matplotlib for
better quality.
Classes:
QLivePlot: Base class for real time plots
QLivePlot_Groundtrack: Real time plot for groundtrack
QLivePlot_Position: Real time plot for x, y, z positions
QLivePlot_Velocity: Real time plot for x, y, z velocities
QLivePlot_Attitude: Real time plot for attitude
"""
from PyQt5 import QtWidgets
import pyqtgraph as pg
import matplotlib.pyplot as plt
import numpy as np
from UWBsim.utils import dataTypes
| 34.66881 | 126 | 0.516602 |
f97ca4c83d65c548b29075ec69330e20d6ca30b3 | 1,018 | py | Python | scripts/plot_summary_stats.py | JackKelly/slicedpy | c2fa7eb4c7b7374f8192a43d8e617b63c9e25e62 | [
"Apache-2.0"
] | 3 | 2017-02-03T22:05:25.000Z | 2017-08-29T19:06:17.000Z | scripts/plot_summary_stats.py | JackKelly/slicedpy | c2fa7eb4c7b7374f8192a43d8e617b63c9e25e62 | [
"Apache-2.0"
] | null | null | null | scripts/plot_summary_stats.py | JackKelly/slicedpy | c2fa7eb4c7b7374f8192a43d8e617b63c9e25e62 | [
"Apache-2.0"
] | null | null | null | #!/usr/bin/env python
from pda.dataset import init_aggregate_and_appliance_dataset_figure
import matplotlib.pyplot as plt
from scipy.stats import *
import numpy as np
subplots, chan = init_aggregate_and_appliance_dataset_figure(
start_date='2013/6/4 10:00', end_date='2013/6/4 13:30',
n_subplots=2, date_format='%H:%M:%S', alpha=0.6,
plot_appliance_ground_truth=False)
DISPLAY = ['mean', 'std', 'ptp', 'gmean', 'skew']
WINDOW = 60
n = chan.series.size - WINDOW
labels = ['mean', 'std', 'ptp', 'gmean', 'skew']
summary_stats = np.empty((n,len(labels)))
print("Calculating...")
for i in range(1,n):
chunk = chan.series.values[i:i+WINDOW]
summary_stats[i] = (chunk.mean(), chunk.std(), chunk.ptp(),
gmean(chunk), skew(chunk))
print("Plotting...")
for i, label in enumerate(labels):
if label in DISPLAY:
subplots[1].plot(chan.series.index[WINDOW:], summary_stats[:,i],
label=label)
plt.legend()
plt.grid()
plt.show()
print("Done!")
| 28.277778 | 73 | 0.656189 |
f97cacad56a833075fdbf1486e99e188f8024b55 | 2,691 | py | Python | sciibo/network/connection.py | fdev/sciibo | 984ec1945cd0f371bce148c1eb1e811befadb478 | [
"MIT"
] | 14 | 2017-06-16T14:16:57.000Z | 2021-02-26T13:53:56.000Z | sciibo/network/connection.py | fdev/sciibo | 984ec1945cd0f371bce148c1eb1e811befadb478 | [
"MIT"
] | 1 | 2018-06-27T16:11:48.000Z | 2019-01-23T12:02:17.000Z | sciibo/network/connection.py | fdev/sciibo | 984ec1945cd0f371bce148c1eb1e811befadb478 | [
"MIT"
] | null | null | null | import socket
import json
import struct
from sciibo.core.helpers import Queue
from .thread import SocketThread
| 27.459184 | 84 | 0.544036 |
f97d02d723f0a4441c6c06372a7158427073778d | 2,651 | py | Python | libs/PieMeter.py | lionheart/TimeTracker-Linux | 64405d53fd12d2593ef4879b867ff38a4d5b9ca9 | [
"MIT"
] | 12 | 2015-02-06T19:06:49.000Z | 2019-09-24T17:58:17.000Z | libs/PieMeter.py | lionheart/TimeTracker-Linux | 64405d53fd12d2593ef4879b867ff38a4d5b9ca9 | [
"MIT"
] | null | null | null | libs/PieMeter.py | lionheart/TimeTracker-Linux | 64405d53fd12d2593ef4879b867ff38a4d5b9ca9 | [
"MIT"
] | 6 | 2015-11-22T01:58:31.000Z | 2019-11-04T22:56:38.000Z | # Copyright (C) 2008 Jimmy Do <jimmydo@users.sourceforge.net>
#
# This program is free software; you can redistribute it and/or modify
# it under the terms of the GNU General Public License as published by
# the Free Software Foundation; either version 2 of the License, or
# (at your option) any later version.
#
# This program is distributed in the hope that it will be useful,
# but WITHOUT ANY WARRANTY; without even the implied warranty of
# MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the
# GNU General Public License for more details.
#
# You should have received a copy of the GNU General Public License
# along with this program; if not, write to the Free Software
# Foundation, Inc., 59 Temple Place, Suite 330, Boston, MA 02111-1307 USA
import math
import gobject
import gtk
gobject.type_register(PieMeter)
| 33.987179 | 97 | 0.626556 |
f97d4fd046debdeff0094ec80a682b86eb50db54 | 6,192 | py | Python | examples/pinball.py | jgrigonis/arcade | 9b624da7da52e3909f6e82c552446b90249041f1 | [
"MIT"
] | 1 | 2021-05-23T20:30:46.000Z | 2021-05-23T20:30:46.000Z | examples/pinball.py | jgrigonis/arcade | 9b624da7da52e3909f6e82c552446b90249041f1 | [
"MIT"
] | null | null | null | examples/pinball.py | jgrigonis/arcade | 9b624da7da52e3909f6e82c552446b90249041f1 | [
"MIT"
] | null | null | null | import arcade
import timeit
BALL_DRAG = 0.001
NO_FLIPPER = 0
FLIPPER_UP = 1
window = MyApplication(800, 1000, resizable=False)
window.set_size(700, 700)
arcade.run()
| 33.652174 | 138 | 0.55491 |
f97e5968772769d07d1c5c3519564d5e93b96cb9 | 2,350 | py | Python | pygomas/pack.py | sfp932705/pygomas | 8cdd7e973b8b4e8de467803c106ec44ca6b8bd03 | [
"MIT"
] | 3 | 2019-06-20T08:55:36.000Z | 2019-07-04T14:10:40.000Z | pygomas/pack.py | sfp932705/pygomas | 8cdd7e973b8b4e8de467803c106ec44ca6b8bd03 | [
"MIT"
] | null | null | null | pygomas/pack.py | sfp932705/pygomas | 8cdd7e973b8b4e8de467803c106ec44ca6b8bd03 | [
"MIT"
] | null | null | null | import json
from loguru import logger
from .config import PERFORMATIVE, PERFORMATIVE_PACK, PERFORMATIVE_PACK_TAKEN, TEAM, X, Y, Z, NAME, ACTION, CREATE, \
TYPE
from .agent import AbstractAgent, LONG_RECEIVE_WAIT
from .vector import Vector3D
from spade.message import Message
from spade.behaviour import OneShotBehaviour, CyclicBehaviour
from spade.template import Template
from spade.agent import Agent
PACK_NONE: int = 1000
PACK_MEDICPACK: int = 1001
PACK_AMMOPACK: int = 1002
PACK_OBJPACK: int = 1003
PACK_NAME = {
PACK_NONE: 'NONE',
PACK_MEDICPACK: 'MEDIC',
PACK_AMMOPACK: 'AMMO',
PACK_OBJPACK: 'OBJ'
}
PACK_AUTODESTROY_TIMEOUT: int = 25
| 31.333333 | 116 | 0.635745 |
f97e89c0eb4e106c1ec357be4b95f0207161d996 | 2,178 | py | Python | Utils/initialize.py | soshishimada/PhysCap_demo_release | 542756ed9ecdca77eda8b6b44ba2348253b999c3 | [
"Unlicense"
] | 62 | 2021-09-05T19:36:06.000Z | 2022-03-29T11:47:09.000Z | Utils/initialize.py | soshishimada/PhysCap_demo_release | 542756ed9ecdca77eda8b6b44ba2348253b999c3 | [
"Unlicense"
] | 4 | 2021-09-21T09:52:02.000Z | 2022-03-27T09:08:30.000Z | Utils/initialize.py | soshishimada/PhysCap_demo_release | 542756ed9ecdca77eda8b6b44ba2348253b999c3 | [
"Unlicense"
] | 10 | 2021-09-05T00:27:17.000Z | 2022-03-22T13:25:57.000Z | import numpy as np
import pybullet as p
| 34.571429 | 166 | 0.573462 |
f97e91890c0cdcab8847df722787798324fca2ec | 3,220 | py | Python | nlptasks/padding.py | ulf1/nlptasks | 07d36448b517a18f76088f5d9cfb853e7602b079 | [
"Apache-2.0"
] | 2 | 2020-12-30T13:11:09.000Z | 2021-11-04T19:40:31.000Z | nlptasks/padding.py | ulf1/nlptasks | 07d36448b517a18f76088f5d9cfb853e7602b079 | [
"Apache-2.0"
] | 99 | 2020-11-02T14:58:04.000Z | 2021-04-09T18:01:34.000Z | nlptasks/padding.py | ulf1/nlptasks | 07d36448b517a18f76088f5d9cfb853e7602b079 | [
"Apache-2.0"
] | null | null | null | import tensorflow.keras as keras # pad_sequences
from pad_sequences import pad_sequences_adjacency
from pad_sequences import pad_sequences_sparse
| 34.255319 | 73 | 0.617081 |
f97eb5e10ca3b047fe571ca899a9ef09001fcef1 | 4,894 | py | Python | py/g1/threads/tests/test_locks.py | clchiou/garage | 446ff34f86cdbd114b09b643da44988cf5d027a3 | [
"MIT"
] | 3 | 2016-01-04T06:28:52.000Z | 2020-09-20T13:18:40.000Z | py/g1/threads/tests/test_locks.py | clchiou/garage | 446ff34f86cdbd114b09b643da44988cf5d027a3 | [
"MIT"
] | null | null | null | py/g1/threads/tests/test_locks.py | clchiou/garage | 446ff34f86cdbd114b09b643da44988cf5d027a3 | [
"MIT"
] | null | null | null | import unittest
import threading
from g1.threads import locks
if __name__ == '__main__':
unittest.main()
| 28.619883 | 66 | 0.585411 |
f9835a83cc85b616ebc4877cb26f2e75d6afe07f | 1,104 | py | Python | statisticalDistributions.py | mrhsce/simPython | 94598164abc9833bad1121a978acb94c4fecec27 | [
"Apache-2.0"
] | 2 | 2015-12-19T04:27:12.000Z | 2016-11-23T18:53:50.000Z | statisticalDistributions.py | mrhsce/simPython | 94598164abc9833bad1121a978acb94c4fecec27 | [
"Apache-2.0"
] | null | null | null | statisticalDistributions.py | mrhsce/simPython | 94598164abc9833bad1121a978acb94c4fecec27 | [
"Apache-2.0"
] | null | null | null | """ Here definitions and attributes of all statistical distributions that are used in the simulation are defined"""
from abc import ABCMeta, abstractmethod
import random
#import np
| 19.714286 | 115 | 0.645833 |
f983fe925ecae418e3ac67726cae140e97825556 | 6,594 | py | Python | RainbowGrades/parsexml.py | hifiadi/Submitty | 62a8239313cff7e3f841ff66aeda6b0557e9c15b | [
"BSD-3-Clause"
] | 2 | 2017-10-11T17:48:33.000Z | 2020-12-15T16:05:05.000Z | RainbowGrades/parsexml.py | hifiadi/Submitty | 62a8239313cff7e3f841ff66aeda6b0557e9c15b | [
"BSD-3-Clause"
] | 4 | 2019-04-25T02:47:34.000Z | 2020-03-31T18:56:45.000Z | RainbowGrades/parsexml.py | hifiadi/Submitty | 62a8239313cff7e3f841ff66aeda6b0557e9c15b | [
"BSD-3-Clause"
] | 1 | 2020-02-07T19:19:20.000Z | 2020-02-07T19:19:20.000Z | #!/usr/bin/env python3
import csv
import xml.etree.ElementTree as ET
import sys
import os.path
def xml_to_csv(xml_filename):
"""
Parses .xml files generated by newer versions of iClicker software in SessionData
A CSV file will be written to the same path as the XML file, so it is important that any path, be it
absolute or relative, is included in the xml_filename argument. The CSV file is not a perfect replica of
older (i.e. iClicker 6) CSV files, but is our best approximation at this time. It should be enough for
Rainbow Grades to function properly.
"""
csv_filename = xml_filename[:-3] + "csv"
try:
with open(xml_filename,"r") as readfile:
tree = ET.parse(xml_filename)
root = tree.getroot()
questions_in_order = []
start_times = {}
stop_times = {}
user_question_data = {}
for child in root:
if child.tag == "p": # This is a polling tag
question = child.attrib["qn"]
start_times[question] = child.attrib["strt"]
stop_times[question] = child.attrib["stp"]
questions_in_order.append(question)
question_votes = {}
for qchild in child:
if qchild.tag == "v": # This is a voting tag
clicker_id = qchild.attrib["id"]
if clicker_id not in user_question_data:
user_question_data[clicker_id] = {}
user_question_data[clicker_id][question] = {}
if "fans" in qchild.attrib:
user_question_data[clicker_id][question] = QuestionData(qchild.attrib["ans"],
qchild.attrib["fanst"],
qchild.attrib["att"],
qchild.attrib["fans"],
qchild.attrib["tm"])
question_votes[clicker_id] = qchild.attrib["ans"]
with open(csv_filename, 'w') as writefile:
csvwriter = csv.writer(writefile) # Need to change dialect to be iclicker compliant
# Write the header
# Right now we don't have min reply/min correct in XML land, instead we have MinPart_S
next_row = ["Scoring"]
if "perf" in root.attrib:
performance = root.attrib["perf"]
else:
performance = -1
if "part" in root.attrib:
participation = root.attrib["part"]
else:
participation = 1
csvwriter.writerow(["Scoring", "Performance = " + performance,
"Participation = " + participation, "Min Reply = 2",
"Min Correct = 0",
" "])
next_row = ["Question", " ", " "]
for i in range(len(questions_in_order)):
next_row = next_row + ["Question " + str(i + 1), "Score", "Final Answer Time", "Number of Attempts",
"First Response", "Time"]
csvwriter.writerow(next_row)
next_row = ["Start Time", " ", " "]
for question in questions_in_order:
next_row = next_row + [" " + start_times[question], " ", " ", " ", " ", " "]
csvwriter.writerow(next_row)
next_row = ["Stop Time", " ", " "]
first_stop = True
for question in questions_in_order:
if not first_stop:
next_row = next_row + [" " + stop_times[question], " ", " ", " ", " ", " "]
else:
next_row = next_row + [stop_times[question], " ", " ", " ", " ", " "]
first_stop = False
csvwriter.writerow(next_row)
next_row = ["Correct Answer", " ", " "]
first_stop = True
for question in questions_in_order:
if not first_stop:
next_row = next_row + [" ", " ", " ", " ", " ", " "]
else:
next_row = next_row + ["", " ", " ", " ", " ", " "]
first_stop = False
csvwriter.writerow(next_row)
for user in sorted(user_question_data.keys()):
next_row = [user, "", "0"]
for question in questions_in_order:
if question in user_question_data[user]:
qd = user_question_data[user][question]
next_row = next_row + [qd.final_answer, 0, qd.final_answer_time, qd.attempts,
qd.first_answer, qd.first_answer_time]
else:
next_row = next_row + ["", "", "", "", "", ""]
csvwriter.writerow(next_row)
except IOError as e:
print("File I/O error: {}".format(e))
exit(-1)
if __name__ == '__main__':
if len(sys.argv) != 2:
print("Correct usage is {} [file with iclicker {\"file\":...} entries]".format(sys.argv[0]))
exit(-1)
files = []
try:
with open(sys.argv[1]) as json_file:
for line in json_file:
# Extract just the filenames of the session data
files += [x.strip()[1:-1] for x in line.split("[")[1].split("]")[0].split(",")]
except IOError as e:
print("Error reading JSON excerpt: {}".format(e))
for filename in files:
if len(filename) >= 4 and filename[-4:] == ".xml":
xml_to_csv(filename)
| 44.554054 | 120 | 0.474826 |
f98449b95d48df636ca504bf4073160f56093406 | 2,255 | py | Python | header.py | yufernando/inDelphi-app | 37938f7aaa1630fb80e7568d3d13472eedb76a6d | [
"FSFAP"
] | 13 | 2018-11-18T21:53:46.000Z | 2021-03-01T16:14:21.000Z | header.py | yufernando/inDelphi-app | 37938f7aaa1630fb80e7568d3d13472eedb76a6d | [
"FSFAP"
] | 2 | 2020-02-11T22:34:41.000Z | 2020-06-05T18:16:10.000Z | header.py | yufernando/inDelphi-app | 37938f7aaa1630fb80e7568d3d13472eedb76a6d | [
"FSFAP"
] | 3 | 2018-12-03T05:20:01.000Z | 2021-07-28T22:33:54.000Z | import dash
import dash_core_components as dcc
import dash_html_components as html
divider_text = ' '
| 23.010204 | 59 | 0.446563 |
f9850dd79a394638d5a5c2e62aadd31fb4c2407b | 96 | py | Python | venv/lib/python3.8/site-packages/poetry/core/_vendor/packaging/tags.py | GiulianaPola/select_repeats | 17a0d053d4f874e42cf654dd142168c2ec8fbd11 | [
"MIT"
] | 2 | 2022-03-13T01:58:52.000Z | 2022-03-31T06:07:54.000Z | venv/lib/python3.8/site-packages/poetry/core/_vendor/packaging/tags.py | DesmoSearch/Desmobot | b70b45df3485351f471080deb5c785c4bc5c4beb | [
"MIT"
] | 19 | 2021-11-20T04:09:18.000Z | 2022-03-23T15:05:55.000Z | venv/lib/python3.8/site-packages/poetry/core/_vendor/packaging/tags.py | DesmoSearch/Desmobot | b70b45df3485351f471080deb5c785c4bc5c4beb | [
"MIT"
] | null | null | null | /home/runner/.cache/pip/pool/68/e2/05/188e3a14bbe42690f0cbce7c7c576b1dbc9d3d1bb571a2d3908f144cea | 96 | 96 | 0.895833 |
f98574c16f4148423e98de5b6034c5f75d3ac988 | 217 | py | Python | toolbox/util/normalize.py | Yilin1010/DeleteKnowledge | 49b7e0e3a2247e482ba8876762719e4adb3074c6 | [
"Apache-2.0"
] | null | null | null | toolbox/util/normalize.py | Yilin1010/DeleteKnowledge | 49b7e0e3a2247e482ba8876762719e4adb3074c6 | [
"Apache-2.0"
] | null | null | null | toolbox/util/normalize.py | Yilin1010/DeleteKnowledge | 49b7e0e3a2247e482ba8876762719e4adb3074c6 | [
"Apache-2.0"
] | null | null | null | # -*- coding: utf-8 -*-
"""
Created on Tue May 24 11:14:03 2016
@author: Wajih-PC
"""
import numpy as np
| 19.727273 | 36 | 0.580645 |
f986bf3f2c420c696f6c53ea84f10ad7ccfa26ea | 1,526 | py | Python | demos/pandas/pandas_concat&append.py | szj2ys/deal_with_the_tasks_and_challenges | 94b9f4aad26c7e2ec5a59cf67e9e977bfa3d5221 | [
"Apache-2.0"
] | null | null | null | demos/pandas/pandas_concat&append.py | szj2ys/deal_with_the_tasks_and_challenges | 94b9f4aad26c7e2ec5a59cf67e9e977bfa3d5221 | [
"Apache-2.0"
] | null | null | null | demos/pandas/pandas_concat&append.py | szj2ys/deal_with_the_tasks_and_challenges | 94b9f4aad26c7e2ec5a59cf67e9e977bfa3d5221 | [
"Apache-2.0"
] | null | null | null | import pandas as pd
import numpy as np
#
df1 = pd.DataFrame(np.ones((3, 4)) * 0, columns=['a', 'b', 'c', 'd'])
df2 = pd.DataFrame(np.ones((3, 4)) * 1, columns=['a', 'b', 'c', 'd'])
df3 = pd.DataFrame(np.ones((3, 4)) * 2, columns=['a', 'b', 'c', 'd'])
#concat axis=0axis=1
res = pd.concat([df1, df2, df3], axis=1)
#
print(res)
#index_ignoreTrue(index0-8)
res = pd.concat([df1, df2, df3], axis=0, ignore_index=True)
#
print(res)
#
df1 = pd.DataFrame(np.ones((3, 4)) * 0,
columns=['a', 'b', 'c', 'd'],
index=[1, 2, 3])
df2 = pd.DataFrame(np.ones((3, 4)) * 1,
columns=['b', 'c', 'd', 'e'],
index=[2, 3, 4])
#""df1df2joinoutercolumnNaN
res = pd.concat([df1, df2], axis=0, join='outer')
#
print(res)
#""df1df2,joininnercolumn
res = pd.concat([df1, df2], axis=0, join='inner')
#
print(res)
#
df1 = pd.DataFrame(np.ones((3, 4)) * 0, columns=['a', 'b', 'c', 'd'])
df2 = pd.DataFrame(np.ones((3, 4)) * 1, columns=['a', 'b', 'c', 'd'])
df3 = pd.DataFrame(np.ones((3, 4)) * 1, columns=['a', 'b', 'c', 'd'])
s1 = pd.Series([1, 2, 3, 4], index=['a', 'b', 'c', 'd'])
#df2df1index
res = df1.append(df2, ignore_index=True) #append
print(res)
#dfdf2df3df1index
res = df1.append([df2, df3], ignore_index=True)
print(res)
#seriess1df1index
res = df1.append(s1, ignore_index=True)
print(res)
| 26.310345 | 69 | 0.593054 |
f9873b3ec6305739faa020963cb0f6929823dc6d | 799 | py | Python | e/mail-relay/web/apps/core/migrations/0051_customersetting_transfer_max_size.py | zhouli121018/nodejsgm | 0ccbc8acf61badc812f684dd39253d55c99f08eb | [
"MIT"
] | null | null | null | e/mail-relay/web/apps/core/migrations/0051_customersetting_transfer_max_size.py | zhouli121018/nodejsgm | 0ccbc8acf61badc812f684dd39253d55c99f08eb | [
"MIT"
] | 18 | 2020-06-05T18:17:40.000Z | 2022-03-11T23:25:21.000Z | e/mail-relay/web/apps/core/migrations/0051_customersetting_transfer_max_size.py | zhouli121018/nodejsgm | 0ccbc8acf61badc812f684dd39253d55c99f08eb | [
"MIT"
] | null | null | null | # -*- coding: utf-8 -*-
from __future__ import unicode_literals
from django.db import models, migrations
| 39.95 | 421 | 0.713392 |
f9873ed126ec1fdd07f8e281595ede0f1e5dfbf6 | 4,128 | py | Python | python-django/oauth2demo/oauth/core/oauthclient.py | SequencingDOTcom/oAuth2-demo | 609bd138cff07643a0c3e1df48f4f2e4adc9be34 | [
"MIT"
] | 1 | 2020-11-05T22:16:37.000Z | 2020-11-05T22:16:37.000Z | python-django/oauth2demo/oauth/core/oauthclient.py | SequencingDOTcom/oAuth2-demo | 609bd138cff07643a0c3e1df48f4f2e4adc9be34 | [
"MIT"
] | 3 | 2018-02-24T15:01:20.000Z | 2021-11-29T17:29:02.000Z | python-django/oauth2demo/oauth/core/oauthclient.py | SequencingDOTcom/oAuth2-demo | 609bd138cff07643a0c3e1df48f4f2e4adc9be34 | [
"MIT"
] | 3 | 2017-04-06T01:38:20.000Z | 2017-05-17T09:44:35.000Z | import urllib
import sched
import time
from threading import Thread
from token import Token
from ..utils.http import do_basic_secure_post
from ..exceptions.exceptions import BasicAuthenticationFailedException
| 34.115702 | 96 | 0.678537 |
f987b372c8da570186369c27352bfdc8a2dc0b25 | 1,019 | py | Python | commands/elastic/utils.py | surfedushare/search-portal | f5486d6b07b7b04a46ce707cee5174db4f8da222 | [
"MIT"
] | 2 | 2021-08-19T09:40:59.000Z | 2021-12-14T11:08:20.000Z | commands/elastic/utils.py | surfedushare/search-portal | 708a0d05eee13c696ca9abd7e84ab620d3900fbe | [
"MIT"
] | 159 | 2020-05-14T14:17:34.000Z | 2022-03-23T10:28:13.000Z | commands/elastic/utils.py | nppo/search-portal | aedf21e334f178c049f9d6cf37cafd6efc07bc0d | [
"MIT"
] | 1 | 2021-11-11T13:37:22.000Z | 2021-11-11T13:37:22.000Z | from elasticsearch import Elasticsearch, RequestsHttpConnection
from requests_aws4auth import AWS4Auth
import boto3
def get_es_client(conn, silent=False):
"""
Returns the elasticsearch client connected through port forwarding settings
"""
elastic_url = "https://localhost:9222"
protocol_config = {
"scheme": "https",
"port": 9222,
"use_ssl": True,
"verify_certs": False,
}
credentials = boto3.Session(profile_name=conn.aws.profile_name).get_credentials()
http_auth = AWS4Auth(credentials.access_key, credentials.secret_key, "eu-central-1", "es",
session_token=credentials.token)
es_client = Elasticsearch(
[elastic_url],
http_auth=http_auth,
connection_class=RequestsHttpConnection,
**protocol_config
)
# test if it works
if not silent and not es_client.cat.health(request_timeout=30):
raise ValueError('Credentials do not work for Elastic search')
return es_client
| 31.84375 | 94 | 0.684004 |
f98a6174a8d5b6ced1433ccb3968837fdf52d7af | 7,135 | py | Python | tests/test_signals.py | sulfadimetoxin/oarepo-taxonomies | b8385173614aa711a5e316c8fc24ac065b48aa3d | [
"MIT"
] | null | null | null | tests/test_signals.py | sulfadimetoxin/oarepo-taxonomies | b8385173614aa711a5e316c8fc24ac065b48aa3d | [
"MIT"
] | 9 | 2020-08-24T08:49:15.000Z | 2021-08-05T16:45:23.000Z | tests/test_signals.py | sulfadimetoxin/oarepo-taxonomies | b8385173614aa711a5e316c8fc24ac065b48aa3d | [
"MIT"
] | 1 | 2020-08-20T18:39:43.000Z | 2020-08-20T18:39:43.000Z | from pprint import pprint
import pytest
from flask_taxonomies.proxies import current_flask_taxonomies
from flask_taxonomies.term_identification import TermIdentification
from invenio_records import Record
from oarepo_taxonomies.exceptions import DeleteAbortedError
from oarepo_taxonomies.signals import lock_term
from oarepo_taxonomies.tasks import unlock_term
| 38.777174 | 99 | 0.568605 |
f98c3635dfd0d3ae569222c031b018e24dab8ea9 | 1,322 | py | Python | sendemail/views.py | sami-sinnari/MilestoneProject4 | 4a66f5cd5e44e9ff4dbaeeb3e8733c0e2db6629e | [
"W3C",
"PostgreSQL"
] | null | null | null | sendemail/views.py | sami-sinnari/MilestoneProject4 | 4a66f5cd5e44e9ff4dbaeeb3e8733c0e2db6629e | [
"W3C",
"PostgreSQL"
] | null | null | null | sendemail/views.py | sami-sinnari/MilestoneProject4 | 4a66f5cd5e44e9ff4dbaeeb3e8733c0e2db6629e | [
"W3C",
"PostgreSQL"
] | 1 | 2021-08-31T03:29:02.000Z | 2021-08-31T03:29:02.000Z | from django.core.mail import send_mail, BadHeaderError
from django.http import HttpResponse
from django.shortcuts import render, redirect
from .forms import ContactForm
from profiles.models import UserProfile
| 31.47619 | 78 | 0.621785 |
f98cbeedab7f46e8e4601542568092c0c0c15c19 | 592 | py | Python | tests/test_accounts.py | edgeee/buycoins-python | 72a3130cf43d0c618e58418b3d8cb7ce73b0f133 | [
"MIT"
] | 55 | 2021-02-02T22:09:37.000Z | 2022-02-24T12:17:23.000Z | tests/test_accounts.py | edgeee/buycoins-python | 72a3130cf43d0c618e58418b3d8cb7ce73b0f133 | [
"MIT"
] | 2 | 2021-03-24T20:11:02.000Z | 2021-04-27T13:13:27.000Z | tests/test_accounts.py | edgeee/buycoins-python | 72a3130cf43d0c618e58418b3d8cb7ce73b0f133 | [
"MIT"
] | 8 | 2021-02-08T17:06:53.000Z | 2022-02-13T09:38:59.000Z | from tests.utils import _mock_gql
create_deposit_response = dict(
createDepositAccount=dict(
accountNumber="123",
accountName="john doe",
accountType="deposit",
bankName="Providus",
accountReference="ref",
)
)
| 23.68 | 58 | 0.689189 |
f98d3f6b60f1e702d811a09d53f295688785eb0a | 3,755 | py | Python | fabfile/s3_copy.py | MadeInHaus/django-template | 73d3bdb85e9b1b2723a1de67d6765ce0647dce3a | [
"MIT"
] | 1 | 2015-06-18T22:37:28.000Z | 2015-06-18T22:37:28.000Z | fabfile/s3_copy.py | MadeInHaus/django-template | 73d3bdb85e9b1b2723a1de67d6765ce0647dce3a | [
"MIT"
] | 11 | 2015-01-07T16:58:55.000Z | 2022-01-27T16:22:22.000Z | fabfile/s3_copy.py | MadeInHaus/django-template | 73d3bdb85e9b1b2723a1de67d6765ce0647dce3a | [
"MIT"
] | null | null | null | from fabric.decorators import task, roles
from haus_vars import APP_INFO, parse_vars
from fabric.api import run, execute
from fabric.context_managers import cd
from heroku import create_fixture_on_s3, grab_fixture_on_s3
import cStringIO
| 40.376344 | 170 | 0.694541 |
f98d78abc4c61ae00ffd3cee5b5299a82b124239 | 505 | py | Python | umysqldb/__init__.py | arozumenko/pyumysql | 34b61faf33e2db644b02c483c07ddca32165539a | [
"Apache-2.0"
] | null | null | null | umysqldb/__init__.py | arozumenko/pyumysql | 34b61faf33e2db644b02c483c07ddca32165539a | [
"Apache-2.0"
] | null | null | null | umysqldb/__init__.py | arozumenko/pyumysql | 34b61faf33e2db644b02c483c07ddca32165539a | [
"Apache-2.0"
] | null | null | null | from umysqldb import connections
from umysqldb import cursors
Connection = Connect = connect | 42.083333 | 79 | 0.609901 |
f98fe6f86f42085c174f1fcd733ce2400cb3d904 | 2,696 | py | Python | system_monitor_script/build_network.py | carabri/carabri | c8b94080331ab66ee116ee6e87e13e295e4f9604 | [
"Apache-2.0"
] | null | null | null | system_monitor_script/build_network.py | carabri/carabri | c8b94080331ab66ee116ee6e87e13e295e4f9604 | [
"Apache-2.0"
] | null | null | null | system_monitor_script/build_network.py | carabri/carabri | c8b94080331ab66ee116ee6e87e13e295e4f9604 | [
"Apache-2.0"
] | null | null | null | import re
import networkx
import itertools
import argparse
import json
if __name__ == '__main__':
argparser = argparse.ArgumentParser(description='Build a network from the given usage log file, then write it to an edge list.')
argparser.add_argument('--filename',type=str,help='provide the memory log file for building the network. Defaults to ./memory.log.sample',default='./memory.log.sample')
argparser.add_argument('--outfile',type=str,help='specify the desired path/name for the output edge list. Defaults to ./example.edgelist',default='./example.edgelist')
argparser.add_argument('--threshold',type=int,help='specify the minimum memory threshold (in MB) of the processes used in the final network. Defaults to 1000',default=1000)
args = argparser.parse_args()
build_network(args.filename,args.outfile,args.threshold) | 42.125 | 177 | 0.555267 |
f98fff79925e8d8be7997e37273c0b32991d86de | 1,428 | py | Python | BigO/insertion_sort.py | jeff-lund/CS350 | 7227b53275c62d45e899a531136a96a866c32a16 | [
"MIT"
] | 2 | 2019-10-16T01:59:42.000Z | 2019-11-13T19:25:00.000Z | BigO/insertion_sort.py | jeff-lund/CS350 | 7227b53275c62d45e899a531136a96a866c32a16 | [
"MIT"
] | null | null | null | BigO/insertion_sort.py | jeff-lund/CS350 | 7227b53275c62d45e899a531136a96a866c32a16 | [
"MIT"
] | 2 | 2019-10-16T01:59:49.000Z | 2019-11-15T01:19:18.000Z | from sys import argv
from random import randint
from time import time
import matplotlib.pyplot as plt
if __name__ == '__main__':
if len(argv) > 1:
sz = int(argv[1])
arr = [randint(1, 1000) for _ in range(sz)]
#print(arr)
start = time()
insertion_sort(arr)
end = time()
#print(arr)
print(end - start)
else:
# performs automated testing
x = []
y = []
sizes = [10, 50, 100, 200, 500, 1000, 1200, 1500, 2000, 2500, 3000, 5000, 6000, 7000, 8000, 9000, 10000, 20000, 30000, 40000]
for sz in sizes:
t = 0
print("running size", sz)
for _ in range(10):
arr = [randint(1, 10000) for _ in range(sz)]
start = time()
insertion_sort(arr)
end = time()
t += (end - start) * 1000
x.append(sz)
y.append(t // 10)
# Plot results of tests
plt.plot(x, y)
plt.xlabel("n (size of array)")
plt.ylabel("time (ms)")
plt.show()
#plt.savefig("python_running_times.png", format='png')
| 28.56 | 134 | 0.459384 |
f994d4e53b4b2fdca4fdd7080892fff0acd2645e | 638 | py | Python | tasks.py | RevolutionTech/revolutiontech.ca | a3f0f1526812554938674c4fc9e7ea90ed4ffe6d | [
"0BSD"
] | null | null | null | tasks.py | RevolutionTech/revolutiontech.ca | a3f0f1526812554938674c4fc9e7ea90ed4ffe6d | [
"0BSD"
] | 171 | 2017-11-02T05:39:37.000Z | 2022-03-07T01:13:53.000Z | tasks.py | RevolutionTech/carrier-owl | f72f47e39ea819681fa7b50de2b52e393edeeb96 | [
"0BSD"
] | 1 | 2018-01-13T08:11:26.000Z | 2018-01-13T08:11:26.000Z | from invoke import Collection, task
from opstrich.invoke import check, openssl
namespace = Collection(check, openssl, deploy, ci_deploy)
| 23.62963 | 106 | 0.694357 |
f994d8e1e290868506a6fadbde009edec090ad8b | 2,490 | py | Python | bear/scripts/lunar_lander/remove_data.py | junmokane/AI602_Project | 59c132ae04751f9fb6cf6ebb491042cbf4de003d | [
"Apache-2.0"
] | 1 | 2020-10-14T05:51:36.000Z | 2020-10-14T05:51:36.000Z | bear/scripts/lunar_lander/remove_data.py | junmokane/AI602_Project | 59c132ae04751f9fb6cf6ebb491042cbf4de003d | [
"Apache-2.0"
] | null | null | null | bear/scripts/lunar_lander/remove_data.py | junmokane/AI602_Project | 59c132ae04751f9fb6cf6ebb491042cbf4de003d | [
"Apache-2.0"
] | null | null | null | import torch
import numpy as np
import copy
if __name__ == "__main__":
path = "/home/seungjae/Desktop/lunarlander/replay_buffer.pt"
remove(path) | 35.070423 | 112 | 0.65743 |
f9990629b2219f3dd1a7da2e2230e3d0eb99c9a8 | 2,435 | py | Python | flex/http/negotiators.py | centergy/flex | 4fc11d3ad48e4b5016f53256015e3eed2157daae | [
"MIT"
] | null | null | null | flex/http/negotiators.py | centergy/flex | 4fc11d3ad48e4b5016f53256015e3eed2157daae | [
"MIT"
] | null | null | null | flex/http/negotiators.py | centergy/flex | 4fc11d3ad48e4b5016f53256015e3eed2157daae | [
"MIT"
] | null | null | null | """
Content negotiation deals with selecting an appropriate renderer given the
incoming request. Typically this will be based on the request's Accept header.
"""
import flask as fl
from . import exc
| 27.988506 | 92 | 0.70308 |
f999e5eac5ca0101fdb8157a0b22f62d11306d51 | 403 | py | Python | accounts/migrations/0005_addtocart_cart_useremail.py | noelsj007/ecommerceweb | e00edfe9110d2cc54deebd97043e0aa152c8afd4 | [
"Unlicense"
] | null | null | null | accounts/migrations/0005_addtocart_cart_useremail.py | noelsj007/ecommerceweb | e00edfe9110d2cc54deebd97043e0aa152c8afd4 | [
"Unlicense"
] | null | null | null | accounts/migrations/0005_addtocart_cart_useremail.py | noelsj007/ecommerceweb | e00edfe9110d2cc54deebd97043e0aa152c8afd4 | [
"Unlicense"
] | null | null | null | # Generated by Django 3.0.8 on 2020-08-11 14:16
from django.db import migrations, models
| 21.210526 | 66 | 0.60794 |
f99b06a71dceb4f5f766c0212d0a17f6f162c70a | 539 | py | Python | uva_answers/10018/main.py | andriisoldatenko/fan | e7ed6ea0f39bd71af4e286af8d81ebc137ae8ff4 | [
"MIT"
] | 6 | 2018-11-18T15:00:02.000Z | 2022-03-23T21:32:24.000Z | uva_answers/10018/main.py | andriisoldatenko/leetcode | 8fef4da00234f8acbea9b71ee730b2267b70395f | [
"MIT"
] | null | null | null | uva_answers/10018/main.py | andriisoldatenko/leetcode | 8fef4da00234f8acbea9b71ee730b2267b70395f | [
"MIT"
] | null | null | null | import pprint
import sys
import re
FILE = sys.stdin
#FILE = open('sample.in')
#import ipdb;ipdb.set_trace()
test_cases = range(int(FILE.readline()))
#import ipdb; ipdb.set_trace()
for tc in test_cases:
n = int(FILE.readline().strip())
total_sum_count = 1
n = reverse_add(n)
while not is_palindrome(n):
n = reverse_add(n)
total_sum_count += 1
print(total_sum_count, n)
| 20.730769 | 40 | 0.64564 |
f99c7dc6ce29a2ffb9fe2abe6759971a3c9cf033 | 214 | py | Python | cogkge/data/processor/fb15k237processor.py | jinzhuoran/CogKGE | b0e819a1d34cf61a7d70c33808da3377b73c8fd6 | [
"MIT"
] | 18 | 2022-01-22T09:52:57.000Z | 2022-03-22T15:02:12.000Z | cogkge/data/processor/fb15k237processor.py | CogNLP/CogKGE | 70d851d6489600c1e90eb25b0388a3ceba2f078c | [
"MIT"
] | null | null | null | cogkge/data/processor/fb15k237processor.py | CogNLP/CogKGE | 70d851d6489600c1e90eb25b0388a3ceba2f078c | [
"MIT"
] | null | null | null | from .baseprocessor import BaseProcessor
| 30.571429 | 71 | 0.771028 |
f99d843d5eb26f48db07153b199bcf310e6ecade | 1,256 | pyw | Python | python/discord.pyw | hentai-burner/mastur-beta | 2893a4ef3ee4aae5a9a78141badae4e6544fb071 | [
"MIT"
] | null | null | null | python/discord.pyw | hentai-burner/mastur-beta | 2893a4ef3ee4aae5a9a78141badae4e6544fb071 | [
"MIT"
] | null | null | null | python/discord.pyw | hentai-burner/mastur-beta | 2893a4ef3ee4aae5a9a78141badae4e6544fb071 | [
"MIT"
] | null | null | null | import time
import os
import pathlib
import sys
from subprocess import call
#TODO: Maybe make a pip_handler file idk
try:
from pypresence import presence
except:
pip_install("pypresence")
STATUS_TEXT = str(sys.argv)
IMGID_CONSTS = ['furcock_img', 'blacked_img', 'censored_img', 'goon_img',
'goon2_img', 'hypno_img', 'futa_img', 'healslut_img', 'gross_img']
if not STATUS_TEXT == '':
try:
#if has file, tries to split at newline break
# uses first line as the string for text description
# uses second line as the image id for requesting image from discord api
ls = STATUS_TEXT.split('\n')
STATUS_TEXT[0] = ls[0]
if ls[1] in IMGID_CONSTS:
STATUS_TEXT[1] = ls[1]
except:
print('failed line split') #tweak this
do_discord()
| 27.304348 | 84 | 0.621815 |
f99fbafb536fdd0dcee45c41f8a1a58e47ef7f46 | 1,086 | py | Python | 2dtree/bin/bpy_validation.py | LeanderSilur/Snippets | 3ff718f91439450bd5aff13342aa98a9d4957e85 | [
"MIT"
] | 9 | 2020-02-04T05:41:09.000Z | 2022-03-08T06:14:54.000Z | 2dtree/bin/bpy_validation.py | LeanderSilur/Snippets | 3ff718f91439450bd5aff13342aa98a9d4957e85 | [
"MIT"
] | 2 | 2020-06-14T19:58:01.000Z | 2021-07-04T14:21:33.000Z | 2dtree/bin/bpy_validation.py | LeanderSilur/Snippets | 3ff718f91439450bd5aff13342aa98a9d4957e85 | [
"MIT"
] | 2 | 2020-07-29T19:54:44.000Z | 2020-07-29T20:00:24.000Z | import bpy
import subprocess
REBUILD = 0
if REBUILD:
subprocess.call([
"g++",
bpy.path.abspath('//../main.cpp'),
bpy.path.abspath('//../PtTree.cpp'),
"-o",
bpy.path.abspath('//PtTree')
])
# Collect the input data.
verts = bpy.data.meshes['PointCloud'].vertices
query_amount = 5
query_obj = bpy.data.objects['Search']
query_pos = query_obj.location
query_radius = query_obj.dimensions[0] / 2
points = [str(v.co.x) + ',' + str(v.co.y) for v in verts]
args = [
bpy.path.abspath('//PtTree.exe'),
str(query_amount),
str(query_radius),
str(query_pos.x) + ',' + str(query_pos.y),
*points
]
# Make the call.
proc = subprocess.run(args, encoding='utf-8', stdout=subprocess.PIPE)
stdout = proc.stdout.split('\n')
[print(line) for line in stdout]
ids = [int(line.split(" ")[0]) for line in stdout]
# Visualize the output.
bpy.ops.object.mode_set(mode="OBJECT")
for i in range(len(verts)):
verts[i].select = False
if i in ids:
verts[i].select = True
bpy.ops.object.mode_set(mode="EDIT") | 22.163265 | 69 | 0.621547 |
f9a216fdaa67e5fc6913f5aa98c379d5a25e120e | 10,274 | py | Python | zgrab2_schemas/zgrab2/ssh.py | aspacewalz/zgrab2 | d9ed4f141dae102d65ba1e08bf2eb4179678d172 | [
"Apache-2.0"
] | 1,031 | 2016-11-29T15:12:05.000Z | 2022-03-31T05:02:50.000Z | zgrab2_schemas/zgrab2/ssh.py | vl4deee11/zgrab2 | c859e9ef1173955dadae88416289ef8cc8910495 | [
"Apache-2.0"
] | 191 | 2017-07-24T17:27:57.000Z | 2022-03-16T04:59:59.000Z | zgrab2_schemas/zgrab2/ssh.py | vl4deee11/zgrab2 | c859e9ef1173955dadae88416289ef8cc8910495 | [
"Apache-2.0"
] | 230 | 2017-11-14T07:25:57.000Z | 2022-03-31T04:20:46.000Z | # zschema sub-schema for zgrab2's ssh module (modules/ssh.go)
# Registers zgrab2-ssh globally, and ssh with the main zgrab2 schema.
from zschema.leaves import *
from zschema.compounds import *
import zschema.registry
import zcrypto_schemas.zcrypto as zcrypto
from . import zgrab2
# NOTE: Despite the fact that we have e.g. "supportedHostKeyAlgos",
# "allSupportedCiphers", etc, including a different value is not syntactically
# incorrect...so all of the following algorithm identifiers are Strings with
# examples=[...], rather tha Enums with values=[...].
# lib/ssh/common.go -- allSupportedKexAlgos
KexAlgorithm = String.with_args(
doc="An ssh key exchange algorithm identifier, named according to section 6 of https://www.ietf.org/rfc/rfc4251.txt; see https://www.iana.org/assignments/ssh-parameters/ssh-parameters.xhtml#ssh-parameters-15 for standard values.",
examples=[
"diffie-hellman-group1-sha1",
"diffie-hellman-group14-sha1",
"ecdh-sha2-nistp256",
"ecdh-sha2-nistp384",
"ecdh-sha2-nistp521",
"curve25519-sha256@libssh.org",
"diffie-hellman-group-exchange-sha1",
"diffie-hellman-group-exchange-sha256",
]
)
KexAlgorithms = ListOf.with_args(KexAlgorithm())
# Defined in lib/ssh/common.go -- supportedHostKeyAlgos, though they are
# generated via PublicKey.Type()
KeyAlgorithm = String.with_args(
doc="An ssh public key algorithm identifier, named according to section 6 of https://www.ietf.org/rfc/rfc4251.txt; see https://www.iana.org/assignments/ssh-parameters/ssh-parameters.xhtml#ssh-parameters-19 for standard values.",
examples=[
"ssh-rsa-cert-v01@openssh.com",
"ssh-dss-cert-v01@openssh.com",
"ecdsa-sha2-nistp256-cert-v01@openssh.com",
"ecdsa-sha2-nistp384-cert-v01@openssh.com",
"ecdsa-sha2-nistp521-cert-v01@openssh.com",
"ssh-ed25519-cert-v01@openssh.com",
"ssh-rsa",
"ssh-dss",
"ecdsa-sha2-nistp256",
"ecdsa-sha2-nistp384",
"ecdsa-sha2-nistp521",
"ssh-ed25519",
]
)
KeyAlgorithms = ListOf.with_args(KeyAlgorithm())
# From lib/ssh/common.go -- allSupportedCiphers
CipherAlgorithm = String.with_args(
doc="An ssh cipher algorithm identifier, named according to section 6 of https://www.ietf.org/rfc/rfc4251.txt; see https://www.iana.org/assignments/ssh-parameters/ssh-parameters.xhtml#ssh-parameters-16 for standard values.",
examples=[
"aes128-ctr", "aes192-ctr", "aes256-ctr", "aes128-gcm@openssh.com",
"aes128-cbc", "3des-cbc", "arcfour256", "arcfour128", "arcfour",
]
)
CipherAlgorithms = ListOf.with_args(CipherAlgorithm())
# From lib/ssh/common.go -- supportedMACs.
MACAlgorithm = String.with_args(
doc="An ssh MAC algorithm identifier, named according to section 6 of https://www.ietf.org/rfc/rfc4251.txt; see https://www.iana.org/assignments/ssh-parameters/ssh-parameters.xhtml#ssh-parameters-18 for standard values.",
examples=["hmac-sha2-256", "hmac-sha1", "hmac-sha1-96"]
)
MACAlgorithms = ListOf.with_args(MACAlgorithm())
# From lib/ssh/common.go -- supportedCompressions
CompressionAlgorithm = String.with_args(
doc="An ssh compression algorithm identifier, named according to section 6 of https://www.ietf.org/rfc/rfc4251.txt; see https://www.iana.org/assignments/ssh-parameters/ssh-parameters.xhtml#ssh-parameters-20 for standard values.",
examples=["none", "zlib"]
)
CompressionAlgorithms = ListOf.with_args(CompressionAlgorithm())
LanguageTag = String.with_args(doc="A language tag, as defined in https://www.ietf.org/rfc/rfc3066.txt.")
LanguageTags = ListOf.with_args(LanguageTag(), doc="A name-list of language tags in order of preference.")
# zgrab2/lib/ssh/messages.go: (Json)kexInitMsg
KexInitMessage = SubRecordType({
"cookie": Binary(),
"kex_algorithms": KexAlgorithms(doc="Key exchange algorithms used in the handshake."),
"host_key_algorithms": KeyAlgorithms(doc="Asymmetric key algorithms for the host key supported by the client."),
"client_to_server_ciphers": CipherAlgorithms(),
"server_to_client_ciphers": CipherAlgorithms(),
"client_to_server_macs": MACAlgorithms(),
"server_to_client_macs": MACAlgorithms(),
"client_to_server_compression": CompressionAlgorithms(),
"server_to_client_compression": CompressionAlgorithms(),
"client_to_server_languages": LanguageTags(),
"server_to_client_languages": LanguageTags(),
"first_kex_follows": Boolean(),
"reserved": Unsigned32BitInteger(),
})
# zgrab2/lib/ssh/log.go: EndpointId
EndpointID = SubRecordType({
"raw": String(),
"version": String(),
"software": String(),
"comment": String(),
})
# This could be merged into a single class with e.g. an analyzed param,
# but it's probably clearer to just duplicate it.
AnalyzedEndpointID = SubRecordType({
"raw": AnalyzedString(),
"version": String(),
"software": AnalyzedString(),
"comment": AnalyzedString(),
})
# zgrab2/lib/ssh/kex.go: kexResult
KexResult = SubRecordType({
"H": Binary(),
"K": Binary(),
"session_id": Binary()
})
# zgrab2/lib/ssh/keys.go: ed25519PublicKey
ED25519PublicKey = SubRecordType({
"public_bytes": Binary(),
})
# zgrab2/lib/ssh/kex.go: curve25519sha256JsonLogParameters (via curve25519sha256)
Curve25519SHA256Params = SubRecordType({
"client_public": Binary(required=False),
"client_private": Binary(required=False),
"server_public": Binary(required=False),
})
# zgrab2/lib/ssh/certs.go: JsonSignature
Signature = SubRecordType({
"parsed": SubRecord({
"algorithm": KeyAlgorithm(),
"value": Binary(),
}),
"raw": Binary(),
"h": Binary(),
})
# lib/ssh/kex.go: PublicKeyJsonLog, sans the certkey_public_key (since that would create a loop)
SSHPublicKey = SubRecordType({
"raw": Binary(),
"fingerprint_sha256": String(),
# TODO: Enum? Obviously must serialize to one of rsa/dsa/ecdsa/ed25519_public_key...
"algorithm": String(),
# For compatiblity with ztag
"key_algorithm":String(),
"rsa_public_key": zcrypto.RSAPublicKey(),
"dsa_public_key": zcrypto.DSAPublicKey(),
"ecdsa_public_key": zcrypto.ECDSAPublicKey(),
"ed25519_public_key": ED25519PublicKey(),
})
# lib/ssh/certs.go: JsonCertType
CertType = SubRecordType({
"id": Unsigned32BitInteger(doc="The numerical certificate type value. 1 identifies user certificates, 2 identifies host certificates."),
"name": Enum(values=["USER", "HOST", "unknown"], doc="The human-readable name for the certificate type."),
})
# lib/ssh/certs.go: JsonCertificate
SSHPublicKeyCert = SubRecord.with_args({
# TODO: Use / include our cert type here, or maybe somewhere else in the response?
"certkey_public_key": SubRecord({
"nonce": Binary(),
# Note that this is not recursive, since SSHPublicKey() does not include certkey_public_key.
"key": SSHPublicKey(),
"serial": String(doc="The certificate serial number, encoded as a base-10 string."),
"cert_type": CertType(),
"key_id": String(doc="A free-form text field filled in by the CA at the time of signing, intended to identify the principal in log messages."),
"valid_principals": ListOf(String(), doc="Names for which this certificate is valid; hostnames for cert_type=HOST certificates and usernames for cert_type=USER certificates."),
"validity": SubRecord({
"valid_after": DateTime(doc="Timestamp of when certificate is first valid. Timezone is UTC."),
"valid_before": DateTime(doc="Timestamp of when certificate expires. Timezone is UTC."),
"length": Signed64BitInteger(),
}),
"reserved": Binary(),
"signature_key": SSHPublicKey(),
"signature": Signature(),
"parse_error": String(),
"extensions": SubRecord({
"known": SubRecord({
"permit_X11_forwarding": String(),
"permit_agent_forwarding": String(),
"permit_port_forwarding": String(),
"permit_pty": String(),
"permit_user_rc": String(),
}),
"unknown": ListOf(String()),
}),
"critical_options": SubRecord({
"known": SubRecord({
"force_command": String(),
"source_address": String(),
}),
"unknown": ListOf(String()),
})
})
}, extends=SSHPublicKey())
# zgrab2/lib/ssh/common.go: directionAlgorithms
DirectionAlgorithms = SubRecordType({
"cipher": CipherAlgorithm(),
"mac": MACAlgorithm(),
"compression": CompressionAlgorithm(),
})
# zgrab2/lib/ssh/kex.go: interface kexAlgorithm
# Searching usages of kexAlgorithm turns up:
# - dhGroup: dh_params, server_signature, server_host_key
# - ecdh: ecdh_params, server_signature, server_host_key
# - curve25519sha256: curve25519_sha256_params, server_signature, server_host_key
# - dhGEXSHA: dh_params, server_signature, server_host_key
KeyExchange = SubRecordType({
"curve25519_sha256_params": Curve25519SHA256Params(),
"ecdh_params": zcrypto.ECDHParams(),
"dh_params": zcrypto.DHParams(),
"server_signature": Signature(),
"server_host_key": SSHPublicKeyCert(),
})
# zgrab2/lib/ssh/common.go: algorithms (aux in MarshalJSON)
AlgorithmSelection = SubRecordType({
"dh_kex_algorithm": KexAlgorithm(),
"host_key_algorithm": KeyAlgorithm(),
"client_to_server_alg_group": DirectionAlgorithms(),
"server_to_client_alg_group": DirectionAlgorithms(),
})
# zgrab2/lib/ssh/log.go: HandshakeLog
# TODO: Can ssh re-use any of the generic TLS model?
ssh_scan_response = SubRecord({
"result": SubRecord({
"banner": WhitespaceAnalyzedString(),
"server_id": AnalyzedEndpointID(),
"client_id": EndpointID(),
"server_key_exchange": KexInitMessage(),
"client_key_exchange": KexInitMessage(),
"algorithm_selection": AlgorithmSelection(),
"key_exchange": KeyExchange(),
"userauth": ListOf(String()),
"crypto": KexResult(),
})
}, extends=zgrab2.base_scan_response)
zschema.registry.register_schema("zgrab2-ssh", ssh_scan_response)
zgrab2.register_scan_response_type("ssh", ssh_scan_response)
| 40.448819 | 234 | 0.694569 |
f9a21f50645fbd8f00212379587d12cc0568bcd5 | 5,123 | py | Python | app/main/views.py | Juru-10/blog | ac554952e884c35ce7dd50cf0ef9748a8da96a3f | [
"MIT"
] | null | null | null | app/main/views.py | Juru-10/blog | ac554952e884c35ce7dd50cf0ef9748a8da96a3f | [
"MIT"
] | null | null | null | app/main/views.py | Juru-10/blog | ac554952e884c35ce7dd50cf0ef9748a8da96a3f | [
"MIT"
] | null | null | null | from flask import render_template,request,redirect,url_for,abort
from ..models import User,Post,Comment,Subscriber
from ..requests import get_quotes
from . import main
from .forms import PostForm,CommentForm,DelForm,UpdateProfile
from app.auth.forms import SubscriptionForm
from .. import db,photos
from flask_login import login_required,current_user
import markdown2
from ..email import mail_message
from app.auth import views,forms
# from sqlalchemy import desc
# @main.route('/user/update/pitch/<id>',methods = ['GET','POST'])
# def single_review(id):
# pitch=Pitch.query.get(id)
# if pitch is None:
# abort(404)
# form = PitchForm()
#
# if form.validate_on_submit():
# user.pitches = form.pitches.data
#
# db.session.add(user)
# db.session.commit()
#
# return redirect(url_for('.profile',pitch=user.pitches))
#
# format_pitch = markdown2.markdown(pitch.movie_pitch,extras=["code-friendly", "fenced-code-blocks"])
# return render_template('new_pitch.html',pitch = pitch,format_pitch=format_pitch)
# @main.route('/delete_post/<int:id>',methods = ['GET','POST'])
# def del_post(id):
# @main.route('/new_vote/',methods = ['GET','POST'])
# @login_required
# def new_vote():
# form = VoteForm()
# # votes = get_vote(id)
#
# if form.validate_on_submit():
# pitch = Pitch(name = form.name.data, user_id = current_user.id)
# upvote = Vote(upvote = form.validate_on_submit(),pitch_id = pitch.id)
# downvote = Vote(downvote = form.validate_on_submit(),pitch_id = pitch.id)
# up=0
# down=0
# for upvote in vote:
# up+=1
# db.session.add(upvote=up)
# db.session.commit()
# for downvote in vote:
# down+=1
# db.session.add(downvote=down)
# db.session.commit()
# user=User.query.filter_by(id = pitch.id).first()
# return redirect(url_for('.index'))
#
# return render_template('profile/new_comment.html',comment_form=form)
# return render_template('new_vote.html',upvote = upvote, downvote = downvote, vote_form=form, votes=votes)
| 33.927152 | 117 | 0.662112 |
f9a2d31ea31e4c014413d3196c6cde1579895080 | 100 | py | Python | data_types/numeric_type/float_type.py | aryanz-co-in/python-indentation-datatypes-tamil | 69c291f0b6bd911fec96e8cd9e670880501d9959 | [
"Apache-2.0"
] | null | null | null | data_types/numeric_type/float_type.py | aryanz-co-in/python-indentation-datatypes-tamil | 69c291f0b6bd911fec96e8cd9e670880501d9959 | [
"Apache-2.0"
] | null | null | null | data_types/numeric_type/float_type.py | aryanz-co-in/python-indentation-datatypes-tamil | 69c291f0b6bd911fec96e8cd9e670880501d9959 | [
"Apache-2.0"
] | null | null | null | # int, float, complex Numeric Types
# Float are nothing but decimal values
pi = 3.14
print(pi)
| 12.5 | 38 | 0.7 |
f9a2fdd3c94e96ddac9d38ba04e226d5f50ff29b | 452 | py | Python | docker/dev_app/views.py | uw-it-aca/uw-django-saml2 | 04cd99c0f8fff6160c13e3aa0e44324f6a4079fe | [
"Apache-2.0"
] | 2 | 2018-04-20T19:02:11.000Z | 2020-01-21T07:08:48.000Z | docker/dev_app/views.py | uw-it-aca/uw-django-saml2 | 04cd99c0f8fff6160c13e3aa0e44324f6a4079fe | [
"Apache-2.0"
] | 71 | 2018-03-27T17:52:31.000Z | 2022-02-18T23:09:05.000Z | docker/dev_app/views.py | uw-it-aca/uw-django-saml2 | 04cd99c0f8fff6160c13e3aa0e44324f6a4079fe | [
"Apache-2.0"
] | 1 | 2018-12-04T19:20:36.000Z | 2018-12-04T19:20:36.000Z | from django.conf import settings
from django.contrib.auth.decorators import login_required
from django.http import HttpResponse
from uw_saml.utils import is_member_of_group
# Create your views here.
| 28.25 | 74 | 0.765487 |
f9a3781192095c8ae404cd60bb006a2f14049443 | 4,370 | py | Python | genoml/steps/model_validate.py | GenoML/genoml | bfe0164e99a27d5ec2b720b5a24e059294603e3f | [
"Apache-2.0"
] | 13 | 2019-03-22T12:12:12.000Z | 2021-10-04T15:06:18.000Z | genoml/steps/model_validate.py | GenoML/genoml | bfe0164e99a27d5ec2b720b5a24e059294603e3f | [
"Apache-2.0"
] | 21 | 2019-03-15T15:40:59.000Z | 2020-08-03T21:44:26.000Z | genoml/steps/model_validate.py | GenoML/genoml | bfe0164e99a27d5ec2b720b5a24e059294603e3f | [
"Apache-2.0"
] | 4 | 2019-06-28T18:25:37.000Z | 2020-01-21T01:22:07.000Z | #! /usr/bin/env python -u
# coding=utf-8
from shutil import copyfile
from genoml.steps import PhenoScale, StepBase
from genoml.utils import DescriptionLoader
__author__ = 'Sayed Hadi Hashemi'
| 38 | 118 | 0.576659 |
f9a4a4c34323aeec9f75c70fae31ad785ce964df | 721 | py | Python | resotocore/tests/resotocore/dependencies_test.py | someengineering/resoto | ee17313f5376e9797ed305e7fdb62d40139a6608 | [
"Apache-2.0"
] | 126 | 2022-01-13T18:22:03.000Z | 2022-03-31T11:03:14.000Z | resotocore/tests/resotocore/dependencies_test.py | someengineering/resoto | ee17313f5376e9797ed305e7fdb62d40139a6608 | [
"Apache-2.0"
] | 110 | 2022-01-13T22:27:55.000Z | 2022-03-30T22:26:50.000Z | resotocore/tests/resotocore/dependencies_test.py | someengineering/resoto | ee17313f5376e9797ed305e7fdb62d40139a6608 | [
"Apache-2.0"
] | 8 | 2022-01-15T10:28:16.000Z | 2022-03-30T16:38:21.000Z | from typing import Tuple, List
from resotocore.dependencies import parse_args
from resotocore.types import JsonElement
| 45.0625 | 103 | 0.617198 |
f9a5ad42dfd6f80195b93f6de20b3058e7e2213b | 7,374 | py | Python | pyquil/api/_benchmark.py | stjordanis/pyquil | 36987ecb78d5dc85d299dd62395b7669a1cedd5a | [
"Apache-2.0"
] | 677 | 2017-01-09T23:20:22.000Z | 2018-11-26T10:57:49.000Z | pyquil/api/_benchmark.py | stjordanis/pyquil | 36987ecb78d5dc85d299dd62395b7669a1cedd5a | [
"Apache-2.0"
] | 574 | 2018-11-28T05:38:40.000Z | 2022-03-23T20:38:28.000Z | pyquil/api/_benchmark.py | stjordanis/pyquil | 36987ecb78d5dc85d299dd62395b7669a1cedd5a | [
"Apache-2.0"
] | 202 | 2018-11-30T06:36:28.000Z | 2022-03-29T15:38:18.000Z | ##############################################################################
# Copyright 2018 Rigetti Computing
#
# 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 typing import List, Optional, Sequence, cast
from qcs_api_client.client import QCSClientConfiguration
from pyquil.api._abstract_compiler import AbstractBenchmarker
from pyquil.api._compiler_client import (
GenerateRandomizedBenchmarkingSequenceRequest,
ConjugatePauliByCliffordRequest,
CompilerClient,
)
from pyquil.paulis import PauliTerm, is_identity
from pyquil.quil import address_qubits, Program
from pyquil.quilbase import Gate
| 46.670886 | 118 | 0.675481 |
f9a664bbf396891165319f919889de28be4868a4 | 212 | py | Python | mine/collatz.py | zahessi/unileaks | 3ed2462e11f8e3decc64ed8faceee42438ec06ff | [
"MIT"
] | null | null | null | mine/collatz.py | zahessi/unileaks | 3ed2462e11f8e3decc64ed8faceee42438ec06ff | [
"MIT"
] | null | null | null | mine/collatz.py | zahessi/unileaks | 3ed2462e11f8e3decc64ed8faceee42438ec06ff | [
"MIT"
] | null | null | null | n = input(" . ")
collatz(n)
| 21.2 | 62 | 0.603774 |
f9a78f0606518ebedfb5bc19389f7930753e4683 | 554 | py | Python | questions/q292_pair_with_given_difference/simple_storage.py | aadhityasw/Competitive-Programs | 901a48d35f024a3a87c32a45b7f4531e8004a203 | [
"MIT"
] | null | null | null | questions/q292_pair_with_given_difference/simple_storage.py | aadhityasw/Competitive-Programs | 901a48d35f024a3a87c32a45b7f4531e8004a203 | [
"MIT"
] | 1 | 2021-05-15T07:56:51.000Z | 2021-05-15T07:56:51.000Z | questions/q292_pair_with_given_difference/simple_storage.py | aadhityasw/Competitive-Programs | 901a48d35f024a3a87c32a45b7f4531e8004a203 | [
"MIT"
] | null | null | null |
if __name__ == '__main__':
t = int(input())
for _ in range(t):
L,N = [int(x) for x in input().split()]
arr = [int(x) for x in input().split()]
solObj = Solution()
if(solObj.findPair(arr,L, N)):
print(1)
else:
print(-1)
| 19.103448 | 47 | 0.440433 |
f9a9b8479139b00ee0e9e3f90eb6496c035fb7c6 | 1,270 | py | Python | tlh/data/pointer.py | notyourav/the-little-hat | f52b38b18b762e704b36cef06c07656348ea6995 | [
"MIT"
] | null | null | null | tlh/data/pointer.py | notyourav/the-little-hat | f52b38b18b762e704b36cef06c07656348ea6995 | [
"MIT"
] | null | null | null | tlh/data/pointer.py | notyourav/the-little-hat | f52b38b18b762e704b36cef06c07656348ea6995 | [
"MIT"
] | 2 | 2021-10-05T20:40:12.000Z | 2022-01-05T00:17:36.000Z | from dataclasses import dataclass
from tlh.const import RomVariant
from intervaltree import IntervalTree, Interval
| 30.97561 | 87 | 0.659843 |
f9ad826a4941dde9f3abe0bd1c8c6c6ea3cdfc2e | 554 | py | Python | tests/testapp/models.py | jcass77/django-yearlessdate | 19ed3ecb16efe33eea6f02138bb4365447cb2ea7 | [
"BSD-3-Clause"
] | 16 | 2016-09-23T07:09:40.000Z | 2022-01-13T13:22:31.000Z | tests/testapp/models.py | jcass77/django-yearlessdate | 19ed3ecb16efe33eea6f02138bb4365447cb2ea7 | [
"BSD-3-Clause"
] | 8 | 2017-12-06T08:32:12.000Z | 2021-05-13T15:31:21.000Z | tests/testapp/models.py | jcass77/django-yearlessdate | 19ed3ecb16efe33eea6f02138bb4365447cb2ea7 | [
"BSD-3-Clause"
] | 16 | 2016-03-04T07:55:56.000Z | 2021-04-16T15:14:26.000Z | from django.db import models
from djangoyearlessdate.models import YearlessDateField, YearField
from djangoyearlessdate.helpers import YearlessDate
| 30.777778 | 88 | 0.772563 |
f9ade94d5d26429d7edd4cdfcee8f28919e4bd4f | 597 | py | Python | ror/NoTieResolver.py | jakub-tomczak/ror | cf9ab38a2d66f4816a1289b9726911960059fce7 | [
"MIT"
] | null | null | null | ror/NoTieResolver.py | jakub-tomczak/ror | cf9ab38a2d66f4816a1289b9726911960059fce7 | [
"MIT"
] | null | null | null | ror/NoTieResolver.py | jakub-tomczak/ror | cf9ab38a2d66f4816a1289b9726911960059fce7 | [
"MIT"
] | null | null | null | from ror.RORParameters import RORParameters
from ror.RORResult import RORResult
from ror.AbstractTieResolver import AbstractTieResolver
from ror.result_aggregator_utils import Rank
| 37.3125 | 99 | 0.740369 |
f9ae44085aad4c16f6592f43de3a099254f05d59 | 47 | py | Python | conjur/util/__init__.py | mbjahnoon/conjur-api-python3 | ec1f62bb1baf2bdcd34d2fb92c97db724f761020 | [
"Apache-2.0"
] | 16 | 2019-05-17T15:34:59.000Z | 2021-11-08T10:30:21.000Z | conjur/util/__init__.py | mbjahnoon/conjur-api-python3 | ec1f62bb1baf2bdcd34d2fb92c97db724f761020 | [
"Apache-2.0"
] | 301 | 2019-05-07T18:27:10.000Z | 2022-01-26T13:03:49.000Z | conjur/util/__init__.py | cyberark/cyberark-conjur-cli | 2507e8769808643d89efa7e2496cfc14f505bd7e | [
"Apache-2.0"
] | 10 | 2019-07-30T17:00:13.000Z | 2022-01-20T17:00:34.000Z | """
util
This package is for util modules
"""
| 7.833333 | 32 | 0.659574 |
f9ae75ada823a3568610724a901cd66400be071c | 331 | py | Python | Algo and DSA/LeetCode-Solutions-master/Python/bulb-switcher-iii.py | Sourav692/FAANG-Interview-Preparation | f523e5c94d582328b3edc449ea16ac6ab28cdc81 | [
"Unlicense"
] | 3,269 | 2018-10-12T01:29:40.000Z | 2022-03-31T17:58:41.000Z | Algo and DSA/LeetCode-Solutions-master/Python/bulb-switcher-iii.py | Sourav692/FAANG-Interview-Preparation | f523e5c94d582328b3edc449ea16ac6ab28cdc81 | [
"Unlicense"
] | 53 | 2018-12-16T22:54:20.000Z | 2022-02-25T08:31:20.000Z | Algo and DSA/LeetCode-Solutions-master/Python/bulb-switcher-iii.py | Sourav692/FAANG-Interview-Preparation | f523e5c94d582328b3edc449ea16ac6ab28cdc81 | [
"Unlicense"
] | 1,236 | 2018-10-12T02:51:40.000Z | 2022-03-30T13:30:37.000Z | # Time: O(n)
# Space: O(1)
| 22.066667 | 42 | 0.483384 |
f9b08e37d9b636d67355ff414f22cda84aa9f53b | 3,472 | py | Python | tilapia/lib/provider/chains/bch/provider.py | huazhouwang/python_multichain_wallet | 52e0acdc2984c08990cb36433ef17a414fbe8312 | [
"MIT"
] | 2 | 2021-09-23T13:47:08.000Z | 2021-09-24T02:39:14.000Z | tilapia/lib/provider/chains/bch/provider.py | huazhouwang/tilapia | 52e0acdc2984c08990cb36433ef17a414fbe8312 | [
"MIT"
] | null | null | null | tilapia/lib/provider/chains/bch/provider.py | huazhouwang/tilapia | 52e0acdc2984c08990cb36433ef17a414fbe8312 | [
"MIT"
] | null | null | null | import itertools
import logging
from typing import Dict, Tuple
from tilapia.lib.basic import bip44
from tilapia.lib.basic.functional.require import require
from tilapia.lib.hardware import interfaces as hardware_interfaces
from tilapia.lib.provider import data
from tilapia.lib.provider.chains import btc
from tilapia.lib.provider.chains.bch.sdk import cash_address
from tilapia.lib.secret import interfaces as secret_interfaces
logger = logging.getLogger("app.chain")
| 39.908046 | 118 | 0.701613 |
f9b1801867198f74dece84cf86c7c8fce031dea8 | 1,747 | py | Python | Excercises/Automata.py | RyanClinton777/graph-theory-project | a3ff9512da3ac2d48138b59d2e8eb8899d8e552d | [
"Unlicense"
] | null | null | null | Excercises/Automata.py | RyanClinton777/graph-theory-project | a3ff9512da3ac2d48138b59d2e8eb8899d8e552d | [
"Unlicense"
] | null | null | null | Excercises/Automata.py | RyanClinton777/graph-theory-project | a3ff9512da3ac2d48138b59d2e8eb8899d8e552d | [
"Unlicense"
] | null | null | null | """ DFA Automata Implementation """
def compile():
""" Create our automaton """
# Creating an DFA with two states; 0 points to themselves, and 1 points to the other. (checking for even parity)
# Compile is standard terminoligy for creating something like this
# Create start state
start = State(True, {})
# Other state
other = State(False, {})
# The states point to themselves for 0
start.arrows['0'] = start
other.arrows['0'] = other
# They point to eachother for 1
start.arrows['1'] = other
other.arrows['1'] = start
a = DFA(start)
return a
# Create automaton instance
myAuto = compile()
# tests
for s in ['1100', '11111', '', '1', '0']:
result = myAuto.match(s)
print(f"{s} accepted? {result}")
for s in ['000', '001', '010', '011', '100', '101', '110', '111']:
result = myAuto.match(s)
print(f"{s} accepted? {result}") | 28.639344 | 117 | 0.611906 |
f9b1deee9145e20a82bd34752d2e98a230a5a620 | 568 | py | Python | src/database/migrations/0027_auto_20190829_1530.py | gregory-chekler/api | 11ecbea945e7eb6fa677a0c0bb32bda51ba15f28 | [
"MIT"
] | 2 | 2020-07-24T12:58:17.000Z | 2020-12-17T02:26:13.000Z | src/database/migrations/0027_auto_20190829_1530.py | gregory-chekler/api | 11ecbea945e7eb6fa677a0c0bb32bda51ba15f28 | [
"MIT"
] | 214 | 2019-06-26T17:33:54.000Z | 2022-03-26T00:02:34.000Z | src/database/migrations/0027_auto_20190829_1530.py | massenergize/portalBackEnd | 7ed971b2be13901667a216d8c8a46f0bed6d6ccd | [
"MIT"
] | 6 | 2020-03-13T20:29:06.000Z | 2021-08-20T16:15:08.000Z | # Generated by Django 2.2.3 on 2019-08-29 15:30
from django.db import migrations, models
| 23.666667 | 64 | 0.584507 |
f9b3824e8469cbf08d1932118a1c35ca85f4a512 | 207 | py | Python | robots/PDF.py | NaskIII/Projeto-Alpha-X | 23e3de59185cdc85b7fc13299cfc51846bfc63b6 | [
"MIT"
] | null | null | null | robots/PDF.py | NaskIII/Projeto-Alpha-X | 23e3de59185cdc85b7fc13299cfc51846bfc63b6 | [
"MIT"
] | 3 | 2019-08-26T03:51:57.000Z | 2019-08-29T04:24:51.000Z | robots/PDF.py | NaskIII/Projeto-Alpha-X | 23e3de59185cdc85b7fc13299cfc51846bfc63b6 | [
"MIT"
] | null | null | null | import sys
import os
| 20.7 | 71 | 0.613527 |
f9b5b83c0da1cf14ae65df8fb1a134313f52638f | 1,181 | py | Python | ntlmlib/__init__.py | Dlat/ntlmlib | 49eadfe4701bcce84a4ca9cbab5b6d5d72eaad05 | [
"Apache-2.0"
] | 1 | 2018-08-20T19:33:58.000Z | 2018-08-20T19:33:58.000Z | ntlmlib/__init__.py | Dlat/ntlmlib | 49eadfe4701bcce84a4ca9cbab5b6d5d72eaad05 | [
"Apache-2.0"
] | null | null | null | ntlmlib/__init__.py | Dlat/ntlmlib | 49eadfe4701bcce84a4ca9cbab5b6d5d72eaad05 | [
"Apache-2.0"
] | null | null | null | """
_ _ _ _ _
_ __ | |_| |_ __ ___ | (_) |__
| '_ \| __| | '_ ` _ \| | | '_ \
| | | | |_| | | | | | | | | |_) |
|_| |_|\__|_|_| |_| |_|_|_|_.__/
A robust, fast and efficient 'first-class' Python Library for NTLM authentication, signing and encryption
(c) 2015, Ian Clegg <ian.clegg@sourcewarp.com>
ntlmlib is 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.
"""
import logging
# Set default logging handler to avoid "No handler found" warnings.
try: # Python 2.7+
from logging import NullHandler
except ImportError:
logging.getLogger(__name__).addHandler(NullHandler())
| 33.742857 | 106 | 0.679932 |
f9b5c8efc58630f49b1fe78511366116237e9554 | 471 | py | Python | tests/conditions/operators/test_set_membership_operator.py | rusintez/flipper-client | cd00ae1a3582c5cb7e661c5aa9b8a7b65b35a9e0 | [
"Apache-2.0"
] | 82 | 2019-04-03T16:09:04.000Z | 2022-03-29T23:48:31.000Z | tests/conditions/operators/test_set_membership_operator.py | rusintez/flipper-client | cd00ae1a3582c5cb7e661c5aa9b8a7b65b35a9e0 | [
"Apache-2.0"
] | 17 | 2019-04-16T17:17:36.000Z | 2021-02-25T22:06:01.000Z | tests/conditions/operators/test_set_membership_operator.py | rusintez/flipper-client | cd00ae1a3582c5cb7e661c5aa9b8a7b65b35a9e0 | [
"Apache-2.0"
] | 12 | 2019-07-29T20:07:28.000Z | 2022-03-29T21:10:15.000Z | import unittest
from flipper.conditions.operators.set_membership_operator import SetMembershipOperator
| 29.4375 | 86 | 0.760085 |
f9b86bf8f49332b5a6eedda3d7d77088bf890eb2 | 19,801 | py | Python | pangtreebuild/pangenome/builders/dagmaf2poagraph.py | meoke/PangTreeBuild | 7cafb76df32c559a76ed1d269699dc0e52313312 | [
"MIT"
] | 2 | 2019-09-04T20:01:28.000Z | 2019-12-23T22:41:57.000Z | pangtreebuild/pangenome/builders/dagmaf2poagraph.py | meoke/PangTreeBuild | 7cafb76df32c559a76ed1d269699dc0e52313312 | [
"MIT"
] | 2 | 2019-08-10T16:18:01.000Z | 2019-10-28T21:40:23.000Z | pangtreebuild/pangenome/builders/dagmaf2poagraph.py | meoke/PangTreeBuild | 7cafb76df32c559a76ed1d269699dc0e52313312 | [
"MIT"
] | 2 | 2020-04-23T23:57:52.000Z | 2020-07-12T17:09:02.000Z | from collections import namedtuple
from typing import Tuple, List, NewType, Optional, Dict
from pangtreebuild.mafgraph.graph import Block
from pangtreebuild.mafgraph.graph.Arc import Arc
from pangtreebuild.mafgraph.mafreader import start_position
from pangtreebuild.pangenome import graph
from pangtreebuild.pangenome import DAGMaf
from pangtreebuild.pangenome.parameters import missings
from pangtreebuild.pangenome.parameters import msa
from pangtreebuild.tools import logprocess
global_logger = logprocess.get_global_logger()
detailed_logger = logprocess.get_logger("details")
MafSequenceID = NewType('MafSequenceID', str)
SequenceInfo = namedtuple('SequenceInfo', ['block_id',
'start',
'strand',
'size',
'srcSize',
'orient'])
Edge = namedtuple('Edge', ['seq_id',
'from_block_id',
'to_block_id',
'last_node_id'])
def get_poagraph(dagmaf: DAGMaf.DAGMaf,
fasta_provider: missings.FastaProvider,
metadata: Optional[msa.MetadataCSV]) -> \
Tuple[List[graph.Node], Dict[msa.SequenceID, graph.Sequence]]:
"""Gets poagraph from given dagmaf using fasta_provider and metadata.
Args:
dagmaf: DagMaf that will be converted to Poagraph.
fasta_provider: Provider of symbols missing in DagMaf.
metadata: MetadataCSV.
Returns:
Tuple of poagraph elements.
"""
sequences_in_dagmaf = _get_sequences_ids(dagmaf)
build_state = _BuildState(initial_nodes=[],
initial_sequences=_init_sequences(sequences_in_dagmaf, metadata),
initial_edges=_init_free_edges(sequences_in_dagmaf),
seqs_info=_get_seqs_info(dagmaf, sequences_in_dagmaf),
initial_column_id=graph.ColumnID(-1),
fasta_provider=fasta_provider)
_complement_starting_nodes(build_state)
for i, mafnode in enumerate(dagmaf.dagmaf_nodes):
_process_block(build_state, mafnode)
return build_state.nodes, build_state.sequences
| 44.596847 | 117 | 0.56982 |
f9b8816aef7a829b307e2a9d13b933fbcd80a3a1 | 353 | py | Python | tests/utils/test_gzipgen.py | takanabe/cli | 7cbf781d7f286fc4e52ef0980712c28f386e8d09 | [
"Apache-2.0"
] | 19 | 2021-01-07T06:41:51.000Z | 2022-03-05T08:23:57.000Z | tests/utils/test_gzipgen.py | takanabe/cli | 7cbf781d7f286fc4e52ef0980712c28f386e8d09 | [
"Apache-2.0"
] | 189 | 2020-11-04T15:38:47.000Z | 2022-03-31T05:02:06.000Z | tests/utils/test_gzipgen.py | takanabe/cli | 7cbf781d7f286fc4e52ef0980712c28f386e8d09 | [
"Apache-2.0"
] | 7 | 2020-11-20T16:55:51.000Z | 2022-02-01T11:17:30.000Z | from launchable.utils.gzipgen import compress
import gzip
from unittest import TestCase
| 27.153846 | 64 | 0.654391 |
f9ba31abc310c48d834cebff8aeef25ad2407242 | 138 | py | Python | project_data_app/urls.py | chrisba11/kickstarter_projects | 08a341d01428d20c384546773a853fc7d99a6140 | [
"MIT"
] | null | null | null | project_data_app/urls.py | chrisba11/kickstarter_projects | 08a341d01428d20c384546773a853fc7d99a6140 | [
"MIT"
] | null | null | null | project_data_app/urls.py | chrisba11/kickstarter_projects | 08a341d01428d20c384546773a853fc7d99a6140 | [
"MIT"
] | null | null | null | from django.urls import path
from .views import project_list_view
urlpatterns = [
path('', project_list_view, name='project_list'),
] | 23 | 53 | 0.753623 |
f9bd66223ae9916274f6536d0f5a42a245f694b0 | 847 | py | Python | tech/CCI.py | A1eXFei/StockMarket3 | 01000d0731395868c4477982c6ed6c632c9a7427 | [
"Apache-2.0"
] | null | null | null | tech/CCI.py | A1eXFei/StockMarket3 | 01000d0731395868c4477982c6ed6c632c9a7427 | [
"Apache-2.0"
] | null | null | null | tech/CCI.py | A1eXFei/StockMarket3 | 01000d0731395868c4477982c6ed6c632c9a7427 | [
"Apache-2.0"
] | null | null | null | # -*- coding: UTF-8 -*-
import talib as ta
import numpy as np
from util import StockUtil as su
from tech import StockTechIndicator
if __name__ == "__main__":
b = CCI()
print b.calculate('chbtc', 'btc_cny', '5min', 1497449100) | 32.576923 | 129 | 0.641086 |
f9beae7adf6d3836aaf0918cb0eb1c2fed9c5001 | 938 | py | Python | timeit/timeit_np_ufunc.py | Dennis-van-Gils/DvG_Arduino_lock-in_amp | 4576aa529413c93c6e4d6152802349f5f0c3ee16 | [
"MIT"
] | 9 | 2020-07-02T15:23:18.000Z | 2022-03-04T03:32:04.000Z | timeit/timeit_np_ufunc.py | Dennis-van-Gils/DvG_Arduino_lock-in_amp | 4576aa529413c93c6e4d6152802349f5f0c3ee16 | [
"MIT"
] | 3 | 2019-04-22T22:53:56.000Z | 2021-11-02T20:13:43.000Z | timeit/timeit_np_ufunc.py | Dennis-van-Gils/DvG_Arduino_lock-in_amp | 4576aa529413c93c6e4d6152802349f5f0c3ee16 | [
"MIT"
] | 2 | 2021-11-05T14:34:22.000Z | 2022-03-04T03:32:06.000Z | # -*- coding: utf-8 -*-
"""
Created on Thu Dec 6 21:22:33 2018
@author: vangi
"""
from timeit import timeit
setup = '''
import numpy as np
np.random.seed(0)
N_array = 200000
a_np = np.random.randn(N_array)
b_np = np.random.randn(N_array)
c_np = np.empty(N_array)
def no_ufunc(a_np, b_np, c_np):
c_np = a_np * b_np
#print(c_np[0])
def ufunc_buffered(a_np, b_np, c_np):
c_np = np.multiply(a_np, b_np)
#print(c_np[0])
def ufunc_unbuffered(a_np, b_np, c_np):
np.multiply(a_np, b_np, out=c_np)
#print(c_np[0])
'''
N = 1000
print("Numpy multiply strategies")
print("no ufunc : %.3f ms" %
(timeit('no_ufunc(a_np, b_np, c_np)', setup=setup, number=N)/N*1000))
print("ufunc buf : %.3f ms" %
(timeit('ufunc_buffered(a_np, b_np, c_np)', setup=setup, number=N)/N*1000))
print("ufunc no buf: %.3f ms" %
(timeit('ufunc_unbuffered(a_np, b_np, c_np)', setup=setup, number=N)/N*1000)) | 22.333333 | 83 | 0.635394 |
f9bff3fda8ac0169c8ed57237e81f02a4608ca3c | 2,451 | py | Python | conductor/conductor/api/controllers/validator.py | aalsudais/optf-has | c3e070b6ebc713a571c10d7a5cd87e5053047136 | [
"Apache-2.0"
] | 4 | 2019-02-14T19:18:09.000Z | 2019-10-21T17:17:59.000Z | conductor/conductor/api/controllers/validator.py | aalsudais/optf-has | c3e070b6ebc713a571c10d7a5cd87e5053047136 | [
"Apache-2.0"
] | null | null | null | conductor/conductor/api/controllers/validator.py | aalsudais/optf-has | c3e070b6ebc713a571c10d7a5cd87e5053047136 | [
"Apache-2.0"
] | 4 | 2019-05-09T07:05:54.000Z | 2020-11-20T05:56:47.000Z | #
# -------------------------------------------------------------------------
# Copyright (c) 2015-2017 AT&T Intellectual Property
#
# 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 yaml.constructor import ConstructorError
from yaml.nodes import MappingNode
try:
from yaml import CLoader as Loader
except ImportError:
from yaml import Loader
| 38.296875 | 78 | 0.572011 |
f9c217fdeaa845a8b5a88bdf4815b175a49ccae7 | 32,310 | py | Python | gamejoltapi.py | bgempire/gamejoltapi | 03a77527e00a67e5990dbc1289c54e280954b712 | [
"MIT"
] | 1 | 2022-01-18T12:08:58.000Z | 2022-01-18T12:08:58.000Z | gamejoltapi.py | bgempire/gamejoltapi | 03a77527e00a67e5990dbc1289c54e280954b712 | [
"MIT"
] | null | null | null | gamejoltapi.py | bgempire/gamejoltapi | 03a77527e00a67e5990dbc1289c54e280954b712 | [
"MIT"
] | 1 | 2021-04-30T11:27:39.000Z | 2021-04-30T11:27:39.000Z | from urllib.parse import urlencode as _urlencode, quote as _quote
from urllib.request import urlopen as _urlopen
from hashlib import md5 as _md5
from ast import literal_eval as _literal_eval
from collections import OrderedDict as _OrderedDict
_DEBUG = False
| 38.327402 | 498 | 0.572857 |
f9c3b4eb59658fb2124d809e4025b7e6912a6d8f | 3,243 | py | Python | poplar/util.py | mortonjt/poplar | 854d1ef819392f54536df386ef034091831802ed | [
"BSD-3-Clause"
] | null | null | null | poplar/util.py | mortonjt/poplar | 854d1ef819392f54536df386ef034091831802ed | [
"BSD-3-Clause"
] | null | null | null | poplar/util.py | mortonjt/poplar | 854d1ef819392f54536df386ef034091831802ed | [
"BSD-3-Clause"
] | null | null | null | import os
import inspect
import torch
import numpy as np
import numbers
def get_data_path(fn, subfolder='data'):
"""Return path to filename ``fn`` in the data folder.
During testing it is often necessary to load data files. This
function returns the full path to files in the ``data`` subfolder
by default.
Parameters
----------
fn : str
File name.
subfolder : str, defaults to ``data``
Name of the subfolder that contains the data.
Returns
-------
str
Inferred absolute path to the test data for the module where
``get_data_path(fn)`` is called.
Notes
-----
The requested path may not point to an existing file, as its
existence is not checked.
This is the same method as borrowed from scikit-bio
"""
# getouterframes returns a list of tuples: the second tuple
# contains info about the caller, and the second element is its
# filename
callers_filename = inspect.getouterframes(inspect.currentframe())[1][1]
path = os.path.dirname(os.path.abspath(callers_filename))
data_path = os.path.join(path, subfolder, fn)
return data_path
def check_random_state(seed):
""" Turn seed into a np.random.RandomState instance.
Parameters
----------
seed : None | int | instance of RandomState
If seed is None, return the RandomState singleton used by np.random.
If seed is an int, return a new RandomState instance seeded with seed.
If seed is already a RandomState instance, return it.
Otherwise raise ValueError.
Note
----
This is from sklearn
"""
if seed is None or seed is np.random:
return np.random.mtrand._rand
if isinstance(seed, numbers.Integral):
return np.random.RandomState(seed)
if isinstance(seed, np.random.RandomState):
return seed
raise ValueError('%r cannot be used to seed a numpy.random.RandomState'
' instance' % seed)
dictionary = {
"A": 1,
"B": 2,
"C": 3,
"D": 4,
"E": 5,
"F": 6,
"G": 7,
"H": 8,
"I": 9,
"J": 10,
"K": 11,
"L": 12,
"M": 13,
"N": 14,
"O": 15,
"P": 16,
"Q": 17,
"R": 18,
"S": 19,
"T": 20,
"U": 21,
"V": 22,
"W": 23,
"X": 24,
"Y": 25,
"Z": 26,
".": 27
}
def encode(x):
""" Convert string to tokens. """
tokens = list(map(lambda i: dictionary[i], list(x)))
tokens = torch.Tensor(tokens)
tokens = tokens.long()
return tokens
| 26.153226 | 81 | 0.588344 |
f9c72fdee75782efa656735bc0a7c52d729983de | 5,109 | py | Python | search-github-ip.py | brilliant116/learning-code | 5378b1f0c53b4ceac56942044bbb666278a138f2 | [
"MIT"
] | null | null | null | search-github-ip.py | brilliant116/learning-code | 5378b1f0c53b4ceac56942044bbb666278a138f2 | [
"MIT"
] | null | null | null | search-github-ip.py | brilliant116/learning-code | 5378b1f0c53b4ceac56942044bbb666278a138f2 | [
"MIT"
] | null | null | null | import asyncio
import time
import socket
import argparse
import aiohttp
if __name__ == '__main__':
import logging
logging.getLogger().addHandler(logging.NullHandler())
parser = argparse.ArgumentParser(
description='GitHub IP ')
parser.add_argument('proto', nargs='*',
default=['http', 'ssh'],
help='')
parser.add_argument('--hosts',
action='store_true',
help=' /etc/hosts')
args = parser.parse_args()
if args.hosts:
main_fu = update_hosts()
else:
main_fu = main(args.proto)
loop = asyncio.get_event_loop()
try:
loop.run_until_complete(main_fu)
except KeyboardInterrupt:
pass
| 24.921951 | 109 | 0.595811 |
f9c7d6fee331123a55864020b776b1d34238b97d | 467 | py | Python | src/todo/522-LongestUncommonSubsequenceII.py | Jiezhi/myleetcode | b346e94c46da2a3033ebc8ff50e621aa179c4f62 | [
"MIT"
] | 1 | 2022-03-03T15:11:48.000Z | 2022-03-03T15:11:48.000Z | src/todo/522-LongestUncommonSubsequenceII.py | Jiezhi/myleetcode | b346e94c46da2a3033ebc8ff50e621aa179c4f62 | [
"MIT"
] | null | null | null | src/todo/522-LongestUncommonSubsequenceII.py | Jiezhi/myleetcode | b346e94c46da2a3033ebc8ff50e621aa179c4f62 | [
"MIT"
] | 2 | 2022-01-20T22:49:58.000Z | 2022-01-20T22:53:13.000Z | #!/usr/bin/env python
"""
CREATED AT: 2021/8/28
Des:
https://leetcode.com/problems/longest-uncommon-subsequence-ii/
GITHUB: https://github.com/Jiezhi/myleetcode
"""
from typing import List
if __name__ == '__main__':
test()
| 18.68 | 68 | 0.648822 |
f9c8ce2fe1e056d6cf0dbb9895f3232eec31c3ce | 23,732 | py | Python | AdventOfCode/2020/day20.py | benhunter/coding-challenges | 0cca059da7c8ae6cdc62dbeb3db8250ab42ac3b6 | [
"MIT"
] | null | null | null | AdventOfCode/2020/day20.py | benhunter/coding-challenges | 0cca059da7c8ae6cdc62dbeb3db8250ab42ac3b6 | [
"MIT"
] | null | null | null | AdventOfCode/2020/day20.py | benhunter/coding-challenges | 0cca059da7c8ae6cdc62dbeb3db8250ab42ac3b6 | [
"MIT"
] | null | null | null | # Advent of Code 2020 Day
# https://adventofcode.com/2020/
import cProfile
import itertools
import math
import numpy as np
from collections import namedtuple
from pprint import pformat, pprint
from typing import List, Optional
from numpy.typing import ArrayLike
USE_EXAMPLE1 = False # example input or full input
DEBUG = False # debug prints to console
PROFILE = False # profiling flag
Tile = namedtuple("Tile", "number, data")
Tile.__repr__ = ( # type: ignore
lambda self: f"Tile: {self.number}\n" + f"{pformat(self.data)}" # type: ignore
) # type: ignore
# class Tile(namedtuple("Tile", "number, data")):
# # Tile with a number ID and data fields.
# # Inheriting from namedtuple to override the repr dunder.
# # Equivalent code:
# # Tile = namedtuple("Tile", "number, data")
# # Tile.__repr__ = lambda self: f"Tile: {self.number}\n{pformat(self.data)}"
# def __new__(cls, number, data: ArrayLike):
# self = super(Tile, cls).__new__(cls, number, data)
# return self
# def __repr__(self) -> str:
# return f"Tile: {self.number}\n{pformat(self.data)}"
def is_tile_matches_neighbors(
y_index: int, x_index: int, solution: List[List[Optional[Tile]]]
):
"""Neighbors can be Tile or None"""
optional_tile: Optional[Tile] = solution[y_index][x_index]
if optional_tile is None:
return True
elif isinstance(optional_tile, Tile):
tile: Tile = optional_tile
else:
raise RuntimeError
assert isinstance(solution[y_index][x_index], Tile)
if DEBUG:
print(tile.data)
# Up
temp_tile: Optional[Tile]
if y_index > 0:
temp_tile = solution[y_index - 1][x_index]
if isinstance(temp_tile, Tile):
# if solution[y_index - 1][x_index]:
neighbor_up: Tile = temp_tile
neighbor_face_down: np.ndarray = neighbor_up.data[-1]
tile_face_up: np.ndarray = tile.data[0]
if not is_face_matches_face(tile_face_up, neighbor_face_down):
return False
# Down
if y_index < (len(solution) - 1):
temp_tile = solution[y_index + 1][x_index]
if isinstance(temp_tile, Tile):
neighbor_down: Tile = temp_tile
neighbor_face_up: np.ndarray = neighbor_down.data[0]
tile_face_down: np.ndarray = tile.data[-1]
if not is_face_matches_face(tile_face_down, neighbor_face_up):
return False
# Left
if x_index > 0:
temp_tile = solution[y_index][x_index - 1]
if isinstance(temp_tile, Tile):
neighbor_left: Tile = temp_tile
neighbor_face_right = neighbor_left.data[:, -1]
tile_face_left = tile.data[:, 0]
if not is_face_matches_face(tile_face_left, neighbor_face_right):
return False
# Right
if x_index < (len(solution[0]) - 1):
temp_tile = solution[y_index][x_index + 1]
if isinstance(temp_tile, Tile):
neighbor_right: Tile = temp_tile
neighbor_face_left = neighbor_right.data[:, 0]
tile_face_right = tile.data[:, -1]
if not is_face_matches_face(tile_face_right, neighbor_face_left):
return False
return True
def is_partial_solution_valid(solution: List[List[Optional[Tile]]]):
# Check a partial solution. None is allowed where a Tile has not been placed yet.
for y_index in range(len(solution)):
for x_index in range(len(solution[0])):
if solution[y_index][x_index] is None:
continue
if not is_tile_matches_neighbors(y_index, x_index, solution):
return False
return True
def repr_solution_tiles(solution: List[List[Tile]]) -> str:
s = ""
for y_index, solution_row in enumerate(solution):
for y_tile_index in range(len(solution[0][0].data)):
for x_index, tile in enumerate(solution_row):
if solution[y_index][x_index]:
s += "".join(solution[y_index][x_index].data[y_tile_index])
s += " "
else:
s += "-" * len(solution[0][0].data[0])
s += " "
s += "\n"
s += "\n"
return s
def list_str_solution(solution: List[List[Tile]]) -> List[str]:
lines = []
for y_index, solution_row in enumerate(solution):
for y_tile_index in range(1, len(solution[0][0].data) - 1):
line = ""
for x_index, tile in enumerate(solution_row):
if solution[y_index][x_index]:
line += "".join(solution[y_index][x_index].data[y_tile_index][1:-1])
else:
line += "-" * len(solution[0][0].data[0][1:-1])
lines.append(line)
return lines
def repr_solution(solution: List[List[Tile]]) -> str:
s = ""
for row in list_str_solution(solution):
s += row + "\n"
return s
def match_2d(pattern_2d: np.ndarray, string_2d: np.ndarray):
matches = []
for y_index in range(len(string_2d) - len(pattern_2d) + 1):
for x_index in range(len(string_2d[0]) - len(pattern_2d[0]) + 1):
next_candidate = False
candidate_str = string_2d[
y_index : y_index + len(pattern_2d),
x_index : x_index + len(pattern_2d[0]),
]
for y_candidate in range(len(pattern_2d)):
for x_candidate in range(len(pattern_2d[0])):
# only looking for "#" in pattern_2d
if pattern_2d[y_candidate][x_candidate] != "#":
continue
if (
pattern_2d[y_candidate][x_candidate]
!= candidate_str[y_candidate][x_candidate]
):
next_candidate = True
break
else:
continue
if next_candidate:
break
if not next_candidate:
matches.append((y_index, x_index))
return matches
def test_match_2d():
monster = [" # ", "# ## ## ###", " # # # # # # "]
monster_nparray = list_str_to_nparray(monster)
sea = ["# . # ", "# ## ## ###", " # # # # # # "]
sea_nparray = list_str_to_nparray(sea)
matches = match_2d(monster_nparray, monster_nparray)
assert matches == [(0, 0)]
matches = match_2d(monster_nparray, sea_nparray)
assert matches == [(0, 0)]
def list_str_to_nparray(list_str: List[str]) -> np.ndarray:
# seperate each character so the nparray can be rotated, flipped
return np.array([[c for c in s] for s in list_str])
def solve_part1(tiles: List[Tile]) -> int:
# find the corners by counting the matching edges of each tile.
# corners have only two matching edges
corners: List[Tile] = find_corner_pieces(tiles)
corner_ids = [corner.number for corner in corners]
return product(corner_ids)
def solve_part2(tiles: List[Tile]) -> int:
dimension = math.isqrt(len(tiles))
solution: List[List[Optional[Tile]]] = [
[None for _ in range(dimension)] for _ in range(dimension)
]
# solution: List[List[Tile]] = [
# [None for _ in range(dimension)] for _ in range(dimension)
# ]
# print(solution)
assert is_partial_solution_valid(solution)
# start the solution with one of the corners found previously
solution[0][0] = find_corner_pieces(tiles)[0] # can be flipped/rotated
# tiles will only hold tiles that are not in solution yet
tiles.remove(solution[0][0])
# print(solution)
assert is_partial_solution_valid(solution)
# place solution[0][1]
# find a matching tile
assert isinstance(solution[0][0], Tile)
candidate_tile = next_match(solution[0][0], tiles)
# print(f"candidate_tile: {candidate_tile}")
# orient the corner. Which face matches?
# Options
# 1. could make this a tuple that also carries the "index" for how to rotate
# 2. or carries the rotated tile with each face
# 3. or just send the rotations and check the desired face below
# tile_faces = [
# tile.data[0], # top
# tile.data[-1], # bottom
# tile.data[:, 0], # left
# tile.data[:, -1], # right
# ]
# tile_rotations = [
# tile.data,
# np.rot90(tile.data, k=1),
# np.rot90(tile.data, k=2),
# np.rot90(tile.data, k=3),
# ]
# for face in tile_faces:
# if is_edge_match(face, candidate_tile):
# print(f"Face {face} matched candidate {candidate_tile}")
# in tile_rotations we are looking for the right face to match
# for orientation in tile_rotations:
y_index: int = 0
x_index: int = 0
tile = solution[y_index][x_index]
assert isinstance(tile, Tile)
for orientation in generate_tile_orientation(tile):
if is_face_matches_tile(orientation[:, -1], candidate_tile):
solution[y_index][x_index] = Tile(tile.number, orientation)
# print("matched orientation")
break
assert is_partial_solution_valid(solution)
# orient the candidate match and place it
for orientation in generate_tile_orientation(candidate_tile):
# compare left face of solved tile to right face of candidate_tile in all possible orientations
tile = solution[y_index][x_index]
assert isinstance(tile, Tile)
if is_face_matches_face(tile.data[:, -1], orientation[:, 0]):
# print(f"Placing candidate tile {candidate_tile.number}")
solution[y_index][x_index + 1] = Tile(candidate_tile.number, orientation)
# remove the matching candidate from tiles
tiles.remove(candidate_tile)
break
assert is_partial_solution_valid(solution)
y_index = 1
x_index = 0
tile = solution[y_index - 1][x_index]
assert isinstance(tile, Tile)
candidate_tile = next_match(tile, tiles)
# does row 0 need to flip?
# does candidate match to top or bottom of solution[0][0]?
needs_flip: bool = False
# compare top face of solution[0][0] to candidate_tile
up_neighbor: Tile = solution[0][0]
if is_face_matches_tile(up_neighbor.data[0], candidate_tile):
needs_flip = True
if needs_flip:
for x_index, tile in enumerate(solution[0]):
if isinstance(tile, Tile):
flipped_data = np.flipud(tile.data) # flip up down
solution[0][x_index] = Tile(tile.line, flipped_data)
# orient candidate_tile to tile above
# for orientation in orientation_generator(candidate_tile):
# if is_face_matches_tile(orientation[0], solution[0][0]):
# print(orientation[0])
# if is_face_matches_face(orientation[0], solution[0][0].data[-1]):
# print(orientation[0])
for orientation in generate_tile_orientation(candidate_tile):
if is_face_matches_face(up_neighbor.data[-1], orientation[0]):
if DEBUG:
print(f"Placing candidate tile {candidate_tile.number}")
solution[y_index][x_index] = Tile(candidate_tile.number, orientation)
# remove candidate match from tiles
tiles.remove(candidate_tile)
break
assert is_partial_solution_valid(solution)
# after the first corner, and it's neighbors have been placed
# the solution cannot be flipped
# solve first row
y_index = 0
for x_index, tile in enumerate(solution[y_index]):
if tile:
continue
# print(f"{x_index} {tile}")
left_neighbor: Optional[Tile] = solution[y_index][x_index - 1]
assert isinstance(left_neighbor, Tile)
for candidate_tile in generate_next_match(left_neighbor, tiles):
# find the right orientation for candidate_tile to left_neighbor
for orientation in generate_tile_orientation(candidate_tile):
if is_face_matches_face(left_neighbor.data[:, -1], orientation[:, 0]):
# print(f"Placing candidate tile {candidate_tile.number}")
solution[y_index][x_index] = Tile(
candidate_tile.number, orientation
)
# remove candidate match from tiles
tiles.remove(candidate_tile)
break
if solution[y_index][x_index] is not None:
break
assert isinstance(solution[y_index][x_index], Tile)
assert is_partial_solution_valid(solution)
# print(f"Solution:\n{solution}")
# print(repr_solution(solution))
assert is_partial_solution_valid(solution)
# print()
# solve other rows. if the left neighbor is empty or we are on the left edge of solution,
# look up to place tile
for y_index, solution_row in enumerate(solution):
for x_index, tile in enumerate(solution[y_index]):
if tile:
continue
if x_index > 0:
# we are not on left edge of solution
assert isinstance(solution[y_index][x_index - 1], Tile)
left_neighbor = solution[y_index][x_index - 1]
assert isinstance(left_neighbor, Tile)
for candidate_tile in generate_next_match(left_neighbor, tiles):
# find the right orientation for candidate_tile to left_neighbor
# and to up_neighbor
for orientation in generate_tile_orientation(candidate_tile):
if is_face_matches_face(
left_neighbor.data[:, -1], orientation[:, 0]
):
# print(f"Placing candidate tile {candidate_tile.number}")
solution[y_index][x_index] = Tile(
candidate_tile.number, orientation
)
if not is_partial_solution_valid(solution):
# keep trying orientations
continue
# this is the right orientation with all neighbors
# remove candidate match from tiles
tiles.remove(candidate_tile)
break
if solution[y_index][x_index] is not None:
break
assert solution[y_index][x_index] is not None
assert is_partial_solution_valid(solution)
elif x_index == 0:
# on left edge of solution, look at up neighbor
temp_tile: Optional[Tile] = solution[y_index - 1][x_index]
assert isinstance(temp_tile, Tile)
up_neighbor = temp_tile
for candidate_tile in generate_next_match(up_neighbor, tiles):
for orientation in generate_tile_orientation(candidate_tile):
if is_face_matches_face(up_neighbor.data[-1], orientation[0]):
# print(f"Placing candidate tile {candidate_tile.number}")
solution[y_index][x_index] = Tile(
candidate_tile.number, orientation
)
if not is_partial_solution_valid(solution):
# keep trying orientations
continue
# remove candidate match from tiles
tiles.remove(candidate_tile)
break
if solution[y_index][x_index] is not None:
break
assert solution[y_index][x_index] is not None
assert is_partial_solution_valid(solution)
for row in solution:
for tile in row:
assert isinstance(tile, Tile)
solution_complete: List[List[Tile]] = solution.copy() # type: ignore # assert above verified correctness
if DEBUG:
print(repr_solution_tiles(solution_complete))
str_solution = repr_solution(solution_complete)
print(str_solution)
monster = [" # ", "# ## ## ###", " # # # # # # "]
nparray_monster = list_str_to_nparray(monster)
# need to rotate and flip str_solution to get matches
nparray_solution = list_str_to_nparray(list_str_solution(solution_complete))
if DEBUG:
print(nparray_solution)
# matches = match_2d(monster, list_str_solution(solution))
# print(matches)
for orientation in generate_nparray_orientation(nparray_solution):
matches = match_2d(nparray_monster, orientation)
if len(matches) > 0:
break
if DEBUG:
print(orientation)
print(matches)
# count "#" minus (count "#" in monster * len(matches))
pound_in_orientation = len(
[char for row in orientation for char in row if char == "#"]
)
pound_in_monster = len(
[char for row in nparray_monster for char in row if char == "#"]
)
part2 = pound_in_orientation - (len(matches) * pound_in_monster)
return part2
def load_tiles(filename: str) -> List[Tile]:
with open(filename) as f:
tiles_str: List[str] = f.read().split("\n\n")
tiles: List[Tile] = []
t_index: int
tile_str: str
for t_index, tile_str in enumerate(tiles_str):
tile_temp: List[str] = tile_str.split("\n")
number: int = int(tile_temp[0].split()[1][:-1])
data: np.ndarray = np.array([[char for char in row] for row in tile_temp[1:]])
tiles.append(Tile(number, data))
return tiles
def main():
if USE_EXAMPLE1:
filename = "./AdventOfCode/2020/day20-example1-input.txt"
else:
filename = "./AdventOfCode/2020/day20-input.txt"
tiles: List[Tile] = load_tiles(filename)
if DEBUG:
pprint(tiles)
print(f"Loaded {len(tiles)} tiles")
print(
f"Each tile is {len(tiles[0].data)} rows, {len(tiles[0].data[0])} columns"
)
# Part 1
part1 = solve_part1(tiles)
print(f"Part 1: {part1}") # 68781323018729
if USE_EXAMPLE1:
assert part1 == 20899048083289
else:
assert part1 == 68781323018729
if PROFILE:
with cProfile.Profile() as pr:
solve_part1(tiles)
pr.print_stats()
# Part 2
part2 = solve_part2(tiles.copy())
print(f"Part 2: {part2}")
if USE_EXAMPLE1:
assert part2 == 273
else:
assert part2 == 1629
if PROFILE:
with cProfile.Profile() as pr:
solve_part2(tiles.copy())
pr.print_stats()
if __name__ == "__main__":
main() | 36.567026 | 110 | 0.605469 |
f9caa403c7cda77ed58ce080740499d1a738c3e3 | 1,870 | py | Python | src/server_main_loop.py | the40san/unity_survival_shooter_multi_server_python | d20d9aa2204bca70d0787acbfe395277b776e92d | [
"MIT"
] | 3 | 2017-04-11T05:36:08.000Z | 2021-03-16T16:22:07.000Z | src/server_main_loop.py | the40san/unity_survival_shooter_multi_server_python | d20d9aa2204bca70d0787acbfe395277b776e92d | [
"MIT"
] | null | null | null | src/server_main_loop.py | the40san/unity_survival_shooter_multi_server_python | d20d9aa2204bca70d0787acbfe395277b776e92d | [
"MIT"
] | 1 | 2017-04-11T05:35:26.000Z | 2017-04-11T05:35:26.000Z | import socket
import select
from server_info import ServerInfo
from client_handler.client_thread import ClientThread
from server_handler.server_thread import ServerThread
from server_handler.server_thread_proxy import ServerThreadProxy
from logger import Logger
| 30.16129 | 81 | 0.647059 |
f9caf1a992a5eacb6d048931ae39cf07dfd472c4 | 8,838 | py | Python | Aula_01/Aula01_Resolucao_Exercicios_Lista_Estruturas_Condicionais.py | elcbasilio/letscode | ea2ed5ee80485d98fad2c77a7a50927a7d524793 | [
"MIT"
] | null | null | null | Aula_01/Aula01_Resolucao_Exercicios_Lista_Estruturas_Condicionais.py | elcbasilio/letscode | ea2ed5ee80485d98fad2c77a7a50927a7d524793 | [
"MIT"
] | null | null | null | Aula_01/Aula01_Resolucao_Exercicios_Lista_Estruturas_Condicionais.py | elcbasilio/letscode | ea2ed5ee80485d98fad2c77a7a50927a7d524793 | [
"MIT"
] | null | null | null | # 1. Pea a idade do usurio e imprima se ele maior ou menor de 18 anos;
idade = int (input ('Digite sua idade:'))
if idade < 18:
print ('Voc tem menos de 18 anos')
else:
print ('Voc tem 18 anos ou mais')
# 2. Pea um nmero e mostre se ele positivo ou negativo;
numero = float (input ('Digite um nmero qualquer:'))
if numero < 0:
print ('Este nmero Negativo')
else:
print ('Este nmero Positivo')
# 3. Dado um nmero digitado, mostre se ele Par ou mpar
numero = int (input ('Digite um nmero inteiro:'))
if numero % 2 == 0:
print ('Este nmero Par')
else:
print ('Este nmero mpar')
# 4. Pea dois nmeros e mostre o maior deles;
n1 = float (input ('Digite um nmero qualquer:'))
n2 = float (input ('Digite mais um nmero qualquer:'))
if n1 < n2:
print ('O nmero',n1,' menor que o nmero',n2)
elif n1 > n2:
print ('O nmero',n1,' maior que o nmero',n2)
else:
print ('Os nmeros digitados so idnticos')
# 5. Faa um programa que leia a validade das informaes:
# a. Idade: entre 0 e 150;
# b. Salrio: maior que 0;
# c. Sexo: M, F ou Outro;
# O programa deve imprimir uma mensagem de erro para cada informao invlida.
idade = int (input ('Digite sua idade:'))
salario = float (input ('Digite seu salrio R$:'))
sexo = input ('Digite seu Sexo (M / F / O):')
if idade < 0 or idade > 150:
print ('A idade informada invlida, digite uma idade entre 0 e 150 anos')
if salario <= 0:
print ('O salrio informado invlido, digite um valor maior que 0')
if sexo != 'M' and sexo != 'F' and sexo != 'O' and sexo != 'm' and sexo != 'f' and sexo != 'o':
print ('O sexo informado invlido, digite M, F ou O')
# 6. Escreva um programa que pea a nota de 3 provas de um aluno, e verifique se ele passou o no de ano:
# Obs: O aluno ir passar de ano se sua mdia for maior que 6.
n1 = float (input ('Digite sua 1 Nota:'))
n2 = float (input ('Digite sua 2 Nota:'))
n3 = float (input ('Digite sua 3 Nota:'))
nf = (n1+n2+n3)/3
if nf <= 6:
print ('Sua nota mdia foi',nf,'e voc foi REPROVADO!')
else:
print ('Sua nota mdia foi',nf,'e voc foi APROVADO!')
# 7. Fazer um programa que mostre uma questo de mltipla escolha com 5 opes (letras a, b, c, d, e e).
# Sabendo a resposta certa, receber a opo do usurio e informar a letra que o usurio marcou e se a
# resposta est certa ou errada.
print ('Escolha a alternativa correta')
print ('')
print ('Pergunta: Quem descobriu o Brasil?')
print ('')
print ('a) Vasco da Gama')
print ('b) Jair Bolsonaro')
print ('c) Silvio Santos')
print ('d) Pedro lvares Cabral')
print ('e) Craque Neto 10')
print ('')
pergunta = (input ('Qual a resposta correta: '))
if pergunta == 'd' or pergunta == 'D':
print ('Voc selecionou a opo d) Pedro lvares Cabral. A resposta est correta')
elif pergunta == 'a' or pergunta == 'A':
print ('Voc selecionou a opo a) Vasco da Gama. A resposta est errada')
elif pergunta == 'b' or pergunta == 'B':
print ('Voc selecionou a opo b) Jair Bolsonaro. A resposta est errada')
elif pergunta == 'c' or pergunta == 'C':
print ('Voc selecionou a opo c) Silvio Santos. A resposta est errada')
elif pergunta == 'e' or pergunta == 'E':
print ('Voc selecionou a opo e) Craque Neto 10. A resposta est errada')
else:
print ('Voc selecionou uma opo invlida')
# 8. Vamos fazer um programa para verificar quem o assassino de um crime.
# Para descobrir a polcia reuniu um dos suspeitos e fez um pequeno questionrio com 5 perguntas de sim ou no:
# a. Telefonou para a vtima?
# b. Esteve no local do crime?
# c. Mora perto da vtima?
# d. Devia para a vtima?
# e. J trabalhou com a vtima?
# Cada resposta sim d um ponto para o suspeito, a polcia considera que os
# suspeitos com 5 pontos so os assassinos, com 4 a 3 pontos so cmplices
# e 2 pontos so apenas suspeitos, necessitando outras investigaes, valores
# abaixo de 1 so liberados.
print ('Responda S para Sim e N para No em cada uma das perguntas abaixo')
print ('')
p1 = input ('Telefonou para a vtima?')
p2 = input ('Esteve no local do crime?')
p3 = input ('Mora perto da vtima?')
p4 = input ('Devia para a vtima?')
p5 = input ('J trabalhou com a vtima?')
if p1 == 's' or p1 == 'S':
p11 = 1
else:
p11 = 0
if p2 == 's' or p1 == 'S':
p22 = 1
else:
p22 = 0
if p3 == 's' or p1 == 'S':
p33 = 1
else:
p33 = 0
if p4 == 's' or p1 == 'S':
p44 = 1
else:
p44 = 0
if p5 == 's' or p1 == 'S':
p55 = 1
else:
p55 = 0
soma = p11+p22+p33+p44+p55
print ('')
if soma == 5:
print ('Voc o Assassino')
elif soma >= 3:
print ('Voc Cmplice')
elif soma >= 1:
print ('Voc Suspeito')
else:
print ('Voc est Liberado')
# 9. Um produto vai sofrer aumento de acordo com a tabela 1 abaixo, pea para
# o usurio digitar o valor do produto de acordo com o preo antigo e
# escreva uma das mensagens da tabela 2, de acordo com o preo reajustado:
# Preo antigo Percentual de aumento
# At R$ 50 5%
# Entre R$ 50 e R$100 10%
# Entre R$100 e R$150 13%
# Acima de R$150 15%
# Preo Novo Mensagem
# Ate R$80 Barato
# Entre R$ 80 e R$115 Razovel
# Entre R$ 115 e R$150 Normal
# Entre R$ 150 e R$170 Caro
# Acima de R$170 Muito caro
print ('Reajuste de Preos')
pa = float (input ('Digit o preo do produto que ser reajustado: R$ '))
if pa <= 0:
print ('Digite um valor maior que ZERO')
pn=0
elif pa <= 50:
pn = pa * 1.05
elif pa <= 100:
pn = pa * 1.1
elif pa <= 150:
pn = pa * 1.13
else:
pn = pa * 1.15
if pn <= 0:
print ('')
elif pn < 80:
print ('O novo valor do produto R$',pn,'- Barato')
elif pn < 115:
print ('O novo valor do produto R$',pn,'- Razovel')
elif pn < 150:
print ('O novo valor do produto R$',pn,'- Normal')
elif pn < 170:
print ('O novo valor do produto R$',pn,'- Caro')
else:
print ('O novo valor do produto R$',pn,'- Muito Caro')
# Desafio
# 1. Faa um programa que leia 3 nmeros e informe o maior deles;
n1 = float (input ('Digite o 1 Nmero: '))
n2 = float (input ('Digite o 2 Nmero: '))
n3 = float (input ('Digite o 3 Nmero: '))
if n1 >= n2 and n1 >= n3:
print ('O maior nmero ',n1)
elif n2 >= n1 and n2 >= n3:
print ('O maior nmero ',n2)
elif n3 >= n1 and n3 >= n2:
print ('O maior nmero ',n3)
# 2. Agora faa com 4 nmeros;
n1 = float (input ('Digite o 1 Nmero: '))
n2 = float (input ('Digite o 2 Nmero: '))
n3 = float (input ('Digite o 3 Nmero: '))
n4 = float (input ('Digite o 4 Nmero: '))
if n1 >= n2 and n1 >= n3 and n1 >= n4:
print ('O maior nmero ',n1)
elif n2 >= n1 and n2 >= n3 and n2 >= n4:
print ('O maior nmero ',n2)
elif n3 >= n1 and n3 >= n2 and n3 >= n4:
print ('O maior nmero ',n3)
elif n4 >= n1 and n4 >= n2 and n4 >= n3:
print ('O maior nmero ',n4)
'''
3. Um hospital quer fazer o diagnstico de gripe ou dengue a partir de um
questionrio de sintomas, tendo as perguntas abaixo, faa um programa
que faa o diagnstico deste hospital:
a. Sente dor no corpo?
b. Voc tem febre?
c. Voc tem tosse?
d. Est com congesto nasal?
e. Tem manchas pelo corpo?
Para o diagnstico ele tem a seguinte tabela:
A B C D E Resultado
Sim Sim No No Sim Dengue
Sim Sim Sim Sim No gripe
No Sim Sim Sim No gripe
Sim No Sim Sim No Gripe
Sim No No No No Sem Doenas
No No No No No Sem Doenas
'''
print ('Diagnstico de gripe ou dengue')
print ('')
print ('Digite S para "Sim" ou N para "No"')
print ('')
p1 = (input ('Sente dor no corpo? '))
p2 = (input ('Voc tem febre? '))
p3 = (input ('Voc tem tosse? '))
p4 = (input ('Est com congesto nasal? '))
p5 = (input ('Tem manchas pelo corpo? '))
if (p1.upper()!='S' and p1.upper()!='N') and (p2.upper()!='S' and p2.upper()!='N') and (p3.upper()!='S' and p3.upper()!='N') and (p4.upper()!='S' and p4.upper()!='N') and (p5.upper()!='S' and p5.upper()!='N'):
print ('Voc digitou uma ou mais opes incorretas')
elif p1.upper()=='S' and p2.upper()=='S' and p3.upper()=='N' and p4.upper()=='N' and p5.upper()=='S':
print ('Diagnstico - Dengue')
elif p1.upper()=='S' and p2.upper()=='S' and p3.upper()=='S' and p4.upper()=='S' and p5.upper()=='N':
print ('Diagnstico - Gripe')
elif p1.upper()=='N' and p2.upper()=='S' and p3.upper()=='S' and p4.upper()=='S' and p5.upper()=='N':
print ('Diagnstico - Gripe')
elif p1.upper()=='S' and p2.upper()=='N' and p3.upper()=='S' and p4.upper()=='S' and p5.upper()=='N':
print ('Diagnstico - Gripe')
elif p1.upper()=='S' and p2.upper()=='N' and p3.upper()=='N' and p4.upper()=='N' and p5.upper()=='N':
print ('Diagnstico - Sem Doenas')
elif p1.upper()=='N' and p2.upper()=='N' and p3.upper()=='N' and p4.upper()=='N' and p5.upper()=='N':
print ('Diagnstico - Sem Doenas')
else:
print ('Diagnstico - Diagnstico no est especificado')
| 34.795276 | 209 | 0.642114 |
f9cd5d6aedbff1e1481a77881774667ef1fefe16 | 2,023 | py | Python | ros_radar_mine/neuro_learning/controller/testing/load_and_test.py | tudelft/blimp_snn | 23acbef8822337387aee196a3a10854e82bb4f80 | [
"Apache-2.0"
] | 3 | 2021-11-08T20:20:21.000Z | 2021-12-29T09:05:37.000Z | ros_radar_mine/neuro_learning/controller/testing/load_and_test.py | tudelft/blimp_snn | 23acbef8822337387aee196a3a10854e82bb4f80 | [
"Apache-2.0"
] | null | null | null | ros_radar_mine/neuro_learning/controller/testing/load_and_test.py | tudelft/blimp_snn | 23acbef8822337387aee196a3a10854e82bb4f80 | [
"Apache-2.0"
] | null | null | null | #!/usr/bin/env python3
# -*- coding: utf-8 -*-
"""
Created on Tue Mar 2 20:41:01 2021
@author: marina
Interesting:
- T2000_NPOP100_NGEN500_NEU2-10-5-2-1_05-04-2021_19-08-51: Really smooth and contained between (-3,3)
- T2000_NPOP100_NGEN500_NEU2-10-5-2-1_05-04-2021_19-25-20
"""
# Set absolute package path
import sys, os
sys.path.append(os.path.abspath(".."))
import os
import extra.aux_funcs as af # :)
import numpy as np
from evol_funcs.evol_mut_eval import evaluate, evaluate_SNNyPID
#from evol_funcs.evol_funcs_ANN import evaluate, evaluate_ANNyPID
import pid.myPID as PID
# Some constants
custom_config = True
#config_file = "config_night/config1.yaml"
config_file = "config.yaml"
# T2500_NPOP50_NGEN200_24-03-2021_23-47-25/
# T1500_NPOP60_NGEN400_24-03-2021_22-21-03/
# T3000_NPOP50_NGEN200_24-03-2021_22-06-17/
# T1800_NPOP40_NGEN500_NEU10-5-1-1_17-06-2021_11-40-05
# "T1800_NPOP40_NGEN500_NEU1-3-2-1_17-06-2021_15-10-09"
net_name = "T1200_NPOP40_NGEN500_NEU10-5-5-1_26-05-2021_13-34-44"
gen = 30
hof = True
num = 0
# Load configuration "cf" dir
cf = af.set_config("../config/" + config_file)
# Load population (IND or HOF)
pop = af.readPopulation(cf, net_name, gen, hof)
#pop = af.readPopulationSD(cf, net_name, gen, hof)
network = pop[num]
# Load network configuration
if not custom_config:
cf = network.cf
# Activate plotting
cf["evol"]["plot"] = True
# Evaluate network + plot
'''
network.pid[0] = -1
network.pid[1] = 0
network.pid[2] = 0
'''
#network.pid = [2,0,0]
individual = [network]
mse = evaluate(individual, cf, h_refList = cf["evol"]["h_ref"], h_init = cf["evol"]["h_init"])
#pid = PID.PID(*cf["pid"]["PID"], cf["pid"]["dt"], cf["pid"]["simple"])
#inputList = np.linspace(*cf["pid"]["input_lim"], cf["pid"]["n_points"])
#inputList = np.random.uniform(low=cf["pid"]["input_lim"][0], high=cf["pid"]["input_lim"][1], size = (cf["pid"]["n_points"],))
#mse = evaluate_PID(individual, cf, pid=pid, inputList=inputList)
print("MSE = ", mse)
#torch.save(model.state_dict(), PATH) | 26.973333 | 126 | 0.707365 |
f9ce968f21d6e6f401b8601663fad589082a13f8 | 293 | py | Python | HackerRank/Python/Sets/py-the-captains-room.py | neiesc/Problem-solving | d3bce7a3b9801e6049e2c135418b31cba47b0964 | [
"MIT"
] | 1 | 2019-07-20T16:59:21.000Z | 2019-07-20T16:59:21.000Z | HackerRank/Python/Sets/py-the-captains-room.py | neiesc/Problem-solving | d3bce7a3b9801e6049e2c135418b31cba47b0964 | [
"MIT"
] | 5 | 2019-03-10T19:46:42.000Z | 2020-04-24T22:42:30.000Z | HackerRank/Python/Sets/py-the-captains-room.py | neiesc/Problem-solving | d3bce7a3b9801e6049e2c135418b31cba47b0964 | [
"MIT"
] | null | null | null | #!/bin/python3
# The Captain's Room
# https://www.hackerrank.com/challenges/py-the-captains-room/problem
from collections import Counter
if __name__ == '__main__':
k = int(input())
room_captain = Counter(map(int, input().split())).most_common()[:-2:-1]
print(room_captain[0][0]) | 29.3 | 76 | 0.68942 |
f9cf4cff9f1ee36f3f46ec1c7c81c7f6a57782b0 | 1,536 | py | Python | transformer_2/data/processing/__init__.py | mingruimingrui/Transformer2 | 2b44289ee7c7312d699f2261c1e4ebccce0f21e2 | [
"MIT"
] | null | null | null | transformer_2/data/processing/__init__.py | mingruimingrui/Transformer2 | 2b44289ee7c7312d699f2261c1e4ebccce0f21e2 | [
"MIT"
] | 1 | 2020-06-01T02:13:10.000Z | 2020-06-01T02:13:10.000Z | transformer_2/data/processing/__init__.py | mingruimingrui/Transformer2 | 2b44289ee7c7312d699f2261c1e4ebccce0f21e2 | [
"MIT"
] | null | null | null | from __future__ import absolute_import
from __future__ import unicode_literals
# Registry
from transformer_2.data.processing._registry import PROCESSOR_REGISTRY, \
BaseProcessor, register_processor, Compose, make_processor_from_list
# Generic processors
from transformer_2.data.processing.general import HtmlUnescape, HtmlEscape, \
Lowercase, Strip, WhitespaceNormalize, UnicodeNormalize
from transformer_2.data.processing.replace import ReplaceSubstrings, \
ReplaceTokens, WhitelistCharacters
# Specialized processors
from transformer_2.data.processing.onmt import OnmtTokenize, OnmtDetokenize
from transformer_2.data.processing.sentencepiece import SpmEncode, SpmDecode
from transformer_2.data.processing.sacremoses import SacremosesTokenize, \
SacremosesDetokenize
# Language specific processors
from transformer_2.data.processing.chinese import ToSimplifiedChinese, \
ToTraditionalChinese, Jieba
# Default processing steps
from transformer_2.data.processing._default import DEFAULT_PROCESSING_STEPS
__all__ = [
'PROCESSOR_REGISTRY', 'BaseProcessor', 'register_processor',
'Compose', 'make_processor_from_list',
'HtmlUnescape', 'HtmlEscape',
'Lowercase', 'Strip',
'WhitespaceNormalize', 'UnicodeNormalize',
'ReplaceSubstrings', 'ReplaceTokens', 'WhitelistCharacters',
'OnmtTokenize', 'OnmtDetokenize',
'SacremosesTokenize', 'SacremosesDetokenize',
'SpmEncode', 'SpmDecode',
'ToSimplifiedChinese', 'ToTraditionalChinese', 'Jieba',
'DEFAULT_PROCESSING_STEPS'
]
| 34.909091 | 77 | 0.802734 |
f9d231776637662c74f12d56ca75ccd899e7d32a | 7,223 | py | Python | pydmc/pydmc.py | TeradataInteractiveAmericas/pydmc | 817899311f7908436fba7e1fc553a019bafadcb6 | [
"MIT"
] | 1 | 2017-02-16T13:55:32.000Z | 2017-02-16T13:55:32.000Z | pydmc/pydmc.py | TeradataInteractiveAmericas/pydmc | 817899311f7908436fba7e1fc553a019bafadcb6 | [
"MIT"
] | null | null | null | pydmc/pydmc.py | TeradataInteractiveAmericas/pydmc | 817899311f7908436fba7e1fc553a019bafadcb6 | [
"MIT"
] | null | null | null | """
PyDMC API Client
"""
import requests
| 29.72428 | 131 | 0.5668 |
f9d3186f39a6e3865241f7bef73bfedbb15ea7d5 | 832 | py | Python | COE/contents/building/__init__.py | Python-Project-Cheap-Empire/cheap-of-empire | 44aaae29e4fadc9df46734f529031ce8c4bb3475 | [
"MIT"
] | null | null | null | COE/contents/building/__init__.py | Python-Project-Cheap-Empire/cheap-of-empire | 44aaae29e4fadc9df46734f529031ce8c4bb3475 | [
"MIT"
] | 2 | 2022-01-31T21:05:15.000Z | 2022-01-31T21:08:11.000Z | COE/contents/building/__init__.py | Python-Project-Cheap-Empire/cheap-of-empire | 44aaae29e4fadc9df46734f529031ce8c4bb3475 | [
"MIT"
] | 1 | 2022-02-04T12:05:14.000Z | 2022-02-04T12:05:14.000Z | from .archery_range import ArcheryRange
from .barrack import Barrack
from .building import Building
from .dock import Dock
from .farm import Farm
from .granary import Granary
from .market import Market
from .military_building import MilitaryBuilding
from .stable import Stable
from .storage_building import StorageBuilding
from .storage_pit import StoragePit
from .technology_building import TechnologyBuilding
from .town_center import TownCenter
from .house import House
from .watch_tower import WatchTower
from .small_wall import SmallWall
__all__ = [
"ArcheryRange",
"Barrack",
"Building",
"Dock",
"Farm",
"Granary",
"Market",
"MilitaryBuilding",
"Stable",
"StorageBuilding",
"StoragePit",
"TechnologyBuilding",
"TownCenter",
"House",
"WatchTower",
"SmallWall",
]
| 23.111111 | 51 | 0.740385 |
f9d3e8e17cb4d7f9fe9db4b44a63b0c8a9f8f65f | 323 | py | Python | test/suite/E27.py | shardros/autopep8 | 2ab2ea74668b10f3910f3d5b9526494fa5671ca1 | [
"MIT"
] | 3,459 | 2015-01-03T15:53:43.000Z | 2022-03-31T16:33:01.000Z | test/suite/E27.py | hayata-yamamoto/autopep8 | 107e29dce22c7b367a36633a78735278e4ad4288 | [
"MIT"
] | 435 | 2015-01-03T12:58:44.000Z | 2022-03-29T12:37:13.000Z | test/suite/E27.py | hayata-yamamoto/autopep8 | 107e29dce22c7b367a36633a78735278e4ad4288 | [
"MIT"
] | 279 | 2015-03-16T16:34:51.000Z | 2022-03-26T23:58:48.000Z | #: Okay
True and False
#: E271
True and False
#: E272
True and False
#: E271
if 1:
#: E273
True and False
#: E273 E274
True and False
#: E271
a and b
#: E271
1 and b
#: E271
a and 2
#: E271 E272
1 and b
#: E271 E272
a and 2
#: E272
this and False
#: E273
a and b
#: E274
a and b
#: E273 E274
this and False
| 10.419355 | 15 | 0.613003 |
f9d666c57cbfbdaa2610dd40857b2cf6d3dbfa06 | 8,973 | py | Python | api/GIS/functionalFun/thread_GIS.py | AutoCoinDCF/NEW_API | f4abc48fff907a0785372b941afcd67e62eec825 | [
"Apache-2.0"
] | null | null | null | api/GIS/functionalFun/thread_GIS.py | AutoCoinDCF/NEW_API | f4abc48fff907a0785372b941afcd67e62eec825 | [
"Apache-2.0"
] | null | null | null | api/GIS/functionalFun/thread_GIS.py | AutoCoinDCF/NEW_API | f4abc48fff907a0785372b941afcd67e62eec825 | [
"Apache-2.0"
] | null | null | null | from threading import Thread,Lock
from api.GIS.config import GIS_mgdb_config
from api.GIS.database.mongoDB import MGO
import json
from api.GIS.GISStaticsFun import GisStaticsFun
| 41.35023 | 140 | 0.5482 |
f9d69be77fcbae4d67f52431660566569a03abe1 | 268 | py | Python | src/cell.py | ViktorBusk/Machine-Learning-Number-Prediction | f9863ccdb623ed3bf83ca26faae310d56f087c4f | [
"MIT"
] | null | null | null | src/cell.py | ViktorBusk/Machine-Learning-Number-Prediction | f9863ccdb623ed3bf83ca26faae310d56f087c4f | [
"MIT"
] | null | null | null | src/cell.py | ViktorBusk/Machine-Learning-Number-Prediction | f9863ccdb623ed3bf83ca26faae310d56f087c4f | [
"MIT"
] | null | null | null | import pygame | 26.8 | 77 | 0.630597 |
f9d780addff74609d2c11318421ccdacd8b15d8d | 1,845 | py | Python | Creating a variable at template using filter.py/filter.py | YooInKeun/Facebook-Page-Insights-Web-Crawler | dbe8477b1e0671aca137cd94eff090d691e99ee2 | [
"MIT"
] | 1 | 2021-07-12T00:04:04.000Z | 2021-07-12T00:04:04.000Z | Creating a variable at template using filter.py/filter.py | YooInKeun/Facebook-Page-Insights-Web-Crawler | dbe8477b1e0671aca137cd94eff090d691e99ee2 | [
"MIT"
] | null | null | null | Creating a variable at template using filter.py/filter.py | YooInKeun/Facebook-Page-Insights-Web-Crawler | dbe8477b1e0671aca137cd94eff090d691e99ee2 | [
"MIT"
] | null | null | null | from django import template
register = template.Library()
#
import re
#
class SetVarNode(template.Node):
| 29.758065 | 112 | 0.616802 |
f9d7b799633ebd72932c23f0a6056d0edfbe48dc | 2,194 | py | Python | kblight.py | marklr/system76-kbdlight-cli | 03ba5ce04c7abd7b125e6777aac7cf19c6651f51 | [
"MIT"
] | null | null | null | kblight.py | marklr/system76-kbdlight-cli | 03ba5ce04c7abd7b125e6777aac7cf19c6651f51 | [
"MIT"
] | null | null | null | kblight.py | marklr/system76-kbdlight-cli | 03ba5ce04c7abd7b125e6777aac7cf19c6651f51 | [
"MIT"
] | null | null | null | #!/bin/env python3
import sys
import plac
import webcolors
import os
_COLOR_FILTERS = {
'#': '',
'(': '',
')': '',
}
LIGHT_CONTROLS = {
'left': '/sys/class/leds/system76::kbd_backlight/color_left',
'center': '/sys/class/leds/system76::kbd_backlight/color_center',
'right': '/sys/class/leds/system76::kbd_backlight/color_right',
}
if __name__ == '__main__':
plac.call(main)
| 26.119048 | 91 | 0.592981 |
f9d8c56ae37748311a4ccb37002818c53ff1fd16 | 420 | py | Python | fimath/constants.py | kalinkinisaac/modular | 301d26ad222a5ef3278aaf251908e0a8537bb58f | [
"MIT"
] | null | null | null | fimath/constants.py | kalinkinisaac/modular | 301d26ad222a5ef3278aaf251908e0a8537bb58f | [
"MIT"
] | null | null | null | fimath/constants.py | kalinkinisaac/modular | 301d26ad222a5ef3278aaf251908e0a8537bb58f | [
"MIT"
] | null | null | null | from .field import Field
from .re_field import ReField
from .matrix import Matrix
inf = Field(is_inf=True)
IDM = Matrix(1, 0, 0, 1)
G0 = Matrix(0, -1, 1, 0)
G1 = Matrix(0, 1, -1, 1)
G1_2 = G1 ** 2
G0_ = Matrix(0, 1, -1, 0)
G1_ = Matrix(1, 1, -1, 0)
G1_2_ = G1_ ** 2
G_ = Matrix(1, -1, 0, 1)
G__ = Matrix(1, 0, -1, 1)
ZERO = Field(0)
ONE = Field(1)
INF = inf
V0 = Field(1j)
V1 = Field(ReField(1/2), ReField(b=1/2))
| 16.8 | 40 | 0.592857 |
f9dab830b35494d6660350f19bc8089f5510126e | 116 | py | Python | test/__init__.py | elagheb/at_commands | 51f1fa553b651b639aa3d1e1b3ac4ff07322f7a0 | [
"BSD-2-Clause"
] | null | null | null | test/__init__.py | elagheb/at_commands | 51f1fa553b651b639aa3d1e1b3ac4ff07322f7a0 | [
"BSD-2-Clause"
] | null | null | null | test/__init__.py | elagheb/at_commands | 51f1fa553b651b639aa3d1e1b3ac4ff07322f7a0 | [
"BSD-2-Clause"
] | null | null | null | import unittest
import unittest.mock as mock
from unittest.mock import patch
__all__ = ['unittest','mock','patch']
| 19.333333 | 37 | 0.767241 |
f9ddbc50ba159c971816ef0bfcfea8bf2513c89c | 5,972 | py | Python | reporte.py | InoveProyectos/Buscador-Alquileres-Python | 78379da88db7957cdc8c804e0491f2a796e2c706 | [
"Unlicense"
] | 1 | 2020-05-13T04:29:44.000Z | 2020-05-13T04:29:44.000Z | reporte.py | InoveProyectos/Buscador-Alquileres-Python | 78379da88db7957cdc8c804e0491f2a796e2c706 | [
"Unlicense"
] | null | null | null | reporte.py | InoveProyectos/Buscador-Alquileres-Python | 78379da88db7957cdc8c804e0491f2a796e2c706 | [
"Unlicense"
] | 3 | 2020-05-13T18:25:34.000Z | 2020-11-24T16:19:37.000Z | #!/usr/bin/env python
'''
Reporte bsqueda de alquileres de Inmuebles
---------------------------
Autor: Inove Coding School
Version: 1.0
Descripcion:
Este script realiza reportes de los datos adquiridos de alquileres de inmuebles
Reporte N
0: Visualizar todos los reportes juntos de estudio por ambientes y m2
1: Cantidad de alquileres por ambiente
2: Precio por ambiente
3: Cantidad de alquileres por m2
4: Precio por m2
5: Calcular y visualizar le prediccion de costos por m2
Requisitos de instalacion:
- Python 3.x
- Libreriras (incluye los comandos de instalacion)
pip install numpy
pip install pandas
pip install matplotlib
pip install seaborn
pip install sklearn
'''
__author__ = "Inove Coding School"
__email__ = "INFO@INOVE.COM.AR"
__version__ = "1.0"
import sys
import pandas as pd
import numpy as np
import matplotlib.pyplot as plt
import matplotlib.axes
import seaborn as sns
from sklearn import linear_model
if __name__ == '__main__':
try:
reporte = int(sys.argv[1]) # Tomo el nmero de reporte de la lne ade comando
except:
reporte = 0 # Sino especificamos el reporte a visualizar se mostrarn todos
if(reporte < 0 or reporte > 7):
print("Error: El reporte especificado debe estar entre los valores 0 y 7")
generar_reporte(reporte=reporte) | 39.289474 | 146 | 0.641996 |