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 |
|---|---|---|---|---|
description = 'Virtual source for the Selene guide'
devices = dict(
dvv = device('nicos_sinq.amor.devices.virtual_source.NumberSwitcher',
description = 'Diaphragm virtual Source Vertical',
mapping = {
1: 0.,
2: 45.,
3: 90.,
4: 135.,
5: 180... | nicos_sinq/amor/setups/virtual_source.py | description = 'Virtual source for the Selene guide'
devices = dict(
dvv = device('nicos_sinq.amor.devices.virtual_source.NumberSwitcher',
description = 'Diaphragm virtual Source Vertical',
mapping = {
1: 0.,
2: 45.,
3: 90.,
4: 135.,
5: 180... | 0.572484 | 0.410284 |
import os
import librosa
import numpy as np
from Frames import Frames
import ParametersExtraction as pe
def label_extraction(file_name):
with open(file_name) as f:
voicing = [(line.rstrip().split(" ")[1]) for line in f]
voicing = np.array(voicing).astype(np.float32)
return voicing
def feature... | DataLoader.py | import os
import librosa
import numpy as np
from Frames import Frames
import ParametersExtraction as pe
def label_extraction(file_name):
with open(file_name) as f:
voicing = [(line.rstrip().split(" ")[1]) for line in f]
voicing = np.array(voicing).astype(np.float32)
return voicing
def feature... | 0.515864 | 0.326943 |
import numpy as np
# Local imports
from variables import Scalar, Vector
import mpitools as mpi
class Grid(object):
def __init__(self, param):
# Copy needed parameters
self.nx = param["nx"]
self.ny = param["ny"]
self.nz = param["nz"]
self.npx = param["npx"]
self.npy... | core/grid.py | import numpy as np
# Local imports
from variables import Scalar, Vector
import mpitools as mpi
class Grid(object):
def __init__(self, param):
# Copy needed parameters
self.nx = param["nx"]
self.ny = param["ny"]
self.nz = param["nz"]
self.npx = param["npx"]
self.npy... | 0.825097 | 0.338596 |
import pytest
from typing import Any
import torch
import onnx
from nncf import NNCFConfig
from nncf.torch.exporter import PTExporter
from tests.torch.helpers import MockModel
from tests.torch.helpers import create_compressed_model_and_algo_for_test
from tests.torch.helpers import get_nodes_by_type
from tests.torch.hel... | tests/torch/test_onnx_export.py | import pytest
from typing import Any
import torch
import onnx
from nncf import NNCFConfig
from nncf.torch.exporter import PTExporter
from tests.torch.helpers import MockModel
from tests.torch.helpers import create_compressed_model_and_algo_for_test
from tests.torch.helpers import get_nodes_by_type
from tests.torch.hel... | 0.857186 | 0.497925 |
# ----- Import Section -----
from facebook import get_user_from_cookie, GraphAPI,auth_url
from symbolic.args import *
from urllib import parse
# ----- End of Import Section -----
# ----- Constant Declaration -----
FB_APP_ID = '156258847901639'
FB_APP_NAME = 'LoginSample'
FB_APP_SECRET = '3ea39e503951c8db93ef73d68fd6... | lib_examples/facebook/facebook-sdk-3.0.0/client_app.py |
# ----- Import Section -----
from facebook import get_user_from_cookie, GraphAPI,auth_url
from symbolic.args import *
from urllib import parse
# ----- End of Import Section -----
# ----- Constant Declaration -----
FB_APP_ID = '156258847901639'
FB_APP_NAME = 'LoginSample'
FB_APP_SECRET = '3ea39e503951c8db93ef73d68fd6... | 0.260954 | 0.099121 |
import os.path
import os
import csv
from openpyxl import Workbook, load_workbook
from openpyxl.styles import Font, PatternFill
def get_workbook(file_path):
if os.path.isfile(file_path):
return load_workbook(filename=file_path)
else:
wb = Workbook()
wb.remove_sheet(wb.active)
r... | report.py | import os.path
import os
import csv
from openpyxl import Workbook, load_workbook
from openpyxl.styles import Font, PatternFill
def get_workbook(file_path):
if os.path.isfile(file_path):
return load_workbook(filename=file_path)
else:
wb = Workbook()
wb.remove_sheet(wb.active)
r... | 0.225417 | 0.168925 |
import json
import logging
import indy.anoncreds
from indy.error import IndyError
from ...ledger.indy import IndySdkLedger
from ..verifier import IndyVerifier, PreVerifyResult
LOGGER = logging.getLogger(__name__)
class IndySdkVerifier(IndyVerifier):
"""Indy-SDK verifier implementation."""
def __init__(s... | aries_cloudagent/indy/sdk/verifier.py |
import json
import logging
import indy.anoncreds
from indy.error import IndyError
from ...ledger.indy import IndySdkLedger
from ..verifier import IndyVerifier, PreVerifyResult
LOGGER = logging.getLogger(__name__)
class IndySdkVerifier(IndyVerifier):
"""Indy-SDK verifier implementation."""
def __init__(s... | 0.638272 | 0.107344 |
import sortedcontainers
import logging
import asyncio
import secrets
import random
import collections
from gear import Database, transaction
from hailtop import aiotools
from hailtop.utils import (secret_alnum_string, retry_long_running, run_if_changed,
time_msecs, WaitableSharedPool, AsyncW... | batch/batch/driver/pool.py | import sortedcontainers
import logging
import asyncio
import secrets
import random
import collections
from gear import Database, transaction
from hailtop import aiotools
from hailtop.utils import (secret_alnum_string, retry_long_running, run_if_changed,
time_msecs, WaitableSharedPool, AsyncW... | 0.511473 | 0.067301 |
from sqlalchemy import Column, Date, DateTime, ForeignKey, Integer, Numeric, String, text, Boolean
from sqlalchemy.orm import relationship
from sqlalchemy.ext.declarative import declarative_base
Base = declarative_base()
metadata = Base.metadata
class Arrest(Base):
__tablename__ = u'arrest'
id = Column(Integ... | models.py | from sqlalchemy import Column, Date, DateTime, ForeignKey, Integer, Numeric, String, text, Boolean
from sqlalchemy.orm import relationship
from sqlalchemy.ext.declarative import declarative_base
Base = declarative_base()
metadata = Base.metadata
class Arrest(Base):
__tablename__ = u'arrest'
id = Column(Integ... | 0.465873 | 0.152379 |
# Checkout folder
repoPath = 'C:/Dev/aws/'
# Relative path to parameters file. Use forward slashes. Change to your domain!
configRelPath = 'cloudformation/testing/oracle-dev-domain-XXXYYYZZZ/private.parameters.json'
# Change to your instance identifier
instanceName = 'InstanceOfYourDBIdentifier'
snapshotIdentifier = '... | Git/respawn.py |
# Checkout folder
repoPath = 'C:/Dev/aws/'
# Relative path to parameters file. Use forward slashes. Change to your domain!
configRelPath = 'cloudformation/testing/oracle-dev-domain-XXXYYYZZZ/private.parameters.json'
# Change to your instance identifier
instanceName = 'InstanceOfYourDBIdentifier'
snapshotIdentifier = '... | 0.399694 | 0.110807 |
import os
import numpy as np
import pandas as pd
from sklearn.ensemble import RandomForestClassifier
"""
This function is used to import the data. Put the data in a folder named all_data in the directory of the code
"""
def import_data(dt_name):
"""
:param dt_name: Name of the Dataset
:r... | Decison-Trees/Decison-Trees-master/random_forest.py | import os
import numpy as np
import pandas as pd
from sklearn.ensemble import RandomForestClassifier
"""
This function is used to import the data. Put the data in a folder named all_data in the directory of the code
"""
def import_data(dt_name):
"""
:param dt_name: Name of the Dataset
:r... | 0.709824 | 0.503845 |
import os
from StringIO import StringIO
from twisted.trial import unittest
from klein import Klein
from klein.resource import KleinResource, ensure_utf8_bytes
from klein.interfaces import IKleinRequest
from twisted.internet.defer import succeed, Deferred
from twisted.web import server
from twisted.web.static import... | src/main/resources/klein/test_resource.py | import os
from StringIO import StringIO
from twisted.trial import unittest
from klein import Klein
from klein.resource import KleinResource, ensure_utf8_bytes
from klein.interfaces import IKleinRequest
from twisted.internet.defer import succeed, Deferred
from twisted.web import server
from twisted.web.static import... | 0.489259 | 0.106087 |
import gym
import numpy as np
class LookAndPush(gym.Env):
"""Memory-requiring Env: Best sequence of actions depends on prev. states.
Optimal behavior:
0) a=0 -> observe next state (s'), which is the "hidden" state.
If a=1 here, the hidden state is not observed.
1) a=1 to always ju... | rllib/examples/env/look_and_push.py | import gym
import numpy as np
class LookAndPush(gym.Env):
"""Memory-requiring Env: Best sequence of actions depends on prev. states.
Optimal behavior:
0) a=0 -> observe next state (s'), which is the "hidden" state.
If a=1 here, the hidden state is not observed.
1) a=1 to always ju... | 0.793826 | 0.570391 |
"""Condition datastructure."""
from .datastructure import DataStructure
from .operator import Operator
# pylint:disable=too-few-public-methods
class Condition(DataStructure):
"""Condition datastructure.
Example::
{
"$condition": {
"if": {
"key": "Key ... | src/jsontas/data_structures/condition.py | """Condition datastructure."""
from .datastructure import DataStructure
from .operator import Operator
# pylint:disable=too-few-public-methods
class Condition(DataStructure):
"""Condition datastructure.
Example::
{
"$condition": {
"if": {
"key": "Key ... | 0.856977 | 0.347426 |
from time import sleep
import sys
import config
import datetime
import logger
from utils import hash_file_sha1, hash_file_md5
import api
class StagingRepository:
"""Represents a staging repository in ossrh"""
def __init__(self, name):
self.name = name
def close(self):
api.close_repository(self.name)
... | ossrh.py |
from time import sleep
import sys
import config
import datetime
import logger
from utils import hash_file_sha1, hash_file_md5
import api
class StagingRepository:
"""Represents a staging repository in ossrh"""
def __init__(self, name):
self.name = name
def close(self):
api.close_repository(self.name)
... | 0.340485 | 0.112186 |
import matplotlib.pyplot as plt
import matplotlib.patheffects as pe
import re
import os, sys
import subprocess
import datetime
import csv
from math import degrees, isnan
# Configuration ###############################################################
dry_run = False
elev_only = False
if (len(sys.argv) > 1... | Plot/plot.py |
import matplotlib.pyplot as plt
import matplotlib.patheffects as pe
import re
import os, sys
import subprocess
import datetime
import csv
from math import degrees, isnan
# Configuration ###############################################################
dry_run = False
elev_only = False
if (len(sys.argv) > 1... | 0.06408 | 0.177027 |
class Rule(object):
"""
Exceptions/suffices as lists of strings for checking matches against ones
"""
def __init__(self, male: list = None, female: list = None, androgynous: list = None):
assert not male is None or not female is None or not androgynous is None
self.male = set(male... | pytrovich/gender_models.py |
class Rule(object):
"""
Exceptions/suffices as lists of strings for checking matches against ones
"""
def __init__(self, male: list = None, female: list = None, androgynous: list = None):
assert not male is None or not female is None or not androgynous is None
self.male = set(male... | 0.772359 | 0.355943 |
from ixnetwork_restpy.base import Base
from ixnetwork_restpy.files import Files
from typing import List, Any, Union
class LearnedLsa(Base):
"""The learned Link State Advertisements on this interface.
The LearnedLsa class encapsulates a list of learnedLsa resources that are managed by the system.
A list of... | ixnetwork_restpy/testplatform/sessions/ixnetwork/vport/protocols/learnedlsa_7ae32a0018f81f135ef70ec5259d7e63.py | from ixnetwork_restpy.base import Base
from ixnetwork_restpy.files import Files
from typing import List, Any, Union
class LearnedLsa(Base):
"""The learned Link State Advertisements on this interface.
The LearnedLsa class encapsulates a list of learnedLsa resources that are managed by the system.
A list of... | 0.932852 | 0.371593 |
import math
def _mapToEllipse(point, rx, ry, cosphi, sinphi, centerx, centery):
x = point[0]
y = point[1]
x *= rx
y *= ry
xp = cosphi * x - sinphi * y
yp = sinphi * x + cosphi * y
return [xp + centerx, yp + centery]
def _approxUnitArc(ang1, ang2):
# If 90 degree circular arc, use a... | elements/arc2bezier.py | import math
def _mapToEllipse(point, rx, ry, cosphi, sinphi, centerx, centery):
x = point[0]
y = point[1]
x *= rx
y *= ry
xp = cosphi * x - sinphi * y
yp = sinphi * x + cosphi * y
return [xp + centerx, yp + centery]
def _approxUnitArc(ang1, ang2):
# If 90 degree circular arc, use a... | 0.662687 | 0.670433 |
from __future__ import absolute_import
from __future__ import division
from __future__ import print_function
from __future__ import unicode_literals
"""
Logging utilities
"""
__author__ = "the01"
__email__ = "<EMAIL>"
__copyright__ = "Copyright (C) 2013-19, <NAME>"
__license__ = "MIT"
__version__ = "0.1.6"
__date__ = ... | flotils/logable.py | from __future__ import absolute_import
from __future__ import division
from __future__ import print_function
from __future__ import unicode_literals
"""
Logging utilities
"""
__author__ = "the01"
__email__ = "<EMAIL>"
__copyright__ = "Copyright (C) 2013-19, <NAME>"
__license__ = "MIT"
__version__ = "0.1.6"
__date__ = ... | 0.666605 | 0.113408 |
import json
import re
from .exceptions import PrereleaseError, VersionError
"""
Uses a slightly modified version of this regex
https://regex101.com/r/E0iVVS/2
copied to:
https://regex101.com/r/NpbTSw/4
"""
SEMVER_RE = re.compile(
r"""
^(?:(?P<prefix>.*)(?P<prefix_separator>.*/))?
(?P<version_triple>
... | src/tagversion/version.py | import json
import re
from .exceptions import PrereleaseError, VersionError
"""
Uses a slightly modified version of this regex
https://regex101.com/r/E0iVVS/2
copied to:
https://regex101.com/r/NpbTSw/4
"""
SEMVER_RE = re.compile(
r"""
^(?:(?P<prefix>.*)(?P<prefix_separator>.*/))?
(?P<version_triple>
... | 0.597256 | 0.205077 |
from abc import ABC
from pathlib import Path
import pandas as pd
import scrapy
from src.crawl.utils import cleanup
from settings import YEAR, CRAWLING_OUTPUT_FOLDER
BASE_URl = "https://directory.unamur.be/teaching/courses/{}/{}" # first format is code course, second is year
PROG_DATA_PATH = Path(__file__).parent.ab... | src/crawl/unicrawl/spiders/unamur_courses.py | from abc import ABC
from pathlib import Path
import pandas as pd
import scrapy
from src.crawl.utils import cleanup
from settings import YEAR, CRAWLING_OUTPUT_FOLDER
BASE_URl = "https://directory.unamur.be/teaching/courses/{}/{}" # first format is code course, second is year
PROG_DATA_PATH = Path(__file__).parent.ab... | 0.319546 | 0.233444 |
class Game(object):
"""
A class to keep track of a game of Connect-4 and determine a winner
Class Constant
--------------
SEARCH_PAIRS: nested list of int
denote search axis for checking for win
Attributes
----------
board: nested list of int
represents the connect four board 0 represents no piece
play... | modules/game.py | class Game(object):
"""
A class to keep track of a game of Connect-4 and determine a winner
Class Constant
--------------
SEARCH_PAIRS: nested list of int
denote search axis for checking for win
Attributes
----------
board: nested list of int
represents the connect four board 0 represents no piece
play... | 0.785267 | 0.632574 |
from __future__ import absolute_import
from ...base.events import BaseEvent
import threading
import importlib
from utils import strings
import logging
log = logging.getLogger('hookbot')
class MessageEvent(BaseEvent):
def process(self, request, body):
update = body
if update.get('message', '') and... | captain_hook/services/telegram/events/message.py | from __future__ import absolute_import
from ...base.events import BaseEvent
import threading
import importlib
from utils import strings
import logging
log = logging.getLogger('hookbot')
class MessageEvent(BaseEvent):
def process(self, request, body):
update = body
if update.get('message', '') and... | 0.38769 | 0.046965 |
import torch
from typing import Dict, Any
import numpy as np
import logging
from theseus.utilities.loggers.observer import LoggerObserver
LOGGER = LoggerObserver.getLogger('main')
class CosineWithRestarts():
"""
Cosine annealing with restarts.
This is described in the paper https://arxiv.org/abs/1608.039... | theseus/base/optimizers/schedulers/cosine.py |
import torch
from typing import Dict, Any
import numpy as np
import logging
from theseus.utilities.loggers.observer import LoggerObserver
LOGGER = LoggerObserver.getLogger('main')
class CosineWithRestarts():
"""
Cosine annealing with restarts.
This is described in the paper https://arxiv.org/abs/1608.039... | 0.946101 | 0.881564 |
from __future__ import print_function
import os
import shutil
import stat
from google.protobuf import text_format
import _init_paths
from caffe.proto import caffe_pb2
from cfgs.arg_parser import config
def check_if_exist(path):
return os.path.exists(path)
def make_if_not_exist(path):
if not os.path.exists(p... | tools/create_new_data.py | from __future__ import print_function
import os
import shutil
import stat
from google.protobuf import text_format
import _init_paths
from caffe.proto import caffe_pb2
from cfgs.arg_parser import config
def check_if_exist(path):
return os.path.exists(path)
def make_if_not_exist(path):
if not os.path.exists(p... | 0.416085 | 0.155784 |
from luxon import g
from luxon import router
from luxon import register
from luxon import render_template
from luxon.utils.bootstrap4 import form
from infinitystone.ui.models.roles import infinitystone_role
g.nav_menu.add('/System/Roles',
href='/system/roles',
tag='infrastructure:admin',... | infinitystone/ui/views/roles.py | from luxon import g
from luxon import router
from luxon import register
from luxon import render_template
from luxon.utils.bootstrap4 import form
from infinitystone.ui.models.roles import infinitystone_role
g.nav_menu.add('/System/Roles',
href='/system/roles',
tag='infrastructure:admin',... | 0.396419 | 0.051415 |
# Imports needed to process arguments
from __future__ import absolute_import
from __future__ import print_function
import sys
import argparse
import numpy as np
# This was adapted from ngon.py from Blaschke
parser = argparse.ArgumentParser(description=__doc__)
parser.add_argument('-N',type=int,default=2,help='Rank ... | compute-polygon.py |
# Imports needed to process arguments
from __future__ import absolute_import
from __future__ import print_function
import sys
import argparse
import numpy as np
# This was adapted from ngon.py from Blaschke
parser = argparse.ArgumentParser(description=__doc__)
parser.add_argument('-N',type=int,default=2,help='Rank ... | 0.530723 | 0.170301 |
centers = {
"57 Cleveland Place": {
"address": "57 Cleveland Pl, Staten Island, NY 10305",
"boro": "Staten Island",
"fullname": "Form<NAME>",
"lat": 40.6012163,
"lng": -74.0687077
},
"Bay Ridge 5th Avenue": {
"address": "8511 & 8515 5th Ave., Brooklyn, NY 1120... | fixtures/__init__.py | centers = {
"57 Cleveland Place": {
"address": "57 Cleveland Pl, Staten Island, NY 10305",
"boro": "Staten Island",
"fullname": "Form<NAME>",
"lat": 40.6012163,
"lng": -74.0687077
},
"Bay Ridge 5th Avenue": {
"address": "8511 & 8515 5th Ave., Brooklyn, NY 1120... | 0.514644 | 0.375764 |
import torch
import torch.nn as nn
import torch.nn.functional as F
import numpy as np
class OhemCELoss(nn.Module):
def __init__(self, thresh, n_min, ignore_lb=255, *args, **kwargs):
super(OhemCELoss, self).__init__()
self.thresh = -torch.log(torch.tensor(thresh, dtype=torch.float)).cuda()
... | DeepLearning/pytorch/papers/BiseNet_V2/loss.py | import torch
import torch.nn as nn
import torch.nn.functional as F
import numpy as np
class OhemCELoss(nn.Module):
def __init__(self, thresh, n_min, ignore_lb=255, *args, **kwargs):
super(OhemCELoss, self).__init__()
self.thresh = -torch.log(torch.tensor(thresh, dtype=torch.float)).cuda()
... | 0.963506 | 0.422624 |
import datetime
from dataclasses import dataclass
from os.path import join
from typing import Optional, List
from django.db import models
from django.urls import reverse
from django.utils.text import slugify
from django.utils.translation import gettext_lazy as _
from django_resized import ResizedImageField
from utils... | elections/models.py | import datetime
from dataclasses import dataclass
from os.path import join
from typing import Optional, List
from django.db import models
from django.urls import reverse
from django.utils.text import slugify
from django.utils.translation import gettext_lazy as _
from django_resized import ResizedImageField
from utils... | 0.7666 | 0.17252 |
from collections import namedtuple
import numpy as np
Reg = namedtuple(
"Reg",
[
"name",
"mode",
"addr",
"rw",
"type",
"val_map",
"info_type",
"config_attr",
],
)
EncFuns = namedtuple("EncFu... | lib/acconeer_utils/clients/reg/protocol.py | from collections import namedtuple
import numpy as np
Reg = namedtuple(
"Reg",
[
"name",
"mode",
"addr",
"rw",
"type",
"val_map",
"info_type",
"config_attr",
],
)
EncFuns = namedtuple("EncFu... | 0.46393 | 0.35796 |
from __future__ import annotations
from typing import Optional, TYPE_CHECKING, Union
from pyspark.sql.types import StructType, DataType
from spark_auto_mapper_fhir.fhir_types.list import FhirList
from spark_auto_mapper_fhir.fhir_types.string import FhirString
from spark_auto_mapper_fhir.extensions.extension_base impo... | spark_auto_mapper_fhir/complex_types/contributor.py | from __future__ import annotations
from typing import Optional, TYPE_CHECKING, Union
from pyspark.sql.types import StructType, DataType
from spark_auto_mapper_fhir.fhir_types.list import FhirList
from spark_auto_mapper_fhir.fhir_types.string import FhirString
from spark_auto_mapper_fhir.extensions.extension_base impo... | 0.889643 | 0.22763 |
import pytest
from synapse_admin.base import SynapseException, HTTPConnection
from synapse_admin import Room
with open("synapse_test/admin.token", "r") as f:
admin_access_token = f.read().replace("\n", "")
with open("synapse_test/user.token", "r") as f:
user_access_token = f.read().replace("\n", "")
conn =... | tests/test_3_room.py | import pytest
from synapse_admin.base import SynapseException, HTTPConnection
from synapse_admin import Room
with open("synapse_test/admin.token", "r") as f:
admin_access_token = f.read().replace("\n", "")
with open("synapse_test/user.token", "r") as f:
user_access_token = f.read().replace("\n", "")
conn =... | 0.30965 | 0.365343 |
from __future__ import print_function
from __future__ import division
from __future__ import unicode_literals
from traceback import print_exc
from datetime import datetime
import errno
from accelerator.compat import ArgumentParser
from accelerator.setupfile import encode_setup
from accelerator.compat import FileNotF... | accelerator/shell/job.py |
from __future__ import print_function
from __future__ import division
from __future__ import unicode_literals
from traceback import print_exc
from datetime import datetime
import errno
from accelerator.compat import ArgumentParser
from accelerator.setupfile import encode_setup
from accelerator.compat import FileNotF... | 0.339828 | 0.074198 |
import os
import torch
import tqdm
from seqmod.utils import load_model
from data import load_pairs
def add_noise(mean=0, stddev=0.05):
"""
Add gaussian noise to the context before starting decode
"""
def callback(m, state):
noise = torch.zeros_like(state.context).normal_(mean, stddev)
... | src/obfuscate.py | import os
import torch
import tqdm
from seqmod.utils import load_model
from data import load_pairs
def add_noise(mean=0, stddev=0.05):
"""
Add gaussian noise to the context before starting decode
"""
def callback(m, state):
noise = torch.zeros_like(state.context).normal_(mean, stddev)
... | 0.605682 | 0.233542 |
import sys
import textwrap
from typing import Set
import jedi
import pytest
import yapytf._containers2 as cnt
prefix_code = textwrap.dedent("""
import yapytf
import yapytf._containers2 as cnt
""")
# new in Python 3.7, not yet added to typeshed
STR_IGNORE = {"isascii"}
@pytest.mark.parametrize(
... | tests/test_containers2_jedi.py | import sys
import textwrap
from typing import Set
import jedi
import pytest
import yapytf._containers2 as cnt
prefix_code = textwrap.dedent("""
import yapytf
import yapytf._containers2 as cnt
""")
# new in Python 3.7, not yet added to typeshed
STR_IGNORE = {"isascii"}
@pytest.mark.parametrize(
... | 0.39036 | 0.343837 |
import requests
import sys
import random
from wikipedia import wikipedia
from datetime import datetime
import config
from azure.cosmosdb.table.tableservice import TableService
from azure.cosmosdb.table.models import Entity
'''
Need to pip install azure
Run python setup.py install
Get Wikipedia Article Ti... | scraper_random.py | import requests
import sys
import random
from wikipedia import wikipedia
from datetime import datetime
import config
from azure.cosmosdb.table.tableservice import TableService
from azure.cosmosdb.table.models import Entity
'''
Need to pip install azure
Run python setup.py install
Get Wikipedia Article Ti... | 0.177098 | 0.146881 |
import random
from datetime import datetime, timedelta
from collaborative_cosinedist import predict_most_similar
class DBTable:
def __init__(self, elems=[]):
self.elems = elems
def add(self, elem):
self.elems.append(elem)
def filter(self, **kwargs):
return DBTable([elem fo... | test_collaborative_cosinedist.py | import random
from datetime import datetime, timedelta
from collaborative_cosinedist import predict_most_similar
class DBTable:
def __init__(self, elems=[]):
self.elems = elems
def add(self, elem):
self.elems.append(elem)
def filter(self, **kwargs):
return DBTable([elem fo... | 0.493164 | 0.157299 |
import os
import re
import sys
import Levenshtein
from dotenv import load_dotenv
from googleapiclient.discovery import build
from ytmusicapi import YTMusic
from Model import Song, Playlist
load_dotenv()
DEVELOPER_KEY = os.environ.get("GOOGLE_DEVELOPER_KEY")
ytmusic = YTMusic('headers_auth.json')
youtube = build('you... | platforms/youtube.py | import os
import re
import sys
import Levenshtein
from dotenv import load_dotenv
from googleapiclient.discovery import build
from ytmusicapi import YTMusic
from Model import Song, Playlist
load_dotenv()
DEVELOPER_KEY = os.environ.get("GOOGLE_DEVELOPER_KEY")
ytmusic = YTMusic('headers_auth.json')
youtube = build('you... | 0.315947 | 0.100172 |
from mako import runtime, filters, cache
UNDEFINED = runtime.UNDEFINED
__M_dict_builtin = dict
__M_locals_builtin = locals
_magic_number = 8
_modified_time = 1350123182.4849229
_enable_loop = True
_template_filename = '/home/smita/cyberweb/cyberweb/templates/gcem/gcem.mako'
_template_uri = '/gcem/gcem.mako'
_source_enc... | data/templates/gcem/gcem.mako.py | from mako import runtime, filters, cache
UNDEFINED = runtime.UNDEFINED
__M_dict_builtin = dict
__M_locals_builtin = locals
_magic_number = 8
_modified_time = 1350123182.4849229
_enable_loop = True
_template_filename = '/home/smita/cyberweb/cyberweb/templates/gcem/gcem.mako'
_template_uri = '/gcem/gcem.mako'
_source_enc... | 0.326164 | 0.074804 |
import sys
import pandas as pd
import numpy as np
from sqlalchemy import create_engine
import re
import pickle
import nltk
nltk.download('stopwords')
from nltk import word_tokenize
from nltk.corpus import stopwords
from nltk.stem import WordNetLemmatizer
from sklearn.pipeline import Pipeline
from sklearn.metrics impo... | workspace/models/train_classifier.py | import sys
import pandas as pd
import numpy as np
from sqlalchemy import create_engine
import re
import pickle
import nltk
nltk.download('stopwords')
from nltk import word_tokenize
from nltk.corpus import stopwords
from nltk.stem import WordNetLemmatizer
from sklearn.pipeline import Pipeline
from sklearn.metrics impo... | 0.483648 | 0.368775 |
import sys
import subprocess
import os
import os.path
if len(sys.argv) > 1:
pythonpath = sys.argv[1]
else:
pythonpath = sys.executable
homepath = os.path.realpath(os.path.dirname(sys.argv[0]))
ophispath = os.path.join(homepath, "..", "bin", "ophis")
failed = 0
# These are some simple routines for forwarding... | tests/test_ophis.py |
import sys
import subprocess
import os
import os.path
if len(sys.argv) > 1:
pythonpath = sys.argv[1]
else:
pythonpath = sys.executable
homepath = os.path.realpath(os.path.dirname(sys.argv[0]))
ophispath = os.path.join(homepath, "..", "bin", "ophis")
failed = 0
# These are some simple routines for forwarding... | 0.253491 | 0.205535 |
import json
import base64
import hashlib
import hmac
import time
# References:
# https://hdknr.github.io/docs/identity/impl_jws.html
# https://codereview.stackexchange.com/questions/150063/validating-hmac-sha256-signature-in-python
# https://jwt.io/introduction/
# http://www.seedbox.com/en/blog/2015/06/05/oauth-2-vs... | server/core/authMech/jwt.py |
import json
import base64
import hashlib
import hmac
import time
# References:
# https://hdknr.github.io/docs/identity/impl_jws.html
# https://codereview.stackexchange.com/questions/150063/validating-hmac-sha256-signature-in-python
# https://jwt.io/introduction/
# http://www.seedbox.com/en/blog/2015/06/05/oauth-2-vs... | 0.654343 | 0.229773 |
from Bio import Seq, SeqIO, SeqRecord
import logging
from pyfaidx import Fasta
import json
import numpy as np
class NonGraphPeak:
def __init__(self, chromosome, start, end, score=None, unique_id=None):
self.chromosome = chromosome
self.start = start
self.end = end
self.score = scor... | graph_peak_caller/analysis/nongraphpeaks.py | from Bio import Seq, SeqIO, SeqRecord
import logging
from pyfaidx import Fasta
import json
import numpy as np
class NonGraphPeak:
def __init__(self, chromosome, start, end, score=None, unique_id=None):
self.chromosome = chromosome
self.start = start
self.end = end
self.score = scor... | 0.51879 | 0.220552 |
from random import randint
letternumbers = '0123456789ABCDEFGHJKLMNPQRSTUVWXYZ'
def rd6():
return randint(1,6)
def r2d6():
return rd6() + rd6()
def rd66():
return rd6() * 10 + rd6()
def one_third():
'''Returns success or failure for a 1/3 check.'''
return randint(1,3) == 1
def... | travellerdice.py | from random import randint
letternumbers = '0123456789ABCDEFGHJKLMNPQRSTUVWXYZ'
def rd6():
return randint(1,6)
def r2d6():
return rd6() + rd6()
def rd66():
return rd6() * 10 + rd6()
def one_third():
'''Returns success or failure for a 1/3 check.'''
return randint(1,3) == 1
def... | 0.39222 | 0.417153 |
def get_language_name(filetype):
"""Return language name (human-readable) for a Vim filetype"""
if filetype in FILETYPE_MAP:
return FILETYPE_MAP[filetype]
return filetype
# all the filetypes from Vim 8.0 + sheerun/vim-polyglot
FILETYPE_MAP = {
"": "Plain text",
"ada": ... | plugin/codestats_filetypes.py | def get_language_name(filetype):
"""Return language name (human-readable) for a Vim filetype"""
if filetype in FILETYPE_MAP:
return FILETYPE_MAP[filetype]
return filetype
# all the filetypes from Vim 8.0 + sheerun/vim-polyglot
FILETYPE_MAP = {
"": "Plain text",
"ada": ... | 0.464416 | 0.353679 |
import json
import logging
import typing as tg
import os
from ..dependencies.elsapy.elsdoc import FullDoc
from ..dependencies.elsapy.elsclient import ElsClient
class ScopusFulltextSpider:
'''通过调用Elsevier的全文API检索指定doi的全文。
全文结果将以xml格式储存在output_path目录下。'''
def __init__(
self, doi: str,
... | data_fetcher/scopus/scopus_fulltext_spider.py | import json
import logging
import typing as tg
import os
from ..dependencies.elsapy.elsdoc import FullDoc
from ..dependencies.elsapy.elsclient import ElsClient
class ScopusFulltextSpider:
'''通过调用Elsevier的全文API检索指定doi的全文。
全文结果将以xml格式储存在output_path目录下。'''
def __init__(
self, doi: str,
... | 0.216425 | 0.058373 |
import django.db.models.deletion
from django.conf import settings
from django.db import migrations, models
class Migration(migrations.Migration):
dependencies = [
migrations.swappable_dependency(settings.AUTH_USER_MODEL),
("moonmining", "0002_add_mining_ledger"),
]
operations = [
... | moonmining/migrations/0003_mining_ledger_reports.py |
import django.db.models.deletion
from django.conf import settings
from django.db import migrations, models
class Migration(migrations.Migration):
dependencies = [
migrations.swappable_dependency(settings.AUTH_USER_MODEL),
("moonmining", "0002_add_mining_ledger"),
]
operations = [
... | 0.523664 | 0.135432 |
import tkinter
from tkinter import ttk
from tkinter import filedialog, messagebox
import tkinter.font as font
import os
import threading
import re
import trainingdriver
from ..gdmodules import gdv
from src.handlers import filehandler
class GUI:
def __init__(self):
self.root = tkinter.Tk()
self.r... | src/classes/traininggui.py | import tkinter
from tkinter import ttk
from tkinter import filedialog, messagebox
import tkinter.font as font
import os
import threading
import re
import trainingdriver
from ..gdmodules import gdv
from src.handlers import filehandler
class GUI:
def __init__(self):
self.root = tkinter.Tk()
self.r... | 0.447943 | 0.184253 |
import datetime
from reports.usage_in_subscription import entrypoint
from unittest.mock import patch
PARAMETERS = {
'period': {
'after': '2020-12-01T00:00:00',
'before': '2021-01-01T00:00:00',
},
'product': {
'all': False,
'choices': ['PRD-1'],
},
}
def test_generat... | tests/test_usage_in_subscription.py |
import datetime
from reports.usage_in_subscription import entrypoint
from unittest.mock import patch
PARAMETERS = {
'period': {
'after': '2020-12-01T00:00:00',
'before': '2021-01-01T00:00:00',
},
'product': {
'all': False,
'choices': ['PRD-1'],
},
}
def test_generat... | 0.475849 | 0.358887 |
import argparse
from pathlib import Path
import yaml
from lib.utils import *
import pandas as pd
import matplotlib.pyplot as plt
from lib.constants import *
from collections import OrderedDict
import functools
config, ac = utils.parameters_init()
config = OrderedDict(config)
fig, ax = plt.subplots()
name = ac.get_name(... | src/plot_mean_and_best.py | import argparse
from pathlib import Path
import yaml
from lib.utils import *
import pandas as pd
import matplotlib.pyplot as plt
from lib.constants import *
from collections import OrderedDict
import functools
config, ac = utils.parameters_init()
config = OrderedDict(config)
fig, ax = plt.subplots()
name = ac.get_name(... | 0.327991 | 0.137561 |
# Problem Statement #1 {{{
"""
In this assignment you will implement one or more algorithms for the all-pairs shortest-path problem.
Here are data files describing three graphs: g1.txt g2.txt g3.txt
The first line indicates the number of vertices and edges, respectively. Each subsequent line
describes an edge (the f... | Course-4:Shortest-Path-Revisited/all_pairs_shortest_path.py |
# Problem Statement #1 {{{
"""
In this assignment you will implement one or more algorithms for the all-pairs shortest-path problem.
Here are data files describing three graphs: g1.txt g2.txt g3.txt
The first line indicates the number of vertices and edges, respectively. Each subsequent line
describes an edge (the f... | 0.720467 | 0.842928 |
from itertools import cycle
from unittest.mock import Mock, patch
from scripts.assign_workflow_kapa_qc import AssignWorkflow
from tests.test_common import TestEPP, NamedMock, FakeEntitiesMaker
class TestAssignNextStep(TestEPP):
def setUp(self):
self.protostep = NamedMock(real_name='SeqPlatePrepST', uri='... | tests/test_assign_workflow_kapa_qc.py | from itertools import cycle
from unittest.mock import Mock, patch
from scripts.assign_workflow_kapa_qc import AssignWorkflow
from tests.test_common import TestEPP, NamedMock, FakeEntitiesMaker
class TestAssignNextStep(TestEPP):
def setUp(self):
self.protostep = NamedMock(real_name='SeqPlatePrepST', uri='... | 0.584271 | 0.253014 |
from pprint import pformat
from six import iteritems
class Lawyer(object):
"""
NOTE: This class is auto generated by the swagger code generator program.
Do not edit the class manually.
"""
def __init__(self):
"""
Lawyer - a model defined in Swagger
:param dict swaggerTypes... | app/hackney_law_data_client/models/lawyer.py | from pprint import pformat
from six import iteritems
class Lawyer(object):
"""
NOTE: This class is auto generated by the swagger code generator program.
Do not edit the class manually.
"""
def __init__(self):
"""
Lawyer - a model defined in Swagger
:param dict swaggerTypes... | 0.660501 | 0.180558 |
class GumballMachine:
def __init__(self):
self.valid_currency = {"nickel": 5, "dime": 10, "quarter": 25}
# Represents the total value of valid currency the user inserted
self.currency_value = 0
self.invalid_currencies = []
def insert(self, currency):
# Checks if the inse... | gumball_machine.py | class GumballMachine:
def __init__(self):
self.valid_currency = {"nickel": 5, "dime": 10, "quarter": 25}
# Represents the total value of valid currency the user inserted
self.currency_value = 0
self.invalid_currencies = []
def insert(self, currency):
# Checks if the inse... | 0.755997 | 0.252822 |
import decimal
import datetime
class ValidateValue:
def __init__(self, default=None, context=None, required=False, max=None, name=None, type=None, format=None, key=None):
self.scale = 2
self.context = context
self.required = required
self.max = max
self.name =... | moippy/entities/lib/datatype.py |
import decimal
import datetime
class ValidateValue:
def __init__(self, default=None, context=None, required=False, max=None, name=None, type=None, format=None, key=None):
self.scale = 2
self.context = context
self.required = required
self.max = max
self.name =... | 0.473901 | 0.098296 |
from hummingbird.maths.filters.tustin_filter import Derivative
import numpy as np
class Pid:
"""Class describing a PID.
This implementation considers:
1. The Tustin bilinear transform to compute low pass filter of the derivative output.
2. The antiwindup has a constraint on the absolute output of the... | hummingbird/maths/pid.py | from hummingbird.maths.filters.tustin_filter import Derivative
import numpy as np
class Pid:
"""Class describing a PID.
This implementation considers:
1. The Tustin bilinear transform to compute low pass filter of the derivative output.
2. The antiwindup has a constraint on the absolute output of the... | 0.86959 | 0.750941 |
import math, random, torch
import warnings
import torch.nn as nn
import torch.nn.functional as F
from copy import deepcopy
from ..cell_operations import OPS
class SearchCell(nn.Module):
def __init__(self, C_in, C_out, stride, max_nodes, op_names):
super(SearchCell, self).__init__()
self.op_names = deepco... | lib/models/cell_searchs/search_cells.py | import math, random, torch
import warnings
import torch.nn as nn
import torch.nn.functional as F
from copy import deepcopy
from ..cell_operations import OPS
class SearchCell(nn.Module):
def __init__(self, C_in, C_out, stride, max_nodes, op_names):
super(SearchCell, self).__init__()
self.op_names = deepco... | 0.801392 | 0.35502 |
from tkinter import font
from tkinter import ttk
import tkinter as tk
## Tkinter konstanty pro pack()
from tkinter.constants import BOTTOM, CENTER, N
import PIL.ImageTk
import PIL.Image
# Databáze
from dbOperations import dbOp
from treeview import viewDatabase
class login:
def loginScreen():
# Custom colors
... | app/login.py | from tkinter import font
from tkinter import ttk
import tkinter as tk
## Tkinter konstanty pro pack()
from tkinter.constants import BOTTOM, CENTER, N
import PIL.ImageTk
import PIL.Image
# Databáze
from dbOperations import dbOp
from treeview import viewDatabase
class login:
def loginScreen():
# Custom colors
... | 0.28597 | 0.085251 |
from django.contrib.auth.models import Group, Permission
from django.contrib.contenttypes.models import ContentType
from django.contrib import messages
from django.core.urlresolvers import reverse
from django.shortcuts import get_object_or_404, redirect, render_to_response
from django.template.response import TemplateR... | saleor/dashboard/drawercash/views.py | from django.contrib.auth.models import Group, Permission
from django.contrib.contenttypes.models import ContentType
from django.contrib import messages
from django.core.urlresolvers import reverse
from django.shortcuts import get_object_or_404, redirect, render_to_response
from django.template.response import TemplateR... | 0.207295 | 0.050776 |
from __future__ import (absolute_import, unicode_literals, print_function)
import sys
import pickle
import numpy as np
PRETRAIN = False
def load(name):
# Pickle module isn't backwards compatible. Hack so it works:
compat = {'encoding': 'latin1'} if sys.version_info[0] == 3 else {}
print("\t"+name)
... | examples/bench_cifar10.py | from __future__ import (absolute_import, unicode_literals, print_function)
import sys
import pickle
import numpy as np
PRETRAIN = False
def load(name):
# Pickle module isn't backwards compatible. Hack so it works:
compat = {'encoding': 'latin1'} if sys.version_info[0] == 3 else {}
print("\t"+name)
... | 0.538012 | 0.257467 |
import os
import json
import socket
import configparser
from datetime import datetime
NSS_CONFIG = os.path.join(
os.path.expanduser('~'), '.nuke', 'NukeServerSocket.ini'
)
def format_output(text):
"""Format output to send at console.
Example: `[17:49:25] [NukeTools] Hello World`
Args:
tex... | src/nuke_tools.py |
import os
import json
import socket
import configparser
from datetime import datetime
NSS_CONFIG = os.path.join(
os.path.expanduser('~'), '.nuke', 'NukeServerSocket.ini'
)
def format_output(text):
"""Format output to send at console.
Example: `[17:49:25] [NukeTools] Hello World`
Args:
tex... | 0.695855 | 0.237068 |
import sys
import os
import json
import copy
import logging
import tempfile
from airflow.models import BaseOperator
from jsonmerge import merge
import cwltool.executors
import cwltool.workflow
import cwltool.errors
import cwltool.stdfsaccess
from cwltool.context import RuntimeContext, getdefault
from cwl_airflow.utils.... | cwl_airflow/dag_components/cwlstepoperator.py | import sys
import os
import json
import copy
import logging
import tempfile
from airflow.models import BaseOperator
from jsonmerge import merge
import cwltool.executors
import cwltool.workflow
import cwltool.errors
import cwltool.stdfsaccess
from cwltool.context import RuntimeContext, getdefault
from cwl_airflow.utils.... | 0.260578 | 0.113629 |
import uuid
import pytest
from citrine.informatics.workflows import PredictorEvaluationWorkflow
from citrine.resources.predictor_evaluation_workflow import PredictorEvaluationWorkflowCollection
from tests.utils.session import FakeSession, FakeCall
@pytest.fixture
def session() -> FakeSession:
return FakeSession... | tests/resources/test_predictor_evaluation_workflows.py | import uuid
import pytest
from citrine.informatics.workflows import PredictorEvaluationWorkflow
from citrine.resources.predictor_evaluation_workflow import PredictorEvaluationWorkflowCollection
from tests.utils.session import FakeSession, FakeCall
@pytest.fixture
def session() -> FakeSession:
return FakeSession... | 0.571886 | 0.398172 |
import logging
from datetime import datetime, timedelta
import numpy as np
import iris
try:
from iris.util import equalise_attributes
except ImportError: # Iris 2
from iris.experimental.equalise_cubes import equalise_attributes
import cftime
from ..config import default_config
from ..utils.constraints import ... | kcs/steering/core.py | import logging
from datetime import datetime, timedelta
import numpy as np
import iris
try:
from iris.util import equalise_attributes
except ImportError: # Iris 2
from iris.experimental.equalise_cubes import equalise_attributes
import cftime
from ..config import default_config
from ..utils.constraints import ... | 0.727007 | 0.487978 |
# Author: <NAME>
# Date: 2019-12-12
# This python script is to obtain training data and testing data from preprocessed file for machine learning prediction
import os
import json
import pandas as pd
from sklearn.model_selection import train_test_split
organisms = {"Y_lipolytica", "S_pombe", "S_cerevisiae", "P_pasto... | s1_data_preparation_2.py |
# Author: <NAME>
# Date: 2019-12-12
# This python script is to obtain training data and testing data from preprocessed file for machine learning prediction
import os
import json
import pandas as pd
from sklearn.model_selection import train_test_split
organisms = {"Y_lipolytica", "S_pombe", "S_cerevisiae", "P_pasto... | 0.230833 | 0.452717 |
import os
import sys
import logging
import base64
import time
from radiator import Broker
from radiator.reactor import GeventReactor
def getenv(key, default):
if os.environ.has_key(key):
return os.environ[key]
else:
return default
class ScenarioLogHandler(logging.Handler):
errors = []
... | test/helper.py | import os
import sys
import logging
import base64
import time
from radiator import Broker
from radiator.reactor import GeventReactor
def getenv(key, default):
if os.environ.has_key(key):
return os.environ[key]
else:
return default
class ScenarioLogHandler(logging.Handler):
errors = []
... | 0.131243 | 0.158435 |
import argparse
import inspect
from argparse import ArgumentParser, _SubParsersAction
from typing import Callable
from .cli.cat import get_parser as cat_parser
from .cli.cat import main as cat_main
from .cli.dicom2img import get_parser as dicom2img_parser
from .cli.dicom2img import main as dicom2img_main
from .cli.di... | dicom_utils/__main__.py |
import argparse
import inspect
from argparse import ArgumentParser, _SubParsersAction
from typing import Callable
from .cli.cat import get_parser as cat_parser
from .cli.cat import main as cat_main
from .cli.dicom2img import get_parser as dicom2img_parser
from .cli.dicom2img import main as dicom2img_main
from .cli.di... | 0.727975 | 0.164081 |
from random import choice
import os, gzip
try:
import simplejson as json
except ImportError:
import json
import archetype_builder
from value_setters import set_value
from structures_builder import normalize_keys
from pyehr.utils import decode_dict
from pyehr.ehr.services.dbmanager.dbservices.wrappers import A... | test/misc/test_query_performance/records_builder.py | from random import choice
import os, gzip
try:
import simplejson as json
except ImportError:
import json
import archetype_builder
from value_setters import set_value
from structures_builder import normalize_keys
from pyehr.utils import decode_dict
from pyehr.ehr.services.dbmanager.dbservices.wrappers import A... | 0.381335 | 0.28279 |
import unittest
import os
import requests
import numpy as np
from pandas.api.types import is_numeric_dtype, is_object_dtype, is_bool_dtype
from pymatgen.core.structure import Structure, Composition
from matminer.datasets.tests.base import DatasetTest, do_complete_test
from matminer.datasets.dataset_retrieval import l... | matminer/datasets/tests/test_datasets.py | import unittest
import os
import requests
import numpy as np
from pandas.api.types import is_numeric_dtype, is_object_dtype, is_bool_dtype
from pymatgen.core.structure import Structure, Composition
from matminer.datasets.tests.base import DatasetTest, do_complete_test
from matminer.datasets.dataset_retrieval import l... | 0.596786 | 0.501221 |
from nubia import command, argument
from termcolor import cprint, colored
import sys
import struct
from io import IOBase
from ...utils.fnv import fnv64a
from ...parsers.bundle import GGGBundle
from ...parsers.index import BundleIndex
@command
class Bundle:
"Command for handling bundle files"
@command
@a... | tool/cli/commands/bundle.py |
from nubia import command, argument
from termcolor import cprint, colored
import sys
import struct
from io import IOBase
from ...utils.fnv import fnv64a
from ...parsers.bundle import GGGBundle
from ...parsers.index import BundleIndex
@command
class Bundle:
"Command for handling bundle files"
@command
@a... | 0.327668 | 0.180558 |
# # Create dataset with pairs of anti-glioblastoma drugs - nanoparticles
# In[4]:
import pandas as pd
import numpy as np
import feather
# ## Modify datasets
#
# Read initial data for drugs:
# In[3]:
df_d = pd.read_csv('./datasets/drug(neuro).csv')
df_d.shape
# In[4]:
# remove duplicates in drugs data
prin... | 0-CreateDatasetWithPairs.py |
# # Create dataset with pairs of anti-glioblastoma drugs - nanoparticles
# In[4]:
import pandas as pd
import numpy as np
import feather
# ## Modify datasets
#
# Read initial data for drugs:
# In[3]:
df_d = pd.read_csv('./datasets/drug(neuro).csv')
df_d.shape
# In[4]:
# remove duplicates in drugs data
prin... | 0.403214 | 0.456773 |
import datetime
import logging
import sched
from wikipolicyd.db import Db
from wikipolicyd.policy import Policy
from wikipolicyd.settings_server import SettingsServer
logger = logging.getLogger(__name__)
class Client(object):
_CHECK_INTERVAL_S = 30
def __init__(self, db: Db, policy: Policy, settings: Sett... | wikipolicyd/client.py | import datetime
import logging
import sched
from wikipolicyd.db import Db
from wikipolicyd.policy import Policy
from wikipolicyd.settings_server import SettingsServer
logger = logging.getLogger(__name__)
class Client(object):
_CHECK_INTERVAL_S = 30
def __init__(self, db: Db, policy: Policy, settings: Sett... | 0.353428 | 0.062531 |
from PySide import QtGui, QtCore
class Widget(QtGui.QFrame):
'''Base widget.
Subclass to create widgets that reflect specific schema fragments.
'''
# Emit when value changes.
valueChanged = QtCore.Signal()
def __init__(self, title=None, description=None, required=False,
p... | source/harmony/ui/widget/base.py |
from PySide import QtGui, QtCore
class Widget(QtGui.QFrame):
'''Base widget.
Subclass to create widgets that reflect specific schema fragments.
'''
# Emit when value changes.
valueChanged = QtCore.Signal()
def __init__(self, title=None, description=None, required=False,
p... | 0.762424 | 0.100084 |
from __future__ import absolute_import
from AsposeEmailCloudSdk.api.api_base import ApiBase
from AsposeEmailCloudSdk.models import *
class ContactApi(ApiBase):
"""
Aspose.Email Cloud API. ContactApi operations.
"""
def __init__(self, api_client):
super(ContactApi, self).__init__(api_client... | sdk/AsposeEmailCloudSdk/api/contact_api.py |
from __future__ import absolute_import
from AsposeEmailCloudSdk.api.api_base import ApiBase
from AsposeEmailCloudSdk.models import *
class ContactApi(ApiBase):
"""
Aspose.Email Cloud API. ContactApi operations.
"""
def __init__(self, api_client):
super(ContactApi, self).__init__(api_client... | 0.760117 | 0.10434 |
import mmh3
import math
import shelve
from bitarray import bitarray
from collections import defaultdict, OrderedDict
class BloomFilter:
def __init__(self, N):
self.capacity = N;
self.size = self.get_size(50, 0.05);
self.hash_count = self.get_hash_count(self.size, 100)
self.bf_array ... | solution-1/bloomfilter.py | import mmh3
import math
import shelve
from bitarray import bitarray
from collections import defaultdict, OrderedDict
class BloomFilter:
def __init__(self, N):
self.capacity = N;
self.size = self.get_size(50, 0.05);
self.hash_count = self.get_hash_count(self.size, 100)
self.bf_array ... | 0.254972 | 0.127952 |
from lexer import *
class esxparser(object):
def __init__(self, lexer):
self.lexer = lexer
self.nxtToken = self.lexer.getToken()
def isType(self, token, tokentype):
if not isinstance(token, tokentype):
raise Exception("parse error , Expected another Token than -> " + str(token))
def token(self):
sel... | parser.py | from lexer import *
class esxparser(object):
def __init__(self, lexer):
self.lexer = lexer
self.nxtToken = self.lexer.getToken()
def isType(self, token, tokentype):
if not isinstance(token, tokentype):
raise Exception("parse error , Expected another Token than -> " + str(token))
def token(self):
sel... | 0.262464 | 0.185726 |
# COMMAND ----------
# MAGIC %md
# MAGIC # Complex Types
# MAGIC
# MAGIC Explore built-in functions for working with collections and strings.
# MAGIC
# MAGIC ##### Objectives
# MAGIC 1. Apply collection functions to process arrays
# MAGIC 1. Union DataFrames together
# MAGIC
# MAGIC ##### Methods
# MAGIC - <a href... | Apache-Spark-Programming-with-Databricks/Solutions/ASP 3 - Functions/ASP 3.3 - Complex Types.py |
# COMMAND ----------
# MAGIC %md
# MAGIC # Complex Types
# MAGIC
# MAGIC Explore built-in functions for working with collections and strings.
# MAGIC
# MAGIC ##### Objectives
# MAGIC 1. Apply collection functions to process arrays
# MAGIC 1. Union DataFrames together
# MAGIC
# MAGIC ##### Methods
# MAGIC - <a href... | 0.835819 | 0.713469 |
print("\n\n")
"""
Bu python kodunda ;
parametre olarak verilen dosyadaki (veriler.txt) verilerin hem hepsini hem de onlu veri grupları
için sırasıyla 1,2,3,4,5,6. dereceden polinoma yakınlaştırarak bu polinomların hata değerlerini, katsayı
değerlerini ve en uygun polinomları sonuc.txt dosyasına yazacagız.
... | vize/180401040.py |
print("\n\n")
"""
Bu python kodunda ;
parametre olarak verilen dosyadaki (veriler.txt) verilerin hem hepsini hem de onlu veri grupları
için sırasıyla 1,2,3,4,5,6. dereceden polinoma yakınlaştırarak bu polinomların hata değerlerini, katsayı
değerlerini ve en uygun polinomları sonuc.txt dosyasına yazacagız.
... | 0.131563 | 0.405508 |
import os
import unittest
from unittest.mock import patch
from pash.file_info import FileInfo
class FileInfoTestCase(unittest.TestCase):
@patch('os.path.isdir')
@patch('os.path.basename')
@patch('os.path.getmtime')
@patch('grp.getgrgid')
@patch('pwd.getpwuid')
@patch('os.stat')
@patch('os... | tests/test_file_info.py | import os
import unittest
from unittest.mock import patch
from pash.file_info import FileInfo
class FileInfoTestCase(unittest.TestCase):
@patch('os.path.isdir')
@patch('os.path.basename')
@patch('os.path.getmtime')
@patch('grp.getgrgid')
@patch('pwd.getpwuid')
@patch('os.stat')
@patch('os... | 0.364891 | 0.184418 |
from typing import Type, Union
import pytest
from do_py import R
from db_able import Creatable, Deletable, Loadable, Paginated, Savable, Scrollable
from db_able.utils.sql_generator import ABCSQL, CoreStoredProcedure, CreateProcedure, DeleteProcedure, LoadProcedure, \
PaginatedListProcedure, SaveProcedure, ScrollL... | tests/utils/test_sql_generator.py | from typing import Type, Union
import pytest
from do_py import R
from db_able import Creatable, Deletable, Loadable, Paginated, Savable, Scrollable
from db_able.utils.sql_generator import ABCSQL, CoreStoredProcedure, CreateProcedure, DeleteProcedure, LoadProcedure, \
PaginatedListProcedure, SaveProcedure, ScrollL... | 0.851968 | 0.546073 |
from velocileptors.LPT.cleft_fftw import CLEFT
from velocileptors.EPT.cleft_kexpanded_resummed_fftw import RKECLEFT
from scipy.interpolate import interp1d
def _cleft_pk(k, p_lin, D=None, cleftobj=None, kecleft=True):
'''
Returns a spline object which computes the cleft component spectra.
Computed either i... | anzu/utils.py | from velocileptors.LPT.cleft_fftw import CLEFT
from velocileptors.EPT.cleft_kexpanded_resummed_fftw import RKECLEFT
from scipy.interpolate import interp1d
def _cleft_pk(k, p_lin, D=None, cleftobj=None, kecleft=True):
'''
Returns a spline object which computes the cleft component spectra.
Computed either i... | 0.885148 | 0.608361 |
from typing import Dict
from PyQt5.QtWidgets import (
QVBoxLayout,
QHBoxLayout,
QTableWidget,
QLabel,
QTableWidgetItem,
QWidget,
QDockWidget,
)
from PyQt5.QtGui import(
QFont,
QColor
)
from PyQt5.QtCore import (
Qt,
pyqtSignal,
QEvent,
)
from ..utils import format_add... | cemu/ui/registers.py | from typing import Dict
from PyQt5.QtWidgets import (
QVBoxLayout,
QHBoxLayout,
QTableWidget,
QLabel,
QTableWidgetItem,
QWidget,
QDockWidget,
)
from PyQt5.QtGui import(
QFont,
QColor
)
from PyQt5.QtCore import (
Qt,
pyqtSignal,
QEvent,
)
from ..utils import format_add... | 0.579162 | 0.23501 |
import sys
import os
import logging
logging.basicConfig(level=logging.INFO,
format='%(asctime)s - %(module) s - %(funcName) s - %(lineno) d - %(levelname)s - %(message)s')
logger = logging.getLogger(__name__)
root_path = os.getcwd()
logger.info(f'PATH = {root_path}')
sys.path.append(root_path)
s... | demos/HFL/common/hfl_message.py |
import sys
import os
import logging
logging.basicConfig(level=logging.INFO,
format='%(asctime)s - %(module) s - %(funcName) s - %(lineno) d - %(levelname)s - %(message)s')
logger = logging.getLogger(__name__)
root_path = os.getcwd()
logger.info(f'PATH = {root_path}')
sys.path.append(root_path)
s... | 0.536556 | 0.111145 |
from ektime import *
class Value(object):
def __init__(self, *args):
self.set(*args)
def set(self):
raise NotImplementedError
def current(self):
return self.predicted_at(Time.from_s(time.time()))
def predicted_at(self, time):
raise NotImplementedError
def predicted_time_when(self, value):... | energykit/value.py | from ektime import *
class Value(object):
def __init__(self, *args):
self.set(*args)
def set(self):
raise NotImplementedError
def current(self):
return self.predicted_at(Time.from_s(time.time()))
def predicted_at(self, time):
raise NotImplementedError
def predicted_time_when(self, value):... | 0.502686 | 0.478285 |
import numpy as np
import pandas as pd
from unify_idents.engine_parsers.base_parser import IdentBaseParser
class Omssa_Parser(IdentBaseParser):
"""File parser for OMSSA."""
def __init__(self, *args, **kwargs):
"""Initialize parser.
Reads in data file and provides mappings.
"""
... | unify_idents/engine_parsers/ident/omssa_2_1_9_parser.py |
import numpy as np
import pandas as pd
from unify_idents.engine_parsers.base_parser import IdentBaseParser
class Omssa_Parser(IdentBaseParser):
"""File parser for OMSSA."""
def __init__(self, *args, **kwargs):
"""Initialize parser.
Reads in data file and provides mappings.
"""
... | 0.743168 | 0.28748 |
import socket
import threading
from select import select
from config import (SECONDS_COUNT_DOWN, SECONDS_PER_SESSION, SESSION,
UPDATE_RATE)
from network import receive, send
from pygame import time
from .utils import TAPPED, UNTAPPED
class Server:
def __init__(self, host: str, port: int) -> ... | server/server.py | import socket
import threading
from select import select
from config import (SECONDS_COUNT_DOWN, SECONDS_PER_SESSION, SESSION,
UPDATE_RATE)
from network import receive, send
from pygame import time
from .utils import TAPPED, UNTAPPED
class Server:
def __init__(self, host: str, port: int) -> ... | 0.290779 | 0.068694 |
import unittest
from diagnostic_msgs.msg import DiagnosticStatus
from diagnostic_updater import DiagnosticStatusWrapper
class TestDiagnosticStatusWrapper(unittest.TestCase):
def test_init_empty(self):
d = DiagnosticStatusWrapper()
self.assertEqual(d.level, b'\x00')
self.assertEqual(d.mes... | diagnostics/diagnostic_updater/test/test_diagnostic_status_wrapper.py | import unittest
from diagnostic_msgs.msg import DiagnosticStatus
from diagnostic_updater import DiagnosticStatusWrapper
class TestDiagnosticStatusWrapper(unittest.TestCase):
def test_init_empty(self):
d = DiagnosticStatusWrapper()
self.assertEqual(d.level, b'\x00')
self.assertEqual(d.mes... | 0.499756 | 0.44071 |
import unittest
from typing import Any, Mapping, Optional, Type
import numpy
from sklearn.tree import DecisionTreeRegressor
from nlkda.models.base import BoundModel, KAsInputWrapper, KAsOutputWrapper
from nlkda.models.linear import MRkNNCoPTreeBounds
from nlkda.utils import all_knn
EPSILON = 1.0e-06
class BoundMod... | tests/test_models.py | import unittest
from typing import Any, Mapping, Optional, Type
import numpy
from sklearn.tree import DecisionTreeRegressor
from nlkda.models.base import BoundModel, KAsInputWrapper, KAsOutputWrapper
from nlkda.models.linear import MRkNNCoPTreeBounds
from nlkda.utils import all_knn
EPSILON = 1.0e-06
class BoundMod... | 0.915181 | 0.434281 |
from sklearn.datasets import load_iris
data = load_iris()
X = data.data
y = data.target
n_iter_0 = 0
n_iter_1 = 33
random_state = 0
cv = 2
n_jobs = 2
search_config = {
"sklearn.tree.DecisionTreeClassifier": {
"criterion": ["gini", "entropy"],
"max_depth": range(1, 21),
"min_samples_split... | src/Hyperactive/tests/test_performance.py |
from sklearn.datasets import load_iris
data = load_iris()
X = data.data
y = data.target
n_iter_0 = 0
n_iter_1 = 33
random_state = 0
cv = 2
n_jobs = 2
search_config = {
"sklearn.tree.DecisionTreeClassifier": {
"criterion": ["gini", "entropy"],
"max_depth": range(1, 21),
"min_samples_split... | 0.835953 | 0.399724 |
#验证
#my
from keras.models import load_model
import os
from keras.preprocessing.image import ImageDataGenerator
import numpy as np
img_width = 128
img_height = 128
batch_size = 32
FishNames = ['rock', 'paper', 'scissors', 'room']
#root_path = '/Users/sharp/dev/project/july/course/my-app/Rock-paper-scissors/my/'... | machine_learning/predict.py |
#验证
#my
from keras.models import load_model
import os
from keras.preprocessing.image import ImageDataGenerator
import numpy as np
img_width = 128
img_height = 128
batch_size = 32
FishNames = ['rock', 'paper', 'scissors', 'room']
#root_path = '/Users/sharp/dev/project/july/course/my-app/Rock-paper-scissors/my/'... | 0.201499 | 0.260533 |
import json
from time import time
import jwt
import pytest
from django.conf import settings
from httpretty import HTTPretty
from jwt.algorithms import RSAAlgorithm
from social_core.backends.utils import load_backends
from social_core.tests.backends.oauth import OAuth2Test
from social_core.tests.backends.test_azuread_b... | auth_backends/tests/azure_ad_base.py | import json
from time import time
import jwt
import pytest
from django.conf import settings
from httpretty import HTTPretty
from jwt.algorithms import RSAAlgorithm
from social_core.backends.utils import load_backends
from social_core.tests.backends.oauth import OAuth2Test
from social_core.tests.backends.test_azuread_b... | 0.500488 | 0.076961 |
import matplotlib.pyplot as plt
from matplotlib.patches import Rectangle
import os
from skimage import io
import sys
from config import DETECTION_THRESHOLD, MINIMAL_EDGE_LENGTH
import lib_classification
sys.path.insert(0, "../annotation/")
from annotate import asset_prefix_from_asset, identifier_from_asset, mkdirp, s... | classification/test_overview.py | import matplotlib.pyplot as plt
from matplotlib.patches import Rectangle
import os
from skimage import io
import sys
from config import DETECTION_THRESHOLD, MINIMAL_EDGE_LENGTH
import lib_classification
sys.path.insert(0, "../annotation/")
from annotate import asset_prefix_from_asset, identifier_from_asset, mkdirp, s... | 0.381911 | 0.296559 |
import threading
import os, time
import json
import traceback
from base.urlop import UrlRequestOp
from core import login, course
from handler.struct.user import UserData
from handler import Pool
from handler.Error import LoginBasicException, UrlOpTimeOutError, PullerBasicException
import gui
import llogger
NOTICE_... | handler/Opa.py | import threading
import os, time
import json
import traceback
from base.urlop import UrlRequestOp
from core import login, course
from handler.struct.user import UserData
from handler import Pool
from handler.Error import LoginBasicException, UrlOpTimeOutError, PullerBasicException
import gui
import llogger
NOTICE_... | 0.140749 | 0.049773 |
import json
import torch
import torch.nn as nn
import torch.nn.functional as F
import torch.optim
import torch.utils.data
from ..config import Config
from ..datasets import SSTreebankDataset
from ..utils import adjust_learning_rate, accuracy, save_checkpoint, AverageMeter, train, validate, testing
class Mode... | tasks/sst/third_party/models/TextAttnBiLSTM.py | import json
import torch
import torch.nn as nn
import torch.nn.functional as F
import torch.optim
import torch.utils.data
from ..config import Config
from ..datasets import SSTreebankDataset
from ..utils import adjust_learning_rate, accuracy, save_checkpoint, AverageMeter, train, validate, testing
class Mode... | 0.60288 | 0.285434 |
import json
import time
from pathlib import Path
import matplotlib as mpl
import numpy as np
import wget
from astropy.io import fits
from matplotlib import pylab as pl
from matplotlib import pyplot as plt
mpl.use("Agg")
def download_metafits(num_files, wait, out_dir):
"""
Download metafits files from `mwate... | src/embers/mwa_utils/mwa_dipoles.py | import json
import time
from pathlib import Path
import matplotlib as mpl
import numpy as np
import wget
from astropy.io import fits
from matplotlib import pylab as pl
from matplotlib import pyplot as plt
mpl.use("Agg")
def download_metafits(num_files, wait, out_dir):
"""
Download metafits files from `mwate... | 0.720762 | 0.414129 |
import json
import math
import tf
class Pose:
def __init__(self, position, orientation):
self.position = position
self.orientation = orientation
@classmethod
def from_json(cls, path):
with open(path) as f:
transform = json.load(f)
# The NxLib transformation i... | ensenso_camera_test/test/helper.py | import json
import math
import tf
class Pose:
def __init__(self, position, orientation):
self.position = position
self.orientation = orientation
@classmethod
def from_json(cls, path):
with open(path) as f:
transform = json.load(f)
# The NxLib transformation i... | 0.905184 | 0.355943 |
import itertools
import functools
import os
import torch
from torch import nn
from torch.autograd import Variable
import torchvision.datasets as dsets
import torchvision.transforms as transforms
import utils
from ops import conv_bn_lrelu, conv_bn_relu, dconv_bn_relu, ResidualBlock
class Discriminator(nn.Module):
... | model.py | import itertools
import functools
import os
import torch
from torch import nn
from torch.autograd import Variable
import torchvision.datasets as dsets
import torchvision.transforms as transforms
import utils
from ops import conv_bn_lrelu, conv_bn_relu, dconv_bn_relu, ResidualBlock
class Discriminator(nn.Module):
... | 0.851722 | 0.311054 |
from django.db import migrations, models
class Migration(migrations.Migration):
dependencies = [
('payment', '0004_auto_20150415_2210'),
]
operations = [
migrations.CreateModel(
name='PaymentPrice',
fields=[
('id', models.AutoField(verbose_name='... | apps/payment/migrations/0005_auto_20150429_1758.py |
from django.db import migrations, models
class Migration(migrations.Migration):
dependencies = [
('payment', '0004_auto_20150415_2210'),
]
operations = [
migrations.CreateModel(
name='PaymentPrice',
fields=[
('id', models.AutoField(verbose_name='... | 0.595022 | 0.12595 |