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 rest_client from xml.etree import ElementTree as et class ModelManager(object): """Handles what can be queried for, and acts as the entry point for querying. There is an instance per model that is used in the django style of Model.objects.get(attr1=value, attr2=value2) for single results, or Model....
common_models/common_models.py
import rest_client from xml.etree import ElementTree as et class ModelManager(object): """Handles what can be queried for, and acts as the entry point for querying. There is an instance per model that is used in the django style of Model.objects.get(attr1=value, attr2=value2) for single results, or Model....
0.624866
0.237698
from unittest import TestCase from json_payload_validator import validate class TestValidator(TestCase): """ To run the tests use: python setup.py test """ flat_schema = { 'type': 'object', 'properties': { 'name': {'type': 'string'}, 'surname': {'type': 'string...
json_payload_validator/tests/test_validator.py
from unittest import TestCase from json_payload_validator import validate class TestValidator(TestCase): """ To run the tests use: python setup.py test """ flat_schema = { 'type': 'object', 'properties': { 'name': {'type': 'string'}, 'surname': {'type': 'string...
0.796292
0.471588
import angr def main(): project= angr.Project("./CADET_00001") #let's find the buffer overflow (overwriting the return address) #overwriting the return pointer with user-controllable data will generate #an "unconstrained" state: the symbolic executor does not know how to proceed #since the instru...
examples/CADET_00001/solve.py
import angr def main(): project= angr.Project("./CADET_00001") #let's find the buffer overflow (overwriting the return address) #overwriting the return pointer with user-controllable data will generate #an "unconstrained" state: the symbolic executor does not know how to proceed #since the instru...
0.315947
0.525125
from my_other_module.parsing_functions import tsv_to_d2_list #FILENAMES ----------------------------------- #CHECK - might have /app after module #Pathways_File_Name = '/kb/module/data/KEGG_pathways.tsv' #END OF FILENAMES ----------------------------- #main_cp returns a d3 list of lists to be printed to a file. ...
lib/my_other_module/Check_Pathway/check_pathways_vs_reactions.py
from my_other_module.parsing_functions import tsv_to_d2_list #FILENAMES ----------------------------------- #CHECK - might have /app after module #Pathways_File_Name = '/kb/module/data/KEGG_pathways.tsv' #END OF FILENAMES ----------------------------- #main_cp returns a d3 list of lists to be printed to a file. ...
0.395251
0.324289
import json from http import HTTPStatus from typing import Dict, Set from mock_vws._database_matchers import get_database_matching_server_keys from mock_vws._services_validators.exceptions import ( Fail, OopsErrorOccurredResponse, TargetNameExist, ) from mock_vws.database import VuforiaDatabase def valid...
src/mock_vws/_services_validators/name_validators.py
import json from http import HTTPStatus from typing import Dict, Set from mock_vws._database_matchers import get_database_matching_server_keys from mock_vws._services_validators.exceptions import ( Fail, OopsErrorOccurredResponse, TargetNameExist, ) from mock_vws.database import VuforiaDatabase def valid...
0.879393
0.2328
from classes import node def huffmanCompress(input): output = "" freqTable = [] for i in range(0, 256): freqTable.append([i, 0]) for i in range(0, len(input), 2): byteInHex = input[i:i+2] byteInDec = int(byteInHex, 16) freqTable[byteInDec][1] += 1 ...
larkstongue/compress/huffman.py
from classes import node def huffmanCompress(input): output = "" freqTable = [] for i in range(0, 256): freqTable.append([i, 0]) for i in range(0, len(input), 2): byteInHex = input[i:i+2] byteInDec = int(byteInHex, 16) freqTable[byteInDec][1] += 1 ...
0.246443
0.315439
import os, logging, sys import logging.handlers from logging import raiseExceptions, Logger LOG_PATH = os.getcwd()+'/logging' class AppLogger(Logger): """ 自定义logger 如果handler名称为console表示在终端打印所有大于等于设置级别的日志 其他handler则只记录等于设置级别的日志 """ def __init__(self, name, level=logging.NOTSET): super(AppLogger, self).__init...
log.py
import os, logging, sys import logging.handlers from logging import raiseExceptions, Logger LOG_PATH = os.getcwd()+'/logging' class AppLogger(Logger): """ 自定义logger 如果handler名称为console表示在终端打印所有大于等于设置级别的日志 其他handler则只记录等于设置级别的日志 """ def __init__(self, name, level=logging.NOTSET): super(AppLogger, self).__init...
0.053663
0.074905
from commonse.config import * from openmdao.main.api import Component, Assembly from openmdao.main.datatypes.api import Array, Float, Bool, Int from math import pi import numpy as np from fusedwind.plant_cost.fused_tcc import FullRotorCostModel, FullRotorCostAggregator, FullHubSystemCostAggregator, BaseComponentCostMo...
src/turbine_costsse/turbine_costsse/rotor_costsse.py
from commonse.config import * from openmdao.main.api import Component, Assembly from openmdao.main.datatypes.api import Array, Float, Bool, Int from math import pi import numpy as np from fusedwind.plant_cost.fused_tcc import FullRotorCostModel, FullRotorCostAggregator, FullHubSystemCostAggregator, BaseComponentCostMo...
0.707809
0.245695
import sys import pysam import subprocess from re import sub import os from itertools import izip bamsortfn = sys.argv[1] bamrepairedfn = sub('.sorted.bam$', ".repaired.bam", bamsortfn) bamrepairedsortfn = sub('.sorted.bam$', ".repaired.sorted.bam", bamsortfn) if(os.path.isfile(bamsortfn)): inbam = pysam.Samfi...
src/qsub/ruffus/re-pair.py
import sys import pysam import subprocess from re import sub import os from itertools import izip bamsortfn = sys.argv[1] bamrepairedfn = sub('.sorted.bam$', ".repaired.bam", bamsortfn) bamrepairedsortfn = sub('.sorted.bam$', ".repaired.sorted.bam", bamsortfn) if(os.path.isfile(bamsortfn)): inbam = pysam.Samfi...
0.045788
0.222806
import pickle from uuid import uuid4 class KeyValueStoreAPI(object): def __init__(self): self.kvstore = {} self.identifier = None def __del__(self): del self.kvstore def set_identifier(self, class_): self.identifier = class_.__name__ + '/' + str(uuid4()) + '/' def ca...
api/data/kvs.py
import pickle from uuid import uuid4 class KeyValueStoreAPI(object): def __init__(self): self.kvstore = {} self.identifier = None def __del__(self): del self.kvstore def set_identifier(self, class_): self.identifier = class_.__name__ + '/' + str(uuid4()) + '/' def ca...
0.451568
0.06885
from MILpy.functions.bagprob import bagprob from MILpy.functions.maxdd2 import maxdd import numpy as np from numpy import inf from sklearn.linear_model import LogisticRegression class maxDD(object): def __init__(self): self._spoints = None self._epochs = None self._frac = None ...
Algorithms/maxDD.py
from MILpy.functions.bagprob import bagprob from MILpy.functions.maxdd2 import maxdd import numpy as np from numpy import inf from sklearn.linear_model import LogisticRegression class maxDD(object): def __init__(self): self._spoints = None self._epochs = None self._frac = None ...
0.683736
0.408867
import sys,os from sklearn.cluster import KMeans from sklearn.decomposition import PCA import pandas as pd import numpy as np import matplotlib.pyplot as plt import math # 对词向量采用K-means聚类抽取TopK关键词 def getkeywords_kmeans(data,topK): words = data["word"] # 词汇 vecs = data.ix[:,1:] # 向量表示 kmeans ...
helper/keyword_extraction/keyextract_word2vec_2.py
import sys,os from sklearn.cluster import KMeans from sklearn.decomposition import PCA import pandas as pd import numpy as np import matplotlib.pyplot as plt import math # 对词向量采用K-means聚类抽取TopK关键词 def getkeywords_kmeans(data,topK): words = data["word"] # 词汇 vecs = data.ix[:,1:] # 向量表示 kmeans ...
0.068928
0.395018
from phycas.utilities.PhycasCommand import * from phycas.utilities.CommonFunctions import CommonFunctions from phycas.commands.CPOImpl import CPOImpl from phycas import mcmc class CPO(PhycasCommand): def __init__(self): args = (("patterns_only", False, "If True, each row of the sitelike output file will co...
src/python/commands/CPO.py
from phycas.utilities.PhycasCommand import * from phycas.utilities.CommonFunctions import CommonFunctions from phycas.commands.CPOImpl import CPOImpl from phycas import mcmc class CPO(PhycasCommand): def __init__(self): args = (("patterns_only", False, "If True, each row of the sitelike output file will co...
0.793186
0.284073
from discord.ext import commands import discord import functions as fnc import psycopg2 import os from cogs.help import get_help_match # 本番用テキストチャンネル CHANNEL_ID = int(os.environ["PERFORMANCE_CHANNEL"]) # ログ管理用クローズドチャンネル TEST_ID = int(os.environ["TEST_CHANNEL"]) # 投稿権限を持つユーザー SCORER_USER = int(os.environ["SCORER"]) c...
cogs/match.py
from discord.ext import commands import discord import functions as fnc import psycopg2 import os from cogs.help import get_help_match # 本番用テキストチャンネル CHANNEL_ID = int(os.environ["PERFORMANCE_CHANNEL"]) # ログ管理用クローズドチャンネル TEST_ID = int(os.environ["TEST_CHANNEL"]) # 投稿権限を持つユーザー SCORER_USER = int(os.environ["SCORER"]) c...
0.138316
0.229373
import os import random class Node: """ >>> lonely_node = Node(None) >>> lonely_node.metadata = [2, 3] >>> lonely_node.compute_meta_value() 5 >>> lonely_node.get_test_string() '0 2 2 3' >>> child_one = Node(lonely_node) >>> child_one.metadata = [41, 5, 1] >>> child_one.compute_...
src/day8/day8.py
import os import random class Node: """ >>> lonely_node = Node(None) >>> lonely_node.metadata = [2, 3] >>> lonely_node.compute_meta_value() 5 >>> lonely_node.get_test_string() '0 2 2 3' >>> child_one = Node(lonely_node) >>> child_one.metadata = [41, 5, 1] >>> child_one.compute_...
0.595257
0.531696
import syntaxhighlight import syntaxhighlight.clexer import htmlutils import configuration class HighlightCPP: def highlightToken(self, token): if token.iskeyword(): self.output.write("<b class='kw'>" + str(token) + "</b>") elif token.isidentifier(): self.output.write("<b c...
src/syntaxhighlight/cpp.py
import syntaxhighlight import syntaxhighlight.clexer import htmlutils import configuration class HighlightCPP: def highlightToken(self, token): if token.iskeyword(): self.output.write("<b class='kw'>" + str(token) + "</b>") elif token.isidentifier(): self.output.write("<b c...
0.38445
0.111121
import numpy as np from bnet.env import ConcurrentSchedule from hbtfmt.model import SarsaAgent from hbtfmt.util import to_onehot def train_under_variable_interval(agent: SarsaAgent, env: ConcurrentSchedule): n, _ = agent.weights.shape # make the value of rewards uniform so that the agent explores randomly ...
hbtfmt/sims/sarsa_variable_interval.py
import numpy as np from bnet.env import ConcurrentSchedule from hbtfmt.model import SarsaAgent from hbtfmt.util import to_onehot def train_under_variable_interval(agent: SarsaAgent, env: ConcurrentSchedule): n, _ = agent.weights.shape # make the value of rewards uniform so that the agent explores randomly ...
0.717903
0.281742
import json import os from dusty import constants from dusty.data_model.canonical_model import DefaultModel as Finding __author__ = 'KarynaTaranova' class NpmScanParser(object): def __init__(self, filename, test, deps): dupes = dict() find_date = None self.items = [] if not os....
dusty/data_model/npm/parser.py
import json import os from dusty import constants from dusty.data_model.canonical_model import DefaultModel as Finding __author__ = 'KarynaTaranova' class NpmScanParser(object): def __init__(self, filename, test, deps): dupes = dict() find_date = None self.items = [] if not os....
0.22093
0.091707
import os from com.microsoft.azure.management.websites.models import SkuOptions, WorkerSizeOptions, DatabaseServerType class CiStub(object): def getProperty(self, name): return self.__dict__[name] def setProperty(self, name, value): self.__dict__[name] = value class SubscriptionCi(CiStub)...
src/test/jython/itests/__init__.py
import os from com.microsoft.azure.management.websites.models import SkuOptions, WorkerSizeOptions, DatabaseServerType class CiStub(object): def getProperty(self, name): return self.__dict__[name] def setProperty(self, name, value): self.__dict__[name] = value class SubscriptionCi(CiStub)...
0.416085
0.045374
from collections import OrderedDict import numpy as np def get_vocab(text): """Get all tokens""" vocab = OrderedDict() i = 0 for word in text: if word not in vocab: vocab[word] = i i += 1 return vocab def get_token_pairs(window_size, text): """Build token_pai...
util/textrank.py
from collections import OrderedDict import numpy as np def get_vocab(text): """Get all tokens""" vocab = OrderedDict() i = 0 for word in text: if word not in vocab: vocab[word] = i i += 1 return vocab def get_token_pairs(window_size, text): """Build token_pai...
0.730001
0.3694
from __future__ import print_function import json from datetime import datetime from model import * __author__ = '<NAME>' def load_json(file): jsonfile = open(file) data = json.load(jsonfile) jsonfile.close() return data def load_members(data): members = [] for fullname in data: m...
rhythmunity/rhythmunity.py
from __future__ import print_function import json from datetime import datetime from model import * __author__ = '<NAME>' def load_json(file): jsonfile = open(file) data = json.load(jsonfile) jsonfile.close() return data def load_members(data): members = [] for fullname in data: m...
0.319121
0.277134
from pickle import loads, dumps import numpy as np import pandas as pd from classicML import _cml_precision from classicML import CLASSICML_LOGGER from classicML.api.models import BaseModel from classicML.backend import type_of_target from classicML.backend import get_conditional_probability from classicML.backend im...
classicML/api/models/bayes/naive_bayes_classifier.py
from pickle import loads, dumps import numpy as np import pandas as pd from classicML import _cml_precision from classicML import CLASSICML_LOGGER from classicML.api.models import BaseModel from classicML.backend import type_of_target from classicML.backend import get_conditional_probability from classicML.backend im...
0.641759
0.406214
from django.db import models from django.core.exceptions import FieldError from django.conf import settings from django.utils.translation import ugettext_lazy as _ from django import forms from django.forms.models import BaseInlineFormSet from django.template.loader import render_to_string from utils.forms import Boot...
src/utils/localized.py
from django.db import models from django.core.exceptions import FieldError from django.conf import settings from django.utils.translation import ugettext_lazy as _ from django import forms from django.forms.models import BaseInlineFormSet from django.template.loader import render_to_string from utils.forms import Boot...
0.470493
0.0538
import sys, re import execlib as ex import dbglib as dbg import common, subprocess class HostConfig: def __init__(self, hname, ifname, nwname): self.host_name = hname self.if_name = ifname self.nw_name = nwname class ContainerConfig: def __init__(self, hname, name, image): self...
src/lib/dockerlib.py
import sys, re import execlib as ex import dbglib as dbg import common, subprocess class HostConfig: def __init__(self, hname, ifname, nwname): self.host_name = hname self.if_name = ifname self.nw_name = nwname class ContainerConfig: def __init__(self, hname, name, image): self...
0.21428
0.05951
from datetime import datetime, timedelta import json import os import pandas as pd import numpy as np from collections import OrderedDict from thetae.util import Daily, Forecast, last_leap_year from thetae.db import readForecast, readTimeSeries, readDaily from thetae import MissingDataError def json_daily(config, sti...
thetae/web/web_json.py
from datetime import datetime, timedelta import json import os import pandas as pd import numpy as np from collections import OrderedDict from thetae.util import Daily, Forecast, last_leap_year from thetae.db import readForecast, readTimeSeries, readDaily from thetae import MissingDataError def json_daily(config, sti...
0.475362
0.236241
import os, sys, getopt from pesky.settings.store import Store from pesky.settings.errors import ConfigureError class OptionParser(object): """ :param parent: :type parent: :class:`BaseOptionParser` :param name: :type name: str :param usage: :type usage: str :param description: :ty...
pesky/settings/optionparser.py
import os, sys, getopt from pesky.settings.store import Store from pesky.settings.errors import ConfigureError class OptionParser(object): """ :param parent: :type parent: :class:`BaseOptionParser` :param name: :type name: str :param usage: :type usage: str :param description: :ty...
0.524395
0.105257
from msrest.service_client import SDKClient from msrest import Serializer, Deserializer from ._configuration import AzureMediaServicesConfiguration from .operations import AccountFiltersOperations from .operations import Operations from .operations import MediaservicesOperations from .operations import LocationsOpera...
sdk/media/azure-mgmt-media/azure/mgmt/media/_azure_media_services.py
from msrest.service_client import SDKClient from msrest import Serializer, Deserializer from ._configuration import AzureMediaServicesConfiguration from .operations import AccountFiltersOperations from .operations import Operations from .operations import MediaservicesOperations from .operations import LocationsOpera...
0.862105
0.085061
import pytest from visma.api import VismaAPIException, VismaClientException from visma.models import Customer, TermsOfPayment, CustomerInvoiceDraft class TestCRUDCustomer: customer_number = 'test_customer' customer_id = None def test_create_customer(self): """ Create a customer ...
tests/integration/test_integration_customers.py
import pytest from visma.api import VismaAPIException, VismaClientException from visma.models import Customer, TermsOfPayment, CustomerInvoiceDraft class TestCRUDCustomer: customer_number = 'test_customer' customer_id = None def test_create_customer(self): """ Create a customer ...
0.357455
0.286185
import json class ReplyMarkup(object): def dict(self): raise NotImplementedError() def json(self): return json.dumps(self.dict()) def __str__(self): return str(self.dict()) class ReplyKeyboardMarkup(ReplyMarkup): def __init__(self, buttons = [], resize_keyboard = False, one_t...
tgbot/reply_markup.py
import json class ReplyMarkup(object): def dict(self): raise NotImplementedError() def json(self): return json.dumps(self.dict()) def __str__(self): return str(self.dict()) class ReplyKeyboardMarkup(ReplyMarkup): def __init__(self, buttons = [], resize_keyboard = False, one_t...
0.506591
0.139045
import argparse import logging import os from credentialdigger import PgClient, SqliteClient from dotenv import load_dotenv from . import (add_rules, get_discoveries, scan, scan_path, scan_snapshot, scan_user, scan_wiki) logger = logging.getLogger(__name__) class customParser(argparse.ArgumentParser...
credentialdigger/cli/cli.py
import argparse import logging import os from credentialdigger import PgClient, SqliteClient from dotenv import load_dotenv from . import (add_rules, get_discoveries, scan, scan_path, scan_snapshot, scan_user, scan_wiki) logger = logging.getLogger(__name__) class customParser(argparse.ArgumentParser...
0.391639
0.092115
from abc import ABC, abstractmethod from typing import Dict, Any class ProcessingUnitPowerModel(ABC): def __init__(self, **kwargs): """ Processing Unit power model :param kwargs: additional configuration parameters """ pass @abstractmethod def compute_power(self, s...
mercury/plugin/edc/pu_pwr.py
from abc import ABC, abstractmethod from typing import Dict, Any class ProcessingUnitPowerModel(ABC): def __init__(self, **kwargs): """ Processing Unit power model :param kwargs: additional configuration parameters """ pass @abstractmethod def compute_power(self, s...
0.950589
0.569404
import orionsdk from orionsdk import SwisClient import requests import csv #input access getCredentials npm_server = '10.248.1.106' username = 'admin' password = '' OutputFileName = 'output.csv' #This is needed if SSL is not setup. verify = False if not verify: from requests.packages.urllib3.exceptions import Inse...
orionAPI.py
import orionsdk from orionsdk import SwisClient import requests import csv #input access getCredentials npm_server = '10.248.1.106' username = 'admin' password = '' OutputFileName = 'output.csv' #This is needed if SSL is not setup. verify = False if not verify: from requests.packages.urllib3.exceptions import Inse...
0.131647
0.105211
import numpy as np import matplotlib.pyplot as plt from matplotlib import cm from sklearn.metrics import silhouette_samples from data_processing import dataUtils from sklearn.cluster import KMeans from sklearn import preprocessing from scipy import stats import pandas as pd import data_processing.MulticlusteringExperim...
clustering/silhouette.py
import numpy as np import matplotlib.pyplot as plt from matplotlib import cm from sklearn.metrics import silhouette_samples from data_processing import dataUtils from sklearn.cluster import KMeans from sklearn import preprocessing from scipy import stats import pandas as pd import data_processing.MulticlusteringExperim...
0.514888
0.493714
import robel import gym import argparse import numpy as np import pandas as pd import torch import time from tqc import DEVICE from tqc.structures import Actor, RescaleAction if __name__ == '__main__': parser = argparse.ArgumentParser() parser.add_argument('--model', default='models/no_field_10_degree_DKittyWa...
test_env.py
import robel import gym import argparse import numpy as np import pandas as pd import torch import time from tqc import DEVICE from tqc.structures import Actor, RescaleAction if __name__ == '__main__': parser = argparse.ArgumentParser() parser.add_argument('--model', default='models/no_field_10_degree_DKittyWa...
0.546738
0.22414
import warnings import geomstats.backend as gs import geomstats.tests import tests.helper as helper from geomstats.spd_matrices_space import SPDMatricesSpace class TestSPDMatricesSpaceMethods(geomstats.tests.TestCase): _multiprocess_can_split_ = True def setUp(self): warnings.simplefilter('ignore',...
tests/test_spd_matrices_space.py
import warnings import geomstats.backend as gs import geomstats.tests import tests.helper as helper from geomstats.spd_matrices_space import SPDMatricesSpace class TestSPDMatricesSpaceMethods(geomstats.tests.TestCase): _multiprocess_can_split_ = True def setUp(self): warnings.simplefilter('ignore',...
0.745584
0.649328
import json import os import random from lib.Command import register_command from lib.Message import Message GAME_PLAYERS = None SPYFALL_FILE = os.path.join('json', 'spyfall.json') @register_command(lambda m: m.content.startswith('/spyfall')) async def spyfall(bot, message): """``` Starts a clone of the gam...
lib/Spyfall.py
import json import os import random from lib.Command import register_command from lib.Message import Message GAME_PLAYERS = None SPYFALL_FILE = os.path.join('json', 'spyfall.json') @register_command(lambda m: m.content.startswith('/spyfall')) async def spyfall(bot, message): """``` Starts a clone of the gam...
0.564819
0.466238
from __future__ import unicode_literals from django import template from django.utils.html import escape from django.utils.safestring import mark_safe from ..compat import parse_bits from ..cachefiles import ImageCacheFile from ..registry import generator_registry from ..lib import force_text register = template.Li...
virtual/lib/python3.6/site-packages/imagekit/templatetags/imagekit.py
from __future__ import unicode_literals from django import template from django.utils.html import escape from django.utils.safestring import mark_safe from ..compat import parse_bits from ..cachefiles import ImageCacheFile from ..registry import generator_registry from ..lib import force_text register = template.Li...
0.685529
0.127462
import argparse from queue import Queue from typing import Any, Optional from src.file_syncer.main.dir_reader.dir_change_event_api import ( DirChangeEventApi, DirChangeEventQueue, ) from src.file_syncer.main.dir_reader.dir_reader_ctrl import DirReaderCtrl from src.file_syncer.main.dir_reader.file_model import F...
src/file_syncer/main/main.py
import argparse from queue import Queue from typing import Any, Optional from src.file_syncer.main.dir_reader.dir_change_event_api import ( DirChangeEventApi, DirChangeEventQueue, ) from src.file_syncer.main.dir_reader.dir_reader_ctrl import DirReaderCtrl from src.file_syncer.main.dir_reader.file_model import F...
0.718693
0.051821
import json import pytest from datetime import timedelta from app.config import settings from app.schemas.game_schemas import NewGamePostRequest @pytest.mark.asyncio async def test_stored_game(app_with_game_tables, authorization_fixture): token = authorization_fixture.create_access_token( subject="test_...
tests/test_game/test_start.py
import json import pytest from datetime import timedelta from app.config import settings from app.schemas.game_schemas import NewGamePostRequest @pytest.mark.asyncio async def test_stored_game(app_with_game_tables, authorization_fixture): token = authorization_fixture.create_access_token( subject="test_...
0.448668
0.300579
import ujson import serviceMongoClient import asyncio import serviceAsyncHttpReqeust from multiprocessing import Process import datetime import aiofiles class ParsingYoutubeChannelId(): googleApiKey = "apikey" def __init__(self): self.db = serviceMongoClient.ServiceMongoClient().getDB() self...
dataHandling/parsingYoutubeChannelId.py
import ujson import serviceMongoClient import asyncio import serviceAsyncHttpReqeust from multiprocessing import Process import datetime import aiofiles class ParsingYoutubeChannelId(): googleApiKey = "apikey" def __init__(self): self.db = serviceMongoClient.ServiceMongoClient().getDB() self...
0.335351
0.085442
import os import shutil from ievv_opensource.utils.ievvbuildstatic import pluginbase class Plugin(pluginbase.Plugin): # Copy specified files from staticsources/<packagename>/node_modules/foo/bar/<libfile>.js to static/<packagename>/<version>/node_modules/<libfile>.js def __init__(self, sour...
ievv_opensource/utils/ievvbuildstatic/nodemodulescopy.py
import os import shutil from ievv_opensource.utils.ievvbuildstatic import pluginbase class Plugin(pluginbase.Plugin): # Copy specified files from staticsources/<packagename>/node_modules/foo/bar/<libfile>.js to static/<packagename>/<version>/node_modules/<libfile>.js def __init__(self, sour...
0.19521
0.061763
from base64 import b64decode, b64encode from enum import Enum from inspect import getmembers, ismethod from .constants import * def _create_string_attribute(value): return { 'DataType': 'String', 'StringValue': str(value) } def _get_string_attribute(value): assert value['DataType'] == 'String' retu...
src/sqs_java_messaging/message.py
from base64 import b64decode, b64encode from enum import Enum from inspect import getmembers, ismethod from .constants import * def _create_string_attribute(value): return { 'DataType': 'String', 'StringValue': str(value) } def _get_string_attribute(value): assert value['DataType'] == 'String' retu...
0.637144
0.200519
from predict import container_predict from skimage.io import imread from glob import glob import numpy as np from PIL import Image import uuid import os TOKEN_TEMPLATE = imread("./token_template.png") TEMPLATE_COLOR = np.empty((280,280,4)) TEMPLATE_COLOR[:,:,0] = 254 TEMPLATE_COLOR[:,:,1] = 0 TEMPLATE_COLOR[:,:,2] = 2...
app_engine/token_creator.py
from predict import container_predict from skimage.io import imread from glob import glob import numpy as np from PIL import Image import uuid import os TOKEN_TEMPLATE = imread("./token_template.png") TEMPLATE_COLOR = np.empty((280,280,4)) TEMPLATE_COLOR[:,:,0] = 254 TEMPLATE_COLOR[:,:,1] = 0 TEMPLATE_COLOR[:,:,2] = 2...
0.244634
0.207958
import torch.utils.data import numpy as np import torch.nn.functional as F import json import matplotlib.pyplot as plt import os, sys, argparse, zipfile, glob, random, pickle, cv2, math from itertools import groupby FileDirPath = os.path.dirname(os.path.realpath(__file__)) sys.path.append(os.path.join(FileDirPath, '.....
tk3dv/ptTools/loaders/GenericImageDataset.py
import torch.utils.data import numpy as np import torch.nn.functional as F import json import matplotlib.pyplot as plt import os, sys, argparse, zipfile, glob, random, pickle, cv2, math from itertools import groupby FileDirPath = os.path.dirname(os.path.realpath(__file__)) sys.path.append(os.path.join(FileDirPath, '.....
0.635901
0.359252
from difflib import SequenceMatcher from abc import abstractmethod, ABCMeta import cloudpickle import numpy as np import pandas as pd from sklearn.model_selection import ParameterGrid from sklearn.utils import check_scalar def _cols(x): return [f'{col}_team{x}' for col in ('home', 'away')] def _create_names_ma...
sportsbet/datasets/_base.py
from difflib import SequenceMatcher from abc import abstractmethod, ABCMeta import cloudpickle import numpy as np import pandas as pd from sklearn.model_selection import ParameterGrid from sklearn.utils import check_scalar def _cols(x): return [f'{col}_team{x}' for col in ('home', 'away')] def _create_names_ma...
0.891835
0.421492
import ipaddress from pcapkit.const.reg.transtype import TransType as TP_PROTO __all__ = [ 'ipv6_hdr_len', 'packet2chain', 'packet2dict', 'ipv4_reassembly', 'ipv6_reassembly', 'tcp_reassembly', 'tcp_traceflow' ] def ipv6_hdr_len(ipv6): """Calculate length of headers before IPv6 Fragment header. Arg...
pcapkit/toolkit/dpkt.py
import ipaddress from pcapkit.const.reg.transtype import TransType as TP_PROTO __all__ = [ 'ipv6_hdr_len', 'packet2chain', 'packet2dict', 'ipv4_reassembly', 'ipv6_reassembly', 'tcp_reassembly', 'tcp_traceflow' ] def ipv6_hdr_len(ipv6): """Calculate length of headers before IPv6 Fragment header. Arg...
0.79854
0.270827
import torch as th import torch.nn as nn from typing import Tuple, List from memonger import SublinearSequential from libs.conv_stft import ConvSTFT, ConviSTFT def param(nnet, Mb=True): """ Return number parameters(not bytes) in nnet """ neles = sum([param.nelement() for param in nnet.parameters()])...
nnet_dpccn.py
import torch as th import torch.nn as nn from typing import Tuple, List from memonger import SublinearSequential from libs.conv_stft import ConvSTFT, ConviSTFT def param(nnet, Mb=True): """ Return number parameters(not bytes) in nnet """ neles = sum([param.nelement() for param in nnet.parameters()])...
0.94843
0.49347
import premailer from django.conf import settings from django.contrib.sites.models import Site from django.core.mail import EmailMultiAlternatives, mail_admins, mail_managers from django.template import Context, TemplateDoesNotExist from django.template.loader import render_to_string from django.utils import translatio...
myenv/lib/python2.7/site-packages/emailit/api.py
import premailer from django.conf import settings from django.contrib.sites.models import Site from django.core.mail import EmailMultiAlternatives, mail_admins, mail_managers from django.template import Context, TemplateDoesNotExist from django.template.loader import render_to_string from django.utils import translatio...
0.389663
0.106133
import pickle import os import numpy as np import matplotlib.pyplot as plt from PIL import Image from torch.utils.data import Dataset class CIFAR10(Dataset): def __init__(self,root,train=True,transforms=None): self.root = root self.transforms = transforms self.split = train...
dataset.py
import pickle import os import numpy as np import matplotlib.pyplot as plt from PIL import Image from torch.utils.data import Dataset class CIFAR10(Dataset): def __init__(self,root,train=True,transforms=None): self.root = root self.transforms = transforms self.split = train...
0.483892
0.212477
import numpy as np import pandas as pd ex_dual_mot = ['sub-13', 'sub-21', 'sub-23', 'sub-50'] # Higly motion subjects in one of four sessions ex_rest_mot = ['sub-21', 'sub-46', 'sub-47'] # Higly motion subjects in one of four sessions / missing data(20-44) ex_rest_mis = ['sub-20', 'sub-44'] # Missing data in resting (...
03-static_FC_analyses/load_data.py
import numpy as np import pandas as pd ex_dual_mot = ['sub-13', 'sub-21', 'sub-23', 'sub-50'] # Higly motion subjects in one of four sessions ex_rest_mot = ['sub-21', 'sub-46', 'sub-47'] # Higly motion subjects in one of four sessions / missing data(20-44) ex_rest_mis = ['sub-20', 'sub-44'] # Missing data in resting (...
0.209308
0.235702
from .base import DownloadController import requests from ..database import CachedRequest, ScheduledDownloadJob, ResourceNamespace, Resource import random import datetime import json class WallhavenController(DownloadController): """ Class representing the API for https://wallhaven.cc/. """ def __init...
src/download/wallhaven.py
from .base import DownloadController import requests from ..database import CachedRequest, ScheduledDownloadJob, ResourceNamespace, Resource import random import datetime import json class WallhavenController(DownloadController): """ Class representing the API for https://wallhaven.cc/. """ def __init...
0.426202
0.070176
"""Tests for views on collections.""" # pylint: disable=no-self-use # pylint: disable=missing-function-docstring from vertizee.classes.collection_views import ItemsView, ListView, SetView class TestCollectionViews: """Tests for functions defined in the collection_views module.""" def test_items_view(self) ...
vertizee/classes/tests/test_collection_views.py
"""Tests for views on collections.""" # pylint: disable=no-self-use # pylint: disable=missing-function-docstring from vertizee.classes.collection_views import ItemsView, ListView, SetView class TestCollectionViews: """Tests for functions defined in the collection_views module.""" def test_items_view(self) ...
0.892732
0.679433
from typing import List import logging, copy from .classes import Params, LightCurve from .plotting import COLORS from scipy import stats import numpy as np from astroquery.nasa_exoplanet_archive import NasaExoplanetArchive import emcee, batman import matplotlib.pyplot as plt from matplotlib import ticker from tqdm i...
exotx/models.py
from typing import List import logging, copy from .classes import Params, LightCurve from .plotting import COLORS from scipy import stats import numpy as np from astroquery.nasa_exoplanet_archive import NasaExoplanetArchive import emcee, batman import matplotlib.pyplot as plt from matplotlib import ticker from tqdm i...
0.64713
0.318035
import sys sys.path.insert(0, '../') import unittest from collections import OrderedDict from map_parser import MapParser class TestMapParser(unittest.TestCase): def setUp(self): self.s1 = MapParser('../examples/Niko - Made of Fire (lesjuh) [Oni].osu') self.s2 = MapParser("../examples/TERRASPEX...
osu_map_parser/test/test_parse_standard_map.py
import sys sys.path.insert(0, '../') import unittest from collections import OrderedDict from map_parser import MapParser class TestMapParser(unittest.TestCase): def setUp(self): self.s1 = MapParser('../examples/Niko - Made of Fire (lesjuh) [Oni].osu') self.s2 = MapParser("../examples/TERRASPEX...
0.411702
0.405979
import discord from discord.ext import commands import asyncio import datetime import time from typing import Optional, Union from parsedatetime import Calendar, VERSION_CONTEXT_STYLE from modules import conversions from utilities import checks ACTIVITES = { "Betrayal.io": 773336526917861400, "Checkers In The Par...
Discord/cogs/discord.py
import discord from discord.ext import commands import asyncio import datetime import time from typing import Optional, Union from parsedatetime import Calendar, VERSION_CONTEXT_STYLE from modules import conversions from utilities import checks ACTIVITES = { "Betrayal.io": 773336526917861400, "Checkers In The Par...
0.324449
0.182207
import time import random # 高速行情接口 def get_random(): return random.randint(1000000000000,9999999999999) URL_QUOTATION = lambda symbols: "http://hq.sinajs.cn/?rn=%s&list=%s" % ( int( time.time() )*1000, symbols ) SINA_QUOTE_COLUMNS = [ 'name', 'open' , 'pre_close', 'price', 'high', 'low', 'bid', 'ask', 'volume'...
dHydra/Vendor/Sina/connection.py
import time import random # 高速行情接口 def get_random(): return random.randint(1000000000000,9999999999999) URL_QUOTATION = lambda symbols: "http://hq.sinajs.cn/?rn=%s&list=%s" % ( int( time.time() )*1000, symbols ) SINA_QUOTE_COLUMNS = [ 'name', 'open' , 'pre_close', 'price', 'high', 'low', 'bid', 'ask', 'volume'...
0.13852
0.106691
import os, httplib, mimetypes, mimetools from utils import fsys body='' cj = cookielib.CookieJar() opener = urllib2.build_opener(urllib2.HTTPCookieProcessor(cj)) urllib2.install_opener(opener) def post_multipart(url, fields, files=[]): """ Post fields and files to an http host as multipart/form-data. fiel...
utils/web_demo.py
import os, httplib, mimetypes, mimetools from utils import fsys body='' cj = cookielib.CookieJar() opener = urllib2.build_opener(urllib2.HTTPCookieProcessor(cj)) urllib2.install_opener(opener) def post_multipart(url, fields, files=[]): """ Post fields and files to an http host as multipart/form-data. fiel...
0.22919
0.095392
import numpy as np import matplotlib.pyplot as plt import pandas as pd from pandas.plotting import table # EDIT: see deprecation warnings below import seaborn as sns number_blocks = [6,12,24,16] rank_importance = [[], [], [], [], []] pre = 'rank_densenet0.35+re_no_retrain/densenet121_limit3' y_max = 56 rank = pre ...
rank_importance_densenet.py
import numpy as np import matplotlib.pyplot as plt import pandas as pd from pandas.plotting import table # EDIT: see deprecation warnings below import seaborn as sns number_blocks = [6,12,24,16] rank_importance = [[], [], [], [], []] pre = 'rank_densenet0.35+re_no_retrain/densenet121_limit3' y_max = 56 rank = pre ...
0.182134
0.363195
from itertools import repeat from ..._thnn import type2backend from ..function import Function, InplaceFunction from ..variable import Variable from .utils import maybe_unexpand, maybe_unexpand_or_view class Exp(InplaceFunction): @staticmethod def forward(ctx, i, inplace=False): if inplace: ...
torch/autograd/_functions/pointwise.py
from itertools import repeat from ..._thnn import type2backend from ..function import Function, InplaceFunction from ..variable import Variable from .utils import maybe_unexpand, maybe_unexpand_or_view class Exp(InplaceFunction): @staticmethod def forward(ctx, i, inplace=False): if inplace: ...
0.581422
0.182644
from dataclasses import replace from datetime import datetime from typing import Any, Dict, List, Optional, Tuple from opentrons.protocol_engine import ( Command as ProtocolEngineCommand, EngineStatus, LoadedLabware, LoadedPipette, ) from .session_store import SessionResource from .action_models impor...
robot-server/robot_server/sessions/session_view.py
from dataclasses import replace from datetime import datetime from typing import Any, Dict, List, Optional, Tuple from opentrons.protocol_engine import ( Command as ProtocolEngineCommand, EngineStatus, LoadedLabware, LoadedPipette, ) from .session_store import SessionResource from .action_models impor...
0.927593
0.287261
def findDecision(obj): #obj[0]: Driving_to, obj[1]: Passanger, obj[2]: Weather, obj[3]: Temperature, obj[4]: Time, obj[5]: Coupon, obj[6]: Coupon_validity, obj[7]: Gender, obj[8]: Age, obj[9]: Maritalstatus, obj[10]: Children, obj[11]: Education, obj[12]: Occupation, obj[13]: Income, obj[14]: Bar, obj[15]: Coffeehouse,...
duke-cs671-fall21-coupon-recommendation/outputs/rules/RF/numtrees_25/rule_20.py
def findDecision(obj): #obj[0]: Driving_to, obj[1]: Passanger, obj[2]: Weather, obj[3]: Temperature, obj[4]: Time, obj[5]: Coupon, obj[6]: Coupon_validity, obj[7]: Gender, obj[8]: Age, obj[9]: Maritalstatus, obj[10]: Children, obj[11]: Education, obj[12]: Occupation, obj[13]: Income, obj[14]: Bar, obj[15]: Coffeehouse,...
0.087342
0.283955
# Licensed under the Apache License, Version 2.0 (the "License"); # you may not use this file except in compliance with the License. # You may obtain a copy of the License at # http://www.apache.org/licenses/LICENSE-2.0 # Unless required by applicable law or agreed to in writing, software # distributed under the...
thewalrus/_permanent.py
# Licensed under the Apache License, Version 2.0 (the "License"); # you may not use this file except in compliance with the License. # You may obtain a copy of the License at # http://www.apache.org/licenses/LICENSE-2.0 # Unless required by applicable law or agreed to in writing, software # distributed under the...
0.955558
0.657566
from cryptography import utils from cryptography.hazmat.primitives.asymmetric import ec from cryptography.hazmat.bindings.openssl.binding import Binding __all__ = tuple() # TODO: investigate defining additional curves using EC_GROUP_new_curve # https://wiki.openssl.org/index.php/Elliptic_Curve_Cryptography#De...
pgpy/_curves.py
from cryptography import utils from cryptography.hazmat.primitives.asymmetric import ec from cryptography.hazmat.bindings.openssl.binding import Binding __all__ = tuple() # TODO: investigate defining additional curves using EC_GROUP_new_curve # https://wiki.openssl.org/index.php/Elliptic_Curve_Cryptography#De...
0.388618
0.156975
from __future__ import print_function import sys sys.path.append('../') from DFRobot_URM13 import * ''' # UART(Modbus-RTU)与I2C/TRIG模式切换 # URM13传感器默认出厂设置为UART模式。 传感器可以在I2C、UART两种模式间通过上电前短接不同的引脚实现简单的模式切换: # I2C/TRIG: 在传感器上电前,将TRIG与ECHO引脚短接,上电后LED闪烁2次,表示传感器已切换为I2C模式。 # UART(Modbus-RTU): 在传感器上电前,将TRIG与BUSY引脚短接,上电...
python/raspberrypi/example/URM13_work_in_I2C.py
from __future__ import print_function import sys sys.path.append('../') from DFRobot_URM13 import * ''' # UART(Modbus-RTU)与I2C/TRIG模式切换 # URM13传感器默认出厂设置为UART模式。 传感器可以在I2C、UART两种模式间通过上电前短接不同的引脚实现简单的模式切换: # I2C/TRIG: 在传感器上电前,将TRIG与ECHO引脚短接,上电后LED闪烁2次,表示传感器已切换为I2C模式。 # UART(Modbus-RTU): 在传感器上电前,将TRIG与BUSY引脚短接,上电...
0.229104
0.270994
from mrjob.job import MRJob from mrjob.step import MRStep from mrjob import protocol """ Transactions layout 0 - block_number: Block number where this transaction was in 1 - from_address: Address of the sender 2 - to_address: Address of the receiver. null when it is a contract creation transaction 3 - value: Value tra...
PartB/PartB_hadoop.py
from mrjob.job import MRJob from mrjob.step import MRStep from mrjob import protocol """ Transactions layout 0 - block_number: Block number where this transaction was in 1 - from_address: Address of the sender 2 - to_address: Address of the receiver. null when it is a contract creation transaction 3 - value: Value tra...
0.600423
0.430746
import tensorflow as tf from tfsnippet.ops import assert_shape_equal from tfsnippet.utils import (add_name_and_scope_arg_doc, get_static_shape, validate_enum_arg, assert_deps, get_shape) from .base import FeatureMappingFlow from .utils import SigmoidScale, ExpS...
tfsnippet/layers/flows/coupling.py
import tensorflow as tf from tfsnippet.ops import assert_shape_equal from tfsnippet.utils import (add_name_and_scope_arg_doc, get_static_shape, validate_enum_arg, assert_deps, get_shape) from .base import FeatureMappingFlow from .utils import SigmoidScale, ExpS...
0.926174
0.459319
from .osvc_python_validations import OSvCPythonValidations from .osvc_python_examples import ANNOTATION_MUST_BE_SHORTER_THAN_40_CHARACTERS class OSvCPythonConfig: def url_format(self,kwargs): if "url" in kwargs: resource_url = kwargs.get("url") else: resource_url = "" client = kwargs.get("client") cust...
osvc_python/osvc_python_config.py
from .osvc_python_validations import OSvCPythonValidations from .osvc_python_examples import ANNOTATION_MUST_BE_SHORTER_THAN_40_CHARACTERS class OSvCPythonConfig: def url_format(self,kwargs): if "url" in kwargs: resource_url = kwargs.get("url") else: resource_url = "" client = kwargs.get("client") cust...
0.321247
0.071106
from flask import Blueprint, jsonify, request, Response import json from blitzdb.document import DoesNotExist import requests from lxml import html from traceback import print_exc from JavHelper.cache import cache from JavHelper.core.javbus import javbus_set_page, JavBusScraper from JavHelper.model.jav_manager import ...
JavHelper/views/javbus_browser.py
from flask import Blueprint, jsonify, request, Response import json from blitzdb.document import DoesNotExist import requests from lxml import html from traceback import print_exc from JavHelper.cache import cache from JavHelper.core.javbus import javbus_set_page, JavBusScraper from JavHelper.model.jav_manager import ...
0.322846
0.048226
import os import datetime try: from urllib.parse import urlparse except ImportError: from urlparse import urlparse from owtf.dependency_management.dependency_resolver import BaseComponent, ServiceLocator from owtf.dependency_management.interfaces import TargetInterface from owtf.lib.exceptions import DBIntegri...
owtf/managers/target.py
import os import datetime try: from urllib.parse import urlparse except ImportError: from urlparse import urlparse from owtf.dependency_management.dependency_resolver import BaseComponent, ServiceLocator from owtf.dependency_management.interfaces import TargetInterface from owtf.lib.exceptions import DBIntegri...
0.437103
0.092155
import unittest from mt_metadata.timeseries.stationxml.utils import BaseTranslator from obspy.core.inventory import Comment class TestReadXMLComment(unittest.TestCase): """ test reading different comments """ def setUp(self): self.run_comment = Comment( "author: <NAME>, comments: ...
tests/timeseries/stationxml/test_base_translator.py
import unittest from mt_metadata.timeseries.stationxml.utils import BaseTranslator from obspy.core.inventory import Comment class TestReadXMLComment(unittest.TestCase): """ test reading different comments """ def setUp(self): self.run_comment = Comment( "author: <NAME>, comments: ...
0.571527
0.489442
import random import unittest import math from myhdl import always from numpy import fft from scipy import signal from fpga_sdrlib import config from fpga_sdrlib.channelizer.build import generate_channelizer_executable from fpga_sdrlib.testbench import TestBenchIcarus from fpga_sdrlib.filterbank.qa_filterbank import ...
python/fpga_sdrlib/channelizer/qa_channelizer.py
import random import unittest import math from myhdl import always from numpy import fft from scipy import signal from fpga_sdrlib import config from fpga_sdrlib.channelizer.build import generate_channelizer_executable from fpga_sdrlib.testbench import TestBenchIcarus from fpga_sdrlib.filterbank.qa_filterbank import ...
0.595845
0.417093
import os from selenium import webdriver from selenium.webdriver.common.by import By from selenium.webdriver.common.action_chains import ActionChains from selenium.common.exceptions import NoSuchElementException from selenium.webdriver.chrome.options import Options from time import sleep class Browser: def __init...
cognito/browser.py
import os from selenium import webdriver from selenium.webdriver.common.by import By from selenium.webdriver.common.action_chains import ActionChains from selenium.common.exceptions import NoSuchElementException from selenium.webdriver.chrome.options import Options from time import sleep class Browser: def __init...
0.331877
0.043896
import pytest from thermo.law import * from chemicals.identifiers import check_CAS, int_to_CAS load_law_data() load_economic_data() from thermo.law import DSL_data, TSCA_data, EINECS_data, SPIN_data, NLP_data from thermo.law import HPV_data, _EPACDRDict, _ECHATonnageDict @pytest.mark.slow def test_DSL_data(): as...
tests/test_law.py
import pytest from thermo.law import * from chemicals.identifiers import check_CAS, int_to_CAS load_law_data() load_economic_data() from thermo.law import DSL_data, TSCA_data, EINECS_data, SPIN_data, NLP_data from thermo.law import HPV_data, _EPACDRDict, _ECHATonnageDict @pytest.mark.slow def test_DSL_data(): as...
0.450359
0.627723
import datetime from django.conf import settings from django.db import models from django.utils import timezone from .enums import OTPStatus, OTPTypes OTP_LENGTH = 6 class OTPManager(models.Manager): def generate(self, user_id): codes = self.model.objects.filter(user_id=user_id, verified=False) ...
alshamelah_api/apps/users/managers.py
import datetime from django.conf import settings from django.db import models from django.utils import timezone from .enums import OTPStatus, OTPTypes OTP_LENGTH = 6 class OTPManager(models.Manager): def generate(self, user_id): codes = self.model.objects.filter(user_id=user_id, verified=False) ...
0.338624
0.149718
import logging from settings.secrets import GR_API_KEY from google.appengine.api import urlfetch from google.appengine.ext import ndb from lxml import etree from StringIO import StringIO from models import Readable from constants import READABLE import urllib def get_books_on_shelf(user, shelf='currently-reading'): ...
services/goodreads.py
import logging from settings.secrets import GR_API_KEY from google.appengine.api import urlfetch from google.appengine.ext import ndb from lxml import etree from StringIO import StringIO from models import Readable from constants import READABLE import urllib def get_books_on_shelf(user, shelf='currently-reading'): ...
0.201656
0.07477
from oslo_config import cfg from oslo_db import exception as d_exc from oslo_utils import uuidutils from neutron.db import db_base_plugin_v2 from neutron.tests.unit.db import test_db_base_plugin_v2 as test_db_plugin from neutron_lib.api import validators from neutron_lib import context as neutron_context from neutron...
vmware_nsx/tests/unit/extensions/test_vnic_index.py
from oslo_config import cfg from oslo_db import exception as d_exc from oslo_utils import uuidutils from neutron.db import db_base_plugin_v2 from neutron.tests.unit.db import test_db_base_plugin_v2 as test_db_plugin from neutron_lib.api import validators from neutron_lib import context as neutron_context from neutron...
0.503662
0.069985
import os import sys import json import tempfile import filecmp # Generated document is included in existing page, so # start at heading of depth 1 (equivalent to markdown h2.) START_DEPTH = 1 class MinimalRstGenerator: def __init__(self): self._lines = [".."] self._lines.append(" This is an au...
doc/generate_config_rst.py
import os import sys import json import tempfile import filecmp # Generated document is included in existing page, so # start at heading of depth 1 (equivalent to markdown h2.) START_DEPTH = 1 class MinimalRstGenerator: def __init__(self): self._lines = [".."] self._lines.append(" This is an au...
0.325628
0.115511
import pyevtk as evtk from femsnek.mesh.feMesh import FeMesh, Mesh import numpy as np import femsnek.fields as fields # Data ~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~ # Dictionary [<fem-snek element type>] -> <VTK Element type> # fem-snek elemen...
femsnek/fio/vtk.py
import pyevtk as evtk from femsnek.mesh.feMesh import FeMesh, Mesh import numpy as np import femsnek.fields as fields # Data ~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~ # Dictionary [<fem-snek element type>] -> <VTK Element type> # fem-snek elemen...
0.608245
0.342269
import argparse import curses import fcntl import os import re import signal import subprocess import sys import time from datetime import datetime RUN_CMD = "foo" RUN_DIR = "./build/" OPTION_TYPE_1 = ["-o", "-i", "-s"] OPTIMUM = ["fib", "gra", "ann", "par", "gen"] INTEGRAL = ["tra", "sim", "rom", "gau", "mon"] SORT ...
script/test.py
import argparse import curses import fcntl import os import re import signal import subprocess import sys import time from datetime import datetime RUN_CMD = "foo" RUN_DIR = "./build/" OPTION_TYPE_1 = ["-o", "-i", "-s"] OPTIMUM = ["fib", "gra", "ann", "par", "gen"] INTEGRAL = ["tra", "sim", "rom", "gau", "mon"] SORT ...
0.208501
0.05375
import os import math def recorded_views(label): """ Get the dimensions of the view from recorded ones. Parameters ---------- label: string Dictionary key for the view. Returns ------- view: 4-tuple of floats The view ('xmin', 'xmax', 'ymin', 'ymax'). """ views = {} views['snake'] = (-...
runs/batchshipyard/snake/2d/2k35/scripts/plotVorticity.py
import os import math def recorded_views(label): """ Get the dimensions of the view from recorded ones. Parameters ---------- label: string Dictionary key for the view. Returns ------- view: 4-tuple of floats The view ('xmin', 'xmax', 'ymin', 'ymax'). """ views = {} views['snake'] = (-...
0.653238
0.239866
import numpy as np from numpy import linalg as la from typing import Tuple, Any, Union from base import nipals class OPLS: """ Orthogonal Projection on Latent Structure (O-PLS). Methods ---------- predictive_scores: np.ndarray First predictive score. predictive_loadings: n...
opls.py
import numpy as np from numpy import linalg as la from typing import Tuple, Any, Union from base import nipals class OPLS: """ Orthogonal Projection on Latent Structure (O-PLS). Methods ---------- predictive_scores: np.ndarray First predictive score. predictive_loadings: n...
0.828384
0.4831
from collections import defaultdict from contextlib import ExitStack from datetime import date, datetime from unittest.mock import Mock, patch import pytest import pytz from todoist.models import Item, Project from synctogit.service import ServiceAPIError, ServiceTokenExpiredError from synctogit.todoist import models...
tests/todoist/test_todoist.py
from collections import defaultdict from contextlib import ExitStack from datetime import date, datetime from unittest.mock import Mock, patch import pytest import pytz from todoist.models import Item, Project from synctogit.service import ServiceAPIError, ServiceTokenExpiredError from synctogit.todoist import models...
0.42656
0.510069
import xbmc import xbmcgui import os from resources.libs.common.config import CONFIG from resources.libs.common import directory from resources.libs.common import logging from resources.libs.common import tools from resources.libs.gui import window def view_current(): window.show_text_box(CONFIG.ADDONTITLE, to...
matrix/plugin.program.openwizard/resources/libs/advanced.py
import xbmc import xbmcgui import os from resources.libs.common.config import CONFIG from resources.libs.common import directory from resources.libs.common import logging from resources.libs.common import tools from resources.libs.gui import window def view_current(): window.show_text_box(CONFIG.ADDONTITLE, to...
0.324021
0.082883
import numpy as np import scipy.sparse as sp import scipy.io as sio import random def sparse_to_tuple(sparse_mx, insert_batch=False): """Convert sparse matrix to tuple representation.""" """Set insert_batch=True if you want to insert a batch dimension.""" def to_tuple(mx): if not sp.isspmatrix_coo...
utils/utils.py
import numpy as np import scipy.sparse as sp import scipy.io as sio import random def sparse_to_tuple(sparse_mx, insert_batch=False): """Convert sparse matrix to tuple representation.""" """Set insert_batch=True if you want to insert a batch dimension.""" def to_tuple(mx): if not sp.isspmatrix_coo...
0.759315
0.568296
import numpy as np from wisdem.floating.floating_turbine_instance import FloatingTurbineInstance, NPTS, vecOption import offshorebos.wind_obos as wind_obos from commonse.utilities import sectional2nodal class TurbineSemiInstance(FloatingTurbineInstance): def __init__(self, refStr): super(TurbineSemiInstan...
wisdem/assemblies/floating/turbine_semi_instance.py
import numpy as np from wisdem.floating.floating_turbine_instance import FloatingTurbineInstance, NPTS, vecOption import offshorebos.wind_obos as wind_obos from commonse.utilities import sectional2nodal class TurbineSemiInstance(FloatingTurbineInstance): def __init__(self, refStr): super(TurbineSemiInstan...
0.464173
0.216446
import unittest import re import numpy as np from PySide2 import QtGui, QtCore, QtWidgets from quantiphyse.data import DataGrid from quantiphyse.test.widget_test import WidgetTest from .widgets import DataStatistics, MultiVoxelAnalysis, VoxelAnalysis, MeasureWidget class DataStatisticsTest(WidgetTest): def wi...
quantiphyse/packages/core/analysis/tests.py
import unittest import re import numpy as np from PySide2 import QtGui, QtCore, QtWidgets from quantiphyse.data import DataGrid from quantiphyse.test.widget_test import WidgetTest from .widgets import DataStatistics, MultiVoxelAnalysis, VoxelAnalysis, MeasureWidget class DataStatisticsTest(WidgetTest): def wi...
0.608594
0.558628
from selenium.common.exceptions import TimeoutException from selenium.webdriver.common.by import By import selenium.webdriver.support.expected_conditions as EC import selenium.webdriver.support.ui as ui from config import Configuration from datetime import datetime, date from selenium import webdriver import time impo...
job/__init__.py
from selenium.common.exceptions import TimeoutException from selenium.webdriver.common.by import By import selenium.webdriver.support.expected_conditions as EC import selenium.webdriver.support.ui as ui from config import Configuration from datetime import datetime, date from selenium import webdriver import time impo...
0.1602
0.069164
import aws_info_helper as ah import input_helper as ih from functools import partial class ParameterStore(object): def __init__(self, profile_name='default'): session = ah.get_session(profile_name) self._client = session.client('ssm') self._profile = profile_name self._cache = {} ...
aws_info_helper/parameter_store.py
import aws_info_helper as ah import input_helper as ih from functools import partial class ParameterStore(object): def __init__(self, profile_name='default'): session = ah.get_session(profile_name) self._client = session.client('ssm') self._profile = profile_name self._cache = {} ...
0.731346
0.149811
import os import pandas as pd from numpy import testing as npt import pandas.util.testing as pdt import ixmp import pytest from ixmp.default_path_constants import CONFIG_PATH from testing_utils import ( test_mp, test_mp_props, test_mp_use_default_dbprops_file, test_mp_use_db_config_path, ) test_args ...
tests/test_core.py
import os import pandas as pd from numpy import testing as npt import pandas.util.testing as pdt import ixmp import pytest from ixmp.default_path_constants import CONFIG_PATH from testing_utils import ( test_mp, test_mp_props, test_mp_use_default_dbprops_file, test_mp_use_db_config_path, ) test_args ...
0.492676
0.382141
import os import re import subprocess from datetime import datetime workingDirectory = "/Users/mli/Projects/isc-dotnet-log-parser/files/" fileFolder = workingDirectory + "output/" resultFile = workingDirectory + "result.txt" sortedResultFile = workingDirectory + "resultSorted.txt" timestamp = r'\d{2}:\d{2}:\d{2}:\d{3...
time-duration-calc.py
import os import re import subprocess from datetime import datetime workingDirectory = "/Users/mli/Projects/isc-dotnet-log-parser/files/" fileFolder = workingDirectory + "output/" resultFile = workingDirectory + "result.txt" sortedResultFile = workingDirectory + "resultSorted.txt" timestamp = r'\d{2}:\d{2}:\d{2}:\d{3...
0.207938
0.156427
import os from spaceone.inventory.libs.common_parser import * from spaceone.inventory.libs.schema.dynamic_widget import ChartWidget, CardWidget from spaceone.inventory.libs.schema.dynamic_field import TextDyField, DateTimeDyField, SearchField from spaceone.inventory.libs.schema.resource import CloudServiceTypeResource,...
src/spaceone/inventory/connector/aws_ecr_connector/schema/service_type.py
import os from spaceone.inventory.libs.common_parser import * from spaceone.inventory.libs.schema.dynamic_widget import ChartWidget, CardWidget from spaceone.inventory.libs.schema.dynamic_field import TextDyField, DateTimeDyField, SearchField from spaceone.inventory.libs.schema.resource import CloudServiceTypeResource,...
0.330579
0.084266
def rotated_array_search(input_list, number): """ Find the index by searching in a rotated sorted array Args: input_list(array), number(int): Input array to search and the target Returns: int: Index or -1 """ return rotated_array_search_recursive(input_list, ...
Data Structures and Algorithms Nanodegree/P3 - Problems vs Algorithms/Problem 2 - Search in a Rotated Sorted Array/solution.py
def rotated_array_search(input_list, number): """ Find the index by searching in a rotated sorted array Args: input_list(array), number(int): Input array to search and the target Returns: int: Index or -1 """ return rotated_array_search_recursive(input_list, ...
0.857336
0.672014
import shutil from dnnv.verifiers.common.base import Parameter, Verifier from dnnv.verifiers.common.executors import VerifierExecutor from dnnv.verifiers.common.reductions import ( IOPolytopeReduction, HalfspacePolytope, HyperRectangle, ) from dnnv.verifiers.common.results import UNKNOWN from dnnv.verifier...
dnnv/verifiers/convert/__init__.py
import shutil from dnnv.verifiers.common.base import Parameter, Verifier from dnnv.verifiers.common.executors import VerifierExecutor from dnnv.verifiers.common.reductions import ( IOPolytopeReduction, HalfspacePolytope, HyperRectangle, ) from dnnv.verifiers.common.results import UNKNOWN from dnnv.verifier...
0.560614
0.165088
import copy import logging from collections import Iterable import numpy as np from numba import jit, prange from ray.rllib.utils import override from marltoolbox.envs import vectorized_coin_game from marltoolbox.envs.vectorized_coin_game import \ _flatten_index, _unflatten_index, _same_pos, move_players logger ...
marltoolbox/envs/vectorized_mixed_motive_coin_game.py
import copy import logging from collections import Iterable import numpy as np from numba import jit, prange from ray.rllib.utils import override from marltoolbox.envs import vectorized_coin_game from marltoolbox.envs.vectorized_coin_game import \ _flatten_index, _unflatten_index, _same_pos, move_players logger ...
0.709523
0.421284
from __future__ import unicode_literals from django.db import migrations, models import django.db.models.deletion class Migration(migrations.Migration): dependencies = [ ('decomposition', '0018_apibatchresult'), ('basicviz', '0065_auto_20170413_1256'), ('ms1analysis', '0006_auto_20170413...
ms2ldaviz/ms1analysis/migrations/0007_decompositionanalysis_decompositionanalysisresult_decompositionanalysisresultplage.py
from __future__ import unicode_literals from django.db import migrations, models import django.db.models.deletion class Migration(migrations.Migration): dependencies = [ ('decomposition', '0018_apibatchresult'), ('basicviz', '0065_auto_20170413_1256'), ('ms1analysis', '0006_auto_20170413...
0.649912
0.135604
import math import torch from torch import nn import torch.nn.functional as F from einops import rearrange class Conv1dIn(nn.Module): def __init__(self, in_dim, out_dim, num_nodes): super().__init__() self.project_k = Conv(1, in_dim, num_nodes, 1) self.project_v = Conv(1, in_dim, out_di...
startup/model/modules.py
import math import torch from torch import nn import torch.nn.functional as F from einops import rearrange class Conv1dIn(nn.Module): def __init__(self, in_dim, out_dim, num_nodes): super().__init__() self.project_k = Conv(1, in_dim, num_nodes, 1) self.project_v = Conv(1, in_dim, out_di...
0.934991
0.630401
import logging from cloudmarker import util _log = logging.getLogger(__name__) class AzWebAppTLSEvent: """Azure web app minimum TLS version check event plugin.""" def __init__(self, _min_tls_version=1.2): """Create an instance of :class:`AzWebAppTLSEvent`. Arguments: _min_tls_v...
cloudmarker/events/azwebapptlsevent.py
import logging from cloudmarker import util _log = logging.getLogger(__name__) class AzWebAppTLSEvent: """Azure web app minimum TLS version check event plugin.""" def __init__(self, _min_tls_version=1.2): """Create an instance of :class:`AzWebAppTLSEvent`. Arguments: _min_tls_v...
0.875973
0.105211
# Import modules. import phonenumbers from tornado.httpclient import AsyncHTTPClient, HTTPRequest import os import logging from tornado.httputil import url_concat import phonenumbers class AsyncGTXClient(object): def __init__(self, username, password, domain='http.gtx-messaging.net', ssl=Fa...
gtxclient.py
# Import modules. import phonenumbers from tornado.httpclient import AsyncHTTPClient, HTTPRequest import os import logging from tornado.httputil import url_concat import phonenumbers class AsyncGTXClient(object): def __init__(self, username, password, domain='http.gtx-messaging.net', ssl=Fa...
0.46952
0.057918
import os import sys import shutil import subprocess target_path = sys.argv[1] base_path = sys.argv[2] directory_path = os.path.dirname(os.path.realpath(__file__)) temporary_path = os.path.join(directory_path, "npcolony") not os.path.exists(target_path) and os.mkdir(target_path) not os.path.exists(tempor...
scripts/make_crx.py
import os import sys import shutil import subprocess target_path = sys.argv[1] base_path = sys.argv[2] directory_path = os.path.dirname(os.path.realpath(__file__)) temporary_path = os.path.join(directory_path, "npcolony") not os.path.exists(target_path) and os.mkdir(target_path) not os.path.exists(tempor...
0.04788
0.042983
import jet import sys from random import randint from inspect import getargspec from helpers import cprint from jet.jit import jit import numpy as np ERROR_MAX = 1.e-12 mode = 0 if 'continue' in sys.argv else 1 dimensions = [] for f_name in ['0d', '1d', '2d']: with open(f_name) as file: dimensions_raw =...
tests/run_test.py
import jet import sys from random import randint from inspect import getargspec from helpers import cprint from jet.jit import jit import numpy as np ERROR_MAX = 1.e-12 mode = 0 if 'continue' in sys.argv else 1 dimensions = [] for f_name in ['0d', '1d', '2d']: with open(f_name) as file: dimensions_raw =...
0.27474
0.514766