code stringlengths 2k 1.04M | repo_path stringlengths 5 517 | parsed_code stringlengths 0 1.04M | quality_prob float64 0.02 0.95 | learning_prob float64 0.02 0.93 |
|---|---|---|---|---|
from six import integer_types
class QuilAtom(object):
"""
Abstract class for atomic elements of Quil.
"""
def out(self):
pass
def __str__(self):
return self.out()
def __eq__(self, other):
return isinstance(other, self.__class__) and self.out() == other.out()
def ... | pyquil/quilatom.py | from six import integer_types
class QuilAtom(object):
"""
Abstract class for atomic elements of Quil.
"""
def out(self):
pass
def __str__(self):
return self.out()
def __eq__(self, other):
return isinstance(other, self.__class__) and self.out() == other.out()
def ... | 0.906155 | 0.439507 |
import consulate
import hashlib
import json
import logging
import os
import time
from datetime import datetime
from urllib import parse
from cluster import util
DEFAULT_TIMEOUT = 300
logger = logging.getLogger(__name__)
class Cluster:
_consul_url = None
_consul = None
_nodes = None
def __init__(s... | cluster/cluster.py | import consulate
import hashlib
import json
import logging
import os
import time
from datetime import datetime
from urllib import parse
from cluster import util
DEFAULT_TIMEOUT = 300
logger = logging.getLogger(__name__)
class Cluster:
_consul_url = None
_consul = None
_nodes = None
def __init__(s... | 0.428233 | 0.105856 |
__all__ = ['NoisyStudent']
# Cell
from ..imports import *
from ..utils import *
from ..data.preprocessing import *
from ..data.transforms import *
from ..models.layers import *
from fastai.callback.all import *
# Cell
import torch.multiprocessing
torch.multiprocessing.set_sharing_strategy('file_system')
# Cell
# T... | tsai/callback/noisy_student.py |
__all__ = ['NoisyStudent']
# Cell
from ..imports import *
from ..utils import *
from ..data.preprocessing import *
from ..data.transforms import *
from ..models.layers import *
from fastai.callback.all import *
# Cell
import torch.multiprocessing
torch.multiprocessing.set_sharing_strategy('file_system')
# Cell
# T... | 0.709523 | 0.461441 |
import torch
import torchnet as tnt
from torchnet.logger import VisdomPlotLogger, VisdomLogger
class MeterLogger(object):
''' A class to package and visualize meters.
Args:
server: The uri of the Visdom server
env: Visdom environment to log to.
port: Port of the visdom server.
... | torchnet/logger/meterlogger.py | import torch
import torchnet as tnt
from torchnet.logger import VisdomPlotLogger, VisdomLogger
class MeterLogger(object):
''' A class to package and visualize meters.
Args:
server: The uri of the Visdom server
env: Visdom environment to log to.
port: Port of the visdom server.
... | 0.780662 | 0.304429 |
import pickle
import time
from unittest import skipIf, TestCase
from nose.tools import istest, raises
import redis
from pycket.driver import MemcachedDriver, RedisDriver
from pycket.session import ConfigurationError, SessionManager, SessionMixin
skip_slow_tests = False
class SessionMixinTest(TestCase):
@istes... | tests/test_session.py | import pickle
import time
from unittest import skipIf, TestCase
from nose.tools import istest, raises
import redis
from pycket.driver import MemcachedDriver, RedisDriver
from pycket.session import ConfigurationError, SessionManager, SessionMixin
skip_slow_tests = False
class SessionMixinTest(TestCase):
@istes... | 0.532425 | 0.279521 |
__author__ = "<NAME>"
#encoding="utf-8"
import pickle
import numpy as np
import os
import cv2
import matplotlib.pyplot as plt
def unpickle(file):
import pickle
with open(file, 'rb') as fo:
dict = pickle.load(fo, encoding='bytes')
return dict
paths_labels=unpickle("FACES_P_S")
images_path = paths_... | Day08_20190909/data_preprocess/generate_data.py | __author__ = "<NAME>"
#encoding="utf-8"
import pickle
import numpy as np
import os
import cv2
import matplotlib.pyplot as plt
def unpickle(file):
import pickle
with open(file, 'rb') as fo:
dict = pickle.load(fo, encoding='bytes')
return dict
paths_labels=unpickle("FACES_P_S")
images_path = paths_... | 0.324663 | 0.268442 |
import asyncio
import logging
from homeassistant.core import callback
from homeassistant.components.apple_tv import (
ATTR_ATV, ATTR_POWER, DATA_APPLE_TV, DATA_ENTITIES)
from homeassistant.components.media_player import (
SUPPORT_NEXT_TRACK, SUPPORT_PAUSE, SUPPORT_PREVIOUS_TRACK, SUPPORT_SEEK,
SUPPORT_STOP... | homeassistant/components/media_player/apple_tv.py | import asyncio
import logging
from homeassistant.core import callback
from homeassistant.components.apple_tv import (
ATTR_ATV, ATTR_POWER, DATA_APPLE_TV, DATA_ENTITIES)
from homeassistant.components.media_player import (
SUPPORT_NEXT_TRACK, SUPPORT_PAUSE, SUPPORT_PREVIOUS_TRACK, SUPPORT_SEEK,
SUPPORT_STOP... | 0.648911 | 0.110184 |
from flask_app.config.mysqlconnection import connectToMySQL
from flask import flash
from flask_app import bcrypt, DATABASE
import re
EMAIL_REGEX = re.compile(r'^[a-zA-Z0-9.+_-]+@[a-zA-Z0-9._-]+\.[a-zA-Z]+$')
class User:
def __init__( self , data ):
self.id = data['id']
self.first_name = data['fir... | flask_mysql/recipes/flask_app/models/model_user.py | from flask_app.config.mysqlconnection import connectToMySQL
from flask import flash
from flask_app import bcrypt, DATABASE
import re
EMAIL_REGEX = re.compile(r'^[a-zA-Z0-9.+_-]+@[a-zA-Z0-9._-]+\.[a-zA-Z]+$')
class User:
def __init__( self , data ):
self.id = data['id']
self.first_name = data['fir... | 0.293 | 0.174305 |
from __future__ import absolute_import
from __future__ import division
from __future__ import print_function
import keras
import argparse
import os
from keras.metrics import top_k_categorical_accuracy, categorical_accuracy
from keras.preprocessing.image import ImageDataGenerator
from keras.layers import *
from keras.... | paper/ImageNet/imagenet_cnn_reasoning_trainable_patches.py | from __future__ import absolute_import
from __future__ import division
from __future__ import print_function
import keras
import argparse
import os
from keras.metrics import top_k_categorical_accuracy, categorical_accuracy
from keras.preprocessing.image import ImageDataGenerator
from keras.layers import *
from keras.... | 0.890735 | 0.458227 |
import tensorflow as tf
import numpy as np
import geo_data_prepare
from keras.preprocessing.sequence import pad_sequences
import geo_config as config
import random
from sklearn.metrics import f1_score
from tqdm import tqdm
from sklearn import metrics
data_pre = geo_data_prepare.Data_Prepare()
con = config.Config()
cl... | geo_test.py | import tensorflow as tf
import numpy as np
import geo_data_prepare
from keras.preprocessing.sequence import pad_sequences
import geo_config as config
import random
from sklearn.metrics import f1_score
from tqdm import tqdm
from sklearn import metrics
data_pre = geo_data_prepare.Data_Prepare()
con = config.Config()
cl... | 0.73659 | 0.211631 |
from django.db import models
from django.contrib.auth.models import PermissionsMixin
from django.contrib.auth.models import Group
from django.contrib.auth.models import Permission
from django.contrib.auth.base_user import AbstractBaseUser
from django.contrib.auth.base_user import BaseUserManager
from django.utils.trans... | back/userapp/models.py | from django.db import models
from django.contrib.auth.models import PermissionsMixin
from django.contrib.auth.models import Group
from django.contrib.auth.models import Permission
from django.contrib.auth.base_user import AbstractBaseUser
from django.contrib.auth.base_user import BaseUserManager
from django.utils.trans... | 0.495606 | 0.071074 |
from tempfile import TemporaryDirectory
from dataclasses import dataclass, asdict
from typing import List, Dict, Any
from pathlib import Path
from tqdm import tqdm
import argparse
import csv
from PIL import Image
import pymongo
import boto3
from botocore.exceptions import ClientError
from dacite import from_dict
import... | check/build_batch_csv.py | from tempfile import TemporaryDirectory
from dataclasses import dataclass, asdict
from typing import List, Dict, Any
from pathlib import Path
from tqdm import tqdm
import argparse
import csv
from PIL import Image
import pymongo
import boto3
from botocore.exceptions import ClientError
from dacite import from_dict
import... | 0.592077 | 0.244792 |
from unittest.mock import Mock
from openslides_backend.action.action_handler import ActionHandler
from openslides_backend.action.util.typing import Payload
from .base import BaseActionTestCase
class GeneralActionCommandFormat(BaseActionTestCase):
"""
Tests the interface to datastore-command with one WriteRe... | tests/system/action/test_action_command_format.py | from unittest.mock import Mock
from openslides_backend.action.action_handler import ActionHandler
from openslides_backend.action.util.typing import Payload
from .base import BaseActionTestCase
class GeneralActionCommandFormat(BaseActionTestCase):
"""
Tests the interface to datastore-command with one WriteRe... | 0.633864 | 0.358521 |
import re
import sys
import llnl.util.lang
from spack.compiler import Compiler
from spack.version import ver
class Aocc(Compiler):
# Subclasses use possible names of C compiler
cc_names = ['clang']
# Subclasses use possible names of C++ compiler
cxx_names = ['clang++']
# Subclasses use possib... | lib/spack/spack/compilers/aocc.py |
import re
import sys
import llnl.util.lang
from spack.compiler import Compiler
from spack.version import ver
class Aocc(Compiler):
# Subclasses use possible names of C compiler
cc_names = ['clang']
# Subclasses use possible names of C++ compiler
cxx_names = ['clang++']
# Subclasses use possib... | 0.361165 | 0.135146 |
import json
import os
import ssl
import urllib.error
from six.moves.urllib import request
from six.moves.urllib import parse
from sfconfig.components import Component
from sfconfig.utils import fail
def get_sf_version():
try:
return open("/etc/sf-release").read().strip()
except IOError:
ret... | ansible/roles/sf-install-server/meta/sfconfig.py |
import json
import os
import ssl
import urllib.error
from six.moves.urllib import request
from six.moves.urllib import parse
from sfconfig.components import Component
from sfconfig.utils import fail
def get_sf_version():
try:
return open("/etc/sf-release").read().strip()
except IOError:
ret... | 0.275325 | 0.075414 |
__author__ = '<EMAIL> (<NAME>)'
import logging
import re
from bisect import bisect_left, bisect_right
from collections import namedtuple
from functools import partial
from picoparse import one_of, choice, many1, tri, commit, p, many_until1
from picoparse.text import run_text_parser, as_string, lexeme, whitespace, quo... | backend/db/query_parser.py | __author__ = '<EMAIL> (<NAME>)'
import logging
import re
from bisect import bisect_left, bisect_right
from collections import namedtuple
from functools import partial
from picoparse import one_of, choice, many1, tri, commit, p, many_until1
from picoparse.text import run_text_parser, as_string, lexeme, whitespace, quo... | 0.805479 | 0.400075 |
import argparse
import glob
import os
import matplotlib.pyplot as plt
import numpy as np
# Collect command line arguments
parser = argparse.ArgumentParser(description='Process command line args.')
parser.add_argument('--input_dir', type=str,
help='Images directory')
parser.add_argument('--output_d... | scripts/padding.py |
import argparse
import glob
import os
import matplotlib.pyplot as plt
import numpy as np
# Collect command line arguments
parser = argparse.ArgumentParser(description='Process command line args.')
parser.add_argument('--input_dir', type=str,
help='Images directory')
parser.add_argument('--output_d... | 0.456894 | 0.279294 |
from openstack.tests.unit import base
from openstack.compute.v2 import flavor
IDENTIFIER = 'IDENTIFIER'
BASIC_EXAMPLE = {
'id': IDENTIFIER,
'links': '2',
'name': '3',
'disk': 4,
'os-flavor-access:is_public': True,
'ram': 6,
'vcpus': 7,
'swap': 8,
'OS-FLV-EXT-DATA:ephemeral': 9,
... | openstack/tests/unit/compute/v2/test_flavor.py |
from openstack.tests.unit import base
from openstack.compute.v2 import flavor
IDENTIFIER = 'IDENTIFIER'
BASIC_EXAMPLE = {
'id': IDENTIFIER,
'links': '2',
'name': '3',
'disk': 4,
'os-flavor-access:is_public': True,
'ram': 6,
'vcpus': 7,
'swap': 8,
'OS-FLV-EXT-DATA:ephemeral': 9,
... | 0.659405 | 0.353345 |
import torch
from . import io
class DataHandler(object):
"""
Data handler for intervention-based Autoencoder.
Args:
num_interventions (int): Number of interventions.
*args (torch.Tensor): The full datasets.
"""
def __init__(self, num_interventions, datasets=torch.Tensor()):
... | examples/utils/data_handler.py | import torch
from . import io
class DataHandler(object):
"""
Data handler for intervention-based Autoencoder.
Args:
num_interventions (int): Number of interventions.
*args (torch.Tensor): The full datasets.
"""
def __init__(self, num_interventions, datasets=torch.Tensor()):
... | 0.880964 | 0.63806 |
import argparse
import os
import unittest
import mock
from kayobe import utils
from kayobe import vault
class TestCase(unittest.TestCase):
def test_validate_args_ok(self):
parser = argparse.ArgumentParser()
vault.add_args(parser)
parsed_args = parser.parse_args([])
vault.valida... | kayobe/tests/unit/test_vault.py |
import argparse
import os
import unittest
import mock
from kayobe import utils
from kayobe import vault
class TestCase(unittest.TestCase):
def test_validate_args_ok(self):
parser = argparse.ArgumentParser()
vault.add_args(parser)
parsed_args = parser.parse_args([])
vault.valida... | 0.519278 | 0.367412 |
import os
import cv2
import yaml
import numpy as np
import tensorflow as tf
from tqdm import tqdm
def make_tf_recoord(in_dir, out_file):
files = os.listdir(in_dir)
with tf.python_io.TFRecordWriter(out_file) as writer:
for f, file in enumerate(tqdm(files)):
arr = cv2.imread(os.path.join(in_dir, file... | data_loader/tfrecord_generator.py | import os
import cv2
import yaml
import numpy as np
import tensorflow as tf
from tqdm import tqdm
def make_tf_recoord(in_dir, out_file):
files = os.listdir(in_dir)
with tf.python_io.TFRecordWriter(out_file) as writer:
for f, file in enumerate(tqdm(files)):
arr = cv2.imread(os.path.join(in_dir, file... | 0.207616 | 0.151969 |
import logging
from oauthlib.oauth2 import AccessDeniedError, MissingTokenError
from ring_doorbell import Auth
import voluptuous as vol
from homeassistant import config_entries, const, core, exceptions
from . import DOMAIN
_LOGGER = logging.getLogger(__name__)
async def validate_input(hass: core.HomeAssistant, da... | homeassistant/components/ring/config_flow.py | import logging
from oauthlib.oauth2 import AccessDeniedError, MissingTokenError
from ring_doorbell import Auth
import voluptuous as vol
from homeassistant import config_entries, const, core, exceptions
from . import DOMAIN
_LOGGER = logging.getLogger(__name__)
async def validate_input(hass: core.HomeAssistant, da... | 0.69451 | 0.132178 |
import os
import sys
import ssl
import argparse
from seldom.logging import log
from seldom.har2case.core import HarParser
from webdriver_manager.firefox import GeckoDriverManager
from webdriver_manager.microsoft import IEDriverManager
from webdriver_manager.microsoft import EdgeChromiumDriverManager
from webdriver_mana... | seldom/cli.py | import os
import sys
import ssl
import argparse
from seldom.logging import log
from seldom.har2case.core import HarParser
from webdriver_manager.firefox import GeckoDriverManager
from webdriver_manager.microsoft import IEDriverManager
from webdriver_manager.microsoft import EdgeChromiumDriverManager
from webdriver_mana... | 0.343892 | 0.146697 |
import graphene
import pendulum
from dagster.core.storage.pipeline_run import PipelineRunStatus, PipelineRunsFilter
from .pipelines.status import GrapheneRunStatus
from .runs import GrapheneRunConfigData
from .util import non_null_list
class GrapheneAssetKeyInput(graphene.InputObjectType):
path = non_null_list(g... | python_modules/dagster-graphql/dagster_graphql/schema/inputs.py | import graphene
import pendulum
from dagster.core.storage.pipeline_run import PipelineRunStatus, PipelineRunsFilter
from .pipelines.status import GrapheneRunStatus
from .runs import GrapheneRunConfigData
from .util import non_null_list
class GrapheneAssetKeyInput(graphene.InputObjectType):
path = non_null_list(g... | 0.752286 | 0.246219 |
from nssrc.com.citrix.netscaler.nitro.resource.base.base_resource import base_resource
from nssrc.com.citrix.netscaler.nitro.resource.base.base_resource import base_response
from nssrc.com.citrix.netscaler.nitro.service.options import options
from nssrc.com.citrix.netscaler.nitro.exception.nitro_exception import nitro... | nitro-python/nssrc/com/citrix/netscaler/nitro/resource/config/wf/wfsite.py |
from nssrc.com.citrix.netscaler.nitro.resource.base.base_resource import base_resource
from nssrc.com.citrix.netscaler.nitro.resource.base.base_resource import base_response
from nssrc.com.citrix.netscaler.nitro.service.options import options
from nssrc.com.citrix.netscaler.nitro.exception.nitro_exception import nitro... | 0.627381 | 0.182936 |
import pytest
import unittest
from nltkma import FreqDist
from nltkma.lm import NgramCounter
from nltkma.util import everygrams
class TestNgramCounter:
"""Tests for NgramCounter that only involve lookup, no modification."""
@classmethod
def setup_class(self):
text = [list("abcd"), list("egdbe")... | nltkma/test/unit/lm/test_counter.py |
import pytest
import unittest
from nltkma import FreqDist
from nltkma.lm import NgramCounter
from nltkma.util import everygrams
class TestNgramCounter:
"""Tests for NgramCounter that only involve lookup, no modification."""
@classmethod
def setup_class(self):
text = [list("abcd"), list("egdbe")... | 0.710729 | 0.744656 |
import warnings
from typing import Any, Dict, Optional
from lhotse import CutSet, Seconds
from lhotse.dataset.sampling.base import CutSampler, TimeConstraint
from lhotse.dataset.sampling.data_source import DataSource
from lhotse.utils import is_none_or_gt
class SimpleCutSampler(CutSampler):
"""
Samples cuts ... | lhotse/dataset/sampling/simple.py | import warnings
from typing import Any, Dict, Optional
from lhotse import CutSet, Seconds
from lhotse.dataset.sampling.base import CutSampler, TimeConstraint
from lhotse.dataset.sampling.data_source import DataSource
from lhotse.utils import is_none_or_gt
class SimpleCutSampler(CutSampler):
"""
Samples cuts ... | 0.945951 | 0.50177 |
import numpy as np
import itertools
import random
def getAllBreakPoints(permutation):
breakpoints = [(i + 1) for i in range(0, len(permutation) - 1) if (isAdjacent(permutation[i], permutation[i+1]) is False)]
if(permutation[0] != 1):
breakpoints.append(0)
if(permutation[len(permutation) - 1] != le... | operationsPermutation.py |
import numpy as np
import itertools
import random
def getAllBreakPoints(permutation):
breakpoints = [(i + 1) for i in range(0, len(permutation) - 1) if (isAdjacent(permutation[i], permutation[i+1]) is False)]
if(permutation[0] != 1):
breakpoints.append(0)
if(permutation[len(permutation) - 1] != le... | 0.427277 | 0.378057 |
from novaclient import base
from novaclient import exceptions
from novaclient.openstack.common.gettextutils import _
class Network(base.Resource):
"""
A network.
"""
HUMAN_ID = False
NAME_ATTR = "label"
def __repr__(self):
return "<Network: %s>" % self.label
def delete(self):
... | novaclient/v1_1/networks.py | from novaclient import base
from novaclient import exceptions
from novaclient.openstack.common.gettextutils import _
class Network(base.Resource):
"""
A network.
"""
HUMAN_ID = False
NAME_ATTR = "label"
def __repr__(self):
return "<Network: %s>" % self.label
def delete(self):
... | 0.797793 | 0.26443 |
from __future__ import absolute_import
from __future__ import division
from __future__ import print_function
import random
import tempfile
import numpy as np
import tensorflow as tf
from tensorflow.contrib import learn
from tensorflow.contrib.learn.python.learn.utils import export
from tensorflow.contrib.session_bun... | tensorflow/contrib/learn/python/learn/utils/export_test.py | from __future__ import absolute_import
from __future__ import division
from __future__ import print_function
import random
import tempfile
import numpy as np
import tensorflow as tf
from tensorflow.contrib import learn
from tensorflow.contrib.learn.python.learn.utils import export
from tensorflow.contrib.session_bun... | 0.772101 | 0.340787 |
from ..helper import config
class tracker_trainer:
"""tracker trainer class"""
def __init__(self, example_generator, regressor_train, logger):
"""TODO: to be defined. """
self.example_generator_ = example_generator
self.regressor_train_ = regressor_train
self.num_batches_ = ... | goturn_single/tracker/tracker_trainer.py |
from ..helper import config
class tracker_trainer:
"""tracker trainer class"""
def __init__(self, example_generator, regressor_train, logger):
"""TODO: to be defined. """
self.example_generator_ = example_generator
self.regressor_train_ = regressor_train
self.num_batches_ = ... | 0.438064 | 0.29733 |
from keras.engine import Model
from keras.layers import ( Bidirectional, Masking, GaussianNoise,
Input, SimpleRNN, LSTM, Dense, Dropout, TimeDistributed )
from keras.optimizers import RMSprop, Adam
from CTCModel import CTCModel
def classif_rnn_network(T , D):
input_layer = Input( shape=( ... | networks.py | from keras.engine import Model
from keras.layers import ( Bidirectional, Masking, GaussianNoise,
Input, SimpleRNN, LSTM, Dense, Dropout, TimeDistributed )
from keras.optimizers import RMSprop, Adam
from CTCModel import CTCModel
def classif_rnn_network(T , D):
input_layer = Input( shape=( ... | 0.814717 | 0.404213 |
import cdms2
import copy
import matplotlib.cm
import matplotlib.pyplot as plt
from matplotlib.patches import Rectangle
import os
def plot_power(d, title, fout, ewr=None):
y = d.getAxis(0)[:]
x = d.getAxis(1)[:]
# adjust font size
SMALL_SIZE = 8
MEDIUM_SIZE = 13
BIGGER_SIZE = 15
plt.rc('f... | pcmdi_metrics/mjo/lib/plot_wavenumber_frequency_power.py | import cdms2
import copy
import matplotlib.cm
import matplotlib.pyplot as plt
from matplotlib.patches import Rectangle
import os
def plot_power(d, title, fout, ewr=None):
y = d.getAxis(0)[:]
x = d.getAxis(1)[:]
# adjust font size
SMALL_SIZE = 8
MEDIUM_SIZE = 13
BIGGER_SIZE = 15
plt.rc('f... | 0.568056 | 0.469155 |
from __future__ import print_function, absolute_import, division #makes KratosMultiphysics backward compatible with python 2.6 and 2.7
# Importing the Kratos Library
import KratosMultiphysics
from KratosMultiphysics.json_utilities import read_external_json
# Import KratosUnittest
import KratosMultiphysics.KratosUnitte... | kratos/python_scripts/from_json_check_result_process.py | from __future__ import print_function, absolute_import, division #makes KratosMultiphysics backward compatible with python 2.6 and 2.7
# Importing the Kratos Library
import KratosMultiphysics
from KratosMultiphysics.json_utilities import read_external_json
# Import KratosUnittest
import KratosMultiphysics.KratosUnitte... | 0.731251 | 0.30368 |
__docformat__ = 'restructuredtext'
__version__ = '$Id: silent.py 1213 2007-08-30 10:47:05Z Alex.Holkner $'
import time
from pyglet.media import BasePlayer, ManagedSoundPlayerMixIn, Listener
from pyglet.media import MediaException
class SilentPlayer(BasePlayer):
def __init__(self):
super(SilentPlayer, sel... | sympy/plotting/pyglet/media/drivers/silent.py | __docformat__ = 'restructuredtext'
__version__ = '$Id: silent.py 1213 2007-08-30 10:47:05Z Alex.Holkner $'
import time
from pyglet.media import BasePlayer, ManagedSoundPlayerMixIn, Listener
from pyglet.media import MediaException
class SilentPlayer(BasePlayer):
def __init__(self):
super(SilentPlayer, sel... | 0.600774 | 0.107227 |
from __future__ import division
from __future__ import print_function
import os, math, random
from collections import OrderedDict
import numpy as np
import pandas as pd
from typing import Text, Union
import copy
from functools import partial
from typing import Optional, Text
from qlib.utils import get_or_create_path
... | xautodl/trade_models/quant_transformer.py | from __future__ import division
from __future__ import print_function
import os, math, random
from collections import OrderedDict
import numpy as np
import pandas as pd
from typing import Text, Union
import copy
from functools import partial
from typing import Optional, Text
from qlib.utils import get_or_create_path
... | 0.939276 | 0.168309 |
from __future__ import annotations
from typing import List, Union, Optional, TYPE_CHECKING
import numpy as np
from pyNastran.bdf.mesh_utils.internal_utils import get_bdf_model
if TYPE_CHECKING:
from pyNastran.bdf.bdf import BDF
def find_coplanar_triangles(bdf_filename: Union[BDF, str],
... | pyNastran/bdf/mesh_utils/find_coplanar_elements.py | from __future__ import annotations
from typing import List, Union, Optional, TYPE_CHECKING
import numpy as np
from pyNastran.bdf.mesh_utils.internal_utils import get_bdf_model
if TYPE_CHECKING:
from pyNastran.bdf.bdf import BDF
def find_coplanar_triangles(bdf_filename: Union[BDF, str],
... | 0.579876 | 0.488039 |
import cog
from .codegen import camel_to_snake, avoid_keyword, ENV
class Tag:
def __init__(self, name, underlying_type, start_value=None, doc=None):
self.kind = "tag"
self.name = name
self.underlying_type = underlying_type
self.start_value = start_value
self.doc = doc
... | support/codegen/unions.py |
import cog
from .codegen import camel_to_snake, avoid_keyword, ENV
class Tag:
def __init__(self, name, underlying_type, start_value=None, doc=None):
self.kind = "tag"
self.name = name
self.underlying_type = underlying_type
self.start_value = start_value
self.doc = doc
... | 0.6705 | 0.155912 |
from urllib import request
from io import BytesIO
import json
import requests
def getStationList(start,end):
print("GENERATION: ",start,end)
start=start.replace(' ','%20')
end= end.replace(' ','%20')
url= 'https://api.tfl.gov.uk/Journey/JourneyResults/'+start + '%20underground%20station/to/'+end+'%2... | External/Functions.py | from urllib import request
from io import BytesIO
import json
import requests
def getStationList(start,end):
print("GENERATION: ",start,end)
start=start.replace(' ','%20')
end= end.replace(' ','%20')
url= 'https://api.tfl.gov.uk/Journey/JourneyResults/'+start + '%20underground%20station/to/'+end+'%2... | 0.402275 | 0.241903 |
import logging
from enhterm.base import EtBase
logger = logging.getLogger('et.p')
class Provider(EtBase):
"""
A class capable of providing command to the terminal.
To install the provider into the terminal one can provide it
to the constructor or use the :meth:`~EnhTerm.install_provider` method.
... | enhterm/provider/__init__.py | import logging
from enhterm.base import EtBase
logger = logging.getLogger('et.p')
class Provider(EtBase):
"""
A class capable of providing command to the terminal.
To install the provider into the terminal one can provide it
to the constructor or use the :meth:`~EnhTerm.install_provider` method.
... | 0.753467 | 0.557604 |
# Launch Docker CI when committing
# Inspired from https://medium.com/@zypherman/my-experiences-with-travis-ci-7f5ea26a87c0
import requests
import json
import time
import sys
import logging
import pprint
import os
LOG_LEVEL = logging.INFO
logging.getLogger().addHandler(logging.StreamHandler())
logging.getLogger().s... | .github/trigger_docker.py |
# Launch Docker CI when committing
# Inspired from https://medium.com/@zypherman/my-experiences-with-travis-ci-7f5ea26a87c0
import requests
import json
import time
import sys
import logging
import pprint
import os
LOG_LEVEL = logging.INFO
logging.getLogger().addHandler(logging.StreamHandler())
logging.getLogger().s... | 0.304455 | 0.10725 |
"""Test a gettext implementation of a Message Catalog.
"""
import os
import unittest
import zope.component
from zope.i18n import tests, translate
from zope.i18n.translationdomain import TranslationDomain
from zope.i18n.gettextmessagecatalog import GettextMessageCatalog
from zope.i18nmessageid import MessageFactory
fro... | ven2/lib/python2.7/site-packages/zope/i18n/tests/test_plurals.py | """Test a gettext implementation of a Message Catalog.
"""
import os
import unittest
import zope.component
from zope.i18n import tests, translate
from zope.i18n.translationdomain import TranslationDomain
from zope.i18n.gettextmessagecatalog import GettextMessageCatalog
from zope.i18nmessageid import MessageFactory
fro... | 0.694095 | 0.384999 |
import json
from alipay.aop.api.constant.ParamConstants import *
class TicketTransInfo(object):
def __init__(self):
self._create_time = None
self._last_modify_time = None
self._ticket_trans_id = None
self._ticket_trans_type = None
@property
def create_time(self):
... | alipay/aop/api/domain/TicketTransInfo.py | import json
from alipay.aop.api.constant.ParamConstants import *
class TicketTransInfo(object):
def __init__(self):
self._create_time = None
self._last_modify_time = None
self._ticket_trans_id = None
self._ticket_trans_type = None
@property
def create_time(self):
... | 0.435661 | 0.133246 |
from django.conf.urls import *
from django.views.generic import TemplateView
from registration.views import ActivationView
from registration.views import RegistrationView
urlpatterns = patterns('',
# Test the 'activate' view with custom template
# name.
... | lib/python2.7/site-packages/registration/tests/urls.py | from django.conf.urls import *
from django.views.generic import TemplateView
from registration.views import ActivationView
from registration.views import RegistrationView
urlpatterns = patterns('',
# Test the 'activate' view with custom template
# name.
... | 0.59972 | 0.100348 |
import asyncio
import logging
import signal
import sys
import traceback
from typing import Dict, List, Union, Any, Iterable, Optional, Callable
from .models.app.cache import CacheManager
from .rest import RESTApp
from .core.gateway import GatewayBotInfo
from .models.guild.channel import Channel, ChannelType
from .mod... | melisa/client.py |
import asyncio
import logging
import signal
import sys
import traceback
from typing import Dict, List, Union, Any, Iterable, Optional, Callable
from .models.app.cache import CacheManager
from .rest import RESTApp
from .core.gateway import GatewayBotInfo
from .models.guild.channel import Channel, ChannelType
from .mod... | 0.760917 | 0.149004 |
import openpnm as op
import numpy as np
import openpnm.models as mods
import pytest
from testfixtures import LogCapture
class ModelsTest:
def setup_class(self):
self.net = op.network.Cubic(shape=[3, 3, 3])
self.geo = op.geometry.StickAndBall(network=self.net,
... | tests/unit/core/ModelsTest.py | import openpnm as op
import numpy as np
import openpnm.models as mods
import pytest
from testfixtures import LogCapture
class ModelsTest:
def setup_class(self):
self.net = op.network.Cubic(shape=[3, 3, 3])
self.geo = op.geometry.StickAndBall(network=self.net,
... | 0.589126 | 0.610453 |
from Source.ArchiveSource import ArchiveSource
from Source.GitSource import GitSource
from Source.SourceBase import *
from Source.SvnSource import SvnSource
class MultiSource(SourceBase):
""" provides multi source type api """
def __init__(self):
SourceBase.__init__(self)
CraftCore.debug.tr... | bin/Source/MultiSource.py |
from Source.ArchiveSource import ArchiveSource
from Source.GitSource import GitSource
from Source.SourceBase import *
from Source.SvnSource import SvnSource
class MultiSource(SourceBase):
""" provides multi source type api """
def __init__(self):
SourceBase.__init__(self)
CraftCore.debug.tr... | 0.383526 | 0.058319 |
import jwt
import uuid
import datetime
from starlette.requests import Request
from starlette.authentication import (
AuthenticationBackend, AuthCredentials, BaseUser
)
from models import token
from models.token import TokenBase
from utils.MyErrors import GenericError
from utils.token_db import token_db
def authen... | friteup/middlewares/authentication.py | import jwt
import uuid
import datetime
from starlette.requests import Request
from starlette.authentication import (
AuthenticationBackend, AuthCredentials, BaseUser
)
from models import token
from models.token import TokenBase
from utils.MyErrors import GenericError
from utils.token_db import token_db
def authen... | 0.34632 | 0.074399 |
import numpy as np
import pandas as pd
from scipy.sparse import issparse
from sklearn.utils import check_consistent_length
from typing import Dict, List
_DF_COLUMN_BAD_NAME = "DataFrame column names must be strings."\
" Name '{0}' is of type {1}"
_LIST_NONSCALAR = "Lists must be of scalar types"
_TOO_MANY_DIMS =... | responsibleai/responsibleai/_input_processing.py |
import numpy as np
import pandas as pd
from scipy.sparse import issparse
from sklearn.utils import check_consistent_length
from typing import Dict, List
_DF_COLUMN_BAD_NAME = "DataFrame column names must be strings."\
" Name '{0}' is of type {1}"
_LIST_NONSCALAR = "Lists must be of scalar types"
_TOO_MANY_DIMS =... | 0.8628 | 0.569823 |
from __future__ import absolute_import
from __future__ import division
from __future__ import print_function
from collections import OrderedDict
from paddle import fluid
from paddle.fluid.param_attr import ParamAttr
from paddle.fluid.framework import Variable
from paddle.fluid.regularizer import L2Decay
from number... | paddlex/cv/nets/hrnet.py |
from __future__ import absolute_import
from __future__ import division
from __future__ import print_function
from collections import OrderedDict
from paddle import fluid
from paddle.fluid.param_attr import ParamAttr
from paddle.fluid.framework import Variable
from paddle.fluid.regularizer import L2Decay
from number... | 0.829423 | 0.406037 |
import argparse
import numpy as np
import matplotlib.pyplot as plt
from scipy.io import wavfile
from scipy.signal import convolve
argument_parser = argparse.ArgumentParser(description='Plots the RMS amplitude of a signal over time.')
argument_parser.add_argument('--wav-file', help='path to the input WAV file', requi... | plot_amplitude.py |
import argparse
import numpy as np
import matplotlib.pyplot as plt
from scipy.io import wavfile
from scipy.signal import convolve
argument_parser = argparse.ArgumentParser(description='Plots the RMS amplitude of a signal over time.')
argument_parser.add_argument('--wav-file', help='path to the input WAV file', requi... | 0.673084 | 0.378459 |
import pygame
class Game:
screen = None
aliens = []
rockets = []
lost = False
def __init__(self, width, height):
pygame.init()
self.width = width
self.height = height
self.screen = pygame.display.set_mode((width, height))
self.clock = pygame.time.Clock()
... | main1.py | import pygame
class Game:
screen = None
aliens = []
rockets = []
lost = False
def __init__(self, width, height):
pygame.init()
self.width = width
self.height = height
self.screen = pygame.display.set_mode((width, height))
self.clock = pygame.time.Clock()
... | 0.297878 | 0.245775 |
from xossynchronizer.pull_steps.pullstep import PullStep
from xossynchronizer.modelaccessor import model_accessor, ONUDevice, VOLTService, OLTDevice, PONPort, ANIPort, UNIPort
from xosconfig import Config
from multistructlog import create_logger
import requests
from requests import ConnectionError
from requests.mode... | xos/synchronizer/pull_steps/pull_onus.py |
from xossynchronizer.pull_steps.pullstep import PullStep
from xossynchronizer.modelaccessor import model_accessor, ONUDevice, VOLTService, OLTDevice, PONPort, ANIPort, UNIPort
from xosconfig import Config
from multistructlog import create_logger
import requests
from requests import ConnectionError
from requests.mode... | 0.273186 | 0.074736 |
import cv2 as cv
import numpy as np
class MorphologicalMixin:
def sharpen(self) -> None:
"""Sharpens the image with 3x3 filter. Only works on 2D images."""
if self.dim != 2:
raise ValueError("Only on 2D images")
filter = np.array([[-1, -1, -1], [-1, 9, -1], [-1, -1, -1]])
... | jduimage/_morphologicalMixin.py | import cv2 as cv
import numpy as np
class MorphologicalMixin:
def sharpen(self) -> None:
"""Sharpens the image with 3x3 filter. Only works on 2D images."""
if self.dim != 2:
raise ValueError("Only on 2D images")
filter = np.array([[-1, -1, -1], [-1, 9, -1], [-1, -1, -1]])
... | 0.895523 | 0.488466 |
from django.contrib.auth import get_user_model
from home.models import Student, Teacher
from django.http import HttpRequest
from django.utils.translation import ugettext_lazy as _
from allauth.account import app_settings as allauth_settings
from allauth.account.forms import ResetPasswordForm
from allauth.utils import e... | backend/home/api/v1/serializers.py | from django.contrib.auth import get_user_model
from home.models import Student, Teacher
from django.http import HttpRequest
from django.utils.translation import ugettext_lazy as _
from allauth.account import app_settings as allauth_settings
from allauth.account.forms import ResetPasswordForm
from allauth.utils import e... | 0.488527 | 0.088308 |
from PyQt5.QtWidgets import *
from MyWizardPage import MyWizardPage
from fontTools.designspaceLib import SourceDescriptor
from PyQt5.QtCore import Qt, pyqtSlot, QPoint, pyqtSignal
from PyQt5 import QtGui
import re, os
from QDesignSpace import DesignSpaceVisualizer
import defcon
class DragDropArea(QPushButton):
go... | DefineSources.py | from PyQt5.QtWidgets import *
from MyWizardPage import MyWizardPage
from fontTools.designspaceLib import SourceDescriptor
from PyQt5.QtCore import Qt, pyqtSlot, QPoint, pyqtSignal
from PyQt5 import QtGui
import re, os
from QDesignSpace import DesignSpaceVisualizer
import defcon
class DragDropArea(QPushButton):
go... | 0.440951 | 0.094218 |
from ..settings import ModelSettings
from ..registry import MultiModelRegistry
from ..repository import ModelRepository
from ..errors import ModelNotFound
from ..types import (
RepositoryIndexRequest,
RepositoryIndexResponse,
RepositoryIndexResponseItem,
State,
)
NO_VERSION_KEY = "__no_version__"
cla... | mlserver/handlers/model_repository.py | from ..settings import ModelSettings
from ..registry import MultiModelRegistry
from ..repository import ModelRepository
from ..errors import ModelNotFound
from ..types import (
RepositoryIndexRequest,
RepositoryIndexResponse,
RepositoryIndexResponseItem,
State,
)
NO_VERSION_KEY = "__no_version__"
cla... | 0.342572 | 0.07603 |
import requests, json
# Version: 1.2.5
class GeodesignHubClient():
'''
This a a Python client that make calls to the Geodesignhub API
and return data. It requires the requests package and the json module.
'''
def __init__(self, url, token, project_id):
'''
Declare your project id, token and the url (optio... | GeodesignHub.py | import requests, json
# Version: 1.2.5
class GeodesignHubClient():
'''
This a a Python client that make calls to the Geodesignhub API
and return data. It requires the requests package and the json module.
'''
def __init__(self, url, token, project_id):
'''
Declare your project id, token and the url (optio... | 0.38827 | 0.156362 |
import simplejson as json
from mongrel2 import handler
import hashlib
import base64
sender_id = "82209006-86FF-4982-B5EA-D1E29E55D481"
conn = handler.Connection(sender_id, "tcp://127.0.0.1:9999",
"tcp://127.0.0.1:9998")
users = {}
user_list = []
def wsChallenge(v):
try:
x=hashl... | examples/wschat/chat.py | import simplejson as json
from mongrel2 import handler
import hashlib
import base64
sender_id = "82209006-86FF-4982-B5EA-D1E29E55D481"
conn = handler.Connection(sender_id, "tcp://127.0.0.1:9999",
"tcp://127.0.0.1:9998")
users = {}
user_list = []
def wsChallenge(v):
try:
x=hashl... | 0.089741 | 0.164081 |
import json
from django.contrib.auth.decorators import login_required
from django.shortcuts import HttpResponse
from django.template import defaultfilters as filters
from django.utils.timezone import localtime
from django.views.decorators.cache import cache_page
from pano.puppetdb import puppetdb
from pano.puppetdb.p... | pano/views/api/report_data.py | import json
from django.contrib.auth.decorators import login_required
from django.shortcuts import HttpResponse
from django.template import defaultfilters as filters
from django.utils.timezone import localtime
from django.views.decorators.cache import cache_page
from pano.puppetdb import puppetdb
from pano.puppetdb.p... | 0.312265 | 0.055311 |
from numpy import asarray, array
from biosteam._utils import wegstein_secant, aitken_secant, wegstein, aitken
__all__ = ('DewPoint',)
class DewPoint:
__slots__ = ('gamma', 'P', 'T', 'x')
rootsolver = staticmethod(aitken_secant)
itersolver = staticmethod(aitken)
def __init__(self, gamma):
self.... | build/lib/biosteam/_equilibrium/dew_point.py | from numpy import asarray, array
from biosteam._utils import wegstein_secant, aitken_secant, wegstein, aitken
__all__ = ('DewPoint',)
class DewPoint:
__slots__ = ('gamma', 'P', 'T', 'x')
rootsolver = staticmethod(aitken_secant)
itersolver = staticmethod(aitken)
def __init__(self, gamma):
self.... | 0.852798 | 0.726037 |
import subprocess, netifaces, logging
from anomalies.anomaly import Anomaly
class TrafficControlAnomaly(Anomaly):
_ifaces = []
_injected = False # Set if no interfaces are injected, but inject() has been called... Pretend the injection happened.
def __init__(self, name, inject_command, status_keyword):
... | anomaly-injector-agent/anomalies/anomaly_network.py | import subprocess, netifaces, logging
from anomalies.anomaly import Anomaly
class TrafficControlAnomaly(Anomaly):
_ifaces = []
_injected = False # Set if no interfaces are injected, but inject() has been called... Pretend the injection happened.
def __init__(self, name, inject_command, status_keyword):
... | 0.551574 | 0.275416 |
import maze.__maze as __maze
__maze.createMaze()
def __canMoveLeft(curPos: []):
room = __maze.mazeLayout[curPos[0]][curPos[1]]
if int(room[0]):
return True
else:
return False
def __canMoveTop(curPos: []):
room = __maze.mazeLayout[curPos[0]][curPos[1]]
if int(room[1]):
retu... | maze/__mazeActions.py | import maze.__maze as __maze
__maze.createMaze()
def __canMoveLeft(curPos: []):
room = __maze.mazeLayout[curPos[0]][curPos[1]]
if int(room[0]):
return True
else:
return False
def __canMoveTop(curPos: []):
room = __maze.mazeLayout[curPos[0]][curPos[1]]
if int(room[1]):
retu... | 0.403449 | 0.490846 |
from __future__ import print_function
import argparse
import torch
import torch.nn as nn
import torch.nn.functional as F
from torchvision import datasets, transforms
from zoo.pipeline.api.torch import TorchModel, TorchLoss, TorchOptim
from zoo.pipeline.estimator import *
from bigdl.optim.optimizer import SGD, Adam
from... | pyzoo/zoo/examples/pytorch/train/mnist/main.py | from __future__ import print_function
import argparse
import torch
import torch.nn as nn
import torch.nn.functional as F
from torchvision import datasets, transforms
from zoo.pipeline.api.torch import TorchModel, TorchLoss, TorchOptim
from zoo.pipeline.estimator import *
from bigdl.optim.optimizer import SGD, Adam
from... | 0.900158 | 0.357455 |
from abc import ABC, abstractmethod
from typing import Optional, Iterable, Callable, Union
try: # Assume we're a sub-module in a package.
from utils import arguments as arg
from utils.external import DataFrame
from utils.algo import JoinType
from streams.interfaces.abstract_stream_interface import Str... | streams/interfaces/columnar_interface.py | from abc import ABC, abstractmethod
from typing import Optional, Iterable, Callable, Union
try: # Assume we're a sub-module in a package.
from utils import arguments as arg
from utils.external import DataFrame
from utils.algo import JoinType
from streams.interfaces.abstract_stream_interface import Str... | 0.928765 | 0.375077 |
from bilibili import bilibili
from statistics import Statistics
import printer
from printer import Printer
import rafflehandler
from configloader import ConfigLoader
import utils
import asyncio
import struct
import json
import sys
import aiohttp
class BaseDanm... | bilibiliCilent.py | from bilibili import bilibili
from statistics import Statistics
import printer
from printer import Printer
import rafflehandler
from configloader import ConfigLoader
import utils
import asyncio
import struct
import json
import sys
import aiohttp
class BaseDanm... | 0.090844 | 0.089694 |
# ----------------------------------------------------------------------
# Imports
# ----------------------------------------------------------------------
# SUAVE imports
import SUAVE
from SUAVE.Analyses.Mission.Segments import Aerodynamic
from SUAVE.Analyses.Mission.Segments import Conditions
from SUAVE.Methods.M... | SUAVE/SUAVE-2.5.0/trunk/SUAVE/Analyses/Mission/Segments/Hover/Climb.py |
# ----------------------------------------------------------------------
# Imports
# ----------------------------------------------------------------------
# SUAVE imports
import SUAVE
from SUAVE.Analyses.Mission.Segments import Aerodynamic
from SUAVE.Analyses.Mission.Segments import Conditions
from SUAVE.Methods.M... | 0.725162 | 0.201853 |
import sys,os
import numpy as np
import matplotlib.pyplot as plt
import tensorflow as tf
sys.path.append("../../")
from Utils.callback_tf import callbacklist
from tensorflow import keras
os.environ['CUDA_VISIBLE_DEVICES'] = '0'
(train_data, train_targets), (test_data, test_targets) = keras.datasets.boston_housing.load... | PictureColoring/study/3.6/boston_housing.py | import sys,os
import numpy as np
import matplotlib.pyplot as plt
import tensorflow as tf
sys.path.append("../../")
from Utils.callback_tf import callbacklist
from tensorflow import keras
os.environ['CUDA_VISIBLE_DEVICES'] = '0'
(train_data, train_targets), (test_data, test_targets) = keras.datasets.boston_housing.load... | 0.552298 | 0.48121 |
from twisted.python import log
class BaseObject(object):
"""
A base object.
"""
raw = None
SIMPLE_PROPS = None
COMPLEX_PROPS = None
LIST_PROPS = None
@classmethod
def fromDict(cls, data):
"""
Fill this objects attributes from a dict for known properties.
""... | txhue/object.py |
from twisted.python import log
class BaseObject(object):
"""
A base object.
"""
raw = None
SIMPLE_PROPS = None
COMPLEX_PROPS = None
LIST_PROPS = None
@classmethod
def fromDict(cls, data):
"""
Fill this objects attributes from a dict for known properties.
""... | 0.492188 | 0.155046 |
import numpy as np
import tensorflow.compat.v1 as tf
from tensor2tensor import models
from tensor2tensor import problems
from tensor2tensor.data_generators import text_encoder
from tensor2tensor.utils import decoding
from tensor2tensor.utils import trainer_lib
from magenta.models.score2perf import score2perf
import n... | src/transformer.py | import numpy as np
import tensorflow.compat.v1 as tf
from tensor2tensor import models
from tensor2tensor import problems
from tensor2tensor.data_generators import text_encoder
from tensor2tensor.utils import decoding
from tensor2tensor.utils import trainer_lib
from magenta.models.score2perf import score2perf
import n... | 0.821152 | 0.229622 |
import os
from typing import Tuple, List
from overrides import overrides
import sentencepiece as spm
from transformers import PreTrainedTokenizerFast, XLNetTokenizerFast
from transformers.tokenization_utils_fast import PreTrainedTokenizerFast
from enums.configuration import Configuration
from services.arguments.pr... | src/services/tokenize/transformer_tokenize_service.py | import os
from typing import Tuple, List
from overrides import overrides
import sentencepiece as spm
from transformers import PreTrainedTokenizerFast, XLNetTokenizerFast
from transformers.tokenization_utils_fast import PreTrainedTokenizerFast
from enums.configuration import Configuration
from services.arguments.pr... | 0.845337 | 0.270158 |
import logging
import apache_beam as beam
from google.oauth2.credentials import Credentials
from googleapiclient.discovery import build
from googleapiclient.http import MediaInMemoryUpload
from uploaders import utils
from models.execution import Batch, DestinationType
class GoogleAnalyticsUserListUploaderDoFn(bea... | megalista_dataflow/uploaders/google_analytics/google_analytics_user_list_uploader.py |
import logging
import apache_beam as beam
from google.oauth2.credentials import Credentials
from googleapiclient.discovery import build
from googleapiclient.http import MediaInMemoryUpload
from uploaders import utils
from models.execution import Batch, DestinationType
class GoogleAnalyticsUserListUploaderDoFn(bea... | 0.35768 | 0.140189 |
import os,sys
import numpy as np
from matplotlib import pyplot as plt
import cv2
def vis_colored_pointcloud(image, points, path):
xyzrgb = np.concatenate([points, np.reshape(image, (-1,3))], axis=-1)
pcwrite(path, xyzrgb)
return None
def pcwrite(filename, xyzrgb):
"""Save a point cloud to a polygon .p... | post_processing/utils_post.py | import os,sys
import numpy as np
from matplotlib import pyplot as plt
import cv2
def vis_colored_pointcloud(image, points, path):
xyzrgb = np.concatenate([points, np.reshape(image, (-1,3))], axis=-1)
pcwrite(path, xyzrgb)
return None
def pcwrite(filename, xyzrgb):
"""Save a point cloud to a polygon .p... | 0.479504 | 0.390679 |
import traceback
import json
from rq.timeouts import JobTimeoutException
import smtplib
import quopri
from email.parser import Parser
import frappe
from frappe import _, safe_encode, task
from frappe.model.document import Document
from frappe.email.queue import get_unsubcribed_url
from frappe.email.email_body import... | frappe/email/doctype/email_queue/email_queue.py |
import traceback
import json
from rq.timeouts import JobTimeoutException
import smtplib
import quopri
from email.parser import Parser
import frappe
from frappe import _, safe_encode, task
from frappe.model.document import Document
from frappe.email.queue import get_unsubcribed_url
from frappe.email.email_body import... | 0.398055 | 0.100128 |
import unittest
import numpy
import six
import cupy
from cupy import testing
@testing.gpu
class TestCount(unittest.TestCase):
@testing.for_all_dtypes()
def test_count_nonzero(self, dtype):
def func(xp):
m = testing.shaped_random((2, 3), xp, xp.bool_)
a = testing.shaped_rando... | tests/cupy_tests/sorting_tests/test_count.py | import unittest
import numpy
import six
import cupy
from cupy import testing
@testing.gpu
class TestCount(unittest.TestCase):
@testing.for_all_dtypes()
def test_count_nonzero(self, dtype):
def func(xp):
m = testing.shaped_random((2, 3), xp, xp.bool_)
a = testing.shaped_rando... | 0.729327 | 0.589037 |
"""This object helps create the result output"""
import logging
import json
from pylons import url
from agent.lib import contextutils
LOG = logging.getLogger(__name__)
NORMAL = '0'
WARNING = '1'
CRITICAL = '2'
DEBUG = '99'
def doneResult(request, response, httpStatus=200, result = None, controller = None):
""" ... | agent/agent/lib/result.py | """This object helps create the result output"""
import logging
import json
from pylons import url
from agent.lib import contextutils
LOG = logging.getLogger(__name__)
NORMAL = '0'
WARNING = '1'
CRITICAL = '2'
DEBUG = '99'
def doneResult(request, response, httpStatus=200, result = None, controller = None):
""" ... | 0.516595 | 0.159741 |
# TODO: In docstring, add description of routing through resource(s) to an operation.
import asyncio
import base64
import fondat.error
import fondat.resource
import fondat.types
import functools
import http
import http.cookies
import inspect
import logging
import multidict
import typing
from collections import name... | fondat/http.py |
# TODO: In docstring, add description of routing through resource(s) to an operation.
import asyncio
import base64
import fondat.error
import fondat.resource
import fondat.types
import functools
import http
import http.cookies
import inspect
import logging
import multidict
import typing
from collections import name... | 0.681197 | 0.200342 |
{
'includes': [ '../build/common.gypi', ],
'conditions': [
['os_posix == 1 and OS != "mac" and OS != "ios"', {
'conditions': [
['sysroot!=""', {
'variables': {
'pkg-config': '../../../build/linux/pkg-config-wrapper "<(sysroot)" "<(target_arch)"',
},
}, {
... | src/lib_ext/webrtc/webrtc/api/api.gyp |
{
'includes': [ '../build/common.gypi', ],
'conditions': [
['os_posix == 1 and OS != "mac" and OS != "ios"', {
'conditions': [
['sysroot!=""', {
'variables': {
'pkg-config': '../../../build/linux/pkg-config-wrapper "<(sysroot)" "<(target_arch)"',
},
}, {
... | 0.36727 | 0.122366 |
from mpmath import *
from numpy import *
from matplotlib.pyplot import *
import matplotlib.patches as patches
from flint import acb
from matplotlib.colors import ListedColormap, LinearSegmentedColormap
rc('text', usetex=True)
realcolor = []
imagcolor = []
highlightcolor = []
highlightbordercolor = []
branchcutcolor =... | source_scripts/xray.py | from mpmath import *
from numpy import *
from matplotlib.pyplot import *
import matplotlib.patches as patches
from flint import acb
from matplotlib.colors import ListedColormap, LinearSegmentedColormap
rc('text', usetex=True)
realcolor = []
imagcolor = []
highlightcolor = []
highlightbordercolor = []
branchcutcolor =... | 0.326593 | 0.449816 |
from __future__ import division
import numpy
import scipy.sparse
from ..utils import safe_solve, safe_diagonal, safe_dot
def linear(hessian, gradient, precondition=True):
r"""
Find the parameter vector that minimizes a linear objective function.
The parameter vector :math:`\bar{p}` that minimizes this o... | fatiando/inversion/solvers.py | from __future__ import division
import numpy
import scipy.sparse
from ..utils import safe_solve, safe_diagonal, safe_dot
def linear(hessian, gradient, precondition=True):
r"""
Find the parameter vector that minimizes a linear objective function.
The parameter vector :math:`\bar{p}` that minimizes this o... | 0.936851 | 0.838151 |
from __future__ import absolute_import
import collections
import socket
import string
from anyjson import loads, dumps
import boto
from boto import exception
from boto import sdb as _sdb
from boto import sqs as _sqs
from boto.sdb.domain import Domain
from boto.sdb.connection import SDBConnection
from boto.sqs.connec... | kombu/transport/SQS.py | from __future__ import absolute_import
import collections
import socket
import string
from anyjson import loads, dumps
import boto
from boto import exception
from boto import sdb as _sdb
from boto import sqs as _sqs
from boto.sdb.domain import Domain
from boto.sdb.connection import SDBConnection
from boto.sqs.connec... | 0.715325 | 0.085061 |
__author__ = '<NAME> (<EMAIL>)'
import urllib
from common import crypto
from controllers import sites
from models import config
from models import models
from models import roles
from models import transforms
from models.custom_modules import Module
from models.models import MemcacheManager
from tests.functional impo... | tests/functional/roles.py | __author__ = '<NAME> (<EMAIL>)'
import urllib
from common import crypto
from controllers import sites
from models import config
from models import models
from models import roles
from models import transforms
from models.custom_modules import Module
from models.models import MemcacheManager
from tests.functional impo... | 0.499268 | 0.185357 |
import data
import model
import os
import pandas
import torch
TRAINING_DATA_DIR_RELATIVE_PATH = "../trained_models/agents" # directory location relative to this .py file
TRAINING_DATA_DIR = os.path.join(os.path.dirname(os.path.realpath(__file__)), TRAINING_DATA_DIR_RELATIVE_PATH)
def get_group_directory_path(group_id... | code/training_data.py | import data
import model
import os
import pandas
import torch
TRAINING_DATA_DIR_RELATIVE_PATH = "../trained_models/agents" # directory location relative to this .py file
TRAINING_DATA_DIR = os.path.join(os.path.dirname(os.path.realpath(__file__)), TRAINING_DATA_DIR_RELATIVE_PATH)
def get_group_directory_path(group_id... | 0.320928 | 0.130396 |
from datetime import datetime
import re
from django.core.urlresolvers import reverse
from django.utils.http import urlencode
from django.utils.translation import ugettext as _
from django.db import models
from django.contrib.comments.views.comments import post_comment
from django.http import HttpResponse
from django.t... | knesset/utils.py | from datetime import datetime
import re
from django.core.urlresolvers import reverse
from django.utils.http import urlencode
from django.utils.translation import ugettext as _
from django.db import models
from django.contrib.comments.views.comments import post_comment
from django.http import HttpResponse
from django.t... | 0.417271 | 0.070592 |
from sqlalchemy import (
Boolean,
Column,
DateTime,
Float,
ForeignKey,
ForeignKeyConstraint,
Integer,
Numeric,
String,
Text)
from sqlalchemy.ext.declarative import declarative_base
from sqlalchemy.orm import relationship
# Mapped classes ---------------------------------------... | coimbra_chamber/access/experiment/models.py |
from sqlalchemy import (
Boolean,
Column,
DateTime,
Float,
ForeignKey,
ForeignKeyConstraint,
Integer,
Numeric,
String,
Text)
from sqlalchemy.ext.declarative import declarative_base
from sqlalchemy.orm import relationship
# Mapped classes ---------------------------------------... | 0.812198 | 0.255355 |
def test_day1():
from challenge1 import get_total_fuel, MASSES, get_total_additional_fuel
assert get_total_fuel(MASSES) == 3397667
assert get_total_additional_fuel(MASSES) == 5093620
def test_day2():
from challenge2 import get_value_at_address_zero_after_calculation, get_correct_noun_verb
assert ge... | test/test_challenges.py | def test_day1():
from challenge1 import get_total_fuel, MASSES, get_total_additional_fuel
assert get_total_fuel(MASSES) == 3397667
assert get_total_additional_fuel(MASSES) == 5093620
def test_day2():
from challenge2 import get_value_at_address_zero_after_calculation, get_correct_noun_verb
assert ge... | 0.679179 | 0.578151 |
import logging
from typing import Dict, Callable, Optional
from ._communicator import Communicator
from ._const import PICMD_NO_ERROR, \
PICMD_COMMAND_FAIL_ERROR
from ._data import CommandRequest, CommandResponse
from ._exception import CommandNotFoundException, \
InvalidResultFormatException
from ._han... | picmd/_picmd.py | import logging
from typing import Dict, Callable, Optional
from ._communicator import Communicator
from ._const import PICMD_NO_ERROR, \
PICMD_COMMAND_FAIL_ERROR
from ._data import CommandRequest, CommandResponse
from ._exception import CommandNotFoundException, \
InvalidResultFormatException
from ._han... | 0.708918 | 0.070017 |
# Standard Libraries
import logging
import os
# Django Imports
from django.db.models.signals import post_init, post_save
from django.dispatch import receiver
# Ghostwriter Libraries
from ghostwriter.modules.reportwriter import TemplateLinter
from ghostwriter.reporting.models import Evidence, ReportTemplate
# Using ... | ghostwriter/reporting/signals.py |
# Standard Libraries
import logging
import os
# Django Imports
from django.db.models.signals import post_init, post_save
from django.dispatch import receiver
# Ghostwriter Libraries
from ghostwriter.modules.reportwriter import TemplateLinter
from ghostwriter.reporting.models import Evidence, ReportTemplate
# Using ... | 0.540924 | 0.056288 |
import os
import random
import time
import pickle
import argparse
import copy
import numpy as np
import torch
import torch.nn as nn
import torch.nn.functional as F
import torch.nn.init as init
import torch.optim as optim
from torch.utils.data import DataLoader
from tqdm import tqdm
from graph4nlp.pytorch.data.data im... | examples/pytorch/math_word_problem/mathqa/src/runner.py | import os
import random
import time
import pickle
import argparse
import copy
import numpy as np
import torch
import torch.nn as nn
import torch.nn.functional as F
import torch.nn.init as init
import torch.optim as optim
from torch.utils.data import DataLoader
from tqdm import tqdm
from graph4nlp.pytorch.data.data im... | 0.568176 | 0.139866 |
from syne_tune import read_version
from setuptools import setup, find_packages
from pathlib import Path
def load_requirements(filename):
with open(filename) as f:
return f.read().splitlines()
def load_benchmark_requirements():
# the requirements of benchmarks are placed into the same directory as th... | setup.py | from syne_tune import read_version
from setuptools import setup, find_packages
from pathlib import Path
def load_requirements(filename):
with open(filename) as f:
return f.read().splitlines()
def load_benchmark_requirements():
# the requirements of benchmarks are placed into the same directory as th... | 0.587588 | 0.151843 |
# Copyright (c) 2019 by University of Kassel, T<NAME>, RWTH Aachen University and Fraunhofer
# Institute for Energy Economics and Energy System Technology (IEE) Kassel and individual
# contributors (see AUTHORS file for details). All rights reserved.
import numpy as np
import pandas as pd
import datetime as dt
from p... | simbench/converter/auxiliary.py |
# Copyright (c) 2019 by University of Kassel, T<NAME>, RWTH Aachen University and Fraunhofer
# Institute for Energy Economics and Energy System Technology (IEE) Kassel and individual
# contributors (see AUTHORS file for details). All rights reserved.
import numpy as np
import pandas as pd
import datetime as dt
from p... | 0.675872 | 0.314912 |
from collections import defaultdict
import gym
from pathlib import Path
import itertools
import numpy as np
import matplotlib.pyplot as plt
import matplotlib.colors as colors
import seaborn as sns
import logging
from rl_agents.agents.tree_search.graphics import TreePlot
from rl_agents.agents.common.factory import agen... | rl_agents_scripts/planners_visualization.py | from collections import defaultdict
import gym
from pathlib import Path
import itertools
import numpy as np
import matplotlib.pyplot as plt
import matplotlib.colors as colors
import seaborn as sns
import logging
from rl_agents.agents.tree_search.graphics import TreePlot
from rl_agents.agents.common.factory import agen... | 0.6973 | 0.261366 |
import os
import json
from pathlib import Path
from settings import ROOT_DIR
lower_length = 2
upper_length = 30
def read_dict(dict_path):
lines = []
with open(dict_path, 'r', encoding='utf-8') as f:
for line in f:
lines.append(json.loads(line))
return lines
def save_mecab(output_path, lines, full=T... | tools/save_mecab_format.py | import os
import json
from pathlib import Path
from settings import ROOT_DIR
lower_length = 2
upper_length = 30
def read_dict(dict_path):
lines = []
with open(dict_path, 'r', encoding='utf-8') as f:
for line in f:
lines.append(json.loads(line))
return lines
def save_mecab(output_path, lines, full=T... | 0.183594 | 0.180757 |
from django.db import migrations, models
import django.db.models.deletion
class Migration(migrations.Migration):
initial = True
dependencies = [
]
operations = [
migrations.CreateModel(
name='Career',
fields=[
('id', models.AutoField(auto_created=Tru... | scheduler/migrations/0001_initial.py |
from django.db import migrations, models
import django.db.models.deletion
class Migration(migrations.Migration):
initial = True
dependencies = [
]
operations = [
migrations.CreateModel(
name='Career',
fields=[
('id', models.AutoField(auto_created=Tru... | 0.610918 | 0.172346 |
import os
# Build paths inside the project like this: os.path.join(BASE_DIR, ...)
BASE_DIR = os.path.dirname(os.path.dirname(os.path.abspath(__file__)))
# Quick-start development settings - unsuitable for production
# SECURITY WARNING: keep the secret key used in production secret!
SECRET_KEY = '<KEY>'
# SECURITY... | server/TeleMedic/settings/base.py | import os
# Build paths inside the project like this: os.path.join(BASE_DIR, ...)
BASE_DIR = os.path.dirname(os.path.dirname(os.path.abspath(__file__)))
# Quick-start development settings - unsuitable for production
# SECURITY WARNING: keep the secret key used in production secret!
SECRET_KEY = '<KEY>'
# SECURITY... | 0.191101 | 0.077973 |
import hashlib
import mimetypes
import re
import evernote.edam.type.ttypes as Types
from evernote.api.client import EvernoteClient
from evernote.edam.error.ttypes import EDAMUserException
from storage import Storage
class EvernoteController(object):
def __init__(self, token, isSpecialToken=False, sandbox=False,... | localevernote/evernoteapi/controller.py | import hashlib
import mimetypes
import re
import evernote.edam.type.ttypes as Types
from evernote.api.client import EvernoteClient
from evernote.edam.error.ttypes import EDAMUserException
from storage import Storage
class EvernoteController(object):
def __init__(self, token, isSpecialToken=False, sandbox=False,... | 0.363082 | 0.132234 |
# Import Modules
import os
import json
import argparse
import pprint
# Declare own config file etc.
app_config = "config.json"
error_general = "An Error Occured"
# Main Program Process
def run():
try:
# Set Variable
run = content['run']
# Print Welcome Message
print(run['welcome_... | dist/app.py |
# Import Modules
import os
import json
import argparse
import pprint
# Declare own config file etc.
app_config = "config.json"
error_general = "An Error Occured"
# Main Program Process
def run():
try:
# Set Variable
run = content['run']
# Print Welcome Message
print(run['welcome_... | 0.273671 | 0.089853 |
import proto # type: ignore
from google.cloud.aiplatform_v1.types import encryption_spec as gca_encryption_spec
from google.cloud.aiplatform_v1.types import job_state
from google.protobuf import struct_pb2 # type: ignore
from google.protobuf import timestamp_pb2 # type: ignore
from google.rpc import status_pb2 # t... | google/cloud/aiplatform_v1/types/data_labeling_job.py | import proto # type: ignore
from google.cloud.aiplatform_v1.types import encryption_spec as gca_encryption_spec
from google.cloud.aiplatform_v1.types import job_state
from google.protobuf import struct_pb2 # type: ignore
from google.protobuf import timestamp_pb2 # type: ignore
from google.rpc import status_pb2 # t... | 0.703244 | 0.341871 |
from .base import BaseRequestHandler, permission
import datetime
import pymysql
import logging
logger = logging.getLogger()
def argements_valid(handler, pk=None):
error = dict()
name = handler.get_argument('name', '')
path = handler.get_argument('path', '')
comment = handler.get_argument('comment', ... | handlers/logfile.py |
from .base import BaseRequestHandler, permission
import datetime
import pymysql
import logging
logger = logging.getLogger()
def argements_valid(handler, pk=None):
error = dict()
name = handler.get_argument('name', '')
path = handler.get_argument('path', '')
comment = handler.get_argument('comment', ... | 0.285472 | 0.071689 |
import warnings
import pulumi
import pulumi.runtime
from typing import Any, Mapping, Optional, Sequence, Union, overload
from .. import _utilities
from . import outputs
from ._inputs import *
__all__ = ['TrafficManagerExternalEndpointArgs', 'TrafficManagerExternalEndpoint']
@pulumi.input_type
class TrafficManagerExt... | sdk/python/pulumi_azure/network/traffic_manager_external_endpoint.py |
import warnings
import pulumi
import pulumi.runtime
from typing import Any, Mapping, Optional, Sequence, Union, overload
from .. import _utilities
from . import outputs
from ._inputs import *
__all__ = ['TrafficManagerExternalEndpointArgs', 'TrafficManagerExternalEndpoint']
@pulumi.input_type
class TrafficManagerExt... | 0.894208 | 0.137504 |