code stringlengths 2k 1.04M | repo_path stringlengths 5 517 | parsed_code stringlengths 0 1.04M | quality_prob float64 0.02 0.95 | learning_prob float64 0.02 0.93 |
|---|---|---|---|---|
from ..core import asyncio, Unit, inport, outport, coroutine
from ..ext import param, Paramed
from .read.ressource import LocateByTime
from pathlib import Path
from tempfile import NamedTemporaryFile
import re
from contextlib import contextmanager
from pyadds.logging import log, logging
from pyadds.annotate import ... | zeroflo/flows/io.py | from ..core import asyncio, Unit, inport, outport, coroutine
from ..ext import param, Paramed
from .read.ressource import LocateByTime
from pathlib import Path
from tempfile import NamedTemporaryFile
import re
from contextlib import contextmanager
from pyadds.logging import log, logging
from pyadds.annotate import ... | 0.461745 | 0.173708 |
import cv2 as cv
import numpy as np
import math
#-----------------霍夫变换---------------------
#前提条件: 边缘检测完成
#标准霍夫线变换
#标准霍夫线变换
# 获取列表的最后一个元素
def takeEnd(elem):
return elem[-1]
def line_detection(image):
gray = cv.cvtColor(image, cv.COLOR_RGB2GRAY)
edges = cv.Canny(gray, 50, 150, apertureSize=3) #apertureS... | utils/hough_line.py |
import cv2 as cv
import numpy as np
import math
#-----------------霍夫变换---------------------
#前提条件: 边缘检测完成
#标准霍夫线变换
#标准霍夫线变换
# 获取列表的最后一个元素
def takeEnd(elem):
return elem[-1]
def line_detection(image):
gray = cv.cvtColor(image, cv.COLOR_RGB2GRAY)
edges = cv.Canny(gray, 50, 150, apertureSize=3) #apertureS... | 0.164181 | 0.402862 |
from __future__ import division
from math import atan2, tan, hypot, cos, degrees, radians
from fontParts.fontshell import RGlyph
import fontTools
import fontTools.misc.bezierTools as bezierTools
import fontTools.misc.arrayTools as arrayTools
import fontTools.misc.transform as transform
from fontTools.pens.boundsPen i... | lib/mutatorScale/utilities/fontUtils.py | from __future__ import division
from math import atan2, tan, hypot, cos, degrees, radians
from fontParts.fontshell import RGlyph
import fontTools
import fontTools.misc.bezierTools as bezierTools
import fontTools.misc.arrayTools as arrayTools
import fontTools.misc.transform as transform
from fontTools.pens.boundsPen i... | 0.667039 | 0.394201 |
import ee
import requests
import zipfile
import os
import xmltodict
import geopandas as gpd
from glob import glob
from Python_Files.hydrolibs.sysops import copy_file
def download_gee_data(year_list, start_month, end_month, aoi_shp_file, outdir):
"""
Download MOD16 and PRISM data. MOD16 has to be divided by 1... | Python_Files/hydrolibs/data_download.py |
import ee
import requests
import zipfile
import os
import xmltodict
import geopandas as gpd
from glob import glob
from Python_Files.hydrolibs.sysops import copy_file
def download_gee_data(year_list, start_month, end_month, aoi_shp_file, outdir):
"""
Download MOD16 and PRISM data. MOD16 has to be divided by 1... | 0.433022 | 0.319121 |
from jinja2 import Template
import re
import os
def _lower_first_char(input_str):
if len(input_str) == 0:
raise Exception("Cannot use an empty string for a field name!")
return input_str[0].lower() + input_str[1:]
def camel_to_snake(input_str):
s1 = re.sub('(.)([A-Z][a-z]+)', r'\1_\2', input_str... | libraries/ShuffleboardGenerator/lib/template_helpers.py | from jinja2 import Template
import re
import os
def _lower_first_char(input_str):
if len(input_str) == 0:
raise Exception("Cannot use an empty string for a field name!")
return input_str[0].lower() + input_str[1:]
def camel_to_snake(input_str):
s1 = re.sub('(.)([A-Z][a-z]+)', r'\1_\2', input_str... | 0.398641 | 0.278011 |
"""Client and server classes corresponding to protobuf-defined services."""
import grpc
from google.ads.google_ads.v6.proto.resources import gender_view_pb2 as google_dot_ads_dot_googleads__v6_dot_proto_dot_resources_dot_gender__view__pb2
from google.ads.google_ads.v6.proto.services import gender_view_service_pb2 as g... | google/ads/google_ads/v6/proto/services/gender_view_service_pb2_grpc.py | """Client and server classes corresponding to protobuf-defined services."""
import grpc
from google.ads.google_ads.v6.proto.resources import gender_view_pb2 as google_dot_ads_dot_googleads__v6_dot_proto_dot_resources_dot_gender__view__pb2
from google.ads.google_ads.v6.proto.services import gender_view_service_pb2 as g... | 0.709221 | 0.187504 |
import os
import numpy as np
import torch
from torch.utils.data import DataLoader
from tqdm import tqdm
from smplx.lbs import batch_rodrigues
from renderers.pytorch3d_textured_renderer import TexturedIUVRenderer
from metrics.eval_metrics_tracker import EvalMetricsTracker
from utils.cam_utils import orthographic_proj... | evaluate/evaluate_poseMF_shapeGaussian_net.py | import os
import numpy as np
import torch
from torch.utils.data import DataLoader
from tqdm import tqdm
from smplx.lbs import batch_rodrigues
from renderers.pytorch3d_textured_renderer import TexturedIUVRenderer
from metrics.eval_metrics_tracker import EvalMetricsTracker
from utils.cam_utils import orthographic_proj... | 0.560012 | 0.241171 |
import torch
import torch.nn as nn
import torch.nn.functional as F
from .config import *
from configs import *
class Embedder(nn.Module):
"""
Embedding different features according to configuration
and concatenate all the embeddings.
"""
def __init__(self, emb_dicts, emb_mats, dropout=0.1, _confi... | Model/Embedder.py | import torch
import torch.nn as nn
import torch.nn.functional as F
from .config import *
from configs import *
class Embedder(nn.Module):
"""
Embedding different features according to configuration
and concatenate all the embeddings.
"""
def __init__(self, emb_dicts, emb_mats, dropout=0.1, _confi... | 0.93784 | 0.435841 |
import os
from enum import Enum
import requests
import argparse
class GitHubRegistry:
def __init__(self, organization, type, personal_access_token):
self._url = f"https://api.github.com/orgs/{organization}/packages/{type}"
self._auth = personal_access_token
def _call(self, *arg... | devops/github/registry.py | import os
from enum import Enum
import requests
import argparse
class GitHubRegistry:
def __init__(self, organization, type, personal_access_token):
self._url = f"https://api.github.com/orgs/{organization}/packages/{type}"
self._auth = personal_access_token
def _call(self, *arg... | 0.388386 | 0.047492 |
import os
import paddle
import pickle
from paddle import inference
import numpy as np
from PIL import Image
from reprod_log import ReprodLogger
class InferenceEngine(object):
"""InferenceEngine
Inference engina class which contains preprocess, run, postprocess
"""
def __init__(self, args):
... | tools/infer.py |
import os
import paddle
import pickle
from paddle import inference
import numpy as np
from PIL import Image
from reprod_log import ReprodLogger
class InferenceEngine(object):
"""InferenceEngine
Inference engina class which contains preprocess, run, postprocess
"""
def __init__(self, args):
... | 0.857261 | 0.23524 |
import roomai
class Stage:
firstStage = 1
secondStage = 2
thirdStage = 3
fourthStage = 4
AllCardsPattern = dict()
#0 1 2 3 4 5 6
#name, isStraight, isPair, isSameSuit, [SizeOfPair1, SizeOfPair2,..](desc), rank, cards
AllCardsPatt... | roomai/games/texasholdem/TexasHoldemUtil.py |
import roomai
class Stage:
firstStage = 1
secondStage = 2
thirdStage = 3
fourthStage = 4
AllCardsPattern = dict()
#0 1 2 3 4 5 6
#name, isStraight, isPair, isSameSuit, [SizeOfPair1, SizeOfPair2,..](desc), rank, cards
AllCardsPatt... | 0.553023 | 0.288857 |
from models.parameter_category import ParameterCategory
from helpers.generic_helpers import get_voms_config, evaluate, get_component_section
def globus_tcp_port_range(component_section):
begin = component_section['config']['globus_tcp_port_range']['begin']
end = component_section['config']['globus_tcp_port_ra... | yaim/pre_config/categories/cream_info_advanced.py | from models.parameter_category import ParameterCategory
from helpers.generic_helpers import get_voms_config, evaluate, get_component_section
def globus_tcp_port_range(component_section):
begin = component_section['config']['globus_tcp_port_range']['begin']
end = component_section['config']['globus_tcp_port_ra... | 0.380759 | 0.16529 |
import gym
import numpy as np
import itertools
import tensorflow as tf
from tf_rl.common.utils import AnnealingSchedule
from tf_rl.common.params import Parameters
from tf_rl.common.utils import logging
config = tf.ConfigProto(allow_soft_placement=True,
intra_op_parallelism_threads=1,
... | examples/Continuous_Q/bare_Continuous_Q.py | import gym
import numpy as np
import itertools
import tensorflow as tf
from tf_rl.common.utils import AnnealingSchedule
from tf_rl.common.params import Parameters
from tf_rl.common.utils import logging
config = tf.ConfigProto(allow_soft_placement=True,
intra_op_parallelism_threads=1,
... | 0.838465 | 0.328449 |
import abc
import base64
import copy
import json
import logging
from typing import Any, Dict, Optional, Union, cast
import requests
from django.contrib.gis.geos import GeometryCollection, GEOSGeometry, Polygon
from django.core.cache import cache
from eventkit_cloud.core.helpers import get_or_update_session... | eventkit_cloud/utils/services/base.py | import abc
import base64
import copy
import json
import logging
from typing import Any, Dict, Optional, Union, cast
import requests
from django.contrib.gis.geos import GeometryCollection, GEOSGeometry, Polygon
from django.core.cache import cache
from eventkit_cloud.core.helpers import get_or_update_session... | 0.73412 | 0.083479 |
import logging
import torch
from torchmetrics import Metric
__all__ = ['MultiBinaryAccuracy']
class MultiBinaryAccuracy(Metric):
"""
This metric computes accuracies that are needed to evaluate multiple binary outputs.
For example, if a model returns a set of multiple sigmoid outputs per each sample or a... | nemo/collections/asr/metrics/multi_binary_acc.py |
import logging
import torch
from torchmetrics import Metric
__all__ = ['MultiBinaryAccuracy']
class MultiBinaryAccuracy(Metric):
"""
This metric computes accuracies that are needed to evaluate multiple binary outputs.
For example, if a model returns a set of multiple sigmoid outputs per each sample or a... | 0.954265 | 0.606091 |
from __future__ import (absolute_import, division, print_function,
unicode_literals)
import argparse
from os.path import basename, exists, isdir
import glob
from bp4dbg_data import DumpData
from bp4dbg_idxtable import DumpIndexTable
from bp4dbg_metadata import DumpMetaData
def SetupArgs():
... | source/utils/bp4dbg/bp4dbg.py | from __future__ import (absolute_import, division, print_function,
unicode_literals)
import argparse
from os.path import basename, exists, isdir
import glob
from bp4dbg_data import DumpData
from bp4dbg_idxtable import DumpIndexTable
from bp4dbg_metadata import DumpMetaData
def SetupArgs():
... | 0.180251 | 0.077938 |
import sys,re,os
import os.path
import tempfile
from libpredweb import myfunc
#Note: 2010-08-26
# still use xslt to read xml files. it is more reliable
usage="""
Usage: compare_topos.py [Options] [-i] xmlfile
Options:
-i <file> : input file
-aapath <dir> : set the path of aaSeqs for obtaining annot... | proj/pred/app/other/scampiXML2TXT.py |
import sys,re,os
import os.path
import tempfile
from libpredweb import myfunc
#Note: 2010-08-26
# still use xslt to read xml files. it is more reliable
usage="""
Usage: compare_topos.py [Options] [-i] xmlfile
Options:
-i <file> : input file
-aapath <dir> : set the path of aaSeqs for obtaining annot... | 0.126111 | 0.128525 |
import math
import torch
class Encoder(object):
'''
The nonlinear encoder class maps data nonlinearly to high dimensional space.
To do this task, it uses two randomly generated tensors:
:math:`B`. The `(dim, features)` sized random basis hypervectors, drawn
from a standard normal distribution
... | febhd_clustering/encoder.py | import math
import torch
class Encoder(object):
'''
The nonlinear encoder class maps data nonlinearly to high dimensional space.
To do this task, it uses two randomly generated tensors:
:math:`B`. The `(dim, features)` sized random basis hypervectors, drawn
from a standard normal distribution
... | 0.93359 | 0.867822 |
import datetime
def getdate():
num = datetime.datetime.now()
return num
def display():
print("Press\n 1 for diet list\n 2 for exercise list")
list_t = int(input("Enter your Choice: "))
if (list_t == 1):
with open(f"{name}.txt") as op:
for i in op:
pr... | Mini-Projects/Python/Health Management.py | import datetime
def getdate():
num = datetime.datetime.now()
return num
def display():
print("Press\n 1 for diet list\n 2 for exercise list")
list_t = int(input("Enter your Choice: "))
if (list_t == 1):
with open(f"{name}.txt") as op:
for i in op:
pr... | 0.037919 | 0.123418 |
def reindex(indexes, l):
return [l[i] for i in indexes]
asts = 'CopyLocal', 'Call', 'MethodCall', 'DirectCall', 'Load', 'ILoad', 'Store', 'IStore', 'Allocate', 'Check', 'Is'
astColors = 'pink', 'red', 'gray', 'orange', 'yellow', 'gray', 'green', 'gray', 'teal', 'blue', 'purple'
class TableBuilder(object):
def __i... | bin/util/io/report.py |
def reindex(indexes, l):
return [l[i] for i in indexes]
asts = 'CopyLocal', 'Call', 'MethodCall', 'DirectCall', 'Load', 'ILoad', 'Store', 'IStore', 'Allocate', 'Check', 'Is'
astColors = 'pink', 'red', 'gray', 'orange', 'yellow', 'gray', 'green', 'gray', 'teal', 'blue', 'purple'
class TableBuilder(object):
def __i... | 0.337094 | 0.416915 |
from typing import List
from dialog_api import groups_pb2
from dialog_api.groups_pb2 import GROUPADMINPERMISSION_EDITSHORTNAME, GROUPADMINPERMISSION_INVITE, \
GROUPADMINPERMISSION_KICK, GROUPADMINPERMISSION_UPDATEINFO, GROUPADMINPERMISSION_SETPERMISSIONS, \
GROUPADMINPERMISSION_EDITMESSAGE, GROUPADMINPERMISSION... | dialog_bot_sdk/entities/Permissions.py | from typing import List
from dialog_api import groups_pb2
from dialog_api.groups_pb2 import GROUPADMINPERMISSION_EDITSHORTNAME, GROUPADMINPERMISSION_INVITE, \
GROUPADMINPERMISSION_KICK, GROUPADMINPERMISSION_UPDATEINFO, GROUPADMINPERMISSION_SETPERMISSIONS, \
GROUPADMINPERMISSION_EDITMESSAGE, GROUPADMINPERMISSION... | 0.596551 | 0.063948 |
import os
from Utils.Sample import Sample
from DocumentDistances.doc2vec_email import *
from DocumentDistances.doc2vec_psalms import *
import numpy as np
import matplotlib.pyplot as plt
from matplotlib import lines
def load_email_as_samples():
k=2
email_path = os.getcwd() + "//project//Datasets//Email//email_... | project/DocumentDistances/misc.py | import os
from Utils.Sample import Sample
from DocumentDistances.doc2vec_email import *
from DocumentDistances.doc2vec_psalms import *
import numpy as np
import matplotlib.pyplot as plt
from matplotlib import lines
def load_email_as_samples():
k=2
email_path = os.getcwd() + "//project//Datasets//Email//email_... | 0.380068 | 0.279324 |
import plotly.graph_objects as go
from plotly.subplots import make_subplots
import dash_bootstrap_components as dbc
import dash_html_components as html
from utils.data_utils import calc_percentage, calc_vertical_percentage
from constants import *
def dataset_infos(name, ntuples, nattributes):
return f'''
... | dash/utils/figure_utils.py | import plotly.graph_objects as go
from plotly.subplots import make_subplots
import dash_bootstrap_components as dbc
import dash_html_components as html
from utils.data_utils import calc_percentage, calc_vertical_percentage
from constants import *
def dataset_infos(name, ntuples, nattributes):
return f'''
... | 0.439507 | 0.241299 |
import incremental_evaluation.utils as IE
import h5py
import numpy as np
import os
import time
TOTAL_ACCURACY = "total_accuracy"
LOCAL_ACCURACY = "local_accuracy"
SUBCLASS_ACCURACY = "subclass_accuracy"
class DataKeys(object):
"""
The structure of the HDF5 data file
"""
# file name
FILE_NAME = "d... | incremental_evaluation/data_file_helper.py | import incremental_evaluation.utils as IE
import h5py
import numpy as np
import os
import time
TOTAL_ACCURACY = "total_accuracy"
LOCAL_ACCURACY = "local_accuracy"
SUBCLASS_ACCURACY = "subclass_accuracy"
class DataKeys(object):
"""
The structure of the HDF5 data file
"""
# file name
FILE_NAME = "d... | 0.620852 | 0.398524 |
from matplotlib import cm
from gooey import GooeyParser
from gooey import Gooey
from ms_datasheet import plot_datapage
__VERSION__="0.1.1"
@Gooey(default_size=(600, 650), program_name='Davis Lab mass spec datasheet')
def main():
parser = GooeyParser(description='Plot a single datasheet for a given therom RAW file... | ms_datasheet_gui.py | from matplotlib import cm
from gooey import GooeyParser
from gooey import Gooey
from ms_datasheet import plot_datapage
__VERSION__="0.1.1"
@Gooey(default_size=(600, 650), program_name='Davis Lab mass spec datasheet')
def main():
parser = GooeyParser(description='Plot a single datasheet for a given therom RAW file... | 0.486819 | 0.236456 |
import datetime, json, logging, urllib
from easyrequest_hay_app import settings_app
from easyrequest_hay_app.models import ItemRequest
log = logging.getLogger(__name__)
class AeonUrlBuilder( object ):
def __init__( self ):
self.aeon_root_url = 'https://brown.aeon.atlas-sys.com/logon/?Action=10&Form=30... | easyrequest_hay_app/lib/aeon.py | import datetime, json, logging, urllib
from easyrequest_hay_app import settings_app
from easyrequest_hay_app.models import ItemRequest
log = logging.getLogger(__name__)
class AeonUrlBuilder( object ):
def __init__( self ):
self.aeon_root_url = 'https://brown.aeon.atlas-sys.com/logon/?Action=10&Form=30... | 0.367384 | 0.164282 |
import numpy as np
import talib as ta
from settings import evaluete
MAKER_COST = evaluete["maker_cost"]
TAKER_COST = evaluete["taker_cost"]
IMPACT = evaluete["impact"]
SLIDE = evaluete["slide"]
LEVER = evaluete["lever"]
MAX_POSITION = evaluete["max_position"]
STOP_EARN = evaluete["stop_earn"]
STOP_LOSS = evaluete["sto... | evaluete.py | import numpy as np
import talib as ta
from settings import evaluete
MAKER_COST = evaluete["maker_cost"]
TAKER_COST = evaluete["taker_cost"]
IMPACT = evaluete["impact"]
SLIDE = evaluete["slide"]
LEVER = evaluete["lever"]
MAX_POSITION = evaluete["max_position"]
STOP_EARN = evaluete["stop_earn"]
STOP_LOSS = evaluete["sto... | 0.249264 | 0.214465 |
import numpy as np
from sklearn.metrics._scorer import _ProbaScorer, _ThresholdScorer, _PredictScorer
def binary_multiclass_score_func(score_func):
def wrapper(y_true, y_pred, **kwargs):
if "average" in kwargs:
if len(np.unique(y_true)) <= 2:
kwargs["average"] = "binary"
... | pycaret/internal/metrics.py | import numpy as np
from sklearn.metrics._scorer import _ProbaScorer, _ThresholdScorer, _PredictScorer
def binary_multiclass_score_func(score_func):
def wrapper(y_true, y_pred, **kwargs):
if "average" in kwargs:
if len(np.unique(y_true)) <= 2:
kwargs["average"] = "binary"
... | 0.940831 | 0.47524 |
import subprocess
#Variables
commands=subprocess.check_output(["netsh", "wlan", "show", "profiles"]).decode('utf-8').split('\n')
networks=[i.split(':') [1] [1:-1] for i in commands if "All User Profile" in i]
#colours used
red = '\033[31m'
yellow = '\033[93m'
lgreen = '\033[92m'
clear = '\033[0m'
bold = '\033[01m'
cy... | WiFucker.py | import subprocess
#Variables
commands=subprocess.check_output(["netsh", "wlan", "show", "profiles"]).decode('utf-8').split('\n')
networks=[i.split(':') [1] [1:-1] for i in commands if "All User Profile" in i]
#colours used
red = '\033[31m'
yellow = '\033[93m'
lgreen = '\033[92m'
clear = '\033[0m'
bold = '\033[01m'
cy... | 0.158402 | 0.218065 |
import sys, math
import numpy as np
from qiskit import QuantumCircuit, ClassicalRegister, QuantumRegister, QiskitError
class HWEA:
"""
Class to implement a hardware efficient ansatz for the QAOA algorithm.
Based on the community detection circuit implemented by Francois-<NAME>.
This ansatz uses the en... | QAOA/hw_efficient_ansatz.py | import sys, math
import numpy as np
from qiskit import QuantumCircuit, ClassicalRegister, QuantumRegister, QiskitError
class HWEA:
"""
Class to implement a hardware efficient ansatz for the QAOA algorithm.
Based on the community detection circuit implemented by Francois-<NAME>.
This ansatz uses the en... | 0.651022 | 0.729074 |
class Cliente:
c_cliente=[]
cuenta=[]
interes=0
m_cuenta=[]
texto=["Id: ","Nombre: ","Apellido: ","Dia_Nac: ","Mes_Nac: ","Año_Nac: ","Dirección: ","Telefono: ","Correo: ","Tipo Cuenta: ","Moneda: ","Fondos: ","Lugar: ","Nom_Sucu: ","Regalia: ","Interes: "]
##getFondos------------------------... | Asignaciones/Clases (1)/Banco_con_clases.py |
class Cliente:
c_cliente=[]
cuenta=[]
interes=0
m_cuenta=[]
texto=["Id: ","Nombre: ","Apellido: ","Dia_Nac: ","Mes_Nac: ","Año_Nac: ","Dirección: ","Telefono: ","Correo: ","Tipo Cuenta: ","Moneda: ","Fondos: ","Lugar: ","Nom_Sucu: ","Regalia: ","Interes: "]
##getFondos------------------------... | 0.118934 | 0.184878 |
import requests
from lxml import html
import json
import re
from pattern.web import URL, DOM, plaintext
from collections import defaultdict
playerlist = dict()
players = ["3975/stephen-curry", "9/ray-allen", "552/reggie-miller", "841/jason-terry", "662/paul-pierce", "429/jason-kidd", "136/vince-carter", "165/jamal-c... | Code/data/total3pmscraper.py |
import requests
from lxml import html
import json
import re
from pattern.web import URL, DOM, plaintext
from collections import defaultdict
playerlist = dict()
players = ["3975/stephen-curry", "9/ray-allen", "552/reggie-miller", "841/jason-terry", "662/paul-pierce", "429/jason-kidd", "136/vince-carter", "165/jamal-c... | 0.239349 | 0.075551 |
import pathlib
import shutil, logging
import click
from filehash import FileHash
from pyspark.sql.functions import array, current_timestamp, explode, lit
from pyspark.sql.types import StructType, StructField, StringType, IntegerType
from luna.common.CodeTimer import CodeTimer
from luna.common.config import ConfigSet
... | pyluna-pathology/luna/pathology/proxy_table/regional_annotation/generate.py | import pathlib
import shutil, logging
import click
from filehash import FileHash
from pyspark.sql.functions import array, current_timestamp, explode, lit
from pyspark.sql.types import StructType, StructField, StringType, IntegerType
from luna.common.CodeTimer import CodeTimer
from luna.common.config import ConfigSet
... | 0.488771 | 0.177811 |
from selenium import webdriver
from selenium.webdriver.common.keys import Keys
from selenium.webdriver.common.by import By
import netaddr
import time
import os
def unique(t):
print "\n Removing duplicated lines ........ \n"
prev = None
for line in sorted(open(t)):
line = line.strip()
... | SearchImportantRange.py | from selenium import webdriver
from selenium.webdriver.common.keys import Keys
from selenium.webdriver.common.by import By
import netaddr
import time
import os
def unique(t):
print "\n Removing duplicated lines ........ \n"
prev = None
for line in sorted(open(t)):
line = line.strip()
... | 0.101534 | 0.038035 |
from conans.test.utils.tools import TestClient, GenConanfile
def test_install():
client = TestClient()
client.save({"conanfile.py": GenConanfile("pkga", "0.1").with_package_file("file.h", "0.1")})
client.run("create . user/channel")
# Use a consumer with a version range
client.save({"conanfile.py... | conans/test/functional/graph_lock/lock_install_test.py | from conans.test.utils.tools import TestClient, GenConanfile
def test_install():
client = TestClient()
client.save({"conanfile.py": GenConanfile("pkga", "0.1").with_package_file("file.h", "0.1")})
client.run("create . user/channel")
# Use a consumer with a version range
client.save({"conanfile.py... | 0.498047 | 0.12787 |
import pytest
import os
import tempfile
import numpy as np
import shutil
from edgel3.cli import positive_float, positive_int, get_file_list, parse_args, run, main
from argparse import ArgumentTypeError
from edgel3.edgel3_exceptions import EdgeL3Error
from unittest.mock import patch
TEST_DIR = os.path.dirname(__file__)... | tests/test_cli.py | import pytest
import os
import tempfile
import numpy as np
import shutil
from edgel3.cli import positive_float, positive_int, get_file_list, parse_args, run, main
from argparse import ArgumentTypeError
from edgel3.edgel3_exceptions import EdgeL3Error
from unittest.mock import patch
TEST_DIR = os.path.dirname(__file__)... | 0.458834 | 0.489015 |
from flask import render_template, redirect, url_for, flash, request, \
session, jsonify, abort
from werkzeug.urls import url_parse
from flask_login import login_user, logout_user, current_user, login_required
from flask_babel import _
from app import db
from app.auth import bp
from app.auth.forms import LoginForm,... | app/auth/routes.py | from flask import render_template, redirect, url_for, flash, request, \
session, jsonify, abort
from werkzeug.urls import url_parse
from flask_login import login_user, logout_user, current_user, login_required
from flask_babel import _
from app import db
from app.auth import bp
from app.auth.forms import LoginForm,... | 0.345105 | 0.053403 |
import pytest
from peewee import DoesNotExist
from app.logic.transcript import *
from app.models.user import User
from app.models.courseParticipant import CourseParticipant
from app.models.event import Event
from app.models.programEvent import ProgramEvent
from app.models.facilitator import Facilitator
from app.logic.... | tests/code/test_transcripts.py | import pytest
from peewee import DoesNotExist
from app.logic.transcript import *
from app.models.user import User
from app.models.courseParticipant import CourseParticipant
from app.models.event import Event
from app.models.programEvent import ProgramEvent
from app.models.facilitator import Facilitator
from app.logic.... | 0.353428 | 0.334508 |
import pytest
import reflectivipy
from .ReflectivityExample import ReflectivityExample
from reflectivipy import MetaLink
@pytest.fixture(autouse=True)
def setup():
reflectivipy.uninstall_all()
def test_original_ast_preservation():
example = ReflectivityExample()
link = MetaLink(example, 'tag_exec', 'af... | tests/test_ReflectiveMethod.py | import pytest
import reflectivipy
from .ReflectivityExample import ReflectivityExample
from reflectivipy import MetaLink
@pytest.fixture(autouse=True)
def setup():
reflectivipy.uninstall_all()
def test_original_ast_preservation():
example = ReflectivityExample()
link = MetaLink(example, 'tag_exec', 'af... | 0.584745 | 0.48499 |
import logging
import requests
import os
import sys
from tributors.utils.file import write_json
from .base import ParserBase
from tributors.main.orcid import get_orcid
bot = logging.getLogger(" zenodo")
class ZenodoParser(ParserBase):
name = "zenodo"
def __init__(self, filename=None, repo=None, params=... | tributors/main/parsers/zenodo.py | import logging
import requests
import os
import sys
from tributors.utils.file import write_json
from .base import ParserBase
from tributors.main.orcid import get_orcid
bot = logging.getLogger(" zenodo")
class ZenodoParser(ParserBase):
name = "zenodo"
def __init__(self, filename=None, repo=None, params=... | 0.439988 | 0.16043 |
import json
import argparse
import sys
import logging
import os
from os import stat
from os.path import exists
from bricklink_api.auth import oauth
from bricklink_api.catalog_item import get_price_guide, get_item, get_item_image, Type, NewOrUsed
from bricklink_api.category import get_category
from bricklink_api.user_in... | inventory_update.py | import json
import argparse
import sys
import logging
import os
from os import stat
from os.path import exists
from bricklink_api.auth import oauth
from bricklink_api.catalog_item import get_price_guide, get_item, get_item_image, Type, NewOrUsed
from bricklink_api.category import get_category
from bricklink_api.user_in... | 0.174692 | 0.085289 |
from django.db import models
# Create your models here.
class io_data(models.Model):
period = models.CharField(max_length=16)
true_value = models.FloatField()
desc = models.CharField(max_length=126)
class io_capacity_predict(models.Model):
predict_value = models.FloatField()
name = models.CharFie... | ora_dual/models.py | from django.db import models
# Create your models here.
class io_data(models.Model):
period = models.CharField(max_length=16)
true_value = models.FloatField()
desc = models.CharField(max_length=126)
class io_capacity_predict(models.Model):
predict_value = models.FloatField()
name = models.CharFie... | 0.392104 | 0.152947 |
import os
import sys
import csv
import pandas as pd
import numpy as np
from sklearn.cluster import AgglomerativeClustering
from sklearn.model_selection import KFold
import random
#random.seed(1)
def get_samples(df, nClusters):
model = AgglomerativeClustering(n_clusters=nClusters)
model.fit(df)
labels_idx ... | lib/stratify.py | import os
import sys
import csv
import pandas as pd
import numpy as np
from sklearn.cluster import AgglomerativeClustering
from sklearn.model_selection import KFold
import random
#random.seed(1)
def get_samples(df, nClusters):
model = AgglomerativeClustering(n_clusters=nClusters)
model.fit(df)
labels_idx ... | 0.181191 | 0.161353 |
import unittest
import os
import json
from processes.insert_movies2companies import Main
from processes.postgres import Postgres
try:
DB_SERVER = os.environ['DB_SERVER']
DB_PORT = os.environ['DB_PORT']
DB_DATABASE = os.environ['DB_DATABASE']
DB_USER = os.environ['DB_USER']
DB_PASSWORD = os.environ... | processes/tests/test_insert_movies2companies.py | import unittest
import os
import json
from processes.insert_movies2companies import Main
from processes.postgres import Postgres
try:
DB_SERVER = os.environ['DB_SERVER']
DB_PORT = os.environ['DB_PORT']
DB_DATABASE = os.environ['DB_DATABASE']
DB_USER = os.environ['DB_USER']
DB_PASSWORD = os.environ... | 0.404978 | 0.104021 |
import multiprocessing
import os
import pytest
import sys
# We whitelist valid test directories. If a new test directory is added, update this.
VALID_TEST_DIRS = ['failure', 'query_test', 'stress', 'unittests', 'aux_query_tests',
'shell', 'hs2', 'catalog_service', 'metadata', 'data_errors',
... | tests/run-tests.py | import multiprocessing
import os
import pytest
import sys
# We whitelist valid test directories. If a new test directory is added, update this.
VALID_TEST_DIRS = ['failure', 'query_test', 'stress', 'unittests', 'aux_query_tests',
'shell', 'hs2', 'catalog_service', 'metadata', 'data_errors',
... | 0.218503 | 0.224215 |
from modelLib import *
from trainUtils import *
import customLoss
import os
import gc
import pickle
from optparse import OptionParser
from keras.models import load_model
from keras.optimizers import Adam, RMSprop
from keras.callbacks import ModelCheckpoint, EarlyStopping, TensorBoard, CSVLogger, ReduceLROnPlateau
fro... | Code/train4.py | from modelLib import *
from trainUtils import *
import customLoss
import os
import gc
import pickle
from optparse import OptionParser
from keras.models import load_model
from keras.optimizers import Adam, RMSprop
from keras.callbacks import ModelCheckpoint, EarlyStopping, TensorBoard, CSVLogger, ReduceLROnPlateau
fro... | 0.434701 | 0.116689 |
import pytest
from django.core.urlresolvers import reverse
from .fixtures import rest_client, tag, user
def test_tags_tags_GET_401(rest_client):
"""
no unauthorized access
"""
url = reverse('tags-list')
response = rest_client.get(url)
assert response.status_code == 401
@pytest.mark.django_... | src/tests/test_tags.py | import pytest
from django.core.urlresolvers import reverse
from .fixtures import rest_client, tag, user
def test_tags_tags_GET_401(rest_client):
"""
no unauthorized access
"""
url = reverse('tags-list')
response = rest_client.get(url)
assert response.status_code == 401
@pytest.mark.django_... | 0.466359 | 0.265482 |
import time, sys
import logging
from sim800h_api import SIM800H
COMPORT_NAME = "/dev/ttyUSB0"
VERSION = "0.0.3"
def main():
print(
"..######..####.##.....##..#######....#####.....#####...##.....##\
\n\r.##....##..##..###...###.##.....##..##...##...##...##..##.....##\
\n\r.##........##..####.####.##........ | sim800h.py | import time, sys
import logging
from sim800h_api import SIM800H
COMPORT_NAME = "/dev/ttyUSB0"
VERSION = "0.0.3"
def main():
print(
"..######..####.##.....##..#######....#####.....#####...##.....##\
\n\r.##....##..##..###...###.##.....##..##...##...##...##..##.....##\
\n\r.##........##..####.####.##........ | 0.091316 | 0.096706 |
from abc import ABC, abstractmethod
from typing import List, Optional
from pycode2seq.inference.common.utils import pre_order
from pycode2seq.inference.common.node import Node
from pycode2seq.inference.methods.model import ElementNode, MethodInfo, MethodNode, ParameterNode
from pycode2seq.inference.parsing.utils impor... | pycode2seq/inference/methods/splitter.py | from abc import ABC, abstractmethod
from typing import List, Optional
from pycode2seq.inference.common.utils import pre_order
from pycode2seq.inference.common.node import Node
from pycode2seq.inference.methods.model import ElementNode, MethodInfo, MethodNode, ParameterNode
from pycode2seq.inference.parsing.utils impor... | 0.891073 | 0.340759 |
from getpass import getuser
from os import path
from sys import platform
import pickle
from simplecrypt import encrypt, decrypt
DBNAME = "db.cronos"
class Cronos():
def __init__(self, passFile=None, storeFile=None):
if passFile is None:
osType = self.get_osType()
if osType == 'os... | cronos/cronos.py | from getpass import getuser
from os import path
from sys import platform
import pickle
from simplecrypt import encrypt, decrypt
DBNAME = "db.cronos"
class Cronos():
def __init__(self, passFile=None, storeFile=None):
if passFile is None:
osType = self.get_osType()
if osType == 'os... | 0.212395 | 0.050658 |
from ansible.module_utils.hashivault import hashivault_argspec
from ansible.module_utils.hashivault import hashivault_auth_client
from ansible.module_utils.hashivault import hashivault_init
from ansible.module_utils.hashivault import hashiwrapper
import json
import requests
ANSIBLE_METADATA = {'status': ['stableinterf... | ansible/modules/hashivault/hashivault_oidc_auth_role.py | from ansible.module_utils.hashivault import hashivault_argspec
from ansible.module_utils.hashivault import hashivault_auth_client
from ansible.module_utils.hashivault import hashivault_init
from ansible.module_utils.hashivault import hashiwrapper
import json
import requests
ANSIBLE_METADATA = {'status': ['stableinterf... | 0.755005 | 0.416915 |
# Code:
"""This is a control case for isolated KC vs KC with feedback
inhibition from GGN. Here KC receives baseline inhibition from GGN,
but its activity has no effect on GGN.
"""
from __future__ import print_function
import sys
import argparse
import numpy as np
from matplotlib import pyplot as plt
import h5py as ... | mb/network/kc_ggn_nofeedback.py |
# Code:
"""This is a control case for isolated KC vs KC with feedback
inhibition from GGN. Here KC receives baseline inhibition from GGN,
but its activity has no effect on GGN.
"""
from __future__ import print_function
import sys
import argparse
import numpy as np
from matplotlib import pyplot as plt
import h5py as ... | 0.616705 | 0.37165 |
from pathlib import Path
from itertools import product
from allennlp.models.archival import load_archive
from allennlp.predictors import Predictor
from allennlp.common.params import Params
from allennlp.data.dataset_readers import DatasetReader
from allennlp.common.checks import ConfigurationError
import pytest
impor... | tests/allen/predictors/target_tagger_predictor_test.py | from pathlib import Path
from itertools import product
from allennlp.models.archival import load_archive
from allennlp.predictors import Predictor
from allennlp.common.params import Params
from allennlp.data.dataset_readers import DatasetReader
from allennlp.common.checks import ConfigurationError
import pytest
impor... | 0.675978 | 0.449574 |
import sys
sys.path.append('../../NLM') #ATENTION: This path depends on where you cloned our NLM repository
import os
import SimpleITK as sitk
from modifiedNLM.estimate.noise_estimate import rician_estimate
from modifiedNLM.filter.modified_nl_means import rician_denoise_nl_means
def NLM(imageData):
"""Wrapper ... | ImageProcessing/denoising.py | import sys
sys.path.append('../../NLM') #ATENTION: This path depends on where you cloned our NLM repository
import os
import SimpleITK as sitk
from modifiedNLM.estimate.noise_estimate import rician_estimate
from modifiedNLM.filter.modified_nl_means import rician_denoise_nl_means
def NLM(imageData):
"""Wrapper ... | 0.666822 | 0.426322 |
import freenect
from time import sleep
from threading import Thread
from collections import deque
from kivy.app import App
from kivy.clock import Clock
from kivy.properties import NumericProperty, StringProperty
from kivy.graphics import RenderContext, Color, Rectangle
from kivy.graphics.texture import Texture
from kiv... | examples/kinect/kinectviewer.py | import freenect
from time import sleep
from threading import Thread
from collections import deque
from kivy.app import App
from kivy.clock import Clock
from kivy.properties import NumericProperty, StringProperty
from kivy.graphics import RenderContext, Color, Rectangle
from kivy.graphics.texture import Texture
from kiv... | 0.655557 | 0.236737 |
# Lint as: python3
"""Input pipeline functions for VTAB and Meta-Dataset."""
from __future__ import absolute_import
from __future__ import division
from __future__ import print_function
import functools
import logging
import numpy as np
from task_adaptation import data_loader
import tensorflow.compat.v2 as tf
def... | head2toe/input_pipeline.py |
# Lint as: python3
"""Input pipeline functions for VTAB and Meta-Dataset."""
from __future__ import absolute_import
from __future__ import division
from __future__ import print_function
import functools
import logging
import numpy as np
from task_adaptation import data_loader
import tensorflow.compat.v2 as tf
def... | 0.918535 | 0.414188 |
import asyncio
import discord
import inspect
from .utils import *
from .core import (
BaseCommand,
MessageCommand,
SlashCommand,
SubCommandGroup,
UserCommand
)
from discord.ext import commands
from typing import Optional, Union, List, Type, Tuple
class CogMeta(commands.CogMeta):
"""A metaclas... | appcommands/cog.py | import asyncio
import discord
import inspect
from .utils import *
from .core import (
BaseCommand,
MessageCommand,
SlashCommand,
SubCommandGroup,
UserCommand
)
from discord.ext import commands
from typing import Optional, Union, List, Type, Tuple
class CogMeta(commands.CogMeta):
"""A metaclas... | 0.683314 | 0.109087 |
import abc, json, os, pickle
from collections import Mapping, MutableMapping
__all__ = ['ItemMapperError',
'ItemMapper', 'ExtItemMapper',
'JsonMapper', 'PickleMapper',
'DirDictReader', 'DirDict']
class ItemMapperError(Exception):
'''used when a ItemMapper fails.
'''
pas... | venv/Lib/site-packages/codeviking/collections/dict/_dirdict.py | import abc, json, os, pickle
from collections import Mapping, MutableMapping
__all__ = ['ItemMapperError',
'ItemMapper', 'ExtItemMapper',
'JsonMapper', 'PickleMapper',
'DirDictReader', 'DirDict']
class ItemMapperError(Exception):
'''used when a ItemMapper fails.
'''
pas... | 0.709321 | 0.212661 |
from optparse import OptionParser
from constants import ACTION, ENV, ALL_SERVICES
from config import Config, ServiceConfig
from service import Service
import constants
parser = OptionParser()
parser.add_option('-e', '--env', dest='env', default=ENV.DEV,
help='ENV should be [dev|prod]',
... | devops/dev.py | from optparse import OptionParser
from constants import ACTION, ENV, ALL_SERVICES
from config import Config, ServiceConfig
from service import Service
import constants
parser = OptionParser()
parser.add_option('-e', '--env', dest='env', default=ENV.DEV,
help='ENV should be [dev|prod]',
... | 0.221603 | 0.059428 |
import os
from urllib.error import HTTPError
from urllib.request import urlretrieve
def download_file_from_google_drive(id, destination):
import requests
URL = "https://docs.google.com/uc"
session = requests.Session()
response = session.get(
URL, params={"id": id, "confirm": "t", "export": "... | trame/assets/remote.py | import os
from urllib.error import HTTPError
from urllib.request import urlretrieve
def download_file_from_google_drive(id, destination):
import requests
URL = "https://docs.google.com/uc"
session = requests.Session()
response = session.get(
URL, params={"id": id, "confirm": "t", "export": "... | 0.583203 | 0.12954 |
import mock
import endpoints
import gae_ts_mon
from .test_support import test_case
from infra_libs.ts_mon import config
from infra_libs.ts_mon.common import http_metrics
from protorpc import message_types
from protorpc import remote
class FakeTime(object):
def __init__(self):
self.timestamp_now = 1000.0
... | appengine_module/gae_ts_mon/test/instrument_endpoint_test.py |
import mock
import endpoints
import gae_ts_mon
from .test_support import test_case
from infra_libs.ts_mon import config
from infra_libs.ts_mon.common import http_metrics
from protorpc import message_types
from protorpc import remote
class FakeTime(object):
def __init__(self):
self.timestamp_now = 1000.0
... | 0.573081 | 0.21103 |
import numpy as np
import pytest
from tagupy.design.generator import PlackettBurman
@pytest.fixture
def correct_input():
return [1, 2, 5, 10, 40, 80, 97]
def test_init_invalid_input():
arg = ["moge", None, np.ones((2, 3)), 3.4, 0, -22]
for el in arg:
with pytest.raises(AssertionError) as e:
... | tests/design/generator/test_plackettburman.py | import numpy as np
import pytest
from tagupy.design.generator import PlackettBurman
@pytest.fixture
def correct_input():
return [1, 2, 5, 10, 40, 80, 97]
def test_init_invalid_input():
arg = ["moge", None, np.ones((2, 3)), 3.4, 0, -22]
for el in arg:
with pytest.raises(AssertionError) as e:
... | 0.635109 | 0.672184 |
import os
import sys
import random
import numpy as np
import torch
from tlidb.TLiDB.datasets.get_dataset import get_dataset
from tlidb.TLiDB.data_loaders.data_loaders import get_dataloader
from tlidb.TLiDB.metrics.initializer import get_metric_computer
def load_datasets_split(split, tasks, datasets, config):
spli... | tlidb/examples/utils.py | import os
import sys
import random
import numpy as np
import torch
from tlidb.TLiDB.datasets.get_dataset import get_dataset
from tlidb.TLiDB.data_loaders.data_loaders import get_dataloader
from tlidb.TLiDB.metrics.initializer import get_metric_computer
def load_datasets_split(split, tasks, datasets, config):
spli... | 0.516595 | 0.247771 |
from __future__ import print_function
import collections
import math
import numpy as np
import random
import tensorflow as tf
from six.moves import range
from assignment5_word2vec.dataset import vocabulary_size, loadDataset
data, count, dictionary, reverse_dictionary = loadDataset()
class BatchGenerator():
def _... | 05 Deep Models for Texts/assignment5_word2vec/cbow.py | from __future__ import print_function
import collections
import math
import numpy as np
import random
import tensorflow as tf
from six.moves import range
from assignment5_word2vec.dataset import vocabulary_size, loadDataset
data, count, dictionary, reverse_dictionary = loadDataset()
class BatchGenerator():
def _... | 0.865381 | 0.359111 |
from rest_framework import serializers
from .models import Batch, Item
from salt_master.models import Salt
from unit_master.models import Unit
from company_master.models import Chain
class ItemSerialzer(serializers.ModelSerializer):
class Meta:
model = Item
fields = [
"name",
"unit_id",
"... | src/item_master/serializers.py | from rest_framework import serializers
from .models import Batch, Item
from salt_master.models import Salt
from unit_master.models import Unit
from company_master.models import Chain
class ItemSerialzer(serializers.ModelSerializer):
class Meta:
model = Item
fields = [
"name",
"unit_id",
"... | 0.455441 | 0.147034 |
import os
class ATM:
def __init__(self, accountListFile, transactionSummary):
self.accountList = []
self.transactionList = []
self.depositRecord = {} # key: account, value: depositted amount
self.withdrawRecord = {} ... | atm.py | import os
class ATM:
def __init__(self, accountListFile, transactionSummary):
self.accountList = []
self.transactionList = []
self.depositRecord = {} # key: account, value: depositted amount
self.withdrawRecord = {} ... | 0.261237 | 0.279275 |
from datetime import datetime
from hashlib import sha1
from os import path
from re import search
from typing import Any, Dict, List
from unicodedata import normalize
from elasticsearch_dsl import Document
from lxml import etree
from kosh.utils import logger
from kosh.utils import namespaces as ns
class entry():
'... | kosh/elastic/entry.py | from datetime import datetime
from hashlib import sha1
from os import path
from re import search
from typing import Any, Dict, List
from unicodedata import normalize
from elasticsearch_dsl import Document
from lxml import etree
from kosh.utils import logger
from kosh.utils import namespaces as ns
class entry():
'... | 0.664976 | 0.268084 |
import numpy
import unittest
import sys
PyRLA_dir = '../../'
sys.path.append(PyRLA_dir)
import sketch.leverage as lev
rawdata_mat = numpy.load(PyRLA_dir + 'data/YearPredictionMSD.npy', mmap_mode='r')
rawdata_mat = rawdata_mat[0:50007, :]
x_mat = rawdata_mat[:, 1:].T
m_int, n_int = x_mat.shape
y_mat = rawdata_mat[:, ... | sketch/test/test_leverage.py | import numpy
import unittest
import sys
PyRLA_dir = '../../'
sys.path.append(PyRLA_dir)
import sketch.leverage as lev
rawdata_mat = numpy.load(PyRLA_dir + 'data/YearPredictionMSD.npy', mmap_mode='r')
rawdata_mat = rawdata_mat[0:50007, :]
x_mat = rawdata_mat[:, 1:].T
m_int, n_int = x_mat.shape
y_mat = rawdata_mat[:, ... | 0.334263 | 0.65397 |
from typing import Union, Tuple, List
import numpy as np
import cv2
import PySpin
from .videocapture import VideoCapture
from .utils import warn
class VideoCaptureEX(VideoCapture):
"""Open a FLIR camera for video capturing.
VideoCaptureEX class is subclass of VideoCapture class.
It provides EXTENSIONS ... | EasyPySpin/videocaptureex.py | from typing import Union, Tuple, List
import numpy as np
import cv2
import PySpin
from .videocapture import VideoCapture
from .utils import warn
class VideoCaptureEX(VideoCapture):
"""Open a FLIR camera for video capturing.
VideoCaptureEX class is subclass of VideoCapture class.
It provides EXTENSIONS ... | 0.941129 | 0.490236 |
from typing import Mapping, Union
import keytree.compat
from keytree.model import GEOM_TYPES, NSMAP, Feature, Geometry
def feature(element, kmlns: Union[str, Mapping] = NSMAP) -> Feature:
kid = element.attrib.get("id")
name = element.findtext("kml:name", namespaces=kmlns) or element.findtext(
"kml:Na... | keytree/factory.py | from typing import Mapping, Union
import keytree.compat
from keytree.model import GEOM_TYPES, NSMAP, Feature, Geometry
def feature(element, kmlns: Union[str, Mapping] = NSMAP) -> Feature:
kid = element.attrib.get("id")
name = element.findtext("kml:name", namespaces=kmlns) or element.findtext(
"kml:Na... | 0.80837 | 0.448185 |
import os
import urlparse
from django.core.files.storage import FileSystemStorage
from django.core.urlresolvers import reverse
from django.db import models
from django.template.defaultfilters import slugify
from django.utils.translation import ugettext_lazy as _
from symposion.schedule.models import Presentation
CO... | cdl/coverage/models.py | import os
import urlparse
from django.core.files.storage import FileSystemStorage
from django.core.urlresolvers import reverse
from django.db import models
from django.template.defaultfilters import slugify
from django.utils.translation import ugettext_lazy as _
from symposion.schedule.models import Presentation
CO... | 0.418459 | 0.095898 |
import copy
import os
import qgis.core as qgc
from qgreenland.constants import PACKAGE_DIR
from qgreenland.util import qgis
mock_layer_cfg = {
'title': 'Example Raster',
'dataset': {
'access_method': 'http',
'metadata': {
'title': 'Example Dataset',
'abstract': 'Exampl... | qgreenland/test/util/test_qgis.py | import copy
import os
import qgis.core as qgc
from qgreenland.constants import PACKAGE_DIR
from qgreenland.util import qgis
mock_layer_cfg = {
'title': 'Example Raster',
'dataset': {
'access_method': 'http',
'metadata': {
'title': 'Example Dataset',
'abstract': 'Exampl... | 0.790894 | 0.64211 |
from copy import deepcopy
from threading import Thread, Lock
WORKER_THREAD_LIMIT = 20 # Limit for the number of concurrently running worker threads
pop_lock = Lock() # Lock for popping the top of the post_queue
class MultiThreadSearcher:
""" Multi-threading scheduler for the bot """
def __init__(self, bo... | src/realtweetornotbot/bot/multithreadsearcher.py | from copy import deepcopy
from threading import Thread, Lock
WORKER_THREAD_LIMIT = 20 # Limit for the number of concurrently running worker threads
pop_lock = Lock() # Lock for popping the top of the post_queue
class MultiThreadSearcher:
""" Multi-threading scheduler for the bot """
def __init__(self, bo... | 0.595728 | 0.117218 |
import numpy as np
import argparse
import os
import shutil
import time
import clf_utilities as clf_ut
import writers as wrtrs
from config import config
def main():
"""
Implements the second step of the experiment pipeline. Trains a series of \
classifiers based on different configurations in terms of bot... | src/algorithm_selection.py | import numpy as np
import argparse
import os
import shutil
import time
import clf_utilities as clf_ut
import writers as wrtrs
from config import config
def main():
"""
Implements the second step of the experiment pipeline. Trains a series of \
classifiers based on different configurations in terms of bot... | 0.603465 | 0.250383 |
from typing import TypeVar, Generic, Iterable
from fidget.core import Fidget, FidgetTemplate
"""
Idiomatic inner widgets are ValidWidget classes defined with the inner_widget decorator inside of wrapper ValidWidget
classes. If an inner widget is defined, it's template becomes the default inner template of the class.
... | Lib/site-packages/fidget/widgets/idiomatic_inner.py | from typing import TypeVar, Generic, Iterable
from fidget.core import Fidget, FidgetTemplate
"""
Idiomatic inner widgets are ValidWidget classes defined with the inner_widget decorator inside of wrapper ValidWidget
classes. If an inner widget is defined, it's template becomes the default inner template of the class.
... | 0.812161 | 0.246567 |
import gpiozero
import json
import sys
import time
import threading
class Ky008:
def __init__(self):
self.version = "0.9.3"
self.state = {}
self.settings = {
"notify_url": "fhtp://broadcast/{DEVICE}/app/{APP}/script/{SCRIPT}",
"pin": 6,
"initial_value": F... | phapps/button_led/led.py | import gpiozero
import json
import sys
import time
import threading
class Ky008:
def __init__(self):
self.version = "0.9.3"
self.state = {}
self.settings = {
"notify_url": "fhtp://broadcast/{DEVICE}/app/{APP}/script/{SCRIPT}",
"pin": 6,
"initial_value": F... | 0.245356 | 0.090213 |
import pandas as pd
"""
Note that Nova Scotia has a year Primary before first grade, which in this case maps to kindergarten/ISCED020.
Pre-Primary is mapped to to ISCED010.
https://novascotiaimmigration.com/live-here/education/
"""
#public
df=pd.read_csv('directoryofpublicschools2019-2020.csv',encoding='cp1252')
ISCED... | scripts/EducationalFacilities/V2/1-PreProcessing/ns/.ipynb_checkpoints/ns_isced-checkpoint.py | import pandas as pd
"""
Note that Nova Scotia has a year Primary before first grade, which in this case maps to kindergarten/ISCED020.
Pre-Primary is mapped to to ISCED010.
https://novascotiaimmigration.com/live-here/education/
"""
#public
df=pd.read_csv('directoryofpublicschools2019-2020.csv',encoding='cp1252')
ISCED... | 0.080376 | 0.116312 |
import aioboto3
import datetime
import aiohttp
import attr
from envs import env
from jose import jwt, JWTError
from .aws_srp import AWSSRP
from .exceptions import TokenVerificationException
from .userobj import UserObj
from .groupobj import GroupObj
from .utils import dict_to_cognito
@attr.s
class Cognito(object):
... | mandate/client.py | import aioboto3
import datetime
import aiohttp
import attr
from envs import env
from jose import jwt, JWTError
from .aws_srp import AWSSRP
from .exceptions import TokenVerificationException
from .userobj import UserObj
from .groupobj import GroupObj
from .utils import dict_to_cognito
@attr.s
class Cognito(object):
... | 0.55929 | 0.060446 |
import requests
import json
import os
import re
# correct discrepencies between APIs
candidateMap = {
"hillary-clinton": "hillary-clinton",
"donald-trump": "donald-trump",
"gary-johnson": "gary-johnson"
}
issueMap = {
"Health Care": "health-care",
"Economy": "economy",
"Terrorism": "terrorism",... | candidata/loadpolitifact.py | import requests
import json
import os
import re
# correct discrepencies between APIs
candidateMap = {
"hillary-clinton": "hillary-clinton",
"donald-trump": "donald-trump",
"gary-johnson": "gary-johnson"
}
issueMap = {
"Health Care": "health-care",
"Economy": "economy",
"Terrorism": "terrorism",... | 0.136464 | 0.232975 |
import wgpu # only for flags/enums
from . import register_wgpu_render_function
from ._shadercomposer import Binding, WorldObjectShader
from ._utils import to_texture_format
from ...objects import Background
from ...materials import BackgroundMaterial, BackgroundImageMaterial
from ...resources import Texture, TextureV... | pygfx/renderers/wgpu/backgroundrender.py | import wgpu # only for flags/enums
from . import register_wgpu_render_function
from ._shadercomposer import Binding, WorldObjectShader
from ._utils import to_texture_format
from ...objects import Background
from ...materials import BackgroundMaterial, BackgroundImageMaterial
from ...resources import Texture, TextureV... | 0.589362 | 0.362489 |
import unittest
from assertpy import assert_that
from algolib.geometry.dim3 import Point3D, Vector3D
class Vector3DTest(unittest.TestCase):
OFFSET = Vector3D.EPSILON
@staticmethod
def test__coordinates__then_triple_of_coordinates():
# when
result = Vector3D(5.0, -19.0, 14.2).coordinates... | tests/geometry/dim3/test_vector_3d.py | import unittest
from assertpy import assert_that
from algolib.geometry.dim3 import Point3D, Vector3D
class Vector3DTest(unittest.TestCase):
OFFSET = Vector3D.EPSILON
@staticmethod
def test__coordinates__then_triple_of_coordinates():
# when
result = Vector3D(5.0, -19.0, 14.2).coordinates... | 0.819171 | 0.742492 |
import sys
import subprocess
import logging
import ConfigParser
'''
Sync glance image between OpenStack Cluster
'''
LOG = logging.getLogger('glance-image-sync')
IMAGE_DIR = "/var/lib/glance/glance-image-sync"
CONFIG_PATH = "/etc/glance/glance-image-sync.conf"
RSYNC_COMMAND = (
"rsync -apur --partial -e 'ssh -p 22 ... | image_sync.py | import sys
import subprocess
import logging
import ConfigParser
'''
Sync glance image between OpenStack Cluster
'''
LOG = logging.getLogger('glance-image-sync')
IMAGE_DIR = "/var/lib/glance/glance-image-sync"
CONFIG_PATH = "/etc/glance/glance-image-sync.conf"
RSYNC_COMMAND = (
"rsync -apur --partial -e 'ssh -p 22 ... | 0.210279 | 0.042543 |
import requests
import json
from bs4 import BeautifulSoup
from xml.dom import minidom
def generateXML(pid, version, summary, description, modified):
dom = minidom.Document()
root_node = dom.createElement('bugrepository')
root_node.setAttribute('name', pid)
dom.appendChild(root_node)
b... | IRBFL/getXML.py | import requests
import json
from bs4 import BeautifulSoup
from xml.dom import minidom
def generateXML(pid, version, summary, description, modified):
dom = minidom.Document()
root_node = dom.createElement('bugrepository')
root_node.setAttribute('name', pid)
dom.appendChild(root_node)
b... | 0.082071 | 0.055952 |
import sys
from collections import OrderedDict
from functools import partial
import torch.nn as nn
from inplace_abn import ABN
from modules import IdentityResidualBlock, GlobalAvgPool2d
class WiderResNet(nn.Module):
def __init__(self,
structure,
norm_act=ABN,
c... | scripts/models/wider_resnet.py | import sys
from collections import OrderedDict
from functools import partial
import torch.nn as nn
from inplace_abn import ABN
from modules import IdentityResidualBlock, GlobalAvgPool2d
class WiderResNet(nn.Module):
def __init__(self,
structure,
norm_act=ABN,
c... | 0.796451 | 0.356111 |
from __future__ import unicode_literals
from django.db import migrations, models
class Migration(migrations.Migration):
dependencies = [
]
operations = [
migrations.CreateModel(
name='Message',
fields=[
('id', models.AutoField(verbose_name='ID', serialize... | rest_messaging/migrations/0001_initial.py | from __future__ import unicode_literals
from django.db import migrations, models
class Migration(migrations.Migration):
dependencies = [
]
operations = [
migrations.CreateModel(
name='Message',
fields=[
('id', models.AutoField(verbose_name='ID', serialize... | 0.658527 | 0.163112 |
from flask import Flask, render_template, redirect, url_for, request, abort
from flask_bootstrap import Bootstrap
from flask_wtf import Form
from wtforms import StringField, SubmitField
from wtforms.validators import DataRequired
from indexer import Searcher, ShelveIndexes
from lang_proc import to_query_terms
import lo... | web_ui.py | from flask import Flask, render_template, redirect, url_for, request, abort
from flask_bootstrap import Bootstrap
from flask_wtf import Form
from wtforms import StringField, SubmitField
from wtforms.validators import DataRequired
from indexer import Searcher, ShelveIndexes
from lang_proc import to_query_terms
import lo... | 0.495117 | 0.066146 |
"""Internal base classes for abstracting away common logic."""
import abc
from googlecloudsdk.api_lib.compute import base_classes
from googlecloudsdk.api_lib.compute import request_helper
from googlecloudsdk.api_lib.compute import utils
from googlecloudsdk.command_lib.compute import flags
from googlecloudsdk.core.iam i... | lib/googlecloudsdk/api_lib/compute/iam_base_classes.py | """Internal base classes for abstracting away common logic."""
import abc
from googlecloudsdk.api_lib.compute import base_classes
from googlecloudsdk.api_lib.compute import request_helper
from googlecloudsdk.api_lib.compute import utils
from googlecloudsdk.command_lib.compute import flags
from googlecloudsdk.core.iam i... | 0.530723 | 0.138404 |
import json
from django.test import TestCase
import django.core.exceptions as django_exceptions
from django.core.exceptions import ValidationError
from django.conf import settings
from djmoney.money import Money
from djmoney.contrib.exchange.models import Rate, convert_money
from djmoney.contrib.exchange.exceptions ... | InvenTree/InvenTree/tests.py | import json
from django.test import TestCase
import django.core.exceptions as django_exceptions
from django.core.exceptions import ValidationError
from django.conf import settings
from djmoney.money import Money
from djmoney.contrib.exchange.models import Rate, convert_money
from djmoney.contrib.exchange.exceptions ... | 0.589716 | 0.441673 |
import connexion
import six
from swagger_server.models.generic_response import GenericResponse # noqa: E501
from swagger_server.models.inline_response401 import InlineResponse401 # noqa: E501
from swagger_server.models.mail_attachment import MailAttachment # noqa: E501
from swagger_server.models.mail_contact import... | swagger-client/python-flask/swagger_server/controllers/default_controller.py | import connexion
import six
from swagger_server.models.generic_response import GenericResponse # noqa: E501
from swagger_server.models.inline_response401 import InlineResponse401 # noqa: E501
from swagger_server.models.mail_attachment import MailAttachment # noqa: E501
from swagger_server.models.mail_contact import... | 0.445288 | 0.075176 |
import unittest
import requests
from onlinejudge.service.atcoder import AtCoderContest, AtCoderProblem, AtCoderProblemDetailedData, AtCoderService, AtCoderSubmission
from onlinejudge.type import TestCase
class AtCoderSerivceTest(unittest.TestCase):
def test_from_url(self):
self.assertIsInstance(AtCoderS... | tests/service_atcoder.py | import unittest
import requests
from onlinejudge.service.atcoder import AtCoderContest, AtCoderProblem, AtCoderProblemDetailedData, AtCoderService, AtCoderSubmission
from onlinejudge.type import TestCase
class AtCoderSerivceTest(unittest.TestCase):
def test_from_url(self):
self.assertIsInstance(AtCoderS... | 0.577734 | 0.451447 |
import numpy as np
from mealpy.optimizer import Optimizer
class BaseTWO(Optimizer):
"""
The original version of: Tug of War Optimization (TWO)
A novel meta-heuristic algorithm: tug of war optimization
Link:
https://www.researchgate.net/publication/332088054_Tug_of_War_Optimization_Algorit... | mealpy/physics_based/TWO.py |
import numpy as np
from mealpy.optimizer import Optimizer
class BaseTWO(Optimizer):
"""
The original version of: Tug of War Optimization (TWO)
A novel meta-heuristic algorithm: tug of war optimization
Link:
https://www.researchgate.net/publication/332088054_Tug_of_War_Optimization_Algorit... | 0.767603 | 0.311767 |
from urllib.request import urlopen
import zipfile
import gzip
import rasterio
import os, urllib
import sys
import shutil
import numpy as np
import math
from preprocess import ee_collection_specifics_TFRecord
import ee
import h5py
class ee_dataset:
def __init__(self, points, buffer, startDate, stopDate, scale... | notebooks/preprocess/ee_dataset_acquisition_TFRecord.py | from urllib.request import urlopen
import zipfile
import gzip
import rasterio
import os, urllib
import sys
import shutil
import numpy as np
import math
from preprocess import ee_collection_specifics_TFRecord
import ee
import h5py
class ee_dataset:
def __init__(self, points, buffer, startDate, stopDate, scale... | 0.495361 | 0.314656 |
import datetime
import mock
from heat.engine import rsrc_defn
from heat.tests import common
from ..resources import lb_node # noqa
from ..resources.lb_node import ( # noqa
LoadbalancerDeleted,
NotFound,
NodeNotFound)
from .test_cloud_loadbalancer import FakeNode # noqa
class LBNode(lb_node.LBNode)... | contrib/rackspace/rackspace/tests/test_lb_node.py |
import datetime
import mock
from heat.engine import rsrc_defn
from heat.tests import common
from ..resources import lb_node # noqa
from ..resources.lb_node import ( # noqa
LoadbalancerDeleted,
NotFound,
NodeNotFound)
from .test_cloud_loadbalancer import FakeNode # noqa
class LBNode(lb_node.LBNode)... | 0.59972 | 0.284352 |
from pprint import pformat
from six import iteritems
class PendingHost(object):
"""
NOTE: This class is auto generated by the swagger code generator program.
Do not edit the class manually.
"""
def __init__(self):
"""
PendingHost - a model defined in Swagger
:param dict sw... | netapp/santricity/models/symbol/pending_host.py | from pprint import pformat
from six import iteritems
class PendingHost(object):
"""
NOTE: This class is auto generated by the swagger code generator program.
Do not edit the class manually.
"""
def __init__(self):
"""
PendingHost - a model defined in Swagger
:param dict sw... | 0.82925 | 0.23656 |
import json
from api import app, test_client
class TestBase():
"""
Class containing common test procedures
"""
def create_user_data(self, **kwags):
return {
'user_name': kwags.get('user_name', 'bison'),
'email': kwags.get('email', '<EMAIL>'),
'first_name': k... | tests/test_base.py | import json
from api import app, test_client
class TestBase():
"""
Class containing common test procedures
"""
def create_user_data(self, **kwags):
return {
'user_name': kwags.get('user_name', 'bison'),
'email': kwags.get('email', '<EMAIL>'),
'first_name': k... | 0.366363 | 0.15131 |
from datetime import datetime
from models import (
User as UserModel, Todo as TodoModel,
session
)
import graphene
from graphene_sqlalchemy import (
SQLAlchemyConnectionField,
SQLAlchemyObjectType
)
from extensions import bcrypt
from typing import Optional
# types
class User(SQLAlchemyObjectType):
... | schema.py | from datetime import datetime
from models import (
User as UserModel, Todo as TodoModel,
session
)
import graphene
from graphene_sqlalchemy import (
SQLAlchemyConnectionField,
SQLAlchemyObjectType
)
from extensions import bcrypt
from typing import Optional
# types
class User(SQLAlchemyObjectType):
... | 0.639736 | 0.208501 |
import os
import unittest
import numpy as np
import petab
import pypesto
from test.petab_util import folder_base
class PetabImportTest(unittest.TestCase):
@classmethod
def setUpClass(cls):
cls.petab_problems = []
cls.petab_importers = []
cls.obj_edatas = []
def test_0_import(se... | test/test_petab_import.py | import os
import unittest
import numpy as np
import petab
import pypesto
from test.petab_util import folder_base
class PetabImportTest(unittest.TestCase):
@classmethod
def setUpClass(cls):
cls.petab_problems = []
cls.petab_importers = []
cls.obj_edatas = []
def test_0_import(se... | 0.513668 | 0.391231 |
from statistics import mean
import geopandas
from shapely.geometry import LineString
import numpy as np
import pandas as pd
_MAP_KWARGS = [
"location",
"prefer_canvas",
"no_touch",
"disable_3d",
"png_enabled",
"zoom_control",
"crs",
"zoom_start",
"left",
"top",
"position",
... | geopandas/explore.py | from statistics import mean
import geopandas
from shapely.geometry import LineString
import numpy as np
import pandas as pd
_MAP_KWARGS = [
"location",
"prefer_canvas",
"no_touch",
"disable_3d",
"png_enabled",
"zoom_control",
"crs",
"zoom_start",
"left",
"top",
"position",
... | 0.878027 | 0.477128 |
from ....dyn.configuration.backend.authentication_failed_exception import AuthenticationFailedException as AuthenticationFailedException
from ....dyn.configuration.backend.backend import Backend as Backend
from ....dyn.configuration.backend.backend_access_exception import BackendAccessException as BackendAccessExceptio... | ooobuild/cssdyn/configuration/backend/__init__.py | from ....dyn.configuration.backend.authentication_failed_exception import AuthenticationFailedException as AuthenticationFailedException
from ....dyn.configuration.backend.backend import Backend as Backend
from ....dyn.configuration.backend.backend_access_exception import BackendAccessException as BackendAccessExceptio... | 0.458349 | 0.133161 |
import logging
from collections import OrderedDict
from django import template
from django.urls import reverse
from django.conf import settings
from django.utils.encoding import smart_text
from django.utils.safestring import mark_safe
from django.template import Variable, VariableDoesNotExist, Template
from django.temp... | comments/templatetags/commentstags.py | import logging
from collections import OrderedDict
from django import template
from django.urls import reverse
from django.conf import settings
from django.utils.encoding import smart_text
from django.utils.safestring import mark_safe
from django.template import Variable, VariableDoesNotExist, Template
from django.temp... | 0.562177 | 0.11689 |