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 moviepy.editor as mpy
import matplotlib.pyplot as plt
import numpy as np
import cv2, wave
import settings
# デバッグ用
import shutil, os
def get_music(id):
"""
音楽の長さが何秒か(浮動小数)と
フレーム数を返す関数
Parameter
---------
id : str
個人識別用uuid
Returns
-------
1.0 * music_frames / SAMPLI... | docker/opt/movie_create/movie_create.py | import moviepy.editor as mpy
import matplotlib.pyplot as plt
import numpy as np
import cv2, wave
import settings
# デバッグ用
import shutil, os
def get_music(id):
"""
音楽の長さが何秒か(浮動小数)と
フレーム数を返す関数
Parameter
---------
id : str
個人識別用uuid
Returns
-------
1.0 * music_frames / SAMPLI... | 0.444083 | 0.383526 |
import scrapy, logging
"""
https://www.klimaundenergiemodellregionen.at/modellregionen/liste-der-regionen/
"""
class GetcontactsSpider(scrapy.Spider):
name = 'getcontacts'
allowed_domains = ['www.klimaundenergiemodellregionen.at']
start_urls = ['https://www.klimaundenergiemodellregionen.at/modellregionen... | kem/kem/spiders/getcontacts.py | import scrapy, logging
"""
https://www.klimaundenergiemodellregionen.at/modellregionen/liste-der-regionen/
"""
class GetcontactsSpider(scrapy.Spider):
name = 'getcontacts'
allowed_domains = ['www.klimaundenergiemodellregionen.at']
start_urls = ['https://www.klimaundenergiemodellregionen.at/modellregionen... | 0.139133 | 0.078043 |
import json
from typing import Tuple
import librosa
import torch
from pororo.models.tts.hifigan.checkpoint import load_checkpoint
from pororo.models.tts.hifigan.model import Generator
from pororo.models.tts.synthesis import synthesize
from pororo.models.tts.tacotron.params import Params as tacotron_hp
from pororo.mod... | pororo/models/tts/synthesizer.py | import json
from typing import Tuple
import librosa
import torch
from pororo.models.tts.hifigan.checkpoint import load_checkpoint
from pororo.models.tts.hifigan.model import Generator
from pororo.models.tts.synthesis import synthesize
from pororo.models.tts.tacotron.params import Params as tacotron_hp
from pororo.mod... | 0.814791 | 0.168925 |
from datetime import datetime, date
from pathlib import Path
from typing import List
from typing import Optional
from pydantic import BaseModel, ValidationError
from pydantic import constr
from sqlalchemy import Column, Integer, String
from sqlalchemy.dialects.postgresql import ARRAY
from sqlalchemy.ext.declarative i... | pydantic_tutorial.py |
from datetime import datetime, date
from pathlib import Path
from typing import List
from typing import Optional
from pydantic import BaseModel, ValidationError
from pydantic import constr
from sqlalchemy import Column, Integer, String
from sqlalchemy.dialects.postgresql import ARRAY
from sqlalchemy.ext.declarative i... | 0.583797 | 0.407216 |
from itertools import izip_longest
outpath = "redd-test/"
dir = "redd-test/house_1/"
with open(dir+'channel_5_6.dat') as f3,\
open(dir+'channel_6_7.dat') as f4, open(dir+'channel_7_5.dat') as f5, open(dir+'channel_8_5.dat') as f6,\
open(dir+'channel_9_3.dat') as f7, open(dir+'channel_11_9.dat') as f8, open(d... | 2a.combfiles_wo_main.py | from itertools import izip_longest
outpath = "redd-test/"
dir = "redd-test/house_1/"
with open(dir+'channel_5_6.dat') as f3,\
open(dir+'channel_6_7.dat') as f4, open(dir+'channel_7_5.dat') as f5, open(dir+'channel_8_5.dat') as f6,\
open(dir+'channel_9_3.dat') as f7, open(dir+'channel_11_9.dat') as f8, open(d... | 0.114183 | 0.122418 |
from __future__ import print_function
import os.path
import pytest
from tool.tb_generate_tads import tbGenerateTADsTool
@pytest.mark.hic
def test_tb_generate_tads_frag_01():
"""
Test case to ensure that the BWA indexer works.
"""
resource_path = os.path.join(os.path.dirname(__file__), "data/")
r... | tests/test_tb_generate_tads.py | from __future__ import print_function
import os.path
import pytest
from tool.tb_generate_tads import tbGenerateTADsTool
@pytest.mark.hic
def test_tb_generate_tads_frag_01():
"""
Test case to ensure that the BWA indexer works.
"""
resource_path = os.path.join(os.path.dirname(__file__), "data/")
r... | 0.539226 | 0.378947 |
import os
import sys
import json
from optparse import OptionParser
from rdmc_base_classes import RdmcCommandBase, RdmcOptionParser
from rdmc_helper import ReturnCodes, InvalidCommandLineError, \
InvalidCommandLineErrorOPTS, UI, InvalidFileInputError, \
InvalidFileFormatt... | src/extensions/RAW COMMANDS/RawPatchCommand.py | import os
import sys
import json
from optparse import OptionParser
from rdmc_base_classes import RdmcCommandBase, RdmcOptionParser
from rdmc_helper import ReturnCodes, InvalidCommandLineError, \
InvalidCommandLineErrorOPTS, UI, InvalidFileInputError, \
InvalidFileFormatt... | 0.314998 | 0.060613 |
class Room:
'''
Define initial values of atributes.
Assign text representation of class.
'''
def __init__(self, name, coordinates, north=None, south=None, east=None, west=None):
'''
Required input:
name = name of room, string
coordinates = location of Room, t... | 07_april_2021.py |
class Room:
'''
Define initial values of atributes.
Assign text representation of class.
'''
def __init__(self, name, coordinates, north=None, south=None, east=None, west=None):
'''
Required input:
name = name of room, string
coordinates = location of Room, t... | 0.605216 | 0.572723 |
from django.shortcuts import render
from django.views.generic import View
from django.views.generic.base import RedirectView
from django.views.generic.edit import FormMixin
from django.views.generic.list import ListView
from django.shortcuts import get_object_or_404
from billing.models import Transaction
from digital... | src/sellers/views.py | from django.shortcuts import render
from django.views.generic import View
from django.views.generic.base import RedirectView
from django.views.generic.edit import FormMixin
from django.views.generic.list import ListView
from django.shortcuts import get_object_or_404
from billing.models import Transaction
from digital... | 0.276886 | 0.079353 |
itemsstartroom = {'bed':'It is an exceptionally lumpy bed. It is probably bes'+\
't to not look further.',\
'window':'The window is too dirty to see much out of, but y'+\
'ou appear to be in a small town.',\
'door':['It is unlocked.',None,['exit']]... | maze/text_game.py | itemsstartroom = {'bed':'It is an exceptionally lumpy bed. It is probably bes'+\
't to not look further.',\
'window':'The window is too dirty to see much out of, but y'+\
'ou appear to be in a small town.',\
'door':['It is unlocked.',None,['exit']]... | 0.073237 | 0.320303 |
import logging
import numpy as np
import os
from collections import defaultdict, Counter
from wikipedia2vec import Wikipedia2Vec
from scipy.spatial.distance import cosine
from src import HOME_DIR
logger = logging.getLogger(__name__)
def _load_wikipedia2vec(
wiki_model_path='data/external/enwiki_20180420_100d.... | src/utils/wiki2vec.py | import logging
import numpy as np
import os
from collections import defaultdict, Counter
from wikipedia2vec import Wikipedia2Vec
from scipy.spatial.distance import cosine
from src import HOME_DIR
logger = logging.getLogger(__name__)
def _load_wikipedia2vec(
wiki_model_path='data/external/enwiki_20180420_100d.... | 0.793466 | 0.437583 |
from django.test import TestCase, Client
from ratings.models import Rating
from ratings.tests.factories import SubmissionFactory, MediaFactory, RatingFactory
from ratings.tests.helpers import RatingValues
class IndexViewTestCase(TestCase):
def test_index_view_with_no_submissions(self):
"""
If no... | ratings/tests/test_views.py | from django.test import TestCase, Client
from ratings.models import Rating
from ratings.tests.factories import SubmissionFactory, MediaFactory, RatingFactory
from ratings.tests.helpers import RatingValues
class IndexViewTestCase(TestCase):
def test_index_view_with_no_submissions(self):
"""
If no... | 0.729231 | 0.372334 |
import os
from . import BaseCommand
from ..i18n import _
class Command(BaseCommand):
name = os.path.splitext(os.path.basename(__file__))[0]
description = _('change the compression characteristics of an '
'audio/video stream')
quiet_fields = {
'source': _('source')
}
... | ems_cli/commands/transcode.py | import os
from . import BaseCommand
from ..i18n import _
class Command(BaseCommand):
name = os.path.splitext(os.path.basename(__file__))[0]
description = _('change the compression characteristics of an '
'audio/video stream')
quiet_fields = {
'source': _('source')
}
... | 0.457379 | 0.072178 |
import copy
import json
import os
import sys
import ccobra
sys.path.append(os.path.abspath(os.path.join(os.path.dirname(os.path.abspath(__file__)), "../../..")))
from modular_models.models.basic_models import PSYCOP
from modular_models.models.ccobra_models.interface import CCobraWrapper
from modular_models.... | syllogistic/2020_bischofberger/modular_models/models/ccobra_models/ccobra_psycop.py | import copy
import json
import os
import sys
import ccobra
sys.path.append(os.path.abspath(os.path.join(os.path.dirname(os.path.abspath(__file__)), "../../..")))
from modular_models.models.basic_models import PSYCOP
from modular_models.models.ccobra_models.interface import CCobraWrapper
from modular_models.... | 0.286768 | 0.089335 |
pdp_name = "pdp1"
policy_name = "RBAC policy example"
model_name = "RBAC"
policy_genre = "authz"
subjects = {
"user0": "",
"user1": "",
"user2": "",
"user3": "",
"user4": "",
"user5": "",
"user6": "",
"user7": "",
"user8": "",
"user9": "",
}
objects = {
"vm0": "",
"vm1":... | moonv4/tests/scenario/rbac_large.py | pdp_name = "pdp1"
policy_name = "RBAC policy example"
model_name = "RBAC"
policy_genre = "authz"
subjects = {
"user0": "",
"user1": "",
"user2": "",
"user3": "",
"user4": "",
"user5": "",
"user6": "",
"user7": "",
"user8": "",
"user9": "",
}
objects = {
"vm0": "",
"vm1":... | 0.244995 | 0.364212 |
import pandas as pd
from sklearn.model_selection import StratifiedShuffleSplit, ShuffleSplit
import numpy as np
from sklearn.ensemble import RandomForestClassifier
from sklearn.feature_extraction.text import CountVectorizer
from nltk.corpus import stopwords
from nltk.tokenize import word_tokenize
from sklearn.metrics i... | traditional_NLP.py | import pandas as pd
from sklearn.model_selection import StratifiedShuffleSplit, ShuffleSplit
import numpy as np
from sklearn.ensemble import RandomForestClassifier
from sklearn.feature_extraction.text import CountVectorizer
from nltk.corpus import stopwords
from nltk.tokenize import word_tokenize
from sklearn.metrics i... | 0.67971 | 0.322393 |
from glados.es.ws2es.es_util import DefaultMappings
# Shards size - can be overridden from the default calculated value here
# shards = 3,
replicas = 1
analysis = DefaultMappings.COMMON_ANALYSIS
mappings = \
{
'properties':
{
'_metadata':
{
'properties': ... | src/glados/es/ws2es/mappings_skeletons/es_chembl_metabolism_mapping.py | from glados.es.ws2es.es_util import DefaultMappings
# Shards size - can be overridden from the default calculated value here
# shards = 3,
replicas = 1
analysis = DefaultMappings.COMMON_ANALYSIS
mappings = \
{
'properties':
{
'_metadata':
{
'properties': ... | 0.405684 | 0.104477 |
from pathlib import Path
from typing import Dict, Optional, Tuple, Union
import pandas as pd
from loguru import logger
from typing_extensions import Literal
# fmt: off
from cava_tools.discrete_summary.parser import (clean_discrete_summary,
get_ds_labels,
... | cava_tools/discrete_summary/api.py | from pathlib import Path
from typing import Dict, Optional, Tuple, Union
import pandas as pd
from loguru import logger
from typing_extensions import Literal
# fmt: off
from cava_tools.discrete_summary.parser import (clean_discrete_summary,
get_ds_labels,
... | 0.885724 | 0.324623 |
import math
import numpy as np
import pandas as pd
import time
from sklearn.model_selection import StratifiedKFold
from sklearn.metrics import roc_auc_score
from sklearn.model_selection import train_test_split
from sklearn.preprocessing import StandardScaler
import matplotlib.pyplot as plt
from sklearn.preprocessing im... | Santander Customer Transaction Prediction/src/models/nn_baseline.py | import math
import numpy as np
import pandas as pd
import time
from sklearn.model_selection import StratifiedKFold
from sklearn.metrics import roc_auc_score
from sklearn.model_selection import train_test_split
from sklearn.preprocessing import StandardScaler
import matplotlib.pyplot as plt
from sklearn.preprocessing im... | 0.855021 | 0.403743 |
from perceptron.perceptron import Perceptron
from perceptron.layers import *
from training_dataset import dataset, test_dataset, NUMBER_COUNT
import random
# запускаем 3 раза, 1й ничего не меняем, далее по комментам чекай
# первый слой (вход) на 15, второй на 300 и третий (выход) 10 нейронов
def train_perceptron():
... | XFouth course/8th semester/AI&NN/main.py | from perceptron.perceptron import Perceptron
from perceptron.layers import *
from training_dataset import dataset, test_dataset, NUMBER_COUNT
import random
# запускаем 3 раза, 1й ничего не меняем, далее по комментам чекай
# первый слой (вход) на 15, второй на 300 и третий (выход) 10 нейронов
def train_perceptron():
... | 0.488527 | 0.459076 |
import os
from pathlib import Path
from django.core.management.base import BaseCommand
from azure.storage.blob import BlobServiceClient
from pipeline.importers.csv_resource import import_csv_resources
from pipeline.importers.databc_resource import import_wms_resource
from pipeline.importers.data_sources import import... | cit-api/pipeline/management/commands/bootstrap.py | import os
from pathlib import Path
from django.core.management.base import BaseCommand
from azure.storage.blob import BlobServiceClient
from pipeline.importers.csv_resource import import_csv_resources
from pipeline.importers.databc_resource import import_wms_resource
from pipeline.importers.data_sources import import... | 0.245356 | 0.183009 |
import unittest
from cartoonista import Cartoons, CartoonError
class TestCartoonista(unittest.TestCase):
def test_random(self):
"""
We should get a dict with random cartoon values.
"""
for x in range(0, 99):
c = Cartoons.get_random_cartoon()
self.assertIsIns... | test.py | import unittest
from cartoonista import Cartoons, CartoonError
class TestCartoonista(unittest.TestCase):
def test_random(self):
"""
We should get a dict with random cartoon values.
"""
for x in range(0, 99):
c = Cartoons.get_random_cartoon()
self.assertIsIns... | 0.590661 | 0.628236 |
from rflint.common import SuiteRule, TestRule, ERROR, WARNING
from static import normalize
MUST_KEYWORDS = [
"New Browser",
"New Page",
"Fill Text",
"Fill Secret",
]
LOGIN_KEYWORDS = [
"Click",
"Keyboard Key",
]
VERIFY_KEYWORDS = [
"Get Title",
"Get Url",
"Get Text",
]
DEFAULT_ME... | setup/02-robot_syntax_rule.py | from rflint.common import SuiteRule, TestRule, ERROR, WARNING
from static import normalize
MUST_KEYWORDS = [
"New Browser",
"New Page",
"Fill Text",
"Fill Secret",
]
LOGIN_KEYWORDS = [
"Click",
"Keyboard Key",
]
VERIFY_KEYWORDS = [
"Get Title",
"Get Url",
"Get Text",
]
DEFAULT_ME... | 0.379723 | 0.2791 |
from sklearn.model_selection import GridSearchCV
from sklearn.tree import DecisionTreeClassifier
from sklearn.tree._tree import TREE_LEAF
def learn_local_decision_tree(Z, Yb, weights, class_values, multi_label=False, one_vs_rest=False, cv=5,
prune_tree=False):
dt = DecisionTre... | decision_tree.py | from sklearn.model_selection import GridSearchCV
from sklearn.tree import DecisionTreeClassifier
from sklearn.tree._tree import TREE_LEAF
def learn_local_decision_tree(Z, Yb, weights, class_values, multi_label=False, one_vs_rest=False, cv=5,
prune_tree=False):
dt = DecisionTre... | 0.395368 | 0.340047 |
from .algorithms import AlgorithmResource, AlgorithmListResource
from .datasets import DatasetLoadResource, DatasetLoadWithIdsResource, DatasetListResource, DatasetResource, \
DatasetAvailableSourcesResource, DatasetExperimentResource, DatasetGroundTruthResource, \
DatasetMetadataResource
from .distributions im... | services/python-images/src/master/resources/__init__.py | from .algorithms import AlgorithmResource, AlgorithmListResource
from .datasets import DatasetLoadResource, DatasetLoadWithIdsResource, DatasetListResource, DatasetResource, \
DatasetAvailableSourcesResource, DatasetExperimentResource, DatasetGroundTruthResource, \
DatasetMetadataResource
from .distributions im... | 0.605333 | 0.069668 |
import os
import datetime
from docx import Document
from docx.shared import Pt
from docx.shared import Cm
from docx.enum.text import WD_ALIGN_PARAGRAPH
# R,C,S,M,L,E,SMA = Religion, Chemistry, Spanish, Math, Latin, English, Rotation
def parsecourse(s):
if s == "R":
print(s)
data = ["C:/Users/Etha... | docTool.py |
import os
import datetime
from docx import Document
from docx.shared import Pt
from docx.shared import Cm
from docx.enum.text import WD_ALIGN_PARAGRAPH
# R,C,S,M,L,E,SMA = Religion, Chemistry, Spanish, Math, Latin, English, Rotation
def parsecourse(s):
if s == "R":
print(s)
data = ["C:/Users/Etha... | 0.252292 | 0.286712 |
import pytest
import salt.states.rabbitmq_policy as rabbitmq_policy
from tests.support.mock import MagicMock, patch
@pytest.fixture
def configure_loader_modules():
return {rabbitmq_policy: {}}
# 'present' function tests: 1
def test_present():
"""
Test to ensure the RabbitMQ policy exists.
"""
... | tests/pytests/unit/states/rabbitmq/test_policy.py | import pytest
import salt.states.rabbitmq_policy as rabbitmq_policy
from tests.support.mock import MagicMock, patch
@pytest.fixture
def configure_loader_modules():
return {rabbitmq_policy: {}}
# 'present' function tests: 1
def test_present():
"""
Test to ensure the RabbitMQ policy exists.
"""
... | 0.712832 | 0.432543 |
import json
import requests
import time
import logging
from assetmunki.client import APIClient
from .exceptions import SnipeITAssetNotFoundError
from . import dto
class SnipeITClient(APIClient):
def __init__(self, base_url, token):
self._base_url = base_url
self._token = token
self.valida... | assetmunki/ext/snipeit/client.py | import json
import requests
import time
import logging
from assetmunki.client import APIClient
from .exceptions import SnipeITAssetNotFoundError
from . import dto
class SnipeITClient(APIClient):
def __init__(self, base_url, token):
self._base_url = base_url
self._token = token
self.valida... | 0.191781 | 0.142053 |
import nkutil
from text import yinsu_symbols, character_symbols, pinyin_symbols
def create_hparams():
hparams = nkutil.HParams(
################################
# PolyPhonic Parameters #
################################
num_classes = 1665, ##?
class2idx... | hparams.py | import nkutil
from text import yinsu_symbols, character_symbols, pinyin_symbols
def create_hparams():
hparams = nkutil.HParams(
################################
# PolyPhonic Parameters #
################################
num_classes = 1665, ##?
class2idx... | 0.371251 | 0.111822 |
import os
import click
import numpy as np
from joblib import Parallel, delayed
import trisicell as tsc
@click.command(short_help="Run SCITE.")
@click.argument(
"genotype_file",
required=True,
type=click.Path(
exists=True, file_okay=True, dir_okay=False, readable=True, resolve_path=True
),
)
... | trisicell/commands/_scite.py | import os
import click
import numpy as np
from joblib import Parallel, delayed
import trisicell as tsc
@click.command(short_help="Run SCITE.")
@click.argument(
"genotype_file",
required=True,
type=click.Path(
exists=True, file_okay=True, dir_okay=False, readable=True, resolve_path=True
),
)
... | 0.477311 | 0.186947 |
import eventlet
from random import SystemRandom
rand = SystemRandom()
import hook, bnetprotocol
from misc import *
from config import config
clantrack = hook.import_plugin('clantrack')
invitations = {}
parsed_settings = {}
def parse_settings():
for i in xrange(9001):
try:
settings = config[_... | plugins/cinvite.py | import eventlet
from random import SystemRandom
rand = SystemRandom()
import hook, bnetprotocol
from misc import *
from config import config
clantrack = hook.import_plugin('clantrack')
invitations = {}
parsed_settings = {}
def parse_settings():
for i in xrange(9001):
try:
settings = config[_... | 0.095851 | 0.092278 |
import nibabel as nib
import os
import torch
from torch.utils.data import Dataset, DataLoader
from torchvision import transforms, utils
class BRATS_test(Dataset):
"""Face Landmarks dataset."""
def __init__(self, root_dir, transform=None):
"""
Args:
csv_file (string): Path to the cs... | load_testdata.py | import nibabel as nib
import os
import torch
from torch.utils.data import Dataset, DataLoader
from torchvision import transforms, utils
class BRATS_test(Dataset):
"""Face Landmarks dataset."""
def __init__(self, root_dir, transform=None):
"""
Args:
csv_file (string): Path to the cs... | 0.88294 | 0.475788 |
import math
import torch
import torch.nn as nn
from fpn import FPN101
class RetinaNet(nn.Module):
def __init__(self, config, num_classes):
super(RetinaNet, self).__init__()
self.fpn = FPN101(pretrained=True)
if num_classes > 2:
self.num_classes = num_classes + 1
... | src/stage1/retinanet.py | import math
import torch
import torch.nn as nn
from fpn import FPN101
class RetinaNet(nn.Module):
def __init__(self, config, num_classes):
super(RetinaNet, self).__init__()
self.fpn = FPN101(pretrained=True)
if num_classes > 2:
self.num_classes = num_classes + 1
... | 0.815306 | 0.26083 |
import phanterpwa.frontend.gatehandler as gatehandler
import phanterpwa.frontend.helpers as helpers
import phanterpwa.frontend.validations as validations
import phanterpwa.frontend.components.widgets as widgets
import phanterpwa.frontend.components.left_bar as left_bar
import phanterpwa.frontend.forms as forms
import p... | static/0.6.0.322/js/transcrypt/handlers.turmas.py | import phanterpwa.frontend.gatehandler as gatehandler
import phanterpwa.frontend.helpers as helpers
import phanterpwa.frontend.validations as validations
import phanterpwa.frontend.components.widgets as widgets
import phanterpwa.frontend.components.left_bar as left_bar
import phanterpwa.frontend.forms as forms
import p... | 0.235548 | 0.111555 |
from logging import basicConfig, getLogger, INFO
from connect_to_ledger import create_qldb_driver
from amazon.ion.simpleion import dumps, loads
logger = getLogger(__name__)
basicConfig(level=INFO)
from sampledata.sample_data import document_exist,get_value_from_documentid,get_document_ids,convert_object_to_ion
from in... | lambda/qldb/create_purchase_order_to_distributor.py | from logging import basicConfig, getLogger, INFO
from connect_to_ledger import create_qldb_driver
from amazon.ion.simpleion import dumps, loads
logger = getLogger(__name__)
basicConfig(level=INFO)
from sampledata.sample_data import document_exist,get_value_from_documentid,get_document_ids,convert_object_to_ion
from in... | 0.262275 | 0.146697 |
import logging
logger = logging.getLogger()
logger.level = logging.INFO
import unittest
from dgraph_common import DgraphClusterTest
from gresearch.spark.dgraph.connector import *
class DgraphTest(DgraphClusterTest):
@classmethod
def get_expected_triples(cls):
jvm = cls.spark._jvm
return j... | python/test/test_dgraph.py |
import logging
logger = logging.getLogger()
logger.level = logging.INFO
import unittest
from dgraph_common import DgraphClusterTest
from gresearch.spark.dgraph.connector import *
class DgraphTest(DgraphClusterTest):
@classmethod
def get_expected_triples(cls):
jvm = cls.spark._jvm
return j... | 0.806586 | 0.425725 |
import readline
from fractions import Fraction as frac
import sys
from .tokens import tokenise, UnknownTokenError
from .parse import parse_tokens, ParsingError
from .eval import eval_parse_tree, EvalError, EvalEnvironment
from .types import Quantity
from .functions import (FUNCTIONS, UnknownFunctionError,
NoMatchi... | src/ka/interpret.py | import readline
from fractions import Fraction as frac
import sys
from .tokens import tokenise, UnknownTokenError
from .parse import parse_tokens, ParsingError
from .eval import eval_parse_tree, EvalError, EvalEnvironment
from .types import Quantity
from .functions import (FUNCTIONS, UnknownFunctionError,
NoMatchi... | 0.289773 | 0.131926 |
from collections import namedtuple
import marshmallow
from . import extra
#: Return type of :meth:`Schema.dump` including serialized data and errors
MarshalResult = namedtuple("MarshalResult", ["data", "errors"])
#: Return type of :meth:`Schema.load`, including deserialized data and errors
UnmarshalResult = namedtu... | swagger_marshmallow_codegen/schema/legacy.py | from collections import namedtuple
import marshmallow
from . import extra
#: Return type of :meth:`Schema.dump` including serialized data and errors
MarshalResult = namedtuple("MarshalResult", ["data", "errors"])
#: Return type of :meth:`Schema.load`, including deserialized data and errors
UnmarshalResult = namedtu... | 0.72086 | 0.135661 |
from parla.multiload import multiload_contexts as VECs
import os
import sys
import getopt
import concurrent.futures
import time
import queue
# Default values, can override with command line args
ROWS = 240000 # Must be >> COLS
COLS = 1000
BLOCK_SIZE = 3000 # Must be >= COLS
MAX_WORKERS = 11 # Must be < 12 due to lim... | examples/TSQR/vec_segfault.py |
from parla.multiload import multiload_contexts as VECs
import os
import sys
import getopt
import concurrent.futures
import time
import queue
# Default values, can override with command line args
ROWS = 240000 # Must be >> COLS
COLS = 1000
BLOCK_SIZE = 3000 # Must be >= COLS
MAX_WORKERS = 11 # Must be < 12 due to lim... | 0.399577 | 0.211295 |
import unittest
import nest
from . import compatibility
try:
import csa
HAVE_CSA = True
except ImportError:
HAVE_CSA = False
try:
import numpy
HAVE_NUMPY = True
except ImportError:
HAVE_NUMPY = False
nest.sli_run("statusdict/have_libneurosim ::")
HAVE_LIBNEUROSIM = nest.sli_pop()
@nest.che... | NEST-14.0-FPGA/pynest/nest/tests/test_csa.py | import unittest
import nest
from . import compatibility
try:
import csa
HAVE_CSA = True
except ImportError:
HAVE_CSA = False
try:
import numpy
HAVE_NUMPY = True
except ImportError:
HAVE_NUMPY = False
nest.sli_run("statusdict/have_libneurosim ::")
HAVE_LIBNEUROSIM = nest.sli_pop()
@nest.che... | 0.679179 | 0.372391 |
import datetime
from django.views.generic import (ListView, FormView, DeleteView, DetailView,
CreateView, UpdateView)
from django.db.models.loading import get_model
from django.core.urlresolvers import reverse
from django.contrib import messages
from django.http import HttpResponseRed... | oscar/apps/dashboard/offers/views.py | import datetime
from django.views.generic import (ListView, FormView, DeleteView, DetailView,
CreateView, UpdateView)
from django.db.models.loading import get_model
from django.core.urlresolvers import reverse
from django.contrib import messages
from django.http import HttpResponseRed... | 0.482917 | 0.059784 |
import os
import logging
import anomalytransfer as at
os.environ["CUDA_VISIBLE_DEVICES"] = '1'
def main():
at.utils.mkdirs(OUTPUT)
file_list = at.utils.file_list(INPUT)
proglog = at.utils.ProgLog(len(file_list))
for file in file_list:
kpi = at.utils.load_kpi(file)
proglog.log(kpi=kpi.... | sample/scripts/transfer/naive_bagel.py | import os
import logging
import anomalytransfer as at
os.environ["CUDA_VISIBLE_DEVICES"] = '1'
def main():
at.utils.mkdirs(OUTPUT)
file_list = at.utils.file_list(INPUT)
proglog = at.utils.ProgLog(len(file_list))
for file in file_list:
kpi = at.utils.load_kpi(file)
proglog.log(kpi=kpi.... | 0.384797 | 0.104889 |
import os
import json
from torch.utils.data import DataLoader
from rssnet.loaders.dataset import Carrada
from rssnet.loaders.dataloaders import SequenceCarradaDataset
from rssnet.utils.paths import Paths
class Initializer:
"""Class to initialize training pipeline
PARAMETERS
----------
cfg: dict
... | rssnet/learners/initializer.py | import os
import json
from torch.utils.data import DataLoader
from rssnet.loaders.dataset import Carrada
from rssnet.loaders.dataloaders import SequenceCarradaDataset
from rssnet.utils.paths import Paths
class Initializer:
"""Class to initialize training pipeline
PARAMETERS
----------
cfg: dict
... | 0.722233 | 0.306787 |
import os
import numpy as np
from train import config
# 训练数据 测试数据提供
# classes 分类数量
# input_size 图像维度/输入维度
# max_pixel 最大数值 0-1/0-255
def get_mnist_data():
classes = 10
input_size = 784
max_pixel = 1
train_dir_path = os.path.join(config.data_save_path, config.mnist_train_data)
test_dir_path = os.pa... | train/data_provider.py | import os
import numpy as np
from train import config
# 训练数据 测试数据提供
# classes 分类数量
# input_size 图像维度/输入维度
# max_pixel 最大数值 0-1/0-255
def get_mnist_data():
classes = 10
input_size = 784
max_pixel = 1
train_dir_path = os.path.join(config.data_save_path, config.mnist_train_data)
test_dir_path = os.pa... | 0.132767 | 0.469581 |
import copy
import random
class Key:
"""
A key that the Cascade protocol reconciles.
"""
_random = random.Random()
ERROR_METHOD_BERNOULLI = "bernoulli"
ERROR_METHOD_EXACT = "exact"
ERROR_METHODS = [ERROR_METHOD_BERNOULLI, ERROR_METHOD_EXACT]
def __init__(self):
"""
Cre... | cascade/key.py | import copy
import random
class Key:
"""
A key that the Cascade protocol reconciles.
"""
_random = random.Random()
ERROR_METHOD_BERNOULLI = "bernoulli"
ERROR_METHOD_EXACT = "exact"
ERROR_METHODS = [ERROR_METHOD_BERNOULLI, ERROR_METHOD_EXACT]
def __init__(self):
"""
Cre... | 0.81457 | 0.450239 |
import threading
import json
import os
import time
from datetime import datetime
from .jobs_manager import JobsManager
from ..utils.constants import STATUS, OK_MESSAGE, KO_MESSAGE, \
END_OF_MESSAGE, DATETIME_FORMAT, RESULTS
from ..utils.logging import get_logger
from ..utils.db import get_... | src/thread/command_handler.py | import threading
import json
import os
import time
from datetime import datetime
from .jobs_manager import JobsManager
from ..utils.constants import STATUS, OK_MESSAGE, KO_MESSAGE, \
END_OF_MESSAGE, DATETIME_FORMAT, RESULTS
from ..utils.logging import get_logger
from ..utils.db import get_... | 0.160398 | 0.083591 |
from instagram_private_api import Client
import account_helper
import input_helper
from actions import following_unshared, followers_unshared
from main import console, base_color
from states import menu
prefix = "(menu): "
unshared: list = []
def start(client: Client):
global unshared
account_helper.do_d... | src/states/action.py | from instagram_private_api import Client
import account_helper
import input_helper
from actions import following_unshared, followers_unshared
from main import console, base_color
from states import menu
prefix = "(menu): "
unshared: list = []
def start(client: Client):
global unshared
account_helper.do_d... | 0.243552 | 0.164886 |
import os
import csv
import keras
import cv2
import numpy as np
import sklearn
from keras.models import Sequential
from keras.layers import Flatten, Dense, Lambda, Cropping2D
from keras.layers.convolutional import Convolution2D
from keras.models import load_model
lines = []
with open('./data3/driving_log.csv') as csvf... | model.py | import os
import csv
import keras
import cv2
import numpy as np
import sklearn
from keras.models import Sequential
from keras.layers import Flatten, Dense, Lambda, Cropping2D
from keras.layers.convolutional import Convolution2D
from keras.models import load_model
lines = []
with open('./data3/driving_log.csv') as csvf... | 0.628293 | 0.335337 |
from __future__ import absolute_import
from galaxy import common
from galaxy import constants
from galaxy.main import models
from . import base
class RoleImporter(base.ContentImporter):
linter_data = {
'is_linter_rule_violation': True,
'linter_type': 'importer',
'linter_rule_id': None,
... | galaxy/worker/importers/role.py |
from __future__ import absolute_import
from galaxy import common
from galaxy import constants
from galaxy.main import models
from . import base
class RoleImporter(base.ContentImporter):
linter_data = {
'is_linter_rule_violation': True,
'linter_type': 'importer',
'linter_rule_id': None,
... | 0.605682 | 0.062331 |
#!/usr/bin/env python3
import math
import time
from collections import deque
from typing import Deque, Dict
import torch
import torch.nn as nn
from torchrec.metrics.metrics_namespace import (
compose_metric_key,
MetricName,
MetricNamespace,
MetricPrefix,
)
MAX_WINDOW_TS = 1_000_000
class Throughpu... | torchrec/metrics/throughput.py |
#!/usr/bin/env python3
import math
import time
from collections import deque
from typing import Deque, Dict
import torch
import torch.nn as nn
from torchrec.metrics.metrics_namespace import (
compose_metric_key,
MetricName,
MetricNamespace,
MetricPrefix,
)
MAX_WINDOW_TS = 1_000_000
class Throughpu... | 0.856407 | 0.386011 |
from NBprocessing.src._constance_dict import data
class Const(object):
def __init__(self):
# check input file
self.CHECK_DATABASE_INPUT = data["CHECK_INPUT"]["CHECK_DATABASE_INPUT"]
self.CHECK_COLUMN_NAME = data["CHECK_INPUT"]["CHECK_COLUMN_NAME"]
self.CHECK_COLUMN_IN_DATABASE = d... | NBprocessing/src/_constance_class.py | from NBprocessing.src._constance_dict import data
class Const(object):
def __init__(self):
# check input file
self.CHECK_DATABASE_INPUT = data["CHECK_INPUT"]["CHECK_DATABASE_INPUT"]
self.CHECK_COLUMN_NAME = data["CHECK_INPUT"]["CHECK_COLUMN_NAME"]
self.CHECK_COLUMN_IN_DATABASE = d... | 0.541166 | 0.132402 |
import datetime
from itertools import cycle
from django.shortcuts import get_object_or_404, render, redirect
from django.urls import reverse
from django.contrib.auth.models import Group
from django.contrib.auth.decorators import login_required
from django.http import HttpResponse, HttpResponseRedirect
from django.contr... | lunch/views.py | import datetime
from itertools import cycle
from django.shortcuts import get_object_or_404, render, redirect
from django.urls import reverse
from django.contrib.auth.models import Group
from django.contrib.auth.decorators import login_required
from django.http import HttpResponse, HttpResponseRedirect
from django.contr... | 0.228156 | 0.076167 |
import os
import json
import prettytable as pt
import tensorflow as tf
from tabulator import Stream
from band.utils import text_length_info
from transformers.data.processors import DataProcessor
from band.config import DEFAULT_DATASET_DOWNLOAD_PATH
def download_dataset(save_path: str, dataset_name: str, file_name: st... | band/base.py | import os
import json
import prettytable as pt
import tensorflow as tf
from tabulator import Stream
from band.utils import text_length_info
from transformers.data.processors import DataProcessor
from band.config import DEFAULT_DATASET_DOWNLOAD_PATH
def download_dataset(save_path: str, dataset_name: str, file_name: st... | 0.528777 | 0.284864 |
from fastapi import APIRouter, Depends, Response, Security, status
from fastapi_okta import OktaUser
from sqlalchemy.orm import Session
from literature import database
from literature.crud import reference_automated_term_tag_crud
from literature.routers.authentication import auth
from literature.schemas import (Refere... | backend/app/literature/routers/reference_automated_term_tag_router.py | from fastapi import APIRouter, Depends, Response, Security, status
from fastapi_okta import OktaUser
from sqlalchemy.orm import Session
from literature import database
from literature.crud import reference_automated_term_tag_crud
from literature.routers.authentication import auth
from literature.schemas import (Refere... | 0.453262 | 0.072112 |
import discord, asyncio, random
from discord import ui
from discord.ext import commands
from . import utils
LONG_TIMEOUT = 1000
def disable_dm_commands(func):
#Unprefixed commands must be disabled for certain responses
async def wrapper(*args, **kwargs):
ctx = args[0] if type(args[0]) == commands.Context else ar... | ht/views.py | import discord, asyncio, random
from discord import ui
from discord.ext import commands
from . import utils
LONG_TIMEOUT = 1000
def disable_dm_commands(func):
#Unprefixed commands must be disabled for certain responses
async def wrapper(*args, **kwargs):
ctx = args[0] if type(args[0]) == commands.Context else ar... | 0.218169 | 0.095518 |
import base64
import json
import random
from django.contrib.auth.models import User
from django.http import JsonResponse, HttpResponse
from rest_framework import mixins, viewsets, authentication, status, permissions
from rest_framework.views import APIView
from rest_framework.response import Response
from rest_framewo... | user_profile/views.py | import base64
import json
import random
from django.contrib.auth.models import User
from django.http import JsonResponse, HttpResponse
from rest_framework import mixins, viewsets, authentication, status, permissions
from rest_framework.views import APIView
from rest_framework.response import Response
from rest_framewo... | 0.400163 | 0.066116 |
import base64
from itsdangerous import BadSignature, SignatureExpired, TimedJSONWebSignatureSerializer
from rest_framework.permissions import BasePermission
from rest_framework.exceptions import AuthenticationFailed
from rest_framework.authentication import get_authorization_header, BasicAuthentication
from django.ur... | gojob/api/v1/customer/__init__.py | import base64
from itsdangerous import BadSignature, SignatureExpired, TimedJSONWebSignatureSerializer
from rest_framework.permissions import BasePermission
from rest_framework.exceptions import AuthenticationFailed
from rest_framework.authentication import get_authorization_header, BasicAuthentication
from django.ur... | 0.527803 | 0.080249 |
from pathlib import Path
import boto3
import click
import json
import logging
import os
import requests
import shutil
import sys
import time
import typing
def start_transcription(
key,
*,
storage,
transcribe,
bucket,
ChannelIdentification=True,
lang='en-US',
... | audio_splitter.py | from pathlib import Path
import boto3
import click
import json
import logging
import os
import requests
import shutil
import sys
import time
import typing
def start_transcription(
key,
*,
storage,
transcribe,
bucket,
ChannelIdentification=True,
lang='en-US',
... | 0.385722 | 0.053527 |
from __future__ import absolute_import
from __future__ import division
from __future__ import print_function
import tensorflow as tf
from VGG import vgg16
from fpn_generator import fpn_generator
from anchor_generator import anchor_generator
from bboxfs import partition_pos_neg_samples, ohem, bbox_decode, bbox_encode
fr... | SSD.py | from __future__ import absolute_import
from __future__ import division
from __future__ import print_function
import tensorflow as tf
from VGG import vgg16
from fpn_generator import fpn_generator
from anchor_generator import anchor_generator
from bboxfs import partition_pos_neg_samples, ohem, bbox_decode, bbox_encode
fr... | 0.79999 | 0.345657 |
# ______________________________________________________________________
# Module imports
import token
# ______________________________________________________________________
# Module data
__DEBUG__ = False
# ______________________________________________________________________
# Function definitions
class Token... | mython/trampoline.py | # ______________________________________________________________________
# Module imports
import token
# ______________________________________________________________________
# Module data
__DEBUG__ = False
# ______________________________________________________________________
# Function definitions
class Token... | 0.431345 | 0.218253 |
from sinor import html_content
from nose.tools import assert_equals
from data_builder import HTMLContentBuilder
def test_parse_empty_string():
html = HTMLContentBuilder().build()
assert_equals(html_content.from_string(html), {'title': '',
'date': '',
... | test/test_html_content.py | from sinor import html_content
from nose.tools import assert_equals
from data_builder import HTMLContentBuilder
def test_parse_empty_string():
html = HTMLContentBuilder().build()
assert_equals(html_content.from_string(html), {'title': '',
'date': '',
... | 0.712532 | 0.242654 |
import os
import pysam
import pybedtools
from pybedtools import BedTool
import log,traceback
cigar_op={'M', 'I', 'D', 'N', 'S', 'H', 'P', '=', 'X'}
cigar_ref_retain={'M', 'D', 'N', '=', 'X'}
cigar_read_retain={'M', 'I', '=', 'X'}
def detect_discordant(args, params, filenames):
log.logger.debug('started')
tr... | scripts/precall_search_discordant.py | import os
import pysam
import pybedtools
from pybedtools import BedTool
import log,traceback
cigar_op={'M', 'I', 'D', 'N', 'S', 'H', 'P', '=', 'X'}
cigar_ref_retain={'M', 'D', 'N', '=', 'X'}
cigar_read_retain={'M', 'I', '=', 'X'}
def detect_discordant(args, params, filenames):
log.logger.debug('started')
tr... | 0.085561 | 0.168925 |
from flask import Blueprint, request, render_template, redirect, url_for, jsonify
from datetime import datetime
from losttime import entryfiles
from ._output_templates import EntryWriter
import re
import csv
from os import remove
from os.path import join, isfile
from collections import Counter
entryManager = Blueprin... | losttime/views/entry_manager.py |
from flask import Blueprint, request, render_template, redirect, url_for, jsonify
from datetime import datetime
from losttime import entryfiles
from ._output_templates import EntryWriter
import re
import csv
from os import remove
from os.path import join, isfile
from collections import Counter
entryManager = Blueprin... | 0.374104 | 0.106505 |
import pandas as pd
import numpy as np
import seaborn as sns
import matplotlib.pyplot as plt
df = pd.read_csv("data/car data.csv")
features = list(filter(lambda x: x!="Car_Name" ,list(df.columns)))
final_dataset = df[features]
final_dataset['No_Year'] = 2020 - df['Year']
final_dataset.drop(['Year'], axis=1, inplace=T... | python_code.py | import pandas as pd
import numpy as np
import seaborn as sns
import matplotlib.pyplot as plt
df = pd.read_csv("data/car data.csv")
features = list(filter(lambda x: x!="Car_Name" ,list(df.columns)))
final_dataset = df[features]
final_dataset['No_Year'] = 2020 - df['Year']
final_dataset.drop(['Year'], axis=1, inplace=T... | 0.382487 | 0.469946 |
from roll import roll
# Source: http://dndspeak.com/2019/03/05/100-warm-up-roleplaying-questions-for-players/
table = [
("If your character wasn’t an adventurer, what livelihood would they lead?", 1),
("Who in the party would your character trust the most with their life?", 1),
("What are your character’s... | warm_up_rp_questions.py | from roll import roll
# Source: http://dndspeak.com/2019/03/05/100-warm-up-roleplaying-questions-for-players/
table = [
("If your character wasn’t an adventurer, what livelihood would they lead?", 1),
("Who in the party would your character trust the most with their life?", 1),
("What are your character’s... | 0.557484 | 0.423577 |
from environment.game import *
from learningAgents import ReinforcementAgent
from featureExtractors import *
from collections import defaultdict
import random, math
import environment.util as util
class QLearningAgent(ReinforcementAgent):
"""
Q-Learning Agent
Functions you should fill in:
... | qLearningAgents.py | from environment.game import *
from learningAgents import ReinforcementAgent
from featureExtractors import *
from collections import defaultdict
import random, math
import environment.util as util
class QLearningAgent(ReinforcementAgent):
"""
Q-Learning Agent
Functions you should fill in:
... | 0.848533 | 0.474327 |
import datetime
import time
from struct import pack
import binascii
from mustaine.protocol import *
# Implementation of Hessian 1.0.2 serialization
# see: http://hessian.caucho.com/doc/hessian-1.0-spec.xtp
ENCODERS = {}
def encoder_for(data_type):
def register(f):
# register function `f` to encode type... | mustaine/encoder.py | import datetime
import time
from struct import pack
import binascii
from mustaine.protocol import *
# Implementation of Hessian 1.0.2 serialization
# see: http://hessian.caucho.com/doc/hessian-1.0-spec.xtp
ENCODERS = {}
def encoder_for(data_type):
def register(f):
# register function `f` to encode type... | 0.68056 | 0.137909 |
import sys
import collections
import pathlib
import json
import numpy as np
from pysgrs.interfaces.score import GenericScore
from pysgrs.settings import settings
from pysgrs import errors
from pysgrs.toolbox.cleaner import AsciiCleaner
class NGramScore(GenericScore):
def __init__(self, source=None, order=1, la... | pysgrs/scores/ngrams.py | import sys
import collections
import pathlib
import json
import numpy as np
from pysgrs.interfaces.score import GenericScore
from pysgrs.settings import settings
from pysgrs import errors
from pysgrs.toolbox.cleaner import AsciiCleaner
class NGramScore(GenericScore):
def __init__(self, source=None, order=1, la... | 0.577614 | 0.16455 |
from scipy import ndimage
import numpy as np
"""###Opening and writing to image files"""
from scipy import misc
import imageio
f = misc.face()
imageio.imsave('face.png', f) # uses the Image module (PIL)
import matplotlib.pyplot as plt
plt.imshow(f)
plt.show()
from scipy import misc
import imageio
face = misc.face()... | Image Processing/imageprocessing.py | from scipy import ndimage
import numpy as np
"""###Opening and writing to image files"""
from scipy import misc
import imageio
f = misc.face()
imageio.imsave('face.png', f) # uses the Image module (PIL)
import matplotlib.pyplot as plt
plt.imshow(f)
plt.show()
from scipy import misc
import imageio
face = misc.face()... | 0.730097 | 0.444806 |
from django.contrib.auth import get_user_model
from django.test import TestCase
from django.urls import reverse
from rest_framework.test import APIClient
from core.models import Tag, Recipe
from recipe.serializers import TagSerializer
TAGS_URL = reverse('recipe:tag-list')
class TestPublicTagAPI(TestCase):
"""Te... | app/recipe/tests/test_tag_api.py | from django.contrib.auth import get_user_model
from django.test import TestCase
from django.urls import reverse
from rest_framework.test import APIClient
from core.models import Tag, Recipe
from recipe.serializers import TagSerializer
TAGS_URL = reverse('recipe:tag-list')
class TestPublicTagAPI(TestCase):
"""Te... | 0.671686 | 0.254474 |
import torch
from torch.autograd import Variable
from torch.autograd import Function
import torch.nn as nn
from typing import Tuple
from . import sparse_interpolate_ext
class SparseThreeNN(Function):
@staticmethod
def forward(ctx, unknown: torch.Tensor,
known: torch.Tensor) -> Tuple[torch.Te... | gorilla3d/ops/sparse_interpolate/sparse_interpolate.py |
import torch
from torch.autograd import Variable
from torch.autograd import Function
import torch.nn as nn
from typing import Tuple
from . import sparse_interpolate_ext
class SparseThreeNN(Function):
@staticmethod
def forward(ctx, unknown: torch.Tensor,
known: torch.Tensor) -> Tuple[torch.Te... | 0.962892 | 0.847337 |
import pymysql
###### https://www.db4free.net/phpMyAdmin/index.php
# Connect to the database
connection = pymysql.connect(host='db4free.net',
user='itccohort19',
password='<PASSWORD>',
db='pymonsquad',
c... | backend/dbutils.py | import pymysql
###### https://www.db4free.net/phpMyAdmin/index.php
# Connect to the database
connection = pymysql.connect(host='db4free.net',
user='itccohort19',
password='<PASSWORD>',
db='pymonsquad',
c... | 0.289071 | 0.182717 |
import numpy as np
import vtk
import slicer
from emoji import UNICODE_EMOJI
def create_np_text_img(text: str, size: tuple = (128, 128),
font_size: int = 24, emoj_size: int = 64) -> np.ndarray:
"""
Create a numpy text image.
Creates a text-on-background image and returns it as a fla... | SlicerPlayground/playground_utils.py | import numpy as np
import vtk
import slicer
from emoji import UNICODE_EMOJI
def create_np_text_img(text: str, size: tuple = (128, 128),
font_size: int = 24, emoj_size: int = 64) -> np.ndarray:
"""
Create a numpy text image.
Creates a text-on-background image and returns it as a fla... | 0.839175 | 0.552841 |
import sys
import getopt
from progress.bar import IncrementalBar
import tempfile
import urllib.request
from bs4 import BeautifulSoup
from urllib.parse import urlparse, parse_qs
import json
def get_page(birder_id, tmp_dir, page_num=1):
fname = f"{tmp_dir}/{birder_id}-{page_num}.html"
url = f"http://orientalbi... | dl-photos.py |
import sys
import getopt
from progress.bar import IncrementalBar
import tempfile
import urllib.request
from bs4 import BeautifulSoup
from urllib.parse import urlparse, parse_qs
import json
def get_page(birder_id, tmp_dir, page_num=1):
fname = f"{tmp_dir}/{birder_id}-{page_num}.html"
url = f"http://orientalbi... | 0.115013 | 0.23001 |
import sys
import requests
from apiclient.discovery import build
from httplib2 import Http
from oauth2client import file, client, tools
def download_photos_by_ids(ids=[]):
"""Download photos from Google Photos by ids"""
output = []
service = setup_api()
length = len(ids)
for i, _id in enumerate... | insta/photos.py |
import sys
import requests
from apiclient.discovery import build
from httplib2 import Http
from oauth2client import file, client, tools
def download_photos_by_ids(ids=[]):
"""Download photos from Google Photos by ids"""
output = []
service = setup_api()
length = len(ids)
for i, _id in enumerate... | 0.242564 | 0.103024 |
from ebaysdk.trading import Connection as Trading
import sqlite3
conn = sqlite3.connect('categoriesDB.db')
c = conn.cursor()
api = Trading(config_file=None, domain='api.sandbox.ebay.com',
appid="EchoBay62-5538-466c-b43b-662768d6841",
devid="16a26b1b-26cf-442d-906d-597b60c41c19",
... | functions.py | from ebaysdk.trading import Connection as Trading
import sqlite3
conn = sqlite3.connect('categoriesDB.db')
c = conn.cursor()
api = Trading(config_file=None, domain='api.sandbox.ebay.com',
appid="EchoBay62-5538-466c-b43b-662768d6841",
devid="16a26b1b-26cf-442d-906d-597b60c41c19",
... | 0.350199 | 0.065905 |
from datetime import datetime
from django import forms
from django.conf import settings
from django.contrib.auth import (password_validation, )
from django.contrib.auth.forms import (AuthenticationForm, UsernameField,
PasswordResetForm, SetPasswordForm)
from django.forms import ModelForm
from django.forms.widgets ... | users/forms/front_forms.py | from datetime import datetime
from django import forms
from django.conf import settings
from django.contrib.auth import (password_validation, )
from django.contrib.auth.forms import (AuthenticationForm, UsernameField,
PasswordResetForm, SetPasswordForm)
from django.forms import ModelForm
from django.forms.widgets ... | 0.385143 | 0.07208 |
import unittest
from sunburst.path import Path, charvalues_to_pv
class PathTest(unittest.TestCase):
def setUp(self):
self.paths = {
"empty": Path(()),
"triple": Path(("a", "b", "c")),
"unicode": Path(("東京",)),
}
def test_length(self):
self.assertEqu... | sunburst/tests/test_path.py | import unittest
from sunburst.path import Path, charvalues_to_pv
class PathTest(unittest.TestCase):
def setUp(self):
self.paths = {
"empty": Path(()),
"triple": Path(("a", "b", "c")),
"unicode": Path(("東京",)),
}
def test_length(self):
self.assertEqu... | 0.49585 | 0.620708 |
# file:///C:/Users/DBSpe/Downloads/F00010738-WVS-7_Master_Questionnaire_2017-2020_English.pdf
from .languages import languages
from country_list import countries_for_language
from flask_login import current_user
from hemlock import (
Check, Debug as D, Embedded, Input, Page, RangeInput, Select,
Submit as S,... | hemlock_demographics/__init__.py |
# file:///C:/Users/DBSpe/Downloads/F00010738-WVS-7_Master_Questionnaire_2017-2020_English.pdf
from .languages import languages
from country_list import countries_for_language
from flask_login import current_user
from hemlock import (
Check, Debug as D, Embedded, Input, Page, RangeInput, Select,
Submit as S,... | 0.697094 | 0.731874 |
import requests
import xlsxwriter
from shapely.geometry import Polygon
from shapely.geometry import Point
# Grab Sector from Combine's Web Services
def api_call(query_type, query_id):
headers = {"Accept": "application/json"}
r = requests.get(f'https://www.swcombine.com/ws/v2.0/galaxy/{query_type}/{query_id}',... | lib/mapper.py | import requests
import xlsxwriter
from shapely.geometry import Polygon
from shapely.geometry import Point
# Grab Sector from Combine's Web Services
def api_call(query_type, query_id):
headers = {"Accept": "application/json"}
r = requests.get(f'https://www.swcombine.com/ws/v2.0/galaxy/{query_type}/{query_id}',... | 0.551574 | 0.39129 |
from urllib.request import urlopen
import re
# This is a collection of helper methods used across the various modules.
def is_unsupported_translation(translation):
"""
A helper function to determine if the provided translation code is supported
:param translation: Translation code
:type translation:... | meaningless/utilities/common.py | from urllib.request import urlopen
import re
# This is a collection of helper methods used across the various modules.
def is_unsupported_translation(translation):
"""
A helper function to determine if the provided translation code is supported
:param translation: Translation code
:type translation:... | 0.839832 | 0.519095 |
import degooged_tube.ytApiHacking as ytapih
import degooged_tube.config as cfg
from typing import Union, Tuple
from degooged_tube.subboxChannel import SubBoxChannel, ChannelLoadIssue, loadChannel, callReload
from degooged_tube import getPool
from degooged_tube.helpers import paginationCalculator
class EndOfSubBox(Exc... | degooged_tube/subbox.py | import degooged_tube.ytApiHacking as ytapih
import degooged_tube.config as cfg
from typing import Union, Tuple
from degooged_tube.subboxChannel import SubBoxChannel, ChannelLoadIssue, loadChannel, callReload
from degooged_tube import getPool
from degooged_tube.helpers import paginationCalculator
class EndOfSubBox(Exc... | 0.572245 | 0.222004 |
import os
import re
import sys
import json
import asyncio
import logging
import discord
from config import log_config
from config.config import AppConfig, DiscordBotConfig
from unity_cloud_build_worker import UnityCloudBuildWorker
log_config.setup_logging()
class DiscordBot(discord.Client):
def __init__(self):
... | app/discord_bot.py | import os
import re
import sys
import json
import asyncio
import logging
import discord
from config import log_config
from config.config import AppConfig, DiscordBotConfig
from unity_cloud_build_worker import UnityCloudBuildWorker
log_config.setup_logging()
class DiscordBot(discord.Client):
def __init__(self):
... | 0.339718 | 0.052158 |
import os
import re
# Ambari Commons & Resource Management Imports
from resource_management.core import shell
from resource_management.core.exceptions import Fail
from resource_management.core.logger import Logger
from resource_management.core.resources.system import Execute
from resource_management.libraries.function... | stacks/XIAOMATECH/1.0/services/HIVE/package/scripts/hive_server_upgrade.py | import os
import re
# Ambari Commons & Resource Management Imports
from resource_management.core import shell
from resource_management.core.exceptions import Fail
from resource_management.core.logger import Logger
from resource_management.core.resources.system import Execute
from resource_management.libraries.function... | 0.519034 | 0.118717 |
import os
import markdown
from bs4 import BeautifulSoup
extensions = [ #根据不同教程加上的扩展
'markdown.extensions.extra',
'markdown.extensions.codehilite', #代码高亮扩展
'markdown.extensions.toc',
'markdown.extensions.tables',
'markdown.extensions.fenced_code',
]
config = {
'codehilite': {
'use_pyg... | python-tool/build.py | import os
import markdown
from bs4 import BeautifulSoup
extensions = [ #根据不同教程加上的扩展
'markdown.extensions.extra',
'markdown.extensions.codehilite', #代码高亮扩展
'markdown.extensions.toc',
'markdown.extensions.tables',
'markdown.extensions.fenced_code',
]
config = {
'codehilite': {
'use_pyg... | 0.152821 | 0.081082 |
from typing import (
TYPE_CHECKING, Any, Generic, Iterable, List, Optional, TypeVar, ValuesView,
)
import pandas
from .info import ExchangeInfo
if TYPE_CHECKING:
from monkq.context import Context # pragma: no cover
from monkq.assets.account import BaseAccount # noqa pragma: no cover
from monkq.asse... | monkq/exchange/base/__init__.py | from typing import (
TYPE_CHECKING, Any, Generic, Iterable, List, Optional, TypeVar, ValuesView,
)
import pandas
from .info import ExchangeInfo
if TYPE_CHECKING:
from monkq.context import Context # pragma: no cover
from monkq.assets.account import BaseAccount # noqa pragma: no cover
from monkq.asse... | 0.859487 | 0.327641 |
import os
import astropy.units as u
from astropy.coordinates import SkyCoord
from banzai.stages import Stage
from banzai import logs
class PointingTest(Stage):
"""
A test to determine whether or not the poiting error on the frame
(as determined by a WCS solve) is within tolerance.
"""
# Typical... | banzai/qc/pointing.py | import os
import astropy.units as u
from astropy.coordinates import SkyCoord
from banzai.stages import Stage
from banzai import logs
class PointingTest(Stage):
"""
A test to determine whether or not the poiting error on the frame
(as determined by a WCS solve) is within tolerance.
"""
# Typical... | 0.787972 | 0.342578 |
from prompt_toolkit.buffer import Buffer
from prompt_toolkit.document import Document
from prompt_toolkit.filters import Condition
from prompt_toolkit.layout.containers import Window as PromptWindow
from prompt_toolkit.layout.containers import ConditionalContainer, VSplit, HSplit
from prompt_toolkit.layout.controls im... | window.py |
from prompt_toolkit.buffer import Buffer
from prompt_toolkit.document import Document
from prompt_toolkit.filters import Condition
from prompt_toolkit.layout.containers import Window as PromptWindow
from prompt_toolkit.layout.containers import ConditionalContainer, VSplit, HSplit
from prompt_toolkit.layout.controls im... | 0.496094 | 0.052961 |
class Node:
def __init__(self, key):
self.key = key
self.left = None
self.right = None
def inorder(root):
if root is not None:
inorder(root.left)
print(root.key)
inorder(root.right)
def insert(node, key):
if node is None:
return Node(key)
if... | class-notes/SCSA1304-advanced-data-structures/unit-1/binary-search-tree.py |
class Node:
def __init__(self, key):
self.key = key
self.left = None
self.right = None
def inorder(root):
if root is not None:
inorder(root.left)
print(root.key)
inorder(root.right)
def insert(node, key):
if node is None:
return Node(key)
if... | 0.486575 | 0.324556 |
import optmod
import unittest
import numpy as np
class TestMultiply(unittest.TestCase):
def test_contruction(self):
x = optmod.variable.VariableScalar(name='x')
f = optmod.function.multiply([x, optmod.expression.make_Expression(1.)])
self.assertTrue(isinstance(f, optmod.function.multiply)... | tests/test_multiply.py | import optmod
import unittest
import numpy as np
class TestMultiply(unittest.TestCase):
def test_contruction(self):
x = optmod.variable.VariableScalar(name='x')
f = optmod.function.multiply([x, optmod.expression.make_Expression(1.)])
self.assertTrue(isinstance(f, optmod.function.multiply)... | 0.654122 | 0.757009 |
import caffe
import numpy as np
import progressbar
import datetime
import math
def pycaffe_init_feat(use_gpu, model_prototxt, model_file):
print ('model_prototxt: {}'.format(model_prototxt))
print ('model_file: {}'.format(model_file))
if use_gpu == 0:
caffe.set_mode_cpu()
print ('Using CP... | libs/cvprw15/feat_tools.py |
import caffe
import numpy as np
import progressbar
import datetime
import math
def pycaffe_init_feat(use_gpu, model_prototxt, model_file):
print ('model_prototxt: {}'.format(model_prototxt))
print ('model_file: {}'.format(model_file))
if use_gpu == 0:
caffe.set_mode_cpu()
print ('Using CP... | 0.325842 | 0.287085 |
from Utilities.utilities import build_dbn
import topologia
import dataframe
import argparse
from pprint import pprint
import sys
from validacao import separa_arquivo_json, cria_json_final
import json
import pandas as pd
from datetime import datetime
import traceback
usuario='user'
def callScript(dataset_name, json_do... | Source/rede_dinamica.py | from Utilities.utilities import build_dbn
import topologia
import dataframe
import argparse
from pprint import pprint
import sys
from validacao import separa_arquivo_json, cria_json_final
import json
import pandas as pd
from datetime import datetime
import traceback
usuario='user'
def callScript(dataset_name, json_do... | 0.092693 | 0.143068 |
from datetime import datetime, timedelta
from unittest.mock import Mock
import pytest
from models.dao import Tap
@pytest.fixture
def bucket():
return Mock()
@pytest.fixture
def tap(account, bucket):
return Tap(
description='Test tap',
withdrawer=account,
bucket=bucket,
rate=... | tests/unit/test_tap.py | from datetime import datetime, timedelta
from unittest.mock import Mock
import pytest
from models.dao import Tap
@pytest.fixture
def bucket():
return Mock()
@pytest.fixture
def tap(account, bucket):
return Tap(
description='Test tap',
withdrawer=account,
bucket=bucket,
rate=... | 0.750004 | 0.639398 |
import numpy as np
import healpy as hp
import scipy.optimize as opt
import numpy.polynomial.polynomial as poly
def hp_slices_horizon(nside=None):
"""Healpix pix indices of NS, EW slices and above horizon"""
# theta phi values of each pixel
hp_indices = np.arange(hp.nside2npix(nside))
θ, ɸ = hp.pix2ang... | paper_plots/presentation/null_test_presentation.py | import numpy as np
import healpy as hp
import scipy.optimize as opt
import numpy.polynomial.polynomial as poly
def hp_slices_horizon(nside=None):
"""Healpix pix indices of NS, EW slices and above horizon"""
# theta phi values of each pixel
hp_indices = np.arange(hp.nside2npix(nside))
θ, ɸ = hp.pix2ang... | 0.591251 | 0.627894 |
import automol
import elstruct
import autofile
from mechroutines.es import runner as es_runner
def structure(run_fs, save_fs, locs, job, mod_thy_info,
zma_locs=(0,), in_zma_fs=False, cart_to_zma=False):
""" Save a geometry and associated information from some
electronic structure routine int... | mechlib/filesys/save.py | import automol
import elstruct
import autofile
from mechroutines.es import runner as es_runner
def structure(run_fs, save_fs, locs, job, mod_thy_info,
zma_locs=(0,), in_zma_fs=False, cart_to_zma=False):
""" Save a geometry and associated information from some
electronic structure routine int... | 0.361954 | 0.420243 |
from persistent import Persistent
from zope.container.contained import Contained
from zope.container.ordered import OrderedContainer
from zope.interface import Interface, alsoProvides
from zope.schema.fieldproperty import FieldProperty
from pyams_file.interfaces import IImageFile, IResponsiveImage
from pyams_file.prop... | src/pyams_portal/portlets/carousel/__init__.py | from persistent import Persistent
from zope.container.contained import Contained
from zope.container.ordered import OrderedContainer
from zope.interface import Interface, alsoProvides
from zope.schema.fieldproperty import FieldProperty
from pyams_file.interfaces import IImageFile, IResponsiveImage
from pyams_file.prop... | 0.546496 | 0.170646 |
import requests
from bs4 import BeautifulSoup
import sys
import time
import json
import random
class Page:
def __init__(self, url, title, heading, languages):
self.url = url
self.title = title
self.heading = heading
self.languages = languages
self.languages.append('English')... | crawler_wiki.py | import requests
from bs4 import BeautifulSoup
import sys
import time
import json
import random
class Page:
def __init__(self, url, title, heading, languages):
self.url = url
self.title = title
self.heading = heading
self.languages = languages
self.languages.append('English')... | 0.086869 | 0.100746 |
from ..buildtool import BuildTool
from ..rmstool import RmsTool
from .gemtoolmixin import GemToolMixIn
class puppetTool(GemToolMixIn, BuildTool, RmsTool):
"""Puppet system automation.
Home: https://puppet.com/
Primary purpose is to support Puppet module development.
"""
__slots__ = ()
METADATA_FILE = ... | futoin/cid/tool/puppettool.py |
from ..buildtool import BuildTool
from ..rmstool import RmsTool
from .gemtoolmixin import GemToolMixIn
class puppetTool(GemToolMixIn, BuildTool, RmsTool):
"""Puppet system automation.
Home: https://puppet.com/
Primary purpose is to support Puppet module development.
"""
__slots__ = ()
METADATA_FILE = ... | 0.391871 | 0.10235 |
import cloudinary.uploader
from django.contrib.auth.mixins import LoginRequiredMixin
from django.shortcuts import redirect
from django.urls import reverse_lazy
from django.views import generic as generic_views
from mytravelblog.main_app.forms.travel_picture import *
from mytravelblog.main_app.models import *
class T... | mytravelblog/main_app/views/picture.py | import cloudinary.uploader
from django.contrib.auth.mixins import LoginRequiredMixin
from django.shortcuts import redirect
from django.urls import reverse_lazy
from django.views import generic as generic_views
from mytravelblog.main_app.forms.travel_picture import *
from mytravelblog.main_app.models import *
class T... | 0.41834 | 0.06724 |
import glob
import os, losses, utils
from torch.utils.data import DataLoader
from data import datasets, trans
import numpy as np
import torch
from torchvision import transforms
import matplotlib.pyplot as plt
from natsort import natsorted
from models.TransMorph import CONFIGS as CONFIGS_TM
import models.Trans... | RaFD/TransMorph2D/infer_TransMorph.py | import glob
import os, losses, utils
from torch.utils.data import DataLoader
from data import datasets, trans
import numpy as np
import torch
from torchvision import transforms
import matplotlib.pyplot as plt
from natsort import natsorted
from models.TransMorph import CONFIGS as CONFIGS_TM
import models.Trans... | 0.411939 | 0.2714 |