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
e0774173b092651de83171acaf096405634f72ae
2,536
py
Python
projects/tutorials/object_nav_ithor_dagger_then_ppo_one_object.py
klemenkotar/dcrl
457be7af1389db37ec12e165dfad646e17359162
[ "MIT" ]
18
2021-06-09T04:50:47.000Z
2022-02-04T22:56:56.000Z
projects/tutorials/object_nav_ithor_dagger_then_ppo_one_object.py
klemenkotar/dcrl
457be7af1389db37ec12e165dfad646e17359162
[ "MIT" ]
null
null
null
projects/tutorials/object_nav_ithor_dagger_then_ppo_one_object.py
klemenkotar/dcrl
457be7af1389db37ec12e165dfad646e17359162
[ "MIT" ]
4
2021-06-09T06:20:25.000Z
2022-03-13T03:11:17.000Z
import torch import torch.optim as optim from torch.optim.lr_scheduler import LambdaLR from allenact.algorithms.onpolicy_sync.losses import PPO from allenact.algorithms.onpolicy_sync.losses.imitation import Imitation from allenact.algorithms.onpolicy_sync.losses.ppo import PPOConfig from allenact.utils.experiment_utils import ( Builder, PipelineStage, TrainingPipeline, LinearDecay, ) from projects.tutorials.object_nav_ithor_ppo_one_object import ( ObjectNavThorPPOExperimentConfig, )
34.27027
88
0.635252
e077592087a48a19c044b7ca66417c720c7d2548
12,328
py
Python
BioCAT/src/Calculating_scores.py
DanilKrivonos/BioCAT-nrp-BIOsynthesis-Caluster-Analyzing-Tool
d58d330e3e11380c0c917a0ad9c12a51447f1624
[ "MIT" ]
4
2021-04-16T14:42:47.000Z
2021-06-11T14:29:35.000Z
BioCAT/src/Calculating_scores.py
DanilKrivonos/BioCAT-nrp-BIOsynthesis-Caluster-Analyzing-Tool
d58d330e3e11380c0c917a0ad9c12a51447f1624
[ "MIT" ]
3
2021-07-23T09:30:59.000Z
2021-11-07T17:40:59.000Z
BioCAT/src/Calculating_scores.py
DanilKrivonos/BioCAT-nrp-BIOsynthesis-Caluster-Analyzing-Tool
d58d330e3e11380c0c917a0ad9c12a51447f1624
[ "MIT" ]
1
2022-02-27T17:19:50.000Z
2022-02-27T17:19:50.000Z
from numpy import array from pickle import load from pandas import read_csv import os from BioCAT.src.Combinatorics import multi_thread_shuffling, multi_thread_calculating_scores, make_combine, get_score, get_max_aminochain, skipper # Importing random forest model modelpath = os.path.dirname(os.path.abspath(__file__)) + '/RFC.dump' Rf = load(open(modelpath, 'rb')) # The function generate list of shuflled matrix def make_shuffle_matrix(matrix, cpu, iterat): """ The functuion generate massive of shuffled matrix. Parameters ---------- matrix : pandas DataFrame PSSM profile. cpu : int Number of tred used. iterat : int Number of iterations of shuffling. Returns ------- module_shuffling_matrix : list List of matrix, shuffled by module. substrate_shuffling_matrix : list List of matrix, shuffled by substrate. """ module_shuffling_matrix = multi_thread_shuffling(matrix, ShufflingType='module', iterations=iterat, threads=cpu) substrate_shuffling_matrix = multi_thread_shuffling(matrix, ShufflingType='substrate', iterations=iterat, threads=cpu) return module_shuffling_matrix, substrate_shuffling_matrix # The fujnction finds suquence with maximum possible value, results from alignment def get_MaxSeq(matrix, variant_seq): """ The functuion parallel calculation of scores for shuffled matrix. Parameters ---------- matrix : pandas DataFrame PSSM profile. variant_seq : list Variant of core peptide chain. Returns ------- shuffled_scores : list List of scores for shuffled matrix. """ MaxSeq = [] subs = matrix.keys()[1: ] # Find sequence, wich have maximum alignment score for idx in matrix.index: MAX_value = max(list(matrix.iloc[idx][1:])) for key in subs: if matrix[key][idx] == MAX_value: MaxSeq.append(key) # If two smonomer have same value break # Making two variants of MaxSeq MaxSeq_full = MaxSeq.copy() MaxSeq_nan = MaxSeq.copy() for max_sub_idx in range(len(MaxSeq)): if variant_seq[max_sub_idx] == 'nan': MaxSeq_nan[max_sub_idx] = 'nan' # Adding nan to MaxSeq return MaxSeq_full, MaxSeq_nan # The function gives an information about clusters def get_cluster_info(table, BGC_ID, target_file): """ The functuion return information about cluster. Parameters ---------- table : pandas DataFrame Table with meta inforamtion about NRPS clusters. BGC_ID : str PSSM cluster ID. target_file : pandas DataFrame PSSM profile. Returns ------- Name : str Cluster ID. Coord_cluster : str Coordinate of cluster. strand : str Strand of cluster. """ for ind in table[table['ID'].str.contains(BGC_ID)].index: Name = table[table['ID'].str.contains(target_file.split('.')[0].split('_A_')[1])]['Name'][ind] Coord_cluster = table['Coordinates of cluster'][ind] strand = table['Gen strand'][ind] break return Name, Coord_cluster, strand # Calculate scores def calculate_scores(variant_seq, matrix, substrate_shuffling_matrix, module_shuffling_matrix, cpu, iterat): """ Calculating scores. Parameters ---------- variant_seq : list Variant of core peptide chain. matrix : pandas DataFrame PSSM profile. substrate_shuffling_matrix : list List of matrix, shuffled by substrate. module_shuffling_matrix : list List of matrix, shuffled by module. cpu : int Number of threads used. iterat : int Number of iterations of shuffling. Returns ------- Sln_score : float Mln_score : float Slt_score : float Mlt_score : float Sdn_score : float Mdn_score : float Sdt_score : float Mdt_score : float Scores, which calculated with shuffling matrix by different variants. M - module shuffling S - substrate shuffling l - logarithmic transformation of score d - raw score n - MaxSeq with nan replacement t - MaxSeq without nan replacement Relative_score : float Relative score (Probability of target class) Binary : float Binary score of cluster matching. """ # Finding suquence with maximum possible value, results from alignment MaxSeq_full, MaxSeq_nan = get_MaxSeq(matrix, variant_seq) # Calculating shuffled scores Sln_shuffled_score = array(multi_thread_calculating_scores(MaxSeq_nan, substrate_shuffling_matrix, type_value='log', iterations=iterat, threads=cpu)) Mln_shuffled_score = array(multi_thread_calculating_scores(MaxSeq_nan, module_shuffling_matrix, type_value='log', iterations=iterat, threads=cpu)) Slt_shuffled_score = array(multi_thread_calculating_scores(MaxSeq_full, substrate_shuffling_matrix, type_value='log', iterations=iterat, threads=cpu)) Mlt_shuffled_score = array(multi_thread_calculating_scores(MaxSeq_full, module_shuffling_matrix, type_value='log', iterations=iterat, threads=cpu)) Sdn_shuffled_score = array(multi_thread_calculating_scores(MaxSeq_nan, substrate_shuffling_matrix, type_value=None, iterations=iterat, threads=cpu)) Mdn_shuffled_score = array(multi_thread_calculating_scores(MaxSeq_nan, module_shuffling_matrix, type_value=None, iterations=iterat, threads=cpu)) Sdt_shuffled_score = array(multi_thread_calculating_scores(MaxSeq_full, substrate_shuffling_matrix, type_value=None, iterations=iterat, threads=cpu)) Mdt_shuffled_score = array(multi_thread_calculating_scores(MaxSeq_full, module_shuffling_matrix, type_value=None, iterations=iterat, threads=cpu)) # Calculating scores for target sequence log_target_score = get_score(variant_seq, matrix, type_value='log') non_log_target_score = get_score(variant_seq, matrix, type_value=None) # Calculating features scores Sln_score = len(Sln_shuffled_score[Sln_shuffled_score < log_target_score])/len(Sln_shuffled_score) Mln_score = len(Mln_shuffled_score[Mln_shuffled_score < log_target_score])/len(Mln_shuffled_score) Slt_score = len(Slt_shuffled_score[Slt_shuffled_score < log_target_score])/len(Slt_shuffled_score) Mlt_score = len(Mlt_shuffled_score[Mlt_shuffled_score < log_target_score])/len(Mlt_shuffled_score) Sdn_score = len(Sdn_shuffled_score[Sdn_shuffled_score < non_log_target_score])/len(Sdn_shuffled_score) Mdn_score = len(Mdn_shuffled_score[Mdn_shuffled_score < non_log_target_score])/len(Mdn_shuffled_score) Sdt_score = len(Sdt_shuffled_score[Sdt_shuffled_score < non_log_target_score])/len(Sdt_shuffled_score) Mdt_score = len(Mdt_shuffled_score[Mdt_shuffled_score < non_log_target_score])/len(Mdt_shuffled_score) # Calculating Relative score Relative_score = round(Rf.predict_proba([[Sln_score, Mln_score, Sdn_score, Mdn_score, Sdt_score, Mdt_score, Slt_score, Mlt_score ]])[0][1], 3) Binary = Rf.predict([[Sln_score, Mln_score, Sdn_score, Mdn_score, Sdt_score, Mdt_score, Slt_score, Mlt_score ]])[0] return Sln_score, Mln_score, Slt_score, Mlt_score, Sdn_score, Mdn_score, Sdt_score, Mdt_score, Relative_score, Binary def give_results(tsv_out, folder, files, table, ID, PeptideSeq, skip, cpu, iterat): """ The functuion return information about cluster. Parameters ---------- tsv_out : dict Empty dictionary for adding results. folder : str Path to PSSMs. files : list List of PSSMs. table : pandas DataFrame Table with meta inforamtion about NRPS clusters. ID : str Name of substance. PeptideSeq : dict Core peptide chains for different biosynthesis types (e.g. A, B, or C). kip : int Number of presumptive skip. cpu : int Number of threads used. iterat : int Number of iterations of shuffling. Returns ------- tsv_out : dict Full dictionary for adding results. """ for target_file in files: try: BGC_ID = target_file.split('.')[0].split('_A_')[1] except: continue if '_A_' not in target_file: continue Name, Coord_cluster, strand = get_cluster_info(table, BGC_ID, target_file) # Getting information about cluster BGC = read_csv(folder + target_file, sep='\t') # Skipping mode if skip == 0: BGC = [BGC] else: BGC == skipper(BGC, skip) for matrix in BGC: # Check quality of matrix if len(matrix) == 1: continue check = 0 values = matrix.drop(matrix.columns[0], axis=1).values for i in values: if all(i) == 0: check += 1 if check == len(values): # If thes condition is True, the matrix of unrecognized monomers continue # Generating shuffling matrix module_shuffling_matrix, substrate_shuffling_matrix = make_shuffle_matrix(matrix, cpu, iterat) for BS_type in PeptideSeq:# For every biosynthesis profile pathways if PeptideSeq[BS_type] == None: # If in sequence only nan monomers continue if len(PeptideSeq[BS_type]) == 0: # If have not the variant continue # Check correctness of PeptideSeq length_max= get_max_aminochain(PeptideSeq[BS_type]) EPs = make_combine(PeptideSeq[BS_type], length_max, matrix, delta=3) if EPs is None: # If length sequnce can't be scaled to cluster size continue for variant_seq in EPs: Sln_score, Mln_score, Slt_score, Mlt_score, Sdn_score, Mdn_score, Sdt_score, Mdt_score, Relative_score, Binary = calculate_scores(variant_seq, matrix, substrate_shuffling_matrix, module_shuffling_matrix, cpu, iterat) #Recordind dictionary tsv_out['Chromosome ID'].append(Name) tsv_out['Coordinates of cluster'].append(Coord_cluster) tsv_out['Strand'].append(strand) tsv_out['Substance'].append(ID) tsv_out['BGC ID'].append(BGC_ID) tsv_out['Putative linearized NRP sequence'].append('--'.join(variant_seq)) tsv_out['Biosynthesis profile'].append('Type {}'.format(BS_type)) tsv_out['Sln score'].append(Sln_score) #shaffling substrates in matrix with log score and nan in maximally possible sequence tsv_out['Mln score'].append(Mln_score) #shaffling modules matrix with log score and nan in maximally possible sequence tsv_out['Sdn score'].append(Sdn_score) #shaffling substrates matrix without log score and nan in maximally possible sequence tsv_out['Mdn score'].append(Mdn_score) #shaffling modules matrix without log score and nan in maximally possible sequence tsv_out['Sdt score'].append(Sdt_score) #shaffling substrates matrix without log score in maximally possible sequence tsv_out['Mdt score'].append(Mdt_score) #shaffling modules matrix without log score in maximally possible sequence tsv_out['Slt score'].append(Slt_score) #shaffling substrates matrix with log score in maximally possible sequence tsv_out['Mlt score'].append(Mlt_score) #shaffling modules matrix with log score in maximally possible sequence tsv_out['Relative score'].append(Relative_score) #Final score tsv_out['Binary'].append(Binary) #Binary value return tsv_out
42.510345
236
0.649903
e0776cc9711477b5d215a8a600b08e98b5af4d8a
857
py
Python
deal/linter/_extractors/returns.py
m4ta1l/deal
2a8e9bf412b8635b00a2b798dd8802375814a1c8
[ "MIT" ]
1
2020-09-05T13:54:16.000Z
2020-09-05T13:54:16.000Z
deal/linter/_extractors/returns.py
m4ta1l/deal
2a8e9bf412b8635b00a2b798dd8802375814a1c8
[ "MIT" ]
7
2020-09-05T13:54:28.000Z
2020-11-27T05:59:19.000Z
deal/linter/_extractors/returns.py
Smirenost/deal
2a8e9bf412b8635b00a2b798dd8802375814a1c8
[ "MIT" ]
null
null
null
# built-in from typing import Optional # app from .common import TOKENS, Extractor, Token, traverse from .value import UNKNOWN, get_value get_returns = Extractor() inner_extractor = Extractor()
25.205882
74
0.711785
e077be2cbaa5c0711f376c7e5a696aa0b37ee960
1,526
py
Python
qubiter/device_specific/chip_couplings_ibm.py
yourball/qubiter
5ef0ea064fa8c9f125f7951a01fbb88504a054a5
[ "Apache-2.0" ]
3
2019-10-03T04:27:36.000Z
2021-02-13T17:49:34.000Z
qubiter/device_specific/chip_couplings_ibm.py
yourball/qubiter
5ef0ea064fa8c9f125f7951a01fbb88504a054a5
[ "Apache-2.0" ]
null
null
null
qubiter/device_specific/chip_couplings_ibm.py
yourball/qubiter
5ef0ea064fa8c9f125f7951a01fbb88504a054a5
[ "Apache-2.0" ]
2
2020-10-07T15:22:19.000Z
2021-06-07T04:59:58.000Z
# retired ibmqx2_c_to_tars =\ { 0: [1, 2], 1: [2], 2: [], 3: [2, 4], 4: [2] } # 6 edges # retired ibmqx4_c_to_tars =\ { 0: [], 1: [0], 2: [0, 1, 4], 3: [2, 4], 4: [] } # 6 edges # retired ibmq16Rus_c_to_tars = \ { 0: [], 1: [0, 2], 2: [3], 3: [4, 14], 4: [], 5: [4], 6: [5, 7, 11], 7: [10], 8: [7], 9: [8, 10], 10: [], 11: [10], 12: [5, 11, 13], 13: [4, 14], 14: [], 15: [0, 2, 14] } # 22 edges ibm20AustinTokyo_c_to_tars = \ { 0: [1, 5], 1: [0, 2, 6, 7], 2: [1, 3, 6, 7], 3: [2, 4, 8, 9], 4: [3, 8, 9], 5: [0, 6, 10, 11], 6: [1, 2, 5, 7, 10, 11], 7: [1, 2, 6, 8, 12, 13], 8: [3, 4, 7, 9, 12, 13], 9: [3, 4, 8, 14], 10: [5, 6, 11, 15], 11: [5, 6, 10, 12, 16, 17], 12: [7, 8, 11, 13, 16, 17], 13: [7, 8, 12, 14, 18, 19], 14: [9, 13, 18, 19], 15: [10, 16], 16: [11, 12, 15, 17], 17: [11, 12, 16, 18], 18: [13, 14, 17, 19], 19: [13, 14, 18] } # 86 edges ibmq5YorktownTenerife_c_to_tars = \ { 0: [1, 2], 1: [0, 2], 2: [0, 1, 3, 4], 3: [2, 4], 4: [2, 3] } # 12 edges ibmq14Melb_c_to_tars = \ { 0: [1], 1: [0, 2, 13], 2: [1, 3, 12], 3: [2, 4, 11], 4: [3, 5, 10], 5: [4, 6, 9], 6: [5, 8], 7: [8], 8: [6, 7, 9], 9: [5, 8, 10], 10: [4, 9, 11], 11: [3, 10, 12], 12: [2, 11, 13], 13: [1, 12] } # 36 edges
15.895833
39
0.355177
e07835355388fff9c6902a335662f753bb73c86c
14,599
py
Python
Template.py
rainshen49/citadel-trading-comp
3c3b6464f548d4920f46b5f5cd113ebc4a1d08a5
[ "MIT" ]
2
2018-12-11T03:33:06.000Z
2021-09-21T01:12:58.000Z
Template.py
rainshen49/citadel-trading-comp
3c3b6464f548d4920f46b5f5cd113ebc4a1d08a5
[ "MIT" ]
null
null
null
Template.py
rainshen49/citadel-trading-comp
3c3b6464f548d4920f46b5f5cd113ebc4a1d08a5
[ "MIT" ]
null
null
null
import signal import requests import time from math import floor shutdown = False MAIN_TAKER = 0.0065 MAIN_MAKER = 0.002 ALT_TAKER = 0.005 ALT_MAKER = 0.0035 TAKER = (MAIN_TAKER + ALT_TAKER)*2 MAKER = MAIN_MAKER + ALT_MAKER TAKEMAIN = MAIN_TAKER - ALT_MAKER TAKEALT = ALT_TAKER - MAIN_MAKER BUFFER = 0.01 NaN = float('nan') def main(): # price does change in every tick # check position # plain arbitradge # index arbitrage # shock handling # wave riding # pairTickers = [('WMT-M', 'WMT-A'), ('CAT-M', 'CAT-A'), ('MMM-M', 'MMM-A')] with Session('http://localhost:9998', 'VHK3DEDE') as session: while session.get_tick(): try: shock_runner(session) exchange_arbitrage(session, "WMT-M", "WMT-A") exchange_arbitrage(session, "CAT-M", "CAT-A") exchange_arbitrage(session, "MMM-M", "MMM-A") index_arbitrage(session, ['WMT', 'MMM', 'CAT']) except Exception as ex: print("error", str(ex)) # trader = session.getTrader() # print(trader['nlv']) # TODO: position cleaner: try to reduce gross position loss-free # TODO: implement range runner for the last x ticks TAKER4 = MAIN_TAKER * 5 # TODO: send limit orders and use market to cover unfilled ones after if __name__ == '__main__': signal.signal(signal.SIGINT, sigint) main()
33.407323
116
0.558052
e078ffec67d1b2046e248c3ee5d65b353731cbf4
1,479
py
Python
examples/basic/wire_feedthrough.py
souviksaha97/spydrnet-physical
b07bcc152737158ea7cbebf0ef844abe49d29c5e
[ "BSD-3-Clause" ]
null
null
null
examples/basic/wire_feedthrough.py
souviksaha97/spydrnet-physical
b07bcc152737158ea7cbebf0ef844abe49d29c5e
[ "BSD-3-Clause" ]
null
null
null
examples/basic/wire_feedthrough.py
souviksaha97/spydrnet-physical
b07bcc152737158ea7cbebf0ef844abe49d29c5e
[ "BSD-3-Clause" ]
null
null
null
""" ========================================== Genrating feedthrough from single instance ========================================== This example demostrates how to generate a feedthrough wire connection for a given scalar or vector wires. **Initial Design** .. hdl-diagram:: ../../../examples/basic/_initial_design.v :type: netlistsvg :align: center :module: top **Output1** ``wire0`` feedthough from ``inst_2_1`` .. hdl-diagram:: ../../../examples/basic/_output_wire.v :type: netlistsvg :align: center :module: top **Output2** ``bus_in`` feedthrough from ``inst_1_0`` .. hdl-diagram:: ../../../examples/basic/_output_bus.v :type: netlistsvg :align: center :module: top """ from os import path import spydrnet as sdn import spydrnet_physical as sdnphy netlist = sdnphy.load_netlist_by_name('basic_hierarchy') top = netlist.top_instance.reference cable0 = next(top.get_cables("wire0")) inst2 = next(top.get_instances("inst_2_0")) sdn.compose(netlist, '_initial_design.v', skip_constraints=True) top.create_feedthrough(inst2, cable0) top.create_unconn_wires() sdn.compose(netlist, '_output_wire.v', skip_constraints=True) netlist = sdnphy.load_netlist_by_name('basic_hierarchy') top = netlist.top_instance.reference bus_in = next(top.get_cables("bus_in")) inst1 = next(top.get_instances("inst_1_0")) cables = top.create_feedthrough(inst1, bus_in) top.create_unconn_wires() sdn.compose(netlist, '_output_bus.v', skip_constraints=True)
24.65
74
0.699797
e079004173a435849592703f1baaf8e8d87ed079
9,131
py
Python
workflows/workflow.py
sunnyfloyd/panderyx
82f03625159833930ff044a43a6619ab710ff159
[ "MIT" ]
null
null
null
workflows/workflow.py
sunnyfloyd/panderyx
82f03625159833930ff044a43a6619ab710ff159
[ "MIT" ]
null
null
null
workflows/workflow.py
sunnyfloyd/panderyx
82f03625159833930ff044a43a6619ab710ff159
[ "MIT" ]
null
null
null
from __future__ import annotations from typing import Optional, Union from tools import tools from exceptions import workflow_exceptions
33.818519
87
0.61461
0eb2577f85f04e68e802521ef8915750223e0174
624
py
Python
tests/wagtail_live/test_apps.py
wagtail/wagtail-live
dd769be089d457cf36db2506520028bc5f506ac3
[ "BSD-3-Clause" ]
22
2021-06-07T20:36:18.000Z
2022-03-29T01:48:58.000Z
tests/wagtail_live/test_apps.py
wagtail/wagtail-live
dd769be089d457cf36db2506520028bc5f506ac3
[ "BSD-3-Clause" ]
73
2021-05-21T16:08:44.000Z
2022-03-20T23:59:59.000Z
tests/wagtail_live/test_apps.py
wagtail/wagtail-live
dd769be089d457cf36db2506520028bc5f506ac3
[ "BSD-3-Clause" ]
11
2021-06-10T10:05:13.000Z
2022-02-12T13:31:34.000Z
from django.apps import apps from django.test import override_settings from wagtail_live.signals import live_page_update
27.130435
77
0.780449
0eb2fde0bae97bffa51893b405703a8d74ef6c29
14,826
py
Python
PLM/options.py
vtta2008/pipelineTool
2431d2fc987e3b31f2a6a63427fee456fa0765a0
[ "Apache-2.0" ]
7
2017-12-22T02:49:58.000Z
2018-05-09T05:29:06.000Z
PLM/options.py
vtta2008/pipelineTool
2431d2fc987e3b31f2a6a63427fee456fa0765a0
[ "Apache-2.0" ]
null
null
null
PLM/options.py
vtta2008/pipelineTool
2431d2fc987e3b31f2a6a63427fee456fa0765a0
[ "Apache-2.0" ]
3
2019-03-11T21:54:52.000Z
2019-11-25T11:23:17.000Z
# -*- coding: utf-8 -*- """ Script Name: Author: Do Trinh/Jimmy - 3D artist. Description: """ # ------------------------------------------------------------------------------------------------------------- """ Import """ import os from PySide2.QtWidgets import (QFrame, QStyle, QAbstractItemView, QSizePolicy, QLineEdit, QPlainTextEdit, QGraphicsItem, QGraphicsView, QGraphicsScene, QRubberBand, QCalendarWidget, ) from PySide2.QtCore import QEvent, QSettings, QSize, Qt, QDateTime from PySide2.QtGui import QColor, QPainter, QFont, QTextCursor SingleSelection = QCalendarWidget.SingleSelection NoSelection = QCalendarWidget.NoSelection SingleLetterDay = QCalendarWidget.SingleLetterDayNames ShortDay = QCalendarWidget.ShortDayNames LongDay = QCalendarWidget.LongDayNames NoHoriHeader = QCalendarWidget.NoHorizontalHeader NoVertHeader = QCalendarWidget.NoVerticalHeader IsoWeekNum = QCalendarWidget.ISOWeekNumbers SelectMode = QCalendarWidget.SelectionMode HoriHeaderFm = QCalendarWidget.HorizontalHeaderFormat VertHeaderFm = QCalendarWidget.VerticalHeaderFormat DayOfWeek = Qt.DayOfWeek Sunday = Qt.Sunday Monday = Qt.Monday Tuesday = Qt.Tuesday Wednesday = Qt.Wednesday Thursday = Qt.Thursday Friday = Qt.Friday Saturday = Qt.Saturday ICONSIZE = 32 ICONBUFFER = -1 BTNTAGSIZE = QSize(87, 20) TAGBTNSIZE = QSize(87-1, 20-1) BTNICONSIZE = QSize(ICONSIZE, ICONSIZE) ICONBTNSIZE = QSize(ICONSIZE+ICONBUFFER, ICONSIZE+ICONBUFFER) DAMG_LOGO_COLOR = QColor(0, 114, 188, 255) # Basic color GlobalColor = Qt.GlobalColor WHITE = QColor(Qt.white) LIGHTGRAY = QColor(Qt.lightGray) GRAY = QColor(Qt.gray) DARKGRAY = QColor(Qt.darkGray) BLACK = QColor(Qt.black) RED = QColor(Qt.red) GREEN = QColor(Qt.green) BLUE = QColor(Qt.blue) DARKRED = QColor(Qt.darkRed) DARKGREEN = QColor(Qt.darkGreen) DARKBLUE = QColor(Qt.darkBlue) CYAN = QColor(Qt.cyan) MAGENTA = QColor(Qt.magenta) YELLOW = QColor(Qt.yellow) DARKCYAN = QColor(Qt.darkCyan) DARKMAGENTA = QColor(Qt.darkMagenta) DARKYELLOW = QColor(Qt.darkYellow) # Dark Palette color Color_BACKGROUND_LIGHT = QColor('#505F69') COLOR_BACKGROUND_NORMAL = QColor('#32414B') COLOR_BACKGROUND_DARK = QColor('#19232D') COLOR_FOREGROUND_LIGHT = QColor('#F0F0F0') COLOR_FOREGROUND_NORMAL = QColor('#AAAAAA') COLOR_FOREGROUND_DARK = QColor('#787878') COLOR_SELECTION_LIGHT = QColor('#148CD2') COLOR_SELECTION_NORMAL = QColor('#1464A0') COLOR_SELECTION_DARK = QColor('#14506E') # Nice color blush = QColor(246, 202, 203, 255) petal = QColor(247, 170, 189, 255) petunia = QColor(231, 62, 151, 255) deep_pink = QColor(229, 2, 120, 255) melon = QColor(241, 118, 110, 255) pomegranate = QColor(178, 27, 32, 255) poppy_red = QColor(236, 51, 39, 255) orange_red = QColor(240, 101, 53, 255) olive = QColor(174, 188, 43, 255) spring = QColor(227, 229, 121, 255) yellow = QColor(255, 240, 29, 255) mango = QColor(254, 209, 26, 255) cantaloupe = QColor(250, 176, 98, 255) tangelo = QColor(247, 151, 47, 255) burnt_orange = QColor(236, 137, 36, 255) bright_orange = QColor(242, 124, 53, 255) moss = QColor(176, 186, 39, 255) sage = QColor(212, 219, 145, 255) apple = QColor(178, 215, 140, 255) grass = QColor(111, 178, 68, 255) forest = QColor(69, 149, 62, 255) peacock = QColor(21, 140, 167, 255) teal = QColor(24, 157, 193, 255) aqua = QColor(153, 214, 218, 255) violet = QColor(55, 52, 144, 255) deep_blue = QColor(15, 86, 163, 255) hydrangea = QColor(150, 191, 229, 255) sky = QColor(139, 210, 244, 255) dusk = QColor(16, 102, 162, 255) midnight = QColor(14, 90, 131, 255) seaside = QColor(87, 154, 188, 255) poolside = QColor(137, 203, 225, 255) eggplant = QColor(86, 5, 79, 255) lilac = QColor(222, 192, 219, 255) chocolate = QColor(87, 43, 3, 255) blackout = QColor(19, 17, 15, 255) stone = QColor(125, 127, 130, 255) gravel = QColor(181, 182, 185, 255) pebble = QColor(217, 212, 206, 255) sand = QColor(185, 172, 151, 255) ignoreARM = Qt.IgnoreAspectRatio scrollAsNeed = Qt.ScrollBarAsNeeded scrollOff = Qt.ScrollBarAlwaysOff scrollOn = Qt.ScrollBarAlwaysOn SiPoMin = QSizePolicy.Minimum # Size policy SiPoMax = QSizePolicy.Maximum SiPoExp = QSizePolicy.Expanding SiPoPre = QSizePolicy.Preferred SiPoIgn = QSizePolicy.Ignored frameStyle = QFrame.Sunken | QFrame.Panel center = Qt.AlignCenter # Alignment right = Qt.AlignRight left = Qt.AlignLeft top = Qt.AlignTop bottom = Qt.AlignBottom hori = Qt.Horizontal vert = Qt.Vertical dockL = Qt.LeftDockWidgetArea # Docking area dockR = Qt.RightDockWidgetArea dockT = Qt.TopDockWidgetArea dockB = Qt.BottomDockWidgetArea dockAll = Qt.AllDockWidgetAreas datetTimeStamp = QDateTime.currentDateTime().toString("hh:mm - dd MMMM yy") # datestamp PRS = dict(password = QLineEdit.Password, center = center , left = left , right = right, spmax = SiPoMax , sppre = SiPoPre, spexp = SiPoExp, spign = SiPoIgn, expanding = QSizePolicy.Expanding, spmin = SiPoMin,) # ------------------------------------------------------------------------------------------------------------- """ Event """ NO_WRAP = QPlainTextEdit.NoWrap NO_FRAME = QPlainTextEdit.NoFrame ELIDE_RIGHT = Qt.ElideRight ELIDE_NONE = Qt.ElideNone # ------------------------------------------------------------------------------------------------------------- """ Window state """ StateNormal = Qt.WindowNoState StateMax = Qt.WindowMaximized StateMin = Qt.WindowMinimized State_Selected = QStyle.State_Selected # ------------------------------------------------------------------------------------------------------------- """ Nodegraph setting variables """ ASPEC_RATIO = Qt.KeepAspectRatio SMOOTH_TRANS = Qt.SmoothTransformation SCROLLBAROFF = Qt.ScrollBarAlwaysOff # Scrollbar SCROLLBARON = Qt.ScrollBarAlwaysOn SCROLLBARNEED = Qt.ScrollBarAsNeeded WORD_WRAP = Qt.TextWordWrap INTERSECT_ITEM_SHAPE = Qt.IntersectsItemShape CONTAIN_ITEM_SHAPE = Qt.ContainsItemShape MATCH_EXACTLY = Qt.MatchExactly DRAG_ONLY = QAbstractItemView.DragOnly # ------------------------------------------------------------------------------------------------------------- """ UI flags """ ITEMENABLE = Qt.ItemIsEnabled ITEMMOVEABLE = QGraphicsItem.ItemIsMovable ITEMSENDGEOCHANGE = QGraphicsItem.ItemSendsGeometryChanges ITEMSCALECHANGE = QGraphicsItem.ItemScaleChange ITEMPOSCHANGE = QGraphicsItem.ItemPositionChange DEVICECACHE = QGraphicsItem.DeviceCoordinateCache SELECTABLE = QGraphicsItem.ItemIsSelectable MOVEABLE = QGraphicsItem.ItemIsMovable FOCUSABLE = QGraphicsItem.ItemIsFocusable PANEL = QGraphicsItem.ItemIsPanel NOINDEX = QGraphicsScene.NoIndex # Scene RUBBER_DRAG = QGraphicsView.RubberBandDrag # Viewer RUBBER_REC = QRubberBand.Rectangle POS_CHANGE = QGraphicsItem.ItemPositionChange NODRAG = QGraphicsView.NoDrag NOFRAME = QGraphicsView.NoFrame ANCHOR_NO = QGraphicsView.NoAnchor ANCHOR_UNDERMICE = QGraphicsView.AnchorUnderMouse ANCHOR_CENTER = QGraphicsView.AnchorViewCenter CACHE_BG = QGraphicsView.CacheBackground UPDATE_VIEWRECT = QGraphicsView.BoundingRectViewportUpdate UPDATE_FULLVIEW = QGraphicsView.FullViewportUpdate UPDATE_SMARTVIEW = QGraphicsView.SmartViewportUpdate UPDATE_BOUNDINGVIEW = QGraphicsView.BoundingRectViewportUpdate UPDATE_MINIMALVIEW = QGraphicsView.MinimalViewportUpdate STAY_ON_TOP = Qt.WindowStaysOnTopHint STRONG_FOCUS = Qt.StrongFocus SPLASHSCREEN = Qt.SplashScreen FRAMELESS = Qt.FramelessWindowHint CUSTOMIZE = Qt.CustomizeWindowHint CLOSEBTN = Qt.WindowCloseButtonHint MINIMIZEBTN = Qt.WindowMinimizeButtonHint AUTO_COLOR = Qt.AutoColor # ------------------------------------------------------------------------------------------------------------- """ Drawing """ ANTIALIAS = QPainter.Antialiasing # Painter ANTIALIAS_TEXT = QPainter.TextAntialiasing ANTIALIAS_HIGH_QUALITY = QPainter.HighQualityAntialiasing SMOOTH_PIXMAP_TRANSFORM = QPainter.SmoothPixmapTransform NON_COSMETIC_PEN = QPainter.NonCosmeticDefaultPen NO_BRUSH = Qt.NoBrush # Brush NO_PEN = Qt.NoPen # Pen ROUND_CAP = Qt.RoundCap ROUND_JOIN = Qt.RoundJoin PATTERN_SOLID = Qt.SolidPattern # Pattern LINE_SOLID = Qt.SolidLine # Line LINE_DASH = Qt.DashLine LINE_DOT = Qt.DotLine LINE_DASH_DOT = Qt.DashDotDotLine TRANSPARENT = Qt.transparent TRANSPARENT_MODE = Qt.TransparentMode # ------------------------------------------------------------------------------------------------------------- """ Meta Object """ QUEUEDCONNECTION = Qt.QueuedConnection # ------------------------------------------------------------------------------------------------------------- """ Keyboard and cursor """ TEXT_BOLD = QFont.Bold TEXT_NORMAL = QFont.Normal MONO_SPACE = QFont.Monospace TEXT_MENEOMIC = Qt.TextShowMnemonic KEY_PRESS = QEvent.KeyPress KEY_RELEASE = QEvent.KeyRelease KEY_ALT = Qt.Key_Alt KEY_DEL = Qt.Key_Delete KEY_TAB = Qt.Key_Tab KEY_SHIFT = Qt.Key_Shift KEY_CTRL = Qt.Key_Control KEY_BACKSPACE = Qt.Key_Backspace KEY_ENTER = Qt.Key_Enter KEY_RETURN = Qt.Key_Return KEY_F = Qt.Key_F KEY_S = Qt.Key_S ALT_MODIFIER = Qt.AltModifier CTRL_MODIFIER = Qt.ControlModifier SHIFT_MODIFIER = Qt.ShiftModifier NO_MODIFIER = Qt.NoModifier CLOSE_HAND_CUSOR = Qt.ClosedHandCursor SIZEF_CURSOR = Qt.SizeFDiagCursor windows = os.name = 'nt' DMK = Qt.AltModifier if windows else CTRL_MODIFIER MOUSE_LEFT = Qt.LeftButton MOUSE_RIGHT = Qt.RightButton MOUSE_MIDDLE = Qt.MiddleButton NO_BUTTON = Qt.NoButton ARROW_NONE = Qt.NoArrow # Cursor CURSOR_ARROW = Qt.ArrowCursor CURSOR_SIZEALL = Qt.SizeAllCursor MOVE_OPERATION = QTextCursor.MoveOperation MOVE_ANCHOR = QTextCursor.MoveMode.MoveAnchor KEEP_ANCHOR = QTextCursor.MoveMode.KeepAnchor ACTION_MOVE = Qt.MoveAction # Action ignoreARM = Qt.IgnoreAspectRatio # ------------------------------------------------------------------------------------------------------------- """ Set number """ RELATIVE_SIZE = Qt.RelativeSize # Size INI = QSettings.IniFormat NATIVE = QSettings.NativeFormat INVALID = QSettings.InvalidFormat SYS_SCOPE = QSettings.SystemScope USER_SCOPE = QSettings.UserScope # ------------------------------------------------------------------------------------------------------------- # Created by Trinh Do on 5/6/2020 - 3:13 AM # 2017 - 2020 DAMGteam. All rights reserved
43.994065
114
0.475651
0eb3ad476194898d48e135372f34d1ee69bc79d8
2,509
py
Python
Crawling/ssafyCrawling.py
Nyapy/FMTG
dcf0a35dbbcd50d5bc861b04ac0db41d27e57b6e
[ "MIT" ]
null
null
null
Crawling/ssafyCrawling.py
Nyapy/FMTG
dcf0a35dbbcd50d5bc861b04ac0db41d27e57b6e
[ "MIT" ]
null
null
null
Crawling/ssafyCrawling.py
Nyapy/FMTG
dcf0a35dbbcd50d5bc861b04ac0db41d27e57b6e
[ "MIT" ]
null
null
null
from selenium import webdriver from selenium.webdriver.chrome.options import Options import sys import time import urllib.request import os sys.stdin = open('idpwd.txt') site = input() id = input() pwd = input() # selenium chromedriver = 'C:\Webdriver\chromedriver.exe' # selenum webdriver chromedirver . driver = webdriver.Chrome(chromedriver) # driver . driver.get(site) driver.find_element_by_name('userId').send_keys(id) driver.find_element_by_name('userPwd').send_keys(pwd) driver.find_element_by_class_name('form-btn').click() driver.set_window_size(1600, 800) driver.find_element_by_xpath("//a[@href='/edu/lectureroom/openlearning/openLearningList.do']/span").click() # driver.find_element_by_id('searchContNm').send_keys('aps') # # driver.find_element_by_xpath("//button[@onclick='fnSearch();']").click() driver.find_elements_by_xpath("//*[contains(text(), '5_B_Java(1)')]")[0].click() driver.find_element_by_xpath("//span[@class='file-name']").click() driver.switch_to.window(driver.window_handles[1]) print(driver.find_elements_by_xpath("//button[@title=' ']")[0].get_attribute('disabled')) # driver.find_elements_by_xpath("//button[@title=' ']")[0].click() # print(driver.find_elements_by_xpath("//button[@title=' ']")[0].get_attribute('disabled')) # url + find # pre = driver.current_url # find = pre.find('/index.html') # url = pre[:find] # src = driver.find_element_by_class_name("background").get_attribute('src') # print(src) ## # for i in driver.find_elements_by_xpath("//button[@title=' ']"): # print(i) cnt = 1 # url = driver.find_elements_by_class_name("background")[-1].get_attribute('src') # print(url) # urllib.request.urlretrieve(url, '123.jpg') # os.system("curl " + url + " > test.jpg") time.sleep(2) driver.get_screenshot_as_file("hi.png") # for i in driver.find_elements_by_class_name("background"): # time.sleep(2) # print(i.get_attribute('style')) # i.screenshot(str(cnt)+'.png') # cnt += 1 while 1: time.sleep(0.4) driver.save_screenshot('APS/C/'+str(cnt)+'.png') # print(driver.find_element_by_class_name("background").get_attribute('src')) # driver.find_element_by_class_name("background").screenshot(str(cnt)+'.png') driver.find_elements_by_xpath("//button[@title=' ']")[0].click() cnt += 1 if driver.find_elements_by_xpath("//button[@title=' ']")[0].get_attribute('disabled') == 'disabled': break
32.166667
109
0.719012
0eb4432b0091105498b6cde85c1c9de8fc2676cc
1,433
py
Python
100days/day95/StringIO_demo.py
chainren/python-learn
5e48e96c4bb212806b9ae0954fdb368abdcf9ba3
[ "Apache-2.0" ]
null
null
null
100days/day95/StringIO_demo.py
chainren/python-learn
5e48e96c4bb212806b9ae0954fdb368abdcf9ba3
[ "Apache-2.0" ]
16
2020-02-12T03:09:30.000Z
2022-03-12T00:08:59.000Z
100days/day95/StringIO_demo.py
chainren/python-learn
5e48e96c4bb212806b9ae0954fdb368abdcf9ba3
[ "Apache-2.0" ]
null
null
null
from io import StringIO # StringIO f = StringIO() f.write('Python-100') str = f.getvalue() # print(':%s' %str) f.write('\n') # f.write('100') f.close() # f1 = StringIO('Python-100' + '\n' + '100') # print(f1.read()) f1.close() # outputData() # dataStr dataStr = outputData() # 1. outputData() dataIO = StringIO(dataStr) # outputData() # dataStr dataStr = outputData() # 1. outputData() dataIO = StringIO(dataStr) # 1.1 StringIO print('1.1:\n%s' %dataIO.getvalue()) # 1.2 print('1.2:') for data in dataIO.readlines(): print(data.strip('\n')) # # 1.2 print('1.2:') for data in dataIO.readlines(): print(data.strip('\n')) # # 1.3 # (32) print(':%d' %dataIO.tell()) # dataIO.seek(0) print('1.3:') for data in dataIO: print(data.strip('\n'))
18.61039
47
0.673412
0eb4945ca1e15b4e7d0b451aa87077b0cebf76c6
10,595
py
Python
src/hub/dataload/sources/drugcentral/drugcentral_upload.py
veleritas/mychem.info
bb22357d4cbbc3c4865da224bf998f2cbc59f8f2
[ "Apache-2.0" ]
1
2021-05-09T04:51:28.000Z
2021-05-09T04:51:28.000Z
src/hub/dataload/sources/drugcentral/drugcentral_upload.py
veleritas/mychem.info
bb22357d4cbbc3c4865da224bf998f2cbc59f8f2
[ "Apache-2.0" ]
null
null
null
src/hub/dataload/sources/drugcentral/drugcentral_upload.py
veleritas/mychem.info
bb22357d4cbbc3c4865da224bf998f2cbc59f8f2
[ "Apache-2.0" ]
null
null
null
import biothings.hub.dataload.uploader as uploader
41.54902
65
0.224823
0eb4f1bf9aa917694ffc04ea836799d3bd9b4710
2,751
py
Python
tests/test_cli.py
Nate1729/FinPack
d76fd5e6538298d5596d5b0f7d3be2bc6520c431
[ "Apache-2.0" ]
1
2022-01-28T20:05:22.000Z
2022-01-28T20:05:22.000Z
tests/test_cli.py
Nate1729/FinPack
d76fd5e6538298d5596d5b0f7d3be2bc6520c431
[ "Apache-2.0" ]
30
2021-11-22T19:07:54.000Z
2021-12-18T03:00:47.000Z
tests/test_cli.py
Nate1729/FinPack
d76fd5e6538298d5596d5b0f7d3be2bc6520c431
[ "Apache-2.0" ]
2
2021-12-13T20:27:52.000Z
2021-12-17T18:39:40.000Z
"""Contains tests for finpack/core/cli.py """ __copyright__ = "Copyright (C) 2021 Matt Ferreira" import os import unittest from importlib import metadata from docopt import docopt from finpack.core import cli
25.238532
62
0.623773
0eb6190157c1946b37b5fd1be18f551d0e559832
612
py
Python
python/Patterns/inheritance/main.py
zinderud/ysa
e34d3f4c7afab3976d86f5d27edfcd273414e496
[ "Apache-2.0" ]
null
null
null
python/Patterns/inheritance/main.py
zinderud/ysa
e34d3f4c7afab3976d86f5d27edfcd273414e496
[ "Apache-2.0" ]
1
2017-12-27T10:09:22.000Z
2017-12-27T10:22:47.000Z
python/Patterns/inheritance/main.py
zinderud/ysa
e34d3f4c7afab3976d86f5d27edfcd273414e496
[ "Apache-2.0" ]
null
null
null
enemy = Yaratik() enemy.move_left() # ejderha also includes all functions from parent class (yaratik) ejderha = Ejderha() ejderha.move_left() ejderha.Ates_puskurtme() # Zombie is called the (child class), inherits from Yaratik (parent class) zombie = Zombie() zombie.move_right() zombie.Isirmak()
18
74
0.679739
0eb71b68b065b14b8eebff52fa3bbffc15201b7a
1,527
py
Python
clustering/graph_utils.py
perathambkk/ml-techniques
5d6fd122322342c0b47dc65d09c4425fd73f2ea9
[ "MIT" ]
null
null
null
clustering/graph_utils.py
perathambkk/ml-techniques
5d6fd122322342c0b47dc65d09c4425fd73f2ea9
[ "MIT" ]
null
null
null
clustering/graph_utils.py
perathambkk/ml-techniques
5d6fd122322342c0b47dc65d09c4425fd73f2ea9
[ "MIT" ]
null
null
null
""" Author: Peratham Wiriyathammabhum """ import numpy as np import pandas as pd from sklearn.neighbors import NearestNeighbors def affinity_graph(X): ''' This function returns a numpy array. ''' ni, nd = X.shape A = np.zeros((ni, ni)) for i in range(ni): for j in range(i+1, ni): dist = ((X[i] - X[j])**2).sum() # compute L2 distance A[i][j] = dist A[j][i] = dist # by symmetry return A def knn_graph(X, knn=4): ''' This function returns a numpy array. ''' ni, nd = X.shape nbrs = NearestNeighbors(n_neighbors=(knn+1), algorithm='ball_tree').fit(X) distances, indices = nbrs.kneighbors(X) A = np.zeros((ni, ni)) for dist, ind in zip(distances, indices): i0 = ind[0] for i in range(1,knn+1): d = dist[i] A[i0, i] = d A[i, i0] = d # by symmetry return A def sparse_affinity_graph(X): ''' TODO: This function returns a numpy sparse matrix. ''' ni, nd = X.shape A = np.zeros((ni, ni)) for i in range(ni): for j in range(i+1, ni): dist = ((X[i] - X[j])**2).sum() # compute L2 distance A[i][j] = dist A[j][i] = dist # by symmetry return A def laplacian_graph(X, mode='affinity', knn=3, eta=0.01, sigma=2.5): ''' The unnormalized graph Laplacian, L = D W. ''' if mode == 'affinity': W = affinity_graph(X) W[abs(W) > eta] = 0 elif mode == 'nearestneighbor': W = knn_graph(X, knn=knn) elif mode == 'gaussian': W = affinity_graph(X) bandwidth = 2.0*(sigma**2) W = np.exp(W) / bandwidth else: pass D = np.diag(W.sum(axis=1)) L = D - W return L
21.814286
75
0.614276
0eb8ddc2c0219670903c4425de4ca4b63a33f316
10,124
py
Python
recipe_engine/internal/commands/__init__.py
Acidburn0zzz/luci
d8993f4684839b58f5f966dd6273d1d8fd001eae
[ "Apache-2.0" ]
1
2021-04-24T04:03:01.000Z
2021-04-24T04:03:01.000Z
recipe_engine/internal/commands/__init__.py
Acidburn0zzz/luci
d8993f4684839b58f5f966dd6273d1d8fd001eae
[ "Apache-2.0" ]
null
null
null
recipe_engine/internal/commands/__init__.py
Acidburn0zzz/luci
d8993f4684839b58f5f966dd6273d1d8fd001eae
[ "Apache-2.0" ]
null
null
null
# Copyright 2019 The LUCI Authors. All rights reserved. # Use of this source code is governed under the Apache License, Version 2.0 # that can be found in the LICENSE file. """This package houses all subcommands for the recipe engine. See implementation_details.md for the expectations of the modules in this directory. """ import argparse import errno import logging import os import pkgutil import sys if sys.version_info >= (3, 5): # we're running python > 3.5 OS_WALK = os.walk else: # From vpython from scandir import walk as OS_WALK # pylint: disable=wrong-import-position from .. import simple_cfg from ..recipe_deps import RecipeDeps from ..recipe_module_importer import RecipeModuleImporter LOG = logging.getLogger(__name__) # This incantation finds all loadable submodules of ourself. The # `prefix=__name__` bit is so that these modules get loaded with the correct # import names, i.e. # # recipe_engine.internal.commands.<submodule> # # If omitted, then these submodules can get double loaded as both: # # <submodule> AND # recipe_engine.internal.commands.<submodule> # # Which can both interfere with the global python module namespace, and lead to # strange errors when doing type assertions (since all data in these modules # will be loaded under two different names; classes will fail isinstance checks # even though they are "the same"). _COMMANDS = [ loader.find_module(module_name).load_module(module_name) for (loader, module_name, _) in pkgutil.walk_packages( __path__, prefix=__name__+'.') if '.' not in module_name[len(__name__)+1:] ] # Order all commands by an optional __cmd_priority__ field, and then by module # name. _COMMANDS.sort( key=lambda mod: ( not hasattr(mod, '__cmd_priority__'), # modules defining priority first getattr(mod, '__cmd_priority__', None), # actual priority mod.__name__ # name )) # Now actually set these commands on ourself so that 'mock' works correctly. # # This is needed to allow some tests (though it may be worth adjusting these # tests later to not need this. Just delete this function and see which tests # fail to find the dependencies on this behavior). _patch_our_attrs() def _check_recipes_cfg_consistency(recipe_deps): """Checks all recipe.cfg files for the loaded recipe_deps and logs inconsistent dependencies. Args: recipe_deps (RecipeDeps) - The loaded+fetched recipe deps for the current run. """ actual = recipe_deps.main_repo.simple_cfg.deps # For every repo we loaded for repo_name in actual: required_deps = recipe_deps.repos[repo_name].simple_cfg.deps for req_repo_name, req_spec in required_deps.iteritems(): # If this depends on something we didn't load, log an error. if req_repo_name not in actual: LOG.error( '%r depends on %r, but your recipes.cfg is missing an ' 'entry for this.', repo_name, req_repo_name) continue actual_spec = actual[req_repo_name] if req_spec.revision == actual_spec.revision: # They match, it's all good. continue LOG.warn( 'recipes.cfg depends on %r @ %s, but %r depends on version %s.', req_repo_name, actual_spec.revision, repo_name, req_spec.revision) def _cleanup_pyc(recipe_deps): """Removes any .pyc files from the recipes/recipe_module directories. Args: * recipe_deps (RecipeDeps) - The loaded recipe dependencies. """ for repo in recipe_deps.repos.itervalues(): for to_walk in (repo.recipes_dir, repo.modules_dir): for root, _dirs, files in OS_WALK(to_walk): for fname in files: if not fname.endswith('.pyc'): continue try: to_clean = os.path.join(root, fname) LOG.info('cleaning %r', to_clean) os.unlink(to_clean) except OSError as ex: # If multiple things are cleaning pyc's at the same time this can # race. Fortunately we only care that SOMETHING deleted the pyc :) if ex.errno != errno.ENOENT: raise def parse_and_run(): """Parses the command line and runs the chosen subcommand. Returns the command's return value (either int or None, suitable as input to `os._exit`). """ parser = argparse.ArgumentParser( description='Interact with the recipe system.') _add_common_args(parser) subp = parser.add_subparsers(dest='command') for module in _COMMANDS: description = module.__doc__ helplines = [] for line in description.splitlines(): line = line.strip() if not line: break helplines.append(line) module.add_arguments(subp.add_parser( module.__name__.split('.')[-1], # use module's short name formatter_class=argparse.RawDescriptionHelpFormatter, help=' '.join(helplines), description=description, )) args = parser.parse_args() _common_post_process(args) args.postprocess_func(parser.error, args) return args.func(args)
35.152778
80
0.697452
0eb8efd29824103fb230c6103a6e3a8b1b30a534
7,295
py
Python
openfl/pipelines/stc_pipeline.py
sarthakpati/openfl
8edebfd565d94f709a7d7f06d9ee38a7975c066e
[ "Apache-2.0" ]
null
null
null
openfl/pipelines/stc_pipeline.py
sarthakpati/openfl
8edebfd565d94f709a7d7f06d9ee38a7975c066e
[ "Apache-2.0" ]
null
null
null
openfl/pipelines/stc_pipeline.py
sarthakpati/openfl
8edebfd565d94f709a7d7f06d9ee38a7975c066e
[ "Apache-2.0" ]
null
null
null
# Copyright (C) 2020-2021 Intel Corporation # SPDX-License-Identifier: Apache-2.0 """STCPipelinemodule.""" import numpy as np import gzip as gz from .pipeline import TransformationPipeline, Transformer
33.159091
99
0.622207
0eb9c920aa1f94bcf5b75523167a5791a71d6de8
1,150
py
Python
modle/__init__.py
Rex0519/NessusToReport
047dd4a2f749addab3991b0ebc8ab609140c32a7
[ "Apache-2.0" ]
244
2020-06-27T12:07:52.000Z
2022-03-30T02:36:27.000Z
modle/__init__.py
Rex0519/NessusToReport
047dd4a2f749addab3991b0ebc8ab609140c32a7
[ "Apache-2.0" ]
23
2021-05-20T07:38:55.000Z
2022-03-13T14:13:01.000Z
modle/__init__.py
Rex0519/NessusToReport
047dd4a2f749addab3991b0ebc8ab609140c32a7
[ "Apache-2.0" ]
74
2020-06-27T12:07:53.000Z
2022-03-11T19:07:45.000Z
#!/usr/bin/env python3 # -*- coding:utf-8 -*- # ------------------------------------------------------------ # File: __init__.py.py # Created Date: 2020/6/24 # Created Time: 0:12 # Author: Hypdncy # Author Mail: [email protected] # Copyright (c) 2020 Hypdncy # ------------------------------------------------------------ # .::::. # .::::::::. # ::::::::::: # ..:::::::::::' # '::::::::::::' # .:::::::::: # '::::::::::::::.. # ..::::::::::::. # ``:::::::::::::::: # ::::``:::::::::' .:::. # ::::' ':::::' .::::::::. # .::::' :::: .:::::::'::::. # .:::' ::::: .:::::::::' ':::::. # .::' :::::.:::::::::' ':::::. # .::' ::::::::::::::' ``::::. # ...::: ::::::::::::' ``::. # ````':. ':::::::::' ::::.. # '.:::::' ':'````.. # ------------------------------------------------------------
39.655172
62
0.117391
0ebc4327dea5e082563be3e589c1e4f6b395a97a
7,146
py
Python
tests/component/test_grid_mixin.py
csdms/pymt
188222d7858cd3e8eb15564e56d9b7f0cb43cae5
[ "MIT" ]
38
2017-06-30T17:10:53.000Z
2022-01-05T07:38:03.000Z
tests/component/test_grid_mixin.py
csdms/pymt
188222d7858cd3e8eb15564e56d9b7f0cb43cae5
[ "MIT" ]
96
2017-04-04T18:52:41.000Z
2021-11-01T21:30:48.000Z
tests/component/test_grid_mixin.py
csdms/pymt
188222d7858cd3e8eb15564e56d9b7f0cb43cae5
[ "MIT" ]
15
2017-05-23T15:40:16.000Z
2021-06-14T21:30:28.000Z
import numpy as np import pytest from pytest import approx from pymt.component.grid import GridMixIn
27.805447
84
0.558354
0ebe32fa6550f0c6be308f3edf45681f0583afc5
730
py
Python
scripts/compare.py
SnoozeTime/nes
4d60562c59e175485eb3dff043c0c78473034cdb
[ "Unlicense" ]
1
2022-01-07T02:00:36.000Z
2022-01-07T02:00:36.000Z
scripts/compare.py
SnoozeTime/nes
4d60562c59e175485eb3dff043c0c78473034cdb
[ "Unlicense" ]
6
2020-12-12T03:21:55.000Z
2022-02-18T11:22:28.000Z
scripts/compare.py
SnoozeTime/nes
4d60562c59e175485eb3dff043c0c78473034cdb
[ "Unlicense" ]
1
2018-12-02T20:42:10.000Z
2018-12-02T20:42:10.000Z
import sys if __name__ == "__main__": mylog = sys.argv[1] correctlog = sys.argv[2] mylog_sp = load_log_sp(mylog) correctlog_sp = load_log_sp(correctlog) for (i, ((nb1, sp1), (nb2, sp2))) in enumerate(zip(mylog_sp, correctlog_sp)): print('{} {} - {} vs {}'.format( nb1, nb2, sp1, sp2)) if sp1.lower() != sp2.lower() or int(nb1.lower(),16) != int(nb2.lower(), 16): break
30.416667
85
0.545205
0ebf6e6f4a1667f2d0b5238c117fa44dfca6f7c4
10,203
py
Python
tercer_modelo.py
nahuelalmeira/deepLearning
f1fcd06f5735c8be9272b0c8392b1ae467c08582
[ "MIT" ]
null
null
null
tercer_modelo.py
nahuelalmeira/deepLearning
f1fcd06f5735c8be9272b0c8392b1ae467c08582
[ "MIT" ]
null
null
null
tercer_modelo.py
nahuelalmeira/deepLearning
f1fcd06f5735c8be9272b0c8392b1ae467c08582
[ "MIT" ]
null
null
null
"""Exercise 1 Usage: $ CUDA_VISIBLE_DEVICES=2 python practico_1_train_petfinder.py --dataset_dir ../ --epochs 30 --dropout 0.1 0.1 --hidden_layer_sizes 200 100 To know which GPU to use, you can check it with the command $ nvidia-smi """ import argparse import os import mlflow import pickle import numpy as np import pandas as pd import tensorflow as tf from sklearn.model_selection import train_test_split from tensorflow.keras import layers, models import warnings warnings.filterwarnings("ignore") from auxiliary import process_features, load_dataset, build_columns, log_dir_name TARGET_COL = 'AdoptionSpeed' ########################################################################################################### print('All operations completed') if __name__ == '__main__': main()
45.346667
138
0.51181
0ebfda6d11cf85e7a67d60d7c46e294592497198
7,576
py
Python
catpy/applications/export.py
catmaid/catpy
481d87591a6dfaedef2767dcddcbed7185ecc8b8
[ "MIT" ]
5
2018-04-24T15:45:31.000Z
2021-06-18T17:38:07.000Z
catpy/applications/export.py
catmaid/catpy
481d87591a6dfaedef2767dcddcbed7185ecc8b8
[ "MIT" ]
35
2017-05-12T21:49:54.000Z
2022-03-12T00:47:09.000Z
catpy/applications/export.py
catmaid/catpy
481d87591a6dfaedef2767dcddcbed7185ecc8b8
[ "MIT" ]
4
2017-08-24T12:15:41.000Z
2019-10-13T01:05:34.000Z
# -*- coding: utf-8 -*- from __future__ import absolute_import from pkg_resources import parse_version from warnings import warn from copy import deepcopy import networkx as nx from networkx.readwrite import json_graph from catpy.applications.base import CatmaidClientApplication NX_VERSION_INFO = parse_version(nx.__version__)._key[1] err_msg = ( "Tried to treat the edge's source/target fields as indices into the list of nodes, but failed. " "See issue #26 [1]. " "Has CATMAID upgraded to networkx 2.x? [2]\n\n" "[1]: https://github.com/catmaid/catpy/issues/26\n" "[2]: https://github.com/catmaid/CATMAID/blob/master/django/requirements.txt" ) def convert_nodelink_data(jso): """NetworkX serialises graphs differently in v1.x and v2.x. This converts v1-style data (as emitted by CATMAID) to v2-style data. See issue #26 https://github.com/catmaid/catpy/issues/26 Parameters ---------- jso : dict Returns ------- dict """ if NX_VERSION_INFO < (2, 0): warn( "You are converting networkx v1-style JSON (emitted by CATMAID) to v2-style JSON," " but you are using networkx v1" ) out = deepcopy(jso) for edge in out["links"]: for label in ["source", "target"]: try: edge[label] = out["nodes"][edge[label]]["id"] except (KeyError, IndexError): raise RuntimeError(err_msg) return out
31.566667
126
0.551082
0ec1afd2facbda8f3febe8ca1dc7c71fb6558f04
1,993
py
Python
packages/watchmen-data-kernel/src/watchmen_data_kernel/meta/external_writer_service.py
Indexical-Metrics-Measure-Advisory/watchmen
c54ec54d9f91034a38e51fd339ba66453d2c7a6d
[ "MIT" ]
null
null
null
packages/watchmen-data-kernel/src/watchmen_data_kernel/meta/external_writer_service.py
Indexical-Metrics-Measure-Advisory/watchmen
c54ec54d9f91034a38e51fd339ba66453d2c7a6d
[ "MIT" ]
null
null
null
packages/watchmen-data-kernel/src/watchmen_data_kernel/meta/external_writer_service.py
Indexical-Metrics-Measure-Advisory/watchmen
c54ec54d9f91034a38e51fd339ba66453d2c7a6d
[ "MIT" ]
null
null
null
from typing import Optional from watchmen_auth import PrincipalService from watchmen_data_kernel.cache import CacheService from watchmen_data_kernel.common import DataKernelException from watchmen_data_kernel.external_writer import find_external_writer_create, register_external_writer_creator from watchmen_meta.common import ask_meta_storage, ask_snowflake_generator from watchmen_meta.system import ExternalWriterService as ExternalWriterStorageService from watchmen_model.common import ExternalWriterId from watchmen_model.system import ExternalWriter
41.520833
110
0.831912
0ec2342f96bb22e61801a222fde8647beb3203c5
304
py
Python
udemy-python/mediaponderada.py
AlbertoAlfredo/exercicios-cursos
792096ad1f853188adec8fc3e5c629742c8dd7ab
[ "MIT" ]
1
2017-08-27T00:57:20.000Z
2017-08-27T00:57:20.000Z
udemy-python/mediaponderada.py
AlbertoAlfredo/exercicios-cursos
792096ad1f853188adec8fc3e5c629742c8dd7ab
[ "MIT" ]
2
2020-09-09T04:22:06.000Z
2020-12-24T16:25:36.000Z
udemy-python/mediaponderada.py
AlbertoAlfredo/exercicios-cursos
792096ad1f853188adec8fc3e5c629742c8dd7ab
[ "MIT" ]
null
null
null
nota1 = float(input('Digite a nota da primeira nota ')) peso1 = float(input('Digite o peso da primeira nota ')) nota2 = float(input('Digite a nota da seugundo nota ')) peso2 = float(input('Digite o peso da segundo nota ')) media = (nota1/peso1+nota2/peso2)/2 print('A mdia das duas notas :', media)
30.4
55
0.703947
0ec2983c9be55e068e1ac3a8da9a2e78b097ece9
882
py
Python
scrywarden/module.py
chasebrewsky/scrywarden
c6a5a81d14016ca58625df68594ef52dd328a0dd
[ "MIT" ]
1
2020-12-13T00:49:51.000Z
2020-12-13T00:49:51.000Z
scrywarden/module.py
chasebrewsky/scrywarden
c6a5a81d14016ca58625df68594ef52dd328a0dd
[ "MIT" ]
null
null
null
scrywarden/module.py
chasebrewsky/scrywarden
c6a5a81d14016ca58625df68594ef52dd328a0dd
[ "MIT" ]
null
null
null
from importlib import import_module from typing import Any def import_string(path: str) -> Any: """Imports a dotted path name and returns the class/attribute. Parameters ---------- path: str Dotted module path to retrieve. Returns ------- Class/attribute at the given import path. Raises ------ ImportError If the path does not exist. """ try: module_path, class_name = path.rsplit('.', 1) except ValueError as error: raise ImportError( f"{path} does not look like a module path", ) from error module = import_module(module_path) try: return getattr(module, class_name) except AttributeError as error: raise ImportError( f"Module '{module_path}' does not define a '{class_name}' " "attribute/class", ) from error
24.5
71
0.603175
0ec3610585ba69b4e61119ece94d8d89e44e43cc
27,448
py
Python
examples/oldexamples/sample_program.py
learningequality/klorimin
c569cd4048ac670bc55a83f4fdda0b818c7f626e
[ "MIT" ]
null
null
null
examples/oldexamples/sample_program.py
learningequality/klorimin
c569cd4048ac670bc55a83f4fdda0b818c7f626e
[ "MIT" ]
null
null
null
examples/oldexamples/sample_program.py
learningequality/klorimin
c569cd4048ac670bc55a83f4fdda0b818c7f626e
[ "MIT" ]
null
null
null
#!/usr/bin/env python import json import os import re from enum import Enum from os.path import join from le_utils.constants import content_kinds from le_utils.constants import exercises from le_utils.constants import file_formats from le_utils.constants import licenses from ricecooker.chefs import SushiChef from ricecooker.classes import files from ricecooker.classes import nodes from ricecooker.classes import questions from ricecooker.classes.licenses import get_license from ricecooker.exceptions import InvalidFormatException from ricecooker.exceptions import raise_for_invalid_channel from ricecooker.exceptions import UnknownContentKindError from ricecooker.exceptions import UnknownFileTypeError from ricecooker.exceptions import UnknownQuestionTypeError # CHANNEL SETTINGS SOURCE_DOMAIN = "<yourdomain.org>" # content provider's domain SOURCE_ID = "<yourid>" # an alphanumeric channel ID CHANNEL_TITLE = "Testing Ricecooker Channel" # a humand-readbale title CHANNEL_LANGUAGE = "en" # language code of channel # LOCAL DIRS EXAMPLES_DIR = os.path.dirname(os.path.realpath(__file__)) DATA_DIR = os.path.join(EXAMPLES_DIR, "data") CONTENT_DIR = os.path.join(EXAMPLES_DIR, "content") # # A utility function to manage absolute paths that allows us to refer to files # in the CONTENT_DIR (subdirectory `content/' in current directory) using content:// def get_abspath(path, content_dir=CONTENT_DIR): """ Replaces `content://` with absolute path of `content_dir`. By default looks for content in subdirectory `content` in current directory. """ if path: file = re.search("content://(.+)", path) if file: return os.path.join(content_dir, file.group(1)) return path FILE_TYPE_MAPPING = { content_kinds.AUDIO: { file_formats.MP3: FileTypes.AUDIO_FILE, file_formats.PNG: FileTypes.THUMBNAIL, file_formats.JPG: FileTypes.THUMBNAIL, file_formats.JPEG: FileTypes.THUMBNAIL, }, content_kinds.DOCUMENT: { file_formats.PDF: FileTypes.DOCUMENT_FILE, file_formats.PNG: FileTypes.THUMBNAIL, file_formats.JPG: FileTypes.THUMBNAIL, file_formats.JPEG: FileTypes.THUMBNAIL, }, content_kinds.HTML5: { file_formats.HTML5: FileTypes.HTML_ZIP_FILE, file_formats.PNG: FileTypes.THUMBNAIL, file_formats.JPG: FileTypes.THUMBNAIL, file_formats.JPEG: FileTypes.THUMBNAIL, }, content_kinds.H5P: { file_formats.H5P: FileTypes.H5P_FILE, file_formats.PNG: FileTypes.THUMBNAIL, file_formats.JPG: FileTypes.THUMBNAIL, file_formats.JPEG: FileTypes.THUMBNAIL, }, content_kinds.VIDEO: { file_formats.MP4: FileTypes.VIDEO_FILE, file_formats.VTT: FileTypes.SUBTITLE_FILE, file_formats.PNG: FileTypes.THUMBNAIL, file_formats.JPG: FileTypes.THUMBNAIL, file_formats.JPEG: FileTypes.THUMBNAIL, }, content_kinds.EXERCISE: { file_formats.PNG: FileTypes.THUMBNAIL, file_formats.JPG: FileTypes.THUMBNAIL, file_formats.JPEG: FileTypes.THUMBNAIL, }, } def guess_file_type(kind, filepath=None, youtube_id=None, web_url=None, encoding=None): """guess_file_class: determines what file the content is Args: filepath (str): filepath of file to check Returns: string indicating file's class """ if youtube_id: return FileTypes.YOUTUBE_VIDEO_FILE elif web_url: return FileTypes.WEB_VIDEO_FILE elif encoding: return FileTypes.BASE64_FILE else: ext = os.path.splitext(filepath)[1][1:].lower() if kind in FILE_TYPE_MAPPING and ext in FILE_TYPE_MAPPING[kind]: return FILE_TYPE_MAPPING[kind][ext] return None def guess_content_kind(path=None, web_video_data=None, questions=None): """guess_content_kind: determines what kind the content is Args: files (str or list): files associated with content Returns: string indicating node's kind """ # If there are any questions, return exercise if questions and len(questions) > 0: return content_kinds.EXERCISE # See if any files match a content kind if path: ext = os.path.splitext(path)[1][1:].lower() if ext in content_kinds.MAPPING: return content_kinds.MAPPING[ext] raise InvalidFormatException( "Invalid file type: Allowed formats are {0}".format( [key for key, value in content_kinds.MAPPING.items()] ) ) elif web_video_data: return content_kinds.VIDEO else: return content_kinds.TOPIC # LOAD sample_tree.json (as dict) with open(join(DATA_DIR, "sample_tree.json"), "r") as json_file: SAMPLE_TREE = json.load(json_file) # LOAD JSON DATA (as string) FOR PERSEUS QUESTIONS SAMPLE_PERSEUS_1_JSON = open(join(DATA_DIR, "sample_perseus01.json"), "r").read() # SAMPLE_PERSEUS_2_JSON = open(join(DATA_DIR,'sample_perseus02.json'),'r').read() # ADD EXERCISES EXERCISES_NODES = [ { "title": "Rice Cookers", "id": "d98752", "description": "Start cooking rice today!", "children": [ { "title": "Rice Chef", "id": "6cafe2", "author": "Revision 3", "description": "Become a master rice cooker", "file": "https://ia600209.us.archive.org/27/items/RiceChef/Rice Chef.mp4", "license": licenses.CC_BY_NC_SA, "copyright_holder": "Learning Equality", "files": [ { "path": "https://ia600209.us.archive.org/27/items/RiceChef/Rice Chef.mp4" }, { "encoding": "data:image/png;base64,iVBORw0KGgoAAAANSUhEUgAAABAAAAAQCAMAAAAoLQ9TAAAABGdBTUEAALGPC/xhBQAAAAFzUkdCAK7OHOkAAAAgY0hSTQAAeiYAAICEAAD6AAAAgOgAAHUwAADqYAAAOpgAABdwnLpRPAAAAmFQTFRF////wN/2I0FiNFFuAAAAxdvsN1RxV3KMnrPFFi9PAB1CVG+KXHaQI0NjttLrEjVchIF4AyNGZXB5V087UUw/EzBMpqWeb2thbmpgpqOceXVsERgfTWeADg8QCAEApKGZBAYIop+XCQkIhZ+2T2mEg5mtnK/AobPDkKO2YXqTAAAAJkBetMraZH2VprjIz9zm4enw7/T47fP3wc7ae5GnAAAAN1BsSmSApLfI1ODq2OHp5Orv8PL09vb38fb5wM/bbISbrL/PfZSpxNPgzdnj2+Pr5evw6+/z6e3w3ePp2OPsma2/ABM5Q197ABk4jKG1yNfjytfh1uDo3eXs4unv1t/nztrjqbzMTmmEXneRES1Ji6CzxtXixdPfztrk1N/n1+Dp1d/oz9vlxdPeq73NVG+KYnyUAAAddIuhwtPhvMzaxtTgytfiy9jjwtHewtHenbDCHT1fS2eCRV52qr7PvM3cucrYv87cv8/cvMzavc3bucvacoyl////ByE8WnKKscXWv9Hguszbu8zbvc7dtcnaiJqrcHZ4f4SHEh0nEitFTWZ+hJqumrDDm7HDj6W5dI2lYGJfmZeQl5SNAAAADRciAAATHjdSOVNsPlhyLklmKCYjW1lUlpOLlZKLFSAqWXSOBQAADA0NAAAAHh0bWlhSk5CIk5CIBAYJDRQbERcdDBAUBgkMAAAEDg4NAAAAHBsZWFZQkY6GAAAAAAAABQUEHBsZAAAAGxoYVlROko+GBAQDZ2RdAAAAGhkYcW9oAgICAAAAExMSDQwLjouDjYuDioiAiIV9hoN7VlRO////Z2DcYwAAAMR0Uk5TAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAACRKrJyrZlBQECaNXCsKaqypMGAUDcu7Gpn5mf03gDo8+4saiipKq3xRMBH83Eu7OsqbG61DkDMdbFvrizsbK3wNs9Ax/VysS/vLq/zNwfArDhxMfExMXE3pMCMe7byMjIzd33ZgYGQtnz6+zooeJXBQMFD1yHejZ1+l8FBgEELlOR+GgFCQ0SGxoBGFKg+m0BBwEMR6v+hAEDM6nRASWURVuYQQ4AAAABYktHRACIBR1IAAAACXBIWXMAAAjLAAAIywGEuOmJAAABCklEQVQY02NgUGZUUVVT19DUYtBmYmZhYdBh1dXTNzA0MjYxZTFjAwqwm1tYWlnb2NrZO3A4cgIFGJycXVzd3D08vbx9uHyBAn7+AYFBwSEhoWHhEdyRQIGo6JjYuPiExKTklFSeNKBAekZmVnZObk5efkEhbxFQgK+4pLSsvKKyqrqGoZZfgIVBsK6+obGpuaW1rV2oQ1hEgKFTtKu7p7evf8LEI5PEJotLMEyZyjJt+oyZsxhmzzk6V3KeFIO01vwFMrJyCxctXrL02DL55QwsClorVq5avWbtuvUbNh7fpMjAwsKyWWvLFJatStu279h5YhdIAAJ2s+zZu+/kfoQAy4HNLAcPHQYA5YtSi+k2/WkAAAAldEVYdGRhdGU6Y3JlYXRlADIwMTMtMTAtMDRUMTk6Mzk6MjEtMDQ6MDAwU1uYAAAAJXRFWHRkYXRlOm1vZGlmeQAyMDEzLTEwLTA0VDE5OjM5OjIxLTA0OjAwQQ7jJAAAABl0RVh0U29mdHdhcmUAd3d3Lmlua3NjYXBlLm9yZ5vuPBoAAAAASUVORK5CYII=" }, ], }, { "title": "Rice Exercise", "id": "6cafe3", "description": "Test how well you know your rice", "license": licenses.CC_BY_NC_SA, "copyright_holder": "Learning Equality", "mastery_model": exercises.DO_ALL, "files": [ { "path": "http://www.publicdomainpictures.net/pictures/110000/nahled/bowl-of-rice.jpg" } ], "questions": [ { "id": "eeeee", "question": "Which rice is your favorite? \\_\\_\\_ ![](data:image/png;base64,iVBORw0KGgoAAAANSUhEUgAAABAAAAAQCAMAAAAoLQ9TAAAABGdBTUEAALGPC/xhBQAAAAFzUkdCAK7OHOkAAAAgY0hSTQAAeiYAAICEAAD6AAAAgOgAAHUwAADqYAAAOpgAABdwnLpRPAAAAmFQTFRF////wN/2I0FiNFFuAAAAxdvsN1RxV3KMnrPFFi9PAB1CVG+KXHaQI0NjttLrEjVchIF4AyNGZXB5V087UUw/EzBMpqWeb2thbmpgpqOceXVsERgfTWeADg8QCAEApKGZBAYIop+XCQkIhZ+2T2mEg5mtnK/AobPDkKO2YXqTAAAAJkBetMraZH2VprjIz9zm4enw7/T47fP3wc7ae5GnAAAAN1BsSmSApLfI1ODq2OHp5Orv8PL09vb38fb5wM/bbISbrL/PfZSpxNPgzdnj2+Pr5evw6+/z6e3w3ePp2OPsma2/ABM5Q197ABk4jKG1yNfjytfh1uDo3eXs4unv1t/nztrjqbzMTmmEXneRES1Ji6CzxtXixdPfztrk1N/n1+Dp1d/oz9vlxdPeq73NVG+KYnyUAAAddIuhwtPhvMzaxtTgytfiy9jjwtHewtHenbDCHT1fS2eCRV52qr7PvM3cucrYv87cv8/cvMzavc3bucvacoyl////ByE8WnKKscXWv9Hguszbu8zbvc7dtcnaiJqrcHZ4f4SHEh0nEitFTWZ+hJqumrDDm7HDj6W5dI2lYGJfmZeQl5SNAAAADRciAAATHjdSOVNsPlhyLklmKCYjW1lUlpOLlZKLFSAqWXSOBQAADA0NAAAAHh0bWlhSk5CIk5CIBAYJDRQbERcdDBAUBgkMAAAEDg4NAAAAHBsZWFZQkY6GAAAAAAAABQUEHBsZAAAAGxoYVlROko+GBAQDZ2RdAAAAGhkYcW9oAgICAAAAExMSDQwLjouDjYuDioiAiIV9hoN7VlRO////Z2DcYwAAAMR0Uk5TAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAACRKrJyrZlBQECaNXCsKaqypMGAUDcu7Gpn5mf03gDo8+4saiipKq3xRMBH83Eu7OsqbG61DkDMdbFvrizsbK3wNs9Ax/VysS/vLq/zNwfArDhxMfExMXE3pMCMe7byMjIzd33ZgYGQtnz6+zooeJXBQMFD1yHejZ1+l8FBgEELlOR+GgFCQ0SGxoBGFKg+m0BBwEMR6v+hAEDM6nRASWURVuYQQ4AAAABYktHRACIBR1IAAAACXBIWXMAAAjLAAAIywGEuOmJAAABCklEQVQY02NgUGZUUVVT19DUYtBmYmZhYdBh1dXTNzA0MjYxZTFjAwqwm1tYWlnb2NrZO3A4cgIFGJycXVzd3D08vbx9uHyBAn7+AYFBwSEhoWHhEdyRQIGo6JjYuPiExKTklFSeNKBAekZmVnZObk5efkEhbxFQgK+4pLSsvKKyqrqGoZZfgIVBsK6+obGpuaW1rV2oQ1hEgKFTtKu7p7evf8LEI5PEJotLMEyZyjJt+oyZsxhmzzk6V3KeFIO01vwFMrJyCxctXrL02DL55QwsClorVq5avWbtuvUbNh7fpMjAwsKyWWvLFJatStu279h5YhdIAAJ2s+zZu+/kfoQAy4HNLAcPHQYA5YtSi+k2/WkAAAAldEVYdGRhdGU6Y3JlYXRlADIwMTMtMTAtMDRUMTk6Mzk6MjEtMDQ6MDAwU1uYAAAAJXRFWHRkYXRlOm1vZGlmeQAyMDEzLTEwLTA0VDE5OjM5OjIxLTA0OjAwQQ7jJAAAABl0RVh0U29mdHdhcmUAd3d3Lmlua3NjYXBlLm9yZ5vuPBoAAAAASUVORK5CYII=)", "type": exercises.MULTIPLE_SELECTION, "correct_answers": [ "White rice", "Brown rice", "Sushi rice <p>abc</p>", ], "all_answers": ["White rice", "Quinoa", "Brown rice", "<"], }, { "id": "bbbbb", "question": "Which rice is the crunchiest?", "type": exercises.SINGLE_SELECTION, "correct_answer": "Rice Krispies \n![](https://upload.wikimedia.org/wikipedia/commons/c/cd/RKTsquares.jpg)", "all_answers": [ "White rice", "Brown rice \n![](https://c2.staticflickr.com/4/3159/2889140143_b99fd8dd4c_z.jpg?zz=1)", "Rice Krispies \n![](https://upload.wikimedia.org/wikipedia/commons/c/cd/RKTsquares.jpg)", ], "hints": "It's delicious", }, { "id": "aaaaa", "question": "How many minutes does it take to cook rice? <img src='https://upload.wikimedia.org/wikipedia/commons/5/5e/Jeera-rice.JPG'>", "type": exercises.INPUT_QUESTION, "answers": ["20", "25", "15"], "hints": [ "Takes roughly same amount of time to install kolibri on Windows machine", "Does this help?\n![](http://www.aroma-housewares.com/images/rice101/delay_timer_1.jpg)", ], }, { "id": "ddddd", "type": exercises.PERSEUS_QUESTION, "item_data": SAMPLE_PERSEUS_1_JSON, }, ], }, { "title": "Rice Exercise 2", "id": "6cafe4", "description": "Test how well you know your rice", "license": licenses.CC_BY_NC_SA, "copyright_holder": "Learning Equality", "mastery_model": exercises.M_OF_N, "files": [ { "path": "https://c1.staticflickr.com/5/4021/4302326650_b11f0f0aaf_b.jpg" } ], "questions": [ { "id": "11111", "question": "<h3 id=\"rainbow\" style=\"font-weight:bold\">RICE COOKING!!!</h3><script type='text/javascript'><!-- setInterval(function() {$('#rainbow').css('color', '#'+((1<<24)*Math.random()|0).toString(16));}, 300); --></script>", "type": exercises.SINGLE_SELECTION, "all_answers": ["Answer"], "correct_answer": "Answer", }, { "id": "121212", "question": "<math> <mrow> <msup><mi> a </mi><mn>2</mn></msup> <mo> + </mo> <msup><mi> b </mi><mn>2</mn></msup> <mo> = </mo> <msup><mi> c </mi><mn>2</mn></msup> </mrow> </math>", "type": exercises.SINGLE_SELECTION, "all_answers": ["Answer"], "correct_answer": "Answer", }, ], }, { "title": "HTML Sample", "id": "abcdef", "description": "An example of how html can be imported from the ricecooker", "license": licenses.PUBLIC_DOMAIN, "files": [{"path": "content://htmltest.zip"}], }, { "title": "Rice Exercise 3", "id": "6cafe5", "description": "Test how well you know your rice", "license": licenses.CC_BY_NC_SA, "copyright_holder": "Learning Equality", "mastery_model": exercises.M_OF_N, "files": [ { "path": "https://upload.wikimedia.org/wikipedia/commons/b/b7/Rice_p1160004.jpg" } ], "questions": [ { "id": "123456", "question": "Solve: $$(111^{x+1}\\times111^\\frac14)\\div111^\\frac12=111^3$$", "type": exercises.SINGLE_SELECTION, "all_answers": ["Yes", "No", "Rice!"], "correct_answer": "Rice!", } ], }, ], } ] SAMPLE_TREE.extend(EXERCISES_NODES) def _build_tree(node, sourcetree): """ Parse nodes given in `sourcetree` and add as children of `node`. """ for child_source_node in sourcetree: try: main_file = ( child_source_node["files"][0] if "files" in child_source_node else {} ) kind = guess_content_kind( path=main_file.get("path"), web_video_data=main_file.get("youtube_id") or main_file.get("web_url"), questions=child_source_node.get("questions"), ) except UnknownContentKindError: continue if kind == content_kinds.TOPIC: child_node = nodes.TopicNode( source_id=child_source_node["id"], title=child_source_node["title"], author=child_source_node.get("author"), description=child_source_node.get("description"), thumbnail=child_source_node.get("thumbnail"), ) node.add_child(child_node) source_tree_children = child_source_node.get("children", []) _build_tree(child_node, source_tree_children) elif kind == content_kinds.VIDEO: child_node = nodes.VideoNode( source_id=child_source_node["id"], title=child_source_node["title"], license=get_license( child_source_node.get("license"), description="Description of license", copyright_holder=child_source_node.get("copyright_holder"), ), author=child_source_node.get("author"), description=child_source_node.get("description"), derive_thumbnail=True, # video-specific data thumbnail=child_source_node.get("thumbnail"), ) add_files(child_node, child_source_node.get("files") or []) node.add_child(child_node) elif kind == content_kinds.AUDIO: child_node = nodes.AudioNode( source_id=child_source_node["id"], title=child_source_node["title"], license=child_source_node.get("license"), author=child_source_node.get("author"), description=child_source_node.get("description"), thumbnail=child_source_node.get("thumbnail"), copyright_holder=child_source_node.get("copyright_holder"), ) add_files(child_node, child_source_node.get("files") or []) node.add_child(child_node) elif kind == content_kinds.DOCUMENT: child_node = nodes.DocumentNode( source_id=child_source_node["id"], title=child_source_node["title"], license=child_source_node.get("license"), author=child_source_node.get("author"), description=child_source_node.get("description"), thumbnail=child_source_node.get("thumbnail"), copyright_holder=child_source_node.get("copyright_holder"), ) add_files(child_node, child_source_node.get("files") or []) node.add_child(child_node) elif kind == content_kinds.EXERCISE: mastery_model = ( child_source_node.get("mastery_model") and {"mastery_model": child_source_node["mastery_model"]} ) or {} child_node = nodes.ExerciseNode( source_id=child_source_node["id"], title=child_source_node["title"], license=child_source_node.get("license"), author=child_source_node.get("author"), description=child_source_node.get("description"), exercise_data=mastery_model, thumbnail=child_source_node.get("thumbnail"), copyright_holder=child_source_node.get("copyright_holder"), ) add_files(child_node, child_source_node.get("files") or []) for q in child_source_node.get("questions"): question = create_question(q) child_node.add_question(question) node.add_child(child_node) elif kind == content_kinds.HTML5: child_node = nodes.HTML5AppNode( source_id=child_source_node["id"], title=child_source_node["title"], license=child_source_node.get("license"), author=child_source_node.get("author"), description=child_source_node.get("description"), thumbnail=child_source_node.get("thumbnail"), copyright_holder=child_source_node.get("copyright_holder"), ) add_files(child_node, child_source_node.get("files") or []) node.add_child(child_node) elif kind == content_kinds.H5P: child_node = nodes.H5PAppNode( source_id=child_source_node["id"], title=child_source_node["title"], license=child_source_node.get("license"), author=child_source_node.get("author"), description=child_source_node.get("description"), thumbnail=child_source_node.get("thumbnail"), copyright_holder=child_source_node.get("copyright_holder"), ) add_files(child_node, child_source_node.get("files") or []) node.add_child(child_node) else: # unknown content file format continue return node if __name__ == "__main__": """ This code will run when the sushi chef is called from the command line. """ chef = SampleChef() chef.main()
45.594684
1,965
0.620847
0ec3a322173dd7c7c650f060b94c615e6cceb769
19,118
py
Python
release/scripts/modules/bl_i18n_utils/utils_spell_check.py
dvgd/blender
4eb2807db1c1bd2514847d182fbb7a3f7773da96
[ "Naumen", "Condor-1.1", "MS-PL" ]
null
null
null
release/scripts/modules/bl_i18n_utils/utils_spell_check.py
dvgd/blender
4eb2807db1c1bd2514847d182fbb7a3f7773da96
[ "Naumen", "Condor-1.1", "MS-PL" ]
null
null
null
release/scripts/modules/bl_i18n_utils/utils_spell_check.py
dvgd/blender
4eb2807db1c1bd2514847d182fbb7a3f7773da96
[ "Naumen", "Condor-1.1", "MS-PL" ]
1
2020-12-02T20:05:42.000Z
2020-12-02T20:05:42.000Z
# ##### BEGIN GPL LICENSE BLOCK ##### # # 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., 51 Franklin Street, Fifth Floor, Boston, MA 02110-1301, USA. # # ##### END GPL LICENSE BLOCK ##### # <pep8 compliant> import enchant import os import pickle import re
23.145278
103
0.437703
0ec3b7be918911b5b776d40be78266905df319e1
7,175
py
Python
naslib/predictors/mlp.py
gmeyerlee/NASLib
21dbceda04cc1faf3d8b6dd391412a459218ef2b
[ "Apache-2.0" ]
null
null
null
naslib/predictors/mlp.py
gmeyerlee/NASLib
21dbceda04cc1faf3d8b6dd391412a459218ef2b
[ "Apache-2.0" ]
null
null
null
naslib/predictors/mlp.py
gmeyerlee/NASLib
21dbceda04cc1faf3d8b6dd391412a459218ef2b
[ "Apache-2.0" ]
null
null
null
import numpy as np import os import json import torch import torch.nn as nn import torch.nn.functional as F import torch.optim as optim from torch.utils.data import DataLoader, TensorDataset from naslib.utils.utils import AverageMeterGroup from naslib.predictors.utils.encodings import encode from naslib.predictors import Predictor # NOTE: faster on CPU device = torch.device("cpu") print("device:", device)
32.466063
88
0.564739
0ec3f2a1fe20def9bc91ffbd4b3742d74abb33b3
1,301
py
Python
pythonforandroid/recipes/libx264/__init__.py
Joreshic/python-for-android
c60e02d2e32e31a3a754838c51e9242cbadcd9e8
[ "MIT" ]
1
2019-09-03T13:44:06.000Z
2019-09-03T13:44:06.000Z
pythonforandroid/recipes/libx264/__init__.py
Joreshic/python-for-android
c60e02d2e32e31a3a754838c51e9242cbadcd9e8
[ "MIT" ]
null
null
null
pythonforandroid/recipes/libx264/__init__.py
Joreshic/python-for-android
c60e02d2e32e31a3a754838c51e9242cbadcd9e8
[ "MIT" ]
1
2018-11-15T07:58:30.000Z
2018-11-15T07:58:30.000Z
from pythonforandroid.toolchain import Recipe, shprint, current_directory, ArchARM from os.path import exists, join, realpath from os import uname import glob import sh recipe = LibX264Recipe()
37.171429
93
0.583397
0ec3f460313d8f825c0daad58ff5e76ef71c5401
1,704
py
Python
Win/reg.py
QGB/QPSU
7bc214676d797f42d2d7189dc67c9377bccdf25d
[ "MIT" ]
6
2018-03-25T20:05:21.000Z
2022-03-13T17:23:05.000Z
Win/reg.py
pen9un/QPSU
76e1a3f6f6f6f78452e02f407870a5a32177b667
[ "MIT" ]
15
2018-05-14T03:30:21.000Z
2022-03-03T15:33:25.000Z
Win/reg.py
pen9un/QPSU
76e1a3f6f6f6f78452e02f407870a5a32177b667
[ "MIT" ]
1
2021-07-15T06:23:45.000Z
2021-07-15T06:23:45.000Z
#coding=utf-8 try: if __name__.startswith('qgb.Win'): from .. import py else: import py except Exception as ei: raise ei raise EnvironmentError(__name__) if py.is2(): import _winreg as winreg from _winreg import * else: import winreg from winreg import * def get(skey,name,root=HKEY_CURRENT_USER,returnType=True): ''' from qgb.Win import reg reg.get(r'Software\Microsoft\Windows\CurrentVersion\Internet Settings','ProxyEnable') reg.get(r'HKLM\SYSTEM\CurrentControlSet\Services\LanmanServer\Parameters\Size' ) There are seven predefined root keys, traditionally named according to their constant handles defined in the Win32 API skey name FileNotFoundError: [WinError 2] ''' r = OpenKey(root,skey) r = QueryValueEx(r,name) if returnType:return r[0],'{} : {}'.format(REG_TYPE[r[1]],r[1]) else :return r[0] REG_TYPE={ 0 : 'REG_NONE', 1 : 'REG_SZ', 2 : 'REG_EXPAND_SZ', 3 : 'REG_BINARY', 4 : 'REG_DWORD', 5 : 'REG_DWORD_BIG_ENDIAN', 6 : 'REG_LINK', 7 : 'REG_MULTI_SZ', 8 : 'REG_RESOURCE_LIST', 9 : 'REG_FULL_RESOURCE_DESCRIPTOR', 10: 'REG_RESOURCE_REQUIREMENTS_LIST', 11: 'REG_QWORD'}
29.894737
119
0.693662
0ec42be3581d1c9d5c9ab4c954473cd6061146b5
3,555
py
Python
tests/test_handler.py
CJSoldier/webssh
b3c33ff6bd76f4f5df40cc1fe9a138cf0cecd08c
[ "MIT" ]
13
2018-09-16T15:51:38.000Z
2019-10-16T09:13:18.000Z
tests/test_handler.py
CJSoldier/webssh
b3c33ff6bd76f4f5df40cc1fe9a138cf0cecd08c
[ "MIT" ]
null
null
null
tests/test_handler.py
CJSoldier/webssh
b3c33ff6bd76f4f5df40cc1fe9a138cf0cecd08c
[ "MIT" ]
null
null
null
import unittest import paramiko from tornado.httputil import HTTPServerRequest from tests.utils import read_file, make_tests_data_path from webssh.handler import MixinHandler, IndexHandler, InvalidValueError
40.397727
72
0.686639
0ec517fad6215e10cf8fdc40288d6f1a4376050d
17,499
py
Python
apps/notifications/tests/test_views.py
SCiO-systems/qcat
8c2b8e07650bc2049420fa6de758fba7e50c2f28
[ "Apache-2.0" ]
null
null
null
apps/notifications/tests/test_views.py
SCiO-systems/qcat
8c2b8e07650bc2049420fa6de758fba7e50c2f28
[ "Apache-2.0" ]
null
null
null
apps/notifications/tests/test_views.py
SCiO-systems/qcat
8c2b8e07650bc2049420fa6de758fba7e50c2f28
[ "Apache-2.0" ]
null
null
null
import logging from unittest import mock from unittest.mock import call from django.conf import settings from django.contrib.auth import get_user_model from django.core.signing import Signer from django.urls import reverse from django.http import Http404 from django.test import RequestFactory from braces.views import LoginRequiredMixin from django.test import override_settings from model_mommy import mommy from apps.notifications.models import Log, StatusUpdate, MemberUpdate, ReadLog, \ ActionContextQuerySet from apps.notifications.views import LogListView, LogCountView, ReadLogUpdateView, \ LogQuestionnairesListView, LogInformationUpdateCreateView, \ LogSubscriptionPreferencesView, SignedLogSubscriptionPreferencesView from apps.qcat.tests import TestCase #def test_add_user_aware_data_is_todo(self): # data = self._test_add_user_aware_data() # self.assertTrue(data[1]['is_todo']) def test_get_status_invalid(self): request = RequestFactory().get('{}?statuses=foo'.format(self.url_path)) view = self.setup_view(self.view, request) self.assertEqual(view.get_statuses(), []) class ReadLogUpdateViewTest(TestCase):
37.958785
91
0.66821
0ec65d0e2393fe675648f46032adc3e480a8ef52
1,032
py
Python
examples/resources.py
willvousden/clint
6dc7ab1a6a162750e968463b43994447bca32544
[ "0BSD" ]
1,230
2015-01-03T05:39:25.000Z
2020-02-18T12:36:03.000Z
examples/resources.py
willvousden/clint
6dc7ab1a6a162750e968463b43994447bca32544
[ "0BSD" ]
50
2015-01-06T17:58:20.000Z
2018-03-19T13:25:22.000Z
examples/resources.py
willvousden/clint
6dc7ab1a6a162750e968463b43994447bca32544
[ "0BSD" ]
153
2015-01-03T03:56:25.000Z
2020-02-13T20:59:03.000Z
#!/usr/bin/env python # -*- coding: utf-8 -*- from __future__ import print_function import sys import os sys.path.insert(0, os.path.abspath('..')) from clint import resources resources.init('kennethreitz', 'clint') lorem = 'Lorem ipsum dolor sit amet, consectetur adipisicing elit, sed do eiusmod tempor incididunt ut labore et dolore magna aliqua. Ut enim ad minim veniam, quis nostrud exercitation ullamco laboris nisi ut aliquip ex ea commodo consequat. Duis aute irure dolor in reprehenderit in voluptate velit esse cillum dolore eu fugiat nulla pariatur. Excepteur sint occaecat cupidatat non proident, sunt in culpa qui officia deserunt mollit anim id est laborum.' print('%s created.' % resources.user.path) resources.user.write('lorem.txt', lorem) print('lorem.txt created') assert resources.user.read('lorem.txt') == lorem print('lorem.txt has correct contents') resources.user.delete('lorem.txt') print('lorem.txt deleted') assert resources.user.read('lorem.txt') == None print('lorem.txt deletion confirmed')
33.290323
456
0.767442
0ec667f34cc8524a0bd9453e82114220e88aef5a
813
py
Python
photos/urls.py
charlesmugambi/Instagram
3a9dfc32c45bf9f221b22b7075ce31b1a16dcba7
[ "MIT" ]
null
null
null
photos/urls.py
charlesmugambi/Instagram
3a9dfc32c45bf9f221b22b7075ce31b1a16dcba7
[ "MIT" ]
null
null
null
photos/urls.py
charlesmugambi/Instagram
3a9dfc32c45bf9f221b22b7075ce31b1a16dcba7
[ "MIT" ]
null
null
null
from django.conf.urls import url from django.conf import settings from django.conf.urls.static import static from . import views urlpatterns = [ url(r'^$', views.index, name='index'), url(r'^image/$', views.add_image, name='upload_image'), url(r'^profile/$', views.profile_info, name='profile'), url(r'^update/$', views.profile_update, name='update'), url(r'^comment/(?P<image_id>\d+)', views.comment, name='comment'), url(r'^search/', views.search_results, name = 'search_results'), url(r'^follow/(?P<user_id>\d+)', views.follow, name = 'follow'), url(r'^unfollow/(?P<user_id>\d+)', views.unfollow, name='unfollow'), url(r'^likes/(\d+)/$', views.like_images,name='likes') ] if settings.DEBUG: urlpatterns += static(settings.MEDIA_URL, document_root=settings.MEDIA_ROOT)
42.789474
80
0.675277
0ec7068e816bc6b2d31f51831d9d75f6ffc1151c
11,247
py
Python
bread.py
vgfang/breadbot
e58807431945e6d4de8dfc6c4dc4c90caebf88ca
[ "MIT" ]
null
null
null
bread.py
vgfang/breadbot
e58807431945e6d4de8dfc6c4dc4c90caebf88ca
[ "MIT" ]
null
null
null
bread.py
vgfang/breadbot
e58807431945e6d4de8dfc6c4dc4c90caebf88ca
[ "MIT" ]
null
null
null
import random import math from fractions import Fraction from datetime import datetime from jinja2 import Template # empty class for passing to template engine # returns flour percent using flour type def get_special_flour_percent(flourType: str, breadFlourPercent:int) -> int: if flourType == 'Hard Red Whole Wheat' or flourType == 'Hard White Wheat': percentages = [0,25,30,35,40,45,50] percentages = list(filter(lambda x: 100-breadFlourPercent >= x, percentages)) return random.choice(percentages) elif flourType == 'Rye' and breadFlourPercent >= 75: percentages = [0,10,15,20] percentages = list(filter(lambda x: 100-breadFlourPercent >= x, percentages)) return random.choice(percentages) else: percentages = [0,10,15,20,25.30] percentages = list(filter(lambda x: 100-breadFlourPercent >= x, percentages)) return random.choice(percentages) # returns multiplied spoon units from teaspoon fraction input, 3 tsp = 1 tbsp # returns amount given the type of flavoring(spices) # returns list of spices using number of spices # check if extract is nut # checks if extract1 and extract2 are both allowed based on zest/extract same flavor # return list of extracts using number of extracts # return percentage of enrichment # return liquid percent from liquid tpye # return fruit puree fruit choice(s), omitted fruit chance weighting for now # retrun fruit puree percent from 0-2 fruitPurees using random generation # returns rounded ml conversion from percent, used in template # takes filename and writes an html recipe file
36.996711
103
0.727927
0ec7b7a0dee386c8044a5e357cb59fce0132a0cf
19,177
py
Python
posthog/api/test/test_organization_domain.py
msnitish/posthog
cb86113f568e72eedcb64b5fd00c313d21e72f90
[ "MIT" ]
null
null
null
posthog/api/test/test_organization_domain.py
msnitish/posthog
cb86113f568e72eedcb64b5fd00c313d21e72f90
[ "MIT" ]
null
null
null
posthog/api/test/test_organization_domain.py
msnitish/posthog
cb86113f568e72eedcb64b5fd00c313d21e72f90
[ "MIT" ]
null
null
null
import datetime from unittest.mock import patch import dns.resolver import dns.rrset import pytest import pytz from django.utils import timezone from freezegun import freeze_time from rest_framework import status from posthog.models import Organization, OrganizationDomain, OrganizationMembership, Team from posthog.test.base import APIBaseTest, BaseTest def test_cannot_list_or_retrieve_domains_for_other_org(self): self.organization_membership.level = OrganizationMembership.Level.ADMIN self.organization_membership.save() response = self.client.get(f"/api/organizations/@current/domains/{self.another_domain.id}") self.assertEqual(response.status_code, status.HTTP_404_NOT_FOUND) self.assertEqual(response.json(), self.not_found_response()) response = self.client.get(f"/api/organizations/{self.another_org.id}/domains/{self.another_domain.id}") self.assertEqual(response.status_code, status.HTTP_403_FORBIDDEN) self.assertEqual(response.json(), self.permission_denied_response()) # Create domains def test_cannot_request_verification_for_verified_domains(self): self.organization_membership.level = OrganizationMembership.Level.ADMIN self.organization_membership.save() self.domain.verified_at = timezone.now() self.domain.save() response = self.client.post(f"/api/organizations/@current/domains/{self.domain.id}/verify") self.assertEqual(response.status_code, status.HTTP_400_BAD_REQUEST) self.assertEqual( response.json(), { "type": "validation_error", "code": "already_verified", "detail": "This domain has already been verified.", "attr": None, }, ) def test_only_admin_can_create_verified_domains(self): count = OrganizationDomain.objects.count() response = self.client.post("/api/organizations/@current/domains/", {"domain": "evil.posthog.com"}) self.assertEqual(response.status_code, status.HTTP_403_FORBIDDEN) self.assertEqual( response.json(), self.permission_denied_response("Your organization access level is insufficient."), ) self.assertEqual(OrganizationDomain.objects.count(), count) def test_only_admin_can_request_verification(self): response = self.client.post(f"/api/organizations/@current/domains/{self.domain.id}/verify") self.assertEqual(response.status_code, status.HTTP_403_FORBIDDEN) self.assertEqual( response.json(), self.permission_denied_response("Your organization access level is insufficient."), ) self.domain.refresh_from_db() self.assertEqual(self.domain.verified_at, None) # Update domains # Delete domains
45.228774
118
0.671012
0ec7d9e291a15b37ad7f7b106420f6f50a25a3a0
1,248
py
Python
tutorial/test input.py
nataliapryakhina/FA_group3
3200464bc20d38a85af9ad3583a360db4ffb7f8d
[ "MIT" ]
null
null
null
tutorial/test input.py
nataliapryakhina/FA_group3
3200464bc20d38a85af9ad3583a360db4ffb7f8d
[ "MIT" ]
null
null
null
tutorial/test input.py
nataliapryakhina/FA_group3
3200464bc20d38a85af9ad3583a360db4ffb7f8d
[ "MIT" ]
null
null
null
import numpy as np import tensorflow as tf from tensorflow import keras import matplotlib.pyplot as plt from os import listdir from tensorflow.keras.callbacks import ModelCheckpoint dataDir = "./data/trainSmallFA/" files = listdir(dataDir) files.sort() totalLength = len(files) inputs = np.empty((len(files), 3, 64, 64)) targets = np.empty((len(files), 3, 64, 64)) for i, file in enumerate(files): npfile = np.load(dataDir + file) d = npfile['a'] inputs[i] = d[0:3] # inx, iny, mask targets[i] = d[3:6] # p, velx, vely # print("inputs shape = ", inputs.shape) print(np.shape(targets[:, 1, :, :].flatten())) maxvel = np.amax(np.sqrt(targets[:, 1, :, :]* targets[:, 1, :, :] + targets[:, 2, :, :]* targets[:, 2, :, :])) print(maxvel) targets[:, 1:3, :, :] /= maxvel targets[:, 0, :, :] /= np.amax(targets[:, 0, :, :]) for input in inputs: plt.figure(num=None, figsize=(20, 10), dpi=80, facecolor='w', edgecolor='k') # predicted data plt.subplot(331) plt.title('x vel') plt.imshow(input[0, :, :], cmap='jet') # vmin=-100,vmax=100, cmap='jet') plt.colorbar() plt.subplot(332) plt.title('y vel') plt.imshow(input[1, :, :], cmap='jet') plt.colorbar() plt.show()
30.439024
80
0.600962
0ec8d0b22163c94b04ce1660f7662d06d776efe5
2,781
py
Python
pepper/responder/brain.py
cltl/pepper
5d34fc5074473163aa9273016d89e5e2b8edffa9
[ "MIT" ]
29
2018-01-20T08:51:42.000Z
2022-01-25T11:59:28.000Z
pepper/responder/brain.py
cltl/pepper
5d34fc5074473163aa9273016d89e5e2b8edffa9
[ "MIT" ]
32
2018-09-20T13:09:34.000Z
2021-06-04T15:23:45.000Z
pepper/responder/brain.py
cltl/pepper
5d34fc5074473163aa9273016d89e5e2b8edffa9
[ "MIT" ]
10
2018-10-25T02:45:21.000Z
2020-10-03T12:59:10.000Z
from pepper.framework import * from pepper import logger from pepper.language import Utterance from pepper.language.generation.thoughts_phrasing import phrase_thoughts from pepper.language.generation.reply import reply_to_question from .responder import Responder, ResponderType from pepper.language import UtteranceType from pepper.knowledge import sentences, animations from random import choice import re from typing import Optional, Union, Tuple, Callable
41.507463
126
0.612729
0ec932467a0e10a4a3b540d34642f573915937be
7,076
py
Python
fedora_college/modules/content/views.py
fedora-infra/fedora-college
cf310dab2e4fea02b9ac5e7f57dc53aafb4834d8
[ "BSD-3-Clause" ]
2
2015-05-16T09:54:17.000Z
2017-01-11T17:58:31.000Z
fedora_college/modules/content/views.py
fedora-infra/fedora-college
cf310dab2e4fea02b9ac5e7f57dc53aafb4834d8
[ "BSD-3-Clause" ]
null
null
null
fedora_college/modules/content/views.py
fedora-infra/fedora-college
cf310dab2e4fea02b9ac5e7f57dc53aafb4834d8
[ "BSD-3-Clause" ]
1
2020-12-07T22:14:01.000Z
2020-12-07T22:14:01.000Z
# -*- coding: utf-8 -*- import re from unicodedata import normalize from flask import Blueprint, render_template, current_app from flask import redirect, url_for, g, abort from sqlalchemy import desc from fedora_college.core.database import db from fedora_college.modules.content.forms import * # noqa from fedora_college.core.models import * # noqa from fedora_college.fedmsgshim import publish from flask_fas_openid import fas_login_required bundle = Blueprint('content', __name__, template_folder='templates') from fedora_college.modules.content.media import * # noqa _punct_re = re.compile(r'[\t !"#$%&\'()*\-/<=>?@\[\\\]^_`{|},.]+') # Verify if user is authenticated # generate url slug def slugify(text, delim=u'-'): """Generates an slightly worse ASCII-only slug.""" result = [] for word in _punct_re.split(text.lower()): word = normalize('NFKD', word).encode('ascii', 'ignore') if word: result.append(word) return unicode(delim.join(result)) # attach tags to a content entry # delete content # add / edit more content # View Blog post
34.517073
79
0.53307
0ecb2c7a8dccded4280171cf1a9314223cfca421
3,611
py
Python
tests/components/airthings/test_config_flow.py
MrDelik/core
93a66cc357b226389967668441000498a10453bb
[ "Apache-2.0" ]
30,023
2016-04-13T10:17:53.000Z
2020-03-02T12:56:31.000Z
tests/components/airthings/test_config_flow.py
MrDelik/core
93a66cc357b226389967668441000498a10453bb
[ "Apache-2.0" ]
31,101
2020-03-02T13:00:16.000Z
2022-03-31T23:57:36.000Z
tests/components/airthings/test_config_flow.py
MrDelik/core
93a66cc357b226389967668441000498a10453bb
[ "Apache-2.0" ]
11,956
2016-04-13T18:42:31.000Z
2020-03-02T09:32:12.000Z
"""Test the Airthings config flow.""" from unittest.mock import patch import airthings from homeassistant import config_entries from homeassistant.components.airthings.const import CONF_ID, CONF_SECRET, DOMAIN from homeassistant.core import HomeAssistant from homeassistant.data_entry_flow import RESULT_TYPE_CREATE_ENTRY, RESULT_TYPE_FORM from tests.common import MockConfigEntry TEST_DATA = { CONF_ID: "client_id", CONF_SECRET: "secret", }
30.601695
84
0.675159
0ecb9ff079e3fe67fcf620b3218ea8892b9b9c1c
1,726
py
Python
utils/utils.py
scomup/StereoNet-ActiveStereoNet
05994cf1eec4a109e095732fe01ecb5558880ba5
[ "MIT" ]
null
null
null
utils/utils.py
scomup/StereoNet-ActiveStereoNet
05994cf1eec4a109e095732fe01ecb5558880ba5
[ "MIT" ]
null
null
null
utils/utils.py
scomup/StereoNet-ActiveStereoNet
05994cf1eec4a109e095732fe01ecb5558880ba5
[ "MIT" ]
null
null
null
# ------------------------------------------------------------------------------ # Copyright (c) NKU # Licensed under the MIT License. # Written by Xuanyi Li ([email protected]) # ------------------------------------------------------------------------------ import os import torch import torch.nn.functional as F #import cv2 as cv import numpy as np if __name__ == '__main__': pass # import matplotlib.pyplot as plt # image = cv.imread('/media/lxy/sdd1/ActiveStereoNet/StereoNet_pytorch/results/forvideo/iter-122.jpg') #im_gray = cv.imread('/media/lxy/sdd1/ActiveStereoNet/StereoNet_pytorch/results/forvideo/iter-133.jpg', cv.IMREAD_GRAYSCALE) # print(im_gray.shape) #im_color = cv.applyColorMap(im_gray*2, cv.COLORMAP_JET) # cv.imshow('test', im_color) # cv.waitKey(0) #cv.imwrite('test.png',im_color) # print(image.shape) # plt.figure('Image') # sc =plt.imshow(image) # sc.set_cmap('hsv') # plt.colorbar() # plt.axis('off') # plt.show() # print('end') # image[:,:,0].save('/media/lxy/sdd1/ActiveStereoNet/StereoNet_pytorch/results/pretrained_StereoNet_single/it1er-151.jpg')
32.566038
128
0.589803
0ecc375d6cf3b58f62ba3d07d23244af90a9b759
1,036
py
Python
worker/main.py
Devalent/facial-recognition-service
342e31fa7d016992d938b0121b03f0e8fe776ea8
[ "MIT" ]
null
null
null
worker/main.py
Devalent/facial-recognition-service
342e31fa7d016992d938b0121b03f0e8fe776ea8
[ "MIT" ]
null
null
null
worker/main.py
Devalent/facial-recognition-service
342e31fa7d016992d938b0121b03f0e8fe776ea8
[ "MIT" ]
null
null
null
from aiohttp import web import base64 import io import face_recognition main()
22.521739
68
0.625483
0ecd026a7b7cddee19fb7d65983aadf807f4917d
657
py
Python
rblod/setup.py
TiKeil/Two-scale-RBLOD
23f17a3e4edf63ea5f208eca50ca90c19bf511a9
[ "BSD-2-Clause" ]
null
null
null
rblod/setup.py
TiKeil/Two-scale-RBLOD
23f17a3e4edf63ea5f208eca50ca90c19bf511a9
[ "BSD-2-Clause" ]
null
null
null
rblod/setup.py
TiKeil/Two-scale-RBLOD
23f17a3e4edf63ea5f208eca50ca90c19bf511a9
[ "BSD-2-Clause" ]
null
null
null
# ~~~ # This file is part of the paper: # # " An Online Efficient Two-Scale Reduced Basis Approach # for the Localized Orthogonal Decomposition " # # https://github.com/TiKeil/Two-scale-RBLOD.git # # Copyright 2019-2021 all developers. All rights reserved. # License: Licensed as BSD 2-Clause License (http://opensource.org/licenses/BSD-2-Clause) # Authors: # Stephan Rave # Tim Keil # ~~~ from setuptools import setup setup(name='rblod', version='2021.1', description='Pymor support for RBLOD', author='Tim Keil', author_email='[email protected]', license='MIT', packages=['rblod'])
26.28
89
0.648402
0ecdf401d5b3926e749aa892bfa6a87de7f72b30
8,060
py
Python
bin/euclid_fine_plot_job_array.py
ndeporzio/cosmicfish
f68f779d73f039512a958d110bb44194d0daceec
[ "MIT" ]
null
null
null
bin/euclid_fine_plot_job_array.py
ndeporzio/cosmicfish
f68f779d73f039512a958d110bb44194d0daceec
[ "MIT" ]
null
null
null
bin/euclid_fine_plot_job_array.py
ndeporzio/cosmicfish
f68f779d73f039512a958d110bb44194d0daceec
[ "MIT" ]
null
null
null
import os import shutil import numpy as np import pandas as pd import seaborn as sns import cosmicfish as cf import matplotlib.pyplot as plt import dill # Instruct pyplot to use seaborn sns.set() # Set project, data, CLASS directories projectdir = os.environ['STORAGE_DIR'] datastore = os.environ['DATASTORE_DIR'] classpath = os.environ['CLASS_DIR'] fidx = int(os.environ['FORECAST_INDEX']) # Generate output paths fp_resultsdir = projectdir cf.makedirectory(fp_resultsdir) # Specify resolution of numerical integrals derivative_step = 0.008 # How much to vary parameter to calculate numerical derivative g_derivative_step = 0.1 mu_integral_step = 0.05 # For calculating numerical integral wrt mu between -1 and 1 # Linda Fiducial Cosmology fp_fid = { "A_s" : 2.2321e-9, "n_s" : 0.967, "omega_b" : 0.02226, "omega_cdm" : 0.1127, "tau_reio" : 0.0598, "h" : 0.701, "T_cmb" : 2.726, # Units [K] "N_ncdm" : 4., "deg_ncdm" : 1.0, "T_ncdm" : (0.79/2.726), # Units [T_cmb]. "m_ncdm" : 0.01, # Units [eV] "b0" : 1.0, "beta0" : 1.7, "beta1" : 1.0, "alphak2" : 1.0, "sigma_fog_0" : 250000, #Units [m s^-2] "N_eff" : 0.0064, #We allow relativistic neutrinos in addition to our DM relic "relic_vary" : "N_ncdm", # Fix T_ncdm or m_ncdm "m_nu" : 0.02 } # EUCLID values z_table = np.array([0.65, 0.75, 0.85, 0.95, 1.05, 1.15, 1.25, 1.35, 1.45, 1.55, 1.65, 1.75, 1.85, 1.95]) dNdz = np.array([2434.280, 4364.812, 4728.559, 4825.798, 4728.797, 4507.625, 4269.851, 3720.657, 3104.309, 2308.975, 1514.831, 1474.707, 893.716, 497.613]) skycover = 0.3636 # Run Fisher Forecast full_masses = np.geomspace(0.01, 10., 21) full_temps = np.array([0.79, 0.91, 0.94, 1.08]) mass_index=(fidx % 21) temp_index=(fidx // 21) masses = np.array([full_masses[mass_index]]) temps = np.array([full_temps[temp_index]]) omegacdm_set = np.array([ fp_fid['omega_cdm'] - ((masses/cf.NEUTRINO_SCALE_FACTOR)* np.power(tval / 1.95, 3.)) for tidx, tval in enumerate(temps)]) fp_fiducialset = [[ dict(fp_fid, **{ 'm_ncdm' : masses[midx], 'omega_cdm' : omegacdm_set[tidx, midx], 'T_ncdm' : temps[tidx]/2.726}) for midx, mval in enumerate(masses)] for tidx, tval in enumerate(temps)] fp_forecastset = [[cf.forecast( classpath, datastore, '2relic', fidval, z_table, "EUCLID", dNdz, fsky=skycover, dstep=derivative_step, gstep=g_derivative_step, RSD=True, FOG=True, AP=True, COV=True) for fididx, fidval in enumerate(fidrowvals)] for fidrowidx, fidrowvals in enumerate(fp_fiducialset)] #dill.load_session('') for frowidx, frowval in enumerate(fp_forecastset): for fidx, fcst in enumerate(frowval): if type(fcst.fisher)==type(None): fcst.gen_pm() fcst.gen_fisher( fisher_order=[ 'omega_b', 'omega_cdm', 'n_s', 'A_s', 'tau_reio', 'h', 'N_ncdm', 'M_ncdm', 'sigma_fog', 'beta0', 'beta1', 'alpha_k2'], mu_step=mu_integral_step, skipgen=False) print("Relic Forecast ", fidx, " complete...") dill.dump_session(os.path.join(fp_resultsdir, 'fp_'+str(temp_index)+'_'+str(mass_index)+'.db')) else: print('Fisher matrix already generated!')
65.528455
116
0.262655
0ece61d6db781e687c9a0cc4ff7c881e2a9a0b06
346
py
Python
project4/test/test_arm.py
XDZhelheim/CS205_C_CPP_Lab
f585fd685a51e19fddc9c582846547d34442c6ef
[ "MIT" ]
3
2022-01-11T08:12:40.000Z
2022-03-27T08:15:45.000Z
project4/test/test_arm.py
XDZhelheim/CS205_C_CPP_Lab
f585fd685a51e19fddc9c582846547d34442c6ef
[ "MIT" ]
null
null
null
project4/test/test_arm.py
XDZhelheim/CS205_C_CPP_Lab
f585fd685a51e19fddc9c582846547d34442c6ef
[ "MIT" ]
2
2022-03-03T03:01:20.000Z
2022-03-27T08:16:02.000Z
import os if __name__ == "__main__": dims = ["32", "64", "128", "256", "512", "1024", "2048"] for dim in dims: os.system( f"perf stat -e r11 -x, -r 10 ../matmul.out ../data/mat-A-{dim}.txt ../data/mat-B-{dim}.txt ./out/out-{dim}.txt 2>>res_arm.csv" ) print(f"Finished {dim}") print("Finished.")
26.615385
138
0.514451
0ecedb23d891d612188b09f34a36b454a3d85a93
6,674
py
Python
src/oci/apm_traces/models/query_result_row_type_summary.py
Manny27nyc/oci-python-sdk
de60b04e07a99826254f7255e992f41772902df7
[ "Apache-2.0", "BSD-3-Clause" ]
249
2017-09-11T22:06:05.000Z
2022-03-04T17:09:29.000Z
src/oci/apm_traces/models/query_result_row_type_summary.py
Manny27nyc/oci-python-sdk
de60b04e07a99826254f7255e992f41772902df7
[ "Apache-2.0", "BSD-3-Clause" ]
228
2017-09-11T23:07:26.000Z
2022-03-23T10:58:50.000Z
src/oci/apm_traces/models/query_result_row_type_summary.py
Manny27nyc/oci-python-sdk
de60b04e07a99826254f7255e992f41772902df7
[ "Apache-2.0", "BSD-3-Clause" ]
224
2017-09-27T07:32:43.000Z
2022-03-25T16:55:42.000Z
# coding: utf-8 # Copyright (c) 2016, 2021, Oracle and/or its affiliates. All rights reserved. # This software is dual-licensed to you under the Universal Permissive License (UPL) 1.0 as shown at https://oss.oracle.com/licenses/upl or Apache License 2.0 as shown at http://www.apache.org/licenses/LICENSE-2.0. You may choose either license. from oci.util import formatted_flat_dict, NONE_SENTINEL, value_allowed_none_or_none_sentinel # noqa: F401 from oci.decorators import init_model_state_from_kwargs
33.878173
245
0.674408
0ecf9572bf4b2d6c4df42c5a6542407de0db8c29
6,920
py
Python
jaxformer/hf/sample.py
salesforce/CodeGen
2ca076874ca2d26c2437df2968f6c43df92748bc
[ "BSD-3-Clause" ]
105
2022-03-29T23:45:55.000Z
2022-03-31T23:57:14.000Z
jaxformer/hf/sample.py
salesforce/CodeGen
2ca076874ca2d26c2437df2968f6c43df92748bc
[ "BSD-3-Clause" ]
2
2022-03-31T04:18:49.000Z
2022-03-31T17:58:09.000Z
jaxformer/hf/sample.py
salesforce/CodeGen
2ca076874ca2d26c2437df2968f6c43df92748bc
[ "BSD-3-Clause" ]
6
2022-03-30T06:05:39.000Z
2022-03-31T21:01:27.000Z
# Copyright (c) 2022, salesforce.com, inc. # All rights reserved. # SPDX-License-Identifier: BSD-3-Clause # For full license text, see the LICENSE file in the repo root or https://opensource.org/licenses/BSD-3-Clause import os import re import time import random import argparse import torch from transformers import GPT2TokenizerFast from jaxformer.hf.codegen.modeling_codegen import CodeGenForCausalLM ######################################################################## # util ######################################################################## # model ######################################################################## # sample ######################################################################## # main if __name__ == '__main__': test_truncate() main() print('done.')
27.244094
224
0.619509
0ecfc00a422b2dc3bba9eb71d7782113b804c267
4,351
py
Python
tests/services/test_rover_runner_service.py
dev-11/mars-rover-challenge
67569fcc4b93e5ec4cbe466d7a2fd5b3e9a316b0
[ "MIT" ]
null
null
null
tests/services/test_rover_runner_service.py
dev-11/mars-rover-challenge
67569fcc4b93e5ec4cbe466d7a2fd5b3e9a316b0
[ "MIT" ]
null
null
null
tests/services/test_rover_runner_service.py
dev-11/mars-rover-challenge
67569fcc4b93e5ec4cbe466d7a2fd5b3e9a316b0
[ "MIT" ]
null
null
null
import unittest from services import RoverRunnerService from tests.test_environment.marses import small_mars_with_one_rover_empty_commands from tests.test_environment import mocks as m from data_objects import Rover
51.188235
85
0.746495
0ed02b6b55177c4481e9ea0e870de71a75e2629f
12,734
py
Python
retrain_with_rotnet.py
ericdaat/self-label
7c12f834c7b6bd5bee2f7f165aab33d4c4e50b51
[ "MIT" ]
440
2020-02-17T06:54:38.000Z
2022-03-24T09:32:13.000Z
retrain_with_rotnet.py
ericdaat/self-label
7c12f834c7b6bd5bee2f7f165aab33d4c4e50b51
[ "MIT" ]
21
2020-02-28T06:40:20.000Z
2022-03-11T10:59:09.000Z
retrain_with_rotnet.py
ericdaat/self-label
7c12f834c7b6bd5bee2f7f165aab33d4c4e50b51
[ "MIT" ]
53
2020-02-27T13:05:49.000Z
2022-03-07T02:33:01.000Z
import argparse import warnings warnings.simplefilter("ignore", UserWarning) import files from tensorboardX import SummaryWriter import os import numpy as np import time import torch import torch.optim import torch.nn as nn import torch.utils.data import torchvision import torchvision.transforms as tfs from data import DataSet,return_model_loader from util import weight_init, write_conv, setup_runtime, AverageMeter, MovingAverage if __name__ == "__main__": args = get_parser().parse_args() name = "%s" % args.comment.replace('/', '_') try: args.device = [int(item) for item in args.device.split(',')] except AttributeError: args.device = [int(args.device)] setup_runtime(seed=42, cuda_dev_id=args.device) print(args, flush=True) print() print(name,flush=True) writer = SummaryWriter('./runs/%s/%s'%(args.data,name)) writer.add_text('args', " \n".join(['%s %s' % (arg, getattr(args, arg)) for arg in vars(args)])) # Setup model and train_loader print('Commencing!', flush=True) model, train_loader = return_model_loader(args) train_loader = RotationDataLoader(args.imagenet_path, is_validation=False, crop_size=224, batch_size=args.batch_size, num_workers=args.workers, shuffle=True) # add additional head to the network for RotNet loss. if args.arch == 'alexnet': if args.hc == 1: model.__setattr__("top_layer0", nn.Linear(4096, args.ncl)) model.top_layer = None model.headcount = args.hc+1 model.__setattr__("top_layer%s" % args.hc, nn.Linear(4096, 4)) else: if args.hc == 1: model.__setattr__("top_layer0", nn.Linear(2048*int(args.archspec), args.ncl)) model.top_layer = None model.headcount = args.hc+1 model.__setattr__("top_layer%s" % args.hc, nn.Linear(2048*int(args.archspec), 4)) if args.init: for mod in model.modules(): mod.apply(weight_init) # Setup optimizer o = Optimizer() o.writer = writer o.lr = args.lr o.num_epochs = args.epochs o.resume = True o.log_interval = args.log_interval o.checkpoint_dir = os.path.join(args.exp, 'checkpoints') # Optimize o.optimize(model, train_loader)
44.369338
154
0.569185
0ed057bb216be080ba95c6d1f2a7ce1ab1dfd4f5
1,341
py
Python
tests/vie.py
Jinwithyoo/han
931a271e56134dcc35029bf75260513b60884f6c
[ "BSD-3-Clause" ]
null
null
null
tests/vie.py
Jinwithyoo/han
931a271e56134dcc35029bf75260513b60884f6c
[ "BSD-3-Clause" ]
null
null
null
tests/vie.py
Jinwithyoo/han
931a271e56134dcc35029bf75260513b60884f6c
[ "BSD-3-Clause" ]
null
null
null
# -*- coding: utf-8 -*- from tests import HangulizeTestCase from hangulize.langs.vie import Vietnamese
24.833333
69
0.463833
0ed0e5f6ef98dbca0fc996f3f87ca29e7cb4b7a2
1,054
py
Python
tests/test_functions/test_trig.py
jackromo/mathLibPy
b80badd293b93da85aaf122c3d3da022f6dab361
[ "MIT" ]
1
2020-06-09T05:43:33.000Z
2020-06-09T05:43:33.000Z
tests/test_functions/test_trig.py
jackromo/mathLibPy
b80badd293b93da85aaf122c3d3da022f6dab361
[ "MIT" ]
15
2016-03-06T17:10:40.000Z
2016-05-28T14:06:16.000Z
tests/test_functions/test_trig.py
jackromo/mathLibPy
b80badd293b93da85aaf122c3d3da022f6dab361
[ "MIT" ]
null
null
null
from mathlibpy.functions import * import unittest if __name__ == "__main__": unittest.main()
20.269231
66
0.63852
0ed195167a4ca32696adae9b1a096d1817a006fd
639
py
Python
src/smallestLetter/target.py
rajitbanerjee/leetcode
720fcdd88d371e2d6592ceec8370a6760a77bb89
[ "CC0-1.0" ]
null
null
null
src/smallestLetter/target.py
rajitbanerjee/leetcode
720fcdd88d371e2d6592ceec8370a6760a77bb89
[ "CC0-1.0" ]
null
null
null
src/smallestLetter/target.py
rajitbanerjee/leetcode
720fcdd88d371e2d6592ceec8370a6760a77bb89
[ "CC0-1.0" ]
1
2021-04-28T18:17:55.000Z
2021-04-28T18:17:55.000Z
if __name__ == '__main__': letters = ["c", "f", "j"] target = "a" print(f"Input: letters = {letters}, target = {target}") print(f"Output: {Solution().nextGreatestLetter(letters, target)}")
31.95
70
0.528951
0ed3370d325b05dcd0ff4ac3d8d74980237e624c
1,004
py
Python
anti_cpdaily/command.py
hyx0329/nonebot_plugin_anti_cpdaily
5868626fb95876f9638aaa1edd9a2f914ea7bed1
[ "MIT" ]
2
2021-11-07T10:33:16.000Z
2021-12-20T08:25:19.000Z
anti_cpdaily/command.py
hyx0329/nonebot_plugin_anti_cpdaily
5868626fb95876f9638aaa1edd9a2f914ea7bed1
[ "MIT" ]
null
null
null
anti_cpdaily/command.py
hyx0329/nonebot_plugin_anti_cpdaily
5868626fb95876f9638aaa1edd9a2f914ea7bed1
[ "MIT" ]
null
null
null
import nonebot from nonebot import on_command from nonebot.rule import to_me from nonebot.typing import T_State from nonebot.adapters import Bot, Event from nonebot.log import logger from .config import global_config from .schedule import anti_cpdaily_check_routine cpdaily = on_command('cpdaily') scheduler = nonebot.require("nonebot_plugin_apscheduler").scheduler
32.387097
124
0.76494
0ed367645577a295c7ca8d2261bca85d6a1facb8
978
py
Python
matplotlib/gallery_python/pyplots/dollar_ticks.py
gottaegbert/penter
8cbb6be3c4bf67c7c69fa70e597bfbc3be4f0a2d
[ "MIT" ]
13
2020-01-04T07:37:38.000Z
2021-08-31T05:19:58.000Z
matplotlib/gallery_python/pyplots/dollar_ticks.py
gottaegbert/penter
8cbb6be3c4bf67c7c69fa70e597bfbc3be4f0a2d
[ "MIT" ]
3
2020-06-05T22:42:53.000Z
2020-08-24T07:18:54.000Z
matplotlib/gallery_python/pyplots/dollar_ticks.py
gottaegbert/penter
8cbb6be3c4bf67c7c69fa70e597bfbc3be4f0a2d
[ "MIT" ]
9
2020-10-19T04:53:06.000Z
2021-08-31T05:20:01.000Z
""" ============ Dollar Ticks ============ Use a `~.ticker.FormatStrFormatter` to prepend dollar signs on y axis labels. """ import numpy as np import matplotlib.pyplot as plt import matplotlib.ticker as ticker # Fixing random state for reproducibility np.random.seed(19680801) fig, ax = plt.subplots() ax.plot(100*np.random.rand(20)) formatter = ticker.FormatStrFormatter('$%1.2f') ax.yaxis.set_major_formatter(formatter) for tick in ax.yaxis.get_major_ticks(): tick.label1.set_visible(False) tick.label2.set_visible(True) tick.label2.set_color('green') plt.show() ############################################################################# # # ------------ # # References # """""""""" # # The use of the following functions, methods, classes and modules is shown # in this example: import matplotlib matplotlib.ticker matplotlib.ticker.FormatStrFormatter matplotlib.axis.Axis.set_major_formatter matplotlib.axis.Axis.get_major_ticks matplotlib.axis.Tick
22.227273
77
0.673824
0ed3c5718d5548ba82fc7cde7bd8e347ef468e10
6,746
py
Python
Chibrary/utils.py
chiro2001/chibrary
da31ef80df394cfb260fbe2c1e675f28717fea3e
[ "MIT" ]
null
null
null
Chibrary/utils.py
chiro2001/chibrary
da31ef80df394cfb260fbe2c1e675f28717fea3e
[ "MIT" ]
null
null
null
Chibrary/utils.py
chiro2001/chibrary
da31ef80df394cfb260fbe2c1e675f28717fea3e
[ "MIT" ]
1
2021-09-21T16:40:58.000Z
2021-09-21T16:40:58.000Z
import json import re from flask import request, abort, jsonify from Chibrary import config from Chibrary.config import logger from Chibrary.exceptions import * from functools import wraps from urllib import parse from Chibrary.server import db """ { code: ..., message: ..., data: ..., } """ # headerAuthorization: {token} # headerAuthorization: {token} # request # def url_check(url: str): # url = url.lower() # reg = "^(https|http|ftp|rtsp|mms)\\://?([a-zA-Z0-9\\.\\-]+(\\:[a-zA-Z0-9\\.&%\\$\\-]+)*@)?((25[0-5]|2" \ # "[0-4][0-9]|[0-1]{1}[0-9]{2}|[1-9]{1}[0-9]{1}|[1-9])\\.(25[0-5]|2[0-4][0-9]|[0-1]{1}[0-9]{2}|[1-9]" \ # "{1}[0-9]{1}|[1-9]|0)\\.(25[0-5]|2[0-4][0-9]|[0-1]{1}[0-9]{2}|[1-9]{1}[0-9]{1}|[1-9]|0)\\.(25[0-5]|" \ # "2[0-4][0-9]|[0-1]{1}[0-9]{2}|[1-9]{1}[0-9]{1}|[0-9])|([a-zA-Z0-9\\-]+\\.)*[a-zA-Z0-9\\-]+\\.[a-zA-Z]" \ # "{2,4})(\\:[0-9]+)?(/[^/][a-zA-Z0-9\\.\\,\\?\\'\\\\/\\+&%\\$\\=~_\\-@]*)*$" # print(re.search(url, reg)) if __name__ == '__main__': print(parse_url_query('http://blog.com/sss/ssss/s?wd=dsfa&a=fdsa&a=1&b=1.1&a=s')) print(format_file_size(20250000)) # print(url_check('http://www.bilibili.com/'))
28.82906
116
0.554996
0ed495b3d64a671dbd7202470a06b2b18d6c7be4
155
py
Python
tests/inputs/loops/51-arrays-in-loop.py
helq/pytropos
497ed5902e6e4912249ca0a46b477f9bfa6ae80a
[ "MIT" ]
4
2019-10-06T18:01:24.000Z
2020-07-03T05:27:35.000Z
tests/inputs/loops/51-arrays-in-loop.py
helq/pytropos
497ed5902e6e4912249ca0a46b477f9bfa6ae80a
[ "MIT" ]
5
2021-06-07T15:50:04.000Z
2021-06-07T15:50:06.000Z
tests/inputs/loops/51-arrays-in-loop.py
helq/pytropos
497ed5902e6e4912249ca0a46b477f9bfa6ae80a
[ "MIT" ]
null
null
null
import numpy as np from something import Top i = 0 while i < 10: a = np.ndarray((10,4)) b = np.ones((10, Top)) i += 1 del Top # show_store()
12.916667
26
0.580645
0ed4e33e928545ea0125662f34b75db4ebefd622
897
py
Python
tests/mappers/fields/test_float_field.py
Arfey/aiohttp_admin2
2b3782389ec9e25809635811b76ef8111b27d8ba
[ "MIT" ]
12
2021-10-15T11:48:12.000Z
2022-03-24T07:31:43.000Z
tests/mappers/fields/test_float_field.py
Arfey/aiohttp_admin2
2b3782389ec9e25809635811b76ef8111b27d8ba
[ "MIT" ]
2
2021-12-29T16:31:05.000Z
2021-12-30T00:50:40.000Z
tests/mappers/fields/test_float_field.py
Arfey/aiohttp_admin2
2b3782389ec9e25809635811b76ef8111b27d8ba
[ "MIT" ]
null
null
null
from aiohttp_admin2.mappers import Mapper from aiohttp_admin2.mappers import fields def test_correct_float_type(): """ In this test we check success convert to float type. """ mapper = FloatMapper({"field": 1}) mapper.is_valid() assert mapper.data["field"] == 1.0 mapper = FloatMapper({"field": 2}) mapper.is_valid() assert mapper.data["field"] == 2.0 mapper = FloatMapper({"field": -3}) mapper.is_valid() assert mapper.data["field"] == -3.0 mapper = FloatMapper({"field": 0}) mapper.is_valid() assert mapper.data["field"] == 0.0 def test_wrong_float_type(): """ In this test we check error when we received wrong float type. """ assert FloatMapper({"field": "string"}).is_valid() is False assert FloatMapper({"field": []}).is_valid() is False
21.878049
66
0.645485
0ed5587a827c8b8f54d7f90abf4042432f650675
1,163
py
Python
autotest/t038_test.py
jdlarsen-UA/flopy
bf2c59aaa689de186bd4c80685532802ac7149cd
[ "CC0-1.0", "BSD-3-Clause" ]
2
2021-09-06T01:08:58.000Z
2021-09-06T06:02:15.000Z
autotest/t038_test.py
jdlarsen-UA/flopy
bf2c59aaa689de186bd4c80685532802ac7149cd
[ "CC0-1.0", "BSD-3-Clause" ]
null
null
null
autotest/t038_test.py
jdlarsen-UA/flopy
bf2c59aaa689de186bd4c80685532802ac7149cd
[ "CC0-1.0", "BSD-3-Clause" ]
null
null
null
""" Try to load all of the MODFLOW-USG examples in ../examples/data/mfusg_test. These are the examples that are distributed with MODFLOW-USG. """ import os import flopy # make the working directory tpth = os.path.join("temp", "t038") if not os.path.isdir(tpth): os.makedirs(tpth) # build list of name files to try and load usgpth = os.path.join("..", "examples", "data", "mfusg_test") usg_files = [] for path, subdirs, files in os.walk(usgpth): for name in files: if name.endswith(".nam"): usg_files.append(os.path.join(path, name)) # # function to load a MODFLOW-USG model and then write it back out def load_model(namfile, model_ws): m = flopy.modflow.Modflow.load( namfile, model_ws=model_ws, version="mfusg", verbose=True, check=False ) assert m, f"Could not load namefile {namfile}" assert m.load_fail is False m.change_model_ws(tpth) m.write_input() return if __name__ == "__main__": for fusg in usg_files: d, f = os.path.split(fusg) load_model(f, d)
25.844444
78
0.663801
0ed56ff83d82e72563699b9ea8ce0b02dcd84908
999
py
Python
botlib/cli.py
relikd/botlib
d0c5072d27db1aa3fad432457c90c9e3f23f22cc
[ "MIT" ]
null
null
null
botlib/cli.py
relikd/botlib
d0c5072d27db1aa3fad432457c90c9e3f23f22cc
[ "MIT" ]
null
null
null
botlib/cli.py
relikd/botlib
d0c5072d27db1aa3fad432457c90c9e3f23f22cc
[ "MIT" ]
null
null
null
#!/usr/bin/env python3 import os from argparse import ArgumentParser, ArgumentTypeError, FileType, Namespace from typing import Any
31.21875
75
0.640641
0ed9a8ae3cb2f6c51bd79bc87c61d261f1d3fcce
3,488
py
Python
pyhanko_certvalidator/asn1_types.py
MatthiasValvekens/certvalidator
246c5075ecdb6d50b14c93fdc97a9d0470f84821
[ "MIT" ]
4
2020-11-11T13:59:05.000Z
2022-03-13T14:06:10.000Z
pyhanko_certvalidator/asn1_types.py
MatthiasValvekens/certvalidator
246c5075ecdb6d50b14c93fdc97a9d0470f84821
[ "MIT" ]
1
2020-11-11T11:29:37.000Z
2020-11-11T11:29:37.000Z
pyhanko_certvalidator/asn1_types.py
MatthiasValvekens/certvalidator
246c5075ecdb6d50b14c93fdc97a9d0470f84821
[ "MIT" ]
2
2020-11-11T10:33:32.000Z
2022-03-13T14:06:11.000Z
from typing import Optional from asn1crypto import core, x509, cms __all__ = [ 'Target', 'TargetCert', 'Targets', 'SequenceOfTargets', 'AttrSpec', 'AAControls' ] # Blame X.509... def _make_tag_explicit(field_decl): tag_dict = field_decl[2] if 'explicit' in tag_dict: return tag_dict['explicit'] = tag_dict['implicit'] del tag_dict['implicit'] def _make_tag_implicit(field_decl): tag_dict = field_decl[2] if 'implicit' in tag_dict: return tag_dict['implicit'] = tag_dict['explicit'] del tag_dict['explicit'] # Deal with wbond/asn1crypto#218 _make_tag_explicit(cms.RoleSyntax._fields[1]) _make_tag_explicit(cms.SecurityCategory._fields[1]) # Deal with wbond/asn1crypto#220 _make_tag_implicit(cms.AttCertIssuer._alternatives[1]) # patch in attribute certificate extensions # Note: unlike in Certomancer, we don't do this one conditionally, since # we need the actual Python types to agree with what we export ext_map = x509.ExtensionId._map ext_specs = x509.Extension._oid_specs ext_map['2.5.29.55'] = 'target_information' ext_specs['target_information'] = SequenceOfTargets ext_map['2.5.29.56'] = 'no_rev_avail' ext_specs['no_rev_avail'] = core.Null ext_map['1.3.6.1.5.5.7.1.6'] = 'aa_controls' ext_specs['aa_controls'] = AAControls ext_map['1.3.6.1.5.5.7.1.4'] = 'audit_identity' ext_specs['audit_identity'] = core.OctetString
30.068966
73
0.663417
0ed9b178770e9775a60fa8ee66730cd786425565
448
py
Python
test/test_delete_group.py
ruslankl9/ironpython_training
51eaad4da24fdce60fbafee556160a9e847c08cf
[ "Apache-2.0" ]
null
null
null
test/test_delete_group.py
ruslankl9/ironpython_training
51eaad4da24fdce60fbafee556160a9e847c08cf
[ "Apache-2.0" ]
null
null
null
test/test_delete_group.py
ruslankl9/ironpython_training
51eaad4da24fdce60fbafee556160a9e847c08cf
[ "Apache-2.0" ]
null
null
null
from model.group import Group import random
32
51
0.712054
0ed9d9ea2d863109661ee50e679a897b97a003a9
3,173
py
Python
Evaluation/batch_detection.py
gurkirt/actNet-inAct
1930bcb41553e50ddd83985a497a9d5ce4f1fcf2
[ "MIT" ]
27
2016-05-04T07:13:05.000Z
2021-12-05T04:45:45.000Z
Evaluation/batch_detection.py
gurkirt/actNet-inAct
1930bcb41553e50ddd83985a497a9d5ce4f1fcf2
[ "MIT" ]
1
2017-12-28T08:29:00.000Z
2017-12-28T08:29:00.000Z
Evaluation/batch_detection.py
gurkirt/actNet-inAct
1930bcb41553e50ddd83985a497a9d5ce4f1fcf2
[ "MIT" ]
12
2016-05-15T21:40:06.000Z
2019-11-27T09:43:55.000Z
''' Autor: Gurkirt Singh Start data: 15th May 2016 purpose: of this file is read frame level predictions and process them to produce a label per video ''' from sklearn.svm import LinearSVC from sklearn.ensemble import RandomForestClassifier import numpy as np import pickle import os import time,json import pylab as plt from eval_detection import ANETdetection import scipy.io as sio #######baseDir = "/mnt/sun-alpha/actnet/"; baseDir = "/data/shared/solar-machines/actnet/"; #baseDir = "/mnt/solar-machines/actnet/"; ########imgDir = "/mnt/sun-alpha/actnet/rgb-images/"; ######## imgDir = "/mnt/DATADISK2/ss-workspace/actnet/rgb-images/"; annotPklFile = "../Evaluation/data/actNet200-V1-3.pkl" if __name__=="__main__": #processOnePredictions() # saveAps() # plotmAPs() evalALL()
36.056818
157
0.627167
0eda0495743701a807a727479d2ba40e2e1b5552
910
py
Python
python/csv/csv_dict_writer.py
y2ghost/study
c5278611b0a732fe19e3d805c0c079e530b1d3b2
[ "MIT" ]
null
null
null
python/csv/csv_dict_writer.py
y2ghost/study
c5278611b0a732fe19e3d805c0c079e530b1d3b2
[ "MIT" ]
null
null
null
python/csv/csv_dict_writer.py
y2ghost/study
c5278611b0a732fe19e3d805c0c079e530b1d3b2
[ "MIT" ]
null
null
null
import csv if __name__ == '__main__': data = '''book_title,author,publisher,pub_date,isbn Python 101,Mike Driscoll, Mike Driscoll,2020,123456789 wxPython Recipes,Mike Driscoll,Apress,2018,978-1-4842-3237-8 Python Interviews,Mike Driscoll,Packt Publishing,2018,9781788399081''' records = [] for line in data.splitlines(): records.append(line.strip().split(',')) headers = records.pop(0) list_of_dicts = [] for row in records: my_dict = dict(zip(headers, row)) list_of_dicts.append(my_dict) csv_dict_writer('output_dict.csv', headers, list_of_dicts)
31.37931
74
0.650549
0eda1b4f399b44a556364cedf6c955fb55a3872c
2,355
py
Python
src/decisionengine/framework/modules/tests/test_module_decorators.py
moibenko/decisionengine
4c458e0c225ec2ce1e82d56e752724983331b7d1
[ "Apache-2.0" ]
9
2018-06-11T20:06:50.000Z
2020-10-01T17:02:02.000Z
src/decisionengine/framework/modules/tests/test_module_decorators.py
moibenko/decisionengine
4c458e0c225ec2ce1e82d56e752724983331b7d1
[ "Apache-2.0" ]
551
2018-06-25T21:06:37.000Z
2022-03-31T13:47:32.000Z
src/decisionengine/framework/modules/tests/test_module_decorators.py
goodenou/decisionengine
b203e2c493cf501562accf1013c6257c348711b7
[ "Apache-2.0" ]
70
2018-06-11T20:07:01.000Z
2022-02-10T16:18:24.000Z
# SPDX-FileCopyrightText: 2017 Fermi Research Alliance, LLC # SPDX-License-Identifier: Apache-2.0 import pytest from decisionengine.framework.modules import Publisher, Source from decisionengine.framework.modules.Module import verify_products from decisionengine.framework.modules.Source import Parameter
31.4
113
0.656476
0edaae48c98ecfaf21b42f1bc713fce970f11754
1,687
py
Python
models/cnn_layer.py
RobinRojowiec/intent-recognition-in-doctor-patient-interviews
b91c7a9f3ad70edd0f39b56e3219f48d1fcf2078
[ "Apache-2.0" ]
null
null
null
models/cnn_layer.py
RobinRojowiec/intent-recognition-in-doctor-patient-interviews
b91c7a9f3ad70edd0f39b56e3219f48d1fcf2078
[ "Apache-2.0" ]
null
null
null
models/cnn_layer.py
RobinRojowiec/intent-recognition-in-doctor-patient-interviews
b91c7a9f3ad70edd0f39b56e3219f48d1fcf2078
[ "Apache-2.0" ]
1
2021-11-24T18:48:47.000Z
2021-11-24T18:48:47.000Z
import torch import torch.nn as nn from torch.nn.functional import max_pool1d from utility.model_parameter import Configuration, ModelParameter
37.488889
109
0.670421
0edc64834d9ac7d861217e389cda5a4bf52a203f
1,129
py
Python
musicscore/musicxml/types/complextypes/backup.py
alexgorji/music_score
b4176da52295361f3436826903485c5cb8054c5e
[ "MIT" ]
2
2020-06-22T13:33:28.000Z
2020-12-30T15:09:00.000Z
musicscore/musicxml/types/complextypes/backup.py
alexgorji/music_score
b4176da52295361f3436826903485c5cb8054c5e
[ "MIT" ]
37
2020-02-18T12:15:00.000Z
2021-12-13T20:01:14.000Z
musicscore/musicxml/types/complextypes/backup.py
alexgorji/music_score
b4176da52295361f3436826903485c5cb8054c5e
[ "MIT" ]
null
null
null
''' <xs:complexType name="backup"> <xs:annotation> <xs:documentation></xs:documentation> </xs:annotation> <xs:sequence> <xs:group ref="duration"/> <xs:group ref="editorial"/> </xs:sequence> </xs:complexType> ''' from musicscore.dtd.dtd import Sequence, GroupReference, Element from musicscore.musicxml.groups.common import Editorial from musicscore.musicxml.elements.note import Duration from musicscore.musicxml.types.complextypes.complextype import ComplexType
35.28125
119
0.732507
0edcbb01b3b82f3bf4be9564d133e3829ce06411
4,429
py
Python
NLP programmes in Python/9.Text Clustering/kmeans.py
AlexandrosPlessias/NLP-Greek-Presentations
4ae9d635a777f24bae5238b9f195bd17d00040ea
[ "MIT" ]
null
null
null
NLP programmes in Python/9.Text Clustering/kmeans.py
AlexandrosPlessias/NLP-Greek-Presentations
4ae9d635a777f24bae5238b9f195bd17d00040ea
[ "MIT" ]
null
null
null
NLP programmes in Python/9.Text Clustering/kmeans.py
AlexandrosPlessias/NLP-Greek-Presentations
4ae9d635a777f24bae5238b9f195bd17d00040ea
[ "MIT" ]
null
null
null
import nltk import re import csv import string import collections import numpy as np from nltk.corpus import wordnet from nltk.corpus import stopwords from nltk.stem import WordNetLemmatizer from nltk.tokenize import WordPunctTokenizer from sklearn.metrics import classification_report from sklearn.metrics import confusion_matrix """"Pre - Processing: tokenization, stopwords removal, remove words(with size 1), lower capitalization & lemmatization""" """"Read Data""" # Open sms corpus. sms_file = open('SMSSpamCollection.txt', encoding="utf8") # Check the structure of this file! sms_data = [] sms_labels = [] # CSV Reader LABEL & DATA are separated by TAB. csv_reader = csv.reader(sms_file,delimiter='\t') # Store labels and data. for line in csv_reader: sms_text = preprocessing(line[1]) if ( sms_text != None): # adding the sms_id sms_labels.append( line[0]) # adding the cleaned text We are calling preprocessing method sms_data.append(sms_text) sms_file.close() """Sampling steps (70:30)""" trainset_size = int(round(len(sms_data)*0.70)) # I chose this threshold for 70:30 train and test split. print('The training set size for this classifier is ' + str(trainset_size) + '\n') x_train = np.array([''.join(el) for el in sms_data[0:trainset_size]]) # train sms_data (70%). y_train = np.array([el for el in sms_labels[0:trainset_size]]) # train sms_labels (70%). x_test = np.array([''.join(el) for el in sms_data[trainset_size+1:len(sms_data)]]) # test sms_data (30%). y_test = np.array([el for el in sms_labels[trainset_size+1:len(sms_labels)]]) # test sms_labels (30%). """We are building a TFIDF vectorizer here""" from sklearn.feature_extraction.text import TfidfVectorizer vectorizer = TfidfVectorizer(min_df=2, ngram_range=(1, 2), stop_words='english', strip_accents='unicode', norm='l2') X_train = vectorizer.fit_transform(x_train) X_test = vectorizer.transform(x_test) """Text Clustering - K Means""" from sklearn.cluster import KMeans, MiniBatchKMeans print('--> Text Clustering - K Means') true_k = 5 km = KMeans(n_clusters=true_k, init='k-means++', max_iter=100, n_init=1) kmini = MiniBatchKMeans(n_clusters=true_k, init='k-means++', n_init=1, init_size=1000, batch_size=1000, verbose=False) #verbose=opts.verbose # we are using the same test,train data in TFIDF form as we did in text classification km_model = km.fit(X_train) print("For K-mean clustering ") clustering = collections.defaultdict(list) for idx, label in enumerate(km_model.labels_): clustering[label].append(idx) print(clustering) kmini_model = kmini.fit(X_train) print("For K-mean Mini batch clustering ") clustering = collections.defaultdict(list) for idx, label in enumerate(kmini_model.labels_): clustering[label].append(idx) print(clustering)
34.069231
141
0.685482
0edd17d0b784bbe0102b923ddf6f8c3e0cea3855
7,304
py
Python
common/utils.py
paTRICK-swk/P-STMO
def1bff3fcc4f1e3b1dd69c8d3c2d77f412e3b75
[ "MIT" ]
8
2022-03-16T02:55:45.000Z
2022-03-31T08:29:05.000Z
common/utils.py
paTRICK-swk/P-STMO
def1bff3fcc4f1e3b1dd69c8d3c2d77f412e3b75
[ "MIT" ]
2
2022-03-24T23:29:23.000Z
2022-03-31T02:59:39.000Z
common/utils.py
paTRICK-swk/P-STMO
def1bff3fcc4f1e3b1dd69c8d3c2d77f412e3b75
[ "MIT" ]
null
null
null
import torch import numpy as np import hashlib from torch.autograd import Variable import os
32.035088
118
0.607065
0edda9355db51eae6f5202748937966f72f31878
1,362
py
Python
personal_ad/advice/converter.py
Sailer43/CSE5914Project
ebb47bff9a6101fac5173b5520e6002563da67d5
[ "MIT" ]
null
null
null
personal_ad/advice/converter.py
Sailer43/CSE5914Project
ebb47bff9a6101fac5173b5520e6002563da67d5
[ "MIT" ]
1
2019-10-15T21:48:27.000Z
2019-10-15T21:48:27.000Z
personal_ad/advice/converter.py
Sailer43/CSE5914Project
ebb47bff9a6101fac5173b5520e6002563da67d5
[ "MIT" ]
null
null
null
from ibm_watson import TextToSpeechV1, SpeechToTextV1, DetailedResponse from os import system from json import loads if __name__ == '__main__': main()
30.954545
84
0.679883
0eddc7235cfdc03253ec66ce28f34006def0e26e
301
py
Python
warg_client/client/apis/controller/attack_controller.py
neel4os/warg-client
4d97904977a6f6865610afd04ca00ddfbad38ff9
[ "MIT" ]
null
null
null
warg_client/client/apis/controller/attack_controller.py
neel4os/warg-client
4d97904977a6f6865610afd04ca00ddfbad38ff9
[ "MIT" ]
null
null
null
warg_client/client/apis/controller/attack_controller.py
neel4os/warg-client
4d97904977a6f6865610afd04ca00ddfbad38ff9
[ "MIT" ]
null
null
null
from subprocess import run
23.153846
66
0.621262
0edddd954e6572bd2613d0926da19b7e62f01353
346
py
Python
torrents/migrations/0011_auto_20190223_2345.py
2600box/harvest
57264c15a3fba693b4b58d0b6d4fbf4bd5453bbd
[ "Apache-2.0" ]
9
2019-03-26T14:50:00.000Z
2020-11-10T16:44:08.000Z
torrents/migrations/0011_auto_20190223_2345.py
2600box/harvest
57264c15a3fba693b4b58d0b6d4fbf4bd5453bbd
[ "Apache-2.0" ]
22
2019-03-02T23:16:13.000Z
2022-02-27T10:36:36.000Z
torrents/migrations/0011_auto_20190223_2345.py
2600box/harvest
57264c15a3fba693b4b58d0b6d4fbf4bd5453bbd
[ "Apache-2.0" ]
5
2019-04-24T00:51:30.000Z
2020-11-06T18:31:49.000Z
# Generated by Django 2.1.7 on 2019-02-23 23:45 from django.db import migrations
19.222222
48
0.586705
0ede1b7c3e14b744474c60d6f5f4a702ad5ce8ca
281
py
Python
common/__init__.py
whyh/FavourDemo
1b19882fb2e79dee9c3332594bf45c91e7476eaa
[ "Unlicense" ]
1
2020-09-14T12:10:22.000Z
2020-09-14T12:10:22.000Z
common/__init__.py
whyh/FavourDemo
1b19882fb2e79dee9c3332594bf45c91e7476eaa
[ "Unlicense" ]
4
2021-04-30T20:54:31.000Z
2021-06-02T00:28:04.000Z
common/__init__.py
whyh/FavourDemo
1b19882fb2e79dee9c3332594bf45c91e7476eaa
[ "Unlicense" ]
null
null
null
from . import (emoji as emj, keyboards as kb, telegram as tg, phrases as phr, finance as fin, utils, glossary, bots, gcp, sed, db)
23.416667
31
0.33452
0ee18d6b7b8309b3efbe99ae9ad5cbadde515b83
1,136
py
Python
questions/serializers.py
aneumeier/questions
fe5451b70d85cd5203b4cb624103c1eb154587d9
[ "BSD-3-Clause" ]
null
null
null
questions/serializers.py
aneumeier/questions
fe5451b70d85cd5203b4cb624103c1eb154587d9
[ "BSD-3-Clause" ]
null
null
null
questions/serializers.py
aneumeier/questions
fe5451b70d85cd5203b4cb624103c1eb154587d9
[ "BSD-3-Clause" ]
null
null
null
#!/usr/bin/env python # -*- coding: utf-8 """ :mod:`question.serializers` -- serializers """ from rest_framework import serializers from .models import Question, PossibleAnswer from category.models import Category
21.846154
63
0.588028
0ee18e4216ec08fa76991908f8a448c6f9b7427c
2,147
py
Python
widgets/ui_ShowResultDialog.py
JaySon-Huang/SecertPhotos
e741cc26c19a5b249d45cc70959ac6817196cb8a
[ "MIT" ]
null
null
null
widgets/ui_ShowResultDialog.py
JaySon-Huang/SecertPhotos
e741cc26c19a5b249d45cc70959ac6817196cb8a
[ "MIT" ]
3
2015-05-19T08:43:46.000Z
2015-06-10T17:55:28.000Z
widgets/ui_ShowResultDialog.py
JaySon-Huang/SecertPhotos
e741cc26c19a5b249d45cc70959ac6817196cb8a
[ "MIT" ]
null
null
null
# -*- coding: utf-8 -*- # Form implementation generated from reading ui file 'src/ui_ShowResultDialog.ui' # # Created: Sat May 16 17:05:43 2015 # by: PyQt5 UI code generator 5.4 # # WARNING! All changes made in this file will be lost! from PyQt5 import QtCore, QtGui, QtWidgets from widgets.ImageLabel import ImageLabel
43.816327
115
0.72054
0ee1c1606231abe837f3edc4544d4485e01f3d4a
6,484
py
Python
mixcoatl/admin/api_key.py
zomGreg/mixcoatl
dd8d7e206682955b251d7f858fffee56b11df8c6
[ "Apache-2.0" ]
null
null
null
mixcoatl/admin/api_key.py
zomGreg/mixcoatl
dd8d7e206682955b251d7f858fffee56b11df8c6
[ "Apache-2.0" ]
null
null
null
mixcoatl/admin/api_key.py
zomGreg/mixcoatl
dd8d7e206682955b251d7f858fffee56b11df8c6
[ "Apache-2.0" ]
null
null
null
""" mixcoatl.admin.api_key ---------------------- Implements access to the DCM ApiKey API """ from mixcoatl.resource import Resource from mixcoatl.decorators.lazy import lazy_property from mixcoatl.decorators.validations import required_attrs from mixcoatl.utils import uncamel, camelize, camel_keys, uncamel_keys import json
31.173077
105
0.610734
0ee1c3866e5f2d77866339896a7b340616b1337d
414
py
Python
Python tests/dictionaries.py
Johnny-QA/Python_training
a15de68195eb155c99731db3e4ff1d9d75681752
[ "Apache-2.0" ]
null
null
null
Python tests/dictionaries.py
Johnny-QA/Python_training
a15de68195eb155c99731db3e4ff1d9d75681752
[ "Apache-2.0" ]
null
null
null
Python tests/dictionaries.py
Johnny-QA/Python_training
a15de68195eb155c99731db3e4ff1d9d75681752
[ "Apache-2.0" ]
null
null
null
my_set = {1, 3, 5} my_dict = {'name': 'Jose', 'age': 90} another_dict = {1: 15, 2: 75, 3: 150} lottery_players = [ { 'name': 'Rolf', 'numbers': (13, 45, 66, 23, 22) }, { 'name': 'John', 'numbers': (14, 56, 80, 23, 22) } ] universities = [ { 'name': 'Oxford', 'location': 'UK' }, { 'name': 'MIT', 'location': 'US' } ]
16.56
39
0.398551
0ee3d5ffc425ea5928ae83711b91532c1603b60f
7,589
py
Python
psdaq/psdaq/control_gui/QWTable.py
ZhenghengLi/lcls2
94e75c6536954a58c8937595dcac295163aa1cdf
[ "BSD-3-Clause-LBNL" ]
16
2017-11-09T17:10:56.000Z
2022-03-09T23:03:10.000Z
psdaq/psdaq/control_gui/QWTable.py
ZhenghengLi/lcls2
94e75c6536954a58c8937595dcac295163aa1cdf
[ "BSD-3-Clause-LBNL" ]
6
2017-12-12T19:30:05.000Z
2020-07-09T00:28:33.000Z
psdaq/psdaq/control_gui/QWTable.py
ZhenghengLi/lcls2
94e75c6536954a58c8937595dcac295163aa1cdf
[ "BSD-3-Clause-LBNL" ]
25
2017-09-18T20:02:43.000Z
2022-03-27T22:27:42.000Z
"""Class :py:class:`QWTable` is a QTableView->QWidget for tree model ====================================================================== Usage :: # Run test: python lcls2/psdaq/psdaq/control_gui/QWTable.py from psdaq.control_gui.QWTable import QWTable w = QWTable() Created on 2019-03-28 by Mikhail Dubrovin Re-designed after copy psana/graphqt/QWTable.py -> psdaq/control_gui/ """ import logging logger = logging.getLogger(__name__) from PyQt5.QtWidgets import QTableView, QVBoxLayout, QAbstractItemView, QSizePolicy from PyQt5.QtGui import QStandardItemModel, QStandardItem from PyQt5.QtCore import Qt, QModelIndex from psdaq.control_gui.QWIcons import icon if __name__ == '__main__': import sys from PyQt5.QtWidgets import QApplication logging.basicConfig(format='%(asctime)s %(name)s %(levelname)s: %(message)s', datefmt='%H:%M:%S', level=logging.DEBUG) app = QApplication(sys.argv) w = QWTable() #w.setGeometry(100, 100, 700, 300) w.setWindowTitle('QWTable') w.move(100,50) w.show() app.exec_() del w del app # EOF
32.431624
122
0.644617
0ee3f4cb54a20c54630494d1b68aa8ef7ce66afa
1,948
py
Python
src/grailbase/mtloader.py
vadmium/grailbrowser
ca94e6db2359bcb16c0da256771550d1327c6d33
[ "CNRI-Python", "CNRI-Jython" ]
9
2015-03-23T23:21:42.000Z
2021-08-01T01:47:22.000Z
src/grailbase/mtloader.py
vadmium/grailbrowser
ca94e6db2359bcb16c0da256771550d1327c6d33
[ "CNRI-Python", "CNRI-Jython" ]
null
null
null
src/grailbase/mtloader.py
vadmium/grailbrowser
ca94e6db2359bcb16c0da256771550d1327c6d33
[ "CNRI-Python", "CNRI-Jython" ]
11
2015-03-23T23:22:22.000Z
2020-06-08T14:24:17.000Z
"""Extension loader for filetype handlers. The extension objects provided by MIMEExtensionLoader objects have four attributes: parse, embed, add_options, and update_options. The first two are used as handlers for supporting the MIME type as primary and embeded resources. The last two are (currently) only used for printing. """ __version__ = '$Revision: 2.4 $' from . import extloader import string
31.934426
77
0.602669
0ee482f843ff11fa45eb748eba4af3c343f6b618
38,737
py
Python
eventstreams_sdk/adminrest_v1.py
IBM/eventstreams-python-sdk
cc898e6901c35d1b43e2be7d152c6d770d967b23
[ "Apache-2.0" ]
2
2021-05-06T10:18:21.000Z
2021-09-17T05:19:57.000Z
eventstreams_sdk/eventstreams_sdk/adminrest_v1.py
IBM/eventstreams-python-sdk
cc898e6901c35d1b43e2be7d152c6d770d967b23
[ "Apache-2.0" ]
1
2021-03-16T17:08:20.000Z
2021-03-18T18:13:49.000Z
eventstreams_sdk/eventstreams_sdk/adminrest_v1.py
IBM/eventstreams-python-sdk
cc898e6901c35d1b43e2be7d152c6d770d967b23
[ "Apache-2.0" ]
null
null
null
# coding: utf-8 # (C) Copyright IBM Corp. 2021. # # 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. # IBM OpenAPI SDK Code Generator Version: 3.25.0-2b3f843a-20210115-164628 """ The administration REST API for IBM Event Streams on Cloud. """ from typing import Dict, List import json from ibm_cloud_sdk_core import BaseService, DetailedResponse from ibm_cloud_sdk_core.authenticators.authenticator import Authenticator from ibm_cloud_sdk_core.get_authenticator import get_authenticator_from_environment from ibm_cloud_sdk_core.utils import convert_model from .common import get_sdk_headers ############################################################################## # Service ############################################################################## ############################################################################## # Models ############################################################################## def _to_dict(self): """Return a json dictionary representing this model.""" return self.to_dict() def __str__(self) -> str: """Return a `str` version of this ReplicaAssignmentBrokers object.""" return json.dumps(self.to_dict(), indent=2) def __eq__(self, other: 'ReplicaAssignmentBrokers') -> bool: """Return `true` when self and other are equal, false otherwise.""" if not isinstance(other, self.__class__): return False return self.__dict__ == other.__dict__ def __ne__(self, other: 'ReplicaAssignmentBrokers') -> bool: """Return `true` when self and other are not equal, false otherwise.""" return not self == other class ConfigCreate(): """ ConfigCreate. :attr str name: (optional) The name of the config property. :attr str value: (optional) The value for a config property. """ def __init__(self, *, name: str = None, value: str = None) -> None: """ Initialize a ConfigCreate object. :param str name: (optional) The name of the config property. :param str value: (optional) The value for a config property. """ self.name = name self.value = value def to_dict(self) -> Dict: """Return a json dictionary representing this model.""" _dict = {} if hasattr(self, 'name') and self.name is not None: _dict['name'] = self.name if hasattr(self, 'value') and self.value is not None: _dict['value'] = self.value return _dict def _to_dict(self): """Return a json dictionary representing this model.""" return self.to_dict() def __str__(self) -> str: """Return a `str` version of this ConfigCreate object.""" return json.dumps(self.to_dict(), indent=2) def __eq__(self, other: 'ConfigCreate') -> bool: """Return `true` when self and other are equal, false otherwise.""" if not isinstance(other, self.__class__): return False return self.__dict__ == other.__dict__ def __ne__(self, other: 'ConfigCreate') -> bool: """Return `true` when self and other are not equal, false otherwise.""" return not self == other class ConfigUpdate(): """ ConfigUpdate. :attr str name: (optional) The name of the config property. :attr str value: (optional) The value for a config property. :attr bool reset_to_default: (optional) When true, the value of the config property is reset to its default value. """ def __init__(self, *, name: str = None, value: str = None, reset_to_default: bool = None) -> None: """ Initialize a ConfigUpdate object. :param str name: (optional) The name of the config property. :param str value: (optional) The value for a config property. :param bool reset_to_default: (optional) When true, the value of the config property is reset to its default value. """ self.name = name self.value = value self.reset_to_default = reset_to_default def to_dict(self) -> Dict: """Return a json dictionary representing this model.""" _dict = {} if hasattr(self, 'name') and self.name is not None: _dict['name'] = self.name if hasattr(self, 'value') and self.value is not None: _dict['value'] = self.value if hasattr(self, 'reset_to_default') and self.reset_to_default is not None: _dict['reset_to_default'] = self.reset_to_default return _dict def _to_dict(self): """Return a json dictionary representing this model.""" return self.to_dict() def __str__(self) -> str: """Return a `str` version of this ConfigUpdate object.""" return json.dumps(self.to_dict(), indent=2) def __eq__(self, other: 'ConfigUpdate') -> bool: """Return `true` when self and other are equal, false otherwise.""" if not isinstance(other, self.__class__): return False return self.__dict__ == other.__dict__ def __ne__(self, other: 'ConfigUpdate') -> bool: """Return `true` when self and other are not equal, false otherwise.""" return not self == other class MirroringActiveTopics(): """ Topics that are being actively mirrored. :attr List[str] active_topics: (optional) """ def __init__(self, *, active_topics: List[str] = None) -> None: """ Initialize a MirroringActiveTopics object. :param List[str] active_topics: (optional) """ self.active_topics = active_topics def to_dict(self) -> Dict: """Return a json dictionary representing this model.""" _dict = {} if hasattr(self, 'active_topics') and self.active_topics is not None: _dict['active_topics'] = self.active_topics return _dict def _to_dict(self): """Return a json dictionary representing this model.""" return self.to_dict() def __str__(self) -> str: """Return a `str` version of this MirroringActiveTopics object.""" return json.dumps(self.to_dict(), indent=2) def __eq__(self, other: 'MirroringActiveTopics') -> bool: """Return `true` when self and other are equal, false otherwise.""" if not isinstance(other, self.__class__): return False return self.__dict__ == other.__dict__ def __ne__(self, other: 'MirroringActiveTopics') -> bool: """Return `true` when self and other are not equal, false otherwise.""" return not self == other class MirroringTopicSelection(): """ Mirroring topic selection payload. :attr List[str] includes: (optional) """ def __init__(self, *, includes: List[str] = None) -> None: """ Initialize a MirroringTopicSelection object. :param List[str] includes: (optional) """ self.includes = includes def to_dict(self) -> Dict: """Return a json dictionary representing this model.""" _dict = {} if hasattr(self, 'includes') and self.includes is not None: _dict['includes'] = self.includes return _dict def _to_dict(self): """Return a json dictionary representing this model.""" return self.to_dict() def __str__(self) -> str: """Return a `str` version of this MirroringTopicSelection object.""" return json.dumps(self.to_dict(), indent=2) def __eq__(self, other: 'MirroringTopicSelection') -> bool: """Return `true` when self and other are equal, false otherwise.""" if not isinstance(other, self.__class__): return False return self.__dict__ == other.__dict__ def __ne__(self, other: 'MirroringTopicSelection') -> bool: """Return `true` when self and other are not equal, false otherwise.""" return not self == other class ReplicaAssignment(): """ ReplicaAssignment. :attr int id: (optional) The ID of the partition. :attr ReplicaAssignmentBrokers brokers: (optional) """ def __init__(self, *, id: int = None, brokers: 'ReplicaAssignmentBrokers' = None) -> None: """ Initialize a ReplicaAssignment object. :param int id: (optional) The ID of the partition. :param ReplicaAssignmentBrokers brokers: (optional) """ self.id = id self.brokers = brokers def to_dict(self) -> Dict: """Return a json dictionary representing this model.""" _dict = {} if hasattr(self, 'id') and self.id is not None: _dict['id'] = self.id if hasattr(self, 'brokers') and self.brokers is not None: _dict['brokers'] = self.brokers.to_dict() return _dict def _to_dict(self): """Return a json dictionary representing this model.""" return self.to_dict() def __str__(self) -> str: """Return a `str` version of this ReplicaAssignment object.""" return json.dumps(self.to_dict(), indent=2) def __eq__(self, other: 'ReplicaAssignment') -> bool: """Return `true` when self and other are equal, false otherwise.""" if not isinstance(other, self.__class__): return False return self.__dict__ == other.__dict__ def __ne__(self, other: 'ReplicaAssignment') -> bool: """Return `true` when self and other are not equal, false otherwise.""" return not self == other class TopicConfigs(): """ TopicConfigs. :attr str cleanup_policy: (optional) The value of config property 'cleanup.policy'. :attr str min_insync_replicas: (optional) The value of config property 'min.insync.replicas'. :attr str retention_bytes: (optional) The value of config property 'retention.bytes'. :attr str retention_ms: (optional) The value of config property 'retention.ms'. :attr str segment_bytes: (optional) The value of config property 'segment.bytes'. :attr str segment_index_bytes: (optional) The value of config property 'segment.index.bytes'. :attr str segment_ms: (optional) The value of config property 'segment.ms'. """ def __init__(self, *, cleanup_policy: str = None, min_insync_replicas: str = None, retention_bytes: str = None, retention_ms: str = None, segment_bytes: str = None, segment_index_bytes: str = None, segment_ms: str = None) -> None: """ Initialize a TopicConfigs object. :param str cleanup_policy: (optional) The value of config property 'cleanup.policy'. :param str min_insync_replicas: (optional) The value of config property 'min.insync.replicas'. :param str retention_bytes: (optional) The value of config property 'retention.bytes'. :param str retention_ms: (optional) The value of config property 'retention.ms'. :param str segment_bytes: (optional) The value of config property 'segment.bytes'. :param str segment_index_bytes: (optional) The value of config property 'segment.index.bytes'. :param str segment_ms: (optional) The value of config property 'segment.ms'. """ self.cleanup_policy = cleanup_policy self.min_insync_replicas = min_insync_replicas self.retention_bytes = retention_bytes self.retention_ms = retention_ms self.segment_bytes = segment_bytes self.segment_index_bytes = segment_index_bytes self.segment_ms = segment_ms def to_dict(self) -> Dict: """Return a json dictionary representing this model.""" _dict = {} if hasattr(self, 'cleanup_policy') and self.cleanup_policy is not None: _dict['cleanup.policy'] = self.cleanup_policy if hasattr(self, 'min_insync_replicas') and self.min_insync_replicas is not None: _dict['min.insync.replicas'] = self.min_insync_replicas if hasattr(self, 'retention_bytes') and self.retention_bytes is not None: _dict['retention.bytes'] = self.retention_bytes if hasattr(self, 'retention_ms') and self.retention_ms is not None: _dict['retention.ms'] = self.retention_ms if hasattr(self, 'segment_bytes') and self.segment_bytes is not None: _dict['segment.bytes'] = self.segment_bytes if hasattr(self, 'segment_index_bytes') and self.segment_index_bytes is not None: _dict['segment.index.bytes'] = self.segment_index_bytes if hasattr(self, 'segment_ms') and self.segment_ms is not None: _dict['segment.ms'] = self.segment_ms return _dict def _to_dict(self): """Return a json dictionary representing this model.""" return self.to_dict() def __str__(self) -> str: """Return a `str` version of this TopicConfigs object.""" return json.dumps(self.to_dict(), indent=2) def __eq__(self, other: 'TopicConfigs') -> bool: """Return `true` when self and other are equal, false otherwise.""" if not isinstance(other, self.__class__): return False return self.__dict__ == other.__dict__ def __ne__(self, other: 'TopicConfigs') -> bool: """Return `true` when self and other are not equal, false otherwise.""" return not self == other class TopicDetail(): """ TopicDetail. :attr str name: (optional) The name of the topic. :attr int partitions: (optional) The number of partitions. :attr int replication_factor: (optional) The number of replication factor. :attr int retention_ms: (optional) The value of config property 'retention.ms'. :attr str cleanup_policy: (optional) The value of config property 'cleanup.policy'. :attr TopicConfigs configs: (optional) :attr List[ReplicaAssignment] replica_assignments: (optional) The replia assignment of the topic. """ def __init__(self, *, name: str = None, partitions: int = None, replication_factor: int = None, retention_ms: int = None, cleanup_policy: str = None, configs: 'TopicConfigs' = None, replica_assignments: List['ReplicaAssignment'] = None) -> None: """ Initialize a TopicDetail object. :param str name: (optional) The name of the topic. :param int partitions: (optional) The number of partitions. :param int replication_factor: (optional) The number of replication factor. :param int retention_ms: (optional) The value of config property 'retention.ms'. :param str cleanup_policy: (optional) The value of config property 'cleanup.policy'. :param TopicConfigs configs: (optional) :param List[ReplicaAssignment] replica_assignments: (optional) The replia assignment of the topic. """ self.name = name self.partitions = partitions self.replication_factor = replication_factor self.retention_ms = retention_ms self.cleanup_policy = cleanup_policy self.configs = configs self.replica_assignments = replica_assignments def to_dict(self) -> Dict: """Return a json dictionary representing this model.""" _dict = {} if hasattr(self, 'name') and self.name is not None: _dict['name'] = self.name if hasattr(self, 'partitions') and self.partitions is not None: _dict['partitions'] = self.partitions if hasattr(self, 'replication_factor') and self.replication_factor is not None: _dict['replicationFactor'] = self.replication_factor if hasattr(self, 'retention_ms') and self.retention_ms is not None: _dict['retentionMs'] = self.retention_ms if hasattr(self, 'cleanup_policy') and self.cleanup_policy is not None: _dict['cleanupPolicy'] = self.cleanup_policy if hasattr(self, 'configs') and self.configs is not None: _dict['configs'] = self.configs.to_dict() if hasattr(self, 'replica_assignments') and self.replica_assignments is not None: _dict['replicaAssignments'] = [x.to_dict() for x in self.replica_assignments] return _dict def _to_dict(self): """Return a json dictionary representing this model.""" return self.to_dict() def __str__(self) -> str: """Return a `str` version of this TopicDetail object.""" return json.dumps(self.to_dict(), indent=2) def __eq__(self, other: 'TopicDetail') -> bool: """Return `true` when self and other are equal, false otherwise.""" if not isinstance(other, self.__class__): return False return self.__dict__ == other.__dict__ def __ne__(self, other: 'TopicDetail') -> bool: """Return `true` when self and other are not equal, false otherwise.""" return not self == other
37.755361
115
0.596226
0ee4cfc2dd5204b72c6c610aac6abe376e79a7c9
3,765
py
Python
3-functions/pytest-exercises/test_functions.py
BaseCampCoding/python-fundamentals
3804c07841d6604b1e5a1c15126b3301aa8ae306
[ "MIT" ]
null
null
null
3-functions/pytest-exercises/test_functions.py
BaseCampCoding/python-fundamentals
3804c07841d6604b1e5a1c15126b3301aa8ae306
[ "MIT" ]
1
2018-07-18T18:01:22.000Z
2019-06-14T15:06:28.000Z
3-functions/pytest-exercises/test_functions.py
BaseCampCoding/python-fundamentals
3804c07841d6604b1e5a1c15126b3301aa8ae306
[ "MIT" ]
null
null
null
import functions from pytest import approx from bcca.test import should_print def test_min_insurance(): assert functions.min_insurance(100000) == approx(80000.0) assert functions.min_insurance(123456789) == approx(98765431.2) assert functions.min_insurance(0) == approx(0.0) assert functions.min_insurance(-54317890) == approx(-43454312.0) def test_bmi(): assert functions.bmi(160, 67) == approx(25.05680552) assert functions.bmi(200, 72) == approx(27.12191358) assert functions.bmi(120, 60) == approx(23.43333333) def test_calories(): assert functions.calories(5, 20) == 125 assert functions.calories(1, 1) == 13 def test_earnings(): assert functions.earnings(100, 100, 100) == 3600 assert functions.earnings(50, 75, 100) == 2550 assert functions.earnings(0, 1000, 79) == 12711
22.957317
74
0.733068
0ee50094e88f5107ffe4383858e5ac2e6c4ea6ec
90
py
Python
src/products/admin.py
apabaad/django_ecommerce
ca04143477b306413158e5311062563f7418700c
[ "bzip2-1.0.6" ]
null
null
null
src/products/admin.py
apabaad/django_ecommerce
ca04143477b306413158e5311062563f7418700c
[ "bzip2-1.0.6" ]
null
null
null
src/products/admin.py
apabaad/django_ecommerce
ca04143477b306413158e5311062563f7418700c
[ "bzip2-1.0.6" ]
null
null
null
from django.contrib import admin from .models import Product admin.site.register(Product)
22.5
32
0.833333
0ee558decdd72d80756553cbdc2a73e521956143
134
py
Python
cio/plugins/txt.py
beshrkayali/content-io
ae44aa4c4eba2234f940ca9d7a4bb310e25075b3
[ "BSD-3-Clause" ]
6
2015-02-12T20:23:42.000Z
2020-01-10T09:42:32.000Z
cio/plugins/txt.py
beshrkayali/content-io
ae44aa4c4eba2234f940ca9d7a4bb310e25075b3
[ "BSD-3-Clause" ]
5
2015-09-08T08:54:39.000Z
2020-01-10T12:13:21.000Z
cio/plugins/txt.py
beshrkayali/content-io
ae44aa4c4eba2234f940ca9d7a4bb310e25075b3
[ "BSD-3-Clause" ]
4
2015-06-29T15:21:41.000Z
2019-12-06T09:29:30.000Z
# coding=utf-8 from __future__ import unicode_literals from .base import BasePlugin
13.4
39
0.753731
0ee595b8e0ae941415e84128e8515b5e48db04fe
2,013
py
Python
ml-scripts/dump-data-to-learn.py
thejoeejoee/SUI-MIT-VUT-2020-2021
aee307aa772c5a0e97578da5ebedd3e2cd39ab91
[ "MIT" ]
null
null
null
ml-scripts/dump-data-to-learn.py
thejoeejoee/SUI-MIT-VUT-2020-2021
aee307aa772c5a0e97578da5ebedd3e2cd39ab91
[ "MIT" ]
null
null
null
ml-scripts/dump-data-to-learn.py
thejoeejoee/SUI-MIT-VUT-2020-2021
aee307aa772c5a0e97578da5ebedd3e2cd39ab91
[ "MIT" ]
1
2021-01-15T19:01:45.000Z
2021-01-15T19:01:45.000Z
#!/usr/bin/env python3 # Project: VUT FIT SUI Project - Dice Wars # Authors: # - Josef Kol <[email protected]> # - Dominik Harmim <[email protected]> # - Petr Kapoun <[email protected]> # - Jindich estk <[email protected]> # Year: 2020 # Description: Generates game configurations. import random import sys from argparse import ArgumentParser import time from signal import signal, SIGCHLD from utils import run_ai_only_game, BoardDefinition parser = ArgumentParser(prog='Dice_Wars') parser.add_argument('-p', '--port', help="Server port", type=int, default=5005) parser.add_argument('-a', '--address', help="Server address", default='127.0.0.1') procs = [] def signal_handler(): """ Handler for SIGCHLD signal that terminates server and clients. """ for p in procs: try: p.kill() except ProcessLookupError: pass PLAYING_AIs = [ 'xkolar71_orig', 'xkolar71_2', 'xkolar71_3', 'xkolar71_4', ] if __name__ == '__main__': main()
25.807692
116
0.623448
0ee5bd4b8f792f655e11610a4d7c25b151f76873
4,041
py
Python
testing/conftest.py
davidszotten/pdbpp
3d90d83902e1d19840d0419362a41c654f93251e
[ "BSD-3-Clause" ]
null
null
null
testing/conftest.py
davidszotten/pdbpp
3d90d83902e1d19840d0419362a41c654f93251e
[ "BSD-3-Clause" ]
null
null
null
testing/conftest.py
davidszotten/pdbpp
3d90d83902e1d19840d0419362a41c654f93251e
[ "BSD-3-Clause" ]
null
null
null
import functools import sys from contextlib import contextmanager import pytest _orig_trace = None # if _orig_trace and not hasattr(sys, "pypy_version_info"): # Fails with PyPy2 (https://travis-ci.org/antocuni/pdb/jobs/509624590)?!
28.0625
80
0.659985
0ee60185bcf81d5e6fbf52b5b69fb40616c44fa1
1,279
py
Python
thing_gym_ros/envs/utils.py
utiasSTARS/thing-gym-ros
6e8a034ac0d1686f29bd29e2aaa63f39a5b188d4
[ "MIT" ]
1
2021-12-25T01:10:32.000Z
2021-12-25T01:10:32.000Z
thing_gym_ros/envs/utils.py
utiasSTARS/thing-gym-ros
6e8a034ac0d1686f29bd29e2aaa63f39a5b188d4
[ "MIT" ]
null
null
null
thing_gym_ros/envs/utils.py
utiasSTARS/thing-gym-ros
6e8a034ac0d1686f29bd29e2aaa63f39a5b188d4
[ "MIT" ]
null
null
null
""" Various generic env utilties. """ def center_crop_img(img, crop_zoom): """ crop_zoom is amount to "zoom" into the image. E.g. 2.0 would cut out half of the width, half of the height, and only give the center. """ raw_height, raw_width = img.shape[:2] center = raw_height // 2, raw_width // 2 crop_size = raw_height // crop_zoom, raw_width // crop_zoom min_y, max_y = int(center[0] - crop_size[0] // 2), int(center[0] + crop_size[0] // 2) min_x, max_x = int(center[1] - crop_size[1] // 2), int(center[1] + crop_size[1] // 2) img_cropped = img[min_y:max_y, min_x:max_x] return img_cropped def crop_img(img, relative_corners): """ relative_corners are floats between 0 and 1 designating where the corners of a crop box should be ([[top_left_x, top_left_y], [bottom_right_x, bottom_right_y]]). e.g. [[0, 0], [1, 1]] would be the full image, [[0.5, 0.5], [1, 1]] would be bottom right.""" rc = relative_corners raw_height, raw_width = img.shape[:2] top_left_pix = [int(rc[0][0] * raw_width), int(rc[0][1] * raw_height)] bottom_right_pix = [int(rc[1][0] * raw_width), int(rc[1][1] * raw_height)] img_cropped = img[top_left_pix[1]:bottom_right_pix[1], top_left_pix[0]:bottom_right_pix[0]] return img_cropped
53.291667
97
0.6638
0ee65ef56e608d8cc1f10a29c3d522f07069ba46
9,006
py
Python
tests/sentry/utils/http/tests.py
arya-s/sentry
959ffbd37cb4a7821f7a2676c137be54cad171a8
[ "BSD-3-Clause" ]
1
2021-06-16T06:57:35.000Z
2021-06-16T06:57:35.000Z
tests/sentry/utils/http/tests.py
arya-s/sentry
959ffbd37cb4a7821f7a2676c137be54cad171a8
[ "BSD-3-Clause" ]
null
null
null
tests/sentry/utils/http/tests.py
arya-s/sentry
959ffbd37cb4a7821f7a2676c137be54cad171a8
[ "BSD-3-Clause" ]
null
null
null
# -*- coding: utf-8 -*- from __future__ import absolute_import import mock from exam import fixture from sentry import options from sentry.models import Project from sentry.testutils import TestCase from sentry.utils.http import ( is_same_domain, is_valid_origin, get_origins, absolute_uri, is_valid_ip, )
38.652361
94
0.663002
0ee6801d23fab1803ee54e727965d043d1914412
224
py
Python
comcenterproject/project/helpers.py
tongpa/bantak_program
66edfe225e8018f65c9c5a6cd7745c17ba557bd5
[ "Apache-2.0" ]
null
null
null
comcenterproject/project/helpers.py
tongpa/bantak_program
66edfe225e8018f65c9c5a6cd7745c17ba557bd5
[ "Apache-2.0" ]
null
null
null
comcenterproject/project/helpers.py
tongpa/bantak_program
66edfe225e8018f65c9c5a6cd7745c17ba557bd5
[ "Apache-2.0" ]
null
null
null
# -*- coding: utf-8 -*- """WebHelpers used in project.""" #from webhelpers import date, feedgenerator, html, number, misc, text from markupsafe import Markup
24.888889
69
0.6875
0ee6ceb6e274923689476909061cf2ae7181004e
1,555
py
Python
Thesis/load/runRiakLoads.py
arnaudsjs/YCSB-1
dc557d209244df72d68c9cb0a048d54e7bd72637
[ "Apache-2.0" ]
null
null
null
Thesis/load/runRiakLoads.py
arnaudsjs/YCSB-1
dc557d209244df72d68c9cb0a048d54e7bd72637
[ "Apache-2.0" ]
null
null
null
Thesis/load/runRiakLoads.py
arnaudsjs/YCSB-1
dc557d209244df72d68c9cb0a048d54e7bd72637
[ "Apache-2.0" ]
null
null
null
import sys; from Thesis.load.loadBenchmark import runLoadBenchmarkAsBatch; from Thesis.cluster.RiakCluster import RiakCluster; NORMAL_BINDING = 'riak'; CONSISTENCY_BINDING = 'riak_consistency'; IPS_IN_CLUSTER = ['172.16.33.14', '172.16.33.15', '172.16.33.16', '172.16.33.17', '172.16.33.18']; cluster = RiakCluster(NORMAL_BINDING, CONSISTENCY_BINDING, IPS_IN_CLUSTER); runLoadBenchmarkAsBatch(cluster, ['172.16.33.10'], '/root/YCSB/workloads/workload_load', 3, '/root/YCSB/loads/riak', ['1000000000'], ['1'], ['1']); # main();
42.027027
161
0.664309
0ee83db3e5e99371f123bcdb50f3fcc2018ce29b
4,947
py
Python
auto_nag/tests/test_round_robin.py
Mozilla-GitHub-Standards/f9c78643f5862cda82001d4471255ac29ef0c6b2c6171e2c1cbecab3d2fef4dd
28d999fcba9ad47d1dd0b2222880b71726ddd47c
[ "BSD-3-Clause" ]
null
null
null
auto_nag/tests/test_round_robin.py
Mozilla-GitHub-Standards/f9c78643f5862cda82001d4471255ac29ef0c6b2c6171e2c1cbecab3d2fef4dd
28d999fcba9ad47d1dd0b2222880b71726ddd47c
[ "BSD-3-Clause" ]
null
null
null
auto_nag/tests/test_round_robin.py
Mozilla-GitHub-Standards/f9c78643f5862cda82001d4471255ac29ef0c6b2c6171e2c1cbecab3d2fef4dd
28d999fcba9ad47d1dd0b2222880b71726ddd47c
[ "BSD-3-Clause" ]
null
null
null
# coding: utf-8 # This Source Code Form is subject to the terms of the Mozilla Public # License, v. 2.0. If a copy of the MPL was not distributed with this file, # You can obtain one at http://mozilla.org/MPL/2.0/. import unittest from mock import patch from auto_nag.people import People from auto_nag.round_robin import BadFallback, RoundRobin
31.711538
86
0.439256
0ee87adc70e779b9ff0da63b63fc29dd8e09baec
21,473
py
Python
scipy/weave/inline_tools.py
tacaswell/scipy
4d7e924a319299e39c9a9514e021fbfdfceb854e
[ "BSD-3-Clause" ]
1
2017-01-18T20:32:35.000Z
2017-01-18T20:32:35.000Z
scipy/weave/inline_tools.py
tacaswell/scipy
4d7e924a319299e39c9a9514e021fbfdfceb854e
[ "BSD-3-Clause" ]
null
null
null
scipy/weave/inline_tools.py
tacaswell/scipy
4d7e924a319299e39c9a9514e021fbfdfceb854e
[ "BSD-3-Clause" ]
null
null
null
# should re-write compiled functions to take a local and global dict # as input. from __future__ import absolute_import, print_function import sys import os from . import ext_tools from . import catalog from . import common_info from numpy.core.multiarray import _get_ndarray_c_version ndarray_api_version = '/* NDARRAY API VERSION %x */' % (_get_ndarray_c_version(),) # not an easy way for the user_path_list to come in here. # the PYTHONCOMPILED environment variable offers the most hope. function_catalog = catalog.catalog() function_cache = {} def inline(code,arg_names=[],local_dict=None, global_dict=None, force=0, compiler='', verbose=0, support_code=None, headers=[], customize=None, type_converters=None, auto_downcast=1, newarr_converter=0, **kw): """ Inline C/C++ code within Python scripts. ``inline()`` compiles and executes C/C++ code on the fly. Variables in the local and global Python scope are also available in the C/C++ code. Values are passed to the C/C++ code by assignment much like variables passed are passed into a standard Python function. Values are returned from the C/C++ code through a special argument called return_val. Also, the contents of mutable objects can be changed within the C/C++ code and the changes remain after the C code exits and returns to Python. inline has quite a few options as listed below. Also, the keyword arguments for distutils extension modules are accepted to specify extra information needed for compiling. Parameters ---------- code : string A string of valid C++ code. It should not specify a return statement. Instead it should assign results that need to be returned to Python in the `return_val`. arg_names : [str], optional A list of Python variable names that should be transferred from Python into the C/C++ code. It defaults to an empty string. local_dict : dict, optional If specified, it is a dictionary of values that should be used as the local scope for the C/C++ code. If local_dict is not specified the local dictionary of the calling function is used. global_dict : dict, optional If specified, it is a dictionary of values that should be used as the global scope for the C/C++ code. If `global_dict` is not specified, the global dictionary of the calling function is used. force : {0, 1}, optional If 1, the C++ code is compiled every time inline is called. This is really only useful for debugging, and probably only useful if your editing `support_code` a lot. compiler : str, optional The name of compiler to use when compiling. On windows, it understands 'msvc' and 'gcc' as well as all the compiler names understood by distutils. On Unix, it'll only understand the values understood by distutils. (I should add 'gcc' though to this). On windows, the compiler defaults to the Microsoft C++ compiler. If this isn't available, it looks for mingw32 (the gcc compiler). On Unix, it'll probably use the same compiler that was used when compiling Python. Cygwin's behavior should be similar. verbose : {0,1,2}, optional Specifies how much information is printed during the compile phase of inlining code. 0 is silent (except on windows with msvc where it still prints some garbage). 1 informs you when compiling starts, finishes, and how long it took. 2 prints out the command lines for the compilation process and can be useful if your having problems getting code to work. Its handy for finding the name of the .cpp file if you need to examine it. verbose has no effect if the compilation isn't necessary. support_code : str, optional A string of valid C++ code declaring extra code that might be needed by your compiled function. This could be declarations of functions, classes, or structures. headers : [str], optional A list of strings specifying header files to use when compiling the code. The list might look like ``["<vector>","'my_header'"]``. Note that the header strings need to be in a form than can be pasted at the end of a ``#include`` statement in the C++ code. customize : base_info.custom_info, optional An alternative way to specify `support_code`, `headers`, etc. needed by the function. See :mod:`scipy.weave.base_info` for more details. (not sure this'll be used much). type_converters : [type converters], optional These guys are what convert Python data types to C/C++ data types. If you'd like to use a different set of type conversions than the default, specify them here. Look in the type conversions section of the main documentation for examples. auto_downcast : {1,0}, optional This only affects functions that have numpy arrays as input variables. Setting this to 1 will cause all floating point values to be cast as float instead of double if all the Numeric arrays are of type float. If even one of the arrays has type double or double complex, all variables maintain their standard types. newarr_converter : int, optional Unused. Other Parameters ---------------- Relevant :mod:`distutils` keywords. These are duplicated from Greg Ward's :class:`distutils.extension.Extension` class for convenience: sources : [string] List of source filenames, relative to the distribution root (where the setup script lives), in Unix form (slash-separated) for portability. Source files may be C, C++, SWIG (.i), platform-specific resource files, or whatever else is recognized by the "build_ext" command as source for a Python extension. .. note:: The `module_path` file is always appended to the front of this list include_dirs : [string] List of directories to search for C/C++ header files (in Unix form for portability). define_macros : [(name : string, value : string|None)] List of macros to define; each macro is defined using a 2-tuple, where 'value' is either the string to define it to or None to define it without a particular value (equivalent of "#define FOO" in source or -DFOO on Unix C compiler command line). undef_macros : [string] List of macros to undefine explicitly. library_dirs : [string] List of directories to search for C/C++ libraries at link time. libraries : [string] List of library names (not filenames or paths) to link against. runtime_library_dirs : [string] List of directories to search for C/C++ libraries at run time (for shared extensions, this is when the extension is loaded). extra_objects : [string] List of extra files to link with (e.g. object files not implied by 'sources', static libraries that must be explicitly specified, binary resource files, etc.) extra_compile_args : [string] Any extra platform- and compiler-specific information to use when compiling the source files in 'sources'. For platforms and compilers where "command line" makes sense, this is typically a list of command-line arguments, but for other platforms it could be anything. extra_link_args : [string] Any extra platform- and compiler-specific information to use when linking object files together to create the extension (or to create a new static Python interpreter). Similar interpretation as for 'extra_compile_args'. export_symbols : [string] List of symbols to be exported from a shared extension. Not used on all platforms, and not generally necessary for Python extensions, which typically export exactly one symbol: "init" + extension_name. swig_opts : [string] Any extra options to pass to SWIG if a source file has the .i extension. depends : [string] List of files that the extension depends on. language : string Extension language (i.e. "c", "c++", "objc"). Will be detected from the source extensions if not provided. See Also -------- distutils.extension.Extension : Describes additional parameters. """ # this grabs the local variables from the *previous* call # frame -- that is the locals from the function that called # inline. global function_catalog call_frame = sys._getframe().f_back if local_dict is None: local_dict = call_frame.f_locals if global_dict is None: global_dict = call_frame.f_globals if force: module_dir = global_dict.get('__file__',None) func = compile_function(code,arg_names,local_dict, global_dict,module_dir, compiler=compiler, verbose=verbose, support_code=support_code, headers=headers, customize=customize, type_converters=type_converters, auto_downcast=auto_downcast, **kw) function_catalog.add_function(code,func,module_dir) results = attempt_function_call(code,local_dict,global_dict) else: # 1. try local cache try: results = apply(function_cache[code],(local_dict,global_dict)) return results except TypeError as msg: msg = str(msg).strip() if msg[:16] == "Conversion Error": pass else: raise TypeError(msg) except NameError as msg: msg = str(msg).strip() if msg[:16] == "Conversion Error": pass else: raise NameError(msg) except KeyError: pass # 2. try function catalog try: results = attempt_function_call(code,local_dict,global_dict) # 3. build the function except ValueError: # compile the library module_dir = global_dict.get('__file__',None) func = compile_function(code,arg_names,local_dict, global_dict,module_dir, compiler=compiler, verbose=verbose, support_code=support_code, headers=headers, customize=customize, type_converters=type_converters, auto_downcast=auto_downcast, **kw) function_catalog.add_function(code,func,module_dir) results = attempt_function_call(code,local_dict,global_dict) return results
42.7749
93
0.593862
0ee8c1be25a8a7813888c36156d1084e0932af6f
22,062
py
Python
trove/guestagent/common/configuration.py
sapcc/trove
c03ec0827687fba202f72f4d264ab70158604857
[ "Apache-2.0" ]
1
2020-04-08T07:42:19.000Z
2020-04-08T07:42:19.000Z
trove/guestagent/common/configuration.py
sapcc/trove
c03ec0827687fba202f72f4d264ab70158604857
[ "Apache-2.0" ]
5
2019-08-14T06:46:03.000Z
2021-12-13T20:01:25.000Z
trove/guestagent/common/configuration.py
sapcc/trove
c03ec0827687fba202f72f4d264ab70158604857
[ "Apache-2.0" ]
2
2020-03-15T01:24:15.000Z
2020-07-22T20:34:26.000Z
# Copyright 2015 Tesora Inc. # All Rights Reserved. # # 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 abc import os import re import six from trove.guestagent.common import guestagent_utils from trove.guestagent.common import operating_system from trove.guestagent.common.operating_system import FileMode
40.629834
79
0.631629
0ee8cb45529200e0a449b9203826ebdcb7530c60
18,018
py
Python
API-Reference-Code-Generator.py
sawyercade/Documentation
257b68c8ca2928e8a730ea44196297a400587437
[ "Apache-2.0" ]
116
2017-09-13T17:11:07.000Z
2022-03-13T00:33:03.000Z
API-Reference-Code-Generator.py
sawyercade/Documentation
257b68c8ca2928e8a730ea44196297a400587437
[ "Apache-2.0" ]
148
2017-09-14T01:07:09.000Z
2022-03-28T21:47:55.000Z
API-Reference-Code-Generator.py
sawyercade/Documentation
257b68c8ca2928e8a730ea44196297a400587437
[ "Apache-2.0" ]
124
2017-09-07T22:05:43.000Z
2022-03-26T05:44:32.000Z
import pathlib import yaml documentations = {"Our Platform": "QuantConnect-Platform-2.0.0.yaml", "Alpha Streams": "QuantConnect-Alpha-0.8.yaml"} for section, source in documentations.items(): yaml_file = open(source) doc = yaml.load(yaml_file, Loader=yaml.Loader) paths = doc["paths"] for api_call, result in paths.items(): j = 1 content = result["post"] if "post" in result else result["get"] # Create path if not exist destination_folder = pathlib.Path("/".join(content["tags"])) destination_folder.mkdir(parents=True, exist_ok=True) # Create Introduction part with open(destination_folder / f'{j:02} Introduction.html', "w") as html_file: html_file.write("<p>\n") html_file.write(f"{content['summary']}\n") html_file.write("</p>\n") j += 1 # Create Description part if having one if "description" in content: with open(destination_folder / f'{j:02} Description.html', "w") as html_file: html_file.write('<p>\n') html_file.write(f'{content["description"]}\n') html_file.write('</p>\n') j += 1 # Create Request part with open(destination_folder / f'{j:02} Request.html', "w") as html_file: description_ = "" if "parameters" in content: writeUp = RequestTable(api_call, content["parameters"]) elif "requestBody" in content: if "description" in content["requestBody"]: description_ = str(content["requestBody"]["description"]) if description_[-1] != ".": description_ += "." description_ += " " writeUp = ResponseTable(content["requestBody"]) else: writeUp = '<table class="table qc-table">\n<thead>\n<tr>\n' writeUp += f'<th colspan="1"><code>{api_call}</code> Method</th>\n</tr>\n</thead>\n' writeUp += f'</tr>\n<td><code>{api_call}</code> method takes no parameters.</td>\n</tr>\n</table>' description_ += f'The <code>{api_call}</code> API accepts requests in the following format:\n' html_file.write("<p>\n" + description_ + "</p>\n") html_file.write(writeUp) j += 1 # Create Response part with open(destination_folder / f'{j:02} Responses.html', "w") as html_file: html_file.write('<p>\n') html_file.write(f'The <code>{api_call}</code> API provides a response in the following format:\n') html_file.write('</p>\n') request_body = content["responses"] for code, properties in request_body.items(): if code == "200": html_file.write('<h4>200 Success</h4>\n') elif code == "401": html_file.write('<h4>401 Authentication Error</h4>\n<table class="table qc-table">\n<thead>\n<tr>\n') html_file.write('<th colspan="2"><code>UnauthorizedError</code> Model - Unauthorized response from the API. Key is missing, invalid, or timestamp is too old for hash.</th>\n') html_file.write('</tr>\n</thead>\n<tr>\n<td width="20%">www_authenticate</td> <td> <code>string</code> <br/> Header</td>\n</tr>\n</table>\n') continue elif code == "404": html_file.write('<h4>404 Not Found Error</h4>\n') html_file.write('<p>The requested item, index, page was not found.</p>\n') continue elif code == "default": html_file.write('<h4>Default Generic Error</h4>\n') writeUp = ResponseTable(properties) html_file.write(writeUp) print(f"Documentation of {section} is generated and inplace!")
41.04328
195
0.466811
0eea2bc9a6e4ca781595beca55133b3f45fb4b7b
551
py
Python
forge_api_client/hubs.py
dmh126/forge-python-data-management-api
9c33f220021251a0340346065e3dd1998fc49a12
[ "MIT" ]
1
2019-07-02T08:32:22.000Z
2019-07-02T08:32:22.000Z
forge_api_client/hubs.py
dmh126/forge-python-data-management-api
9c33f220021251a0340346065e3dd1998fc49a12
[ "MIT" ]
null
null
null
forge_api_client/hubs.py
dmh126/forge-python-data-management-api
9c33f220021251a0340346065e3dd1998fc49a12
[ "MIT" ]
2
2019-07-04T05:13:42.000Z
2020-05-09T22:15:05.000Z
from .utils import get_request, authorized
21.192308
75
0.575318
0eeb15222dc7d564fdca952a76722513fa52548a
144
py
Python
tlp/django_app/app/urls.py
munisisazade/create-django-app
f62395af2adaacacc4d3a3857c6570c9647d13a1
[ "MIT" ]
14
2018-01-08T12:50:10.000Z
2021-12-26T18:38:14.000Z
tlp/django_app/app/urls.py
munisisazade/create-django-app
f62395af2adaacacc4d3a3857c6570c9647d13a1
[ "MIT" ]
10
2018-03-01T14:17:05.000Z
2022-03-11T23:26:11.000Z
tlp/django_app/app/urls.py
munisisazade/create-django-app
f62395af2adaacacc4d3a3857c6570c9647d13a1
[ "MIT" ]
4
2019-04-09T17:29:34.000Z
2020-06-07T14:46:23.000Z
from django.conf.urls import url # from .views import BaseIndexView urlpatterns = [ # url(r'^$', BaseIndexView.as_view(), name="index"), ]
20.571429
56
0.6875
0eeba77c6034df540d6e02d1c1935e84c28bdcd9
10,427
py
Python
tools/archive/create_loadable_configs.py
madelinemccombe/iron-skillet
f7bb805ac5ed0f2b44e4b438f8c021eaf2f5c66b
[ "MIT" ]
null
null
null
tools/archive/create_loadable_configs.py
madelinemccombe/iron-skillet
f7bb805ac5ed0f2b44e4b438f8c021eaf2f5c66b
[ "MIT" ]
null
null
null
tools/archive/create_loadable_configs.py
madelinemccombe/iron-skillet
f7bb805ac5ed0f2b44e4b438f8c021eaf2f5c66b
[ "MIT" ]
null
null
null
# Copyright (c) 2018, Palo Alto Networks # # Permission to use, copy, modify, and/or distribute this software for any # purpose with or without fee is hereby granted, provided that the above # copyright notice and this permission notice appear in all copies. # # THE SOFTWARE IS PROVIDED "AS IS" AND THE AUTHOR DISCLAIMS ALL WARRANTIES # WITH REGARD TO THIS SOFTWARE INCLUDING ALL IMPLIED WARRANTIES OF # MERCHANTABILITY AND FITNESS. IN NO EVENT SHALL THE AUTHOR BE LIABLE FOR # ANY SPECIAL, DIRECT, INDIRECT, OR CONSEQUENTIAL DAMAGES OR ANY DAMAGES # WHATSOEVER RESULTING FROM LOSS OF USE, DATA OR PROFITS, WHETHER IN AN # ACTION OF CONTRACT, NEGLIGENCE OR OTHER TORTIOUS ACTION, ARISING OUT OF # OR IN CONNECTION WITH THE USE OR PERFORMANCE OF THIS SOFTWARE. # Author: Scott Shoaf <[email protected]> ''' Palo Alto Networks create_loadable_configs.py Provides rendering of configuration templates with user defined values Output is a set of loadable full configurations and set commands for Panos and Panorama Edit the config_variables.yaml values and then run the script This software is provided without support, warranty, or guarantee. Use at your own risk. ''' import datetime import os import shutil import sys import time import getpass import oyaml from jinja2 import Environment, FileSystemLoader from passlib.hash import des_crypt from passlib.hash import md5_crypt from passlib.hash import sha256_crypt from passlib.hash import sha512_crypt defined_filters = ['md5_hash', 'des_hash', 'sha512_hash'] def myconfig_newdir(myconfigdir_name, foldertime): ''' create a new main loadable_configs folder if required then new subdirectories for configs :param myconfigdir_name: prefix folder name from the my_variables.py file :param foldertime: datetime when script run; to be used as suffix of folder name :return: the myconfigdir full path name ''' # get the full path to the config directory we want (panos / panorama) myconfigpath = os.path.abspath(os.path.join('..', 'loadable_configs')) if os.path.isdir(myconfigpath) is False: os.mkdir(myconfigpath, mode=0o755) print('created new loadable config directory') # check that configs folder exists and if not create a new one # then create snippets and full sub-directories myconfigdir = '{0}/{1}-{2}'.format(myconfigpath, myconfigdir_name, foldertime) if os.path.isdir(myconfigdir) is False: os.mkdir(myconfigdir, mode=0o755) print('\ncreated new archive folder {0}-{1}'.format(myconfigdir_name, foldertime)) if os.path.isdir('{0}/{1}'.format(myconfigdir, config_type)) is False: os.mkdir('{0}/{1}'.format(myconfigdir, config_type)) print('created new subdirectories for {0}'.format(config_type)) return myconfigdir def template_render(filename, template_path, render_type, context): ''' render the jinja template using the context value from config_variables.yaml :param filename: name of the template file :param template_path: path for the template file :param render_type: type if full or set commands; aligns with folder name :param context: dict of variables to render :return: return the rendered xml file and set conf file ''' print('..creating template for {0}'.format(filename)) env = Environment(loader=FileSystemLoader('{0}/{1}'.format(template_path, render_type))) # load our custom jinja filters here, see the function defs below for reference env.filters['md5_hash'] = md5_hash env.filters['des_hash'] = des_hash env.filters['sha512_hash'] = sha512_hash template = env.get_template(filename) rendered_template = template.render(context) return rendered_template def template_save(snippet_name, myconfigdir, config_type, element): ''' after rendering the template save to the myconfig directory each run saves with a unique prefix name + datetime :param snippet_name: name of the output file :param myconfigdir: path to the my_config directory :param config_type: based on initial run list; eg. panos or panorama :param element: xml element rendered based on input variables; used as folder name :param render_type: type eg. if full or snippets; aligns with folder name :return: no value returned (future could be success code) ''' print('..saving template for {0}'.format(snippet_name)) filename = snippet_name with open('{0}/{1}/{2}'.format(myconfigdir, config_type, filename), 'w') as configfile: configfile.write(element) # copy the variables file used for the render into the my_template folder var_file = 'loadable_config_vars/config_variables.yaml' if os.path.isfile('{0}/{1}'.format(myconfigdir, var_file)) is False: vfilesrc = var_file vfiledst = '{0}/{1}'.format(myconfigdir, var_file) shutil.copy(vfilesrc, vfiledst) return # define functions for custom jinja filters def md5_hash(txt): ''' Returns the MD5 Hashed secret for use as a password hash in the PanOS configuration :param txt: text to be hashed :return: password hash of the string with salt and configuration information. Suitable to place in the phash field in the configurations ''' return md5_crypt.hash(txt) def des_hash(txt): ''' Returns the DES Hashed secret for use as a password hash in the PanOS configuration :param txt: text to be hashed :return: password hash of the string with salt and configuration information. Suitable to place in the phash field in the configurations ''' return des_crypt.hash(txt) def sha256_hash(txt): ''' Returns the SHA256 Hashed secret for use as a password hash in the PanOS configuration :param txt: text to be hashed :return: password hash of the string with salt and configuration information. Suitable to place in the phash field in the configurations ''' return sha256_crypt.hash(txt) def sha512_hash(txt): ''' Returns the SHA512 Hashed secret for use as a password hash in the PanOS configuration :param txt: text to be hashed :return: password hash of the string with salt and configuration information. Suitable to place in the phash field in the configurations ''' return sha512_crypt.hash(txt) def replace_variables(config_type, render_type, input_var): ''' get the input variables and render the output configs with jinja2 inputs are read from the template directory and output to my_config :param config_type: panos or panorama to read/write to the respective directories :param archivetime: datetimestamp used for the output my_config folder naming ''' config_variables = 'config_variables.yaml' # create dict of values for the jinja template render context = create_context(config_variables) # update context dict with variables from user input for snippet_var in input_var: context[snippet_var] = input_var[snippet_var] # get the full path to the output directory we want (panos / panorama) template_path = os.path.abspath(os.path.join('..', 'templates', config_type)) # append to the sys path for module lookup sys.path.append(template_path) # output subdir located in loadable_configs dir myconfig_path = myconfig_newdir(input_var['output_dir'], input_var['archive_time']) # render full and set conf files print('\nworking with {0} config template'.format(render_type)) if render_type == 'full': filename = 'iron_skillet_{0}_full.xml'.format(config_type) if render_type == 'set_commands': filename = 'iron_skillet_{0}_full.conf'.format(config_type) element = template_render(filename, template_path, render_type, context) template_save(filename, myconfig_path, config_type, element) print('\nconfigs have been created and can be found in {0}'.format(myconfig_path)) print('along with the metadata values used to render the configs\n') return if __name__ == '__main__': # Use the timestamp to create a unique folder name print('=' * 80) print(' ') print('Welcome to Iron-Skillet'.center(80)) print(' ') print('=' * 80) input_var = {} # archive_time used as part of the my_config directory name input_var['archive_time'] = datetime.datetime.fromtimestamp(time.time()).strftime('%Y%m%d_%H%M%S') print('\ndatetime used for folder creation: {0}\n'.format(input_var['archive_time'])) # this prompts for the prefix name of the output directory input_var['output_dir'] = input('Enter the name of the output directory: ') # this prompts for the superuser username to be added into the configuration; no default admin/admin used input_var['ADMINISTRATOR_USERNAME'] = input('Enter the superuser administrator account username: ') print('\na phash will be created for superuser {0} and added to the config file\n'.format( input_var['ADMINISTRATOR_USERNAME'])) passwordmatch = False # prompt for the superuser password to create a phash and store in the my_config files; no default admin/admin while passwordmatch is False: password1 = getpass.getpass("Enter the superuser administrator account password: ") password2 = getpass.getpass("Enter password again to verify: ") if password1 == password2: input_var['ADMINISTRATOR_PASSWORD'] = password1 passwordmatch = True else: print('\nPasswords do not match. Please try again.\n') # loop through all config types that have their respective template folders for config_type in ['panos', 'panorama']: for render_type in ['full', 'set_commands']: replace_variables(config_type, render_type, input_var)
38.762082
118
0.720629
0eebd18c0a711ceedaa9842ae51084a3bb575a36
8,841
py
Python
pactman/verifier/pytest_plugin.py
piotrantosz/pactman
2838e273d79831721da9c1b658b8f9d249efc789
[ "MIT" ]
67
2018-08-26T03:39:16.000Z
2022-02-24T10:05:18.000Z
pactman/verifier/pytest_plugin.py
piotrantosz/pactman
2838e273d79831721da9c1b658b8f9d249efc789
[ "MIT" ]
82
2018-08-29T00:09:32.000Z
2022-02-08T02:46:15.000Z
pactman/verifier/pytest_plugin.py
piotrantosz/pactman
2838e273d79831721da9c1b658b8f9d249efc789
[ "MIT" ]
37
2018-08-22T04:40:31.000Z
2022-02-08T13:31:31.000Z
import glob import logging import os import warnings import pytest from _pytest.outcomes import Failed from _pytest.reports import TestReport from .broker_pact import BrokerPact, BrokerPacts, PactBrokerConfig from .result import PytestResult, log # Future options to be implemented. Listing them here so naming consistency can be a thing. # group.addoption("--pact-publish-pacts", action="store_true", default=False, # help="publish pacts to pact broker") # group.addoption("--pact-consumer-version", default=None, # help="consumer version to use when publishing pacts to the broker") # group.addoption("--pact-consumer-version-source", default=None, # help="generate consumer version from source 'git-tag' or 'git-hash'") # group.addoption("--pact-consumer-version-tag", metavar='TAG', action="append", # help="tag(s) that should be applied to the consumer version when pacts " # "are uploaded to the broker; multiple tags may be supplied") # add the pact broker URL to the pytest output if running verbose def test_id(identifier): interaction, _ = identifier return str(interaction) def pytest_generate_tests(metafunc): if "pact_verifier" in metafunc.fixturenames: broker_url = get_broker_url(metafunc.config) if not broker_url: pact_files_location = metafunc.config.getoption("pact_files") if not pact_files_location: raise ValueError("need a --pact-broker-url or --pact-files option") pact_files = load_pact_files(pact_files_location) metafunc.parametrize( "pact_verifier", flatten_pacts(pact_files), ids=test_id, indirect=True ) else: provider_name = get_provider_name(metafunc.config) if not provider_name: raise ValueError("--pact-broker-url requires the --pact-provider-name option") broker = PactBrokerConfig( broker_url, metafunc.config.getoption("pact_broker_token"), metafunc.config.getoption("pact_verify_consumer_tag", []), ) broker_pacts = BrokerPacts( provider_name, pact_broker=broker, result_factory=PytestResult ) pacts = broker_pacts.consumers() filter_consumer_name = metafunc.config.getoption("pact_verify_consumer") if not filter_consumer_name: filter_consumer_name = metafunc.config.getoption("pact_consumer_name") if filter_consumer_name: warnings.warn( "The --pact-consumer-name command-line option is deprecated " "and will be removed in the 3.0.0 release.", DeprecationWarning, ) if filter_consumer_name: pacts = [pact for pact in pacts if pact.consumer == filter_consumer_name] metafunc.parametrize("pact_verifier", flatten_pacts(pacts), ids=test_id, indirect=True)
38.776316
109
0.658862
0eec4303c142298ab8af1f1876c980b2e097801b
1,503
py
Python
interface/docstring.py
karttur/geoimagine02-grass
09c207707ddd0dae04a871e006e184409aa87d99
[ "BSD-3-Clause" ]
null
null
null
interface/docstring.py
karttur/geoimagine02-grass
09c207707ddd0dae04a871e006e184409aa87d99
[ "BSD-3-Clause" ]
null
null
null
interface/docstring.py
karttur/geoimagine02-grass
09c207707ddd0dae04a871e006e184409aa87d99
[ "BSD-3-Clause" ]
null
null
null
# -*- coding: utf-8 -*- def docstring_property(class_doc): """Property attribute for docstrings. Took from: https://gist.github.com/bfroehle/4041015 >>> class A(object): ... '''Main docstring''' ... def __init__(self, x): ... self.x = x ... @docstring_property(__doc__) ... def __doc__(self): ... return "My value of x is %s." % self.x >>> A.__doc__ 'Main docstring' >>> a = A(10) >>> a.__doc__ 'My value of x is 10.' """ return wrapper
26.839286
78
0.611444
0eec9d3074b439e55c9718c0b6f3f23b0eb54adb
1,906
py
Python
autocnet/matcher/cuda_matcher.py
gsn9/autocnet
ddcca3ce3a6b59f720804bb3da03857efa4ff534
[ "CC0-1.0" ]
null
null
null
autocnet/matcher/cuda_matcher.py
gsn9/autocnet
ddcca3ce3a6b59f720804bb3da03857efa4ff534
[ "CC0-1.0" ]
1
2018-09-13T16:03:53.000Z
2018-09-13T16:03:53.000Z
autocnet/matcher/cuda_matcher.py
gsn9/autocnet
ddcca3ce3a6b59f720804bb3da03857efa4ff534
[ "CC0-1.0" ]
1
2018-09-13T15:12:51.000Z
2018-09-13T15:12:51.000Z
import warnings try: import cudasift as cs except: cs = None import numpy as np import pandas as pd def match(edge, aidx=None, bidx=None, **kwargs): """ Apply a composite CUDA matcher and ratio check. If this method is used, no additional ratio check is necessary and no symmetry check is required. The ratio check is embedded on the cuda side and returned as an ambiguity value. In testing symmetry is not required as it is expensive without significant gain in accuracy when using this implementation. """ source_kps = edge.source.get_keypoints(index=aidx) source_des = edge.source.descriptors[aidx] source_map = {k:v for k, v in enumerate(source_kps.index)} destin_kps = edge.destination.get_keypoints(index=bidx) destin_des = edge.destination.descriptors[bidx] destin_map = {k:v for k, v in enumerate(destin_kps.index)} s_siftdata = cs.PySiftData.from_data_frame(source_kps, source_des) d_siftdata = cs.PySiftData.from_data_frame(destin_kps, destin_des) cs.PyMatchSiftData(s_siftdata, d_siftdata) matches, _ = s_siftdata.to_data_frame() # Matches are reindexed 0-n, but need to be remapped to the source_kps, # destin_kps indices. This is the mismatch) source = np.empty(len(matches)) source[:] = edge.source['node_id'] destination = np.empty(len(matches)) destination[:] = edge.destination['node_id'] df = pd.concat([pd.Series(source), pd.Series(matches.index), pd.Series(destination), matches.match, matches.score, matches.ambiguity], axis=1) df.columns = ['source_image', 'source_idx', 'destination_image', 'destination_idx', 'score', 'ambiguity'] df.source_idx = df.source_idx.map(source_map) df.destination_idx = df.destination_idx.map(destin_map) # Set the matches and set the 'ratio' (ambiguity) mask edge.matches = df
35.962264
77
0.707765
0eed163a13b8bf28c8e3cc3018df9acf80f8ef9a
199
py
Python
app/apis/__init__.py
FabienArcellier/blueprint-webapp-flask-restx
84bc9dbe697c4b0f6667d2a2d8144a3f934a307a
[ "MIT" ]
null
null
null
app/apis/__init__.py
FabienArcellier/blueprint-webapp-flask-restx
84bc9dbe697c4b0f6667d2a2d8144a3f934a307a
[ "MIT" ]
null
null
null
app/apis/__init__.py
FabienArcellier/blueprint-webapp-flask-restx
84bc9dbe697c4b0f6667d2a2d8144a3f934a307a
[ "MIT" ]
null
null
null
from flask_restx import Api from app.apis.hello import api as hello api = Api( title='api', version='1.0', description='', prefix='/api', doc='/api' ) api.add_namespace(hello)
14.214286
39
0.633166
0eed2f6be467201cff2adf42d27d251ad3cba2b3
1,339
py
Python
tests/test_core.py
Kantouzin/brainfuck
812834320b080e2317d3fac377db64782057c8f4
[ "WTFPL" ]
null
null
null
tests/test_core.py
Kantouzin/brainfuck
812834320b080e2317d3fac377db64782057c8f4
[ "WTFPL" ]
null
null
null
tests/test_core.py
Kantouzin/brainfuck
812834320b080e2317d3fac377db64782057c8f4
[ "WTFPL" ]
null
null
null
# coding: utf-8 import unittest from test.support import captured_stdout from brainfuck import BrainFuck if __name__ == "__main__": unittest.main()
24.345455
68
0.546677