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 |
|---|---|---|---|---|
import importlib
import uuid
from exceptions import ValueError
from utility.models.constant import constant
from decimal import *
from datetime import date, datetime
class Field(object):
def __init__(self, **options):
self.tipo_class = constant.TIPO_CAMPO
self.default = None
self.null = ... | utility/models/fields.py |
import importlib
import uuid
from exceptions import ValueError
from utility.models.constant import constant
from decimal import *
from datetime import date, datetime
class Field(object):
def __init__(self, **options):
self.tipo_class = constant.TIPO_CAMPO
self.default = None
self.null = ... | 0.430028 | 0.115686 |
import atexit
from typing import Callable, List
import _pytest.config
import _pytest.config.argparsing
import _pytest.fixtures
import _pytest.mark
import pytest
from _pytest.monkeypatch import MonkeyPatch
N_GPU_OPTIONS = (0, 1, 2, 4, 8)
# Add the path of any pytest fixture files you want to make global
pytest_plugi... | tests/conftest.py |
import atexit
from typing import Callable, List
import _pytest.config
import _pytest.config.argparsing
import _pytest.fixtures
import _pytest.mark
import pytest
from _pytest.monkeypatch import MonkeyPatch
N_GPU_OPTIONS = (0, 1, 2, 4, 8)
# Add the path of any pytest fixture files you want to make global
pytest_plugi... | 0.541166 | 0.380299 |
import os
import sys
import pandas as pd
from datetime import datetime
sys.path.append('src')
from Broker import Robinhood # noqa autopep8
import Constants as C # noqa autopep8
rh = Robinhood()
if not C.CI:
rh.writer.store.bucket_name = os.environ['S3_DEV_BUCKET']
rh.reader.store.bucket_name = os.... | test/test_Broker.py | import os
import sys
import pandas as pd
from datetime import datetime
sys.path.append('src')
from Broker import Robinhood # noqa autopep8
import Constants as C # noqa autopep8
rh = Robinhood()
if not C.CI:
rh.writer.store.bucket_name = os.environ['S3_DEV_BUCKET']
rh.reader.store.bucket_name = os.... | 0.245356 | 0.240819 |
import shutil
import os.path
import requests
from collections import defaultdict
import time
from datetime import datetime
import pickle
import networkx as nx
from glob import glob
import os
for_encoding = 'é'
wdt_sparql_url = 'https://query.wikidata.org/sparql'
WIKIDATA_PREFIX = 'http://www.wikidata.org/entity/'
def... | utils.py | import shutil
import os.path
import requests
from collections import defaultdict
import time
from datetime import datetime
import pickle
import networkx as nx
from glob import glob
import os
for_encoding = 'é'
wdt_sparql_url = 'https://query.wikidata.org/sparql'
WIKIDATA_PREFIX = 'http://www.wikidata.org/entity/'
def... | 0.247169 | 0.134122 |
def twodhist(xs,ys,fname):
import scipy
xbins = scipy.arange(0,1.5,0.0225)
ybins = scipy.arange(0,1.5,0.0225)
prob_matrix,X,Y = scipy.histogram2d(ys,xs,bins=[xbins,ybins])
prob_matrix = prob_matrix / prob_matrix.max()
import pylab
#X, Y = pylab.meshgrid(zs_copy,zs_c... | plot_rederr.py |
def twodhist(xs,ys,fname):
import scipy
xbins = scipy.arange(0,1.5,0.0225)
ybins = scipy.arange(0,1.5,0.0225)
prob_matrix,X,Y = scipy.histogram2d(ys,xs,bins=[xbins,ybins])
prob_matrix = prob_matrix / prob_matrix.max()
import pylab
#X, Y = pylab.meshgrid(zs_copy,zs_c... | 0.129169 | 0.235966 |
import xml.etree.ElementTree as ET
from twisted.trial import unittest
from twisted.internet import reactor
import twisted
import platform
# Import PyMh files and modules.
from Modules.Core.data_objects import MqttBrokerData, \
LocationData, ScheduleLightData, ControllerData
from test.xml_data import XML_... | src/Modules/Computer/Mqtt/test/test_mqtt_client.py | import xml.etree.ElementTree as ET
from twisted.trial import unittest
from twisted.internet import reactor
import twisted
import platform
# Import PyMh files and modules.
from Modules.Core.data_objects import MqttBrokerData, \
LocationData, ScheduleLightData, ControllerData
from test.xml_data import XML_... | 0.246533 | 0.116337 |
from . import SequenceManipMethods
from . import PropensityFactory, ProbeVectorFactory
PropensityFactory = PropensityFactory.PropensityFactory
ProbeVectorFactory = ProbeVectorFactory.ProbeVectorFactory
from . import CodonDictionaries
import matplotlib.pyplot as plt
from matplotlib import cm
import matplotlib.patches a... | build/lib/rsnapsim/poi.py | from . import SequenceManipMethods
from . import PropensityFactory, ProbeVectorFactory
PropensityFactory = PropensityFactory.PropensityFactory
ProbeVectorFactory = ProbeVectorFactory.ProbeVectorFactory
from . import CodonDictionaries
import matplotlib.pyplot as plt
from matplotlib import cm
import matplotlib.patches a... | 0.612426 | 0.382487 |
import datetime
import random
def _get_nin_lt_checksum(code: str) -> int:
numbers = list(map(int, code))
factors = [1, 2, 3, 4, 5, 6, 7, 8, 9, 1]
checksum = sum(x * i for x, i in zip(numbers, factors)) % 11
if checksum == 10:
factors = [3, 4, 5, 6, 7, 8, 9, 1, 2, 3]
checksum = sum(x *... | spinta/utils/nin.py |
import datetime
import random
def _get_nin_lt_checksum(code: str) -> int:
numbers = list(map(int, code))
factors = [1, 2, 3, 4, 5, 6, 7, 8, 9, 1]
checksum = sum(x * i for x, i in zip(numbers, factors)) % 11
if checksum == 10:
factors = [3, 4, 5, 6, 7, 8, 9, 1, 2, 3]
checksum = sum(x *... | 0.49585 | 0.371365 |
import requests
from collections import namedtuple
import datetime
_YNABTransactionBase = namedtuple(
"YNABTransactionBase",
("date", "amount", "payee_name", "import_id", "is_foreign", "is_cleared"),
)
class YNABTransaction(_YNABTransactionBase):
@classmethod
def from_up_transaction_data(cls, transac... | up2ynab/clients/ynab.py | import requests
from collections import namedtuple
import datetime
_YNABTransactionBase = namedtuple(
"YNABTransactionBase",
("date", "amount", "payee_name", "import_id", "is_foreign", "is_cleared"),
)
class YNABTransaction(_YNABTransactionBase):
@classmethod
def from_up_transaction_data(cls, transac... | 0.802362 | 0.290868 |
import unittest
from paip.emycin import *
def eq(x, y):
return x == y
class CFTests(unittest.TestCase):
def test_cf_or(self):
cases = [
(0.6, 0.4, 0.76),
(-0.3, -0.75, -0.825),
(0.3, -0.4, -1.0/7.0),
(-0.4, 0.3, -1.0/7.0),
]
for... | paip/tests/test_emycin.py | import unittest
from paip.emycin import *
def eq(x, y):
return x == y
class CFTests(unittest.TestCase):
def test_cf_or(self):
cases = [
(0.6, 0.4, 0.76),
(-0.3, -0.75, -0.825),
(0.3, -0.4, -1.0/7.0),
(-0.4, 0.3, -1.0/7.0),
]
for... | 0.5144 | 0.771176 |
import pandas as pd
import numpy as np
import random
import sys
from tabulate import tabulate
'''
Reads the .csv file into a Pandas dataframe.
'''
def read_csv_into_dataframe(filename):
return pd.read_csv(filename)
'''
Takes in a dictionary correlating first names with "M" (if the name is
commonly a male name), an... | apda_gender_stats.py | import pandas as pd
import numpy as np
import random
import sys
from tabulate import tabulate
'''
Reads the .csv file into a Pandas dataframe.
'''
def read_csv_into_dataframe(filename):
return pd.read_csv(filename)
'''
Takes in a dictionary correlating first names with "M" (if the name is
commonly a male name), an... | 0.341363 | 0.486636 |
import oci # noqa: F401
from oci.util import WAIT_RESOURCE_NOT_FOUND # noqa: F401
class DataSafeClientCompositeOperations(object):
"""
This class provides a wrapper around :py:class:`~oci.data_safe.DataSafeClient` and offers convenience methods
for operations that would otherwise need to be chained tog... | src/oci/data_safe/data_safe_client_composite_operations.py |
import oci # noqa: F401
from oci.util import WAIT_RESOURCE_NOT_FOUND # noqa: F401
class DataSafeClientCompositeOperations(object):
"""
This class provides a wrapper around :py:class:`~oci.data_safe.DataSafeClient` and offers convenience methods
for operations that would otherwise need to be chained tog... | 0.778313 | 0.463201 |
import serial
import pydirectinput
arduino = serial.Serial('COM3', 115200, timeout=.1) #serial input from arduino. change COM port to wherever your arduino is connected
pydirectinput.PAUSE = 0
keysDown = {} #list of currently pressed keys
def keyDown(key): #what to do if key pressed. ... | PY/JoystickP3.py | import serial
import pydirectinput
arduino = serial.Serial('COM3', 115200, timeout=.1) #serial input from arduino. change COM port to wherever your arduino is connected
pydirectinput.PAUSE = 0
keysDown = {} #list of currently pressed keys
def keyDown(key): #what to do if key pressed. ... | 0.126664 | 0.143698 |
from starkeffect import *
from ext.las_str.SimplexModMPF import Simplex
from mpmath import *
import sys
class Stark_calcSS:
def __init__(self,_n1, _n2, _m, point_ground_state):
mp.prec = 10000
self.n1 = _n1
self.n2 = _n2
self.m = abs(_m)
... | py/ext/las_str/StarkEffectSS.py | from starkeffect import *
from ext.las_str.SimplexModMPF import Simplex
from mpmath import *
import sys
class Stark_calcSS:
def __init__(self,_n1, _n2, _m, point_ground_state):
mp.prec = 10000
self.n1 = _n1
self.n2 = _n2
self.m = abs(_m)
... | 0.097393 | 0.183082 |
from kivy.app import App
from kivy.base import EventLoop
from kivy.config import Config
from kivy.uix.boxlayout import BoxLayout
from kivy.uix.button import Button
from shell import *
from plotter import *
from kivyextras import *
from sympy import *
from sympy.abc import *
FONT_NAME = "res/ubuntu-font-family-0.80/U... | main.py |
from kivy.app import App
from kivy.base import EventLoop
from kivy.config import Config
from kivy.uix.boxlayout import BoxLayout
from kivy.uix.button import Button
from shell import *
from plotter import *
from kivyextras import *
from sympy import *
from sympy.abc import *
FONT_NAME = "res/ubuntu-font-family-0.80/U... | 0.420005 | 0.111217 |
from os.path import join
import pandas as pd
from model import utils
CUMULATIVE_HDX_ADDRESS = 'coronavirus-covid-19-cases-and-deaths'
CUMULATIVE_DATASET_NAME = 'WHO-COVID-19-global-data.csv'
POP_HDX_ADDRESS = 'world-bank-indicators-of-interest-to-the-covid-19-outbreak'
POP_DATASET_NAME = 'Total Population'
COLUMNS... | model/cumulative.py | from os.path import join
import pandas as pd
from model import utils
CUMULATIVE_HDX_ADDRESS = 'coronavirus-covid-19-cases-and-deaths'
CUMULATIVE_DATASET_NAME = 'WHO-COVID-19-global-data.csv'
POP_HDX_ADDRESS = 'world-bank-indicators-of-interest-to-the-covid-19-outbreak'
POP_DATASET_NAME = 'Total Population'
COLUMNS... | 0.243103 | 0.240306 |
#!/usr/bin/env python3
# -*- coding: utf-8 -*-
import cv2
from scipy.signal import convolve2d
import numpy as np
from CSVHandler import CSVHandler
class ImgFeatureExtractor:
def __init__(self,imgDim,color_space,resizeFac,dataDir,imgDataDir,inputDataDir,learnSet):
self.color_space = color_sp... | ITU-Challenge-ML5G-PHY-master/Beam_selection/code/ImgFeatureExtractor.py |
#!/usr/bin/env python3
# -*- coding: utf-8 -*-
import cv2
from scipy.signal import convolve2d
import numpy as np
from CSVHandler import CSVHandler
class ImgFeatureExtractor:
def __init__(self,imgDim,color_space,resizeFac,dataDir,imgDataDir,inputDataDir,learnSet):
self.color_space = color_sp... | 0.189259 | 0.198549 |
from csv import reader
import sys
import os
import time
import subprocess
import sys
from subprocess import DEVNULL
if len(sys.argv) < 2:
print('usage: python3 {} <out dir>'.format(sys.argv[0]))
sys.exit(-1)
fin = sys.stdin
outdir = sys.argv[1]
def version(prog):
try:
subprocess.check_call(['p4tes... | sigcomm-2020/run_exps.py | from csv import reader
import sys
import os
import time
import subprocess
import sys
from subprocess import DEVNULL
if len(sys.argv) < 2:
print('usage: python3 {} <out dir>'.format(sys.argv[0]))
sys.exit(-1)
fin = sys.stdin
outdir = sys.argv[1]
def version(prog):
try:
subprocess.check_call(['p4tes... | 0.118806 | 0.065515 |
from __future__ import unicode_literals
from django.conf import settings
from django.core.urlresolvers import reverse
from django.db import models
from django.utils.encoding import python_2_unicode_compatible
from django.utils.functional import cached_property
from elasticsearch import ConnectionError
from modelcluste... | article/models.py | from __future__ import unicode_literals
from django.conf import settings
from django.core.urlresolvers import reverse
from django.db import models
from django.utils.encoding import python_2_unicode_compatible
from django.utils.functional import cached_property
from elasticsearch import ConnectionError
from modelcluste... | 0.616474 | 0.135461 |
import click
import pandas as pd
from simpletransformers.classification import ClassificationModel
from sklearn.metrics import f1_score, accuracy_score
def load_validation_data(valid_in_cat_path, valid_out_of_cat_path):
valid_in_cat = pd.read_csv(valid_in_cat_path, delimiter=',')
valid_out_of_cat = pd.read_cs... | src/models/train_roberta_model.py | import click
import pandas as pd
from simpletransformers.classification import ClassificationModel
from sklearn.metrics import f1_score, accuracy_score
def load_validation_data(valid_in_cat_path, valid_out_of_cat_path):
valid_in_cat = pd.read_csv(valid_in_cat_path, delimiter=',')
valid_out_of_cat = pd.read_cs... | 0.598547 | 0.260121 |
import numpy as np
import xarray as xr
from . import orca_names
def trim_and_squeeze(ds,
model_config="GLOBAL",
y_slice=None, x_slice=None,
**kwargs):
"""Remove redundant grid points and drop singleton dimensions.
Parameters
----------
... | xorca/lib.py |
import numpy as np
import xarray as xr
from . import orca_names
def trim_and_squeeze(ds,
model_config="GLOBAL",
y_slice=None, x_slice=None,
**kwargs):
"""Remove redundant grid points and drop singleton dimensions.
Parameters
----------
... | 0.762866 | 0.775711 |
import os
import sys
from random import randint, getrandbits
from boring import BoringHelper
from proc import Process
class MemoryManager(object):
"""
MemoryManager
Class that handles:
1. Creation of random processes.
2. Assigning/removing memory units from a process
3. Compacting the memory map when ne... | tareas/3/MartinezNestor/memory.py | import os
import sys
from random import randint, getrandbits
from boring import BoringHelper
from proc import Process
class MemoryManager(object):
"""
MemoryManager
Class that handles:
1. Creation of random processes.
2. Assigning/removing memory units from a process
3. Compacting the memory map when ne... | 0.149128 | 0.27788 |
import os
import logging
from .pyfl_utils import INIFile, FLDll
from .errors import ParserError
_logger = logging.getLogger(__name__)
class ConfigLoader(object):
CONFIG_FILES = [
('DATA', 'SHIPS', 'shiparch.ini'),
('DATA', 'EQUIPMENT', 'goods.ini'),
('DATA', 'EQUIPMENT', '... | importer/importer/config_loader.py | import os
import logging
from .pyfl_utils import INIFile, FLDll
from .errors import ParserError
_logger = logging.getLogger(__name__)
class ConfigLoader(object):
CONFIG_FILES = [
('DATA', 'SHIPS', 'shiparch.ini'),
('DATA', 'EQUIPMENT', 'goods.ini'),
('DATA', 'EQUIPMENT', '... | 0.23634 | 0.071656 |
import dockercloud, getopt, json, requests, signal, socket, sys, time, websocket
class HealthCheckRedeploy:
containers = []
service = None
websocket = None
completedHealthChecks = 0
healthCheck = 'off'
healthCheckPort = 80
healthCheckUrlPath = ''
healthCheckTimeout = 600
healthC... | health-check-redeploy/health-check-redeploy.py |
import dockercloud, getopt, json, requests, signal, socket, sys, time, websocket
class HealthCheckRedeploy:
containers = []
service = None
websocket = None
completedHealthChecks = 0
healthCheck = 'off'
healthCheckPort = 80
healthCheckUrlPath = ''
healthCheckTimeout = 600
healthC... | 0.218419 | 0.091463 |
import json
from alipay.aop.api.constant.ParamConstants import *
class AlipayUserDetail(object):
def __init__(self):
self._alipay_user_id = None
self._certified = None
self._logon_id = None
self._real_name = None
self._sex = None
self._user_status = None
s... | alipay/aop/api/domain/AlipayUserDetail.py | import json
from alipay.aop.api.constant.ParamConstants import *
class AlipayUserDetail(object):
def __init__(self):
self._alipay_user_id = None
self._certified = None
self._logon_id = None
self._real_name = None
self._sex = None
self._user_status = None
s... | 0.413951 | 0.064624 |
# Commands for activation.
import sys, os, readline, acttools
import ConfigParser
# kpython
from kfile import *
from kreadline import Command
def dump_KAP(kap):
l1 = ["Key ID: %s" % (str(kap.key_id) if not kap.key_id is None else "no"),
"KDN: %s" % (kap.kdn if not kap.kdn is None else "no")]
l2 ... | adminacttools/actadmcmds/actadmcmds.py |
# Commands for activation.
import sys, os, readline, acttools
import ConfigParser
# kpython
from kfile import *
from kreadline import Command
def dump_KAP(kap):
l1 = ["Key ID: %s" % (str(kap.key_id) if not kap.key_id is None else "no"),
"KDN: %s" % (kap.kdn if not kap.kdn is None else "no")]
l2 ... | 0.32896 | 0.114492 |
import tensorflow as tf
# tf.disable_v2_behavior()
import numpy as np
import os
def write_graph(name):
logdir = os.path.join("log", name)
file_writer = tf.summary.FileWriter(logdir)
with tf.Session() as sess:
file_writer.add_graph(sess.graph)
n_classes = 10
num_layers = 2
state_size = 100
keep_pr... | sequence_labelling/document_parsing.py | import tensorflow as tf
# tf.disable_v2_behavior()
import numpy as np
import os
def write_graph(name):
logdir = os.path.join("log", name)
file_writer = tf.summary.FileWriter(logdir)
with tf.Session() as sess:
file_writer.add_graph(sess.graph)
n_classes = 10
num_layers = 2
state_size = 100
keep_pr... | 0.726717 | 0.24326 |
class scene:
def __init__(self):
self.textures = {}
self.materials = {}
self.objects = []
def resolution(self, width, height):
self.width = width
self.height = height
def detail(self, samples_per_pixel, max_ray_bounces):
self.samples_per_pixel = samples_per_p... | scenes/scenekit.py |
class scene:
def __init__(self):
self.textures = {}
self.materials = {}
self.objects = []
def resolution(self, width, height):
self.width = width
self.height = height
def detail(self, samples_per_pixel, max_ray_bounces):
self.samples_per_pixel = samples_per_p... | 0.721351 | 0.423458 |
from typing import List, Dict
import os
from codecs import ignore_errors
from pathlib import Path
import urllib.request
from glob import glob
from tqdm import tqdm
from concurrent.futures import ProcessPoolExecutor
import re
import csv
import json
import numpy as np
import pandas as pd
from collections import namedtupl... | utils/dataset_utils.py | from typing import List, Dict
import os
from codecs import ignore_errors
from pathlib import Path
import urllib.request
from glob import glob
from tqdm import tqdm
from concurrent.futures import ProcessPoolExecutor
import re
import csv
import json
import numpy as np
import pandas as pd
from collections import namedtupl... | 0.49048 | 0.266581 |
from typing import List, Iterable
from ..ex.relational import IRelationalRow
from . import xivrow, XivRow, IXivSheet
from .interfaces import IShop, IShopListing, IShopListingItem
@xivrow
class FccShop(XivRow, IShop):
@property
def name(self) -> str:
return str(self.as_string('Name'))
@property
... | pysaintcoinach/xiv/fcc_shop.py | from typing import List, Iterable
from ..ex.relational import IRelationalRow
from . import xivrow, XivRow, IXivSheet
from .interfaces import IShop, IShopListing, IShopListingItem
@xivrow
class FccShop(XivRow, IShop):
@property
def name(self) -> str:
return str(self.as_string('Name'))
@property
... | 0.532182 | 0.168515 |
import copy
import unittest
import numpy
import numpy as np
from functools import reduce
from pyscf import lib
from pyscf import gto
from pyscf import scf
from pyscf import ao2mo
from pyscf.cc import rccsd
from pyscf.cc import addons
from pyscf.cc import rccsd_lambda
from pyscf.cc import ccsd_rdm
from pyscf.cc import... | pyscf/cc/test/test_rccsd_lambda.py |
import copy
import unittest
import numpy
import numpy as np
from functools import reduce
from pyscf import lib
from pyscf import gto
from pyscf import scf
from pyscf import ao2mo
from pyscf.cc import rccsd
from pyscf.cc import addons
from pyscf.cc import rccsd_lambda
from pyscf.cc import ccsd_rdm
from pyscf.cc import... | 0.309441 | 0.268956 |
from robot.api import logger
from .base_handler import BaseHandler
from .errors import GatlingHandlerException, SubprocessException
from .utils import run_command_line, validate_path
class GatlingHandler(BaseHandler):
def run_gatling(self, result_file, command, check_return_code=False, **env):
'''Run Gat... | src/oxygen/gatling.py | from robot.api import logger
from .base_handler import BaseHandler
from .errors import GatlingHandlerException, SubprocessException
from .utils import run_command_line, validate_path
class GatlingHandler(BaseHandler):
def run_gatling(self, result_file, command, check_return_code=False, **env):
'''Run Gat... | 0.729616 | 0.382141 |
# This source code is licensed under the MIT license found in the
# LICENSE file in the root directory of this source tree.
import logging
import unittest
from hydra.errors import ConfigCompositionException, HydraException
from parameterized import parameterized
from utils import (
BENCHMARK_CONFIGS,
INTEGRA... | tests/test_configs.py |
# This source code is licensed under the MIT license found in the
# LICENSE file in the root directory of this source tree.
import logging
import unittest
from hydra.errors import ConfigCompositionException, HydraException
from parameterized import parameterized
from utils import (
BENCHMARK_CONFIGS,
INTEGRA... | 0.772745 | 0.283938 |
import os
import torch
import torch.nn as nn
import torch.optim as optim
from torch.utils.data import DataLoader
import torchmetrics
from model.seq2seq import JointNLU
from util.conf_util import read_conf
from util.dataset_util import DatasetUtil
device = "cuda" if torch.cuda.is_available() else "cpu"
print(f"device... | run/train.py | import os
import torch
import torch.nn as nn
import torch.optim as optim
from torch.utils.data import DataLoader
import torchmetrics
from model.seq2seq import JointNLU
from util.conf_util import read_conf
from util.dataset_util import DatasetUtil
device = "cuda" if torch.cuda.is_available() else "cpu"
print(f"device... | 0.804828 | 0.31409 |
import unittest
from unittest.mock import patch, ANY
import networkx as nx
import mapper
class TestIntegration(unittest.TestCase):
def test_linear(self):
# 1D-test with 8 nodes. Make 4 edges heavy -> those 4 pairs should be mapped together
G = nx.complete_graph(8)
G.graph['edge_weight_att... | graph_mapper/test_mapper.py | import unittest
from unittest.mock import patch, ANY
import networkx as nx
import mapper
class TestIntegration(unittest.TestCase):
def test_linear(self):
# 1D-test with 8 nodes. Make 4 edges heavy -> those 4 pairs should be mapped together
G = nx.complete_graph(8)
G.graph['edge_weight_att... | 0.70069 | 0.699627 |
import copy
from collections import OrderedDict
from itertools import chain
import logging
import ir
def build_unified_ir(name_protocol_map):
class UnifiedClassSpec(object):
def __init__(self, name):
self.name = name
self.members = OrderedDict()
self.superclass_name = ... | loxigen/loxi_ir/unified.py |
import copy
from collections import OrderedDict
from itertools import chain
import logging
import ir
def build_unified_ir(name_protocol_map):
class UnifiedClassSpec(object):
def __init__(self, name):
self.name = name
self.members = OrderedDict()
self.superclass_name = ... | 0.298696 | 0.101456 |
"""Mech integration tests: multiple instances"""
import re
import subprocess
import pytest
from mech import utils
@pytest.mark.vmware
@pytest.mark.int
def test_int_multiple_instances():
"""Test with multiple instances."""
test_dir = "tests/int/multiple_instances"
utils.cleanup_dir_and_vms_from_dir(t... | mech/tests/test_int_multiple_instances.py |
"""Mech integration tests: multiple instances"""
import re
import subprocess
import pytest
from mech import utils
@pytest.mark.vmware
@pytest.mark.int
def test_int_multiple_instances():
"""Test with multiple instances."""
test_dir = "tests/int/multiple_instances"
utils.cleanup_dir_and_vms_from_dir(t... | 0.541166 | 0.421373 |
import h5py
import os
import pandas as pd
from . import ardupilot_log
from . import aura_csv
from . import aura_hdf5
from . import px4_ulog
from . import px4_sdlog2
from . import px4_csv
from . import sentera
from . import sentera2
from . import umn1_mat
from . import umn3_hdf5
def load(path):
flight_data = {}
... | rcUAS_flightdata/flight_loader.py | import h5py
import os
import pandas as pd
from . import ardupilot_log
from . import aura_csv
from . import aura_hdf5
from . import px4_ulog
from . import px4_sdlog2
from . import px4_csv
from . import sentera
from . import sentera2
from . import umn1_mat
from . import umn3_hdf5
def load(path):
flight_data = {}
... | 0.220175 | 0.140631 |
import numpy as np
from math import sqrt,log
from stochastic.processes.noise import ColoredNoise
import FWT
def generate_detectorTS(columns, rows, pixel_time = 10, jump_time = 120, return_image = False, beta = 1., sigma = 1., add_poisson = False, poisson_sigma = 1.):
"""
This function simulates a JWST detect... | src/pinknoise/utils.py | import numpy as np
from math import sqrt,log
from stochastic.processes.noise import ColoredNoise
import FWT
def generate_detectorTS(columns, rows, pixel_time = 10, jump_time = 120, return_image = False, beta = 1., sigma = 1., add_poisson = False, poisson_sigma = 1.):
"""
This function simulates a JWST detect... | 0.895728 | 0.891055 |
import argparse
import ast
import json
import logging
import re
import time
import urllib.parse
from http.server import BaseHTTPRequestHandler, HTTPServer
from pathlib import Path
from threading import Event, Thread
from typing import Dict, List, Optional, Tuple, Union
import boto3
import numpy as np
from flwr_experi... | src/py/flwr_experimental/logserver/server.py | import argparse
import ast
import json
import logging
import re
import time
import urllib.parse
from http.server import BaseHTTPRequestHandler, HTTPServer
from pathlib import Path
from threading import Event, Thread
from typing import Dict, List, Optional, Tuple, Union
import boto3
import numpy as np
from flwr_experi... | 0.742328 | 0.148973 |
from datetime import datetime
from . import db
from flask import jsonify
from flask_jwt_extended import get_jwt_identity
from .schemas.sendMessage import validate_sendMessage
def send_message(user_input):
'''
This method send message to user by given employees id, shifts or dates.
'''
data = validate_s... | server/MembersService/send_message.py | from datetime import datetime
from . import db
from flask import jsonify
from flask_jwt_extended import get_jwt_identity
from .schemas.sendMessage import validate_sendMessage
def send_message(user_input):
'''
This method send message to user by given employees id, shifts or dates.
'''
data = validate_s... | 0.402275 | 0.147402 |
import pygame
import pygame.gfxdraw
import time
import configparser
import random
gameConfig = configparser.ConfigParser()
gameConfig.read('config/config.ini')
sizeX, sizeY, interval = int(gameConfig['Cell']['x']), int(gameConfig['Cell']['y']), float(gameConfig['Snake']['speed'])
def initGrid():
return [["e" for ... | snake.py | import pygame
import pygame.gfxdraw
import time
import configparser
import random
gameConfig = configparser.ConfigParser()
gameConfig.read('config/config.ini')
sizeX, sizeY, interval = int(gameConfig['Cell']['x']), int(gameConfig['Cell']['y']), float(gameConfig['Snake']['speed'])
def initGrid():
return [["e" for ... | 0.209066 | 0.438545 |
import pathlib
import pytest
import sys
from neuro_sdk import Client
from re_assert import Matches
from typing import AbstractSet, Any, AsyncIterator, Callable, Mapping
from neuro_flow.context import FlowCtx, GitCtx, LiveContext, ProjectCtx, TagsCtx
from neuro_flow.expr import EvalError, RootABC, StrExpr, TypeT
from n... | tests/unit/test_functions.py | import pathlib
import pytest
import sys
from neuro_sdk import Client
from re_assert import Matches
from typing import AbstractSet, Any, AsyncIterator, Callable, Mapping
from neuro_flow.context import FlowCtx, GitCtx, LiveContext, ProjectCtx, TagsCtx
from neuro_flow.expr import EvalError, RootABC, StrExpr, TypeT
from n... | 0.455925 | 0.498291 |
import cv2
import Image
from BaseHTTPServer import BaseHTTPRequestHandler, HTTPServer
import StringIO
import time
capture = None
class CamHandler(BaseHTTPRequestHandler):
def do_GET(self):
if self.path.endswith('.mjpg'):
self.send_response(200)
self.send_header('Content-type', 'mu... | src/large_scale experiment/featureExtractor/video_stream/mjpegStreamer.py | import cv2
import Image
from BaseHTTPServer import BaseHTTPRequestHandler, HTTPServer
import StringIO
import time
capture = None
class CamHandler(BaseHTTPRequestHandler):
def do_GET(self):
if self.path.endswith('.mjpg'):
self.send_response(200)
self.send_header('Content-type', 'mu... | 0.233269 | 0.045395 |
import copy
import numpy as np
from mmhuman3d.data.datasets import HumanImageDataset
from mmhuman3d.data.datasets.pipelines import (
LoadImageFromFile,
MeshAffine,
RandomHorizontalFlip,
)
def test_human_image_dataset():
# test auto padding for bbox_xywh
train_dataset = HumanImageDataset(
... | tests/test_datasets/test_human_image_dataset.py | import copy
import numpy as np
from mmhuman3d.data.datasets import HumanImageDataset
from mmhuman3d.data.datasets.pipelines import (
LoadImageFromFile,
MeshAffine,
RandomHorizontalFlip,
)
def test_human_image_dataset():
# test auto padding for bbox_xywh
train_dataset = HumanImageDataset(
... | 0.585812 | 0.675778 |
import timeit
import time
y = '''
def y(n):
sum = 0;
for i in range(n):
sum += 1;
''';
g = '''
def g(n):
sum = 0;
for i in range(n):
for j in range(n):
sum += 1;
''';
h = '''
def h(n):
sum = 0;
for i in range(n):
for j in range(n*n):
sum += 1;
'... | a1_raox6250/code.py | import timeit
import time
y = '''
def y(n):
sum = 0;
for i in range(n):
sum += 1;
''';
g = '''
def g(n):
sum = 0;
for i in range(n):
for j in range(n):
sum += 1;
''';
h = '''
def h(n):
sum = 0;
for i in range(n):
for j in range(n*n):
sum += 1;
'... | 0.146118 | 0.16987 |
# # Logistic Regression with Gradient Descent
#
# Logistic regression is a predictive modelling algorithm that is used when the Y variable is binary categorical. That is, it can take only two values like 1 or 0. In this notebook we are going to discuss logistic regression for classification problems. For more info... | DataSciencePractice/MachineLearning/Logistic_Regression.py |
# # Logistic Regression with Gradient Descent
#
# Logistic regression is a predictive modelling algorithm that is used when the Y variable is binary categorical. That is, it can take only two values like 1 or 0. In this notebook we are going to discuss logistic regression for classification problems. For more info... | 0.768863 | 0.903209 |
import contextvars
import dataclasses
import functools
import sys
from collections.abc import Iterable, Sequence
from typing import Any, Callable, Optional
import morello.impl.actions
import morello.impl.base
from .. import cost, pruning, specs, system_config
prune_column_major: contextvars.ContextVar[bool] = contex... | morello/search/common.py | import contextvars
import dataclasses
import functools
import sys
from collections.abc import Iterable, Sequence
from typing import Any, Callable, Optional
import morello.impl.actions
import morello.impl.base
from .. import cost, pruning, specs, system_config
prune_column_major: contextvars.ContextVar[bool] = contex... | 0.741019 | 0.254092 |
from django import forms
from django.conf import settings
from django.utils.translation import ugettext_lazy as _
from crispy_forms.layout import Layout, Fieldset
from core.models import Person
from core.utils import horizontal_form_helper, indented_without_label, ensure_user_is_member_of_group
from .models import T... | intra/forms.py | from django import forms
from django.conf import settings
from django.utils.translation import ugettext_lazy as _
from crispy_forms.layout import Layout, Fieldset
from core.models import Person
from core.utils import horizontal_form_helper, indented_without_label, ensure_user_is_member_of_group
from .models import T... | 0.574514 | 0.078961 |
from __future__ import absolute_import, division, print_function, unicode_literals
import os
import sys
import logging
import shutil
import multiprocessing
from ava import APP_NAME
from ava.core.agent import start_agent
from ava.util import base_path
#makes multiprocessing work when in freeze mode.
multiprocessing.... | src/ava/launcher.py | from __future__ import absolute_import, division, print_function, unicode_literals
import os
import sys
import logging
import shutil
import multiprocessing
from ava import APP_NAME
from ava.core.agent import start_agent
from ava.util import base_path
#makes multiprocessing work when in freeze mode.
multiprocessing.... | 0.327561 | 0.050705 |
#1° Módulo - pyautogui
#Módulo para Automação de GUI (Graphical User Interface / Interface gráfica do usuário)
#Função que retorna coordenadas(x,y) na tela, referênte ao centro imagem passada como parâmetro.
from pyautogui import locateCenterOnScreen
#Função que movimenta o mouse até uma coordenada(x,y) expecífica
f... | cmd/aceita_partida.py |
#1° Módulo - pyautogui
#Módulo para Automação de GUI (Graphical User Interface / Interface gráfica do usuário)
#Função que retorna coordenadas(x,y) na tela, referênte ao centro imagem passada como parâmetro.
from pyautogui import locateCenterOnScreen
#Função que movimenta o mouse até uma coordenada(x,y) expecífica
f... | 0.33928 | 0.338255 |
from django.http import HttpResponseRedirect
from django.contrib.auth import authenticate, login, logout
from django.shortcuts import redirect
try:
from urllib import urlencode
except ImportError:
from urllib.parse import urlencode
from ucamwebauth import MalformedResponseError
from ucamwebauth.utils import set... | ucamwebauth/views.py | from django.http import HttpResponseRedirect
from django.contrib.auth import authenticate, login, logout
from django.shortcuts import redirect
try:
from urllib import urlencode
except ImportError:
from urllib.parse import urlencode
from ucamwebauth import MalformedResponseError
from ucamwebauth.utils import set... | 0.439747 | 0.042305 |
import traceback
import psycopg2
from Classes.Funcionario import Funcionario
class FuncionarioDAO(object):
# Método utilizado para listar todos os usuarios existentes
def listas_todas(self):
resultados = []
try:
connection = psycopg2.connect(user="postgres", password="<PA... | ClassesDAO/FuncionarioDAO.py | import traceback
import psycopg2
from Classes.Funcionario import Funcionario
class FuncionarioDAO(object):
# Método utilizado para listar todos os usuarios existentes
def listas_todas(self):
resultados = []
try:
connection = psycopg2.connect(user="postgres", password="<PA... | 0.157817 | 0.079317 |
import os
import pandas as pd
from PyQt5 import QtWidgets
from PyQt5.QtGui import QCloseEvent
from PyQt5.QtWidgets import QTableWidget
from PyQt5.QtWidgets import (QTableWidgetItem)
from PyQt5.QtWidgets import QWidget
from config.PATH import SUBDIRS
subdir = SUBDIRS[1]
class DataSetsWindow(QWidget):
def __init_... | GUI/PyQt/DLart/network_interface.py | import os
import pandas as pd
from PyQt5 import QtWidgets
from PyQt5.QtGui import QCloseEvent
from PyQt5.QtWidgets import QTableWidget
from PyQt5.QtWidgets import (QTableWidgetItem)
from PyQt5.QtWidgets import QWidget
from config.PATH import SUBDIRS
subdir = SUBDIRS[1]
class DataSetsWindow(QWidget):
def __init_... | 0.374448 | 0.126461 |
import numba
import numpy as np
from . import general_kernels as kernels
from typing import Literal, Optional
def delta(x: np.ndarray, interval: int) -> np.ndarray:
"""Returns the delta between two timeseries with an interval offset
Args:
x (np.ndarray): n-vector timeseries
interval (int): ... | finfast/analyze/indicators/general.py | import numba
import numpy as np
from . import general_kernels as kernels
from typing import Literal, Optional
def delta(x: np.ndarray, interval: int) -> np.ndarray:
"""Returns the delta between two timeseries with an interval offset
Args:
x (np.ndarray): n-vector timeseries
interval (int): ... | 0.934813 | 0.721964 |
from django.conf import settings
# Some default settings that needed in app
TEST = False
LOGIN_URL = getattr( settings, 'LOGIN_URL' )
# To allow Anonymous access
# Need user "Anonymous" in DB
LIMITED_ANONYMOUS = getattr( settings, 'LIMITED_ANONYMOUS', False )
# Anonymous user ID
LIMITED_ANONYMOUS_ID = getattr( se... | limited/core/settings.py |
from django.conf import settings
# Some default settings that needed in app
TEST = False
LOGIN_URL = getattr( settings, 'LOGIN_URL' )
# To allow Anonymous access
# Need user "Anonymous" in DB
LIMITED_ANONYMOUS = getattr( settings, 'LIMITED_ANONYMOUS', False )
# Anonymous user ID
LIMITED_ANONYMOUS_ID = getattr( se... | 0.425605 | 0.045671 |
import os.path
import click
import tensorflow as tf
import numpy
import pkg_resources
import sklearn.model_selection
from xtreme_vision.Detection.keras_resnet import metrics as m
from xtreme_vision.Detection.keras_resnet import models
_benchmarks = {
"CIFAR-10": tf.keras.datasets.cifar10,
"CIFAR-100": tf.ker... | xtreme_vision/Detection/keras_resnet/benchmarks/__init__.py | import os.path
import click
import tensorflow as tf
import numpy
import pkg_resources
import sklearn.model_selection
from xtreme_vision.Detection.keras_resnet import metrics as m
from xtreme_vision.Detection.keras_resnet import models
_benchmarks = {
"CIFAR-10": tf.keras.datasets.cifar10,
"CIFAR-100": tf.ker... | 0.497559 | 0.34895 |
import argparse
import yaml
import imp
from termcolor import colored
import configparser
import sys
import os
# Add relative path to sys path
# This is necessary so the user can import modules (e.g., views) in their tests
sys.path.insert(0, os.getcwd())
#---
# GLOBAL VARIABLES
# Dictionary of tests loaded
tests_loa... | selt/run.py | import argparse
import yaml
import imp
from termcolor import colored
import configparser
import sys
import os
# Add relative path to sys path
# This is necessary so the user can import modules (e.g., views) in their tests
sys.path.insert(0, os.getcwd())
#---
# GLOBAL VARIABLES
# Dictionary of tests loaded
tests_loa... | 0.447943 | 0.233193 |
import os
import torch
import torch.nn as nn
import numpy as np
import sys
from tensorboardX import SummaryWriter
from config import SearchConfig
import utils
from architect import Architect
from importlib import import_module
def main():
config = SearchConfig(section='fine-tune')
device = torch.device("cud... | fine_tune.py | import os
import torch
import torch.nn as nn
import numpy as np
import sys
from tensorboardX import SummaryWriter
from config import SearchConfig
import utils
from architect import Architect
from importlib import import_module
def main():
config = SearchConfig(section='fine-tune')
device = torch.device("cud... | 0.47171 | 0.136868 |
from showcase_utils import *
from tbase.skeleton import Skeleton
fs = tf.app.flags
fs.DEFINE_string('model', 'none',
'which model to use for the prediction, expected format is "model_name/run_id[ft]" [none]')
fs.DEFINE_integer('samples', 20, 'amount of examples to be shown')
FLAGS = fs.FLAGS
def ma... | infilling/showcase_motion_blending_extended.py | from showcase_utils import *
from tbase.skeleton import Skeleton
fs = tf.app.flags
fs.DEFINE_string('model', 'none',
'which model to use for the prediction, expected format is "model_name/run_id[ft]" [none]')
fs.DEFINE_integer('samples', 20, 'amount of examples to be shown')
FLAGS = fs.FLAGS
def ma... | 0.63409 | 0.446133 |
import os
import yaml
from yaml import dump
IMPORT_TAG = '!import'
SEQ_TAG = 'tag:yaml.org,2002:seq'
class ImportLoader(yaml.Loader):
"""
Override default loader to support inclusion of YAML files and permit lists
as YAML keys.
"""
def __init__(self, stream):
"""
Obtain path to s... | tests/import_yaml.py | import os
import yaml
from yaml import dump
IMPORT_TAG = '!import'
SEQ_TAG = 'tag:yaml.org,2002:seq'
class ImportLoader(yaml.Loader):
"""
Override default loader to support inclusion of YAML files and permit lists
as YAML keys.
"""
def __init__(self, stream):
"""
Obtain path to s... | 0.513912 | 0.195863 |
from django.test import TestCase
from django.test import Client
from django.contrib.auth.models import User
from ..models import Message, UserFollowingRelationship
class ServicesTestCase(TestCase):
def setUp(self):
self.username = 'test'
self.password = '<PASSWORD>'
self.email = '<EMAIL>'
... | hirundo/website/tests/tests.py | from django.test import TestCase
from django.test import Client
from django.contrib.auth.models import User
from ..models import Message, UserFollowingRelationship
class ServicesTestCase(TestCase):
def setUp(self):
self.username = 'test'
self.password = '<PASSWORD>'
self.email = '<EMAIL>'
... | 0.369201 | 0.338118 |
import os
import numpy as np
from libpysal import io
import libpysal as ps
import unittest
from spglm.family import Gaussian, Poisson, Binomial
from ..sel_bw import Sel_BW
from numpy.testing import assert_allclose
class TestSelBWGaussian(unittest.TestCase):
def setUp(self):
data_path = ps.examples.get_pat... | mgwr/tests/test_sel_bw.py | import os
import numpy as np
from libpysal import io
import libpysal as ps
import unittest
from spglm.family import Gaussian, Poisson, Binomial
from ..sel_bw import Sel_BW
from numpy.testing import assert_allclose
class TestSelBWGaussian(unittest.TestCase):
def setUp(self):
data_path = ps.examples.get_pat... | 0.595493 | 0.571468 |
import argparse
import torch
from torch.autograd import Variable
import data
parser = argparse.ArgumentParser(description='PyTorch PTB Language Model')
# Model parameters.
parser.add_argument('--data', type=str, default='./data/penn',
help='location of the data corpus')
parser.add_argument('--m... | generate.py |
import argparse
import torch
from torch.autograd import Variable
import data
parser = argparse.ArgumentParser(description='PyTorch PTB Language Model')
# Model parameters.
parser.add_argument('--data', type=str, default='./data/penn',
help='location of the data corpus')
parser.add_argument('--m... | 0.472197 | 0.139895 |
import argparse
import os
import shlex
import socket
import subprocess
import sys
from datetime import datetime
MINIMUM_WATCHED_PERCENTAGE = 80
MINIMUM_DURATION = 300 # five minutes
IGNORE_ONLINE_STREAMS = True
REMOTE_HOST = "drizzle"
REMOTE_CMD = "echo %s>>data/playback.lst"
ALLOWED_EXTENSIONS = [
"mkv",
"mp... | cfg/mpv/config/scripts/playback_logger.py | import argparse
import os
import shlex
import socket
import subprocess
import sys
from datetime import datetime
MINIMUM_WATCHED_PERCENTAGE = 80
MINIMUM_DURATION = 300 # five minutes
IGNORE_ONLINE_STREAMS = True
REMOTE_HOST = "drizzle"
REMOTE_CMD = "echo %s>>data/playback.lst"
ALLOWED_EXTENSIONS = [
"mkv",
"mp... | 0.281011 | 0.063978 |
from collections import namedtuple
import requests
from .api_collections import (
LogisticsApi,
CatalogApi,
GiftCardApi,
PaymentsGatewayApi,
OrderManagementApi,
MasterDataApi,
)
DEFAULT_TIMEOUT = 60.0
class Vtex:
"""
Client class for the Vtex apis endpoints
"""
def __init__... | vtex/vtex.py | from collections import namedtuple
import requests
from .api_collections import (
LogisticsApi,
CatalogApi,
GiftCardApi,
PaymentsGatewayApi,
OrderManagementApi,
MasterDataApi,
)
DEFAULT_TIMEOUT = 60.0
class Vtex:
"""
Client class for the Vtex apis endpoints
"""
def __init__... | 0.86212 | 0.128717 |
#pylint: disable=invalid-name
from ply import yacc
from . import ast, lexer
from .lexer import tokens #pylint: disable=unused-import
class ParserGlobals:
"""Global variables for parser."""
def __init__(self):
"""Global variables for parser."""
self.error_list = []
start = 'program'
# Empt... | llb3d/parser.py | #pylint: disable=invalid-name
from ply import yacc
from . import ast, lexer
from .lexer import tokens #pylint: disable=unused-import
class ParserGlobals:
"""Global variables for parser."""
def __init__(self):
"""Global variables for parser."""
self.error_list = []
start = 'program'
# Empt... | 0.528533 | 0.347842 |
__author__ = 'ipetrash'
from pathlib import Path
import re
from bs4 import BeautifulSoup
FILE_NAME_ACL = Path(r'C:\<...>\ads\<...>\src\<...>.xml')
LICENSE_PATH = "<...>/<...>/<...>/"
TEMPLATE_THIS_PROP = """
<xsc:Item>
<xsc:IdReference Path="{acl_id} {prop_id}" Invoke="true" extStr="#STD_PROP_VALUE#">
... | tx_parse_xml/acl_update_License_for_GetterSources.py |
__author__ = 'ipetrash'
from pathlib import Path
import re
from bs4 import BeautifulSoup
FILE_NAME_ACL = Path(r'C:\<...>\ads\<...>\src\<...>.xml')
LICENSE_PATH = "<...>/<...>/<...>/"
TEMPLATE_THIS_PROP = """
<xsc:Item>
<xsc:IdReference Path="{acl_id} {prop_id}" Invoke="true" extStr="#STD_PROP_VALUE#">
... | 0.359364 | 0.086401 |
import torch
from torch import nn
import torch.nn.functional as F
from torch.autograd import Variable
class CrossEntropyLabelSmooth(nn.Module):
"""Cross entropy loss with label smoothing regularizer.
Reference:
Szegedy et al. Rethinking the Inception Architecture for Computer Vision. CVPR 2016.
Equati... | layers/cls_loss.py | import torch
from torch import nn
import torch.nn.functional as F
from torch.autograd import Variable
class CrossEntropyLabelSmooth(nn.Module):
"""Cross entropy loss with label smoothing regularizer.
Reference:
Szegedy et al. Rethinking the Inception Architecture for Computer Vision. CVPR 2016.
Equati... | 0.930348 | 0.696036 |
from __future__ import unicode_literals
import logging
import os
import sys
import zipfile
from distutils import msvc9compiler
from distutils.spawn import spawn
# pylint: disable=import-error
# pylint: disable=no-name-in-module
if sys.version_info[0] < 3:
# Use urllib2 here since this code should be able to be use... | data/msi_prebuild/pysqlite.py | from __future__ import unicode_literals
import logging
import os
import sys
import zipfile
from distutils import msvc9compiler
from distutils.spawn import spawn
# pylint: disable=import-error
# pylint: disable=no-name-in-module
if sys.version_info[0] < 3:
# Use urllib2 here since this code should be able to be use... | 0.357792 | 0.096663 |
import os
import logging
import sys
import uamqp
from uamqp import authentication
def get_logger(level):
uamqp_logger = logging.getLogger("uamqp")
if not uamqp_logger.handlers:
handler = logging.StreamHandler(stream=sys.stdout)
handler.setFormatter(logging.Formatter('%(asctime)s %(name)-12s ... | samples/test_azure_event_hubs_send.py |
import os
import logging
import sys
import uamqp
from uamqp import authentication
def get_logger(level):
uamqp_logger = logging.getLogger("uamqp")
if not uamqp_logger.handlers:
handler = logging.StreamHandler(stream=sys.stdout)
handler.setFormatter(logging.Formatter('%(asctime)s %(name)-12s ... | 0.248717 | 0.066327 |
import cv2
import pytesseract
import numpy as np
import os
per = 25
roi = [[(410, 236), (768, 282), 'text', 'Số'],
[(300, 302), (830, 344), 'text', 'Họ tên'],
[(584, 352), (770, 388), 'text', 'Ngày sinh'],
[(480, 380), (566, 420), 'text', 'Giới tính'],
[(838, 384), (984, 422), 'text', 'Quố... | IdentityCardDetection.py | import cv2
import pytesseract
import numpy as np
import os
per = 25
roi = [[(410, 236), (768, 282), 'text', 'Số'],
[(300, 302), (830, 344), 'text', 'Họ tên'],
[(584, 352), (770, 388), 'text', 'Ngày sinh'],
[(480, 380), (566, 420), 'text', 'Giới tính'],
[(838, 384), (984, 422), 'text', 'Quố... | 0.065605 | 0.234977 |
import pandas as pd
import numpy as np
from PAINTeR import global_vars
from PAINTeR import misc
from PAINTeR import qst
# load tables
df_bochum = pd.read_csv(global_vars._BOCHUM_TABLE_)
df_essen = pd.read_csv(global_vars._ESSEN_TABLE_)
df_szeged = pd.read_csv(global_vars._SZEGED_TABLE_)
# calculate BMI
df_essen['BM... | scripts/process_tables.py | import pandas as pd
import numpy as np
from PAINTeR import global_vars
from PAINTeR import misc
from PAINTeR import qst
# load tables
df_bochum = pd.read_csv(global_vars._BOCHUM_TABLE_)
df_essen = pd.read_csv(global_vars._ESSEN_TABLE_)
df_szeged = pd.read_csv(global_vars._SZEGED_TABLE_)
# calculate BMI
df_essen['BM... | 0.341583 | 0.205495 |
import gc
import io
import math
import os
import time
from collections import deque
from multiprocessing import Pool
import numpy as np # linear algebra
import pandas as pd # data processing, CSV file I/O (e.g. pd.read_csv)
from scipy.optimize import curve_fit
from sklearn.preprocessing import StandardSca... | src/feature_extractors/magnitude_features.py | import gc
import io
import math
import os
import time
from collections import deque
from multiprocessing import Pool
import numpy as np # linear algebra
import pandas as pd # data processing, CSV file I/O (e.g. pd.read_csv)
from scipy.optimize import curve_fit
from sklearn.preprocessing import StandardSca... | 0.270095 | 0.158142 |
from typing import List, Tuple, Optional
import torch
import torch.nn as nn
from torecsys.layers import DNNLayer
from torecsys.models.ctr import CtrBaseModel
class ElaboratedEntireSpaceSupervisedMultiTaskModel(CtrBaseModel):
"""
Model class of Elaborated Entire Space Supervised Multi Task Model (ESM2).
... | torecsys/models/ctr/elaborated_entire_space_supervised_multi_task.py | from typing import List, Tuple, Optional
import torch
import torch.nn as nn
from torecsys.layers import DNNLayer
from torecsys.models.ctr import CtrBaseModel
class ElaboratedEntireSpaceSupervisedMultiTaskModel(CtrBaseModel):
"""
Model class of Elaborated Entire Space Supervised Multi Task Model (ESM2).
... | 0.916133 | 0.712826 |
from minpiler.std import MObject, L, M, inline, Processors, sync
class DekkersAlgorithm:
"""
Seems to be slower than the Peterson's algorithm.
https://en.wikipedia.org/wiki/Dekker%27s_algorithm
"""
@inline
@staticmethod
def reset(mem: MObject, addr_wants_to_enter_0: int, addr_wants_to_ent... | samples/std/lock.py | from minpiler.std import MObject, L, M, inline, Processors, sync
class DekkersAlgorithm:
"""
Seems to be slower than the Peterson's algorithm.
https://en.wikipedia.org/wiki/Dekker%27s_algorithm
"""
@inline
@staticmethod
def reset(mem: MObject, addr_wants_to_enter_0: int, addr_wants_to_ent... | 0.537527 | 0.561696 |
import numpy as np
import pandas as pd
import json
import re
from statistics import mean
import argparse
class InstanceMetrics:
def __init__(self, inst, instance, decision_paths, weights, label, features, depth):
self.inst = inst
self.instance = instance
self.decision_paths = decision_path... | experiments/PythonScripts/instance_metrics.py | import numpy as np
import pandas as pd
import json
import re
from statistics import mean
import argparse
class InstanceMetrics:
def __init__(self, inst, instance, decision_paths, weights, label, features, depth):
self.inst = inst
self.instance = instance
self.decision_paths = decision_path... | 0.512937 | 0.338378 |
import math
import numpy as np
from scipy.optimize import fsolve
# use below functions in synthesizer.py to determine noise type and corresponding noise parameters
def lap_comp(epsilon, delta, sensitivity, k):
return epsilon * 1.0 / k / sensitivity
def lap_adv_comp(epsilon, delta, sensitivity, k):
def fun... | utils/advanced_composition.py | import math
import numpy as np
from scipy.optimize import fsolve
# use below functions in synthesizer.py to determine noise type and corresponding noise parameters
def lap_comp(epsilon, delta, sensitivity, k):
return epsilon * 1.0 / k / sensitivity
def lap_adv_comp(epsilon, delta, sensitivity, k):
def fun... | 0.564819 | 0.666158 |
import os
import json
import binascii
import numpy as np
from TrafficFlowClassification.TrafficLog.setLog import logger
def getIntfrom_pcap(filename):
"""将 pcap 文件读入, 转换为 十进制 的格式
Args:
filename (str): pcap 文件的路径
Returns:
np.array: 返回 pcap 对应的数组, 如果是 784 bytes, array 的长度就是 784
"""
... | TrafficFlowClassification/preprocess/pcap2npy.py | import os
import json
import binascii
import numpy as np
from TrafficFlowClassification.TrafficLog.setLog import logger
def getIntfrom_pcap(filename):
"""将 pcap 文件读入, 转换为 十进制 的格式
Args:
filename (str): pcap 文件的路径
Returns:
np.array: 返回 pcap 对应的数组, 如果是 784 bytes, array 的长度就是 784
"""
... | 0.284278 | 0.320535 |
from __future__ import absolute_import
from __future__ import unicode_literals
import io
import os
import stat
import pytest
from identify import identify
def test_all_tags_includes_basic_ones():
assert 'file' in identify.ALL_TAGS
assert 'directory' in identify.ALL_TAGS
def test_tags_from_path_does_not_e... | tests/identify_test.py | from __future__ import absolute_import
from __future__ import unicode_literals
import io
import os
import stat
import pytest
from identify import identify
def test_all_tags_includes_basic_ones():
assert 'file' in identify.ALL_TAGS
assert 'directory' in identify.ALL_TAGS
def test_tags_from_path_does_not_e... | 0.364099 | 0.303016 |
__author__ = '<EMAIL>'
# Partially derived from https://github.com/mattermost/mattermost-integration-gitlab
import json
import time
import sys
import logging
import os
import settings
import ssl
import threading
import urlparse
from BaseHTTPServer import BaseHTTPRequestHandler, HTTPServer
from rssfeed import RssFeed
... | feedfetcher.py | __author__ = '<EMAIL>'
# Partially derived from https://github.com/mattermost/mattermost-integration-gitlab
import json
import time
import sys
import logging
import os
import settings
import ssl
import threading
import urlparse
from BaseHTTPServer import BaseHTTPRequestHandler, HTTPServer
from rssfeed import RssFeed
... | 0.305801 | 0.102889 |
import logging
import random
from abc import ABC
from collections import defaultdict
from numbers import Number
import networkx as nx
from torch import nn
from ctrl.commons.tree import Tree
from ctrl.transformations.transformation import Transformation
from ctrl.transformations.transformation_pool import Transformati... | ctrl/transformations/transformation_tree.py | import logging
import random
from abc import ABC
from collections import defaultdict
from numbers import Number
import networkx as nx
from torch import nn
from ctrl.commons.tree import Tree
from ctrl.transformations.transformation import Transformation
from ctrl.transformations.transformation_pool import Transformati... | 0.700178 | 0.212334 |
import numpy
from dpnp.dpnp_algo import *
from dpnp.dparray import dparray
from dpnp.dpnp_utils import *
import dpnp
import dpnp.config as config
__all__ = [
"dot",
"einsum",
"einsum_path",
"inner",
"kron",
"outer",
"tensordot",
"vdot"
]
def dot(x1, x2, **kwargs):
"""
Return... | dpnp/dpnp_iface_linearalgebra.py | import numpy
from dpnp.dpnp_algo import *
from dpnp.dparray import dparray
from dpnp.dpnp_utils import *
import dpnp
import dpnp.config as config
__all__ = [
"dot",
"einsum",
"einsum_path",
"inner",
"kron",
"outer",
"tensordot",
"vdot"
]
def dot(x1, x2, **kwargs):
"""
Return... | 0.84941 | 0.596463 |
import re
import copy
from word2number import w2n
from utils.enum_type import NumMask,EPT
def trans_symbol_2_number(equ_list, num_list):
"""transfer mask symbol in equation to number.
Args:
equ_list (list): equation.
num_list (list): number list.
Return:
(list): equation.
... | mwp_solver/utils/preprocess_tool/number_operator.py |
import re
import copy
from word2number import w2n
from utils.enum_type import NumMask,EPT
def trans_symbol_2_number(equ_list, num_list):
"""transfer mask symbol in equation to number.
Args:
equ_list (list): equation.
num_list (list): number list.
Return:
(list): equation.
... | 0.612773 | 0.216446 |
from datetime import datetime
import random
from typing import Callable, Optional, Union
import boto3
from emoji import emojize
from github import Github
from github.AuthenticatedUser import AuthenticatedUser
from github.Repository import Repository
from jinja2 import Template
from loguru import logger
import mistune ... | starminder.py | from datetime import datetime
import random
from typing import Callable, Optional, Union
import boto3
from emoji import emojize
from github import Github
from github.AuthenticatedUser import AuthenticatedUser
from github.Repository import Repository
from jinja2 import Template
from loguru import logger
import mistune ... | 0.597608 | 0.118105 |
"""Tests the functions of web service."""
from itertools import chain
from airflights.auxiliary_func import formatting_time
from airflights.data_analysis import (
get_all_routes,
get_flights_filtered_direction,
get_optimal_route,
)
from tests.unit_tests.checking_sorting import (
get_median_price,
... | tests/unit_tests/unit_test.py | """Tests the functions of web service."""
from itertools import chain
from airflights.auxiliary_func import formatting_time
from airflights.data_analysis import (
get_all_routes,
get_flights_filtered_direction,
get_optimal_route,
)
from tests.unit_tests.checking_sorting import (
get_median_price,
... | 0.933461 | 0.696028 |
import unittest
from pythogic.fol.semantics.Assignment import Assignment
from pythogic.fol.semantics.Function import Function
from pythogic.fol.semantics.Interpretation import Interpretation
from pythogic.fol.semantics.Relation import Relation
from pythogic.fol.syntax.FOLAlphabet import FOLAlphabet
from pythogic.base.... | tests/test_fol.py | import unittest
from pythogic.fol.semantics.Assignment import Assignment
from pythogic.fol.semantics.Function import Function
from pythogic.fol.semantics.Interpretation import Interpretation
from pythogic.fol.semantics.Relation import Relation
from pythogic.fol.syntax.FOLAlphabet import FOLAlphabet
from pythogic.base.... | 0.688678 | 0.531513 |
from pathlib import Path
from aws_cdk.assertions import Match, Template
from aws_cdk.aws_lambda import Code, Function, LayerVersion, Runtime
from aws_cdk.aws_sqs import Queue
from aws_ddk_core.base import BaseStack
from aws_ddk_core.stages.sqs_lambda import SqsToLambdaStage
def test_sqs_lambda(test_stack: BaseStack... | core/tests/unit/test_sqs_lambda_stage.py |
from pathlib import Path
from aws_cdk.assertions import Match, Template
from aws_cdk.aws_lambda import Code, Function, LayerVersion, Runtime
from aws_cdk.aws_sqs import Queue
from aws_ddk_core.base import BaseStack
from aws_ddk_core.stages.sqs_lambda import SqsToLambdaStage
def test_sqs_lambda(test_stack: BaseStack... | 0.68742 | 0.391493 |
from time import localtime, strftime
import numpy as np
import datetime
import os
import re
class Indexer:
def __init__(self):
pass
@staticmethod
def generate_time_tag():
"""
file tags : YYYYMMDDHHMMSS
exemple 11 May 1918 14h 49m 52s => 19180511144952
:return:
... | server/indexer.py | from time import localtime, strftime
import numpy as np
import datetime
import os
import re
class Indexer:
def __init__(self):
pass
@staticmethod
def generate_time_tag():
"""
file tags : YYYYMMDDHHMMSS
exemple 11 May 1918 14h 49m 52s => 19180511144952
:return:
... | 0.486088 | 0.175679 |
# XXX needed because of
# https://github.com/Anorov/PySocks/issues/119
def warn(*args, **kwargs):
pass
import warnings
warnings.warn = warn
# Import the Canvas class
from canvasapi import Canvas
import argparse
import sys
from pprint import pprint
import tempfile
import pycurl
import os
import string
# Canvas AP... | assigntool.py |
# XXX needed because of
# https://github.com/Anorov/PySocks/issues/119
def warn(*args, **kwargs):
pass
import warnings
warnings.warn = warn
# Import the Canvas class
from canvasapi import Canvas
import argparse
import sys
from pprint import pprint
import tempfile
import pycurl
import os
import string
# Canvas AP... | 0.241668 | 0.138637 |
import logging
import os
import boto3
import pytz
import requests
import json
from datetime import datetime, timezone
from requests import RequestException
from common_lib import detailed_exception, get_adjusted_unix_time
# Log level
logging.basicConfig()
LOGGER = logging.getLogger()
if os.environ["DEBUG_MODE"] == "tr... | functions/get_events_data/get_events_data.py | import logging
import os
import boto3
import pytz
import requests
import json
from datetime import datetime, timezone
from requests import RequestException
from common_lib import detailed_exception, get_adjusted_unix_time
# Log level
logging.basicConfig()
LOGGER = logging.getLogger()
if os.environ["DEBUG_MODE"] == "tr... | 0.428831 | 0.159938 |
import json
import re
import joblib
import pandas as pd
import plotly
from flask import Flask
from flask import render_template, request
from nltk.corpus import stopwords
from nltk.stem.wordnet import WordNetLemmatizer
from nltk.tokenize import word_tokenize
from plotly.graph_objs import Bar, Scatter
from sqlalchemy i... | app/run.py | import json
import re
import joblib
import pandas as pd
import plotly
from flask import Flask
from flask import render_template, request
from nltk.corpus import stopwords
from nltk.stem.wordnet import WordNetLemmatizer
from nltk.tokenize import word_tokenize
from plotly.graph_objs import Bar, Scatter
from sqlalchemy i... | 0.607197 | 0.195421 |
import urllib
import click
import gitlab
from tabulate import tabulate
from ..log import echo_warning, get_logger, verbosity_option
from ..pipelines import process_log
from ..release import get_gitlab_instance
from . import bdt
logger = get_logger(__name__)
@click.command(
epilog="""
Examples:
1. Process ... | bob/devtools/scripts/pipelines.py |
import urllib
import click
import gitlab
from tabulate import tabulate
from ..log import echo_warning, get_logger, verbosity_option
from ..pipelines import process_log
from ..release import get_gitlab_instance
from . import bdt
logger = get_logger(__name__)
@click.command(
epilog="""
Examples:
1. Process ... | 0.573798 | 0.103115 |
import jsonschema
from tempest.openstack.common import log as logging
LOG = logging.getLogger(__name__)
def _check_for_expected_result(name, schema):
expected_result = None
if "results" in schema:
if name in schema["results"]:
expected_result = schema["results"][name]
return expecte... | tempest/common/generator/base_generator.py |
import jsonschema
from tempest.openstack.common import log as logging
LOG = logging.getLogger(__name__)
def _check_for_expected_result(name, schema):
expected_result = None
if "results" in schema:
if name in schema["results"]:
expected_result = schema["results"][name]
return expecte... | 0.524395 | 0.337558 |
import os
import random
import sys
import time
import numpy as np
import tensorflow as tf
class DataLoader(object):
"""Wrapper class around TF dataset pipeline"""
def __init__(self, address_file, mode, batch_size, height, jitter,
shuffle=True, buffer_size=1000, num_threads=8):
... | modelnet/dataloader.py | import os
import random
import sys
import time
import numpy as np
import tensorflow as tf
class DataLoader(object):
"""Wrapper class around TF dataset pipeline"""
def __init__(self, address_file, mode, batch_size, height, jitter,
shuffle=True, buffer_size=1000, num_threads=8):
... | 0.486332 | 0.433442 |
from __future__ import absolute_import, division, print_function, unicode_literals
import cv2
import numpy as np
import os
from .model import MODELS
from .data import numDetectionWindowsAlongAxis, squashCoords, MIN_FACE_SCALE, OFFSET, SCALES, CALIB_PATTERNS_ARR, OBJECT_DATABASE_PATHS, NEGATIVE_DATABASE_PATHS
from .p... | Vision/Face Detection/trainer/detect.py | from __future__ import absolute_import, division, print_function, unicode_literals
import cv2
import numpy as np
import os
from .model import MODELS
from .data import numDetectionWindowsAlongAxis, squashCoords, MIN_FACE_SCALE, OFFSET, SCALES, CALIB_PATTERNS_ARR, OBJECT_DATABASE_PATHS, NEGATIVE_DATABASE_PATHS
from .p... | 0.529507 | 0.158369 |
import smart_imports
smart_imports.all()
class CollectDataTests(helpers.BankTestsMixin,
utils_testcase.TestCase):
def setUp(self):
super().setUp()
game_logic.create_test_map()
self.accounts = [self.accounts_factory.create_account() for _ in range(3)]
self... | src/the_tale/the_tale/finances/bank/tests/test_data_protection.py | import smart_imports
smart_imports.all()
class CollectDataTests(helpers.BankTestsMixin,
utils_testcase.TestCase):
def setUp(self):
super().setUp()
game_logic.create_test_map()
self.accounts = [self.accounts_factory.create_account() for _ in range(3)]
self... | 0.418222 | 0.239816 |
import mxnet as mx
import numpy as np
import pandas as pd
from gluonts.model.deepstate.issm import (
CompositeISSM,
LevelISSM,
LevelTrendISSM,
SeasonalityISSM,
ZeroFeature,
_make_block_diagonal,
)
from gluonts.time_feature import DayOfWeekIndex, MonthOfYearIndex
def test_zero_feature():
... | test/model/deepstate/test_issm.py |
import mxnet as mx
import numpy as np
import pandas as pd
from gluonts.model.deepstate.issm import (
CompositeISSM,
LevelISSM,
LevelTrendISSM,
SeasonalityISSM,
ZeroFeature,
_make_block_diagonal,
)
from gluonts.time_feature import DayOfWeekIndex, MonthOfYearIndex
def test_zero_feature():
... | 0.707506 | 0.789112 |
import asyncio
from datetime import datetime, timezone
from json import loads
import binascii
from domopyc.daq import rfxcom_emiter_receiver
from domopyc.daq.publishers.redis_publisher import RedisPublisher
from domopyc.daq.rfxcom_emiter_receiver import RfxTrx433e, RfxTrx433eMessageHandler, RFXCOM_KEY_CMD
from rfxcom.p... | domopyc/daq/tests/test_rfxcom_reader.py | import asyncio
from datetime import datetime, timezone
from json import loads
import binascii
from domopyc.daq import rfxcom_emiter_receiver
from domopyc.daq.publishers.redis_publisher import RedisPublisher
from domopyc.daq.rfxcom_emiter_receiver import RfxTrx433e, RfxTrx433eMessageHandler, RFXCOM_KEY_CMD
from rfxcom.p... | 0.569972 | 0.273835 |
import cStringIO
import sys
import unittest
import explain_binary_size_delta
class ExplainBinarySizeDeltaTest(unittest.TestCase):
def testCompare(self):
# List entries have form: symbol_name, symbol_type, symbol_size, file_path
symbol_list1 = (
# File with one symbol, left as-is.
( 'unchanged'... | tools/binary_size/explain_binary_size_delta_unittest.py | import cStringIO
import sys
import unittest
import explain_binary_size_delta
class ExplainBinarySizeDeltaTest(unittest.TestCase):
def testCompare(self):
# List entries have form: symbol_name, symbol_type, symbol_size, file_path
symbol_list1 = (
# File with one symbol, left as-is.
( 'unchanged'... | 0.431584 | 0.397471 |