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 mysql.connector
def insertOwnerDataIntoDB(myDB, myCursor, shopName, ownerName, shopType, openingTime, closingTime, timeReqPerUser,
address, city, pinCode, phone, email, password):
print('end')
myDB.autocommit = False
cursor = myDB.cursor(dictionary=True)
try:
... | hackathon_covid_19_Token_System_Server/InsertIntoTable.py | import mysql.connector
def insertOwnerDataIntoDB(myDB, myCursor, shopName, ownerName, shopType, openingTime, closingTime, timeReqPerUser,
address, city, pinCode, phone, email, password):
print('end')
myDB.autocommit = False
cursor = myDB.cursor(dictionary=True)
try:
... | 0.293 | 0.047581 |
from flask import Flask, redirect
from flask_cors import CORS
import logging
from marshmallow.exceptions import ValidationError
from . import Environment
from . extensions import db, filtr
from . config import Config
from . api import blueprint as api_v1
from . util import error
logger = logging.getLogger(__name__)
... | api/honeyhole/app.py | from flask import Flask, redirect
from flask_cors import CORS
import logging
from marshmallow.exceptions import ValidationError
from . import Environment
from . extensions import db, filtr
from . config import Config
from . api import blueprint as api_v1
from . util import error
logger = logging.getLogger(__name__)
... | 0.506591 | 0.063251 |
import logging
import sys
from abc import ABC, abstractmethod
from filelock import SoftFileLock
from disco.storage.db import create_engine
from disco.storage.ingesters import OutputIngester, dump_storage_index
from disco.storage.outputs import get_simulation_output
from disco.storage.parsers import OutputParser
logg... | disco/storage/core.py | import logging
import sys
from abc import ABC, abstractmethod
from filelock import SoftFileLock
from disco.storage.db import create_engine
from disco.storage.ingesters import OutputIngester, dump_storage_index
from disco.storage.outputs import get_simulation_output
from disco.storage.parsers import OutputParser
logg... | 0.556761 | 0.314314 |
import sys
from wrap_smhi_api import *
from collections import defaultdict
start_year = 1961
end_year = 2018
margin = 100 # Allowed missed data points
min_no_of_data_points = (end_year - start_year + 1)*365.25 - 200
stations = get_stations()
all_lines = [] # Text lines to output
num_saved_stations = 0
for i, name in st... | for_developers/smhidata/fetchdata.py | import sys
from wrap_smhi_api import *
from collections import defaultdict
start_year = 1961
end_year = 2018
margin = 100 # Allowed missed data points
min_no_of_data_points = (end_year - start_year + 1)*365.25 - 200
stations = get_stations()
all_lines = [] # Text lines to output
num_saved_stations = 0
for i, name in st... | 0.202996 | 0.29419 |
from functools import wraps
from datetime import datetime, date
def _is_period_now(begin, end, **kwargs):
"""
Utility method. Determines if the current moment falls within the given
time period. Works with periods that fall over two days e.g. 10pm - 6am.
:param begin: time period begins in isoformat... | app/main/cache_timeout.py |
from functools import wraps
from datetime import datetime, date
def _is_period_now(begin, end, **kwargs):
"""
Utility method. Determines if the current moment falls within the given
time period. Works with periods that fall over two days e.g. 10pm - 6am.
:param begin: time period begins in isoformat... | 0.830766 | 0.529811 |
import sys
class HDL_Signal:
"""Holds all the info for an HDL signal."""
def __init__(self, name, msb, lsb, array_ind):
self.local_name = name.split('.')[-1]
self.hierarchy = name[0:-len(self.local_name + '.')]
self.lsb = lsb
self.msb = msb
self.array_ind = array_ind
self.isff = False
... | bomberman/hdl_signal.py |
import sys
class HDL_Signal:
"""Holds all the info for an HDL signal."""
def __init__(self, name, msb, lsb, array_ind):
self.local_name = name.split('.')[-1]
self.hierarchy = name[0:-len(self.local_name + '.')]
self.lsb = lsb
self.msb = msb
self.array_ind = array_ind
self.isff = False
... | 0.484624 | 0.35407 |
import numpy as np
import sys
import math
class kmean:
def __init__(self, data) -> None:
self.data = np.array(data)
self.p1set = []
self.p2set = []
def normalize(self, data):
norm = np.linalg.norm(data)
if norm == 0:
return data
return data/norm
... | ex2function.py | import numpy as np
import sys
import math
class kmean:
def __init__(self, data) -> None:
self.data = np.array(data)
self.p1set = []
self.p2set = []
def normalize(self, data):
norm = np.linalg.norm(data)
if norm == 0:
return data
return data/norm
... | 0.096211 | 0.415432 |
from wake.utils import *
import jshlib
class Store(object):
"""
(#SPC-arch.store): The default pkg and module storage boject.
Stores objects on the local filesystem.
"""
def __init__(self, base, store_dir):
self.store_dir = store_dir
self.defined = pjoin(self.store_dir, "pkgsDefi... | oldwake/store.py |
from wake.utils import *
import jshlib
class Store(object):
"""
(#SPC-arch.store): The default pkg and module storage boject.
Stores objects on the local filesystem.
"""
def __init__(self, base, store_dir):
self.store_dir = store_dir
self.defined = pjoin(self.store_dir, "pkgsDefi... | 0.430746 | 0.106505 |
from collections import defaultdict
from functools import lru_cache
from typing import Dict, List
import logging
from hardware.config import Config
from hardware.device import WrappedNode
from hardware.fdt import FdtParser
from hardware.memory import Region
def get_macro_str(macro: str) -> str:
''' Helper func... | kernel/tools/hardware/utils/rule.py |
from collections import defaultdict
from functools import lru_cache
from typing import Dict, List
import logging
from hardware.config import Config
from hardware.device import WrappedNode
from hardware.fdt import FdtParser
from hardware.memory import Region
def get_macro_str(macro: str) -> str:
''' Helper func... | 0.782829 | 0.205994 |
import randmac
import math
import random
FIELDSIZE = 600
uelist = []
class ESP:
def __init__(self,name,outputmode,espnum):
self.name = name
self.pos = (random.randint(16, FIELDSIZE - 16),random.randint(16, FIELDSIZE - 16))
self.outputmode = outputmode
print("Created ESP #{} name:... | models.py | import randmac
import math
import random
FIELDSIZE = 600
uelist = []
class ESP:
def __init__(self,name,outputmode,espnum):
self.name = name
self.pos = (random.randint(16, FIELDSIZE - 16),random.randint(16, FIELDSIZE - 16))
self.outputmode = outputmode
print("Created ESP #{} name:... | 0.394201 | 0.304778 |
import pytest
import time
from datetime import datetime, timezone
from coinflow.protocol.structs import *
def test_varint():
uint8_t = Varint(0x10)
uint16_t = Varint(0x1000)
uint32_t = Varint(0x10000000)
uint64_t = Varint(0x1000000000000000)
assert Varint.decode(uint8_t.encode()) == (0x10, 1)
... | tests/test_structs.py | import pytest
import time
from datetime import datetime, timezone
from coinflow.protocol.structs import *
def test_varint():
uint8_t = Varint(0x10)
uint16_t = Varint(0x1000)
uint32_t = Varint(0x10000000)
uint64_t = Varint(0x1000000000000000)
assert Varint.decode(uint8_t.encode()) == (0x10, 1)
... | 0.336113 | 0.446736 |
import pytest
@pytest.fixture
def toml_adfh() -> str:
"""Fixture for ADFH in toml."""
return """
[adfh]
version = "1.0"
[[adfh.extra]]
type = "metadata"
name = "name"
value = "todo"
tags = ["oas"]
[[adfh.extra]]
type = "metadata"
name = "title"
value = "ToDo API"
tags = ["oas", "user"]
[[adfh.fields]] # It... | tests/conftest.py | import pytest
@pytest.fixture
def toml_adfh() -> str:
"""Fixture for ADFH in toml."""
return """
[adfh]
version = "1.0"
[[adfh.extra]]
type = "metadata"
name = "name"
value = "todo"
tags = ["oas"]
[[adfh.extra]]
type = "metadata"
name = "title"
value = "ToDo API"
tags = ["oas", "user"]
[[adfh.fields]] # It... | 0.372734 | 0.211274 |
import sys
if '..' not in sys.path:
sys.path.append('..')
import Mesh.ysMeshUtil as ysu
import Math.mmMath as mm
import Implicit.csIMSModel as cmm
def getSpringLengthsFromMesh(mesh, springConfigs):
springLengths = [None]*len(springConfigs)
for i in range(len(springConfigs)):
springLengt... | PyCommon/modules/Simulator/ysIMSUtil.py | import sys
if '..' not in sys.path:
sys.path.append('..')
import Mesh.ysMeshUtil as ysu
import Math.mmMath as mm
import Implicit.csIMSModel as cmm
def getSpringLengthsFromMesh(mesh, springConfigs):
springLengths = [None]*len(springConfigs)
for i in range(len(springConfigs)):
springLengt... | 0.076127 | 0.278533 |
"""Tests of streamable Keyword Spotting models implemented in Keras."""
import os
import sys
import pathlib
from absl import app
from absl import flags
from absl import logging
import numpy as np
from pyiree.tf.support import tf_test_utils
from pyiree.tf.support import tf_utils
import tensorflow.compat.v2 as tf
from... | integrations/tensorflow/e2e/keras/keyword_spotting_streaming_test.py | """Tests of streamable Keyword Spotting models implemented in Keras."""
import os
import sys
import pathlib
from absl import app
from absl import flags
from absl import logging
import numpy as np
from pyiree.tf.support import tf_test_utils
from pyiree.tf.support import tf_utils
import tensorflow.compat.v2 as tf
from... | 0.64512 | 0.295344 |
import maproulette
import unittest
from tests.sample_data import test_geojson, test_overpassQL_query
from unittest.mock import patch
class TestProjectAPI(unittest.TestCase):
config = maproulette.Configuration(api_key="API_KEY")
api = maproulette.Project(config)
@patch('maproulette.api.maproulette_server... | tests/test_project_api.py | import maproulette
import unittest
from tests.sample_data import test_geojson, test_overpassQL_query
from unittest.mock import patch
class TestProjectAPI(unittest.TestCase):
config = maproulette.Configuration(api_key="API_KEY")
api = maproulette.Project(config)
@patch('maproulette.api.maproulette_server... | 0.550003 | 0.244095 |
from collections import defaultdict
from typing import Union
import pandas as pd
import numpy as np
from remake.schematic.core.transformation import TransformationCore
class SchematicTransformation(TransformationCore):
def __init__(self, **given_params):
self._param_values = {}
for parameter in... | src/remake/schematic/transform.py | from collections import defaultdict
from typing import Union
import pandas as pd
import numpy as np
from remake.schematic.core.transformation import TransformationCore
class SchematicTransformation(TransformationCore):
def __init__(self, **given_params):
self._param_values = {}
for parameter in... | 0.880354 | 0.356503 |
import unittest
from aiohttp.web import HTTPNotFound, HTTPMethodNotAllowed
from freesia.route import Route, Router
async def temp():
pass
class RouterTestCase(unittest.TestCase):
def test_add_static_route(self):
r = Route("/", ["GET"], temp, {
"checking_param": False
})
... | tests/test_router.py | import unittest
from aiohttp.web import HTTPNotFound, HTTPMethodNotAllowed
from freesia.route import Route, Router
async def temp():
pass
class RouterTestCase(unittest.TestCase):
def test_add_static_route(self):
r = Route("/", ["GET"], temp, {
"checking_param": False
})
... | 0.515132 | 0.406744 |
__author__ = '<NAME> <<EMAIL>>'
from unittest import TestSuite
from .testcase_create_job_invalid_data import CreateJobInvalidDataTestCase
from .testcase_create_job_incomplete_data import CreateJobIncompleteDataTestCase
from .testcase_create_job import CreateJobTestCase
from .testcase_get_job import GetJobTestCase
fro... | bitcodin/test/job/__init__.py | __author__ = '<NAME> <<EMAIL>>'
from unittest import TestSuite
from .testcase_create_job_invalid_data import CreateJobInvalidDataTestCase
from .testcase_create_job_incomplete_data import CreateJobIncompleteDataTestCase
from .testcase_create_job import CreateJobTestCase
from .testcase_get_job import GetJobTestCase
fro... | 0.23292 | 0.385172 |
import cv2
import sys
import json
import pytesseract
def crop(imageFileName, cropXStart,cropXEnd,cropYStart,cropYEnd):
"""crops the given image with the given bounding box coordinates."""
#print('cropping')
#print(type(cropXEnd))
image = cv2.imread(imageFileName)
croppedImage = image[cropXStart:cro... | tools/image2text.py | import cv2
import sys
import json
import pytesseract
def crop(imageFileName, cropXStart,cropXEnd,cropYStart,cropYEnd):
"""crops the given image with the given bounding box coordinates."""
#print('cropping')
#print(type(cropXEnd))
image = cv2.imread(imageFileName)
croppedImage = image[cropXStart:cro... | 0.281307 | 0.115911 |
import numpy as np
import unittest
from day_two import unittest_
if False:
class _GradientBoostingRegressorTest(unittest_.TestCase):
def test_bootstrap_method(self):
import day_two
gb_regr = day_two.sklearn_.ensemble._gradient_boosting.GradientBoostingRegressor_()
n_sa... | test/_gradient_boosting_test______.py | import numpy as np
import unittest
from day_two import unittest_
if False:
class _GradientBoostingRegressorTest(unittest_.TestCase):
def test_bootstrap_method(self):
import day_two
gb_regr = day_two.sklearn_.ensemble._gradient_boosting.GradientBoostingRegressor_()
n_sa... | 0.67662 | 0.666429 |
from __future__ import unicode_literals
from django.db import models, migrations
import django.db.models.deletion
class Migration(migrations.Migration):
dependencies = [
]
operations = [
migrations.CreateModel(
name='Assessment',
fields=[
('id', models.Au... | cogpheno/apps/assessments/migrations/old/0001_initial.py | from __future__ import unicode_literals
from django.db import models, migrations
import django.db.models.deletion
class Migration(migrations.Migration):
dependencies = [
]
operations = [
migrations.CreateModel(
name='Assessment',
fields=[
('id', models.Au... | 0.656548 | 0.164114 |
# Internal module. Internal API may move, disappear or otherwise change at any
# time and without notice.
from __future__ import print_function, unicode_literals
class LatexContextDb(object):
r"""
Store a database of specifications of known macros, environments, and other
latex specials. This might... | pylatexenc/macrospec/_latexcontextdb.py |
# Internal module. Internal API may move, disappear or otherwise change at any
# time and without notice.
from __future__ import print_function, unicode_literals
class LatexContextDb(object):
r"""
Store a database of specifications of known macros, environments, and other
latex specials. This might... | 0.88063 | 0.538923 |
from common import *
from sys import stderr
def main(options):
read_conf()
if "-h" in options or "--help" in options:
show_help()
if len(options) < 1 or not(options[0] in ["-s", "--service"]):
show_help()
# STEP 0. FETCH ALL INSTALLED SERVICES
INSTALLED_SERVICES = get_installed... | server/admin_tools/service_tools/service_log.py |
from common import *
from sys import stderr
def main(options):
read_conf()
if "-h" in options or "--help" in options:
show_help()
if len(options) < 1 or not(options[0] in ["-s", "--service"]):
show_help()
# STEP 0. FETCH ALL INSTALLED SERVICES
INSTALLED_SERVICES = get_installed... | 0.202917 | 0.106737 |
import torch
import torch.nn as nn
import torch.optim as optim
from data import make_font_trainloader
from model import Net
use_cuda = torch.cuda.is_available()
device = torch.device('cuda:0' if use_cuda else 'cpu')
host = torch.device('cpu')
contexts = None
def create_inputs(model, objects, labels, criterion, iter... | mnist/train.py | import torch
import torch.nn as nn
import torch.optim as optim
from data import make_font_trainloader
from model import Net
use_cuda = torch.cuda.is_available()
device = torch.device('cuda:0' if use_cuda else 'cpu')
host = torch.device('cpu')
contexts = None
def create_inputs(model, objects, labels, criterion, iter... | 0.850748 | 0.441974 |
from multiprocessing.pool import ThreadPool
import pandas as pd
import requests
import xmltodict
from helper import *
class Data:
def __init__(self):
self.df = pd.DataFrame(data={})
# https://volby.cz/pls/ps2017nss/vysledky_okres?nuts=CZ0806
self.downloaded = 0
self.to_download... | data.py | from multiprocessing.pool import ThreadPool
import pandas as pd
import requests
import xmltodict
from helper import *
class Data:
def __init__(self):
self.df = pd.DataFrame(data={})
# https://volby.cz/pls/ps2017nss/vysledky_okres?nuts=CZ0806
self.downloaded = 0
self.to_download... | 0.438545 | 0.279343 |
from types import MethodType
import os
import numpy as np
import cv2
from pointsmap import invertTransform, combineTransforms
from h5dataloader.common.structure import *
from h5dataloader.common.create_funcs import NORMALIZE_INF
from h5dataloader.pytorch import HDF5Dataset
from h5dataloader.pytorch.structure import CON... | pmod/dataloader/pmod_dataset.py | from types import MethodType
import os
import numpy as np
import cv2
from pointsmap import invertTransform, combineTransforms
from h5dataloader.common.structure import *
from h5dataloader.common.create_funcs import NORMALIZE_INF
from h5dataloader.pytorch import HDF5Dataset
from h5dataloader.pytorch.structure import CON... | 0.708112 | 0.322459 |
import gc
import six
import numpy as np
from abc import ABCMeta, abstractmethod
from .base import BaseEstimator
class BaseSVM(six.with_metaclass(ABCMeta, BaseEstimator)):
def __init__(self, kernel='linear', degree=3, C=1.0, epsilon=1e-3, max_iter=100):
self.max_iter = max_iter
self._kernel = kern... | hklearn/svm.py | import gc
import six
import numpy as np
from abc import ABCMeta, abstractmethod
from .base import BaseEstimator
class BaseSVM(six.with_metaclass(ABCMeta, BaseEstimator)):
def __init__(self, kernel='linear', degree=3, C=1.0, epsilon=1e-3, max_iter=100):
self.max_iter = max_iter
self._kernel = kern... | 0.237753 | 0.375477 |
import sys
from traceback import format_exception
from tuttle.error import TuttleError
from tuttle.report.dot_repport import create_dot_report
from tuttle.report.html_repport import create_html_report
from pickle import dump, load
from tuttle.workflow_runner import WorkflowRunner, TuttleEnv
from tuttle_directories imp... | tuttle/workflow.py | import sys
from traceback import format_exception
from tuttle.error import TuttleError
from tuttle.report.dot_repport import create_dot_report
from tuttle.report.html_repport import create_html_report
from pickle import dump, load
from tuttle.workflow_runner import WorkflowRunner, TuttleEnv
from tuttle_directories imp... | 0.551091 | 0.117978 |
import unittest
import os, shutil
from cybercaptain.visualization.map import visualization_map
from cybercaptain.utils.exceptions import ValidationError
TESTDATA_FOLDER = os.path.join(os.path.dirname(__file__), '../assets')
TESTDATA_GEN_OUTPUT_FOLDER = os.path.join(TESTDATA_FOLDER, 'output')
# Append Needed Args - ... | src/unittest/python/modules/visualization/map_validate_tests.py | import unittest
import os, shutil
from cybercaptain.visualization.map import visualization_map
from cybercaptain.utils.exceptions import ValidationError
TESTDATA_FOLDER = os.path.join(os.path.dirname(__file__), '../assets')
TESTDATA_GEN_OUTPUT_FOLDER = os.path.join(TESTDATA_FOLDER, 'output')
# Append Needed Args - ... | 0.551332 | 0.343837 |
from azext_iot.common.sas_token_auth import SasTokenAuthentication
from azext_iot.common.shared import SdkType
def iot_hub_service_factory(cli_ctx, *_):
"""
Factory for importing deps and getting service client resources.
Args:
cli_ctx (knack.cli.CLI): CLI context.
*_ : all other args ign... | azext_iot/_factory.py | from azext_iot.common.sas_token_auth import SasTokenAuthentication
from azext_iot.common.shared import SdkType
def iot_hub_service_factory(cli_ctx, *_):
"""
Factory for importing deps and getting service client resources.
Args:
cli_ctx (knack.cli.CLI): CLI context.
*_ : all other args ign... | 0.765769 | 0.092729 |
def parse_data(data, outpath):
import numpy as np
import matplotlib.pyplot as plt
import os
import datetime
from hurry.filesize import size
df = data['df']
world_size = data['world_size']
plt.figure(figsize=(9,8/5*world_size))
for proc in range(0, world_size):
X = df[df['r... | tex/templates/single_run/single_run.py | def parse_data(data, outpath):
import numpy as np
import matplotlib.pyplot as plt
import os
import datetime
from hurry.filesize import size
df = data['df']
world_size = data['world_size']
plt.figure(figsize=(9,8/5*world_size))
for proc in range(0, world_size):
X = df[df['r... | 0.130258 | 0.637609 |
import warnings
warnings.filterwarnings('ignore')
import time
import pandas as pd
import numpy as np
import matplotlib.pyplot as plt
from sklearn import model_selection
from sklearn.impute import SimpleImputer
from sklearn.linear_model import LogisticRegression
from sklearn.linear_model import SGDClassifier
from skl... | gossipcat/lab/Comparison.py | import warnings
warnings.filterwarnings('ignore')
import time
import pandas as pd
import numpy as np
import matplotlib.pyplot as plt
from sklearn import model_selection
from sklearn.impute import SimpleImputer
from sklearn.linear_model import LogisticRegression
from sklearn.linear_model import SGDClassifier
from skl... | 0.66454 | 0.333123 |
import os
import re
from fbs.proc.common_util.util import FileFormatError
from fbs.proc.file_handlers import generic_file
from fbs.proc.file_handlers import netcdf_file
from fbs.proc.file_handlers import nasaames_file
from fbs.proc.file_handlers import pp_file
from fbs.proc.file_handlers import grib_file
from fbs.proc... | python/src/fbs/proc/file_handlers/handler_picker.py | import os
import re
from fbs.proc.common_util.util import FileFormatError
from fbs.proc.file_handlers import generic_file
from fbs.proc.file_handlers import netcdf_file
from fbs.proc.file_handlers import nasaames_file
from fbs.proc.file_handlers import pp_file
from fbs.proc.file_handlers import grib_file
from fbs.proc... | 0.384334 | 0.091748 |
from twitter_sentiment.params import sw_persian
import pandas as pd
import re
def correction(series:pd.Series):
assert isinstance(series, pd.Series)
for line in series:
line = line.replace('\n', '').replace('.', '')
line = line.split(' ')
yield list(map(int, line))
def remove_e... | twitter_sentiment/preprocessing/Preprocessing.py | from twitter_sentiment.params import sw_persian
import pandas as pd
import re
def correction(series:pd.Series):
assert isinstance(series, pd.Series)
for line in series:
line = line.replace('\n', '').replace('.', '')
line = line.split(' ')
yield list(map(int, line))
def remove_e... | 0.514644 | 0.280983 |
from pm4py.util import exec_utils, xes_constants, constants
from typing import Optional, Dict, Any, Union, Tuple, List, Set
from pm4py.objects.log.obj import EventLog
import pandas as pd
from enum import Enum
class Outputs(Enum):
DFG = "dfg"
SEQUENCE = "sequence"
PARALLEL = "parallel"
START_ACTIVITIE... | ws2122-lspm/Lib/site-packages/pm4py/algo/conformance/footprints/variants/log_model.py | from pm4py.util import exec_utils, xes_constants, constants
from typing import Optional, Dict, Any, Union, Tuple, List, Set
from pm4py.objects.log.obj import EventLog
import pandas as pd
from enum import Enum
class Outputs(Enum):
DFG = "dfg"
SEQUENCE = "sequence"
PARALLEL = "parallel"
START_ACTIVITIE... | 0.910446 | 0.331039 |
import h5py
import numpy as np
import cv2
class dbReader:
def __init__(self):
self.FILE_PATH = 'dataset/nyu_depth_v2_labeled.mat'
self.SAVE_PATH = 'dataset/'
def loadData(self, c, d):
"""
'rgb' or 'grayscale'(default)
'origin' or 'normalized'(default)
"""
... | dbReader_simplified.py | import h5py
import numpy as np
import cv2
class dbReader:
def __init__(self):
self.FILE_PATH = 'dataset/nyu_depth_v2_labeled.mat'
self.SAVE_PATH = 'dataset/'
def loadData(self, c, d):
"""
'rgb' or 'grayscale'(default)
'origin' or 'normalized'(default)
"""
... | 0.330687 | 0.359701 |
from . import map_kor_to_braille
import re
UNRECOGNIZED = '?'
open_quotes = True
BASE_CODE, CHOSUNG, JUNGSUNG = 44032, 588, 28
# 초성 리스트. 00 ~ 18
CHOSUNG_LIST = ['ㄱ', 'ㄲ', 'ㄴ', 'ㄷ', 'ㄸ', 'ㄹ', 'ㅁ',
'ㅂ', 'ㅃ', 'ㅅ', 'ㅆ', 'ㅇ', 'ㅈ', 'ㅉ',
'ㅊ', 'ㅋ', 'ㅌ', 'ㅍ', 'ㅎ']
# 중성 리스트. 00 ~ 20
JUNGSUNG... | braille_experience/braille_translator_kor/kor_to_braille2.py | from . import map_kor_to_braille
import re
UNRECOGNIZED = '?'
open_quotes = True
BASE_CODE, CHOSUNG, JUNGSUNG = 44032, 588, 28
# 초성 리스트. 00 ~ 18
CHOSUNG_LIST = ['ㄱ', 'ㄲ', 'ㄴ', 'ㄷ', 'ㄸ', 'ㄹ', 'ㅁ',
'ㅂ', 'ㅃ', 'ㅅ', 'ㅆ', 'ㅇ', 'ㅈ', 'ㅉ',
'ㅊ', 'ㅋ', 'ㅌ', 'ㅍ', 'ㅎ']
# 중성 리스트. 00 ~ 20
JUNGSUNG... | 0.156169 | 0.205137 |
import numpy as np
import matplotlib.pyplot as plt
from sklearn.datasets import make_blobs, make_moons, make_circles
X, y = make_moons(n_samples=1000, noise=0.1, random_state=2)
data = []
data2 = []
for i in range(len(y)):
if y[i] == 0: # the target distribution
data.append(X[i]+1)
else: # the source... | Synthetic Experiments/moon.py | import numpy as np
import matplotlib.pyplot as plt
from sklearn.datasets import make_blobs, make_moons, make_circles
X, y = make_moons(n_samples=1000, noise=0.1, random_state=2)
data = []
data2 = []
for i in range(len(y)):
if y[i] == 0: # the target distribution
data.append(X[i]+1)
else: # the source... | 0.797083 | 0.626238 |
# Standard Library
from typing import List
from datetime import datetime
# Third Party
from pydantic import StrictInt, StrictStr, StrictBool, constr, root_validator
# Project
from hyperglass.log import log
# Local
from ..main import HyperglassModel
from .serialized import ParsedRoutes
VyOSPeerType = constr(regex=r... | hyperglass/models/parsing/vyos.py |
# Standard Library
from typing import List
from datetime import datetime
# Third Party
from pydantic import StrictInt, StrictStr, StrictBool, constr, root_validator
# Project
from hyperglass.log import log
# Local
from ..main import HyperglassModel
from .serialized import ParsedRoutes
VyOSPeerType = constr(regex=r... | 0.719876 | 0.300425 |
# Config file description:
# test ECAL sequence: tcc hw input -> tp digi -> tcc hw input
# check consistency of original and created tcc hardware input files
import FWCore.ParameterSet.Config as cms
process = cms.Process("TCCFlat2Flat")
process.load("FWCore.MessageLogger.MessageLogger_cfi")
#-#-# Flat -> Digi [c... | SimCalorimetry/EcalElectronicsEmulation/test/Flat2Flat_cfg.py |
# Config file description:
# test ECAL sequence: tcc hw input -> tp digi -> tcc hw input
# check consistency of original and created tcc hardware input files
import FWCore.ParameterSet.Config as cms
process = cms.Process("TCCFlat2Flat")
process.load("FWCore.MessageLogger.MessageLogger_cfi")
#-#-# Flat -> Digi [c... | 0.252292 | 0.223589 |
import _nx
import warnings
from .utils import bit, cached_property
AUTO_PLAYER_1_ID = 10
def refresh_inputs():
"""Refreshes inputs.
Should normally be called at least once
within every iteration of your main loop.
"""
_nx.hid_scan_input()
def _determine_controller_type(player):
# TODO det... | lib/python3.5/nx/controllers.py | import _nx
import warnings
from .utils import bit, cached_property
AUTO_PLAYER_1_ID = 10
def refresh_inputs():
"""Refreshes inputs.
Should normally be called at least once
within every iteration of your main loop.
"""
_nx.hid_scan_input()
def _determine_controller_type(player):
# TODO det... | 0.592313 | 0.44571 |
import re, os
from bs4 import BeautifulSoup
import pandas as pd
import numpy as np
def find_entities_in_tables(dirctory_path: str, file_list, entities: dict):
data_frame = []
columns= ['DOI', 'Tab_nr', 'Tab_text'] + [key for key in entities.keys()]
count = 0
for file_name in file_list:
with ope... | Python code/records_tables.py | import re, os
from bs4 import BeautifulSoup
import pandas as pd
import numpy as np
def find_entities_in_tables(dirctory_path: str, file_list, entities: dict):
data_frame = []
columns= ['DOI', 'Tab_nr', 'Tab_text'] + [key for key in entities.keys()]
count = 0
for file_name in file_list:
with ope... | 0.118181 | 0.291006 |
from yalexs.activity import (
ACTION_BRIDGE_OFFLINE,
ACTION_BRIDGE_ONLINE,
ACTION_DOOR_CLOSED,
ACTION_DOOR_OPEN,
ACTION_DOORBELL_BUTTON_PUSHED,
ACTION_DOORBELL_IMAGE_CAPTURE,
ACTION_DOORBELL_MOTION_DETECTED,
ACTION_LOCK_JAMMED,
ACTION_LOCK_LOCK,
ACTION_LOCK_LOCKING,
ACTION_LO... | yalexs/pubnub_activity.py | from yalexs.activity import (
ACTION_BRIDGE_OFFLINE,
ACTION_BRIDGE_ONLINE,
ACTION_DOOR_CLOSED,
ACTION_DOOR_OPEN,
ACTION_DOORBELL_BUTTON_PUSHED,
ACTION_DOORBELL_IMAGE_CAPTURE,
ACTION_DOORBELL_MOTION_DETECTED,
ACTION_LOCK_JAMMED,
ACTION_LOCK_LOCK,
ACTION_LOCK_LOCKING,
ACTION_LO... | 0.439988 | 0.082365 |
import collections.abc
import copy
import os
import re
from functools import wraps
from werkzeug.datastructures import MultiDict
from flask import current_app, g, flash, abort
from flask_login import current_user
from .paths import ShellDirectory
def read_rules_file(rule_file):
"""Generate (key, value) tuples from... | flfm/shell/rules.py | import collections.abc
import copy
import os
import re
from functools import wraps
from werkzeug.datastructures import MultiDict
from flask import current_app, g, flash, abort
from flask_login import current_user
from .paths import ShellDirectory
def read_rules_file(rule_file):
"""Generate (key, value) tuples from... | 0.673621 | 0.17749 |
from django.conf.urls import url
from . import views
urlpatterns = [
url(r'^$', views.ml_maillist, name='ml_maillist'),
url(r'^ajax_ml_maillist/$', views.ajax_ml_maillist, name='ajax_ml_maillist'),
url(r'^ajax_count/(?P<list_id>\d+)/$', views.ajax_maillist_count, name='ajax_maillist_count'),
url(r'^ad... | edm_web1/app/address/urls.py | from django.conf.urls import url
from . import views
urlpatterns = [
url(r'^$', views.ml_maillist, name='ml_maillist'),
url(r'^ajax_ml_maillist/$', views.ajax_ml_maillist, name='ajax_ml_maillist'),
url(r'^ajax_count/(?P<list_id>\d+)/$', views.ajax_maillist_count, name='ajax_maillist_count'),
url(r'^ad... | 0.185689 | 0.070784 |
import time
ADS1x15_DEFAULT_ADDRESS = 0x48
ADS1x15_POINTER_CONVERSION = 0x00
ADS1x15_POINTER_CONFIG = 0x01
ADS1x15_POINTER_LOW_THRESHOLD = 0x02
ADS1x15_POINTER_HIGH_THRESHOLD = 0x03
ADS1x15_CONFIG_OS_SINGLE = 0x8000
ADS1x15_CONFIG_MUX_OFFSET = 12
ADS1x15_CONFIG_GAIN = {
2 / 3: 0x0000,
1: 0x0200,
2: 0x0400,... | lib/adc/ads1115.py | import time
ADS1x15_DEFAULT_ADDRESS = 0x48
ADS1x15_POINTER_CONVERSION = 0x00
ADS1x15_POINTER_CONFIG = 0x01
ADS1x15_POINTER_LOW_THRESHOLD = 0x02
ADS1x15_POINTER_HIGH_THRESHOLD = 0x03
ADS1x15_CONFIG_OS_SINGLE = 0x8000
ADS1x15_CONFIG_MUX_OFFSET = 12
ADS1x15_CONFIG_GAIN = {
2 / 3: 0x0000,
1: 0x0200,
2: 0x0400,... | 0.424889 | 0.244126 |
import torch
import numpy as np
import torch.nn as nn
from pruner.filter_pruner import FilterPruner
from model.MobileNetV2 import InvertedResidual
class FilterPrunerMBNetV2(FilterPruner):
def parse_dependency(self):
pass
def forward(self, x):
if isinstance(self.model, nn.DataParallel):
... | pruner/fp_mbnetv2.py | import torch
import numpy as np
import torch.nn as nn
from pruner.filter_pruner import FilterPruner
from model.MobileNetV2 import InvertedResidual
class FilterPrunerMBNetV2(FilterPruner):
def parse_dependency(self):
pass
def forward(self, x):
if isinstance(self.model, nn.DataParallel):
... | 0.758332 | 0.397851 |
import modules.angles as angles
import modules.dihedrals as dihedrals
class Bond:
pass
class Angle:
pass
class Dihedral:
pass
def dist(t=(), s=(), l=None):
zdist = abs(t[2] - s[2])
if zdist > 0.5 * l:
zdist = l - zdist
square = (t[0] - s[0])**2 + (t[1] - s[1])**2 + zdist**2
d... | Create_Graphene_Sheet/convert_cnt_gnp_2_iff/modules/locality.py | import modules.angles as angles
import modules.dihedrals as dihedrals
class Bond:
pass
class Angle:
pass
class Dihedral:
pass
def dist(t=(), s=(), l=None):
zdist = abs(t[2] - s[2])
if zdist > 0.5 * l:
zdist = l - zdist
square = (t[0] - s[0])**2 + (t[1] - s[1])**2 + zdist**2
d... | 0.665628 | 0.55254 |
from typing import Optional, Union
from .errors import TemplateModifierNotImplemented
from .page_modifier import PageModifierBase
from .wiki_client import WikiClient
class TemplateModifierBase(PageModifierBase):
def __init__(self, site: WikiClient, template, page_list=None, title_list=None, limit=-1, summary=Non... | mwcleric/template_modifier.py | from typing import Optional, Union
from .errors import TemplateModifierNotImplemented
from .page_modifier import PageModifierBase
from .wiki_client import WikiClient
class TemplateModifierBase(PageModifierBase):
def __init__(self, site: WikiClient, template, page_list=None, title_list=None, limit=-1, summary=Non... | 0.877115 | 0.067454 |
from functools import partial, wraps
import attr
import pytest
import trio
import trustme
from async_generator import async_generator, yield_
from trio_websocket import (
connect_websocket,
connect_websocket_url,
ConnectionClosed,
open_websocket,
open_websocket_url,
serve_websocket,
WebSoc... | tests/test_connection.py | from functools import partial, wraps
import attr
import pytest
import trio
import trustme
from async_generator import async_generator, yield_
from trio_websocket import (
connect_websocket,
connect_websocket_url,
ConnectionClosed,
open_websocket,
open_websocket_url,
serve_websocket,
WebSoc... | 0.652906 | 0.196749 |
from cyclone.web import asynchronous
from xml.sax.saxutils import escape
from plugins.web.request_handler import RequestHandler
__author__ = '<NAME>'
class Route(RequestHandler):
factoids = None
name = "factoids"
def initialize(self):
#: :type: FactoidsPlugin
self.factoids = self.plu... | plugins/factoids/route.py |
from cyclone.web import asynchronous
from xml.sax.saxutils import escape
from plugins.web.request_handler import RequestHandler
__author__ = '<NAME>'
class Route(RequestHandler):
factoids = None
name = "factoids"
def initialize(self):
#: :type: FactoidsPlugin
self.factoids = self.plu... | 0.42322 | 0.076546 |
contents of files."""
import os
import re
from validator.contextgenerator import ContextGenerator
from validator.decorator import define_post_init
from .base import RegexTestBase
class FileRegexTest(RegexTestBase):
"""Matches regular expressions in complete file texts, with filters
for individual tests."""
... | validator/testcases/regex/generic.py | contents of files."""
import os
import re
from validator.contextgenerator import ContextGenerator
from validator.decorator import define_post_init
from .base import RegexTestBase
class FileRegexTest(RegexTestBase):
"""Matches regular expressions in complete file texts, with filters
for individual tests."""
... | 0.658198 | 0.256651 |
import os
# Build paths inside the project like this: os.path.join(BASE_DIR, ...)
BASE_DIR = os.path.dirname(os.path.dirname(os.path.abspath(__file__)))
# Quick-start development settings - unsuitable for production
# See https://docs.djangoproject.com/en/2.0/howto/deployment/checklist/
# SECURITY WARNING: keep the... | template3/settings.py | import os
# Build paths inside the project like this: os.path.join(BASE_DIR, ...)
BASE_DIR = os.path.dirname(os.path.dirname(os.path.abspath(__file__)))
# Quick-start development settings - unsuitable for production
# See https://docs.djangoproject.com/en/2.0/howto/deployment/checklist/
# SECURITY WARNING: keep the... | 0.335351 | 0.07056 |
import numpy as np
from amadeus import Flights
import pandas as pd
import random
import datetime
import time
from ortools.constraint_solver import pywrapcp
from ortools.constraint_solver import routing_enums_pb2
def choose_countries(origin, number_countries, number_continents):
DATA_PATH = 'static/custom.csv'
... | wtour/utils.py | import numpy as np
from amadeus import Flights
import pandas as pd
import random
import datetime
import time
from ortools.constraint_solver import pywrapcp
from ortools.constraint_solver import routing_enums_pb2
def choose_countries(origin, number_countries, number_continents):
DATA_PATH = 'static/custom.csv'
... | 0.4436 | 0.307168 |
from tensorboardX import SummaryWriter
from pathlib import Path
import sys
base_dir = Path(__file__).resolve().parent.parent
sys.path.append(str(base_dir))
from common import *
from log_path import *
from algo.qmix import QMIX
from algo.qmix_s import QMIX_s
from env.chooseenv import make
def step_trainer(args):
pr... | rl_trainer_qmix/trainer.py | from tensorboardX import SummaryWriter
from pathlib import Path
import sys
base_dir = Path(__file__).resolve().parent.parent
sys.path.append(str(base_dir))
from common import *
from log_path import *
from algo.qmix import QMIX
from algo.qmix_s import QMIX_s
from env.chooseenv import make
def step_trainer(args):
pr... | 0.457137 | 0.393502 |
import copy
from django.test import tag
from rest_framework.test import APIClient, APITestCase
from users.models import User
from saef.models import JobSession
from saefportal.settings import MSG_ERROR_INVALID_INPUT, MSG_ERROR_REQUIRED_INPUT, MSG_ERROR_MISSING_OBJECT_INPUT, \
MSG_ERROR_EXISTING
from utils.test_uti... | saefportal/restapi/tests/test_job_session.py | import copy
from django.test import tag
from rest_framework.test import APIClient, APITestCase
from users.models import User
from saef.models import JobSession
from saefportal.settings import MSG_ERROR_INVALID_INPUT, MSG_ERROR_REQUIRED_INPUT, MSG_ERROR_MISSING_OBJECT_INPUT, \
MSG_ERROR_EXISTING
from utils.test_uti... | 0.376165 | 0.152253 |
from subprocess import check_output
nano_results = check_output(
"./generate_table.awk < nano.txt", shell=True, text=True)
micro_results = check_output(
"./generate_table.awk < micro.txt", shell=True, text=True)
samd_results = check_output(
"./generate_table.awk < samd.txt", shell=True, text=True)
stm32_r... | examples/MemoryBenchmark/generate_readme.py | $ make clean_benchmarks
$ make benchmarks
$ make README.md
{nano_results}
{micro_results}
{samd_results}
{stm32_results}
{esp8266_results}
{esp32_results}
{teensy32_results} | 0.504883 | 0.81772 |
import time
from collections import OrderedDict
from typing import List, Dict
from trafficgenerator.tgn_utils import is_false, TgnError
from trafficgenerator.tgn_tcl import tcl_str, py_list_to_tcl_list
from ixnetwork.ixn_app import IxnRoot
from ixnetwork.ixn_object import IxnObject
from ixnetwork.api.ixn_rest import ... | ixnetwork/ixn_statistics_view.py | import time
from collections import OrderedDict
from typing import List, Dict
from trafficgenerator.tgn_utils import is_false, TgnError
from trafficgenerator.tgn_tcl import tcl_str, py_list_to_tcl_list
from ixnetwork.ixn_app import IxnRoot
from ixnetwork.ixn_object import IxnObject
from ixnetwork.api.ixn_rest import ... | 0.807005 | 0.220563 |
from django.test import TestCase
from .product_test_helper import create_product
from .login_test_helper import registrate_new_user, login_user
import json
default_name = "test1234"
default_fk_vendor = 1
default_price = 10.0
default_photo = 'www.google.com'
default_description = 'description'
default_product_id = 1
#... | api/api_gateway/api/tests/test_product.py | from django.test import TestCase
from .product_test_helper import create_product
from .login_test_helper import registrate_new_user, login_user
import json
default_name = "test1234"
default_fk_vendor = 1
default_price = 10.0
default_photo = 'www.google.com'
default_description = 'description'
default_product_id = 1
#... | 0.295738 | 0.085289 |
import torch
from nnrl.nn.critic import ClippedVValue
from nnrl.nn.utils import update_polyak
from nnrl.optim import build_optimizer
from nnrl.types import TensorDict
from ray.rllib.utils import override
from torch import nn
from raylab.options import configure, option
from raylab.policy import TorchPolicy
from raylab... | raylab/agents/naf/policy.py | import torch
from nnrl.nn.critic import ClippedVValue
from nnrl.nn.utils import update_polyak
from nnrl.optim import build_optimizer
from nnrl.types import TensorDict
from ray.rllib.utils import override
from torch import nn
from raylab.options import configure, option
from raylab.policy import TorchPolicy
from raylab... | 0.915682 | 0.209611 |
from db import ticker
from .status import *
import pandas as pd
import copy
import numpy as np
def get_ticker_data():
"""
Get a list of all tickers' data
:return: List of tickers along with price data list
"""
raw_data = list(ticker.get_all_tickers())
# convert price data into float
def c... | insight/ticker.py | from db import ticker
from .status import *
import pandas as pd
import copy
import numpy as np
def get_ticker_data():
"""
Get a list of all tickers' data
:return: List of tickers along with price data list
"""
raw_data = list(ticker.get_all_tickers())
# convert price data into float
def c... | 0.566378 | 0.51946 |
class SwitchCode(object):
'''
Container object for storing code filenames for switch configuration.
'''
def __init__(self, modelName, codeFile):
'''
Purpose : Initialize a SwitchCode object
Parameters :
modelName: The model name of a switch. Used to parse codeFile
... | switchcode.py |
class SwitchCode(object):
'''
Container object for storing code filenames for switch configuration.
'''
def __init__(self, modelName, codeFile):
'''
Purpose : Initialize a SwitchCode object
Parameters :
modelName: The model name of a switch. Used to parse codeFile
... | 0.684264 | 0.245144 |
try:
import sys
sys.path[1] = '/flash/lib'
mkdir('/flash/lib')
except:
pass
#helper functions
import m5stack
from windows import *
borders(clear=False)
header('boot.py')
mainwindow(clear=False)
home()
def beepHappy():
#Happy
m5stack.tone(4200, 80)
m5stack.tone(2800, 100)
m5stack.t... | Labs/Lab-7 Weather/boot.py | try:
import sys
sys.path[1] = '/flash/lib'
mkdir('/flash/lib')
except:
pass
#helper functions
import m5stack
from windows import *
borders(clear=False)
header('boot.py')
mainwindow(clear=False)
home()
def beepHappy():
#Happy
m5stack.tone(4200, 80)
m5stack.tone(2800, 100)
m5stack.t... | 0.11645 | 0.113555 |
import simulation
import math
# This is the file to run in order to give this demo a spin. It should work out of the box.
#
# Some parameters can be changed, such as initial conditions, boundary conditions, and which physical problem you want
# to solve. As of now there is only the wave equation and the heat equ... | main.py | import simulation
import math
# This is the file to run in order to give this demo a spin. It should work out of the box.
#
# Some parameters can be changed, such as initial conditions, boundary conditions, and which physical problem you want
# to solve. As of now there is only the wave equation and the heat equ... | 0.75392 | 0.634487 |
import tensorflow as tf
import numpy as np
import pytest
import os
from tndm import TNDM
from tndm.utils import AdaptiveWeights, upsert_empty_folder, remove_folder
@pytest.fixture(scope='module', autouse=True)
def cleanup(request):
def remove_test_dir():
folder = os.path.join(
'test', 'models... | test/models/tndm_test.py | import tensorflow as tf
import numpy as np
import pytest
import os
from tndm import TNDM
from tndm.utils import AdaptiveWeights, upsert_empty_folder, remove_folder
@pytest.fixture(scope='module', autouse=True)
def cleanup(request):
def remove_test_dir():
folder = os.path.join(
'test', 'models... | 0.481941 | 0.518668 |
import yaml
import collections as col
import PolyLibScan as pls
import pathlib2 as pl
import LammpsSubmit as LS
import epitopsy as epi
import MDlatticeAnalysisTool as mdl
import sklearn as sk
import operator
import random
import os
import time
class Genetic_algorithm(object):
gene_list = ['BA', 'BP', 'Bor', 'CBS',... | genetic_algorithm.py | import yaml
import collections as col
import PolyLibScan as pls
import pathlib2 as pl
import LammpsSubmit as LS
import epitopsy as epi
import MDlatticeAnalysisTool as mdl
import sklearn as sk
import operator
import random
import os
import time
class Genetic_algorithm(object):
gene_list = ['BA', 'BP', 'Bor', 'CBS',... | 0.503418 | 0.372049 |
import sublime, sublimeplugin
import os.path
import functools
def findCommonPathPrefix(files):
if len(files) > 1:
# Remove any common prefix from the set of files, to drop redundant
# information
common = os.path.commonprefix(files)
# os.path.commonprefix is calculated character by... | sb/Data/Packages/Default/SelectFile.py | import sublime, sublimeplugin
import os.path
import functools
def findCommonPathPrefix(files):
if len(files) > 1:
# Remove any common prefix from the set of files, to drop redundant
# information
common = os.path.commonprefix(files)
# os.path.commonprefix is calculated character by... | 0.304559 | 0.112016 |
from oci.util import formatted_flat_dict, NONE_SENTINEL, value_allowed_none_or_none_sentinel # noqa: F401
from oci.decorators import init_model_state_from_kwargs
@init_model_state_from_kwargs
class CreateTablespaceDetails(object):
"""
The details required to create a tablespace.
"""
#: A constant ... | src/oci/database_management/models/create_tablespace_details.py |
from oci.util import formatted_flat_dict, NONE_SENTINEL, value_allowed_none_or_none_sentinel # noqa: F401
from oci.decorators import init_model_state_from_kwargs
@init_model_state_from_kwargs
class CreateTablespaceDetails(object):
"""
The details required to create a tablespace.
"""
#: A constant ... | 0.811452 | 0.284854 |
import booksdatasource
import unittest
class BooksDataSourceTester(unittest.TestCase):
def setUp(self):
self.data_source = booksdatasource.BooksDataSource('books1.csv')
def tearDown(self):
pass
def test_unique_author_len(self):
authors = self.data_source.authors('Pratchett')
... | books/booksdatasourcetests.py | import booksdatasource
import unittest
class BooksDataSourceTester(unittest.TestCase):
def setUp(self):
self.data_source = booksdatasource.BooksDataSource('books1.csv')
def tearDown(self):
pass
def test_unique_author_len(self):
authors = self.data_source.authors('Pratchett')
... | 0.479747 | 0.606265 |
import unittest
from unittest import mock
from airflow.providers.trino.transfers.gcs_to_trino import GCSToTrinoOperator
BUCKET = "source_bucket"
PATH = "path/to/file.csv"
GCP_CONN_ID = "test_gcp"
IMPERSONATION_CHAIN = ["ACCOUNT_1", "ACCOUNT_2", "ACCOUNT_3"]
TRINO_CONN_ID = "test_trino"
TRINO_TABLE = "test_table"
TASK... | tests/providers/trino/transfers/test_gcs_trino.py | import unittest
from unittest import mock
from airflow.providers.trino.transfers.gcs_to_trino import GCSToTrinoOperator
BUCKET = "source_bucket"
PATH = "path/to/file.csv"
GCP_CONN_ID = "test_gcp"
IMPERSONATION_CHAIN = ["ACCOUNT_1", "ACCOUNT_2", "ACCOUNT_3"]
TRINO_CONN_ID = "test_trino"
TRINO_TABLE = "test_table"
TASK... | 0.488527 | 0.49762 |
from __future__ import absolute_import
import argparse
import logging
from complete.merge_pipeline.joiner.file_transform import ParseFileTransform
import apache_beam as beam
from apache_beam.io import ReadFromText
from apache_beam.options.pipeline_options import PipelineOptions
from apache_beam.options.pipeline_opt... | complete/merge_pipeline/join_pipeline.py |
from __future__ import absolute_import
import argparse
import logging
from complete.merge_pipeline.joiner.file_transform import ParseFileTransform
import apache_beam as beam
from apache_beam.io import ReadFromText
from apache_beam.options.pipeline_options import PipelineOptions
from apache_beam.options.pipeline_opt... | 0.71113 | 0.145267 |
import json
import scrapy
from locations.hours import OpeningHours
from locations.items import GeojsonPointItem
class IkeaSpider(scrapy.Spider):
name = "ikea"
item_attributes = {"brand": "IKEA", "brand_wikidata": "Q54078"}
allowed_domains = ["ikea.com"]
start_urls = [
"https://www.ikea.com/ae... | locations/spiders/ikea.py | import json
import scrapy
from locations.hours import OpeningHours
from locations.items import GeojsonPointItem
class IkeaSpider(scrapy.Spider):
name = "ikea"
item_attributes = {"brand": "IKEA", "brand_wikidata": "Q54078"}
allowed_domains = ["ikea.com"]
start_urls = [
"https://www.ikea.com/ae... | 0.412175 | 0.298364 |
table = {
'table_name' : 'adm_tran_types',
'module_id' : 'adm',
'short_descr' : 'Transaction types',
'long_descr' : 'Transaction types',
'sub_types' : None,
'sub_trans' : None,
'sequence' : ['seq', ['module_row_id'], None],
'tree_params' : [
'module_row... | aib/init/tables/adm_tran_types.py | table = {
'table_name' : 'adm_tran_types',
'module_id' : 'adm',
'short_descr' : 'Transaction types',
'long_descr' : 'Transaction types',
'sub_types' : None,
'sub_trans' : None,
'sequence' : ['seq', ['module_row_id'], None],
'tree_params' : [
'module_row... | 0.280814 | 0.199444 |
# W celu przeprowadzenia operacji odczytu z pliku, musimy otworzyć ten plik w trybie
# odczytu (r) lub edycji (w+, a+, x+).
# Istnieje kilka sposobów odczytu zawartości pliku. Przedstawimy je na przykładzie
# pliku plik.txt o następującej zawartości:
# Pierwsza linia.
# Druga linia.
# Trzecia linia.
# Sposó... | Notatki/2_Pliki/1_Operacje-na-plikach/2_Odczyt-z-pliku.py |
# W celu przeprowadzenia operacji odczytu z pliku, musimy otworzyć ten plik w trybie
# odczytu (r) lub edycji (w+, a+, x+).
# Istnieje kilka sposobów odczytu zawartości pliku. Przedstawimy je na przykładzie
# pliku plik.txt o następującej zawartości:
# Pierwsza linia.
# Druga linia.
# Trzecia linia.
# Sposó... | 0.154759 | 0.640509 |
r"""Fit subunits with localized sparsity prior."""
from __future__ import absolute_import
from __future__ import division
from __future__ import print_function
import os
import os.path
import pickle
from absl import app
from absl import flags
import numpy as np
import scipy.io as sio
from tensorflow.python.platform im... | response_model/python/ASM/su_fit_nov/fit_nsem_3_datasets.py | r"""Fit subunits with localized sparsity prior."""
from __future__ import absolute_import
from __future__ import division
from __future__ import print_function
import os
import os.path
import pickle
from absl import app
from absl import flags
import numpy as np
import scipy.io as sio
from tensorflow.python.platform im... | 0.567218 | 0.222478 |
import logging
from dq0.sdk.estimators.linear_model import sklearn_lm
import numpy as np
logger = logging.getLogger(__name__)
def get_data_int():
X = np.ones((4, 3))
y_int = np.array([1, 2, 3, 4])
return X, y_int
def test_LogisticRegression_001():
X, y = get_data_int()
estimator = sklearn_lm... | tests/test_estimators/linear_model/test_sklearn_linear_models.py | import logging
from dq0.sdk.estimators.linear_model import sklearn_lm
import numpy as np
logger = logging.getLogger(__name__)
def get_data_int():
X = np.ones((4, 3))
y_int = np.array([1, 2, 3, 4])
return X, y_int
def test_LogisticRegression_001():
X, y = get_data_int()
estimator = sklearn_lm... | 0.485112 | 0.362546 |
import json
import jsonpatch
from tomviz import operators, modules
from ._pipeline import PipelineStateManager
from ._utils import to_namespaces
op_class_attrs = ['description', 'label', 'script', 'type']
class InvalidStateError(RuntimeError):
pass
class Base(object):
def __init__(self, **kwargs):
... | tomviz/python/tomviz/state/_models.py | import json
import jsonpatch
from tomviz import operators, modules
from ._pipeline import PipelineStateManager
from ._utils import to_namespaces
op_class_attrs = ['description', 'label', 'script', 'type']
class InvalidStateError(RuntimeError):
pass
class Base(object):
def __init__(self, **kwargs):
... | 0.582135 | 0.127843 |
from . import logging
from . import exceptions
__all__ = ['ScopedContextOverride', 'ScopedActionGroup', 'ScopedProgressManager']
class ScopedContextOverride(object):
"""
A convenience context manager to allow locale, access and retention to be
overridden within a scope.
"""
def __init__(self, context):... | source/FnAssetAPI/contextManagers.py | from . import logging
from . import exceptions
__all__ = ['ScopedContextOverride', 'ScopedActionGroup', 'ScopedProgressManager']
class ScopedContextOverride(object):
"""
A convenience context manager to allow locale, access and retention to be
overridden within a scope.
"""
def __init__(self, context):... | 0.482673 | 0.13589 |
import multiprocessing
from datetime import datetime
from methods.fuser import Fuser
from methods.fuser import init_indices
from methods.fuser import init_matched_group
from methods.dna import PatternDNA
from utils import accessor
read_path = "../data_set/Ecoli_K-1_MG1655.protein.fa"
write_path = "../output... | tentative_test/first_matrix.py | import multiprocessing
from datetime import datetime
from methods.fuser import Fuser
from methods.fuser import init_indices
from methods.fuser import init_matched_group
from methods.dna import PatternDNA
from utils import accessor
read_path = "../data_set/Ecoli_K-1_MG1655.protein.fa"
write_path = "../output... | 0.214691 | 0.151278 |
import sys
import random
import csv
import numpy as np
from sklearn.cross_validation import KFold
# custom modules
import network
from utils import data
FOLDS = 10
def main():
filename = sys.argv[1]
X = data.load_dataset('{}_X.npy'.format(filename))
Y = data.load_dataset('{}_Y.npy'.format(filename))
... | run.py | import sys
import random
import csv
import numpy as np
from sklearn.cross_validation import KFold
# custom modules
import network
from utils import data
FOLDS = 10
def main():
filename = sys.argv[1]
X = data.load_dataset('{}_X.npy'.format(filename))
Y = data.load_dataset('{}_Y.npy'.format(filename))
... | 0.192615 | 0.296425 |
import glob
import sys
import time
from typing import List, Optional
import serial
def search_for_serial_devices(device: str) -> List[str]:
"""Returns a list of device paths with corresponding device name.
If the device identification string contains the string given in the input
paramter 'device', the ... | S15lib/instruments/serial_connection.py | import glob
import sys
import time
from typing import List, Optional
import serial
def search_for_serial_devices(device: str) -> List[str]:
"""Returns a list of device paths with corresponding device name.
If the device identification string contains the string given in the input
paramter 'device', the ... | 0.755141 | 0.266738 |
from string import Template
URXVT_TEMPLATE = Template(r"""
{
"app-id": "de.uchuujin.fp.termzoo.urxvt${urxvt_version}",
"runtime": "org.freedesktop.Platform",
"runtime-version": "18.08",
"sdk": "org.freedesktop.Sdk",
"command": "urxvt",
"finish-args": ["--socket=x11", "--device=dri", "--talk-na... | rxvt-unicode/generate.py |
from string import Template
URXVT_TEMPLATE = Template(r"""
{
"app-id": "de.uchuujin.fp.termzoo.urxvt${urxvt_version}",
"runtime": "org.freedesktop.Platform",
"runtime-version": "18.08",
"sdk": "org.freedesktop.Sdk",
"command": "urxvt",
"finish-args": ["--socket=x11", "--device=dri", "--talk-na... | 0.3512 | 0.152442 |
from __future__ import annotations
from enum import Enum
from flask import g
import pytest
from byceps.util.authorization import create_permission_enum
from byceps.util.authorization import (
has_current_user_any_permission,
has_current_user_permission,
)
ChillPermission = create_permission_enum(
'chill... | tests/integration/util/test_authorization.py | from __future__ import annotations
from enum import Enum
from flask import g
import pytest
from byceps.util.authorization import create_permission_enum
from byceps.util.authorization import (
has_current_user_any_permission,
has_current_user_permission,
)
ChillPermission = create_permission_enum(
'chill... | 0.725454 | 0.153137 |
from operator import add
import types
from .vendor.lexicon import Lexicon
from .parser import Context, Argument
from .tasks import Task
class Collection(object):
"""
A collection of executable tasks.
"""
def __init__(self, *args, **kwargs):
"""
Create a new task collection/namespace.... | invoke/collection.py | from operator import add
import types
from .vendor.lexicon import Lexicon
from .parser import Context, Argument
from .tasks import Task
class Collection(object):
"""
A collection of executable tasks.
"""
def __init__(self, *args, **kwargs):
"""
Create a new task collection/namespace.... | 0.83545 | 0.324784 |
import datetime
import numpy as np
import pytest
import dsch
# Ensure dsch.schema is automatically imported alongside the dsch package.
# Normally, we would get the "schema" shorthand via "from dsch import schema".
schema = dsch.schema
@pytest.fixture(params=('hdf5', 'mat', 'npz'))
def storage_path(request, tmpdir... | tests/test_high_level.py | import datetime
import numpy as np
import pytest
import dsch
# Ensure dsch.schema is automatically imported alongside the dsch package.
# Normally, we would get the "schema" shorthand via "from dsch import schema".
schema = dsch.schema
@pytest.fixture(params=('hdf5', 'mat', 'npz'))
def storage_path(request, tmpdir... | 0.507324 | 0.529203 |
import xml.etree.ElementTree as ET
from detectron2.data import DatasetCatalog, MetadataCatalog
def get_vid_dicts(data_dir):
meta = MetadataCatalog.get("vid")
dataset_dicts = []
vid_dir = os.path.join(data_dir, "VID")
for video in os.listdir(vid_dir):
records = []
jpegs = os.listdir(os... | projects/e2evod/e2evod/dataset.py | import xml.etree.ElementTree as ET
from detectron2.data import DatasetCatalog, MetadataCatalog
def get_vid_dicts(data_dir):
meta = MetadataCatalog.get("vid")
dataset_dicts = []
vid_dir = os.path.join(data_dir, "VID")
for video in os.listdir(vid_dir):
records = []
jpegs = os.listdir(os... | 0.468547 | 0.174235 |
import glob
import multiprocessing as mp
from multiprocessing import shared_memory
import argparse
import numpy as np
import xarray as xr
import os
import time
pool = None
data_vars = None
def load_file(file_name,var_mems):
'''Load a netcdf dataset into memory'''
d = xr.open_dataset(file_name)
subset(d... | helpers/aggregate_parallel_files_par.py |
import glob
import multiprocessing as mp
from multiprocessing import shared_memory
import argparse
import numpy as np
import xarray as xr
import os
import time
pool = None
data_vars = None
def load_file(file_name,var_mems):
'''Load a netcdf dataset into memory'''
d = xr.open_dataset(file_name)
subset(d... | 0.252016 | 0.33704 |
def date_visualization(queries,query_results,graph_filename,csv_filename,month_flag=False,year_flag=True,weight_flag=False,cite_flag=False,database='CrossRef'):
import numpy as np
def counts(dates):
import pandas as pd
if month_flag==True:
freq='M'
date_format='%Y-%... | Python/visualization.py | def date_visualization(queries,query_results,graph_filename,csv_filename,month_flag=False,year_flag=True,weight_flag=False,cite_flag=False,database='CrossRef'):
import numpy as np
def counts(dates):
import pandas as pd
if month_flag==True:
freq='M'
date_format='%Y-%... | 0.206494 | 0.302803 |
from collections import OrderedDict
from sqlalchemy import create_engine
from sqlalchemy import ForeignKey, ForeignKeyConstraint, Column, Integer, String, DateTime
from sqlalchemy.types import Boolean
from sqlalchemy.orm import relationship, sessionmaker
from sqlalchemy.ext.declarative import declarative_base
import co... | model.py | from collections import OrderedDict
from sqlalchemy import create_engine
from sqlalchemy import ForeignKey, ForeignKeyConstraint, Column, Integer, String, DateTime
from sqlalchemy.types import Boolean
from sqlalchemy.orm import relationship, sessionmaker
from sqlalchemy.ext.declarative import declarative_base
import co... | 0.759404 | 0.136551 |
import pytest
from tests.functional.services.api.conftest import USER_API_CONFS
from tests.functional.services.api.images import wait_for_image_to_analyze, get_image_id, \
get_image_digest
from tests.functional.utils.http_utils import http_post, RequestFailedError, http_del
from tests.functional.conftest import ge... | tests/functional/services/api/archives/conftest.py | import pytest
from tests.functional.services.api.conftest import USER_API_CONFS
from tests.functional.services.api.images import wait_for_image_to_analyze, get_image_id, \
get_image_digest
from tests.functional.utils.http_utils import http_post, RequestFailedError, http_del
from tests.functional.conftest import ge... | 0.413004 | 0.234516 |
import datetime
import math
import argparse
MONDAY, TUESDAY, WEDNESDAY = 0, 1, 2
def _vernal_equinox(y):
"""整数で年を与えると、その年の春分の日が3月の何日であるかを返す
"""
if y <= 1947:
d = 0
elif y <= 1979:
d = math.floor(20.8357 + 0.242194 * (y - 1980) - math.floor((y - 1980) / 4))
elif y <= 2099:
... | stock/src/lib/jholiday.py | import datetime
import math
import argparse
MONDAY, TUESDAY, WEDNESDAY = 0, 1, 2
def _vernal_equinox(y):
"""整数で年を与えると、その年の春分の日が3月の何日であるかを返す
"""
if y <= 1947:
d = 0
elif y <= 1979:
d = math.floor(20.8357 + 0.242194 * (y - 1980) - math.floor((y - 1980) / 4))
elif y <= 2099:
... | 0.24817 | 0.28439 |
r"""Binary merger rate module.
This module provides functions to calculate compact binary merger rates
for individual galaxies.
"""
from astropy import constants, units
__all__ = [
'b_band_merger_rate',
]
abadie_table_III = {
'NS-NS': {
'low': 0.6,
'realistic': 60,
'high': 600,
... | skypy/gravitational_wave/merger_rate.py | r"""Binary merger rate module.
This module provides functions to calculate compact binary merger rates
for individual galaxies.
"""
from astropy import constants, units
__all__ = [
'b_band_merger_rate',
]
abadie_table_III = {
'NS-NS': {
'low': 0.6,
'realistic': 60,
'high': 600,
... | 0.959116 | 0.710415 |
from telnetlib import Telnet
def yield_vision_telnet_connection(host: str, port: int, user: str, password: str) -> Telnet:
try:
with Telnet(host, port) as telnet:
telnet.read_until(b"login: ", 5)
telnet.write(user.encode("ascii") + b"\n")
telnet.read_until(b"Password: ... | VisionBackofficeTools/VisionConnection.py | from telnetlib import Telnet
def yield_vision_telnet_connection(host: str, port: int, user: str, password: str) -> Telnet:
try:
with Telnet(host, port) as telnet:
telnet.read_until(b"login: ", 5)
telnet.write(user.encode("ascii") + b"\n")
telnet.read_until(b"Password: ... | 0.375821 | 0.138549 |
import subprocess
import sys
INIT_RUNTIME_ENV_COMMAND = """\
# Set noninteractive to avoid irrelevant warning messages
export DEBIAN_FRONTEND=noninteractive
echo 'Step 1/{steps}: Install docker'
sudo -E apt-get update
sudo -E apt-get install -y apt-transport-https ca-certificates curl software-properties-common
curl ... | maro/cli/grass/lib/scripts/build_node_image_vm/init_build_node_image_vm.py | import subprocess
import sys
INIT_RUNTIME_ENV_COMMAND = """\
# Set noninteractive to avoid irrelevant warning messages
export DEBIAN_FRONTEND=noninteractive
echo 'Step 1/{steps}: Install docker'
sudo -E apt-get update
sudo -E apt-get install -y apt-transport-https ca-certificates curl software-properties-common
curl ... | 0.212069 | 0.038829 |
class MetaData:
"""
Data structure to hold all meta information.
A instance of this class is typically created by processing all
meta data relevant tags of all doc comments in the given node structure.
Hint: Must be a clean data class without links to other
systems for optiomal cachab... | jasy/js/MetaData.py |
class MetaData:
"""
Data structure to hold all meta information.
A instance of this class is typically created by processing all
meta data relevant tags of all doc comments in the given node structure.
Hint: Must be a clean data class without links to other
systems for optiomal cachab... | 0.650911 | 0.284756 |
import logging
from django.contrib import messages
from django.template import RequestContext
from django.urls import reverse_lazy
from django.utils.translation import ugettext_lazy as _, ungettext
from mayan.apps.views.generics import (
MultipleObjectConfirmActionView, SingleObjectCreateView,
SingleObjectEdi... | mayan/apps/motd/views.py | import logging
from django.contrib import messages
from django.template import RequestContext
from django.urls import reverse_lazy
from django.utils.translation import ugettext_lazy as _, ungettext
from mayan.apps.views.generics import (
MultipleObjectConfirmActionView, SingleObjectCreateView,
SingleObjectEdi... | 0.369315 | 0.06148 |
from torch.distributions import Categorical
import gym
import numpy as np
import torch
import torch.nn as nn
import torch.optim as optim
'''
Chapter 2. REINFORCE
Most code here is copied from SLM-Lab first and then modified to show a plain torch implementation.
'''
gamma = 0.99
# Policy Pi
class Pi(nn... | Code/REINFORCE.py | from torch.distributions import Categorical
import gym
import numpy as np
import torch
import torch.nn as nn
import torch.optim as optim
'''
Chapter 2. REINFORCE
Most code here is copied from SLM-Lab first and then modified to show a plain torch implementation.
'''
gamma = 0.99
# Policy Pi
class Pi(nn... | 0.933756 | 0.502014 |
import datetime
import aiohttp
import pytest
from aio_geojson_client.consts import UPDATE_OK
from aio_geojson_flightairmap.feed import FlightAirMapFeed
from tests.utils import load_fixture
@pytest.mark.asyncio
async def test_update_ok(aresponses, event_loop):
"""Test updating feed is ok."""
home_coordinate... | tests/test_feed.py | import datetime
import aiohttp
import pytest
from aio_geojson_client.consts import UPDATE_OK
from aio_geojson_flightairmap.feed import FlightAirMapFeed
from tests.utils import load_fixture
@pytest.mark.asyncio
async def test_update_ok(aresponses, event_loop):
"""Test updating feed is ok."""
home_coordinate... | 0.59843 | 0.404566 |
from __future__ import print_function
from time import time
import numpy as np
import matplotlib.pyplot as plt
from pymongo import MongoClient
from sklearn import metrics
from sklearn.feature_extraction.text import TfidfVectorizer
from sklearn.pipeline import Pipeline
from sklearn.svm import LinearSVC
from sklearn... | classification/initial_baseline_sklearn_classification.py | from __future__ import print_function
from time import time
import numpy as np
import matplotlib.pyplot as plt
from pymongo import MongoClient
from sklearn import metrics
from sklearn.feature_extraction.text import TfidfVectorizer
from sklearn.pipeline import Pipeline
from sklearn.svm import LinearSVC
from sklearn... | 0.690037 | 0.314866 |
from enum import Enum
from typing import Any, Dict, Optional, Tuple, Union
from snr import *
from snr.utils.dummy_endpoint.dummy_endpoint_factory import \
DummyEndpointFactory
class MyEnum(Enum):
a = "a"
b = "b"
c = "c"
Id = Tuple[MyEnum, str]
Key = Union[MyEnum, Id]
class TestNode(SNRTestCase):
... | tests/test_node.py | from enum import Enum
from typing import Any, Dict, Optional, Tuple, Union
from snr import *
from snr.utils.dummy_endpoint.dummy_endpoint_factory import \
DummyEndpointFactory
class MyEnum(Enum):
a = "a"
b = "b"
c = "c"
Id = Tuple[MyEnum, str]
Key = Union[MyEnum, Id]
class TestNode(SNRTestCase):
... | 0.744935 | 0.223758 |