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 random import unittest from copy import deepcopy from unittest import TestCase import numpy as np from learn2learn.data import MetaDataset, TaskGenerator from .util_datasets import TestDatasets class TestTaskGenerator(TestCase): @classmethod def setUpClass(cls) -> None: cls.ds = TestDatasets(...
tests/unit/task_generator/task_generator_test.py
import random import unittest from copy import deepcopy from unittest import TestCase import numpy as np from learn2learn.data import MetaDataset, TaskGenerator from .util_datasets import TestDatasets class TestTaskGenerator(TestCase): @classmethod def setUpClass(cls) -> None: cls.ds = TestDatasets(...
0.482429
0.606469
schema = { "$schema": "http://json-schema.org/draft-06/schema#", "$comment": "Definition of the custom exchange with price data included in the specified CSV file.", "type": "object", "properties": { "baseAsset": { "$comment": "Base asset of the pair in the input CSV file, e.g. BTC, ETH, XLM, ADA, ...", "t...
creten/json_schemas/DbExchangeSchema.py
schema = { "$schema": "http://json-schema.org/draft-06/schema#", "$comment": "Definition of the custom exchange with price data included in the specified CSV file.", "type": "object", "properties": { "baseAsset": { "$comment": "Base asset of the pair in the input CSV file, e.g. BTC, ETH, XLM, ADA, ...", "t...
0.507812
0.430506
import enum import logging import threading import time from grpc._adapter import _common from grpc._adapter import _intermediary_low as _low from grpc.framework.base import interfaces as base_interfaces from grpc.framework.base import null from grpc.framework.foundation import activated from grpc.framework.foundation...
src/python/src/grpc/_adapter/fore.py
import enum import logging import threading import time from grpc._adapter import _common from grpc._adapter import _intermediary_low as _low from grpc.framework.base import interfaces as base_interfaces from grpc.framework.base import null from grpc.framework.foundation import activated from grpc.framework.foundation...
0.546617
0.075687
from typing import List, Dict import jc.utils from jc.parsers.universal import simple_table_parse from jc.exceptions import ParseError class info(): """Provides parser metadata (version, author, etc.)""" version = '1.0' description = '`pidstat` command parser' author = '<NAME>' author_email = '<EM...
jc/parsers/pidstat.py
from typing import List, Dict import jc.utils from jc.parsers.universal import simple_table_parse from jc.exceptions import ParseError class info(): """Provides parser metadata (version, author, etc.)""" version = '1.0' description = '`pidstat` command parser' author = '<NAME>' author_email = '<EM...
0.740737
0.357063
optimize = ( 'Disabled', # = 0, // optimization disabled 'Complete', # = 1, // "Slow complete algorithm" 'Genetic', # = 2, // "Fast genetic based algorithm" 'AllSymbols' # = 3, // "All symbols selected in Market Watch" ) optimize_crit = ( 'Balance', # = 0, // the maximum ba...
backtestd/enums.py
optimize = ( 'Disabled', # = 0, // optimization disabled 'Complete', # = 1, // "Slow complete algorithm" 'Genetic', # = 2, // "Fast genetic based algorithm" 'AllSymbols' # = 3, // "All symbols selected in Market Watch" ) optimize_crit = ( 'Balance', # = 0, // the maximum ba...
0.551091
0.581303
import warnings import pulumi import pulumi.runtime from typing import Any, Mapping, Optional, Sequence, Union, overload from .. import _utilities __all__ = [ 'AssetFilterPresentationTimeRangeArgs', 'AssetFilterTrackSelectionArgs', 'AssetFilterTrackSelectionConditionArgs', 'ContentKeyPolicyPolicyOptio...
sdk/python/pulumi_azure/media/_inputs.py
import warnings import pulumi import pulumi.runtime from typing import Any, Mapping, Optional, Sequence, Union, overload from .. import _utilities __all__ = [ 'AssetFilterPresentationTimeRangeArgs', 'AssetFilterTrackSelectionArgs', 'AssetFilterTrackSelectionConditionArgs', 'ContentKeyPolicyPolicyOptio...
0.897184
0.165357
from vyapp.panel import PanedVerticalWindow from vyapp.areavi import AreaVi from tkinter.ttk import Notebook from tkinter import BOTH import sys class NoteVi(Notebook): """ This class implements vy tabs. """ def __init__(self, *args, **kwargs): Notebook.__init__(self, *args, **kwargs) ...
vyapp/notebook.py
from vyapp.panel import PanedVerticalWindow from vyapp.areavi import AreaVi from tkinter.ttk import Notebook from tkinter import BOTH import sys class NoteVi(Notebook): """ This class implements vy tabs. """ def __init__(self, *args, **kwargs): Notebook.__init__(self, *args, **kwargs) ...
0.433502
0.273392
from __future__ import unicode_literals, print_function from six import text_type import logging from collections import namedtuple import kazoo from netaddr import IPNetwork, IPAddress, AddrFormatError from contrail_api_cli.exceptions import CommandError, ResourceNotFound from contrail_api_cli.utils import printo f...
contrail_api_cli_extra/fix/fix_zk_ip.py
from __future__ import unicode_literals, print_function from six import text_type import logging from collections import namedtuple import kazoo from netaddr import IPNetwork, IPAddress, AddrFormatError from contrail_api_cli.exceptions import CommandError, ResourceNotFound from contrail_api_cli.utils import printo f...
0.609524
0.097691
from abc import ABC from torch import Tensor import torch import torch.nn as nn from gpssm.models.components.utilities import inverse_softplus, safe_softplus from gpytorch.distributions import MultivariateNormal import copy from typing import Any __author__ = '<NAME>' __all__ = ['Recognition', 'OutputRecognition', 'Z...
gpssm/models/components/recognition_model.py
from abc import ABC from torch import Tensor import torch import torch.nn as nn from gpssm.models.components.utilities import inverse_softplus, safe_softplus from gpytorch.distributions import MultivariateNormal import copy from typing import Any __author__ = '<NAME>' __all__ = ['Recognition', 'OutputRecognition', 'Z...
0.973152
0.688288
from qiskit import QuantumCircuit from qiskit import QuantumRegister from qiskit import ClassicalRegister try: from qft import create_qft_circuit except ModuleNotFoundError: from core.algorithms.qft import create_qft_circuit try: from counting import build_diffuser except ModuleNotFoundError: from cor...
app/core-service/core/algorithms/walk.py
from qiskit import QuantumCircuit from qiskit import QuantumRegister from qiskit import ClassicalRegister try: from qft import create_qft_circuit except ModuleNotFoundError: from core.algorithms.qft import create_qft_circuit try: from counting import build_diffuser except ModuleNotFoundError: from cor...
0.462716
0.622287
from sklearn.pipeline import FeatureUnion from sklearn import preprocessing from sklearn.ensemble import GradientBoostingRegressor, RandomForestRegressor import sklearn.linear_model import img_to_pickle as i_p import features as f import classify import pickle import numpy as np import pandas as pd import datetime imp...
script/repredict.py
from sklearn.pipeline import FeatureUnion from sklearn import preprocessing from sklearn.ensemble import GradientBoostingRegressor, RandomForestRegressor import sklearn.linear_model import img_to_pickle as i_p import features as f import classify import pickle import numpy as np import pandas as pd import datetime imp...
0.401805
0.438304
import numpy as np from numpy.linalg import multi_dot from scipy import stats from scipy.linalg import inv from joblib import Parallel, delayed from sklearn.utils.validation import check_memory from sklearn.linear_model import Lasso from .noise_std import reid, group_reid from .stat_tools import pval_from_two_sided_pv...
hidimstat/desparsified_lasso.py
import numpy as np from numpy.linalg import multi_dot from scipy import stats from scipy.linalg import inv from joblib import Parallel, delayed from sklearn.utils.validation import check_memory from sklearn.linear_model import Lasso from .noise_std import reid, group_reid from .stat_tools import pval_from_two_sided_pv...
0.900568
0.686977
from numpy import * import math import pickle def v_angle(a,b): """ returns angle between two vectors coded as numpy.array """ ab=dot(a,b) ab/=linalg.norm(a)*linalg.norm(b) return math.degrees(math.acos(ab)) class UCell: ''' Class to handle crystallographic basis and ...
transform.py
from numpy import * import math import pickle def v_angle(a,b): """ returns angle between two vectors coded as numpy.array """ ab=dot(a,b) ab/=linalg.norm(a)*linalg.norm(b) return math.degrees(math.acos(ab)) class UCell: ''' Class to handle crystallographic basis and ...
0.676299
0.357539
__revision__ = "$Revision: 236 $" import sys sys.path.append(".") from pywinauto.XMLHelpers import * import unittest class XMLHelperTestCases(unittest.TestCase): "Unit tests for the ListViewWrapper class" def setUp(self): """Actually does nothing!""" pass def tearDown(s...
win/pywinauto/unittests/test_XMLHelpers.py
__revision__ = "$Revision: 236 $" import sys sys.path.append(".") from pywinauto.XMLHelpers import * import unittest class XMLHelperTestCases(unittest.TestCase): "Unit tests for the ListViewWrapper class" def setUp(self): """Actually does nothing!""" pass def tearDown(s...
0.380068
0.345492
import tensorflow as tf from blueoil.layers import batch_norm, conv2d # TODO(wakisaka): should be replace to conv_bn_act(). def darknet(name, inputs, filters, kernel_size, is_training=tf.constant(False), activation=None, data_format="NHWC"): """Darknet19 block. Do convolution, batch_norm, bias, leaky_relu a...
blueoil/blocks.py
import tensorflow as tf from blueoil.layers import batch_norm, conv2d # TODO(wakisaka): should be replace to conv_bn_act(). def darknet(name, inputs, filters, kernel_size, is_training=tf.constant(False), activation=None, data_format="NHWC"): """Darknet19 block. Do convolution, batch_norm, bias, leaky_relu a...
0.739234
0.459622
import unittest from jinja2.runtime import Undefined from dbt.adapters.databricks.relation import DatabricksRelation class TestDatabricksRelation(unittest.TestCase): def test_pre_deserialize(self): data = { "quote_policy": {"database": False, "schema": False, "identifier": False}, ...
tests/unit/test_relation.py
import unittest from jinja2.runtime import Undefined from dbt.adapters.databricks.relation import DatabricksRelation class TestDatabricksRelation(unittest.TestCase): def test_pre_deserialize(self): data = { "quote_policy": {"database": False, "schema": False, "identifier": False}, ...
0.652684
0.438304
from pydantic import Field, constr from typing import List, Union from ._base import NoExtraBaseModel from .altnumber import Autocalculate class Outdoors(NoExtraBaseModel): type: constr(regex='^Outdoors$') = 'Outdoors' sun_exposure: bool = Field( True, description='A boolean noting whether ...
honeybee_schema/bc.py
from pydantic import Field, constr from typing import List, Union from ._base import NoExtraBaseModel from .altnumber import Autocalculate class Outdoors(NoExtraBaseModel): type: constr(regex='^Outdoors$') = 'Outdoors' sun_exposure: bool = Field( True, description='A boolean noting whether ...
0.913802
0.487429
from PyQt5 import QtCore, QtGui, QtWidgets from PyQt5.QtWidgets import * import sys,os,getpass,platform import anki_addon_exporter class MyApp(QtWidgets.QMainWindow, anki_addon_exporter.Ui_Dialog): """ A GUI class for the app ... Constructor-Parameters ---------------------------- QtWidge...
macApp/dist/ankiExport.app/Contents/Resources/ankiExport.py
from PyQt5 import QtCore, QtGui, QtWidgets from PyQt5.QtWidgets import * import sys,os,getpass,platform import anki_addon_exporter class MyApp(QtWidgets.QMainWindow, anki_addon_exporter.Ui_Dialog): """ A GUI class for the app ... Constructor-Parameters ---------------------------- QtWidge...
0.450601
0.072112
from pysc2.agents import base_agent from pysc2.lib import actions from pysc2.lib import features import time import numpy # Functions _BUILD_BARRACKS = actions.FUNCTIONS.Build_Barracks_screen.id _BUILD_SUPPLYDEPOT = actions.FUNCTIONS.Build_SupplyDepot_screen.id _NOOP = actions.FUNCTIONS.no_op.id _SELECT_POINT = actio...
experiments/cms_move_1_rand_s_v1.py
from pysc2.agents import base_agent from pysc2.lib import actions from pysc2.lib import features import time import numpy # Functions _BUILD_BARRACKS = actions.FUNCTIONS.Build_Barracks_screen.id _BUILD_SUPPLYDEPOT = actions.FUNCTIONS.Build_SupplyDepot_screen.id _NOOP = actions.FUNCTIONS.no_op.id _SELECT_POINT = actio...
0.465873
0.274956
from __future__ import absolute_import __all__ = ('Widget', 'TextWidget', 'ChoiceWidget') from django.utils.safestring import mark_safe from django.utils.html import escape class Widget(object): def __init__(self, filter, request): self.filter = filter self.request = request def get_query_s...
src/sentry/filters/widgets.py
from __future__ import absolute_import __all__ = ('Widget', 'TextWidget', 'ChoiceWidget') from django.utils.safestring import mark_safe from django.utils.html import escape class Widget(object): def __init__(self, filter, request): self.filter = filter self.request = request def get_query_s...
0.532425
0.089893
import contextlib import boto3 import botocore.exceptions from botocore.config import Config from flask import current_app boto3_config = Config( retries={ "max_attempts": 5, "mode": "standard", } ) def get_client_kwargs(app=current_app): return { "endpoint_url": app.config.get("...
vulnerable_people_form/integrations/persistence.py
import contextlib import boto3 import botocore.exceptions from botocore.config import Config from flask import current_app boto3_config = Config( retries={ "max_attempts": 5, "mode": "standard", } ) def get_client_kwargs(app=current_app): return { "endpoint_url": app.config.get("...
0.370795
0.087486
from __future__ import absolute_import from __future__ import division from __future__ import print_function import numpy as np import queue import os from time import sleep import dataset_loading as dl import pytest MAX_TIMEOUT = 0.1 # 50 ms TEST_BASE = os.path.dirname(os.path.realpath(__file__)) PACKAGE_BASE = os...
tests/test_core.py
from __future__ import absolute_import from __future__ import division from __future__ import print_function import numpy as np import queue import os from time import sleep import dataset_loading as dl import pytest MAX_TIMEOUT = 0.1 # 50 ms TEST_BASE = os.path.dirname(os.path.realpath(__file__)) PACKAGE_BASE = os...
0.508788
0.223441
import patch import dash_devices from dash_devices.dependencies import Input, Output, State import dash_html_components as html import dash_core_components as dcc import plotly.express as px from threading import Timer from websocket import create_connection from datetime import datetime import logging as log from ...
dashboard/plant_dash/dashboard.py
import patch import dash_devices from dash_devices.dependencies import Input, Output, State import dash_html_components as html import dash_core_components as dcc import plotly.express as px from threading import Timer from websocket import create_connection from datetime import datetime import logging as log from ...
0.436982
0.054575
import copy from decimal import Decimal import pytest from django_scopes import scopes_disabled from pretix.base.models import GiftCard @pytest.fixture def giftcard(organizer, event): gc = organizer.issued_gift_cards.create(secret="ABCDEF", currency="EUR") gc.transactions.create(value=Decimal('23.00')) ...
src/tests/api/test_giftcards.py
import copy from decimal import Decimal import pytest from django_scopes import scopes_disabled from pretix.base.models import GiftCard @pytest.fixture def giftcard(organizer, event): gc = organizer.issued_gift_cards.create(secret="ABCDEF", currency="EUR") gc.transactions.create(value=Decimal('23.00')) ...
0.481941
0.339034
import copy from vitrage.common.constants import EntityCategory from vitrage.common.constants import NotifierEventTypes as NType from vitrage.common.constants import VertexProperties as VProps from vitrage.datasources.nova.host import NOVA_HOST_DATASOURCE from vitrage.entity_graph.processor.notifier import _get_notifi...
vitrage/tests/unit/notifier/test_notifier.py
import copy from vitrage.common.constants import EntityCategory from vitrage.common.constants import NotifierEventTypes as NType from vitrage.common.constants import VertexProperties as VProps from vitrage.datasources.nova.host import NOVA_HOST_DATASOURCE from vitrage.entity_graph.processor.notifier import _get_notifi...
0.532425
0.195613
import os import pika import requests import pickle from lando_messaging.workqueue import WorkQueueConfig, WorkQueueConnection # Environment variable names MESSAGE_QUEUE_HOST = "MESSAGE_QUEUE_HOST" MESSAGE_QUEUE_USERNAME = "MESSAGE_QUEUE_USERNAME" MESSAGE_QUEUE_PASSWORD = "MESSAGE_QUEUE_PASSWORD" BESPIN_API_TOKEN = "B...
mailsender.py
import os import pika import requests import pickle from lando_messaging.workqueue import WorkQueueConfig, WorkQueueConnection # Environment variable names MESSAGE_QUEUE_HOST = "MESSAGE_QUEUE_HOST" MESSAGE_QUEUE_USERNAME = "MESSAGE_QUEUE_USERNAME" MESSAGE_QUEUE_PASSWORD = "MESSAGE_QUEUE_PASSWORD" BESPIN_API_TOKEN = "B...
0.466603
0.04952
from edu.uiowa.parser.LarkParser import pLTLParser from edu.uiowa.parser.Formula import PLTLFormula import logging class Trace: #Adopt the trace format suggested by <NAME> & Garvan def __init__(self, data, Id, Lit = None): self.Id = Id self.traceVector = [[self.str2bool(var) for var in timeSt...
src/edu/uiowa/parser/Tracer.py
from edu.uiowa.parser.LarkParser import pLTLParser from edu.uiowa.parser.Formula import PLTLFormula import logging class Trace: #Adopt the trace format suggested by <NAME> & Garvan def __init__(self, data, Id, Lit = None): self.Id = Id self.traceVector = [[self.str2bool(var) for var in timeSt...
0.451085
0.282821
import json import tempfile import shutil from os import path from f5sdk import exceptions from f5sdk.utils import http_utils from ....global_test_imports import pytest, Mock, PropertyMock from ....shared import constants from ....shared import mock_utils REQUESTS = constants.MOCK['requests'] EXAMPLE_VERSION_INFO =...
tests/unit/bigip/extension/test_extension.py
import json import tempfile import shutil from os import path from f5sdk import exceptions from f5sdk.utils import http_utils from ....global_test_imports import pytest, Mock, PropertyMock from ....shared import constants from ....shared import mock_utils REQUESTS = constants.MOCK['requests'] EXAMPLE_VERSION_INFO =...
0.524638
0.208521
from django.core.management.utils import get_random_secret_key import os import logging.config # Build paths inside the project like this: os.path.join(BASE_DIR, ...) BASE_DIR = os.path.dirname(os.path.dirname(os.path.abspath(__file__))) # SECURITY WARNING: don't run with debug turned on in production! DEBUG = os.g...
do_classroom/settings.py
from django.core.management.utils import get_random_secret_key import os import logging.config # Build paths inside the project like this: os.path.join(BASE_DIR, ...) BASE_DIR = os.path.dirname(os.path.dirname(os.path.abspath(__file__))) # SECURITY WARNING: don't run with debug turned on in production! DEBUG = os.g...
0.282295
0.109777
python_file_types = FileType(['.py', '.pyc']) proto_file_types = FileType(['.proto']) def collect_transitive_srcs(ctx): transitive_srcs = depset(order="compile") for dep in ctx.attr.deps: transitive_srcs += dep.transitive_srcs transitive_srcs += python_file_types.filter(ctx.files.srcs) return ...
tools/build_rules/pex_rules.bzl
python_file_types = FileType(['.py', '.pyc']) proto_file_types = FileType(['.proto']) def collect_transitive_srcs(ctx): transitive_srcs = depset(order="compile") for dep in ctx.attr.deps: transitive_srcs += dep.transitive_srcs transitive_srcs += python_file_types.filter(ctx.files.srcs) return ...
0.373876
0.176352
from __future__ import annotations import re from typing import Any, Generic, Optional, TypeVar, Union from .client import GUILD_ID_DEFAULT, GuildID from .commands import ( ChildSlashCommand, SlashCommandGroup, SlashCommandSubGroup, SlashSubCommand, SlashSubCommandConstructor, ) def class_name_t...
dslash/groups.py
from __future__ import annotations import re from typing import Any, Generic, Optional, TypeVar, Union from .client import GUILD_ID_DEFAULT, GuildID from .commands import ( ChildSlashCommand, SlashCommandGroup, SlashCommandSubGroup, SlashSubCommand, SlashSubCommandConstructor, ) def class_name_t...
0.92342
0.105625
import maya.OpenMaya as OpenMaya import maya.cmds as cmds import maya import re def repNameChanged(repNameControl): """ Callback invoked when the render settings UI control for the representation name regular expression text field changes. """ pass def readFromGlobalsNode(): pass def activateR...
python/maya/site-packages/pymel-1.0.5/extras/completion/py/maya/app/sceneAssembly/adskPrepareRender.py
import maya.OpenMaya as OpenMaya import maya.cmds as cmds import maya import re def repNameChanged(repNameControl): """ Callback invoked when the render settings UI control for the representation name regular expression text field changes. """ pass def readFromGlobalsNode(): pass def activateR...
0.596551
0.389111
import logging from pathlib import Path import matplotlib.pyplot as plt import motmetrics import pandas as pd from vvc import config from vvc.detector import object_detection from vvc.format import vvc_format from vvc.tracker.iou_tracker import IOUTracker from vvc.tracker.opencv_tracker import OpenCVTracker from vvc....
experiments/run_all_trackers.py
import logging from pathlib import Path import matplotlib.pyplot as plt import motmetrics import pandas as pd from vvc import config from vvc.detector import object_detection from vvc.format import vvc_format from vvc.tracker.iou_tracker import IOUTracker from vvc.tracker.opencv_tracker import OpenCVTracker from vvc....
0.604866
0.203529
from abc import abstractmethod, ABCMeta from importlib import import_module from beets.util.confit import ConfigValueError from beets import ui from beets.plugins import BeetsPlugin METASYNC_MODULE = 'beetsplug.metasync' # Dictionary to map the MODULE and the CLASS NAME of meta sources SOURCES = { 'amarok': 'Am...
beetsplug/metasync/__init__.py
from abc import abstractmethod, ABCMeta from importlib import import_module from beets.util.confit import ConfigValueError from beets import ui from beets.plugins import BeetsPlugin METASYNC_MODULE = 'beetsplug.metasync' # Dictionary to map the MODULE and the CLASS NAME of meta sources SOURCES = { 'amarok': 'Am...
0.609408
0.148294
import logging import sys import os from apscheduler.schedulers.tornado import TornadoScheduler from apscheduler.jobstores.base import JobLookupError from redis import from_url from tornado import httpserver from tornado.concurrent import run_on_executor from concurrent.futures import ThreadPoolExecutor from tornado im...
web_service/app.py
import logging import sys import os from apscheduler.schedulers.tornado import TornadoScheduler from apscheduler.jobstores.base import JobLookupError from redis import from_url from tornado import httpserver from tornado.concurrent import run_on_executor from concurrent.futures import ThreadPoolExecutor from tornado im...
0.284775
0.093719
r"""Implements Guided Integrated Gradients method. This implementation of the method allows setting the maximum distance that the Guided IG path can deviate from the straight-line path. https://arxiv.org/abs/TBD """ from .base import CoreSaliency from .base import INPUT_OUTPUT_GRADIENTS import math import numpy as...
saliency/core/guided_ig.py
r"""Implements Guided Integrated Gradients method. This implementation of the method allows setting the maximum distance that the Guided IG path can deviate from the straight-line path. https://arxiv.org/abs/TBD """ from .base import CoreSaliency from .base import INPUT_OUTPUT_GRADIENTS import math import numpy as...
0.958236
0.74389
from django.test import TestCase from mock import patch import httpretty import requests from notice_comment.docket import sanitize_fields class SanitizeFieldsTest(TestCase): def setUp(self): self.patch_document_fields = patch( 'notice_comment.docket.get_document_fields') mock_object ...
notice_comment/tests/docket_tests.py
from django.test import TestCase from mock import patch import httpretty import requests from notice_comment.docket import sanitize_fields class SanitizeFieldsTest(TestCase): def setUp(self): self.patch_document_fields = patch( 'notice_comment.docket.get_document_fields') mock_object ...
0.620392
0.312645
import numpy as np import torch import torch.nn.functional as F def masked_mse_loss(y_hat, y, mask): loss_tensor = F.mse_loss(y_hat * mask, y * mask, reduction='none') loss = torch.sum(loss_tensor) / (torch.sum(mask) + 1e-7) return loss def masked_wmse_loss(y_hat, y, mask, w): loss_tensor = F.mse_lo...
vaemof/losses.py
import numpy as np import torch import torch.nn.functional as F def masked_mse_loss(y_hat, y, mask): loss_tensor = F.mse_loss(y_hat * mask, y * mask, reduction='none') loss = torch.sum(loss_tensor) / (torch.sum(mask) + 1e-7) return loss def masked_wmse_loss(y_hat, y, mask, w): loss_tensor = F.mse_lo...
0.827515
0.776559
import pickle import tables import numpy as np from sklearn.neighbors import KDTree from scipy.interpolate import LinearNDInterpolator def quads_from_corner_lookup(lon, lat, corner_points, pixel_lon, pixel_lat, nadir_lon=0.0, inflate=1.0): """ Given co...
glmtools/io/ccd.py
import pickle import tables import numpy as np from sklearn.neighbors import KDTree from scipy.interpolate import LinearNDInterpolator def quads_from_corner_lookup(lon, lat, corner_points, pixel_lon, pixel_lat, nadir_lon=0.0, inflate=1.0): """ Given co...
0.814791
0.619327
import unittest import numpy import pytest import cupy from cupy import testing @testing.gpu class TestTranspose(unittest.TestCase): @testing.numpy_cupy_array_equal() def test_moveaxis1(self, xp): a = testing.shaped_arange((2, 3, 4), xp) return xp.moveaxis(a, [0, 1], [1, 2]) @testing.n...
tests/cupy_tests/manipulation_tests/test_transpose.py
import unittest import numpy import pytest import cupy from cupy import testing @testing.gpu class TestTranspose(unittest.TestCase): @testing.numpy_cupy_array_equal() def test_moveaxis1(self, xp): a = testing.shaped_arange((2, 3, 4), xp) return xp.moveaxis(a, [0, 1], [1, 2]) @testing.n...
0.59796
0.757144
import os prefix_1 = 'TrimedSession' prefix_1_1 = prefix_1 +'/Train/' prefix_1_2 = prefix_1 +'/Test/' prefix_2 = 'TrimedSession_5' prefix_2_1 = prefix_2 +'/Train/' prefix_2_2 = prefix_2 +'/Test/' #ad-ALL be-ALL ra-ALL sc-ALL sms-ALL paths = ['ad-ALL/','be-ALL/','sc-ALL/','sms-ALL/','ra-ALL/'] print("Preparing train...
network_traffic/create_data/findout.py
import os prefix_1 = 'TrimedSession' prefix_1_1 = prefix_1 +'/Train/' prefix_1_2 = prefix_1 +'/Test/' prefix_2 = 'TrimedSession_5' prefix_2_1 = prefix_2 +'/Train/' prefix_2_2 = prefix_2 +'/Test/' #ad-ALL be-ALL ra-ALL sc-ALL sms-ALL paths = ['ad-ALL/','be-ALL/','sc-ALL/','sms-ALL/','ra-ALL/'] print("Preparing train...
0.059197
0.126057
import torch import os import sys import urllib.request import zipfile from glob import glob import scipy.io as sio def download_modelnet_category(modelnet_location): r"""Downloads a modelnet category to a specified direcotry You may complete this function to automate downloading from a central source. ...
kaolin/datasets/modelnet.py
import torch import os import sys import urllib.request import zipfile from glob import glob import scipy.io as sio def download_modelnet_category(modelnet_location): r"""Downloads a modelnet category to a specified direcotry You may complete this function to automate downloading from a central source. ...
0.487795
0.315657
import torch import torch.nn as nn import torch.nn.functional as F import argparse _desc_message = """ Convolutional Sentence Encoder -- sentence embeddings are the output of a convolutional layer applied to a sentence's word embeddings. Output of each convolutional filter is concatenated and fed through...
summarize/nnsum/nnsum/module/sentence_encoder/cnn_sentence_encoder.py
import torch import torch.nn as nn import torch.nn.functional as F import argparse _desc_message = """ Convolutional Sentence Encoder -- sentence embeddings are the output of a convolutional layer applied to a sentence's word embeddings. Output of each convolutional filter is concatenated and fed through...
0.92523
0.429609
from manubot.cite.citekey import standardize_citekey, infer_citekey_prefix, is_valid_citekey def csl_item_set_standard_id(csl_item): """ Extract the standard_id (standard citation key) for a csl_item and modify the csl_item in-place to set its "id" field. The standard_id is extracted from a "standard_cita...
manubot/cite/csl_item.py
from manubot.cite.citekey import standardize_citekey, infer_citekey_prefix, is_valid_citekey def csl_item_set_standard_id(csl_item): """ Extract the standard_id (standard citation key) for a csl_item and modify the csl_item in-place to set its "id" field. The standard_id is extracted from a "standard_cita...
0.419886
0.431644
import argparse import asyncio import datetime import json import logging import logging.config import time from picamera_mqtt import deploy from picamera_mqtt.imaging import imaging from picamera_mqtt.mqtt_clients import AsyncioClient, message_string_encoding from picamera_mqtt.protocol import ( control_topic, d...
picamera_mqtt/imaging/mqtt_client_camera.py
import argparse import asyncio import datetime import json import logging import logging.config import time from picamera_mqtt import deploy from picamera_mqtt.imaging import imaging from picamera_mqtt.mqtt_clients import AsyncioClient, message_string_encoding from picamera_mqtt.protocol import ( control_topic, d...
0.624064
0.093017
import struct import os from .base import FirmwareObject, RawObject, BaseObject, AutoRawObject from .uefi import FirmwareVolume from .utils import print_error, dump_data, sguid, green, blue PFS_GUIDS = { "FIRMWARE_VOLUMES": "7ec6c2b0-3fe3-42a0-a316-22dd0517c1e8", "INTEL_ME": "7439ed9e-70d3-4b65-9e33-...
uefi_firmware/pfs.py
import struct import os from .base import FirmwareObject, RawObject, BaseObject, AutoRawObject from .uefi import FirmwareVolume from .utils import print_error, dump_data, sguid, green, blue PFS_GUIDS = { "FIRMWARE_VOLUMES": "7ec6c2b0-3fe3-42a0-a316-22dd0517c1e8", "INTEL_ME": "7439ed9e-70d3-4b65-9e33-...
0.476336
0.166574
from colorama import Fore, init init() # type hints and annotations. from logistics.plugins.metaclass import Meta # imports all data types. from logistics.plugins.types import * # package. class MonteCarlo: ''' (OBJECT INFO) ------------- eg. MonteCarlo = vandal.MonteCarlo() ...
vandal/objects/montecarlo.py
from colorama import Fore, init init() # type hints and annotations. from logistics.plugins.metaclass import Meta # imports all data types. from logistics.plugins.types import * # package. class MonteCarlo: ''' (OBJECT INFO) ------------- eg. MonteCarlo = vandal.MonteCarlo() ...
0.635336
0.548371
import weakref from .core import CProxyType, CProxy, InvalidAddressSpaceError from .void import CVoidType from ..address_space import AddressSpace from typing import Union, TextIO, List from functools import partial class CFuncType(CProxyType): PRECEDENCE = 20 def __init__(self, returns:CProxyType=None, arg...
headlock/c_data_model/function.py
import weakref from .core import CProxyType, CProxy, InvalidAddressSpaceError from .void import CVoidType from ..address_space import AddressSpace from typing import Union, TextIO, List from functools import partial class CFuncType(CProxyType): PRECEDENCE = 20 def __init__(self, returns:CProxyType=None, arg...
0.652131
0.194387
from __future__ import print_function import os import json import random import h5py import numpy as np class GenerateSampleCoords(object): # pylint: disable=too-few-public-methods """ Generate a sample 3D models file if one does not exist """ @staticmethod def main(): # pylint: disable=too-...
dm_generator/GenerateSampleCoords.py
from __future__ import print_function import os import json import random import h5py import numpy as np class GenerateSampleCoords(object): # pylint: disable=too-few-public-methods """ Generate a sample 3D models file if one does not exist """ @staticmethod def main(): # pylint: disable=too-...
0.493653
0.264289
from ast import literal_eval from distutils.util import strtobool import logging import os import random import shutil import sys from typing import Any, FrozenSet, List, Optional import numpy as np import pkg_resources import tensorflow as tf from seqgra import ModelSize from seqgra.learner import Learner from seqgr...
seqgra/learner/tensorflow/kerashelper.py
from ast import literal_eval from distutils.util import strtobool import logging import os import random import shutil import sys from typing import Any, FrozenSet, List, Optional import numpy as np import pkg_resources import tensorflow as tf from seqgra import ModelSize from seqgra.learner import Learner from seqgr...
0.645567
0.18999
from .. import utils from .scatter import _ScatterParams from .tools import generate_colorbar from .tools import generate_legend from .tools import label_axis from .utils import _get_figure from .utils import _with_default from .utils import parse_fontsize from .utils import show from .utils import temp_fontsize impor...
scprep/plot/jitter.py
from .. import utils from .scatter import _ScatterParams from .tools import generate_colorbar from .tools import generate_legend from .tools import label_axis from .utils import _get_figure from .utils import _with_default from .utils import parse_fontsize from .utils import show from .utils import temp_fontsize impor...
0.87982
0.42185
import sys from lib.build_job import * # 新平台加入, 在 lib/config.py 加入新平台的流程, 并在 job_dict 加入key即可 job_dict = { 'test1': test1 , 'test2': test2 , 'test3': test3 , 'test_api': test_api , 'test_hot_job_list': test_hot_job_list , 'andriod_test_job_list': andriod_test_job_li...
lib/Run.py
import sys from lib.build_job import * # 新平台加入, 在 lib/config.py 加入新平台的流程, 并在 job_dict 加入key即可 job_dict = { 'test1': test1 , 'test2': test2 , 'test3': test3 , 'test_api': test_api , 'test_hot_job_list': test_hot_job_list , 'andriod_test_job_list': andriod_test_job_li...
0.081465
0.054777
from knack.help_files import helps # pylint: disable=unused-import helps['container'] = """ type: group short-summary: (PREVIEW) Manage Azure Container Instances. """ helps['container create'] = """ type: command short-summary: Create a container group. examples: - name: Create a contai...
src/command_modules/azure-cli-container/azure/cli/command_modules/container/_help.py
from knack.help_files import helps # pylint: disable=unused-import helps['container'] = """ type: group short-summary: (PREVIEW) Manage Azure Container Instances. """ helps['container create'] = """ type: command short-summary: Create a container group. examples: - name: Create a contai...
0.540196
0.147801
import os import pytest from dvc.exceptions import DownloadError, UploadError from dvc.remote.base import BaseRemote from dvc.remote.index import RemoteIndex from dvc.remote.local import LocalRemote, LocalRemoteTree from dvc.utils.fs import remove @pytest.fixture(scope="function") def remote(tmp_dir, dvc, tmp_path_...
tests/func/remote/test_index.py
import os import pytest from dvc.exceptions import DownloadError, UploadError from dvc.remote.base import BaseRemote from dvc.remote.index import RemoteIndex from dvc.remote.local import LocalRemote, LocalRemoteTree from dvc.utils.fs import remove @pytest.fixture(scope="function") def remote(tmp_dir, dvc, tmp_path_...
0.427755
0.252995
from .config import * from .activations_autofn import * from .activations_jit import * from .activations import * _ACT_FN_DEFAULT = dict( swish=swish, mish=mish, relu=F.relu, relu6=F.relu6, sigmoid=sigmoid, tanh=tanh, hard_sigmoid=hard_sigmoid, hard_swish=hard_swish, ) _ACT_FN_AUTO = ...
models/activations/__init__.py
from .config import * from .activations_autofn import * from .activations_jit import * from .activations import * _ACT_FN_DEFAULT = dict( swish=swish, mish=mish, relu=F.relu, relu6=F.relu6, sigmoid=sigmoid, tanh=tanh, hard_sigmoid=hard_sigmoid, hard_swish=hard_swish, ) _ACT_FN_AUTO = ...
0.588653
0.143788
import os import re import time import pickle import random import datetime import requests from tqdm import tqdm HEADER = {'User-Agent': 'Mozilla/5.0 (Macintosh; Intel Mac OS X 10_11_5) \ AppleWebKit/537.36 (KHTML, like Gecko) Chrome/50.0.2661.102 Safari/537.36'} class Scraper(): ''' Scrapes a list of we...
samssimplescraper/scraper.py
import os import re import time import pickle import random import datetime import requests from tqdm import tqdm HEADER = {'User-Agent': 'Mozilla/5.0 (Macintosh; Intel Mac OS X 10_11_5) \ AppleWebKit/537.36 (KHTML, like Gecko) Chrome/50.0.2661.102 Safari/537.36'} class Scraper(): ''' Scrapes a list of we...
0.345768
0.099821
# salttran contains tasks involving the transformation of images import saltprint import numpy, pyfits from salterror import SaltError # ----------------------------------------------------------- # Embed an array in a larger array def embed(arr, x0, y0, emarr): """Directly embed a 2-D array into a larger arra...
lib/salttran.py
# salttran contains tasks involving the transformation of images import saltprint import numpy, pyfits from salterror import SaltError # ----------------------------------------------------------- # Embed an array in a larger array def embed(arr, x0, y0, emarr): """Directly embed a 2-D array into a larger arra...
0.367043
0.405449
import sys from collections import OrderedDict import torch.nn as nn import torch import functools def conv3x3(in_planes, out_planes, stride=1): """3x3 convolution with padding""" return nn.Conv2d(in_planes, out_planes, kernel_size=3, stride=stride, padding=1, bias=False) def conv1x1(in_...
mono_and_depth_image_attitude_estimator/pycode/common/net_util.py
import sys from collections import OrderedDict import torch.nn as nn import torch import functools def conv3x3(in_planes, out_planes, stride=1): """3x3 convolution with padding""" return nn.Conv2d(in_planes, out_planes, kernel_size=3, stride=stride, padding=1, bias=False) def conv1x1(in_...
0.922369
0.553566
import numpy as np from calamari_ocr.ocr.dataset.textprocessors import synchronize from calamari_ocr.ocr.voting.voter import Voter class SequenceVoter(Voter): def __init__(self, optimize=False, n_best=3): super().__init__() self.optimize = optimize self.n_best = n_best def _apply_vot...
calamari_ocr/ocr/voting/sequence_voter.py
import numpy as np from calamari_ocr.ocr.dataset.textprocessors import synchronize from calamari_ocr.ocr.voting.voter import Voter class SequenceVoter(Voter): def __init__(self, optimize=False, n_best=3): super().__init__() self.optimize = optimize self.n_best = n_best def _apply_vot...
0.605682
0.342352
import logging import re import os import glob import makelib as ml def allfuncs (): return { "wildcard" : wildcard, "firstword" : firstword, "lastword" : lastword, "dir" : mkfdir, "patsubst" : patsubst } def wildcard (args, context): if len(args) != 1: ...
make/makefuncs.py
import logging import re import os import glob import makelib as ml def allfuncs (): return { "wildcard" : wildcard, "firstword" : firstword, "lastword" : lastword, "dir" : mkfdir, "patsubst" : patsubst } def wildcard (args, context): if len(args) != 1: ...
0.14442
0.188548
from domonic.html import closed_tag from domonic.dom import Element x3d = X3D = type('x3d', (Element,), {'name': 'x3d'}) scene = Scene = type('scene', (Element,), {'name': 'scene'}) material = Material = type('material', (Element,), {'name': 'material'}) appearance = Appearance = type('appearance', (Element,), {'name...
domonic/xml/x3d.py
from domonic.html import closed_tag from domonic.dom import Element x3d = X3D = type('x3d', (Element,), {'name': 'x3d'}) scene = Scene = type('scene', (Element,), {'name': 'scene'}) material = Material = type('material', (Element,), {'name': 'material'}) appearance = Appearance = type('appearance', (Element,), {'name...
0.405449
0.118283
import matplotlib.pyplot as plt from mpl_toolkits.basemap import Basemap from mpl_toolkits.mplot3d import Axes3D import numpy as np crashPath = "crashfile.txt" drone1Path = "drone1file.txt" drone2Path = "drone2file.txt" crashSitesX = [] crashSitesY = [] crashSitesZ = [] drone1Start = [] drone1X = [] drone1Y = [] dron...
drone_decon/src/plot.py
import matplotlib.pyplot as plt from mpl_toolkits.basemap import Basemap from mpl_toolkits.mplot3d import Axes3D import numpy as np crashPath = "crashfile.txt" drone1Path = "drone1file.txt" drone2Path = "drone2file.txt" crashSitesX = [] crashSitesY = [] crashSitesZ = [] drone1Start = [] drone1X = [] drone1Y = [] dron...
0.204025
0.547464
import argparse import datetime import io import itertools import json from pathlib import Path import webdataset as wds import numpy as np import pandas as pd import PIL import torchvision.transforms as transforms from PIL import Image from torch.utils.data import DataLoader, Dataset, Subset from tqdm import tqdm t...
scripts/computestats.py
import argparse import datetime import io import itertools import json from pathlib import Path import webdataset as wds import numpy as np import pandas as pd import PIL import torchvision.transforms as transforms from PIL import Image from torch.utils.data import DataLoader, Dataset, Subset from tqdm import tqdm t...
0.6705
0.51751
import os from cs50 import SQL from flask import Flask, flash, redirect, render_template, request, session from flask_session import Session from tempfile import mkdtemp from werkzeug.exceptions import default_exceptions, HTTPException, InternalServerError from werkzeug.security import check_password_hash, generate_pa...
application.py
import os from cs50 import SQL from flask import Flask, flash, redirect, render_template, request, session from flask_session import Session from tempfile import mkdtemp from werkzeug.exceptions import default_exceptions, HTTPException, InternalServerError from werkzeug.security import check_password_hash, generate_pa...
0.46223
0.057573
import numpy as np import os import paddle.fluid as fluid import logging from collections import defaultdict logging.basicConfig(format='%(asctime)s - %(levelname)s - %(message)s') logger = logging.getLogger("fluid") logger.setLevel(logging.INFO) all_field_id = ['101', '109_14', '110_14', '127_14', '150_14', '121', ...
PaddleRec/multi_task/esmm/utils.py
import numpy as np import os import paddle.fluid as fluid import logging from collections import defaultdict logging.basicConfig(format='%(asctime)s - %(levelname)s - %(message)s') logger = logging.getLogger("fluid") logger.setLevel(logging.INFO) all_field_id = ['101', '109_14', '110_14', '127_14', '150_14', '121', ...
0.223123
0.113678
from utils.ast import * from utils import visitor from utils.errors import * from semantic.tools import * from semantic.types import * from utils.utils import Utils class TypeChecker: def __init__(self, context:Context, errors=[]): self.context:Context = context self.errors:list = errors se...
src/semantic/visitors/type_checker.py
from utils.ast import * from utils import visitor from utils.errors import * from semantic.tools import * from semantic.types import * from utils.utils import Utils class TypeChecker: def __init__(self, context:Context, errors=[]): self.context:Context = context self.errors:list = errors se...
0.416559
0.234746
import mechanize from bs4 import BeautifulSoup import re,string from collections import defaultdict from bugger.util import levenshtein from bugger.exceptions import * class Mantis(object): texts = {"access_denied": re.compile("Your account may be disabled or blocked or the username/password you entered is incorrect."...
bugger/backends/mantis.py
import mechanize from bs4 import BeautifulSoup import re,string from collections import defaultdict from bugger.util import levenshtein from bugger.exceptions import * class Mantis(object): texts = {"access_denied": re.compile("Your account may be disabled or blocked or the username/password you entered is incorrect."...
0.294418
0.073264
import os from pathlib import Path import shutil import subprocess from resource import setrlimit, RLIMIT_CORE, RLIM_INFINITY import typing as t from _madvise import madvise, _madv_dontdump def fork_and_abort(): pid = os.fork() if pid == 0: # child process calls abort(), creating a core dump (if enabl...
python/madv_dontdump/repro.py
import os from pathlib import Path import shutil import subprocess from resource import setrlimit, RLIMIT_CORE, RLIM_INFINITY import typing as t from _madvise import madvise, _madv_dontdump def fork_and_abort(): pid = os.fork() if pid == 0: # child process calls abort(), creating a core dump (if enabl...
0.438064
0.096408
import os import requests import string import random from pandas import DataFrame, Series import dna.logging log = dna.logging.logger(__name__) def _clean_pairs(pairs): if not isinstance(pairs, list): pairs = [pairs] return ','.join(map(str.upper, pairs)) def _fx_mapping(raw_rates): ''' Map ra...
intuition/data/forex.py
import os import requests import string import random from pandas import DataFrame, Series import dna.logging log = dna.logging.logger(__name__) def _clean_pairs(pairs): if not isinstance(pairs, list): pairs = [pairs] return ','.join(map(str.upper, pairs)) def _fx_mapping(raw_rates): ''' Map ra...
0.445288
0.171998
from typing import ( Tuple, ) import random import torch import numpy from utils_types import ( BatchAction, BatchDone, BatchNext, BatchReward, BatchState, TensorStack5, TorchDevice, ) class SumTree: write = 0 def __init__(self, channels, capacity, device): self.capac...
per-duel-dqn/utils_memory.py
from typing import ( Tuple, ) import random import torch import numpy from utils_types import ( BatchAction, BatchDone, BatchNext, BatchReward, BatchState, TensorStack5, TorchDevice, ) class SumTree: write = 0 def __init__(self, channels, capacity, device): self.capac...
0.824073
0.288895
import pandas as pd import requests from io import StringIO def main(hotel_url, output_path, type='train'): """ :param hotel_url: link for the data to be downloaded from :param output_path: relative path where the cleaned data will be saved :param type: train if the data to be cleaned contains the tar...
clean.py
import pandas as pd import requests from io import StringIO def main(hotel_url, output_path, type='train'): """ :param hotel_url: link for the data to be downloaded from :param output_path: relative path where the cleaned data will be saved :param type: train if the data to be cleaned contains the tar...
0.542863
0.514522
from __future__ import unicode_literals, print_function, absolute_import, division import logging, logging.handlers import sys import os import atexit import errno import signal import pwd from ConfigParser import RawConfigParser from .sniffer import get_sniffer from .daemon import drop_privileges, write_pid, daemoni...
amadash/main.py
from __future__ import unicode_literals, print_function, absolute_import, division import logging, logging.handlers import sys import os import atexit import errno import signal import pwd from ConfigParser import RawConfigParser from .sniffer import get_sniffer from .daemon import drop_privileges, write_pid, daemoni...
0.310694
0.054399
u'''MCL Site Knowledge — Utilities.''' from Products.CMFCore.interfaces import IFolderish from Products.CMFCore.WorkflowCore import WorkflowException from plone.app.dexterity.behaviors.exclfromnav import IExcludeFromNavigation from zope.event import notify from zope.lifecycleevent import modified import plone.api ...
src/jpl/mcl/site/knowledge/_utils.py
u'''MCL Site Knowledge — Utilities.''' from Products.CMFCore.interfaces import IFolderish from Products.CMFCore.WorkflowCore import WorkflowException from plone.app.dexterity.behaviors.exclfromnav import IExcludeFromNavigation from zope.event import notify from zope.lifecycleevent import modified import plone.api ...
0.513912
0.153644
import datetime as dt import blpapi import logging from .BbgRefDataService import BbgRefDataService import pandas as pd import numpy as np from . import BbgLogger import pytz from tzlocal import get_localzone logger = BbgLogger.logger SECURITY_DATA = blpapi.Name("securityData") SECURITY = blpapi.Name("security") FIEL...
BloombergData/bbgIntradayBar.py
import datetime as dt import blpapi import logging from .BbgRefDataService import BbgRefDataService import pandas as pd import numpy as np from . import BbgLogger import pytz from tzlocal import get_localzone logger = BbgLogger.logger SECURITY_DATA = blpapi.Name("securityData") SECURITY = blpapi.Name("security") FIEL...
0.656768
0.353875
from litex.build.generic_platform import * from litex.build.altera import AlteraPlatform from litex.build.altera.programmer import USBBlaster # IOs ---------------------------------------------------------------------------------------------- _io = [ ("clk50", 0, Pins("R8"), IOStandard("3.3-V LVTTL")), ("us...
litex_boards/platforms/de0nano.py
from litex.build.generic_platform import * from litex.build.altera import AlteraPlatform from litex.build.altera.programmer import USBBlaster # IOs ---------------------------------------------------------------------------------------------- _io = [ ("clk50", 0, Pins("R8"), IOStandard("3.3-V LVTTL")), ("us...
0.402392
0.235394
from flask import Blueprint, flash, redirect, render_template, request, url_for, session, jsonify, current_app from flask_login import current_user, login_required, login_user, logout_user from werkzeug.utils import secure_filename from functools import wraps import os import config from wiki.web.forms import EditorFo...
wiki/web/routes.py
from flask import Blueprint, flash, redirect, render_template, request, url_for, session, jsonify, current_app from flask_login import current_user, login_required, login_user, logout_user from werkzeug.utils import secure_filename from functools import wraps import os import config from wiki.web.forms import EditorFo...
0.332635
0.054174
from __future__ import unicode_literals from datetime import timedelta from django.db import models from django.core.urlresolvers import reverse from django.utils.translation import ugettext_lazy as _ from django.utils import timezone from django.conf import settings from ..core.utils.models import AutoSlugField c...
spirit/user/models.py
from __future__ import unicode_literals from datetime import timedelta from django.db import models from django.core.urlresolvers import reverse from django.utils.translation import ugettext_lazy as _ from django.utils import timezone from django.conf import settings from ..core.utils.models import AutoSlugField c...
0.669096
0.103976
from __future__ import absolute_import, unicode_literals, print_function def __virtual__(): ''' Only load if the postgres module is present ''' if 'postgres.default_privileges_grant' not in __salt__: return (False, 'Unable to load postgres module. Make sure `postgres.bins_dir` is set.') r...
salt/states/postgres_default_privileges.py
from __future__ import absolute_import, unicode_literals, print_function def __virtual__(): ''' Only load if the postgres module is present ''' if 'postgres.default_privileges_grant' not in __salt__: return (False, 'Unable to load postgres module. Make sure `postgres.bins_dir` is set.') r...
0.734881
0.131118
from freezegun import freeze_time import pytest from McAfee_ESM_v2 import * from McAfee_ESM_v2 import McAfeeESMClient list_test_filtering_incidents = [ {'id': 3}, {'id': 1}, {'id': 5}, {'id': 4}, {'id': 0}, {'id': 2} ] data_test_filtering_incidents = [ ( ( 0, 0 )...
Packs/McAfee_ESM/Integrations/McAfee_ESM_v2/McAfee_ESM_v2_test.py
from freezegun import freeze_time import pytest from McAfee_ESM_v2 import * from McAfee_ESM_v2 import McAfeeESMClient list_test_filtering_incidents = [ {'id': 3}, {'id': 1}, {'id': 5}, {'id': 4}, {'id': 0}, {'id': 2} ] data_test_filtering_incidents = [ ( ( 0, 0 )...
0.298798
0.450118
import antialiased_cnns from satflow.models.layers.RUnetLayers import * import pytorch_lightning as pl import torchvision from typing import Union from nowcasting_utils.models.base import register_model from nowcasting_utils.models.loss import get_loss import numpy as np @register_model class RUnet(pl.LightningModule...
satflow/models/runet.py
import antialiased_cnns from satflow.models.layers.RUnetLayers import * import pytorch_lightning as pl import torchvision from typing import Union from nowcasting_utils.models.base import register_model from nowcasting_utils.models.loss import get_loss import numpy as np @register_model class RUnet(pl.LightningModule...
0.934335
0.428532
# flake8: noqa import json import os import numpy as np import pytest import openvino.runtime.opset8 as ov from openvino.runtime.impl import Function, PartialShape, Shape from openvino.runtime.impl.passes import Manager from tests.test_ngraph.util import count_ops_of_type from openvino.runtime import Core def tes...
src/bindings/python/tests/test_ngraph/test_manager.py
# flake8: noqa import json import os import numpy as np import pytest import openvino.runtime.opset8 as ov from openvino.runtime.impl import Function, PartialShape, Shape from openvino.runtime.impl.passes import Manager from tests.test_ngraph.util import count_ops_of_type from openvino.runtime import Core def tes...
0.62681
0.325936
import os import argparse # --- BEGIN QA --- # seed_variance_test = [21] def QA_task(args): for seed in seed_variance_test: os.system(f"python main.py --do_explain false " f"--model_name baseline " f"--data_dir data/v1.0 --gpu {args.gpu} --seed {seed} --num_...
sim_experiments/run_tasks.py
import os import argparse # --- BEGIN QA --- # seed_variance_test = [21] def QA_task(args): for seed in seed_variance_test: os.system(f"python main.py --do_explain false " f"--model_name baseline " f"--data_dir data/v1.0 --gpu {args.gpu} --seed {seed} --num_...
0.391522
0.187356
from bs4 import BeautifulSoup from twilio.rest import Client import sys, requests, time, configparser config = configparser.ConfigParser() config.read('twilioConfig.ini') TWILIO_ACCOUNT_SID = config.get('twilio', 'TWILIO_ACCOUNT_SID') TWILIO_AUTH_TOKEN = config.get('twilio', 'TWILIO_AUTH_TOKEN') TWILIO_NUMBER_FROM =...
python3/amcEpisodeTracker.py
from bs4 import BeautifulSoup from twilio.rest import Client import sys, requests, time, configparser config = configparser.ConfigParser() config.read('twilioConfig.ini') TWILIO_ACCOUNT_SID = config.get('twilio', 'TWILIO_ACCOUNT_SID') TWILIO_AUTH_TOKEN = config.get('twilio', 'TWILIO_AUTH_TOKEN') TWILIO_NUMBER_FROM =...
0.216094
0.075687
import json import warnings import pulumi import pulumi.runtime from typing import Union from .. import utilities, tables class Lab(pulumi.CustomResource): artifacts_storage_account_id: pulumi.Output[str] """ The ID of the Storage Account used for Artifact Storage. """ default_premium_storage_acco...
sdk/python/pulumi_azure/devtest/lab.py
import json import warnings import pulumi import pulumi.runtime from typing import Union from .. import utilities, tables class Lab(pulumi.CustomResource): artifacts_storage_account_id: pulumi.Output[str] """ The ID of the Storage Account used for Artifact Storage. """ default_premium_storage_acco...
0.795102
0.125574
from collections import namedtuple, deque import numpy as np from scipy import signal import tensorflow as tf from tensorlib.rl.utils.replay.replay import ReplayBuffer from tensorlib.rl.utils.replay.sampler import Sampler from tensorlib.utils.math import unnormalize, normalize Trajectory = namedtuple('Trajectory', ('...
tensorlib/rl/algo/ppo/utils.py
from collections import namedtuple, deque import numpy as np from scipy import signal import tensorflow as tf from tensorlib.rl.utils.replay.replay import ReplayBuffer from tensorlib.rl.utils.replay.sampler import Sampler from tensorlib.utils.math import unnormalize, normalize Trajectory = namedtuple('Trajectory', ('...
0.887671
0.499023
from intent_parser.table.intent_parser_table_type import TableType import intent_parser.table.cell_parser as cell_parser class IntentParserTable(object): """ Intent Parser's representation of a table. """ def __init__(self): self._rows = [] self._caption_index = None self._h...
intent_parser/table/intent_parser_table.py
from intent_parser.table.intent_parser_table_type import TableType import intent_parser.table.cell_parser as cell_parser class IntentParserTable(object): """ Intent Parser's representation of a table. """ def __init__(self): self._rows = [] self._caption_index = None self._h...
0.795261
0.402921
import collections from copy import deepcopy from ..internal.logger import get_logger from ..span import Span log = get_logger(__name__) class Hooks(object): """ Hooks configuration object is used for registering and calling hook functions Example:: @config.falcon.hooks.on('request') d...
ddtrace/settings/hooks.py
import collections from copy import deepcopy from ..internal.logger import get_logger from ..span import Span log = get_logger(__name__) class Hooks(object): """ Hooks configuration object is used for registering and calling hook functions Example:: @config.falcon.hooks.on('request') d...
0.722331
0.168344
import numpy as np from numpy import sin,cos from functools import reduce from copy import copy def single_qubitify(mat, channel, n): """ given a unitary 2x2 matrix and the channel to apply it on returns the associated 2**n x 2**n matrix""" assert mat.shape == (2,2) return reduce(np.kron, [ n...
UNSTABLE/CircuitParser/CircuitParser/Gates.py
import numpy as np from numpy import sin,cos from functools import reduce from copy import copy def single_qubitify(mat, channel, n): """ given a unitary 2x2 matrix and the channel to apply it on returns the associated 2**n x 2**n matrix""" assert mat.shape == (2,2) return reduce(np.kron, [ n...
0.902066
0.528716
#___Import Modules: import rclpy from rclpy.node import Node from geometry_msgs.msg import Twist import getch #___Global Variables: PUBLISH_TOPIC = '/cmd_vel' #__Classes class GamepadTwist(Node): """Gamepad Twist Class. This class contains all methods to publish gamepad controller data. """ ...
simulation_ws/src/ros2_keyboard_to_twist_message/ros2_keyboard_to_twist_message/keyboard_to_twist_function.py
#___Import Modules: import rclpy from rclpy.node import Node from geometry_msgs.msg import Twist import getch #___Global Variables: PUBLISH_TOPIC = '/cmd_vel' #__Classes class GamepadTwist(Node): """Gamepad Twist Class. This class contains all methods to publish gamepad controller data. """ ...
0.393618
0.206454
import sys from pathlib import Path import torch import torchvision as tv from omegaconf.omegaconf import DictConfig, OmegaConf from .util import dump_as_json, pickle_object def get_datasets(dataset_root: "str|Path", nn_input_size: int, test_ratio: float, split_seed: int): """ Returns train and test sets. ...
ghoti/dataset.py
import sys from pathlib import Path import torch import torchvision as tv from omegaconf.omegaconf import DictConfig, OmegaConf from .util import dump_as_json, pickle_object def get_datasets(dataset_root: "str|Path", nn_input_size: int, test_ratio: float, split_seed: int): """ Returns train and test sets. ...
0.452536
0.499573
import sys import unittest import string_buffer class TestStringBuffer(unittest.TestCase): def test_append_mode(self): sb = string_buffer.StringBuffer("", 5) self.assertEqual(sb.content, "") self.assertEqual(sb.display_string, "") self.assertEqual(sb.cpos_buffer, 0) sb.ha...
tests/old_string_buffer.py
import sys import unittest import string_buffer class TestStringBuffer(unittest.TestCase): def test_append_mode(self): sb = string_buffer.StringBuffer("", 5) self.assertEqual(sb.content, "") self.assertEqual(sb.display_string, "") self.assertEqual(sb.cpos_buffer, 0) sb.ha...
0.393968
0.339828
from __future__ import unicode_literals from operator import itemgetter import glob import os import struct import zlib class AD1Reader(object): def __init__(self, ad1_path, separator='/', margin=512, string_encoding='utf-8'): self.separator = separator self.margin = margin self.string_e...
pyad1/reader.py
from __future__ import unicode_literals from operator import itemgetter import glob import os import struct import zlib class AD1Reader(object): def __init__(self, ad1_path, separator='/', margin=512, string_encoding='utf-8'): self.separator = separator self.margin = margin self.string_e...
0.470007
0.088623
import time from pathlib import Path from os import PathLike from nlp_architect.models.absa import TRAIN_OUT from nlp_architect.models.absa.train.acquire_terms import AcquireTerms from nlp_architect.models.absa.train.rerank_terms import RerankTerms from nlp_architect.models.absa.utils import parse_docs, _download_pretr...
nlp_architect/models/absa/train/train.py
import time from pathlib import Path from os import PathLike from nlp_architect.models.absa import TRAIN_OUT from nlp_architect.models.absa.train.acquire_terms import AcquireTerms from nlp_architect.models.absa.train.rerank_terms import RerankTerms from nlp_architect.models.absa.utils import parse_docs, _download_pretr...
0.423935
0.155046
import urllib import logging from typing import Text from resilient_exporters import utils from resilient_exporters.exporters import Exporter, ExportResult from resilient_exporters.exceptions import MissingConfigError, \ InvalidConfigError, \ ...
resilient_exporters/exporters/exporter_sqlserver.py
import urllib import logging from typing import Text from resilient_exporters import utils from resilient_exporters.exporters import Exporter, ExportResult from resilient_exporters.exceptions import MissingConfigError, \ InvalidConfigError, \ ...
0.712032
0.156685
import os import jieba import pickle from pyecharts import options from wordcloud import WordCloud from pyecharts.globals import ThemeType from pyecharts.charts import Pie, Bar, Funnel '''检查文件在是否存在''' def checkDir(dirpath): if not os.path.exists(dirpath): os.mkdir(dirpath) return False return True '''画饼图''' d...
examples/userWeiboSpider/analysis.py
import os import jieba import pickle from pyecharts import options from wordcloud import WordCloud from pyecharts.globals import ThemeType from pyecharts.charts import Pie, Bar, Funnel '''检查文件在是否存在''' def checkDir(dirpath): if not os.path.exists(dirpath): os.mkdir(dirpath) return False return True '''画饼图''' d...
0.06644
0.149656
from ..testcase import BaseTestCase class ForeignKeyFieldTestCase(BaseTestCase): def test_foreign_key(self): from django.db import models as dj_models from djangostdnet import models class ADjangoParentModel(dj_models.Model): name = dj_models.CharField(max_length=255) ...
tests/fields/foreign_key_field.py
from ..testcase import BaseTestCase class ForeignKeyFieldTestCase(BaseTestCase): def test_foreign_key(self): from django.db import models as dj_models from djangostdnet import models class ADjangoParentModel(dj_models.Model): name = dj_models.CharField(max_length=255) ...
0.524638
0.290805
def list_dependencies(): return [ { "bind_args": { "actual": "@scala_annex_ch_epfl_scala_bloop_backend_2_12", "name": "jar/scala_annex_ch/epfl/scala/bloop_backend_2_12", }, "import_args": { "default_visibility": ["//visibili...
3rdparty/maven.bzl
def list_dependencies(): return [ { "bind_args": { "actual": "@scala_annex_ch_epfl_scala_bloop_backend_2_12", "name": "jar/scala_annex_ch/epfl/scala/bloop_backend_2_12", }, "import_args": { "default_visibility": ["//visibili...
0.477798
0.202079
import argparse import json import os import re import subprocess import sys import time import yaml from datetime import datetime # streams which don't use lockfiles UNLOCKED_STREAMS = [ 'rawhide', 'branched', 'bodhi-updates-testing', 'bodhi-updates', ] # https://github.com/coreos/fedora-coreos-trac...
scripts/versionary.py
import argparse import json import os import re import subprocess import sys import time import yaml from datetime import datetime # streams which don't use lockfiles UNLOCKED_STREAMS = [ 'rawhide', 'branched', 'bodhi-updates-testing', 'bodhi-updates', ] # https://github.com/coreos/fedora-coreos-trac...
0.320928
0.202956
class Graph: def __init__(self, vSet, eSet) -> None: #アトリビュートを隠蔽 self.__vertexSet = vSet self.__edgeSet = eSet # vertexSetのゲッター def getVertexSet(self): return self.__vertexSet # edgeSetのゲッター def getEdgeSet(self): return self.__edgeSet # vertexSetのセッター ...
object/shortest_path_class1.py
class Graph: def __init__(self, vSet, eSet) -> None: #アトリビュートを隠蔽 self.__vertexSet = vSet self.__edgeSet = eSet # vertexSetのゲッター def getVertexSet(self): return self.__vertexSet # edgeSetのゲッター def getEdgeSet(self): return self.__edgeSet # vertexSetのセッター ...
0.260484
0.435962
import sys import time from boost_adaptbx.boost.python import streambuf from cctbx.eltbx import attenuation_coefficient from scitbx import matrix from scitbx.array_family import flex from dxtbx.ext import read_int32 from dxtbx.format.FormatSMVRigaku import FormatSMVRigaku from dxtbx.model import ParallaxCorrectedPxMm...
src/dxtbx/format/FormatSMVRigakuEiger.py
import sys import time from boost_adaptbx.boost.python import streambuf from cctbx.eltbx import attenuation_coefficient from scitbx import matrix from scitbx.array_family import flex from dxtbx.ext import read_int32 from dxtbx.format.FormatSMVRigaku import FormatSMVRigaku from dxtbx.model import ParallaxCorrectedPxMm...
0.658198
0.379206