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 os import subprocess from collections import OrderedDict from mock import patch, call, MagicMock, Mock os.environ['JUJU_UNIT_NAME'] = 'cinder' import cinder_utils as cinder_utils from test_utils import CharmTestCase TO_PATCH = [ # helpers.core.hookenv 'config', 'log', 'juju_log', 'relati...
unit_tests/test_cinder_utils.py
import os import subprocess from collections import OrderedDict from mock import patch, call, MagicMock, Mock os.environ['JUJU_UNIT_NAME'] = 'cinder' import cinder_utils as cinder_utils from test_utils import CharmTestCase TO_PATCH = [ # helpers.core.hookenv 'config', 'log', 'juju_log', 'relati...
0.499512
0.131368
from zipfile import Path import json def search_zip(folder: Path, file_type: str) -> list[Path]: """ Recursively search a zip file by iterating through its files and subfolders. Paths are basically just fancy strings with some extra features, like checking if they are directories or files. Args: ...
assignments/Lesson 18- Recursion/find_password.py
from zipfile import Path import json def search_zip(folder: Path, file_type: str) -> list[Path]: """ Recursively search a zip file by iterating through its files and subfolders. Paths are basically just fancy strings with some extra features, like checking if they are directories or files. Args: ...
0.858881
0.461502
from __future__ import annotations def hsv_to_rgb(hue: float, saturation: float, value: float) -> list[int]: """ Conversion from the HSV-representation to the RGB-representation. Expected RGB-values taken from https://www.rapidtables.com/convert/color/hsv-to-rgb.html >>> hsv_to_rgb(0, 0, 0...
conversions/rgb_hsv_conversion.py
from __future__ import annotations def hsv_to_rgb(hue: float, saturation: float, value: float) -> list[int]: """ Conversion from the HSV-representation to the RGB-representation. Expected RGB-values taken from https://www.rapidtables.com/convert/color/hsv-to-rgb.html >>> hsv_to_rgb(0, 0, 0...
0.87724
0.503113
import os from functools import partial from threading import RLock from types import FunctionType from typing import Any, Optional, Type from haps.exceptions import ConfigurationError, UnknownConfigVariable _NONE = object() def _env_resolver(var_name: str, env_name: str = None, default: Any = _NO...
haps/config.py
import os from functools import partial from threading import RLock from types import FunctionType from typing import Any, Optional, Type from haps.exceptions import ConfigurationError, UnknownConfigVariable _NONE = object() def _env_resolver(var_name: str, env_name: str = None, default: Any = _NO...
0.745954
0.079317
from nitorch import spatial, io from nitorch.core import py, utils import os def pool(inp, window=3, stride=None, method='mean', dim=3, output=None, device=None): """Pool a ND volume, while preserving the orientation matrices. Parameters ---------- inp : str or (tensor, tensor) Eithe...
nitorch/tools/misc/pool/main.py
from nitorch import spatial, io from nitorch.core import py, utils import os def pool(inp, window=3, stride=None, method='mean', dim=3, output=None, device=None): """Pool a ND volume, while preserving the orientation matrices. Parameters ---------- inp : str or (tensor, tensor) Eithe...
0.90776
0.613931
x00 = 37107287533902102798797998220837590246510135740250 x01 = 46376937677490009712648124896970078050417018260538 x02 = 74324986199524741059474233309513058123726617309629 x03 = 91942213363574161572522430563301811072406154908250 x04 = 23067588207539346171171980310421047513778063246676 x05 = 8926167069662363382013637841...
examples/ProjectEuler013.py
x00 = 37107287533902102798797998220837590246510135740250 x01 = 46376937677490009712648124896970078050417018260538 x02 = 74324986199524741059474233309513058123726617309629 x03 = 91942213363574161572522430563301811072406154908250 x04 = 23067588207539346171171980310421047513778063246676 x05 = 8926167069662363382013637841...
0.133528
0.269067
from __future__ import absolute_import from __future__ import division from __future__ import print_function import cv2 import numpy as np # Error metrics def compute_accel(joints): """ Computes acceleration of 3D joints. Args: joints (Nx25x3). Returns: Accelerations (N-2). """...
src/evaluation/eval_util.py
from __future__ import absolute_import from __future__ import division from __future__ import print_function import cv2 import numpy as np # Error metrics def compute_accel(joints): """ Computes acceleration of 3D joints. Args: joints (Nx25x3). Returns: Accelerations (N-2). """...
0.943996
0.516656
from .protocols.http import request as http_request, request_handler as http_request_handler from .protocols.ws import request_handler as ws_request_handler, request as ws_request from .protocols.grpc import request as grpc_request from .dbapi import request as dbo_request from .protocols.proxy import tunnel_handler fr...
aquests/request_builder.py
from .protocols.http import request as http_request, request_handler as http_request_handler from .protocols.ws import request_handler as ws_request_handler, request as ws_request from .protocols.grpc import request as grpc_request from .dbapi import request as dbo_request from .protocols.proxy import tunnel_handler fr...
0.280222
0.042523
DEBUG = True TEMPLATE_DEBUG = DEBUG ADMINS = ( # ('<NAME>', '<EMAIL>'), ) CACHE_BACKEND = 'locmem:///' MANAGERS = ADMINS # Local time zone for this installation. Choices can be found here: # http://en.wikipedia.org/wiki/List_of_tz_zones_by_name # although not all choices may be avilable on all operating system...
src/token_auth/settings.py
DEBUG = True TEMPLATE_DEBUG = DEBUG ADMINS = ( # ('<NAME>', '<EMAIL>'), ) CACHE_BACKEND = 'locmem:///' MANAGERS = ADMINS # Local time zone for this installation. Choices can be found here: # http://en.wikipedia.org/wiki/List_of_tz_zones_by_name # although not all choices may be avilable on all operating system...
0.49707
0.070113
''' Class for work with testing Modules ''' import os import sys import time import MySQLdb from .fmod_db import FModDB class MySQL(FModDB): ''' Class for work with DB ''' def __init__ (self, config, pathTmp, verbose): """ Initialising object Parameters ---------- config : dict config of ...
src/mysql.py
''' Class for work with testing Modules ''' import os import sys import time import MySQLdb from .fmod_db import FModDB class MySQL(FModDB): ''' Class for work with DB ''' def __init__ (self, config, pathTmp, verbose): """ Initialising object Parameters ---------- config : dict config of ...
0.256459
0.064772
import pygame from pygame.locals import * import os # Constantes BLANCO = (255,255,255) AMARILLO = (255,255,0) NEGRO = (0,0,0) class Pelota(object): def __init__(self): self.x = 400 self.y = 300 self.dx = 5 self.dy = 5 ruta_sonido = os.path.join('data','sonidoPelota.wav')...
pygame/pong/pong [full]/gamelib.py
import pygame from pygame.locals import * import os # Constantes BLANCO = (255,255,255) AMARILLO = (255,255,0) NEGRO = (0,0,0) class Pelota(object): def __init__(self): self.x = 400 self.y = 300 self.dx = 5 self.dy = 5 ruta_sonido = os.path.join('data','sonidoPelota.wav')...
0.247169
0.1602
import os import sys import argparse from loguru import logger from modules import apps from modules import config from modules import arg_parser from modules.reporter import Reporter, BundleReporter from modules.agent import Agent, ActivityAgent, MonkeyAgent from modules.done_list_handler import Status from modules.en...
main.py
import os import sys import argparse from loguru import logger from modules import apps from modules import config from modules import arg_parser from modules.reporter import Reporter, BundleReporter from modules.agent import Agent, ActivityAgent, MonkeyAgent from modules.done_list_handler import Status from modules.en...
0.164852
0.067056
from __future__ import division from __future__ import unicode_literals import time import numpy as np import torch import torch.nn as nn import collections from deepchem.utils.save import log from deepchem.metrics import to_one_hot from deepchem.metrics import from_one_hot from deepchem.models.torchgraph...
torch_progressive_multitask.py
from __future__ import division from __future__ import unicode_literals import time import numpy as np import torch import torch.nn as nn import collections from deepchem.utils.save import log from deepchem.metrics import to_one_hot from deepchem.metrics import from_one_hot from deepchem.models.torchgraph...
0.885594
0.406833
import copy from logging import getLogger from collections import deque import os import gym import numpy as np import cv2 from pfrl.wrappers import ContinuingTimeLimit, RandomizeAction, Monitor from pfrl.wrappers.atari_wrappers import ScaledFloatFrame, LazyFrames cv2.ocl.setUseOpenCL(False) logger = getLogger(__nam...
mod/env_wrappers.py
import copy from logging import getLogger from collections import deque import os import gym import numpy as np import cv2 from pfrl.wrappers import ContinuingTimeLimit, RandomizeAction, Monitor from pfrl.wrappers.atari_wrappers import ScaledFloatFrame, LazyFrames cv2.ocl.setUseOpenCL(False) logger = getLogger(__nam...
0.810291
0.285915
from abc import ABC from tempfile import NamedTemporaryFile from tempfile import TemporaryDirectory from typing import Union from fabric import Connection from crud.crud_config import crud_ssh_config from crud.crud_module import crud_redirector from crud.crud_module import crud_team_server from db.session import sess...
src/backend/tasks/module.py
from abc import ABC from tempfile import NamedTemporaryFile from tempfile import TemporaryDirectory from typing import Union from fabric import Connection from crud.crud_config import crud_ssh_config from crud.crud_module import crud_redirector from crud.crud_module import crud_team_server from db.session import sess...
0.560373
0.062217
from django.db import migrations, models class Migration(migrations.Migration): dependencies = [ ('lookup_hub', '0002_add_dictionary'), ] operations = [ migrations.AlterModelOptions( name='category', options={'ordering': ('order',), 'verbose_name_plural': 'Catego...
thomann/lookup_hub/migrations/0003_auto_20210729_1146.py
from django.db import migrations, models class Migration(migrations.Migration): dependencies = [ ('lookup_hub', '0002_add_dictionary'), ] operations = [ migrations.AlterModelOptions( name='category', options={'ordering': ('order',), 'verbose_name_plural': 'Catego...
0.645902
0.164382
from homeassistant.const import ATTR_NAME from homeassistant.core import callback from homeassistant.helpers.entity import Entity from homeassistant.helpers.typing import HomeAssistantType, ConfigType, EventType from . import AutoBackup from .const import ( DOMAIN, EVENT_SNAPSHOTS_PURGED, EVENT_SNAPSHOT_SUC...
Configuration/custom_components/auto_backup/sensor.py
from homeassistant.const import ATTR_NAME from homeassistant.core import callback from homeassistant.helpers.entity import Entity from homeassistant.helpers.typing import HomeAssistantType, ConfigType, EventType from . import AutoBackup from .const import ( DOMAIN, EVENT_SNAPSHOTS_PURGED, EVENT_SNAPSHOT_SUC...
0.766818
0.191857
"""pypozyx.definitions.constants - contains all Pozyx constants, such as error definitions, delays, physical convertions.""" # Pozyx status returns POZYX_FAILURE = 0x0 POZYX_SUCCESS = 0x1 POZYX_TIMEOUT = 0x8 class PozyxConstants: # Pozyx serial buffer sizes MAX_BUF_SIZE = 100 MAX_SERIAL_SIZE = 28 # ...
Backend/Pozyx/pypozyx/definitions/constants.py
"""pypozyx.definitions.constants - contains all Pozyx constants, such as error definitions, delays, physical convertions.""" # Pozyx status returns POZYX_FAILURE = 0x0 POZYX_SUCCESS = 0x1 POZYX_TIMEOUT = 0x8 class PozyxConstants: # Pozyx serial buffer sizes MAX_BUF_SIZE = 100 MAX_SERIAL_SIZE = 28 # ...
0.583085
0.310302
import sys reload(sys) sys.setdefaultencoding('utf8') import copy from PIL import Image import re import urlparse from bs4 import BeautifulSoup from bs4.element import NavigableString sys.path.append("/home/dev/Repository/news/") from Tegenaria.tSpider.tSpider.middlewares.doraemonMiddleware import Doraemon from Tegenar...
Tegenaria/tSpider/tSpider/storeHtml/storeFiles.py
import sys reload(sys) sys.setdefaultencoding('utf8') import copy from PIL import Image import re import urlparse from bs4 import BeautifulSoup from bs4.element import NavigableString sys.path.append("/home/dev/Repository/news/") from Tegenaria.tSpider.tSpider.middlewares.doraemonMiddleware import Doraemon from Tegenar...
0.23118
0.07403
dataset_type = 'VOCDataset' data_root = 'data/processed/vin_dataVOC2012/' img_norm_cfg = dict(mean=[128, 128, 128], std=[60, 60, 60], to_rgb=True) albumentation_transforms = [ dict(type='ShiftScaleRotate', shift_limit=0.0625, scale_limit=0.0, rotate_limit=7, p=0.5), dict(type='RandomBrightnessContrast', brigh...
configs/mmdetection/dataset.py
dataset_type = 'VOCDataset' data_root = 'data/processed/vin_dataVOC2012/' img_norm_cfg = dict(mean=[128, 128, 128], std=[60, 60, 60], to_rgb=True) albumentation_transforms = [ dict(type='ShiftScaleRotate', shift_limit=0.0625, scale_limit=0.0, rotate_limit=7, p=0.5), dict(type='RandomBrightnessContrast', brigh...
0.467575
0.364664
def CoilSelectionUI(path_coilsys_folder, grid_col=4): from ipywidgets import GridspecLayout, Checkbox, Layout, Button, HBox from IPython.display import display import asyncio, time from .file import read_coil, coilsys_names def wait_for_change(widget1, widget2): future = asyncio.Future() ...
MHDpy/IPyUI.py
def CoilSelectionUI(path_coilsys_folder, grid_col=4): from ipywidgets import GridspecLayout, Checkbox, Layout, Button, HBox from IPython.display import display import asyncio, time from .file import read_coil, coilsys_names def wait_for_change(widget1, widget2): future = asyncio.Future() ...
0.50293
0.438124
import time import random import emoji import playsound escolha = input(str("Escreva pedra,papel ou tesoura: ")) escolha = escolha.strip().lower().rstrip() permissao = 1 emo = 0 emo1 = 0 if escolha == 'papel': vaiprojogo = "papel" emo = emoji.emojize(" :page_facing_up:", use_aliases=True) elif escolha == 'pedra...
45.py
import time import random import emoji import playsound escolha = input(str("Escreva pedra,papel ou tesoura: ")) escolha = escolha.strip().lower().rstrip() permissao = 1 emo = 0 emo1 = 0 if escolha == 'papel': vaiprojogo = "papel" emo = emoji.emojize(" :page_facing_up:", use_aliases=True) elif escolha == 'pedra...
0.079537
0.206994
import rospy import tf import ros import cv2 from cv_bridge import CvBridge, CvBridgeError from std_msgs.msg import String from nav_msgs.msg import Odometry, Path import tf as tft import math # bridge = CvBridge() cur_state = [0, 0, 0] DIRECTION_PATHS = [] for i in range(10): if i==0: # DIRECTION_PATHS....
knu_ws/src/knu_project/src/direction.py
import rospy import tf import ros import cv2 from cv_bridge import CvBridge, CvBridgeError from std_msgs.msg import String from nav_msgs.msg import Odometry, Path import tf as tft import math # bridge = CvBridge() cur_state = [0, 0, 0] DIRECTION_PATHS = [] for i in range(10): if i==0: # DIRECTION_PATHS....
0.26218
0.091626
import os import shutil import unittest from datetime import datetime from glob import iglob from unittest.mock import patch from click.testing import CliRunner from pdst.cli import cli def mocked_abspath(path): return f'/a/fake/data/path/{path}' def mocked_rename(old, new): print(f"(MOCK...
tests/test_cli_move.py
import os import shutil import unittest from datetime import datetime from glob import iglob from unittest.mock import patch from click.testing import CliRunner from pdst.cli import cli def mocked_abspath(path): return f'/a/fake/data/path/{path}' def mocked_rename(old, new): print(f"(MOCK...
0.301876
0.260892
import os import pytest import trio import time import warnings from .media_test_app import DemoTestApp warnings.filterwarnings( "ignore", message="numpy.ufunc size changed, may indicate binary incompatibility. " "Expected 192 from C header, got 216 from PyObject" ) os.environ['KIVY_USE_DEFAULTCON...
cpl_media/tests/conftest.py
import os import pytest import trio import time import warnings from .media_test_app import DemoTestApp warnings.filterwarnings( "ignore", message="numpy.ufunc size changed, may indicate binary incompatibility. " "Expected 192 from C header, got 216 from PyObject" ) os.environ['KIVY_USE_DEFAULTCON...
0.292393
0.099645
import numpy as np from matplotlib import pyplot as plt from scipy.optimize import minimize import sys import os from os.path import join as osjoin from pc_path import definir_path path_git, path_datos_global = definir_path() os.chdir(path_git) sys.path.append('./Software/Funcionales/') from funciones_data import lee...
Software/Estadística/MCMC/LCDM/Cosas viejas/MCMC_supernovas_LCDM_1params_loops.py
import numpy as np from matplotlib import pyplot as plt from scipy.optimize import minimize import sys import os from os.path import join as osjoin from pc_path import definir_path path_git, path_datos_global = definir_path() os.chdir(path_git) sys.path.append('./Software/Funcionales/') from funciones_data import lee...
0.237222
0.299733
import os from torch.utils.data import TensorDataset, DataLoader, Dataset, Sampler import torch import torch.nn as nn import torch.optim as optim import torch.nn.functional as F import numpy as np import pandas as pd from scipy.stats import pearsonr from tqdm import tqdm import scanpy as sc class Setting: """Para...
code/mtSC.py
import os from torch.utils.data import TensorDataset, DataLoader, Dataset, Sampler import torch import torch.nn as nn import torch.optim as optim import torch.nn.functional as F import numpy as np import pandas as pd from scipy.stats import pearsonr from tqdm import tqdm import scanpy as sc class Setting: """Para...
0.9003
0.569194
import pytest from testsuite.ui.views.admin.audience.application import ApplicationDetailView from testsuite.ui.views.admin.product.integration.policies import ProductPoliciesView, Policies from testsuite.ui.views.admin.product.integration.configuration import ProductConfigurationView from testsuite.ui.views.admin.pr...
testsuite/tests/ui/policies/test_referrer_policy.py
import pytest from testsuite.ui.views.admin.audience.application import ApplicationDetailView from testsuite.ui.views.admin.product.integration.policies import ProductPoliciesView, Policies from testsuite.ui.views.admin.product.integration.configuration import ProductConfigurationView from testsuite.ui.views.admin.pr...
0.575349
0.253705
from collections import deque from plistlib import * from operator import itemgetter import time, datetime, copy class device: TIMEOUT = 20 # Number of seconds before command times out WHITELIST = "ABCDEFGHIJKLMNOPQRSTUVWXYZabcdefghijklmnopqrstuvwxyz0123456789 " def __init__(self, newUDID, tuple): ...
server/device.py
from collections import deque from plistlib import * from operator import itemgetter import time, datetime, copy class device: TIMEOUT = 20 # Number of seconds before command times out WHITELIST = "ABCDEFGHIJKLMNOPQRSTUVWXYZabcdefghijklmnopqrstuvwxyz0123456789 " def __init__(self, newUDID, tuple): ...
0.265309
0.119459
import os import sys import imp import numpy as np import warnings warnings.filterwarnings("ignore") # Test for Torch def torch(test_models, model_path, img_path): results_o, results_d, op_sets = dict(), dict(), dict() from PIL import Image import torch import torchvision.models as models from tor...
test.py
import os import sys import imp import numpy as np import warnings warnings.filterwarnings("ignore") # Test for Torch def torch(test_models, model_path, img_path): results_o, results_d, op_sets = dict(), dict(), dict() from PIL import Image import torch import torchvision.models as models from tor...
0.448668
0.456955
from token import * class LexerError(Exception): def __init__(self, message): self.message = message class Lexer: def __init__(self, string): self.source = string self.start = 0 self.current = 0 self.tokens = [] self.length = len(string) def skipWhitespace(...
lexer.py
from token import * class LexerError(Exception): def __init__(self, message): self.message = message class Lexer: def __init__(self, string): self.source = string self.start = 0 self.current = 0 self.tokens = [] self.length = len(string) def skipWhitespace(...
0.45302
0.210097
from decimal import Decimal from orders.constants import OrderStatus from django.core.exceptions import ValidationError from django.db import transaction from django.db.models.aggregates import Sum from django.db.models.expressions import F from orders.models import Order, OrderProduct, Note from inventory.constants ...
ecommerce/apps/orders/logic.py
from decimal import Decimal from orders.constants import OrderStatus from django.core.exceptions import ValidationError from django.db import transaction from django.db.models.aggregates import Sum from django.db.models.expressions import F from orders.models import Order, OrderProduct, Note from inventory.constants ...
0.604049
0.14137
import copy import numpy as np def get_diff(x): """ Returns the edge represetnation Abs value of Edge representation of the image the simpliest way, only sum of differences in both directions Returns :param x: gets image :return: edge representation """ return np.abs(np.diff(x, axis=0...
code/segmentation/MELC/Client/Registration.py
import copy import numpy as np def get_diff(x): """ Returns the edge represetnation Abs value of Edge representation of the image the simpliest way, only sum of differences in both directions Returns :param x: gets image :return: edge representation """ return np.abs(np.diff(x, axis=0...
0.844377
0.759894
import sys import time import contextlib import collections _ENABLED = False @contextlib.contextmanager def profile(namespace, key): start = time.time() yield if _ENABLED: ProfileManager().increment(start, namespace, key) class ProfileManager(object): _singleton = {} def __init__(sel...
venv/lib/python3.7/site-packages/diffoscope/profiling.py
import sys import time import contextlib import collections _ENABLED = False @contextlib.contextmanager def profile(namespace, key): start = time.time() yield if _ENABLED: ProfileManager().increment(start, namespace, key) class ProfileManager(object): _singleton = {} def __init__(sel...
0.335677
0.104204
import struct from collections import namedtuple import petscii # From https://vice-emu.sourceforge.io/vice_17.html#SEC345 # fmt: off TRACK_START = ( -21, 0, 21, 42, 63, 84, 105, 126, 147, 168, 189, 210, 231, 252, 273, 294, 315, 336, 357, 376, 395, 414, 433, 452, 471, 490, 508, 526, 544, 562, 580, 598,...
disk.py
import struct from collections import namedtuple import petscii # From https://vice-emu.sourceforge.io/vice_17.html#SEC345 # fmt: off TRACK_START = ( -21, 0, 21, 42, 63, 84, 105, 126, 147, 168, 189, 210, 231, 252, 273, 294, 315, 336, 357, 376, 395, 414, 433, 452, 471, 490, 508, 526, 544, 562, 580, 598,...
0.501221
0.180829
import argparse import contextlib import logging from typing import Iterator, Set, Tuple from eth_enr import ENRAPI, ENRDB, ENRManager, default_identity_scheme_registry from eth_enr.exceptions import OldSequenceNumber from eth_typing import NodeID from eth_utils import encode_hex import trio from ddht.app import Base...
ddht/v5/crawl.py
import argparse import contextlib import logging from typing import Iterator, Set, Tuple from eth_enr import ENRAPI, ENRDB, ENRManager, default_identity_scheme_registry from eth_enr.exceptions import OldSequenceNumber from eth_typing import NodeID from eth_utils import encode_hex import trio from ddht.app import Base...
0.622459
0.08196
import json import math import random from string import ascii_letters from typing import Callable, Tuple import confluent_kafka import pytest from click.testing import CliRunner from confluent_kafka import OFFSET_END, Producer from pytest_cases import parametrize from esque.cli.commands import esque from esque.contr...
tests/integration/commands/test_get.py
import json import math import random from string import ascii_letters from typing import Callable, Tuple import confluent_kafka import pytest from click.testing import CliRunner from confluent_kafka import OFFSET_END, Producer from pytest_cases import parametrize from esque.cli.commands import esque from esque.contr...
0.627609
0.322846
class BaseItem: def __init_(self, name, item_id, page_url): self.name = name self.id = item_id self.page_url = page_url class ItemDrop: def __init__(self, enabled, level, max_level, leagues, areas, text): self.enabled = enabled self.level = level self.max_level ...
poe/models.py
class BaseItem: def __init_(self, name, item_id, page_url): self.name = name self.id = item_id self.page_url = page_url class ItemDrop: def __init__(self, enabled, level, max_level, leagues, areas, text): self.enabled = enabled self.level = level self.max_level ...
0.722625
0.105671
from struct import * from vmipl_aux.constants import Constants from vmipl_aux.helper import Helper class DataProbe (): def __init__(self, probe_type, output_channel): self.type = probe_type self.output_channel = output_channel self.group_id = 0 class ReadRegisterProbe (DataProbe): def __init__(self, probe...
front_end/vmipl/data_probes.py
from struct import * from vmipl_aux.constants import Constants from vmipl_aux.helper import Helper class DataProbe (): def __init__(self, probe_type, output_channel): self.type = probe_type self.output_channel = output_channel self.group_id = 0 class ReadRegisterProbe (DataProbe): def __init__(self, probe...
0.331012
0.162979
from pyrogram import Client, Filters import re import io import html import traceback import subprocess from contextlib import redirect_stdout from config import cmds from db import db from utils import meval @Client.on_message(Filters.regex(r'.*<py>.+</py>', re.S) & Filters.me) async def pytag(client, message): f...
plugins/intags.py
from pyrogram import Client, Filters import re import io import html import traceback import subprocess from contextlib import redirect_stdout from config import cmds from db import db from utils import meval @Client.on_message(Filters.regex(r'.*<py>.+</py>', re.S) & Filters.me) async def pytag(client, message): f...
0.195517
0.062274
from enum import Enum from typing import Union import numpy as np class ParamInfo: def __init__(self, candidate_type, sampled_at): self.type = candidate_type self.sampled_at = sampled_at self.finished_at = None self.is_canceled = False class CandidateType(Enum): INIT = 0 ...
pyhopper/utils.py
from enum import Enum from typing import Union import numpy as np class ParamInfo: def __init__(self, candidate_type, sampled_at): self.type = candidate_type self.sampled_at = sampled_at self.finished_at = None self.is_canceled = False class CandidateType(Enum): INIT = 0 ...
0.691081
0.244803
import functools import logging import threading import time import pika from pika.exchange_type import ExchangeType LOG_FORMAT = ('%(levelname) -10s %(asctime)s %(name) -30s %(funcName) ' '-35s %(lineno) -5d: %(message)s') LOGGER = logging.getLogger(__name__) logging.basicConfig(level=logging.DEBUG, f...
examples/basic_consumer_threaded.py
import functools import logging import threading import time import pika from pika.exchange_type import ExchangeType LOG_FORMAT = ('%(levelname) -10s %(asctime)s %(name) -30s %(funcName) ' '-35s %(lineno) -5d: %(message)s') LOGGER = logging.getLogger(__name__) logging.basicConfig(level=logging.DEBUG, f...
0.470737
0.111676
from __future__ import print_function, division, absolute_import, unicode_literals import sys from RPLCD_i2c import CharLCD from RPLCD_i2c import Alignment, CursorMode, ShiftMode from RPLCD_i2c import cursor, cleared try: input = raw_input except NameError: pass try: unichr = unichr except NameError: ...
test_20x4.py
from __future__ import print_function, division, absolute_import, unicode_literals import sys from RPLCD_i2c import CharLCD from RPLCD_i2c import Alignment, CursorMode, ShiftMode from RPLCD_i2c import cursor, cleared try: input = raw_input except NameError: pass try: unichr = unichr except NameError: ...
0.222489
0.237278
import os, re, sys if len(sys.argv) != 2: print("wrong number of arguments") print(sys.argv[0], "mod language directory") sys.exit(-1) match = re.search('(.*)/', sys.argv[0]) if match != None: os.chdir(match.group(1)) os.chdir('../') source_exts = [".c", ".cpp", ".h"] def parse_source(): stringtable = {} def ...
scripts/update_mod_localization.py
import os, re, sys if len(sys.argv) != 2: print("wrong number of arguments") print(sys.argv[0], "mod language directory") sys.exit(-1) match = re.search('(.*)/', sys.argv[0]) if match != None: os.chdir(match.group(1)) os.chdir('../') source_exts = [".c", ".cpp", ".h"] def parse_source(): stringtable = {} def ...
0.03882
0.100304
import re from math import inf from heapq import heappush, heappop from typing import List, Any def create_cave(depth: int, tx: int, ty: int) -> List[List[int]]: """ Creates the cave according to the cave generation rules. Since the cave is essentially infinite a constant size padding is applied arou...
day22.py
import re from math import inf from heapq import heappush, heappop from typing import List, Any def create_cave(depth: int, tx: int, ty: int) -> List[List[int]]: """ Creates the cave according to the cave generation rules. Since the cave is essentially infinite a constant size padding is applied arou...
0.831006
0.643721
""" R-AGI Interface Window In this script, blah blah blah Author: <NAME> Designer: <NAME> """ # This is the stuff we imported from tkinter import * from PIL import Image, ImageTk from tkinter import Tk, Text, BOTH, W, N, E, S from tkinter.ttk import Frame, Button, Label, Style from tkinter import ttk ...
ragiface.py
""" R-AGI Interface Window In this script, blah blah blah Author: <NAME> Designer: <NAME> """ # This is the stuff we imported from tkinter import * from PIL import Image, ImageTk from tkinter import Tk, Text, BOTH, W, N, E, S from tkinter.ttk import Frame, Button, Label, Style from tkinter import ttk ...
0.576304
0.161717
import numpy as np import pandas as pd from bokeh.layouts import row from bokeh.models import ColorBar, ColumnDataSource from bokeh.plotting import figure from bokeh.tile_providers import Vendors, get_provider from bokeh.transform import linear_cmap from powersimdata.input.check import _check_date from powersimdata.sce...
postreise/plot/plot_shadowprice_map.py
import numpy as np import pandas as pd from bokeh.layouts import row from bokeh.models import ColorBar, ColumnDataSource from bokeh.plotting import figure from bokeh.tile_providers import Vendors, get_provider from bokeh.transform import linear_cmap from powersimdata.input.check import _check_date from powersimdata.sce...
0.846546
0.486819
import argparse import tensorflow as tf import numpy as np import os from PIL import Image from utils import build_content_loss from utils import build_style_loss from utils import buid_cc_loss_lays from vgg_model import build_vgg19 parser = argparse.ArgumentParser() parser.add_argument('--iteration', type=int, defau...
main.py
import argparse import tensorflow as tf import numpy as np import os from PIL import Image from utils import build_content_loss from utils import build_style_loss from utils import buid_cc_loss_lays from vgg_model import build_vgg19 parser = argparse.ArgumentParser() parser.add_argument('--iteration', type=int, defau...
0.400515
0.116261
import io import re from urllib.parse import urlparse import requests from fair_test import FairTest, FairTestEvaluation class MetricTest(FairTest): metric_path = 'i2-fair-vocabularies-resolve' applies_to_principle = 'I2' title = 'Metadata uses resolvable FAIR Vocabularies' description = """Maturity ...
metrics/i2_fair_vocabularies_resolve.py
import io import re from urllib.parse import urlparse import requests from fair_test import FairTest, FairTestEvaluation class MetricTest(FairTest): metric_path = 'i2-fair-vocabularies-resolve' applies_to_principle = 'I2' title = 'Metadata uses resolvable FAIR Vocabularies' description = """Maturity ...
0.557604
0.403861
from typing import List import pandas as pd from numpy import tril from toolz import curry from fklearn.types import LogType @curry def correlation_feature_selection(train_set: pd.DataFrame, features: List[str], threshold: float = 1.0) -> LogType: ...
src/fklearn/tuning/model_agnostic_fc.py
from typing import List import pandas as pd from numpy import tril from toolz import curry from fklearn.types import LogType @curry def correlation_feature_selection(train_set: pd.DataFrame, features: List[str], threshold: float = 1.0) -> LogType: ...
0.938962
0.599602
import os from dataclasses import dataclass, field from typing import Any, Dict, List from jinja2 import Environment, FileSystemLoader, Template, select_autoescape import mkapi from mkapi.core import linker from mkapi.core.base import Docstring, Section from mkapi.core.code import Code from mkapi.core.module import M...
mkapi/core/renderer.py
import os from dataclasses import dataclass, field from typing import Any, Dict, List from jinja2 import Environment, FileSystemLoader, Template, select_autoescape import mkapi from mkapi.core import linker from mkapi.core.base import Docstring, Section from mkapi.core.code import Code from mkapi.core.module import M...
0.806472
0.178669
import datetime try: import psycopg2 except ImportError as e: from blitzortung.db import create_psycopg2_dummy psycopg2 = create_psycopg2_dummy() import pytz from assertpy import assert_that from mock import Mock, call import blitzortung.db.table class BaseForTest(blitzortung.db.table.Base): def _...
tests/db/test_db_table.py
import datetime try: import psycopg2 except ImportError as e: from blitzortung.db import create_psycopg2_dummy psycopg2 = create_psycopg2_dummy() import pytz from assertpy import assert_that from mock import Mock, call import blitzortung.db.table class BaseForTest(blitzortung.db.table.Base): def _...
0.469763
0.377369
from spaceone.api.cost_analysis.v1 import cost_pb2, cost_pb2_grpc from spaceone.core.pygrpc import BaseAPI class Cost(BaseAPI, cost_pb2_grpc.CostServicer): pb2 = cost_pb2 pb2_grpc = cost_pb2_grpc def create(self, request, context): params, metadata = self.parse_request(request, context) ...
src/spaceone/cost_analysis/interface/grpc/v1/cost.py
from spaceone.api.cost_analysis.v1 import cost_pb2, cost_pb2_grpc from spaceone.core.pygrpc import BaseAPI class Cost(BaseAPI, cost_pb2_grpc.CostServicer): pb2 = cost_pb2 pb2_grpc = cost_pb2_grpc def create(self, request, context): params, metadata = self.parse_request(request, context) ...
0.673729
0.154408
import numpy as np import os class TextData: def __init__(self, standQf="./data/faq/standFAQ.txt"): self.standQ = None self.standQf = standQf def transform_label(self): """ label_text => label_id :return: """ standQ = open(self.standQf, 'r').readlines(...
cnnClassifier/data_helpers.py
import numpy as np import os class TextData: def __init__(self, standQf="./data/faq/standFAQ.txt"): self.standQ = None self.standQf = standQf def transform_label(self): """ label_text => label_id :return: """ standQ = open(self.standQf, 'r').readlines(...
0.388038
0.261366
import argparse import pandas as pd import re #read arguments parser = argparse.ArgumentParser(description="Recluster the gene clusters by species pairs based on orthopairs") parser.add_argument("--orthopairs", "-op", required=True) parser.add_argument("--orthogroups", "-og", required=True) parser.add_argument("--s...
bin/D3.1_recluster_genes_by_species_pair.py
import argparse import pandas as pd import re #read arguments parser = argparse.ArgumentParser(description="Recluster the gene clusters by species pairs based on orthopairs") parser.add_argument("--orthopairs", "-op", required=True) parser.add_argument("--orthogroups", "-og", required=True) parser.add_argument("--s...
0.210685
0.397178
import pickle as pkl from copy import deepcopy from tqdm import tqdm from selenium import webdriver from selenium.webdriver.common.by import By from bs4 import BeautifulSoup as bs from .utils import (delay, parseLinks, parsePageScript, parsePostMetadata, parseComment, parseReply, getLinks, getMoreCo...
fbscraper/scraper.py
import pickle as pkl from copy import deepcopy from tqdm import tqdm from selenium import webdriver from selenium.webdriver.common.by import By from bs4 import BeautifulSoup as bs from .utils import (delay, parseLinks, parsePageScript, parsePostMetadata, parseComment, parseReply, getLinks, getMoreCo...
0.473414
0.051035
# noqa from __future__ import unicode_literals from django.db import migrations, models class Migration(migrations.Migration): dependencies = [ ('fta_solutions_app', '0022_init_alarm_application'), ] operations = [ migrations.AddField( model_name='adviceftadef', ...
web_app/fta_solutions_app/migrations/0023_auto_20170619_1028.py
# noqa from __future__ import unicode_literals from django.db import migrations, models class Migration(migrations.Migration): dependencies = [ ('fta_solutions_app', '0022_init_alarm_application'), ] operations = [ migrations.AddField( model_name='adviceftadef', ...
0.419886
0.141726
from load_json import get_columns, get_current_courses from vaderSentiment.vaderSentiment import SentimentIntensityAnalyzer data = get_current_courses() columns = get_columns(data) titles = [" ".join(x) for x in columns["titles"]] evaluations = columns["evaluations"] N = len(titles) # "YC401": "What knowledge, skills...
ferry/nlp/sentiment.py
from load_json import get_columns, get_current_courses from vaderSentiment.vaderSentiment import SentimentIntensityAnalyzer data = get_current_courses() columns = get_columns(data) titles = [" ".join(x) for x in columns["titles"]] evaluations = columns["evaluations"] N = len(titles) # "YC401": "What knowledge, skills...
0.306112
0.322473
import smach __all__ = ['is_shutdown', 'set_shutdown_check', 'cb_interface', 'has_smach_interface', 'CBInterface'] def is_shutdown(): return False def set_shutdown_check(cb): smach.is_shutdown = cb def has_smach_interface(obj): """Returns True if the object has SMACH interface accessors.""...
movo_common/movo_third_party/executive_smach/smach/src/smach/util.py
import smach __all__ = ['is_shutdown', 'set_shutdown_check', 'cb_interface', 'has_smach_interface', 'CBInterface'] def is_shutdown(): return False def set_shutdown_check(cb): smach.is_shutdown = cb def has_smach_interface(obj): """Returns True if the object has SMACH interface accessors.""...
0.837786
0.264608
def get_mock_hermes_result_succ(): """mock请求hermes创建表成功的返回结果""" return '{"status":"SUCCESS","message":"config success!","code":0}' def get_mock_hermes_result_failed(): """mock请求hermes创建表失败的返回结果""" return "java.lang.NullPointerException" def get_mock_hermes_conn_info(): """mock hermes的连接信息""" ...
src/api/datahub/storekit/tests/mocker/mockers.py
def get_mock_hermes_result_succ(): """mock请求hermes创建表成功的返回结果""" return '{"status":"SUCCESS","message":"config success!","code":0}' def get_mock_hermes_result_failed(): """mock请求hermes创建表失败的返回结果""" return "java.lang.NullPointerException" def get_mock_hermes_conn_info(): """mock hermes的连接信息""" ...
0.422028
0.233182
from skimage.restoration import inpaint #2 # Import the module from restoration from skimage.restoration import inpaint # Show the defective image show_image(defect_image, 'Image to restore') #3 # Import the module from restoration from skimage.restoration import inpaint # Show the defective image show_image(defect_i...
Machine Learning Scientist with Python Track/18. Image Processing in Python/ch3_exercises.py
from skimage.restoration import inpaint #2 # Import the module from restoration from skimage.restoration import inpaint # Show the defective image show_image(defect_image, 'Image to restore') #3 # Import the module from restoration from skimage.restoration import inpaint # Show the defective image show_image(defect_i...
0.692226
0.692837
from PYB11Generator import * from CRKSPHHydroBase import * @PYB11template("Dimension") @PYB11module("SpheralCRKSPH") @PYB11dynamic_attr class CRKSPHVariant(CRKSPHHydroBase): "CRKSPHVariant -- A development variant of CRKSPH for experimentation." PYB11typedefs = """ typedef typename %(Dimension)s::Scalar S...
src/Pybind11Wraps/CRKSPH/CRKSPHVariant.py
from PYB11Generator import * from CRKSPHHydroBase import * @PYB11template("Dimension") @PYB11module("SpheralCRKSPH") @PYB11dynamic_attr class CRKSPHVariant(CRKSPHHydroBase): "CRKSPHVariant -- A development variant of CRKSPH for experimentation." PYB11typedefs = """ typedef typename %(Dimension)s::Scalar S...
0.71123
0.359786
import functools import sys import importlib from ._base import parse_args class _ClientWrapper(object): def __init__(self, pool, app): self._pool = pool self._app = app self._thrift = pool.thrift_module for func in pool.service.thrift_services: api = functools.partial...
folklore_cli/cmds/shell.py
import functools import sys import importlib from ._base import parse_args class _ClientWrapper(object): def __init__(self, pool, app): self._pool = pool self._app = app self._thrift = pool.thrift_module for func in pool.service.thrift_services: api = functools.partial...
0.245447
0.042167
import binascii import logging logger = logging.getLogger(__name__) def get_conn_cmd(mac: str, conn_to_ms=250, min_con_int_us=7500, max_con_int_us=9000, link_sup_timeout_us=4000000) -> bytes: resp = f'connect {mac} {conn_to_ms} {min_con_int_us} {...
contact_tracing/src/sb/command.py
import binascii import logging logger = logging.getLogger(__name__) def get_conn_cmd(mac: str, conn_to_ms=250, min_con_int_us=7500, max_con_int_us=9000, link_sup_timeout_us=4000000) -> bytes: resp = f'connect {mac} {conn_to_ms} {min_con_int_us} {...
0.412294
0.217774
import datetime import json import jsons from typing import Optional from config import SlackConfig from app.utils.notifications.actions import set_notification_settings_raw_single_target from app.utils.notifications.user_preferences import get_effective_notification_settings, \ get_effective_active_notification_s...
app/views/v1/notification_settings.py
import datetime import json import jsons from typing import Optional from config import SlackConfig from app.utils.notifications.actions import set_notification_settings_raw_single_target from app.utils.notifications.user_preferences import get_effective_notification_settings, \ get_effective_active_notification_s...
0.555918
0.053379
import subprocess import testing.postgresql import os.path projectRootDirectory = os.path.realpath(__file__ + "/../../") coreProjectDirectory = os.path.join(projectRootDirectory, "Construct.Core") migrationsDirectory = os.path.join(coreProjectDirectory, "Migrations") """ Runs a process. """ def run(command, workingD...
scripts/CreateMigrate.py
import subprocess import testing.postgresql import os.path projectRootDirectory = os.path.realpath(__file__ + "/../../") coreProjectDirectory = os.path.join(projectRootDirectory, "Construct.Core") migrationsDirectory = os.path.join(coreProjectDirectory, "Migrations") """ Runs a process. """ def run(command, workingD...
0.328853
0.064183
import os import unittest from ph5.core import ph5api, experiment from ph5.core.tests.test_base import LogTestCase, TempDirTestCase class TestExperiment_srm(TempDirTestCase, LogTestCase): def tearDown(self): self.ph5_object.ph5close() super(TestExperiment_srm, self).tearDown() def set_curren...
ph5/core/tests/test_experiment.py
import os import unittest from ph5.core import ph5api, experiment from ph5.core.tests.test_base import LogTestCase, TempDirTestCase class TestExperiment_srm(TempDirTestCase, LogTestCase): def tearDown(self): self.ph5_object.ph5close() super(TestExperiment_srm, self).tearDown() def set_curren...
0.391871
0.355999
from scene import * from time import time, perf_counter, process_time from stltool import ray_triangle_intersection, normalize from utils import generate_rays, rel_error, abs_error ray_points = generate_rays(view_plane, ray_density=8) # mesh_sizes = [4,8,16,32,64]#,128] mesh_sizes = [4,8,16] + list(range(32,65,8)) n...
Python/time_attack.py
from scene import * from time import time, perf_counter, process_time from stltool import ray_triangle_intersection, normalize from utils import generate_rays, rel_error, abs_error ray_points = generate_rays(view_plane, ray_density=8) # mesh_sizes = [4,8,16,32,64]#,128] mesh_sizes = [4,8,16] + list(range(32,65,8)) n...
0.448426
0.268625
import sys import os requirements = "FATAL: Hob requires Gtk+ 2.20.0 or higher, PyGtk 2.21.0 or higher" try: import gobject import gtk import pygtk pygtk.require('2.0') # to be certain we don't have gtk+ 1.x !?! gtkver = gtk.gtk_version pygtkver = gtk.pygtk_version if gtkver < (2, 20, 0) o...
yocto/poky/bitbake/lib/bb/ui/hob.py
import sys import os requirements = "FATAL: Hob requires Gtk+ 2.20.0 or higher, PyGtk 2.21.0 or higher" try: import gobject import gtk import pygtk pygtk.require('2.0') # to be certain we don't have gtk+ 1.x !?! gtkver = gtk.gtk_version pygtkver = gtk.pygtk_version if gtkver < (2, 20, 0) o...
0.256646
0.170681
import os import pandas as pd import numpy as np import shutil import librosa from warnings import filterwarnings filterwarnings('ignore') from sklearn.base import BaseEstimator, TransformerMixin """ ------------------------------------------------------ --- 2. FUNÇÕES DE LEITURA E ENRIQUECIMENTO DE BASE --- ------...
ml/prep.py
import os import pandas as pd import numpy as np import shutil import librosa from warnings import filterwarnings filterwarnings('ignore') from sklearn.base import BaseEstimator, TransformerMixin """ ------------------------------------------------------ --- 2. FUNÇÕES DE LEITURA E ENRIQUECIMENTO DE BASE --- ------...
0.469034
0.29956
import os from maple.core import logging from maple.core import proto _memo_failed_limit = 2 _memo_total_failed_limit = 6 def iroot_pb2(): return proto.module('idiom.iroot_pb2') def memo_pb2(): return proto.module('idiom.memo_pb2') class iRootInfo(object): def __init__(self, proto, memo): self.p...
script/maple/idiom/memo.py
import os from maple.core import logging from maple.core import proto _memo_failed_limit = 2 _memo_total_failed_limit = 6 def iroot_pb2(): return proto.module('idiom.iroot_pb2') def memo_pb2(): return proto.module('idiom.memo_pb2') class iRootInfo(object): def __init__(self, proto, memo): self.p...
0.311846
0.099383
import ctypes intGo = ctypes.c_longlong floatGo = ctypes.c_double stringGo = ctypes.c_char_p boolGo = ctypes.c_bool class intGoSlice(ctypes.Structure): """ Golang slice structure for intGo type """ _fields_ = [("data", ctypes.POINTER(intGo)), ("len", ctypes.c_longlong), ...
goinpy/goinpy.py
import ctypes intGo = ctypes.c_longlong floatGo = ctypes.c_double stringGo = ctypes.c_char_p boolGo = ctypes.c_bool class intGoSlice(ctypes.Structure): """ Golang slice structure for intGo type """ _fields_ = [("data", ctypes.POINTER(intGo)), ("len", ctypes.c_longlong), ...
0.696578
0.382516
from tkinter import * from Controllers.JoinController import JoinController from Controllers.ApplicationController import ApplicationController from Views import RecruiterPage from Views import LoginPage from tkinter import messagebox class SelectApplicant(Frame): def __init__(self, recTk, jobID, companyEmail): ...
Views/ApplicantSelectionByRecruiter.py
from tkinter import * from Controllers.JoinController import JoinController from Controllers.ApplicationController import ApplicationController from Views import RecruiterPage from Views import LoginPage from tkinter import messagebox class SelectApplicant(Frame): def __init__(self, recTk, jobID, companyEmail): ...
0.409457
0.103749
import sys import pytest import paramiko class DibCtlPlugin(object): def __init__(self, ssh, tos, environment_variables): self.cached_ssh_backend = None self.env_vars = environment_variables self.tos = tos self.ssh_data = ssh self.enable_control_master = False # I wasn't a...
dibctl/pytest_runner.py
import sys import pytest import paramiko class DibCtlPlugin(object): def __init__(self, ssh, tos, environment_variables): self.cached_ssh_backend = None self.env_vars = environment_variables self.tos = tos self.ssh_data = ssh self.enable_control_master = False # I wasn't a...
0.143038
0.23404
from typing import List from rest_framework import routers from rest_framework.parsers import FileUploadParser from rest_framework.request import Request from rest_framework.response import Response from ufdl.json.core import FileMetadata from ...exceptions import JSONParseFailure from ...renderers import BinaryFile...
ufdl-core-app/src/ufdl/core_app/views/mixins/_FileContainerViewSet.py
from typing import List from rest_framework import routers from rest_framework.parsers import FileUploadParser from rest_framework.request import Request from rest_framework.response import Response from ufdl.json.core import FileMetadata from ...exceptions import JSONParseFailure from ...renderers import BinaryFile...
0.79956
0.168139
import pytest from grandchallenge.annotations.models import ( BooleanClassificationAnnotation, PolygonAnnotationSet, ) from grandchallenge.retina_core.management.commands.migratelesionnames import ( migrate_annotations, ) from tests.annotations_tests.factories import ( PolygonAnnotationSetFactory, ...
app/tests/retina_core_tests/test_commands.py
import pytest from grandchallenge.annotations.models import ( BooleanClassificationAnnotation, PolygonAnnotationSet, ) from grandchallenge.retina_core.management.commands.migratelesionnames import ( migrate_annotations, ) from tests.annotations_tests.factories import ( PolygonAnnotationSetFactory, ...
0.627723
0.519704
import json import dlib import numpy as np import rospy from cv_bridge import CvBridge from home_robot_msgs.msg import ObjectBoxes from core.Nodes import Node class FaceRecognition(Node): def __init__(self): super(FaceRecognition, self).__init__('face_desc_parser', anonymous=False) _shape_dat =...
RCJ_pcms_base/scripts/FaceDescParserNode.py
import json import dlib import numpy as np import rospy from cv_bridge import CvBridge from home_robot_msgs.msg import ObjectBoxes from core.Nodes import Node class FaceRecognition(Node): def __init__(self): super(FaceRecognition, self).__init__('face_desc_parser', anonymous=False) _shape_dat =...
0.520496
0.100525
import argparse import os.path as path import sys import torch import torch.nn as nn from PIL import Image from fastseg import MobileV3Large, MobileV3Small from fastseg.image import colorize, blend torch.backends.cudnn.benchmark = True parser = argparse.ArgumentParser(description=__doc__) parser.add_argument('ima...
infer.py
import argparse import os.path as path import sys import torch import torch.nn as nn from PIL import Image from fastseg import MobileV3Large, MobileV3Small from fastseg.image import colorize, blend torch.backends.cudnn.benchmark = True parser = argparse.ArgumentParser(description=__doc__) parser.add_argument('ima...
0.419767
0.156105
import torch import torch.nn.functional as F from torch import nn import fvcore.nn.weight_init as weight_init from detectron2.layers import Conv2d, ShapeSpec, get_norm from detectron2.modeling.backbone.build import BACKBONE_REGISTRY from detectron2.modeling.backbone.fpn import FPN from detectron2.modeling.backbone.re...
projects/PoseNet/posenet/backbone/fpn.py
import torch import torch.nn.functional as F from torch import nn import fvcore.nn.weight_init as weight_init from detectron2.layers import Conv2d, ShapeSpec, get_norm from detectron2.modeling.backbone.build import BACKBONE_REGISTRY from detectron2.modeling.backbone.fpn import FPN from detectron2.modeling.backbone.re...
0.946318
0.301574
import sys import pygame as pg import re from enum import Enum import copy import numpy as np class color(Enum): RED = (255,0,0) GREEN = (0,255,0) BLUE =(0,0,255) BLACK =(0,0,0) WHITE =(255,255,255) GRAY =(150,150,150) def fill_gradient(surface, color, gradient, rect=None, vertical=True, forwa...
pygame_lib.py
import sys import pygame as pg import re from enum import Enum import copy import numpy as np class color(Enum): RED = (255,0,0) GREEN = (0,255,0) BLUE =(0,0,255) BLACK =(0,0,0) WHITE =(255,255,255) GRAY =(150,150,150) def fill_gradient(surface, color, gradient, rect=None, vertical=True, forwa...
0.472927
0.142232
from __future__ import division, absolute_import, print_function import confuse import yaml import unittest from . import TempDir def load(s): return yaml.load(s, Loader=confuse.Loader) class ParseTest(unittest.TestCase): def test_dict_parsed_as_ordereddict(self): v = load("a: b\nc: d") sel...
test/test_yaml.py
from __future__ import division, absolute_import, print_function import confuse import yaml import unittest from . import TempDir def load(s): return yaml.load(s, Loader=confuse.Loader) class ParseTest(unittest.TestCase): def test_dict_parsed_as_ordereddict(self): v = load("a: b\nc: d") sel...
0.630457
0.456228
import json import device import code_descriptor def send_message(recv_id, message): x = {} x['process-code'] = 21 x['process-description'] = code_descriptor.get_description('21') x['sender'] = device.get_full_id() x['receiver'] = recv_id x['path'] = [] x['message'] = message return json.dumps(x) ...
Device/lib/header.py
import json import device import code_descriptor def send_message(recv_id, message): x = {} x['process-code'] = 21 x['process-description'] = code_descriptor.get_description('21') x['sender'] = device.get_full_id() x['receiver'] = recv_id x['path'] = [] x['message'] = message return json.dumps(x) ...
0.157072
0.045692
import unittest import numpy as np from perform.constants import REAL_TYPE from perform.gas_model.gas_model import GasModel from constants import CHEM_DICT_AIR class GasModelInitTestCase(unittest.TestCase): def setUp(self): self.chem_dict = CHEM_DICT_AIR def test_gas_model_init(self): gas...
tests/unit_tests/test_gas_model/test_gas_model.py
import unittest import numpy as np from perform.constants import REAL_TYPE from perform.gas_model.gas_model import GasModel from constants import CHEM_DICT_AIR class GasModelInitTestCase(unittest.TestCase): def setUp(self): self.chem_dict = CHEM_DICT_AIR def test_gas_model_init(self): gas...
0.635222
0.763021
"""Let viewers pay currency to boost currency payouts for everyone in chat for x seconds""" import json import os, os.path import time import codecs import glob #--------------------------------------- # [Required] Script information #--------------------------------------- ScriptName = "NextGame" Website = "https://w...
NextGame/NextGame_StreamlabsSystem.py
"""Let viewers pay currency to boost currency payouts for everyone in chat for x seconds""" import json import os, os.path import time import codecs import glob #--------------------------------------- # [Required] Script information #--------------------------------------- ScriptName = "NextGame" Website = "https://w...
0.377196
0.243856
import unittest from geodepy.transform import geo2grid, grid2geo, llh2xyz, xyz2llh, conform7, conform14, atrftogda2020, gda2020toatrf from geodepy.convert import dms2dd_v, read_dnacoord from geodepy.constants import itrf14togda20, gda94to20 from datetime import date import numpy as np import os.path class TestTransf...
geodepy/tests/test_transform.py
import unittest from geodepy.transform import geo2grid, grid2geo, llh2xyz, xyz2llh, conform7, conform14, atrftogda2020, gda2020toatrf from geodepy.convert import dms2dd_v, read_dnacoord from geodepy.constants import itrf14togda20, gda94to20 from datetime import date import numpy as np import os.path class TestTransf...
0.295942
0.685607
import copy from aocd import get_data, submit DAY = 19 YEAR = 2021 # https://stackoverflow.com/questions/16452383/how-to-get-all-24-rotations-of-a-3-dimensional-array def roll(v): return [v[0],v[2],-v[1]] def turn(v): return [-v[1],v[0],v[2]] def sequence (v): for cycle in range(2): for step in range(3):...
days/day19.py
import copy from aocd import get_data, submit DAY = 19 YEAR = 2021 # https://stackoverflow.com/questions/16452383/how-to-get-all-24-rotations-of-a-3-dimensional-array def roll(v): return [v[0],v[2],-v[1]] def turn(v): return [-v[1],v[0],v[2]] def sequence (v): for cycle in range(2): for step in range(3):...
0.357007
0.425009
from django.db import models from django.urls import reverse_lazy from django.contrib.auth.models import User from django.utils import timezone # Create your models here. class SchoolProfile(models.Model): username = models.OneToOneField(User, on_delete=models.CASCADE) contact_no = models.CharField(d...
home/models.py
from django.db import models from django.urls import reverse_lazy from django.contrib.auth.models import User from django.utils import timezone # Create your models here. class SchoolProfile(models.Model): username = models.OneToOneField(User, on_delete=models.CASCADE) contact_no = models.CharField(d...
0.422266
0.088662
import base64 import re import urllib import urlparse from dejan7.abstract.ordict import * class Url(object): DEFAULT_SCHEME = "https" SPLIT_KEYS = ("scheme", "netloc", "path", "query", "fragment") SPLIT_EX_KEYS = ("scheme", "hostname", "port", "username", "password", "path", "query", "fragment") @...
web/Url.py
import base64 import re import urllib import urlparse from dejan7.abstract.ordict import * class Url(object): DEFAULT_SCHEME = "https" SPLIT_KEYS = ("scheme", "netloc", "path", "query", "fragment") SPLIT_EX_KEYS = ("scheme", "hostname", "port", "username", "password", "path", "query", "fragment") @...
0.368406
0.142799
import enum import bleak_winrt _ns_module = bleak_winrt._import_ns_module("Windows.Devices.Enumeration") try: import bleak_winrt.windows.applicationmodel.background except Exception: pass try: import bleak_winrt.windows.foundation except Exception: pass try: import bleak_winr...
pywinrt/bleak_winrt/windows/devices/enumeration/__init__.py
import enum import bleak_winrt _ns_module = bleak_winrt._import_ns_module("Windows.Devices.Enumeration") try: import bleak_winrt.windows.applicationmodel.background except Exception: pass try: import bleak_winrt.windows.foundation except Exception: pass try: import bleak_winr...
0.182389
0.049108
from __future__ import print_function import os import sys import logging import argparse import code from configobj import ConfigObj from apscheduler.schedulers.background import BackgroundScheduler from apscheduler.jobstores.sqlalchemy import SQLAlchemyJobStore from validate import Validator from .layer import TomBot...
tombot/run.py
from __future__ import print_function import os import sys import logging import argparse import code from configobj import ConfigObj from apscheduler.schedulers.background import BackgroundScheduler from apscheduler.jobstores.sqlalchemy import SQLAlchemyJobStore from validate import Validator from .layer import TomBot...
0.36886
0.079603
import cv2 import PIL import numpy from PIL import ImageGrab class KeyType(object): def __init__(self, src: str, dx=None, dy=None): self.keysrc = src self.dx = dx self.dy = dy def __str__(self): return 'key: "%s", dx: %d, dy: %d' % (self.key, self.dx, self.dy) class Position...
cvauto/position.py
import cv2 import PIL import numpy from PIL import ImageGrab class KeyType(object): def __init__(self, src: str, dx=None, dy=None): self.keysrc = src self.dx = dx self.dy = dy def __str__(self): return 'key: "%s", dx: %d, dy: %d' % (self.key, self.dx, self.dy) class Position...
0.340924
0.217338
from types import MethodType from typing import ( Any, Callable, Iterable, Mapping, Optional, Text, Type, TypeVar, Union, ) from wired import ServiceContainer, ServiceRegistry from zope.interface import Interface __version__ = "0.1.dev0" T = TypeVar("T") class AutowireError(Exce...
autowired/__init__.py
from types import MethodType from typing import ( Any, Callable, Iterable, Mapping, Optional, Text, Type, TypeVar, Union, ) from wired import ServiceContainer, ServiceRegistry from zope.interface import Interface __version__ = "0.1.dev0" T = TypeVar("T") class AutowireError(Exce...
0.78695
0.195844
import os import time from multiprocessing import Process import numpy as np from pyqtgraph.Qt import QtCore from traits.api import Button, Enum, Bool, Int, File from traitsui.api import View, VGroup, HGroup, UItem, \ Item, FileEditor, RangeEditor from pyface.timer.api import Timer import ecoglib.vis.ani as ani ...
fast_scroller/modules/animation.py
import os import time from multiprocessing import Process import numpy as np from pyqtgraph.Qt import QtCore from traits.api import Button, Enum, Bool, Int, File from traitsui.api import View, VGroup, HGroup, UItem, \ Item, FileEditor, RangeEditor from pyface.timer.api import Timer import ecoglib.vis.ani as ani ...
0.502686
0.102081
from pathlib import Path from typing import Dict import logging import yaml from suzieq.poller.controller.source.base_source import Source from suzieq.shared.exceptions import InventorySourceError logger = logging.getLogger(__name__) class AnsibleInventory(Source): """The AnsibleInventory is a class allowing to ...
suzieq/poller/controller/source/ansible.py
from pathlib import Path from typing import Dict import logging import yaml from suzieq.poller.controller.source.base_source import Source from suzieq.shared.exceptions import InventorySourceError logger = logging.getLogger(__name__) class AnsibleInventory(Source): """The AnsibleInventory is a class allowing to ...
0.768212
0.20044
import os import pickle import time from multiprocessing.pool import Pool import argparse import chainer import gc as gc_m import numpy as np import pandas as pd from scripts.utils import check_path __doc__ = """ train_cnn_multi - a training, testing and feature extraction scripts for CNN module =====================...
scripts/train_cnn_multi.py
import os import pickle import time from multiprocessing.pool import Pool import argparse import chainer import gc as gc_m import numpy as np import pandas as pd from scripts.utils import check_path __doc__ = """ train_cnn_multi - a training, testing and feature extraction scripts for CNN module =====================...
0.658966
0.34443
import cv2 import numpy as np from skimage import io from pathlib import Path import random class ImageProc: """ Contain image pre process functions """ @staticmethod def binarize(image, maxval=255): """ Binarization by ostu threshold Parameters --...
akaocr/pre/image.py
import cv2 import numpy as np from skimage import io from pathlib import Path import random class ImageProc: """ Contain image pre process functions """ @staticmethod def binarize(image, maxval=255): """ Binarization by ostu threshold Parameters --...
0.74158
0.338473
import json import boto3 from botocore.stub import Stubber import pytest from pytest_mock import mocker import cis1314 from lib.logger import Logger from lib.applogger import LogHandler from lib.awsapi_helpers import BotoSession from lib.applogger import LogHandler import lib.sechub_findings from unittest.mock import p...
source/playbooks/CIS/lambda/tests/test_cis1314.py
import json import boto3 from botocore.stub import Stubber import pytest from pytest_mock import mocker import cis1314 from lib.logger import Logger from lib.applogger import LogHandler from lib.awsapi_helpers import BotoSession from lib.applogger import LogHandler import lib.sechub_findings from unittest.mock import p...
0.469763
0.161419
import numpy as np # Local from . import Model, PREDICTION_MODELS, MOTION_MODELS from filterpy.kalman import KalmanFilter class KalmanTracker(KalmanFilter): """ This class represents the internel state of individual tracked objects observed as bbox. """ def __init__(self, feature, model,**kwargs): ...
mm3dot/model/kalman_tracker.py
import numpy as np # Local from . import Model, PREDICTION_MODELS, MOTION_MODELS from filterpy.kalman import KalmanFilter class KalmanTracker(KalmanFilter): """ This class represents the internel state of individual tracked objects observed as bbox. """ def __init__(self, feature, model,**kwargs): ...
0.46393
0.295395
import sys import json from ansible.module_utils import ntap_util try: from NaServer import * NASERVER_AVAILABLE = True except ImportError: NASERVER_AVAILABLE = False if not NASERVER_AVAILABLE: module.fail_json(msg="The NetApp Manageability SDK library is not installed") DOCUMENTATTION = ''' --- mo...
library/aggr_hybrid.py
import sys import json from ansible.module_utils import ntap_util try: from NaServer import * NASERVER_AVAILABLE = True except ImportError: NASERVER_AVAILABLE = False if not NASERVER_AVAILABLE: module.fail_json(msg="The NetApp Manageability SDK library is not installed") DOCUMENTATTION = ''' --- mo...
0.383295
0.13658
from __future__ import unicode_literals from collections import defaultdict from copilot.conf import settings from copilot.api import CopilotClient from copilot.events.api_models import EventManager import logging logger = logging.getLogger('djangocms-copilot') class Artist(object): def __init__(self, id, **kwar...
copilot/artists/api_models.py
from __future__ import unicode_literals from collections import defaultdict from copilot.conf import settings from copilot.api import CopilotClient from copilot.events.api_models import EventManager import logging logger = logging.getLogger('djangocms-copilot') class Artist(object): def __init__(self, id, **kwar...
0.548674
0.048722