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 warnings
from ... import tensor, placeholder, target as _target
from ..util import get_const_tuple
from .task import create, register
def serialize_args(args):
"""serialize arguments of a topi function to a hashable tuple.
Parameters
----------
args: list of hashable or Tensor
"""
re... | python/tvm/autotvm/task/nnvm_integration.py | import warnings
from ... import tensor, placeholder, target as _target
from ..util import get_const_tuple
from .task import create, register
def serialize_args(args):
"""serialize arguments of a topi function to a hashable tuple.
Parameters
----------
args: list of hashable or Tensor
"""
re... | 0.778565 | 0.431764 |
from rest_framework.views import APIView
from rest_framework.response import Response
from rest_framework import status
from rest_framework.authentication import TokenAuthentication
from rest_framework import viewsets
from rest_framework import filters
from rest_framework.authtoken.views import ObtainAuthToken
from res... | profiles_api/views.py | from rest_framework.views import APIView
from rest_framework.response import Response
from rest_framework import status
from rest_framework.authentication import TokenAuthentication
from rest_framework import viewsets
from rest_framework import filters
from rest_framework.authtoken.views import ObtainAuthToken
from res... | 0.801042 | 0.15084 |
import pandas as pd
from pandas import Series, DataFrame
import numpy as np
import matplotlib.pyplot as plt
import seaborn as sns
student_df = pd.read_csv("StudentsPerformance.csv")
print("======Data Headers=======")
student_df.head()
print("=====Data Decription=====")
student_df.info()
student_df.describe()
studen... | SEE/Scripting/2/2b/2b.py | import pandas as pd
from pandas import Series, DataFrame
import numpy as np
import matplotlib.pyplot as plt
import seaborn as sns
student_df = pd.read_csv("StudentsPerformance.csv")
print("======Data Headers=======")
student_df.head()
print("=====Data Decription=====")
student_df.info()
student_df.describe()
studen... | 0.44746 | 0.426979 |
import pennylane as qml
from pennylane import math
from ..qnodes import global_parity_expval_qnode
def mermin_klyshko_inputs_scalars(n):
"""Helper function for handling the algebra of combining correlator terms
in the Mermin-Klyshko (MK) inequality.
This function supports :meth:`mermin_klyshko_cost_fn`.
... | src/qnetvo/cost/mermin_klyshko_inequality.py | import pennylane as qml
from pennylane import math
from ..qnodes import global_parity_expval_qnode
def mermin_klyshko_inputs_scalars(n):
"""Helper function for handling the algebra of combining correlator terms
in the Mermin-Klyshko (MK) inequality.
This function supports :meth:`mermin_klyshko_cost_fn`.
... | 0.812793 | 0.528898 |
import functools
import time
__author__ = 'turgay.pamuklu'
class Observer():
_observers = []
def __init__(self):
self._observers.append(self)
self._observables = {}
def observe(self, event_name, callback):
self._observables[event_name] = callback
class Event():
def __init_... | green/performanceCalculator.py | import functools
import time
__author__ = 'turgay.pamuklu'
class Observer():
_observers = []
def __init__(self):
self._observers.append(self)
self._observables = {}
def observe(self, event_name, callback):
self._observables[event_name] = callback
class Event():
def __init_... | 0.601008 | 0.100746 |
import json
from os import stat
from typing import List
from tqdm import tqdm
import argparse
from config import Config
# Indic library
import sys
from indicnlp import common
INDIC_NLP_LIB_HOME=r"indic_nlp_library"
INDIC_NLP_RESOURCES=r"indic_nlp_resources"
sys.path.append(r'{}\src'.format(INDIC_NLP_LIB_HOME))
common... | utils/check_cap_len.py | import json
from os import stat
from typing import List
from tqdm import tqdm
import argparse
from config import Config
# Indic library
import sys
from indicnlp import common
INDIC_NLP_LIB_HOME=r"indic_nlp_library"
INDIC_NLP_RESOURCES=r"indic_nlp_resources"
sys.path.append(r'{}\src'.format(INDIC_NLP_LIB_HOME))
common... | 0.186539 | 0.176069 |
# usage: compleconta.py /path/to/protein_file.faa /path/to/hmmer_results.faa.out
import sys
import os
import subprocess
import argparse
from compleconta import FileIO, Annotation, EnogLists, aminoAcidIdentity, Check, MarkerGeneBlast, ncbiTaxonomyTree
def get_args():
parser = argparse.ArgumentParser(description... | compleconta.py |
# usage: compleconta.py /path/to/protein_file.faa /path/to/hmmer_results.faa.out
import sys
import os
import subprocess
import argparse
from compleconta import FileIO, Annotation, EnogLists, aminoAcidIdentity, Check, MarkerGeneBlast, ncbiTaxonomyTree
def get_args():
parser = argparse.ArgumentParser(description... | 0.410047 | 0.156523 |
import re
import json
from xml.dom import minidom
from hashlib import sha256
# This list is up-to-date as of 11/19/2021.
# Please contact <EMAIL> if your eyes-on subscription is not included.
EYES_ON_SUBSCRIPTIONS = set(
[
"dfcaf96e30a340fae2fcd5871a5e94cf3805f6521d5e2571d55b097df857c9c3",
"89b8... | shrike/_core/eyesoff.py |
import re
import json
from xml.dom import minidom
from hashlib import sha256
# This list is up-to-date as of 11/19/2021.
# Please contact <EMAIL> if your eyes-on subscription is not included.
EYES_ON_SUBSCRIPTIONS = set(
[
"dfcaf96e30a340fae2fcd5871a5e94cf3805f6521d5e2571d55b097df857c9c3",
"89b8... | 0.298083 | 0.074905 |
from typing import List
from dataclasses import dataclass
import dataclasses_json
import json
import stringcase
from ..common.utils import OrderedEnum, ExtendedEncoder
from ..common.modelcommon import (
ArmorPenetration,
DamageType,
Health,
HealthRegen,
Mana,
ManaRegen,
Armor,
MagicResi... | lolstaticdata/items/modelitem.py | from typing import List
from dataclasses import dataclass
import dataclasses_json
import json
import stringcase
from ..common.utils import OrderedEnum, ExtendedEncoder
from ..common.modelcommon import (
ArmorPenetration,
DamageType,
Health,
HealthRegen,
Mana,
ManaRegen,
Armor,
MagicResi... | 0.524395 | 0.160365 |
import collections
import datetime
import json
import os
from core.results_processor import util
OUTPUT_FILENAME = 'test-results.json'
def ProcessIntermediateResults(test_results, options):
"""Process intermediate results and write output in output_dir."""
results = Convert(test_results, options.output_dir, op... | tools/perf/core/results_processor/formatters/json3_output.py | import collections
import datetime
import json
import os
from core.results_processor import util
OUTPUT_FILENAME = 'test-results.json'
def ProcessIntermediateResults(test_results, options):
"""Process intermediate results and write output in output_dir."""
results = Convert(test_results, options.output_dir, op... | 0.583203 | 0.351923 |
import pandas as pd
import torch
import matplotlib.pyplot as plt
from sklearn.model_selection import train_test_split
import numpy as np
# extract data from csv files
def data_preprocessing(data_path, device='cpu'):
# train_dataset
train_validation_test = ['train', 'validation', 'test']
X, y = ... | model/util.py | import pandas as pd
import torch
import matplotlib.pyplot as plt
from sklearn.model_selection import train_test_split
import numpy as np
# extract data from csv files
def data_preprocessing(data_path, device='cpu'):
# train_dataset
train_validation_test = ['train', 'validation', 'test']
X, y = ... | 0.733738 | 0.642769 |
from django.shortcuts import get_object_or_404
from rest_framework import viewsets, permissions, status
from rest_framework.decorators import action
from rest_framework.response import Response
from .serializers import *
class RoomViewSet(viewsets.ModelViewSet):
serializer_class = RoomSerializer
queryset = R... | api/views.py | from django.shortcuts import get_object_or_404
from rest_framework import viewsets, permissions, status
from rest_framework.decorators import action
from rest_framework.response import Response
from .serializers import *
class RoomViewSet(viewsets.ModelViewSet):
serializer_class = RoomSerializer
queryset = R... | 0.456652 | 0.133924 |
from __future__ import absolute_import, division, unicode_literals
import ddt
from twisted.trial.unittest import SynchronousTestCase
from mimic.model.identity_errors import (
EndpointTemplateAlreadyExists,
EndpointTemplateDisabledForTenant,
EndpointTemplateDoesNotExist,
InvalidEndpointTemplateId,
... | mimic/test/test_identity_objects.py | from __future__ import absolute_import, division, unicode_literals
import ddt
from twisted.trial.unittest import SynchronousTestCase
from mimic.model.identity_errors import (
EndpointTemplateAlreadyExists,
EndpointTemplateDisabledForTenant,
EndpointTemplateDoesNotExist,
InvalidEndpointTemplateId,
... | 0.798226 | 0.331796 |
from __future__ import annotations
import json
from meerschaum.utils.packages import import_html, import_dcc
html, dcc = import_html(), import_dcc()
import dash_bootstrap_components as dbc
from meerschaum.api import permissions_config, endpoints
from meerschaum.config import get_config
dash_endpoint = endpoints['dash'... | meerschaum/api/dash/pages/login.py | from __future__ import annotations
import json
from meerschaum.utils.packages import import_html, import_dcc
html, dcc = import_html(), import_dcc()
import dash_bootstrap_components as dbc
from meerschaum.api import permissions_config, endpoints
from meerschaum.config import get_config
dash_endpoint = endpoints['dash'... | 0.487307 | 0.061087 |
import requests
import pandas as pd
import re
import datetime as dt
from bs4 import BeautifulSoup as bs
# comprehend list for years
years = [str(2000 + i) for i in range(5,19)]
this_year = '2019'
# print(years)
# multiple functions for cleaning data
# regex for finding round names
pattern = re.compile("^(Round|Week|S... | data_features.py | import requests
import pandas as pd
import re
import datetime as dt
from bs4 import BeautifulSoup as bs
# comprehend list for years
years = [str(2000 + i) for i in range(5,19)]
this_year = '2019'
# print(years)
# multiple functions for cleaning data
# regex for finding round names
pattern = re.compile("^(Round|Week|S... | 0.191177 | 0.245435 |
import pytest
from click.testing import CliRunner
from clinicadl.cmdline import cli
# Test to ensure that the help string at the command line is invoked without errors
# Test for the first level at the command line
@pytest.fixture(
params=[
"extract",
"generate",
"interpret",
"pr... | tests/test_cli.py |
import pytest
from click.testing import CliRunner
from clinicadl.cmdline import cli
# Test to ensure that the help string at the command line is invoked without errors
# Test for the first level at the command line
@pytest.fixture(
params=[
"extract",
"generate",
"interpret",
"pr... | 0.475849 | 0.481515 |
import argparse
from vit import fine_tune
if __name__ == "__main__":
parser = argparse.ArgumentParser(description='Train VQ-VAE')
# Directory args
parser.add_argument("--data_dir",
default="./data/ImageNet",
help="location dataset is stored",
... | fine_tune_vit.py | import argparse
from vit import fine_tune
if __name__ == "__main__":
parser = argparse.ArgumentParser(description='Train VQ-VAE')
# Directory args
parser.add_argument("--data_dir",
default="./data/ImageNet",
help="location dataset is stored",
... | 0.421314 | 0.068631 |
import os
import WrightTools as wt
import matplotlib.pyplot as plt
from itertools import islice
import numpy as np
from . import artists as art
from . import data_import as di
from . import format_conversions as fc
def director_hl3_full(directory, verbose, hdf5, plot, fit):
count = 0
for root, dirs, files in... | research_kit/quick.py | import os
import WrightTools as wt
import matplotlib.pyplot as plt
from itertools import islice
import numpy as np
from . import artists as art
from . import data_import as di
from . import format_conversions as fc
def director_hl3_full(directory, verbose, hdf5, plot, fit):
count = 0
for root, dirs, files in... | 0.267504 | 0.185523 |
import shutil
from pathlib import Path
import pprint
import yaml
try:
from agavepy.agave import Agave
except ImportError: pass
from git import Repo
from git.exc import GitError
import requests
from geneflow.app_installer import AppInstaller
from geneflow.data_manager import DataManager
from geneflow.log import L... | src/geneflow/workflow_installer.py | import shutil
from pathlib import Path
import pprint
import yaml
try:
from agavepy.agave import Agave
except ImportError: pass
from git import Repo
from git.exc import GitError
import requests
from geneflow.app_installer import AppInstaller
from geneflow.data_manager import DataManager
from geneflow.log import L... | 0.496094 | 0.070336 |
from .fhirbase import fhirbase
class SampledData(fhirbase):
"""
A series of measurements taken by a device, with upper and lower
limits. There may be more than one dimension in the data.
Args:
origin: The base quantity that a measured value of zero represents. In
addition, this pr... | cardea/fhir/SampledData.py | from .fhirbase import fhirbase
class SampledData(fhirbase):
"""
A series of measurements taken by a device, with upper and lower
limits. There may be more than one dimension in the data.
Args:
origin: The base quantity that a measured value of zero represents. In
addition, this pr... | 0.921803 | 0.710854 |
import argparse
import time
import unittest
import dbinfo
import numpy as np
from aperturedb import Connector, Status
from aperturedb import EntityLoader, ConnectionLoader
from aperturedb import ImageLoader, BBoxLoader, BlobLoader
from aperturedb import DescriptorSetLoader, DescriptorLoader
class TestLoader(unittes... | test/test_Loaders.py | import argparse
import time
import unittest
import dbinfo
import numpy as np
from aperturedb import Connector, Status
from aperturedb import EntityLoader, ConnectionLoader
from aperturedb import ImageLoader, BBoxLoader, BlobLoader
from aperturedb import DescriptorSetLoader, DescriptorLoader
class TestLoader(unittes... | 0.337422 | 0.088465 |
import torch.utils.data as data
import os.path
from PIL import Image
from glob import glob
from shutil import copyfile, rmtree
import numpy as np
import scipy.io
import pandas as pd
import torch
from torch.autograd import Variable
from torchvision import transforms
IMG_EXTENSIONS = [
'.jpg', '.JPG', '.jpeg', '... | ml_src/preprocessing.py | import torch.utils.data as data
import os.path
from PIL import Image
from glob import glob
from shutil import copyfile, rmtree
import numpy as np
import scipy.io
import pandas as pd
import torch
from torch.autograd import Variable
from torchvision import transforms
IMG_EXTENSIONS = [
'.jpg', '.JPG', '.jpeg', '... | 0.580947 | 0.371707 |
import pygame
import pygcurse
from pygame.locals import *
from win32api import GetSystemMetrics
from graph.twodmap import TwoDMap
class GuiState(object):
def __init__(self, gui):
self.gui = gui
def update(self, events):
for event in events:
if event.type == QUIT or (event.type == ... | graphalgogui.py | import pygame
import pygcurse
from pygame.locals import *
from win32api import GetSystemMetrics
from graph.twodmap import TwoDMap
class GuiState(object):
def __init__(self, gui):
self.gui = gui
def update(self, events):
for event in events:
if event.type == QUIT or (event.type == ... | 0.452294 | 0.17849 |
from __future__ import print_function
from pynams import styles
from olivine.SanCarlos import SanCarlos_spectra as SC
from olivine.KilaueaIki import Kiki_spectra as kiki
import os
import olivine
file = os.path.join(olivine.__path__[0], 'Fig6_SC_vs_Kiki.tif')
specSCinit = SC.SC_untreated_Ea
specSC = SC.wb_800C_hyd_ave... | olivine/Fig6_SC_vs_Kiki.py | from __future__ import print_function
from pynams import styles
from olivine.SanCarlos import SanCarlos_spectra as SC
from olivine.KilaueaIki import Kiki_spectra as kiki
import os
import olivine
file = os.path.join(olivine.__path__[0], 'Fig6_SC_vs_Kiki.tif')
specSCinit = SC.SC_untreated_Ea
specSC = SC.wb_800C_hyd_ave... | 0.493653 | 0.18418 |
from typing import TYPE_CHECKING, Dict, Any, Optional
if TYPE_CHECKING:
from vizier.engine.project.base import ProjectHandle
from vizier.viztrail.branch import BranchHandle
from vizier.viztrail.workflow import WorkflowHandle, WorkflowDescriptor
from vizier.api.routes.base import UrlFactory
import vizier.ap... | vizier/api/serialize/workflow.py | from typing import TYPE_CHECKING, Dict, Any, Optional
if TYPE_CHECKING:
from vizier.engine.project.base import ProjectHandle
from vizier.viztrail.branch import BranchHandle
from vizier.viztrail.workflow import WorkflowHandle, WorkflowDescriptor
from vizier.api.routes.base import UrlFactory
import vizier.ap... | 0.876039 | 0.141697 |
import milk.supervised.svm
from milk.supervised.svm import svm_learn_smo, svm_learn_libsvm, _svm_apply, learn_sigmoid_constants, svm_sigmoidal_correction
import numpy
import random
import numpy as np
import milk.supervised.svm
import pickle
eps=1e-3
def approximate(a,b):
a=numpy.asanyarray(a)
b=numpy.asanyarray... | milk/tests/test_svm.py | import milk.supervised.svm
from milk.supervised.svm import svm_learn_smo, svm_learn_libsvm, _svm_apply, learn_sigmoid_constants, svm_sigmoidal_correction
import numpy
import random
import numpy as np
import milk.supervised.svm
import pickle
eps=1e-3
def approximate(a,b):
a=numpy.asanyarray(a)
b=numpy.asanyarray... | 0.569015 | 0.485966 |
import os
import sys
import time
import random
class self.seconds_before_artwork_change()
s = 3600
class self.time_last_image_change = datetime.datetime.now()
class ArtCronJob:
"""
Parameters
----------
active_artwork_file_path : str
Path to the active artwork file. This is the image tha... | kiosk/artcronjob.py | import os
import sys
import time
import random
class self.seconds_before_artwork_change()
s = 3600
class self.time_last_image_change = datetime.datetime.now()
class ArtCronJob:
"""
Parameters
----------
active_artwork_file_path : str
Path to the active artwork file. This is the image tha... | 0.455683 | 0.260303 |
import argparse
import os, os.path
import sys
import subprocess
#=========================================================
parser = argparse.ArgumentParser(
description="OTU table; in biom format")
parser.add_argument(
'-i',
'--otu_table',
help = "Biom format",
required = True)
parser.add_argument(
'-o',
'--... | Convert_to_RelAbund.py |
import argparse
import os, os.path
import sys
import subprocess
#=========================================================
parser = argparse.ArgumentParser(
description="OTU table; in biom format")
parser.add_argument(
'-i',
'--otu_table',
help = "Biom format",
required = True)
parser.add_argument(
'-o',
'--... | 0.302906 | 0.169303 |
from __future__ import annotations
from typing import Any
import matplotlib.pyplot as plt
import numpy as np
import PIL.Image
from matplotlib import patches
from matplotlib import patheffects
from CCAgT_utils.categories import CategoriesInfos
from CCAgT_utils.types.annotation import BBox
from CCAgT_utils.types.mask ... | CCAgT_utils/visualization/plot.py | from __future__ import annotations
from typing import Any
import matplotlib.pyplot as plt
import numpy as np
import PIL.Image
from matplotlib import patches
from matplotlib import patheffects
from CCAgT_utils.categories import CategoriesInfos
from CCAgT_utils.types.annotation import BBox
from CCAgT_utils.types.mask ... | 0.845688 | 0.315921 |
import numpy as np
import matplotlib.pyplot as plt
from matplotlib import animation
def init_byouga(plt):
""" 迷路の初期描画"""
# 迷路を描画
fig = plt.figure(figsize=(5, 5))
ax = plt.gca()
# 壁の描画
plt.plot([1,1], [0,1], color='red', linewidth=2)
plt.plot([1,2], [2,2], color='red', lin... | Deep-Reinforcement-Learning-Book/meirotansaku/housakuhanpuku/my_meirotansaku_housakuhanpuku.py | import numpy as np
import matplotlib.pyplot as plt
from matplotlib import animation
def init_byouga(plt):
""" 迷路の初期描画"""
# 迷路を描画
fig = plt.figure(figsize=(5, 5))
ax = plt.gca()
# 壁の描画
plt.plot([1,1], [0,1], color='red', linewidth=2)
plt.plot([1,2], [2,2], color='red', lin... | 0.26588 | 0.636381 |
import logging
import os
import threading
import time
import fs.path
from watchdog.observers import Observer
from watchdog.events import FileSystemEventHandler
import events
log = logging.getLogger(__name__)
class Watcher(threading.Thread):
def __init__(self, processing, sync_dir, moved_callback=None,
... | app/sync/watcher.py | import logging
import os
import threading
import time
import fs.path
from watchdog.observers import Observer
from watchdog.events import FileSystemEventHandler
import events
log = logging.getLogger(__name__)
class Watcher(threading.Thread):
def __init__(self, processing, sync_dir, moved_callback=None,
... | 0.416322 | 0.047625 |
__author__ = '<NAME>'
__copyright__ = 'Copyright (C) 2018, Nokia'
__email__ = '<EMAIL>'
from moler.cmd.unix.genericunix import GenericUnixCommand
from moler.exceptions import CommandFailure
from moler.exceptions import ParsingDone
import re
class Gunzip(GenericUnixCommand):
def __init__(self, connection, archive... | moler/cmd/unix/gunzip.py | __author__ = '<NAME>'
__copyright__ = 'Copyright (C) 2018, Nokia'
__email__ = '<EMAIL>'
from moler.cmd.unix.genericunix import GenericUnixCommand
from moler.exceptions import CommandFailure
from moler.exceptions import ParsingDone
import re
class Gunzip(GenericUnixCommand):
def __init__(self, connection, archive... | 0.427516 | 0.076718 |
import time
import base64
import json
import math
from .util.json_canonicalize.Canonicalize import canonicalize
from .signer_algorithm import verify_ES256K
from src.util import pad_base64
from src.ebsi_did_resolver import resolve
def decode_jws(jws):
parts = jws.split(".")
assert len(parts) == 3
return... | src/did_jwt/__init__.py | import time
import base64
import json
import math
from .util.json_canonicalize.Canonicalize import canonicalize
from .signer_algorithm import verify_ES256K
from src.util import pad_base64
from src.ebsi_did_resolver import resolve
def decode_jws(jws):
parts = jws.split(".")
assert len(parts) == 3
return... | 0.551574 | 0.356167 |
import os.path as osp
from mmcv.runner import HOOKS, Hook, master_only
from mmcv.runner.checkpoint import save_checkpoint, get_state_dict, weights_to_cpu
from torch.optim.swa_utils import AveragedModel
from mmdet.core import EvalHook, DistEvalHook
import torch
import mmcv
@HOOKS.register_module()
class SWAHook(Hook)... | mmdet/core/utils/swa_hook.py | import os.path as osp
from mmcv.runner import HOOKS, Hook, master_only
from mmcv.runner.checkpoint import save_checkpoint, get_state_dict, weights_to_cpu
from torch.optim.swa_utils import AveragedModel
from mmdet.core import EvalHook, DistEvalHook
import torch
import mmcv
@HOOKS.register_module()
class SWAHook(Hook)... | 0.811041 | 0.24747 |
import os
import csv
import json
from string import ascii_uppercase
from collections import Counter
import numpy as np
from tqdm import tqdm
from sklearn.utils import shuffle
from sklearn.model_selection import train_test_split
seed = 3535999445
def _rocstories(path):
with open(path) as f:
f = csv.read... | datasets.py | import os
import csv
import json
from string import ascii_uppercase
from collections import Counter
import numpy as np
from tqdm import tqdm
from sklearn.utils import shuffle
from sklearn.model_selection import train_test_split
seed = 3535999445
def _rocstories(path):
with open(path) as f:
f = csv.read... | 0.146545 | 0.152821 |
from __future__ import print_function
import collections
try:
from docker.errors import APIError
except ImportError:
# Fall back to <= 0.3.1 location
from docker.client import APIError
import json
import time
try:
import urlparse
except ImportError:
# Try for Python3
from urllib import parse... | maestro/plays/tasks.py |
from __future__ import print_function
import collections
try:
from docker.errors import APIError
except ImportError:
# Fall back to <= 0.3.1 location
from docker.client import APIError
import json
import time
try:
import urlparse
except ImportError:
# Try for Python3
from urllib import parse... | 0.664431 | 0.135976 |
import datetime
import getopt
from util.util_filepath import *
class UtilParameter:
GLOBAL = "global"
DATASET = "dataset"
MODEL_BUILD = "build"
TRAIN = "train"
PREDICT = "predict"
part = [GLOBAL, DATASET, MODEL_BUILD, TRAIN, PREDICT]
# part: 模块划分
def __init__(self, file_name="config_... | util/util_parameter.py | import datetime
import getopt
from util.util_filepath import *
class UtilParameter:
GLOBAL = "global"
DATASET = "dataset"
MODEL_BUILD = "build"
TRAIN = "train"
PREDICT = "predict"
part = [GLOBAL, DATASET, MODEL_BUILD, TRAIN, PREDICT]
# part: 模块划分
def __init__(self, file_name="config_... | 0.157655 | 0.095856 |
import json
import warnings
import pulumi
import pulumi.runtime
from typing import Union
from . import utilities, tables
class UserContactMethod(pulumi.CustomResource):
address: pulumi.Output[str]
"""
The "address" to deliver to: `email`, `phone number`, etc., depending on the type.
"""
blackliste... | sdk/python/pulumi_pagerduty/user_contact_method.py |
import json
import warnings
import pulumi
import pulumi.runtime
from typing import Union
from . import utilities, tables
class UserContactMethod(pulumi.CustomResource):
address: pulumi.Output[str]
"""
The "address" to deliver to: `email`, `phone number`, etc., depending on the type.
"""
blackliste... | 0.73173 | 0.218701 |
from copy import deepcopy
from django.urls import reverse
from django.test import override_settings
from django.conf import settings
from rest_framework.test import APITestCase
from formidable.models import Formidable
from . import form_data, form_data_items
class CreateFormTestCase(APITestCase):
@override_s... | demo/tests/test_post_save_callbacks_regression_tests.py | from copy import deepcopy
from django.urls import reverse
from django.test import override_settings
from django.conf import settings
from rest_framework.test import APITestCase
from formidable.models import Formidable
from . import form_data, form_data_items
class CreateFormTestCase(APITestCase):
@override_s... | 0.462959 | 0.092811 |
from galaxy.util import bunch
import logging
log = logging.getLogger( __name__ )
def form( *args, **kwargs ):
return FormBuilder( *args, **kwargs )
class FormBuilder( object ):
"""
Simple class describing an HTML form
"""
def __init__( self, action="", title="", name="form", submit_text="submit... | lib/galaxy/web/framework/formbuilder.py | from galaxy.util import bunch
import logging
log = logging.getLogger( __name__ )
def form( *args, **kwargs ):
return FormBuilder( *args, **kwargs )
class FormBuilder( object ):
"""
Simple class describing an HTML form
"""
def __init__( self, action="", title="", name="form", submit_text="submit... | 0.610802 | 0.081374 |
import os
import json
import time
import pyasn
import logging
import requests
import ipaddress
import numpy as np
from datetime import datetime
import matplotlib.pyplot as plt
from collections import defaultdict
from concurrent.futures import ThreadPoolExecutor
class Parser(object):
class IPAddr(object):
... | draft-version/utils/node_churn.py | import os
import json
import time
import pyasn
import logging
import requests
import ipaddress
import numpy as np
from datetime import datetime
import matplotlib.pyplot as plt
from collections import defaultdict
from concurrent.futures import ThreadPoolExecutor
class Parser(object):
class IPAddr(object):
... | 0.328099 | 0.148386 |
from PySide2.QtWidgets import *
from PySide2.QtCore import *
from PySide2.QtGui import *
class SideGrip(QWidget):
def __init__(self, parent, edge):
QWidget.__init__(self, parent)
#self.setWindowFlags(Qt.FramelessWindowHint)
#self.setAttribute(Qt.WA_TranslucentBackground)
if edge == ... | modules/ui/resize_grid.py | from PySide2.QtWidgets import *
from PySide2.QtCore import *
from PySide2.QtGui import *
class SideGrip(QWidget):
def __init__(self, parent, edge):
QWidget.__init__(self, parent)
#self.setWindowFlags(Qt.FramelessWindowHint)
#self.setAttribute(Qt.WA_TranslucentBackground)
if edge == ... | 0.528777 | 0.139543 |
from dataclasses import dataclass
from random import shuffle
import ipaddr
import pytest
from pycroft.helpers.net import sort_ports
from pycroft.lib.host import change_mac, generate_hostname
from pycroft.lib.net import SubnetFullException, get_free_ip
from pycroft.model.host import IP
from tests import FactoryDataTes... | tests/helpers/test_host.py | from dataclasses import dataclass
from random import shuffle
import ipaddr
import pytest
from pycroft.helpers.net import sort_ports
from pycroft.lib.host import change_mac, generate_hostname
from pycroft.lib.net import SubnetFullException, get_free_ip
from pycroft.model.host import IP
from tests import FactoryDataTes... | 0.539711 | 0.439026 |
from numpy.testing import assert_array_equal
from rl.callbacks import History, AgentStateLogger, EnvironmentStateLogger
from rl.simulator import SingleAgentWaitingSimulator
from .fakes import FakeEnvironment, fake_agent
class TestHistory:
def test_init(self) -> None:
h = History()
assert len(h.sta... | tests/test_callbacks.py | from numpy.testing import assert_array_equal
from rl.callbacks import History, AgentStateLogger, EnvironmentStateLogger
from rl.simulator import SingleAgentWaitingSimulator
from .fakes import FakeEnvironment, fake_agent
class TestHistory:
def test_init(self) -> None:
h = History()
assert len(h.sta... | 0.779657 | 0.725454 |
import torch
import torch.nn as nn
import torch.optim as optim
import torch.nn.functional as F
import torch.backends.cudnn as cudnn
import torchvision
import torchvision.transforms as transforms
import os
import argparse
from sklearn.metrics import classification_report
from datasets import cifar10
import metrics
fro... | codes/20200113_pytorch_cifar10_arcface/src/train.py | import torch
import torch.nn as nn
import torch.optim as optim
import torch.nn.functional as F
import torch.backends.cudnn as cudnn
import torchvision
import torchvision.transforms as transforms
import os
import argparse
from sklearn.metrics import classification_report
from datasets import cifar10
import metrics
fro... | 0.807688 | 0.302224 |
import unittest
import numpy as np
from graph_nets import utils_tf
from bark.runtime.commons.parameters import ParameterServer
from bark_ml.observers.graph_observer import GraphObserver
class PyGraphNetsTests(unittest.TestCase):
def test_gnn(self):
# Node features for graph 0.
nodes_0 = [[10.1, 20., 30.]... | bark_ml/tests/py_graph_nets_tests.py |
import unittest
import numpy as np
from graph_nets import utils_tf
from bark.runtime.commons.parameters import ParameterServer
from bark_ml.observers.graph_observer import GraphObserver
class PyGraphNetsTests(unittest.TestCase):
def test_gnn(self):
# Node features for graph 0.
nodes_0 = [[10.1, 20., 30.]... | 0.59561 | 0.551091 |
import argparse
from maple.launchers.launcher_util import run_experiment
from maple.launchers.robosuite_launcher import experiment
import maple.util.hyperparameter as hyp
import collections
base_variant = dict(
layer_size=256,
replay_buffer_size=int(1E6),
rollout_fn_kwargs=dict(
terminals_all_fals... | scripts/train.py | import argparse
from maple.launchers.launcher_util import run_experiment
from maple.launchers.robosuite_launcher import experiment
import maple.util.hyperparameter as hyp
import collections
base_variant = dict(
layer_size=256,
replay_buffer_size=int(1E6),
rollout_fn_kwargs=dict(
terminals_all_fals... | 0.484624 | 0.181789 |
import pandas as pd
import numpy as np
import time
from sklearn.feature_extraction.text import TfidfVectorizer
from sklearn.metrics import accuracy_score, f1_score
from sklearn.ensemble import RandomForestClassifier
# Load datasets
df = pd.read_csv('Data/all_cves_cleaned.csv')
# Extract year from ID
import re
def ex... | Reproduction package/RQ3_WoM_Testing.py | import pandas as pd
import numpy as np
import time
from sklearn.feature_extraction.text import TfidfVectorizer
from sklearn.metrics import accuracy_score, f1_score
from sklearn.ensemble import RandomForestClassifier
# Load datasets
df = pd.read_csv('Data/all_cves_cleaned.csv')
# Extract year from ID
import re
def ex... | 0.750095 | 0.41324 |
import os
import shutil
import pandas as pd
import numpy as np
import cv2 as cv
from PIL import Image
import argparse
import re
from tqdm import tqdm
def get_parser():
parser = argparse.ArgumentParser(description='parameters for dataset preprocessing')
parser.add_argument('--input_dir', default="", help='Input... | preprocessor.py | import os
import shutil
import pandas as pd
import numpy as np
import cv2 as cv
from PIL import Image
import argparse
import re
from tqdm import tqdm
def get_parser():
parser = argparse.ArgumentParser(description='parameters for dataset preprocessing')
parser.add_argument('--input_dir', default="", help='Input... | 0.078709 | 0.123868 |
import json
from typing import Optional
from shipengine.enums import ErrorCode, ErrorSource, ErrorType, does_member_value_exist
class ShipEngineError(Exception):
def __init__(
self,
message: str,
request_id: Optional[str] = None,
error_source: Optional[str] = None,
error_t... | shipengine/errors/__init__.py | import json
from typing import Optional
from shipengine.enums import ErrorCode, ErrorSource, ErrorType, does_member_value_exist
class ShipEngineError(Exception):
def __init__(
self,
message: str,
request_id: Optional[str] = None,
error_source: Optional[str] = None,
error_t... | 0.883097 | 0.102619 |
from django.shortcuts import render
from django.views import View
from driver.models import store,driver,order
from django.shortcuts import render
from django.views import View
from django.contrib.auth.mixins import UserPassesTestMixin, LoginRequiredMixin
from django.utils.timezone import datetime
from .forms import Or... | src/store/views.py | from django.shortcuts import render
from django.views import View
from driver.models import store,driver,order
from django.shortcuts import render
from django.views import View
from django.contrib.auth.mixins import UserPassesTestMixin, LoginRequiredMixin
from django.utils.timezone import datetime
from .forms import Or... | 0.331228 | 0.058158 |
from hathor.checkpoint import Checkpoint as cp
from hathor.conf.settings import HathorSettings
SETTINGS = HathorSettings(
P2PKH_VERSION_BYTE=b'\x49',
MULTISIG_VERSION_BYTE=b'\x87',
NETWORK_NAME='testnet-golf',
BOOTSTRAP_DNS=['golf.testnet.hathor.network'],
# Genesis stuff
GENESIS_OUTPUT_SCRIPT... | hathor/conf/testnet.py |
from hathor.checkpoint import Checkpoint as cp
from hathor.conf.settings import HathorSettings
SETTINGS = HathorSettings(
P2PKH_VERSION_BYTE=b'\x49',
MULTISIG_VERSION_BYTE=b'\x87',
NETWORK_NAME='testnet-golf',
BOOTSTRAP_DNS=['golf.testnet.hathor.network'],
# Genesis stuff
GENESIS_OUTPUT_SCRIPT... | 0.36557 | 0.175573 |
import inspect
from pysec.core import Object, Error
from pysec.expr import Expression
from pysec import lang
NO_CHECK = Object()
class CheckError(Error):
pass
class CheckRuleError(Error, ValueError):
def __init__(self, check, values):
self.check = check
self.values = values
def __st... | pysec/check.py | import inspect
from pysec.core import Object, Error
from pysec.expr import Expression
from pysec import lang
NO_CHECK = Object()
class CheckError(Error):
pass
class CheckRuleError(Error, ValueError):
def __init__(self, check, values):
self.check = check
self.values = values
def __st... | 0.401336 | 0.123102 |
import numpy as np
import six
from sklearn.base import TransformerMixin, BaseEstimator
from sklearn.exceptions import NotFittedError
from gensim import models
class FTTransformer(TransformerMixin, BaseEstimator):
"""Base FastText module, wraps :class:`~gensim.models.fasttext.FastText`.
For more information ... | bobo/Lib/site-packages/gensim/sklearn_api/ftmodel.py | import numpy as np
import six
from sklearn.base import TransformerMixin, BaseEstimator
from sklearn.exceptions import NotFittedError
from gensim import models
class FTTransformer(TransformerMixin, BaseEstimator):
"""Base FastText module, wraps :class:`~gensim.models.fasttext.FastText`.
For more information ... | 0.92849 | 0.597784 |
import contextlib
from types import MappingProxyType
from typing import Any
from unittest.mock import patch
import pytest
from renault_api.kamereon import exceptions, schemas
from renault_api.renault_account import RenaultAccount
from homeassistant.components.renault.const import DOMAIN
from homeassistant.config_entr... | tests/components/renault/conftest.py | import contextlib
from types import MappingProxyType
from typing import Any
from unittest.mock import patch
import pytest
from renault_api.kamereon import exceptions, schemas
from renault_api.renault_account import RenaultAccount
from homeassistant.components.renault.const import DOMAIN
from homeassistant.config_entr... | 0.73412 | 0.217815 |
from __future__ import division
import warnings
from distutils.version import LooseVersion
import numpy as np
import sklearn
from sklearn.base import TransformerMixin
from sklearn.decomposition import dict_learning_online
from sklearn.externals.joblib import Memory
from sklearn.linear_model import Ridge
from .base ... | nilearn/decomposition/dict_learning.py |
from __future__ import division
import warnings
from distutils.version import LooseVersion
import numpy as np
import sklearn
from sklearn.base import TransformerMixin
from sklearn.decomposition import dict_learning_online
from sklearn.externals.joblib import Memory
from sklearn.linear_model import Ridge
from .base ... | 0.945764 | 0.481454 |
import logging
import discord
from discord.ext import commands
class BooksCog(commands.Cog):
"""
This cog is for commands that are related to retrieve info from books.
"""
def __init__(self, bot):
self.bot = bot
@commands.command(name="monster", aliases=['m'])
async def monster(self,... | src/cogs/books.py | import logging
import discord
from discord.ext import commands
class BooksCog(commands.Cog):
"""
This cog is for commands that are related to retrieve info from books.
"""
def __init__(self, bot):
self.bot = bot
@commands.command(name="monster", aliases=['m'])
async def monster(self,... | 0.632616 | 0.152001 |
# Based on
# https://github.com/hjuutilainen/adminscripts/blob/master/
# check-10.12-sierra-compatibility.py
# sysctl function by <NAME>
# https://gist.github.com/pudquick/581a71425439f2cf8f09
# IOKit bindings by <NAME>
# https://gist.github.com/pudquick/
# c7dd1262bd81a32663f0#file-get_platform-py-L... | facts/mojave_upgrade_supported.py |
# Based on
# https://github.com/hjuutilainen/adminscripts/blob/master/
# check-10.12-sierra-compatibility.py
# sysctl function by <NAME>
# https://gist.github.com/pudquick/581a71425439f2cf8f09
# IOKit bindings by <NAME>
# https://gist.github.com/pudquick/
# c7dd1262bd81a32663f0#file-get_platform-py-L... | 0.506836 | 0.147986 |
import nanome
from nanome.api.structure import Complex
from nanome.util import async_callback, Logs
from cairosvg import svg2png
from rdkit import Chem
from rdkit.Chem import AllChem, Draw
import argparse
import asyncio
import base64
import json
import os
import random
import string
import tempfile
import websockets
... | plugin/DataTable.py | import nanome
from nanome.api.structure import Complex
from nanome.util import async_callback, Logs
from cairosvg import svg2png
from rdkit import Chem
from rdkit.Chem import AllChem, Draw
import argparse
import asyncio
import base64
import json
import os
import random
import string
import tempfile
import websockets
... | 0.319227 | 0.184345 |
import json
import os
import sys
import xml.dom.minidom as minidom
from collections import deque
from io import StringIO
from typing import List
from .common import get_text
from .config import SEARCHOPTIONSPATH
from .searchexception import SearchException
from .searchoption import SearchOption
from .searchsettings im... | python/pysearch/pysearch/searchoptions.py | import json
import os
import sys
import xml.dom.minidom as minidom
from collections import deque
from io import StringIO
from typing import List
from .common import get_text
from .config import SEARCHOPTIONSPATH
from .searchexception import SearchException
from .searchoption import SearchOption
from .searchsettings im... | 0.344113 | 0.078961 |
"""Plist related rdfvalues."""
from __future__ import absolute_import
from __future__ import division
from __future__ import unicode_literals
from grr_response_core.lib import lexer
from grr_response_core.lib import plist
from grr_response_core.lib import rdfvalue
from grr_response_core.lib import type_info
from grr_... | Incident-Response/Tools/grr/grr/core/grr_response_core/lib/rdfvalues/plist.py | """Plist related rdfvalues."""
from __future__ import absolute_import
from __future__ import division
from __future__ import unicode_literals
from grr_response_core.lib import lexer
from grr_response_core.lib import plist
from grr_response_core.lib import rdfvalue
from grr_response_core.lib import type_info
from grr_... | 0.64969 | 0.213582 |
from .fetchers import NUMetadatasFetcher
from .fetchers import NUGlobalMetadatasFetcher
from bambou import NURESTObject
class NUBGPProfile(NURESTObject):
""" Represents a BGPProfile in the VSD
Notes:
Definitions for default import/export routing policies and dampening profiles
"""
... | vspk/v5_0/nubgpprofile.py |
from .fetchers import NUMetadatasFetcher
from .fetchers import NUGlobalMetadatasFetcher
from bambou import NURESTObject
class NUBGPProfile(NURESTObject):
""" Represents a BGPProfile in the VSD
Notes:
Definitions for default import/export routing policies and dampening profiles
"""
... | 0.766556 | 0.101589 |
from __future__ import print_function
import hashlib
import os
from image_checksummer import ImageChecksummer
from cros_utils.file_utils import FileUtils
from cros_utils import misc
class Label(object):
"""The label class."""
def __init__(self,
name,
build,
chromeos... | crosperf/label.py | from __future__ import print_function
import hashlib
import os
from image_checksummer import ImageChecksummer
from cros_utils.file_utils import FileUtils
from cros_utils import misc
class Label(object):
"""The label class."""
def __init__(self,
name,
build,
chromeos... | 0.610337 | 0.08152 |
import os
from flask.ext.script import Manager, Shell
from flask.ext.migrate import Migrate, MigrateCommand
from longboxed.core import db
from longboxed.frontend import create_app
from longboxed.models import (User, Issue, Title, Publisher, Bundle, Role,
DiamondList)
from longboxed.manag... | manage.py | import os
from flask.ext.script import Manager, Shell
from flask.ext.migrate import Migrate, MigrateCommand
from longboxed.core import db
from longboxed.frontend import create_app
from longboxed.models import (User, Issue, Title, Publisher, Bundle, Role,
DiamondList)
from longboxed.manag... | 0.409221 | 0.041852 |
import sympy
from ..finite_element import CiarletElement
from ..functionals import PointEvaluation, DerivativePointEvaluation
from ..polynomials import polynomial_set
from ..symbolic import PiecewiseFunction, x
class P1Hermite(CiarletElement):
"""P1Hermite finite element."""
def __init__(self, reference, ord... | symfem/elements/rhct.py | import sympy
from ..finite_element import CiarletElement
from ..functionals import PointEvaluation, DerivativePointEvaluation
from ..polynomials import polynomial_set
from ..symbolic import PiecewiseFunction, x
class P1Hermite(CiarletElement):
"""P1Hermite finite element."""
def __init__(self, reference, ord... | 0.637482 | 0.666076 |
from __future__ import absolute_import
import json
from .property import Property
from .util import text, unicode_list
__author__ = "nebula"
class PropertyCondition(object):
TYPE2Class = {
}
@property
def type(self):
raise RuntimeError("not implemented yet")
@property
def srcPrope... | threathunter_common_python/threathunter_common/propertycondition.py | from __future__ import absolute_import
import json
from .property import Property
from .util import text, unicode_list
__author__ = "nebula"
class PropertyCondition(object):
TYPE2Class = {
}
@property
def type(self):
raise RuntimeError("not implemented yet")
@property
def srcPrope... | 0.814533 | 0.172625 |
from pydeflate.tools import exchange
import pandas as pd
import pytest
empty_df = pd.DataFrame([{}])
test_df = pd.DataFrame(
{
"iso_code": ["FRA", "GBR", "USA"],
"date": [2010, 2015, 2018],
"value": [100, 100, 100],
}
)
errors = (
(
"df, source_currency, target_currency, r... | tests/test_tools/test_exchange.py | from pydeflate.tools import exchange
import pandas as pd
import pytest
empty_df = pd.DataFrame([{}])
test_df = pd.DataFrame(
{
"iso_code": ["FRA", "GBR", "USA"],
"date": [2010, 2015, 2018],
"value": [100, 100, 100],
}
)
errors = (
(
"df, source_currency, target_currency, r... | 0.777807 | 0.472379 |
from django.contrib.auth.models import User
from django.contrib.auth import authenticate, login
from django.contrib.messages.storage.fallback import FallbackStorage
from django.http import HttpRequest
from django.test import TestCase
from campaigns.models import *
from campaigns.forms import *
from campaigns.views impo... | campaigns/tests/test_views.py | from django.contrib.auth.models import User
from django.contrib.auth import authenticate, login
from django.contrib.messages.storage.fallback import FallbackStorage
from django.http import HttpRequest
from django.test import TestCase
from campaigns.models import *
from campaigns.forms import *
from campaigns.views impo... | 0.370453 | 0.178418 |
import numpy as np
from scipy.sparse import csc_matrix, isspmatrix_csc
from scipy.sparse.linalg import eigsh
from tqdm.auto import tqdm
from ..chain import Chain
from ..data import Data
from ..posterior import PosteriorParameter
from ..utils import get_generator
from .parallel import sample_parallel
from .state impor... | occuspytial/gibbs/base.py | import numpy as np
from scipy.sparse import csc_matrix, isspmatrix_csc
from scipy.sparse.linalg import eigsh
from tqdm.auto import tqdm
from ..chain import Chain
from ..data import Data
from ..posterior import PosteriorParameter
from ..utils import get_generator
from .parallel import sample_parallel
from .state impor... | 0.897707 | 0.625795 |
import ftplib
import time
import os
import ast
from pathlib import Path
class FTPConnection:
def __init__(self, server, port=21, username='anonymous', password='<PASSWORD>'):
self.server = server
self.port = port
self.username = username
self.password = password
def load(self,... | harvester.py | import ftplib
import time
import os
import ast
from pathlib import Path
class FTPConnection:
def __init__(self, server, port=21, username='anonymous', password='<PASSWORD>'):
self.server = server
self.port = port
self.username = username
self.password = password
def load(self,... | 0.301568 | 0.083106 |
from rest_framework import status
from rest_framework.decorators import APIView
from rest_framework.response import Response
from drf_yasg import openapi
from drf_yasg.utils import swagger_auto_schema
from core import serializers, calculator
class FibonacciView(APIView):
"""fibonacci view in api/calculate/fibona... | core/views.py | from rest_framework import status
from rest_framework.decorators import APIView
from rest_framework.response import Response
from drf_yasg import openapi
from drf_yasg.utils import swagger_auto_schema
from core import serializers, calculator
class FibonacciView(APIView):
"""fibonacci view in api/calculate/fibona... | 0.701713 | 0.132515 |
import pandas as pd
def Pashto_dictionary(num , encoding = "utf-8") :
'''
Pashto_dictionary() is the functin to convert the counting digit into
the Pashto text form. Pashto_dictionary() covering the only 1 to 9 digit
parameter : it takes two parameter one of his by default and othe... | 3-Notebooks/TTS/linguistic_dictionay.py | import pandas as pd
def Pashto_dictionary(num , encoding = "utf-8") :
'''
Pashto_dictionary() is the functin to convert the counting digit into
the Pashto text form. Pashto_dictionary() covering the only 1 to 9 digit
parameter : it takes two parameter one of his by default and othe... | 0.19923 | 0.383612 |
import requests
from django import forms
from django.core.files.uploadedfile import InMemoryUploadedFile
from django.db.models import Q
from captcha.fields import ReCaptchaField
from captcha.fields import ReCaptchaV3
from haystack.backends import SQ
from haystack.inputs import Raw
from haystack.query import EmptySear... | lametro/forms.py | import requests
from django import forms
from django.core.files.uploadedfile import InMemoryUploadedFile
from django.db.models import Q
from captcha.fields import ReCaptchaField
from captcha.fields import ReCaptchaV3
from haystack.backends import SQ
from haystack.inputs import Raw
from haystack.query import EmptySear... | 0.433502 | 0.152442 |
from dataclasses import dataclass, field
from enum import Enum
from typing import Optional, Union
from xsdata.models.datatype import XmlDate, XmlDateTime
from .dynamics import SpellsContent
__NAMESPACE__ = "http://www.gexf.net/1.2draft/viz"
class EdgeShapeType(Enum):
SOLID = "solid"
DOTTED = "dott... | gexfpy/viz.py | from dataclasses import dataclass, field
from enum import Enum
from typing import Optional, Union
from xsdata.models.datatype import XmlDate, XmlDateTime
from .dynamics import SpellsContent
__NAMESPACE__ = "http://www.gexf.net/1.2draft/viz"
class EdgeShapeType(Enum):
SOLID = "solid"
DOTTED = "dott... | 0.878177 | 0.200479 |
from pathlib import Path
import respx
import pytest
import asyncio
from uuid import uuid4
from httpx import Response
from unittest.mock import patch
from qcs_api_client.client import QCSAuth, QCSAccountType, QCSClientConfiguration
from qcs_api_client.client._configuration.secrets import toml
@pytest.mark.parametrize... | tests/test_client/test_auth.py | from pathlib import Path
import respx
import pytest
import asyncio
from uuid import uuid4
from httpx import Response
from unittest.mock import patch
from qcs_api_client.client import QCSAuth, QCSAccountType, QCSClientConfiguration
from qcs_api_client.client._configuration.secrets import toml
@pytest.mark.parametrize... | 0.627152 | 0.205416 |
from httplib import HTTPConnection
import os
from subprocess import Popen, PIPE
import sys
from time import sleep, time
from collections import defaultdict
import unittest
from nose import SkipTest
from swiftclient import get_auth, head_account
from swift.common.ring import Ring
from swift.common.utils import readco... | test/probe/common.py |
from httplib import HTTPConnection
import os
from subprocess import Popen, PIPE
import sys
from time import sleep, time
from collections import defaultdict
import unittest
from nose import SkipTest
from swiftclient import get_auth, head_account
from swift.common.ring import Ring
from swift.common.utils import readco... | 0.241758 | 0.097048 |
from uuid import UUID
from connector import MySQL
from constants import messages
def get_messages(group_id: int):
sql = MySQL(dict_cursor=True)
result = list(sql.query('SELECT submitter, message, image, reg_date FROM messages '
'WHERE group_id=%s ORDER BY reg_date asc', (group_id... | Flask-Base Backend Server/methods/message.py | from uuid import UUID
from connector import MySQL
from constants import messages
def get_messages(group_id: int):
sql = MySQL(dict_cursor=True)
result = list(sql.query('SELECT submitter, message, image, reg_date FROM messages '
'WHERE group_id=%s ORDER BY reg_date asc', (group_id... | 0.203985 | 0.089494 |
import os
from os import listdir
from os.path import isfile, join
import logging
import json
# Log file directory
LOG_DIR = "logs/"
if not os.path.isdir(LOG_DIR):
os.mkdir(LOG_DIR)
# Store move data
MOVE_DATA = None
with open("data/moves/moves.json") as move_file:
MOVE_DATA = json.load(move_file)
# Store pok... | config.py | import os
from os import listdir
from os.path import isfile, join
import logging
import json
# Log file directory
LOG_DIR = "logs/"
if not os.path.isdir(LOG_DIR):
os.mkdir(LOG_DIR)
# Store move data
MOVE_DATA = None
with open("data/moves/moves.json") as move_file:
MOVE_DATA = json.load(move_file)
# Store pok... | 0.290176 | 0.198841 |
import pytest
import voluptuous as vol
from homeassistant.components.sql.sensor import validate_sql_select
from homeassistant.const import STATE_UNKNOWN
from homeassistant.setup import async_setup_component
async def test_query(hass):
"""Test the SQL sensor."""
config = {
"sensor": {
"pla... | tests/components/sql/test_sensor.py | import pytest
import voluptuous as vol
from homeassistant.components.sql.sensor import validate_sql_select
from homeassistant.const import STATE_UNKNOWN
from homeassistant.setup import async_setup_component
async def test_query(hass):
"""Test the SQL sensor."""
config = {
"sensor": {
"pla... | 0.719975 | 0.706159 |
import platform
import unittest
import tempfile
import os
import logging
from subprocess import PIPE, Popen
from conans import __version__ as client_version
from conans.model.version import Version
try:
from StringIO import StringIO
except ImportError:
from io import StringIO
logger = logging.getLogger('cona... | conan_tests/test_regression/utils/base_exe.py | import platform
import unittest
import tempfile
import os
import logging
from subprocess import PIPE, Popen
from conans import __version__ as client_version
from conans.model.version import Version
try:
from StringIO import StringIO
except ImportError:
from io import StringIO
logger = logging.getLogger('cona... | 0.23118 | 0.102484 |
import argparse
import os
import sys
from scheduler import Scheduler
from output import Output
def _check_int_positive(value):
try:
ivalue = int(value)
except ValueError:
raise argparse.ArgumentTypeError("%s is not integer" % value)
if ivalue <= 0:
raise argparse.ArgumentTypeError... | src/benchmark/__main__.py | import argparse
import os
import sys
from scheduler import Scheduler
from output import Output
def _check_int_positive(value):
try:
ivalue = int(value)
except ValueError:
raise argparse.ArgumentTypeError("%s is not integer" % value)
if ivalue <= 0:
raise argparse.ArgumentTypeError... | 0.290075 | 0.098382 |
import math
import shutil
from pathlib import Path
from queue import LifoQueue
from pydantic import Field
from ..agent import (
Agent,
AgentMonitoringDataPoint,
AgentPriority,
TimedAgentConfig,
)
from ..utils.annotations import log_agent_lifecycle
class DiskFillConfig(TimedAgentConfig):
"""
... | src/ychaos/agents/system/disk.py | import math
import shutil
from pathlib import Path
from queue import LifoQueue
from pydantic import Field
from ..agent import (
Agent,
AgentMonitoringDataPoint,
AgentPriority,
TimedAgentConfig,
)
from ..utils.annotations import log_agent_lifecycle
class DiskFillConfig(TimedAgentConfig):
"""
... | 0.631594 | 0.315248 |
import sys
from pathlib import Path
from imgcompare import imgcompare
from PIL import Image
THISDIR = str(Path(__file__).resolve().parent)
sys.path.insert(0, str(Path(THISDIR).parent))
from blendmodes.blend import BlendType, blendLayers
# pylint:disable=invalid-name
def test_normal():
"""Test normal."""
backgr... | test/test.py |
import sys
from pathlib import Path
from imgcompare import imgcompare
from PIL import Image
THISDIR = str(Path(__file__).resolve().parent)
sys.path.insert(0, str(Path(THISDIR).parent))
from blendmodes.blend import BlendType, blendLayers
# pylint:disable=invalid-name
def test_normal():
"""Test normal."""
backgr... | 0.453504 | 0.425426 |
from google.protobuf import timestamp_pb2
from cadence.cadence_types import StartWorkflowExecutionRequest, WorkflowType, TaskList, TaskListKind, \
WorkflowIdReusePolicy, ChildPolicy, RetryPolicy, Memo, SearchAttributes, Header, GetWorkflowExecutionHistoryRequest, \
WorkflowExecution, HistoryEventFilterType, En... | cadence/tests/mapping/grpc/test_service_workflow.py | from google.protobuf import timestamp_pb2
from cadence.cadence_types import StartWorkflowExecutionRequest, WorkflowType, TaskList, TaskListKind, \
WorkflowIdReusePolicy, ChildPolicy, RetryPolicy, Memo, SearchAttributes, Header, GetWorkflowExecutionHistoryRequest, \
WorkflowExecution, HistoryEventFilterType, En... | 0.501221 | 0.401453 |
# Python 2.5 compatibility
from __future__ import with_statement
import argparse
import io
import os
import platform
import re
import shutil
import subprocess
import sys
import time
import zipfile
# Update the module path, assuming that this script is in src/remoting/webapp,
# and that the google_api_keys module is i... | remoting/webapp/build-webapp.py | # Python 2.5 compatibility
from __future__ import with_statement
import argparse
import io
import os
import platform
import re
import shutil
import subprocess
import sys
import time
import zipfile
# Update the module path, assuming that this script is in src/remoting/webapp,
# and that the google_api_keys module is i... | 0.546012 | 0.161155 |
import argparse
import glob
import os
import random
if __name__ == '__main__':
parser = argparse.ArgumentParser()
parser.add_argument("--comet_api", type=str, default='')
parser.add_argument("--comet_workspace", type=str, default='koustuvs')
parser.add_argument("--comet_project", type=str, default='com... | experiments/snli/infersent_comp/run_generator.py | import argparse
import glob
import os
import random
if __name__ == '__main__':
parser = argparse.ArgumentParser()
parser.add_argument("--comet_api", type=str, default='')
parser.add_argument("--comet_workspace", type=str, default='koustuvs')
parser.add_argument("--comet_project", type=str, default='com... | 0.19544 | 0.048182 |
__author__ = '<NAME>'
__copyright__ = 'Oregon State University'
__credits__ = ['<NAME>']
__license__ = 'MIT'
__version__ = '0.1.0'
__maintainer__ = ''
__email__ = ''
__status__ = 'Prototype'
import argparse
import kg2_util
import sys
import prefixcommons
# - check for any input edge labels that occur twice in the pre... | code/kg2/filter_kg_and_remap_predicates.py | __author__ = '<NAME>'
__copyright__ = 'Oregon State University'
__credits__ = ['<NAME>']
__license__ = 'MIT'
__version__ = '0.1.0'
__maintainer__ = ''
__email__ = ''
__status__ = 'Prototype'
import argparse
import kg2_util
import sys
import prefixcommons
# - check for any input edge labels that occur twice in the pre... | 0.288268 | 0.157428 |
from convertdate import gregorian, persian
from . import CalTestCase
# fmt: off
JDS = (
2130575, 2131306, 2132036, 2132767, 2133497, 2134228, 2134958, 2135689,
2136419, 2137150, 2137880, 2138611, 2139341, 2140072, 2140802, 2141533,
2142263, 2142994, 2143724, 2144455, 2145185, 2145916, 2146646, 2147377,
... | tests/test_persian.py | from convertdate import gregorian, persian
from . import CalTestCase
# fmt: off
JDS = (
2130575, 2131306, 2132036, 2132767, 2133497, 2134228, 2134958, 2135689,
2136419, 2137150, 2137880, 2138611, 2139341, 2140072, 2140802, 2141533,
2142263, 2142994, 2143724, 2144455, 2145185, 2145916, 2146646, 2147377,
... | 0.567098 | 0.46873 |
import unittest
import mock
from telemetry.internal.backends.chrome import chrome_startup_args
from telemetry.internal.browser import browser_options as browser_options_module
from telemetry.util import wpr_modes
class FakeBrowserOptions(browser_options_module.BrowserOptions):
def __init__(self, wpr_mode=wpr_mode... | telemetry/telemetry/internal/backends/chrome/chrome_startup_args_unittest.py |
import unittest
import mock
from telemetry.internal.backends.chrome import chrome_startup_args
from telemetry.internal.browser import browser_options as browser_options_module
from telemetry.util import wpr_modes
class FakeBrowserOptions(browser_options_module.BrowserOptions):
def __init__(self, wpr_mode=wpr_mode... | 0.644337 | 0.193338 |
import logging
from datetime import datetime
from slack_bolt import App, Ack
from slack_sdk import WebClient
logging.basicConfig(level=logging.DEBUG)
app = App()
step1_modal = {
"type": "modal",
"callback_id": "helpdesk-request-modal",
"title": {"type": "plain_text", "text": "ヘルプデスク申請"},
"close": {"... | python/app.py | import logging
from datetime import datetime
from slack_bolt import App, Ack
from slack_sdk import WebClient
logging.basicConfig(level=logging.DEBUG)
app = App()
step1_modal = {
"type": "modal",
"callback_id": "helpdesk-request-modal",
"title": {"type": "plain_text", "text": "ヘルプデスク申請"},
"close": {"... | 0.242026 | 0.303822 |
from __future__ import print_function
import tensorflow as tf
from keras.datasets.mnist import load_data
element_size = 28
time_steps = 28
num_classes = 10
batch_size = 128
hidden_layer_size = 128
def main():
tf.compat.v1.disable_eager_execution()
mnist = load_data(path="/tmp/data")
_inputs = tf.compa... | src/tensorflow-examples/tensorflow_examples/examples/text_and_visualizations/BasicRNNCell.py | from __future__ import print_function
import tensorflow as tf
from keras.datasets.mnist import load_data
element_size = 28
time_steps = 28
num_classes = 10
batch_size = 128
hidden_layer_size = 128
def main():
tf.compat.v1.disable_eager_execution()
mnist = load_data(path="/tmp/data")
_inputs = tf.compa... | 0.808748 | 0.507446 |
import contextlib
from mock import Mock
from mock import patch
from httplib2 import ServerNotFoundError
from pytest import raises
from chronos_tools import ChronosNotConfigured
from paasta_tools import paasta_metastatus
from paasta_tools import mesos_tools
from paasta_tools.utils import PaastaColors
from paasta_tool... | tests/test_paasta_metastatus.py |
import contextlib
from mock import Mock
from mock import patch
from httplib2 import ServerNotFoundError
from pytest import raises
from chronos_tools import ChronosNotConfigured
from paasta_tools import paasta_metastatus
from paasta_tools import mesos_tools
from paasta_tools.utils import PaastaColors
from paasta_tool... | 0.615088 | 0.31703 |
import argparse
import dataclasses
import itertools
import os
import sys
import yaml
sys.path.append(os.path.join(os.path.dirname(__file__), ".."))
from typing import Any, Dict, List, Optional, Tuple
from libs.config import Config
def get_arguments() -> argparse.Namespace:
"""parse all the arguments from com... | utils/make_configs.py | import argparse
import dataclasses
import itertools
import os
import sys
import yaml
sys.path.append(os.path.join(os.path.dirname(__file__), ".."))
from typing import Any, Dict, List, Optional, Tuple
from libs.config import Config
def get_arguments() -> argparse.Namespace:
"""parse all the arguments from com... | 0.601594 | 0.129595 |
#Python imports
import sys
import getopt
from datetime import datetime
from dateutil import tz
import ConfigParser
#delphixpy imports
from delphixpy.v1_7_0.delphix_engine import DelphixEngine
from delphixpy.v1_7_0.web.database import database
from delphixpy.v1_7_0.exceptions import RequestError
from delphixpy.v1_7_0.... | v1_8_0/database.py |
#Python imports
import sys
import getopt
from datetime import datetime
from dateutil import tz
import ConfigParser
#delphixpy imports
from delphixpy.v1_7_0.delphix_engine import DelphixEngine
from delphixpy.v1_7_0.web.database import database
from delphixpy.v1_7_0.exceptions import RequestError
from delphixpy.v1_7_0.... | 0.217753 | 0.075142 |
import os
import numpy as np
import nibabel as nib
import re
import gzip
import cv2
# Directory where the .nii files are located.
train_data_dir = r"data\Training_Batch2"
# Directory where the preprocessed data will be stored.
output_dir = r"data\Training_Batch2\preprocessed"
def preprocess_labels():
# Converts... | src/preprocessing.py | import os
import numpy as np
import nibabel as nib
import re
import gzip
import cv2
# Directory where the .nii files are located.
train_data_dir = r"data\Training_Batch2"
# Directory where the preprocessed data will be stored.
output_dir = r"data\Training_Batch2\preprocessed"
def preprocess_labels():
# Converts... | 0.457864 | 0.435121 |
from django.test import TestCase
from rest_framework import status
from mimesis import Generic
from ..models import User
class SignUpViewTestCase(TestCase):
def setUp(self):
self.gen = Generic()
self.payload = {
'first_name': self.gen.person.full_name().split()[0],
'last_n... | api_auth/tests/test_views.py | from django.test import TestCase
from rest_framework import status
from mimesis import Generic
from ..models import User
class SignUpViewTestCase(TestCase):
def setUp(self):
self.gen = Generic()
self.payload = {
'first_name': self.gen.person.full_name().split()[0],
'last_n... | 0.415254 | 0.210513 |
from bdgenomics.adam.adamContext import ADAMContext
from bdgenomics.adam.test import SparkTestCase
class GenotypeRDDTest(SparkTestCase):
def check_for_line_in_file(self, path, line):
try:
fp = open(path)
foundLine = False
for l in fp:
if l.strip().r... | adam-python/bdgenomics/adam/test/genotypeRdd_test.py |
from bdgenomics.adam.adamContext import ADAMContext
from bdgenomics.adam.test import SparkTestCase
class GenotypeRDDTest(SparkTestCase):
def check_for_line_in_file(self, path, line):
try:
fp = open(path)
foundLine = False
for l in fp:
if l.strip().r... | 0.215062 | 0.304707 |
import requests
from requests.auth import HTTPBasicAuth
import sys
import json
import urllib3
urllib3.disable_warnings()
import time
# Global static parameters
DNAC = "sandboxdnac.cisco.com" # DNAC address
DNAC_USER = "devnetuser" # DNAC username
DNAC_PASSWORD = "<PASSWORD>!" # DNAC passowrd
DNAC_PORT = 443 # DNAC ... | async_command_runner.py | import requests
from requests.auth import HTTPBasicAuth
import sys
import json
import urllib3
urllib3.disable_warnings()
import time
# Global static parameters
DNAC = "sandboxdnac.cisco.com" # DNAC address
DNAC_USER = "devnetuser" # DNAC username
DNAC_PASSWORD = "<PASSWORD>!" # DNAC passowrd
DNAC_PORT = 443 # DNAC ... | 0.23092 | 0.090293 |
from operator import itemgetter
import os.path
import pickle
class Historico:
def __init__(self, aluno):
self.__aluno = aluno
self.__disciplinas = []
def getAluno(self):
return self.__aluno
def getDisciplinas(self):
return self.__disciplinas
def addDisciplina(self, reg... | Atividades/Trabalho12/historico.py | from operator import itemgetter
import os.path
import pickle
class Historico:
def __init__(self, aluno):
self.__aluno = aluno
self.__disciplinas = []
def getAluno(self):
return self.__aluno
def getDisciplinas(self):
return self.__disciplinas
def addDisciplina(self, reg... | 0.151624 | 0.060252 |
from django.conf.urls import patterns, include, url
import django.views.generic
from django.views.generic import DetailView, ListView
from django.contrib import admin
from qmpy.db import settings
from rest_framework import routers
from qmpy.web import views
#router = routers.DefaultRouter()
#router.register(r'users'... | qmpy/web/urls.py | from django.conf.urls import patterns, include, url
import django.views.generic
from django.views.generic import DetailView, ListView
from django.contrib import admin
from qmpy.db import settings
from rest_framework import routers
from qmpy.web import views
#router = routers.DefaultRouter()
#router.register(r'users'... | 0.402157 | 0.093719 |