max_stars_repo_path
stringlengths
4
286
max_stars_repo_name
stringlengths
5
119
max_stars_count
int64
0
191k
id
stringlengths
1
7
content
stringlengths
6
1.03M
content_cleaned
stringlengths
6
1.03M
language
stringclasses
111 values
language_score
float64
0.03
1
comments
stringlengths
0
556k
edu_score
float64
0.32
5.03
edu_int_score
int64
0
5
tests/test_data/lazy_mod.py
brettcannon/modutil
17
3000
import modutil mod, __getattr__ = modutil.lazy_import(__name__, ['tests.test_data.A', '.B', '.C as still_C']) def trigger_A(): return mod.A def trigger_B(): return mod.B def trigger_C(): return mod.still_C def trigger_failure(): return mod.does_not_exist
import modutil mod, __getattr__ = modutil.lazy_import(__name__, ['tests.test_data.A', '.B', '.C as still_C']) def trigger_A(): return mod.A def trigger_B(): return mod.B def trigger_C(): return mod.still_C def trigger_failure(): return mod.does_not_exist
none
1
1.926926
2
test.py
xiaohuaibaoguigui/EllSeg
1
3001
#!/usr/bin/env python3 # -*- coding: utf-8 -*- import os import sys import tqdm import torch import pickle import resource import numpy as np import matplotlib.pyplot as plt from args import parse_args from modelSummary import model_dict from pytorchtools import load_from_file from torch.utils.data import DataLoader ...
#!/usr/bin/env python3 # -*- coding: utf-8 -*- import os import sys import tqdm import torch import pickle import resource import numpy as np import matplotlib.pyplot as plt from args import parse_args from modelSummary import model_dict from pytorchtools import load_from_file from torch.utils.data import DataLoader ...
en
0.588163
#!/usr/bin/env python3 # -*- coding: utf-8 -*- #%% #%% # Unnormalizes the points # Unnormalizes the points # Unnormalizes the points # Unnormalizes the points
1.957662
2
tests/test_util.py
meskio/tuf
1
3002
#!/usr/bin/env python """ <Program Name> test_util.py <Author> <NAME>. <Started> February 1, 2013. <Copyright> See LICENSE for licensing information. <Purpose> Unit test for 'util.py' """ # Help with Python 3 compatibility, where the print statement is a function, an # implicit relative import is invali...
#!/usr/bin/env python """ <Program Name> test_util.py <Author> <NAME>. <Started> February 1, 2013. <Copyright> See LICENSE for licensing information. <Purpose> Unit test for 'util.py' """ # Help with Python 3 compatibility, where the print statement is a function, an # implicit relative import is invali...
en
0.729916
#!/usr/bin/env python <Program Name> test_util.py <Author> <NAME>. <Started> February 1, 2013. <Copyright> See LICENSE for licensing information. <Purpose> Unit test for 'util.py' # Help with Python 3 compatibility, where the print statement is a function, an # implicit relative import is invalid, and the...
2.828059
3
background/forms.py
BFlameSwift/AirplaneReservationSystem
3
3003
from django import forms class FlightrForm(forms.Form): flight_number = forms.CharField(max_length=30, label="航班号", widget=forms.TextInput(attrs={'class': 'form-control'})) plane_type_choices = [ ('波音', ( ('1', '747'), ('2', '777'), ('3', '787'), ) ...
from django import forms class FlightrForm(forms.Form): flight_number = forms.CharField(max_length=30, label="航班号", widget=forms.TextInput(attrs={'class': 'form-control'})) plane_type_choices = [ ('波音', ( ('1', '747'), ('2', '777'), ('3', '787'), ) ...
en
0.232198
# highlevel_economy_class_price = forms.FloatField(label="高级经济舱价格",widget=forms.NumberInput(attrs={'class': 'form-control'})) # book_sum = forms.IntegerField(label="订票总数") # plane_capacity = forms.IntegerField(label="飞机容量")
2.251322
2
cams/propressing/data_rotate.py
boliqq07/cam3d
1
3004
<gh_stars>1-10 from functools import lru_cache from math import cos, sin import scipy from scipy.ndimage import affine_transform import numpy as np @lru_cache(maxsize=10) def get_matrix(angles=(90, 90, 90), inverse=False): """ Axis of rotation Get matrix by angle. (shear+compress) Examples: z = 120 ...
from functools import lru_cache from math import cos, sin import scipy from scipy.ndimage import affine_transform import numpy as np @lru_cache(maxsize=10) def get_matrix(angles=(90, 90, 90), inverse=False): """ Axis of rotation Get matrix by angle. (shear+compress) Examples: z = 120 ######...
en
0.585381
Axis of rotation Get matrix by angle. (shear+compress) Examples: z = 120 ############################################################ ---------------------- -------------------------------- -oooooooooooooooooooo- -------------------------------- -oooooooooooooooooooo-...
2.950971
3
playground/conversions/parser/lola2dot.py
flange/esp
0
3005
#!/usr/bin/env python import sys #lolafile = open("ex-small.graph", "r") source = 0 target = 0 lowlink = 0 trans = "bla" print("digraph {") with open(sys.argv[1]) as lolafile: for line in lolafile: if len(line) == 1: continue linelist = line.split(" ") if "STATE" in linelist: ...
#!/usr/bin/env python import sys #lolafile = open("ex-small.graph", "r") source = 0 target = 0 lowlink = 0 trans = "bla" print("digraph {") with open(sys.argv[1]) as lolafile: for line in lolafile: if len(line) == 1: continue linelist = line.split(" ") if "STATE" in linelist: ...
en
0.451118
#!/usr/bin/env python #lolafile = open("ex-small.graph", "r") {} -> {} [label="{}", lowlink="{}"];
3.135111
3
engkor/views.py
takeshixx/dprkdict
10
3006
<gh_stars>1-10 import re import urllib.parse from django.shortcuts import render, get_object_or_404 from django.http import HttpResponse, JsonResponse from django.core.paginator import Paginator, PageNotAnInteger, EmptyPage from .models import Definition RE_HANGUL = re.compile(r'[(]*[\uAC00-\uD7AF]+[\uAC00-\uD7AF ()...
import re import urllib.parse from django.shortcuts import render, get_object_or_404 from django.http import HttpResponse, JsonResponse from django.core.paginator import Paginator, PageNotAnInteger, EmptyPage from .models import Definition RE_HANGUL = re.compile(r'[(]*[\uAC00-\uD7AF]+[\uAC00-\uD7AF (),;]*', re.IGNOR...
en
0.350525
#ko/en/{word_url}" '
2.133076
2
appdaemon/apps/toggle_switch/toggle_switch.py
Mithras/ha
3
3007
<reponame>Mithras/ha import globals class ToggleSwitch(globals.Hass): async def initialize(self): config = self.args["config"] self._input = config["input"] self._toggle_service = config["toggle_service"] self._toggle_payload = config["toggle_payload"] self._power = config[...
import globals class ToggleSwitch(globals.Hass): async def initialize(self): config = self.args["config"] self._input = config["input"] self._toggle_service = config["toggle_service"] self._toggle_payload = config["toggle_payload"] self._power = config["power"] self...
en
0.418591
# self.log("Terminate") # self.log(f"InputChange: old = {old}, new = {new}") # self.log(f"EnsureState: immediate = {immediate}") # self.log( # f"EnsureState: input = {input}, power: {power}") # self.log("Toggle")
2.46786
2
templates_deepdive_app_bagofwords/udf/dd_extract_features.py
charlieccarey/rdoc
0
3008
<filename>templates_deepdive_app_bagofwords/udf/dd_extract_features.py<gh_stars>0 #!/usr/bin/env python from __future__ import print_function ''' 1\taaaa~^~bbbb~^~cccc 2\tdddd~^~EEEE~^~ffff ''' import sys ARR_DELIM = '~^~' for row in sys.stdin: row = row.strip() sent_id, lemmas = row.split('\t') lemmas ...
<filename>templates_deepdive_app_bagofwords/udf/dd_extract_features.py<gh_stars>0 #!/usr/bin/env python from __future__ import print_function ''' 1\taaaa~^~bbbb~^~cccc 2\tdddd~^~EEEE~^~ffff ''' import sys ARR_DELIM = '~^~' for row in sys.stdin: row = row.strip() sent_id, lemmas = row.split('\t') lemmas ...
fr
0.113352
#!/usr/bin/env python 1\taaaa~^~bbbb~^~cccc 2\tdddd~^~EEEE~^~ffff
2.378427
2
src/supplier/templates/supplier/urls.py
vandana0608/Pharmacy-Managament
0
3009
from django.urls import path from . import views urlpatterns = [ path('', views.SupplierList.as_view(), name='supplier_list'), path('view/<int:pk>', views.SupplierView.as_view(), name='supplier_view'), path('new', views.SupplierCreate.as_view(), name='supplier_new'), path('view/<int:pk>', views.Suppli...
from django.urls import path from . import views urlpatterns = [ path('', views.SupplierList.as_view(), name='supplier_list'), path('view/<int:pk>', views.SupplierView.as_view(), name='supplier_view'), path('new', views.SupplierCreate.as_view(), name='supplier_new'), path('view/<int:pk>', views.Suppli...
none
1
1.769325
2
web_scraper/extract/common.py
rarc41/web_scraper_pro
0
3010
<reponame>rarc41/web_scraper_pro<filename>web_scraper/extract/common.py import yaml __config=None def config(): global __config if not __config: with open('config.yaml', mode='r') as f: __config=yaml.safe_load(f) return __config
import yaml __config=None def config(): global __config if not __config: with open('config.yaml', mode='r') as f: __config=yaml.safe_load(f) return __config
none
1
2.145251
2
engine/config/constant.py
infiniteloop98/lazies-cmd
1
3011
APP_PROFILE_DIRECTORY_NAME = 'lazies-cmd' DOSKEY_FILE_NAME = 'doskey.bat' AUTO_RUN_REGISTRY_NAME = 'AutoRun'
APP_PROFILE_DIRECTORY_NAME = 'lazies-cmd' DOSKEY_FILE_NAME = 'doskey.bat' AUTO_RUN_REGISTRY_NAME = 'AutoRun'
none
1
1.119077
1
sequence/get_seqs_from_list.py
fanglu01/cDNA_Cupcake
1
3012
#!/usr/bin/env python import os, sys from Bio import SeqIO def get_seqs_from_list(fastafile, listfile): seqs = [line.strip() for line in open(listfile)] for r in SeqIO.parse(open(fastafile), 'fasta'): if r.id in seqs or r.id.split('|')[0] in seqs or any(r.id.startswith(x) for x in seqs): pr...
#!/usr/bin/env python import os, sys from Bio import SeqIO def get_seqs_from_list(fastafile, listfile): seqs = [line.strip() for line in open(listfile)] for r in SeqIO.parse(open(fastafile), 'fasta'): if r.id in seqs or r.id.split('|')[0] in seqs or any(r.id.startswith(x) for x in seqs): pr...
ru
0.26433
#!/usr/bin/env python
3.583136
4
ppos_dex_data.py
cusma/pposdex
10
3013
<gh_stars>1-10 import time import json import base64 import msgpack from schema import Schema, And, Optional from datetime import datetime from algosdk import mnemonic from algosdk.account import address_from_private_key from algosdk.error import * from algosdk.future.transaction import PaymentTxn from inequality_inde...
import time import json import base64 import msgpack from schema import Schema, And, Optional from datetime import datetime from algosdk import mnemonic from algosdk.account import address_from_private_key from algosdk.error import * from algosdk.future.transaction import PaymentTxn from inequality_indexes import * fro...
en
0.756677
Wait until the transaction is confirmed or rejected, or until 'timeout' number of rounds have passed. Args: algod_client (AlgodClient): Algod Client transaction_id (str): the transaction to wait for timeout (int): maximum number of rounds to wait Returns: (dict): pending tr...
2.260021
2
src/test/python/programmingtheiot/part01/unit/system/SystemMemUtilTaskTest.py
Zhengrui-Liu/FireAlarmingSysCDA
0
3014
##### # # This class is part of the Programming the Internet of Things # project, and is available via the MIT License, which can be # found in the LICENSE file at the top level of this repository. # # Copyright (c) 2020 by <NAME> # import logging import unittest from programmingtheiot.cda.system.SystemMemUtilTask...
##### # # This class is part of the Programming the Internet of Things # project, and is available via the MIT License, which can be # found in the LICENSE file at the top level of this repository. # # Copyright (c) 2020 by <NAME> # import logging import unittest from programmingtheiot.cda.system.SystemMemUtilTask...
en
0.907756
##### # # This class is part of the Programming the Internet of Things # project, and is available via the MIT License, which can be # found in the LICENSE file at the top level of this repository. # # Copyright (c) 2020 by <NAME> # This test case class contains very basic unit tests for SystemMemUtilTask. It should n...
2.932331
3
api/base/settings/defaults.py
mattclark/osf.io
0
3015
""" Django settings for api project. Generated by 'django-admin startproject' using Django 1.8. For more information on this file, see https://docs.djangoproject.com/en/1.8/topics/settings/ For the full list of settings and their values, see https://docs.djangoproject.com/en/1.8/ref/settings/ """ import os from url...
""" Django settings for api project. Generated by 'django-admin startproject' using Django 1.8. For more information on this file, see https://docs.djangoproject.com/en/1.8/topics/settings/ For the full list of settings and their values, see https://docs.djangoproject.com/en/1.8/ref/settings/ """ import os from url...
en
0.708137
Django settings for api project. Generated by 'django-admin startproject' using Django 1.8. For more information on this file, see https://docs.djangoproject.com/en/1.8/topics/settings/ For the full list of settings and their values, see https://docs.djangoproject.com/en/1.8/ref/settings/ # Quick-start development s...
1.946835
2
tests/__init__.py
GTedHa/gblackboard
0
3016
# -*- coding: utf-8 -*- """Unit test package for gblackboard."""
# -*- coding: utf-8 -*- """Unit test package for gblackboard."""
en
0.796495
# -*- coding: utf-8 -*- Unit test package for gblackboard.
0.872825
1
src/fabricflow/fibc/api/fibcapis_pb2_grpc.py
RudSmith/beluganos
119
3017
# Generated by the gRPC Python protocol compiler plugin. DO NOT EDIT! import grpc import fibcapi_pb2 as fibcapi__pb2 import fibcapis_pb2 as fibcapis__pb2 class FIBCApApiStub(object): # missing associated documentation comment in .proto file pass def __init__(self, channel): """Constructor. Args: ...
# Generated by the gRPC Python protocol compiler plugin. DO NOT EDIT! import grpc import fibcapi_pb2 as fibcapi__pb2 import fibcapis_pb2 as fibcapis__pb2 class FIBCApApiStub(object): # missing associated documentation comment in .proto file pass def __init__(self, channel): """Constructor. Args: ...
en
0.68985
# Generated by the gRPC Python protocol compiler plugin. DO NOT EDIT! # missing associated documentation comment in .proto file Constructor. Args: channel: A grpc.Channel. # missing associated documentation comment in .proto file # missing associated documentation comment in .proto file # missing associated ...
1.717561
2
cymbology/identifiers/__init__.py
pmart123/security_id
12
3018
<gh_stars>10-100 from cymbology.identifiers.sedol import Sedol from cymbology.identifiers.cusip import Cusip, cusip_from_isin from cymbology.identifiers.isin import Isin __all__ = ('Sedol', 'Cusip', 'cusip_from_isin', 'Isin')
from cymbology.identifiers.sedol import Sedol from cymbology.identifiers.cusip import Cusip, cusip_from_isin from cymbology.identifiers.isin import Isin __all__ = ('Sedol', 'Cusip', 'cusip_from_isin', 'Isin')
none
1
1.789364
2
api/src/error_report/models.py
Noahffiliation/corpus-christi
35
3019
from marshmallow import Schema, fields from marshmallow.validate import Range, Length from sqlalchemy import Column, Integer, Boolean, DateTime from ..db import Base from ..shared.models import StringTypes # ---- Error-report class ErrorReport(Base): __tablename__ = 'error_report' id = Column(Integer, prim...
from marshmallow import Schema, fields from marshmallow.validate import Range, Length from sqlalchemy import Column, Integer, Boolean, DateTime from ..db import Base from ..shared.models import StringTypes # ---- Error-report class ErrorReport(Base): __tablename__ = 'error_report' id = Column(Integer, prim...
en
0.352795
# ---- Error-report
2.412125
2
Python/Vowel-Substring/solution.py
arpitran/HackerRank_solutions
0
3020
<reponame>arpitran/HackerRank_solutions #!/bin/python3 import math import os import random import re import sys # # Complete the 'findSubstring' function below. # # The function is expected to return a STRING. # The function accepts following parameters: # 1. STRING s # 2. INTEGER k # def isVowel(x): if(x=="...
#!/bin/python3 import math import os import random import re import sys # # Complete the 'findSubstring' function below. # # The function is expected to return a STRING. # The function accepts following parameters: # 1. STRING s # 2. INTEGER k # def isVowel(x): if(x=="a" or x=='e' or x=='i' or x=='o' or x=='...
en
0.489266
#!/bin/python3 # # Complete the 'findSubstring' function below. # # The function is expected to return a STRING. # The function accepts following parameters: # 1. STRING s # 2. INTEGER k # # Write your code here
3.988847
4
nima/models/productos/constants.py
erichav/NIMA
0
3021
<reponame>erichav/NIMA COLLECTION = 'productos'
COLLECTION = 'productos'
none
1
1.168028
1
deepchem/metrics/score_function.py
hsjang001205/deepchem
1
3022
<reponame>hsjang001205/deepchem<filename>deepchem/metrics/score_function.py """Evaluation metrics.""" import numpy as np from sklearn.metrics import matthews_corrcoef # noqa from sklearn.metrics import recall_score # noqa from sklearn.metrics import cohen_kappa_score from sklearn.metrics import r2_score # noqa from...
"""Evaluation metrics.""" import numpy as np from sklearn.metrics import matthews_corrcoef # noqa from sklearn.metrics import recall_score # noqa from sklearn.metrics import cohen_kappa_score from sklearn.metrics import r2_score # noqa from sklearn.metrics import mean_squared_error from sklearn.metrics import mean_...
en
0.658596
Evaluation metrics. # noqa # noqa # noqa # noqa # noqa # noqa # noqa # kappa_score is an alias for `sklearn.metrics.cohen_kappa_score` Computes Pearson R^2 (square of Pearson correlation). Parameters ---------- y: np.ndarray ground truth array y_pred: np.ndarray predicted array Returns ------- f...
2.719385
3
hvm/chains/base.py
hyperevo/py-helios-node
0
3023
<reponame>hyperevo/py-helios-node from __future__ import absolute_import import operator from collections import deque import functools from abc import ( ABCMeta, abstractmethod ) import rlp_cython as rlp import time import math from uuid import UUID from typing import ( # noqa: F401 Any, Optional, ...
from __future__ import absolute_import import operator from collections import deque import functools from abc import ( ABCMeta, abstractmethod ) import rlp_cython as rlp import time import math from uuid import UUID from typing import ( # noqa: F401 Any, Optional, Callable, cast, Dict, ...
en
0.831571
# noqa: F401 # noqa: F401 # Mapping from address to account state. # 'balance', 'nonce' -> int # 'code' -> bytes # 'storage' -> Dict[int, int] The base class for all Chain objects # type: Type[BaseChainDB] # type: Tuple[Tuple[int, Type[BaseVM]], ...] # # Helpers # # # Chain API # # # VM API # Returns the VM instance fo...
1.445672
1
integreat_cms/api/v3/regions.py
Integreat/cms-django
21
3024
<filename>integreat_cms/api/v3/regions.py """ This module includes functions related to the regions API endpoint. """ from django.http import JsonResponse from ...cms.models import Region from ...cms.constants import region_status from ..decorators import json_response def transform_region(region): """ Funct...
<filename>integreat_cms/api/v3/regions.py """ This module includes functions related to the regions API endpoint. """ from django.http import JsonResponse from ...cms.models import Region from ...cms.constants import region_status from ..decorators import json_response def transform_region(region): """ Funct...
en
0.716906
This module includes functions related to the regions API endpoint. Function to create a JSON from a single region object, including information if region is live/active. :param region: The region object which should be converted :type region: ~integreat_cms.cms.models.regions.region.Region :return: data ...
2.570915
3
cli/src/ansible/AnsibleVarsGenerator.py
romsok24/epiphany
0
3025
<filename>cli/src/ansible/AnsibleVarsGenerator.py import copy import os from cli.src.Config import Config from cli.src.helpers.build_io import (get_ansible_path, get_ansible_path_for_build, get_ansible_vault_path) from cli.src.helpers.data_loa...
<filename>cli/src/ansible/AnsibleVarsGenerator.py import copy import os from cli.src.Config import Config from cli.src.helpers.build_io import (get_ansible_path, get_ansible_path_for_build, get_ansible_vault_path) from cli.src.helpers.data_loa...
en
0.861113
# reserved word in ansible! # For upgrade we always need common, repository, image_registry, node_exporter and postgresql. Common is # already provisioned from the cluster model constructed from the inventory. As PostgreSQL configuration # is changed between versions (e.g. wal_keep_segments -> wal_keep_size) and someti...
1.941914
2
Python/4 kyu/Snail/test_snail.py
newtonsspawn/codewars_challenges
3
3026
<filename>Python/4 kyu/Snail/test_snail.py<gh_stars>1-10 from unittest import TestCase from snail import snail class TestSnail(TestCase): def test_snail_001(self): self.assertEqual(snail([[]]), []) def test_snail_002(self): self.assertEqual(snail([[1]]), [1]) def test_snail...
<filename>Python/4 kyu/Snail/test_snail.py<gh_stars>1-10 from unittest import TestCase from snail import snail class TestSnail(TestCase): def test_snail_001(self): self.assertEqual(snail([[]]), []) def test_snail_002(self): self.assertEqual(snail([[1]]), [1]) def test_snail...
none
1
2.766312
3
python/tink/jwt/_raw_jwt.py
cuonglm/tink
0
3027
<gh_stars>0 # Copyright 2021 Google LLC # # Licensed under the Apache License, Version 2.0 (the "License"); # you may not use this file except in compliance with the License. # You may obtain a copy of the License at # # http://www.apache.org/licenses/LICENSE-2.0 # # Unless required by applicable law or agreed to ...
# Copyright 2021 Google LLC # # Licensed under the Apache License, Version 2.0 (the "License"); # you may not use this file except in compliance with the License. # You may obtain a copy of the License at # # http://www.apache.org/licenses/LICENSE-2.0 # # Unless required by applicable law or agreed to in writing, ...
en
0.87678
# Copyright 2021 Google LLC # # Licensed under the Apache License, Version 2.0 (the "License"); # you may not use this file except in compliance with the License. # You may obtain a copy of the License at # # http://www.apache.org/licenses/LICENSE-2.0 # # Unless required by applicable law or agreed to in writing, ...
2.042974
2
plenum/test/view_change/test_no_instance_change_before_node_is_ready.py
evernym/indy-plenum
0
3028
import pytest from plenum.server.view_change.view_changer import ViewChanger from stp_core.common.log import getlogger from plenum.test.pool_transactions.helper import start_not_added_node, add_started_node logger = getlogger() @pytest.fixture(scope="module", autouse=True) def tconf(tconf): old_vc_timeout = tc...
import pytest from plenum.server.view_change.view_changer import ViewChanger from stp_core.common.log import getlogger from plenum.test.pool_transactions.helper import start_not_added_node, add_started_node logger = getlogger() @pytest.fixture(scope="module", autouse=True) def tconf(tconf): old_vc_timeout = tc...
en
0.89895
Test steps: 1. create a new node, but don't add it to the pool (so not send NODE txn), so that the node is not ready. 2. wait for more than VIEW_CHANGE_TIMEOUT (a timeout for initial check for disconnected primary) 3. make sure no InstanceChange sent by the new node 4. add the node to the pool (send NOD...
2.033439
2
src/cache/requests_cache_abstract.py
tomaszkingukrol/rest-api-cache-proxy
0
3029
<reponame>tomaszkingukrol/rest-api-cache-proxy from abc import ABC, abstractclassmethod from model.response import ResponseModel class CacheInterface(ABC): @abstractclassmethod async def get(cls, url: str) -> ResponseModel: pass @abstractclassmethod async def set(cls, url: str, value: ResponseModel,...
from abc import ABC, abstractclassmethod from model.response import ResponseModel class CacheInterface(ABC): @abstractclassmethod async def get(cls, url: str) -> ResponseModel: pass @abstractclassmethod async def set(cls, url: str, value: ResponseModel, ttl=0): pass
none
1
2.78438
3
dialogue-engine/test/programytest/config/file/test_json.py
cotobadesign/cotoba-agent-oss
104
3030
""" Copyright (c) 2020 COTOBA DESIGN, Inc. Permission is hereby granted, free of charge, to any person obtaining a copy of this software and associated documentation files (the "Software"), to deal in the Software without restriction, including without limitation the rights to use, copy, modify, merge, publish, distri...
""" Copyright (c) 2020 COTOBA DESIGN, Inc. Permission is hereby granted, free of charge, to any person obtaining a copy of this software and associated documentation files (the "Software"), to deal in the Software without restriction, including without limitation the rights to use, copy, modify, merge, publish, distri...
en
0.331915
Copyright (c) 2020 COTOBA DESIGN, Inc. Permission is hereby granted, free of charge, to any person obtaining a copy of this software and associated documentation files (the "Software"), to deal in the Software without restriction, including without limitation the rights to use, copy, modify, merge, publish, distribute...
1.790426
2
searching/jump_search.py
magnusrodseth/data-structures-and-algorithms
0
3031
import math from typing import List def jump_search(array: List[int], value: int) -> int: """ Performs a jump search on a list of integers. :param array: is the array to search. :param value: is the value to search. :return: the index of the value, or -1 if it doesn't exist.' """ if len(ar...
import math from typing import List def jump_search(array: List[int], value: int) -> int: """ Performs a jump search on a list of integers. :param array: is the array to search. :param value: is the value to search. :return: the index of the value, or -1 if it doesn't exist.' """ if len(ar...
en
0.870113
Performs a jump search on a list of integers. :param array: is the array to search. :param value: is the value to search. :return: the index of the value, or -1 if it doesn't exist.' # Pointers for traversing the array # Prevent next from going out of bounds # Linear search through the relevant block Gets t...
4.400256
4
pincer/objects/message/sticker.py
mjneff2/Pincer
0
3032
<reponame>mjneff2/Pincer # Copyright Pincer 2021-Present # Full MIT License can be found in `LICENSE` at the project root. from __future__ import annotations from dataclasses import dataclass from enum import IntEnum from typing import List, Optional, TYPE_CHECKING from ...utils.api_object import APIObject from ...u...
# Copyright Pincer 2021-Present # Full MIT License can be found in `LICENSE` at the project root. from __future__ import annotations from dataclasses import dataclass from enum import IntEnum from typing import List, Optional, TYPE_CHECKING from ...utils.api_object import APIObject from ...utils.types import MISSING...
en
0.792613
# Copyright Pincer 2021-Present # Full MIT License can be found in `LICENSE` at the project root. Displays from where the sticker comes from. :param STANDARD: Sticker is included in the default Discord sticker pack. :param GUILD: Sticker is a custom sticker from a discord server. The type of t...
2.213972
2
app/core/utils.py
yayunl/llfselfhelp
0
3033
from django.views.generic import \ UpdateView as BaseUpdateView class UpdateView(BaseUpdateView): template_name_suffix = '_form_update'
from django.views.generic import \ UpdateView as BaseUpdateView class UpdateView(BaseUpdateView): template_name_suffix = '_form_update'
none
1
1.316206
1
demo/test_bug_3d.py
zhanwj/multi-task-pytorch
2
3034
import torch import lib.modeling.resnet as resnet import lib.modeling.semseg_heads as snet import torch.nn as nn import torch.optim as optim import utils.resnet_weights_helper as resnet_utils from torch.autograd import Variable from roi_data.loader import RoiDataLoader, MinibatchSampler, collate_minibatch, collate_mini...
import torch import lib.modeling.resnet as resnet import lib.modeling.semseg_heads as snet import torch.nn as nn import torch.optim as optim import utils.resnet_weights_helper as resnet_utils from torch.autograd import Variable from roi_data.loader import RoiDataLoader, MinibatchSampler, collate_minibatch, collate_mini...
en
0.157011
#load net #cfg_from_list(cfg_file) #assert_and_infer_cfg() #torch.cuda.set_device(3) #net = mynn.DataParallel(load_net().to('cuda'), minibatch=True) #dataloader= dataloader(batch_size, len_gpus) #for i, inputs in zip(range(1000), dataloader):
1.905359
2
regenesis/modelgen.py
crijke/regenesis
16
3035
<reponame>crijke/regenesis<filename>regenesis/modelgen.py import json from regenesis.queries import get_cubes, get_all_dimensions, get_dimensions from pprint import pprint def generate_dimensions(): dimensions = [] for dimension in get_all_dimensions(): pprint (dimension) if dimension.get('mea...
import json from regenesis.queries import get_cubes, get_all_dimensions, get_dimensions from pprint import pprint def generate_dimensions(): dimensions = [] for dimension in get_all_dimensions(): pprint (dimension) if dimension.get('measure_type').startswith('W-'): continue ...
none
1
2.396489
2
tests/components/evil_genius_labs/test_light.py
liangleslie/core
30,023
3036
<gh_stars>1000+ """Test Evil Genius Labs light.""" from unittest.mock import patch import pytest from homeassistant.components.light import ( ATTR_COLOR_MODE, ATTR_SUPPORTED_COLOR_MODES, ColorMode, LightEntityFeature, ) from homeassistant.const import ATTR_SUPPORTED_FEATURES @pytest.mark.parametrize...
"""Test Evil Genius Labs light.""" from unittest.mock import patch import pytest from homeassistant.components.light import ( ATTR_COLOR_MODE, ATTR_SUPPORTED_COLOR_MODES, ColorMode, LightEntityFeature, ) from homeassistant.const import ATTR_SUPPORTED_FEATURES @pytest.mark.parametrize("platforms", [(...
en
0.89046
Test Evil Genius Labs light. Test it works. Test turning on with a color. Test turning on with an effect. Test turning off.
2.428049
2
python_on_whales/download_binaries.py
joshbode/python-on-whales
0
3037
import platform import shutil import tempfile import warnings from pathlib import Path import requests from tqdm import tqdm DOCKER_VERSION = "20.10.5" BUILDX_VERSION = "0.5.1" CACHE_DIR = Path.home() / ".cache" / "python-on-whales" TEMPLATE_CLI = ( "https://download.docker.com/{os}/static/stable/{arch}/docker-...
import platform import shutil import tempfile import warnings from pathlib import Path import requests from tqdm import tqdm DOCKER_VERSION = "20.10.5" BUILDX_VERSION = "0.5.1" CACHE_DIR = Path.home() / ".cache" / "python-on-whales" TEMPLATE_CLI = ( "https://download.docker.com/{os}/static/stable/{arch}/docker-...
en
0.790508
# Streaming, so we can iterate over the response. # I don't know the exact list of possible architectures, # so if a user reports a NotImplementedError, we can easily add # his/her platform here.
2.298099
2
reinvent-2019/connected-photo-booth/lambda_code/Cerebro_GetQRCode.py
chriscoombs/aws-builders-fair-projects
0
3038
import boto3 import json import os import logging from contextlib import closing from boto3.dynamodb.conditions import Key, Attr from botocore.exceptions import ClientError from random import shuffle import time import pyqrcode import png __BUCKET_NAME__ = "project-cerebro" dynamo = boto3.client('dynamodb') logg...
import boto3 import json import os import logging from contextlib import closing from boto3.dynamodb.conditions import Key, Attr from botocore.exceptions import ClientError from random import shuffle import time import pyqrcode import png __BUCKET_NAME__ = "project-cerebro" dynamo = boto3.client('dynamodb') logg...
en
0.625812
Generate a presigned URL to share an S3 object :param bucket_name: string :param object_name: string :param expiration: Time in seconds for the presigned URL to remain valid :return: Presigned URL as string. If error, returns None. # Generate a presigned URL for the S3 object # The response contains th...
2.162849
2
dependencies/svgwrite/tests/test_drawing.py
charlesmchen/typefacet
21
3039
<filename>dependencies/svgwrite/tests/test_drawing.py #!/usr/bin/env python #coding:utf-8 # Author: mozman --<<EMAIL>> # Purpose: test drawing module # Created: 11.09.2010 # Copyright (C) 2010, <NAME> # License: GPLv3 from __future__ import unicode_literals import os import unittest from io import StringIO...
<filename>dependencies/svgwrite/tests/test_drawing.py #!/usr/bin/env python #coding:utf-8 # Author: mozman --<<EMAIL>> # Purpose: test drawing module # Created: 11.09.2010 # Copyright (C) 2010, <NAME> # License: GPLv3 from __future__ import unicode_literals import os import unittest from io import StringIO...
en
0.327929
#!/usr/bin/env python #coding:utf-8 # Author: mozman --<<EMAIL>> # Purpose: test drawing module # Created: 11.09.2010 # Copyright (C) 2010, <NAME> # License: GPLv3
2.312303
2
src/cms/views/error_handler/error_handler.py
digitalfabrik/coldaid-backend
4
3040
<reponame>digitalfabrik/coldaid-backend<gh_stars>1-10 from django.shortcuts import render from django.utils.translation import ugettext as _ # pylint: disable=unused-argument def handler400(request, exception): ctx = {'code': 400, 'title': _('Bad request'), 'message': _('There was an error in your requ...
from django.shortcuts import render from django.utils.translation import ugettext as _ # pylint: disable=unused-argument def handler400(request, exception): ctx = {'code': 400, 'title': _('Bad request'), 'message': _('There was an error in your request.')} response = render(request, 'error_handler/...
en
0.229153
# pylint: disable=unused-argument # pylint: disable=unused-argument # pylint: disable=unused-argument # pylint: disable=unused-argument # pylint: disable=unused-argument
2.073759
2
examples/ex3/app/models.py
trym-inc/django-msg
7
3041
from typing import NamedTuple from django.contrib.auth.models import AbstractUser from django.db import models from msg.models import Msg class User(AbstractUser): phone_number: 'str' = models.CharField(max_length=255, null=True, blank=True) class HelloSMSMessage(...
from typing import NamedTuple from django.contrib.auth.models import AbstractUser from django.db import models from msg.models import Msg class User(AbstractUser): phone_number: 'str' = models.CharField(max_length=255, null=True, blank=True) class HelloSMSMessage(...
none
1
2.78219
3
Data_Structures/2d_array_ds.py
csixteen/HackerRank
4
3042
<gh_stars>1-10 matrix = [list(map(int, input().split())) for _ in range(6)] max_sum = None for i in range(4): for j in range(4): s = sum(matrix[i][j:j+3]) + matrix[i+1][j+1] + sum(matrix[i+2][j:j+3]) if max_sum is None or s > max_sum: max_sum = s print(max_sum)
matrix = [list(map(int, input().split())) for _ in range(6)] max_sum = None for i in range(4): for j in range(4): s = sum(matrix[i][j:j+3]) + matrix[i+1][j+1] + sum(matrix[i+2][j:j+3]) if max_sum is None or s > max_sum: max_sum = s print(max_sum)
none
1
3.292345
3
sklearn/utils/_bunch.py
jlopezNEU/scikit-learn
3
3043
<filename>sklearn/utils/_bunch.py class Bunch(dict): """Container object exposing keys as attributes. Bunch objects are sometimes used as an output for functions and methods. They extend dictionaries by enabling values to be accessed by key, `bunch["value_key"]`, or by an attribute, `bunch.value_key`. ...
<filename>sklearn/utils/_bunch.py class Bunch(dict): """Container object exposing keys as attributes. Bunch objects are sometimes used as an output for functions and methods. They extend dictionaries by enabling values to be accessed by key, `bunch["value_key"]`, or by an attribute, `bunch.value_key`. ...
en
0.769651
Container object exposing keys as attributes. Bunch objects are sometimes used as an output for functions and methods. They extend dictionaries by enabling values to be accessed by key, `bunch["value_key"]`, or by an attribute, `bunch.value_key`. Examples -------- >>> from sklearn.utils import...
3.646791
4
tfx/examples/chicago_taxi_pipeline/serving/chicago_taxi_client.py
pingsutw/tfx
1
3044
# Lint as: python2, python3 # Copyright 2019 Google LLC. 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 # # https://www.apache.org/licenses/LICENSE-2.0 # # Unless re...
# Lint as: python2, python3 # Copyright 2019 Google LLC. 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 # # https://www.apache.org/licenses/LICENSE-2.0 # # Unless re...
en
0.767713
# Lint as: python2, python3 # Copyright 2019 Google LLC. 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 # # https://www.apache.org/licenses/LICENSE-2.0 # # Unless re...
1.680917
2
PyVideo/main.py
BlackIQ/Cute
5
3045
<gh_stars>1-10 from PyQt5.QtCore import (pyqtSignal, pyqtSlot, Q_ARG, QAbstractItemModel, QFileInfo, qFuzzyCompare, QMetaObject, QModelIndex, QObject, Qt, QThread, QTime, QUrl) from PyQt5.QtGui import QColor, qGray, QImage, QPainter, QPalette from PyQt5.QtMultimedia import (QAbstractVideoBuffer, QMediaC...
from PyQt5.QtCore import (pyqtSignal, pyqtSlot, Q_ARG, QAbstractItemModel, QFileInfo, qFuzzyCompare, QMetaObject, QModelIndex, QObject, Qt, QThread, QTime, QUrl) from PyQt5.QtGui import QColor, qGray, QImage, QPainter, QPalette from PyQt5.QtMultimedia import (QAbstractVideoBuffer, QMediaContent, ...
en
0.749498
# Process YUV data. # Process RGB data. # Find the maximum value. # Normalise the values between 0 and 1. # Draw the level. # Clear the rest of the control. # Go to the previous track if we are within the first 5 seconds of # playback. Otherwise, seek to the beginning.
2.001901
2
tests/snapshot/periodic.py
Uornca/mirheo
22
3046
#!/usr/bin/env python """Test checkpoint-like periodic snapshots. We test that there are that many folders and that the currentStep changes. """ import mirheo as mir u = mir.Mirheo(nranks=(1, 1, 1), domain=(4, 6, 8), debug_level=3, log_filename='log', no_splash=True, checkpoint_every=1...
#!/usr/bin/env python """Test checkpoint-like periodic snapshots. We test that there are that many folders and that the currentStep changes. """ import mirheo as mir u = mir.Mirheo(nranks=(1, 1, 1), domain=(4, 6, 8), debug_level=3, log_filename='log', no_splash=True, checkpoint_every=1...
en
0.548523
#!/usr/bin/env python Test checkpoint-like periodic snapshots. We test that there are that many folders and that the currentStep changes. # TEST: snapshot.periodic # cd snapshot # rm -rf periodic_snapshots/ # mir.run --runargs "-n 2" ./periodic.py # ls periodic_snapshots | cat > snapshot.out.txt # grep -rH --include=*...
2.236528
2
tools/resource_prefetch_predictor/generate_database.py
xzhan96/chromium.src
1
3047
<filename>tools/resource_prefetch_predictor/generate_database.py #!/usr/bin/python # # Copyright 2016 The Chromium Authors. All rights reserved. # Use of this source code is governed by a BSD-style license that can be # found in the LICENSE file. """Loads a set of web pages several times on a device, and extracts the ...
<filename>tools/resource_prefetch_predictor/generate_database.py #!/usr/bin/python # # Copyright 2016 The Chromium Authors. All rights reserved. # Use of this source code is governed by a BSD-style license that can be # found in the LICENSE file. """Loads a set of web pages several times on a device, and extracts the ...
en
0.726963
#!/usr/bin/python # # Copyright 2016 The Chromium Authors. All rights reserved. # Use of this source code is governed by a BSD-style license that can be # found in the LICENSE file. Loads a set of web pages several times on a device, and extracts the predictor database. Creates and returns the argument parser. Returns ...
2.418945
2
palm_wrapper/job_submission/domain.py
madeline-scyphers/palm
0
3048
from abc import ABC, abstractmethod from typing import Optional from xml import dom import numpy as np import pandas as pd from .utils import get_factors_rev def calc_plot_size(domain_x, domain_y, plot_goal, house_goal): f1 = sorted(get_factors_rev(domain_x)) f2 = sorted(get_factors_rev(domain_y)) plot_...
from abc import ABC, abstractmethod from typing import Optional from xml import dom import numpy as np import pandas as pd from .utils import get_factors_rev def calc_plot_size(domain_x, domain_y, plot_goal, house_goal): f1 = sorted(get_factors_rev(domain_x)) f2 = sorted(get_factors_rev(domain_y)) plot_...
en
0.296729
# tmp["ratio_diff"] = abs(((tmp.trimmed_area) / tmp.full_domain - plot_ratio)) # tmp = tmp.sort_values(by=["goal_diff", "domain_y_diff", "trimmed_area"], ascending=[True, True, False]) Get the numpy matrix representation of the domain area # self._validate_matrix_size(subplot=self.subplot) # stack for surface scalar to...
2.636034
3
zad5.py
Alba126/Laba21
0
3049
#!/usr/bin/env python3 # -*- config: utf-8 -*- from tkinter import * from random import random def on_click(): x = random() y = random() bt1.place(relx=x, rely=y) root = Tk() root['bg'] = 'white' root.title('crown') img = PhotoImage(file='crown.png') bt1 = Button(image=img, command=on_click) bt1.place...
#!/usr/bin/env python3 # -*- config: utf-8 -*- from tkinter import * from random import random def on_click(): x = random() y = random() bt1.place(relx=x, rely=y) root = Tk() root['bg'] = 'white' root.title('crown') img = PhotoImage(file='crown.png') bt1 = Button(image=img, command=on_click) bt1.place...
en
0.164492
#!/usr/bin/env python3 # -*- config: utf-8 -*-
3.49402
3
tests/importer/utils/test_utils.py
HumanCellAtlas/ingest-common
0
3050
<gh_stars>0 from openpyxl import Workbook def create_test_workbook(*worksheet_titles, include_default_sheet=False): workbook = Workbook() for title in worksheet_titles: workbook.create_sheet(title) if not include_default_sheet: default_sheet = workbook['Sheet'] workbook.remove(def...
from openpyxl import Workbook def create_test_workbook(*worksheet_titles, include_default_sheet=False): workbook = Workbook() for title in worksheet_titles: workbook.create_sheet(title) if not include_default_sheet: default_sheet = workbook['Sheet'] workbook.remove(default_sheet) ...
none
1
2.633658
3
test/test_import_stats.py
WBobby/pytorch
24
3051
<gh_stars>10-100 import subprocess import sys import unittest import pathlib from torch.testing._internal.common_utils import TestCase, run_tests, IS_LINUX, IS_IN_CI REPO_ROOT = pathlib.Path(__file__).resolve().parent.parent try: # Just in case PyTorch was not built in 'develop' mode sys.path.append(str(REP...
import subprocess import sys import unittest import pathlib from torch.testing._internal.common_utils import TestCase, run_tests, IS_LINUX, IS_IN_CI REPO_ROOT = pathlib.Path(__file__).resolve().parent.parent try: # Just in case PyTorch was not built in 'develop' mode sys.path.append(str(REPO_ROOT)) from...
en
0.938636
# Just in case PyTorch was not built in 'develop' mode # these tests could eventually be changed to fail if the import/init # time is greater than a certain threshold, but for now we just use them # as a way to track the duration of `import torch` in our ossci-metrics # S3 bucket (see tools/stats/print_test_stats.py)
1.996759
2
post_office/validators.py
fasih/django-post_office
661
3052
from django.core.exceptions import ValidationError from django.core.validators import validate_email from django.template import Template, TemplateSyntaxError, TemplateDoesNotExist from django.utils.encoding import force_str def validate_email_with_name(value): """ Validate email address. Both "<NAME> <<...
from django.core.exceptions import ValidationError from django.core.validators import validate_email from django.template import Template, TemplateSyntaxError, TemplateDoesNotExist from django.utils.encoding import force_str def validate_email_with_name(value): """ Validate email address. Both "<NAME> <<...
en
0.727427
Validate email address. Both "<NAME> <<EMAIL>>" and "<EMAIL>" are valid. Validate every email address in a comma separated list of emails. Basic Django Template syntax validation. This allows for robuster template authoring.
2.763173
3
paperhub/input.py
GiuseppeBaldini/PaperHub
0
3053
# Input DOI / URL import re import sys # Pyperclip is not built-in, check and download if needed try: import pyperclip except (ImportError, ModuleNotFoundError): print('Pyperclip module not found. Please download it.') sys.exit(0) # Regex for links link_regex = re.compile(r'''( http[s]?:// (?:[a-...
# Input DOI / URL import re import sys # Pyperclip is not built-in, check and download if needed try: import pyperclip except (ImportError, ModuleNotFoundError): print('Pyperclip module not found. Please download it.') sys.exit(0) # Regex for links link_regex = re.compile(r'''( http[s]?:// (?:[a-...
en
0.407398
# Input DOI / URL # Pyperclip is not built-in, check and download if needed # Regex for links ( http[s]?:// (?:[a-zA-Z]| [0-9]| [$-_@.&+]| [!*\(\),]| (?:%[0-9a-fA-F][0-9a-fA-F]))+ ) # Get DOI / URL using different methods # Method 1: argument # Method 2: clipboard # Method 3: manual input Ch...
3.300607
3
main.py
chillum1718/EffcientNetV2
0
3054
<filename>main.py import argparse import csv import os import torch import tqdm from torch import distributed from torch.utils import data from torchvision import datasets from torchvision import transforms from nets import nn from utils import util data_dir = os.path.join('..', 'Dataset', 'IMAGENET') def batch(im...
<filename>main.py import argparse import csv import os import torch import tqdm from torch import distributed from torch.utils import data from torchvision import datasets from torchvision import transforms from nets import nn from utils import util data_dir = os.path.join('..', 'Dataset', 'IMAGENET') def batch(im...
en
0.14737
# python -m torch.distributed.launch --nproc_per_node=3 main.py --train
2.47462
2
cgbind/esp.py
duartegroup/cgbind
7
3055
<gh_stars>1-10 import numpy as np from time import time from cgbind.atoms import get_atomic_number from cgbind.log import logger from cgbind.constants import Constants from cgbind.exceptions import CgbindCritical def get_esp_cube_lines(charges, atoms): """ From a list of charges and a set of xyzs create the e...
import numpy as np from time import time from cgbind.atoms import get_atomic_number from cgbind.log import logger from cgbind.constants import Constants from cgbind.exceptions import CgbindCritical def get_esp_cube_lines(charges, atoms): """ From a list of charges and a set of xyzs create the electrostatic po...
en
0.687027
From a list of charges and a set of xyzs create the electrostatic potential map grid-ed uniformly between the most negative x, y, z values -5 Å and the largest x, y, z +5 Å :param charges: (list(float)) :param atoms: (list(autode.atoms.Atom)) :return: (list(str)), (min ESP value, max ESP value) # G...
2.524609
3
codes/test_specular.py
mcdenoising/AdvMCDenoise
35
3056
import os import sys import logging import time import argparse import numpy as np from collections import OrderedDict import scripts.options as option import utils.util as util from data.util import bgr2ycbcr from data import create_dataset, create_dataloader from models import create_model # options parser = argpar...
import os import sys import logging import time import argparse import numpy as np from collections import OrderedDict import scripts.options as option import utils.util as util from data.util import bgr2ycbcr from data import create_dataset, create_dataloader from models import create_model # options parser = argpar...
en
0.27746
# options # Create test dataset and dataloader # Create model # need_GT = True # test # uint8 # uint8 # save images # calculate PSNR and SSIM # gt_img = util.tensor2img(visuals['GT']) #[crop_border:-crop_border, crop_border:-crop_border, :] #[crop_border:-crop_border, crop_border:-crop_border, :] # RGB image # uint8 # ...
2.008258
2
neuralNetwork/layer3/nerualNet.py
zzw0929/deeplearning
4
3057
<filename>neuralNetwork/layer3/nerualNet.py # coding:utf-8 import time import matplotlib.pyplot as plt import numpy as np import sklearn import sklearn.datasets import sklearn.linear_model import matplotlib matplotlib.rcParams['figure.figsize'] = (10.0, 8.0) np.random.seed(0) X, y = sklearn.datasets.make_moons(200, ...
<filename>neuralNetwork/layer3/nerualNet.py # coding:utf-8 import time import matplotlib.pyplot as plt import numpy as np import sklearn import sklearn.datasets import sklearn.linear_model import matplotlib matplotlib.rcParams['figure.figsize'] = (10.0, 8.0) np.random.seed(0) X, y = sklearn.datasets.make_moons(200, ...
en
0.729909
# coding:utf-8 # plt.show() # Helper function to plot a decision boundary. # If you don't fully understand this function don't worry, it just generates # the contour plot below. # Set min and max values and give it some padding # Generate a grid of points with distance h between them # Predict the function value for th...
3.200123
3
app/domain/create_db.py
Lifeistrange/flaskweb
0
3058
<reponame>Lifeistrange/flaskweb<filename>app/domain/create_db.py<gh_stars>0 #!/usr/bin/env python # coding=utf-8 from manage import db import app.domain.model db.create_all()
#!/usr/bin/env python # coding=utf-8 from manage import db import app.domain.model db.create_all()
en
0.244401
#!/usr/bin/env python # coding=utf-8
1.14236
1
tljh_repo2docker/tests/utils.py
TimoRoth/tljh-repo2docker
46
3059
<gh_stars>10-100 import asyncio import json from aiodocker import Docker, DockerError from jupyterhub.tests.utils import api_request async def add_environment( app, *, repo, ref="master", name="", memory="", cpu="" ): """Use the POST endpoint to add a new environment""" r = await api_request( app...
import asyncio import json from aiodocker import Docker, DockerError from jupyterhub.tests.utils import api_request async def add_environment( app, *, repo, ref="master", name="", memory="", cpu="" ): """Use the POST endpoint to add a new environment""" r = await api_request( app, "enviro...
en
0.836423
Use the POST endpoint to add a new environment wait until an image is built Use the DELETE endpoint to remove an environment
2.431536
2
05_ARIADNE_SUBSCRIPTIONS_GRAPHQL/api/resolvers/mutations/__init__.py
CrispenGari/python-flask
2
3060
from api import db from uuid import uuid4 from ariadne import MutationType from api.models import Post from api.store import queues mutation = MutationType() @mutation.field("createPost") async def create_post_resolver(obj, info, input): try: post = Post(postId=uuid4(), caption=input["caption"]) ...
from api import db from uuid import uuid4 from ariadne import MutationType from api.models import Post from api.store import queues mutation = MutationType() @mutation.field("createPost") async def create_post_resolver(obj, info, input): try: post = Post(postId=uuid4(), caption=input["caption"]) ...
none
1
2.328293
2
async_sched/client/__init__.py
justengel/async_sched
1
3061
<filename>async_sched/client/__init__.py from async_sched.client import quit_server as module_quit from async_sched.client import request_schedules as module_request from async_sched.client import run_command as module_run from async_sched.client import schedule_command as module_schedule from async_sched.client import...
<filename>async_sched/client/__init__.py from async_sched.client import quit_server as module_quit from async_sched.client import request_schedules as module_request from async_sched.client import run_command as module_run from async_sched.client import schedule_command as module_schedule from async_sched.client import...
en
0.470109
# The other modules in this package exist for the "-m" python flag # `python -m async_sched.client.request_schedules --host "172.16.17.32" --port 8000`
2.060452
2
full-stack-angular-ngrx/backend/src/core/interfaces/crud.py
t4d-classes/angular_02212022
0
3062
import abc from typing import TypeVar, Generic, List, Dict T = TypeVar('T') class CRUDInterface(Generic[T], metaclass=abc.ABCMeta): @abc.abstractmethod def all(self) -> List[T]: pass @abc.abstractmethod def one_by_id(self, entity_id: int) -> T: pass @abc.abstractmethod def ...
import abc from typing import TypeVar, Generic, List, Dict T = TypeVar('T') class CRUDInterface(Generic[T], metaclass=abc.ABCMeta): @abc.abstractmethod def all(self) -> List[T]: pass @abc.abstractmethod def one_by_id(self, entity_id: int) -> T: pass @abc.abstractmethod def ...
none
1
3.006948
3
package/tests/test_init_command.py
MrKriss/stonemason
2
3063
<filename>package/tests/test_init_command.py from pathlib import Path import pytest import git import json from conftest import TEST_DIR def test_init_with_project(tmpdir): output_path = Path(tmpdir.strpath) # Set arguments args = f"init -o {output_path} {TEST_DIR}/example_templates/python_project" ...
<filename>package/tests/test_init_command.py from pathlib import Path import pytest import git import json from conftest import TEST_DIR def test_init_with_project(tmpdir): output_path = Path(tmpdir.strpath) # Set arguments args = f"init -o {output_path} {TEST_DIR}/example_templates/python_project" ...
en
0.991896
# Set arguments # Run from entry point # Check files were created # Check requirements were polulated # Check git repo was created and commits made # Set arguments # Run from entry point # Check files were created # Check requirements were polulated # Check MANIFEST was prefixed # Check git repo was created and commits...
2.360242
2
mistral/mistral/api/controllers/v2/service.py
Toure/openstack_mistral_wip
0
3064
# Copyright 2015 Huawei Technologies Co., Ltd. # # 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 applica...
# Copyright 2015 Huawei Technologies Co., Ltd. # # 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 applica...
en
0.82753
# Copyright 2015 Huawei Technologies Co., Ltd. # # 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 applica...
1.730582
2
setup.py
jtauber/greek-utils
13
3065
from setuptools import setup setup( name="greek-utils", version="0.2", description="various utilities for processing Ancient Greek", license="MIT", url="http://github.com/jtauber/greek-utils", author="<NAME>", author_email="<EMAIL>", packages=["greekutils"], classifiers=[ "D...
from setuptools import setup setup( name="greek-utils", version="0.2", description="various utilities for processing Ancient Greek", license="MIT", url="http://github.com/jtauber/greek-utils", author="<NAME>", author_email="<EMAIL>", packages=["greekutils"], classifiers=[ "D...
none
1
1.036429
1
source/tweet.py
jfilter/foia-bot
0
3066
""" tweet stuff in intervals """ import time import datetime import twitter from markov_chains import german_text from config import config_no, config_yes MAX_TWEET_LENGTH = 280 greeting = ' Sehr geehrte/r Anstragssteller/in.' ending = ' MfG' num_tweets = 3 class FoiaBot: def __init__(self, config): s...
""" tweet stuff in intervals """ import time import datetime import twitter from markov_chains import german_text from config import config_no, config_yes MAX_TWEET_LENGTH = 280 greeting = ' Sehr geehrte/r Anstragssteller/in.' ending = ' MfG' num_tweets = 3 class FoiaBot: def __init__(self, config): s...
en
0.686657
tweet stuff in intervals # https://stackoverflow.com/questions/7703865/going-from-twitter-date-to-python-datetime-date # something is broken with the date but whatever # for the space # because of space # ensure space for the ending # at ending # if __name__ == '__main__': # main()
2.937487
3
account_processing.py
amitjoshi9627/Playong
4
3067
<reponame>amitjoshi9627/Playong from selenium.webdriver import Firefox from selenium.webdriver.firefox.options import Options import getpass import time from selenium.webdriver.common.keys import Keys from selenium.webdriver.common.action_chains import ActionChains from utils import * def login_user(browser, email=''...
from selenium.webdriver import Firefox from selenium.webdriver.firefox.options import Options import getpass import time from selenium.webdriver.common.keys import Keys from selenium.webdriver.common.action_chains import ActionChains from utils import * def login_user(browser, email='', password=''): print('Redir...
en
0.497086
# response = int(input("Press 1 to Log in with you account else Press 0: ")) # if response: # login_user(browser) # return True # else: # go_without_login(browser)
2.715245
3
Mundo 3/teste.py
RafaelSdm/Curso-de-Python
1
3068
pessoas = {'nomes': "Rafael","sexo":"macho alfa","idade":19} print(f"o {pessoas['nomes']} que se considera um {pessoas['sexo']} possui {pessoas['idade']}") print(pessoas.keys()) print(pessoas.values()) print(pessoas.items()) for c in pessoas.keys(): print(c) for c in pessoas.values(): print(c) for c, j in pe...
pessoas = {'nomes': "Rafael","sexo":"macho alfa","idade":19} print(f"o {pessoas['nomes']} que se considera um {pessoas['sexo']} possui {pessoas['idade']}") print(pessoas.keys()) print(pessoas.values()) print(pessoas.items()) for c in pessoas.keys(): print(c) for c in pessoas.values(): print(c) for c, j in pe...
none
1
4.326023
4
rsa-cipher/makeRsaKeys.py
mumbo-pro/cyrptography-algorithm
1
3069
# RSA Key Generator 2. # http://inventwithpython.com/hacking (BSD Licensed) 3. 4. import random, sys, os, rabinMiller, cryptomath The program imports the rabinMiller and cryptomath modules that we created in the last chapter, along with a few others. Chapter 24 – Public Key Cryptography and the RSA Cipher 387...
# RSA Key Generator 2. # http://inventwithpython.com/hacking (BSD Licensed) 3. 4. import random, sys, os, rabinMiller, cryptomath The program imports the rabinMiller and cryptomath modules that we created in the last chapter, along with a few others. Chapter 24 – Public Key Cryptography and the RSA Cipher 387...
en
0.41739
# RSA Key Generator # http://inventwithpython.com/hacking (BSD Licensed) 3. 4. import random, sys, os, rabinMiller, cryptomath # create a public/private keypair with 1024 bit keys 9. print('Making key files...') 10. makeKeyFiles('al_sweigart', 1024) 11. print('Key files made.')
2.774892
3
atlas-outreach-data-tools-framework-1.1/Configurations/PlotConf_TTbarAnalysis.py
Harvard-Neutrino/phys145
0
3070
config = { "Luminosity": 1000, "InputDirectory": "results", "Histograms" : { "WtMass" : {}, "etmiss" : {}, "lep_n" : {}, "lep_pt" : {}, "lep_eta" : {}, "lep_E" : {}, "lep_phi" : {"y_margin" : 0.6}, "lep_...
config = { "Luminosity": 1000, "InputDirectory": "results", "Histograms" : { "WtMass" : {}, "etmiss" : {}, "lep_n" : {}, "lep_pt" : {}, "lep_eta" : {}, "lep_E" : {}, "lep_phi" : {"y_margin" : 0.6}, "lep_...
none
1
1.212566
1
modules/optimizations/dead_codes.py
OMGhozlan/deobshell
0
3071
<filename>modules/optimizations/dead_codes.py # coding=utf-8 from ..logger import log_debug from ..utils import parent_map, replace_node, is_prefixed_var, get_used_vars def opt_unused_variable(ast): parents = parent_map(ast) used_vars = get_used_vars(ast) for node in ast.iter(): if node.tag in ["...
<filename>modules/optimizations/dead_codes.py # coding=utf-8 from ..logger import log_debug from ..utils import parent_map, replace_node, is_prefixed_var, get_used_vars def opt_unused_variable(ast): parents = parent_map(ast) used_vars = get_used_vars(ast) for node in ast.iter(): if node.tag in ["...
en
0.644078
# coding=utf-8
2.313833
2
Convert Integer A to Integer B.py
RijuDasgupta9116/LintCode
321
3072
<reponame>RijuDasgupta9116/LintCode """ Determine the number of bits required to convert integer A to integer B Example Given n = 31, m = 14,return 2 (31)10=(11111)2 (14)10=(01110)2 """ __author__ = 'Danyang' class Solution: def bitSwapRequired(self, a, b): """ :param a: :param b: ...
""" Determine the number of bits required to convert integer A to integer B Example Given n = 31, m = 14,return 2 (31)10=(11111)2 (14)10=(01110)2 """ __author__ = 'Danyang' class Solution: def bitSwapRequired(self, a, b): """ :param a: :param b: :return: int """ ...
en
0.336725
Determine the number of bits required to convert integer A to integer B Example Given n = 31, m = 14,return 2 (31)10=(11111)2 (14)10=(01110)2 :param a: :param b: :return: int 2's complement 32-bit :param n: :return: :param n: :return: # 2's complement
3.571879
4
examples/basic/findQSpark.py
myriadrf/pyLMS7002M
46
3073
from pyLMS7002M import * print("Searching for QSpark...") try: QSpark = QSpark() except: print("QSpark not found") exit(1) print("\QSpark info:") QSpark.printInfo() # print the QSpark board info # QSpark.LMS7002_Reset() # reset the LMS7002M lms700...
from pyLMS7002M import * print("Searching for QSpark...") try: QSpark = QSpark() except: print("QSpark not found") exit(1) print("\QSpark info:") QSpark.printInfo() # print the QSpark board info # QSpark.LMS7002_Reset() # reset the LMS7002M lms700...
en
0.533723
# print the QSpark board info # QSpark.LMS7002_Reset() # reset the LMS7002M # get the LMS7002M object # get the chip info
2.802094
3
macaddress/__init__.py
paradxum/django-macaddress
42
3074
from django.conf import settings from netaddr import mac_unix, mac_eui48 import importlib import warnings class mac_linux(mac_unix): """MAC format with zero-padded all upper-case hex and colon separated""" word_fmt = '%.2X' def default_dialect(eui_obj=None): # Check to see if a default dialect class has...
from django.conf import settings from netaddr import mac_unix, mac_eui48 import importlib import warnings class mac_linux(mac_unix): """MAC format with zero-padded all upper-case hex and colon separated""" word_fmt = '%.2X' def default_dialect(eui_obj=None): # Check to see if a default dialect class has...
en
0.716207
MAC format with zero-padded all upper-case hex and colon separated # Check to see if a default dialect class has been specified in settings, # using 'module.dialect_cls' string and use importlib and getattr to retrieve dialect class. 'module' is the module and # 'dialect_cls' is the class name of the custom dialect. Th...
2.341057
2
textmagic/test/message_status_tests.py
dfstrauss/textmagic-sms-api-python
2
3075
import time from textmagic.test import ONE_TEST_NUMBER from textmagic.test import THREE_TEST_NUMBERS from textmagic.test import TextMagicTestsBase from textmagic.test import LiveUnsafeTests class MessageStatusTestsBase(TextMagicTestsBase): def sendAndCheckStatusTo(self, numbers): message = 'sdfqwersdfg...
import time from textmagic.test import ONE_TEST_NUMBER from textmagic.test import THREE_TEST_NUMBERS from textmagic.test import TextMagicTestsBase from textmagic.test import LiveUnsafeTests class MessageStatusTestsBase(TextMagicTestsBase): def sendAndCheckStatusTo(self, numbers): message = 'sdfqwersdfg...
en
0.92176
This test is live-unsafe because it is intended to be sent to a real telephone number. It keeps asking for message status until it receives a "delivered" response.
2.466579
2
apps/orders/models.py
LinkanDawang/FreshMallDemo
0
3076
from django.db import models from utils.models import BaseModel from users.models import User, Address from goods.models import GoodsSKU # Create your models here. class OrderInfo(BaseModel): """订单信息""" PAY_METHOD = ['1', '2'] PAY_METHOD_CHOICES = ( (1, "货到付款"), (2, "支付宝"), ) OR...
from django.db import models from utils.models import BaseModel from users.models import User, Address from goods.models import GoodsSKU # Create your models here. class OrderInfo(BaseModel): """订单信息""" PAY_METHOD = ['1', '2'] PAY_METHOD_CHOICES = ( (1, "货到付款"), (2, "支付宝"), ) OR...
en
0.435249
# Create your models here. 订单信息 ---------订单信息------------------------ 订单商品
2.333272
2
event/arguments/prepare/event_vocab.py
hunterhector/DDSemantics
0
3077
<gh_stars>0 from collections import defaultdict, Counter import os import gzip import json import pickle from json.decoder import JSONDecodeError import logging from typing import Dict import pdb from event import util from event.arguments.prepare.slot_processor import get_simple_dep, is_propbank_dep logger = logging...
from collections import defaultdict, Counter import os import gzip import json import pickle from json.decoder import JSONDecodeError import logging from typing import Dict import pdb from event import util from event.arguments.prepare.slot_processor import get_simple_dep, is_propbank_dep logger = logging.getLogger(_...
en
0.673992
# Now filter the vocabulary. # Do not use frame,fe format to alleviate sparsity. # If a specific entity text is provided. # Use the argument's own text. # Use the text after hypen. # Fall back to use the argument's own text. # Fall back to NER tag. # This will create a full unknown argument, try to back off to # a par...
2.395811
2
20.py
dexinl/kids_math
0
3078
#!/usr/bin/python import random count = 20 test_set = [] while count: a = random.randrange(3,20) b = random.randrange(3,20) if a > b and a - b > 1: if (b, a-b) not in test_set: test_set.append((b, a-b)) count -= 1 elif b > a and b - a > 1: if (a, b-a) not in te...
#!/usr/bin/python import random count = 20 test_set = [] while count: a = random.randrange(3,20) b = random.randrange(3,20) if a > b and a - b > 1: if (b, a-b) not in test_set: test_set.append((b, a-b)) count -= 1 elif b > a and b - a > 1: if (a, b-a) not in te...
ru
0.258958
#!/usr/bin/python
3.715799
4
autovirt/equipment/domain/equipment.py
xlam/autovirt
0
3079
<reponame>xlam/autovirt from enum import Enum from functools import reduce from math import ceil from typing import Optional, Tuple from autovirt import utils from autovirt.exception import AutovirtError from autovirt.structs import UnitEquipment, RepairOffer logger = utils.get_logger() # maximum allowed equipment p...
from enum import Enum from functools import reduce from math import ceil from typing import Optional, Tuple from autovirt import utils from autovirt.exception import AutovirtError from autovirt.structs import UnitEquipment, RepairOffer logger = utils.get_logger() # maximum allowed equipment price PRICE_MAX = 100000 ...
en
0.906578
# maximum allowed equipment price # value to add and sub from offer quality when filtering Calculate total quantity of equipment to repair on given units Calculate total equipment count on given units # select units in range [quality-DELTA ... quality+DELTA] and having enough repair parts Split units by quality (requir...
2.804267
3
day09/part2.py
mtn/advent16
0
3080
<gh_stars>0 #!/usr/bin/env python3 import re with open("input.txt") as f: content = f.read().strip() def ulen(content): ans = 0 i = 0 while i < len(content): if content[i] == "(": end = content[i:].find(")") + i instr = content[i+1:end] chars, times = map(...
#!/usr/bin/env python3 import re with open("input.txt") as f: content = f.read().strip() def ulen(content): ans = 0 i = 0 while i < len(content): if content[i] == "(": end = content[i:].find(")") + i instr = content[i+1:end] chars, times = map(int, content...
fr
0.221828
#!/usr/bin/env python3
3.208398
3
cirq-core/cirq/contrib/quimb/mps_simulator_test.py
Nexuscompute/Cirq
0
3081
<gh_stars>0 # pylint: disable=wrong-or-nonexistent-copyright-notice import itertools import math import numpy as np import pytest import sympy import cirq import cirq.contrib.quimb as ccq import cirq.testing from cirq import value def assert_same_output_as_dense(circuit, qubit_order, initial_state=0, grouping=None)...
# pylint: disable=wrong-or-nonexistent-copyright-notice import itertools import math import numpy as np import pytest import sympy import cirq import cirq.contrib.quimb as ccq import cirq.testing from cirq import value def assert_same_output_as_dense(circuit, qubit_order, initial_state=0, grouping=None): mps_si...
en
0.859779
# pylint: disable=wrong-or-nonexistent-copyright-notice # Expected value is 1/4: # There are two "Tensor()" copies in the string. # There are two "Tensor()" copies in the string.
1.981723
2
e2e_tests/tests/config.py
winding-lines/determined
0
3082
import os from pathlib import Path from typing import Any, Dict from determined.common import util MASTER_SCHEME = "http" MASTER_IP = "localhost" MASTER_PORT = "8080" DET_VERSION = None DEFAULT_MAX_WAIT_SECS = 1800 MAX_TASK_SCHEDULED_SECS = 30 MAX_TRIAL_BUILD_SECS = 90 DEFAULT_TF1_CPU_IMAGE = "determinedai/environm...
import os from pathlib import Path from typing import Any, Dict from determined.common import util MASTER_SCHEME = "http" MASTER_IP = "localhost" MASTER_PORT = "8080" DET_VERSION = None DEFAULT_MAX_WAIT_SECS = 1800 MAX_TASK_SCHEDULED_SECS = 30 MAX_TRIAL_BUILD_SECS = 90 DEFAULT_TF1_CPU_IMAGE = "determinedai/environm...
none
1
2.045749
2
src/greenbudget/app/subaccount/serializers.py
nickmflorin/django-proper-architecture-testing
0
3083
from django.contrib.contenttypes.models import ContentType from rest_framework import serializers, exceptions from greenbudget.lib.rest_framework_utils.fields import ModelChoiceField from greenbudget.lib.rest_framework_utils.serializers import ( EnhancedModelSerializer) from greenbudget.app.budget.models import B...
from django.contrib.contenttypes.models import ContentType from rest_framework import serializers, exceptions from greenbudget.lib.rest_framework_utils.fields import ModelChoiceField from greenbudget.lib.rest_framework_utils.serializers import ( EnhancedModelSerializer) from greenbudget.app.budget.models import B...
en
0.945845
# Note that the updated_by argument is the user updating the # Account by adding new SubAccount(s), so the SubAccount(s) # should be denoted as having been created by this user.
1.696912
2
modules/dbnd/src/dbnd/_core/tracking/managers/callable_tracking.py
busunkim96/dbnd
224
3084
import contextlib import logging import typing from typing import Any, Dict, Tuple import attr from dbnd._core.configuration import get_dbnd_project_config from dbnd._core.constants import ( RESULT_PARAM, DbndTargetOperationStatus, DbndTargetOperationType, TaskRunState, ) from dbnd._core.current impo...
import contextlib import logging import typing from typing import Any, Dict, Tuple import attr from dbnd._core.configuration import get_dbnd_project_config from dbnd._core.constants import ( RESULT_PARAM, DbndTargetOperationStatus, DbndTargetOperationType, TaskRunState, ) from dbnd._core.current impo...
en
0.886019
# type: Tuple[Any] # type: Dict[str,Any] # type: (CallableTrackingManager, TaskDecorator) -> None # whether we got to executing of user code # whether we passed executing of user code # 1. check that we don't have too many calls # 2. Start or reuse existing "main tracking task" that is root for tracked tasks try to g...
1.660647
2
api.py
Benardi/redis-basics
0
3085
import os import logging from json import loads, dumps from datetime import timedelta from argparse import ArgumentParser from redis import Redis from flask import Response, Flask, request app = Flask(__name__) log = logging.getLogger(__name__) parser = ArgumentParser() parser.add_argument("-a", "--address", ...
import os import logging from json import loads, dumps from datetime import timedelta from argparse import ArgumentParser from redis import Redis from flask import Response, Flask, request app = Flask(__name__) log = logging.getLogger(__name__) parser = ArgumentParser() parser.add_argument("-a", "--address", ...
none
1
2.604535
3
zhihu_spider/ZhihuSpider/spiders/zhihu.py
Ki-Seki/gadgets
1
3086
""" 启动此 spider 前需要手动启动 Chrome,cmd 命令如下: cd 进入 Chrome 可执行文件 所在的目录 执行:chrome.exe --remote-debugging-port=9222 此时在浏览器窗口地址栏访问:http://127.0.0.1:9222/json,如果页面出现 json 数据,则表明手动启动成功 启动此 spider 后,注意与命令行交互! 在 settings 当中要做的: # ROBOTSTXT_OBEY = False # 如果不关闭,parse 方法无法执行 # COOKIES_ENABLED = True # 以便 Request 值在传递时自动传递 cookies...
""" 启动此 spider 前需要手动启动 Chrome,cmd 命令如下: cd 进入 Chrome 可执行文件 所在的目录 执行:chrome.exe --remote-debugging-port=9222 此时在浏览器窗口地址栏访问:http://127.0.0.1:9222/json,如果页面出现 json 数据,则表明手动启动成功 启动此 spider 后,注意与命令行交互! 在 settings 当中要做的: # ROBOTSTXT_OBEY = False # 如果不关闭,parse 方法无法执行 # COOKIES_ENABLED = True # 以便 Request 值在传递时自动传递 cookies...
zh
0.796219
启动此 spider 前需要手动启动 Chrome,cmd 命令如下: cd 进入 Chrome 可执行文件 所在的目录 执行:chrome.exe --remote-debugging-port=9222 此时在浏览器窗口地址栏访问:http://127.0.0.1:9222/json,如果页面出现 json 数据,则表明手动启动成功 启动此 spider 后,注意与命令行交互! 在 settings 当中要做的: # ROBOTSTXT_OBEY = False # 如果不关闭,parse 方法无法执行 # COOKIES_ENABLED = True # 以便 Request 值在传递时自动传递 cookies # U...
2.631259
3
tests/test_bindiff.py
Kyle-Kyle/angr
6,132
3087
import nose import angr import logging l = logging.getLogger("angr.tests.test_bindiff") import os test_location = os.path.join(os.path.dirname(os.path.realpath(__file__)), '..', '..', 'binaries', 'tests') # todo make a better test def test_bindiff_x86_64(): binary_path_1 = os.path.join(test_location, 'x86_64', '...
import nose import angr import logging l = logging.getLogger("angr.tests.test_bindiff") import os test_location = os.path.join(os.path.dirname(os.path.realpath(__file__)), '..', '..', 'binaries', 'tests') # todo make a better test def test_bindiff_x86_64(): binary_path_1 = os.path.join(test_location, 'x86_64', '...
en
0.714522
# todo make a better test # check identical functions # check differing functions # check unmatched functions # check for no major regressions # check a function diff
2.278664
2
main/handle_file.py
nucluster/us_states
0
3088
from pathlib import Path BASE_DIR = Path(__file__).resolve().parent.parent # def handle_uploaded_file(f): # with open('screenshot.png', 'wb') as destination: # # for chunk in f.chunks(): # # destination.write(chunk) # destination.write(f) with open( BASE_DIR/'media'/'Greater_coat...
from pathlib import Path BASE_DIR = Path(__file__).resolve().parent.parent # def handle_uploaded_file(f): # with open('screenshot.png', 'wb') as destination: # # for chunk in f.chunks(): # # destination.write(chunk) # destination.write(f) with open( BASE_DIR/'media'/'Greater_coat...
en
0.712617
# def handle_uploaded_file(f): # with open('screenshot.png', 'wb') as destination: # # for chunk in f.chunks(): # # destination.write(chunk) # destination.write(f) # handle_uploaded_file(flag) # print(flag) # for place in sys.path: # print(place)
2.898978
3
2018/finals/pwn-gdb-as-a-service/web_challenge/challenge/gaas.py
iicarus-bit/google-ctf
2,757
3089
#!/usr/bin/env python3 # # Copyright 2018 Google LLC # # Licensed under the Apache License, Version 2.0 (the "License"); # you may not use this file except in compliance with the License. # You may obtain a copy of the License at # # http://www.apache.org/licenses/LICENSE-2.0 # # Unless required by applicable law ...
#!/usr/bin/env python3 # # Copyright 2018 Google LLC # # Licensed under the Apache License, Version 2.0 (the "License"); # you may not use this file except in compliance with the License. # You may obtain a copy of the License at # # http://www.apache.org/licenses/LICENSE-2.0 # # Unless required by applicable law ...
en
0.868488
#!/usr/bin/env python3 # # Copyright 2018 Google LLC # # Licensed under the Apache License, Version 2.0 (the "License"); # you may not use this file except in compliance with the License. # You may obtain a copy of the License at # # http://www.apache.org/licenses/LICENSE-2.0 # # Unless required by applicable law ...
1.875773
2
examples/multi_physics/piezo_elasticity.py
BubuLK/sfepy
0
3090
<filename>examples/multi_physics/piezo_elasticity.py r""" Piezo-elasticity problem - linear elastic material with piezoelectric effects. Find :math:`\ul{u}`, :math:`\phi` such that: .. math:: - \omega^2 \int_{Y} \rho\ \ul{v} \cdot \ul{u} + \int_{Y} D_{ijkl}\ e_{ij}(\ul{v}) e_{kl}(\ul{u}) - \int_{Y_2} g_{k...
<filename>examples/multi_physics/piezo_elasticity.py r""" Piezo-elasticity problem - linear elastic material with piezoelectric effects. Find :math:`\ul{u}`, :math:`\phi` such that: .. math:: - \omega^2 \int_{Y} \rho\ \ul{v} \cdot \ul{u} + \int_{Y} D_{ijkl}\ e_{ij}(\ul{v}) e_{kl}(\ul{u}) - \int_{Y_2} g_{k...
en
0.43661
Piezo-elasticity problem - linear elastic material with piezoelectric effects. Find :math:`\ul{u}`, :math:`\phi` such that: .. math:: - \omega^2 \int_{Y} \rho\ \ul{v} \cdot \ul{u} + \int_{Y} D_{ijkl}\ e_{ij}(\ul{v}) e_{kl}(\ul{u}) - \int_{Y_2} g_{kij}\ e_{ij}(\ul{v}) \nabla_k \phi = 0 \;, \quad \f...
2.405553
2
01-logica-de-programacao-e-algoritmos/Aula 06/01 Tuplas/1.2 Desempacotamento de parametros em funcoes/ex01.py
rafaelbarretomg/Uninter
0
3091
<reponame>rafaelbarretomg/Uninter<gh_stars>0 # Desempacotamento de parametros em funcoes # somando valores de uma tupla def soma(*num): soma = 0 print('Tupla: {}' .format(num)) for i in num: soma += i return soma # Programa principal print('Resultado: {}\n' .format(soma(1, 2))) print('Resultad...
# Desempacotamento de parametros em funcoes # somando valores de uma tupla def soma(*num): soma = 0 print('Tupla: {}' .format(num)) for i in num: soma += i return soma # Programa principal print('Resultado: {}\n' .format(soma(1, 2))) print('Resultado: {}\n' .format(soma(1, 2, 3, 4, 5, 6, 7, 8,...
pt
0.944312
# Desempacotamento de parametros em funcoes # somando valores de uma tupla # Programa principal
4.028688
4
services/model.py
theallknowng/eKheti
1
3092
<reponame>theallknowng/eKheti<filename>services/model.py<gh_stars>1-10 import pandas from keras.models import Sequential from keras.layers import Dense from keras.wrappers.scikit_learn import KerasClassifier from keras.utils import np_utils from sklearn.model_selection import cross_val_score from sklearn.model_selectio...
import pandas from keras.models import Sequential from keras.layers import Dense from keras.wrappers.scikit_learn import KerasClassifier from keras.utils import np_utils from sklearn.model_selection import cross_val_score from sklearn.model_selection import KFold from sklearn.preprocessing import LabelEncoder from skle...
en
0.596691
# define baseline model # create model # Compile model # data = sys.argv[1] # data = '{"pH min":5.7,"pH max":7,"nitrogen min":109,"nitrogen max":146,"phosphorus min":20,"phosphorus max":30,"potasium min":78,"potasium max":115,"calcium min":270,"calcium max":990,"magnesium min":46,"magnesium max":96,"sulphur min":10,"su...
2.698021
3
tests/sentry/api/endpoints/test_project_details.py
erhuabushuo/sentry
0
3093
from django.core.urlresolvers import reverse from sentry.models import Project from sentry.testutils import APITestCase class ProjectDetailsTest(APITestCase): def test_simple(self): project = self.project # force creation self.login_as(user=self.user) url = reverse('sentry-api-0-project-d...
from django.core.urlresolvers import reverse from sentry.models import Project from sentry.testutils import APITestCase class ProjectDetailsTest(APITestCase): def test_simple(self): project = self.project # force creation self.login_as(user=self.user) url = reverse('sentry-api-0-project-d...
en
0.77783
# force creation # force creation
2.235779
2
tests/test_table.py
databook1/python-pptx
0
3094
# encoding: utf-8 """Unit-test suite for `pptx.table` module.""" import pytest from pptx.dml.fill import FillFormat from pptx.dml.border import BorderFormat from pptx.enum.text import MSO_ANCHOR from pptx.oxml.ns import qn from pptx.oxml.table import CT_Table, CT_TableCell, TcRange from pptx.shapes.graphfrm import G...
# encoding: utf-8 """Unit-test suite for `pptx.table` module.""" import pytest from pptx.dml.fill import FillFormat from pptx.dml.border import BorderFormat from pptx.enum.text import MSO_ANCHOR from pptx.oxml.ns import qn from pptx.oxml.table import CT_Table, CT_TableCell, TcRange from pptx.shapes.graphfrm import G...
en
0.240091
# encoding: utf-8 Unit-test suite for `pptx.table` module. Unit-test suite for `pptx.table.Table` objects. # fixtures ------------------------------------------------------- # fixture components --------------------------------------------- # fixtures ------------------------------------------------------- Unit-test su...
2.296951
2
imread/tests/test_bmp.py
luispedro/imread
51
3095
<reponame>luispedro/imread<filename>imread/tests/test_bmp.py import numpy as np from imread import imread from . import file_path def test_read(): im = imread(file_path('star1.bmp')) assert np.any(im) assert im.shape == (128, 128, 3) def test_indexed(): im = imread(file_path('py-installer-indexed.bmp'...
import numpy as np from imread import imread from . import file_path def test_read(): im = imread(file_path('star1.bmp')) assert np.any(im) assert im.shape == (128, 128, 3) def test_indexed(): im = imread(file_path('py-installer-indexed.bmp')) assert np.any(im) assert im.shape == (352, 162, 3)...
none
1
2.370711
2
bl60x_flash/main.py
v3l0c1r4pt0r/bl60x-flash
0
3096
from serial import Serial from tqdm import tqdm import binascii import hashlib import struct import time import sys import os def if_read(ser, data_len): data = bytearray(0) received = 0 while received < data_len: tmp = ser.read(data_len - received) if len(tmp) == 0: ...
from serial import Serial from tqdm import tqdm import binascii import hashlib import struct import time import sys import os def if_read(ser, data_len): data = bytearray(0) received = 0 while received < data_len: tmp = ser.read(data_len - received) if len(tmp) == 0: ...
en
0.965925
# there is a length parameter here but it doesn't seem to work correctly # at this point, the eflash loader binary is running with efl_ commands # (which seems to work with a higher baudrate)
2.479536
2
lang/py/test/test_avro_builder.py
zerofox-oss/yelp-avro
0
3097
<filename>lang/py/test/test_avro_builder.py # -*- coding: utf-8 -*- import unittest from avro import avro_builder from avro import schema class TestAvroSchemaBuilder(unittest.TestCase): def setUp(self): self.builder = avro_builder.AvroSchemaBuilder() def tearDown(self): del self.builder ...
<filename>lang/py/test/test_avro_builder.py # -*- coding: utf-8 -*- import unittest from avro import avro_builder from avro import schema class TestAvroSchemaBuilder(unittest.TestCase): def setUp(self): self.builder = avro_builder.AvroSchemaBuilder() def tearDown(self): del self.builder ...
en
0.550219
# -*- coding: utf-8 -*- # non-union schema type # union schema type # non-union schema type # union schema type
2.392531
2
monte_py/__init__.py
domluna/fun_with_ffi
1
3098
import random def estimate_pi(sims, needles): trials = [] for _ in xrange(sims): trials.append(simulate_pi(needles)) mean = sum(trials) / sims return mean # use a unit square def simulate_pi(needles): hits = 0 # how many hits we hit the circle for _ in xrange(needles): x = ran...
import random def estimate_pi(sims, needles): trials = [] for _ in xrange(sims): trials.append(simulate_pi(needles)) mean = sum(trials) / sims return mean # use a unit square def simulate_pi(needles): hits = 0 # how many hits we hit the circle for _ in xrange(needles): x = ran...
en
0.759904
# use a unit square # how many hits we hit the circle
3.34566
3
tools/mpy_ld.py
UVA-DSI/circuitpython
1
3099
#!/usr/bin/env python3 # # This file is part of the MicroPython project, http://micropython.org/ # # The MIT License (MIT) # # Copyright (c) 2019 <NAME> # # Permission is hereby granted, free of charge, to any person obtaining a copy # of this software and associated documentation files (the "Software"), to deal # in t...
#!/usr/bin/env python3 # # This file is part of the MicroPython project, http://micropython.org/ # # The MIT License (MIT) # # Copyright (c) 2019 <NAME> # # Permission is hereby granted, free of charge, to any person obtaining a copy # of this software and associated documentation files (the "Software"), to deal # in t...
en
0.67027
#!/usr/bin/env python3 # # This file is part of the MicroPython project, http://micropython.org/ # # The MIT License (MIT) # # Copyright (c) 2019 <NAME> # # Permission is hereby granted, free of charge, to any person obtaining a copy # of this software and associated documentation files (the "Software"), to deal # in t...
1.538295
2