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 time import json from .base import PublisherBase, to_float, to_str, arr_to_bytearray from .topic import pub_tub_json_topic, pub_tub_image_topic, pub_tub_fwd_image_topic class UserPublisher(PublisherBase): """ Tubデータ(辞書型、手動運転データのみ)をAWS IoT CoreへPublishするパーツクラス。 """ def __init__(self, aws_iot_clie...
parts/broker/pub/tub.py
import time import json from .base import PublisherBase, to_float, to_str, arr_to_bytearray from .topic import pub_tub_json_topic, pub_tub_image_topic, pub_tub_fwd_image_topic class UserPublisher(PublisherBase): """ Tubデータ(辞書型、手動運転データのみ)をAWS IoT CoreへPublishするパーツクラス。 """ def __init__(self, aws_iot_clie...
0.318909
0.105211
from abc import ABCMeta, abstractmethod from weightmass import WeightMass from vendor.HoeffdingTree.core import utils class HNode(object): __metaclass__ = ABCMeta """Base for the Hoeffding Tree nodes. Args: class_distribution (dict): The class distribution used to create the node. (default None) ...
vendor/HoeffdingTree/ht/hnode.py
from abc import ABCMeta, abstractmethod from weightmass import WeightMass from vendor.HoeffdingTree.core import utils class HNode(object): __metaclass__ = ABCMeta """Base for the Hoeffding Tree nodes. Args: class_distribution (dict): The class distribution used to create the node. (default None) ...
0.808219
0.220825
import time import torch import networkx as nx from torch.nn import Linear from torch_geometric.nn import GCNConv from torch_geometric.datasets import KarateClub from torch_geometric.utils import to_networkx # Helper function for visualization. import matplotlib.pyplot as plt # Visualization function for NX graph or ...
code/gcn_karateclub.py
import time import torch import networkx as nx from torch.nn import Linear from torch_geometric.nn import GCNConv from torch_geometric.datasets import KarateClub from torch_geometric.utils import to_networkx # Helper function for visualization. import matplotlib.pyplot as plt # Visualization function for NX graph or ...
0.951448
0.626096
from unittest import TestCase import gym import numpy as np import copy from auto_rl.learning.ppo import PPO from auto_rl.learning.policy import MLPActorCritic from auto_rl.utils.torch import validate_state_dicts class TestPPO(TestCase): def __init__(self, *args, **kwargs): super(TestPPO, self).__init__(...
algorithms/refactor/tests/learning/test_ppo.py
from unittest import TestCase import gym import numpy as np import copy from auto_rl.learning.ppo import PPO from auto_rl.learning.policy import MLPActorCritic from auto_rl.utils.torch import validate_state_dicts class TestPPO(TestCase): def __init__(self, *args, **kwargs): super(TestPPO, self).__init__(...
0.83901
0.526221
from dataclasses import dataclass, replace from typing import Type import numpy as np from numpy import ndarray from ..element import Element, ElementHex1 from .mesh_3d import Mesh3D from .mesh_tet_1 import MeshTet1 @dataclass(repr=False) class MeshHex1(Mesh3D): """A standard first-order hexahedral mesh. I...
skfem/mesh/mesh_hex_1.py
from dataclasses import dataclass, replace from typing import Type import numpy as np from numpy import ndarray from ..element import Element, ElementHex1 from .mesh_3d import Mesh3D from .mesh_tet_1 import MeshTet1 @dataclass(repr=False) class MeshHex1(Mesh3D): """A standard first-order hexahedral mesh. I...
0.884688
0.693719
from __future__ import division from iotbx.pdb.multimer_reconstruction import multimer import mmtbx.refinement.minimization_ncs_constraints import mmtbx.monomer_library.pdb_interpretation from scitbx.array_family import flex import mmtbx.monomer_library.server from libtbx import adopt_init_args from libtbx.utils import...
work/NCS/test_files/test_2qzv.py
from __future__ import division from iotbx.pdb.multimer_reconstruction import multimer import mmtbx.refinement.minimization_ncs_constraints import mmtbx.monomer_library.pdb_interpretation from scitbx.array_family import flex import mmtbx.monomer_library.server from libtbx import adopt_init_args from libtbx.utils import...
0.338077
0.191233
import logging import uuid from enum import Enum import attr import cattr from attr.validators import in_ from retry import retry from metadata.exc import ERPError, ERPParamsError from metadata.runtime import rt_context, rt_local from metadata.type_system.core import MetaData, parse_list_type from metadata.util.commo...
src/datamgr/metadata/metadata/backend/erp/functions.py
import logging import uuid from enum import Enum import attr import cattr from attr.validators import in_ from retry import retry from metadata.exc import ERPError, ERPParamsError from metadata.runtime import rt_context, rt_local from metadata.type_system.core import MetaData, parse_list_type from metadata.util.commo...
0.439386
0.094971
import app.preprocessing as preprocessing import app.text_detection as text_detection import app.text_recognition as text_recognition import app.post_proccess as post_process import app.util as util import cv2 import os import pathlib import matplotlib.pyplot as plt import matplotlib.image as mpimg # High = Less boxes...
app.py
import app.preprocessing as preprocessing import app.text_detection as text_detection import app.text_recognition as text_recognition import app.post_proccess as post_process import app.util as util import cv2 import os import pathlib import matplotlib.pyplot as plt import matplotlib.image as mpimg # High = Less boxes...
0.1844
0.230411
import os import volatility.obj as obj import volatility.debug as debug import volatility.plugins.linux.common as linux_common import volatility.plugins.linux.find_file as linux_find_file class linux_recover_filesystem(linux_common.AbstractLinuxCommand): """Recovers the entire cached file system from memory""" ...
volatility/volatility/plugins/linux/recover_filesystem.py
import os import volatility.obj as obj import volatility.debug as debug import volatility.plugins.linux.common as linux_common import volatility.plugins.linux.find_file as linux_find_file class linux_recover_filesystem(linux_common.AbstractLinuxCommand): """Recovers the entire cached file system from memory""" ...
0.309963
0.081119
import os import nltk import codecs import logging import numpy as np from scipy.ndimage import convolve1d from util import get_lds_kernel_window, STSShotAverage def process_sentence(sent, max_seq_len): '''process a sentence using NLTK toolkit''' return nltk.word_tokenize(sent)[:max_seq_len] def load_tsv(data...
sts-b-dir/tasks.py
import os import nltk import codecs import logging import numpy as np from scipy.ndimage import convolve1d from util import get_lds_kernel_window, STSShotAverage def process_sentence(sent, max_seq_len): '''process a sentence using NLTK toolkit''' return nltk.word_tokenize(sent)[:max_seq_len] def load_tsv(data...
0.394901
0.3295
import logging import signal from abc import ABCMeta, abstractmethod from contextlib import contextmanager from botocore.vendored import requests from exceptions import InvalidRequestType, TimeoutError from response import Response class Agent(object): """Base class that should be inherited from your CustomAgen...
customs_agent/agent.py
import logging import signal from abc import ABCMeta, abstractmethod from contextlib import contextmanager from botocore.vendored import requests from exceptions import InvalidRequestType, TimeoutError from response import Response class Agent(object): """Base class that should be inherited from your CustomAgen...
0.703957
0.100834
import pandas as pd from sklearn.preprocessing import LabelEncoder from sklearn.model_selection import StratifiedShuffleSplit from keras.models import Sequential from keras.layers import Dense from keras.utils import np_utils train = pd.read_csv('E:/Pro/python_proj/python_proj/WAND_Release/1D_CNN/dataset/100train.c...
Software/Python_Scripts/1D_CNN_Trainning/Model_Compile/1D_CNN.py
import pandas as pd from sklearn.preprocessing import LabelEncoder from sklearn.model_selection import StratifiedShuffleSplit from keras.models import Sequential from keras.layers import Dense from keras.utils import np_utils train = pd.read_csv('E:/Pro/python_proj/python_proj/WAND_Release/1D_CNN/dataset/100train.c...
0.45302
0.422326
from django.dispatch import receiver from django.db.models.signals import post_delete, pre_delete from builtins import str from builtins import zip from builtins import object from django.utils.translation import gettext_lazy as _ from future.utils import python_2_unicode_compatible from bluebottle.fsm.state import ...
bluebottle/fsm/triggers.py
from django.dispatch import receiver from django.db.models.signals import post_delete, pre_delete from builtins import str from builtins import zip from builtins import object from django.utils.translation import gettext_lazy as _ from future.utils import python_2_unicode_compatible from bluebottle.fsm.state import ...
0.7586
0.131229
import pytest import petlib @pytest.mark.task1 def test_petlib_present(): """ Try to import Petlib and pytest to ensure they are present on the system, and accessible to the python environment """ import petlib import pytest assert True @pytest.mark.task1 def test_code_present(): ...
EAC-code/TestCommitment.py
import pytest import petlib @pytest.mark.task1 def test_petlib_present(): """ Try to import Petlib and pytest to ensure they are present on the system, and accessible to the python environment """ import petlib import pytest assert True @pytest.mark.task1 def test_code_present(): ...
0.396419
0.599895
import torch import torch.optim as optim import torch.utils.data import time from datetime import datetime import torch.nn.functional as F from torch.autograd import Variable from model_logging import Logger from wavenet_modules import * import random def print_last_loss(opt): print("loss: ", opt.losses[-1]) de...
wavenet_training.py
import torch import torch.optim as optim import torch.utils.data import time from datetime import datetime import torch.nn.functional as F from torch.autograd import Variable from model_logging import Logger from wavenet_modules import * import random def print_last_loss(opt): print("loss: ", opt.losses[-1]) de...
0.762954
0.27837
from jetengine.metaclasses import DocumentMetaClass from jetengine.errors import InvalidDocumentError, LoadReferencesRequiredError AUTHORIZED_FIELDS = ["_id", "_values", "_reference_loaded_fields", "is_partly_loaded"] class BaseDocument(object): def __init__(self, _is_partly_loaded=False, _reference_loaded_fiel...
jetengine/document.py
from jetengine.metaclasses import DocumentMetaClass from jetengine.errors import InvalidDocumentError, LoadReferencesRequiredError AUTHORIZED_FIELDS = ["_id", "_values", "_reference_loaded_fields", "is_partly_loaded"] class BaseDocument(object): def __init__(self, _is_partly_loaded=False, _reference_loaded_fiel...
0.852767
0.28582
from flask import Flask, request, render_template from nltk_api.definition.response import DefinitionResponseBuilder from nltk_api.lemma.processor import POS from werkzeug.exceptions import BadRequest from nltk_api.definition.processor import DefinitionProcessor from nltk_api.util.responses import BadRequestIncorrect...
nltk_api/application.py
from flask import Flask, request, render_template from nltk_api.definition.response import DefinitionResponseBuilder from nltk_api.lemma.processor import POS from werkzeug.exceptions import BadRequest from nltk_api.definition.processor import DefinitionProcessor from nltk_api.util.responses import BadRequestIncorrect...
0.541894
0.113826
"""Tests for `block.py`.""" from absl.testing import absltest from absl.testing import parameterized import chex from distrax._src.bijectors import bijector as base from distrax._src.bijectors import block as block_bijector from distrax._src.bijectors import scalar_affine from distrax._src.utils import conversion imp...
distrax/_src/bijectors/block_test.py
"""Tests for `block.py`.""" from absl.testing import absltest from absl.testing import parameterized import chex from distrax._src.bijectors import bijector as base from distrax._src.bijectors import block as block_bijector from distrax._src.bijectors import scalar_affine from distrax._src.utils import conversion imp...
0.852629
0.795857
import numpy as np import pytest import tensorflow as tf from adnc.model.mann import MANN INPUT_SIZE = 22 OUTPUT_SIZE = 22 BATCH_SIZE = 31 CONFIG = { "seed": 123, "input_size": INPUT_SIZE, "output_size": OUTPUT_SIZE, "batch_size": BATCH_SIZE, "input_embedding": False, "architecture": 'uni', ...
test/adnc/model/test_mann.py
import numpy as np import pytest import tensorflow as tf from adnc.model.mann import MANN INPUT_SIZE = 22 OUTPUT_SIZE = 22 BATCH_SIZE = 31 CONFIG = { "seed": 123, "input_size": INPUT_SIZE, "output_size": OUTPUT_SIZE, "batch_size": BATCH_SIZE, "input_embedding": False, "architecture": 'uni', ...
0.654232
0.465691
from __future__ import absolute_import import re # noqa: F401 # python 2 and python 3 compatibility library import six from tb_rest_client.api_client import ApiClient class SchedulerEventControllerApi(object): """NOTE: This class is auto generated by the swagger code generator program. Do not edit the cl...
tb_rest_client/api/api_pe/scheduler_event_controller_api.py
from __future__ import absolute_import import re # noqa: F401 # python 2 and python 3 compatibility library import six from tb_rest_client.api_client import ApiClient class SchedulerEventControllerApi(object): """NOTE: This class is auto generated by the swagger code generator program. Do not edit the cl...
0.694613
0.073099
import numpy as np import pandas as pd # The column names of following_count A_FOLLOWER_COUNT = 'A_following_count' B_FOLLOWER_COUNT = 'B_following_count' MARGIN = 10 COST = 10 def get_influencer_follower_counts(test_data, y, y_val, column_name): """ :param test_data: (DataFrame) columns A_follower...
assignment_1/evaluation/model_value_calculator.py
import numpy as np import pandas as pd # The column names of following_count A_FOLLOWER_COUNT = 'A_following_count' B_FOLLOWER_COUNT = 'B_following_count' MARGIN = 10 COST = 10 def get_influencer_follower_counts(test_data, y, y_val, column_name): """ :param test_data: (DataFrame) columns A_follower...
0.637144
0.620966
# testing functions in datar.dplyr.funs import pytest from datar.core.backends import pandas as pd from datar.dplyr import ( between, lead, lag, cumany, cumall, nth, order_by, with_order, percent_rank, cume_dist, cummean, na_if, near, desc, first, last, ...
tests/dplyr/test_funs.py
# testing functions in datar.dplyr.funs import pytest from datar.core.backends import pandas as pd from datar.dplyr import ( between, lead, lag, cumany, cumall, nth, order_by, with_order, percent_rank, cume_dist, cummean, na_if, near, desc, first, last, ...
0.636127
0.647032
import os import click import hashlib import defaults import pkg_resources from manifest_checker import version import commands def validate_report_out(ctx, param, value): if value is None: return None if value.name == '-': raise click.BadParameter("Cannot use stdout for this parameter : use...
manifest_checker/main.py
import os import click import hashlib import defaults import pkg_resources from manifest_checker import version import commands def validate_report_out(ctx, param, value): if value is None: return None if value.name == '-': raise click.BadParameter("Cannot use stdout for this parameter : use...
0.409457
0.119331
from typing import Any, Callable, Dict, List, NoReturn, Optional, Union, cast from ..language import ( DirectiveDefinitionNode, DirectiveLocation, DocumentNode, EnumTypeDefinitionNode, EnumValueDefinitionNode, FieldDefinitionNode, InputObjectTypeDefinitionNode, InputValueDefinitionNode,...
graphql/utilities/build_ast_schema.py
from typing import Any, Callable, Dict, List, NoReturn, Optional, Union, cast from ..language import ( DirectiveDefinitionNode, DirectiveLocation, DocumentNode, EnumTypeDefinitionNode, EnumValueDefinitionNode, FieldDefinitionNode, InputObjectTypeDefinitionNode, InputValueDefinitionNode,...
0.900781
0.439507
def chamberofcommerce_data_scraper(url, source_phone): import urllib2 import time hdr = {'User-Agent': 'Mozilla/5.0 (X11; Linux x86_64) AppleWebKit/537.11 (KHTML, like Gecko) Chrome/23.0.1271.64 Safari/537.11', 'Accept': 'text/html,application/xhtml+xml,application/xml;q=0.9,*/*;q=0.8', ...
fetchers/test_all/data_scrapers/chamberofcommerce_data_scraper.py
def chamberofcommerce_data_scraper(url, source_phone): import urllib2 import time hdr = {'User-Agent': 'Mozilla/5.0 (X11; Linux x86_64) AppleWebKit/537.11 (KHTML, like Gecko) Chrome/23.0.1271.64 Safari/537.11', 'Accept': 'text/html,application/xhtml+xml,application/xml;q=0.9,*/*;q=0.8', ...
0.077481
0.137185
from django.test import TestCase from accounts.models import User from Support.Code.actions.Support.forms.for_fields import set_slug from unittest import expectedFailure class UserTest(TestCase): def setUp(self): self.user = User( username='<EMAIL>', name='name_test', email='<EMA...
project/Support/Code/tests/models/accounts/user.py
from django.test import TestCase from accounts.models import User from Support.Code.actions.Support.forms.for_fields import set_slug from unittest import expectedFailure class UserTest(TestCase): def setUp(self): self.user = User( username='<EMAIL>', name='name_test', email='<EMA...
0.414069
0.35973
def checkout(skus): price_table ={ "A": { "price" : 50, "offer" : True, "item_offer": False, "required_unit_for_offer" : {"3": 130,"5":200}, }, "B": { "price" : 30, "offer" : True, "item_o...
lib/solutions/CHK/checkout_solution.py
def checkout(skus): price_table ={ "A": { "price" : 50, "offer" : True, "item_offer": False, "required_unit_for_offer" : {"3": 130,"5":200}, }, "B": { "price" : 30, "offer" : True, "item_o...
0.256553
0.266023
import mimetypes import shutil import os from collections import OrderedDict from onegov.core.csv import convert_list_of_dicts_to_csv from onegov.core.csv import convert_list_of_dicts_to_xlsx from onegov.core.csv import convert_excel_to_csv from onegov.core.csv import CSVFile from onegov.core.custom import json from o...
src/onegov/directory/archive.py
import mimetypes import shutil import os from collections import OrderedDict from onegov.core.csv import convert_list_of_dicts_to_csv from onegov.core.csv import convert_list_of_dicts_to_xlsx from onegov.core.csv import convert_excel_to_csv from onegov.core.csv import CSVFile from onegov.core.custom import json from o...
0.597021
0.224969
from azure.cosmos import exceptions, CosmosClient, PartitionKey from json import loads container = None client = None def init(config): # Initialize the Cosmos client global container global client if container is None: client = CosmosClient(config.cosmos.endpoint, config.cosmos.primarykey) ...
cosmos.py
from azure.cosmos import exceptions, CosmosClient, PartitionKey from json import loads container = None client = None def init(config): # Initialize the Cosmos client global container global client if container is None: client = CosmosClient(config.cosmos.endpoint, config.cosmos.primarykey) ...
0.630571
0.079639
import numpy as np import tensorflow as tf import argparse import matplotlib.pyplot as plt from util import name_and_path_util from util.datahandler import DataHandler from util.records import Recorder from models.simple_dnn import SimpleDNN from models.trainer import Trainer from util import save_and_load def main...
train_model.py
import numpy as np import tensorflow as tf import argparse import matplotlib.pyplot as plt from util import name_and_path_util from util.datahandler import DataHandler from util.records import Recorder from models.simple_dnn import SimpleDNN from models.trainer import Trainer from util import save_and_load def main...
0.672224
0.301041
from __future__ import unicode_literals import re import json import time import uuid import random from django.shortcuts import render from django.contrib import messages from django.template.response import TemplateResponse from django.core.paginator import Paginator, EmptyPage, InvalidPage from django.http import H...
Linux-Operation0605/app/maillog/views.py
from __future__ import unicode_literals import re import json import time import uuid import random from django.shortcuts import render from django.contrib import messages from django.template.response import TemplateResponse from django.core.paginator import Paginator, EmptyPage, InvalidPage from django.http import H...
0.21984
0.082107
from pandas import Series from .plot_and_save import plot_and_save def plot_scatter_and_annotate( x, y, abs_dimension, annotation=(), opacity=0.64, annotation_font_size=10, title=None, html_file_path=None, ): if x is None: x = Series(range(y.size), name="Rank", index=y.i...
ccal/plot_scatter_and_annotate.py
from pandas import Series from .plot_and_save import plot_and_save def plot_scatter_and_annotate( x, y, abs_dimension, annotation=(), opacity=0.64, annotation_font_size=10, title=None, html_file_path=None, ): if x is None: x = Series(range(y.size), name="Rank", index=y.i...
0.532911
0.422326
import time import pytest import subprocess import boto3 from e2e.utils.config import metadata from e2e.utils.cognito_bootstrap.common import load_cfg, write_cfg from e2e.fixtures.kustomize import kustomize, configure_manifests from e2e.conftest import region from e2e.fixtures.cluster import cluster from e2e.fixtures....
tests/e2e/fixtures/storage_fsx_dependencies.py
import time import pytest import subprocess import boto3 from e2e.utils.config import metadata from e2e.utils.cognito_bootstrap.common import load_cfg, write_cfg from e2e.fixtures.kustomize import kustomize, configure_manifests from e2e.conftest import region from e2e.fixtures.cluster import cluster from e2e.fixtures....
0.159283
0.149811
from collections import defaultdict import torch from torch import nn import torch.nn.functional as F from ...utils.nn import get_rnn_hidden_state from .. import FF from ..attention import get_attention class XuDecoder(nn.Module): """A decoder which implements Show-attend-and-tell decoder.""" def __init__(se...
nmtpytorch/layers/decoders/xu.py
from collections import defaultdict import torch from torch import nn import torch.nn.functional as F from ...utils.nn import get_rnn_hidden_state from .. import FF from ..attention import get_attention class XuDecoder(nn.Module): """A decoder which implements Show-attend-and-tell decoder.""" def __init__(se...
0.909163
0.325708
import numpy as np from matplotlib import pyplot as plt import numpy.linalg as la import os def rk4(f, y0, T, N): # f(t_n, y_n) -> y'_n # y0 = Initial value # T = Final value of t, t varies from 0 to T inclusive # N = number of steps y = np.array(y0, dtype=float) h = float(T)/N ts = np.lin...
514/hwk11/h11.py
import numpy as np from matplotlib import pyplot as plt import numpy.linalg as la import os def rk4(f, y0, T, N): # f(t_n, y_n) -> y'_n # y0 = Initial value # T = Final value of t, t varies from 0 to T inclusive # N = number of steps y = np.array(y0, dtype=float) h = float(T)/N ts = np.lin...
0.495606
0.55435
import datetime import json try: from feedgenerator import SyndicationFeed, rfc3339_date except ImportError: from django.utils.feedgenerator import SyndicationFeed, rfc3339_date class JSONFeed(SyndicationFeed): content_type = 'application/json; charset=utf-8' @staticmethod def json_serial(obj): ...
jsonfeed/core.py
import datetime import json try: from feedgenerator import SyndicationFeed, rfc3339_date except ImportError: from django.utils.feedgenerator import SyndicationFeed, rfc3339_date class JSONFeed(SyndicationFeed): content_type = 'application/json; charset=utf-8' @staticmethod def json_serial(obj): ...
0.261425
0.04888
import argparse import hmac import io import ipaddress import logging import os import re from hashlib import sha1 from uuid import UUID import pathlib import flask from expiringdict import ExpiringDict from flask import abort, request, json import grappled import grappled.helpers h = logging.StreamHandler() h.setL...
grappled/__main__.py
import argparse import hmac import io import ipaddress import logging import os import re from hashlib import sha1 from uuid import UUID import pathlib import flask from expiringdict import ExpiringDict from flask import abort, request, json import grappled import grappled.helpers h = logging.StreamHandler() h.setL...
0.471467
0.055515
import urllib.request import json import tarfile import os from io import BytesIO from shutil import copyfile with open("./downloads/MicrocycSubstitution.tsv","r") as fSubtitution: lineMicrocyc=fSubtitution.readlines()[1:] #Create a dic Microcyc ID to PGDBs Name and a list of all PGDBsName dMicrocycIdtoPGDBname...
Bacteria/DLMicrocycandExtractWithoutdownloads.py
import urllib.request import json import tarfile import os from io import BytesIO from shutil import copyfile with open("./downloads/MicrocycSubstitution.tsv","r") as fSubtitution: lineMicrocyc=fSubtitution.readlines()[1:] #Create a dic Microcyc ID to PGDBs Name and a list of all PGDBsName dMicrocycIdtoPGDBname...
0.111598
0.090655
from queue import Empty from unittest.mock import patch, Mock, MagicMock, call, ANY from django.db import DatabaseError from django.test import TestCase from django_partisan.workers_manager import WorkersManager is_alive_return_value = 'is_alive.return_value' is_alive_side_effect = 'is_alive.side_effect' @patch('d...
django_partisan/tests/test_workers_manager.py
from queue import Empty from unittest.mock import patch, Mock, MagicMock, call, ANY from django.db import DatabaseError from django.test import TestCase from django_partisan.workers_manager import WorkersManager is_alive_return_value = 'is_alive.return_value' is_alive_side_effect = 'is_alive.side_effect' @patch('d...
0.579519
0.240948
from nltk import tokenize import numpy as np import os import re from itertools import permutations # analystic constants punc_list = [",", ".", ")", "_", "-", "/", '"', "'", "}", "]", "|", "?", "!"] char_list = ["a", "b", "c", "d", "e", "f", "g", "h", "i", "j", "k", "l", "m", "n", "o", "p", "q", "r", "s", "t", "u", "...
datasets/codra_check.py
from nltk import tokenize import numpy as np import os import re from itertools import permutations # analystic constants punc_list = [",", ".", ")", "_", "-", "/", '"', "'", "}", "]", "|", "?", "!"] char_list = ["a", "b", "c", "d", "e", "f", "g", "h", "i", "j", "k", "l", "m", "n", "o", "p", "q", "r", "s", "t", "u", "...
0.140307
0.135346
import random SUITS = ('Hearts', 'Diamonds', 'Spades', 'Clubs') RANKS = ('Two', 'Three', 'Four', 'Five', 'Six', 'Seven', 'Eight', 'Nine', 'Ten', 'Jack', 'Queen', 'King', 'Ace') VALUES = {'Two': 2, 'Three': 3, 'Four': 4, 'Five': 5, 'Six': 6, 'Seven': 7, 'Eight': 8, 'Nine': 9, 'Ten': 10, 'Jack': 10, 'Quee...
card-games/blackjack.py
import random SUITS = ('Hearts', 'Diamonds', 'Spades', 'Clubs') RANKS = ('Two', 'Three', 'Four', 'Five', 'Six', 'Seven', 'Eight', 'Nine', 'Ten', 'Jack', 'Queen', 'King', 'Ace') VALUES = {'Two': 2, 'Three': 3, 'Four': 4, 'Five': 5, 'Six': 6, 'Seven': 7, 'Eight': 8, 'Nine': 9, 'Ten': 10, 'Jack': 10, 'Quee...
0.444806
0.242021
from socket import * import threading from threading import Thread import tkinter import pyaudio import time def Receive(): while True: try: msg = client_socket.recv(BuffferSize).decode("utf8") if msg[0:12] == "{modifyList}": setNameList(msg[12:]) else: msg_list.insert(tkinter.END, msg) except OS...
client.py
from socket import * import threading from threading import Thread import tkinter import pyaudio import time def Receive(): while True: try: msg = client_socket.recv(BuffferSize).decode("utf8") if msg[0:12] == "{modifyList}": setNameList(msg[12:]) else: msg_list.insert(tkinter.END, msg) except OS...
0.30767
0.058966
import io import sys import time import datetime from enum import Enum HAS_CUDA = False try: import torch index = torch.cuda.current_device() torch.cuda.memory_allocated(index) HAS_CUDA = True except: pass # to avoid import common.torch and the cycle resulting from it def memory(): """ G...
common/log.py
import io import sys import time import datetime from enum import Enum HAS_CUDA = False try: import torch index = torch.cuda.current_device() torch.cuda.memory_allocated(index) HAS_CUDA = True except: pass # to avoid import common.torch and the cycle resulting from it def memory(): """ G...
0.565539
0.351895
from markupsafe import escape import sys import prometheus_client as prom import socket from OpenSSL import SSL, crypto from ssl import PROTOCOL_TLSv1_2 from fastapi import FastAPI, HTTPException import uvicorn import logging logging.basicConfig(format='%(asctime)s %(message)s', datefmt='%m/%d/%Y %I...
app/certificate_checker.py
from markupsafe import escape import sys import prometheus_client as prom import socket from OpenSSL import SSL, crypto from ssl import PROTOCOL_TLSv1_2 from fastapi import FastAPI, HTTPException import uvicorn import logging logging.basicConfig(format='%(asctime)s %(message)s', datefmt='%m/%d/%Y %I...
0.368747
0.064095
from __future__ import print_function, division __copyright__="""Copyright (c) 2003-2018 by The University of Queensland http://www.uq.edu.au Primary Business: Queensland, Australia""" __license__="""Licensed under the Open Software License version 3.0 http://www.opensource.org/licenses/osl-3.0.php""" __url__="https:...
dudley/test/python/run_trilinosComplexSolversOnDudley.py
from __future__ import print_function, division __copyright__="""Copyright (c) 2003-2018 by The University of Queensland http://www.uq.edu.au Primary Business: Queensland, Australia""" __license__="""Licensed under the Open Software License version 3.0 http://www.opensource.org/licenses/osl-3.0.php""" __url__="https:...
0.649912
0.263641
import pygame, sys class Spritesheet(object): def __init__(self, filename): """ Initialize a spritesheet. filename - Filename of the sprite sheet. """ try: self.sheet = pygame.image.load(filename).convert() except pygame.error, message: pri...
lib/graphics/spritesheet.py
import pygame, sys class Spritesheet(object): def __init__(self, filename): """ Initialize a spritesheet. filename - Filename of the sprite sheet. """ try: self.sheet = pygame.image.load(filename).convert() except pygame.error, message: pri...
0.503906
0.425009
import cv2 import numpy as np import scipy.ndimage import matplotlib.pyplot as plt def compute_gradients(firstImage, secondImage): """ Compute gradients in x, y and t direction between images :param firstImage: First image :param secondImage: Second image :return: Gradients """ firstImage...
horn_schunck/horn_schunk.py
import cv2 import numpy as np import scipy.ndimage import matplotlib.pyplot as plt def compute_gradients(firstImage, secondImage): """ Compute gradients in x, y and t direction between images :param firstImage: First image :param secondImage: Second image :return: Gradients """ firstImage...
0.816736
0.795777
import serial import sys # Utilities used by all UBX tools import ubx.Sensors from ubx.utilities import ubx_crc, log_file_name, mc_sender, ip_validator, udp_sender from ubx.UBXParser import UBXParser # Get all the settings for this programme import settings.sensors as settings this_programme = settings.UBXHEADINGSENS...
UBX/UBXHeadingSensor.py
import serial import sys # Utilities used by all UBX tools import ubx.Sensors from ubx.utilities import ubx_crc, log_file_name, mc_sender, ip_validator, udp_sender from ubx.UBXParser import UBXParser # Get all the settings for this programme import settings.sensors as settings this_programme = settings.UBXHEADINGSENS...
0.314577
0.135833
import argparse import os import sys import errno import shutil import subprocess import itertools import re import pyparanoid.pyparanoid as pp import multiprocessing as mp from Bio import SeqIO def parse_args(): parser = argparse.ArgumentParser(description=''' Master script for running PyParanoid process. modes: m...
BuildGroups.py
import argparse import os import sys import errno import shutil import subprocess import itertools import re import pyparanoid.pyparanoid as pp import multiprocessing as mp from Bio import SeqIO def parse_args(): parser = argparse.ArgumentParser(description=''' Master script for running PyParanoid process. modes: m...
0.131521
0.103341
# In[1]: import pandas as pd from datetime import datetime import requests from alphacast import Alphacast from dotenv import dotenv_values # In[2]: #Armo un diccionario con las urls de los archivos y sus respectivas hojas para el loop urlDict = {'constantes': ['https://www.bcu.gub.uy/Estadisticas-e-Indicadores/...
0284.Activity-Uruguay-BCU-National_Accounts.py
# In[1]: import pandas as pd from datetime import datetime import requests from alphacast import Alphacast from dotenv import dotenv_values # In[2]: #Armo un diccionario con las urls de los archivos y sus respectivas hojas para el loop urlDict = {'constantes': ['https://www.bcu.gub.uy/Estadisticas-e-Indicadores/...
0.395718
0.449513
import tkinter from tkinter import* def mod(a,b): return ( a % b) def StandardKnot(): global m knot = [] L = len(points) - 2 if L <= m -2 : print('make more points than m') return [] for i in range(m - 1): knot.append(0) for i in range(L - m + 3): knot.appe...
tktoolbox/incoming/spline.py
import tkinter from tkinter import* def mod(a,b): return ( a % b) def StandardKnot(): global m knot = [] L = len(points) - 2 if L <= m -2 : print('make more points than m') return [] for i in range(m - 1): knot.append(0) for i in range(L - m + 3): knot.appe...
0.225672
0.296826
import pandas as pd import cv2 as cv import os import numpy as np from keras.preprocessing.image import load_img, img_to_array X_train = [] X_test=[] root="G:/INTERNSHIP IIITA/Dataset/NUS-WIDE/Images/Flickr/Flickr/" #============================Train Images====================================== file=open("...
Code/test3.py
import pandas as pd import cv2 as cv import os import numpy as np from keras.preprocessing.image import load_img, img_to_array X_train = [] X_test=[] root="G:/INTERNSHIP IIITA/Dataset/NUS-WIDE/Images/Flickr/Flickr/" #============================Train Images====================================== file=open("...
0.241132
0.220049
import pytest from api.base.settings.defaults import API_BASE from api_tests.requests.mixins import NodeRequestTestMixin, PreprintRequestTestMixin @pytest.mark.django_db class TestActionDetailNodeRequests(NodeRequestTestMixin): @pytest.fixture() def url(self, node_request): action = node_request.acti...
api_tests/actions/views/test_action_detail.py
import pytest from api.base.settings.defaults import API_BASE from api_tests.requests.mixins import NodeRequestTestMixin, PreprintRequestTestMixin @pytest.mark.django_db class TestActionDetailNodeRequests(NodeRequestTestMixin): @pytest.fixture() def url(self, node_request): action = node_request.acti...
0.382372
0.288394
from typing import Dict, Set, Tuple from pants.backend.codegen.protobuf.target_types import ProtobufGrpcToggle, ProtobufSources from pants.backend.python.dependency_inference.module_mapper import ( FirstPartyPythonMappingImpl, FirstPartyPythonMappingImplMarker, ) from pants.base.specs import AddressSpecs, Des...
src/python/pants/backend/codegen/protobuf/python/python_protobuf_module_mapper.py
from typing import Dict, Set, Tuple from pants.backend.codegen.protobuf.target_types import ProtobufGrpcToggle, ProtobufSources from pants.backend.python.dependency_inference.module_mapper import ( FirstPartyPythonMappingImpl, FirstPartyPythonMappingImplMarker, ) from pants.base.specs import AddressSpecs, Des...
0.874507
0.179315
import imageio from skimage import img_as_ubyte, exposure from PIL import Image, ImageDraw, ImageFont import glob import numpy as np import os from numpy import unravel_index import cv2 from pathlib import Path from functions.pngTools import nBitPNG from functions.scanparameter import get_scanpara def downsize_img(i...
dataanalysis-notebook/functions/image_convert.py
import imageio from skimage import img_as_ubyte, exposure from PIL import Image, ImageDraw, ImageFont import glob import numpy as np import os from numpy import unravel_index import cv2 from pathlib import Path from functions.pngTools import nBitPNG from functions.scanparameter import get_scanpara def downsize_img(i...
0.510496
0.520801
from typing import TYPE_CHECKING, Iterable, List, Optional from logging import warning from uuid import uuid4 import numpy as np from qulacs import Observable, QuantumState # type: ignore from qulacs.observable import create_observable_from_openfermion_text # type: ignore from pytket.backends import ( Backend, ...
modules/pytket-qulacs/pytket/extensions/qulacs/backends/qulacs_backend.py
from typing import TYPE_CHECKING, Iterable, List, Optional from logging import warning from uuid import uuid4 import numpy as np from qulacs import Observable, QuantumState # type: ignore from qulacs.observable import create_observable_from_openfermion_text # type: ignore from pytket.backends import ( Backend, ...
0.895231
0.414543
import warnings import pulumi import pulumi.runtime from typing import Any, Mapping, Optional, Sequence, Union, overload from ... import _utilities from ._enums import * __all__ = [ 'ConnectedClusterAADProfileResponse', 'ConnectedClusterIdentityResponse', 'CredentialResultResponse', 'HybridConnectionC...
sdk/python/pulumi_azure_native/kubernetes/v20200101preview/outputs.py
import warnings import pulumi import pulumi.runtime from typing import Any, Mapping, Optional, Sequence, Union, overload from ... import _utilities from ._enums import * __all__ = [ 'ConnectedClusterAADProfileResponse', 'ConnectedClusterIdentityResponse', 'CredentialResultResponse', 'HybridConnectionC...
0.861684
0.063657
import numpy as np import numpy.ma as ma from numpy.testing import assert_array_equal from cloudnetpy.categorize import falling import pytest class Obs: def __init__(self): self.z = ma.array([[.4, .5, .6, .7, .5, .5], [.5, .5, .5, .5, .5, .5]], mask=[[...
tests/unit/test_falling.py
import numpy as np import numpy.ma as ma from numpy.testing import assert_array_equal from cloudnetpy.categorize import falling import pytest class Obs: def __init__(self): self.z = ma.array([[.4, .5, .6, .7, .5, .5], [.5, .5, .5, .5, .5, .5]], mask=[[...
0.510985
0.668021
import window import pygame from reversi import ReversiGame from typing import List, Dict from stats import plot_game_statistics from ai_players import RandomPlayer, MinimaxABPlayer def increment_player_score(player: str, w: window.Window) -> None: """Increments the player score of the corresponding player.""" ...
ui_handler.py
import window import pygame from reversi import ReversiGame from typing import List, Dict from stats import plot_game_statistics from ai_players import RandomPlayer, MinimaxABPlayer def increment_player_score(player: str, w: window.Window) -> None: """Increments the player score of the corresponding player.""" ...
0.879626
0.284148
import torch from mmdeploy.codebase.mmdet import (get_post_processing_params, pad_with_value_if_necessary) from mmdeploy.codebase.mmrotate.core.post_processing import \ multiclass_nms_rotated from mmdeploy.core import FUNCTION_REWRITER from mmdeploy.utils import is_dynamic_shap...
mmdeploy/codebase/mmrotate/models/rotated_anchor_head.py
import torch from mmdeploy.codebase.mmdet import (get_post_processing_params, pad_with_value_if_necessary) from mmdeploy.codebase.mmrotate.core.post_processing import \ multiclass_nms_rotated from mmdeploy.core import FUNCTION_REWRITER from mmdeploy.utils import is_dynamic_shap...
0.878744
0.404155
from datetime import datetime from unittest import TestCase try: from unittest.mock import patch, Mock except ImportError: from mock import patch, Mock from laika.reports import ReportFormatter, FilenameFormatter class ReportFormatterTest(TestCase): def setUp(self): now = datetime(2016, 2, 12, ...
laika/tests/test_formatter.py
from datetime import datetime from unittest import TestCase try: from unittest.mock import patch, Mock except ImportError: from mock import patch, Mock from laika.reports import ReportFormatter, FilenameFormatter class ReportFormatterTest(TestCase): def setUp(self): now = datetime(2016, 2, 12, ...
0.753829
0.319732
# no functions # classes class ArrayList(object): """ Implements the System.Collections.IList interface using an array whose size is dynamically increased as required. ArrayList() ArrayList(capacity: int) ArrayList(c: ICollection) """ def ZZZ(self): """hardcoded/mock instance of the class"...
release/stubs.min/System/Collections/__init__.py
# no functions # classes class ArrayList(object): """ Implements the System.Collections.IList interface using an array whose size is dynamically increased as required. ArrayList() ArrayList(capacity: int) ArrayList(c: ICollection) """ def ZZZ(self): """hardcoded/mock instance of the class"...
0.664105
0.505615
import numpy as np import teneva from ttopt import TTOpt from ttopt import ttopt_init np.random.seed(16333) def run(d=10, p=2, q=25, evals=1.E+5, rmax=4, with_cache=False): n = np.ones(d * q, dtype=int) * p Y0 = ttopt_init(n, rmax) for func in teneva.func_demo_all(d=d): name = func.name + ' '...
check/test.py
import numpy as np import teneva from ttopt import TTOpt from ttopt import ttopt_init np.random.seed(16333) def run(d=10, p=2, q=25, evals=1.E+5, rmax=4, with_cache=False): n = np.ones(d * q, dtype=int) * p Y0 = ttopt_init(n, rmax) for func in teneva.func_demo_all(d=d): name = func.name + ' '...
0.225672
0.218221
import logging from multiprocessing import Process from haddock.libs.libutil import parse_ncores logger = logging.getLogger(__name__) class Worker(Process): def __init__(self, tasks): super(Worker, self).__init__() self.tasks = tasks logger.info(f"Worker ready with {len(self.tasks)} ta...
src/haddock/libs/libparallel.py
import logging from multiprocessing import Process from haddock.libs.libutil import parse_ncores logger = logging.getLogger(__name__) class Worker(Process): def __init__(self, tasks): super(Worker, self).__init__() self.tasks = tasks logger.info(f"Worker ready with {len(self.tasks)} ta...
0.755276
0.230573
# encoding:utf-8 import cv2 import torch from torch.autograd import Variable import argparse from load_data import * from utils import PDR import config if __name__ == '__main__': ap = argparse.ArgumentParser() ap.add_argument("-m", "--model", required=True,help="path to the model file") args = vars(ap.pa...
video_detect.py
# encoding:utf-8 import cv2 import torch from torch.autograd import Variable import argparse from load_data import * from utils import PDR import config if __name__ == '__main__': ap = argparse.ArgumentParser() ap.add_argument("-m", "--model", required=True,help="path to the model file") args = vars(ap.pa...
0.433502
0.269833
import sys import maya.api._OpenMaya_py2 as om2 def maya_useNewAPI(): """ Function to Maya recognize the use of the Python API 2.0. """ # pylint: disable=invalid-name, unnecessary-pass pass def INPUT_ATTR(FNATTR): """ Configure a input attribute. """ # pylint: disable=invalid-name FNATTR.wri...
plugin/maya/nodes/mpx/MPxNode.py
import sys import maya.api._OpenMaya_py2 as om2 def maya_useNewAPI(): """ Function to Maya recognize the use of the Python API 2.0. """ # pylint: disable=invalid-name, unnecessary-pass pass def INPUT_ATTR(FNATTR): """ Configure a input attribute. """ # pylint: disable=invalid-name FNATTR.wri...
0.453746
0.384565
__version__ = "1.0.0" __modname__ = "Indigo Plugin User Interface" __author__ = "ColoradoFourWheeler" __copyright__ = "Copyright 2018, ColoradoFourWheeler & EPS" __credits__ = ["ColoradoFourWheeler"] __license__ = "GPL" __maintainer__ = "ColoradoFourWheeler" __email__ = "Indigo Forums" __status__ = "Produ...
EPS HomeKit Bridge.indigoPlugin/Contents/Server Plugin/lib/ifactory/include/ui.py
__version__ = "1.0.0" __modname__ = "Indigo Plugin User Interface" __author__ = "ColoradoFourWheeler" __copyright__ = "Copyright 2018, ColoradoFourWheeler & EPS" __credits__ = ["ColoradoFourWheeler"] __license__ = "GPL" __maintainer__ = "ColoradoFourWheeler" __email__ = "Indigo Forums" __status__ = "Produ...
0.294621
0.081483
import asyncio from datetime import datetime loop = asyncio.get_event_loop() asyncio.set_event_loop(loop) from asyncdb import AsyncDB, AsyncPool from asyncdb.providers.pg import pg, pgPool params = { "user": "troc_pgdata", "password": "<PASSWORD>", "host": "127.0.0.1", "port": "5432", "database":...
probe/test_pg.py
import asyncio from datetime import datetime loop = asyncio.get_event_loop() asyncio.set_event_loop(loop) from asyncdb import AsyncDB, AsyncPool from asyncdb.providers.pg import pg, pgPool params = { "user": "troc_pgdata", "password": "<PASSWORD>", "host": "127.0.0.1", "port": "5432", "database":...
0.296451
0.125199
from flask import Flask, render_template, request import os from subprocess import Popen, PIPE, CalledProcessError # ALLOWED_EXTENSIONS = set([]) installer = Flask(__name__) def _popen_yield(cmd): popen = Popen(cmd, stdout=PIPE, stderr=PIPE, universal_newlines=True) for stdout_line in iter(popen.stdout.read...
carrier_installer/installer.py
from flask import Flask, render_template, request import os from subprocess import Popen, PIPE, CalledProcessError # ALLOWED_EXTENSIONS = set([]) installer = Flask(__name__) def _popen_yield(cmd): popen = Popen(cmd, stdout=PIPE, stderr=PIPE, universal_newlines=True) for stdout_line in iter(popen.stdout.read...
0.360714
0.048631
from django.contrib.auth.forms import UserCreationForm from django.contrib.auth.models import User from django import forms from .models import Profile class RegisterForm(UserCreationForm): username = forms.CharField(label=False, max_length=20, widget=forms.TextInput( attrs={'class': 'form-control', 'plac...
users/forms.py
from django.contrib.auth.forms import UserCreationForm from django.contrib.auth.models import User from django import forms from .models import Profile class RegisterForm(UserCreationForm): username = forms.CharField(label=False, max_length=20, widget=forms.TextInput( attrs={'class': 'form-control', 'plac...
0.41324
0.098339
def gen08(fnumber, data, number_of_points=16777216, comment=None): """ http://www.csounds.com/manual/html/GEN08.html """ # generate parts off data step = number_of_points / len(data) gen = "f%s 0 %s -8 " % (fnumber, number_of_points) for i in data: gen += "%s %s " % (i, step) ...
src/csound/orchestra.py
def gen08(fnumber, data, number_of_points=16777216, comment=None): """ http://www.csounds.com/manual/html/GEN08.html """ # generate parts off data step = number_of_points / len(data) gen = "f%s 0 %s -8 " % (fnumber, number_of_points) for i in data: gen += "%s %s " % (i, step) ...
0.582729
0.309787
from django import forms from django.contrib.auth.models import User from django.contrib.auth import authenticate from crispy_forms.helper import FormHelper from crispy_forms.layout import Layout, Fieldset, ButtonHolder, Submit class LoginForm(forms.Form): username = forms.CharField(label="Username:", max...
watpi/apps/login/forms.py
from django import forms from django.contrib.auth.models import User from django.contrib.auth import authenticate from crispy_forms.helper import FormHelper from crispy_forms.layout import Layout, Fieldset, ButtonHolder, Submit class LoginForm(forms.Form): username = forms.CharField(label="Username:", max...
0.232049
0.056783
import getpass import re import tempfile from binascii import hexlify, unhexlify import pytest from ..crypto import bytes_to_long, num_aes_blocks from ..helpers import Location from ..helpers import Chunk from ..helpers import IntegrityError from ..key import PlaintextKey, PassphraseKey, KeyfileKey, Passphrase, Passw...
src/borg/testsuite/key.py
import getpass import re import tempfile from binascii import hexlify, unhexlify import pytest from ..crypto import bytes_to_long, num_aes_blocks from ..helpers import Location from ..helpers import Chunk from ..helpers import IntegrityError from ..key import PlaintextKey, PassphraseKey, KeyfileKey, Passphrase, Passw...
0.396302
0.299377
import os import discord from discord.ext import commands from dotenv import load_dotenv from markov_generator import generate from jep_functions import parse_jep, clean_answer import asyncio import json import requests import time import re import random load_dotenv() TOKEN = os.getenv('DISCORD_TOKEN') client = co...
bot.py
0.096376
0.185228
import frappe from frappe.utils import flt from erpnext.controllers.buying_controller import BuyingController from erpnext.controllers.selling_controller import SellingController from erpnext.stock.doctype.stock_entry.stock_entry import StockEntry import erpnext.accounts.party def update_ordered_and_reserved_qty(self...
repost_sles/overrides.py
import frappe from frappe.utils import flt from erpnext.controllers.buying_controller import BuyingController from erpnext.controllers.selling_controller import SellingController from erpnext.stock.doctype.stock_entry.stock_entry import StockEntry import erpnext.accounts.party def update_ordered_and_reserved_qty(self...
0.226869
0.169234
DEFAULT_EP = "http://api.moodstocks.com/v2" from requests.auth import HTTPDigestAuth import requests import json import os import base64 version = '0.1' codes = requests.codes def b64_encode(s): """ Encode input string with base64url safe without padding scheme. """ return base64.urlsafe_b64encode(...
python/moodstocks.py
DEFAULT_EP = "http://api.moodstocks.com/v2" from requests.auth import HTTPDigestAuth import requests import json import os import base64 version = '0.1' codes = requests.codes def b64_encode(s): """ Encode input string with base64url safe without padding scheme. """ return base64.urlsafe_b64encode(...
0.785597
0.272
from __future__ import print_function import mock from chromite.cbuildbot import commands from chromite.cbuildbot import manifest_version from chromite.cbuildbot import prebuilts from chromite.cbuildbot.stages import completion_stages from chromite.cbuildbot.stages import generic_stages from chromite.cbuildbot.stages...
cbuildbot/stages/completion_stages_unittest.py
from __future__ import print_function import mock from chromite.cbuildbot import commands from chromite.cbuildbot import manifest_version from chromite.cbuildbot import prebuilts from chromite.cbuildbot.stages import completion_stages from chromite.cbuildbot.stages import generic_stages from chromite.cbuildbot.stages...
0.755366
0.170992
from PyQt5.QtCore import qInstallMessageHandler from PyQt5.QtCore import qDebug, QtInfoMsg, QtWarningMsg, QtCriticalMsg, QtFatalMsg from PyQt5.QtCore import QObject, pyqtSlot, pyqtSignal, pyqtProperty import logging class SignalStreamHandler(QObject, logging.StreamHandler): logEvent = pyqtSignal(str, str, str, st...
Logger.py
from PyQt5.QtCore import qInstallMessageHandler from PyQt5.QtCore import qDebug, QtInfoMsg, QtWarningMsg, QtCriticalMsg, QtFatalMsg from PyQt5.QtCore import QObject, pyqtSlot, pyqtSignal, pyqtProperty import logging class SignalStreamHandler(QObject, logging.StreamHandler): logEvent = pyqtSignal(str, str, str, st...
0.424531
0.072472
import os import sys sys.path.insert(0, os.path.dirname('__file__')) from unittest.mock import patch, call, Mock import lib.nonogram as nonogram def test_ModeData_initialisation_empty(): mode_data = nonogram.ModeData() assert mode_data.fig == None assert mode_data.image == None assert mode_data.wait ...
tests/test_ModeData_class.py
import os import sys sys.path.insert(0, os.path.dirname('__file__')) from unittest.mock import patch, call, Mock import lib.nonogram as nonogram def test_ModeData_initialisation_empty(): mode_data = nonogram.ModeData() assert mode_data.fig == None assert mode_data.image == None assert mode_data.wait ...
0.559049
0.671151
from collections import OrderedDict from copy import deepcopy from random import randint, choice from plenum.common.util import randomString from state.db.persistent_db import PersistentDB from state.trie.pruning_trie import Trie, rlp_encode, rlp_decode from storage.kv_in_memory import KeyValueStorageInMemory def ge...
state/test/trie/test_proof.py
from collections import OrderedDict from copy import deepcopy from random import randint, choice from plenum.common.util import randomString from state.db.persistent_db import PersistentDB from state.trie.pruning_trie import Trie, rlp_encode, rlp_decode from storage.kv_in_memory import KeyValueStorageInMemory def ge...
0.592431
0.456713
import sys sys.path.append('../') from django.contrib.auth.forms import UserCreationForm from django.shortcuts import render from .forms import ContactForm from django.http import HttpResponse from mysite.model.main import Main def _form_view(request, template_name='basic.html', form_class=ContactForm): if reque...
mysite/views.py
import sys sys.path.append('../') from django.contrib.auth.forms import UserCreationForm from django.shortcuts import render from .forms import ContactForm from django.http import HttpResponse from mysite.model.main import Main def _form_view(request, template_name='basic.html', form_class=ContactForm): if reque...
0.13759
0.165054
import requests import aiohttp import asyncio import datetime import json from os import getenv from urllib.parse import urlparse, urlunparse from urllib3.util import Retry class DistributedApiTaskManager: def __init__(self): self.cache_connector_upsert_url = getenv('CACHE_CONNECTOR_UPSERT_URI') se...
APIs/1.0/Common/task_management/distributed_api_task.py
import requests import aiohttp import asyncio import datetime import json from os import getenv from urllib.parse import urlparse, urlunparse from urllib3.util import Retry class DistributedApiTaskManager: def __init__(self): self.cache_connector_upsert_url = getenv('CACHE_CONNECTOR_UPSERT_URI') se...
0.308711
0.064007
import json import logging import os from xml.etree import ElementTree as ET from typing import Dict import aiohttp import aiohttp.web_request from aiohttp import web from async_lru import alru_cache from lxml.html import document_fromstring, HtmlElement logging.basicConfig() logger = logging.getLogger(__name__) logg...
main.py
import json import logging import os from xml.etree import ElementTree as ET from typing import Dict import aiohttp import aiohttp.web_request from aiohttp import web from async_lru import alru_cache from lxml.html import document_fromstring, HtmlElement logging.basicConfig() logger = logging.getLogger(__name__) logg...
0.370909
0.099208
import argparse import os from itertools import combinations, product from multiprocessing import Pool import networkx as nx import pandas as pd from custom_utils import get_jaccard, get_structures_added, load_json from statics import STRUCTURE_TYPES def get_product_graph(g1, g2, graphicspath, resultspath): o1 ...
code/compute_structure_alignment.py
import argparse import os from itertools import combinations, product from multiprocessing import Pool import networkx as nx import pandas as pd from custom_utils import get_jaccard, get_structures_added, load_json from statics import STRUCTURE_TYPES def get_product_graph(g1, g2, graphicspath, resultspath): o1 ...
0.438304
0.36574
__facility__ = "Online" __abstract__ = __doc__ __author__ = "<NAME>" __date__ = "$Date: 2008/02/15 22:48:21 $" __version__ = "$Revision: 1.1 $, $Author: fewtrell $" __release__ = "$Name: $" __credits__ = "NRL code 7650" def ROOTFit(func, xpts, ypts,...
python/lib/ROOTFit.py
__facility__ = "Online" __abstract__ = __doc__ __author__ = "<NAME>" __date__ = "$Date: 2008/02/15 22:48:21 $" __version__ = "$Revision: 1.1 $, $Author: fewtrell $" __release__ = "$Name: $" __credits__ = "NRL code 7650" def ROOTFit(func, xpts, ypts,...
0.622574
0.269927
import hashlib from django.contrib.auth import get_user_model from django.contrib.auth.hashers import make_password from django.db.models import Q from django import forms from django.utils import timezone from django.utils.translation import ugettext_lazy as _ from dateutil.relativedelta import relativedelta from ....
payslip/forms.py
import hashlib from django.contrib.auth import get_user_model from django.contrib.auth.hashers import make_password from django.db.models import Q from django import forms from django.utils import timezone from django.utils.translation import ugettext_lazy as _ from dateutil.relativedelta import relativedelta from ....
0.547706
0.099733
from typing import Any, Dict, Iterable, List, Optional import requests from .camunda_models import ProcessDefinition, Task, factory from .client import get_client from .types import CamundaId, ProcessVariables from .utils import deserialize_variable, serialize_variable def get_process_definitions() -> List[ProcessD...
django_camunda/api.py
from typing import Any, Dict, Iterable, List, Optional import requests from .camunda_models import ProcessDefinition, Task, factory from .client import get_client from .types import CamundaId, ProcessVariables from .utils import deserialize_variable, serialize_variable def get_process_definitions() -> List[ProcessD...
0.680242
0.139983
from os import urandom from gmpy2 import next_prime from random import randrange, getrandbits from Crypto.Cipher import AES from fastecdsa.curve import Curve def bytes_to_long(data): return int.from_bytes(data, 'big') def generate_random_point(p): while True: a, x, y = (randrange(0, p) for _ in ran...
Aero/2021/crypto/horcrux/horcrux.py
from os import urandom from gmpy2 import next_prime from random import randrange, getrandbits from Crypto.Cipher import AES from fastecdsa.curve import Curve def bytes_to_long(data): return int.from_bytes(data, 'big') def generate_random_point(p): while True: a, x, y = (randrange(0, p) for _ in ran...
0.592549
0.335242
import torch import torch.nn as nn from torch import Tensor from .Embedding import PositionalEmbedding from .loss import SCELoss from utils import generate_square_subsequent_mask from typing import List, Tuple, Optional class CapDecoder(nn.Module): def __init__(self, num_layers, embed_dim, nhead, dim_feedforward...
model/CapDecoder.py
import torch import torch.nn as nn from torch import Tensor from .Embedding import PositionalEmbedding from .loss import SCELoss from utils import generate_square_subsequent_mask from typing import List, Tuple, Optional class CapDecoder(nn.Module): def __init__(self, num_layers, embed_dim, nhead, dim_feedforward...
0.951154
0.472623
from antlr4 import * from io import StringIO from typing.io import TextIO import sys def serializedATN(): with StringIO() as buf: buf.write("\3\u608b\ua72a\u8133\ub9ed\u417c\u3be7\u7786\u5964\2\66") buf.write("\u0164\b\1\4\2\t\2\4\3\t\3\4\4\t\4\4\5\t\5\4\6\t\6\4\7") buf.write("\t\7\4\b\t\...
ToyCLexer.py
from antlr4 import * from io import StringIO from typing.io import TextIO import sys def serializedATN(): with StringIO() as buf: buf.write("\3\u608b\ua72a\u8133\ub9ed\u417c\u3be7\u7786\u5964\2\66") buf.write("\u0164\b\1\4\2\t\2\4\3\t\3\4\4\t\4\4\5\t\5\4\6\t\6\4\7") buf.write("\t\7\4\b\t\...
0.218836
0.271867
__author__ = "<NAME>" # Character class to create character objects with stats # Will have character stat manager to manage base stats plus pots (default maxed) class Character: # unfortunately, "def" is a keyword :) # slots are objects of items which contain active stats def __init__(self, life, mana, att...
src/functions/character.py
__author__ = "<NAME>" # Character class to create character objects with stats # Will have character stat manager to manage base stats plus pots (default maxed) class Character: # unfortunately, "def" is a keyword :) # slots are objects of items which contain active stats def __init__(self, life, mana, att...
0.748812
0.243204
import socket import select from .parser import Parser from .ports import MultiPort, BaseIOPort from .py2 import PY2 def _is_readable(socket): """Return True if there is data to be read on the socket.""" timeout = 0 (rlist, wlist, elist) = select.select( [socket.fileno()], [], [], timeout) ...
mido/sockets.py
import socket import select from .parser import Parser from .ports import MultiPort, BaseIOPort from .py2 import PY2 def _is_readable(socket): """Return True if there is data to be read on the socket.""" timeout = 0 (rlist, wlist, elist) = select.select( [socket.fileno()], [], [], timeout) ...
0.652352
0.098903
from lxml import etree from enum import Enum import sys FileReaderStatus = Enum('FileReaderStatus', 'MODULE_FOUND MODULE_NOT_FOUND') ParameterTypes = Enum('ParameterTypes', 'INTEGER FLOAT BOOLEAN STRING FUNCTION ENUMERATION') ReferenceTypes = Enum('ReferenceTypes', 'SIMPLE_REFERENCE CHOICE_REFERENCE FOREIGN_REFERENCE ...
asrGenerator/autosarfileprocessor.py
from lxml import etree from enum import Enum import sys FileReaderStatus = Enum('FileReaderStatus', 'MODULE_FOUND MODULE_NOT_FOUND') ParameterTypes = Enum('ParameterTypes', 'INTEGER FLOAT BOOLEAN STRING FUNCTION ENUMERATION') ReferenceTypes = Enum('ReferenceTypes', 'SIMPLE_REFERENCE CHOICE_REFERENCE FOREIGN_REFERENCE ...
0.285272
0.074534
import matplotlib as mpl mpl.use('agg') import os import numpy as np import pylab as plt import ngene as ng from ngene.architectures.simple import architecture import ccgpack as ccg import tensorflow as tf from tqdm import tqdm, trange from scipy.stats import ttest_ind cl = np.load('../data/cl_planck_lensed.npy') sfs...
scripts/toy_strings.py
import matplotlib as mpl mpl.use('agg') import os import numpy as np import pylab as plt import ngene as ng from ngene.architectures.simple import architecture import ccgpack as ccg import tensorflow as tf from tqdm import tqdm, trange from scipy.stats import ttest_ind cl = np.load('../data/cl_planck_lensed.npy') sfs...
0.229104
0.223896
import unittest class Result(unittest.TestResult): def __init__(self, test_id, queue): super().__init__() self._test_id = test_id self._queue = queue def startTestRun(self): super().startTestRun() data = {"id": self._test_id, "event": "start_test_run"} self._q...
jupitest/host/result.py
import unittest class Result(unittest.TestResult): def __init__(self, test_id, queue): super().__init__() self._test_id = test_id self._queue = queue def startTestRun(self): super().startTestRun() data = {"id": self._test_id, "event": "start_test_run"} self._q...
0.422147
0.447279
import pytest import factories_v2 import factories_v5 import setup_django # NOQA import aeat import aeat.rest_framework.validators as validators ''' Test tagged as functional are are not run by default (see setup.cfg) Copy .env-sample to .env and set the certificate paths Enable the env vars with ```export `cat ....
tests/test_aeat_functional.py
import pytest import factories_v2 import factories_v5 import setup_django # NOQA import aeat import aeat.rest_framework.validators as validators ''' Test tagged as functional are are not run by default (see setup.cfg) Copy .env-sample to .env and set the certificate paths Enable the env vars with ```export `cat ....
0.720565
0.73344
import xml.dom.minidom as minidom import os.path import os import sys import getopt # validation validation=False #parameters partest_1=0 partest_2=0 partest_3=0 partest_1_bool=False partest_2_bool=False partest_3_bool=False # files outputFilename=None inputFilename=None referenceXsd=None def ma...
tests/xml/stub_dump.py
import xml.dom.minidom as minidom import os.path import os import sys import getopt # validation validation=False #parameters partest_1=0 partest_2=0 partest_3=0 partest_1_bool=False partest_2_bool=False partest_3_bool=False # files outputFilename=None inputFilename=None referenceXsd=None def ma...
0.069633
0.087291
from PyQt5 import QtCore, QtWidgets, QtGui import ctypes from PyQt5.QtGui import QTextCursor from PyQt5.QtWidgets import QFileDialog, QMessageBox, QColorDialog, QFormLayout, QLineEdit, QPushButton, QInputDialog, \ QWidget, QHBoxLayout, QDialog import Utils from Restore import Restore from Settings import Settings ...
UI.py
from PyQt5 import QtCore, QtWidgets, QtGui import ctypes from PyQt5.QtGui import QTextCursor from PyQt5.QtWidgets import QFileDialog, QMessageBox, QColorDialog, QFormLayout, QLineEdit, QPushButton, QInputDialog, \ QWidget, QHBoxLayout, QDialog import Utils from Restore import Restore from Settings import Settings ...
0.283087
0.045142
import torch from mmcv.utils import print_log from .base import BaseDataset from .builder import DATASETS from .utils import to_numpy @DATASETS.register_module() class SingleViewDataset(BaseDataset): """The dataset outputs one view of an image, containing some other information such as label, idx, etc. ...
mmselfsup/datasets/single_view.py
import torch from mmcv.utils import print_log from .base import BaseDataset from .builder import DATASETS from .utils import to_numpy @DATASETS.register_module() class SingleViewDataset(BaseDataset): """The dataset outputs one view of an image, containing some other information such as label, idx, etc. ...
0.853471
0.464719
from typing import Optional, List from biocommons.seqrepo import SeqRepo from variation import SEQREPO_DATA_PATH from os import environ import logging logger = logging.getLogger('variation') logger.setLevel(logging.DEBUG) class SeqRepoAccess: """The SeqRepoAccess class.""" def __init__(self, seqrepo_data_p...
variation/data_sources/seq_repo_access.py
from typing import Optional, List from biocommons.seqrepo import SeqRepo from variation import SEQREPO_DATA_PATH from os import environ import logging logger = logging.getLogger('variation') logger.setLevel(logging.DEBUG) class SeqRepoAccess: """The SeqRepoAccess class.""" def __init__(self, seqrepo_data_p...
0.936445
0.203411