code stringlengths 2k 1.04M | repo_path stringlengths 5 517 | parsed_code stringlengths 0 1.04M | quality_prob float64 0.02 0.95 | learning_prob float64 0.02 0.93 |
|---|---|---|---|---|
from rdkit import Chem
from rdkit.Chem import AllChem, MACCSkeys
from rdkit.SimDivFilters import rdSimDivPickers
from rdkit.Chem.Fingerprints import FingerprintMols
import numpy
from rdkit import DataStructs
from rdkit.ML.Cluster import Butina, Murtagh
from rdkit.ML.Cluster import ClusterUtils
# read sdf file and do fi... | cluster.py | from rdkit import Chem
from rdkit.Chem import AllChem, MACCSkeys
from rdkit.SimDivFilters import rdSimDivPickers
from rdkit.Chem.Fingerprints import FingerprintMols
import numpy
from rdkit import DataStructs
from rdkit.ML.Cluster import Butina, Murtagh
from rdkit.ML.Cluster import ClusterUtils
# read sdf file and do fi... | 0.435421 | 0.420659 |
import pprint
import re # noqa: F401
import six
from openapi_client.configuration import Configuration
class Fills(object):
"""NOTE: This class is auto generated by OpenAPI Generator.
Ref: https://openapi-generator.tech
Do not edit the class manually.
"""
"""
Attributes:
openapi_typ... | oeml-sdk/python/openapi_client/models/fills.py | import pprint
import re # noqa: F401
import six
from openapi_client.configuration import Configuration
class Fills(object):
"""NOTE: This class is auto generated by OpenAPI Generator.
Ref: https://openapi-generator.tech
Do not edit the class manually.
"""
"""
Attributes:
openapi_typ... | 0.812421 | 0.189352 |
import pytest
from moa.primitives import NDArray, UnaryOperation, BinaryOperation, Function
from moa.yaccer import build_parser
@pytest.mark.parametrize("expression,result", [
("< 1 2 3>", NDArray(shape=(3,), data=[1, 2, 3], constant=False)),
])
def test_parse_vector(expression, result):
parser = build_parse... | tests/test_yaccer.py | import pytest
from moa.primitives import NDArray, UnaryOperation, BinaryOperation, Function
from moa.yaccer import build_parser
@pytest.mark.parametrize("expression,result", [
("< 1 2 3>", NDArray(shape=(3,), data=[1, 2, 3], constant=False)),
])
def test_parse_vector(expression, result):
parser = build_parse... | 0.626696 | 0.747363 |
from flask_wtf import FlaskForm
from wtforms import StringField, PasswordField, BooleanField, SubmitField
from wtforms.validators import DataRequired, Email, EqualTo, Length, ValidationError
from app.models.users import Users
class LoginForm(FlaskForm):
email = StringField('Email', validators=[DataRequired(), Ema... | app/auth/forms.py | from flask_wtf import FlaskForm
from wtforms import StringField, PasswordField, BooleanField, SubmitField
from wtforms.validators import DataRequired, Email, EqualTo, Length, ValidationError
from app.models.users import Users
class LoginForm(FlaskForm):
email = StringField('Email', validators=[DataRequired(), Ema... | 0.47098 | 0.131507 |
from flask import redirect, request, jsonify, flash, url_for
from rest import ses_login, put_session
from conf import app
import ldap
from conf import config
def init(uri):
try:
return ldap.initialize(uri)
except ldap.LDAPError as e:
print(e)
return None
def chk_login(ld, userDN, user_pass):
bin... | login/login_ldap.py |
from flask import redirect, request, jsonify, flash, url_for
from rest import ses_login, put_session
from conf import app
import ldap
from conf import config
def init(uri):
try:
return ldap.initialize(uri)
except ldap.LDAPError as e:
print(e)
return None
def chk_login(ld, userDN, user_pass):
bin... | 0.194521 | 0.04597 |
import os, random, time, re, requests, threading
Colors = ['\033[31m', '\033[32m', '\033[33m', '\033[34m', '\033[35m', '\033[36m', '\033[39m']
try:
os.mkdir('Results')
except:
pass
def Print_Logo():
Logo = '''
__ __ _ _... | Website-Viewer-master/Website Viewer.py | import os, random, time, re, requests, threading
Colors = ['\033[31m', '\033[32m', '\033[33m', '\033[34m', '\033[35m', '\033[36m', '\033[39m']
try:
os.mkdir('Results')
except:
pass
def Print_Logo():
Logo = '''
__ __ _ _... | 0.101679 | 0.056862 |
import os
import shutil
import tensorflow as tf
import numpy as np
from helpers import cache_json
def test(args, model, sess, dataset):
print('|========= START TEST =========|')
saver = tf.compat.v1.train.Saver(max_to_keep=10)
# Identify which checkpoints are available.
state = tf.compat.v1.train.get... | snip-tensorflow/test.py | import os
import shutil
import tensorflow as tf
import numpy as np
from helpers import cache_json
def test(args, model, sess, dataset):
print('|========= START TEST =========|')
saver = tf.compat.v1.train.Saver(max_to_keep=10)
# Identify which checkpoints are available.
state = tf.compat.v1.train.get... | 0.449393 | 0.357624 |
from pathlib import Path
INPUTFILE = "input.txt"
SAMPLE_TEXT = """
abc
a
b
c
ab
ac
a
a
a
a
b
"""
# Utility functions
def load_input(infile):
return list(Path(infile).open())
# Solution
def parse_answers(lines):
groups = []
group = set()
for line in lines:
line = line.strip()
... | day6/day6.py | from pathlib import Path
INPUTFILE = "input.txt"
SAMPLE_TEXT = """
abc
a
b
c
ab
ac
a
a
a
a
b
"""
# Utility functions
def load_input(infile):
return list(Path(infile).open())
# Solution
def parse_answers(lines):
groups = []
group = set()
for line in lines:
line = line.strip()
... | 0.707203 | 0.287158 |
from typing import List
from pysymphony import SymphonyClient
from ..common.cache import LOCATION_TYPES
from ..common.data_class import Location, LocationType, PropertyDefinition
from ..common.data_enum import Entity
from ..common.data_format import (
format_to_property_definitions,
format_to_property_type_i... | symphony/cli/pyinventory/api/location_type.py |
from typing import List
from pysymphony import SymphonyClient
from ..common.cache import LOCATION_TYPES
from ..common.data_class import Location, LocationType, PropertyDefinition
from ..common.data_enum import Entity
from ..common.data_format import (
format_to_property_definitions,
format_to_property_type_i... | 0.847842 | 0.25904 |
__author__ = '<NAME> (bcaller)'
__copyright__ = 'Copyright 2014, <NAME>'
__credits__ = ['<NAME> (rmmh)']
__license__ = 'MIT'
import json
from Prefix import Prefix
from merge_dict import merge
import gzip
import re
hasPartOfSpeech = re.compile('^([A-Za-z][a-z]+)_(ADJ|NOUN|VERB)')
pos = ['ADJ', 'NOUN', 'VERB']
print('... | unigrams.py |
__author__ = '<NAME> (bcaller)'
__copyright__ = 'Copyright 2014, <NAME>'
__credits__ = ['<NAME> (rmmh)']
__license__ = 'MIT'
import json
from Prefix import Prefix
from merge_dict import merge
import gzip
import re
hasPartOfSpeech = re.compile('^([A-Za-z][a-z]+)_(ADJ|NOUN|VERB)')
pos = ['ADJ', 'NOUN', 'VERB']
print('... | 0.142291 | 0.107954 |
from PyQt4 import QtGui, QtCore
import mne
import numpy as np
from ui_TimeSeriesDialog import Ui_TimeSeriesDialog
from powerSpectrumWidget import PowerSpectrumWidget
from general.caller import Caller
class TimeSeriesDialog(QtGui.QDialog):
"""
"""
caller = Caller.Instance()
widgets = []
timeSeries... | ui/timeSeriesDialog.py | from PyQt4 import QtGui, QtCore
import mne
import numpy as np
from ui_TimeSeriesDialog import Ui_TimeSeriesDialog
from powerSpectrumWidget import PowerSpectrumWidget
from general.caller import Caller
class TimeSeriesDialog(QtGui.QDialog):
"""
"""
caller = Caller.Instance()
widgets = []
timeSeries... | 0.515376 | 0.080213 |
import lab as B
from ..constant import Constant, Zero
from ..diagonal import Diagonal
from ..kronecker import Kronecker
from ..lowrank import LowRank
from ..matrix import Dense
from ..triangular import LowerTriangular, UpperTriangular
from ..woodbury import Woodbury
__all__ = []
# We don't implement a fallback meth... | matrix/ops/broadcast_batch_to.py | import lab as B
from ..constant import Constant, Zero
from ..diagonal import Diagonal
from ..kronecker import Kronecker
from ..lowrank import LowRank
from ..matrix import Dense
from ..triangular import LowerTriangular, UpperTriangular
from ..woodbury import Woodbury
__all__ = []
# We don't implement a fallback meth... | 0.905407 | 0.500183 |
def __virtual__():
'''
Only load if the pushover module is available in __salt__
'''
return 'pushover' if 'pushover.post_message' in __salt__ else False
def post_message(name,
user=None,
device=None,
message=None,
title=None,
... | salt/states/pushover.py | def __virtual__():
'''
Only load if the pushover module is available in __salt__
'''
return 'pushover' if 'pushover.post_message' in __salt__ else False
def post_message(name,
user=None,
device=None,
message=None,
title=None,
... | 0.645902 | 0.13084 |
import numpy as np
class BoxList(object):
"""Box collection.
BoxList represents a list of bounding boxes as numpy array, where each
bounding box is represented as a row of 4 numbers,
[y_min, x_min, y_max, x_max]. It is assumed that all bounding boxes within a
given list correspond to a single ima... | effdet/evaluation/np_box_list.py | import numpy as np
class BoxList(object):
"""Box collection.
BoxList represents a list of bounding boxes as numpy array, where each
bounding box is represented as a row of 4 numbers,
[y_min, x_min, y_max, x_max]. It is assumed that all bounding boxes within a
given list correspond to a single ima... | 0.958294 | 0.756132 |
from generator import Generator
from instruction_set import InstructionSet
from instruction_tree import InstructionTree
class TableGenerator(Generator):
HEADER_VAR = 'TABLE_MODULE_HEADER'
FOOTER_VAR = 'TABLE_MODULE_FOOTER'
def __init__(self, instructions, variables):
Generator.__init__(self, variables)
... | table_generator.py | from generator import Generator
from instruction_set import InstructionSet
from instruction_tree import InstructionTree
class TableGenerator(Generator):
HEADER_VAR = 'TABLE_MODULE_HEADER'
FOOTER_VAR = 'TABLE_MODULE_FOOTER'
def __init__(self, instructions, variables):
Generator.__init__(self, variables)
... | 0.716814 | 0.154058 |
import pytest
import json, sys
import pexpect
def pytest_collect_file(path, parent):
if path.ext == ".q" and path.basename.endswith("_test.q"):
return QuarkFile(path, parent)
class QuarkFile(pytest.File):
def collect(self):
for lang in ["python", "java", "javascript", "ruby"]:
yiel... | quarkc/test/lib/conftest.py | import pytest
import json, sys
import pexpect
def pytest_collect_file(path, parent):
if path.ext == ".q" and path.basename.endswith("_test.q"):
return QuarkFile(path, parent)
class QuarkFile(pytest.File):
def collect(self):
for lang in ["python", "java", "javascript", "ruby"]:
yiel... | 0.254694 | 0.305529 |
from __future__ import absolute_import
import os
import sys
import socket
# noinspection PyPackageRequirements
from scrumtools import data, error
from termcolor import cprint, colored
from cement.core import controller
try:
prompt = raw_input
except NameError:
prompt = input
class EvalToolController(contro... | src/main/python/scrumtools/evaltool.py | from __future__ import absolute_import
import os
import sys
import socket
# noinspection PyPackageRequirements
from scrumtools import data, error
from termcolor import cprint, colored
from cement.core import controller
try:
prompt = raw_input
except NameError:
prompt = input
class EvalToolController(contro... | 0.348645 | 0.076718 |
import redis
from common.log import logger
from datamanage.exceptions import DatamanageErrorCode
try:
from django.conf import settings
REDIS_CONFIG = settings.REDIS_CONFIG
except Exception as e:
logger.warning(f'{str(e)}')
REDIS_CONFIG = {}
_redis_cache = {}
def init_redis_conn(db='default', confi... | src/api/datamanage/utils/dbtools/redis_util.py | import redis
from common.log import logger
from datamanage.exceptions import DatamanageErrorCode
try:
from django.conf import settings
REDIS_CONFIG = settings.REDIS_CONFIG
except Exception as e:
logger.warning(f'{str(e)}')
REDIS_CONFIG = {}
_redis_cache = {}
def init_redis_conn(db='default', confi... | 0.307254 | 0.097476 |
import warnings
import pulumi
import pulumi.runtime
from typing import Any, Mapping, Optional, Sequence, Union, overload
from .. import _utilities
from . import outputs
from ._inputs import *
__all__ = ['NatGatewayArgs', 'NatGateway']
@pulumi.input_type
class NatGatewayArgs:
def __init__(__self__, *,
... | sdk/python/pulumi_aws_native/ec2/nat_gateway.py |
import warnings
import pulumi
import pulumi.runtime
from typing import Any, Mapping, Optional, Sequence, Union, overload
from .. import _utilities
from . import outputs
from ._inputs import *
__all__ = ['NatGatewayArgs', 'NatGateway']
@pulumi.input_type
class NatGatewayArgs:
def __init__(__self__, *,
... | 0.83762 | 0.053899 |
from functools import reduce
import unittest
import numpy
from pyscf import gto, lib
from pyscf.symm import Dmatrix, geom
class KnownValues(unittest.TestCase):
def test_Dmatrix(self):
self.assertAlmostEqual(lib.finger(Dmatrix.Dmatrix(0, -.7, .5, .2)), 1, 12)
self.assertAlmostEqual(lib.finger(Dmat... | pyscf/symm/test/test_Dmatrix.py |
from functools import reduce
import unittest
import numpy
from pyscf import gto, lib
from pyscf.symm import Dmatrix, geom
class KnownValues(unittest.TestCase):
def test_Dmatrix(self):
self.assertAlmostEqual(lib.finger(Dmatrix.Dmatrix(0, -.7, .5, .2)), 1, 12)
self.assertAlmostEqual(lib.finger(Dmat... | 0.79538 | 0.703069 |
import numpy as np
from mahotas.internal import _get_output, _get_axis
from mahotas.internal import _normalize_sequence, _verify_is_integer_type, _verify_is_floatingpoint_type, _as_floating_point_array
from mahotas.internal import _check_3
import pytest
def test_get_output():
f = np.arange(256).reshape((32,8))
... | mahotas/tests/test_internal.py | import numpy as np
from mahotas.internal import _get_output, _get_axis
from mahotas.internal import _normalize_sequence, _verify_is_integer_type, _verify_is_floatingpoint_type, _as_floating_point_array
from mahotas.internal import _check_3
import pytest
def test_get_output():
f = np.arange(256).reshape((32,8))
... | 0.401219 | 0.669083 |
import pytest
import numpy as np
from numpy.testing import assert_allclose
from keras import layers
from keras import models
from keras import backend as K
from keras.utils.test_utils import layer_test
from keras.utils.test_utils import keras_test
from keras.layers import merge
@keras_test
def test_merge_add():
i... | tests/keras/layers/merge_test.py | import pytest
import numpy as np
from numpy.testing import assert_allclose
from keras import layers
from keras import models
from keras import backend as K
from keras.utils.test_utils import layer_test
from keras.utils.test_utils import keras_test
from keras.layers import merge
@keras_test
def test_merge_add():
i... | 0.811041 | 0.692063 |
from libs.extensions import Extension
import pandas as pd
from flask import g
from settings.gdxf.extensions.cfxflv.get_base_sql_map import get_base_sql_map
from utils.qh_processor import get_qh_level
DEBUG = False
def get_sql_map(flag):
if flag:
base_sql_map = {
"3-4-全": "3_4",
"3... | settings/jyxf/extensions/cfxflv/__init__.py | from libs.extensions import Extension
import pandas as pd
from flask import g
from settings.gdxf.extensions.cfxflv.get_base_sql_map import get_base_sql_map
from utils.qh_processor import get_qh_level
DEBUG = False
def get_sql_map(flag):
if flag:
base_sql_map = {
"3-4-全": "3_4",
"3... | 0.238816 | 0.127273 |
from random import randint
# DUEL variables
DUEL_DICE = 4
MAX_HP = 6
# write the action on screen
def action(roll):
if roll == 4:
return "blocks"
elif roll == 3:
return "dodges"
elif roll == 2:
return "swings low"
else:
return "swings high"
# Duel between two fighters
... | duel.py | from random import randint
# DUEL variables
DUEL_DICE = 4
MAX_HP = 6
# write the action on screen
def action(roll):
if roll == 4:
return "blocks"
elif roll == 3:
return "dodges"
elif roll == 2:
return "swings low"
else:
return "swings high"
# Duel between two fighters
... | 0.191101 | 0.265517 |
import logging
import json
import os
logger = logging.getLogger(__name__)
'''
Given a directory with receipt file and OCR output, this function should extract the amount
Parameters:
dirpath (str): directory path containing receipt and ocr output
Returns:
float: returns the extracted amount
'''
... | extract.py | import logging
import json
import os
logger = logging.getLogger(__name__)
'''
Given a directory with receipt file and OCR output, this function should extract the amount
Parameters:
dirpath (str): directory path containing receipt and ocr output
Returns:
float: returns the extracted amount
'''
... | 0.222785 | 0.21463 |
import scraper
import utils
import sys
import datetime
import argparse
import pandas as pd
ELO_BASE = 1500
NEW_ELO = 925
K_FACTOR = 43
SEASON_CARRY = 0.9
HOME_ADVANTAGE = 81
ELO_TO_POINTS_FACTOR = -25.7 #divide an elo margin by this to get the predicted point spread
GAMES_REQUIRED = 5
DATA_FOLDER = utils.DATA_FOLDER
... | elo.py | import scraper
import utils
import sys
import datetime
import argparse
import pandas as pd
ELO_BASE = 1500
NEW_ELO = 925
K_FACTOR = 43
SEASON_CARRY = 0.9
HOME_ADVANTAGE = 81
ELO_TO_POINTS_FACTOR = -25.7 #divide an elo margin by this to get the predicted point spread
GAMES_REQUIRED = 5
DATA_FOLDER = utils.DATA_FOLDER
... | 0.268462 | 0.23316 |
from functools import partial
import pytest
from pyspark.sql import types as T
from getl.blocks.write.entrypoint import batch_mysql_upsert
from getl.common.upsert import (
MysqlUpsertQuery,
handle_partition,
mysql_connection_cursor,
)
def create_dataframe(spark_session, data):
schema = T.StructType... | tests/getl/blocks/write/test_write_mysql_upsert.py |
from functools import partial
import pytest
from pyspark.sql import types as T
from getl.blocks.write.entrypoint import batch_mysql_upsert
from getl.common.upsert import (
MysqlUpsertQuery,
handle_partition,
mysql_connection_cursor,
)
def create_dataframe(spark_session, data):
schema = T.StructType... | 0.667039 | 0.363534 |
from __future__ import absolute_import
import re
from .isoerror import ISO8601Error
from .tzinfo import UTC, FixedOffset, ZERO
TZ_REGEX = r"(?P<tzname>(Z|(?P<tzsign>[+-])"\
r"(?P<tzhour>[0-9]{2})(:?(?P<tzmin>[0-9]{2}))?)?)"
TZ_RE = re.compile(TZ_REGEX)
def build_tzinfo(tzname, tzsign='+', tzhour=0, tzm... | resources/lib/streamlink/utils/isodate/isotzinfo.py | from __future__ import absolute_import
import re
from .isoerror import ISO8601Error
from .tzinfo import UTC, FixedOffset, ZERO
TZ_REGEX = r"(?P<tzname>(Z|(?P<tzsign>[+-])"\
r"(?P<tzhour>[0-9]{2})(:?(?P<tzmin>[0-9]{2}))?)?)"
TZ_RE = re.compile(TZ_REGEX)
def build_tzinfo(tzname, tzsign='+', tzhour=0, tzm... | 0.627381 | 0.206094 |
import time
import enum
import struct
from .string_table import StringTable
class MachineType(enum.IntEnum):
UNKNOWN = 0x0
AM33 = 0x1d3
AMD64 = 0x8664
ARM = 0x1c0
ARM64 = 0xaa64
ARMNT = 0x1c4
EBC = 0xebc
I386 = 0x14c
IA64 = 0x200
M32R = 0x9041
MIPS16 = 0x266
MIPSFPU = ... | cough/file.py | import time
import enum
import struct
from .string_table import StringTable
class MachineType(enum.IntEnum):
UNKNOWN = 0x0
AM33 = 0x1d3
AMD64 = 0x8664
ARM = 0x1c0
ARM64 = 0xaa64
ARMNT = 0x1c4
EBC = 0xebc
I386 = 0x14c
IA64 = 0x200
M32R = 0x9041
MIPS16 = 0x266
MIPSFPU = ... | 0.602997 | 0.31563 |
from crispy_forms.layout import Div, HTML, Field
from django import forms
from django.core.exceptions import ValidationError
from django.core.validators import RegexValidator
from django.dispatch import receiver
from markdownx.fields import MarkdownxFormField
from fiscal.models import MembershipTask
from workshops.for... | amy/fiscal/forms.py | from crispy_forms.layout import Div, HTML, Field
from django import forms
from django.core.exceptions import ValidationError
from django.core.validators import RegexValidator
from django.dispatch import receiver
from markdownx.fields import MarkdownxFormField
from fiscal.models import MembershipTask
from workshops.for... | 0.616128 | 0.128416 |
import base64
import configparser
import pathlib
import os
from plugins.adversary.app.database.dao import Dao
class AdversaryPluginSettings:
def __init__(self, config_obj=None, filestore_path=None):
self._config = config_obj
self.plugin_root = pathlib.Path(__file__).parents[1]
if filesto... | app/config.py | import base64
import configparser
import pathlib
import os
from plugins.adversary.app.database.dao import Dao
class AdversaryPluginSettings:
def __init__(self, config_obj=None, filestore_path=None):
self._config = config_obj
self.plugin_root = pathlib.Path(__file__).parents[1]
if filesto... | 0.566738 | 0.050331 |
import os
import tempfile
from unittest import TestCase
import numpy as np
import pyarrow as pa
from nlp.arrow_reader import BaseReader
from nlp.info import DatasetInfo
from nlp.splits import SplitDict, SplitInfo
class ReaderTester(BaseReader):
"""
Build a Dataset object out of Instruction instance(s).
... | tests/test_arrow_dataset.py | import os
import tempfile
from unittest import TestCase
import numpy as np
import pyarrow as pa
from nlp.arrow_reader import BaseReader
from nlp.info import DatasetInfo
from nlp.splits import SplitDict, SplitInfo
class ReaderTester(BaseReader):
"""
Build a Dataset object out of Instruction instance(s).
... | 0.454956 | 0.389024 |
import json
from tests.integration.integration_test_case import IntegrationTestCase
class TestQuestionnaireCsrf(IntegrationTestCase):
def test_given_on_interstitial_page_when_submit_with_no_csrf_token_then_forbidden(
self,
):
# Given
self.launchSurvey("test_interstitial_page")
... | tests/integration/questionnaire/test_questionnaire_csrf.py | import json
from tests.integration.integration_test_case import IntegrationTestCase
class TestQuestionnaireCsrf(IntegrationTestCase):
def test_given_on_interstitial_page_when_submit_with_no_csrf_token_then_forbidden(
self,
):
# Given
self.launchSurvey("test_interstitial_page")
... | 0.519034 | 0.36458 |
import numpy as np
def get_ABL_U(z,Ur,zr,type='Log',**kwargs):
"""Function of undisturbed inflow wind speed
Inputs
----------
z: np.array, float
Heights to evaluate the streamwise wind speed
Ur: float
Reference wind speed
zr: float
Reference height
type: str, opti... | fusedwake/Inflow.py | import numpy as np
def get_ABL_U(z,Ur,zr,type='Log',**kwargs):
"""Function of undisturbed inflow wind speed
Inputs
----------
z: np.array, float
Heights to evaluate the streamwise wind speed
Ur: float
Reference wind speed
zr: float
Reference height
type: str, opti... | 0.792906 | 0.481576 |
import tkinter as tk
import tkinter.font as tk_font
from tkinter import ttk
import random
def pigeonhole_sort(values, max):
""" Use pigeonhole sort to sort the array."""
# Make the pigeonholes.
pigeonholes = [None for i in range(max + 1)]
# Move items into the pigeonholes.
for value in ... | algs2e_python/Chapter 06/python/pigeonhole_sort.py | import tkinter as tk
import tkinter.font as tk_font
from tkinter import ttk
import random
def pigeonhole_sort(values, max):
""" Use pigeonhole sort to sort the array."""
# Make the pigeonholes.
pigeonholes = [None for i in range(max + 1)]
# Move items into the pigeonholes.
for value in ... | 0.565419 | 0.268899 |
from django.db import migrations, models
import django.db.models.deletion
class Migration(migrations.Migration):
dependencies = [
('ligand', '0012_auto_20210308_1819'),
]
operations = [
migrations.RemoveField(
model_name='biasedpathways',
name='ligand_pubchem',
... | ligand/migrations/0013_auto_20210727_1339.py |
from django.db import migrations, models
import django.db.models.deletion
class Migration(migrations.Migration):
dependencies = [
('ligand', '0012_auto_20210308_1819'),
]
operations = [
migrations.RemoveField(
model_name='biasedpathways',
name='ligand_pubchem',
... | 0.586168 | 0.206554 |
import multiprocessing
import random
import time
import typing
import numpy as np
from transformers import GPT2TokenizerFast
from .dataclass import ModelParameter
from .utils_core import chunks, color_print
def render_video(model_output: typing.List[typing.Tuple[np.ndarray, typing.List[str]]],
coun... | src/interface.py | import multiprocessing
import random
import time
import typing
import numpy as np
from transformers import GPT2TokenizerFast
from .dataclass import ModelParameter
from .utils_core import chunks, color_print
def render_video(model_output: typing.List[typing.Tuple[np.ndarray, typing.List[str]]],
coun... | 0.408159 | 0.194406 |
# ======================================================================
import sys
import traceback
# ======================================================================
class MessageLogger:
VERBOSITY_LEVELS = {
-1: [],
0: ["FATAL"],
1: ["INFO", "FATAL"],
2: ["INFO", "ERROR... | src/olympus/utils/logger.py |
# ======================================================================
import sys
import traceback
# ======================================================================
class MessageLogger:
VERBOSITY_LEVELS = {
-1: [],
0: ["FATAL"],
1: ["INFO", "FATAL"],
2: ["INFO", "ERROR... | 0.40392 | 0.199347 |
import json
import logging
from AWSIoTPythonSDK.MQTTLib import AWSIoTMQTTClient
from common._libs.helpers.singleton import Singleton, delete_singleton_object, get_singleton_instance
logger = logging.getLogger(__name__)
class AWSIotClient(metaclass=Singleton):
def __init__(self, certs, client_id, endpoint):
... | common/_iot_qa_api/aws_iot_client/aws_client.py | import json
import logging
from AWSIoTPythonSDK.MQTTLib import AWSIoTMQTTClient
from common._libs.helpers.singleton import Singleton, delete_singleton_object, get_singleton_instance
logger = logging.getLogger(__name__)
class AWSIotClient(metaclass=Singleton):
def __init__(self, certs, client_id, endpoint):
... | 0.522446 | 0.066387 |
import os
import glob
import pickle
import datetime as dt
import matplotlib.pyplot as plt
import calmap
import pandas as pd
from googleapiclient.discovery import build
from google_auth_oauthlib.flow import InstalledAppFlow
from google.auth.transport.requests import Request
import credentials.config_lifelogs as config... | src/process_lifelogs.py | import os
import glob
import pickle
import datetime as dt
import matplotlib.pyplot as plt
import calmap
import pandas as pd
from googleapiclient.discovery import build
from google_auth_oauthlib.flow import InstalledAppFlow
from google.auth.transport.requests import Request
import credentials.config_lifelogs as config... | 0.159348 | 0.229222 |
from django.http import HttpRequest
from rest_framework.views import APIView
from rest_framework.response import Response
from rest_framework.decorators import api_view
from workflows.services import WorkflowServices, WorkflowActions
class Workflows(APIView):
"""
Class to get and post workflows
"""
de... | api/workflows/views.py | from django.http import HttpRequest
from rest_framework.views import APIView
from rest_framework.response import Response
from rest_framework.decorators import api_view
from workflows.services import WorkflowServices, WorkflowActions
class Workflows(APIView):
"""
Class to get and post workflows
"""
de... | 0.709925 | 0.23467 |
__all__ = [
'LazyStartResponseMiddleware', 'SynchronousInputMiddleware'
]
try:
from cStringIO import StringIO
except ImportError:
from StringIO import StringIO
class COGENOperationWrapper(object):
def __init__(self, gate, module):
self.module = module
self.gate = gate
... | cogen/web/async.py | __all__ = [
'LazyStartResponseMiddleware', 'SynchronousInputMiddleware'
]
try:
from cStringIO import StringIO
except ImportError:
from StringIO import StringIO
class COGENOperationWrapper(object):
def __init__(self, gate, module):
self.module = module
self.gate = gate
... | 0.503662 | 0.042782 |
import time
import ujson
import requests
import logging
from network import WLAN
# https://developers.google.com/maps/documentation/geolocation/intro
# {
# "homeMobileCountryCode": 310,
# "homeMobileNetworkCode": 410,
# "radioType": "gsm",
# "carrier": "Vodafone",
# "considerIp": "true",
# "wifiAccessPoin... | geoposition.py |
import time
import ujson
import requests
import logging
from network import WLAN
# https://developers.google.com/maps/documentation/geolocation/intro
# {
# "homeMobileCountryCode": 310,
# "homeMobileNetworkCode": 410,
# "radioType": "gsm",
# "carrier": "Vodafone",
# "considerIp": "true",
# "wifiAccessPoin... | 0.335242 | 0.14554 |
import math
from pprint import pprint
class Slicer:
@staticmethod
def slice_bin(bin_data, chunks, debug=False):
"""
Slice a binary string into smaller binary chunks given binary data and a list of chunk boundaries.
"""
slices = []
bin_int = int.from_bytes(bin_data, 'b... | src/backend/lib/util.py | import math
from pprint import pprint
class Slicer:
@staticmethod
def slice_bin(bin_data, chunks, debug=False):
"""
Slice a binary string into smaller binary chunks given binary data and a list of chunk boundaries.
"""
slices = []
bin_int = int.from_bytes(bin_data, 'b... | 0.597021 | 0.301298 |
from azext_iot.digitaltwins.commands_twins import delete_all_twin
from azext_iot.digitaltwins.commands_models import delete_all_models
from azext_iot.digitaltwins.providers.resource import ResourceProvider
from azext_iot.digitaltwins.common import (
ADTEndpointType,
ADTEndpointAuthType,
ADTPublicNetworkAcc... | azext_iot/digitaltwins/commands_resource.py |
from azext_iot.digitaltwins.commands_twins import delete_all_twin
from azext_iot.digitaltwins.commands_models import delete_all_models
from azext_iot.digitaltwins.providers.resource import ResourceProvider
from azext_iot.digitaltwins.common import (
ADTEndpointType,
ADTEndpointAuthType,
ADTPublicNetworkAcc... | 0.415254 | 0.064653 |
from ansible.module_utils.hashivault import hashivault_argspec
from ansible.module_utils.hashivault import hashivault_auth_client
from ansible.module_utils.hashivault import hashivault_init
from ansible.module_utils.hashivault import hashiwrapper
DEFAULT_TTL = 2764800
ANSIBLE_METADATA = {'status': ['stableinterface'],... | ansible/modules/hashivault/hashivault_namespace.py | from ansible.module_utils.hashivault import hashivault_argspec
from ansible.module_utils.hashivault import hashivault_auth_client
from ansible.module_utils.hashivault import hashivault_init
from ansible.module_utils.hashivault import hashiwrapper
DEFAULT_TTL = 2764800
ANSIBLE_METADATA = {'status': ['stableinterface'],... | 0.651909 | 0.338104 |
import click
import filelock
import os
import tqdm
from psutil import cpu_count
from typing import TYPE_CHECKING
from multiprocessing.pool import ThreadPool
from functools import partial
from aim.sdk.run import Run
from aim.storage.rockscontainer import RocksContainer
if TYPE_CHECKING:
from aim.sdk.repo import R... | aim/cli/reindex/utils.py | import click
import filelock
import os
import tqdm
from psutil import cpu_count
from typing import TYPE_CHECKING
from multiprocessing.pool import ThreadPool
from functools import partial
from aim.sdk.run import Run
from aim.storage.rockscontainer import RocksContainer
if TYPE_CHECKING:
from aim.sdk.repo import R... | 0.189034 | 0.077727 |
from __future__ import unicode_literals
from django.core.cache import caches
from django.db import models
from django.utils.encoding import python_2_unicode_compatible
from django.utils.translation import ugettext_lazy as _
from rdmo.core.utils import get_uri_prefix
from rdmo.core.models import Model, TranslationMixi... | rdmo/questions/models.py | from __future__ import unicode_literals
from django.core.cache import caches
from django.db import models
from django.utils.encoding import python_2_unicode_compatible
from django.utils.translation import ugettext_lazy as _
from rdmo.core.utils import get_uri_prefix
from rdmo.core.models import Model, TranslationMixi... | 0.684897 | 0.080502 |
import numpy as np
import matplotlib
matplotlib.use('Agg')
import matplotlib.pyplot as plt
import matplotlib.cm as cm
from matplotlib.colors import Normalize
from mpl_toolkits.mplot3d import Axes3D
def plotSwarm( sim, t ):
fig = plt.figure()
ax = fig.gca(projection='3d')
locations = []
directions = []
for fish in... | examples/learning/reinforcement/swarm/_model/plotter.py | import numpy as np
import matplotlib
matplotlib.use('Agg')
import matplotlib.pyplot as plt
import matplotlib.cm as cm
from matplotlib.colors import Normalize
from mpl_toolkits.mplot3d import Axes3D
def plotSwarm( sim, t ):
fig = plt.figure()
ax = fig.gca(projection='3d')
locations = []
directions = []
for fish in... | 0.203866 | 0.538862 |
# standard imports
import datetime
import os
import platform
import signal
import sys
import time
import json
import logging
import logging.handlers
# third party imports
import pygame
import requests
import locale
#now = datetime.datetime.now()
locale.setlocale(locale.LC_TIME, "")
url_holfuy = "http://api.holfuy.c... | piweatherrock/weather.py |
# standard imports
import datetime
import os
import platform
import signal
import sys
import time
import json
import logging
import logging.handlers
# third party imports
import pygame
import requests
import locale
#now = datetime.datetime.now()
locale.setlocale(locale.LC_TIME, "")
url_holfuy = "http://api.holfuy.c... | 0.295942 | 0.107672 |
import datetime
import os
import pendulum
import pytest
from dagfactory import utils
NOW = datetime.datetime.today().replace(hour=0, minute=0, second=0, microsecond=0)
CET = pendulum.timezone("Europe/Amsterdam")
UTC = pendulum.timezone("UTC")
def test_get_start_date_date_no_timezone():
expected = datetime.dat... | tests/test_utils.py | import datetime
import os
import pendulum
import pytest
from dagfactory import utils
NOW = datetime.datetime.today().replace(hour=0, minute=0, second=0, microsecond=0)
CET = pendulum.timezone("Europe/Amsterdam")
UTC = pendulum.timezone("UTC")
def test_get_start_date_date_no_timezone():
expected = datetime.dat... | 0.524638 | 0.644498 |
import sys
import pygit2
import shutil
import pika
import json
import gc
from github import Github
from pymongo import MongoClient
from bson.objectid import ObjectId
sys.path.append("..")
from common.settings import cfg
import common.file_system_manager as fsm
from github_common import commit, push
def callback(ch,... | github/github_update_mq.py | import sys
import pygit2
import shutil
import pika
import json
import gc
from github import Github
from pymongo import MongoClient
from bson.objectid import ObjectId
sys.path.append("..")
from common.settings import cfg
import common.file_system_manager as fsm
from github_common import commit, push
def callback(ch,... | 0.170888 | 0.080683 |
import uuid
from rest_framework import status
from rest_framework.test import APITestCase
from backoffice.business_logic.user_login import UserLoginLogic
from backoffice.test.helper.authorization_helper import http_authorization_setup_by_current_user
from backoffice.test.mock.group import group_payload
from backoffic... | backoffice/test/group/test_get_group.py | import uuid
from rest_framework import status
from rest_framework.test import APITestCase
from backoffice.business_logic.user_login import UserLoginLogic
from backoffice.test.helper.authorization_helper import http_authorization_setup_by_current_user
from backoffice.test.mock.group import group_payload
from backoffic... | 0.359027 | 0.079997 |
from rest_framework.permissions import IsAuthenticated, BasePermission, \
SAFE_METHODS
from rest_framework.viewsets import ModelViewSet
from rest_framework.response import Response
from rest_framework.decorators import action
from rest_framework.status import HTTP_400_BAD_REQUEST, HTTP_401_UNAUTHORIZED, \
HTTP_... | api/drinks/views/users.py | from rest_framework.permissions import IsAuthenticated, BasePermission, \
SAFE_METHODS
from rest_framework.viewsets import ModelViewSet
from rest_framework.response import Response
from rest_framework.decorators import action
from rest_framework.status import HTTP_400_BAD_REQUEST, HTTP_401_UNAUTHORIZED, \
HTTP_... | 0.519034 | 0.092893 |
from nets.ogb_node_classification.gated_gcn_net import GatedGCNNet, GatedGCNNet_pyg, ResGatedGCNNet_pyg
from nets.ogb_node_classification.gcn_net import GCNNet_pyg
from nets.ogb_node_classification.gat_net import GATNet_pyg
from nets.ogb_node_classification.graphsage_net import GraphSageNet, GraphSageNet_pyg
from nets.... | nets/ogb_node_classification/load_net.py | from nets.ogb_node_classification.gated_gcn_net import GatedGCNNet, GatedGCNNet_pyg, ResGatedGCNNet_pyg
from nets.ogb_node_classification.gcn_net import GCNNet_pyg
from nets.ogb_node_classification.gat_net import GATNet_pyg
from nets.ogb_node_classification.graphsage_net import GraphSageNet, GraphSageNet_pyg
from nets.... | 0.644561 | 0.288106 |
from ...imcmo import ManagedObject
from ...imccoremeta import MoPropertyMeta, MoMeta
from ...imcmeta import VersionMeta
class ComputeRackUnitConsts:
ADMIN_POWER_BMC_RESET_DEFAULT = "bmc-reset-default"
ADMIN_POWER_BMC_RESET_IMMEDIATE = "bmc-reset-immediate"
ADMIN_POWER_CMOS_RESET_IMMEDIATE = "cmos-reset-i... | imcsdk/mometa/compute/ComputeRackUnit.py |
from ...imcmo import ManagedObject
from ...imccoremeta import MoPropertyMeta, MoMeta
from ...imcmeta import VersionMeta
class ComputeRackUnitConsts:
ADMIN_POWER_BMC_RESET_DEFAULT = "bmc-reset-default"
ADMIN_POWER_BMC_RESET_IMMEDIATE = "bmc-reset-immediate"
ADMIN_POWER_CMOS_RESET_IMMEDIATE = "cmos-reset-i... | 0.428353 | 0.114196 |
import numpy as np
import cv2
import os
def load_raw(path: str,
site: str,
multipage: bool = True):
"""Raw data loader
This function takes a path to an experiment folder and
loads specified site data into a numpy array.
Output array will be of shape: (n_frames, 2048, 204... | pipeline/preprocess.py |
import numpy as np
import cv2
import os
def load_raw(path: str,
site: str,
multipage: bool = True):
"""Raw data loader
This function takes a path to an experiment folder and
loads specified site data into a numpy array.
Output array will be of shape: (n_frames, 2048, 204... | 0.672224 | 0.509947 |
# Authors: <NAME>
# License: BSD 3 clause
import numpy as np
def _is_builtin(obj):
"""
Check if the type of `obj` is a builtin type.
Parameters
----------
obj : object
Object in question.
Returns
-------
builtin : bool
True if `obj` is a builtin type
"""
return obj.__class__.__module__ == 'builtins'
... | kdtrees/_utils.py | # Authors: <NAME>
# License: BSD 3 clause
import numpy as np
def _is_builtin(obj):
"""
Check if the type of `obj` is a builtin type.
Parameters
----------
obj : object
Object in question.
Returns
-------
builtin : bool
True if `obj` is a builtin type
"""
return obj.__class__.__module__ == 'builtins'
... | 0.902872 | 0.585753 |
import numpy as np
import tensorflow as tf
from model.baseline import Baseline
class CNNBaseline(Baseline):
"""CapsNet model."""
def __init__(self, hps, images, labels):
"""CapsNet constructor"""
"""
Args:
hps: Hyperparameters.
images: Batches of images. [batch_si... | model/cnn_baseline.py | import numpy as np
import tensorflow as tf
from model.baseline import Baseline
class CNNBaseline(Baseline):
"""CapsNet model."""
def __init__(self, hps, images, labels):
"""CapsNet constructor"""
"""
Args:
hps: Hyperparameters.
images: Batches of images. [batch_si... | 0.885737 | 0.514278 |
import json
import hashlib
import base64
from django.utils import timezone
from django.core.mail import EmailMultiAlternatives
from posters.models import Conference, Poster, Author, PosterAuthor
import logging
logFormatter = logging.Formatter("%(asctime)s [%(threadName)-12.12s] [%(levelname)-5.5s] %(message)s")
logg... | send_emails.py | import json
import hashlib
import base64
from django.utils import timezone
from django.core.mail import EmailMultiAlternatives
from posters.models import Conference, Poster, Author, PosterAuthor
import logging
logFormatter = logging.Formatter("%(asctime)s [%(threadName)-12.12s] [%(levelname)-5.5s] %(message)s")
logg... | 0.253306 | 0.097176 |
import abc
import logging
import pickle
import threading
import uuid
from oslo_utils import reflection
from taskflow import retry
from taskflow import task
from taskflow.patterns import linear_flow
from cloudferry import discover
from cloudferry import model
from cloudferry.lib.utils import override
from cloudferry.l... | cloudferry/lib/os/migrate/base.py | import abc
import logging
import pickle
import threading
import uuid
from oslo_utils import reflection
from taskflow import retry
from taskflow import task
from taskflow.patterns import linear_flow
from cloudferry import discover
from cloudferry import model
from cloudferry.lib.utils import override
from cloudferry.l... | 0.680666 | 0.139279 |
import logging
import json
import httplib2
import urlparse
from django.conf import settings
from iondb.rundb.plan.ampliseq import AmpliSeqPanelImport
from iondb.utils.utils import convert
logger = logging.getLogger(__name__)
"""
This parses all the existing designs, both user created(logged in User) panesls
and fix... | dbReports/iondb/rundb/configure/ampliseq_design_parser.py | import logging
import json
import httplib2
import urlparse
from django.conf import settings
from iondb.rundb.plan.ampliseq import AmpliSeqPanelImport
from iondb.utils.utils import convert
logger = logging.getLogger(__name__)
"""
This parses all the existing designs, both user created(logged in User) panesls
and fix... | 0.302597 | 0.125279 |
import typing
from uecp.commands.base import (
UECPCommand,
UECPCommandDecodeElementCodeMismatchError,
UECPCommandDecodeNotEnoughData,
)
@UECPCommand.register_type
class RDSEnabledSetCommand(UECPCommand):
ELEMENT_CODE = 0x1E
def __init__(self, enable: bool):
self._enable = bool(enable)
... | uecp/commands/rds_control.py | import typing
from uecp.commands.base import (
UECPCommand,
UECPCommandDecodeElementCodeMismatchError,
UECPCommandDecodeNotEnoughData,
)
@UECPCommand.register_type
class RDSEnabledSetCommand(UECPCommand):
ELEMENT_CODE = 0x1E
def __init__(self, enable: bool):
self._enable = bool(enable)
... | 0.639511 | 0.222109 |
class KStacks:
def __init__(self, k, n):
self.k = k # Number of stacks.
self.n = n # Total size of array holding
# all the 'k' stacks.
# Array which holds 'k' stacks.
self.arr = [0] * self.n
# All stacks are empty to begin with
# (-1 denotes stack is em... | Competitive Programming/Stacks & Queues/implement k stacks in a single array.py |
class KStacks:
def __init__(self, k, n):
self.k = k # Number of stacks.
self.n = n # Total size of array holding
# all the 'k' stacks.
# Array which holds 'k' stacks.
self.arr = [0] * self.n
# All stacks are empty to begin with
# (-1 denotes stack is em... | 0.830869 | 0.36727 |
id_map = {}
keywords = ["int", "float", "while", "until", "string", "if", "else", "boolean", "true", "false", "for", "printf", "struct", "return"]
operators = ["+", "-", "*", "/", "%", "=", "equals", ">", "<", "and", "or", "not", "?", ":"]
delimiters = ["{", "}", "(", ")", "[", "]", ";"," "]
comments = ['#']
val... | CC Assignment/a.py | id_map = {}
keywords = ["int", "float", "while", "until", "string", "if", "else", "boolean", "true", "false", "for", "printf", "struct", "return"]
operators = ["+", "-", "*", "/", "%", "=", "equals", ">", "<", "and", "or", "not", "?", ":"]
delimiters = ["{", "}", "(", ")", "[", "]", ";"," "]
comments = ['#']
val... | 0.172033 | 0.193414 |
from datetime import datetime, timedelta
import logging
import pytest
from prosafe_exporter.prosafe_exporter_base import ProSafeExporter, ProSafeRetrieve
logging.basicConfig(level=logging.INFO)
@pytest.fixture(name='client')
def fixture_client():
exporter = ProSafeExporter(retrievers=[])
wit... | prosafe_exporter/tests/test_prosafe_exporter_endpoint.py | from datetime import datetime, timedelta
import logging
import pytest
from prosafe_exporter.prosafe_exporter_base import ProSafeExporter, ProSafeRetrieve
logging.basicConfig(level=logging.INFO)
@pytest.fixture(name='client')
def fixture_client():
exporter = ProSafeExporter(retrievers=[])
wit... | 0.444324 | 0.281653 |
import datetime
import math
def convert_K_to_RGB(colour_temperature):
"""
https://gist.github.com/petrklus/b1f427accdf7438606a6
Converts from K to RGB, algorithm courtesy of
http://www.tannerhelland.com/4435/convert-temperature-rgb-algorithm-code/
"""
#range check
if colour_temperature <... | rpi/util.py | import datetime
import math
def convert_K_to_RGB(colour_temperature):
"""
https://gist.github.com/petrklus/b1f427accdf7438606a6
Converts from K to RGB, algorithm courtesy of
http://www.tannerhelland.com/4435/convert-temperature-rgb-algorithm-code/
"""
#range check
if colour_temperature <... | 0.510741 | 0.359758 |
from django.http import HttpResponseRedirect
from django.shortcuts import get_object_or_404, render
from django.core.urlresolvers import reverse
from richard.base.utils import smart_int
from richard.playlists import models
def playlist_delete(request):
if not request.method == 'POST':
return HttpRespons... | src/richard/playlists/views.py |
from django.http import HttpResponseRedirect
from django.shortcuts import get_object_or_404, render
from django.core.urlresolvers import reverse
from richard.base.utils import smart_int
from richard.playlists import models
def playlist_delete(request):
if not request.method == 'POST':
return HttpRespons... | 0.20458 | 0.034619 |
import sys
import os
from os import environ
import django
from django.conf import settings
settings.configure(DEBUG=True,
DATABASES={
'default': {
'ENGINE': 'django.db.backends.sqlite3',
}
},
... | runtests.py | import sys
import os
from os import environ
import django
from django.conf import settings
settings.configure(DEBUG=True,
DATABASES={
'default': {
'ENGINE': 'django.db.backends.sqlite3',
}
},
... | 0.148232 | 0.075756 |
import sys
from mininet.topo import Topo
from mininet.node import Host
from mininet.net import Mininet
from mininet.log import setLogLevel
import pathlib
node_names = [f'h{h+1}' for h in range(25)]
key_server_name = 'ks'
class SingleSwitchTopo(Topo):
def build(self):
switch: str = self.addSwitch('s1')
... | src/test/mininet/topology.py | import sys
from mininet.topo import Topo
from mininet.node import Host
from mininet.net import Mininet
from mininet.log import setLogLevel
import pathlib
node_names = [f'h{h+1}' for h in range(25)]
key_server_name = 'ks'
class SingleSwitchTopo(Topo):
def build(self):
switch: str = self.addSwitch('s1')
... | 0.2522 | 0.078784 |
#
# Autocapstone v0.4
# Created for the OMA course from Parrot Labs at KEYW Corporation.
# https://github.com/vesche
#
import json
import os
import subprocess
import sys
import time
from email_crawl import crawl
# email template
email_text = '''Hey there!<br/ >
I'm new in the office and ran into ... | autocapstone/autocapstone.py |
#
# Autocapstone v0.4
# Created for the OMA course from Parrot Labs at KEYW Corporation.
# https://github.com/vesche
#
import json
import os
import subprocess
import sys
import time
from email_crawl import crawl
# email template
email_text = '''Hey there!<br/ >
I'm new in the office and ran into ... | 0.183265 | 0.061819 |
import tensorflow as tf
import numpy as np
from tensorflow.contrib.rnn import MultiRNNCell
from tensorflow.contrib.rnn import GRUCell
from tensorflow.contrib.rnn import DropoutWrapper, ResidualWrapper
# cell instance
def gru_cell(hidden_dim):
return tf.contrib.rnn.GRUCell(num_units=hidden_dim)
# cell insta... | model/layers.py |
import tensorflow as tf
import numpy as np
from tensorflow.contrib.rnn import MultiRNNCell
from tensorflow.contrib.rnn import GRUCell
from tensorflow.contrib.rnn import DropoutWrapper, ResidualWrapper
# cell instance
def gru_cell(hidden_dim):
return tf.contrib.rnn.GRUCell(num_units=hidden_dim)
# cell insta... | 0.798069 | 0.312724 |
import random
import nltk
from nltk.grammar import Nonterminal, Production
class Grammar(object):
def __init__(self, filepath=None):
if filepath:
self.load(filepath)
def load(self, filepath):
cfg_string = ''.join(list(open(filepath).readlines()))
# parse from nltk
... | mol_vae/cfg_parser/cfg_parser.py |
import random
import nltk
from nltk.grammar import Nonterminal, Production
class Grammar(object):
def __init__(self, filepath=None):
if filepath:
self.load(filepath)
def load(self, filepath):
cfg_string = ''.join(list(open(filepath).readlines()))
# parse from nltk
... | 0.411347 | 0.199776 |
import networkx as nx
import matplotlib.pyplot as plt
import pandas as pd
df = pd.read_csv('CommuterRailStationLineOrdering.csv')
graph = {}
for i in range(len(df)):
if df.iloc[i].stop_id not in graph:
graph[df.iloc[i].stop_id] = []
if i != len(df)-1:
if df.iloc[i+1].route_long_name == df.il... | app.py | import networkx as nx
import matplotlib.pyplot as plt
import pandas as pd
df = pd.read_csv('CommuterRailStationLineOrdering.csv')
graph = {}
for i in range(len(df)):
if df.iloc[i].stop_id not in graph:
graph[df.iloc[i].stop_id] = []
if i != len(df)-1:
if df.iloc[i+1].route_long_name == df.il... | 0.153994 | 0.345602 |
from typing import Callable
import pytest
from moona.http.context import HTTPContext
from moona.http.handlers import HTTPHandler, end
from moona.http.request_route import (
bind_params,
bind_query,
route,
route_ci,
subroute,
subroute_ci,
)
@pytest.mark.asyncio
@pytest.mark.parametrize(
"... | tests/http/test_request_route.py | from typing import Callable
import pytest
from moona.http.context import HTTPContext
from moona.http.handlers import HTTPHandler, end
from moona.http.request_route import (
bind_params,
bind_query,
route,
route_ci,
subroute,
subroute_ci,
)
@pytest.mark.asyncio
@pytest.mark.parametrize(
"... | 0.477798 | 0.204203 |
# Copyright xmuspeech (Author: JFZhou 2020-05-31)
import numpy as np
import os
import sys
sys.path.insert(0, 'subtools/pytorch')
import libs.support.kaldi_io as kaldi_io
from plda_base import PLDA
class CORAL(object):
def __init__(self,
mean_diff_scale=1.0,
w... | score/pyplda/ivector-adapt-plda-cip.py |
# Copyright xmuspeech (Author: JFZhou 2020-05-31)
import numpy as np
import os
import sys
sys.path.insert(0, 'subtools/pytorch')
import libs.support.kaldi_io as kaldi_io
from plda_base import PLDA
class CORAL(object):
def __init__(self,
mean_diff_scale=1.0,
w... | 0.193185 | 0.236098 |
from django.conf.urls import url
from . import views
from django.contrib.auth import views as auth_views
app_name = 'prof'
urlpatterns = [
url(r'^$', views.index, name='index'),
# url(r'^login/$', auth_views.login, name='login'),
# url(r'^logout/$', auth_views.logout, name='logout'),
url(r'^regi... | prof/urls.py | from django.conf.urls import url
from . import views
from django.contrib.auth import views as auth_views
app_name = 'prof'
urlpatterns = [
url(r'^$', views.index, name='index'),
# url(r'^login/$', auth_views.login, name='login'),
# url(r'^logout/$', auth_views.logout, name='logout'),
url(r'^regi... | 0.125132 | 0.088741 |
import pygame
class textInput:
def __init__(self,screen,axex,axey,length,height,
maxdigit = 8,
textsize=20,
textcolor=(255,255,255),
bordercolor=(255,255,255),
bordercolor_click=(0,0,255),
fontcolor=(7,9,44) ):
"""
Required parameters :
- screen of your game/app (created with pygame.display.set_... | textinput.py | import pygame
class textInput:
def __init__(self,screen,axex,axey,length,height,
maxdigit = 8,
textsize=20,
textcolor=(255,255,255),
bordercolor=(255,255,255),
bordercolor_click=(0,0,255),
fontcolor=(7,9,44) ):
"""
Required parameters :
- screen of your game/app (created with pygame.display.set_... | 0.371707 | 0.370339 |
def add(num1,num2):
return num1 + num2
def subtract(num1,num2):
return num1 - num2
def multiply(num1,num2):
return num1 * num2
def division(num1,num2):
return num1 / num2
print("Choose an option:\n 1.Add \n 2.Subtract \n 3.Multiply\n 4.Division")
user_choice = input(">")
while user_cho... | SimpleCalculator.py | def add(num1,num2):
return num1 + num2
def subtract(num1,num2):
return num1 - num2
def multiply(num1,num2):
return num1 * num2
def division(num1,num2):
return num1 / num2
print("Choose an option:\n 1.Add \n 2.Subtract \n 3.Multiply\n 4.Division")
user_choice = input(">")
while user_cho... | 0.341253 | 0.452173 |
import sys
import time
import m5
import m5.ticks
from m5.objects import *
import argparse
from system import *
def parse_arguments():
parser = argparse.ArgumentParser(description=
"gem5 config file to run GAPBS")
parser.add_argument("kernel", type = str, help = "Path to vmlin... | gem5-configs/configs-gapbs-tests/gapbs_config.py | import sys
import time
import m5
import m5.ticks
from m5.objects import *
import argparse
from system import *
def parse_arguments():
parser = argparse.ArgumentParser(description=
"gem5 config file to run GAPBS")
parser.add_argument("kernel", type = str, help = "Path to vmlin... | 0.360714 | 0.167763 |
def intToBin(x: int) -> str:
return "{0:b}".format(int(x))
def removeLeadingZeros(x: str) -> str:
if '1' in x:
return x.lstrip('0')
else:
return '0'
def addBin(first: str, second: str) -> str:
if int(first, 2) == 0:
return second
elif int(second, 2) == 0:
return f... | module1/binary_arithmetic/__init__.py | def intToBin(x: int) -> str:
return "{0:b}".format(int(x))
def removeLeadingZeros(x: str) -> str:
if '1' in x:
return x.lstrip('0')
else:
return '0'
def addBin(first: str, second: str) -> str:
if int(first, 2) == 0:
return second
elif int(second, 2) == 0:
return f... | 0.287668 | 0.598224 |
import ctypes
import dace
import torch
import torch.utils.dlpack
from dace import data, dtypes
class DLDeviceType(ctypes.c_int):
kDLCPU = 1
kDLGPU = 2
kDLCPUPinned = 3
kDLOpenCL = 4
kDLVulkan = 7
kDLMetal = 8
kDLVPI = 9
kDLROCM = 10
kDLExtDev = 12
class DLDataTypeCode(ctypes.c_u... | daceml/pytorch/dlpack.py | import ctypes
import dace
import torch
import torch.utils.dlpack
from dace import data, dtypes
class DLDeviceType(ctypes.c_int):
kDLCPU = 1
kDLGPU = 2
kDLCPUPinned = 3
kDLOpenCL = 4
kDLVulkan = 7
kDLMetal = 8
kDLVPI = 9
kDLROCM = 10
kDLExtDev = 12
class DLDataTypeCode(ctypes.c_u... | 0.580352 | 0.42316 |
from .Core import overrideMethod, CORE
from gui.Scaleform.daapi.view.meta.TankCarouselMeta import TankCarouselMeta
from gui.Scaleform.daapi.view.lobby.messengerBar.NotificationListButton import NotificationListButton
from gui.Scaleform.daapi.view.lobby.header.LobbyHeader import LobbyHeader
from gui.Scaleform.daapi.vie... | source/ivm/res/scripts/client/gui/mods/ivm/ivmGarage.py | from .Core import overrideMethod, CORE
from gui.Scaleform.daapi.view.meta.TankCarouselMeta import TankCarouselMeta
from gui.Scaleform.daapi.view.lobby.messengerBar.NotificationListButton import NotificationListButton
from gui.Scaleform.daapi.view.lobby.header.LobbyHeader import LobbyHeader
from gui.Scaleform.daapi.vie... | 0.500732 | 0.076891 |
import albumentations as A
import cv2
import torch
from albumentations.pytorch import ToTensorV2
from utils import seed_everything
DATASET = 'PASCAL_VOC'
DEVICE = "cuda" if torch.cuda.is_available() else "cpu"
# seed_everything() # If you want deterministic behavior
NUM_WORKERS = 4
BATCH_SIZE = 32
IMAGE_SIZE = 416
N... | yolov3/config.py | import albumentations as A
import cv2
import torch
from albumentations.pytorch import ToTensorV2
from utils import seed_everything
DATASET = 'PASCAL_VOC'
DEVICE = "cuda" if torch.cuda.is_available() else "cpu"
# seed_everything() # If you want deterministic behavior
NUM_WORKERS = 4
BATCH_SIZE = 32
IMAGE_SIZE = 416
N... | 0.572006 | 0.290789 |
import numpy as np
import pandas as pd
import matplotlib.pyplot as plt
import os
class Sink:
def write(self, key, obj):
raise Exception('Virtual function is not overriden')
def flush(self):
raise Exception('Virtual function is not overriden')
class CompositeSink(Sink):
def __init__(se... | sinks.py | import numpy as np
import pandas as pd
import matplotlib.pyplot as plt
import os
class Sink:
def write(self, key, obj):
raise Exception('Virtual function is not overriden')
def flush(self):
raise Exception('Virtual function is not overriden')
class CompositeSink(Sink):
def __init__(se... | 0.513425 | 0.277253 |
import mock
from oslo_config import cfg
from oslo_utils import uuidutils
from webob import exc
import webtest
from apmec.api import extensions
from apmec.api.v1 import attributes
from apmec.tests.unit import test_api_v2
from apmec.tests.unit import test_extensions
from apmec.tests.unit import testlib_api
class Exte... | apmec/tests/unit/test_api_v2_extension.py |
import mock
from oslo_config import cfg
from oslo_utils import uuidutils
from webob import exc
import webtest
from apmec.api import extensions
from apmec.api.v1 import attributes
from apmec.tests.unit import test_api_v2
from apmec.tests.unit import test_extensions
from apmec.tests.unit import testlib_api
class Exte... | 0.546496 | 0.057546 |
# Core Django imports
# Third-party app imports
from django_mock_queries.query import MockModel
# Imports from your apps
from usaspending_api.common.helpers.unit_test_helper import add_to_mock_objects
from usaspending_api.awards.v2.views.subawards import SubawardsViewSet
def strip_award_id(api_dict):
d = {k: ... | usaspending_api/awards/tests/unit/test_subawards.py |
# Core Django imports
# Third-party app imports
from django_mock_queries.query import MockModel
# Imports from your apps
from usaspending_api.common.helpers.unit_test_helper import add_to_mock_objects
from usaspending_api.awards.v2.views.subawards import SubawardsViewSet
def strip_award_id(api_dict):
d = {k: ... | 0.642208 | 0.284938 |
from __future__ import unicode_literals
from django.conf import settings
from django.db import migrations, models
import django.db.models.deletion
class Migration(migrations.Migration):
initial = True
dependencies = [
migrations.swappable_dependency(settings.AUTH_USER_MODEL),
]
operations ... | choicapp/migrations/0001_initial.py | from __future__ import unicode_literals
from django.conf import settings
from django.db import migrations, models
import django.db.models.deletion
class Migration(migrations.Migration):
initial = True
dependencies = [
migrations.swappable_dependency(settings.AUTH_USER_MODEL),
]
operations ... | 0.608129 | 0.14439 |
from __future__ import division,print_function,absolute_import,unicode_literals
import time
import datetime
import os
LTsv_HourMAXLower,LTsv_HourMAXUpper=(24,48)
LTsv_overhour=LTsv_HourMAXLower
LTsv_diffminute=0
LTsv_zodiacjp=("鼠","牛","虎","兎","龍","蛇","馬","羊","猿","鶏","犬","猪")
LTsv_zodiacch=("子","丑","寅","卯","辰","巳","午",... | LTsv/LTsv_time.py | from __future__ import division,print_function,absolute_import,unicode_literals
import time
import datetime
import os
LTsv_HourMAXLower,LTsv_HourMAXUpper=(24,48)
LTsv_overhour=LTsv_HourMAXLower
LTsv_diffminute=0
LTsv_zodiacjp=("鼠","牛","虎","兎","龍","蛇","馬","羊","猿","鶏","犬","猪")
LTsv_zodiacch=("子","丑","寅","卯","辰","巳","午",... | 0.224991 | 0.16455 |
from torch.utils.data import Dataset
from scipy.sparse import coo_matrix
from torchtext import datasets
from .base import GraphBatcher, Batch
import numpy as np
import torch as th
import dgl
def get_nli_dataset(name='snli'):
if name == 'snli':
return datasets.SNLI
elif name == 'mnli':
return d... | graph/nli.py | from torch.utils.data import Dataset
from scipy.sparse import coo_matrix
from torchtext import datasets
from .base import GraphBatcher, Batch
import numpy as np
import torch as th
import dgl
def get_nli_dataset(name='snli'):
if name == 'snli':
return datasets.SNLI
elif name == 'mnli':
return d... | 0.737158 | 0.312265 |
import multiprocessing
import os
import time
import typing
import matplotlib.pyplot as plt
import matplotlib.animation as animation
import numpy as np
PROCESSES: typing.List[multiprocessing.Process] = []
PAUSE: bool = False
class UpdateCells:
def __init__(self, universe: np.ndarray):
"""
UpdateC... | conways_gol/cells/update_cells_multiprocessing.py | import multiprocessing
import os
import time
import typing
import matplotlib.pyplot as plt
import matplotlib.animation as animation
import numpy as np
PROCESSES: typing.List[multiprocessing.Process] = []
PAUSE: bool = False
class UpdateCells:
def __init__(self, universe: np.ndarray):
"""
UpdateC... | 0.392453 | 0.21305 |
import logging
import json
import requests
import random
import time
import threading
from DataHandler import DataHandler, DataManager
from config import config
from cachetools import cached, TTLCache
logger = logging.getLogger(__name__)
def enum(*sequential, **named):
enums = dict(list(zip(sequential, list(ran... | src/utils/authorization.py | import logging
import json
import requests
import random
import time
import threading
from DataHandler import DataHandler, DataManager
from config import config
from cachetools import cached, TTLCache
logger = logging.getLogger(__name__)
def enum(*sequential, **named):
enums = dict(list(zip(sequential, list(ran... | 0.29696 | 0.081301 |
import os
import sys
import copy
import click
import signal
import socket
import facet
from typing import (
Any,
Dict,
)
CONTEXT_SETTINGS = {
'max_content_width': 90,
'allow_extra_args': True, # enabled allows '&' (background process)
'ignore_unknown_options': False,
# 'show_default': False, ... | facet/scripts/cli.py | import os
import sys
import copy
import click
import signal
import socket
import facet
from typing import (
Any,
Dict,
)
CONTEXT_SETTINGS = {
'max_content_width': 90,
'allow_extra_args': True, # enabled allows '&' (background process)
'ignore_unknown_options': False,
# 'show_default': False, ... | 0.544559 | 0.135061 |
from typing import Any, Callable, Dict, Iterator, List, Optional
from globus_sdk.response import GlobusHTTPResponse
from .base import Paginator
class _LimitOffsetBasedPaginator(Paginator):
def __init__(
self,
method: Callable,
*,
items_key: Optional[str] = None,
get_page_... | src/globus_sdk/paging/limit_offset.py | from typing import Any, Callable, Dict, Iterator, List, Optional
from globus_sdk.response import GlobusHTTPResponse
from .base import Paginator
class _LimitOffsetBasedPaginator(Paginator):
def __init__(
self,
method: Callable,
*,
items_key: Optional[str] = None,
get_page_... | 0.855369 | 0.080973 |
from dataclasses import dataclass
from modulefinder import ModuleFinder
from pathlib import Path
from pkgutil import ModuleInfo
from ward import fixture, raises, test
from ward.collect import (
get_module_path,
handled_within,
is_excluded_module,
is_test_module,
remove_excluded_paths,
search_ge... | tests/test_collect.py | from dataclasses import dataclass
from modulefinder import ModuleFinder
from pathlib import Path
from pkgutil import ModuleInfo
from ward import fixture, raises, test
from ward.collect import (
get_module_path,
handled_within,
is_excluded_module,
is_test_module,
remove_excluded_paths,
search_ge... | 0.696887 | 0.508849 |
import sys
from datetime import timedelta
from celery import Celery
from flask import Flask, Blueprint, json as flask_json, has_request_context
from flask_socketio import SocketIO
from flask_limiter import Limiter
from flask_limiter.util import get_remote_address
from flask_caching import Cache
from const.path impor... | querybook/server/app/flask_app.py | import sys
from datetime import timedelta
from celery import Celery
from flask import Flask, Blueprint, json as flask_json, has_request_context
from flask_socketio import SocketIO
from flask_limiter import Limiter
from flask_limiter.util import get_remote_address
from flask_caching import Cache
from const.path impor... | 0.348978 | 0.073364 |
__docformat__ = "restructuredtext en"
__version__ = '2.0dev'
__release_date__ = 'notyet'
# Check basic dependencies
import sys
missing = []
try:
import numpy
except ImportError as ex:
sys.stderr.write('Importing numpy failed: %s\n' % ex)
missing.append('numpy')
try:
import scipy
except ... | brian2/__init__.py | __docformat__ = "restructuredtext en"
__version__ = '2.0dev'
__release_date__ = 'notyet'
# Check basic dependencies
import sys
missing = []
try:
import numpy
except ImportError as ex:
sys.stderr.write('Importing numpy failed: %s\n' % ex)
missing.append('numpy')
try:
import scipy
except ... | 0.389314 | 0.067948 |
import uuid
import datetime
from typing import Tuple
import logging
from dateutil import parser as dp
from dateutil import tz
from flask import request, jsonify, Response
from models import Activities, Categories
from api_utils import auth_utils
FORMATTER = logging.Formatter("%(asctime)s — %(name)s — %(levelname)s ... | api_backend_server/web_app/apis/activities.py | import uuid
import datetime
from typing import Tuple
import logging
from dateutil import parser as dp
from dateutil import tz
from flask import request, jsonify, Response
from models import Activities, Categories
from api_utils import auth_utils
FORMATTER = logging.Formatter("%(asctime)s — %(name)s — %(levelname)s ... | 0.468304 | 0.159741 |
class Trie:
__slots__ = ('v', 'root', 'd', 'zero_complete')
EMPTY = object()
def __init__(self, *, zero_complete=True):
self.d = {}
self.root = True
self.v = self.EMPTY
self.zero_complete = zero_complete
def _create_item(self, root=False):
obj = (type(self))(zer... | trie/trie.py | class Trie:
__slots__ = ('v', 'root', 'd', 'zero_complete')
EMPTY = object()
def __init__(self, *, zero_complete=True):
self.d = {}
self.root = True
self.v = self.EMPTY
self.zero_complete = zero_complete
def _create_item(self, root=False):
obj = (type(self))(zer... | 0.517571 | 0.333151 |
from collections import defaultdict, namedtuple
import binascii
import hashlib
import logging
import numpy as np
import time
import traceback
from word2number.w2n import word_to_num
from typing import Tuple, List, TypeVar
import uuid
##FFS FIXME!!!! arrange utils properly, put things in one place
XYZ = Tuple[int, int,... | base_agent/base_util.py | from collections import defaultdict, namedtuple
import binascii
import hashlib
import logging
import numpy as np
import time
import traceback
from word2number.w2n import word_to_num
from typing import Tuple, List, TypeVar
import uuid
##FFS FIXME!!!! arrange utils properly, put things in one place
XYZ = Tuple[int, int,... | 0.545528 | 0.336794 |