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
from __future__ import division from __future__ import absolute_import from __future__ import print_function from __future__ import unicode_literals from abc import abstractmethod from builtins import range import json from asciimatics.renderers.base import DynamicRenderer from asciimatics.screen import Screen from as...
asciimatics/renderers/players.py
from __future__ import division from __future__ import absolute_import from __future__ import print_function from __future__ import unicode_literals from abc import abstractmethod from builtins import range import json from asciimatics.renderers.base import DynamicRenderer from asciimatics.screen import Screen from as...
0.66236
0.131535
from settings import OSM_COMPONENTS, LOGGING from httpclient.client import Client import logging.config import urllib3 urllib3.disable_warnings(urllib3.exceptions.InsecureRequestWarning) logging.config.dictConfig(LOGGING) logger = logging.getLogger("osm") class User(object): """Description of User class""" ...
nbiapi/user.py
from settings import OSM_COMPONENTS, LOGGING from httpclient.client import Client import logging.config import urllib3 urllib3.disable_warnings(urllib3.exceptions.InsecureRequestWarning) logging.config.dictConfig(LOGGING) logger = logging.getLogger("osm") class User(object): """Description of User class""" ...
0.755907
0.087291
"""base class for columns""" from ELDAmwl.component.interface import ILogger from ELDAmwl.utils.constants import NC_FILL_BYTE from ELDAmwl.utils.constants import NC_FILL_INT from zope import component import numpy as np import xarray as xr class Columns(object): """ base column class (2 dimensional: (time, l...
ELDAmwl/bases/columns.py
"""base class for columns""" from ELDAmwl.component.interface import ILogger from ELDAmwl.utils.constants import NC_FILL_BYTE from ELDAmwl.utils.constants import NC_FILL_INT from zope import component import numpy as np import xarray as xr class Columns(object): """ base column class (2 dimensional: (time, l...
0.790045
0.350394
import pytest import pandas as pd from delphi_utils.geomap import GeoMapper from delphi_nchs_mortality.pull import pull_nchs_mortality_data, standardize_columns from delphi_nchs_mortality.constants import METRICS # export_start_date = PARAMS["indicator"]["export_start_date"] EXPORT_DIR = "./receiving" TOKEN = "" c...
nchs_mortality/tests/test_pull.py
import pytest import pandas as pd from delphi_utils.geomap import GeoMapper from delphi_nchs_mortality.pull import pull_nchs_mortality_data, standardize_columns from delphi_nchs_mortality.constants import METRICS # export_start_date = PARAMS["indicator"]["export_start_date"] EXPORT_DIR = "./receiving" TOKEN = "" c...
0.542379
0.582491
import os import glob import pandas as pd import argparse def args(): parser = argparse.ArgumentParser() parser.add_argument("-f", "--folder", required=True, help="Enter into the folder") parser.add_argument("-omega", "--omega_path", required=True, help="Enter the O...
modeling_script.py
import os import glob import pandas as pd import argparse def args(): parser = argparse.ArgumentParser() parser.add_argument("-f", "--folder", required=True, help="Enter into the folder") parser.add_argument("-omega", "--omega_path", required=True, help="Enter the O...
0.299617
0.164987
import unittest from mock import patch from PyQt5.QtCore import QSettings from inselect.gui.plugins.barcode_dialog import BarcodeDialog from .gui_test import GUITest class TestBarcodeDialog(GUITest): """Tests the config dialog box of the 'Read barcode' plugin """ @patch.object(QSettings, 'setValue') ...
inselect/tests/gui/test_barcode_dialog.py
import unittest from mock import patch from PyQt5.QtCore import QSettings from inselect.gui.plugins.barcode_dialog import BarcodeDialog from .gui_test import GUITest class TestBarcodeDialog(GUITest): """Tests the config dialog box of the 'Read barcode' plugin """ @patch.object(QSettings, 'setValue') ...
0.426083
0.207676
from typing import Pattern, Dict import regex from recognizers_text import RegExpUtility from ...resources.chinese_date_time import ChineseDateTime from ..extractors import DateTimeExtractor from ..parsers import DateTimeParser from ..base_dateperiod import DatePeriodParserConfiguration from .duration_extractor impor...
Python/libraries/recognizers-date-time/recognizers_date_time/date_time/chinese/dateperiod_parser_config.py
from typing import Pattern, Dict import regex from recognizers_text import RegExpUtility from ...resources.chinese_date_time import ChineseDateTime from ..extractors import DateTimeExtractor from ..parsers import DateTimeParser from ..base_dateperiod import DatePeriodParserConfiguration from .duration_extractor impor...
0.821331
0.311741
from __future__ import print_function from __future__ import division from __future__ import unicode_literals from __future__ import absolute_import from builtins import * # NOQA from future import standard_library standard_library.install_aliases() # NOQA import argparse import os import sys import gym import chain...
chokozainerrl/train_dqn_ale.py
from __future__ import print_function from __future__ import division from __future__ import unicode_literals from __future__ import absolute_import from builtins import * # NOQA from future import standard_library standard_library.install_aliases() # NOQA import argparse import os import sys import gym import chain...
0.586641
0.148109
"""Munki manifests module tests.""" import logging from google.apputils import app from simian.mac import models from tests.simian.mac.common import test from simian.mac.munki import plist from simian.mac.munki.handlers import manifests class HandlersTest(test.RequestHandlerTest): def GetTestClassInstance(self)...
src/tests/simian/mac/munki/handlers/manifests_medium_test.py
"""Munki manifests module tests.""" import logging from google.apputils import app from simian.mac import models from tests.simian.mac.common import test from simian.mac.munki import plist from simian.mac.munki.handlers import manifests class HandlersTest(test.RequestHandlerTest): def GetTestClassInstance(self)...
0.597843
0.277442
from typing import Optional, Union import torch def update_bn( loader: torch.utils.data.DataLoader, model: torch.nn.Module, device: Optional[Union[str, torch.device]] = None, num_datapoints: Optional[int] = None, ): r"""Updates BatchNorm running_mean, running_var buffers in the model. It perf...
afterglow/trackers/batchnorm.py
from typing import Optional, Union import torch def update_bn( loader: torch.utils.data.DataLoader, model: torch.nn.Module, device: Optional[Union[str, torch.device]] = None, num_datapoints: Optional[int] = None, ): r"""Updates BatchNorm running_mean, running_var buffers in the model. It perf...
0.965029
0.634515
import os, sys sys.path.insert(0, '../train-procgen/') sys.path.insert(0, '../') import torch import numpy as np from collections import deque import hyperparams as hps from idaac_test import evaluate from procgen import ProcgenEnv from baselines import logger from baselines.common.vec_env import ( VecExtractDict...
rl-baselines/idaac_train.py
import os, sys sys.path.insert(0, '../train-procgen/') sys.path.insert(0, '../') import torch import numpy as np from collections import deque import hyperparams as hps from idaac_test import evaluate from procgen import ProcgenEnv from baselines import logger from baselines.common.vec_env import ( VecExtractDict...
0.374905
0.149842
import json import shutil import uuid from pathlib import Path import pytest from django.apps import apps from django.core.management import call_command from django.core.management.base import CommandError def test_tailwind_init(installed_app): _, app_path = installed_app for fname in [ "apps.py", ...
tests/tests.py
import json import shutil import uuid from pathlib import Path import pytest from django.apps import apps from django.core.management import call_command from django.core.management.base import CommandError def test_tailwind_init(installed_app): _, app_path = installed_app for fname in [ "apps.py", ...
0.371023
0.162746
from shipstest import ShipsTest """ Tests basic management of channels, i.e. creating / joining / aborting them as well as declaring loss to close a channel in agreement. Disputes and resolutions (which deal with protos and signatures) are left for another test. """ class ChannelManagementTest (ShipsTest): def ...
ships/gametest/channel_management.py
from shipstest import ShipsTest """ Tests basic management of channels, i.e. creating / joining / aborting them as well as declaring loss to close a channel in agreement. Disputes and resolutions (which deal with protos and signatures) are left for another test. """ class ChannelManagementTest (ShipsTest): def ...
0.824497
0.573619
from iconservice import * TAG = 'Receipt' class InterCallInterface(InterfaceScore): @interface def call_event_log(self, p_log_index: int, p_bool: bool, p_addr: Address, p_int: int, p_bytes: bytes, p_str: str): pass class Receipt(IconScoreBase): @eventlog def event_log_no_index(self, p_bool: ...
testsuite/data/scores/receipt/receipt.py
from iconservice import * TAG = 'Receipt' class InterCallInterface(InterfaceScore): @interface def call_event_log(self, p_log_index: int, p_bool: bool, p_addr: Address, p_int: int, p_bytes: bytes, p_str: str): pass class Receipt(IconScoreBase): @eventlog def event_log_no_index(self, p_bool: ...
0.515864
0.313
from django.urls import reverse from rest_framework import status from lego.apps.quotes.models import Quote from lego.apps.users.models import AbakusGroup, User from lego.utils.test_utils import BaseAPITestCase def _get_list_url(): return reverse('api:v1:quote-list') def _get_list_approved_url(): return _g...
lego/apps/quotes/tests/test_api_quotes.py
from django.urls import reverse from rest_framework import status from lego.apps.quotes.models import Quote from lego.apps.users.models import AbakusGroup, User from lego.utils.test_utils import BaseAPITestCase def _get_list_url(): return reverse('api:v1:quote-list') def _get_list_approved_url(): return _g...
0.534855
0.194521
# standard library from unittest.mock import patch from dateutil import parser # third party from django.contrib.auth import get_user_model from django.test import TestCase from django.test.client import RequestFactory # local from cyphon.fieldsets import QueryFieldset from distilleries.models import Distillery from ...
Incident-Response/Tools/cyphon/cyphon/query/search/tests/test_distillery_search_results.py
# standard library from unittest.mock import patch from dateutil import parser # third party from django.contrib.auth import get_user_model from django.test import TestCase from django.test.client import RequestFactory # local from cyphon.fieldsets import QueryFieldset from distilleries.models import Distillery from ...
0.682468
0.378861
from json import loads from tenable_io.api.base import BaseApi, BaseRequest from tenable_io.api.models import CredentialList, CredentialDetails, CredentialPermission, CredentialPrimitiveType class CredentialsApi(BaseApi): def list(self, f=None, ft='and', limit=None, offset=0, sort=None, referrer_owner_uuid=None...
tenable_io/api/credentials.py
from json import loads from tenable_io.api.base import BaseApi, BaseRequest from tenable_io.api.models import CredentialList, CredentialDetails, CredentialPermission, CredentialPrimitiveType class CredentialsApi(BaseApi): def list(self, f=None, ft='and', limit=None, offset=0, sort=None, referrer_owner_uuid=None...
0.770119
0.208259
import pandas as pd from sklearn.model_selection import train_test_split #path - Path of file df=pd.read_csv(path) # Code starts here X=df.drop(['customerID','Churn'],1) y=df['Churn'].copy() X_train,X_test,y_train,y_test=train_test_split(X,y,test_size=.3,random_state=0) # -------------- import numpy as np from skl...
BOOSTING/code.py
import pandas as pd from sklearn.model_selection import train_test_split #path - Path of file df=pd.read_csv(path) # Code starts here X=df.drop(['customerID','Churn'],1) y=df['Churn'].copy() X_train,X_test,y_train,y_test=train_test_split(X,y,test_size=.3,random_state=0) # -------------- import numpy as np from skl...
0.17971
0.272153
__version__ = '1.1' import requests import json import time import sys from collections import OrderedDict import xml.etree.ElementTree as ET from . import __version__ from .response import Checked from .constants import base_url from .constants import CheckResult _agent = requests.Session() PY3 = sys.version_info[0...
hanspell/spell_checker.py
__version__ = '1.1' import requests import json import time import sys from collections import OrderedDict import xml.etree.ElementTree as ET from . import __version__ from .response import Checked from .constants import base_url from .constants import CheckResult _agent = requests.Session() PY3 = sys.version_info[0...
0.168173
0.17245
from sympy.abc import x from sympy.core.numbers import (I, Rational) from sympy.core.singleton import S from sympy.functions.elementary.miscellaneous import sqrt from sympy.polys import Poly, cyclotomic_poly from sympy.polys.domains import FF, QQ from sympy.polys.matrices import DomainMatrix, DM from sympy.polys.matric...
sympy/polys/numberfields/tests/test_utilities.py
from sympy.abc import x from sympy.core.numbers import (I, Rational) from sympy.core.singleton import S from sympy.functions.elementary.miscellaneous import sqrt from sympy.polys import Poly, cyclotomic_poly from sympy.polys.domains import FF, QQ from sympy.polys.matrices import DomainMatrix, DM from sympy.polys.matric...
0.665954
0.67657
import dataclasses import torch import torch.nn as nn import torch.nn.functional as F @dataclasses.dataclass class Node: inp: any module: nn.Module activated: bool stride: int dim: int def __hash__(self): return hash(self.module) class NetFactory(nn.Module): def __init__(self): super().__in...
simnet/lib/net/models/simplenet.py
import dataclasses import torch import torch.nn as nn import torch.nn.functional as F @dataclasses.dataclass class Node: inp: any module: nn.Module activated: bool stride: int dim: int def __hash__(self): return hash(self.module) class NetFactory(nn.Module): def __init__(self): super().__in...
0.939967
0.396711
import mock import pytest import unittest from svcm import exceptions from svcm.nssm import WinSvcManagerNSSM CONF_STUB = { 'service': { 'description': 'the_description', 'displayname': 'the_displayname', 'name': 'the_name', 'application': 'the_application', 'appdirectory':...
packages/winpanda/extra/src/winpanda/tests/unit/test_svcm_nssm.py
import mock import pytest import unittest from svcm import exceptions from svcm.nssm import WinSvcManagerNSSM CONF_STUB = { 'service': { 'description': 'the_description', 'displayname': 'the_displayname', 'name': 'the_name', 'application': 'the_application', 'appdirectory':...
0.477554
0.141163
import numpy, os, copy from labutil.objects import TextFile, ExternalCode, File, Param from labutil.util import prepare_dir, run_command class PWscf_inparam(Param): """ Data class containing parameters for a Quantum Espresso PWSCF calculation it does not include info on the cell itself, since that will be...
labutil/plugins/pwscf.py
import numpy, os, copy from labutil.objects import TextFile, ExternalCode, File, Param from labutil.util import prepare_dir, run_command class PWscf_inparam(Param): """ Data class containing parameters for a Quantum Espresso PWSCF calculation it does not include info on the cell itself, since that will be...
0.504883
0.330917
import json from distutils.dir_util import copy_tree import os, sys import click from pathlib import Path import time import yaml from dataherb.serve.models import SaveModel from dataherb.serve.mkdocs_templates import site_config as _site_config from dataherb.serve.mkdocs_templates import index_template as _index_temp...
dataherb/serve/save_mkdocs.py
import json from distutils.dir_util import copy_tree import os, sys import click from pathlib import Path import time import yaml from dataherb.serve.models import SaveModel from dataherb.serve.mkdocs_templates import site_config as _site_config from dataherb.serve.mkdocs_templates import index_template as _index_temp...
0.32306
0.130645
import dgl class HeteroGraphNeighborSampler: """Neighbor sampler on heterogeneous graphs Parameters ---------- g : DGLHeteroGraph Full graph category : str Category name of the seed nodes. nhops : int Number of hops to sample/number of layers in the node flow. f...
source/sagemaker/sagemaker_graph_german_risk/dgl_german_risk/sampler.py
import dgl class HeteroGraphNeighborSampler: """Neighbor sampler on heterogeneous graphs Parameters ---------- g : DGLHeteroGraph Full graph category : str Category name of the seed nodes. nhops : int Number of hops to sample/number of layers in the node flow. f...
0.884551
0.596874
import unittest import time from path_condition_generator import PathConditionGenerator from disambiguate import Disambiguator from PyRamify import PyRamify from t_core.matcher import Matcher from t_core.rewriter import Rewriter from t_core.iterator import Iterator from t_core.messages import Packet from t_core.tc...
tests/disambiguate_test.py
import unittest import time from path_condition_generator import PathConditionGenerator from disambiguate import Disambiguator from PyRamify import PyRamify from t_core.matcher import Matcher from t_core.rewriter import Rewriter from t_core.iterator import Iterator from t_core.messages import Packet from t_core.tc...
0.354321
0.22307
import robosuite as suite from robosuite.wrappers.gym_wrapper import GymWrapper from robosuite import load_controller_config import maple.torch.pytorch_util as ptu from maple.data_management.env_replay_buffer import EnvReplayBuffer from maple.samplers.data_collector import MdpPathCollector from maple.torch.sac.policie...
maple/launchers/robosuite_launcher.py
import robosuite as suite from robosuite.wrappers.gym_wrapper import GymWrapper from robosuite import load_controller_config import maple.torch.pytorch_util as ptu from maple.data_management.env_replay_buffer import EnvReplayBuffer from maple.samplers.data_collector import MdpPathCollector from maple.torch.sac.policie...
0.554953
0.241305
import json from decouple import config from django.shortcuts import render from django.http import HttpResponseRedirect import requests def index(request): if request.session.get('github_user'): pusher_key = config('PUSHER_APP_KEY') user = json.dumps(request.session['github_user']) contex...
backend/gitcommits/views.py
import json from decouple import config from django.shortcuts import render from django.http import HttpResponseRedirect import requests def index(request): if request.session.get('github_user'): pusher_key = config('PUSHER_APP_KEY') user = json.dumps(request.session['github_user']) contex...
0.225161
0.034036
from rest_framework import serializers from rest_framework.relations import SlugRelatedField from .models import * class ReadersSerializer(serializers.ModelSerializer): """Сериализация читателей""" class Meta: model = Reader fields = ('id', 'library_card', 'name', 'passport_number') class R...
students/k3340/laboratory_works/Bakirova_Shoola/LR2-3/project_library/library/serializers.py
from rest_framework import serializers from rest_framework.relations import SlugRelatedField from .models import * class ReadersSerializer(serializers.ModelSerializer): """Сериализация читателей""" class Meta: model = Reader fields = ('id', 'library_card', 'name', 'passport_number') class R...
0.540681
0.119537
from typing import Callable, Tuple import numpy as np from numpy.typing import ArrayLike try: import cupy as cp import cusignal NO_CUPY = False except ImportError: NO_CUPY = True import scipy.signal import scipy.fft def direct_ambiguity( delay_bins: ArrayLike, doppler_bins: ArrayLike, s...
pluto_sdr_pr/processing.py
from typing import Callable, Tuple import numpy as np from numpy.typing import ArrayLike try: import cupy as cp import cusignal NO_CUPY = False except ImportError: NO_CUPY = True import scipy.signal import scipy.fft def direct_ambiguity( delay_bins: ArrayLike, doppler_bins: ArrayLike, s...
0.94688
0.649294
from SimpleCV import Camera, Image import numpy as np import time import serial import RPi.GPIO as GPIO # setup() ## arguments area imgCropCoorList = [ (21,453),(16,240),(11,13), (311,457),(312,241),(313,18), (587,459),(593,242),(603,18)] imgCropWidth, imgCropHeight = 15,15 gpioList= [ 29,31,32, 33,3...
bin/fan_trigger.py
from SimpleCV import Camera, Image import numpy as np import time import serial import RPi.GPIO as GPIO # setup() ## arguments area imgCropCoorList = [ (21,453),(16,240),(11,13), (311,457),(312,241),(313,18), (587,459),(593,242),(603,18)] imgCropWidth, imgCropHeight = 15,15 gpioList= [ 29,31,32, 33,3...
0.227255
0.178938
import riemann from riemann import simple, utils from riemann.encoding import addresses as addr from riemann.script import serialization as ser riemann.select_network('zcash_sapling_main') prevout_addr_1 = 't1S3kN4zusjHtDEwfdaCMgk132bqo9DaYW4' prevout_addr_2 = 't1VQCUYzApF5eWf4UFAGdWwaFEpBfG2su1A' # This is the scri...
riemann/examples/sapling_example.py
import riemann from riemann import simple, utils from riemann.encoding import addresses as addr from riemann.script import serialization as ser riemann.select_network('zcash_sapling_main') prevout_addr_1 = 't1S3kN4zusjHtDEwfdaCMgk132bqo9DaYW4' prevout_addr_2 = 't1VQCUYzApF5eWf4UFAGdWwaFEpBfG2su1A' # This is the scri...
0.391639
0.183887
from __future__ import annotations import asyncio import enum import logging import re import threading from typing import TYPE_CHECKING from . import ai from . import bitboard as bb from .player import AIPlayer, Color, Player if TYPE_CHECKING: from queue import Queue _LOGGER = logging.getLogger(__name__) Even...
othelloai/game.py
from __future__ import annotations import asyncio import enum import logging import re import threading from typing import TYPE_CHECKING from . import ai from . import bitboard as bb from .player import AIPlayer, Color, Player if TYPE_CHECKING: from queue import Queue _LOGGER = logging.getLogger(__name__) Even...
0.886181
0.230335
import unittest import os import subprocess class TestTaxonomicClassification(unittest.TestCase): ''' Test the taxonomic classification workflows: We test by checking if the correct files are created at the end of the workflow. ''' # @classmethod # def setUpClass(cls): # os.ch...
test/test_taxonomic_classification.py
import unittest import os import subprocess class TestTaxonomicClassification(unittest.TestCase): ''' Test the taxonomic classification workflows: We test by checking if the correct files are created at the end of the workflow. ''' # @classmethod # def setUpClass(cls): # os.ch...
0.159021
0.211112
import config import os import glob import time import datetime import logging from logging import StreamHandler, Formatter from logging.handlers import TimedRotatingFileHandler import sqlite3 def get_logger(logger_name): _logger = logging.getLogger(logger_name) file_formatter = Formatter( '%(leveln...
thermostat.py
import config import os import glob import time import datetime import logging from logging import StreamHandler, Formatter from logging.handlers import TimedRotatingFileHandler import sqlite3 def get_logger(logger_name): _logger = logging.getLogger(logger_name) file_formatter = Formatter( '%(leveln...
0.154791
0.062904
from random import random, randint __all__ = ["DNA"] # range constraint for the function being optimized min_i, max_i = -100, +100 k_i = 22 # number of bits for the ​​x and y variables of this problem # a chromosome is represented by 44 binary digits, with 22 for x and 22 for y # the convert_to_real method retrieves...
src/DNA.py
from random import random, randint __all__ = ["DNA"] # range constraint for the function being optimized min_i, max_i = -100, +100 k_i = 22 # number of bits for the ​​x and y variables of this problem # a chromosome is represented by 44 binary digits, with 22 for x and 22 for y # the convert_to_real method retrieves...
0.622
0.484258
import argparse import re from django.core.management.base import BaseCommand, CommandError from openpyxl import load_workbook from account.models import Profile from account.utils import format_phonenumber from friend.models import PhoneContactRecord class Command(BaseCommand): help = 'Batch import Phone Conta...
friend/management/commands/import_phonecontact.py
import argparse import re from django.core.management.base import BaseCommand, CommandError from openpyxl import load_workbook from account.models import Profile from account.utils import format_phonenumber from friend.models import PhoneContactRecord class Command(BaseCommand): help = 'Batch import Phone Conta...
0.158012
0.077797
import networkx as nx import time from random import random class ModularityRCommunityDiscovery(object): minimum_improvement = 0.000001 def __init__(self, graph): self.graph = graph self.starting_node = None self.community = [] self.boundary = set() self.shell = set()...
cdlib/algorithms/internal/modularity_r.py
import networkx as nx import time from random import random class ModularityRCommunityDiscovery(object): minimum_improvement = 0.000001 def __init__(self, graph): self.graph = graph self.starting_node = None self.community = [] self.boundary = set() self.shell = set()...
0.383757
0.244622
class Solution: def solve(self, board: List[List[str]]) -> None: self.board = board row = len(board) if row <=2:return col = len(board[0]) if col <=2: return for i in range(row): for j in range(col): if board[i][j] == 'O' and (i == 0 or j ...
surrounded_regions.py
class Solution: def solve(self, board: List[List[str]]) -> None: self.board = board row = len(board) if row <=2:return col = len(board[0]) if col <=2: return for i in range(row): for j in range(col): if board[i][j] == 'O' and (i == 0 or j ...
0.317638
0.57827
from __future__ import print_function from time import sleep def start_foreground_mode(): import jnius print("STARTING FOREGROUND MODE") Context = jnius.autoclass('android.content.Context') Intent = jnius.autoclass('android.content.Intent') PendingIntent = jnius.autoclass('android.app.Pendi...
pocs/pictures/customservice.py
from __future__ import print_function from time import sleep def start_foreground_mode(): import jnius print("STARTING FOREGROUND MODE") Context = jnius.autoclass('android.content.Context') Intent = jnius.autoclass('android.content.Intent') PendingIntent = jnius.autoclass('android.app.Pendi...
0.422743
0.046292
import numpy as np import pandas as pd from pandas import DataFrame as df from pandas import Series as sr import matplotlib.pyplot as plt l=[2,3,5] def checkPrime(a): for i in range(2,int(np.sqrt(a)+1)): if a%i==0: return False return True def prime(n=1000): global l if ...
math_prob2.py
import numpy as np import pandas as pd from pandas import DataFrame as df from pandas import Series as sr import matplotlib.pyplot as plt l=[2,3,5] def checkPrime(a): for i in range(2,int(np.sqrt(a)+1)): if a%i==0: return False return True def prime(n=1000): global l if ...
0.209389
0.280869
import logging import json import re def main(): logging.basicConfig(format="%(asctime)s - %(message)s", level=logging.INFO) with open(r'../Data/Dataset/comments.json') as f: # open master comments.json file comments = json.load(f) cleaned_comments = [] # storage for cleaned comment...
Scripts/clean_comments.py
import logging import json import re def main(): logging.basicConfig(format="%(asctime)s - %(message)s", level=logging.INFO) with open(r'../Data/Dataset/comments.json') as f: # open master comments.json file comments = json.load(f) cleaned_comments = [] # storage for cleaned comment...
0.472927
0.164382
import os.path import pathlib from typing import Any, Dict, List from pydantic import Field, validator from emulation_system.compose_file_creator.input.hardware_models.hardware_model import ( HardwareModel, ) from emulation_system.compose_file_creator.settings.config_file_settings import ( ROBOT_SERVER_MOUNT_...
emulation_system/emulation_system/compose_file_creator/input/hardware_models/robots/robot_model.py
import os.path import pathlib from typing import Any, Dict, List from pydantic import Field, validator from emulation_system.compose_file_creator.input.hardware_models.hardware_model import ( HardwareModel, ) from emulation_system.compose_file_creator.settings.config_file_settings import ( ROBOT_SERVER_MOUNT_...
0.721841
0.186539
import os import subprocess import pytest from os.path import join, abspath, dirname, basename from tests.functional.driver import Driver from tests.functional.settings import ( testbot_apitoken, testbot_username, driver_apitoken, driver_username, test_channel, test_group ) TRAVIS = 'TRAVIS' in os.environ def...
tests/functional/test_functional.py
import os import subprocess import pytest from os.path import join, abspath, dirname, basename from tests.functional.driver import Driver from tests.functional.settings import ( testbot_apitoken, testbot_username, driver_apitoken, driver_username, test_channel, test_group ) TRAVIS = 'TRAVIS' in os.environ def...
0.246261
0.125627
from __future__ import absolute_import from __future__ import print_function from pprint import pprint import collections import logging from django.conf import settings from django.shortcuts import render_to_response from django.template import RequestContext from readthedocs.builds.constants import LATEST from read...
readthedocs/search/views.py
from __future__ import absolute_import from __future__ import print_function from pprint import pprint import collections import logging from django.conf import settings from django.shortcuts import render_to_response from django.template import RequestContext from readthedocs.builds.constants import LATEST from read...
0.411347
0.084909
try: import tkinter as tk except: print("You need Python 3.8 installed and Python Tkinter. This script will automatically install dependencies... :]") import os os.system('sudo apt-get install python3.8 python3-tk') import tkinter as tk window = tk.Tk() window.title("Corn Hole!!!") WHITE = (255, 2...
CornHole.py
try: import tkinter as tk except: print("You need Python 3.8 installed and Python Tkinter. This script will automatically install dependencies... :]") import os os.system('sudo apt-get install python3.8 python3-tk') import tkinter as tk window = tk.Tk() window.title("Corn Hole!!!") WHITE = (255, 2...
0.172485
0.070144
from rest_framework.serializers import * from .models import * class ExtraFieldSerializer(ModelSerializer): class Meta: model = ExtraField fields = ('key', 'value', ) class PolicySerializer(ModelSerializer): class Meta: model = Policy fields = '__all__' class PolicyListSeri...
uav_data/api/serializers.py
from rest_framework.serializers import * from .models import * class ExtraFieldSerializer(ModelSerializer): class Meta: model = ExtraField fields = ('key', 'value', ) class PolicySerializer(ModelSerializer): class Meta: model = Policy fields = '__all__' class PolicyListSeri...
0.66061
0.083853
import os import matplotlib.pyplot as plt import itertools import pickle import imageio import torch import torch.nn as nn import torch.nn.functional as F import torch.optim as optim from torchvision import datasets, transforms from torch.autograd import Variable import numpy as np # training parameters batch_size = ...
Repopulation/main_mnist_us.py
import os import matplotlib.pyplot as plt import itertools import pickle import imageio import torch import torch.nn as nn import torch.nn.functional as F import torch.optim as optim from torchvision import datasets, transforms from torch.autograd import Variable import numpy as np # training parameters batch_size = ...
0.509764
0.478833
from scipy.stats import chi2 import numpy as np from typing import NamedTuple import matplotlib.pyplot as plt from warnings import warn import enum def clamp_step(x_origin, x_step, lb, ub): """Shortens a step to stay within some box constraints.""" assert np.all( np.logical_and(x_origin >= lb, x_origi...
lumicks/pylake/fitting/profile_likelihood.py
from scipy.stats import chi2 import numpy as np from typing import NamedTuple import matplotlib.pyplot as plt from warnings import warn import enum def clamp_step(x_origin, x_step, lb, ub): """Shortens a step to stay within some box constraints.""" assert np.all( np.logical_and(x_origin >= lb, x_origi...
0.941627
0.755885
from appJar import gui from pyswip import Prolog def formatText(word): rWord=word.lower().replace(" ", "") for l in rWord: if l < 'a' or l> 'z': rWord="" break return rWord def formatNumber(number): rNumber = number.replace(" ", "") ...
code.py
from appJar import gui from pyswip import Prolog def formatText(word): rWord=word.lower().replace(" ", "") for l in rWord: if l < 'a' or l> 'z': rWord="" break return rWord def formatNumber(number): rNumber = number.replace(" ", "") ...
0.090348
0.15084
from Proc import ActorProc, LearnerProc from NetworkData import NetworkData from SumoSim import SumoSim import math from multiprocessing import * import numpy as np from help_funcs import save_data, load_data class DistProcs(): def __init__(self, n_actors, n_learners, mode, net_fp, args): self.args = args ...
DistProcs.py
from Proc import ActorProc, LearnerProc from NetworkData import NetworkData from SumoSim import SumoSim import math from multiprocessing import * import numpy as np from help_funcs import save_data, load_data class DistProcs(): def __init__(self, n_actors, n_learners, mode, net_fp, args): self.args = args ...
0.411702
0.233171
from django.conf.urls import url from django.urls import path from . import views from .export import ExportCompleteEnrollingTable urlpatterns = [ url(r'^enrolling/$', views.enrolling, name='enrolling'), url(r'^enrolling/data/$', views.enrolling_data, name='enrolling_data'), url(r'^enrolling/(?P<user_id>...
src/web/modules/entrance/staff/urls.py
from django.conf.urls import url from django.urls import path from . import views from .export import ExportCompleteEnrollingTable urlpatterns = [ url(r'^enrolling/$', views.enrolling, name='enrolling'), url(r'^enrolling/data/$', views.enrolling_data, name='enrolling_data'), url(r'^enrolling/(?P<user_id>...
0.179207
0.08882
import warnings import pulumi import pulumi.runtime from typing import Any, Mapping, Optional, Sequence, Union, overload from .. import _utilities __all__ = [ 'GetUserHierarchyGroupResult', 'AwaitableGetUserHierarchyGroupResult', 'get_user_hierarchy_group', 'get_user_hierarchy_group_output', ] @pulum...
sdk/python/pulumi_aws_native/connect/get_user_hierarchy_group.py
import warnings import pulumi import pulumi.runtime from typing import Any, Mapping, Optional, Sequence, Union, overload from .. import _utilities __all__ = [ 'GetUserHierarchyGroupResult', 'AwaitableGetUserHierarchyGroupResult', 'get_user_hierarchy_group', 'get_user_hierarchy_group_output', ] @pulum...
0.794783
0.060169
import subprocess import os import shutil def copy_EGS(top): """ Copy EGS from installation to docker """ src = None try: src = os.environ["EGS_HOME"] except KeyError: raise RuntimeError("No EGS_HOME found, aborting") egsd = os.path.join(top, "egsnrc_mp") print(egsd) ...
Docker/build_image.py
import subprocess import os import shutil def copy_EGS(top): """ Copy EGS from installation to docker """ src = None try: src = os.environ["EGS_HOME"] except KeyError: raise RuntimeError("No EGS_HOME found, aborting") egsd = os.path.join(top, "egsnrc_mp") print(egsd) ...
0.311636
0.111773
import unittest from unittest.mock import Mock import numpy as np from core.instrument import Instrument from core.trade import Trade from core.events import TradeExecutedEvent from portfolio.portfolio import Portfolio class TestPortfolio(unittest.TestCase): """ Unittest to test implementation of portfolio c...
tests/portfolio/test_portfolio.py
import unittest from unittest.mock import Mock import numpy as np from core.instrument import Instrument from core.trade import Trade from core.events import TradeExecutedEvent from portfolio.portfolio import Portfolio class TestPortfolio(unittest.TestCase): """ Unittest to test implementation of portfolio c...
0.679923
0.588061
import boto3 from botocore.exceptions import ClientError import json import logging import os import re import ruamel.yaml as yaml from . import utils LOG = logging.getLogger(__name__) LAMBDA_ROLE_ARN_TEMPLATE = "arn:aws:iam::{account_id}:role/{role}" class YokeConfig(object): def __init__(self, shellargs, pro...
yoke/config.py
import boto3 from botocore.exceptions import ClientError import json import logging import os import re import ruamel.yaml as yaml from . import utils LOG = logging.getLogger(__name__) LAMBDA_ROLE_ARN_TEMPLATE = "arn:aws:iam::{account_id}:role/{role}" class YokeConfig(object): def __init__(self, shellargs, pro...
0.303216
0.07538
import pickle import os from modules.nlp_engine.model_builder.trainer import Trainer from modules.services.auth_service import AuthService from modules.data.dao.broker_dao import BrokerDao from modules.data.dao.trained_classifier_dao import TrainedClassifierDao from modules.utils.yaml_parser import Config import loggin...
modules/services/training_service.py
import pickle import os from modules.nlp_engine.model_builder.trainer import Trainer from modules.services.auth_service import AuthService from modules.data.dao.broker_dao import BrokerDao from modules.data.dao.trained_classifier_dao import TrainedClassifierDao from modules.utils.yaml_parser import Config import loggin...
0.482673
0.087486
import argparse from releasy.cli.base import BaseCli from releasy.model_git import Project from releasy.factory import ProjectFactory class Match(BaseCli): """ Test release name matches of a project """ def __init__(self): super().__init__() self.help = 'Test release name matches of a project'...
releasy/cli/match.py
import argparse from releasy.cli.base import BaseCli from releasy.model_git import Project from releasy.factory import ProjectFactory class Match(BaseCli): """ Test release name matches of a project """ def __init__(self): super().__init__() self.help = 'Test release name matches of a project'...
0.418459
0.118793
import json import os from argparse import Action from typing import Dict, Union from .actions import _is_action_value_list from .loaders_dumpers import get_loader_exceptions, load_value, load_value_context from .namespace import strip_meta from .optionals import ( argcomplete_warn_redraw_prompt, get_jsonsche...
jsonargparse/jsonschema.py
import json import os from argparse import Action from typing import Dict, Union from .actions import _is_action_value_list from .loaders_dumpers import get_loader_exceptions, load_value, load_value_context from .namespace import strip_meta from .optionals import ( argcomplete_warn_redraw_prompt, get_jsonsche...
0.683947
0.107954
import hou import husdshadertranslators.utils as utils from husdshadertranslators.default import DefaultShaderTranslatorHelper, renderContextName, RampParmTranslator from pxr import Usd, UsdShade, Sdf, Vt from itertools import izip # TODO(pal): # - Support putting fetch nodes in the middle of the shader graph. # - ...
third_party/houdini/scripts/python/husdshadertranslators/arnold.py
import hou import husdshadertranslators.utils as utils from husdshadertranslators.default import DefaultShaderTranslatorHelper, renderContextName, RampParmTranslator from pxr import Usd, UsdShade, Sdf, Vt from itertools import izip # TODO(pal): # - Support putting fetch nodes in the middle of the shader graph. # - ...
0.411229
0.215248
try: from setuptools import setup except ImportError: from distutils.core import setup long_description = """ # Yandex.Checkout API Python Client Library [![Build Status](https://travis-ci.org/yandex-money/yandex-checkout-sdk-python.svg?branch=master)](https://travis-ci.org/yandex-money/yandex-checkout-sdk-p...
setup.py
pip install --upgrade yandex_checkout easy_install --upgrade yandex_checkout wget https://pypi.python.org/packages/5a/be/5eafdfb14aa6f32107e9feb6514ca1ad3fe56f8e5ee59d20693b32f7e79f/yandex_checkout-1.0.0.tar.gz#md5=46595279b5578fd82a199bfd4cd51db2 tar zxf yandex_checkout-1.0.0.tar.gz cd yandex_checkout-1.0.0 python s...
0.542379
0.879716
from flask import current_app from testAuxiliaryFuncs import decryptAES, getDecryptor, encryptAES from bson import json_util, ObjectId def test_get_user(client, auth, app): token = auth.login('test2', 'test2') response = client.get('/api/User', headers={"token": token}) # check response status code ...
tests/test_api_user.py
from flask import current_app from testAuxiliaryFuncs import decryptAES, getDecryptor, encryptAES from bson import json_util, ObjectId def test_get_user(client, auth, app): token = auth.login('test2', 'test2') response = client.get('/api/User', headers={"token": token}) # check response status code ...
0.534612
0.241881
import copy import os.path as osp import numpy as np from mmflow.datasets.pipelines import LoadAnnotations, LoadImageFromFile img1_ = osp.join(osp.dirname(__file__), '../data/00001_img1.ppm') img2_ = osp.join(osp.dirname(__file__), '../data/00001_img2.ppm') flow_ = osp.join(osp.dirname(__file__), '../data/00001_flow...
tests/test_datasets/test_loading.py
import copy import os.path as osp import numpy as np from mmflow.datasets.pipelines import LoadAnnotations, LoadImageFromFile img1_ = osp.join(osp.dirname(__file__), '../data/00001_img1.ppm') img2_ = osp.join(osp.dirname(__file__), '../data/00001_img2.ppm') flow_ = osp.join(osp.dirname(__file__), '../data/00001_flow...
0.423696
0.605187
from typing import Dict, List, Tuple, Set, Optional from collections import defaultdict from . import crypto from .crypto import G1, H1, G2, H2, add, multiply, pairing, normalize from .crypto import PointG1, PointG2 INVALID_SHARE = -1 class Node: n: int t: int idx: int # a one based index, typically a...
ethdkg/node.py
from typing import Dict, List, Tuple, Set, Optional from collections import defaultdict from . import crypto from .crypto import G1, H1, G2, H2, add, multiply, pairing, normalize from .crypto import PointG1, PointG2 INVALID_SHARE = -1 class Node: n: int t: int idx: int # a one based index, typically a...
0.902497
0.433802
from django.conf import settings from django import forms from crispy_forms.helper import FormHelper from crispy_forms.layout import Submit, Layout, Fieldset, ButtonHolder, HTML from Utuputki.manager.models import Video from django.utils.translation import ugettext_lazy as _ import urlparse import httplib import json...
Utuputki/manager/forms.py
from django.conf import settings from django import forms from crispy_forms.helper import FormHelper from crispy_forms.layout import Submit, Layout, Fieldset, ButtonHolder, HTML from Utuputki.manager.models import Video from django.utils.translation import ugettext_lazy as _ import urlparse import httplib import json...
0.44553
0.080973
from types import SimpleNamespace import numpy as np import torch import pytest from chemprop.train.loss_functions import ( bounded_mse_loss, dirichlet_class_loss, evidential_loss, get_loss_func, normal_mve, ) # Fixtures @pytest.fixture(params=["regression", "classification", "multiclass"]) def ...
tests/test_unit/test_loss_functions.py
from types import SimpleNamespace import numpy as np import torch import pytest from chemprop.train.loss_functions import ( bounded_mse_loss, dirichlet_class_loss, evidential_loss, get_loss_func, normal_mve, ) # Fixtures @pytest.fixture(params=["regression", "classification", "multiclass"]) def ...
0.878666
0.58433
# Copyright 2019 <NAME> (Nagoya University) # Apache 2.0 (http://www.apache.org/licenses/LICENSE-2.0) import math # ACOUSTIC PARAMETER class acoustic_parameter(object): def __init__(self, fs, feature_type="world", shiftms=5, fftl=1024, mag=0.5, mcep_dim_start=2, f0_dim_idx=1, ...
src/utils/param_feat.py
# Copyright 2019 <NAME> (Nagoya University) # Apache 2.0 (http://www.apache.org/licenses/LICENSE-2.0) import math # ACOUSTIC PARAMETER class acoustic_parameter(object): def __init__(self, fs, feature_type="world", shiftms=5, fftl=1024, mag=0.5, mcep_dim_start=2, f0_dim_idx=1, ...
0.468304
0.141133
from plyer.utils import platform from plyer.compat import PY2 from kivy.logger import Logger if platform == 'android': from android.broadcast import BroadcastReceiver from . import notification else: notification = None Logger.warning( 'Platform is not android, ignoring AndroidNotification and '...
app_modules/noti_builder/builder.py
from plyer.utils import platform from plyer.compat import PY2 from kivy.logger import Logger if platform == 'android': from android.broadcast import BroadcastReceiver from . import notification else: notification = None Logger.warning( 'Platform is not android, ignoring AndroidNotification and '...
0.553385
0.073231
import bagit from bun import UI, inform, alert, alert_fatal from collections import defaultdict from commonpy.data_utils import flattened, parsed_datetime, pluralized import getpass from humanize import intcomma import keyring from lxml import etree import os from os import path, cpu_count import plac impor...
eprints2bags/__main__.py
import bagit from bun import UI, inform, alert, alert_fatal from collections import defaultdict from commonpy.data_utils import flattened, parsed_datetime, pluralized import getpass from humanize import intcomma import keyring from lxml import etree import os from os import path, cpu_count import plac impor...
0.248534
0.126731
import pprint import re # noqa: F401 import six class Currency(object): """NOTE: This class is auto generated by the swagger code generator program. Do not edit the class manually. """ """ Attributes: swagger_types (dict): The key is attribute name and the val...
swg_generated/python/swagger_client/models/currency.py
import pprint import re # noqa: F401 import six class Currency(object): """NOTE: This class is auto generated by the swagger code generator program. Do not edit the class manually. """ """ Attributes: swagger_types (dict): The key is attribute name and the val...
0.722821
0.257929
import io import os from helper_util import relpath, source_files from ppci import api from ppci.utils.reporting import html_reporter from ppci.lang.c import COptions def create_test_function(source, output, lang): """ Create a test function for a source file """ with open(source) as f: snippet = f.re...
test/samples/sample_helpers.py
import io import os from helper_util import relpath, source_files from ppci import api from ppci.utils.reporting import html_reporter from ppci.lang.c import COptions def create_test_function(source, output, lang): """ Create a test function for a source file """ with open(source) as f: snippet = f.re...
0.387459
0.209066
import pprint import re # noqa: F401 import six class AlertInfo(object): """NOTE: This class is auto generated by the swagger code generator program. Do not edit the class manually. """ """ Attributes: swagger_types (dict): The key is attribute name and the val...
varsom_landslide_client/models/alert_info.py
import pprint import re # noqa: F401 import six class AlertInfo(object): """NOTE: This class is auto generated by the swagger code generator program. Do not edit the class manually. """ """ Attributes: swagger_types (dict): The key is attribute name and the val...
0.676299
0.077762
from binaryninja import * import lz4.block import struct def unpack32(x): return struct.unpack("<I", x)[0] def unpack64(x): return struct.unpack("<Q", x)[0] def inpack32(x): return struct.unpack("<i", x)[0] class SwitchSection: is_compressed = False check_hash = False sectionData = None fileOffset = 0 memor...
__init__.py
from binaryninja import * import lz4.block import struct def unpack32(x): return struct.unpack("<I", x)[0] def unpack64(x): return struct.unpack("<Q", x)[0] def inpack32(x): return struct.unpack("<i", x)[0] class SwitchSection: is_compressed = False check_hash = False sectionData = None fileOffset = 0 memor...
0.358241
0.249256
import mock import os.path test_data = { "procurementMethod": "open", "doc_type": "Tender", "qualificationPeriod": { "startDate": "2017-11-14T15:15:00+02:00" }, "date": "2017-11-15T00:01:50Z", "owner": "test", "_id": "tender_id", "tenderID": "UA-2017-11-30", "dateModified":...
reports/tests/utils.py
import mock import os.path test_data = { "procurementMethod": "open", "doc_type": "Tender", "qualificationPeriod": { "startDate": "2017-11-14T15:15:00+02:00" }, "date": "2017-11-15T00:01:50Z", "owner": "test", "_id": "tender_id", "tenderID": "UA-2017-11-30", "dateModified":...
0.383988
0.347482
from django.shortcuts import reverse from django.test import TestCase from posts.models import Group, Post, User class TestCreatePost(TestCase): def setUp(self): self.text = 'I\'m Muzzy! I\'m big Muzzy!' self.user = User.objects.create(username='muzzy') self.group = Group.objects.create(t...
yatube/posts/tests/tests_posts.py
from django.shortcuts import reverse from django.test import TestCase from posts.models import Group, Post, User class TestCreatePost(TestCase): def setUp(self): self.text = 'I\'m Muzzy! I\'m big Muzzy!' self.user = User.objects.create(username='muzzy') self.group = Group.objects.create(t...
0.523664
0.307943
import unittest from unittest.mock import ( AsyncMock, call, ) from uuid import ( UUID, uuid4, ) from psycopg2.sql import ( SQL, ) from minos.common import ( Model, ) from minos.common.testing import ( PostgresAsyncTestCase, ) from minos.networks import ( BrokerMessage, BrokerMessa...
tests/test_networks/test_brokers/test_publishers/test_publishers.py
import unittest from unittest.mock import ( AsyncMock, call, ) from uuid import ( UUID, uuid4, ) from psycopg2.sql import ( SQL, ) from minos.common import ( Model, ) from minos.common.testing import ( PostgresAsyncTestCase, ) from minos.networks import ( BrokerMessage, BrokerMessa...
0.754282
0.395134
"""Reddit Bot that provides downloadable links for v.redd.it videos""" import os import re import urllib.parse from urllib.error import HTTPError, URLError from urllib.request import Request, urlopen import praw import requests import yaml from praw.models import Comment, Message def load_configuration(): conf_...
bot.py
"""Reddit Bot that provides downloadable links for v.redd.it videos""" import os import re import urllib.parse from urllib.error import HTTPError, URLError from urllib.request import Request, urlopen import praw import requests import yaml from praw.models import Comment, Message def load_configuration(): conf_...
0.385953
0.143698
import collections import context import util from .ordered_set import OrderedSet class JavaValue(object): """A Java value, typically representing a field or a method in a Java class and optionally a javadoc comment. A JavaValue can have its attributes set using the optional keyword arguments of the...
gen/tools/jnc_plugin/java_value.py
import collections import context import util from .ordered_set import OrderedSet class JavaValue(object): """A Java value, typically representing a field or a method in a Java class and optionally a javadoc comment. A JavaValue can have its attributes set using the optional keyword arguments of the...
0.85341
0.321567
def cast_spell(func): """ Wraps a function that is tied to a spell cast. What is general for all spells is they require some resource (currently - mana) and have a cooldown. This decorator checks if both those needs are met, and if not, does not cast the spell. """ def decorator(*args, **kwa...
decorators.py
def cast_spell(func): """ Wraps a function that is tied to a spell cast. What is general for all spells is they require some resource (currently - mana) and have a cooldown. This decorator checks if both those needs are met, and if not, does not cast the spell. """ def decorator(*args, **kwa...
0.638272
0.37777
import argparse import json import os import ijson parser = argparse.ArgumentParser() # /questions/CLEVR_test_questions.json # Inputs parser.add_argument('--input_questions_file', default='../data/CLEVR_v1.0/questions/CLEVR_train_questions.json', help="JSON file containing questions information fo...
caption_generation/caption_gen.py
import argparse import json import os import ijson parser = argparse.ArgumentParser() # /questions/CLEVR_test_questions.json # Inputs parser.add_argument('--input_questions_file', default='../data/CLEVR_v1.0/questions/CLEVR_train_questions.json', help="JSON file containing questions information fo...
0.088485
0.118819
from AirSimClient import * import sys import time import argparse class SurveyNavigator: def __init__(self, args): self.boxsize = args.size self.stripewidth = args.stripewidth self.altitude = args.altitude self.velocity = args.speed self.client = MultirotorClient(...
mytest/PythonClient_1.0/survey.py
from AirSimClient import * import sys import time import argparse class SurveyNavigator: def __init__(self, args): self.boxsize = args.size self.stripewidth = args.stripewidth self.altitude = args.altitude self.velocity = args.speed self.client = MultirotorClient(...
0.240329
0.137156
import matplotlib.pyplot as plt import numpy as np import math import re from docopt import docopt from benchmark import load_json, parse_benchmark, allowed_algorithms, allowed_geometries def find_available_backends(input_jsons): arborx_backend_regex = "[^<]*<ArborX::BVH<([^>]*)>.*" backends = set() for ...
scripts/benchmark_plot.py
import matplotlib.pyplot as plt import numpy as np import math import re from docopt import docopt from benchmark import load_json, parse_benchmark, allowed_algorithms, allowed_geometries def find_available_backends(input_jsons): arborx_backend_regex = "[^<]*<ArborX::BVH<([^>]*)>.*" backends = set() for ...
0.54359
0.224278
try: import bpy except ImportError: bpy = None class AlbamRegistry: def __init__(self): self.import_registry = {} self.export_registry = {} self._blender_panels = set() self._blender_operators = set() self._blender_props = {} # (bpy.type, custom_name, bpy_prop): ...
albam/registry.py
try: import bpy except ImportError: bpy = None class AlbamRegistry: def __init__(self): self.import_registry = {} self.export_registry = {} self._blender_panels = set() self._blender_operators = set() self._blender_props = {} # (bpy.type, custom_name, bpy_prop): ...
0.359589
0.132262
sampleInput = """{ "data": [ { "type": "checks", "id": "ccc:AccountId:S3-001:S3:us-east-1:S3Bucket", "attributes": { "region": "us-east-1", "status": "FAILURE", "risk-level": "VERY_HIGH", "pretty-risk-level": "Very High", "message": "Bucket S3Bucket allows...
tests/unit/sample_data.py
sampleInput = """{ "data": [ { "type": "checks", "id": "ccc:AccountId:S3-001:S3:us-east-1:S3Bucket", "attributes": { "region": "us-east-1", "status": "FAILURE", "risk-level": "VERY_HIGH", "pretty-risk-level": "Very High", "message": "Bucket S3Bucket allows...
0.482429
0.36727
import numpy as np import pandas as pd from scipy.spatial import Delaunay from scipy.spatial.distance import cdist from sklearn.linear_model import RANSACRegressor, LinearRegression import ops.utils def find_triangles(df): v, c = get_vectors(df[['i', 'j']].values) return (pd.concat([ pd.DataFrame(v)....
ops/triangle_hash.py
import numpy as np import pandas as pd from scipy.spatial import Delaunay from scipy.spatial.distance import cdist from sklearn.linear_model import RANSACRegressor, LinearRegression import ops.utils def find_triangles(df): v, c = get_vectors(df[['i', 'j']].values) return (pd.concat([ pd.DataFrame(v)....
0.863219
0.636071
import curses import threading import time from typing import Any, Dict import workflows.transport from workflows.services.common_service import CommonService basestring = (str, bytes) class Monitor: # pragma: no cover """A sample implementation of a status monitor showing all running services. To use this...
src/workflows/contrib/status_monitor.py
import curses import threading import time from typing import Any, Dict import workflows.transport from workflows.services.common_service import CommonService basestring = (str, bytes) class Monitor: # pragma: no cover """A sample implementation of a status monitor showing all running services. To use this...
0.744656
0.253953
import sys _b=sys.version_info[0]<3 and (lambda x:x) or (lambda x:x.encode('latin1')) from google.protobuf import descriptor as _descriptor from google.protobuf import message as _message from google.protobuf import reflection as _reflection from google.protobuf import symbol_database as _symbol_database from google.p...
orderbook/orderbook_pb2.py
import sys _b=sys.version_info[0]<3 and (lambda x:x) or (lambda x:x.encode('latin1')) from google.protobuf import descriptor as _descriptor from google.protobuf import message as _message from google.protobuf import reflection as _reflection from google.protobuf import symbol_database as _symbol_database from google.p...
0.329607
0.110976
# Copyright (C) 2009-2010 <NAME> # This file is part of MiniINI # For conditions of distribution and use, see copyright notice in LICENSE.txt import random import sys import getopt valtype = "string" sections = 128 minarrays = 1 maxarrays = 2 mintags = 16 maxtags = 64 mintaglength = 4 maxtaglength = 16 minstrlength...
testgen.py
# Copyright (C) 2009-2010 <NAME> # This file is part of MiniINI # For conditions of distribution and use, see copyright notice in LICENSE.txt import random import sys import getopt valtype = "string" sections = 128 minarrays = 1 maxarrays = 2 mintags = 16 maxtags = 64 mintaglength = 4 maxtaglength = 16 minstrlength...
0.229708
0.105303
import hypothesis.strategies as st from caffe2.python import core, workspace from hypothesis import given import caffe2.python.hypothesis_test_util as hu import numpy as np class TestNGramOps(hu.HypothesisTestCase): @given( seed=st.integers(0, 2**32 - 1), N=st.integers(min_value=10, max_value=10...
caffe2/python/operator_test/ngram_ops_test.py
import hypothesis.strategies as st from caffe2.python import core, workspace from hypothesis import given import caffe2.python.hypothesis_test_util as hu import numpy as np class TestNGramOps(hu.HypothesisTestCase): @given( seed=st.integers(0, 2**32 - 1), N=st.integers(min_value=10, max_value=10...
0.453262
0.435421
from fastapi import APIRouter, status, Depends from whendo.api.shared import return_success, raised_exception, get_dispatcher from whendo.core.resolver import resolve_scheduler from whendo.core.util import DateTime router = APIRouter(prefix="/schedulers", tags=["Schedulers"]) @router.get("", status_code=status.HTTP_...
whendo/api/router/schedulers.py
from fastapi import APIRouter, status, Depends from whendo.api.shared import return_success, raised_exception, get_dispatcher from whendo.core.resolver import resolve_scheduler from whendo.core.util import DateTime router = APIRouter(prefix="/schedulers", tags=["Schedulers"]) @router.get("", status_code=status.HTTP_...
0.477311
0.14016
from constants import point_symbol, PointState class BoardSlice(object): def __init__(self, row_offset, column_offset, slice2d, row_labels, parent): self._slice2d = slice2d self._row_offset = row_offset self._column_offset = column_offset self._row_labels = row_labels ...
boardslice.py
from constants import point_symbol, PointState class BoardSlice(object): def __init__(self, row_offset, column_offset, slice2d, row_labels, parent): self._slice2d = slice2d self._row_offset = row_offset self._column_offset = column_offset self._row_labels = row_labels ...
0.62395
0.285262
from PyQt6.QtWidgets import QApplication, QWidget, QGridLayout, QMessageBox from Assets import Assets from Toolbox import ToolboxLeft, ToolboxTop from ReactorGrid import ReactorGrid from Simulation import Simulation from InfoPanel import InfoPanel from Historian import Historian from MenuBar import DialogResult from R...
Fission Reactor Simulator/MainWidget.py
from PyQt6.QtWidgets import QApplication, QWidget, QGridLayout, QMessageBox from Assets import Assets from Toolbox import ToolboxLeft, ToolboxTop from ReactorGrid import ReactorGrid from Simulation import Simulation from InfoPanel import InfoPanel from Historian import Historian from MenuBar import DialogResult from R...
0.523664
0.189934
import scrapy from urllib.parse import urljoin, quote from scrapy import Selector from scrapy.spiders import Spider from datetime import datetime from jobcrawler.items import JobcrawlerItem from jobcrawler.settings import EXTENDED_REQUIREMENTS_STR from jobcrawler.utils import change_url_params class SkyWalkerSpider...
jobcrawler/spiders/skywalker_spider.py
import scrapy from urllib.parse import urljoin, quote from scrapy import Selector from scrapy.spiders import Spider from datetime import datetime from jobcrawler.items import JobcrawlerItem from jobcrawler.settings import EXTENDED_REQUIREMENTS_STR from jobcrawler.utils import change_url_params class SkyWalkerSpider...
0.506591
0.101947
import string import trio import trio.testing import server.initiator as initiator import net from server.types import Player from typings import * def new_half_stream_pair() -> Tuple[net.JSONStream, trio.abc.Stream]: left, right = trio.testing.memory_stream_pair() client = net.JSONStream(left) return cli...
tests/server/test_initiator.py
import string import trio import trio.testing import server.initiator as initiator import net from server.types import Player from typings import * def new_half_stream_pair() -> Tuple[net.JSONStream, trio.abc.Stream]: left, right = trio.testing.memory_stream_pair() client = net.JSONStream(left) return cli...
0.448185
0.402979
import numpy as np from numpy import pi #Code for calculating couplings (given values of Rnp and f, or an index) #Define the grid of coupling values to evaluate over Np = 32 Rrange = np.linspace(0.6, 1.00, Np) frange = np.append(np.linspace(-1.0, -0.97, 3*Np/4 + 1)[:-1], np.linspace(-0.97, -0.94,Np/4)) #Format of co...
analysis/CalcParamPoint.py
import numpy as np from numpy import pi #Code for calculating couplings (given values of Rnp and f, or an index) #Define the grid of coupling values to evaluate over Np = 32 Rrange = np.linspace(0.6, 1.00, Np) frange = np.append(np.linspace(-1.0, -0.97, 3*Np/4 + 1)[:-1], np.linspace(-0.97, -0.94,Np/4)) #Format of co...
0.599485
0.622918
import posixpath from memory_inspector.core import symbol class Stacktrace(object): """Models a stack-trace, which is a sequence of stack |Frame|s.""" def __init__(self): self.frames = [] def Add(self, frame): assert(isinstance(frame, Frame)) self.frames += [frame] @property def depth(self)...
tools/memory_inspector/memory_inspector/core/stacktrace.py
import posixpath from memory_inspector.core import symbol class Stacktrace(object): """Models a stack-trace, which is a sequence of stack |Frame|s.""" def __init__(self): self.frames = [] def Add(self, frame): assert(isinstance(frame, Frame)) self.frames += [frame] @property def depth(self)...
0.923186
0.489381
import numpy as np from warnings import warn from ..analysis.math import Vrf2dBm def generate_lin_array(start, stop, step=None, num=None, tol=1e-10): """ generate an array over a specified interval. requires <start> and <stop> and either <step> or <num> args: start (Union[int, float]): starti...
mesoscopy/measurement/array.py
import numpy as np from warnings import warn from ..analysis.math import Vrf2dBm def generate_lin_array(start, stop, step=None, num=None, tol=1e-10): """ generate an array over a specified interval. requires <start> and <stop> and either <step> or <num> args: start (Union[int, float]): starti...
0.799599
0.513668
import os import gc import numpy as np import pandas as pd from functools import partial from features import Feature, one_hot_encoder, parallel_apply, add_features_in_group, add_trend_feature, get_feature_names_by_period, safe_div from features.base import Base from features.raw_data import InstallmentsPayments from ...
src/features/installments_payments.py
import os import gc import numpy as np import pandas as pd from functools import partial from features import Feature, one_hot_encoder, parallel_apply, add_features_in_group, add_trend_feature, get_feature_names_by_period, safe_div from features.base import Base from features.raw_data import InstallmentsPayments from ...
0.584508
0.300534
from sql_metadata import Parser def test_getting_values(): parser = Parser( "INSERT /* VoteHelper::addVote xxx */ " "INTO `page_vote` (article_id,user_id,`time`) " "VALUES ('442001','27574631','20180228130846')" ) assert parser.values == ["442001", "27574631", "20180228130846"] ...
test/test_values.py
from sql_metadata import Parser def test_getting_values(): parser = Parser( "INSERT /* VoteHelper::addVote xxx */ " "INTO `page_vote` (article_id,user_id,`time`) " "VALUES ('442001','27574631','20180228130846')" ) assert parser.values == ["442001", "27574631", "20180228130846"] ...
0.571886
0.362687
from django.shortcuts import render, redirect from django.http import HttpResponse, Http404, HttpResponseBadRequest from django.views.defaults import bad_request from django.urls import reverse from urllib.parse import urlencode import datetime import requests from utils import SNI_URL, SNI_DYNAMIC_TOKEN, SNI_TEMP_US...
group/views.py
from django.shortcuts import render, redirect from django.http import HttpResponse, Http404, HttpResponseBadRequest from django.views.defaults import bad_request from django.urls import reverse from urllib.parse import urlencode import datetime import requests from utils import SNI_URL, SNI_DYNAMIC_TOKEN, SNI_TEMP_US...
0.47658
0.082512