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 django.db import migrations, models class Migration(migrations.Migration): dependencies = [ ('content_management', '0023_auto_20180424_1227'), ] operations = [ migrations.AlterField( model_name='cataloger', name='description', field=models.CharFi...
build_automation/content_management/migrations/0024_auto_20180428_1833.py
from django.db import migrations, models class Migration(migrations.Migration): dependencies = [ ('content_management', '0023_auto_20180424_1227'), ] operations = [ migrations.AlterField( model_name='cataloger', name='description', field=models.CharFi...
0.6705
0.120284
import unittest import orca import os.path as path from setup.settings import * from pandas.util.testing import * class Csv: pdf_csv = None odf_csv = None class DataFrameReindexingTest(unittest.TestCase): @classmethod def setUpClass(cls): # configure data directory DATA_DIR = path.ab...
tests/orca_unit_testing/test_dataframe_reindexing_selection.py
import unittest import orca import os.path as path from setup.settings import * from pandas.util.testing import * class Csv: pdf_csv = None odf_csv = None class DataFrameReindexingTest(unittest.TestCase): @classmethod def setUpClass(cls): # configure data directory DATA_DIR = path.ab...
0.609873
0.493958
import sys, os, pwd, string, re, selinux obj = "(\{[^\}]*\}|[^ \t:]*)" allow_regexp = "(allow|dontaudit)[ \t]+%s[ \t]*%s[ \t]*:[ \t]*%s[ \t]*%s" % (obj, obj, obj, obj) awk_script = '/^[[:blank:]]*interface[[:blank:]]*\(/ {\n\ IFACEFILE=FILENAME\n\ IFACENAME = gensub("^[[:blank:]]*interface[[:blank:]]*\\\\(\`?...
contrib/sebsd/policycoreutils/audit2allow/avc.py
import sys, os, pwd, string, re, selinux obj = "(\{[^\}]*\}|[^ \t:]*)" allow_regexp = "(allow|dontaudit)[ \t]+%s[ \t]*%s[ \t]*:[ \t]*%s[ \t]*%s" % (obj, obj, obj, obj) awk_script = '/^[[:blank:]]*interface[[:blank:]]*\(/ {\n\ IFACEFILE=FILENAME\n\ IFACENAME = gensub("^[[:blank:]]*interface[[:blank:]]*\\\\(\`?...
0.064337
0.147218
from datetime import datetime from enum import IntEnum from typing import Any, Optional, Union from pydisco.http import Http from pydisco.utils import convert_snowflake_to_datetime class UserFlags(IntEnum): """ This enum represents flags that can be added to a user's account. See Also --...
pydisco/user.py
from datetime import datetime from enum import IntEnum from typing import Any, Optional, Union from pydisco.http import Http from pydisco.utils import convert_snowflake_to_datetime class UserFlags(IntEnum): """ This enum represents flags that can be added to a user's account. See Also --...
0.919077
0.356783
import torch import torchaudio from torch.utils.data import DataLoader from torch import nn from USDataset import US8KDataset BATCH_SIZE = 64 EPOCHS = 20 LEARNING_RATE = 0.001 ANNOTATIONS_FILE = "UrbanSound8K/metadata/UrbanSound8K.csv" AUDIO_DIR = "UrbanSound8K/audio" SAMPLE_RATE = 44100 NUM_SAMPLES = 44100 device = ...
model.py
import torch import torchaudio from torch.utils.data import DataLoader from torch import nn from USDataset import US8KDataset BATCH_SIZE = 64 EPOCHS = 20 LEARNING_RATE = 0.001 ANNOTATIONS_FILE = "UrbanSound8K/metadata/UrbanSound8K.csv" AUDIO_DIR = "UrbanSound8K/audio" SAMPLE_RATE = 44100 NUM_SAMPLES = 44100 device = ...
0.931579
0.339007
import argparse import pandas as pd import numpy as np def net_stats(net_df, n_edges, pos_df, neg_df, wt_attr): top_df = net_df.head(n_edges) tp_shape = top_df[ top_df.edge.isin(pos_df.edge) ].shape fp_shape = top_df[ top_df.edge.isin(neg_df.edge) ].shape max_wt = np.max(top_df[wt_attr]) min_wt = n...
utils/analyse_network.py
import argparse import pandas as pd import numpy as np def net_stats(net_df, n_edges, pos_df, neg_df, wt_attr): top_df = net_df.head(n_edges) tp_shape = top_df[ top_df.edge.isin(pos_df.edge) ].shape fp_shape = top_df[ top_df.edge.isin(neg_df.edge) ].shape max_wt = np.max(top_df[wt_attr]) min_wt = n...
0.418935
0.205197
import os import re from git import Repo import syncmanagerclient.util.globalproperties as globalproperties class DeletionRegistration: def __init__(self, **kwargs): self.branch_path = kwargs.get('branch_path', None) self.registry_dir = globalproperties.var_dir # first check if directory ...
syncmanagerclient/syncmanagerclient/clients/deletion_registration.py
import os import re from git import Repo import syncmanagerclient.util.globalproperties as globalproperties class DeletionRegistration: def __init__(self, **kwargs): self.branch_path = kwargs.get('branch_path', None) self.registry_dir = globalproperties.var_dir # first check if directory ...
0.221687
0.058615
class ImageFolderDataset(Dataset): def __init__(self, root_path, transform=None, target_window=100, first_k=None, last_k=None, skip_every=1, repeat=1, cache='in_memory', shuffle_mapping=False, forced_mapping=None, real_shuffle=False, batch_size=args.batch_size, l...
datasets/contrastive.py
class ImageFolderDataset(Dataset): def __init__(self, root_path, transform=None, target_window=100, first_k=None, last_k=None, skip_every=1, repeat=1, cache='in_memory', shuffle_mapping=False, forced_mapping=None, real_shuffle=False, batch_size=args.batch_size, l...
0.522689
0.175256
import typing from dataclasses import dataclass from aiothornode.types import ThorConstants, ThorMimir from services.lib.texts import split_by_camel_case from services.models.base import BaseModelMixin @dataclass class MimirEntry: name: str pretty_name: str real_value: str hard_coded_value: str ...
app/services/models/mimir.py
import typing from dataclasses import dataclass from aiothornode.types import ThorConstants, ThorMimir from services.lib.texts import split_by_camel_case from services.models.base import BaseModelMixin @dataclass class MimirEntry: name: str pretty_name: str real_value: str hard_coded_value: str ...
0.650689
0.150559
import requests import json from django.shortcuts import render, redirect from django.http import HttpResponse from common.fetching import Fetcher as DataFetcher from common.tokening import TokenManager from .services.summary import ( BatchJobErrorSummary, BatchJobExecutingSummary, BatchJobWa...
daxboard/sysadmin/views.py
import requests import json from django.shortcuts import render, redirect from django.http import HttpResponse from common.fetching import Fetcher as DataFetcher from common.tokening import TokenManager from .services.summary import ( BatchJobErrorSummary, BatchJobExecutingSummary, BatchJobWa...
0.340376
0.043164
polls = { 'newsint2_baseline' : ('Interest in news and public affairs', 'Some people seem to follow what\'s going on in government and public affairs most of the time, whether there\'s an election going on or not. Others aren\'t that interested. Would you say you follow what\'s goin...
polls.py
polls = { 'newsint2_baseline' : ('Interest in news and public affairs', 'Some people seem to follow what\'s going on in government and public affairs most of the time, whether there\'s an election going on or not. Others aren\'t that interested. Would you say you follow what\'s goin...
0.272702
0.59884
import logging from apel.db.records.storage import StorageRecord from apel.db.records.group_attribute import GroupAttributeRecord from apel.common.datetime_utils import parse_timestamp from xml_parser import XMLParser, XMLParserException log = logging.getLogger(__name__) class StarParser(XMLParser): ''' Pa...
apel/db/loader/star_parser.py
import logging from apel.db.records.storage import StorageRecord from apel.db.records.group_attribute import GroupAttributeRecord from apel.common.datetime_utils import parse_timestamp from xml_parser import XMLParser, XMLParserException log = logging.getLogger(__name__) class StarParser(XMLParser): ''' Pa...
0.456894
0.232795
import sys import ast import vim import os.path import pkgutil class Pin: def __init__(self): self.cWORD = vim.eval("expand('<cWORD>')") self.cword = vim.eval("expand('<cword>')") self.cline = vim.eval("getline('.')") if self.cWORD in ["import", "from", "as"]: raise Va...
ftplugin/python/pin.py
import sys import ast import vim import os.path import pkgutil class Pin: def __init__(self): self.cWORD = vim.eval("expand('<cWORD>')") self.cword = vim.eval("expand('<cword>')") self.cline = vim.eval("getline('.')") if self.cWORD in ["import", "from", "as"]: raise Va...
0.41561
0.236197
from bio2bel_mirtarbase.manager import _build_entrez_map from bio2bel_mirtarbase.models import Evidence, HGNC, MIRBASE, Mirna, NCBIGENE, Species, Target from pybel import BELGraph from pybel.constants import FUNCTION, IDENTIFIER, NAME, NAMESPACE from pybel.dsl import BaseAbundance, mirna, rna from tests.constants impor...
tests/test_build_db.py
from bio2bel_mirtarbase.manager import _build_entrez_map from bio2bel_mirtarbase.models import Evidence, HGNC, MIRBASE, Mirna, NCBIGENE, Species, Target from pybel import BELGraph from pybel.constants import FUNCTION, IDENTIFIER, NAME, NAMESPACE from pybel.dsl import BaseAbundance, mirna, rna from tests.constants impor...
0.724675
0.430866
class Word2Sequence: UNK_TAG="<UNK>" PAD_TAG = "<PAD>" UNK = 0 PAD = 1 ''' 1.初始化dict词典,加入初始字符,count词频统计 ''' def __init__(self): self.dict={ self.UNK_TAG:self.UNK, self.PAD_TAG:self.PAD } self.counter={} ''' 2.接收单个wordlist,统计...
src/search/sort/word_to_sequence.py
class Word2Sequence: UNK_TAG="<UNK>" PAD_TAG = "<PAD>" UNK = 0 PAD = 1 ''' 1.初始化dict词典,加入初始字符,count词频统计 ''' def __init__(self): self.dict={ self.UNK_TAG:self.UNK, self.PAD_TAG:self.PAD } self.counter={} ''' 2.接收单个wordlist,统计...
0.182826
0.403449
from abc import abstractmethod from collections import OrderedDict from django.utils.translation import ugettext from datawinners.search.index_utils import es_unique_id_code_field_name, es_questionnaire_field_name from datawinners.search.submission_index_constants import SubmissionIndexConstants from datawinners.util...
datawinners/search/submission_headers.py
from abc import abstractmethod from collections import OrderedDict from django.utils.translation import ugettext from datawinners.search.index_utils import es_unique_id_code_field_name, es_questionnaire_field_name from datawinners.search.submission_index_constants import SubmissionIndexConstants from datawinners.util...
0.633637
0.131424
__all__ = ['test_endpoints', 'construct_method_to_params_dict', 'construct_request_type_filter', 'check_request_type_filter', 'determine_request_type_from_fields', 'determine_method_request_types', 'construct_method_to_params_map', 'construct_method_info_dict'] # Cell from tqdm import tqdm from ...
ElexonDataPortal/dev/clientprep.py
__all__ = ['test_endpoints', 'construct_method_to_params_dict', 'construct_request_type_filter', 'check_request_type_filter', 'determine_request_type_from_fields', 'determine_method_request_types', 'construct_method_to_params_map', 'construct_method_info_dict'] # Cell from tqdm import tqdm from ...
0.684475
0.428413
from unittest import TestCase import httpretty from click.testing import CliRunner from arcsecond import cli from arcsecond.api.error import ArcsecondError from arcsecond.config import config_file_clear_section from tests.utils import make_successful_login, mock_http_get, mock_http_post class DatasetsInOrganisation...
tests/cli/test_datasets_organisations.py
from unittest import TestCase import httpretty from click.testing import CliRunner from arcsecond import cli from arcsecond.api.error import ArcsecondError from arcsecond.config import config_file_clear_section from tests.utils import make_successful_login, mock_http_get, mock_http_post class DatasetsInOrganisation...
0.612773
0.414425
import os import qrcode from telegram.ext import Updater, CommandHandler, ConversationHandler, MessageHandler, Filters from telegram import ChatAction # Una variable para que el Bot se quede esperando el texto del QR INPUT_TEXT = 0 def start(update, context): update.message.reply_text('Bienvenido a el Bot de Prue...
bot.py
import os import qrcode from telegram.ext import Updater, CommandHandler, ConversationHandler, MessageHandler, Filters from telegram import ChatAction # Una variable para que el Bot se quede esperando el texto del QR INPUT_TEXT = 0 def start(update, context): update.message.reply_text('Bienvenido a el Bot de Prue...
0.332852
0.090173
import kernel from kernel.Interfaces.IStoreManager import IStoreManager import jsonpickle import os import numpy as np class JsonStoreManager(IStoreManager): def __init__(self): """ Constructor that initializes entity """ super().__init__() self.refresh() def refresh(...
backend/managers/JsonStoreManager.py
import kernel from kernel.Interfaces.IStoreManager import IStoreManager import jsonpickle import os import numpy as np class JsonStoreManager(IStoreManager): def __init__(self): """ Constructor that initializes entity """ super().__init__() self.refresh() def refresh(...
0.387922
0.097864
from optparse import OptionParser from struct import * import sys import os.path import time import binascii MAGIC = 0x27051956 IMG_NAME_LENGTH = 32 archs = {'invalid':0, 'alpha':1, 'arm':2, 'x86':3, 'ia64':4, 'm68k':12, 'microblaze':14, 'mips':5, 'mips64':6, 'nios':13, 'nios2':15, 'powerpc':7, 'p...
mkimage.py
from optparse import OptionParser from struct import * import sys import os.path import time import binascii MAGIC = 0x27051956 IMG_NAME_LENGTH = 32 archs = {'invalid':0, 'alpha':1, 'arm':2, 'x86':3, 'ia64':4, 'm68k':12, 'microblaze':14, 'mips':5, 'mips64':6, 'nios':13, 'nios2':15, 'powerpc':7, 'p...
0.214527
0.094803
from __future__ import unicode_literals from django.db import migrations, models import django.db.models.deletion class Migration(migrations.Migration): initial = True dependencies = [ ] operations = [ migrations.CreateModel( name='Menu', fields=[ ('...
treemenus/migrations/0001_initial.py
from __future__ import unicode_literals from django.db import migrations, models import django.db.models.deletion class Migration(migrations.Migration): initial = True dependencies = [ ] operations = [ migrations.CreateModel( name='Menu', fields=[ ('...
0.568655
0.114715
import contextlib import pathlib import tempfile import typing from foodx_devops_tools.pipeline_config import load_template_context @contextlib.contextmanager def context_files( content: typing.Dict[str, typing.Dict[str, str]] ) -> typing.Generator[typing.List[pathlib.Path], None, None]: dir_paths = set() ...
tests/ci/unit_tests/pipeline_config/test_template_context.py
import contextlib import pathlib import tempfile import typing from foodx_devops_tools.pipeline_config import load_template_context @contextlib.contextmanager def context_files( content: typing.Dict[str, typing.Dict[str, str]] ) -> typing.Generator[typing.List[pathlib.Path], None, None]: dir_paths = set() ...
0.566258
0.294665
from typing import Optional, Union from matchsticks.game_types import Move from matchsticks.utils import generate_allowed class Game(object): def __init__(self, num_layers: int = 4) -> None: """ A game of matchsticks. :param num_layers: The number of layers of (odd numbers of) matchsticks you want to ...
matchsticks/game.py
from typing import Optional, Union from matchsticks.game_types import Move from matchsticks.utils import generate_allowed class Game(object): def __init__(self, num_layers: int = 4) -> None: """ A game of matchsticks. :param num_layers: The number of layers of (odd numbers of) matchsticks you want to ...
0.837736
0.618723
import logging import sys import time from selenium import webdriver from selenium.webdriver.common.keys import Keys from selenium.webdriver.support.select import Select import settings import utils logging.info("starting teetime booking application") #calculate date / time values dates = utils.days_to_dates(setting...
teetime.py
import logging import sys import time from selenium import webdriver from selenium.webdriver.common.keys import Keys from selenium.webdriver.support.select import Select import settings import utils logging.info("starting teetime booking application") #calculate date / time values dates = utils.days_to_dates(setting...
0.09268
0.055285
import logging import numpy as np import onnx import os import tempfile import torch import unittest from fairseq import models from pytorch_translate import rnn # noqa from pytorch_translate.ensemble_export import ( DecoderBatchedStepEnsemble, DecoderStepEnsemble, EncoderEnsemble, BeamSearch ) from ...
pytorch_translate/test/test_onnx.py
import logging import numpy as np import onnx import os import tempfile import torch import unittest from fairseq import models from pytorch_translate import rnn # noqa from pytorch_translate.ensemble_export import ( DecoderBatchedStepEnsemble, DecoderStepEnsemble, EncoderEnsemble, BeamSearch ) from ...
0.466359
0.390592
from __future__ import print_function from amuse.units import units, nbody_system from amuse.datamodel import Particle from amuse.community.athena.interface import Athena from amuse.community.hermite.interface import Hermite from matplotlib import pyplot def hydro_grid_in_potential_well(mass=1 | units.MSun, length=1...
examples/simple/grid_potential.py
from __future__ import print_function from amuse.units import units, nbody_system from amuse.datamodel import Particle from amuse.community.athena.interface import Athena from amuse.community.hermite.interface import Hermite from matplotlib import pyplot def hydro_grid_in_potential_well(mass=1 | units.MSun, length=1...
0.861378
0.400867
from django.shortcuts import render from django.shortcuts import render_to_response from django.template import RequestContext from django.http import HttpResponse import googlemaps from vets.models import VetSpot gmaps = googlemaps.Client(key='AIzaSyA0tl-yTrvyi_9UESPKQ27Ny4L0ONoktj8') def index(request): return re...
petcare/vets/views.py
from django.shortcuts import render from django.shortcuts import render_to_response from django.template import RequestContext from django.http import HttpResponse import googlemaps from vets.models import VetSpot gmaps = googlemaps.Client(key='AIzaSyA0tl-yTrvyi_9UESPKQ27Ny4L0ONoktj8') def index(request): return re...
0.272896
0.125065
from bs4 import BeautifulSoup import time import requests from random import randint class bcolors: HEADER = '\033[95m' OKBLUE = '\033[94m' OKGREEN = '\033[92m' WARNING = '\033[93m' FAIL = '\033[91m' ENDC = '\033[0m' BOLD = '\033[1m' UNDERLINE = '\033[4m' def offlineMode(): try: fil...
learntype.py
from bs4 import BeautifulSoup import time import requests from random import randint class bcolors: HEADER = '\033[95m' OKBLUE = '\033[94m' OKGREEN = '\033[92m' WARNING = '\033[93m' FAIL = '\033[91m' ENDC = '\033[0m' BOLD = '\033[1m' UNDERLINE = '\033[4m' def offlineMode(): try: fil...
0.056986
0.076477
import importlib from pydashery import Widget def find_function(search_def): """ Dynamically load the function based on the search definition. :param str search_def: A string to tell us the function to load, e.g. module:funcname or module.path:class.staticmethod :raises Val...
backend/widgets/functionresult.py
import importlib from pydashery import Widget def find_function(search_def): """ Dynamically load the function based on the search definition. :param str search_def: A string to tell us the function to load, e.g. module:funcname or module.path:class.staticmethod :raises Val...
0.547222
0.395426
from enum import Enum from typing import Dict, List from robot.board import Board class PinMode(Enum): """A pin-mode for a pin on the servo board.""" INPUT = 'Z' INPUT_PULLUP = 'P' OUTPUT_HIGH = 'H' OUTPUT_LOW = 'L' class PinValue(Enum): """A value state for a pin on the servo board.""" ...
robot/servo.py
from enum import Enum from typing import Dict, List from robot.board import Board class PinMode(Enum): """A pin-mode for a pin on the servo board.""" INPUT = 'Z' INPUT_PULLUP = 'P' OUTPUT_HIGH = 'H' OUTPUT_LOW = 'L' class PinValue(Enum): """A value state for a pin on the servo board.""" ...
0.928198
0.432962
from django.contrib.auth.decorators import login_required from django.http import HttpResponse import datetime from openpyxl import Workbook import xlwt from dashboard.sheet_builder import NewSheetBuilder from dashboard.utils import extract_list_from_sheet, controlePlanosSheetFiller, cotachSheetFiller from .models imp...
projetos/reports.py
from django.contrib.auth.decorators import login_required from django.http import HttpResponse import datetime from openpyxl import Workbook import xlwt from dashboard.sheet_builder import NewSheetBuilder from dashboard.utils import extract_list_from_sheet, controlePlanosSheetFiller, cotachSheetFiller from .models imp...
0.36886
0.069007
from version import __version__ import re import os import unittest import logging def SlashContrl(strpath): ''' Solves windows - os.path normalize fail for i.e. tests\\tests, considers \t an escape sequence. :filters:: ['\\r', '\\t', '\\f', '\\a', '\\v']. :return: true path [str] ...
regt.py
from version import __version__ import re import os import unittest import logging def SlashContrl(strpath): ''' Solves windows - os.path normalize fail for i.e. tests\\tests, considers \t an escape sequence. :filters:: ['\\r', '\\t', '\\f', '\\a', '\\v']. :return: true path [str] ...
0.324235
0.099645
from __future__ import annotations from typing import TYPE_CHECKING, Union, Optional from enum import Enum from asyncio import Event from random import sample import discord from rtlib import sendableString from .music import Music, is_url if TYPE_CHECKING: from .__init__ import MusicCog class NotAddedReas...
cogs/music/player.py
from __future__ import annotations from typing import TYPE_CHECKING, Union, Optional from enum import Enum from asyncio import Event from random import sample import discord from rtlib import sendableString from .music import Music, is_url if TYPE_CHECKING: from .__init__ import MusicCog class NotAddedReas...
0.776962
0.169234
from __future__ import annotations import abc import numpy as np from pyrsistent.typing import PMap as PMapT from pyrsistent import pmap from typing import Union, Tuple, Any, FrozenSet, List from dataclasses import dataclass from functools import cached_property, cache from more_itertools import zip_equal as zip from...
src/feinsum/einsum.py
from __future__ import annotations import abc import numpy as np from pyrsistent.typing import PMap as PMapT from pyrsistent import pmap from typing import Union, Tuple, Any, FrozenSet, List from dataclasses import dataclass from functools import cached_property, cache from more_itertools import zip_equal as zip from...
0.780913
0.54952
import tensorflow as tf from typing import Tuple ##- def unet(input_size: Tuple[int,int,int] =(256, 256, 1)) -> tf.keras.Model: """Construct a basic U-Net model for baseline experiments. Params: input_size (tuple): image size to segment: (wodth, height, n_channels) Return: keras.model.Mo...
cpm/unet/basic.py
import tensorflow as tf from typing import Tuple ##- def unet(input_size: Tuple[int,int,int] =(256, 256, 1)) -> tf.keras.Model: """Construct a basic U-Net model for baseline experiments. Params: input_size (tuple): image size to segment: (wodth, height, n_channels) Return: keras.model.Mo...
0.940503
0.856272
import os from decouple import config import dj_database_url # Build paths inside the project like this: os.path.join(BASE_DIR, ...) BASE_DIR = os.path.dirname(os.path.dirname(os.path.abspath(__file__))) # Quick-start development settings - unsuitable for production # See https://docs.djangoproject.com/en/1.11/howt...
booky/settings.py
import os from decouple import config import dj_database_url # Build paths inside the project like this: os.path.join(BASE_DIR, ...) BASE_DIR = os.path.dirname(os.path.dirname(os.path.abspath(__file__))) # Quick-start development settings - unsuitable for production # See https://docs.djangoproject.com/en/1.11/howt...
0.376738
0.067886
import unittest from language_detector import detect_language from language_detector.languages import LANGUAGES class TestLanguageDetector(unittest.TestCase): def test_detect_language_spanish(self): text = """ <NAME> (Rosario, 24 de junio de 1987), conocido como <NAME>, es un fut...
tests/test_main.py
import unittest from language_detector import detect_language from language_detector.languages import LANGUAGES class TestLanguageDetector(unittest.TestCase): def test_detect_language_spanish(self): text = """ <NAME> (Rosario, 24 de junio de 1987), conocido como <NAME>, es un fut...
0.416441
0.511595
import torch import torch.nn as nn from torch.autograd import Function import torch.nn.functional as F import torch.nn.init as init from torch.autograd import Variable import math class NormalizeLayer(torch.nn.Module): """Standardize the channels of a batch of images by subtracting the dataset mean and divid...
RMC/models/resnet.py
import torch import torch.nn as nn from torch.autograd import Function import torch.nn.functional as F import torch.nn.init as init from torch.autograd import Variable import math class NormalizeLayer(torch.nn.Module): """Standardize the channels of a batch of images by subtracting the dataset mean and divid...
0.964111
0.73137
import datetime import webparser import puzzleraw import wordmatch class Puzzle: def __init__(self, date="", psid=""): now = datetime.datetime.now() if len(date) is 0: date = str(now.year) + "-" + str(now.month) + "-" + str(now.day) if len(psid) is 0: psid = "10000...
puzzle.py
import datetime import webparser import puzzleraw import wordmatch class Puzzle: def __init__(self, date="", psid=""): now = datetime.datetime.now() if len(date) is 0: date = str(now.year) + "-" + str(now.month) + "-" + str(now.day) if len(psid) is 0: psid = "10000...
0.4856
0.392977
import os import requests import time from tests.integration import TestsBase from tests.integration.test_file_storage import VALID_KML, NOT_WELL_FORMED_KML class TestVarnish(TestsBase): ''' Testing the Varnish 'security' configuration. As some settings are IP address dependant, we use an external HTTP...
tests/e2e/test_varnish.py
import os import requests import time from tests.integration import TestsBase from tests.integration.test_file_storage import VALID_KML, NOT_WELL_FORMED_KML class TestVarnish(TestsBase): ''' Testing the Varnish 'security' configuration. As some settings are IP address dependant, we use an external HTTP...
0.470737
0.174059
import re import json from collections import defaultdict from scrapy.spider import BaseSpider from scrapy.selector import HtmlXPathSelector from scrapy.http import Request, HtmlResponse, FormRequest from scrapy.utils.response import get_base_url from scrapy.utils.url import urljoin_rfc from product_spiders.items imp...
portfolio/Python/scrapy/instrumart/transcat.py
import re import json from collections import defaultdict from scrapy.spider import BaseSpider from scrapy.selector import HtmlXPathSelector from scrapy.http import Request, HtmlResponse, FormRequest from scrapy.utils.response import get_base_url from scrapy.utils.url import urljoin_rfc from product_spiders.items imp...
0.275714
0.072472
import numpy as np from scipy import ndimage as nd from nilabels.tools.aux_methods.utils_nib import set_new_data def contour_from_array_at_label(im_arr, lab, thr=0.3, omit_axis=None, verbose=0): """ Get the contour of a single label :param im_arr: input array with segmentation :param lab: considered ...
nilabels/tools/detections/contours.py
import numpy as np from scipy import ndimage as nd from nilabels.tools.aux_methods.utils_nib import set_new_data def contour_from_array_at_label(im_arr, lab, thr=0.3, omit_axis=None, verbose=0): """ Get the contour of a single label :param im_arr: input array with segmentation :param lab: considered ...
0.870556
0.799873
import ast import requests import configparser from flask import Flask, request, jsonify, render_template from flask import Flask, request from flask_cors import CORS, cross_origin app = Flask(__name__) CORS(app) a = 5.0 b = 5.0 c = 5.0 d = 5.0 e = 5.0 f = 5.0 g = 5.0 h = 5.0 i = 5.0 j = 5.0 k = 5.0 l = 5.0 m = 5.0 ...
main.py
import ast import requests import configparser from flask import Flask, request, jsonify, render_template from flask import Flask, request from flask_cors import CORS, cross_origin app = Flask(__name__) CORS(app) a = 5.0 b = 5.0 c = 5.0 d = 5.0 e = 5.0 f = 5.0 g = 5.0 h = 5.0 i = 5.0 j = 5.0 k = 5.0 l = 5.0 m = 5.0 ...
0.095941
0.097648
import lasagne import theano import lasagne.layers as L import theano.tensor as T import numpy as np import sys import time from deep_dialog import dialog_config from collections import Counter, defaultdict, deque import random import cPickle as pkl EPS = 1e-10 def categorical_sample(probs, mode='sample'): if ...
deep_dialog/agents/agent_lu_rl.py
import lasagne import theano import lasagne.layers as L import theano.tensor as T import numpy as np import sys import time from deep_dialog import dialog_config from collections import Counter, defaultdict, deque import random import cPickle as pkl EPS = 1e-10 def categorical_sample(probs, mode='sample'): if ...
0.257485
0.213992
"""Low-level, core functionality for DayDream""" __all__ = ['DayDreamError', 'Reference', 'Aggregator'] from copy import copy, deepcopy from functools import reduce from operator import add from typing import Any, AbstractSet, Set, Optional, Union class DayDreamError(Exception): """Error for package-specific is...
defn/core.py
"""Low-level, core functionality for DayDream""" __all__ = ['DayDreamError', 'Reference', 'Aggregator'] from copy import copy, deepcopy from functools import reduce from operator import add from typing import Any, AbstractSet, Set, Optional, Union class DayDreamError(Exception): """Error for package-specific is...
0.89785
0.333693
import typing from .error import fatalError, warnOrError class Named: def __init__( self, name: str, context: "Named" = None, private: bool = False, inner: bool = False ): self._name: str = name sep = "$" if inner else "." self._longname: str = ( f"{context.longnam...
bareAST/bare/scope.py
import typing from .error import fatalError, warnOrError class Named: def __init__( self, name: str, context: "Named" = None, private: bool = False, inner: bool = False ): self._name: str = name sep = "$" if inner else "." self._longname: str = ( f"{context.longnam...
0.635109
0.19789
import calc_postion import datetime import backend import json import io from baselib import error_print from flask import Flask, render_template, make_response from flask import request from flask_restful import reqparse, abort, Api, Resource app = Flask(__name__) api_loader = Api(app) parser = reqparse.Request...
gpsmap/work_app.py
import calc_postion import datetime import backend import json import io from baselib import error_print from flask import Flask, render_template, make_response from flask import request from flask_restful import reqparse, abort, Api, Resource app = Flask(__name__) api_loader = Api(app) parser = reqparse.Request...
0.243642
0.143638
from functools import partial import time import os import sys import threading import resotolib.proc from typing import List, Dict from .config import add_config from resotolib.config import Config from resotolib.logger import log, setup_logger, add_args as logging_add_args from resotolib.jwt import add_args as jwt_ad...
resotoworker/resotoworker/__main__.py
from functools import partial import time import os import sys import threading import resotolib.proc from typing import List, Dict from .config import add_config from resotolib.config import Config from resotolib.logger import log, setup_logger, add_args as logging_add_args from resotolib.jwt import add_args as jwt_ad...
0.405802
0.08882
import numpy as np class OneHiddenLayerNN: """ @brief: One hidden layer neural network with batch gradient descent. Currently supporting only relu, tanh and sigmoid activation functions. """ def __init__(self, number_of_neurons, batch_size = 20, hidden_activation='relu', ...
one_hidden_layer_nn.py
import numpy as np class OneHiddenLayerNN: """ @brief: One hidden layer neural network with batch gradient descent. Currently supporting only relu, tanh and sigmoid activation functions. """ def __init__(self, number_of_neurons, batch_size = 20, hidden_activation='relu', ...
0.883513
0.687918
import time import os import psycopg2 import csv import pandas as pd import re import tweepy import json from datetime import timedelta from datetime import datetime from psycopg2.extensions import ISOLATION_LEVEL_AUTOCOMMIT from collections import defaultdict def twitter_str_to_dt(dt_str): retur...
twitter2sql/core/util.py
import time import os import psycopg2 import csv import pandas as pd import re import tweepy import json from datetime import timedelta from datetime import datetime from psycopg2.extensions import ISOLATION_LEVEL_AUTOCOMMIT from collections import defaultdict def twitter_str_to_dt(dt_str): retur...
0.299617
0.059811
from fastapi import HTTPException from iso639 import languages import pytest from textblob import TextBlob from app.internal.translation import ( _detect_text_language, _get_language_code, _get_user_language, translate_text, translate_text_for_user ) TEXT = [ ("Привет мой друг", "english", "russian"), ...
tests/test_translation.py
from fastapi import HTTPException from iso639 import languages import pytest from textblob import TextBlob from app.internal.translation import ( _detect_text_language, _get_language_code, _get_user_language, translate_text, translate_text_for_user ) TEXT = [ ("Привет мой друг", "english", "russian"), ...
0.503418
0.333246
import json import os import copy from Evaluate import cocoTools sourceJsonPath = './rainSnowGt.json' destDir = '' with open('./splitSequenceTranslator.json') as f: splitSequenceTranslator = json.load(f) # List rain removal methods here methods = ['baseline', 'Fu2017', 'GargNayar/Median', ...
InstanceSegmentation/copyJsonForRainSnow.py
import json import os import copy from Evaluate import cocoTools sourceJsonPath = './rainSnowGt.json' destDir = '' with open('./splitSequenceTranslator.json') as f: splitSequenceTranslator = json.load(f) # List rain removal methods here methods = ['baseline', 'Fu2017', 'GargNayar/Median', ...
0.250271
0.17849
import abc import spar_python.query_generation.query_schema as qs """ This class represents the vertical integration of creating aggregators for queries, refining the queries within the batch, and writing the selected queries and their results to the results database within one object. """ class QueryBatch(object):...
spar_python/query_generation/BOQs/query_batch.py
import abc import spar_python.query_generation.query_schema as qs """ This class represents the vertical integration of creating aggregators for queries, refining the queries within the batch, and writing the selected queries and their results to the results database within one object. """ class QueryBatch(object):...
0.740456
0.403596
from sentiment_analysis import SentiStrength from question_analysis.post import Post import json import os class FeatureAnalysis: def __init__(self,request={},config_file="config_question_analysis.json"): in_file=open(os.path.dirname(os.path.abspath(__file__))+'/'+config_file,"r") self.__config=json.loads(in_fil...
src/question_analysis/feature_analysis.py
from sentiment_analysis import SentiStrength from question_analysis.post import Post import json import os class FeatureAnalysis: def __init__(self,request={},config_file="config_question_analysis.json"): in_file=open(os.path.dirname(os.path.abspath(__file__))+'/'+config_file,"r") self.__config=json.loads(in_fil...
0.174762
0.132374
import os from india_wris.base import WaterQualityBase DATASET_NAME = 'India_WRIS_Surface' ## Defining MCF and TMCF template nodes SOLUTE_MCF_NODES = """Node: dcid:Concentration_{variable}_BodyOfWater_SurfaceWater name: Concentration of {variable}, SurfaceWater typeOf: dcs:StatisticalVariable populationType: dcs:Bo...
scripts/india_wris/India_WRIS_Surface/preprocess.py
import os from india_wris.base import WaterQualityBase DATASET_NAME = 'India_WRIS_Surface' ## Defining MCF and TMCF template nodes SOLUTE_MCF_NODES = """Node: dcid:Concentration_{variable}_BodyOfWater_SurfaceWater name: Concentration of {variable}, SurfaceWater typeOf: dcs:StatisticalVariable populationType: dcs:Bo...
0.40592
0.418697
set_name(0x8007B9C0, "GetTpY__FUs", SN_NOWARN) set_name(0x8007B9DC, "GetTpX__FUs", SN_NOWARN) set_name(0x8007B9E8, "Remove96__Fv", SN_NOWARN) set_name(0x8007BA20, "AppMain", SN_NOWARN) set_name(0x8007BAC0, "MAIN_RestartGameTask__Fv", SN_NOWARN) set_name(0x8007BAEC, "GameTask__FP4TASK", SN_NOWARN) set_name(0x8007BBD4, "...
psx/_dump_/35/_dump_ida_/make_psx.py
set_name(0x8007B9C0, "GetTpY__FUs", SN_NOWARN) set_name(0x8007B9DC, "GetTpX__FUs", SN_NOWARN) set_name(0x8007B9E8, "Remove96__Fv", SN_NOWARN) set_name(0x8007BA20, "AppMain", SN_NOWARN) set_name(0x8007BAC0, "MAIN_RestartGameTask__Fv", SN_NOWARN) set_name(0x8007BAEC, "GameTask__FP4TASK", SN_NOWARN) set_name(0x8007BBD4, "...
0.16175
0.060891
import sys import dlib import cv2 import os import argparse import largest_face_detector import copy Images_Folder = 'train/personB' OutFace_Folder = 'train/personB_face/' Images_Path = os.path.join(os.path.realpath('.'), Images_Folder) Out_Path = os.path.join(os.path.realpath('.'), OutFace_Folder) pictures = os.li...
Ref/deepfake-pytorch/crop_face.py
import sys import dlib import cv2 import os import argparse import largest_face_detector import copy Images_Folder = 'train/personB' OutFace_Folder = 'train/personB_face/' Images_Path = os.path.join(os.path.realpath('.'), Images_Folder) Out_Path = os.path.join(os.path.realpath('.'), OutFace_Folder) pictures = os.li...
0.188026
0.136464
import unittest from kubedriver.kubeobjects.names import NameHelper class TestNameHelper(unittest.TestCase): def setUp(self): self.helper = NameHelper() def test_is_valid_subdomain_name_allows_lowercase(self): valid, reason = self.helper.is_valid_subdomain_name('testing') self.assertI...
tests/unit/kubeobjects/test_names.py
import unittest from kubedriver.kubeobjects.names import NameHelper class TestNameHelper(unittest.TestCase): def setUp(self): self.helper = NameHelper() def test_is_valid_subdomain_name_allows_lowercase(self): valid, reason = self.helper.is_valid_subdomain_name('testing') self.assertI...
0.683525
0.501526
# Description: # This tool helps you to find hack attempts # within webserver log files (e.g. Apache2 access logs). # Features: # - Error handling # - Scan a log file for four different attack types # - Display a short scan report # - Write scan results to a new log file # - Easy to use (everything is simple and auto...
machine-learning-gists/a25a81cdaf63c90d0c08cb466a0371b8f9273d00/snippet.py
# Description: # This tool helps you to find hack attempts # within webserver log files (e.g. Apache2 access logs). # Features: # - Error handling # - Scan a log file for four different attack types # - Display a short scan report # - Write scan results to a new log file # - Easy to use (everything is simple and auto...
0.46223
0.197541
import pytest import pyeventdispatcher from pyeventdispatcher import ( EventDispatcher, Event, EventDispatcherException, EventSubscriber, listen, ) from pyeventdispatcher.event_dispatcher import ( MemoryRegistry, register_global_listener, register_event_subscribers, ) class TestRegist...
test/test_pyeventdispatcher.py
import pytest import pyeventdispatcher from pyeventdispatcher import ( EventDispatcher, Event, EventDispatcherException, EventSubscriber, listen, ) from pyeventdispatcher.event_dispatcher import ( MemoryRegistry, register_global_listener, register_event_subscribers, ) class TestRegist...
0.530723
0.413536
import base64 import subprocess import json import sys import logging import requests from requests.adapters import HTTPAdapter from requests.packages.urllib3.util.retry import Retry from urllib.parse import urljoin from kubernetes import client, config class APIRequest(object): """ Example use: api...
goss-testing/scripts/python/check_ncn_uan_ip_dns.py
import base64 import subprocess import json import sys import logging import requests from requests.adapters import HTTPAdapter from requests.packages.urllib3.util.retry import Retry from urllib.parse import urljoin from kubernetes import client, config class APIRequest(object): """ Example use: api...
0.126961
0.048858
import smbus import time HTS221_ADDR = 0x5F HTS221_WHO_AM_I = 0x0F HTS221_ID = 0xBC HTS221_AV_CONF = 0x10 HTS221_CTRL_REG1 = 0x20 # Humidity HTS221_H0_rH_x2 = 0x30 HTS221_H1_rH_x2 = 0x31 HTS221_H0_T0_OUT_L = 0x36 HTS221_H0_T0_OUT_H = 0x37 HTS221_H1_T0_OUT_L = 0x3A HTS221_H1_T0_OUT_H = 0x3B HTS221_H_OUT_L = 0x28 HTS22...
CZNBIoT/HTS221.py
import smbus import time HTS221_ADDR = 0x5F HTS221_WHO_AM_I = 0x0F HTS221_ID = 0xBC HTS221_AV_CONF = 0x10 HTS221_CTRL_REG1 = 0x20 # Humidity HTS221_H0_rH_x2 = 0x30 HTS221_H1_rH_x2 = 0x31 HTS221_H0_T0_OUT_L = 0x36 HTS221_H0_T0_OUT_H = 0x37 HTS221_H1_T0_OUT_L = 0x3A HTS221_H1_T0_OUT_H = 0x3B HTS221_H_OUT_L = 0x28 HTS22...
0.379608
0.240017
import copy class System: pass class LinearSystem(System): def __init__(self, equations): self.equations = equations def __str__(self): eqsStr = [] greaterEqualSignPos = 0 for eq in self.equations: eqStr = str(eq) equalSignPos = eqStr.find('=') if equalSignPos > greaterEqualSignPos: greate...
main.py
import copy class System: pass class LinearSystem(System): def __init__(self, equations): self.equations = equations def __str__(self): eqsStr = [] greaterEqualSignPos = 0 for eq in self.equations: eqStr = str(eq) equalSignPos = eqStr.find('=') if equalSignPos > greaterEqualSignPos: greate...
0.425605
0.305089
import sys sys.path.append('/home/george2/Raise/ProgramRepair/CodeSeer/projects/src/main/python') from CodeJam.Y14R5P1.Grzesiu.A import * def func_0c1046dd31d944ea823eab991f0e63dc(totalsum, b, a): kA = totalsum[a - 1] if a > 0 else 0 kB = totalsum[b] - kA return kA def func_422fc4f073a5491ca907af45698930...
projects/src/main/python/CodeJam/Y14R5P1/Grzesiu/generated_py_84e0dc4f0d374ae0ba338a870469e2f9.py
import sys sys.path.append('/home/george2/Raise/ProgramRepair/CodeSeer/projects/src/main/python') from CodeJam.Y14R5P1.Grzesiu.A import * def func_0c1046dd31d944ea823eab991f0e63dc(totalsum, b, a): kA = totalsum[a - 1] if a > 0 else 0 kB = totalsum[b] - kA return kA def func_422fc4f073a5491ca907af45698930...
0.205535
0.34798
from __future__ import absolute_import from __future__ import print_function import sys import getopt import os import csv from six.moves import range from six.moves import zip PROG = os.path.basename(sys.argv[0]) def main(args): opts, args = getopt.getopt(args, "f:s:hk:H") func = None sep = "," lamb...
data_filters/src/filter.py
from __future__ import absolute_import from __future__ import print_function import sys import getopt import os import csv from six.moves import range from six.moves import zip PROG = os.path.basename(sys.argv[0]) def main(args): opts, args = getopt.getopt(args, "f:s:hk:H") func = None sep = "," lamb...
0.308086
0.142411
from src.params.NeuronTypes import * class ParamsIzhikevich: """ This class contains Izhikevich parameters. :param peak_potential: potential at which spikes terminate. :type peak_potential: float :param alpha_E: describes the timescale of recovery for excitatory neurons. :type alpha_E: float...
src/params/ParamsIzhikevich.py
from src.params.NeuronTypes import * class ParamsIzhikevich: """ This class contains Izhikevich parameters. :param peak_potential: potential at which spikes terminate. :type peak_potential: float :param alpha_E: describes the timescale of recovery for excitatory neurons. :type alpha_E: float...
0.9231
0.812867
class Filter: exactKeyFilter = ['name', 'ele', 'comment', 'image', 'symbol', 'deanery', 'jel', 'rating', 'school:FR', 'alt', 'is_in', 'url', 'web', 'wikipedia', 'email', 'converted_by', 'phone', 'opening_hours', 'date', 'time', 'collection_times', 'website', 'colour', 'f...
OSMTagFinder/thesaurus/filter.py
class Filter: exactKeyFilter = ['name', 'ele', 'comment', 'image', 'symbol', 'deanery', 'jel', 'rating', 'school:FR', 'alt', 'is_in', 'url', 'web', 'wikipedia', 'email', 'converted_by', 'phone', 'opening_hours', 'date', 'time', 'collection_times', 'website', 'colour', 'f...
0.494385
0.433082
import os import re import sys import math import time import jieba import torch import config # 常规参数设置 import random import argparse import numpy as np import pandas as pd import torch.nn as nn from torch import optim import torch.nn.functional as F from torch.autograd import Variable from preprocessin...
gru_seq2seq/evaluate.py
import os import re import sys import math import time import jieba import torch import config # 常规参数设置 import random import argparse import numpy as np import pandas as pd import torch.nn as nn from torch import optim import torch.nn.functional as F from torch.autograd import Variable from preprocessin...
0.145813
0.060363
import numpy as np from qlazy import QState Hamming = np.array([[0,1,1,1,1,0,0], [1,0,1,1,0,1,0], [1,1,0,1,0,0,1]]) Hamming_T = Hamming.T Steane_0 = ['0000000', '1101001', '1011010', '0110011', '0111100', '1010101', '1100110', '0001111'] Steane_1 = ['1111111', '0010110', '0100101', '1001100', ...
example/py/ErrorCorrection/steane_code_0.py
import numpy as np from qlazy import QState Hamming = np.array([[0,1,1,1,1,0,0], [1,0,1,1,0,1,0], [1,1,0,1,0,0,1]]) Hamming_T = Hamming.T Steane_0 = ['0000000', '1101001', '1011010', '0110011', '0111100', '1010101', '1100110', '0001111'] Steane_1 = ['1111111', '0010110', '0100101', '1001100', ...
0.50293
0.459925
import sys from xml.sax.saxutils import escape USAGE_TEXT = """ usage: python3 Ch02Ex04.py [maxwidth=int] [format=str] <infile.csv> <outfile.html> maxwidth is an optional integer; if specified, it sets the maximum number of characters that can be output for string fields, otherwise a default of 100 characters is used...
Chapter 02/Ch02Ex04.py
import sys from xml.sax.saxutils import escape USAGE_TEXT = """ usage: python3 Ch02Ex04.py [maxwidth=int] [format=str] <infile.csv> <outfile.html> maxwidth is an optional integer; if specified, it sets the maximum number of characters that can be output for string fields, otherwise a default of 100 characters is used...
0.260672
0.139279
"""Take usage data .csv file from SCE, parse it, and analyze it""" import sys import os import re import datetime from power_plotting import PowerPlotting def print_usage(error_string=""): """Print usage in the case of bad inputs""" script_name = os.path.basename(__file__) print "==========================...
power_parser.py
"""Take usage data .csv file from SCE, parse it, and analyze it""" import sys import os import re import datetime from power_plotting import PowerPlotting def print_usage(error_string=""): """Print usage in the case of bad inputs""" script_name = os.path.basename(__file__) print "==========================...
0.369884
0.38027
import random from pathlib import Path import numpy as np import tensorflow as tf from models.PositiveLearningElkan.pu_learning import PULogisticRegressionSK from models.baselines import LogisticRegressionSK from models.recurrent.basic_recurrent import BasicRecurrent from project_paths import ProjectPaths from run_fi...
run_files/random_sample_train.py
import random from pathlib import Path import numpy as np import tensorflow as tf from models.PositiveLearningElkan.pu_learning import PULogisticRegressionSK from models.baselines import LogisticRegressionSK from models.recurrent.basic_recurrent import BasicRecurrent from project_paths import ProjectPaths from run_fi...
0.563618
0.268538
import scrapy from alleco.objects.official import Official class braddock_b(scrapy.Spider): name = "braddock_b" muniName = "BRADDOCK" muniType = "BOROUGH" complete = True def start_requests(self): urls = ['http://www.braddockborough.com/council/', 'http://www.braddockborough.com/staff', 'ht...
alleco/spiders/braddock_b.py
import scrapy from alleco.objects.official import Official class braddock_b(scrapy.Spider): name = "braddock_b" muniName = "BRADDOCK" muniType = "BOROUGH" complete = True def start_requests(self): urls = ['http://www.braddockborough.com/council/', 'http://www.braddockborough.com/staff', 'ht...
0.064831
0.140926
#SILENCING THE FALSE POSITIVE WARNINGS import warnings warnings.simplefilter('always') with warnings.catch_warnings(): warnings.filterwarnings('ignore', category=pd.core.common.SettingWithCopyWarning) #IMPORTING DEPENDENCIES import tensorflow as tf import pandas as pd import numpy as np from tensorflow.keras.prepr...
.py files/decisiontreeclassifier_unpruned(fake_news_detection).py
#SILENCING THE FALSE POSITIVE WARNINGS import warnings warnings.simplefilter('always') with warnings.catch_warnings(): warnings.filterwarnings('ignore', category=pd.core.common.SettingWithCopyWarning) #IMPORTING DEPENDENCIES import tensorflow as tf import pandas as pd import numpy as np from tensorflow.keras.prepr...
0.357119
0.260754
import base64 import rapidjson import logging import asyncio # redis pool import aioredis from aiohttp import web, hdrs from .base import BaseAuthBackend from navigator.exceptions import ( NavException, UserDoesntExists, InvalidAuth ) from datetime import datetime, timedelta from navigator.conf import ( ...
navigator/auth/backends/django.py
import base64 import rapidjson import logging import asyncio # redis pool import aioredis from aiohttp import web, hdrs from .base import BaseAuthBackend from navigator.exceptions import ( NavException, UserDoesntExists, InvalidAuth ) from datetime import datetime, timedelta from navigator.conf import ( ...
0.475605
0.080683
import os import json import iso8601 from hashlib import sha256 import requests from requests.compat import urlencode PYBOSSA_API_KEY = os.environ.get("PYBOSSA_API_KEY") SCISTARTER_API_KEY = os.environ.get("SCISTARTER_API_KEY") def retrieve_email(user_id): """ Input: A user_id mapping to some User Profile...
vdashboard/scistarter.py
import os import json import iso8601 from hashlib import sha256 import requests from requests.compat import urlencode PYBOSSA_API_KEY = os.environ.get("PYBOSSA_API_KEY") SCISTARTER_API_KEY = os.environ.get("SCISTARTER_API_KEY") def retrieve_email(user_id): """ Input: A user_id mapping to some User Profile...
0.588889
0.171651
import django.db.models.deletion from django.conf import settings from django.db import migrations from django.db import models class Migration(migrations.Migration): dependencies = [ migrations.swappable_dependency(settings.AUTH_USER_MODEL), ("contenttypes", "0002_remove_content_type_name"), ...
checkerapp/migrations/0012_alertplugin_alertpluginuserdata.py
import django.db.models.deletion from django.conf import settings from django.db import migrations from django.db import models class Migration(migrations.Migration): dependencies = [ migrations.swappable_dependency(settings.AUTH_USER_MODEL), ("contenttypes", "0002_remove_content_type_name"), ...
0.426799
0.124266
import datetime import json import logging from decimal import Decimal from typing import Generator, Tuple import boto3 from botocore.config import Config from igata import settings logger = logging.getLogger("cliexecutor") TEN_SECONDS = 10 config = Config(connect_timeout=TEN_SECONDS, retries={"max_attempts": 5}) D...
igata/handlers/aws/output/utils.py
import datetime import json import logging from decimal import Decimal from typing import Generator, Tuple import boto3 from botocore.config import Config from igata import settings logger = logging.getLogger("cliexecutor") TEN_SECONDS = 10 config = Config(connect_timeout=TEN_SECONDS, retries={"max_attempts": 5}) D...
0.658966
0.291731
import json import requests from config import Config, CAR0, CAR1, CAR2, CAR3 #pylint: disable=unused-import class Coordinator: """ Provides all communication between the Starting Gate and the Race Coordinator The local race controller communicates with the Race Coordinator at via 4 interactions: *...
StartingGate/coordinator.py
import json import requests from config import Config, CAR0, CAR1, CAR2, CAR3 #pylint: disable=unused-import class Coordinator: """ Provides all communication between the Starting Gate and the Race Coordinator The local race controller communicates with the Race Coordinator at via 4 interactions: *...
0.606265
0.294262
from django.conf import settings from django.contrib.auth import get_backends from django.utils.functional import cached_property from social_core.backends.base import BaseAuth class BackendMetaMetaclass(type): def __new__(mcs, name, bases, attrs): cls = type.__new__(mcs, name, bases, attrs) if cl...
forsta_auth/backend_meta.py
from django.conf import settings from django.contrib.auth import get_backends from django.utils.functional import cached_property from social_core.backends.base import BaseAuth class BackendMetaMetaclass(type): def __new__(mcs, name, bases, attrs): cls = type.__new__(mcs, name, bases, attrs) if cl...
0.554832
0.070977
import pandas as pd TIME = { 'a': 3, 'b': 5, 'c': 2, 'd': 4, 'e': 3, 'f': 1, 'g': 4, 'h': 3, 'i': 3, 'j': 2, 'k': 5 } # Функция формирования таблицы. def create_table(data_, id_): with pd.option_context('display.width', None): table = pd.DataFrame(data_, index...
lab7/main.py
import pandas as pd TIME = { 'a': 3, 'b': 5, 'c': 2, 'd': 4, 'e': 3, 'f': 1, 'g': 4, 'h': 3, 'i': 3, 'j': 2, 'k': 5 } # Функция формирования таблицы. def create_table(data_, id_): with pd.option_context('display.width', None): table = pd.DataFrame(data_, index...
0.224565
0.318684
# Manage DNS Records # Functions: # - Add # - Update # - Delete # Usage: # ./dns_records.py <zone_id> <command> [name] [type] [content] [ttl] [record_id] # WGM CloudFlare integration import cf # WGM DB Integration import wgm_db # Other dependencies import sys import psycopg2.extras def update_dns_record(zone_id,rec...
wgm/cli/dns/dns_records.py
# Manage DNS Records # Functions: # - Add # - Update # - Delete # Usage: # ./dns_records.py <zone_id> <command> [name] [type] [content] [ttl] [record_id] # WGM CloudFlare integration import cf # WGM DB Integration import wgm_db # Other dependencies import sys import psycopg2.extras def update_dns_record(zone_id,rec...
0.106058
0.089694
import math import components_3d as com import esper import glm import pygame import pygame.locals import resources as res def add_systems_1_to_world(world): world.add_processor(GameControlSystem()) def add_systems_2_to_world(world): world.add_processor(ThirdPersonCameraSystem()) world.add_processor(Fr...
src/control_system.py
import math import components_3d as com import esper import glm import pygame import pygame.locals import resources as res def add_systems_1_to_world(world): world.add_processor(GameControlSystem()) def add_systems_2_to_world(world): world.add_processor(ThirdPersonCameraSystem()) world.add_processor(Fr...
0.383295
0.272917
from unittest import TestCase from exceptions import InvalidCardSize, InvalidPlayerMove from game.game_state_machine import GameStateMachine from game.game_variant import GameVariantGrand from game.state.game_state_bid import GameStateBid, BidStateCallTurn, BidCallAction, BidStateResponseTurn, \ BidAcceptAction, B...
tests/game/state/test_game_state_bid.py
from unittest import TestCase from exceptions import InvalidCardSize, InvalidPlayerMove from game.game_state_machine import GameStateMachine from game.game_variant import GameVariantGrand from game.state.game_state_bid import GameStateBid, BidStateCallTurn, BidCallAction, BidStateResponseTurn, \ BidAcceptAction, B...
0.400515
0.308529
from __future__ import unicode_literals from rest_framework.views import APIView from rest_framework.parsers import JSONParser from rest_framework.response import Response from rest_framework import status from credocommon.exceptions import RegistrationException from credoapiv2.authentication import DRFTokenAuthenti...
credoapiv2/views.py
from __future__ import unicode_literals from rest_framework.views import APIView from rest_framework.parsers import JSONParser from rest_framework.response import Response from rest_framework import status from credocommon.exceptions import RegistrationException from credoapiv2.authentication import DRFTokenAuthenti...
0.500244
0.088583
from __future__ import absolute_import import sys from esky.util import lazy_import @lazy_import def os(): import os return os @lazy_import def tempfile(): import tempfile return tempfile @lazy_import def threading(): try: import threading except ImportError: threading = No...
esky/slaveproc.py
from __future__ import absolute_import import sys from esky.util import lazy_import @lazy_import def os(): import os return os @lazy_import def tempfile(): import tempfile return tempfile @lazy_import def threading(): try: import threading except ImportError: threading = No...
0.382949
0.124612
import random from typing import Type, Union, Dict, Any, List, Tuple # 3rd party imports import streamlit as st import numpy as np import pandas as pd import altair as alt import seaborn as sns from wordcloud import WordCloud from yellowbrick.classifier import classification_report from sklearn.model_selection import ...
pywebconf_st.py
import random from typing import Type, Union, Dict, Any, List, Tuple # 3rd party imports import streamlit as st import numpy as np import pandas as pd import altair as alt import seaborn as sns from wordcloud import WordCloud from yellowbrick.classifier import classification_report from sklearn.model_selection import ...
0.847211
0.379608
import os import shutil import math import time import menpo.io as mio import menpo3d.io as m3io import numpy as np from pathlib import Path from functools import partial # deepmachine import keras import tensorflow as tf import deepmachine as dm # flag definitions from deepmachine.flags import FLAGS def main(): ...
deepmachine/contrib/training/DenseRegFace.py
import os import shutil import math import time import menpo.io as mio import menpo3d.io as m3io import numpy as np from pathlib import Path from functools import partial # deepmachine import keras import tensorflow as tf import deepmachine as dm # flag definitions from deepmachine.flags import FLAGS def main(): ...
0.537284
0.183246
import logging import os.path import subprocess import tarfile import tempfile from dbnd import output, task from dbnd._core.constants import CloudType from dbnd._core.errors import DatabandRuntimeError from dbnd._core.utils.timezone import utcnow from targets.types import Path logger = logging.getLogger(__name__) ...
modules/dbnd/src/dbnd/tasks/basics/export.py
import logging import os.path import subprocess import tarfile import tempfile from dbnd import output, task from dbnd._core.constants import CloudType from dbnd._core.errors import DatabandRuntimeError from dbnd._core.utils.timezone import utcnow from targets.types import Path logger = logging.getLogger(__name__) ...
0.26218
0.069668
import cv2 from image_morphing.np import np, GPU from image_morphing.utils import load_points, resize_v from image_morphing.render import render_animation from image_morphing.optimize_v import adam from image_morphing.quadratic_motion_path import adam_w import os def image_morphing(img0_path, img1_path, p0_path, p1_pa...
image_morphing/morpher.py
import cv2 from image_morphing.np import np, GPU from image_morphing.utils import load_points, resize_v from image_morphing.render import render_animation from image_morphing.optimize_v import adam from image_morphing.quadratic_motion_path import adam_w import os def image_morphing(img0_path, img1_path, p0_path, p1_pa...
0.386532
0.24271
import os from pathlib import Path import albumentations as A import cv2 import matplotlib.pyplot as plt import torch from albumentations.pytorch import ToTensorV2 from ignite.contrib.handlers import ProgressBar from ignite.contrib.metrics import GpuInfo from ignite.engine import Events, create_supervised_evaluator, c...
unet/train.py
import os from pathlib import Path import albumentations as A import cv2 import matplotlib.pyplot as plt import torch from albumentations.pytorch import ToTensorV2 from ignite.contrib.handlers import ProgressBar from ignite.contrib.metrics import GpuInfo from ignite.engine import Events, create_supervised_evaluator, c...
0.782164
0.356587
import builtins import keyword import sys import textwrap from typing import Any, List, Optional, TextIO, Tuple import pydantic from . import utils def build_from_document(doc: dict) -> dict: return build_models(doc["schemas"]) def build_models(schemas: dict) -> dict: """Create schema models from an API s...
src/verydisco/schemas.py
import builtins import keyword import sys import textwrap from typing import Any, List, Optional, TextIO, Tuple import pydantic from . import utils def build_from_document(doc: dict) -> dict: return build_models(doc["schemas"]) def build_models(schemas: dict) -> dict: """Create schema models from an API s...
0.656328
0.241959
from __future__ import annotations from typing import Tuple, Union, Any, Optional from engine.threed.base.plane import AbstractPlane from engine.threed.base.vector import AbstractVector from engine.threed.base.point import AbstractPoint from engine.threed.base.line import AbstractLine from engine.threed.point import ...
engine/threed/plane.py
from __future__ import annotations from typing import Tuple, Union, Any, Optional from engine.threed.base.plane import AbstractPlane from engine.threed.base.vector import AbstractVector from engine.threed.base.point import AbstractPoint from engine.threed.base.line import AbstractLine from engine.threed.point import ...
0.968306
0.568655
import logging import pyarrow as pa import pyarrow.csv as pv import pyarrow.parquet as pq from dataset_builder.exceptions.exceptions import BuilderStepError logger = logging.getLogger() def _get_read_options(): return pv.ReadOptions( skip_rows=0, encoding="utf8", column_names=[ ...
dataset_builder/steps/dataset_converter.py
import logging import pyarrow as pa import pyarrow.csv as pv import pyarrow.parquet as pq from dataset_builder.exceptions.exceptions import BuilderStepError logger = logging.getLogger() def _get_read_options(): return pv.ReadOptions( skip_rows=0, encoding="utf8", column_names=[ ...
0.461502
0.213039
from ion_functions.data.perf.test_performance import PerformanceTestCase, a_deca from ion_functions.data import opt_functions as optfunc import numpy as np class TestOPTAAPerformance(PerformanceTestCase): def setUp(self): ### realistic values for ac-s data packets: n_wvl = 90 # number of wavelen...
ion_functions/data/perf/test_opt_performance.py
from ion_functions.data.perf.test_performance import PerformanceTestCase, a_deca from ion_functions.data import opt_functions as optfunc import numpy as np class TestOPTAAPerformance(PerformanceTestCase): def setUp(self): ### realistic values for ac-s data packets: n_wvl = 90 # number of wavelen...
0.498779
0.512693
import numpy as np import tensorflow as tf class ANN(object): def __init__(self, size, logPath): """ 创建一个神经网络 """ # 重置tensorflow的graph,确保神经网络可多次运行 tf.reset_default_graph() tf.set_random_seed(1908) self.logPath = logPath self.layerNum = len(size)...
ch12-ann/mlp.py
import numpy as np import tensorflow as tf class ANN(object): def __init__(self, size, logPath): """ 创建一个神经网络 """ # 重置tensorflow的graph,确保神经网络可多次运行 tf.reset_default_graph() tf.set_random_seed(1908) self.logPath = logPath self.layerNum = len(size)...
0.581065
0.549943
from sns_boomerang.common.items import sns_client, Job, Topic, JOB_TABLE from contextlib import contextmanager import pytest from unittest.mock import MagicMock from datetime import datetime def test_new_job(): job = Job('topic', 'payload', 123) assert job.id assert job.topic == 'topic' assert job.pay...
tests/test_item_job.py
from sns_boomerang.common.items import sns_client, Job, Topic, JOB_TABLE from contextlib import contextmanager import pytest from unittest.mock import MagicMock from datetime import datetime def test_new_job(): job = Job('topic', 'payload', 123) assert job.id assert job.topic == 'topic' assert job.pay...
0.520496
0.468122
__author__ = '<EMAIL> (<NAME>)' import logging from categories import test_set_base from categories import test_set_params _CATEGORY = 'reflow' class ReflowTest(test_set_base.TestBase): TESTS_URL_PATH = '/%s/test' % _CATEGORY def __init__(self, key, name, doc): test_set_base.TestBase.__init__( se...
categories/reflow/test_set.py
__author__ = '<EMAIL> (<NAME>)' import logging from categories import test_set_base from categories import test_set_params _CATEGORY = 'reflow' class ReflowTest(test_set_base.TestBase): TESTS_URL_PATH = '/%s/test' % _CATEGORY def __init__(self, key, name, doc): test_set_base.TestBase.__init__( se...
0.713931
0.411702
__version__ = "1.0" __author__ = "2-REC" import logging logger = logging.getLogger(__name__) from Qt.QtCore import Qt as qt from Qt.QtWidgets import ( QMessageBox, QTextEdit, QDialogButtonBox, QSizePolicy ) class ResizableMessageBox(QMessageBox): _max_width = 4096 _max_height = 2048 ...
resizable_messagebox.py
__version__ = "1.0" __author__ = "2-REC" import logging logger = logging.getLogger(__name__) from Qt.QtCore import Qt as qt from Qt.QtWidgets import ( QMessageBox, QTextEdit, QDialogButtonBox, QSizePolicy ) class ResizableMessageBox(QMessageBox): _max_width = 4096 _max_height = 2048 ...
0.337968
0.052038