code
stringlengths
2k
1.04M
repo_path
stringlengths
5
517
parsed_code
stringlengths
0
1.04M
quality_prob
float64
0.02
0.95
learning_prob
float64
0.02
0.93
import random import numpy as np from netqasm.examples.lib.bqc import recv_meas_outcome, send_meas_cmd, teleport_state from netqasm.logging.glob import get_netqasm_logger from netqasm.sdk import EPRSocket from netqasm.sdk.external import NetQASMConnection, Socket logger = get_netqasm_logger() def main(app_config=N...
netqasm/examples/apps/blind_rotation/app_client.py
import random import numpy as np from netqasm.examples.lib.bqc import recv_meas_outcome, send_meas_cmd, teleport_state from netqasm.logging.glob import get_netqasm_logger from netqasm.sdk import EPRSocket from netqasm.sdk.external import NetQASMConnection, Socket logger = get_netqasm_logger() def main(app_config=N...
0.527317
0.267459
import mock import yaml from boto3.session import Session from botocore.exceptions import ClientError from botocore.exceptions import NoCredentialsError from botocore.exceptions import EndpointConnectionError from st2tests.base import BaseSensorTestCase from sqs_sensor import AWSSQSSensor class SQSSensorTestCase(Ba...
tests/test_sensor_sqs.py
import mock import yaml from boto3.session import Session from botocore.exceptions import ClientError from botocore.exceptions import NoCredentialsError from botocore.exceptions import EndpointConnectionError from st2tests.base import BaseSensorTestCase from sqs_sensor import AWSSQSSensor class SQSSensorTestCase(Ba...
0.715126
0.181082
import logging import os import sys import time import requests logger = logging.getLogger("xgg_logger") def run_github_search(api_url, search_query, extension, token_env): """ Run the GitHub API search with given search query Get the items from the response content and Return params: api_url - stri...
xgitguard/common/github_calls.py
import logging import os import sys import time import requests logger = logging.getLogger("xgg_logger") def run_github_search(api_url, search_query, extension, token_env): """ Run the GitHub API search with given search query Get the items from the response content and Return params: api_url - stri...
0.342352
0.137272
import json import sys # pylint: disable=W0105 """Data structure of input files of this script. The format of the json files is as follows. Each json file contains multiple "interface"s. Each "interface" contains 'ExtAttributes', 'Consts', 'Attributes' and 'Operations'. Each item in them are called a "member". {'I...
third_party/blink/tools/blinkpy/bindings/generate_idl_diff.py
import json import sys # pylint: disable=W0105 """Data structure of input files of this script. The format of the json files is as follows. Each json file contains multiple "interface"s. Each "interface" contains 'ExtAttributes', 'Consts', 'Attributes' and 'Operations'. Each item in them are called a "member". {'I...
0.569733
0.26653
import qctests.ICDC_aqc_01_level_order as ICDC import qctests.ICDC_aqc_06_n_temperature_extrema as ICDC_nte import util.testingProfile import util.main as main import numpy as np ##### ICDC number of temperature extrema. ##### -------------------------------------------------- class TestClass: parameters = { ...
tests/ICDC_aqc_06_n_temperature_extrema_validation.py
import qctests.ICDC_aqc_01_level_order as ICDC import qctests.ICDC_aqc_06_n_temperature_extrema as ICDC_nte import util.testingProfile import util.main as main import numpy as np ##### ICDC number of temperature extrema. ##### -------------------------------------------------- class TestClass: parameters = { ...
0.299925
0.339116
import albumentations as alb from albumentations.pytorch import ToTensorV2 from os.path import join from tqdm import tqdm import torch from torch.utils.data import DataLoader from src.data.isprs.config import ISPRSChannels from src.data.isprs import ISPRSDataset, PotsdamDataset, VaihingenDataset def test_dataset_va...
tests/test_datasets.py
import albumentations as alb from albumentations.pytorch import ToTensorV2 from os.path import join from tqdm import tqdm import torch from torch.utils.data import DataLoader from src.data.isprs.config import ISPRSChannels from src.data.isprs import ISPRSDataset, PotsdamDataset, VaihingenDataset def test_dataset_va...
0.538255
0.401453
import cv2 import numpy as np import tensorflow as tf class Tracker: view_a = None view_b = None start_pos = np.asarray([0, 0]) dist_thresh = 0 infer = True def __init__(self, frame, bbox, color): self.tracker = cv2.TrackerKCF_create() self.color = color self.tracker.i...
lighting_model/application/tracker.py
import cv2 import numpy as np import tensorflow as tf class Tracker: view_a = None view_b = None start_pos = np.asarray([0, 0]) dist_thresh = 0 infer = True def __init__(self, frame, bbox, color): self.tracker = cv2.TrackerKCF_create() self.color = color self.tracker.i...
0.552419
0.397354
from itertools import combinations import pycld2 LANGS_DICT = dict([(lang[1], lang[0].lower().capitalize()) for lang in pycld2.LANGUAGES]) def area_dict(countries_study_data, cc, region=None): if region: region_dict = countries_study_data[cc]['regions'][region].copy() else: ...
src/utils/make_config.py
from itertools import combinations import pycld2 LANGS_DICT = dict([(lang[1], lang[0].lower().capitalize()) for lang in pycld2.LANGUAGES]) def area_dict(countries_study_data, cc, region=None): if region: region_dict = countries_study_data[cc]['regions'][region].copy() else: ...
0.439747
0.254584
import boto3 from boto3.dynamodb.conditions import Attr, Key from botocore.exceptions import ClientError from fdbk import DBConnection from fdbk.utils import ( generate_data_entry, generate_topic_dict, generate_topic_response, generate_topics_list, timestamp_as_str) from fdbk.utils.messages import ...
fdbk_dynamodb_plugin/_dynamodb_connection.py
import boto3 from boto3.dynamodb.conditions import Attr, Key from botocore.exceptions import ClientError from fdbk import DBConnection from fdbk.utils import ( generate_data_entry, generate_topic_dict, generate_topic_response, generate_topics_list, timestamp_as_str) from fdbk.utils.messages import ...
0.468791
0.169509
from __future__ import unicode_literals, division, absolute_import, print_function import hashlib import hmac import re import binascii from ._asn1 import ( CertBag, Certificate, DSAPrivateKey, ECPrivateKey, EncryptedData, EncryptedPrivateKeyInfo, Integer, OctetString, Pfx, Pri...
package_control/deps/oscrypto/_asymmetric.py
from __future__ import unicode_literals, division, absolute_import, print_function import hashlib import hmac import re import binascii from ._asn1 import ( CertBag, Certificate, DSAPrivateKey, ECPrivateKey, EncryptedData, EncryptedPrivateKeyInfo, Integer, OctetString, Pfx, Pri...
0.821259
0.180107
import cv2 import numpy as mp from similarity import * from hist import * class PF_Tracker: def __init__(self, model, search_space, num_particles=100, state_dims=2, control_std=10, sim_std=20, alpha=0.0): self.model = model self.search_space = search_space[::-1] s...
Particle-Filter-Tracking/PF_Tracker.py
import cv2 import numpy as mp from similarity import * from hist import * class PF_Tracker: def __init__(self, model, search_space, num_particles=100, state_dims=2, control_std=10, sim_std=20, alpha=0.0): self.model = model self.search_space = search_space[::-1] s...
0.582847
0.341171
from django.conf.urls import url from rest_framework.urlpatterns import format_suffix_patterns from lcm.ns.views.deprecated.create_ns_view import CreateNSView from lcm.ns.views.deprecated.get_del_ns_view import NSDetailView from lcm.ns.views.deprecated.inst_ns_post_deal_view import NSInstPostDealView from lcm.ns.vi...
test_scripts/ns_instance/duan/service/vfc/nfvo/lcm/lcm/ns/urls.py
from django.conf.urls import url from rest_framework.urlpatterns import format_suffix_patterns from lcm.ns.views.deprecated.create_ns_view import CreateNSView from lcm.ns.views.deprecated.get_del_ns_view import NSDetailView from lcm.ns.views.deprecated.inst_ns_post_deal_view import NSInstPostDealView from lcm.ns.vi...
0.427875
0.0704
import abc import collections import itertools from decimal import Decimal from core.calculators.utils import round_float from core.calculators.value import Value class OrderCalculatorMixin: class Item: def __init__(self, price, count, vat, amount=1, seller=None): self.price = price ...
core/calculators/order_calculator.py
import abc import collections import itertools from decimal import Decimal from core.calculators.utils import round_float from core.calculators.value import Value class OrderCalculatorMixin: class Item: def __init__(self, price, count, vat, amount=1, seller=None): self.price = price ...
0.777764
0.31275
from __future__ import annotations from typing import TYPE_CHECKING, List, Optional import tensorflow as tf from ashpy.contexts.base_context import BaseContext from ashpy.metrics import Metric from ashpy.modes import LogEvalMode if TYPE_CHECKING: from ashpy.losses.executor import Executor class ClassifierCont...
ashpy/contexts/classifier.py
from __future__ import annotations from typing import TYPE_CHECKING, List, Optional import tensorflow as tf from ashpy.contexts.base_context import BaseContext from ashpy.metrics import Metric from ashpy.modes import LogEvalMode if TYPE_CHECKING: from ashpy.losses.executor import Executor class ClassifierCont...
0.961326
0.357035
## Class name selected in a class+level search LAST_CLASS_NAME = "last_class_name" ## Class name selected in a class+level search LAST_SCHOOL_NAME = "last_school_name" ## Id of last message sended #@note Required for update the spell displayed LAST_MESSAGE_ID = "last_message_id" ## List of spells requested CACHED_S...
globals.py
## Class name selected in a class+level search LAST_CLASS_NAME = "last_class_name" ## Class name selected in a class+level search LAST_SCHOOL_NAME = "last_school_name" ## Id of last message sended #@note Required for update the spell displayed LAST_MESSAGE_ID = "last_message_id" ## List of spells requested CACHED_S...
0.38145
0.126542
import os import sys import pytest sys.path.insert(0, os.path.abspath(".")) sys.path.insert(0, os.path.abspath("../")) from tests._wrappers import forward from pypunisher.example_data._example_data import X_train # ----------------------------------------------------------------------------- # Test `forward()` Par...
tests/test_forward_selection.py
import os import sys import pytest sys.path.insert(0, os.path.abspath(".")) sys.path.insert(0, os.path.abspath("../")) from tests._wrappers import forward from pypunisher.example_data._example_data import X_train # ----------------------------------------------------------------------------- # Test `forward()` Par...
0.598195
0.318485
from __future__ import division, print_function from kernels import kernel_matrix, adjust_K from eigen_update import expand_eigensystem, update_eigensystem from copy import copy, deepcopy import numpy as np from numpy import dot, diag, ones from scipy import linalg def kernel_error(*args, **kwargs): raise Val...
inkpca/incremental_kpca.py
from __future__ import division, print_function from kernels import kernel_matrix, adjust_K from eigen_update import expand_eigensystem, update_eigensystem from copy import copy, deepcopy import numpy as np from numpy import dot, diag, ones from scipy import linalg def kernel_error(*args, **kwargs): raise Val...
0.885427
0.4206
import sqlite3 from collections import OrderedDict from .schema import table_schema from .globals import db_path class DrisyDb: def __init__(self): self.db_path = db_path self.db_conn = sqlite3.connect(db_path) def create_table(self, schema): query = f"CREATE TABLE IF NOT EXISTS {sc...
drisy/core/db.py
import sqlite3 from collections import OrderedDict from .schema import table_schema from .globals import db_path class DrisyDb: def __init__(self): self.db_path = db_path self.db_conn = sqlite3.connect(db_path) def create_table(self, schema): query = f"CREATE TABLE IF NOT EXISTS {sc...
0.290377
0.133868
from opnfv_testapi.tornado_swagger import swagger from handlers import GenericApiHandler from opnfv_testapi.common.constants import HTTP_FORBIDDEN from project_models import Project class GenericProjectHandler(GenericApiHandler): def __init__(self, application, request, **kwargs): super(GenericProjectHand...
utils/test/testapi/opnfv_testapi/resources/project_handlers.py
from opnfv_testapi.tornado_swagger import swagger from handlers import GenericApiHandler from opnfv_testapi.common.constants import HTTP_FORBIDDEN from project_models import Project class GenericProjectHandler(GenericApiHandler): def __init__(self, application, request, **kwargs): super(GenericProjectHand...
0.673621
0.105902
from django.contrib import admin, messages from django.db import models from django.forms import CheckboxSelectMultiple # Register your models here. from .models import Site_Page, Department, Category, Person, Training_Session, Training_Spec class PersonAdmin(admin.ModelAdmin): fields = ['first_name', 'last_name',...
nt_training/admin.py
from django.contrib import admin, messages from django.db import models from django.forms import CheckboxSelectMultiple # Register your models here. from .models import Site_Page, Department, Category, Person, Training_Session, Training_Spec class PersonAdmin(admin.ModelAdmin): fields = ['first_name', 'last_name',...
0.409929
0.133472
import string import re import operator from typing import List, Union OPERATIONS = { "+": operator.add, "-": operator.sub, "*": operator.mul, "/": operator.truediv, } def get_user_input(): """Get user input.""" user_input = input("Enter your term (q to exit): ") if user_input == "q": ...
calculator/calculator.py
import string import re import operator from typing import List, Union OPERATIONS = { "+": operator.add, "-": operator.sub, "*": operator.mul, "/": operator.truediv, } def get_user_input(): """Get user input.""" user_input = input("Enter your term (q to exit): ") if user_input == "q": ...
0.873768
0.457137
import tensorflow as tf from tensorflow.keras.regularizers import l2 def vgg16(): weight_decay = 0.0005 model = tf.keras.Sequential( [ tf.keras.layers.Conv2D( 64, (3, 3), activation="relu", kernel_regularizer=l2(we...
integration_tests/models/vgg16.py
import tensorflow as tf from tensorflow.keras.regularizers import l2 def vgg16(): weight_decay = 0.0005 model = tf.keras.Sequential( [ tf.keras.layers.Conv2D( 64, (3, 3), activation="relu", kernel_regularizer=l2(we...
0.856032
0.512693
from base64 import b64decode, b64encode from hashlib import sha256 as _sha256 from os import environ, urandom from typing import Generator from qrng import qgenerate from coincurve.context import GLOBAL_CONTEXT, Context from coincurve.types import Hasher from ._libsecp256k1 import ffi, lib GROUP_ORDER = ( b'\xff...
coincurve/utils.py
from base64 import b64decode, b64encode from hashlib import sha256 as _sha256 from os import environ, urandom from typing import Generator from qrng import qgenerate from coincurve.context import GLOBAL_CONTEXT, Context from coincurve.types import Hasher from ._libsecp256k1 import ffi, lib GROUP_ORDER = ( b'\xff...
0.814201
0.193795
import base64 import time import jwt from jwt.exceptions import ExpiredSignatureError from weixin.helper import smart_str from apis.models.oauth import Account, OAuth2Client from apis.settings import Config from apis.exception import Unauthorized from apis.models import ObjectModel class CurrentAccount(object): ...
apis/verification.py
import base64 import time import jwt from jwt.exceptions import ExpiredSignatureError from weixin.helper import smart_str from apis.models.oauth import Account, OAuth2Client from apis.settings import Config from apis.exception import Unauthorized from apis.models import ObjectModel class CurrentAccount(object): ...
0.319971
0.099865
# BCDI: tools for pre(post)-processing Bragg coherent X-ray diffraction imaging data # (c) 07/2017-06/2019 : CNRS UMR 7344 IM2NP # (c) 07/2019-05/2021 : DESY PHOTON SCIENCE # authors: # <NAME>, <EMAIL> import io import unittest from pathlib import Path from bcdi.utils.io_helper import ContextFile f...
tests/utils/test_io_helper.py
# BCDI: tools for pre(post)-processing Bragg coherent X-ray diffraction imaging data # (c) 07/2017-06/2019 : CNRS UMR 7344 IM2NP # (c) 07/2019-05/2021 : DESY PHOTON SCIENCE # authors: # <NAME>, <EMAIL> import io import unittest from pathlib import Path from bcdi.utils.io_helper import ContextFile f...
0.544075
0.383266
import cv2 import numpy as np from progress.bar import Bar from mtcnn import p_net, o_net, r_net from .log import logger from .utils import load_weights, process_image, generate_bbox, py_nms, bbox_2_square, pad, calibrate_bbox class Detector: def __init__(self, weight_dir, min_face_size=24, ...
mtcnn/detector.py
import cv2 import numpy as np from progress.bar import Bar from mtcnn import p_net, o_net, r_net from .log import logger from .utils import load_weights, process_image, generate_bbox, py_nms, bbox_2_square, pad, calibrate_bbox class Detector: def __init__(self, weight_dir, min_face_size=24, ...
0.627951
0.344499
import sys from urllib.parse import urljoin import json import requests from bs4 import BeautifulSoup args = sys.argv baseURL = 'https://just-eat.ca/' def getTowns(): print('Listing available towns ..') page = requests.get(baseURL) soup = BeautifulSoup(page.content, 'html.parser') temp = soup.select('div.c-foote...
justeat.py
import sys from urllib.parse import urljoin import json import requests from bs4 import BeautifulSoup args = sys.argv baseURL = 'https://just-eat.ca/' def getTowns(): print('Listing available towns ..') page = requests.get(baseURL) soup = BeautifulSoup(page.content, 'html.parser') temp = soup.select('div.c-foote...
0.035461
0.067301
from _base import workflow_schema, comments_schema, watchers_schema, audit_schema, acl_item_schema _schema = { 'name': {'type': 'string', 'required': True}, 'url': {'type': 'string', 'required': False}, 'contact': {'type'...
domain/gear_manufacturers.py
from _base import workflow_schema, comments_schema, watchers_schema, audit_schema, acl_item_schema _schema = { 'name': {'type': 'string', 'required': True}, 'url': {'type': 'string', 'required': False}, 'contact': {'type'...
0.352871
0.166743
from __future__ import unicode_literals import datetime from django.test import TestCase, RequestFactory from django.core.cache import cache from django.core.urlresolvers import reverse from django.utils import timezone from django.core.exceptions import ObjectDoesNotExist from djconfig.utils import override_djconf...
tests/tests_topic.py
from __future__ import unicode_literals import datetime from django.test import TestCase, RequestFactory from django.core.cache import cache from django.core.urlresolvers import reverse from django.utils import timezone from django.core.exceptions import ObjectDoesNotExist from djconfig.utils import override_djconf...
0.4917
0.215175
from configparser import ConfigParser from argparse import ArgumentParser import torch import gym import numpy as np import os from agents.ppo import PPO from agents.sac import SAC from agents.ddpg import DDPG from utils.utils import make_transition, Dict, RunningMeanStd os.makedirs('./model_weights', exist_ok=True)...
main.py
from configparser import ConfigParser from argparse import ArgumentParser import torch import gym import numpy as np import os from agents.ppo import PPO from agents.sac import SAC from agents.ddpg import DDPG from utils.utils import make_transition, Dict, RunningMeanStd os.makedirs('./model_weights', exist_ok=True)...
0.434581
0.128034
import unittest from http import HTTPStatus from eynnyd.response_builder import ResponseBuilder from eynnyd.exceptions import ErrorHandlingBuilderException, RouteNotFoundException, \ CallbackIncorrectNumberOfParametersException, NonCallableExceptionHandlerException, \ InvalidCookieHeaderException from eynnyd.e...
tests/plan_execution/test_error_handlers_builder.py
import unittest from http import HTTPStatus from eynnyd.response_builder import ResponseBuilder from eynnyd.exceptions import ErrorHandlingBuilderException, RouteNotFoundException, \ CallbackIncorrectNumberOfParametersException, NonCallableExceptionHandlerException, \ InvalidCookieHeaderException from eynnyd.e...
0.746139
0.199795
import re import fnmatch import threading class LocalStore(threading.local): """ A thread-local OpenStruct that can be used as a local cache. An instance is located at ``johnny.cache.local``, and is cleared on every request by the ``LocalStoreClearMiddleware``. It can be a thread-safe way to handle...
johnny/localstore.py
import re import fnmatch import threading class LocalStore(threading.local): """ A thread-local OpenStruct that can be used as a local cache. An instance is located at ``johnny.cache.local``, and is cleared on every request by the ``LocalStoreClearMiddleware``. It can be a thread-safe way to handle...
0.576304
0.170439
from random import shuffle from random import random def mprint(c): pass #print c init_black = [8, 17, 23, 31, 40]#, 50] init_crash = [5, 7, 10, 15, 20]#, 25] sumturn = 0 sumnbcrashpergame = 0 sumnbcrash = {} sumcrashspace = {} for black in init_black: sumnbcrash[black] = 0 sumcrashspace[black] = 0 nb = 0.0 fo...
lentest/lentest.py
from random import shuffle from random import random def mprint(c): pass #print c init_black = [8, 17, 23, 31, 40]#, 50] init_crash = [5, 7, 10, 15, 20]#, 25] sumturn = 0 sumnbcrashpergame = 0 sumnbcrash = {} sumcrashspace = {} for black in init_black: sumnbcrash[black] = 0 sumcrashspace[black] = 0 nb = 0.0 fo...
0.055304
0.163312
import tkinter as tk import os # Global configuration parameters to easily change the style. config = dict( # Global "theme" for all widgets. theme=dict( bg="black", fg="white", selectbackground="grey", insertbackground="white", borderwidth=3, font="Courier 9 bol...
tead/gui.py
import tkinter as tk import os # Global configuration parameters to easily change the style. config = dict( # Global "theme" for all widgets. theme=dict( bg="black", fg="white", selectbackground="grey", insertbackground="white", borderwidth=3, font="Courier 9 bol...
0.638723
0.132402
import os import tensorflow as tf import augmentations class CoronetOrgDataset: def __init__(self, image_height=512, image_width=512, max_rotation=50, max_shear=0.25, max_pixel_shift=10, max_pixel_scale_change=0.2, shuffle_buffer=1000): # General parameters self.image_height = i...
coronet/coronet_org_dataset.py
import os import tensorflow as tf import augmentations class CoronetOrgDataset: def __init__(self, image_height=512, image_width=512, max_rotation=50, max_shear=0.25, max_pixel_shift=10, max_pixel_scale_change=0.2, shuffle_buffer=1000): # General parameters self.image_height = i...
0.670069
0.296196
from random import randint from email_validator import validate_email from flask import Blueprint, render_template, request, flash, redirect, url_for from flask_login import login_user, logout_user, login_required, current_user from werkzeug.security import generate_password_hash, check_password_hash from .load import...
website/auth.py
from random import randint from email_validator import validate_email from flask import Blueprint, render_template, request, flash, redirect, url_for from flask_login import login_user, logout_user, login_required, current_user from werkzeug.security import generate_password_hash, check_password_hash from .load import...
0.387459
0.10904
male = [ 'BYEONG-HO', 'BYUNG-HO', 'DAE-JUNG', 'DONG-GEUN', 'DO-YUN', 'DURI', 'EUN', 'EUN-JUNG', 'GYEONG', 'HA-JUN', 'HANEUL', 'HWAN', 'HYE', 'HYEON', 'HYEON-JEONG', 'HYEON-JU', 'HYEON-U', 'HYUN', 'HYUN-JOO', 'HYUN-JUNG', 'HYUN-WOO', ...
john_doe/names/south_korea.py
male = [ 'BYEONG-HO', 'BYUNG-HO', 'DAE-JUNG', 'DONG-GEUN', 'DO-YUN', 'DURI', 'EUN', 'EUN-JUNG', 'GYEONG', 'HA-JUN', 'HANEUL', 'HWAN', 'HYE', 'HYEON', 'HYEON-JEONG', 'HYEON-JU', 'HYEON-U', 'HYUN', 'HYUN-JOO', 'HYUN-JUNG', 'HYUN-WOO', ...
0.260954
0.160069
import numpy as np import pathlib, sys import pressiotools.linalg as ptla #----------------------------------------------------------------- def leverageScores(ls, A): ls.data()[:] = np.einsum("ij,ij->i", A, A) #----------------------------------------------------------------- def _leverageScorePmf(l_scores, pmf_bl...
pressiotools/levscores.py
import numpy as np import pathlib, sys import pressiotools.linalg as ptla #----------------------------------------------------------------- def leverageScores(ls, A): ls.data()[:] = np.einsum("ij,ij->i", A, A) #----------------------------------------------------------------- def _leverageScorePmf(l_scores, pmf_bl...
0.399577
0.370994
from functools import partial from itertools import repeat from typing import (Any, List, Optional) from hypothesis import strategies from tests.port_tests.hints import (PortedContour, PortedPoint, PortedPo...
tests/port_tests/factories.py
from functools import partial from itertools import repeat from typing import (Any, List, Optional) from hypothesis import strategies from tests.port_tests.hints import (PortedContour, PortedPoint, PortedPo...
0.861786
0.37542
import sys import copy from parseipl import parseIplInst from parseide import parseIdePath def enumerate_reverse(L): for index in reversed(xrange(len(L))): yield index, L[index] def wxyzConjugate(q): return q[0], -q[1], -q[2], -q[3] def quatMultiply(q, p): return q[0]*p[0] - q[1]*p[1] - q[2]*p[2] - q[3]*p[3], ...
pathattach/pathdetach.py
import sys import copy from parseipl import parseIplInst from parseide import parseIdePath def enumerate_reverse(L): for index in reversed(xrange(len(L))): yield index, L[index] def wxyzConjugate(q): return q[0], -q[1], -q[2], -q[3] def quatMultiply(q, p): return q[0]*p[0] - q[1]*p[1] - q[2]*p[2] - q[3]*p[3], ...
0.076057
0.264874
from typing import Union from pyrogram import raw from pyrogram.scaffold import Scaffold class SetAdministratorTitle(Scaffold): async def set_administrator_title( self, chat_id: Union[int, str], user_id: Union[int, str], title: str, ) -> bool: """Set a...
backend/pyrogram/methods/chats/set_administrator_title.py
from typing import Union from pyrogram import raw from pyrogram.scaffold import Scaffold class SetAdministratorTitle(Scaffold): async def set_administrator_title( self, chat_id: Union[int, str], user_id: Union[int, str], title: str, ) -> bool: """Set a...
0.907729
0.174656
import typing from fiepipelib.locallymanagedtypes.data.abstractmanager import AbstractUserLocalTypeManager class GitLabServer(object): """ A GitLab Server to use for high level trust/storage and data. In theory, if the URL you use is a trustable URL, this is a trusworthy source. e.g. HTTPS or SSH ...
fiepipelib/gitlabserver/data/gitlab_server.py
import typing from fiepipelib.locallymanagedtypes.data.abstractmanager import AbstractUserLocalTypeManager class GitLabServer(object): """ A GitLab Server to use for high level trust/storage and data. In theory, if the URL you use is a trustable URL, this is a trusworthy source. e.g. HTTPS or SSH ...
0.500488
0.255721
import threading import requests import pytest from opentracing.mocktracer import MockTracer from opentracing.ext import tags as ext_tags from requests.sessions import Session from flask import Flask, request from werkzeug.serving import make_server from signalfx_tracing.libraries import requests_config as config fro...
tests/integration/requests_/test_instrumented_session.py
import threading import requests import pytest from opentracing.mocktracer import MockTracer from opentracing.ext import tags as ext_tags from requests.sessions import Session from flask import Flask, request from werkzeug.serving import make_server from signalfx_tracing.libraries import requests_config as config fro...
0.435421
0.237664
import pytest from psec import pinblock # fmt: off @pytest.mark.parametrize( ["pin", "pan", "error"], [ ("123", "55555555555555", "PIN must be between 4 and 12 digits long"), ("1234567890123", "55555555555555", "PIN must be between 4 and 12 digits long"), ("123A", "55555555555555", "PI...
tests/test_pinblock.py
import pytest from psec import pinblock # fmt: off @pytest.mark.parametrize( ["pin", "pan", "error"], [ ("123", "55555555555555", "PIN must be between 4 and 12 digits long"), ("1234567890123", "55555555555555", "PIN must be between 4 and 12 digits long"), ("123A", "55555555555555", "PI...
0.68941
0.74727
#python libs from __future__ import division import sys, time #numpy and scipy import numpy as np from scipy.ndimage import filters from matplotlib import pyplot as plt #Everything we need to do quaternion math from tf.transformations import * #openCV import cv2 import cv2.aruco as aruco #ros libraries import r...
catkin_ws/src/coatimunde/src/coati_pfinder.py
#python libs from __future__ import division import sys, time #numpy and scipy import numpy as np from scipy.ndimage import filters from matplotlib import pyplot as plt #Everything we need to do quaternion math from tf.transformations import * #openCV import cv2 import cv2.aruco as aruco #ros libraries import r...
0.269422
0.166709
import time import cv2 import datetime import imutils import json import os import numpy as np import tensorflow as tf os.environ['CUDA_VISIBLE_DEVICES'] = '0' gpu_options = tf.GPUOptions(per_process_gpu_memory_fraction=0.25) config = tf.ConfigProto(allow_soft_placement=True, gpu_options=gpu_options) sess = tf.Sessi...
project/car_exam/predict_plates.py
import time import cv2 import datetime import imutils import json import os import numpy as np import tensorflow as tf os.environ['CUDA_VISIBLE_DEVICES'] = '0' gpu_options = tf.GPUOptions(per_process_gpu_memory_fraction=0.25) config = tf.ConfigProto(allow_soft_placement=True, gpu_options=gpu_options) sess = tf.Sessi...
0.613584
0.219965
import configparser import logging from datetime import datetime, timedelta from pathlib import Path from typing import List, Tuple from pyspark.sql import SparkSession, DataFrame from pyspark.sql.functions import udf, regexp_replace from pyspark.sql.types import StructType, StructField, StringType, DoubleType, Integ...
etl.py
import configparser import logging from datetime import datetime, timedelta from pathlib import Path from typing import List, Tuple from pyspark.sql import SparkSession, DataFrame from pyspark.sql.functions import udf, regexp_replace from pyspark.sql.types import StructType, StructField, StringType, DoubleType, Integ...
0.782995
0.268995
import pycuda import pycuda.autoinit import pycuda.gpuarray as gpuarray import numpy as np from codepy.cgen import * from codepy.bpl import BoostPythonModule from codepy.cuda import CudaModule #Make a host_module, compiled for CPU host_mod = BoostPythonModule() #Make a device module, compiled with NVCC nvcc_mod = Cu...
thrust_sort.py
import pycuda import pycuda.autoinit import pycuda.gpuarray as gpuarray import numpy as np from codepy.cgen import * from codepy.bpl import BoostPythonModule from codepy.cuda import CudaModule #Make a host_module, compiled for CPU host_mod = BoostPythonModule() #Make a device module, compiled with NVCC nvcc_mod = Cu...
0.439026
0.18769
import urllib2 def get_item_url(url): if url.find('?') < 0: num_iid = url else: num_iid = 0 for para in url.split('?')[1].split('&'): k, v = para.split('=') if k == 'id': num_iid = v return 'http://item.taobao.com/item.htm?id=' + num_iid ...
actions/checker.py
import urllib2 def get_item_url(url): if url.find('?') < 0: num_iid = url else: num_iid = 0 for para in url.split('?')[1].split('&'): k, v = para.split('=') if k == 'id': num_iid = v return 'http://item.taobao.com/item.htm?id=' + num_iid ...
0.202167
0.153517
import sqlite3 def main( ): db = sqlite3.connect( 'test.db' ) # Create the database file db.execute( 'drop table if exists test' ) # Create a new table if it didn't already exist db.execute( 'create table test (t1 text, i1 int)' ) # To populate the table db.execute( 'insert into test (t1, i1) value...
Mini Challenge/AddressesChallenge.py
import sqlite3 def main( ): db = sqlite3.connect( 'test.db' ) # Create the database file db.execute( 'drop table if exists test' ) # Create a new table if it didn't already exist db.execute( 'create table test (t1 text, i1 int)' ) # To populate the table db.execute( 'insert into test (t1, i1) value...
0.222109
0.283248
import os import logging import shutil import jsonpickle from distutils.file_util import copy_file from distutils.dir_util import copy_tree, mkpath from ebbs import Builder # Class name is what is used at cli, so we defy convention here in favor of ease-of-use. class cpp(Builder): def __init__(this, name="C++ Bui...
inc/cpp.py
import os import logging import shutil import jsonpickle from distutils.file_util import copy_file from distutils.dir_util import copy_tree, mkpath from ebbs import Builder # Class name is what is used at cli, so we defy convention here in favor of ease-of-use. class cpp(Builder): def __init__(this, name="C++ Bui...
0.209712
0.075312
import configparser import sys from tkinter import Tk, Canvas, font, mainloop from configparser import NoSectionError, NoOptionError from pyowm import OWM from datetime import datetime, timedelta from pyowm.exceptions.api_call_error import APIInvalidSSLCertificateError #standard size of period rectangles for v...
src/test/visualizeTk/forecast/CityBarChart.py
import configparser import sys from tkinter import Tk, Canvas, font, mainloop from configparser import NoSectionError, NoOptionError from pyowm import OWM from datetime import datetime, timedelta from pyowm.exceptions.api_call_error import APIInvalidSSLCertificateError #standard size of period rectangles for v...
0.485356
0.2341
from __future__ import division, absolute_import from functools import partial from pickle import TRUE from warnings import simplefilter from caffe2.python.workspace import FetchBlob from numpy.core.fromnumeric import shape from numpy.core.records import format_parser from numpy.lib.function_base import _flip_di...
torchreid/models/mudeep3modal.py
from __future__ import division, absolute_import from functools import partial from pickle import TRUE from warnings import simplefilter from caffe2.python.workspace import FetchBlob from numpy.core.fromnumeric import shape from numpy.core.records import format_parser from numpy.lib.function_base import _flip_di...
0.85738
0.118845
import pytest from ..token_classes import ( OfflineToken, OnlineToken, PrivateToken, offline_token_data, online_token_data, test_information, ) @pytest.mark.asyncio async def test_online_token(): # Create a new token online_token = await OnlineToken.load( store_name=test_infor...
tests/token/test_initialization.py
import pytest from ..token_classes import ( OfflineToken, OnlineToken, PrivateToken, offline_token_data, online_token_data, test_information, ) @pytest.mark.asyncio async def test_online_token(): # Create a new token online_token = await OnlineToken.load( store_name=test_infor...
0.451568
0.374305
import sqlite3 import tkinter as tk from tkinter import ttk from tkinter import messagebox from schema import * class Application(tk.Toplevel): def __init__(self, master=None): tk.Toplevel.__init__(self, master) self.withdraw() self.frame = tk.Frame(self) self.frame.pack(...
ResetDatabase.py
import sqlite3 import tkinter as tk from tkinter import ttk from tkinter import messagebox from schema import * class Application(tk.Toplevel): def __init__(self, master=None): tk.Toplevel.__init__(self, master) self.withdraw() self.frame = tk.Frame(self) self.frame.pack(...
0.277571
0.073397
import getpass import os import socket from datetime import datetime as dt class Log: """This is a small and simple log file creator/writer class. The calling program is responsible for passing the proper arguments to create the log file header. For example:: (printheader=True, headertext='some,...
utils4/log.py
import getpass import os import socket from datetime import datetime as dt class Log: """This is a small and simple log file creator/writer class. The calling program is responsible for passing the proper arguments to create the log file header. For example:: (printheader=True, headertext='some,...
0.69451
0.419945
import os from pathlib import Path import random import pytest from ouroboros.tools.pproject import git from ouroboros.tools.pproject import pproject from tests.test_config import testing_project_kwargs CURRENT_PATH = Path.cwd() # ----------------------------------------------------------------------------- def cr...
tests/test_git.py
import os from pathlib import Path import random import pytest from ouroboros.tools.pproject import git from ouroboros.tools.pproject import pproject from tests.test_config import testing_project_kwargs CURRENT_PATH = Path.cwd() # ----------------------------------------------------------------------------- def cr...
0.314577
0.280038
import json def append_cells(obj, key): return ''.join(["<td>"+x[key]+"</td>" for x in obj]) def append_cells2(obj, key, key2): return ''.join(["<td>"+x[key][key2]+"</td>" for x in obj]) def append_int_cells(obj, key): return ''.join(["<td>"+str(x[key])+"</td>" for x in obj]) def append_int_cells2(obj,...
perf/scripts/format_html_output.py
import json def append_cells(obj, key): return ''.join(["<td>"+x[key]+"</td>" for x in obj]) def append_cells2(obj, key, key2): return ''.join(["<td>"+x[key][key2]+"</td>" for x in obj]) def append_int_cells(obj, key): return ''.join(["<td>"+str(x[key])+"</td>" for x in obj]) def append_int_cells2(obj,...
0.185799
0.176388
#登陆注册相关业务, # #python3自带hashlib 模块,直接导入 from py import dbutils from py import utils import json #注册 def register(username_front, passwd_front): #前台传参数 # json数据 data = {} # 要返回的数据 code = 500 # 返回给调用者的值,默认是500 Number类型的 msg = '注册失败' count = 0 regiser_sql_return_json_data = list() ...
py/c_account.py
#登陆注册相关业务, # #python3自带hashlib 模块,直接导入 from py import dbutils from py import utils import json #注册 def register(username_front, passwd_front): #前台传参数 # json数据 data = {} # 要返回的数据 code = 500 # 返回给调用者的值,默认是500 Number类型的 msg = '注册失败' count = 0 regiser_sql_return_json_data = list() ...
0.162845
0.115561
from __future__ import division, print_function, absolute_import import rospy import numpy as np from qcar.product_QCar import QCar from qcar.q_interpretation import * from std_msgs.msg import String, Float64 from geometry_msgs.msg import Vector3Stamped from sensor_msgs.msg import BatteryState import time class QCa...
src/qcar/src/qcarnode.py
from __future__ import division, print_function, absolute_import import rospy import numpy as np from qcar.product_QCar import QCar from qcar.q_interpretation import * from std_msgs.msg import String, Float64 from geometry_msgs.msg import Vector3Stamped from sensor_msgs.msg import BatteryState import time class QCa...
0.486088
0.120646
from flask import render_template from flask_babel import gettext from flask_mail import Message from .extensions import mail def send_duplicate_registration_email(email): msg = Message( subject=gettext('Duplicate Registration'), recipients=[email], body=render_template( 'dupli...
swpt_login/emails.py
from flask import render_template from flask_babel import gettext from flask_mail import Message from .extensions import mail def send_duplicate_registration_email(email): msg = Message( subject=gettext('Duplicate Registration'), recipients=[email], body=render_template( 'dupli...
0.362743
0.064624
from flask import json import random import main from tests.sample_requests import sample_facebook_text_request, sample_facebook_flac_request_en, \ sample_facebook_opus_request_en, sample_facebook_opus_request_it def test_post_facebook_text(): main.app.testing = True client = main.app.test_client() ...
tests/test_main.py
from flask import json import random import main from tests.sample_requests import sample_facebook_text_request, sample_facebook_flac_request_en, \ sample_facebook_opus_request_en, sample_facebook_opus_request_it def test_post_facebook_text(): main.app.testing = True client = main.app.test_client() ...
0.474144
0.192919
import re import csv import requests from bs4 import BeautifulSoup HEADERS = { 'user-agent': 'User-Agent: Mozilla/5.0 (Macintosh; Intel Mac OS X 10.15; rv:84.0) Gecko/20100101 Firefox/84.0' } BASE_URL = 'https://www.mpo.cz' START_URLS = [ 'https://www.mpo.cz/cz/energetika/statistika/obnovitelne-zdroje-energ...
mpo/links.py
import re import csv import requests from bs4 import BeautifulSoup HEADERS = { 'user-agent': 'User-Agent: Mozilla/5.0 (Macintosh; Intel Mac OS X 10.15; rv:84.0) Gecko/20100101 Firefox/84.0' } BASE_URL = 'https://www.mpo.cz' START_URLS = [ 'https://www.mpo.cz/cz/energetika/statistika/obnovitelne-zdroje-energ...
0.302597
0.09343
from sandbox.rocky.tf.core.layers_powered import LayersPowered import sandbox.rocky.tf.core.layers as L from sandbox.rocky.tf.core.network import MLP from rllab.core.serializable import Serializable from sandbox.rocky.tf.distributions.categorical import Categorical from sandbox.rocky.tf.policies.base import StochasticP...
sandbox/rocky/tf/policies/categorical_mlp_policy.py
from sandbox.rocky.tf.core.layers_powered import LayersPowered import sandbox.rocky.tf.core.layers as L from sandbox.rocky.tf.core.network import MLP from rllab.core.serializable import Serializable from sandbox.rocky.tf.distributions.categorical import Categorical from sandbox.rocky.tf.policies.base import StochasticP...
0.815894
0.346956
# Author: <NAME> #$Id$ from exceptions import InvalidParamterException import string import roslib roslib.load_manifest('sick_ldmrs') import rospy from sick_ldmrs.cfg import ldmrsConfig #config auto-generated by CMake from math import pi class LDMRSParams(object): """ parameter object converts between ROS and l...
src/sick_ldmrs/params.py
# Author: <NAME> #$Id$ from exceptions import InvalidParamterException import string import roslib roslib.load_manifest('sick_ldmrs') import rospy from sick_ldmrs.cfg import ldmrsConfig #config auto-generated by CMake from math import pi class LDMRSParams(object): """ parameter object converts between ROS and l...
0.538983
0.291208
from numpy import array, pi, sqrt, arcsin from matplotlib_venn._venn3 import * from matplotlib_venn._math import * def test_circle_intersection(): f = lambda x: (sqrt(1-x**2)*x + arcsin(x))*0.5 # Integral [sqrt(1 - x^2) dx] area_x = lambda R: 4*R**2*(f(1) - f(0.5)) # Area of intersection of ...
tests/venn3_test.py
from numpy import array, pi, sqrt, arcsin from matplotlib_venn._venn3 import * from matplotlib_venn._math import * def test_circle_intersection(): f = lambda x: (sqrt(1-x**2)*x + arcsin(x))*0.5 # Integral [sqrt(1 - x^2) dx] area_x = lambda R: 4*R**2*(f(1) - f(0.5)) # Area of intersection of ...
0.676086
0.75224
import numpy as np import pdb from scipy.stats import percentileofscore def generate_g(g_config): # Return set of examples x, where first n_groups features # are a one-hot-encoding of the group # and the remaining feature are randomly sampled from a multivariate Gaussian std = g_config['std'] * np.eye...
relative_prevalence_benchmark/simulation_helpers.py
import numpy as np import pdb from scipy.stats import percentileofscore def generate_g(g_config): # Return set of examples x, where first n_groups features # are a one-hot-encoding of the group # and the remaining feature are randomly sampled from a multivariate Gaussian std = g_config['std'] * np.eye...
0.592313
0.494873
from selenium.webdriver.support.ui import Select from model.contact import Contact import re class ContactHelper: def __init__(self, app): self.app = app def fill_contact_info(self, contact): wd = self.app.wd self.fill_contact_form(contact) wd.find_element_by_name("submit").c...
fixture/contact.py
from selenium.webdriver.support.ui import Select from model.contact import Contact import re class ContactHelper: def __init__(self, app): self.app = app def fill_contact_info(self, contact): wd = self.app.wd self.fill_contact_form(contact) wd.find_element_by_name("submit").c...
0.294519
0.079104
from pants.backend.jvm.subsystems.junit import JUnit from pants.backend.jvm.targets.jvm_target import JvmTarget from pants.backend.jvm.targets.runtime_platform_mixin import RuntimePlatformMixin from pants.base.deprecated import deprecated, deprecated_conditional from pants.base.exceptions import TargetDefinitionExcep...
src/python/pants/backend/jvm/targets/junit_tests.py
from pants.backend.jvm.subsystems.junit import JUnit from pants.backend.jvm.targets.jvm_target import JvmTarget from pants.backend.jvm.targets.runtime_platform_mixin import RuntimePlatformMixin from pants.base.deprecated import deprecated, deprecated_conditional from pants.base.exceptions import TargetDefinitionExcep...
0.756178
0.107813
import tornado.ioloop import tornado.web import tornado.websocket import tornado.httpserver import json class WebSocketHandler(tornado.websocket.WebSocketHandler): clients = [] telemetry_entry_list = [] last_msg = None browser_location_msg = None device_num = 0; def open(self, *args): ...
vehicle/vehicle-io-api-server.py
import tornado.ioloop import tornado.web import tornado.websocket import tornado.httpserver import json class WebSocketHandler(tornado.websocket.WebSocketHandler): clients = [] telemetry_entry_list = [] last_msg = None browser_location_msg = None device_num = 0; def open(self, *args): ...
0.058824
0.046703
import inspect import json import time from pathlib import Path import pytest import redis from confluent_kafka import admin from factory import Factory from pytest_factoryboy import register from django.conf import settings from common.adapters.fhir_api import fhir_api from tests.conftest import load_export_data, l...
tests/river/conftest.py
import inspect import json import time from pathlib import Path import pytest import redis from confluent_kafka import admin from factory import Factory from pytest_factoryboy import register from django.conf import settings from common.adapters.fhir_api import fhir_api from tests.conftest import load_export_data, l...
0.53437
0.169406
import os import sys from argparse import ArgumentParser import pandas as pd import numpy as np import csv from collections import defaultdict from collections import ChainMap def extract_wp(document): wp_corpus_list = [] with open(document) as input_f: for line in input_f: wp = line.strip().split()[0] wp_co...
vectors_concatenation.py
import os import sys from argparse import ArgumentParser import pandas as pd import numpy as np import csv from collections import defaultdict from collections import ChainMap def extract_wp(document): wp_corpus_list = [] with open(document) as input_f: for line in input_f: wp = line.strip().split()[0] wp_co...
0.168857
0.141459
import os from nose.plugins.attrib import attr from mi.core.log import get_logger from mi.dataset.dataset_parser import DataSetDriverConfigKeys from mi.dataset.driver.winch_cspp.resource import RESOURCE_PATH from mi.dataset.parser.winch_cspp import WinchCsppParser from mi.dataset.test.test_parser import ParserUnitTest...
mi/dataset/parser/test/test_winch_cspp.py
import os from nose.plugins.attrib import attr from mi.core.log import get_logger from mi.dataset.dataset_parser import DataSetDriverConfigKeys from mi.dataset.driver.winch_cspp.resource import RESOURCE_PATH from mi.dataset.parser.winch_cspp import WinchCsppParser from mi.dataset.test.test_parser import ParserUnitTest...
0.382487
0.216436
from streamselect.repository.transition_fsm import TransitionFSM def test_add_transition() -> None: """Test adding a transition to the transition FSM""" # 0 -> 1 -> 0 -> 2 -> 0 -> 1 # Adjacency List # 0 : {1: 2, 2: 1} # 1 : {0: 1} # 2: {0: 1} fsm = TransitionFSM() state_ids = [0, 1, 0...
streamselect/repository/test_transition_fsm.py
from streamselect.repository.transition_fsm import TransitionFSM def test_add_transition() -> None: """Test adding a transition to the transition FSM""" # 0 -> 1 -> 0 -> 2 -> 0 -> 1 # Adjacency List # 0 : {1: 2, 2: 1} # 1 : {0: 1} # 2: {0: 1} fsm = TransitionFSM() state_ids = [0, 1, 0...
0.869936
0.841728
import os, sys, logging, json from cdumay_rest_client.client import RESTClient class TatManager(object): def __init__(self, config="~/.tatcli/config.json"): self.root = os.curdir self.file_version = os.path.join(self.root, "VERSION") self.file_topic = os.path.join(self.root, "TOPIC") ...
src/tat_pytools/common.py
import os, sys, logging, json from cdumay_rest_client.client import RESTClient class TatManager(object): def __init__(self, config="~/.tatcli/config.json"): self.root = os.curdir self.file_version = os.path.join(self.root, "VERSION") self.file_topic = os.path.join(self.root, "TOPIC") ...
0.311113
0.05257
import allure import pytest from selenium.common import exceptions from creds import Credentials from tests.base_test import BaseTestCase from common import exceptions as CE from ui.pages.dashboard_page import DashboardPage from ui.pages.campaign_page import CampaignPage from ui.pages.segments_page import SegmentsPag...
tests/test_ui_target.py
import allure import pytest from selenium.common import exceptions from creds import Credentials from tests.base_test import BaseTestCase from common import exceptions as CE from ui.pages.dashboard_page import DashboardPage from ui.pages.campaign_page import CampaignPage from ui.pages.segments_page import SegmentsPag...
0.273089
0.305179
from django.core.validators import MinValueValidator from django.db import models class Category(models.Model): BAKERY = 'Bakery' FRUITS = 'Fruits' VEGETABLES = 'Vegetables' MEAT = 'Meat' RICE_AND_PASTA = 'Rice and Pasta' FISH_AND_SEAFOOD = 'Fish and Seafood' OILS_VINEGAR_AND_DRIED_HERBS =...
grocery_store/grocery_store/product/models.py
from django.core.validators import MinValueValidator from django.db import models class Category(models.Model): BAKERY = 'Bakery' FRUITS = 'Fruits' VEGETABLES = 'Vegetables' MEAT = 'Meat' RICE_AND_PASTA = 'Rice and Pasta' FISH_AND_SEAFOOD = 'Fish and Seafood' OILS_VINEGAR_AND_DRIED_HERBS =...
0.547222
0.199503
import SimpleITK as sitk import pymia.filtering.filter as pymia_fltr class BinaryThreshold(pymia_fltr.Filter): def __init__(self, threshold: float): """Represents a binary threshold image filter. Args: threshold (float): The threshold value. """ super().__init__() ...
pymia/filtering/postprocessing.py
import SimpleITK as sitk import pymia.filtering.filter as pymia_fltr class BinaryThreshold(pymia_fltr.Filter): def __init__(self, threshold: float): """Represents a binary threshold image filter. Args: threshold (float): The threshold value. """ super().__init__() ...
0.946523
0.657628
from collections.abc import MutableMapping import math import copy sides = [ (-1, 0), (0, 1), (1, 0), (0, -1), (-1, 1), (1, -1), (1, 1), (-1, -1), ] class Board(MutableMapping): """This is a test.""" def __init__(self, **options): if "_data" in options: # ...
udebs/board.py
from collections.abc import MutableMapping import math import copy sides = [ (-1, 0), (0, 1), (1, 0), (0, -1), (-1, 1), (1, -1), (1, 1), (-1, -1), ] class Board(MutableMapping): """This is a test.""" def __init__(self, **options): if "_data" in options: # ...
0.840193
0.342957
import exceptions import clientPackets import glob import fokabot import consoleHelper import bcolors import serverPackets def handle(userToken, packetData): """ Event called when someone sends a public message userToken -- request user token packetData -- request data bytes """ try: # Get uesrToken data u...
c.ppy.sh/sendPublicMessageEvent.py
import exceptions import clientPackets import glob import fokabot import consoleHelper import bcolors import serverPackets def handle(userToken, packetData): """ Event called when someone sends a public message userToken -- request user token packetData -- request data bytes """ try: # Get uesrToken data u...
0.247714
0.168891
import asyncio import inspect import logging from collections import namedtuple from zmq import Again from meru.actions import Action, Ping, RequireState from meru.exceptions import PingTimeout from meru.helpers import get_full_path_to_class, inspect_action_handler from meru.state import StateNode HANDLERS = dict() ...
src/meru/handlers.py
import asyncio import inspect import logging from collections import namedtuple from zmq import Again from meru.actions import Action, Ping, RequireState from meru.exceptions import PingTimeout from meru.helpers import get_full_path_to_class, inspect_action_handler from meru.state import StateNode HANDLERS = dict() ...
0.303835
0.146026
import tensorflow as tf import numpy as np import tensorflow as tf import numpy as np import os def xavier_init(size): in_dim = size[0] xavier_stddev = 1. / tf.sqrt(in_dim / 2.) return tf.random_normal(shape=size, stddev=xavier_stddev) class New_Start_Invariant_Mnist( object ): def __init__(...
model/new_start_invariant.py
import tensorflow as tf import numpy as np import tensorflow as tf import numpy as np import os def xavier_init(size): in_dim = size[0] xavier_stddev = 1. / tf.sqrt(in_dim / 2.) return tf.random_normal(shape=size, stddev=xavier_stddev) class New_Start_Invariant_Mnist( object ): def __init__(...
0.431704
0.18248
import numpy as np import tensorflow as tf from weighted_average import weighted_average def kpn_conv2d(x, filter_size, out_channel, is_training=False, name='conv', relu=True): with tf.variable_scope(name, reuse=tf.AUTO_REUSE): in_shape = x.get_shape().as_list() in_channel = in_shape[-1] ...
codes/model.py
import numpy as np import tensorflow as tf from weighted_average import weighted_average def kpn_conv2d(x, filter_size, out_channel, is_training=False, name='conv', relu=True): with tf.variable_scope(name, reuse=tf.AUTO_REUSE): in_shape = x.get_shape().as_list() in_channel = in_shape[-1] ...
0.828419
0.401688
import torch from torch import distributions from torch import nn from torch.nn import functional as F from pytorch_generative import nn as pg_nn from pytorch_generative.models import base def _elu_conv_elu(conv, x): return F.elu(conv(F.elu(x))) class ResidualBlock(nn.Module): """Residual block with a gated a...
pytorch_generative/models/pixel_snail.py
import torch from torch import distributions from torch import nn from torch.nn import functional as F from pytorch_generative import nn as pg_nn from pytorch_generative.models import base def _elu_conv_elu(conv, x): return F.elu(conv(F.elu(x))) class ResidualBlock(nn.Module): """Residual block with a gated a...
0.973645
0.510985
from rest_framework import serializers from .models import * class BookshelfSerializer(serializers.ModelSerializer): class Meta: model = Bookshelf fields = ('name',) class FormatSerializer(serializers.ModelSerializer): class Meta: model = Format fields = ('book', 'mime_type'...
books/serializers.py
from rest_framework import serializers from .models import * class BookshelfSerializer(serializers.ModelSerializer): class Meta: model = Bookshelf fields = ('name',) class FormatSerializer(serializers.ModelSerializer): class Meta: model = Format fields = ('book', 'mime_type'...
0.690455
0.105856
import datetime import os import shutil import subprocess import tempfile from odkim_rotate.key_table import * from odkim_rotate import utils class Manager: def __init__(self, verbose): self.verbose = verbose self.scratch_dir = tempfile.mkdtemp() self.starting_dir = os.getcwd() # ...
odkim_rotate/manager.py
import datetime import os import shutil import subprocess import tempfile from odkim_rotate.key_table import * from odkim_rotate import utils class Manager: def __init__(self, verbose): self.verbose = verbose self.scratch_dir = tempfile.mkdtemp() self.starting_dir = os.getcwd() # ...
0.178025
0.13489
# -------------------------------------------------------------------------- # |Purpose: | # |--------------------------------------------------------------------------| # |Check Kubra outage map for last update time to ensure that the last | ...
functioneririzerFluxCapacitor.py
# -------------------------------------------------------------------------- # |Purpose: | # |--------------------------------------------------------------------------| # |Check Kubra outage map for last update time to ensure that the last | ...
0.567817
0.147218
from Tkinter import * from GridLocation import * import tkMessageBox class TkHelper(object): _wraplength = 350 def showAlert(self, message): """ Show a new window as an alert. :param message: The message in the label to be shown """ tkMessageBox.showinfo("Error", mess...
Python/tax/TkHelper.py
from Tkinter import * from GridLocation import * import tkMessageBox class TkHelper(object): _wraplength = 350 def showAlert(self, message): """ Show a new window as an alert. :param message: The message in the label to be shown """ tkMessageBox.showinfo("Error", mess...
0.902156
0.579043
from __future__ import unicode_literals from django.contrib import admin # Register your models here. from .models import Type from .models import Text from .models import Rating from .models import UserRating from .models import Question from .models import TextComment from django.http import HttpResponse from djan...
bettertexts/admin.py
from __future__ import unicode_literals from django.contrib import admin # Register your models here. from .models import Type from .models import Text from .models import Rating from .models import UserRating from .models import Question from .models import TextComment from django.http import HttpResponse from djan...
0.465145
0.081703
import torch from torch.nn.utils import rnn from torch.utils.data import Dataset, DataLoader from datasets.vocab import Vocabulary class EmbeddingDataset(Dataset): '''This class serves as a wrapper for an existing dataset that serves a mapped representation of original sentences. This is useful in training ...
datasets/embed.py
import torch from torch.nn.utils import rnn from torch.utils.data import Dataset, DataLoader from datasets.vocab import Vocabulary class EmbeddingDataset(Dataset): '''This class serves as a wrapper for an existing dataset that serves a mapped representation of original sentences. This is useful in training ...
0.927091
0.649884
# Strictly For Educational/Ethical Pen Testing Purposes ONLY. I condone no illegal activities with this script # Use of this code for unlawful purposes is wrong in every sense of the word, a crime, and strictly discouraged # To help discourage/limit illegal use of this code, advanced functionality of the script has be...
email_dictionary_attack.py
# Strictly For Educational/Ethical Pen Testing Purposes ONLY. I condone no illegal activities with this script # Use of this code for unlawful purposes is wrong in every sense of the word, a crime, and strictly discouraged # To help discourage/limit illegal use of this code, advanced functionality of the script has be...
0.327238
0.277383
import os import vlc import center_tk_window as centerTK import tkinter as tk from tkinter import * import tkinter.font as tkFont import tkinter.filedialog as fdialog import tkinter.messagebox as messagebox print("guage ui") Instance = vlc.Instance(['--no-xlib']) player = Instance.media_player_new() Media = Instan...
guage_ui.py
import os import vlc import center_tk_window as centerTK import tkinter as tk from tkinter import * import tkinter.font as tkFont import tkinter.filedialog as fdialog import tkinter.messagebox as messagebox print("guage ui") Instance = vlc.Instance(['--no-xlib']) player = Instance.media_player_new() Media = Instan...
0.135104
0.091139
import pandas as pd from DataHandler.mongoObjects import CollectionManager from datetime import date from datetime import datetime as dt import datedelta import numpy as np features = ['Asset Growth', 'Book Value per Share Growth', 'Debt Growth', 'Dividends per Basic Common Share Growth', 'EBIT Growth', 'E...
DueDiligence/addFundamentals.py
import pandas as pd from DataHandler.mongoObjects import CollectionManager from datetime import date from datetime import datetime as dt import datedelta import numpy as np features = ['Asset Growth', 'Book Value per Share Growth', 'Debt Growth', 'Dividends per Basic Common Share Growth', 'EBIT Growth', 'E...
0.679604
0.461441
from neodiff import PyDiffGenerator from neodiff import NeoDiff from boa.compiler import Compiler import random import secrets import struct import shutil from logzero import logger # random.seed(1) while True: seed = secrets.randbelow(1 << 32) # logger.info() code = PyDiffGenerator.run( seed=seed...
NeoSemanticDiffFuzzer.py
from neodiff import PyDiffGenerator from neodiff import NeoDiff from boa.compiler import Compiler import random import secrets import struct import shutil from logzero import logger # random.seed(1) while True: seed = secrets.randbelow(1 << 32) # logger.info() code = PyDiffGenerator.run( seed=seed...
0.10862
0.176334
import sys from pathlib import Path import os import copy self_file_path = Path(__file__).resolve() project_folder_path = str(self_file_path.parent.parent.parent) sys.path.append(project_folder_path) from common_classes.file_folder_handle import FileListConvert, TraversalFoldersFiles class CreateInitFile(object): ...
create_init_file.py
import sys from pathlib import Path import os import copy self_file_path = Path(__file__).resolve() project_folder_path = str(self_file_path.parent.parent.parent) sys.path.append(project_folder_path) from common_classes.file_folder_handle import FileListConvert, TraversalFoldersFiles class CreateInitFile(object): ...
0.104626
0.098209
from pycket.base import W_Object from pycket.error import SchemeException from pycket import values, values_string from pycket import regexp from rpython.rlib.rsre import rsre_core, rsre_char from rpython.rlib import buffer, jit import sys CACHE = regexp.RegexpCache() class PortBuffer(buffer.Buffer): """match co...
pycket/values_regex.py
from pycket.base import W_Object from pycket.error import SchemeException from pycket import values, values_string from pycket import regexp from rpython.rlib.rsre import rsre_core, rsre_char from rpython.rlib import buffer, jit import sys CACHE = regexp.RegexpCache() class PortBuffer(buffer.Buffer): """match co...
0.4917
0.288839
from naoqi import ALProxy names = list() times = list() keys = list() names.append("HeadPitch") times.append([0.8, 1.56, 2.24, 2.8, 3.48, 4.6]) keys.append([0.29602, -0.170316, -0.340591, -0.0598679, -0.193327, -0.01078]) names.append("HeadYaw") times.append([0.8, 1.56, 2.24, 2.8, 3.48, 4.6]) keys.append([-0.135034, ...
moves/hello.py
from naoqi import ALProxy names = list() times = list() keys = list() names.append("HeadPitch") times.append([0.8, 1.56, 2.24, 2.8, 3.48, 4.6]) keys.append([0.29602, -0.170316, -0.340591, -0.0598679, -0.193327, -0.01078]) names.append("HeadYaw") times.append([0.8, 1.56, 2.24, 2.8, 3.48, 4.6]) keys.append([-0.135034, ...
0.110892
0.206934
import pyglet from pyglet.window import key import logging from TempoFinder import TempoFinder from TwoFeetTempoMove import TwoFeetTempoMove if __name__ == '__main__': logging.basicConfig(filename='TwisterTempo.log', level=logging.INFO, filemode='w') # a sample rate of 8000 is somehow...
TwisterTempo.py
import pyglet from pyglet.window import key import logging from TempoFinder import TempoFinder from TwoFeetTempoMove import TwoFeetTempoMove if __name__ == '__main__': logging.basicConfig(filename='TwisterTempo.log', level=logging.INFO, filemode='w') # a sample rate of 8000 is somehow...
0.288369
0.280429
import os import argparse import pandas as pd parser = argparse.ArgumentParser() parser.add_argument('-g', '--gsl', help='Gene set libraries (comma separated strings)', default='KEGG_2016,ARCHS4_Tissues,ChEA_2016') parser.add_argument('-e', '--etype', help='Enrichment type', default='samplewise-z') # predict pathw...
scripts/check_and_update_existing_GEO_datasets.py
import os import argparse import pandas as pd parser = argparse.ArgumentParser() parser.add_argument('-g', '--gsl', help='Gene set libraries (comma separated strings)', default='KEGG_2016,ARCHS4_Tissues,ChEA_2016') parser.add_argument('-e', '--etype', help='Enrichment type', default='samplewise-z') # predict pathw...
0.102165
0.144511
import requests import datetime from pyquery import PyQuery as pq def getUserNameFromId(userId): url=f'https://www.nicovideo.jp/user/{str(userId)}' print(f'Access to {url}...') dom = pq(url) result=dom('head').find('meta[property="profile:username"]').attr['content'] print(f'Success! userName = {re...
src/main.py
import requests import datetime from pyquery import PyQuery as pq def getUserNameFromId(userId): url=f'https://www.nicovideo.jp/user/{str(userId)}' print(f'Access to {url}...') dom = pq(url) result=dom('head').find('meta[property="profile:username"]').attr['content'] print(f'Success! userName = {re...
0.140779
0.139836