code
stringlengths
2k
1.04M
repo_path
stringlengths
5
517
parsed_code
stringlengths
0
1.04M
quality_prob
float64
0.02
0.95
learning_prob
float64
0.02
0.93
from typing import List, Any, Union import torch from dlex.torch.utils.ops_utils import maybe_cuda from torch import LongTensor def pad_sequence( data: List[List[Any]], padding_value, max_len: int = None, output_tensor: bool = False, dim: int = 2): if dim == 3...
dlex/torch/utils/variable_length_tensor.py
from typing import List, Any, Union import torch from dlex.torch.utils.ops_utils import maybe_cuda from torch import LongTensor def pad_sequence( data: List[List[Any]], padding_value, max_len: int = None, output_tensor: bool = False, dim: int = 2): if dim == 3...
0.67822
0.421611
import numpy as np from sklearn.metrics import confusion_matrix def compute_score(y_test, y_pred, verbose=True): conf = confusion_matrix(y_test, y_pred, labels=[0,1]) TN, FP, FN, TP = conf.ravel() TPR = np.nan_to_num(round(TP / (TP + FN), 4)) SPC = np.nan_to_num(round(TN / (FP + TN), 4)) PPV = np....
python/irc_utils.py
import numpy as np from sklearn.metrics import confusion_matrix def compute_score(y_test, y_pred, verbose=True): conf = confusion_matrix(y_test, y_pred, labels=[0,1]) TN, FP, FN, TP = conf.ravel() TPR = np.nan_to_num(round(TP / (TP + FN), 4)) SPC = np.nan_to_num(round(TN / (FP + TN), 4)) PPV = np....
0.627267
0.547162
from __future__ import unicode_literals import pendulum locale = 'de' def test_diff_for_humans(): with pendulum.test(pendulum.datetime(2016, 8, 29)): diff_for_humans() def diff_for_humans(): d = pendulum.now().subtract(seconds=1) assert d.diff_for_humans(locale=locale) == 'vor 1 Sekunde' ...
tests/localization/test_de.py
from __future__ import unicode_literals import pendulum locale = 'de' def test_diff_for_humans(): with pendulum.test(pendulum.datetime(2016, 8, 29)): diff_for_humans() def diff_for_humans(): d = pendulum.now().subtract(seconds=1) assert d.diff_for_humans(locale=locale) == 'vor 1 Sekunde' ...
0.664867
0.698098
from maya import cmds from maya import mel import os, json import datetime as dt def formatPath(path): path = path.replace("/", os.sep) path = path.replace("\\", os.sep) return path mayaAppDir = formatPath(mel.eval('getenv MAYA_APP_DIR')) scriptsDir = formatPath(mayaAppDir + os.sep + 'scripts') projectD...
service/setup.py
from maya import cmds from maya import mel import os, json import datetime as dt def formatPath(path): path = path.replace("/", os.sep) path = path.replace("\\", os.sep) return path mayaAppDir = formatPath(mel.eval('getenv MAYA_APP_DIR')) scriptsDir = formatPath(mayaAppDir + os.sep + 'scripts') projectD...
0.116337
0.04888
from django.test import TestCase from cyder.cydhcp.vlan.models import Vlan from cyder.cydhcp.site.models import Site from cyder.cydhcp.range.models import Range from cyder.cydhcp.network.models import Network from cyder.cydhcp.interface.static_intr.models import StaticInterface from cyder.cydhcp.lib.utils import calc_...
cyder/cydhcp/lib/tests/free_ip.py
from django.test import TestCase from cyder.cydhcp.vlan.models import Vlan from cyder.cydhcp.site.models import Site from cyder.cydhcp.range.models import Range from cyder.cydhcp.network.models import Network from cyder.cydhcp.interface.static_intr.models import StaticInterface from cyder.cydhcp.lib.utils import calc_...
0.613468
0.272853
import os import unittest import pfnet as pf import numpy as np from . import test_cases from numpy.linalg import norm class TestBranches(unittest.TestCase): def setUp(self): # Random np.random.seed(0) def test_power_flow_utils(self): h = 1e-8 tol = 1e-5 eps = 1.0 #...
tests/test_branches.py
import os import unittest import pfnet as pf import numpy as np from . import test_cases from numpy.linalg import norm class TestBranches(unittest.TestCase): def setUp(self): # Random np.random.seed(0) def test_power_flow_utils(self): h = 1e-8 tol = 1e-5 eps = 1.0 #...
0.393968
0.358493
import argparse import torch import numpy as np import os # os.environ["CUDA_VISIBLE_DEVICES"] = "3,6" parser = argparse.ArgumentParser(description='PyTorch implementation of pre-training of graph neural networks') parser.add_argument('--device', type=int, default=0, help='which gpu to use if any ...
main_training.py
import argparse import torch import numpy as np import os # os.environ["CUDA_VISIBLE_DEVICES"] = "3,6" parser = argparse.ArgumentParser(description='PyTorch implementation of pre-training of graph neural networks') parser.add_argument('--device', type=int, default=0, help='which gpu to use if any ...
0.444565
0.0745
from matplotlib import cm from cicliminds_lib.utils import patch_config from cicliminds_lib.bindings import FLOAT_MISSING_VALUE from cicliminds_lib.bindings import nco_fldmean_from_data from cicliminds_lib.math import xr_weighted_median from cicliminds_lib.math import xr_weighted_quantile from cicliminds_lib.unify.mod...
cicliminds_lib/plotting/recipes/time_series.py
from matplotlib import cm from cicliminds_lib.utils import patch_config from cicliminds_lib.bindings import FLOAT_MISSING_VALUE from cicliminds_lib.bindings import nco_fldmean_from_data from cicliminds_lib.math import xr_weighted_median from cicliminds_lib.math import xr_weighted_quantile from cicliminds_lib.unify.mod...
0.709523
0.37419
from campy.graphics.gobjects import GOval, GRect, GLabel, GLine, GPolygon, GArc from campy.graphics.gwindow import GWindow def main(): """ TODO: """ window=GWindow(500,400,title='cute') #頭 head=GOval(200,180) head.filled =True head.fill_color='khaki' head.color='khaki' window.add(h...
StanCode_project/my_drawing/my_drawing.py
from campy.graphics.gobjects import GOval, GRect, GLabel, GLine, GPolygon, GArc from campy.graphics.gwindow import GWindow def main(): """ TODO: """ window=GWindow(500,400,title='cute') #頭 head=GOval(200,180) head.filled =True head.fill_color='khaki' head.color='khaki' window.add(h...
0.188548
0.182389
__author__ = '<NAME>' import models.mainmodel as model import models.dataio as dataio import models.abstractplugin as abstractplugin import models.config as config import models.ultrasonicgate as ultrasonicgate import controllers.pathfinder as pathfinder from utils.skiptest import skipIfModuleNotInstalled import h5py ...
models/tests/test_mainmodel.py
__author__ = '<NAME>' import models.mainmodel as model import models.dataio as dataio import models.abstractplugin as abstractplugin import models.config as config import models.ultrasonicgate as ultrasonicgate import controllers.pathfinder as pathfinder from utils.skiptest import skipIfModuleNotInstalled import h5py ...
0.533884
0.220867
from __future__ import annotations __all__ = ( "extract_codecs", "extract_codec_metadata", "extract_default_codec", "insert_default_codec", "EncodeFunction", "DecodeFunction", "Codec", ) from typing import ( cast, overload, final, Any, Type, TypeVar, Generic, ...
src/testplates/impl/base/codec.py
from __future__ import annotations __all__ = ( "extract_codecs", "extract_codec_metadata", "extract_default_codec", "insert_default_codec", "EncodeFunction", "DecodeFunction", "Codec", ) from typing import ( cast, overload, final, Any, Type, TypeVar, Generic, ...
0.870996
0.274753
import re __authors__ = """ <NAME> <<EMAIL>> <NAME> <<EMAIL>> """ ABBREVS = { ('Bl', '.', 'a', '.'): 'Bl.a.', ('Bl', 'a'): 'Bl.a', ('Bl.a', '.'): 'Bl.a.', ('D', 'v', 's'): 'D.v.s', ('Fr', 'o', 'm'): 'Fr.o.m', ('O', 's', 'v'): 'O.s.v', ('S', 'k'): 'S.k', ('T', '.', 'ex', '.'): 'T.ex.', ...
tokenizer.py
import re __authors__ = """ <NAME> <<EMAIL>> <NAME> <<EMAIL>> """ ABBREVS = { ('Bl', '.', 'a', '.'): 'Bl.a.', ('Bl', 'a'): 'Bl.a', ('Bl.a', '.'): 'Bl.a.', ('D', 'v', 's'): 'D.v.s', ('Fr', 'o', 'm'): 'Fr.o.m', ('O', 's', 'v'): 'O.s.v', ('S', 'k'): 'S.k', ('T', '.', 'ex', '.'): 'T.ex.', ...
0.511229
0.199055
from django.http import JsonResponse from django.views import View incoming_requests = { "incoming_requests": [ { "requestor": "<NAME>", "request": { "type": "HR044 - Leave Application", "id": "HR-015715" }, "history": [ { "date": "Monday 26 June 2017", ...
demo/src/wss_ui/site/fake_data_views/incoming_requests.py
from django.http import JsonResponse from django.views import View incoming_requests = { "incoming_requests": [ { "requestor": "<NAME>", "request": { "type": "HR044 - Leave Application", "id": "HR-015715" }, "history": [ { "date": "Monday 26 June 2017", ...
0.426083
0.276443
import numpy as np from wepy.util.util import box_vectors_to_lengths_angles from geomm.recentering import recenter_pair from geomm.superimpose import superimpose from geomm.rmsd import calc_rmsd from wepy.resampling.distances.distance import Distance class UnbindingDistance(Distance): def __init__(self, ligand_...
wepy/resampling/distances/receptor.py
import numpy as np from wepy.util.util import box_vectors_to_lengths_angles from geomm.recentering import recenter_pair from geomm.superimpose import superimpose from geomm.rmsd import calc_rmsd from wepy.resampling.distances.distance import Distance class UnbindingDistance(Distance): def __init__(self, ligand_...
0.666605
0.444324
# Copyright 2020-2022 Blue Brain Project / EPFL # Licensed under the Apache License, Version 2.0 (the "License"); # you may not use this file except in compliance with the License. # You may obtain a copy of the License at # http://www.apache.org/licenses/LICENSE-2.0 # Unless required by applicable law or agree...
emodelrunner/output.py
# Copyright 2020-2022 Blue Brain Project / EPFL # Licensed under the Apache License, Version 2.0 (the "License"); # you may not use this file except in compliance with the License. # You may obtain a copy of the License at # http://www.apache.org/licenses/LICENSE-2.0 # Unless required by applicable law or agree...
0.869659
0.359252
from ...utils.yaml import yaml from ...utils.collections import OrderedDict from .reader import Reader from .locator import Locator from .exceptions import ReaderSyntaxError from .locator import (LocatableString, LocatableInt, LocatableFloat) # YAML mapping tag MAP_TAG = u'tag:yaml.org,2002:map' # This is an intern...
aria/parser/reading/yaml.py
from ...utils.yaml import yaml from ...utils.collections import OrderedDict from .reader import Reader from .locator import Locator from .exceptions import ReaderSyntaxError from .locator import (LocatableString, LocatableInt, LocatableFloat) # YAML mapping tag MAP_TAG = u'tag:yaml.org,2002:map' # This is an intern...
0.533154
0.1692
import torch import torch.nn as nn import hdvw.models.alexnet_dnn_block as alexnet_dnn import hdvw.models.alexnet_mcdo_block as alexnet_mcdo import hdvw.models.smoothing_block as smoothing import hdvw.models.classifier_block as classifier class AlexNet(nn.Module): def __init__(self, block, sbloc...
hdvw/models/alexnet.py
import torch import torch.nn as nn import hdvw.models.alexnet_dnn_block as alexnet_dnn import hdvw.models.alexnet_mcdo_block as alexnet_mcdo import hdvw.models.smoothing_block as smoothing import hdvw.models.classifier_block as classifier class AlexNet(nn.Module): def __init__(self, block, sbloc...
0.896635
0.313026
import itertools import json import os import sys names = [ "language", "subset_uri", "fail_on_first_error", "provide_detailed_stack_trace", "check_uri_compliance", "check_completeness", "check_best_practices", "uri_prefix", "version", "insert_type", "test_equality", "return_file", "main_file_name", "diff_file_name",...
src/test/generate_test_cases.py
import itertools import json import os import sys names = [ "language", "subset_uri", "fail_on_first_error", "provide_detailed_stack_trace", "check_uri_compliance", "check_completeness", "check_best_practices", "uri_prefix", "version", "insert_type", "test_equality", "return_file", "main_file_name", "diff_file_name",...
0.164014
0.200734
# Copyright 2019 The Chromium Authors. All rights reserved. # Use of this source code is governed by a BSD-style license that can be # found in the LICENSE file. """ Install Debian sysroots for cross compiling Open Screen. """ # The sysroot is needed to ensure that binaries that get built will run on # the oldest st...
build/scripts/install-sysroot.py
# Copyright 2019 The Chromium Authors. All rights reserved. # Use of this source code is governed by a BSD-style license that can be # found in the LICENSE file. """ Install Debian sysroots for cross compiling Open Screen. """ # The sysroot is needed to ensure that binaries that get built will run on # the oldest st...
0.596668
0.282689
from typing import Tuple, Union import torch from torchvision.transforms import ToTensor as ImageToTensor from data.transforms import ( MaskToTensor, DynamicSquareCrop, Resize, stabilized_padding, ) from data.Human36M.skeleton import JOINTS from data.Human36M.statistics import MEDIAN_PIXEL from geome...
data/Human36M/transform.py
from typing import Tuple, Union import torch from torchvision.transforms import ToTensor as ImageToTensor from data.transforms import ( MaskToTensor, DynamicSquareCrop, Resize, stabilized_padding, ) from data.Human36M.skeleton import JOINTS from data.Human36M.statistics import MEDIAN_PIXEL from geome...
0.863334
0.581362
from time import sleep import os import platform import pyASCIIgenerator # # # # # # # # # # # # # # INFO # # # # # # # # # # # # # # logofile = open('logo.txt', 'r') logolines = logofile.readlines() for line in logolines: print("{}".format(line.strip())) print('pyCMD by HYKANTUS')...
main.py
from time import sleep import os import platform import pyASCIIgenerator # # # # # # # # # # # # # # INFO # # # # # # # # # # # # # # logofile = open('logo.txt', 'r') logolines = logofile.readlines() for line in logolines: print("{}".format(line.strip())) print('pyCMD by HYKANTUS')...
0.051678
0.042404
from perf_tools import histogram_metric from telemetry.page import page_measurement MEMORY_HISTOGRAMS = [ {'name': 'V8.MemoryExternalFragmentationTotal', 'units': 'percent'}, {'name': 'V8.MemoryHeapSampleTotalCommitted', 'units': 'kb'}, {'name': 'V8.MemoryHeapSampleTotalUsed', 'units': 'kb'}, {'name': ...
tools/perf/perf_tools/memory_measurement.py
from perf_tools import histogram_metric from telemetry.page import page_measurement MEMORY_HISTOGRAMS = [ {'name': 'V8.MemoryExternalFragmentationTotal', 'units': 'percent'}, {'name': 'V8.MemoryHeapSampleTotalCommitted', 'units': 'kb'}, {'name': 'V8.MemoryHeapSampleTotalUsed', 'units': 'kb'}, {'name': ...
0.672977
0.181118
import unittest import UserDict from cStringIO import StringIO from zope import interface from zope import component from zope import schema from zope.copypastemove.interfaces import IObjectCopier, IObjectMover from zope.location.traversing import LocationPhysicallyLocatable from zope.traversing.adapters import Traver...
src/z3c/dav/tests/test_copymove.py
import unittest import UserDict from cStringIO import StringIO from zope import interface from zope import component from zope import schema from zope.copypastemove.interfaces import IObjectCopier, IObjectMover from zope.location.traversing import LocationPhysicallyLocatable from zope.traversing.adapters import Traver...
0.505859
0.203925
import numpy as np import metriks def test_label_mrr_with_errors(): y_true = np.array([[0, 1, 1, 0], [1, 1, 1, 0], [0, 1, 1, 1]]) y_prob = np.array([[0.2, 0.9, 0.8, 0.4], [0.9, 0.2, 0.8, 0.4], [0.2, 0.8, 0.9, 0.4]]) ...
tests/test_label_mean_reciprocal_rank.py
import numpy as np import metriks def test_label_mrr_with_errors(): y_true = np.array([[0, 1, 1, 0], [1, 1, 1, 0], [0, 1, 1, 1]]) y_prob = np.array([[0.2, 0.9, 0.8, 0.4], [0.9, 0.2, 0.8, 0.4], [0.2, 0.8, 0.9, 0.4]]) ...
0.796767
0.700495
from bpy.types import Context, Operator from bpy.props import BoolProperty from typing import Set from .body_group import BodyGroup class MaleBody(Operator): """Add imvu mesh primitive male body parts to scene""" group = BodyGroup("male", [("head", "eyes", "brows", "lashes"), "torso", "hands", "legs", "calfs"...
src/ops/m_body.py
from bpy.types import Context, Operator from bpy.props import BoolProperty from typing import Set from .body_group import BodyGroup class MaleBody(Operator): """Add imvu mesh primitive male body parts to scene""" group = BodyGroup("male", [("head", "eyes", "brows", "lashes"), "torso", "hands", "legs", "calfs"...
0.902516
0.463687
import requests from plugins.oob import verify_request, gen_oob_domain # Vuln Base Info def info(): return { "author": "cckuailong", "name": '''Seagate BlackArmor NAS - Command Injection''', "description": '''Seagate BlackArmor NAS allows remote attackers to execute arbitrary code via the...
2014/CVE-2014-3206/poc/pocsploit/CVE-2014-3206.py
import requests from plugins.oob import verify_request, gen_oob_domain # Vuln Base Info def info(): return { "author": "cckuailong", "name": '''Seagate BlackArmor NAS - Command Injection''', "description": '''Seagate BlackArmor NAS allows remote attackers to execute arbitrary code via the...
0.213131
0.164987
import _kaldilm def arpa2fst(input_arpa: str, output_fst: str = '', bos_symbol: str = '<s>', disambig_symbol: str = '', eos_symbol: str = '</s>', ilabel_sort: bool = True, keep_symbols: bool = False, max_arpa_warnings: int = 3...
kaldilm/python/kaldilm/arpa2fst.py
import _kaldilm def arpa2fst(input_arpa: str, output_fst: str = '', bos_symbol: str = '<s>', disambig_symbol: str = '', eos_symbol: str = '</s>', ilabel_sort: bool = True, keep_symbols: bool = False, max_arpa_warnings: int = 3...
0.774583
0.286344
import re RUBY_SPEC_MATCHER = re.compile(r"_spec\.rb$") RUBY_SOUCE_MATCHER = re.compile(r"\.rb$") RUBY_SPECIAL_SPEC_MATCHER = re.compile(r"(\.erb|\.haml|\.slim|\.jbuilder)_spec\.rb$") RUBY_SPECIAL_SOURCE_MATCHER = re.compile(r"\.erb$|\.haml$|\.slim$|\.jbuilder$") JS_SPEC_MATCHER = re.compile(r"-test\.js$") PYTHON_SPEC...
resolver.py
import re RUBY_SPEC_MATCHER = re.compile(r"_spec\.rb$") RUBY_SOUCE_MATCHER = re.compile(r"\.rb$") RUBY_SPECIAL_SPEC_MATCHER = re.compile(r"(\.erb|\.haml|\.slim|\.jbuilder)_spec\.rb$") RUBY_SPECIAL_SOURCE_MATCHER = re.compile(r"\.erb$|\.haml$|\.slim$|\.jbuilder$") JS_SPEC_MATCHER = re.compile(r"-test\.js$") PYTHON_SPEC...
0.277669
0.115038
import os import errno import sys import traceback from time import sleep import unicodedata from config import patches_dir import git_tracker as git import svn_tracker as svn import tracker def start_git_revision_tracker(): print("Starting revision tracker...") iteration_count = 0 co...
app.py
import os import errno import sys import traceback from time import sleep import unicodedata from config import patches_dir import git_tracker as git import svn_tracker as svn import tracker def start_git_revision_tracker(): print("Starting revision tracker...") iteration_count = 0 co...
0.056953
0.060308
from __future__ import absolute_import import six import numpy as np import chainer from chainer.backends import cuda from chainer import function from chainer.utils import type_check from ..loss._helper import to_onehot class DiscreteJaccard(function.Function): """ Jaccard index NOTE: This is not a differen...
chainer_bcnn/functions/accuracy/discrete_jaccard.py
from __future__ import absolute_import import six import numpy as np import chainer from chainer.backends import cuda from chainer import function from chainer.utils import type_check from ..loss._helper import to_onehot class DiscreteJaccard(function.Function): """ Jaccard index NOTE: This is not a differen...
0.912204
0.328368
from manipulator import Manipulator import numpy as np class Transformer(Manipulator): def __init__(self,df,metadataO): metadata=metadataO.copy() metadata = super().metadata_verifier(df,metadata) tmp_metadata=self.remove_no_actions_per_type(metadata,'transformation') super().__init__(...
src/pyroar/transformation/transformation.py
from manipulator import Manipulator import numpy as np class Transformer(Manipulator): def __init__(self,df,metadataO): metadata=metadataO.copy() metadata = super().metadata_verifier(df,metadata) tmp_metadata=self.remove_no_actions_per_type(metadata,'transformation') super().__init__(...
0.558327
0.343617
import argparse import os import time import numpy as np import cv2 from pobalog.hp_bar_recognition import HPBarRecognition from pobalog.text_area_detection import TextAreaDetection from pobalog.whole_image_matching import WholeImageMatching def nothing(x): pass def run(video, screenshot_dir, engines): cap...
pobalog/frame_input.py
import argparse import os import time import numpy as np import cv2 from pobalog.hp_bar_recognition import HPBarRecognition from pobalog.text_area_detection import TextAreaDetection from pobalog.whole_image_matching import WholeImageMatching def nothing(x): pass def run(video, screenshot_dir, engines): cap...
0.343452
0.159774
import unittest import sys import random import os dirname, filename = os.path.split(os.path.abspath(__file__)) sys.path.append(dirname + '/..') from src import populations class TestPopulationGA(unittest.TestCase): @classmethod def setUpClass(cls): def of1(*vars): return vars[0] + vars...
unit_testing/test_populations_GA.py
import unittest import sys import random import os dirname, filename = os.path.split(os.path.abspath(__file__)) sys.path.append(dirname + '/..') from src import populations class TestPopulationGA(unittest.TestCase): @classmethod def setUpClass(cls): def of1(*vars): return vars[0] + vars...
0.30013
0.488283
import os import tempfile import unittest from telemetry.core import util from telemetry.page import page from telemetry.page import page_set from telemetry.util import cloud_storage class TestPageSet(unittest.TestCase): def testServingDirs(self): directory_path = tempfile.mkdtemp() try: ps = page_...
tools/telemetry/telemetry/page/page_set_unittest.py
import os import tempfile import unittest from telemetry.core import util from telemetry.page import page from telemetry.page import page_set from telemetry.util import cloud_storage class TestPageSet(unittest.TestCase): def testServingDirs(self): directory_path = tempfile.mkdtemp() try: ps = page_...
0.38341
0.241087
from __future__ import absolute_import import sys import os import re # python 2 and python 3 compatibility library from six import iteritems from ..configuration import Configuration from ..api_client import ApiClient class PackagesApi(object): """ NOTE: This class is auto generated by the swagger code ge...
bindings/python/src/cloudsmith_api/apis/packages_api.py
from __future__ import absolute_import import sys import os import re # python 2 and python 3 compatibility library from six import iteritems from ..configuration import Configuration from ..api_client import ApiClient class PackagesApi(object): """ NOTE: This class is auto generated by the swagger code ge...
0.650467
0.0538
from __future__ import annotations from typing import Any, Dict, List, Optional, Union from connect.processors_toolkit import find_by_id, merge from connect.processors_toolkit.requests.assets import AssetBuilder from connect.processors_toolkit.requests.helpers import make_param, request_model from connect.processors_...
connect/processors_toolkit/requests/__init__.py
from __future__ import annotations from typing import Any, Dict, List, Optional, Union from connect.processors_toolkit import find_by_id, merge from connect.processors_toolkit.requests.assets import AssetBuilder from connect.processors_toolkit.requests.helpers import make_param, request_model from connect.processors_...
0.925731
0.11129
import datetime import re import bs4 import aiohttp import isodate import colors import logger import plugin_api _logger = logger.LOGGER class Plugin(plugin_api.LocalPlugin): """Youtube plugin""" def help_msg(self): return "displays youtube uri title" @classmethod async def _parse_youtub...
bot_modules/py/youtube.py
import datetime import re import bs4 import aiohttp import isodate import colors import logger import plugin_api _logger = logger.LOGGER class Plugin(plugin_api.LocalPlugin): """Youtube plugin""" def help_msg(self): return "displays youtube uri title" @classmethod async def _parse_youtub...
0.454472
0.128498
import ctypes import functools from types import TracebackType from typing import Optional from typing import Type from typing import TYPE_CHECKING if TYPE_CHECKING: from pathlib import Path __all__ = ('OppaiWrapper',) class OppaiWrapper: """Lightweight wrapper around franc[e]sco's c89 oppai-ng library.""" ...
tests/oppai_wrapper.py
import ctypes import functools from types import TracebackType from typing import Optional from typing import Type from typing import TYPE_CHECKING if TYPE_CHECKING: from pathlib import Path __all__ = ('OppaiWrapper',) class OppaiWrapper: """Lightweight wrapper around franc[e]sco's c89 oppai-ng library.""" ...
0.809577
0.190536
from PySide2.QtWidgets import QWidget, QApplication, QTextEdit, QVBoxLayout, QPushButton from PySide2.QtCore import QEventLoop import sys import threading import asyncio from concurrent import futures import multiprocessing import time # Checking which blocks UI activity class MainWindow(QWidget): def __init__(...
Testbeds/asynchronousQtDemonstration.py
from PySide2.QtWidgets import QWidget, QApplication, QTextEdit, QVBoxLayout, QPushButton from PySide2.QtCore import QEventLoop import sys import threading import asyncio from concurrent import futures import multiprocessing import time # Checking which blocks UI activity class MainWindow(QWidget): def __init__(...
0.323166
0.082475
import scipy.sparse as sp from scipy.sparse import linalg import numpy as np import torch import torch.nn as nn from logging import getLogger from libcity.model.abstract_traffic_state_model import AbstractTrafficStateModel from libcity.model import loss def calculate_normalized_laplacian(adj): """ L = D^-1/2 ...
libcity/model/traffic_speed_prediction/DCRNN.py
import scipy.sparse as sp from scipy.sparse import linalg import numpy as np import torch import torch.nn as nn from logging import getLogger from libcity.model.abstract_traffic_state_model import AbstractTrafficStateModel from libcity.model import loss def calculate_normalized_laplacian(adj): """ L = D^-1/2 ...
0.825836
0.538619
from webob import Request, Response import sys, logging, threading, random, urllib2 log = logging.getLogger(__name__) def _make_test_app(test_op): def app(env, sr): req = Request(env) log.debug('starting test operation: %s', test_op) test_op(req) log.debug('done') r = Respo...
lib/WebOb-1.0.8/tests/test_in_wsgiref.py
from webob import Request, Response import sys, logging, threading, random, urllib2 log = logging.getLogger(__name__) def _make_test_app(test_op): def app(env, sr): req = Request(env) log.debug('starting test operation: %s', test_op) test_op(req) log.debug('done') r = Respo...
0.235021
0.134804
import os import sys import json import urllib.request from docopt import docopt args = docopt(__doc__) def get_datasets(): # Starting dataset retrieval print("\n\n##### get_datasets: Retrieving datasets") if verbose: print(f"Running get_dataset with arguments: \n {args}") assert input, "Empty input ...
src/get_datasets.py
import os import sys import json import urllib.request from docopt import docopt args = docopt(__doc__) def get_datasets(): # Starting dataset retrieval print("\n\n##### get_datasets: Retrieving datasets") if verbose: print(f"Running get_dataset with arguments: \n {args}") assert input, "Empty input ...
0.169784
0.23351
import itertools from flask import request from ggrc.models.cache import Cache from ggrc.models.event import Event from ggrc.models.revision import Revision from ggrc.login import get_current_user_id def _revision_generator(user_id, action, objects): for obj in objects: yield Revision(obj, user_id, action, ob...
src/ggrc/utils/log_event.py
import itertools from flask import request from ggrc.models.cache import Cache from ggrc.models.event import Event from ggrc.models.revision import Revision from ggrc.login import get_current_user_id def _revision_generator(user_id, action, objects): for obj in objects: yield Revision(obj, user_id, action, ob...
0.657868
0.067026
import gym import sonnet as snt import tensorflow as tf import numpy as np from ray.rllib.models.tf.tf_modelv2 import TFModelV2 def build_logits(action_space, latent_vec): if isinstance(action_space, gym.spaces.Discrete): return snt.Linear(output_size=action_space.n, initializers...
rllib/models/doom_nature_model.py
import gym import sonnet as snt import tensorflow as tf import numpy as np from ray.rllib.models.tf.tf_modelv2 import TFModelV2 def build_logits(action_space, latent_vec): if isinstance(action_space, gym.spaces.Discrete): return snt.Linear(output_size=action_space.n, initializers...
0.900319
0.428831
import argparse def str2bool(v): return v.lower() in ('true') def getParameters(): parser = argparse.ArgumentParser() # general parser.add_argument('--mode', type=str, default="test", choices=['train', 'finetune','test','debug']) parser.add_argument('--cuda', type=int, default=0) # training ...
parameters.py
import argparse def str2bool(v): return v.lower() in ('true') def getParameters(): parser = argparse.ArgumentParser() # general parser.add_argument('--mode', type=str, default="test", choices=['train', 'finetune','test','debug']) parser.add_argument('--cuda', type=int, default=0) # training ...
0.357792
0.073132
import pandas as pd import os import re from datapipeline.utils.loggers import Preprocessing_logger from datapipeline.utils.io import (load_data, write_preprocessed_data, create_file_object, file_object) from datapipeline.utils.copy import copy_csv def preprocess_c_trials (clinicalT): """ Descri...
src/datapipeline/preprocess/run.py
import pandas as pd import os import re from datapipeline.utils.loggers import Preprocessing_logger from datapipeline.utils.io import (load_data, write_preprocessed_data, create_file_object, file_object) from datapipeline.utils.copy import copy_csv def preprocess_c_trials (clinicalT): """ Descri...
0.370909
0.437343
""" Test for smoothing with kernels """ import numpy as np from numpy.random import random_integers as randint from ... import load_image from ..kernel_smooth import LinearFilter, sigma2fwhm, fwhm2sigma from ...externals.transforms3d.taitbryan import euler2mat from ...core.api import Image, compose, AffineTransform, d...
nipy/algorithms/tests/test_kernel_smooth.py
""" Test for smoothing with kernels """ import numpy as np from numpy.random import random_integers as randint from ... import load_image from ..kernel_smooth import LinearFilter, sigma2fwhm, fwhm2sigma from ...externals.transforms3d.taitbryan import euler2mat from ...core.api import Image, compose, AffineTransform, d...
0.839832
0.72054
import numpy as np import pyrotein as pr import os from loaddata import load_xlsx # [[[ OBTAIN THE CONSENSUS SEQUENCE ]]] # Read the sequence alignment result... # [WARNING] !!!sequence alignment is not trustworthy, need to check manually fl_aln = 'seq.align.fasta' seq_dict = pr.fasta.read(fl_aln) # Obtain the con...
examples/svd.full.py
import numpy as np import pyrotein as pr import os from loaddata import load_xlsx # [[[ OBTAIN THE CONSENSUS SEQUENCE ]]] # Read the sequence alignment result... # [WARNING] !!!sequence alignment is not trustworthy, need to check manually fl_aln = 'seq.align.fasta' seq_dict = pr.fasta.read(fl_aln) # Obtain the con...
0.511717
0.251383
__author__ = """<NAME>""" __email__ = '<EMAIL>' __version__ = '0.2.2' from typing import Optional, Type import deta from fastapi_users.manager import UserNotExists from pydantic import UUID4 from fastapi_users.db.base import BaseUserDatabase from fastapi_users.models import UD class DetaBaseUserDatabase(BaseUserD...
fastapi_users_db_deta/__init__.py
__author__ = """<NAME>""" __email__ = '<EMAIL>' __version__ = '0.2.2' from typing import Optional, Type import deta from fastapi_users.manager import UserNotExists from pydantic import UUID4 from fastapi_users.db.base import BaseUserDatabase from fastapi_users.models import UD class DetaBaseUserDatabase(BaseUserD...
0.827026
0.102709
import torch from torch import nn import numpy as np from .event_representation import EventRepresentation from hats_pytorch import HATS class HATSRepresentation(EventRepresentation): def __init__(self, cfg, *args, **kwargs): super().__init__(cfg, *args, **kwargs) self.bins = cfg.bins ...
N-Caltech101/evrepr/representations/hats.py
import torch from torch import nn import numpy as np from .event_representation import EventRepresentation from hats_pytorch import HATS class HATSRepresentation(EventRepresentation): def __init__(self, cfg, *args, **kwargs): super().__init__(cfg, *args, **kwargs) self.bins = cfg.bins ...
0.764935
0.329877
from docopt import docopt import h5py import logging import warnings warnings.filterwarnings('ignore',category=FutureWarning) # This supresses a warning caused by old TF version import tensorflow as tf import numpy as np from tqdm import tqdm tf.compat.v1.enable_eager_execution() logging.basicConfig(level=logging.INF...
convert_tfrecord.py
from docopt import docopt import h5py import logging import warnings warnings.filterwarnings('ignore',category=FutureWarning) # This supresses a warning caused by old TF version import tensorflow as tf import numpy as np from tqdm import tqdm tf.compat.v1.enable_eager_execution() logging.basicConfig(level=logging.INF...
0.458106
0.260372
import math import os from decimal import Decimal from django import template from django.utils import timezone from djmoney.money import Money from app import settings from app.enums import FileStatus from app.utils import get_site_url from event.enums import ApplicationStatus, DietType, TshirtSize, CompanyTier from...
app/templatetags/app_tags.py
import math import os from decimal import Decimal from django import template from django.utils import timezone from djmoney.money import Money from app import settings from app.enums import FileStatus from app.utils import get_site_url from event.enums import ApplicationStatus, DietType, TshirtSize, CompanyTier from...
0.359589
0.19046
from __future__ import absolute_import from __future__ import print_function import numpy as np import torch.nn as nn import torch from torch.nn.parameter import Parameter import math class GraphConvolution(nn.Module): """ adapted from : https://github.com/tkipf/gcn/blob/92600c39797c2bfb61a508e52b88fb554df30...
model/GCN.py
from __future__ import absolute_import from __future__ import print_function import numpy as np import torch.nn as nn import torch from torch.nn.parameter import Parameter import math class GraphConvolution(nn.Module): """ adapted from : https://github.com/tkipf/gcn/blob/92600c39797c2bfb61a508e52b88fb554df30...
0.906581
0.326714
import numpy as np import gym import matplotlib.pyplot as plt env = gym.make('CartPole-v0') states = 4 dim = 2*states number_actions = 2 epsilon = .5 alpha = .1 gamma = .9 lam = .5 MLR = .01 nrounds = 10000 def epsilongreedy(Qf, obs, epsilonf, num_actions): actions = np.dot(Qf, obs) if np.random.random() > ep...
RLbasics/Cart-addedfeatures.py
import numpy as np import gym import matplotlib.pyplot as plt env = gym.make('CartPole-v0') states = 4 dim = 2*states number_actions = 2 epsilon = .5 alpha = .1 gamma = .9 lam = .5 MLR = .01 nrounds = 10000 def epsilongreedy(Qf, obs, epsilonf, num_actions): actions = np.dot(Qf, obs) if np.random.random() > ep...
0.210766
0.606003
import logging import numpy as np from scipy.cluster.hierarchy import linkage, fcluster from sklearn.cluster import dbscan from scipy.stats import gmean from article_separation.gnn.clustering.dbscan_textblocks import DBScanRelation class TextblockClustering(object): """ class for textblock clustering Usa...
article_separation/gnn/clustering/textblock_clustering.py
import logging import numpy as np from scipy.cluster.hierarchy import linkage, fcluster from sklearn.cluster import dbscan from scipy.stats import gmean from article_separation.gnn.clustering.dbscan_textblocks import DBScanRelation class TextblockClustering(object): """ class for textblock clustering Usa...
0.805364
0.26938
import os import json import sqlite3 from time import strftime, localtime from index.neo4j import Neo4jToJson from django.shortcuts import render from django.http import HttpResponse data_neo4j = Neo4jToJson() # Create your views here. def index(request): data = {'nodes': [], 'links': []} try: data = ...
index/views.py
import os import json import sqlite3 from time import strftime, localtime from index.neo4j import Neo4jToJson from django.shortcuts import render from django.http import HttpResponse data_neo4j = Neo4jToJson() # Create your views here. def index(request): data = {'nodes': [], 'links': []} try: data = ...
0.10711
0.06134
from abc import abstractmethod import torch from flambe.metric.metric import Metric class BinaryMetric(Metric): def __init__(self, threshold: float = 0.5) -> None: """Initialize the Binary metric. Parameters --------- threshold: float Given a probability p of belong...
flambe/metric/dev/binary.py
from abc import abstractmethod import torch from flambe.metric.metric import Metric class BinaryMetric(Metric): def __init__(self, threshold: float = 0.5) -> None: """Initialize the Binary metric. Parameters --------- threshold: float Given a probability p of belong...
0.972663
0.940024
load("//nixpkgs:nixpkgs.bzl", "nixpkgs_package") load("//nixpkgs:private/constraints.bzl", "ensure_constraints") _foreign_cc_nix_build = """ load("@rules_foreign_cc//toolchains/native_tools:native_tools_toolchain.bzl", "native_tool_toolchain") filegroup( name = "data", srcs = glob(["bin/**"]), ) native_tool_t...
nixpkgs/toolchains/foreign_cc.bzl
load("//nixpkgs:nixpkgs.bzl", "nixpkgs_package") load("//nixpkgs:private/constraints.bzl", "ensure_constraints") _foreign_cc_nix_build = """ load("@rules_foreign_cc//toolchains/native_tools:native_tools_toolchain.bzl", "native_tool_toolchain") filegroup( name = "data", srcs = glob(["bin/**"]), ) native_tool_t...
0.360827
0.090454
from utils import * from itertools import combinations import numpy as np import scipy.sparse as sp from decagon.utility import preprocessing from typing import Dict, NoReturn from run_decagon import RunDecagon class RunDecagonToy(RunDecagon): """ Decagon Runner on synthetic data. Attributes --------...
run_decagon_toy.py
from utils import * from itertools import combinations import numpy as np import scipy.sparse as sp from decagon.utility import preprocessing from typing import Dict, NoReturn from run_decagon import RunDecagon class RunDecagonToy(RunDecagon): """ Decagon Runner on synthetic data. Attributes --------...
0.879794
0.567098
def printComp(z) -> str: return str(z.real) + "," + str(z.imag) + "\n" def file_len(fname): with open(fname) as f: for i, l in enumerate(f): pass return i + 1 def leja(): for _i in range(18): leja = [] with open(path + "data\\leja\\segment_" + str(_i) + ".txt", "r...
scripts/main.py
def printComp(z) -> str: return str(z.real) + "," + str(z.imag) + "\n" def file_len(fname): with open(fname) as f: for i, l in enumerate(f): pass return i + 1 def leja(): for _i in range(18): leja = [] with open(path + "data\\leja\\segment_" + str(_i) + ".txt", "r...
0.322526
0.164416
from http import HTTPStatus from typing import Set, Type # 3rd party import docutils.nodes import pytest from apeye.requests_url import RequestsURL from coincidence.params import count from docutils import nodes from docutils.utils import Reporter from pytest_httpserver import HTTPServer from sphinx.events import Even...
tests/test_github.py
from http import HTTPStatus from typing import Set, Type # 3rd party import docutils.nodes import pytest from apeye.requests_url import RequestsURL from coincidence.params import count from docutils import nodes from docutils.utils import Reporter from pytest_httpserver import HTTPServer from sphinx.events import Even...
0.685634
0.297062
import json import warnings import pulumi import pulumi.runtime from typing import Union from .. import utilities, tables class GetMariaDbServerResult: """ A collection of values returned by getMariaDbServer. """ def __init__(__self__, administrator_login=None, fqdn=None, id=None, location=None, name=...
sdk/python/pulumi_azure/mariadb/get_maria_db_server.py
import json import warnings import pulumi import pulumi.runtime from typing import Union from .. import utilities, tables class GetMariaDbServerResult: """ A collection of values returned by getMariaDbServer. """ def __init__(__self__, administrator_login=None, fqdn=None, id=None, location=None, name=...
0.664758
0.10316
import inetutils import socket import struct import string import os IPVERSION = 4 IP_DF = 0x4000 IP_MF = 0x2000 IP_MAXPACKET = 65535 IPTOS_LOWDELAY = 0x10 IPTOS_THROUGHPUT = 0x08 IPTOS_RELIABILITY = 0x04 IPTOS_PREC_NETCONTROL = 0xe0 IPTOS_PREC_INTERNETCONTROL = 0xc0 IPTOS_PREC_CRITIC_ECP = 0xa0 IPTOS_PREC_FLASHOVER...
ip.py
import inetutils import socket import struct import string import os IPVERSION = 4 IP_DF = 0x4000 IP_MF = 0x2000 IP_MAXPACKET = 65535 IPTOS_LOWDELAY = 0x10 IPTOS_THROUGHPUT = 0x08 IPTOS_RELIABILITY = 0x04 IPTOS_PREC_NETCONTROL = 0xe0 IPTOS_PREC_INTERNETCONTROL = 0xc0 IPTOS_PREC_CRITIC_ECP = 0xa0 IPTOS_PREC_FLASHOVER...
0.428831
0.161585
import json from rest_framework import status from rest_framework.test import APIClient, force_authenticate from django.contrib.auth.models import User from django.test import TestCase from quickstart.models import Comment, Author, Post from quickstart.serializers import CommentSerializer from quickstart.tests.helper_t...
back-end/api/quickstart/tests/endpoints/test_comment.py
import json from rest_framework import status from rest_framework.test import APIClient, force_authenticate from django.contrib.auth.models import User from django.test import TestCase from quickstart.models import Comment, Author, Post from quickstart.serializers import CommentSerializer from quickstart.tests.helper_t...
0.475605
0.231147
import logging import tabix import biograph.variants as bgexvar class VcfEntryInfo: """ Holds tracking information for a specific VCF entry while processing all the associated assemblies call static method parse_vcf over a fetched region """ __slots__ = ["vcf_entry", "total_alleles", "alleles_r...
python/biograph/coverage/vcf_entry_info.py
import logging import tabix import biograph.variants as bgexvar class VcfEntryInfo: """ Holds tracking information for a specific VCF entry while processing all the associated assemblies call static method parse_vcf over a fetched region """ __slots__ = ["vcf_entry", "total_alleles", "alleles_r...
0.676086
0.205037
import os import copy import yaml import pandas as pd from autumn.model_runner import build_model_runner from autumn.tool_kit.scenarios import Scenario from autumn.tool_kit.params import update_params from datetime import date, timedelta from apps.covid_19 import RegionApp from apps.covid_19.mixing_optimisation.cons...
apps/covid_19/mixing_optimisation/mixing_opti.py
import os import copy import yaml import pandas as pd from autumn.model_runner import build_model_runner from autumn.tool_kit.scenarios import Scenario from autumn.tool_kit.params import update_params from datetime import date, timedelta from apps.covid_19 import RegionApp from apps.covid_19.mixing_optimisation.cons...
0.503906
0.292103
import os import dq0.sdk from dq0.sdk.data.utils import plotting, util def preprocess_dataset(data_source): column_names_list = [ 'lastname', 'firstname', 'age', 'workclass', 'fnlwgt', 'education', 'education-num', 'marital-status', 'occupa...
dq0/sdk/examples/census/eda.py
import os import dq0.sdk from dq0.sdk.data.utils import plotting, util def preprocess_dataset(data_source): column_names_list = [ 'lastname', 'firstname', 'age', 'workclass', 'fnlwgt', 'education', 'education-num', 'marital-status', 'occupa...
0.648132
0.35883
import logging from pathvalidate import sanitize_filename from pathlib import Path from .utils import validate_url, write_details from .utils import download as download_file from .errors import InvalidURL from .fetcher import * from .manga import Manga from .chapter import Chapter from .downloader import ChapterPageDo...
mangadex_downloader/main.py
import logging from pathvalidate import sanitize_filename from pathlib import Path from .utils import validate_url, write_details from .utils import download as download_file from .errors import InvalidURL from .fetcher import * from .manga import Manga from .chapter import Chapter from .downloader import ChapterPageDo...
0.759225
0.169269
import numpy as np from Supervised.Regression.RegressionTree import regress_tree_utils def prune(tree, testData): """ Desc: 从上而下找到叶节点,用测试数据集来判断将这些叶节点合并是否能降低测试误差 Args: tree -- 待剪枝的树 testData -- 剪枝所需要的测试数据 testData Returns: tree -- 剪枝完成的树 """ # 判断是否测试数据集没有数据,如果没...
Supervised/Regression/RegressionTree/rt_prune.py
import numpy as np from Supervised.Regression.RegressionTree import regress_tree_utils def prune(tree, testData): """ Desc: 从上而下找到叶节点,用测试数据集来判断将这些叶节点合并是否能降低测试误差 Args: tree -- 待剪枝的树 testData -- 剪枝所需要的测试数据 testData Returns: tree -- 剪枝完成的树 """ # 判断是否测试数据集没有数据,如果没...
0.467332
0.620075
import tensorflow as tf import os import pandas as pd import functools import random LABEL_FILE = 'train.csv' IMAGE_SHAPE = [224, 224] NB_EPOCHS = None NUM_PARALLEL_CALLS = 4 PREFETCH_BUFFER_SIZE = 2 ** 8 SHUFFLE_BUFFER_SIZE = 2 ** 8 def get_landmark_challange_generator(data_dir, is_training=True): """ Args: dat...
data_generation/data_generator.py
import tensorflow as tf import os import pandas as pd import functools import random LABEL_FILE = 'train.csv' IMAGE_SHAPE = [224, 224] NB_EPOCHS = None NUM_PARALLEL_CALLS = 4 PREFETCH_BUFFER_SIZE = 2 ** 8 SHUFFLE_BUFFER_SIZE = 2 ** 8 def get_landmark_challange_generator(data_dir, is_training=True): """ Args: dat...
0.47171
0.258262
import caffe import re from pittnuts import * import os import matplotlib.pyplot as plt import argparse import caffeparser import caffe_apps if __name__ == "__main__": parser = argparse.ArgumentParser() parser.add_argument('--original_alexnet', type=str, required=True,help="The original alexnet with group.") ...
python/group_spitter.py
import caffe import re from pittnuts import * import os import matplotlib.pyplot as plt import argparse import caffeparser import caffe_apps if __name__ == "__main__": parser = argparse.ArgumentParser() parser.add_argument('--original_alexnet', type=str, required=True,help="The original alexnet with group.") ...
0.269806
0.102754
import config from api import send_message from reborn import is_sudoer def on_msg_received(msg, matches): # Checa se o usuário tem permissão e tem a quantidade correta de args no comando command = matches.group(2) plugin = matches.group(3) if command is None and plugin is None: string = "" ...
plugins/plugins.py
import config from api import send_message from reborn import is_sudoer def on_msg_received(msg, matches): # Checa se o usuário tem permissão e tem a quantidade correta de args no comando command = matches.group(2) plugin = matches.group(3) if command is None and plugin is None: string = "" ...
0.202996
0.197406
import random import sys import argparse from de_sim.simulation_message import SimulationMessage from de_sim.simulation_object import ApplicationSimulationObject from de_sim.simulation_engine import SimulationEngine from de_sim.examples.debug_logs import logs def obj_name(obj_num): # create object name from inde...
de_sim/examples/phold.py
import random import sys import argparse from de_sim.simulation_message import SimulationMessage from de_sim.simulation_object import ApplicationSimulationObject from de_sim.simulation_engine import SimulationEngine from de_sim.examples.debug_logs import logs def obj_name(obj_num): # create object name from inde...
0.475362
0.36886
from bota.utility.db_utility import BotaDB from bota import db_constants as dbc from bota.constant import DEFAULT_PREFIX bota_db = BotaDB(host=dbc.HOST_NAME, database=dbc.DATABASE_NAME, user=dbc.USER, password=dbc.PASSWORD) class GuildCaller: def __init__(self): pass def get_gu...
bota/guild_process/guild_main.py
from bota.utility.db_utility import BotaDB from bota import db_constants as dbc from bota.constant import DEFAULT_PREFIX bota_db = BotaDB(host=dbc.HOST_NAME, database=dbc.DATABASE_NAME, user=dbc.USER, password=dbc.PASSWORD) class GuildCaller: def __init__(self): pass def get_gu...
0.344885
0.065425
import torch import torch.nn as nn import random from transformers import ( ElectraConfig, ElectraTokenizer ) from model.koelectra import koElectraForSequenceClassification,koelectra_input from model.kobert import KoBERTforSequenceClassfication, kobert_input from kobert_transformers import get_tokenizer class Dia...
ai/chatbot/service/module.py
import torch import torch.nn as nn import random from transformers import ( ElectraConfig, ElectraTokenizer ) from model.koelectra import koElectraForSequenceClassification,koelectra_input from model.kobert import KoBERTforSequenceClassfication, kobert_input from kobert_transformers import get_tokenizer class Dia...
0.582847
0.27488
import pytz from sqlalchemy import Column, Integer, String, DateTime, Interval, ForeignKey, UniqueConstraint from sqlalchemy.orm import relationship from .base import Base class Flight(Base): """ Class representing a numbered flight for a named airline on a given date and at a given time """ __tablena...
src/flight_model/model/flight.py
import pytz from sqlalchemy import Column, Integer, String, DateTime, Interval, ForeignKey, UniqueConstraint from sqlalchemy.orm import relationship from .base import Base class Flight(Base): """ Class representing a numbered flight for a named airline on a given date and at a given time """ __tablena...
0.847179
0.474022
from snakemake.io import expand from snakemake.exceptions import WildcardError import pytest def test_simple_expand(): # single filepattern assert expand("{a}.out", a="test") == ["test.out"] # multiple filepatterns assert expand(["{a}.out", "{b}.out"], a="a", b="b") == ["a.out", "b.out"] # multipl...
tests/test_expand.py
from snakemake.io import expand from snakemake.exceptions import WildcardError import pytest def test_simple_expand(): # single filepattern assert expand("{a}.out", a="test") == ["test.out"] # multiple filepatterns assert expand(["{a}.out", "{b}.out"], a="a", b="b") == ["a.out", "b.out"] # multipl...
0.787686
0.754915
"""Evaluates a network on a dataset and writes the result in an npy file.""" import os import pickle import time from absl import app from absl import flags import apache_beam as beam # LDIF is an internal package, should be imported last. # pylint: disable=g-bad-import-order from ldif.inference import e...
ldif/results/make_results.py
"""Evaluates a network on a dataset and writes the result in an npy file.""" import os import pickle import time from absl import app from absl import flags import apache_beam as beam # LDIF is an internal package, should be imported last. # pylint: disable=g-bad-import-order from ldif.inference import e...
0.521471
0.294773
#------------------------------------------------------------------------------ # module imports #------------------------------------------------------------------------------ import sys import json import tftpy import socket import select #----------------------------------------------------------------------------...
utilities/TDK_Automation_Scripts/python-lib/consoleLogTransfer.py
#------------------------------------------------------------------------------ # module imports #------------------------------------------------------------------------------ import sys import json import tftpy import socket import select #----------------------------------------------------------------------------...
0.207696
0.048519
from incuna_test_utils.compat import DJANGO_LT_16, Python2AssertMixin from incuna_test_utils.testcases.request import BaseRequestTestCase import mock from . import factories from .. import views from videos.module.chapters.tests.factories import ChapterFactory from videos.module.speakers.tests.factories import Speaker...
videos/tests/test_views.py
from incuna_test_utils.compat import DJANGO_LT_16, Python2AssertMixin from incuna_test_utils.testcases.request import BaseRequestTestCase import mock from . import factories from .. import views from videos.module.chapters.tests.factories import ChapterFactory from videos.module.speakers.tests.factories import Speaker...
0.695545
0.393909
import argparse import os import dgl import torch as th import torch.nn as nn import torch.nn.functional as F from dgl import load_graphs from models import dummy_gnn_model, GCNII from NodeExplainerModule import NodeExplainerModule from utils_graph import extract_subgraph, visualize_sub_graph def main(args): #...
examples/pytorch/gnn_explainer/explain_main.py
import argparse import os import dgl import torch as th import torch.nn as nn import torch.nn.functional as F from dgl import load_graphs from models import dummy_gnn_model, GCNII from NodeExplainerModule import NodeExplainerModule from utils_graph import extract_subgraph, visualize_sub_graph def main(args): #...
0.832441
0.293803
import hashlib import os __copyright__ = '2015, JSK Lab' __author__ = '<NAME> <<EMAIL>>' __version__ = '0.1' def rst_image_table_data(url_prefix, img_files): N_COLUMN = 3 # collect label and blocks labels = [] blocks = [] for i, img_file in enumerate(img_files): title, _ = os.path.splite...
jsk_recognition/doc/add_img_tables_to_index.py
import hashlib import os __copyright__ = '2015, JSK Lab' __author__ = '<NAME> <<EMAIL>>' __version__ = '0.1' def rst_image_table_data(url_prefix, img_files): N_COLUMN = 3 # collect label and blocks labels = [] blocks = [] for i, img_file in enumerate(img_files): title, _ = os.path.splite...
0.186836
0.101189
from pyomo.environ import * model = m = ConcreteModel() m.x1 = Var(within=Reals,bounds=(0,None),initialize=0) m.x2 = Var(within=Reals,bounds=(0,None),initialize=0) m.x3 = Var(within=Reals,bounds=(0,None),initialize=0) m.x4 = Var(within=Reals,bounds=(0,None),initialize=0) m.x5 = Var(within=Reals,bounds=(0,None),ini...
tests/examples/minlplib/st_m2.py
from pyomo.environ import * model = m = ConcreteModel() m.x1 = Var(within=Reals,bounds=(0,None),initialize=0) m.x2 = Var(within=Reals,bounds=(0,None),initialize=0) m.x3 = Var(within=Reals,bounds=(0,None),initialize=0) m.x4 = Var(within=Reals,bounds=(0,None),initialize=0) m.x5 = Var(within=Reals,bounds=(0,None),ini...
0.413951
0.212845
from pretraining.utils import * import numpy as np from pretraining.oov import readParam from collections import defaultdict import operator posParser = {'n': 'NN', 'a': 'JJ', 's': 'JJ', 'v': 'VB', 'r': 'RB'} pos = ['VB', 'NN', 'RB', 'JJ'] def load_gre_test(path): gre = [] with open(path, 'r') as f: f...
bptf/gre_test.py
from pretraining.utils import * import numpy as np from pretraining.oov import readParam from collections import defaultdict import operator posParser = {'n': 'NN', 'a': 'JJ', 's': 'JJ', 'v': 'VB', 'r': 'RB'} pos = ['VB', 'NN', 'RB', 'JJ'] def load_gre_test(path): gre = [] with open(path, 'r') as f: f...
0.214691
0.33764
import argparse import sqlite3 from flask import Flask, jsonify, send_from_directory from flask_cors import CORS # http://blog.miguelgrinberg.com/post/designing-a-restful-api-with-python-and-flask from werkzeug.utils import redirect app = Flask(__name__) CORS(app) def read_calling_points(all_points): points = [...
railserver.py
import argparse import sqlite3 from flask import Flask, jsonify, send_from_directory from flask_cors import CORS # http://blog.miguelgrinberg.com/post/designing-a-restful-api-with-python-and-flask from werkzeug.utils import redirect app = Flask(__name__) CORS(app) def read_calling_points(all_points): points = [...
0.47658
0.209672
import warnings from sklearn.metrics import mean_squared_error from sklearn.model_selection._split import train_test_split import traceback from unsupervised_learning.src import plot_clusters import copy warnings.filterwarnings("ignore") import os os.chdir(os.path.dirname(__file__)) from sklearn.metrics.pair...
unsupervised_learning/src/assignment3_script.py
import warnings from sklearn.metrics import mean_squared_error from sklearn.model_selection._split import train_test_split import traceback from unsupervised_learning.src import plot_clusters import copy warnings.filterwarnings("ignore") import os os.chdir(os.path.dirname(__file__)) from sklearn.metrics.pair...
0.279533
0.300797
import logging import gspread import datetime from django.conf import settings from .models import Cleanup logger = logging.getLogger('cleanups.google_sheets') # TODO: Remove variables and use settings directly. GOOGLE_SHEETS_VALIDATION = settings.GOOGLE_SHEETS_VALIDATION GOOGLE_SHEETS_SCOPE = settings.GOOGLE_SHEE...
trashtalk/apps/integrations/google_sheets/google_sheets.py
import logging import gspread import datetime from django.conf import settings from .models import Cleanup logger = logging.getLogger('cleanups.google_sheets') # TODO: Remove variables and use settings directly. GOOGLE_SHEETS_VALIDATION = settings.GOOGLE_SHEETS_VALIDATION GOOGLE_SHEETS_SCOPE = settings.GOOGLE_SHEE...
0.193414
0.099996
import argparse from collections import defaultdict import cv2, os from pytorch_toolbelt.inference.tiles import ImageSlicer from pytorch_toolbelt.utils import fs from pytorch_toolbelt.utils.fs import id_from_fname, read_image_as_is import pandas as pd from tqdm import tqdm from inria.dataset import TRAIN_LOCATIONS, r...
make_train_tiles.py
import argparse from collections import defaultdict import cv2, os from pytorch_toolbelt.inference.tiles import ImageSlicer from pytorch_toolbelt.utils import fs from pytorch_toolbelt.utils.fs import id_from_fname, read_image_as_is import pandas as pd from tqdm import tqdm from inria.dataset import TRAIN_LOCATIONS, r...
0.470007
0.285702
import datetime import json import sqlalchemy from sqlalchemy import and_, desc, func, or_, distinct from rdr_service.census_regions import census_regions from rdr_service.code_constants import PPI_SYSTEM from rdr_service.dao.base_dao import BaseDao, UpdatableDao from rdr_service.dao.code_dao import CodeDao from rdr_...
rdr_service/dao/metrics_cache_dao.py
import datetime import json import sqlalchemy from sqlalchemy import and_, desc, func, or_, distinct from rdr_service.census_regions import census_regions from rdr_service.code_constants import PPI_SYSTEM from rdr_service.dao.base_dao import BaseDao, UpdatableDao from rdr_service.dao.code_dao import CodeDao from rdr_...
0.397938
0.132458
from unittest.mock import Mock, patch import pytest from graph_structures_pb2 import Client, Node, NodeType, Status, VirtualNode import ujt.constants import ujt.transformers @pytest.fixture def patch_path(): return "ujt.transformers" def test_apply_node_property_classes(assert_same_elements): node_name =...
tests/test_transformers.py
from unittest.mock import Mock, patch import pytest from graph_structures_pb2 import Client, Node, NodeType, Status, VirtualNode import ujt.constants import ujt.transformers @pytest.fixture def patch_path(): return "ujt.transformers" def test_apply_node_property_classes(assert_same_elements): node_name =...
0.706798
0.535159
import datetime import io import json import logging import re import boto3 import xlwt from botocore.exceptions import ClientError from jinja2 import Template from xlwt.compat import basestring from constant import Constant from me_logger import log_error from util import get_accounts_by_company_name, get_all_accoun...
src/reports.py
import datetime import io import json import logging import re import boto3 import xlwt from botocore.exceptions import ClientError from jinja2 import Template from xlwt.compat import basestring from constant import Constant from me_logger import log_error from util import get_accounts_by_company_name, get_all_accoun...
0.378459
0.087252
from Adafruit_LED_Backpack import AlphaNum4, BicolorBargraph24, SevenSegment import widget import RPi.GPIO as GPIO from PIL import Image, ImageDraw, ImageFont import cups import datetime import time class Timer(object): """A simple timer class""" def __init__(self): pass def start(self): ...
ParkTimer.python/parktimer.py
from Adafruit_LED_Backpack import AlphaNum4, BicolorBargraph24, SevenSegment import widget import RPi.GPIO as GPIO from PIL import Image, ImageDraw, ImageFont import cups import datetime import time class Timer(object): """A simple timer class""" def __init__(self): pass def start(self): ...
0.669961
0.2667
from functools import partial from enum import Enum import logging import serial class Protocol(Enum): UNKNOWN = 0 NEC = 1 SONY = 2 NECX = 7 NUM_N_BYTES = 4 class Ack(object): def __init__(self, label, nac_info=None): self.label = label self.nac_info = nac_info def __bool...
python/ser_com.py
from functools import partial from enum import Enum import logging import serial class Protocol(Enum): UNKNOWN = 0 NEC = 1 SONY = 2 NECX = 7 NUM_N_BYTES = 4 class Ack(object): def __init__(self, label, nac_info=None): self.label = label self.nac_info = nac_info def __bool...
0.516839
0.110904
import json import math #loads the give file location and creates a lootTable object def load(f): fp = open(f, 'r') return lootTable(f,json.load(fp)) #saves the provided lootTable object at the provided location def save(f, table): fp = open(f,'w') json.dump(table.convert_to_dict(), fp, indent=2) def...
loot_table.py
import json import math #loads the give file location and creates a lootTable object def load(f): fp = open(f, 'r') return lootTable(f,json.load(fp)) #saves the provided lootTable object at the provided location def save(f, table): fp = open(f,'w') json.dump(table.convert_to_dict(), fp, indent=2) def...
0.254602
0.09645
import pyttsx3 import speech_recognition as sr import re import sys from webscraper import Scraper # pyaudio scraper = Scraper() # RegEx Patterns BASIC_PATTERNS = { re.compile("[\w\s]+ (cases|case)"): scraper.get_cases, re.compile("[\w\s]+ (cases|case) worldwide"): scraper.get_cases, re.compile("[\w\s]+ ...
voice_assistant.py
import pyttsx3 import speech_recognition as sr import re import sys from webscraper import Scraper # pyaudio scraper = Scraper() # RegEx Patterns BASIC_PATTERNS = { re.compile("[\w\s]+ (cases|case)"): scraper.get_cases, re.compile("[\w\s]+ (cases|case) worldwide"): scraper.get_cases, re.compile("[\w\s]+ ...
0.128361
0.304494
import torch.nn as nn from segmentation_models_pytorch.unet.decoder import CenterBlock, DecoderBlock class UnetDecoderClipped(nn.Module): def __init__( self, encoder_channels, decoder_channels, decoder_blocks=5, use_batchnorm=True, attention_t...
multitask_lightning/models/decoder.py
import torch.nn as nn from segmentation_models_pytorch.unet.decoder import CenterBlock, DecoderBlock class UnetDecoderClipped(nn.Module): def __init__( self, encoder_channels, decoder_channels, decoder_blocks=5, use_batchnorm=True, attention_t...
0.937769
0.39004
# [3rd party modules] import numpy as np import sys import time import pickle from modules.utils import my_print import matplotlib.pyplot as plt try: import mujoco_py as mjPy except ImportError as e: raise error.DependencyNotInstalled( "{}. (HINT: you need to install mujoco_py, \ ...
MuJoCo/modules/controllers.py
# [3rd party modules] import numpy as np import sys import time import pickle from modules.utils import my_print import matplotlib.pyplot as plt try: import mujoco_py as mjPy except ImportError as e: raise error.DependencyNotInstalled( "{}. (HINT: you need to install mujoco_py, \ ...
0.289472
0.387574
from scipy.spatial import Delaunay from collections import defaultdict from itertools import combinations import numpy as np from memly.metrics import Metric class Domains(Metric): def __init__(self, membrane, title="Domains", units="unitless"): """ Detects lipid domains using Delaunay triangulat...
memly/domains.py
from scipy.spatial import Delaunay from collections import defaultdict from itertools import combinations import numpy as np from memly.metrics import Metric class Domains(Metric): def __init__(self, membrane, title="Domains", units="unitless"): """ Detects lipid domains using Delaunay triangulat...
0.767123
0.536738
import doxygen_parsing import inspect import string import os import sys import comment_verifier comment_verifier.check(inspect.getdoc(doxygen_parsing.someFunction), "The function comment") comment_verifier.check(inspect.getdoc(doxygen_parsing.SomeClass), "The class comment") comment_verifier.check(inspect.get...
cacreader/swig-4.0.2/Examples/test-suite/python/doxygen_parsing_runme.py
import doxygen_parsing import inspect import string import os import sys import comment_verifier comment_verifier.check(inspect.getdoc(doxygen_parsing.someFunction), "The function comment") comment_verifier.check(inspect.getdoc(doxygen_parsing.SomeClass), "The class comment") comment_verifier.check(inspect.get...
0.408985
0.226377
import contextlib import logging import random from flask import request, g from sqlalchemy import create_engine as sqlalchemy_create_engine from sqlalchemy.ext.declarative import declarative_base from sqlalchemy.orm import scoped_session, sessionmaker from app import app, load_app_config from app.exc import GulDanEx...
app/db.py
import contextlib import logging import random from flask import request, g from sqlalchemy import create_engine as sqlalchemy_create_engine from sqlalchemy.ext.declarative import declarative_base from sqlalchemy.orm import scoped_session, sessionmaker from app import app, load_app_config from app.exc import GulDanEx...
0.348867
0.075346