code stringlengths 2k 1.04M | repo_path stringlengths 5 517 | parsed_code stringlengths 0 1.04M | quality_prob float64 0.02 0.95 | learning_prob float64 0.02 0.93 |
|---|---|---|---|---|
import time
from w1thermsensor import W1ThermSensor
from datetime import datetime
from datetime import timedelta
#création d'une string au format : jj/mm/aaaa hh:mm:ss
# que l'on renvoie
def recupDate() :
date = datetime.now()
strDate = date.strftime("%d/%m/%Y %H:%M:%S")
print(strDate)
return strDate
... | Communication/Projet/src/projet/getTemperature.py | import time
from w1thermsensor import W1ThermSensor
from datetime import datetime
from datetime import timedelta
#création d'une string au format : jj/mm/aaaa hh:mm:ss
# que l'on renvoie
def recupDate() :
date = datetime.now()
strDate = date.strftime("%d/%m/%Y %H:%M:%S")
print(strDate)
return strDate
... | 0.226099 | 0.247589 |
import sys
from types import ModuleType, new_class
import importlib
from importlib.abc import MetaPathFinder, Loader
import qsharp
from typing import Optional, Any, Dict
import logging
logger = logging.getLogger(__name__)
class QSharpModuleFinder(MetaPathFinder):
def find_module(self, full_name : str, path : Op... | src/Python/qsharp-core/qsharp/loader.py |
import sys
from types import ModuleType, new_class
import importlib
from importlib.abc import MetaPathFinder, Loader
import qsharp
from typing import Optional, Any, Dict
import logging
logger = logging.getLogger(__name__)
class QSharpModuleFinder(MetaPathFinder):
def find_module(self, full_name : str, path : Op... | 0.688678 | 0.274124 |
import sys
import os
import multiprocessing
import subprocess
import itertools
import tempfile
import argparse
import pandas as pd
from Bio import SeqIO
def run_spbuild(seq, tempdir):
"""
Run SPBuild
"""
node_name = multiprocessing.current_process().name
print(f'Processing {seq.id} on {node_name}',... | bin/predict_spbuild.py | import sys
import os
import multiprocessing
import subprocess
import itertools
import tempfile
import argparse
import pandas as pd
from Bio import SeqIO
def run_spbuild(seq, tempdir):
"""
Run SPBuild
"""
node_name = multiprocessing.current_process().name
print(f'Processing {seq.id} on {node_name}',... | 0.2763 | 0.122839 |
from direct.directnotify import DirectNotifyGlobal
from direct.task import Task
from otp.level import DistributedLevelAI, LevelSpec
from otp.level import LevelSpec
from toontown.coghq import CountryClubRoomBase, LevelSuitPlannerAI
from toontown.coghq import DistributedCountryClubBattleAI
from toontown.coghq import Fact... | toontown/coghq/DistributedCountryClubRoomAI.py | from direct.directnotify import DirectNotifyGlobal
from direct.task import Task
from otp.level import DistributedLevelAI, LevelSpec
from otp.level import LevelSpec
from toontown.coghq import CountryClubRoomBase, LevelSuitPlannerAI
from toontown.coghq import DistributedCountryClubBattleAI
from toontown.coghq import Fact... | 0.413596 | 0.087097 |
from test import helpers
from passlib.hash import bcrypt
from flaskeddit import db
from flaskeddit.models import AppUser, Community, Post, PostVote
class TestPost:
def test_get_post(self, test_client):
"""
Test GET request to the /community/_/post/_ route to assert the community's
post p... | test/test_post.py | from test import helpers
from passlib.hash import bcrypt
from flaskeddit import db
from flaskeddit.models import AppUser, Community, Post, PostVote
class TestPost:
def test_get_post(self, test_client):
"""
Test GET request to the /community/_/post/_ route to assert the community's
post p... | 0.658966 | 0.174656 |
import pytest
import os
from bigdl.dllib.utils.common import *
from bigdl.dllib.feature.transform.vision.image import *
import tempfile
class TestLayer():
def setup_method(self, method):
""" setup any state tied to the execution of the given method in a
class. setup_method is invoked for every ... | python/dllib/test/bigdl/transform/test_image.py |
import pytest
import os
from bigdl.dllib.utils.common import *
from bigdl.dllib.feature.transform.vision.image import *
import tempfile
class TestLayer():
def setup_method(self, method):
""" setup any state tied to the execution of the given method in a
class. setup_method is invoked for every ... | 0.61057 | 0.543651 |
import numpy as np
try:
import matplotlib.pyplot as pl
except(ImportError):
pass
from ..plotting.utils import get_best
__all__ = ["get_best", "get_truths", "get_percentiles", "get_stats",
"posterior_samples", "hist_samples", "joint_pdf", "compute_sigma_level",
"trim_walkers", "fill_betw... | prospect/utils/plotting.py |
import numpy as np
try:
import matplotlib.pyplot as pl
except(ImportError):
pass
from ..plotting.utils import get_best
__all__ = ["get_best", "get_truths", "get_percentiles", "get_stats",
"posterior_samples", "hist_samples", "joint_pdf", "compute_sigma_level",
"trim_walkers", "fill_betw... | 0.769557 | 0.606469 |
def render_graph_PathTracerGraph():
g = RenderGraph("PathTracerGraph")
loadRenderPassLibrary("AccumulatePass.dll")
loadRenderPassLibrary("GBuffer.dll")
loadRenderPassLibrary("OptixDenoiser.dll")
loadRenderPassLibrary("ToneMapper.dll")
loadRenderPassLibrary("WavefrontPathTracer.dll")
Accumula... | Source/RenderPasses/MegakernelPathTracer/Data/PathTracerTexLOD_Megakernel.py | def render_graph_PathTracerGraph():
g = RenderGraph("PathTracerGraph")
loadRenderPassLibrary("AccumulatePass.dll")
loadRenderPassLibrary("GBuffer.dll")
loadRenderPassLibrary("OptixDenoiser.dll")
loadRenderPassLibrary("ToneMapper.dll")
loadRenderPassLibrary("WavefrontPathTracer.dll")
Accumula... | 0.403097 | 0.204401 |
from autotabular.pipeline.components.base import AutotabularPreprocessingAlgorithm
from autotabular.pipeline.components.feature_preprocessing.select_percentile import SelectPercentileBase
from autotabular.pipeline.constants import DENSE, INPUT, SPARSE, UNSIGNED_DATA
from ConfigSpace.configuration_space import Configura... | autotabular/pipeline/components/feature_preprocessing/select_percentile_regression.py | from autotabular.pipeline.components.base import AutotabularPreprocessingAlgorithm
from autotabular.pipeline.components.feature_preprocessing.select_percentile import SelectPercentileBase
from autotabular.pipeline.constants import DENSE, INPUT, SPARSE, UNSIGNED_DATA
from ConfigSpace.configuration_space import Configura... | 0.808143 | 0.62892 |
from functools import partial
import logging
from homeassistant.const import ATTR_BATTERY_LEVEL, STATE_OFF, STATE_ON
from homeassistant.core import callback
from homeassistant.helpers.dispatcher import async_dispatcher_connect
from homeassistant.helpers.entity import Entity
from .const import CHILD_CALLBACK, NODE_CAL... | homeassistant/components/mysensors/device.py | from functools import partial
import logging
from homeassistant.const import ATTR_BATTERY_LEVEL, STATE_OFF, STATE_ON
from homeassistant.core import callback
from homeassistant.helpers.dispatcher import async_dispatcher_connect
from homeassistant.helpers.entity import Entity
from .const import CHILD_CALLBACK, NODE_CAL... | 0.747247 | 0.133726 |
"""Tests the `client` module in client–server mode."""
########################################
# Dependencies #
########################################
import mph
from fixtures import logging_disabled
from fixtures import setup_logging
from pytest import raises
from pathlib import P... | tests/test_client.py | """Tests the `client` module in client–server mode."""
########################################
# Dependencies #
########################################
import mph
from fixtures import logging_disabled
from fixtures import setup_logging
from pytest import raises
from pathlib import P... | 0.70791 | 0.266778 |
# pylint: disable=unused-argument, line-too-long
from msrestazure.tools import is_valid_resource_id, parse_resource_id, is_valid_resource_name, resource_id # pylint: disable=import-error
from knack.log import get_logger
from azure.cli.core.profiles import ResourceType
from azure.cli.core.commands.client_factory impo... | src/azure-cli/azure/cli/command_modules/rdbms/flexible_server_virtual_network.py |
# pylint: disable=unused-argument, line-too-long
from msrestazure.tools import is_valid_resource_id, parse_resource_id, is_valid_resource_name, resource_id # pylint: disable=import-error
from knack.log import get_logger
from azure.cli.core.profiles import ResourceType
from azure.cli.core.commands.client_factory impo... | 0.524395 | 0.046551 |
import argparse
import logging
import locale
import relman
from relman.cmd import release
from relman.cmd import release_verify
logging.basicConfig(level=logging.INFO)
LG = logging.getLogger(__name__)
def parse_args():
"""parse command-line arguments."""
parser = argparse.ArgumentParser(
descripti... | relman/main.py | import argparse
import logging
import locale
import relman
from relman.cmd import release
from relman.cmd import release_verify
logging.basicConfig(level=logging.INFO)
LG = logging.getLogger(__name__)
def parse_args():
"""parse command-line arguments."""
parser = argparse.ArgumentParser(
descripti... | 0.398055 | 0.089574 |
from __future__ import unicode_literals
import six
def _update_instance(instance, obj_dict):
if not obj_dict:
return
for p_name in instance.__class__.core_properties:
if p_name in obj_dict:
object.__setattr__(instance, p_name, obj_dict.pop(p_name))
class PropertyDictMeta(type):
... | dockermap/map/__init__.py | from __future__ import unicode_literals
import six
def _update_instance(instance, obj_dict):
if not obj_dict:
return
for p_name in instance.__class__.core_properties:
if p_name in obj_dict:
object.__setattr__(instance, p_name, obj_dict.pop(p_name))
class PropertyDictMeta(type):
... | 0.663342 | 0.09277 |
from pathlib import Path
import click
import tensorflow as tf
import numpy as np
import cv2
from modules.utils import load_yaml, draw_bbox_landm, resize_and_pad_input_image, recover_pad_output
from export import export_to_saved_model
def _run_detection(detector_model, image_arr, score_thres, iou_thres, detection_wi... | inference.py | from pathlib import Path
import click
import tensorflow as tf
import numpy as np
import cv2
from modules.utils import load_yaml, draw_bbox_landm, resize_and_pad_input_image, recover_pad_output
from export import export_to_saved_model
def _run_detection(detector_model, image_arr, score_thres, iou_thres, detection_wi... | 0.702122 | 0.188548 |
from shipmmg.mmg_3dof import (
Mmg3DofBasicParams,
Mmg3DofManeuveringParams,
simulate_mmg_3dof,
get_sub_values_from_simulation_result,
zigzag_test_mmg_3dof,
)
from shipmmg.ship_obj_3dof import ShipObj3dof
import numpy as np
import pytest
import os
import matplotlib.pyplot as plt
@pytest.fixture
d... | tests/test_mmg_3dof.py |
from shipmmg.mmg_3dof import (
Mmg3DofBasicParams,
Mmg3DofManeuveringParams,
simulate_mmg_3dof,
get_sub_values_from_simulation_result,
zigzag_test_mmg_3dof,
)
from shipmmg.ship_obj_3dof import ShipObj3dof
import numpy as np
import pytest
import os
import matplotlib.pyplot as plt
@pytest.fixture
d... | 0.315314 | 0.32748 |
import logging
import hashlib
from xml.sax import SAXParseException
from collections import defaultdict
from rdflib import URIRef, ConjunctiveGraph, util as rdflib_util
from rdflib.namespace import DC, RDF, OWL
from dipper.utils.CurieUtil import CurieUtil
__author__ = 'nlw'
LOG = logging.getLogger(__name__)
class... | dipper/utils/GraphUtils.py | import logging
import hashlib
from xml.sax import SAXParseException
from collections import defaultdict
from rdflib import URIRef, ConjunctiveGraph, util as rdflib_util
from rdflib.namespace import DC, RDF, OWL
from dipper.utils.CurieUtil import CurieUtil
__author__ = 'nlw'
LOG = logging.getLogger(__name__)
class... | 0.666062 | 0.175998 |
import logging
import random
from ipaddress import ip_address
import ptf
from scapy.all import IP, Ether
import ptf.packet as scapy
from ptf.base_tests import BaseTest
from ptf.mask import Mask
from ptf.testutils import *
# packet count for verifying traffic is forwarded via IPinIP tunnel
PACKET_NUM = 10000
# packet c... | ansible/roles/test/files/ptftests/ip_in_ip_tunnel_test.py | import logging
import random
from ipaddress import ip_address
import ptf
from scapy.all import IP, Ether
import ptf.packet as scapy
from ptf.base_tests import BaseTest
from ptf.mask import Mask
from ptf.testutils import *
# packet count for verifying traffic is forwarded via IPinIP tunnel
PACKET_NUM = 10000
# packet c... | 0.610337 | 0.155655 |
import os
TRAIN_SPLIT_FILE = os.path.join('data','classification_data','training_split.csv')
TEST_SPLIT_FILE = os.path.join('data','classification_data','test_split.csv')
VAL_SPLIT_FILE = os.path.join('data','classification_data','dev_split.csv')
D_ND_DIR = os.path.join('data','disc_nondisc')
POS_NEG_DIR = os.path.joi... | src/main/config.py | import os
TRAIN_SPLIT_FILE = os.path.join('data','classification_data','training_split.csv')
TEST_SPLIT_FILE = os.path.join('data','classification_data','test_split.csv')
VAL_SPLIT_FILE = os.path.join('data','classification_data','dev_split.csv')
D_ND_DIR = os.path.join('data','disc_nondisc')
POS_NEG_DIR = os.path.joi... | 0.163112 | 0.103477 |
import numpy as np
from numpy.lib.stride_tricks import as_strided
import scipy.fftpack as fft
import scipy
import scipy.signal
import six
MAX_MEM_BLOCK = 2**8 * 2**10
def stft(y, n_fft=2048, hop_length=None, win_length=None, window=None,
center=True, dtype=np.complex64):
"""Short-time Fourier transform ... | gccNMF/realtime/librosaSTFT.py |
import numpy as np
from numpy.lib.stride_tricks import as_strided
import scipy.fftpack as fft
import scipy
import scipy.signal
import six
MAX_MEM_BLOCK = 2**8 * 2**10
def stft(y, n_fft=2048, hop_length=None, win_length=None, window=None,
center=True, dtype=np.complex64):
"""Short-time Fourier transform ... | 0.851583 | 0.664078 |
from sfm.routes.work_items import crud
from sfm.dependencies import get_db
from sfm.models import WorkItemRead, WorkItemCreate, WorkItemUpdate
from typing import List, Optional
from sqlmodel import Session
from fastapi import APIRouter, HTTPException, Depends, Path, Header
from opencensus.ext.azure.log_exporter import ... | src/backend/sfm/routes/work_items/routes.py | from sfm.routes.work_items import crud
from sfm.dependencies import get_db
from sfm.models import WorkItemRead, WorkItemCreate, WorkItemUpdate
from typing import List, Optional
from sqlmodel import Session
from fastapi import APIRouter, HTTPException, Depends, Path, Header
from opencensus.ext.azure.log_exporter import ... | 0.836154 | 0.165728 |
import torch
import torch.nn as nn
from collections import namedtuple
import functools
Conv = namedtuple('Conv', ['stride', 'depth'])
DepthSepConv = namedtuple('DepthSepConv', ['stride', 'depth'])
InvertedResidual = namedtuple('InvertedResidual', ['stride', 'depth', 'num', 't']) # t is the expension factor
V1_CONV_D... | lib/modeling/nets/mobilenet.py | import torch
import torch.nn as nn
from collections import namedtuple
import functools
Conv = namedtuple('Conv', ['stride', 'depth'])
DepthSepConv = namedtuple('DepthSepConv', ['stride', 'depth'])
InvertedResidual = namedtuple('InvertedResidual', ['stride', 'depth', 'num', 't']) # t is the expension factor
V1_CONV_D... | 0.919681 | 0.600247 |
from __future__ import absolute_import
import json
import sys
from functools import partial
from io import BytesIO
from unittest import mock
from urllib.parse import urlencode
from falcon import HTTP_METHODS
from falcon.testing import StartResponseMock, create_environ
from hug import output_format
from hug.api impor... | hug/test.py | from __future__ import absolute_import
import json
import sys
from functools import partial
from io import BytesIO
from unittest import mock
from urllib.parse import urlencode
from falcon import HTTP_METHODS
from falcon.testing import StartResponseMock, create_environ
from hug import output_format
from hug.api impor... | 0.386879 | 0.118819 |
from __future__ import print_function
import numpy as np
import unittest
import time
import argparse
import os
import sys
import subprocess
import traceback
import functools
import pickle
from contextlib import closing
import paddle.fluid as fluid
import paddle.fluid.unique_name as nameGen
from paddle.fluid import cor... | python/paddle/fluid/tests/unittests/mlu/test_collective_base_mlu.py |
from __future__ import print_function
import numpy as np
import unittest
import time
import argparse
import os
import sys
import subprocess
import traceback
import functools
import pickle
from contextlib import closing
import paddle.fluid as fluid
import paddle.fluid.unique_name as nameGen
from paddle.fluid import cor... | 0.272993 | 0.113187 |
import os
import sqlite3
from datetime import datetime
from pathlib import Path
from typing import Any, Callable, Dict, List, Optional, Sequence, Tuple, Union
import pytz
from feast import Entity, FeatureTable
from feast.feature_view import FeatureView
from feast.infra.key_encoding_utils import serialize_entity_key
... | sdk/python/feast/infra/online_stores/sqlite.py |
import os
import sqlite3
from datetime import datetime
from pathlib import Path
from typing import Any, Callable, Dict, List, Optional, Sequence, Tuple, Union
import pytz
from feast import Entity, FeatureTable
from feast.feature_view import FeatureView
from feast.infra.key_encoding_utils import serialize_entity_key
... | 0.795857 | 0.271522 |
import aifc
import random
def monoChannelWrapper(gen):
for s in gen:
yield [s]
def saveM(gen,t,name = "save.aiff"):
saveSample(monoChannelWrapper(extent(gen,t)),name,1,1)
def saveSample(gen,name = "out.aiff",channels=2,prec=3,rate=48000,dither=1):
f = aifc.open(name,'w')
... | sampleGen.py | import aifc
import random
def monoChannelWrapper(gen):
for s in gen:
yield [s]
def saveM(gen,t,name = "save.aiff"):
saveSample(monoChannelWrapper(extent(gen,t)),name,1,1)
def saveSample(gen,name = "out.aiff",channels=2,prec=3,rate=48000,dither=1):
f = aifc.open(name,'w')
... | 0.096211 | 0.199327 |
import argparse
import sys
import json
from .utils import as_obj
def command_arg(*args, **kwargs):
"""
Small tweak to build argparse.add_argument() arguments through a command
declaration (see `command` decorator and `Command.add_arguments` method)
"""
class CommandArg:
def __init__(self, ... | lib/decorators.py | import argparse
import sys
import json
from .utils import as_obj
def command_arg(*args, **kwargs):
"""
Small tweak to build argparse.add_argument() arguments through a command
declaration (see `command` decorator and `Command.add_arguments` method)
"""
class CommandArg:
def __init__(self, ... | 0.378229 | 0.102709 |
import csv
import sys
if __name__ == '__main__':
if len(sys.argv) != 2:
print("Accepts exactly one parameter - the filepath to a Funding Circle CSV export.")
sys.exit(1)
entries = {}
with open('input.csv', 'r') as f:
csv_reader = csv.reader(f)
next(csv_reader) # Remove the... | modules/app_minis/files/fundingcircle_gnucash_summariser/fundingcircle_gnucash_summariser.py |
import csv
import sys
if __name__ == '__main__':
if len(sys.argv) != 2:
print("Accepts exactly one parameter - the filepath to a Funding Circle CSV export.")
sys.exit(1)
entries = {}
with open('input.csv', 'r') as f:
csv_reader = csv.reader(f)
next(csv_reader) # Remove the... | 0.265785 | 0.328435 |
import grpc
import model_service_pb2 as model__service__pb2
class ModelServiceStub(object):
# missing associated documentation comment in .proto file
pass
def __init__(self, channel):
"""Constructor.
Args:
channel: A grpc.Channel.
"""
self.publishLoad = channel.unary_unary(
'/co... | arch/api/proto/model_service_pb2_grpc.py | import grpc
import model_service_pb2 as model__service__pb2
class ModelServiceStub(object):
# missing associated documentation comment in .proto file
pass
def __init__(self, channel):
"""Constructor.
Args:
channel: A grpc.Channel.
"""
self.publishLoad = channel.unary_unary(
'/co... | 0.61682 | 0.048586 |
import os
import sys
import ray
import numpy as np
import pytest
import time
from ray._private.test_utils import SignalActor
@pytest.mark.parametrize(
"ray_start_cluster_head", [{
"num_cpus": 5,
"object_store_memory": 10**8,
}],
indirect=True)
def test_parallel_actor_fill_plasma_retry(r... | python/ray/tests/test_failure_3.py | import os
import sys
import ray
import numpy as np
import pytest
import time
from ray._private.test_utils import SignalActor
@pytest.mark.parametrize(
"ray_start_cluster_head", [{
"num_cpus": 5,
"object_store_memory": 10**8,
}],
indirect=True)
def test_parallel_actor_fill_plasma_retry(r... | 0.501465 | 0.355999 |
from rdkit import Chem
import cv2
import os
import numpy as np
import os.path
from rdkit import Chem
from rdkit.Chem import AllChem
class Compound:
extension = 'png'
#compound identifier in the dataset
id=""
#compound SMILE
_SMILE=""
#mutagen
mutagen=False
#rdk model
rdkMolecule = None
def __init__(self,id... | chemception/models/compound.py | from rdkit import Chem
import cv2
import os
import numpy as np
import os.path
from rdkit import Chem
from rdkit.Chem import AllChem
class Compound:
extension = 'png'
#compound identifier in the dataset
id=""
#compound SMILE
_SMILE=""
#mutagen
mutagen=False
#rdk model
rdkMolecule = None
def __init__(self,id... | 0.144722 | 0.159283 |
from html.parser import HTMLParser
from goose.text import innerTrim
import html
class OutputFormatter(object):
def __init__(self, config):
self.top_node = None
self.config = config
# parser
self.parser = self.config.get_parser()
self.stopwords_class = config.stopwords_clas... | goose/outputformatters.py | from html.parser import HTMLParser
from goose.text import innerTrim
import html
class OutputFormatter(object):
def __init__(self, config):
self.top_node = None
self.config = config
# parser
self.parser = self.config.get_parser()
self.stopwords_class = config.stopwords_clas... | 0.567937 | 0.097219 |
from __future__ import (absolute_import, division, print_function)
__metaclass__ = type
import os
import re
from .util import (
display,
)
from .data import (
data_context,
)
def get_powershell_module_utils_imports(powershell_targets):
"""Return a dictionary of module_utils names mapped to sets of powe... | ansible/venv/lib/python2.7/site-packages/ansible_test/_internal/powershell_import_analysis.py | from __future__ import (absolute_import, division, print_function)
__metaclass__ = type
import os
import re
from .util import (
display,
)
from .data import (
data_context,
)
def get_powershell_module_utils_imports(powershell_targets):
"""Return a dictionary of module_utils names mapped to sets of powe... | 0.655005 | 0.162812 |
from django.test import TestCase
from .models import Image, Location, Category
class LocationTestClass(TestCase):
def setUp(self):
self.location = Location(location = 'Mombasa')
def test_instance(self):
self.assertTrue(isinstance(self.location, Location))
def test_save_location(self):
... | galleria/tests.py | from django.test import TestCase
from .models import Image, Location, Category
class LocationTestClass(TestCase):
def setUp(self):
self.location = Location(location = 'Mombasa')
def test_instance(self):
self.assertTrue(isinstance(self.location, Location))
def test_save_location(self):
... | 0.520009 | 0.459015 |
import pytest
from asserts import assert_gpu_and_cpu_are_equal_collect
from data_gen import *
from marks import ignore_order
from pyspark.sql.types import *
import pyspark.sql.functions as f
def four_op_df(spark, gen, length=2048, seed=0):
return gen_df(spark, StructGen([
('a', gen),
('b', gen),
... | integration_tests/src/main/python/generate_expr_test.py |
import pytest
from asserts import assert_gpu_and_cpu_are_equal_collect
from data_gen import *
from marks import ignore_order
from pyspark.sql.types import *
import pyspark.sql.functions as f
def four_op_df(spark, gen, length=2048, seed=0):
return gen_df(spark, StructGen([
('a', gen),
('b', gen),
... | 0.701509 | 0.612802 |
from defoe import query_utils
from defoe.nlsArticles.query_utils import clean_headers_page_as_string, get_articles_eb, filter_terms_page
from pyspark.sql import Row, SparkSession, SQLContext
import yaml, os
def comp(o):
num_page=o.split("_")[0]
print("-----> ROSA ----> %s" %num_page)
return(int(num_page))
... | defoe/nlsArticles/queries/write_articles_pages_df_yaml.py | from defoe import query_utils
from defoe.nlsArticles.query_utils import clean_headers_page_as_string, get_articles_eb, filter_terms_page
from pyspark.sql import Row, SparkSession, SQLContext
import yaml, os
def comp(o):
num_page=o.split("_")[0]
print("-----> ROSA ----> %s" %num_page)
return(int(num_page))
... | 0.521959 | 0.335895 |
"""Pooling layers definitions."""
import tensorflow as tf
class MAC(tf.keras.layers.Layer):
"""Global max pooling (MAC) layer.
Maximum Activations of Convolutions (MAC) is simply constructed by
max-pooling over all dimensions per feature map. See
https://arxiv.org/abs/1511.05879 for a reference.
"""
de... | research/delf/delf/python/pooling_layers/pooling.py | """Pooling layers definitions."""
import tensorflow as tf
class MAC(tf.keras.layers.Layer):
"""Global max pooling (MAC) layer.
Maximum Activations of Convolutions (MAC) is simply constructed by
max-pooling over all dimensions per feature map. See
https://arxiv.org/abs/1511.05879 for a reference.
"""
de... | 0.978385 | 0.843154 |
import re
import xml.etree.cElementTree as ElementTree
from hashlib import md5
import pytest
from html5lib import getTreeBuilder, HTMLParser
from test_build_html import flat_dict, tail_check, check_xpath
from sphinx.util.docutils import is_html5_writer_available
TREE_BUILDER = getTreeBuilder('etree', implementation=... | tests/test_build_html5.py | import re
import xml.etree.cElementTree as ElementTree
from hashlib import md5
import pytest
from html5lib import getTreeBuilder, HTMLParser
from test_build_html import flat_dict, tail_check, check_xpath
from sphinx.util.docutils import is_html5_writer_available
TREE_BUILDER = getTreeBuilder('etree', implementation=... | 0.325413 | 0.139543 |
from copy import deepcopy
class EventServiceException(Exception):
"""
Exception class for the event service.
"""
def __init__(self, value):
super().__init__()
self.value = value
def __str__(self):
return self.value
class PublisherEventService:
"""
Interface to t... | ipsframework/cca_es_spec.py | from copy import deepcopy
class EventServiceException(Exception):
"""
Exception class for the event service.
"""
def __init__(self, value):
super().__init__()
self.value = value
def __str__(self):
return self.value
class PublisherEventService:
"""
Interface to t... | 0.704465 | 0.151812 |
import asyncio
import logging
import datetime
from typing import Optional, Iterable, Any, Union, Callable, Awaitable, List
from .._common.message import ServiceBusReceivedMessage
from ._servicebus_session_async import ServiceBusSession
from ._servicebus_receiver_async import ServiceBusReceiver
from .._common.utils im... | sdk/servicebus/azure-servicebus/azure/servicebus/aio/_async_auto_lock_renewer.py |
import asyncio
import logging
import datetime
from typing import Optional, Iterable, Any, Union, Callable, Awaitable, List
from .._common.message import ServiceBusReceivedMessage
from ._servicebus_session_async import ServiceBusSession
from ._servicebus_receiver_async import ServiceBusReceiver
from .._common.utils im... | 0.800536 | 0.097907 |
from collections import namedtuple
import logging
from pymol import cmd
import pyrosetta.distributed.packed_pose as packed_pose
from pyrosetta.rosetta.protocols.rosetta_scripts import XmlObjects
from .utils import (
pymol_to_rosetta,
rosetta_to_pymol,
pymol_selection_to_residue_selector,
)
logger = logging... | pymol_rosetta_utils/selectors.py | from collections import namedtuple
import logging
from pymol import cmd
import pyrosetta.distributed.packed_pose as packed_pose
from pyrosetta.rosetta.protocols.rosetta_scripts import XmlObjects
from .utils import (
pymol_to_rosetta,
rosetta_to_pymol,
pymol_selection_to_residue_selector,
)
logger = logging... | 0.693784 | 0.523238 |
from contextlib import contextmanager
from django.contrib.auth import get_user_model
from django.core import mail
from django.http import HttpRequest
from django.test import TestCase, override_settings
from ..forms import RegistrationForm
from .. import signals
try:
from django.urls import reverse
except ImportE... | virtual/lib/python3.6/site-packages/registration/tests/base.py | from contextlib import contextmanager
from django.contrib.auth import get_user_model
from django.core import mail
from django.http import HttpRequest
from django.test import TestCase, override_settings
from ..forms import RegistrationForm
from .. import signals
try:
from django.urls import reverse
except ImportE... | 0.665954 | 0.240095 |
from string import Template
from builtins import object
import six
import requests
from shapely.wkt import loads as load_wkt
from collections import OrderedDict
import json, time, os
from shapely.ops import cascaded_union
from shapely.geometry import shape, box
from shapely.wkt import loads as from_wkt
from gbdxtool... | gbdxtools/vectors.py | from string import Template
from builtins import object
import six
import requests
from shapely.wkt import loads as load_wkt
from collections import OrderedDict
import json, time, os
from shapely.ops import cascaded_union
from shapely.geometry import shape, box
from shapely.wkt import loads as from_wkt
from gbdxtool... | 0.794305 | 0.355579 |
import os
from environs import Env
env = Env()
env.read_env() # read .env file, if it exists
# Build paths inside the project like this: os.path.join(BASE_DIR, ...)
BASE_DIR = os.path.dirname(os.path.dirname(os.path.abspath(__file__)))
# Override in .env for local development
DEBUG = TEMPLATE_DEBUG = env.bool("DEB... | primetver/settings.py | import os
from environs import Env
env = Env()
env.read_env() # read .env file, if it exists
# Build paths inside the project like this: os.path.join(BASE_DIR, ...)
BASE_DIR = os.path.dirname(os.path.dirname(os.path.abspath(__file__)))
# Override in .env for local development
DEBUG = TEMPLATE_DEBUG = env.bool("DEB... | 0.297674 | 0.053949 |
from __future__ import print_function, absolute_import, division
import KratosMultiphysics
import KratosMultiphysics.StructuralMechanicsApplication as StructuralMechanicsApplication
import KratosMultiphysics.KratosUnittest as KratosUnittest
import math
def get_displacement_vector(mp,disp):
index=0
for node in... | applications/StructuralMechanicsApplication/tests/test_cr_beam_adjoint_element_3d2n.py | from __future__ import print_function, absolute_import, division
import KratosMultiphysics
import KratosMultiphysics.StructuralMechanicsApplication as StructuralMechanicsApplication
import KratosMultiphysics.KratosUnittest as KratosUnittest
import math
def get_displacement_vector(mp,disp):
index=0
for node in... | 0.444324 | 0.319705 |
import unittest
from decimal import Decimal
from djmodels.core import validators
from djmodels.core.exceptions import ValidationError
from djmodels.db import connection, models
from djmodels.test import TestCase
from .models import BigD, Foo
class DecimalFieldTests(TestCase):
def test_to_python(self):
... | tests/model_fields/test_decimalfield.py | import unittest
from decimal import Decimal
from djmodels.core import validators
from djmodels.core.exceptions import ValidationError
from djmodels.db import connection, models
from djmodels.test import TestCase
from .models import BigD, Foo
class DecimalFieldTests(TestCase):
def test_to_python(self):
... | 0.830353 | 0.544741 |
from cell import cell_to_rgb, rgb_to_cell, iterate_cell
import numpy as np
from PIL import Image
def board_from_pic(image):
""" Given an h*w*3 numpy array 'image',
return the h*w numpy array 'board'.
"""
return np.apply_along_axis(rgb_to_cell, 2, image)
def pic_from_board(board):
""" Given an ... | bbworld.py | from cell import cell_to_rgb, rgb_to_cell, iterate_cell
import numpy as np
from PIL import Image
def board_from_pic(image):
""" Given an h*w*3 numpy array 'image',
return the h*w numpy array 'board'.
"""
return np.apply_along_axis(rgb_to_cell, 2, image)
def pic_from_board(board):
""" Given an ... | 0.649356 | 0.665016 |
import numpy as np
import pandas as pd
import pytest
import xarray as xr
from xclim.sdba.base import Grouper
from xclim.sdba.processing import adapt_freq, jitter_over_thresh, jitter_under_thresh
def test_jitter_under_thresh():
da = xr.DataArray([0.5, 2.1, np.nan])
out = jitter_under_thresh(da, 1)
assert... | xclim/testing/tests/test_sdba/test_processing.py | import numpy as np
import pandas as pd
import pytest
import xarray as xr
from xclim.sdba.base import Grouper
from xclim.sdba.processing import adapt_freq, jitter_over_thresh, jitter_under_thresh
def test_jitter_under_thresh():
da = xr.DataArray([0.5, 2.1, np.nan])
out = jitter_under_thresh(da, 1)
assert... | 0.663233 | 0.574932 |
would_you_rather_array = [
"Would you rather have the ability to see 10 minutes into the future or 150 years into the "
"future? ",
"Would you rather have telekinesis (the ability to move things with your mind) or telepathy (the ability to read "
"minds)? ", "Would you rather team up with Wonder Woman o... | would_you_rather/wyr.py | would_you_rather_array = [
"Would you rather have the ability to see 10 minutes into the future or 150 years into the "
"future? ",
"Would you rather have telekinesis (the ability to move things with your mind) or telepathy (the ability to read "
"minds)? ", "Would you rather team up with Wonder Woman o... | 0.220091 | 0.364834 |
r"""
Implements a buffer with insertion points. When you know you need to
"get back" to a place and write more later, simply call insertion_point()
at that spot and get a new StringIOTree object that is "left behind".
EXAMPLE:
>>> a = StringIOTree()
>>> _= a.write('first\n')
>>> b = a.insertion_point()
>>> _= a.writ... | Cython/StringIOTree.py |
r"""
Implements a buffer with insertion points. When you know you need to
"get back" to a place and write more later, simply call insertion_point()
at that spot and get a new StringIOTree object that is "left behind".
EXAMPLE:
>>> a = StringIOTree()
>>> _= a.write('first\n')
>>> b = a.insertion_point()
>>> _= a.writ... | 0.755005 | 0.261667 |
import re
from nvflare.apis.dxo import DXO, DataKind, MetaKey, from_shareable
from nvflare.apis.fl_constant import ReservedKey, ReturnCode
from nvflare.apis.fl_context import FLContext
from nvflare.apis.shareable import Shareable
from nvflare.app_common.abstract.aggregator import Aggregator
from nvflare.app_common.ap... | nvflare/app_common/aggregators/intime_accumulate_model_aggregator.py |
import re
from nvflare.apis.dxo import DXO, DataKind, MetaKey, from_shareable
from nvflare.apis.fl_constant import ReservedKey, ReturnCode
from nvflare.apis.fl_context import FLContext
from nvflare.apis.shareable import Shareable
from nvflare.app_common.abstract.aggregator import Aggregator
from nvflare.app_common.ap... | 0.810141 | 0.199113 |
import json
import re
from typing import Callable, Iterator, List, Optional, Union
import scrapy
from scrapy.http import Request, Response
from scrapy.linkextractors import IGNORED_EXTENSIONS
from scrapy.linkextractors.lxmlhtml import LxmlLinkExtractor
from scrapy.spidermiddlewares.httperror import HttpError
from scra... | tools/documentation_crawler/documentation_crawler/spiders/common/spiders.py | import json
import re
from typing import Callable, Iterator, List, Optional, Union
import scrapy
from scrapy.http import Request, Response
from scrapy.linkextractors import IGNORED_EXTENSIONS
from scrapy.linkextractors.lxmlhtml import LxmlLinkExtractor
from scrapy.spidermiddlewares.httperror import HttpError
from scra... | 0.637144 | 0.232016 |
from typing import Dict, Union, Callable
import tensorflow as tf
from opengnn.inputters.inputter import Inputter
from opengnn.utils.data import shifted_batch, get_padded_shapes, diverse_batch
from opengnn.utils.misc import count_lines
class TokenEmbedder(Inputter):
def __init__(self,
vocabulary... | opengnn/inputters/token_embedder.py | from typing import Dict, Union, Callable
import tensorflow as tf
from opengnn.inputters.inputter import Inputter
from opengnn.utils.data import shifted_batch, get_padded_shapes, diverse_batch
from opengnn.utils.misc import count_lines
class TokenEmbedder(Inputter):
def __init__(self,
vocabulary... | 0.862916 | 0.436562 |
"""Test the Report Queries."""
from tenant_schemas.utils import tenant_context
from api.functions import JSONBObjectKeys
from api.iam.test.iam_test_case import IamTestCase
from api.tags.gcp.queries import GCPTagQueryHandler
from api.tags.gcp.view import GCPTagView
from reporting.models import GCPCostEntryLineItemDaily... | koku/api/tags/test/gcp/tests_queries.py | """Test the Report Queries."""
from tenant_schemas.utils import tenant_context
from api.functions import JSONBObjectKeys
from api.iam.test.iam_test_case import IamTestCase
from api.tags.gcp.queries import GCPTagQueryHandler
from api.tags.gcp.view import GCPTagView
from reporting.models import GCPCostEntryLineItemDaily... | 0.783368 | 0.487307 |
"""BERT finetuning runner."""
from __future__ import absolute_import
import logging
import torch
from torch import nn
from pytorch_transformers.modeling_bert import BertPreTrainedModel, BertModel
from torch.nn import CrossEntropyLoss
logging.basicConfig(format='%(asctime)s - %(levelname)s - %(name)s - %(message)... | pytorch_transformers/models/hf_bert_mcq_concat.py | """BERT finetuning runner."""
from __future__ import absolute_import
import logging
import torch
from torch import nn
from pytorch_transformers.modeling_bert import BertPreTrainedModel, BertModel
from torch.nn import CrossEntropyLoss
logging.basicConfig(format='%(asctime)s - %(levelname)s - %(name)s - %(message)... | 0.906647 | 0.248073 |
from pprint import pformat
from six import iteritems
import re
class BiosServerManagement(object):
"""
NOTE: This class is auto generated by the swagger code generator program.
Do not edit the class manually.
"""
"""
Attributes:
swagger_types (dict): The key is attribute name
... | intersight/models/bios_server_management.py | from pprint import pformat
from six import iteritems
import re
class BiosServerManagement(object):
"""
NOTE: This class is auto generated by the swagger code generator program.
Do not edit the class manually.
"""
"""
Attributes:
swagger_types (dict): The key is attribute name
... | 0.538741 | 0.056548 |
import numpy as np
from PyQt5.QtCore import Qt, QThread, QTimer
from PyQt5.QtGui import QPixmap, QFont, QImage, QCursor, QIntValidator
from PyQt5.QtWidgets import QMainWindow, QWidget, QPushButton, QHBoxLayout, QApplication, QLabel, \
QDialog, QDialogButtonBox, QVBoxLayout, QLineEdit
from p... | view.py | import numpy as np
from PyQt5.QtCore import Qt, QThread, QTimer
from PyQt5.QtGui import QPixmap, QFont, QImage, QCursor, QIntValidator
from PyQt5.QtWidgets import QMainWindow, QWidget, QPushButton, QHBoxLayout, QApplication, QLabel, \
QDialog, QDialogButtonBox, QVBoxLayout, QLineEdit
from p... | 0.511717 | 0.10581 |
import datetime
import os
import time
import pytest
from xxhash import xxh3_128
from ocdskingfisherarchive.crawl import Crawl
from ocdskingfisherarchive.exceptions import FutureDataVersionError, SourceMismatchError
from tests import crawl_fixture, create_crawl_directory, path
with open(path('data.json'), 'rb') as f:... | tests/test_crawl.py | import datetime
import os
import time
import pytest
from xxhash import xxh3_128
from ocdskingfisherarchive.crawl import Crawl
from ocdskingfisherarchive.exceptions import FutureDataVersionError, SourceMismatchError
from tests import crawl_fixture, create_crawl_directory, path
with open(path('data.json'), 'rb') as f:... | 0.379493 | 0.405037 |
from typing import Any, Callable, Dict, List, Optional
import os
import torch
from torch.utils.data import Dataset
from catalyst.contrib.datasets.functional import (
download_and_extract_archive,
read_image_file,
read_label_file,
)
from catalyst.data.dataset.metric_learning import (
MetricLearningTrai... | catalyst/contrib/datasets/mnist.py | from typing import Any, Callable, Dict, List, Optional
import os
import torch
from torch.utils.data import Dataset
from catalyst.contrib.datasets.functional import (
download_and_extract_archive,
read_image_file,
read_label_file,
)
from catalyst.data.dataset.metric_learning import (
MetricLearningTrai... | 0.840062 | 0.394463 |
from __future__ import division
import math
import torch
from torch import nn
from torch.nn import functional as F
# Factorised NoisyLinear layer with bias
class NoisyLinear(nn.Module):
def __init__(self, in_features, out_features, std_init=0.5):
super(NoisyLinear, self).__init__()
self.module_name = 'noisy... | model.py | from __future__ import division
import math
import torch
from torch import nn
from torch.nn import functional as F
# Factorised NoisyLinear layer with bias
class NoisyLinear(nn.Module):
def __init__(self, in_features, out_features, std_init=0.5):
super(NoisyLinear, self).__init__()
self.module_name = 'noisy... | 0.942599 | 0.579995 |
import logging
import os
import difflib
from urllib import quote
from django.utils import simplejson
from google.appengine.api import users
from google.appengine.ext import webapp
from google.appengine.ext.webapp import template
import access
import model
import settings
import util
DEFAULT_LABEL_BODY = u"""name: ... | gaewiki/view.py |
import logging
import os
import difflib
from urllib import quote
from django.utils import simplejson
from google.appengine.api import users
from google.appengine.ext import webapp
from google.appengine.ext.webapp import template
import access
import model
import settings
import util
DEFAULT_LABEL_BODY = u"""name: ... | 0.386185 | 0.090133 |
import sys
import os
import torch
from torch import nn
from torch.nn import functional as F
sys.path.insert(0, os.path.abspath(os.path.join(os.path.dirname(__file__), '..')))
from my_ai import utility
from my_ai import vision
def softmax_regression():
# step1.load dataset
batch_size = 256
vision.LoadDat... | example/cnn.py | import sys
import os
import torch
from torch import nn
from torch.nn import functional as F
sys.path.insert(0, os.path.abspath(os.path.join(os.path.dirname(__file__), '..')))
from my_ai import utility
from my_ai import vision
def softmax_regression():
# step1.load dataset
batch_size = 256
vision.LoadDat... | 0.780997 | 0.425307 |
from Ui_MainWindow import Ui_MainWindow
from PyQt4.QtGui import QKeySequence, QIcon, QPixmap
from PyQt4.QtCore import Qt, SIGNAL, QTime, QString
from Serial import Serial
import util
import config
class Ui_Proxy(Ui_MainWindow):
def __init__(self, parent=None):
Ui_MainWindow.__init__(self)
def se... | Ui_Proxy.py | from Ui_MainWindow import Ui_MainWindow
from PyQt4.QtGui import QKeySequence, QIcon, QPixmap
from PyQt4.QtCore import Qt, SIGNAL, QTime, QString
from Serial import Serial
import util
import config
class Ui_Proxy(Ui_MainWindow):
def __init__(self, parent=None):
Ui_MainWindow.__init__(self)
def se... | 0.29696 | 0.066995 |
import numpy as np
import scipy.io
import os
import gzip
import pickle
path = os.environ['ML_DATA_PATH']+'/norb/'
#export PYLEARN2_DATA_PATH=~/ws/python/pylearn2data
def load_resized(size=24, binarize_y=False):
# resized NORB dataset
f = gzip.open(path+'norb_'+str(size)+'.pkl.gz', 'rb')
train, valid = pi... | anglepy/data/norb.py | import numpy as np
import scipy.io
import os
import gzip
import pickle
path = os.environ['ML_DATA_PATH']+'/norb/'
#export PYLEARN2_DATA_PATH=~/ws/python/pylearn2data
def load_resized(size=24, binarize_y=False):
# resized NORB dataset
f = gzip.open(path+'norb_'+str(size)+'.pkl.gz', 'rb')
train, valid = pi... | 0.411466 | 0.355635 |
from socket import AF_INET, SOCK_STREAM, socket
from flask import Flask, request
import os
import json
import random
import string
from enum import IntEnum
from flask.json import jsonify
import base64
from werkzeug.utils import secure_filename
NAME = 'fpm_sandbox_proxy'
LISTEN_PORT = os.environ.get('PROXY_LISTEN_POR... | external/php_fpm_sandbox/proxy.py |
from socket import AF_INET, SOCK_STREAM, socket
from flask import Flask, request
import os
import json
import random
import string
from enum import IntEnum
from flask.json import jsonify
import base64
from werkzeug.utils import secure_filename
NAME = 'fpm_sandbox_proxy'
LISTEN_PORT = os.environ.get('PROXY_LISTEN_POR... | 0.218003 | 0.065575 |
import htmlmth.mods.http
from . import TransformFunction, http_payload_to_tfarg_function
def _generate_encode_chunked_equisize(*args, **kwargs):
chunksize = kwargs.get("chunksize", 256)
assert(chunksize > 0)
return TransformFunction("",
"chunked encoding (equisize)",
... | htmlmth/evasions/http/chunked.py | import htmlmth.mods.http
from . import TransformFunction, http_payload_to_tfarg_function
def _generate_encode_chunked_equisize(*args, **kwargs):
chunksize = kwargs.get("chunksize", 256)
assert(chunksize > 0)
return TransformFunction("",
"chunked encoding (equisize)",
... | 0.577376 | 0.494995 |
import datetime
import uuid
import mock
from oslo_config import fixture as fixture_config
from oslotest import base
import requests
from ceilometer.dispatcher import http
from ceilometer.event.storage import models as event_models
from ceilometer.publisher import utils
class TestDispatcherHttp(base.BaseTestCase):
... | ceilometer/tests/unit/dispatcher/test_http.py |
import datetime
import uuid
import mock
from oslo_config import fixture as fixture_config
from oslotest import base
import requests
from ceilometer.dispatcher import http
from ceilometer.event.storage import models as event_models
from ceilometer.publisher import utils
class TestDispatcherHttp(base.BaseTestCase):
... | 0.69035 | 0.127245 |
from src.main import *
from src.header import *
from core.protocols import *
from core.xmpp import *
from core.web import *
class Bruteforce(object):
def __init__(self, service, username, wordlist, address, port, delay, proxy):
self.service = service
self.username = username
self.... | brut3k1t/src/brut3k1t.py | from src.main import *
from src.header import *
from core.protocols import *
from core.xmpp import *
from core.web import *
class Bruteforce(object):
def __init__(self, service, username, wordlist, address, port, delay, proxy):
self.service = service
self.username = username
self.... | 0.408631 | 0.065875 |
import numpy as np
import random
import sys
import math
import ot
from datetime import datetime, timedelta
import pickle
import numpy as np
import pandas as pd
import torch
from .drift import DriftSampling
from scipy.stats import anderson_ksamp
from utils import timer_func
class pvalueSampling(DriftSampling):
""" ... | query_strategies/p_value.py | import numpy as np
import random
import sys
import math
import ot
from datetime import datetime, timedelta
import pickle
import numpy as np
import pandas as pd
import torch
from .drift import DriftSampling
from scipy.stats import anderson_ksamp
from utils import timer_func
class pvalueSampling(DriftSampling):
""" ... | 0.521959 | 0.406567 |
from discord.ext import commands
import discord
import json
from loguru import logger
from discord.ext import tasks
import base64
import aiohttp
import asyncio
with open('data/database.json') as d:
database = json.load(d)
class Admin(commands.Cog):
def __init__(self, client):
self.... | cogs/admin.py | from discord.ext import commands
import discord
import json
from loguru import logger
from discord.ext import tasks
import base64
import aiohttp
import asyncio
with open('data/database.json') as d:
database = json.load(d)
class Admin(commands.Cog):
def __init__(self, client):
self.... | 0.434941 | 0.077065 |
import json
from django.urls import reverse
from unittest import skipIf
# Projectroles dependency
from projectroles.models import SODAR_CONSTANTS
from projectroles.plugins import get_backend_api
from projectroles.tests.test_views_api import TestAPIViewsBase
# Samplesheets dependency
from samplesheets.tests.test_io... | landingzones/tests/test_views_api.py |
import json
from django.urls import reverse
from unittest import skipIf
# Projectroles dependency
from projectroles.models import SODAR_CONSTANTS
from projectroles.plugins import get_backend_api
from projectroles.tests.test_views_api import TestAPIViewsBase
# Samplesheets dependency
from samplesheets.tests.test_io... | 0.547706 | 0.133302 |
# noqa
from django import forms
from components.component import Component, SetupConfMixin
from common.forms import BaseComponentForm, TypeCheckField
from common.constants import API_TYPE_OP
from .toolkit import tools, configs
class SendVoiceMsg(Component, SetupConfMixin):
""""""
sys_name = configs.SYSTEM_N... | paas-ce/paas/esb/components/generic/templates/qcloud_voice/send_voice_msg.py | # noqa
from django import forms
from components.component import Component, SetupConfMixin
from common.forms import BaseComponentForm, TypeCheckField
from common.constants import API_TYPE_OP
from .toolkit import tools, configs
class SendVoiceMsg(Component, SetupConfMixin):
""""""
sys_name = configs.SYSTEM_N... | 0.282988 | 0.130452 |
from __future__ import print_function
__author__ = '<NAME> (<EMAIL>)'
__version__ = '0.8r1'
import logging
import os
import sys
# Allow the local advanced_shell_history library to be imported.
_LIB = '/usr/local/lib'
if _LIB not in sys.path:
sys.path.append(_LIB)
from advanced_shell_history import unix
from adva... | python/_ash_log.py | from __future__ import print_function
__author__ = '<NAME> (<EMAIL>)'
__version__ = '0.8r1'
import logging
import os
import sys
# Allow the local advanced_shell_history library to be imported.
_LIB = '/usr/local/lib'
if _LIB not in sys.path:
sys.path.append(_LIB)
from advanced_shell_history import unix
from adva... | 0.432183 | 0.096748 |
from typing import Any, TypeVar, Callable, List, Union
import gym
import ray
from muzero.global_vars import GlobalVars
from muzero.policy import Policy
from muzero.rollout_worker import RolloutWorker
TrainerConfigDict = dict
EnvType = gym.Env
class WorkerSet:
"""Represents a set of RolloutWorkers.
There ... | muzero/worker_set.py | from typing import Any, TypeVar, Callable, List, Union
import gym
import ray
from muzero.global_vars import GlobalVars
from muzero.policy import Policy
from muzero.rollout_worker import RolloutWorker
TrainerConfigDict = dict
EnvType = gym.Env
class WorkerSet:
"""Represents a set of RolloutWorkers.
There ... | 0.930062 | 0.236098 |
import pandas as pd
from sklearn.feature_extraction.text import CountVectorizer
from sklearn.feature_extraction.text import TfidfTransformer
from sklearn.linear_model import LogisticRegression
from sklearn.model_selection import cross_val_score
from sklearn.pipeline import Pipeline
def predict_numerical_from_text(tr... | src/mle/text.py | import pandas as pd
from sklearn.feature_extraction.text import CountVectorizer
from sklearn.feature_extraction.text import TfidfTransformer
from sklearn.linear_model import LogisticRegression
from sklearn.model_selection import cross_val_score
from sklearn.pipeline import Pipeline
def predict_numerical_from_text(tr... | 0.93906 | 0.662911 |
from django.db import models
from django.utils import timezone
class ReindexingManager(models.Manager):
"""Used to flag when an elasticsearch reindexing is occurring."""
def _flag_reindexing(self, site, new_index, old_index, alias):
"""Flag the database for a reindex on the given site."""
if ... | src/olympia/lib/es/models.py | from django.db import models
from django.utils import timezone
class ReindexingManager(models.Manager):
"""Used to flag when an elasticsearch reindexing is occurring."""
def _flag_reindexing(self, site, new_index, old_index, alias):
"""Flag the database for a reindex on the given site."""
if ... | 0.637369 | 0.372106 |
import torch.nn as nn
import torch
up_kwargs = {'mode': 'bilinear', 'align_corners': False}
norm_layer = nn.BatchNorm2d
class _PositionAttentionModule(nn.Module):
""" Position attention module"""
def __init__(self, in_channels):
super(_PositionAttentionModule, self).__init__()
self.conv_b = ... | models/head/da.py | import torch.nn as nn
import torch
up_kwargs = {'mode': 'bilinear', 'align_corners': False}
norm_layer = nn.BatchNorm2d
class _PositionAttentionModule(nn.Module):
""" Position attention module"""
def __init__(self, in_channels):
super(_PositionAttentionModule, self).__init__()
self.conv_b = ... | 0.955047 | 0.571109 |
import functools
from flask_login import current_user
from flask_restful import abort
from funcy import flatten
view_only = True
not_view_only = False
ACCESS_TYPE_VIEW = "view"
ACCESS_TYPE_MODIFY = "modify"
ACCESS_TYPE_DELETE = "delete"
ACCESS_TYPES = (ACCESS_TYPE_VIEW, ACCESS_TYPE_MODIFY, ACCESS_TYPE_DELETE)
def... | redash/permissions.py | import functools
from flask_login import current_user
from flask_restful import abort
from funcy import flatten
view_only = True
not_view_only = False
ACCESS_TYPE_VIEW = "view"
ACCESS_TYPE_MODIFY = "modify"
ACCESS_TYPE_DELETE = "delete"
ACCESS_TYPES = (ACCESS_TYPE_VIEW, ACCESS_TYPE_MODIFY, ACCESS_TYPE_DELETE)
def... | 0.421909 | 0.077938 |
import os
import sys
import argparse
import pytest
from modelmachine.ide import get_program, debug, assemble
__version__ = "0.1.6" # Don't forget fix in setup.py
def run_program(args):
"""Get params from args and run file."""
cpu = get_program(args.filename, args.protect_memory)
cpu.run()
def run_debug... | modelmachine/__main__.py | import os
import sys
import argparse
import pytest
from modelmachine.ide import get_program, debug, assemble
__version__ = "0.1.6" # Don't forget fix in setup.py
def run_program(args):
"""Get params from args and run file."""
cpu = get_program(args.filename, args.protect_memory)
cpu.run()
def run_debug... | 0.322099 | 0.124001 |
import torch
import torch.utils.data
from .transforms import *
def fast_collate(batch):
targets = torch.tensor([b[1] for b in batch], dtype=torch.int64)
batch_size = len(targets)
tensor = torch.zeros((batch_size, *batch[0][0].shape), dtype=torch.uint8)
for i in range(batch_size):
tensor[i] += ... | data/loader.py | import torch
import torch.utils.data
from .transforms import *
def fast_collate(batch):
targets = torch.tensor([b[1] for b in batch], dtype=torch.int64)
batch_size = len(targets)
tensor = torch.zeros((batch_size, *batch[0][0].shape), dtype=torch.uint8)
for i in range(batch_size):
tensor[i] += ... | 0.888916 | 0.420064 |
import os, sys
import yaml, json
import logging
import click
from voluptuous import Schema
from .defaults import settings
from .validators import SchemaCheck, config_file, options
from .config_utils import test_config, set_logging
from .exceptions import *
from .utils import *
from .indexlist import IndexList
from .sna... | curator/singletons.py | import os, sys
import yaml, json
import logging
import click
from voluptuous import Schema
from .defaults import settings
from .validators import SchemaCheck, config_file, options
from .config_utils import test_config, set_logging
from .exceptions import *
from .utils import *
from .indexlist import IndexList
from .sna... | 0.270288 | 0.080755 |
import asyncio
import datetime
import time
import traceback
from concurrent.futures import CancelledError
import discord
from discord.ext import commands
from discord.ext.commands import BadArgument
from Util import Permissioncheckers, Configuration, Utils, GearbotLogging, Pages, InfractionUtils, Emoji, Translator, \... | GearBot/Cogs/Moderation.py | import asyncio
import datetime
import time
import traceback
from concurrent.futures import CancelledError
import discord
from discord.ext import commands
from discord.ext.commands import BadArgument
from Util import Permissioncheckers, Configuration, Utils, GearbotLogging, Pages, InfractionUtils, Emoji, Translator, \... | 0.453504 | 0.18704 |
class MovieWorld:
def __init__(self, name):
self.name = name
self.customers = []
self.dvds = []
def __repr__(self):
customers = '\n'.join(repr(customer) for customer in self.customers)
dvds = '\n'.join(repr(dvd) for dvd in self.dvds)
return customers + "\n" + dvd... | static_and_class_methods/movie_world/movie_world.py | class MovieWorld:
def __init__(self, name):
self.name = name
self.customers = []
self.dvds = []
def __repr__(self):
customers = '\n'.join(repr(customer) for customer in self.customers)
dvds = '\n'.join(repr(dvd) for dvd in self.dvds)
return customers + "\n" + dvd... | 0.458227 | 0.202089 |
import sys
import os.path
import json
sys.path.append(
os.path.abspath(os.path.join(os.path.dirname(__file__), os.path.pardir)))
import models.models as database
from sqlalchemy.exc import IntegrityError
import uuid
from config.config import env
from config.mongo_adapter import mongo
from bot import reactbot, chat... | controllers/chat_ctrl.py | import sys
import os.path
import json
sys.path.append(
os.path.abspath(os.path.join(os.path.dirname(__file__), os.path.pardir)))
import models.models as database
from sqlalchemy.exc import IntegrityError
import uuid
from config.config import env
from config.mongo_adapter import mongo
from bot import reactbot, chat... | 0.084278 | 0.072112 |
from typing import List
import pydantic
from fastapi.testclient import TestClient
from seisspark.pipeline_repository import PipelineInfo
from seisspark_service.routers.pipelines import CreateModuleRequest, CreatePipelineRequest, ModuleDescription, PipelineDescription
def test_seisspark_service_modules(seisspark_ser... | tests/test_seisspark_service.py | from typing import List
import pydantic
from fastapi.testclient import TestClient
from seisspark.pipeline_repository import PipelineInfo
from seisspark_service.routers.pipelines import CreateModuleRequest, CreatePipelineRequest, ModuleDescription, PipelineDescription
def test_seisspark_service_modules(seisspark_ser... | 0.659624 | 0.349505 |
import serial
import struct
import binascii
import numpy as np
from time import sleep
from threading import Thread
from matplotlib import pyplot as plt
from matplotlib import animation
global ax1
global ax2
global ax3
global ax4
global ax5
global ax6
global f
global Name_Str
global finish_data
REPORT_DATA_LEN = 66
... | python/10_uart/01_uart.py |
import serial
import struct
import binascii
import numpy as np
from time import sleep
from threading import Thread
from matplotlib import pyplot as plt
from matplotlib import animation
global ax1
global ax2
global ax3
global ax4
global ax5
global ax6
global f
global Name_Str
global finish_data
REPORT_DATA_LEN = 66
... | 0.051762 | 0.128006 |
# Python imports
import urllib
import logging
# AppEngine imports
from google.appengine.ext import db
from google.appengine.api import urlfetch
# Django imports
from django.utils import simplejson
# Local imports
import utils
import models
import hashlib
import settings
class LabelProvider(object):
""" Provides m... | providers/restaurants.py | # Python imports
import urllib
import logging
# AppEngine imports
from google.appengine.ext import db
from google.appengine.api import urlfetch
# Django imports
from django.utils import simplejson
# Local imports
import utils
import models
import hashlib
import settings
class LabelProvider(object):
""" Provides m... | 0.58522 | 0.388328 |
import unittest
import pandas as pd
from etl.helpers.field_mapping import common
from etl.helpers.field_mapping.common import FieldMapping
class TestCommonMethods(unittest.TestCase):
def test_get_field_mapping_filename(self):
filename = common.get_field_mapping_filename("field_name", "random_dir/")
... | etl/helpers/field_mapping/test_common.py | import unittest
import pandas as pd
from etl.helpers.field_mapping import common
from etl.helpers.field_mapping.common import FieldMapping
class TestCommonMethods(unittest.TestCase):
def test_get_field_mapping_filename(self):
filename = common.get_field_mapping_filename("field_name", "random_dir/")
... | 0.650134 | 0.493836 |
"""Cache model."""
__all__ = ['CacheCell']
import mxnet as mx
from mxnet.gluon import HybridBlock
class CacheCell(HybridBlock):
r"""Cache language model.
We implement the neural cache language model proposed in the following work::
@article{grave2016improving,
title={Improving neural languag... | src/gluonnlp/model/train/cache.py | """Cache model."""
__all__ = ['CacheCell']
import mxnet as mx
from mxnet.gluon import HybridBlock
class CacheCell(HybridBlock):
r"""Cache language model.
We implement the neural cache language model proposed in the following work::
@article{grave2016improving,
title={Improving neural languag... | 0.92984 | 0.554048 |
import time
import warnings
from typing import Any, Dict, List, Optional, Sequence, Union
from googleapiclient.discovery import build
from airflow.providers.google.common.hooks.base_google import GoogleBaseHook
class DatastoreHook(GoogleBaseHook):
"""
Interact with Google Cloud Datastore. This hook uses the... | airflow/providers/google/cloud/hooks/datastore.py | import time
import warnings
from typing import Any, Dict, List, Optional, Sequence, Union
from googleapiclient.discovery import build
from airflow.providers.google.common.hooks.base_google import GoogleBaseHook
class DatastoreHook(GoogleBaseHook):
"""
Interact with Google Cloud Datastore. This hook uses the... | 0.874734 | 0.251073 |
import os
import re
import numpy as np
import tensorflow.compat.v2 as tf
import tensorflow_datasets.public_api as tfds
class TedliumReleaseConfig(tfds.core.BuilderConfig):
"""BuilderConfig for a release of the TED-LIUM dataset."""
def __init__(self, *, url, download_url, split_paths, citation, **kwargs):
s... | tensorflow_datasets/audio/tedlium.py | import os
import re
import numpy as np
import tensorflow.compat.v2 as tf
import tensorflow_datasets.public_api as tfds
class TedliumReleaseConfig(tfds.core.BuilderConfig):
"""BuilderConfig for a release of the TED-LIUM dataset."""
def __init__(self, *, url, download_url, split_paths, citation, **kwargs):
s... | 0.788339 | 0.350394 |
import unittest
from user import User
from credentials import Credentials
class TestLocker(unittest.TestCase):
"""
Test class that defines test cases for the contact class behaviours.
Args:
unittest.TestCase: TestCase class that helps in creating test cases
"""
def setUp(self):
''... | test.py | import unittest
from user import User
from credentials import Credentials
class TestLocker(unittest.TestCase):
"""
Test class that defines test cases for the contact class behaviours.
Args:
unittest.TestCase: TestCase class that helps in creating test cases
"""
def setUp(self):
''... | 0.546012 | 0.398348 |
from enum import IntEnum
import dataclasses
from typing import Optional
class InstructionClass(IntEnum):
LD = 0x00
LDX = 0x01
ST = 0x02
STX = 0x03
ALU = 0x04
JMP = 0x05
JMP32 = 0x06
ALU64 = 0x07
@dataclasses.dataclass
class NormalOpcodeEncoding:
opcode: IntEnum
inst_class: I... | disasm/instruction.py | from enum import IntEnum
import dataclasses
from typing import Optional
class InstructionClass(IntEnum):
LD = 0x00
LDX = 0x01
ST = 0x02
STX = 0x03
ALU = 0x04
JMP = 0x05
JMP32 = 0x06
ALU64 = 0x07
@dataclasses.dataclass
class NormalOpcodeEncoding:
opcode: IntEnum
inst_class: I... | 0.71889 | 0.273424 |
from arkfbp.executer import Executer
# pylint: disable=line-too-long
from arkfbp.node import FunctionNode
from ...modeling import get_api_config, collect_model_mapping, get_serializer_node, set_flow_debug
# Editor your node here.
class SerializerCore(FunctionNode):
"""
it will generate all serializer nodes an... | arkfbp/common/django/app/automation/flows/admin/nodes/serializer.py | from arkfbp.executer import Executer
# pylint: disable=line-too-long
from arkfbp.node import FunctionNode
from ...modeling import get_api_config, collect_model_mapping, get_serializer_node, set_flow_debug
# Editor your node here.
class SerializerCore(FunctionNode):
"""
it will generate all serializer nodes an... | 0.341363 | 0.141934 |
import frappe
from frappe import _
from frappe.custom.doctype.custom_field.custom_field import create_custom_fields
def get_setup_stages(args=None):
return [
{
'status': _('Creating shipstation masters'),
'fail_msg': _('Failed to create shipstation masters'),
'tasks': [
{
'fn': create_customer_gr... | shipstation_integration/setup.py | import frappe
from frappe import _
from frappe.custom.doctype.custom_field.custom_field import create_custom_fields
def get_setup_stages(args=None):
return [
{
'status': _('Creating shipstation masters'),
'fail_msg': _('Failed to create shipstation masters'),
'tasks': [
{
'fn': create_customer_gr... | 0.366136 | 0.164752 |
from __future__ import print_function
from utils import *
import os
import json
import shutil
import time
import uuid
import yaml
def build_image(path_sample, config):
global log
service_name = config["service_name"]
image_name = config["image_name"]
tag_name = config["tag_name"]
image_tag = "{}:... | checkpoint_manager.py | from __future__ import print_function
from utils import *
import os
import json
import shutil
import time
import uuid
import yaml
def build_image(path_sample, config):
global log
service_name = config["service_name"]
image_name = config["image_name"]
tag_name = config["tag_name"]
image_tag = "{}:... | 0.273963 | 0.081593 |
from ad_api.base import Client, sp_endpoint, fill_query_params, ApiResponse
class BidRecommendations(Client):
"""Amazon Advertising API for Sponsored Display
Documentation: https://advertising.amazon.com/API/docs/en-us/sponsored-display/3-0/openapi#/Bid%20Recommendations
This API enables programmatic acc... | ad_api/api/sd/bid_recommendations.py | from ad_api.base import Client, sp_endpoint, fill_query_params, ApiResponse
class BidRecommendations(Client):
"""Amazon Advertising API for Sponsored Display
Documentation: https://advertising.amazon.com/API/docs/en-us/sponsored-display/3-0/openapi#/Bid%20Recommendations
This API enables programmatic acc... | 0.859266 | 0.36458 |
import torch
import torch.distributions as dist
from torch import nn
import os
from im2mesh.encoder import encoder_dict, encoder_temporal_dict
from im2mesh.oflow import models, training, generation
from im2mesh import data
def get_decoder(cfg, device, dim=3, c_dim=0, z_dim=0):
''' Returns a decoder instance.
... | im2mesh/oflow/config.py | import torch
import torch.distributions as dist
from torch import nn
import os
from im2mesh.encoder import encoder_dict, encoder_temporal_dict
from im2mesh.oflow import models, training, generation
from im2mesh import data
def get_decoder(cfg, device, dim=3, c_dim=0, z_dim=0):
''' Returns a decoder instance.
... | 0.957147 | 0.452536 |
import os
import argparse
import torch
from torch import nn
import torch.distributed as dist
import torch.backends.cudnn as cudnn
from torchvision import datasets
from torchvision import transforms as pth_transforms
from torchvision.transforms import InterpolationMode
import utils
import vision_transformer as vits
d... | eval_or_predict_knn.py | import os
import argparse
import torch
from torch import nn
import torch.distributed as dist
import torch.backends.cudnn as cudnn
from torchvision import datasets
from torchvision import transforms as pth_transforms
from torchvision.transforms import InterpolationMode
import utils
import vision_transformer as vits
d... | 0.605099 | 0.434101 |
import numpy as np
from ..base import TransformerMixin
from ..utils.validation import check_is_fitted
from scipy.sparse import issparse
###############################################################################
# Mixin class for feature agglomeration.
class AgglomerationTransform(TransformerMixin):... | venv/Lib/site-packages/sklearn/cluster/_feature_agglomeration.py |
import numpy as np
from ..base import TransformerMixin
from ..utils.validation import check_is_fitted
from scipy.sparse import issparse
###############################################################################
# Mixin class for feature agglomeration.
class AgglomerationTransform(TransformerMixin):... | 0.855021 | 0.46308 |