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 tkinter from tkinter import ttk import mqtt_remote_method_calls as mqtt import m2_laptop_code as m2 import m3_laptop_code as m3 def get_my_frame(root, window, mqtt_sender): # Construct your frame: frame = ttk.Frame(window, padding=10, borderwidth=5, relief="ridge") frame_label = ttk.Label(frame, ...
src/m1_laptop_code.py
import tkinter from tkinter import ttk import mqtt_remote_method_calls as mqtt import m2_laptop_code as m2 import m3_laptop_code as m3 def get_my_frame(root, window, mqtt_sender): # Construct your frame: frame = ttk.Frame(window, padding=10, borderwidth=5, relief="ridge") frame_label = ttk.Label(frame, ...
0.509032
0.234889
import numpy as np import visgeom as vg from camera import PerspectiveCamera from measurements import PrecalibratedCameraMeasurementsFixedWorld from optim import levenberg_marquardt from visualise_ba import visualise_moba """Example 1 - Motion-only Bundle Adjustment""" class PrecalibratedMotionOnlyBAObjective: ...
ex_1_motion_only_ba.py
import numpy as np import visgeom as vg from camera import PerspectiveCamera from measurements import PrecalibratedCameraMeasurementsFixedWorld from optim import levenberg_marquardt from visualise_ba import visualise_moba """Example 1 - Motion-only Bundle Adjustment""" class PrecalibratedMotionOnlyBAObjective: ...
0.908425
0.82748
import os import sys import numpy as np import argparse import functools import paddle import paddle.fluid as fluid from utility import add_arguments, print_arguments from se_resnext import SE_ResNeXt import reader parser = argparse.ArgumentParser(description=__doc__) add_arg = functools.partial(add_arguments, argpar...
fluid/image_classification/infer.py
import os import sys import numpy as np import argparse import functools import paddle import paddle.fluid as fluid from utility import add_arguments, print_arguments from se_resnext import SE_ResNeXt import reader parser = argparse.ArgumentParser(description=__doc__) add_arg = functools.partial(add_arguments, argpar...
0.362179
0.161122
import asyncio import itertools import os import random import re import subprocess from collections import UserDict from typing import Any, Iterable, List, Optional HASH_BYTES = 32 def get_package_path(): """ Returns ROOT_PATH s.t. $ROOT_PATH/starkware is the package folder. """ import starkware.pyt...
src/starkware/python/utils.py
import asyncio import itertools import os import random import re import subprocess from collections import UserDict from typing import Any, Iterable, List, Optional HASH_BYTES = 32 def get_package_path(): """ Returns ROOT_PATH s.t. $ROOT_PATH/starkware is the package folder. """ import starkware.pyt...
0.786869
0.366363
import csv import h5py import logging import logging.config import numpy as np import os from os import path import pandas as pd import pathlib import re import xlsxwriter class CreateCsv: """Class combines csv linking IDs to csv containing feature info. Merge linked track and object IDs to corresponding feat...
formats/polus-imaris-parser-plugin/src/merge_ids_to_features.py
import csv import h5py import logging import logging.config import numpy as np import os from os import path import pandas as pd import pathlib import re import xlsxwriter class CreateCsv: """Class combines csv linking IDs to csv containing feature info. Merge linked track and object IDs to corresponding feat...
0.692122
0.272285
import os import sys import unittest from click.testing import CliRunner from dirindex._cli import cli from dirindex.version import VERSION class Test1(unittest.TestCase): def test1(self): self.assertFalse(False, "False is False") # self.assertTrue(False, "not Implemented") def testUsage(self...
tests/test_1.py
import os import sys import unittest from click.testing import CliRunner from dirindex._cli import cli from dirindex.version import VERSION class Test1(unittest.TestCase): def test1(self): self.assertFalse(False, "False is False") # self.assertTrue(False, "not Implemented") def testUsage(self...
0.364438
0.529507
from django.db import models from allianceauth.services.hooks import get_extension_logger from esi.models import Token from bravado.exception import HTTPUnauthorized, HTTPForbidden from eveuniverse.models import EveSolarSystem from . import __title__ from .utils import LoggerAddTag from .helpers import esi_fetch # C...
buybacks/managers.py
from django.db import models from allianceauth.services.hooks import get_extension_logger from esi.models import Token from bravado.exception import HTTPUnauthorized, HTTPForbidden from eveuniverse.models import EveSolarSystem from . import __title__ from .utils import LoggerAddTag from .helpers import esi_fetch # C...
0.387574
0.112844
import pandas as pd import pytest import numpy as np from designs import conduction_1d from designs.conduction_1d import Config @pytest.fixture(params=[{ "value": conduction_1d.BOUNDARY_CONVECTIVE }, { "value": conduction_1d.BOUNDARY_INSULATED }, { "value": conduction_1d.BOUNDARY_CONSTANT }], ...
tests/test_1d_conduction.py
import pandas as pd import pytest import numpy as np from designs import conduction_1d from designs.conduction_1d import Config @pytest.fixture(params=[{ "value": conduction_1d.BOUNDARY_CONVECTIVE }, { "value": conduction_1d.BOUNDARY_INSULATED }, { "value": conduction_1d.BOUNDARY_CONSTANT }], ...
0.733452
0.429669
import torch from torch.autograd import Variable import torch.nn.functional as F from torch.nn.parameter import Parameter import numpy as np from classifier_control.classifier.utils.subnetworks import ConvEncoder, ConvDecoder from classifier_control.classifier.utils.layers import Linear class VAE(torch.nn.Module): ...
classifier_control/classifier/utils/vae.py
import torch from torch.autograd import Variable import torch.nn.functional as F from torch.nn.parameter import Parameter import numpy as np from classifier_control.classifier.utils.subnetworks import ConvEncoder, ConvDecoder from classifier_control.classifier.utils.layers import Linear class VAE(torch.nn.Module): ...
0.928789
0.342407
import numpy as np import matplotlib.pyplot as plt from torch.optim.lr_scheduler import StepLR, ReduceLROnPlateau, OneCycleLR def StepLR_scheduler(optimizer, step_size=6, gamma=0.1): return StepLR(optimizer, step_size=step_size, gamma=gamma) def LR_on_pleateau_scheduler(optimizer, patience=10, threshold=0.0001, ...
Week11/main_engine/schedulers.py
import numpy as np import matplotlib.pyplot as plt from torch.optim.lr_scheduler import StepLR, ReduceLROnPlateau, OneCycleLR def StepLR_scheduler(optimizer, step_size=6, gamma=0.1): return StepLR(optimizer, step_size=step_size, gamma=gamma) def LR_on_pleateau_scheduler(optimizer, patience=10, threshold=0.0001, ...
0.769254
0.421016
from collections import defaultdict from logs.services import get_order_log_time_by_order_num from order.constant import OrderStatus from order.models import Order, OrderAddress, OrderDetail from user.constant import USER_OUTPUT_CONSTANT def get_shop_order_by_num(shop_id: int, num: str): """ 通过店铺id和订单号获取订单及详...
wsc_django/wsc_django/apps/order/selectors.py
from collections import defaultdict from logs.services import get_order_log_time_by_order_num from order.constant import OrderStatus from order.models import Order, OrderAddress, OrderDetail from user.constant import USER_OUTPUT_CONSTANT def get_shop_order_by_num(shop_id: int, num: str): """ 通过店铺id和订单号获取订单及详...
0.483405
0.166032
def facility(): """Return a selector function for the facility a component refers to.""" # This works both for analysis components, and facilities (in which case the # facility itself is returned). return lambda component: component.facility def self(): """Return a selector function that selects t...
biopharma/optimisation/sel.py
def facility(): """Return a selector function for the facility a component refers to.""" # This works both for analysis components, and facilities (in which case the # facility itself is returned). return lambda component: component.facility def self(): """Return a selector function that selects t...
0.835215
0.855369
import json import xml from collections import defaultdict import xmltodict import yaml from chibi.snippet.dict import hate_ordered_dict, remove_xml_notatation class Atlas: def __new__( cls, item, *args, **kw ): return _wrap( item ) def loads( string ): try: return Chibi_atlas( json.loads...
chibi/atlas/__init__.py
import json import xml from collections import defaultdict import xmltodict import yaml from chibi.snippet.dict import hate_ordered_dict, remove_xml_notatation class Atlas: def __new__( cls, item, *args, **kw ): return _wrap( item ) def loads( string ): try: return Chibi_atlas( json.loads...
0.430985
0.075007
from django import forms from django.contrib.auth.forms import AuthenticationForm, UserCreationForm from .models import Parking_place, MyUser choice = (('Manager', 'Manager'), ('Employee', 'Employee')) class RegisterForm(UserCreationForm): role = forms.ChoiceField( required=True, choices=choice ...
frigate/users/forms.py
from django import forms from django.contrib.auth.forms import AuthenticationForm, UserCreationForm from .models import Parking_place, MyUser choice = (('Manager', 'Manager'), ('Employee', 'Employee')) class RegisterForm(UserCreationForm): role = forms.ChoiceField( required=True, choices=choice ...
0.432543
0.071267
from django.urls import path, re_path from .views import ( StaffMemberPaymentsView, OtherStaffMemberPaymentsView, FinancesByMonthView, FinancesByDateView, FinancesByEventView, AllExpensesViewCSV, AllRevenuesViewCSV, FinancialDetailView, ExpenseReportingView, RevenueReportingView, CompensationRuleUpdate...
danceschool/financial/urls.py
from django.urls import path, re_path from .views import ( StaffMemberPaymentsView, OtherStaffMemberPaymentsView, FinancesByMonthView, FinancesByDateView, FinancesByEventView, AllExpensesViewCSV, AllRevenuesViewCSV, FinancialDetailView, ExpenseReportingView, RevenueReportingView, CompensationRuleUpdate...
0.358802
0.095645
from __future__ import absolute_import from __future__ import division from __future__ import print_function from racket_compiler.racket_parser import Parser from solver_input_generator import Solver_Input from third_party.demo2program.karel_env.dsl import get_KarelDSL from third_party.demo2program.karel_env.dsl imp...
solver.py
from __future__ import absolute_import from __future__ import division from __future__ import print_function from racket_compiler.racket_parser import Parser from solver_input_generator import Solver_Input from third_party.demo2program.karel_env.dsl import get_KarelDSL from third_party.demo2program.karel_env.dsl imp...
0.560734
0.106784
from os import getenv, path import numpy as np import torch import torchvision class ImageGenerationDataset(object): def _transform(self, x): x = np.array(x, dtype=np.int64).ravel() y = (x.astype(np.float32) / 255) * 2 - 1 return torch.from_numpy(x[:-1]), torch.from_numpy(y[1:]) @p...
image-generation/image_datasets.py
from os import getenv, path import numpy as np import torch import torchvision class ImageGenerationDataset(object): def _transform(self, x): x = np.array(x, dtype=np.int64).ravel() y = (x.astype(np.float32) / 255) * 2 - 1 return torch.from_numpy(x[:-1]), torch.from_numpy(y[1:]) @p...
0.757615
0.323955
import sys import os import tempfile import unittest import sd3.cfa.graph import sd3.cfa.shortestpath class TestGraph(unittest.TestCase): def test_edge(self): node_src_id = 1 node_dest_id = 2 node_src = sd3.cfa.graph.Node(node_src_id) node_dest = sd3.cfa.graph.Node(node_dest_id) ...
tests/cfa/test_graph.py
import sys import os import tempfile import unittest import sd3.cfa.graph import sd3.cfa.shortestpath class TestGraph(unittest.TestCase): def test_edge(self): node_src_id = 1 node_dest_id = 2 node_src = sd3.cfa.graph.Node(node_src_id) node_dest = sd3.cfa.graph.Node(node_dest_id) ...
0.449393
0.529811
import os import numpy as np import torch import shutil import torchvision.transforms as transforms from torch.autograd import Variable from collections import defaultdict from config import config class AvgrageMeter(object): def __init__(self): self.reset() def reset(self): self.avg = 0 self.sum = 0...
darts_search_space/imagenet/rlnas/evolution_search/utils.py
import os import numpy as np import torch import shutil import torchvision.transforms as transforms from torch.autograd import Variable from collections import defaultdict from config import config class AvgrageMeter(object): def __init__(self): self.reset() def reset(self): self.avg = 0 self.sum = 0...
0.599485
0.37051
def objective(trial): global layer_depth global first_hidden_dim global second_hidden_dim global third_hidden_dim global latent_dim global beta global kappa global batch_size global learning_rate #leaky_reluの時に使用する global leaky_alpha #ドロップアウトを用いる場合 global dr_rate ...
CVAE/hyper_parameter_optimizer/optuna_object.py
def objective(trial): global layer_depth global first_hidden_dim global second_hidden_dim global third_hidden_dim global latent_dim global beta global kappa global batch_size global learning_rate #leaky_reluの時に使用する global leaky_alpha #ドロップアウトを用いる場合 global dr_rate ...
0.423696
0.437944
import numpy as np from glob import glob import matplotlib.pyplot as plt import numpy as np import os import pandas as pd from sklearn.neighbors import NearestNeighbors from winnow.feature_extraction import SimilarityModel import cv2 import yaml def create_directory(directories,root_dir,alias): for r in director...
winnow/utils/utils.py
import numpy as np from glob import glob import matplotlib.pyplot as plt import numpy as np import os import pandas as pd from sklearn.neighbors import NearestNeighbors from winnow.feature_extraction import SimilarityModel import cv2 import yaml def create_directory(directories,root_dir,alias): for r in director...
0.41941
0.344829
import os import logging from keyring.keyring.util import properties from keyring.keyring.backend import KeyringBackend from keyring.keyring.errors import (InitError, PasswordDeleteError, ExceptionRaisedContext) try: import secretstorage.exceptions except ImportError: pass log = logging.getLogger(__name_...
keyring/keyring/backends/SecretService.py
import os import logging from keyring.keyring.util import properties from keyring.keyring.backend import KeyringBackend from keyring.keyring.errors import (InitError, PasswordDeleteError, ExceptionRaisedContext) try: import secretstorage.exceptions except ImportError: pass log = logging.getLogger(__name_...
0.464416
0.094678
import numpy as np import math def calculateSurface(mesh, vertGroups=None, faceMask=None): """ Calculate surface area of a mesh. Specify vertGroups or faceMask to calculate area of a subset of the mesh and filter out other faces. """ if vertGroups is not None: f_idx = mesh.getFacesForGroups...
makehuman-master/makehuman/shared/mesh_operations.py
import numpy as np import math def calculateSurface(mesh, vertGroups=None, faceMask=None): """ Calculate surface area of a mesh. Specify vertGroups or faceMask to calculate area of a subset of the mesh and filter out other faces. """ if vertGroups is not None: f_idx = mesh.getFacesForGroups...
0.793026
0.753263
import htmlvis import pytest from mock import Mock, mock_open @pytest.fixture(autouse=True) def patch_seqdiag_draw(mocker): mocker.patch('htmlvis.seqdiag.draw') @pytest.fixture(autouse=True) def patch_open(mocker): try: mocker.patch('builtins.open', mock_open()) except ImportError: mocke...
tests/test_htmlvis.py
import htmlvis import pytest from mock import Mock, mock_open @pytest.fixture(autouse=True) def patch_seqdiag_draw(mocker): mocker.patch('htmlvis.seqdiag.draw') @pytest.fixture(autouse=True) def patch_open(mocker): try: mocker.patch('builtins.open', mock_open()) except ImportError: mocke...
0.453988
0.215433
from aws_adfs import account_aliases_fetcher def _aws_account(account_alias, account_no): return u'<div class="saml-account-name">Account: {} ({})</div>'.format(account_alias, account_no) def _account_page_response(accounts): response = type('', (), {})() response.request = type('', (), {})() respon...
test/test_account_aliases_fetcher.py
from aws_adfs import account_aliases_fetcher def _aws_account(account_alias, account_no): return u'<div class="saml-account-name">Account: {} ({})</div>'.format(account_alias, account_no) def _account_page_response(accounts): response = type('', (), {})() response.request = type('', (), {})() respon...
0.661595
0.110112
from . import sys, librosa, np def voice_frequency( audio_path: str, sr: int = 1000, sr_scalar: int = 22, deno: int = 30, freqdiff: int = 13, freqmin: int = 65, ) -> float: y, _ = librosa.load(audio_path, sr=sr) y_fourier = librosa.stft(y, n_fft=1024) data = librosa.amplitude_to_db...
backend/utils/voice_frequency2.py
from . import sys, librosa, np def voice_frequency( audio_path: str, sr: int = 1000, sr_scalar: int = 22, deno: int = 30, freqdiff: int = 13, freqmin: int = 65, ) -> float: y, _ = librosa.load(audio_path, sr=sr) y_fourier = librosa.stft(y, n_fft=1024) data = librosa.amplitude_to_db...
0.242026
0.383237
import base64 import zlib from google.protobuf import descriptor_pb2 # Includes description of the api/api_proto/features.proto and all of its transitive # dependencies. Includes source code info. FILE_DESCRIPTOR_SET = descriptor_pb2.FileDescriptorSet() FILE_DESCRIPTOR_SET.ParseFromString(zlib.decompress(base64.b64d...
appengine/monorail/api/api_proto/features_prpc_pb2.py
import base64 import zlib from google.protobuf import descriptor_pb2 # Includes description of the api/api_proto/features.proto and all of its transitive # dependencies. Includes source code info. FILE_DESCRIPTOR_SET = descriptor_pb2.FileDescriptorSet() FILE_DESCRIPTOR_SET.ParseFromString(zlib.decompress(base64.b64d...
0.198996
0.071009
from pycograph.config import settings from pycograph.schemas.parse_result import PackageWithContext def test_package_production_code(): package = PackageWithContext( name="example", full_name="example", dir_path="", ) assert package.is_test_object is False assert package.label...
tests/unit/schemas/parse_result/test_package.py
from pycograph.config import settings from pycograph.schemas.parse_result import PackageWithContext def test_package_production_code(): package = PackageWithContext( name="example", full_name="example", dir_path="", ) assert package.is_test_object is False assert package.label...
0.667581
0.535038
from bokeh.plotting import figure from bokeh.layouts import column from bokeh.io import export_png, show from bokeh.palettes import Category20 from sklearn.decomposition import PCA import holoviews as hv from holoviews.operation import gridmatrix import numpy as np import pandas as pd import os if not os.path.exists("...
PCA/src/DimReduction.py
from bokeh.plotting import figure from bokeh.layouts import column from bokeh.io import export_png, show from bokeh.palettes import Category20 from sklearn.decomposition import PCA import holoviews as hv from holoviews.operation import gridmatrix import numpy as np import pandas as pd import os if not os.path.exists("...
0.595257
0.683471
from collections import defaultdict import math import sys book = sys.argv[1] def get_chapter(sid): def single(s): return int(s.split('-')[-1]) p = sid.split(':') if len(p) == 2: return [single(p[0])] else: return [single(p[0]), single(p[1])] total_sents = 0 total_words = 0 re...
report.py
from collections import defaultdict import math import sys book = sys.argv[1] def get_chapter(sid): def single(s): return int(s.split('-')[-1]) p = sid.split(':') if len(p) == 2: return [single(p[0])] else: return [single(p[0]), single(p[1])] total_sents = 0 total_words = 0 re...
0.181372
0.284647
"""The Virtual File System (VFS) file-like object interface.""" import abc import os # Since this class implements the file-like object interface # the names of the interface functions are in lower case as an exception # to the normal naming convention. class FileIO(object): """Class that implements the VFS file...
dfvfs/file_io/file_io.py
"""The Virtual File System (VFS) file-like object interface.""" import abc import os # Since this class implements the file-like object interface # the names of the interface functions are in lower case as an exception # to the normal naming convention. class FileIO(object): """Class that implements the VFS file...
0.931774
0.34017
import sys import time import os import math import json import geopy import pandas as pd import numpy as np import shapefile as shp import math import multiprocessing as mp from pyproj import Proj, transform from geopy.distance import VincentyDistance from shapely.geometry import box, mapping, shape lon_km = 0.00449...
create_grid.py
import sys import time import os import math import json import geopy import pandas as pd import numpy as np import shapefile as shp import math import multiprocessing as mp from pyproj import Proj, transform from geopy.distance import VincentyDistance from shapely.geometry import box, mapping, shape lon_km = 0.00449...
0.135804
0.212824
import copy import mock try: import unittest2 as unittest except ImportError: import unittest from testrail.helper import TestRailError from testrail.section import Section from testrail.suite import Suite class TestSuite(unittest.TestCase): def setUp(self): self.mock_suite_data = [ {...
tests/test_section.py
import copy import mock try: import unittest2 as unittest except ImportError: import unittest from testrail.helper import TestRailError from testrail.section import Section from testrail.suite import Suite class TestSuite(unittest.TestCase): def setUp(self): self.mock_suite_data = [ {...
0.512937
0.371222
import os import sys import numpy as np from time import time import argparse from py_data_getter import data_getter from py_db import db db = db('nba_shots') def initiate(start_year, end_year): start_time = time() print "-------------------------" print "percentiles.py" print '\n\ncalculating perc...
processing/percentiles.py
import os import sys import numpy as np from time import time import argparse from py_data_getter import data_getter from py_db import db db = db('nba_shots') def initiate(start_year, end_year): start_time = time() print "-------------------------" print "percentiles.py" print '\n\ncalculating perc...
0.087692
0.139075
import numpy as np import matplotlib.pyplot as plt import seaborn as sns from scipy import stats from keras.datasets import imdb from keras.preprocessing.sequence import pad_sequences from keras.models import Sequential from keras.layers.embeddings import Embedding from keras.layers import SimpleRNN, Dense, A...
preprocessing.py
import numpy as np import matplotlib.pyplot as plt import seaborn as sns from scipy import stats from keras.datasets import imdb from keras.preprocessing.sequence import pad_sequences from keras.models import Sequential from keras.layers.embeddings import Embedding from keras.layers import SimpleRNN, Dense, A...
0.387227
0.307657
import os import time from abc import abstractmethod from . import helpers from .config import client class ClientTrader: def __init__(self): self._config = client.create(self.broker_type) def prepare(self, config_path=None, user=None, password=None, exe_path=None, comm_password=None, ...
Stock/Trade/Broker/YhNew/clienttrader.py
import os import time from abc import abstractmethod from . import helpers from .config import client class ClientTrader: def __init__(self): self._config = client.create(self.broker_type) def prepare(self, config_path=None, user=None, password=None, exe_path=None, comm_password=None, ...
0.44746
0.089614
import functools import os import pathlib import sys import pytest import typer from _pytest.logging import LogCaptureFixture from loguru import logger @pytest.fixture(scope="session") def tmp_cwd(tmp_path_factory): cwd = pathlib.Path.cwd() tmp_wd = tmp_path_factory.mktemp("bucky_integration") os.chdir(t...
tests/conftest.py
import functools import os import pathlib import sys import pytest import typer from _pytest.logging import LogCaptureFixture from loguru import logger @pytest.fixture(scope="session") def tmp_cwd(tmp_path_factory): cwd = pathlib.Path.cwd() tmp_wd = tmp_path_factory.mktemp("bucky_integration") os.chdir(t...
0.379608
0.181807
# -*- coding: utf-8 -*- __author__ = "<NAME>" __date__ = "08 Mar 2016" import os, sys; sys.path.append(os.path.join('..', '..', '..')) # analysis:ignore import numpy as np import xrt.plotter as xrtp import xrt.runner as xrtr import xrt.backends.raycing.materials as rm import BalderBL showIn3D = False BalderBL.show...
examples/withRaycing/02_Balder_BL/traceDCMBalderBL.py
# -*- coding: utf-8 -*- __author__ = "<NAME>" __date__ = "08 Mar 2016" import os, sys; sys.path.append(os.path.join('..', '..', '..')) # analysis:ignore import numpy as np import xrt.plotter as xrtp import xrt.runner as xrtr import xrt.backends.raycing.materials as rm import BalderBL showIn3D = False BalderBL.show...
0.38445
0.267378
import sys import argparse from argparse import ArgumentParser import logging import easywrk from easywrk.commands import help_command, request_command, run_command, view_config_command from easywrk.commands import list_command, init_command from easywrk.commands import register_cmd_help def setup_config_argparse(p...
easywrk/cli.py
import sys import argparse from argparse import ArgumentParser import logging import easywrk from easywrk.commands import help_command, request_command, run_command, view_config_command from easywrk.commands import list_command, init_command from easywrk.commands import register_cmd_help def setup_config_argparse(p...
0.299822
0.07333
import itertools from collections import UserDict from operator import itemgetter from typing import Dict, Iterator, Set, Tuple, TypeVar, Union, cast from pyproj import Proj, Transformer from shapely.geometry import LineString, MultiLineString, MultiPolygon, Polygon from shapely.geometry.base import BaseGeometry from ...
cartes/osm/overpass/relations/boundary.py
import itertools from collections import UserDict from operator import itemgetter from typing import Dict, Iterator, Set, Tuple, TypeVar, Union, cast from pyproj import Proj, Transformer from shapely.geometry import LineString, MultiLineString, MultiPolygon, Polygon from shapely.geometry.base import BaseGeometry from ...
0.814164
0.308047
if __name__ == "__main__": from sys import path path.append('webapi') # Load .flaskenv from os.path import isfile if isfile('.flaskenv'): from libs.basics.system import load_export_file load_export_file('.flaskenv') # Pre-load config from libs.config import Config confi...
src/webapi.py
if __name__ == "__main__": from sys import path path.append('webapi') # Load .flaskenv from os.path import isfile if isfile('.flaskenv'): from libs.basics.system import load_export_file load_export_file('.flaskenv') # Pre-load config from libs.config import Config confi...
0.224225
0.04736
# COMMAND ---------- # DBTITLE 1,Create Database # MAGIC %sql # MAGIC CREATE DATABASE IF NOT EXISTS dvd_objects # COMMAND ---------- import pyspark from pyspark.sql.functions import to_date, col #LOAD CSV FILE - INCLUDES 5M ROWS actor = (spark.read.format('csv') .option('header', 'True') .op...
src/Utils/Create DVD Database.py
# COMMAND ---------- # DBTITLE 1,Create Database # MAGIC %sql # MAGIC CREATE DATABASE IF NOT EXISTS dvd_objects # COMMAND ---------- import pyspark from pyspark.sql.functions import to_date, col #LOAD CSV FILE - INCLUDES 5M ROWS actor = (spark.read.format('csv') .option('header', 'True') .op...
0.35031
0.082254
from string import ascii_letters import numpy as np from dataclasses import dataclass, field from crossover import single_point from mutate import exchange2 from selection import roulette_wheel CHAR_VOCAB = np.array(list(ascii_letters)) TARGET = "Hello World" TARGET_LIST = list(TARGET) TARGET_INDICES = np.array([TAR...
src/pythogen/main.py
from string import ascii_letters import numpy as np from dataclasses import dataclass, field from crossover import single_point from mutate import exchange2 from selection import roulette_wheel CHAR_VOCAB = np.array(list(ascii_letters)) TARGET = "Hello World" TARGET_LIST = list(TARGET) TARGET_INDICES = np.array([TAR...
0.738009
0.4133
from __future__ import division from typing import Dict, List, Set, Any import os import shutil import subprocess from collections import defaultdict import flye.utils.fasta_parser as fp from bioclass.sam import GeneralSamFile class RgNode(object): __slots__ = ("in_edges", "out_edges") def __init__(self):...
flye/repeat_graph/repeat_graph.py
from __future__ import division from typing import Dict, List, Set, Any import os import shutil import subprocess from collections import defaultdict import flye.utils.fasta_parser as fp from bioclass.sam import GeneralSamFile class RgNode(object): __slots__ = ("in_edges", "out_edges") def __init__(self):...
0.586523
0.240173
# Modules import os import argparse from collections import defaultdict from Bio import SeqIO import numpy as np from hivwholeseq.datasets import MiSeq_runs from hivwholeseq.sequencing.filenames import get_consensus_filename, get_merged_consensus_filename, \ get_consensi_alignment_dataset_filename from hivwhol...
hivwholeseq/sequencing/align_consensi_dataset.py
# Modules import os import argparse from collections import defaultdict from Bio import SeqIO import numpy as np from hivwholeseq.datasets import MiSeq_runs from hivwholeseq.sequencing.filenames import get_consensus_filename, get_merged_consensus_filename, \ get_consensi_alignment_dataset_filename from hivwhol...
0.294519
0.206954
from pysignfe.xml_sped import * from pysignfe.nfe.manual_500 import ESQUEMA_ATUAL from .evento_base import DetEvento, InfEventoEnviado, Evento, EnvEvento, InfEventoRecebido, RetEvento, RetEnvEvento, ProcEventoNFe import os DIRNAME = os.path.dirname(__file__) CONDICAO_USO = u'A Carta de Correcao e disciplinada pelo ...
gestaoemp/lib/python3.6/site-packages/pysignfe/nfe/manual_500/carta_correcao.py
from pysignfe.xml_sped import * from pysignfe.nfe.manual_500 import ESQUEMA_ATUAL from .evento_base import DetEvento, InfEventoEnviado, Evento, EnvEvento, InfEventoRecebido, RetEvento, RetEnvEvento, ProcEventoNFe import os DIRNAME = os.path.dirname(__file__) CONDICAO_USO = u'A Carta de Correcao e disciplinada pelo ...
0.334481
0.115811
import pandas as pd from pgmpy.estimators import BayesianEstimator from pgmpy.models import BayesianModel from pomegranate.BayesianNetwork import BayesianNetwork from pomegranate.base import State from pomegranate.distributions.ConditionalProbabilityTable import ConditionalProbabilityTable from pomegranate.distribution...
peepo/playground/baby_in_crib/model.py
import pandas as pd from pgmpy.estimators import BayesianEstimator from pgmpy.models import BayesianModel from pomegranate.BayesianNetwork import BayesianNetwork from pomegranate.base import State from pomegranate.distributions.ConditionalProbabilityTable import ConditionalProbabilityTable from pomegranate.distribution...
0.712332
0.436382
import argparse import json import logging import os import shlex import shutil import sys # Hardcoded configuration values JAVA_LAST_KIOSK_LOG = "/tmp/java-last-kiosk.log" # Parse CLI arguments parser = argparse.ArgumentParser(description='JavaFX Last Kiosk Launcher', allow_abbrev=False) parser.add_argument('-d', '-...
base/resources/java/java-last-kiosk.py
import argparse import json import logging import os import shlex import shutil import sys # Hardcoded configuration values JAVA_LAST_KIOSK_LOG = "/tmp/java-last-kiosk.log" # Parse CLI arguments parser = argparse.ArgumentParser(description='JavaFX Last Kiosk Launcher', allow_abbrev=False) parser.add_argument('-d', '-...
0.354657
0.045205
from torch.autograd import Variable import torch from .module import Module from .container import Sequential from .activation import LogSoftmax from .. import functional as F def _assert_no_grad(variable): assert not variable.requires_grad, \ "nn criterions don't compute the gradient w.r.t. targets - ple...
torch/nn/modules/loss.py
from torch.autograd import Variable import torch from .module import Module from .container import Sequential from .activation import LogSoftmax from .. import functional as F def _assert_no_grad(variable): assert not variable.requires_grad, \ "nn criterions don't compute the gradient w.r.t. targets - ple...
0.968812
0.734381
from itertools import combinations from string import ascii_letters import editdistance from gensim.models import KeyedVectors from tqdm import tqdm class CodeMaster: ''' A robo code master in the Codenames game ''' def __init__(self, red_words, blue_words, bad_words, model=None, word_pairs=None): s...
src/code_master.py
from itertools import combinations from string import ascii_letters import editdistance from gensim.models import KeyedVectors from tqdm import tqdm class CodeMaster: ''' A robo code master in the Codenames game ''' def __init__(self, red_words, blue_words, bad_words, model=None, word_pairs=None): s...
0.576542
0.203609
import sys from PyQt5.QtCore import Qt from PyQt5.QtWidgets import (QWidget, QApplication, QFrame, QVBoxLayout, QSplitter, QDesktopWidget) from .params import Params from .introduction import Introduction from .type_of_task import TypeOfTask from .set_file import SetFile from .dat...
malss/app/app.py
import sys from PyQt5.QtCore import Qt from PyQt5.QtWidgets import (QWidget, QApplication, QFrame, QVBoxLayout, QSplitter, QDesktopWidget) from .params import Params from .introduction import Introduction from .type_of_task import TypeOfTask from .set_file import SetFile from .dat...
0.38943
0.241434
import os import sys """ Test 72 transform, if transformed data by old transformer is the same in tf2 and tf1 Conclusion: It is the same """ PROJECT_PATH = os.path.abspath( os.path.join(os.path.dirname(__file__), '..')) sys.path.append(PROJECT_PATH) import matplotlib; matplotlib.use('agg') import pandas as pd ...
tests/test_72_transformation_transformed_data_tf1.py
import os import sys """ Test 72 transform, if transformed data by old transformer is the same in tf2 and tf1 Conclusion: It is the same """ PROJECT_PATH = os.path.abspath( os.path.join(os.path.dirname(__file__), '..')) sys.path.append(PROJECT_PATH) import matplotlib; matplotlib.use('agg') import pandas as pd ...
0.417865
0.402862
from __future__ import annotations from typing import Any, Generic, List, Optional, TypeVar import jax import jax.numpy as jnp from jax.nn import softplus from jax.scipy import special as jss from tjax import Generator, RealArray, Shape from tjax.dataclasses import dataclass from ..exp_to_nat import ExpToNat from .....
efax/_src/distributions/dirichlet_common.py
from __future__ import annotations from typing import Any, Generic, List, Optional, TypeVar import jax import jax.numpy as jnp from jax.nn import softplus from jax.scipy import special as jss from tjax import Generator, RealArray, Shape from tjax.dataclasses import dataclass from ..exp_to_nat import ExpToNat from .....
0.905669
0.371479
import PySimpleGUI as sg import asyncio import os import sys import time from collections import deque import driver delay_start = None gra_ids = deque() async def connect(tc: driver.Thermocycler): await tc.connect(port='/dev/ttyACM0') async def open_lid(tc: driver.Thermocycler): await tc.open() async def ...
pcr_gui.py
import PySimpleGUI as sg import asyncio import os import sys import time from collections import deque import driver delay_start = None gra_ids = deque() async def connect(tc: driver.Thermocycler): await tc.connect(port='/dev/ttyACM0') async def open_lid(tc: driver.Thermocycler): await tc.open() async def ...
0.165492
0.136608
import functools import re from typing import ( List, Union ) from net_models.models.BaseModels.SharedModels import VRFAddressFamily, VRFModel from net_parser.config import BaseConfigLine class IosConfigLine(BaseConfigLine): def __init__(self, number: int, text: str, config, verbosity: int, name: str...
net_parser/config/IosSectionParsers.py
import functools import re from typing import ( List, Union ) from net_models.models.BaseModels.SharedModels import VRFAddressFamily, VRFModel from net_parser.config import BaseConfigLine class IosConfigLine(BaseConfigLine): def __init__(self, number: int, text: str, config, verbosity: int, name: str...
0.616243
0.069827
import torch from tqdm.auto import tqdm import numpy as np from .random import sample_best_distributed, sample_best_distributed_pointwise from ..losses import Chamfer class ShapeSampler: def __init__(self, method = "random", N = 5): if (method not in ["random", "kmeans++", "template", "fir...
dlm/utils/shape_sampler.py
import torch from tqdm.auto import tqdm import numpy as np from .random import sample_best_distributed, sample_best_distributed_pointwise from ..losses import Chamfer class ShapeSampler: def __init__(self, method = "random", N = 5): if (method not in ["random", "kmeans++", "template", "fir...
0.531453
0.456834
from thrift.Thrift import TType, TMessageType, TException, TApplicationException from thrift.transport import TTransport from thrift.protocol import TBinaryProtocol, TProtocol try: from thrift.protocol import fastbinary except: fastbinary = None class AuthenticationLoginRequest: """ Attributes: - user_n...
jet-python/build/lib.linux-x86_64-2.7/jnpr/jet/authentication/ttypes.py
from thrift.Thrift import TType, TMessageType, TException, TApplicationException from thrift.transport import TTransport from thrift.protocol import TBinaryProtocol, TProtocol try: from thrift.protocol import fastbinary except: fastbinary = None class AuthenticationLoginRequest: """ Attributes: - user_n...
0.406273
0.08772
from collections import OrderedDict import six from pyangbind.lib.base import PybindBase from pyangbind.lib.yangtypes import YANGDynClass # PY3 support of some PY2 keywords (needs improved) if six.PY3: import builtins as __builtin__ long = int elif six.PY2: import __builtin__ class supported_bandwidth(...
grpc/rbindings/node/port/available_transceiver/supported_bandwidth/__init__.py
from collections import OrderedDict import six from pyangbind.lib.base import PybindBase from pyangbind.lib.yangtypes import YANGDynClass # PY3 support of some PY2 keywords (needs improved) if six.PY3: import builtins as __builtin__ long = int elif six.PY2: import __builtin__ class supported_bandwidth(...
0.721056
0.089733
import numpy as np import cv2 import os import pandas as pd import torch from torchvision import transforms class CardImageDataset(): def __init__(self, root_dir='../data', header_file='gicsd_labels.csv', image_dir='images'): ''' root_dir: location of the dataset dir header_file: location...
code/Dataset.py
import numpy as np import cv2 import os import pandas as pd import torch from torchvision import transforms class CardImageDataset(): def __init__(self, root_dir='../data', header_file='gicsd_labels.csv', image_dir='images'): ''' root_dir: location of the dataset dir header_file: location...
0.63477
0.397529
import demistomock as demisto # noqa import ExpanseEnrichAttribution CURRENT_IP = [ {"ip": "1.1.1.1", "attr1": "value1"}, {"ip": "8.8.8.8", "attr1": "value2"}, ] ENRICH_IP = [ {"ipaddress": "1.1.1.1", "provider": "Cloudflare", "ignored": "ignored-right"}, {"ipaddress": "8.8.8.4", "provider": "Googl...
Packs/ExpanseV2/Scripts/ExpanseEnrichAttribution/ExpanseEnrichAttribution_test.py
import demistomock as demisto # noqa import ExpanseEnrichAttribution CURRENT_IP = [ {"ip": "1.1.1.1", "attr1": "value1"}, {"ip": "8.8.8.8", "attr1": "value2"}, ] ENRICH_IP = [ {"ipaddress": "1.1.1.1", "provider": "Cloudflare", "ignored": "ignored-right"}, {"ipaddress": "8.8.8.4", "provider": "Googl...
0.46393
0.434701
import click, pkg_resources, os def fileType(ctx, param, value): if not value or ctx.resilient_parsing: return value if not isinstance(ctx.obj, dict): ctx.obj = dict() if str(param)[-2] == 'l': ctx.obj['filetype'] = str(param)[-4:-1] else: ctx.obj['filetype'] = str(pa...
prog/commands.py
import click, pkg_resources, os def fileType(ctx, param, value): if not value or ctx.resilient_parsing: return value if not isinstance(ctx.obj, dict): ctx.obj = dict() if str(param)[-2] == 'l': ctx.obj['filetype'] = str(param)[-4:-1] else: ctx.obj['filetype'] = str(pa...
0.231354
0.085862
import calendar import os import signal import subprocess import sys import time import deimos.cleanup import deimos.config import deimos.containerizer import deimos.containerizer.docker from deimos.err import Err import deimos.flock from deimos.logger import log import deimos.sig import deimos.usage def cli(argv=No...
deimos/__init__.py
import calendar import os import signal import subprocess import sys import time import deimos.cleanup import deimos.config import deimos.containerizer import deimos.containerizer.docker from deimos.err import Err import deimos.flock from deimos.logger import log import deimos.sig import deimos.usage def cli(argv=No...
0.28577
0.117243
import os import time from modules.findlorf_main import findlorf_main from modules.transfix_main import transfix_main from modules.transfeat_main import transfeat_main from lib.parsing.gtf_parsing_tools import filter_gtf_file, add_features_to_gtf def file_exist(outfile, skip_message=True): if os.path.exists(outf...
modules/auto_main.py
import os import time from modules.findlorf_main import findlorf_main from modules.transfix_main import transfix_main from modules.transfeat_main import transfeat_main from lib.parsing.gtf_parsing_tools import filter_gtf_file, add_features_to_gtf def file_exist(outfile, skip_message=True): if os.path.exists(outf...
0.274254
0.090213
from collections import OrderedDict import logging from pyidf.helper import DataObject logger = logging.getLogger("pyidf") logger.addHandler(logging.NullHandler()) class EnergyManagementSystemSensor(DataObject): """ Corresponds to IDD object `EnergyManagementSystem:Sensor` Declares EMS variable as a se...
pyidf/energy_management_system.py
from collections import OrderedDict import logging from pyidf.helper import DataObject logger = logging.getLogger("pyidf") logger.addHandler(logging.NullHandler()) class EnergyManagementSystemSensor(DataObject): """ Corresponds to IDD object `EnergyManagementSystem:Sensor` Declares EMS variable as a se...
0.840423
0.250042
import sys import weakref import operator from random import randint from array import array from .base import ( lib, ffi, NULL, NoValue, _check, _build_range, _get_select_op, _get_bin_op, ) from . import types, binaryop, monoid, unaryop from .vector import Vector from .scalar import S...
pygraphblas/matrix.py
import sys import weakref import operator from random import randint from array import array from .base import ( lib, ffi, NULL, NoValue, _check, _build_range, _get_select_op, _get_bin_op, ) from . import types, binaryop, monoid, unaryop from .vector import Vector from .scalar import S...
0.599368
0.328408
from __future__ import absolute_import import HLL class Counter(object): def __init__(self, op): self.__op = op self._value = None @property def op(self): return self.__op @property def value(self): return self._value def append(self, raw): raise NotI...
vcc/counters.py
from __future__ import absolute_import import HLL class Counter(object): def __init__(self, op): self.__op = op self._value = None @property def op(self): return self.__op @property def value(self): return self._value def append(self, raw): raise NotI...
0.679604
0.160135
import numpy from discrete_fuzzy_operators.base.operators.binary_operators.suboperators.fuzzy_aggregation_operator import \ DiscreteFuzzyAggregationBinaryOperator from typing import Callable, Dict class Uninorm(DiscreteFuzzyAggregationBinaryOperator): def __init__(self, n: int, e: int, oper...
discrete_fuzzy_operators/base/operators/binary_operators/suboperators/fuzzy_aggregation_suboperators/uninorm.py
import numpy from discrete_fuzzy_operators.base.operators.binary_operators.suboperators.fuzzy_aggregation_operator import \ DiscreteFuzzyAggregationBinaryOperator from typing import Callable, Dict class Uninorm(DiscreteFuzzyAggregationBinaryOperator): def __init__(self, n: int, e: int, oper...
0.899539
0.728555
from dataclasses import dataclass, is_dataclass, asdict from typing import Callable, List, Union # noinspection PyUnreachableCode if False: # noinspection PyUnresolvedReferences from _stubs import * from ..EditorExt import Editor ext.editor = Editor(None) iop.hostedComp = COMP() @dataclass class ToolContext: to...
rack/editor/components/EditorToolsExt.py
from dataclasses import dataclass, is_dataclass, asdict from typing import Callable, List, Union # noinspection PyUnreachableCode if False: # noinspection PyUnresolvedReferences from _stubs import * from ..EditorExt import Editor ext.editor = Editor(None) iop.hostedComp = COMP() @dataclass class ToolContext: to...
0.668447
0.085175
from heat.common.i18n import _ from heat.engine import attributes from heat.engine import constraints from heat.engine import properties from heat.engine.resources.openstack.neutron import neutron from oslo_log import log as logging import neutronclient.common.exceptions as neutron_exp LOG = logging.getLogger(__nam...
heat/engine/resources/wr/neutron_provider_net_range.py
from heat.common.i18n import _ from heat.engine import attributes from heat.engine import constraints from heat.engine import properties from heat.engine.resources.openstack.neutron import neutron from oslo_log import log as logging import neutronclient.common.exceptions as neutron_exp LOG = logging.getLogger(__nam...
0.713132
0.192881
from flask_restful import Resource, marshal, fields, reqparse from app import auth from app.models import PatientMeal # Viewed from patient details meal_by_patient_fields = { 'id': fields.Integer, 'label': fields.String, 'quantity': fields.Integer, 'uri': fields.Url('meal_list_by_patient'), 'meal':...
app/resources/patient_meal.py
from flask_restful import Resource, marshal, fields, reqparse from app import auth from app.models import PatientMeal # Viewed from patient details meal_by_patient_fields = { 'id': fields.Integer, 'label': fields.String, 'quantity': fields.Integer, 'uri': fields.Url('meal_list_by_patient'), 'meal':...
0.589953
0.113629
import dectate import morepath from morepath.error import ConflictError import pytest from webtest import TestApp as Client def test_settings_property(): class App(morepath.App): pass @App.setting("foo", "bar") def get_foo_setting(): return "bar" dectate.commit(App) app = App() ...
morepath/tests/test_setting_directive.py
import dectate import morepath from morepath.error import ConflictError import pytest from webtest import TestApp as Client def test_settings_property(): class App(morepath.App): pass @App.setting("foo", "bar") def get_foo_setting(): return "bar" dectate.commit(App) app = App() ...
0.683208
0.311505
from __future__ import absolute_import, division, print_function import os import re from collections import OrderedDict from ..defs import (task_name_sep, task_state_to_int, task_int_to_state) from ...util import option_list from ...io import findfile from .base import (BaseTask, task_classes) from desiutil.lo...
py/desispec/pipeline/tasks/preproc.py
from __future__ import absolute_import, division, print_function import os import re from collections import OrderedDict from ..defs import (task_name_sep, task_state_to_int, task_int_to_state) from ...util import option_list from ...io import findfile from .base import (BaseTask, task_classes) from desiutil.lo...
0.495606
0.139162
import numpy as np #This class contains all the default parameters for DynaPhoPy class Parameters: def __init__(self, #General silent=False, #Projections reduced_q_vector=(0, 0, 0), # default reduced wave vector #Maximum Entr...
dynaphopy/classes/parameters.py
import numpy as np #This class contains all the default parameters for DynaPhoPy class Parameters: def __init__(self, #General silent=False, #Projections reduced_q_vector=(0, 0, 0), # default reduced wave vector #Maximum Entr...
0.886224
0.518302
######################################################################### ## Customize your APP title, subtitle and menus here ######################################################################### #response.title = ' '.join(word.capitalize() for word in request.application.split('_')) #response.subtitle = T...
models/menu.py
######################################################################### ## Customize your APP title, subtitle and menus here ######################################################################### #response.title = ' '.join(word.capitalize() for word in request.application.split('_')) #response.subtitle = T...
0.172381
0.127816
from __future__ import annotations import tempfile from pathlib import Path from typing import List, Set, Dict, Generator, Tuple import pandas as pd from Bio import SeqIO from Bio.SeqRecord import SeqRecord from pybedtools import BedTool from genomics_data_index.storage.model import NUCLEOTIDE_UNKNOWN, NUCLEOTIDE_UN...
genomics_data_index/storage/MaskedGenomicRegions.py
from __future__ import annotations import tempfile from pathlib import Path from typing import List, Set, Dict, Generator, Tuple import pandas as pd from Bio import SeqIO from Bio.SeqRecord import SeqRecord from pybedtools import BedTool from genomics_data_index.storage.model import NUCLEOTIDE_UNKNOWN, NUCLEOTIDE_UN...
0.886868
0.516656
import floppyforms.__future__ as forms from django.utils.translation import ugettext_lazy as _ from django_backend.forms import FilterForm from django_backend.forms import SearchFilterFormMixin from django_backend.backend.base.backends import ModelBackend from django_backend.backend.columns import BackendColumn from dj...
examples/simple_blog/project/blog/backend.py
import floppyforms.__future__ as forms from django.utils.translation import ugettext_lazy as _ from django_backend.forms import FilterForm from django_backend.forms import SearchFilterFormMixin from django_backend.backend.base.backends import ModelBackend from django_backend.backend.columns import BackendColumn from dj...
0.539226
0.098903
import pytest from boto3.dynamodb.conditions import Attr from pcluster.aws.dynamo import DynamoResource @pytest.fixture() def mocked_dynamo_table(mocker): mock_table = mocker.MagicMock(autospec=True) mock_dynamo_resource = mocker.patch("boto3.resource") mock_dynamo_resource.return_value.Table.return_val...
cli/tests/pcluster/aws/test_dynamo.py
import pytest from boto3.dynamodb.conditions import Attr from pcluster.aws.dynamo import DynamoResource @pytest.fixture() def mocked_dynamo_table(mocker): mock_table = mocker.MagicMock(autospec=True) mock_dynamo_resource = mocker.patch("boto3.resource") mock_dynamo_resource.return_value.Table.return_val...
0.475605
0.346541
import torch.nn as nn import numpy as np FAIRFACE_AE_N_UPSAMPLING_EXTRA = {1: 1, 2: 1, 3: 2, 4: 2, 5: 3, 6: 5, 7: 5} class ResnetBlock(nn.Module): """Define a Resnet block""" def __init__(self, dim, padding_type, norm_layer, use_dropout, use_bias): """Initialize the Resnet block A r...
public/reconstruction/AEs.py
import torch.nn as nn import numpy as np FAIRFACE_AE_N_UPSAMPLING_EXTRA = {1: 1, 2: 1, 3: 2, 4: 2, 5: 3, 6: 5, 7: 5} class ResnetBlock(nn.Module): """Define a Resnet block""" def __init__(self, dim, padding_type, norm_layer, use_dropout, use_bias): """Initialize the Resnet block A r...
0.904445
0.551332
import pytest from flask import session def test_login(client, auth): with client: # test that successful login redirects to the index page response = auth.login() # login request set the user_id in the session # check that the user is loaded from the session assert respo...
tests/test_auth.py
import pytest from flask import session def test_login(client, auth): with client: # test that successful login redirects to the index page response = auth.login() # login request set the user_id in the session # check that the user is loaded from the session assert respo...
0.332419
0.324342
import json import ssl import urllib.request # ugly fix the ssl certificate bug ssl._create_default_https_context = ssl._create_unverified_context # ╔╗ ╦ ╔╦╗ ╔═╗ ╔╦╗ ╔═╗ ╔╦╗ ╔═╗ # ╠╩╗ ║ ║ ╚═╗ ║ ╠═╣ ║║║ ╠═╝ # ╚═╝ ╩ ╩ ╚═╝ ╩ ╩ ╩ ╩ ╩ ╩ raw_bitstamp_pairs = ["btcusd", "btceur", "eurusd", "x...
get_pairs_name.py
import json import ssl import urllib.request # ugly fix the ssl certificate bug ssl._create_default_https_context = ssl._create_unverified_context # ╔╗ ╦ ╔╦╗ ╔═╗ ╔╦╗ ╔═╗ ╔╦╗ ╔═╗ # ╠╩╗ ║ ║ ╚═╗ ║ ╠═╣ ║║║ ╠═╝ # ╚═╝ ╩ ╩ ╚═╝ ╩ ╩ ╩ ╩ ╩ ╩ raw_bitstamp_pairs = ["btcusd", "btceur", "eurusd", "x...
0.303732
0.199035
import os import glob import argparse import oneflow as flow import transforms.spatial_transforms as ST from image import * from model import CSRNet parser = argparse.ArgumentParser(description='Oneflow CSRNet') parser.add_argument('modelPath', metavar='MODELPATH',type=str, help='path to ...
CSRNet/val.py
import os import glob import argparse import oneflow as flow import transforms.spatial_transforms as ST from image import * from model import CSRNet parser = argparse.ArgumentParser(description='Oneflow CSRNet') parser.add_argument('modelPath', metavar='MODELPATH',type=str, help='path to ...
0.218503
0.227448
from typing import Any, Callable, Optional, Tuple from _sysrepo import ffi, lib from .util import c2str # ------------------------------------------------------------------------------ class SysrepoError(Exception): rc = None __slots__ = ("msg",) def __init__(self, msg: str): super().__init__(...
sysrepo/errors.py
from typing import Any, Callable, Optional, Tuple from _sysrepo import ffi, lib from .util import c2str # ------------------------------------------------------------------------------ class SysrepoError(Exception): rc = None __slots__ = ("msg",) def __init__(self, msg: str): super().__init__(...
0.650356
0.085327
import logging import sys import ccxt import release_trader.webscaper as ws websites = [ # 'binance', # 'coinbase', "gateio", # 'kraken' ] logging.basicConfig( level=logging.INFO, ) log_formatter = logging.Formatter( "%(asctime)s [%(threadName)-12.12s] [%(levelname)-5.5s] %(message)s" ) roo...
src/release_trader/check_availability.py
import logging import sys import ccxt import release_trader.webscaper as ws websites = [ # 'binance', # 'coinbase', "gateio", # 'kraken' ] logging.basicConfig( level=logging.INFO, ) log_formatter = logging.Formatter( "%(asctime)s [%(threadName)-12.12s] [%(levelname)-5.5s] %(message)s" ) roo...
0.385143
0.141252
import csv import bz2 import pickle from hashlib import sha256 BASE58_ALPHABET = '123456789ABCDEFGHJKLMNPQRSTUVWXYZabcdefghijkmnopqrstuvwxyz' BASE58_ALPHABET_INDEX = {char: index for index, char in enumerate(BASE58_ALPHABET)} def hex_to_bytes(hexed): if len(hexed) & 1: hexed = '0' + hexed return byte...
csv_to_hash160_set.py
import csv import bz2 import pickle from hashlib import sha256 BASE58_ALPHABET = '123456789ABCDEFGHJKLMNPQRSTUVWXYZabcdefghijkmnopqrstuvwxyz' BASE58_ALPHABET_INDEX = {char: index for index, char in enumerate(BASE58_ALPHABET)} def hex_to_bytes(hexed): if len(hexed) & 1: hexed = '0' + hexed return byte...
0.350977
0.271234
import scipy as sp import matplotlib matplotlib.rcParams = matplotlib.rc_params_from_file('../../matplotlibrc') import matplotlib.pyplot as plt import numpy as np import math from discretelognorm import discretelognorm def reservation_wage(): m = 20 v = 200 N = 500 Wmax = 100 Wmin = 0 gamma = ...
Labs/PolicyFunctionIteration/plots.py
import scipy as sp import matplotlib matplotlib.rcParams = matplotlib.rc_params_from_file('../../matplotlibrc') import matplotlib.pyplot as plt import numpy as np import math from discretelognorm import discretelognorm def reservation_wage(): m = 20 v = 200 N = 500 Wmax = 100 Wmin = 0 gamma = ...
0.423458
0.598899
from typing import List from sqlmodel import Session, or_ from models.job import Job, JobCreate, JobRead, JobUpdate from models.user import User, UserSession from services.base import BaseService from helpers.exceptions import ApiException from repositories.job import JobRepository from repositories.user import UserRep...
services/job.py
from typing import List from sqlmodel import Session, or_ from models.job import Job, JobCreate, JobRead, JobUpdate from models.user import User, UserSession from services.base import BaseService from helpers.exceptions import ApiException from repositories.job import JobRepository from repositories.user import UserRep...
0.678327
0.158174
import os from flask import Flask from flask_sqlalchemy import SQLAlchemy from models import * from slack import WebClient from flask import request from datetime import datetime from sqlalchemy import create_engine app = Flask(__name__) db_url = os.environ.get('DB_URL') app.config['SQLALCHEMY_DATABASE_URI'] = db_url ...
app.py
import os from flask import Flask from flask_sqlalchemy import SQLAlchemy from models import * from slack import WebClient from flask import request from datetime import datetime from sqlalchemy import create_engine app = Flask(__name__) db_url = os.environ.get('DB_URL') app.config['SQLALCHEMY_DATABASE_URI'] = db_url ...
0.274935
0.043164
import numpy as np from baselines.ecbp.agents.buffer.lru_knn_combine import LRU_KNN_COMBINE from baselines.ecbp.agents.graph.model import * import tensorflow as tf from baselines.ecbp.agents.graph.build_graph_dueling import * from baselines import logger import copy class OnlineAgent(object): def __init__(self, m...
baselines/ecbp/agents/online_agent.py
import numpy as np from baselines.ecbp.agents.buffer.lru_knn_combine import LRU_KNN_COMBINE from baselines.ecbp.agents.graph.model import * import tensorflow as tf from baselines.ecbp.agents.graph.build_graph_dueling import * from baselines import logger import copy class OnlineAgent(object): def __init__(self, m...
0.416559
0.23579
import random import string import subprocess #Process commands import socket #Process socket data import pyfiglet import sys import os from subprocess import call def SplashScreen(): print(" . ) )") print(" ( (| .") print(" ) )\/ ( ( (") prin...
tools/pswf.py
import random import string import subprocess #Process commands import socket #Process socket data import pyfiglet import sys import os from subprocess import call def SplashScreen(): print(" . ) )") print(" ( (| .") print(" ) )\/ ( ( (") prin...
0.093388
0.058561
import time import struct from collections import namedtuple from mesh.generic.tdmaState import TDMAStatus from mesh.generic.cmdDict import CmdDict from mesh.generic.cmds import NodeCmds, PixhawkCmds, TDMACmds, PixhawkFCCmds from mesh.generic.commandMsg import CommandMsg from mesh.generic.navigation import convertLatLo...
python/unittests/testCmds.py
import time import struct from collections import namedtuple from mesh.generic.tdmaState import TDMAStatus from mesh.generic.cmdDict import CmdDict from mesh.generic.cmds import NodeCmds, PixhawkCmds, TDMACmds, PixhawkFCCmds from mesh.generic.commandMsg import CommandMsg from mesh.generic.navigation import convertLatLo...
0.134066
0.112308
import os.path import logging from typing import List, Optional from google.auth.transport.requests import Request from google.auth.exceptions import RefreshError from google.oauth2.credentials import Credentials from google_auth_oauthlib.flow import InstalledAppFlow from googleapiclient.discovery import build from ....
src/service/gcal/__init__.py
import os.path import logging from typing import List, Optional from google.auth.transport.requests import Request from google.auth.exceptions import RefreshError from google.oauth2.credentials import Credentials from google_auth_oauthlib.flow import InstalledAppFlow from googleapiclient.discovery import build from ....
0.698535
0.216032
import os from pathlib import Path from numba import cuda, jit import numpy as np os.chdir(Path.cwd().parent) from pahmc_ode_gpu import cuda_lib_dynamics os.chdir(Path.cwd()/'unit_tests') """Prepare data, as well as variables to be compared to.""" name = 'lorenz96' D = 200 M = 2000 X = np.random....
unit_tests/test-cuda_dynamics (lorenz96).py
import os from pathlib import Path from numba import cuda, jit import numpy as np os.chdir(Path.cwd().parent) from pahmc_ode_gpu import cuda_lib_dynamics os.chdir(Path.cwd()/'unit_tests') """Prepare data, as well as variables to be compared to.""" name = 'lorenz96' D = 200 M = 2000 X = np.random....
0.453988
0.398611
import csv import string from model import Model import numpy as np from progress.bar import Bar import util from datetime import datetime import codecs from lime.lime_tabular import LimeTabularExplainer class TimeModel(Model): model = 'time' def __init__(self, datapath=""): super().__init__('time', ...
linreg/time_model.py
import csv import string from model import Model import numpy as np from progress.bar import Bar import util from datetime import datetime import codecs from lime.lime_tabular import LimeTabularExplainer class TimeModel(Model): model = 'time' def __init__(self, datapath=""): super().__init__('time', ...
0.39129
0.404155
import hmac import hashlib import binascii import base64 import json from datetime import datetime key = "<KEY>" byte_key = binascii.unhexlify(key) # creates dictionary object def create_jwt(exp: int = 60 * 60 * 1000) -> dict: return { "header": { "alg": "HS256", ...
pyjwt.py
import hmac import hashlib import binascii import base64 import json from datetime import datetime key = "<KEY>" byte_key = binascii.unhexlify(key) # creates dictionary object def create_jwt(exp: int = 60 * 60 * 1000) -> dict: return { "header": { "alg": "HS256", ...
0.395951
0.144934
from django.shortcuts import get_object_or_404 from rest_framework import filters, permissions, status from rest_framework.decorators import action from rest_framework.pagination import PageNumberPagination from rest_framework.permissions import AllowAny, IsAdminUser, IsAuthenticated from rest_framework.response import...
api/views.py
from django.shortcuts import get_object_or_404 from rest_framework import filters, permissions, status from rest_framework.decorators import action from rest_framework.pagination import PageNumberPagination from rest_framework.permissions import AllowAny, IsAdminUser, IsAuthenticated from rest_framework.response import...
0.620392
0.077727
from sympy import * import sys sys.path.insert(1, '..') from tait_bryan_R_utils import * from rodrigues_R_utils import * from quaternion_R_utils import * px_1, py_1, pz_1 = symbols('px_1 py_1 pz_1') om_1, fi_1, ka_1 = symbols('om_1 fi_1 ka_1') #sx_1, sy_1, sz_1 = symbols('sx_1 sy_1 sz_1') #q0_1, q1_1, q2_1, q3_1 = sym...
codes/python-scripts/camera-metrics/metric_camera_coplanarity_tait_bryan_wc_jacobian.py
from sympy import * import sys sys.path.insert(1, '..') from tait_bryan_R_utils import * from rodrigues_R_utils import * from quaternion_R_utils import * px_1, py_1, pz_1 = symbols('px_1 py_1 pz_1') om_1, fi_1, ka_1 = symbols('om_1 fi_1 ka_1') #sx_1, sy_1, sz_1 = symbols('sx_1 sy_1 sz_1') #q0_1, q1_1, q2_1, q3_1 = sym...
0.320821
0.503967
from logging import getLogger import requests_cache from kivy.clock import Clock from naturtag.app import alert, get_app from naturtag.controllers import Controller from naturtag.inat_metadata import get_http_cache_size from naturtag.thumbnails import delete_thumbnails, get_thumbnail_cache_size logger = getLogger(__...
naturtag/controllers/cache_controller.py
from logging import getLogger import requests_cache from kivy.clock import Clock from naturtag.app import alert, get_app from naturtag.controllers import Controller from naturtag.inat_metadata import get_http_cache_size from naturtag.thumbnails import delete_thumbnails, get_thumbnail_cache_size logger = getLogger(__...
0.785966
0.053034
from azure.cli.core.commands.parameters import ( tags_type, get_enum_type, resource_group_name_type, get_location_type ) from azure.cli.core.commands.validators import ( get_default_location_from_resource_group, validate_file_or_dict ) from azext_healthcareapis.action import ( AddAccessPoli...
src/healthcareapis/azext_healthcareapis/generated/_params.py
from azure.cli.core.commands.parameters import ( tags_type, get_enum_type, resource_group_name_type, get_location_type ) from azure.cli.core.commands.validators import ( get_default_location_from_resource_group, validate_file_or_dict ) from azext_healthcareapis.action import ( AddAccessPoli...
0.627951
0.056288
from os import name from src.Types.TokenTypes import TokenTypes from src.Node import Node from src.SymbolTable import SymbolTable from src.Nodes.FuncArguments import FuncArguments from llvmlite import ir class FuncDeclaration(Node): def __init__(self, func_name, statements, args: FuncArguments): self.args ...
src/Nodes/FuncDeclaration.py
from os import name from src.Types.TokenTypes import TokenTypes from src.Node import Node from src.SymbolTable import SymbolTable from src.Nodes.FuncArguments import FuncArguments from llvmlite import ir class FuncDeclaration(Node): def __init__(self, func_name, statements, args: FuncArguments): self.args ...
0.400632
0.234385
import time from code_statistics import * imgurl = "https://ae01.alicdn.com/kf/U56b2fb24ff7b4e5fa05c5acf7d3d0318r.jpg" file_name = "day.html" if __name__ == "__main__": print(time.strftime("%Y-%m-%d %H:%M:%S", time.localtime()) + " [日]") time1 = time.strftime("%Y-%m-%d 00:00:00") # 开始时间 time2 = time.st...
day.py
import time from code_statistics import * imgurl = "https://ae01.alicdn.com/kf/U56b2fb24ff7b4e5fa05c5acf7d3d0318r.jpg" file_name = "day.html" if __name__ == "__main__": print(time.strftime("%Y-%m-%d %H:%M:%S", time.localtime()) + " [日]") time1 = time.strftime("%Y-%m-%d 00:00:00") # 开始时间 time2 = time.st...
0.125426
0.122418