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
"""Module to keep login and logout command.""" from contextlib import contextmanager import six from ..core.commands import AbstractCommand from ..core.signals import post_logout from ..core.commands.arg_types import boolean_yes_no from ..core.exceptions import OptionNotSetException from ..core.api import AuthyTokenIss...
termius/account/commands.py
"""Module to keep login and logout command.""" from contextlib import contextmanager import six from ..core.commands import AbstractCommand from ..core.signals import post_logout from ..core.commands.arg_types import boolean_yes_no from ..core.exceptions import OptionNotSetException from ..core.api import AuthyTokenIss...
0.653127
0.122786
from typing import List from src.models.inference.base_prediction import BasePrediction from src.models.inference.representation import BoundingBox from src.models.storage.batch import Batch from src.models.storage.frame import Frame class Prediction(BasePrediction): """ Data model used to store the predicte...
src/models/inference/classifier_prediction.py
from typing import List from src.models.inference.base_prediction import BasePrediction from src.models.inference.representation import BoundingBox from src.models.storage.batch import Batch from src.models.storage.frame import Frame class Prediction(BasePrediction): """ Data model used to store the predicte...
0.930142
0.664877
from tensorflow import keras import tensorflow as tf import archs from utils import data_utils, train_utils, augment, argmanager from utils.loss import multinomial_nll import numpy as np import random import string import math import os import json def subsample_nonpeak_data(nonpeak_seqs, nonpeak_cts, peak_data_size,...
src/train.py
from tensorflow import keras import tensorflow as tf import archs from utils import data_utils, train_utils, augment, argmanager from utils.loss import multinomial_nll import numpy as np import random import string import math import os import json def subsample_nonpeak_data(nonpeak_seqs, nonpeak_cts, peak_data_size,...
0.780453
0.473049
def tournament_scores(lst) countA = 0 countB = 0 countC = 0 countD = 0 goalA = 0 goalB = 0 goalC = 0 goalD = 0 concededgoalA = 0 concededgoalB = 0 concededgoalC = 0 concededgoalD = 0 for i in lst if i.split()[1] i.split()[3] ...
Data Science and Machine Learning/Machine-Learning-In-Python-THOROUGH/EXAMPLES/EDABIT/EXPERT/001_100/07_football_tournement_scores.py
def tournament_scores(lst) countA = 0 countB = 0 countC = 0 countD = 0 goalA = 0 goalB = 0 goalC = 0 goalD = 0 concededgoalA = 0 concededgoalB = 0 concededgoalC = 0 concededgoalD = 0 for i in lst if i.split()[1] i.split()[3] ...
0.159315
0.637652
import re from ..ebuild import atom, cpv, errors, restricts from ..restrictions import packages, values from ..restrictions.util import collect_package_restrictions valid_globbing = re.compile(r"^(?:[\w+-.]+|(?<!\*)\*)+$").match class ParseError(ValueError): """Raised if parsing a restriction expression failed....
src/pkgcore/util/parserestrict.py
import re from ..ebuild import atom, cpv, errors, restricts from ..restrictions import packages, values from ..restrictions.util import collect_package_restrictions valid_globbing = re.compile(r"^(?:[\w+-.]+|(?<!\*)\*)+$").match class ParseError(ValueError): """Raised if parsing a restriction expression failed....
0.698844
0.356951
import torch def videoset_train_collate(batch): videos, vmasks, labels = [], [], [] for item, label in batch: videos.append(item[0]) vmasks.append(item[1]) labels.append(label) return (torch.cat(videos, dim=0), torch.cat(vmasks, dim=0), torch.cat(labels, dim=0)) def ...
dataloader/collate.py
import torch def videoset_train_collate(batch): videos, vmasks, labels = [], [], [] for item, label in batch: videos.append(item[0]) vmasks.append(item[1]) labels.append(label) return (torch.cat(videos, dim=0), torch.cat(vmasks, dim=0), torch.cat(labels, dim=0)) def ...
0.462473
0.423995
import sys sys.path.insert(0, "../../Sknet/") import sknet import os import numpy as np import time import tensorflow as tf from sknet import ops,layers import argparse parser = argparse.ArgumentParser() parser.add_argument('--data_augmentation', type=int) parser.add_argument('--dataset', type=str) parser.add_argume...
REGUL/run_test.py
import sys sys.path.insert(0, "../../Sknet/") import sknet import os import numpy as np import time import tensorflow as tf from sknet import ops,layers import argparse parser = argparse.ArgumentParser() parser.add_argument('--data_augmentation', type=int) parser.add_argument('--dataset', type=str) parser.add_argume...
0.439507
0.163746
from datetime import datetime from datetime import timedelta import pytz import time import numpy as np import json import pandas as pd from fitness_all import fitnessOfPath import random from scipy.stats import truncnorm from matplotlib import pyplot as plt def evaluate_fitness_of_all(generation,sessions,travel_time,...
Project2/python/geneticAlgorithm.py
from datetime import datetime from datetime import timedelta import pytz import time import numpy as np import json import pandas as pd from fitness_all import fitnessOfPath import random from scipy.stats import truncnorm from matplotlib import pyplot as plt def evaluate_fitness_of_all(generation,sessions,travel_time,...
0.154631
0.26429
import logging from typing import Optional import grpc import redis from dgad.grpc import classification_pb2, classification_pb2_grpc class RedisWorker: def __init__( self, redis_host: str, redis_port: int, redis_set: str, grpc_host: str, grpc_port: str, ): ...
redis-worker/dgad_redis_worker/worker.py
import logging from typing import Optional import grpc import redis from dgad.grpc import classification_pb2, classification_pb2_grpc class RedisWorker: def __init__( self, redis_host: str, redis_port: int, redis_set: str, grpc_host: str, grpc_port: str, ): ...
0.762778
0.156846
from pogle_math import Vector, Matrix4x4, Transform __author__ = '<NAME>' __copyright__ = "Copyright 2013, The Python OpenGL Engine" __license__ = "Closed Source" __version__ = "0.0.1" __email__ = "<EMAIL>" __status__ = "Prototype" class Light(object): def __init__(self, pos=Vector(0.0, 0.0, 0.0)): self...
pogle/pogle_scene.py
from pogle_math import Vector, Matrix4x4, Transform __author__ = '<NAME>' __copyright__ = "Copyright 2013, The Python OpenGL Engine" __license__ = "Closed Source" __version__ = "0.0.1" __email__ = "<EMAIL>" __status__ = "Prototype" class Light(object): def __init__(self, pos=Vector(0.0, 0.0, 0.0)): self...
0.599368
0.217234
import pytest import icat import icat.config from icat.ids import DataSelection from conftest import getConfig @pytest.fixture(scope="module") def client(setupicat): client, conf = getConfig() client.login(conf.auth, conf.credentials) return client # parameter lists param_ids = [ ([42], [], []), ...
tests/test_07_dataselection.py
import pytest import icat import icat.config from icat.ids import DataSelection from conftest import getConfig @pytest.fixture(scope="module") def client(setupicat): client, conf = getConfig() client.login(conf.auth, conf.credentials) return client # parameter lists param_ids = [ ([42], [], []), ...
0.568176
0.455078
# pylint: enable=line-too-long from unittest import TestCase from unittest import main as launch_tests from unittest.mock import patch from PyFunceble.abstracts import Version class TestVersion(TestCase): """ Tests of PyFunceble.abstracts.Version """ def test_split_version(self): """ ...
tests/test_abstracts_package.py
# pylint: enable=line-too-long from unittest import TestCase from unittest import main as launch_tests from unittest.mock import patch from PyFunceble.abstracts import Version class TestVersion(TestCase): """ Tests of PyFunceble.abstracts.Version """ def test_split_version(self): """ ...
0.850313
0.686941
import time import utime import machine # tuodaan koko kirjasto from machine import Pin from umqttsimple import MQTTClient import network import gc gc.enable() # aktivoidaan automaattinen roskankeruu # asetetaan hitaampi kellotus 20MHz, 40MHz, 80Mhz, 160MHz or 240MHz machine.freq(80000000) print ("Prosessorin nopeus...
esp32-liiketunnistus/main.py
import time import utime import machine # tuodaan koko kirjasto from machine import Pin from umqttsimple import MQTTClient import network import gc gc.enable() # aktivoidaan automaattinen roskankeruu # asetetaan hitaampi kellotus 20MHz, 40MHz, 80Mhz, 160MHz or 240MHz machine.freq(80000000) print ("Prosessorin nopeus...
0.17621
0.136551
import sys, socket from struct import * def carry_around_add(a, b): c = a + b return (c & 0xffff) + (c >> 16) def checksum(msg): s = 0 for i in range(0, len(msg), 2): w = (ord(msg[i]) << 8 ) + ord(msg[i+1]) s = carry_around_add(s, w) return ~s & 0xffff try: s = socket.socket(s...
attack/smuf-attack.py
import sys, socket from struct import * def carry_around_add(a, b): c = a + b return (c & 0xffff) + (c >> 16) def checksum(msg): s = 0 for i in range(0, len(msg), 2): w = (ord(msg[i]) << 8 ) + ord(msg[i+1]) s = carry_around_add(s, w) return ~s & 0xffff try: s = socket.socket(s...
0.070901
0.078607
from django.core.exceptions import ValidationError import cyder.base.tests from cyder.cydns.domain.models import Domain from cyder.cydns.nameserver.models import Nameserver from cyder.cydns.mx.models import MX from cyder.cydns.srv.models import SRV from cyder.cydns.txt.models import TXT from cyder.cydns.ptr.models imp...
cyder/cydns/cname/tests/test_models.py
from django.core.exceptions import ValidationError import cyder.base.tests from cyder.cydns.domain.models import Domain from cyder.cydns.nameserver.models import Nameserver from cyder.cydns.mx.models import MX from cyder.cydns.srv.models import SRV from cyder.cydns.txt.models import TXT from cyder.cydns.ptr.models imp...
0.624523
0.283918
from flask import render_template, request, redirect, session, Blueprint import uuid from crud import client from crud import producer app = Blueprint("login", "app") @app.route('/', methods=['GET', 'POST']) def index(): if "cpf" in session: return redirect("/main") elif "cnpj" in session: r...
api/login.py
from flask import render_template, request, redirect, session, Blueprint import uuid from crud import client from crud import producer app = Blueprint("login", "app") @app.route('/', methods=['GET', 'POST']) def index(): if "cpf" in session: return redirect("/main") elif "cnpj" in session: r...
0.249082
0.052207
from django.db import models, transaction from django.contrib.contenttypes.fields import GenericRelation from django.core.exceptions import ValidationError from mezzanine.pages.page_processors import processor_for from hs_core.models import BaseResource, ResourceManager, resource_processor, CoreMetaData, \ Abstra...
hs_script_resource/models.py
from django.db import models, transaction from django.contrib.contenttypes.fields import GenericRelation from django.core.exceptions import ValidationError from mezzanine.pages.page_processors import processor_for from hs_core.models import BaseResource, ResourceManager, resource_processor, CoreMetaData, \ Abstra...
0.495606
0.057705
class VerticeInvalidoException(Exception): pass class ArestaInvalidaException(Exception): pass class MatrizInvalidaException(Exception): pass class Grafo: QTDE_MAX_SEPARADOR = 1 SEPARADOR_ARESTA = '-' __maior_vertice = 0 def __init__(self, V=None, M=None): ''' Constró...
Graphs/Kruskal algorithm/grafo_adj_nao_dir.py
class VerticeInvalidoException(Exception): pass class ArestaInvalidaException(Exception): pass class MatrizInvalidaException(Exception): pass class Grafo: QTDE_MAX_SEPARADOR = 1 SEPARADOR_ARESTA = '-' __maior_vertice = 0 def __init__(self, V=None, M=None): ''' Constró...
0.434221
0.441553
import sys, struct import numpy as np def read_one_data_block(data, header, indices, fid): """Reads one 60-sample data block from fid into data, at the location indicated by indices.""" # In version 1.2, we moved from saving timestamps as unsigned # integers to signed integers to accommodate negative (ad...
pyspike/intanutil/read_one_data_block.py
import sys, struct import numpy as np def read_one_data_block(data, header, indices, fid): """Reads one 60-sample data block from fid into data, at the location indicated by indices.""" # In version 1.2, we moved from saving timestamps as unsigned # integers to signed integers to accommodate negative (ad...
0.385837
0.29146
import pandas as pd def exclude_the_min_row_sum(feature_count_table, feature_count_start_column, feature_count_end_column, min_row, output_file): feature_count_table_df = pd.read_table(feature_count_table) matrix_value = _extract_value_matrix(feature_count_table_df, ...
graditudelib/min_row_sum.py
import pandas as pd def exclude_the_min_row_sum(feature_count_table, feature_count_start_column, feature_count_end_column, min_row, output_file): feature_count_table_df = pd.read_table(feature_count_table) matrix_value = _extract_value_matrix(feature_count_table_df, ...
0.371935
0.338842
import abc from bokeh.document import Document from bokeh.io import export_png, export_svgs from bokeh.layouts import column, gridplot, row from bokeh.models import Spacer class BasePanel(object): """ Base class for all panels. """ def __init__(self): self.layout = None self.doc = None ...
xrview/core/panel.py
import abc from bokeh.document import Document from bokeh.io import export_png, export_svgs from bokeh.layouts import column, gridplot, row from bokeh.models import Spacer class BasePanel(object): """ Base class for all panels. """ def __init__(self): self.layout = None self.doc = None ...
0.457137
0.291397
from __future__ import print_function from __future__ import absolute_import from __future__ import division import compas_rhino from ._shapeartist import ShapeArtist class PolyhedronArtist(ShapeArtist): """Artist for drawing polyhedron shapes. Parameters ---------- shape : :class:`compas.geometry.P...
src/compas_rhino/artists/polyhedronartist.py
from __future__ import print_function from __future__ import absolute_import from __future__ import division import compas_rhino from ._shapeartist import ShapeArtist class PolyhedronArtist(ShapeArtist): """Artist for drawing polyhedron shapes. Parameters ---------- shape : :class:`compas.geometry.P...
0.898711
0.38549
import torch from torch import nn from fastNLP.core.batch import Batch from fastNLP.core.dataset import DataSet from fastNLP.core.metrics import _prepare_metrics from fastNLP.core.sampler import SequentialSampler from fastNLP.core.utils import CheckError from fastNLP.core.utils import _build_args from fastNLP.core.uti...
fastNLP/core/tester.py
import torch from torch import nn from fastNLP.core.batch import Batch from fastNLP.core.dataset import DataSet from fastNLP.core.metrics import _prepare_metrics from fastNLP.core.sampler import SequentialSampler from fastNLP.core.utils import CheckError from fastNLP.core.utils import _build_args from fastNLP.core.uti...
0.929015
0.394114
import os, sys, abc, re from errand.util import which, shellcmd class Compiler(abc.ABC): """Parent class for all compiler classes """ def __init__(self, path, flags): self.path = path self.flags = flags self.version = None def isavail(self): if self.version is None: ...
errand/compiler.py
import os, sys, abc, re from errand.util import which, shellcmd class Compiler(abc.ABC): """Parent class for all compiler classes """ def __init__(self, path, flags): self.path = path self.flags = flags self.version = None def isavail(self): if self.version is None: ...
0.468061
0.102305
import pytest from aiida_siesta.utils.pao_manager import PaoManager def test_set_from_ion(generate_ion_data): pao_man = PaoManager() ion = generate_ion_data('Si') pao_man.set_from_ion(ion) assert pao_man.name == "Si" assert pao_man._gen_dict is not None assert pao_man._pol_dict == {3: {1: {...
tests/utils/test_pao_manager.py
import pytest from aiida_siesta.utils.pao_manager import PaoManager def test_set_from_ion(generate_ion_data): pao_man = PaoManager() ion = generate_ion_data('Si') pao_man.set_from_ion(ion) assert pao_man.name == "Si" assert pao_man._gen_dict is not None assert pao_man._pol_dict == {3: {1: {...
0.632957
0.683268
from string import Template import numpy as np import pycuda.autoinit from pycuda.compiler import SourceModule from pycuda.gpuarray import GPUArray, to_gpu from .utils import all_arrays_to_gpu, parse_cu_files_to_string def batch_mvcnn_voxel_traversal_with_ray_marching( M, D, N, F, H, W, ...
raynet/cuda_implementations/mvcnn_with_ray_marching_and_voxels_mapping.py
from string import Template import numpy as np import pycuda.autoinit from pycuda.compiler import SourceModule from pycuda.gpuarray import GPUArray, to_gpu from .utils import all_arrays_to_gpu, parse_cu_files_to_string def batch_mvcnn_voxel_traversal_with_ray_marching( M, D, N, F, H, W, ...
0.902526
0.61396
import sys import pkgutil as pkg # pip install PyQt5 to install the library from PyQt5.QtWidgets import QApplication, QWidget, QLabel, QLineEdit, QTextEdit, QListWidget, QComboBox, QVBoxLayout, QHBoxLayout from PyQt5.QtCore import QStringListModel, QFile, QTextStream, Qt from PyQt5.QtGui import QIcon import PyQt5.QtWi...
pyqt5_module_navigator.py
import sys import pkgutil as pkg # pip install PyQt5 to install the library from PyQt5.QtWidgets import QApplication, QWidget, QLabel, QLineEdit, QTextEdit, QListWidget, QComboBox, QVBoxLayout, QHBoxLayout from PyQt5.QtCore import QStringListModel, QFile, QTextStream, Qt from PyQt5.QtGui import QIcon import PyQt5.QtWi...
0.181916
0.063715
import os import pandas as pd import geopandas as gpd files = ['prop_urban_2000_2010.csv', 'pop_women_2010.csv', 'pop_men_2010.csv', 'idhm_2000_2010.csv', 'estimativas_pop.csv', 'interest_real.csv', 'num_people_age_gender_AP_2010.csv', 'qualification_APs_...
auxiliary/read_input_data.py
import os import pandas as pd import geopandas as gpd files = ['prop_urban_2000_2010.csv', 'pop_women_2010.csv', 'pop_men_2010.csv', 'idhm_2000_2010.csv', 'estimativas_pop.csv', 'interest_real.csv', 'num_people_age_gender_AP_2010.csv', 'qualification_APs_...
0.272025
0.229298
from unittest import mock from django.apps import apps from django.test import SimpleTestCase, TestCase from wagtail.core import blocks from wagtail.core.models import Page from wagtail.tests.testapp.models import StreamPage from v1.tests.wagtail_pages.helpers import save_new_page from v1.util.migrations import ( ...
cfgov/v1/tests/util/test_migrations.py
from unittest import mock from django.apps import apps from django.test import SimpleTestCase, TestCase from wagtail.core import blocks from wagtail.core.models import Page from wagtail.tests.testapp.models import StreamPage from v1.tests.wagtail_pages.helpers import save_new_page from v1.util.migrations import ( ...
0.781622
0.408395
import pandas as pd from humor_features.utils import * class HumorFeatures: def __init__(self, dataset = None): self.df = dataset self.df["text"] = self.df["text"].str.replace("!"," !",regex = False) self.df["text"] = self.df["text"].str.replace("?"," ?",regex = False) self.df["tex...
humor_features/HumorFeatures.py
import pandas as pd from humor_features.utils import * class HumorFeatures: def __init__(self, dataset = None): self.df = dataset self.df["text"] = self.df["text"].str.replace("!"," !",regex = False) self.df["text"] = self.df["text"].str.replace("?"," ?",regex = False) self.df["tex...
0.458591
0.171616
import argparse from typing import List, Union import pandas as pd from zvt.contract import IntervalLevel from zvt.utils.pd_utils import pd_is_not_null from zvt.utils.time_utils import now_pd_timestamp from zvt.api import get_entities, Stock from zvt.api.quote import get_zen_factor_schema from zvt.factors.factor impo...
zvt/factors/zen/zen_factor.py
import argparse from typing import List, Union import pandas as pd from zvt.contract import IntervalLevel from zvt.utils.pd_utils import pd_is_not_null from zvt.utils.time_utils import now_pd_timestamp from zvt.api import get_entities, Stock from zvt.api.quote import get_zen_factor_schema from zvt.factors.factor impo...
0.506347
0.296215
import pytest from open_city_profile.consts import ( SERVICE_CONNECTION_ALREADY_EXISTS_ERROR, SERVICE_NOT_IDENTIFIED_ERROR, ) from open_city_profile.tests.asserts import assert_match_error_code from services.enums import ServiceType from services.tests.factories import ProfileFactory, ServiceConnectionFactory ...
services/tests/test_services_graphql_api.py
import pytest from open_city_profile.consts import ( SERVICE_CONNECTION_ALREADY_EXISTS_ERROR, SERVICE_NOT_IDENTIFIED_ERROR, ) from open_city_profile.tests.asserts import assert_match_error_code from services.enums import ServiceType from services.tests.factories import ProfileFactory, ServiceConnectionFactory ...
0.582372
0.363534
import os import rospy import rospkg import tensorflow as tf import numpy as np import cv2 from PIL import Image, ImageFont, ImageDraw from abc import ABCMeta, abstractmethod from styx_msgs.msg import TrafficLight from light_classification.tl_classifier import TLClassifier class SSDTLClassifier(TLClassifier): _...
ros/src/tl_detector/light_classification/ssd_tl_classifier.py
import os import rospy import rospkg import tensorflow as tf import numpy as np import cv2 from PIL import Image, ImageFont, ImageDraw from abc import ABCMeta, abstractmethod from styx_msgs.msg import TrafficLight from light_classification.tl_classifier import TLClassifier class SSDTLClassifier(TLClassifier): _...
0.731059
0.362264
__author__ = "<NAME> <<EMAIL>>" import re import collections from time import sleep from unicon.bases.routers.services import BaseService from unicon.core.errors import SubCommandFailure, StateMachineError from unicon.eal.dialogs import Dialog, Statement from unicon.plugins.generic.statements import GenericStateme...
src/unicon/plugins/confd/csp/service_implementation.py
__author__ = "<NAME> <<EMAIL>>" import re import collections from time import sleep from unicon.bases.routers.services import BaseService from unicon.core.errors import SubCommandFailure, StateMachineError from unicon.eal.dialogs import Dialog, Statement from unicon.plugins.generic.statements import GenericStateme...
0.460532
0.063482
from datetime import datetime, timedelta import pandas as pd import flask from sqlalchemy import extract, asc, desc, func, text from app import db, app today = datetime.today() first_of_this_month = today.replace(day=1, hour=0, minute=0, second=0, microsecond=0) last_of_prev_month = first_of_this_month - timedelta(day...
app/models_postgresql.py
from datetime import datetime, timedelta import pandas as pd import flask from sqlalchemy import extract, asc, desc, func, text from app import db, app today = datetime.today() first_of_this_month = today.replace(day=1, hour=0, minute=0, second=0, microsecond=0) last_of_prev_month = first_of_this_month - timedelta(day...
0.393385
0.147034
import rospy from geometry_msgs.msg import Twist from std_msgs.msg import Float64 from std_msgs.msg import Bool import math pubLeft = rospy.Publisher('/setpoint_left', Float64, queue_size=10) pubRigth = rospy.Publisher('/setpoint_right', Float64, queue_size=10) pubFront = rospy.Publisher('/setpoint_front', Float64, qu...
src/hermesIII/src/PID_general.py
import rospy from geometry_msgs.msg import Twist from std_msgs.msg import Float64 from std_msgs.msg import Bool import math pubLeft = rospy.Publisher('/setpoint_left', Float64, queue_size=10) pubRigth = rospy.Publisher('/setpoint_right', Float64, queue_size=10) pubFront = rospy.Publisher('/setpoint_front', Float64, qu...
0.127151
0.135604
from typing import List from pydantic import BaseModel, Field from models.domain.resource import ResourceType from models.domain.resource_template import ResourceTemplate, Parameter def get_sample_workspace_template_object(template_name: str = "tre-workspace-vanilla") -> ResourceTemplate: return ResourceTemplate...
management_api_app/models/schemas/workspace_template.py
from typing import List from pydantic import BaseModel, Field from models.domain.resource import ResourceType from models.domain.resource_template import ResourceTemplate, Parameter def get_sample_workspace_template_object(template_name: str = "tre-workspace-vanilla") -> ResourceTemplate: return ResourceTemplate...
0.842215
0.255762
import argparse import os import sys import datetime import re import time import numpy as np from config import Config import utils import model as modellib from dataset import NOCSDataset # Root directory of the project ROOT_DIR = os.getcwd() # Directory to save logs and trained model MODEL_DIR = os.path.join(ROOT...
research/6D_Pose/nocs_train.py
import argparse import os import sys import datetime import re import time import numpy as np from config import Config import utils import model as modellib from dataset import NOCSDataset # Root directory of the project ROOT_DIR = os.getcwd() # Directory to save logs and trained model MODEL_DIR = os.path.join(ROOT...
0.365796
0.301264
import requests def dataset_definition(connection, dataset_id, fields=None, verbose=False): """Get the definition of a dataset. Args: connection (object): MicroStrategy connection object returned by `microstrategy.Connection()`. dataset_id (str): Identifier of a pre-existing dataset. Used whe...
mstrio/api/datasets.py
import requests def dataset_definition(connection, dataset_id, fields=None, verbose=False): """Get the definition of a dataset. Args: connection (object): MicroStrategy connection object returned by `microstrategy.Connection()`. dataset_id (str): Identifier of a pre-existing dataset. Used whe...
0.856558
0.375907
"""This module contains a Google Cloud Speech Hook.""" from typing import Dict, Optional, Sequence, Union from google.api_core.retry import Retry from google.cloud.speech_v1 import SpeechClient from google.cloud.speech_v1.types import RecognitionAudio, RecognitionConfig from airflow.providers.google.common.consts imp...
airflow/providers/google/cloud/hooks/speech_to_text.py
"""This module contains a Google Cloud Speech Hook.""" from typing import Dict, Optional, Sequence, Union from google.api_core.retry import Retry from google.cloud.speech_v1 import SpeechClient from google.cloud.speech_v1.types import RecognitionAudio, RecognitionConfig from airflow.providers.google.common.consts imp...
0.952431
0.42471
from netapp.connection import NaConnection from nis_get_iter_key_td import NisGetIterKeyTd # 2 properties from nis_domain_config_info import NisDomainConfigInfo # 4 properties class NisConnection(NaConnection): def nis_get(self, nis_domain, desired_attributes=None): """ Get NIS domain configur...
generated-libraries/python/netapp/nis/__init__.py
from netapp.connection import NaConnection from nis_get_iter_key_td import NisGetIterKeyTd # 2 properties from nis_domain_config_info import NisDomainConfigInfo # 4 properties class NisConnection(NaConnection): def nis_get(self, nis_domain, desired_attributes=None): """ Get NIS domain configur...
0.874064
0.390766
from typing import List import numpy as np from braket.default_simulator.operation import GateOperation, Observable class Simulation: """ This class tracks the evolution of a quantum system with `qubit_count` qubits. The state of system the evolves by application of `GateOperation`s using the `evolve()...
src/braket/default_simulator/simulation.py
from typing import List import numpy as np from braket.default_simulator.operation import GateOperation, Observable class Simulation: """ This class tracks the evolution of a quantum system with `qubit_count` qubits. The state of system the evolves by application of `GateOperation`s using the `evolve()...
0.974288
0.835886
import torch import numpy as np import pandas as pd import seaborn as sns import matplotlib.pyplot as plt from collections import defaultdict def mean_of_attention_heads(matrix, out_dim): chunks = torch.split(matrix, out_dim, dim=1) return torch.mean(torch.stack(chunks), dim=0) def latent_dim_participation_...
cellvgae/utils/top_genes.py
import torch import numpy as np import pandas as pd import seaborn as sns import matplotlib.pyplot as plt from collections import defaultdict def mean_of_attention_heads(matrix, out_dim): chunks = torch.split(matrix, out_dim, dim=1) return torch.mean(torch.stack(chunks), dim=0) def latent_dim_participation_...
0.742422
0.574723
import numpy as np import random import keras class QLearning_NN(): def __init__(self,rl_params,weights_save_dir): self.parameters = dict(rl_params) self.weights_save_dir = weights_save_dir self.parameters['output_length'] = len(self.parameters['actions']) self.epoch = 0 sel...
RL.py
import numpy as np import random import keras class QLearning_NN(): def __init__(self,rl_params,weights_save_dir): self.parameters = dict(rl_params) self.weights_save_dir = weights_save_dir self.parameters['output_length'] = len(self.parameters['actions']) self.epoch = 0 sel...
0.562898
0.232997
import re from os.path import join import glob import os import pandas as pd from datetime import date import pygal from pygal.style import BlueStyle from pygal.style import DarkGreenBlueStyle from pygal.style import TurquoiseStyle from pygal.style import CleanStyle from collections import Counter from pygal.style impo...
code/viz_laufzeit_fachgebiet_ling.py
import re from os.path import join import glob import os import pandas as pd from datetime import date import pygal from pygal.style import BlueStyle from pygal.style import DarkGreenBlueStyle from pygal.style import TurquoiseStyle from pygal.style import CleanStyle from collections import Counter from pygal.style impo...
0.144239
0.1811
import torch import torch.nn as nn import torch.nn.functional as F import pydicom import numpy as np import cv2 import re import glob import os, os.path as osp from PIL import Image from torch.utils.data import Dataset, Sampler from .utils import _isnone from .crop_tta import crop_tta, resize_for_crop import numpy a...
src/factory/data/datasets.py
import torch import torch.nn as nn import torch.nn.functional as F import pydicom import numpy as np import cv2 import re import glob import os, os.path as osp from PIL import Image from torch.utils.data import Dataset, Sampler from .utils import _isnone from .crop_tta import crop_tta, resize_for_crop import numpy a...
0.393152
0.282295
import os import json import base64 import gzip import boto3 from satstac import Collection, Item from stac_updater import utils sns_client = boto3.client('sns') s3_res = boto3.resource('s3') ACCOUNT_ID = boto3.client('sts').get_caller_identity()['Account'] REGION = os.getenv('REGION') NOTIFICATION_TOPIC = os.geten...
stac_updater/handler.py
import os import json import base64 import gzip import boto3 from satstac import Collection, Item from stac_updater import utils sns_client = boto3.client('sns') s3_res = boto3.resource('s3') ACCOUNT_ID = boto3.client('sts').get_caller_identity()['Account'] REGION = os.getenv('REGION') NOTIFICATION_TOPIC = os.geten...
0.222278
0.047162
# use tdklib library,which provides a wrapper for tdk testcase script import tdklib; from tdkbVariables import *; from FWUpgradeUtility import * #Test component to be tested obj = tdklib.TDKScriptingLibrary("fwupgradehal","1"); obj1 = tdklib.TDKScriptingLibrary("sysutil","1"); #IP and Port of box, No need to change, ...
testscripts/RDKB/component/FWUpgradeHAL/TS_FWUPGRADEHAL_SetDownloadUrl.py
# use tdklib library,which provides a wrapper for tdk testcase script import tdklib; from tdkbVariables import *; from FWUpgradeUtility import * #Test component to be tested obj = tdklib.TDKScriptingLibrary("fwupgradehal","1"); obj1 = tdklib.TDKScriptingLibrary("sysutil","1"); #IP and Port of box, No need to change, ...
0.327668
0.252695
import itertools import warnings # 3rd-party modules import holoviews as hv from holoviews import opts, dim from holoviews.operation.datashader import datashade, bundle_graph import networkx as nx import pandas as pd # My handwritten modules from .s3_utils import savefig from . import knn from . import sourmash_utils...
khtools/holoviews.py
import itertools import warnings # 3rd-party modules import holoviews as hv from holoviews import opts, dim from holoviews.operation.datashader import datashade, bundle_graph import networkx as nx import pandas as pd # My handwritten modules from .s3_utils import savefig from . import knn from . import sourmash_utils...
0.495117
0.297585
INPUT_FILE = 'input.txt' def sin(angle): angle %= 360 if angle == 0 or angle == 180: return 0 elif angle == 90: return 1 elif angle == 270: return -1 raise ValueError('Only the multiples of the right angle are supported.') def cos(angle): return sin(angle + 90) def...
year-2021/day-19/part-2.py
INPUT_FILE = 'input.txt' def sin(angle): angle %= 360 if angle == 0 or angle == 180: return 0 elif angle == 90: return 1 elif angle == 270: return -1 raise ValueError('Only the multiples of the right angle are supported.') def cos(angle): return sin(angle + 90) def...
0.625667
0.678806
from neutron_lib.api import converters as conv from neutron_lib.api import extensions from neutron_lib import constants as nlib_const from gbpservice.neutron.extensions import group_policy as gp # Extended attributes for Group Policy resource to map to Neutron constructs EXTENDED_ATTRIBUTES_2_0 = { gp.POLICY_TA...
gbpservice/neutron/extensions/group_policy_mapping.py
from neutron_lib.api import converters as conv from neutron_lib.api import extensions from neutron_lib import constants as nlib_const from gbpservice.neutron.extensions import group_policy as gp # Extended attributes for Group Policy resource to map to Neutron constructs EXTENDED_ATTRIBUTES_2_0 = { gp.POLICY_TA...
0.604866
0.156491
# Licensed under the Apache License, Version 2.0 (the "License"); # you may not use this file except in compliance with the License. # You may obtain a copy of the License at # http://www.apache.org/licenses/LICENSE-2.0 # Unless required by applicable law or agreed to in writing, software # distributed under the ...
mxnet_to_caffe.py
# Licensed under the Apache License, Version 2.0 (the "License"); # you may not use this file except in compliance with the License. # You may obtain a copy of the License at # http://www.apache.org/licenses/LICENSE-2.0 # Unless required by applicable law or agreed to in writing, software # distributed under the ...
0.794265
0.309963
import common import numpy as np data = common.read_file('2017/21/data.txt') lines = data.splitlines() repetitions = 5 # part 1 repetitions = 18 # part 2 def parse_rule(rule): segments = rule.split(' ') pattern_lines = segments[0].split('/') result_lines = segments[2].split('/') def interpret_char...
2017/21/solution.py
import common import numpy as np data = common.read_file('2017/21/data.txt') lines = data.splitlines() repetitions = 5 # part 1 repetitions = 18 # part 2 def parse_rule(rule): segments = rule.split(' ') pattern_lines = segments[0].split('/') result_lines = segments[2].split('/') def interpret_char...
0.272702
0.458652
import asyncio from asyncio import Future, PriorityQueue from typing import (AsyncIterable, Awaitable, Deque, Dict, Iterable, List, Optional, Set, Tuple, Union) from collections import deque from time import monotonic import anyio from asyncio_rlock import RLock from asyncio_throttle import ...
ircrobots/server.py
import asyncio from asyncio import Future, PriorityQueue from typing import (AsyncIterable, Awaitable, Deque, Dict, Iterable, List, Optional, Set, Tuple, Union) from collections import deque from time import monotonic import anyio from asyncio_rlock import RLock from asyncio_throttle import ...
0.550728
0.075687
import os from typing import Optional from .imagelist import ImageList from ._util import download as download_data, check_exits class COCO70(ImageList): """COCO-70 dataset is a large-scale classification dataset (1000 images per class) created from `COCO <https://cocodataset.org/>`_ Dataset. It ...
common/vision/datasets/coco70.py
import os from typing import Optional from .imagelist import ImageList from ._util import download as download_data, check_exits class COCO70(ImageList): """COCO-70 dataset is a large-scale classification dataset (1000 images per class) created from `COCO <https://cocodataset.org/>`_ Dataset. It ...
0.822653
0.459986
import pandas from bitstring import ReadError from .base_parser_class import InteropBinParser class InteropControlMetrics(InteropBinParser): __version = 0.1 supported_versions = [1] codename = 'control' def _init_variables(self): self.data = { 'lane': [], 'tile': [], ...
illuminate/control_metrics.py
import pandas from bitstring import ReadError from .base_parser_class import InteropBinParser class InteropControlMetrics(InteropBinParser): __version = 0.1 supported_versions = [1] codename = 'control' def _init_variables(self): self.data = { 'lane': [], 'tile': [], ...
0.390011
0.22448
from cafe.drivers.unittest.decorators import tags from cloudcafe.common.tools.datagen import rand_name from cloudcafe.compute.common.exceptions import BadRequest, ItemNotFound from cloudroast.compute.fixtures import ComputeAdminFixture class DeleteFlavorTest(ComputeAdminFixture): @classmethod def setUpClass(...
cloudroast/compute/admin_api/flavors/test_delete_flavor.py
from cafe.drivers.unittest.decorators import tags from cloudcafe.common.tools.datagen import rand_name from cloudcafe.compute.common.exceptions import BadRequest, ItemNotFound from cloudroast.compute.fixtures import ComputeAdminFixture class DeleteFlavorTest(ComputeAdminFixture): @classmethod def setUpClass(...
0.741206
0.308229
from __future__ import absolute_import, division, print_function, unicode_literals from itertools import chain from nose.tools import eq_, raises from six.moves import xrange from smarkets.streaming_api.framing import ( frame_decode_all, frame_encode, IncompleteULEB128, uleb128_decode, uleb128_encode, ) test_d...
smarkets/tests/streaming_api/framing.py
from __future__ import absolute_import, division, print_function, unicode_literals from itertools import chain from nose.tools import eq_, raises from six.moves import xrange from smarkets.streaming_api.framing import ( frame_decode_all, frame_encode, IncompleteULEB128, uleb128_decode, uleb128_encode, ) test_d...
0.736685
0.30641
import komand import time from .schema import UsersAddedRemovedFromGroupInput, UsersAddedRemovedFromGroupOutput, Input, Output, Component # Custom imports below from komand.exceptions import PluginException from komand_okta.util import helpers class UsersAddedRemovedFromGroup(komand.Trigger): def __init__(self):...
okta/komand_okta/triggers/users_added_removed_from_group/trigger.py
import komand import time from .schema import UsersAddedRemovedFromGroupInput, UsersAddedRemovedFromGroupOutput, Input, Output, Component # Custom imports below from komand.exceptions import PluginException from komand_okta.util import helpers class UsersAddedRemovedFromGroup(komand.Trigger): def __init__(self):...
0.389663
0.113826
import re import os import json import argparse import traceback import subprocess """ This tool will invoke checked-c-convert on a compile_commands.json database. It contains some work-arounds for cmake+nmake generated compile_commands.json files, where the files are malformed. """ SLASH = os.sep # to separate mul...
tools/checked-c-convert/utils/convert-commands.py
import re import os import json import argparse import traceback import subprocess """ This tool will invoke checked-c-convert on a compile_commands.json database. It contains some work-arounds for cmake+nmake generated compile_commands.json files, where the files are malformed. """ SLASH = os.sep # to separate mul...
0.216342
0.083965
import sys # insert at 1, 0 is the script path (or '' in REPL) sys.path.insert(1, '../') # %% from exh import * from exh.exts.focus import * # %% """ # Construction and evaluation """ f = Focus(a | b, [b]) assignment = np.array([ [True, True], [True, False], [False, True], [False, False] ]) assert((f.eva...
tests/focus.py
import sys # insert at 1, 0 is the script path (or '' in REPL) sys.path.insert(1, '../') # %% from exh import * from exh.exts.focus import * # %% """ # Construction and evaluation """ f = Focus(a | b, [b]) assignment = np.array([ [True, True], [True, False], [False, True], [False, False] ]) assert((f.eva...
0.286568
0.565839
__all__ = [ 'DataLoaderTask', 'SimpleDataLoaderTask', 'TrainTask', 'SimpleTrainTask' ] from abc import abstractmethod from copy import deepcopy from logging import Logger from typing import List, Text, Tuple, Dict, Any from ..mixin import value from ..storages.basic import Storage from ..tasks.contain...
src/tasker/contrib/torch.py
__all__ = [ 'DataLoaderTask', 'SimpleDataLoaderTask', 'TrainTask', 'SimpleTrainTask' ] from abc import abstractmethod from copy import deepcopy from logging import Logger from typing import List, Text, Tuple, Dict, Any from ..mixin import value from ..storages.basic import Storage from ..tasks.contain...
0.828904
0.539347
import numpy as np import pytest from pandas import MultiIndex import pandas._testing as tm def test_numeric_compat(idx): with pytest.raises(TypeError, match="cannot perform __mul__"): idx * 1 with pytest.raises(TypeError, match="cannot perform __rmul__"): 1 * idx div_err = "cannot perf...
venv/Lib/site-packages/pandas/tests/indexes/multi/test_compat.py
import numpy as np import pytest from pandas import MultiIndex import pandas._testing as tm def test_numeric_compat(idx): with pytest.raises(TypeError, match="cannot perform __mul__"): idx * 1 with pytest.raises(TypeError, match="cannot perform __rmul__"): 1 * idx div_err = "cannot perf...
0.512205
0.662783
chars = [ [ "0000", "0000", "0000", "0000" ], [ "0100", "0100", "0000", "0100" ], [ "1010", "1010", "0000", "0000" ], [ "1010", "1111", "1010", "1111" ], [ "1110", "1100", "0110", "1110" ], [ "1001", "0010", "0100", "1001" ], [ "0110", "0110", "1010", "1111" ], [ "0100", "0100", "0000", "0000" ], [ "0010", "0100", "010...
font4x4.py
chars = [ [ "0000", "0000", "0000", "0000" ], [ "0100", "0100", "0000", "0100" ], [ "1010", "1010", "0000", "0000" ], [ "1010", "1111", "1010", "1111" ], [ "1110", "1100", "0110", "1110" ], [ "1001", "0010", "0100", "1001" ], [ "0110", "0110", "1010", "1111" ], [ "0100", "0100", "0000", "0000" ], [ "0010", "0100", "010...
0.275812
0.391755
import gzip import io import json import time import sys def decompress(inputBytes): with io.BytesIO() as bio: with io.BytesIO(inputBytes) as stream: decompressor = gzip.GzipFile(fileobj=stream, mode='r') while True: # until EOF chunk = decompressor.read(...
tools/save_gzipper.py
import gzip import io import json import time import sys def decompress(inputBytes): with io.BytesIO() as bio: with io.BytesIO(inputBytes) as stream: decompressor = gzip.GzipFile(fileobj=stream, mode='r') while True: # until EOF chunk = decompressor.read(...
0.144239
0.072112
import os import re def update_repository_name(repository): """Update given repository name so it won't contain any prefix(es).""" lastSlash = repository.rfind("/") # make sure we use just the repo name if lastSlash >= 0 and lastSlash < len(repository) - 1: return repository[1 + lastSlash:] ...
dashboard/src/git_utils.py
import os import re def update_repository_name(repository): """Update given repository name so it won't contain any prefix(es).""" lastSlash = repository.rfind("/") # make sure we use just the repo name if lastSlash >= 0 and lastSlash < len(repository) - 1: return repository[1 + lastSlash:] ...
0.523908
0.093844
import json import types import itertools import torch import numpy as np from train import argument_parser, parse_args, configure from train import get_validation_dataset, get_validation_iterator from train import build_net from diora.logging.configuration import get_logger try: import faiss from faiss im...
pytorch/diora/scripts/phrase_embed.py
import json import types import itertools import torch import numpy as np from train import argument_parser, parse_args, configure from train import get_validation_dataset, get_validation_iterator from train import build_net from diora.logging.configuration import get_logger try: import faiss from faiss im...
0.70304
0.32861
import requests from requests.auth import HTTPBasicAuth from ..resources.resource import Resource class Products(Resource): def __init__(self): super().__init__("products") def activate_product(self, id): return requests.post(self.config.base_url + self.path + '/' + str(id), ...
picqer_client_python/resources/products.py
import requests from requests.auth import HTTPBasicAuth from ..resources.resource import Resource class Products(Resource): def __init__(self): super().__init__("products") def activate_product(self, id): return requests.post(self.config.base_url + self.path + '/' + str(id), ...
0.347426
0.045016
from collections import namedtuple from django.db import models from django.test import TestCase from rest_framework.viewsets import ModelViewSet from rest_framework_nested.routers import SimpleRouter, NestedSimpleRouter from tests.helpers import get_regex_pattern def pattern_from_url(url_pattern): """ Finds...
tests/test_routers.py
from collections import namedtuple from django.db import models from django.test import TestCase from rest_framework.viewsets import ModelViewSet from rest_framework_nested.routers import SimpleRouter, NestedSimpleRouter from tests.helpers import get_regex_pattern def pattern_from_url(url_pattern): """ Finds...
0.800926
0.298364
import os import sys import subprocess from workflow import Workflow3 as Workflow, MATCH_SUBSTRING from workflow.background import run_in_background import cask_actions import helpers GITHUB_SLUG = 'fniephaus/alfred-homebrew' OPEN_HELP = 'open https://github.com/fniephaus/alfred-homebrew && exit' def execute(wf, ...
src/cask.py
import os import sys import subprocess from workflow import Workflow3 as Workflow, MATCH_SUBSTRING from workflow.background import run_in_background import cask_actions import helpers GITHUB_SLUG = 'fniephaus/alfred-homebrew' OPEN_HELP = 'open https://github.com/fniephaus/alfred-homebrew && exit' def execute(wf, ...
0.315314
0.083928
import argparse import collections import datetime import json import progress.bar import sqlalchemy as sa import sqlalchemy.orm as orm import _sqlalchemy.models as m def bar(label, total): return progress.bar.Bar(label[:32].ljust(32), max=total) def bulk_insert(db, label, data, into): label = f"Creatin...
_sqlalchemy/loaddata.py
import argparse import collections import datetime import json import progress.bar import sqlalchemy as sa import sqlalchemy.orm as orm import _sqlalchemy.models as m def bar(label, total): return progress.bar.Bar(label[:32].ljust(32), max=total) def bulk_insert(db, label, data, into): label = f"Creatin...
0.350421
0.241165
from __future__ import division import numpy as np #============================================================================== # The hat function #============================================================================== def hat(x): return -npHeaviside(x) * (-np.pi+x)/np.pi + npHeaviside(-x) * (np.pi+...
Math_Apps/Fourier_series_approximation/fourier_functions.py
from __future__ import division import numpy as np #============================================================================== # The hat function #============================================================================== def hat(x): return -npHeaviside(x) * (-np.pi+x)/np.pi + npHeaviside(-x) * (np.pi+...
0.896597
0.544135
import sys import hydra import torch from omegaconf.listconfig import ListConfig import logging from pathlib import Path log = logging.getLogger(__name__) # https://github.com/pytorch/examples/blob/8df8e747857261ea481e0b2492413d52bf7cc3a8/imagenet/main.py#L363 class AverageMeter(object): """Computes and stores ...
utils/helper.py
import sys import hydra import torch from omegaconf.listconfig import ListConfig import logging from pathlib import Path log = logging.getLogger(__name__) # https://github.com/pytorch/examples/blob/8df8e747857261ea481e0b2492413d52bf7cc3a8/imagenet/main.py#L363 class AverageMeter(object): """Computes and stores ...
0.612078
0.167151
import os import re import sys from setuptools import find_packages, setup PKG = "hy" VERSIONFILE = os.path.join(PKG, "version.py") verstr = "unknown" try: verstrline = open(VERSIONFILE, "rt").read() except EnvironmentError: pass # Okay, there is no version file. else: VSRE = r"^__version__ = ['\"]([^'\...
setup.py
import os import re import sys from setuptools import find_packages, setup PKG = "hy" VERSIONFILE = os.path.join(PKG, "version.py") verstr = "unknown" try: verstrline = open(VERSIONFILE, "rt").read() except EnvironmentError: pass # Okay, there is no version file. else: VSRE = r"^__version__ = ['\"]([^'\...
0.232833
0.116011
from ludwig.backend.base import Backend, LocalTrainingMixin from ludwig.constants import NAME, PARQUET, PREPROCESSING from ludwig.data.dataframe.dask import DaskEngine from ludwig.data.dataset.partitioned import PartitionedDataset from ludwig.models.predictor import BasePredictor, Predictor, get_output_columns class...
ludwig/backend/dask.py
from ludwig.backend.base import Backend, LocalTrainingMixin from ludwig.constants import NAME, PARQUET, PREPROCESSING from ludwig.data.dataframe.dask import DaskEngine from ludwig.data.dataset.partitioned import PartitionedDataset from ludwig.models.predictor import BasePredictor, Predictor, get_output_columns class...
0.636127
0.203787
import glob import os import sys import warnings from typing import Optional import pkginfo class Installed(pkginfo.Installed): def read(self) -> Optional[str]: opj = os.path.join if self.package is not None: package = self.package.__package__ if package is None: ...
venv/Lib/site-packages/twine/_installed.py
import glob import os import sys import warnings from typing import Optional import pkginfo class Installed(pkginfo.Installed): def read(self) -> Optional[str]: opj = os.path.join if self.package is not None: package = self.package.__package__ if package is None: ...
0.372049
0.06148
from bson import ObjectId from app.api.data.command.UserMongoCommandRepository import UserMongoCommandRepository from app.api.domain.models.User import User from app.api.domain.services.data.command.errors.CommandError import CommandError from tests.integration.PdbMongoIntegrationTestBase import PdbMongoIntegrationTes...
app/tests/integration/UserMongoCommandRepositoryIntegrationTest.py
from bson import ObjectId from app.api.data.command.UserMongoCommandRepository import UserMongoCommandRepository from app.api.domain.models.User import User from app.api.domain.services.data.command.errors.CommandError import CommandError from tests.integration.PdbMongoIntegrationTestBase import PdbMongoIntegrationTes...
0.384912
0.149345
import logging import torchvision.transforms import torchvision.utils import thelper.utils logger = logging.getLogger(__name__) def load_transforms(stages, avoid_transform_wrapper=False): """Loads a transformation pipeline from a list of stages. Each entry in the provided list will be considered a stage i...
thelper/transforms/utils.py
import logging import torchvision.transforms import torchvision.utils import thelper.utils logger = logging.getLogger(__name__) def load_transforms(stages, avoid_transform_wrapper=False): """Loads a transformation pipeline from a list of stages. Each entry in the provided list will be considered a stage i...
0.86674
0.697107
__all__ = [ 'CHORDS', 'CHORD_TABS', 'UkuleleNoteError', 'UkuleleChordError', 'get_chord', 'get_note' ] class UkuleleNoteError(Exception) : pass class UkuleleChordError(Exception) : pass def get_note(string, fret) : if abs(string) < len(FRETS) : if abs(fret) < len(FRETS[string...
psox/ukulele.py
__all__ = [ 'CHORDS', 'CHORD_TABS', 'UkuleleNoteError', 'UkuleleChordError', 'get_chord', 'get_note' ] class UkuleleNoteError(Exception) : pass class UkuleleChordError(Exception) : pass def get_note(string, fret) : if abs(string) < len(FRETS) : if abs(fret) < len(FRETS[string...
0.361052
0.325789
__authors__ = [ '"Madhusudan.C.S" <<EMAIL>>', ] from datetime import datetime from datetime import timedelta from google.appengine.ext import db from google.appengine.api import users from fixture import DataSet class UserData(DataSet): class all_admin: key_name = '<EMAIL>' link_id = 'super_admin' ...
src/melange/src/tests/datasets.py
__authors__ = [ '"Madhusudan.C.S" <<EMAIL>>', ] from datetime import datetime from datetime import timedelta from google.appengine.ext import db from google.appengine.api import users from fixture import DataSet class UserData(DataSet): class all_admin: key_name = '<EMAIL>' link_id = 'super_admin' ...
0.336658
0.0745
import argparse import logging import sys import time import numpy as np import torch import torch.nn as nn import torch.nn.functional as F import torchvision from torchvision import datasets, transforms from torch.utils.data import DataLoader, Dataset from mnist_net import mnist_net logger = logging.getLogger(__nam...
pytorch_ares/third_party/fast_adversarial/MNIST/evaluate_mnist.py
import argparse import logging import sys import time import numpy as np import torch import torch.nn as nn import torch.nn.functional as F import torchvision from torchvision import datasets, transforms from torch.utils.data import DataLoader, Dataset from mnist_net import mnist_net logger = logging.getLogger(__nam...
0.57523
0.431105
import datetime import os import sys from extension.src.ActionHandler import ActionHandler from extension.src.EnvLayer import EnvLayer from extension.src.EnvHealthManager import EnvHealthManager from extension.src.RuntimeContextHandler import RuntimeContextHandler from extension.src.TelemetryWriter import TelemetryWri...
src/extension/src/__main__.py
import datetime import os import sys from extension.src.ActionHandler import ActionHandler from extension.src.EnvLayer import EnvLayer from extension.src.EnvHealthManager import EnvHealthManager from extension.src.RuntimeContextHandler import RuntimeContextHandler from extension.src.TelemetryWriter import TelemetryWri...
0.285571
0.041269
from unittest import mock from openstackclient.common import module as osc_module from openstackclient.tests.unit import fakes from openstackclient.tests.unit import utils # NOTE(dtroyer): module_1 must match the version list filter (not --all) # currently == '*client*' module_name_1 = 'fakeclient' mo...
openstackclient/tests/unit/common/test_module.py
from unittest import mock from openstackclient.common import module as osc_module from openstackclient.tests.unit import fakes from openstackclient.tests.unit import utils # NOTE(dtroyer): module_1 must match the version list filter (not --all) # currently == '*client*' module_name_1 = 'fakeclient' mo...
0.487795
0.336944
from __future__ import absolute_import from __future__ import division from __future__ import print_function from __future__ import unicode_literals __author__ = "d01" __email__ = "<EMAIL>" __copyright__ = "Copyright (C) 2016, <NAME>" __license__ = "MIT" __version__ = "0.1.0" __date__ = "2016-04-01" # Created: 2016-03...
paps_settings/settable_plugin.py
from __future__ import absolute_import from __future__ import division from __future__ import print_function from __future__ import unicode_literals __author__ = "d01" __email__ = "<EMAIL>" __copyright__ = "Copyright (C) 2016, <NAME>" __license__ = "MIT" __version__ = "0.1.0" __date__ = "2016-04-01" # Created: 2016-03...
0.678007
0.081923
import numpy as np from PuzzleLib.Backend import gpuarray from PuzzleLib.Containers.Sequential import Sequential from PuzzleLib.Containers.Parallel import Parallel from PuzzleLib.Modules.Conv2D import Conv2D from PuzzleLib.Modules.BatchNorm2D import BatchNorm2D from PuzzleLib.Modules.Activation import Activation, re...
Models/Nets/Inception.py
import numpy as np from PuzzleLib.Backend import gpuarray from PuzzleLib.Containers.Sequential import Sequential from PuzzleLib.Containers.Parallel import Parallel from PuzzleLib.Modules.Conv2D import Conv2D from PuzzleLib.Modules.BatchNorm2D import BatchNorm2D from PuzzleLib.Modules.Activation import Activation, re...
0.489259
0.316554
import pytest from netaddr import * import sys import time import ipaddress from ansible_host import AnsibleHost from ptf_runner import ptf_runner def generate_ips(num, prefix, exclude_ips): """ Generate random ips within prefix """ prefix = IPNetwork(prefix) exclude_ips.append(prefix.broadcast)...
tests/test_bgp_speaker.py
import pytest from netaddr import * import sys import time import ipaddress from ansible_host import AnsibleHost from ptf_runner import ptf_runner def generate_ips(num, prefix, exclude_ips): """ Generate random ips within prefix """ prefix = IPNetwork(prefix) exclude_ips.append(prefix.broadcast)...
0.283881
0.167083
import os import inspect from ..utils.import_helper import ImportHelper from ..core.errors import ImproperlyConfigured from . import global_settings from ..utils.lazy_obj import empty, LazyObject __all__ = ['settings', 'SettingsFileFinder'] class SettingsFileFinder(object): def __init__(self, settings_file_name=...
stest/conf/__init__.py
import os import inspect from ..utils.import_helper import ImportHelper from ..core.errors import ImproperlyConfigured from . import global_settings from ..utils.lazy_obj import empty, LazyObject __all__ = ['settings', 'SettingsFileFinder'] class SettingsFileFinder(object): def __init__(self, settings_file_name=...
0.324663
0.09118
from sys import version_info if version_info >= (3,0,0): new_instancemethod = lambda func, inst, cls: _GccIter.SWIG_PyInstanceMethod_New(func) else: from new import instancemethod as new_instancemethod if version_info >= (2,6,0): def swig_import_helper(): from os.path import dirname imp...
Lib/site-packages/OCC/GccIter.py
from sys import version_info if version_info >= (3,0,0): new_instancemethod = lambda func, inst, cls: _GccIter.SWIG_PyInstanceMethod_New(func) else: from new import instancemethod as new_instancemethod if version_info >= (2,6,0): def swig_import_helper(): from os.path import dirname imp...
0.154153
0.081447
import json # Used when TRACE=jsonp import os # Used to get the TRACE environment variable import re # Used when TRACE=jsonp import sys # Used to smooth over the range / xrange issue. import aug_avl # Python 3 doesn't have xrange, and range behaves like xrange. if sys.version_info >= (3,): xrange = r...
Problem sets/PS3/circuit2/circuit2.py
import json # Used when TRACE=jsonp import os # Used to get the TRACE environment variable import re # Used when TRACE=jsonp import sys # Used to smooth over the range / xrange issue. import aug_avl # Python 3 doesn't have xrange, and range behaves like xrange. if sys.version_info >= (3,): xrange = r...
0.651577
0.467089
from typing import Type import coreapi import coreschema from django.db.models import Choices, IntegerChoices from rest_framework.filters import BaseFilterBackend class BaseKeyFilter(BaseFilterBackend): """Filter by foreign or primary key implementation.""" key: str def _get_pk_parameter(self, params):...
django_boilerplate/common/drf_helpers/filters.py
from typing import Type import coreapi import coreschema from django.db.models import Choices, IntegerChoices from rest_framework.filters import BaseFilterBackend class BaseKeyFilter(BaseFilterBackend): """Filter by foreign or primary key implementation.""" key: str def _get_pk_parameter(self, params):...
0.845017
0.206844
import re from typing import List from bs4 import BeautifulSoup from ...orders.pending.models import PendingOrder from ...utils.input import InputHelper def parse_pending_orders(account_id: int, pending_orders_html: str) -> List[PendingOrder]: pending_orders = [] soup = BeautifulSoup(pending_orders_html, '...
hargreaves/orders/pending/parsers.py
import re from typing import List from bs4 import BeautifulSoup from ...orders.pending.models import PendingOrder from ...utils.input import InputHelper def parse_pending_orders(account_id: int, pending_orders_html: str) -> List[PendingOrder]: pending_orders = [] soup = BeautifulSoup(pending_orders_html, '...
0.404743
0.144873
from __future__ import absolute_import, print_function from glob import glob from friedrich.lightcurve import (LightCurve, generate_lc_depth, kepler17_params_db) from friedrich.fitting import peak_finder, summed_gaussians, gaussian import matplotlib.pyplot as plt import numpy as np f...
example_k17.py
from __future__ import absolute_import, print_function from glob import glob from friedrich.lightcurve import (LightCurve, generate_lc_depth, kepler17_params_db) from friedrich.fitting import peak_finder, summed_gaussians, gaussian import matplotlib.pyplot as plt import numpy as np f...
0.769946
0.354517
from typing import Optional, Sequence import numpy as np from fastmri.data.subsample import MaskFunc, RandomMaskFunc def create_mask_for_mask_type( mask_type_str: str, center_fractions: Sequence[float], accelerations: Sequence[int], skip_low_freqs: bool, ) -> MaskFunc: """ Creates a mask of t...
fastmri_examples/adaptive_varnet/subsample.py
from typing import Optional, Sequence import numpy as np from fastmri.data.subsample import MaskFunc, RandomMaskFunc def create_mask_for_mask_type( mask_type_str: str, center_fractions: Sequence[float], accelerations: Sequence[int], skip_low_freqs: bool, ) -> MaskFunc: """ Creates a mask of t...
0.980243
0.831554
from selenium import webdriver from keyboard import press from selenium.webdriver.common.keys import Keys import time import pandas as pd import keyboard import random pause_pt =False # setpause value to false def pause_func(): #function to stop loop global pause_pt pause_pt = True #s...
msg_automation.py
from selenium import webdriver from keyboard import press from selenium.webdriver.common.keys import Keys import time import pandas as pd import keyboard import random pause_pt =False # setpause value to false def pause_func(): #function to stop loop global pause_pt pause_pt = True #s...
0.165762
0.056288
from __future__ import absolute_import import six from django.core import mail from sentry.mail.actions import ActionTargetType, NotifyEmailAction, NotifyEmailForm from sentry.models import OrganizationMember, OrganizationMemberTeam, Rule from sentry.testutils import TestCase from sentry.testutils.cases import RuleTe...
tests/sentry/mail/test_actions.py
from __future__ import absolute_import import six from django.core import mail from sentry.mail.actions import ActionTargetType, NotifyEmailAction, NotifyEmailForm from sentry.models import OrganizationMember, OrganizationMemberTeam, Rule from sentry.testutils import TestCase from sentry.testutils.cases import RuleTe...
0.44071
0.275501
# template for calling functions in another file def print_function(): print("I'm in another file :)") def while_loop(max_number=10): my_list = [] i = 1 while i <= max_number: my_list.append(i) i += 1 print(my_list) def while_loop2(neg_number): my_list1 = [] i = 1 ...
Lab5/functions.py
# template for calling functions in another file def print_function(): print("I'm in another file :)") def while_loop(max_number=10): my_list = [] i = 1 while i <= max_number: my_list.append(i) i += 1 print(my_list) def while_loop2(neg_number): my_list1 = [] i = 1 ...
0.134037
0.182044
import logging import os import sys try: import cPickle as pickle except ImportError: # Python 3.x import pickle import colorlog import numpy as np from PIL import Image logger = logging.getLogger() logger.setLevel(colorlog.colorlog.logging.INFO) handler = colorlog.StreamHandler() handler.setFormatter(col...
MP4/mp4_histogram_training.py
import logging import os import sys try: import cPickle as pickle except ImportError: # Python 3.x import pickle import colorlog import numpy as np from PIL import Image logger = logging.getLogger() logger.setLevel(colorlog.colorlog.logging.INFO) handler = colorlog.StreamHandler() handler.setFormatter(col...
0.391057
0.209025
import json import logging import uuid from typing import Type, TypeVar from dataclasses import replace from server.engine.action_result import ActionResult from server.engine.ending import Ending from server.engine.location import Location from server.engine.object import AdventureObject, Activateable # Generic var...
server/engine/scenario.py
import json import logging import uuid from typing import Type, TypeVar from dataclasses import replace from server.engine.action_result import ActionResult from server.engine.ending import Ending from server.engine.location import Location from server.engine.object import AdventureObject, Activateable # Generic var...
0.78037
0.179135
from bs4 import BeautifulSoup from Spiders.spiders.lottery.lottery_model import LotteryCNSSQ from Spiders.common import config, database, utils, utils_html def get_page_num(url, headers): """获取url总页数""" soup = BeautifulSoup(utils_html.getPage(url, headers).content, 'lxml') pagenums = soup.select('body > ...
Learn_pkgs/learn/BeautifulSoup/spider_ssq.py
from bs4 import BeautifulSoup from Spiders.spiders.lottery.lottery_model import LotteryCNSSQ from Spiders.common import config, database, utils, utils_html def get_page_num(url, headers): """获取url总页数""" soup = BeautifulSoup(utils_html.getPage(url, headers).content, 'lxml') pagenums = soup.select('body > ...
0.246715
0.120724
from __future__ import absolute_import from __future__ import division from __future__ import print_function import numpy as np from tensorflow.python.eager import def_function from tensorflow.python.estimator.estimator import Estimator from tensorflow.python.estimator.model_fn import EstimatorSpec from tensorflow.py...
tensorflow/core/platform/ram_file_system_test.py
from __future__ import absolute_import from __future__ import division from __future__ import print_function import numpy as np from tensorflow.python.eager import def_function from tensorflow.python.estimator.estimator import Estimator from tensorflow.python.estimator.model_fn import EstimatorSpec from tensorflow.py...
0.759047
0.32021