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 pytest
from snuba.clickhouse.columns import ColumnSet, String, UInt
from snuba.query import SelectedExpression
from snuba.query.conditions import binary_condition
from snuba.query.expressions import Column, FunctionCall, Literal
from snuba.query.logical import Query
from snuba.query.processors.custom_function im... | tests/query/processors/test_custom_function.py | import pytest
from snuba.clickhouse.columns import ColumnSet, String, UInt
from snuba.query import SelectedExpression
from snuba.query.conditions import binary_condition
from snuba.query.expressions import Column, FunctionCall, Literal
from snuba.query.logical import Query
from snuba.query.processors.custom_function im... | 0.612194 | 0.465691 |
from sample_players import DataPlayer
import math, random
class CustomPlayer_AB(DataPlayer):
def minimax(self, state, depth):
'''
Min-max algorithm
:param state: Game state
:param depth: Depth of tree
:return: the state with highest score
'''
def min_value(... | Projects/3_Adversarial Search/my_custom_player.py | from sample_players import DataPlayer
import math, random
class CustomPlayer_AB(DataPlayer):
def minimax(self, state, depth):
'''
Min-max algorithm
:param state: Game state
:param depth: Depth of tree
:return: the state with highest score
'''
def min_value(... | 0.753104 | 0.612107 |
from django.views.generic.edit import (
CreateView,
UpdateView,
)
from django_addanother.views import CreatePopupMixin, UpdatePopupMixin
from django.urls import reverse, reverse_lazy
from django.contrib import messages
from django.contrib.auth.views import redirect_to_login
from gbe_utils.mixins import (
Gb... | gbe/views/make_troupe_view.py | from django.views.generic.edit import (
CreateView,
UpdateView,
)
from django_addanother.views import CreatePopupMixin, UpdatePopupMixin
from django.urls import reverse, reverse_lazy
from django.contrib import messages
from django.contrib.auth.views import redirect_to_login
from gbe_utils.mixins import (
Gb... | 0.461988 | 0.059237 |
from __future__ import print_function
import torch
import torch.nn as nn
from torch.autograd import Variable
import torch.optim as optim
from PIL import Image
import matplotlib.pyplot as plt
import torchvision.transforms as transforms
import torchvision.models as models
import copy
import os
# whether cuda is avai... | main.py | from __future__ import print_function
import torch
import torch.nn as nn
from torch.autograd import Variable
import torch.optim as optim
from PIL import Image
import matplotlib.pyplot as plt
import torchvision.transforms as transforms
import torchvision.models as models
import copy
import os
# whether cuda is avai... | 0.932622 | 0.427576 |
from lenstronomywrapper.LensSystem.LensComponents.macromodel_base import ComponentBase
class NFWperturber(ComponentBase):
def __init__(self, redshift, kwargs_init=None, param_min=None, param_max=None, prior=[], convention_index=False):
self._prior = prior
self._kwargs_init = kwargs_init
... | lenstronomywrapper/LensSystem/LensComponents/NFWperturber.py | from lenstronomywrapper.LensSystem.LensComponents.macromodel_base import ComponentBase
class NFWperturber(ComponentBase):
def __init__(self, redshift, kwargs_init=None, param_min=None, param_max=None, prior=[], convention_index=False):
self._prior = prior
self._kwargs_init = kwargs_init
... | 0.785144 | 0.171027 |
face_normal_happy = ['00001001000',
'00001001000',
'00000000000',
'00010000100',
'00001111000']
face_normal_tongue = ['00001001000',
'00001001000',
'00000000000',
'... | sprite.py | face_normal_happy = ['00001001000',
'00001001000',
'00000000000',
'00010000100',
'00001111000']
face_normal_tongue = ['00001001000',
'00001001000',
'00000000000',
'... | 0.436622 | 0.086054 |
import math
import random
import sys
import numpy as np
import tensorflow as tf
from multiprocessing import Pool
class paramAdapter(object):
"""This object stores the variables required to implement an adaptive
step size and number of leapfrog steps as detailed in "Adaptive Hamiltonian
and Riemann Manif... | tensorBNN/paramAdapter.py | import math
import random
import sys
import numpy as np
import tensorflow as tf
from multiprocessing import Pool
class paramAdapter(object):
"""This object stores the variables required to implement an adaptive
step size and number of leapfrog steps as detailed in "Adaptive Hamiltonian
and Riemann Manif... | 0.741955 | 0.748605 |
import os
import tushare as ts
import pandas as pd
from datetime import datetime
from datetime import timedelta
from log import log
from scipy.stats import norm
import numpy as np
import math
import json
PREFIX = 'data'
def __estimation_formula_bg_dynamic(growth, eps, pe):
''' BG formula, integrate with the norma... | libs/worker.py | import os
import tushare as ts
import pandas as pd
from datetime import datetime
from datetime import timedelta
from log import log
from scipy.stats import norm
import numpy as np
import math
import json
PREFIX = 'data'
def __estimation_formula_bg_dynamic(growth, eps, pe):
''' BG formula, integrate with the norma... | 0.2227 | 0.195038 |
from xdevs.models import Coupled, Port
from typing import Dict, Tuple, Optional
from mercury.config.core import CoreConfig
from mercury.config.network import NodeConfig
from mercury.config.smart_grid import ConsumerConfig
from mercury.config.edcs import EdgeFederationConfig
from mercury.config.iot_devices import Servic... | mercury/fog_model/core/core.py | from xdevs.models import Coupled, Port
from typing import Dict, Tuple, Optional
from mercury.config.core import CoreConfig
from mercury.config.network import NodeConfig
from mercury.config.smart_grid import ConsumerConfig
from mercury.config.edcs import EdgeFederationConfig
from mercury.config.iot_devices import Servic... | 0.851027 | 0.133924 |
from typing import overload
import cv2
import pprint
import mediapipe as mp
import time
import traceback
from cv2Decorator import cv2Decorator
class Face:
padding = 10
image_size = 200
def __init__(self):
self.trained_model =cv2.CascadeClassifier(cv2.data.haarcascades + "haarcascade_f... | Face/FaceDetecter.py | from typing import overload
import cv2
import pprint
import mediapipe as mp
import time
import traceback
from cv2Decorator import cv2Decorator
class Face:
padding = 10
image_size = 200
def __init__(self):
self.trained_model =cv2.CascadeClassifier(cv2.data.haarcascades + "haarcascade_f... | 0.384565 | 0.137561 |
import typing
from decimal import Decimal
import pydantic
import stackprinter
stackprinter.set_excepthook(style="darkbg2")
from crypto_dom.kraken.definitions import ASSETCLASS, ASSET
# ============================================================
# DEPOSIT METHODS
# =================================================... | src/crypto_dom/kraken/user_funding/deposit_methods.py | import typing
from decimal import Decimal
import pydantic
import stackprinter
stackprinter.set_excepthook(style="darkbg2")
from crypto_dom.kraken.definitions import ASSETCLASS, ASSET
# ============================================================
# DEPOSIT METHODS
# =================================================... | 0.240329 | 0.134293 |
import requests
topics = {
"topics": [
{
"text": [
"Art_Event",
"Celebrities",
"Entertainment",
"Fashion",
"Food_Drink",
"Games",
"Literature",
"Math",
... | skills/topicalchat_convert_retrieval/test_server.py | import requests
topics = {
"topics": [
{
"text": [
"Art_Event",
"Celebrities",
"Entertainment",
"Fashion",
"Food_Drink",
"Games",
"Literature",
"Math",
... | 0.22448 | 0.460107 |
from flask import Blueprint, request
import config
from blueprints.private.settings import setting
from modules.registration import Registration
from modules.validations import Validation
PublicForm_bp = Blueprint("PublicForm_bp", __name__)
register = Registration()
validate = Validation()
def responseData(data):
... | blueprints/public/form.py | from flask import Blueprint, request
import config
from blueprints.private.settings import setting
from modules.registration import Registration
from modules.validations import Validation
PublicForm_bp = Blueprint("PublicForm_bp", __name__)
register = Registration()
validate = Validation()
def responseData(data):
... | 0.320715 | 0.094971 |
import time
import pygame
import pygame.freetype
from component import config
from .game_window import GameWindow
from .system import System
from .configure import Configure
from .heartbeat import Heartbeat
from .keyboard import Keyboard
from .moving import Moving
from .painting import Painting
from .respawn impor... | system/game.py | import time
import pygame
import pygame.freetype
from component import config
from .game_window import GameWindow
from .system import System
from .configure import Configure
from .heartbeat import Heartbeat
from .keyboard import Keyboard
from .moving import Moving
from .painting import Painting
from .respawn impor... | 0.192919 | 0.087681 |
from OpenGL.raw.GL.VERSION.GL_1_0 import glClearColor
from libraries import *
import glfw
from OpenGL.GL import GL_VERSION, glGetString, GLError, glEnable, GL_BLEND, glBlendFunc, GL_SRC_ALPHA, GL_ONE_MINUS_SRC_ALPHA
import numpy as np
import sys
import ctypes
import traceback
import pyrr
from tests import *
import time... | TestApplication.py | from OpenGL.raw.GL.VERSION.GL_1_0 import glClearColor
from libraries import *
import glfw
from OpenGL.GL import GL_VERSION, glGetString, GLError, glEnable, GL_BLEND, glBlendFunc, GL_SRC_ALPHA, GL_ONE_MINUS_SRC_ALPHA
import numpy as np
import sys
import ctypes
import traceback
import pyrr
from tests import *
import time... | 0.284477 | 0.133105 |
from collections import Mapping, OrderedDict
from xldlib.general import sequence
from xldlib.utils import serialization
from .table import TableModelMixin
__all__ = [
'FrozenTable',
'TableModel'
]
# OBJECTS
# -------
class FrozenTable(OrderedDict):
'''
Nearly immutable OrderedDict with a list per... | xldlib/general/mapping/frozen.py | from collections import Mapping, OrderedDict
from xldlib.general import sequence
from xldlib.utils import serialization
from .table import TableModelMixin
__all__ = [
'FrozenTable',
'TableModel'
]
# OBJECTS
# -------
class FrozenTable(OrderedDict):
'''
Nearly immutable OrderedDict with a list per... | 0.892202 | 0.243238 |
import random
import string
# Calculate max fitness based on population
def calculate_max_fitness():
i = board_size - 1
max_fitness = 0
while i > 0:
max_fitness += i
i -= 1
return max_fitness
# Generate a random individual based on the board size
def random_individual(board_size):
... | Genetic_8QueensProblem.py |
import random
import string
# Calculate max fitness based on population
def calculate_max_fitness():
i = board_size - 1
max_fitness = 0
while i > 0:
max_fitness += i
i -= 1
return max_fitness
# Generate a random individual based on the board size
def random_individual(board_size):
... | 0.522933 | 0.605099 |
import os
import mock
import pytest
from ddtrace import Tracer
from ddtrace.internal import agent
AGENT_VERSION = os.environ.get("AGENT_VERSION")
class TestTraceAcceptedByAgent:
def test_simple_trace_accepted_by_agent(self):
tracer = Tracer()
with mock.patch("ddtrace.internal.writer.log") as l... | tests/integration/test_encoding.py | import os
import mock
import pytest
from ddtrace import Tracer
from ddtrace.internal import agent
AGENT_VERSION = os.environ.get("AGENT_VERSION")
class TestTraceAcceptedByAgent:
def test_simple_trace_accepted_by_agent(self):
tracer = Tracer()
with mock.patch("ddtrace.internal.writer.log") as l... | 0.618896 | 0.343369 |
from __future__ import absolute_import
from harness.test_base_remote import TestBaseRemote
from harness.decorators import (
cpp_only_test,
ordered_test
)
class TestBreakpointFileLineMultipleRSFiles(TestBaseRemote):
'''Tests the setting of a breakpoint on one of multiple RS files.'''
bundle_target = ... | android/android_9/frameworks/rs/tests/lldb/tests/testcases/test_breakpoint_fileline_multiple_rs_files.py | from __future__ import absolute_import
from harness.test_base_remote import TestBaseRemote
from harness.decorators import (
cpp_only_test,
ordered_test
)
class TestBreakpointFileLineMultipleRSFiles(TestBaseRemote):
'''Tests the setting of a breakpoint on one of multiple RS files.'''
bundle_target = ... | 0.547948 | 0.184437 |
import numpy as np
from sklearn.ensemble.forest import BaseForest
from sklearn.tree.tree import BaseDecisionTree
from sklearn.ensemble.weight_boosting import AdaBoostClassifier
from sklearn.tree._tree import DTYPE
from sklearn.utils import check_X_y
class AdaBoostAbstainingClassifier(AdaBoostClassifier):
def __in... | rain/adaboost.py | import numpy as np
from sklearn.ensemble.forest import BaseForest
from sklearn.tree.tree import BaseDecisionTree
from sklearn.ensemble.weight_boosting import AdaBoostClassifier
from sklearn.tree._tree import DTYPE
from sklearn.utils import check_X_y
class AdaBoostAbstainingClassifier(AdaBoostClassifier):
def __in... | 0.894525 | 0.548129 |
import requests
import re
import webbrowser
# Directions API / Static Maps API Documentation
# https://developers.google.com/maps/documentation/directions/overview
# https://developers.google.com/maps/documentation/maps-static/overview
class Coordinates:
def __init__(self, origin, destination):
'''Setup a... | google_apis.py | import requests
import re
import webbrowser
# Directions API / Static Maps API Documentation
# https://developers.google.com/maps/documentation/directions/overview
# https://developers.google.com/maps/documentation/maps-static/overview
class Coordinates:
def __init__(self, origin, destination):
'''Setup a... | 0.599954 | 0.287605 |
import tensorflow as tf
import numpy as np
import matplotlib.pyplot as plt
import os
SEED = 42
tf.set_random_seed(SEED)
class GAN():
def sample_Z(self, batch_size, n):
return np.random.uniform(-1., 1., size=(batch_size, n))
def __init__(self, num_features, num_historical_days, generator_input_size=2... | StockMarketGAN/gan.py | import tensorflow as tf
import numpy as np
import matplotlib.pyplot as plt
import os
SEED = 42
tf.set_random_seed(SEED)
class GAN():
def sample_Z(self, batch_size, n):
return np.random.uniform(-1., 1., size=(batch_size, n))
def __init__(self, num_features, num_historical_days, generator_input_size=2... | 0.68458 | 0.443239 |
import re
import time
import urllib
import random
import urlparse
from collections import namedtuple
from zitkino import log
from zitkino import http
from zitkino import parsers
from zitkino.models import Film
from . import BaseFilmID, BaseFilmService
class CsfdFilmID(BaseFilmID):
url_re = re.compile(r'/film/... | zitkino/services/csfd.py |
import re
import time
import urllib
import random
import urlparse
from collections import namedtuple
from zitkino import log
from zitkino import http
from zitkino import parsers
from zitkino.models import Film
from . import BaseFilmID, BaseFilmService
class CsfdFilmID(BaseFilmID):
url_re = re.compile(r'/film/... | 0.398992 | 0.094302 |
def check_match_format(matches):
matches = matches.upper()
if len(matches) != 5:
raise Exception("Matches must be 5 characters long!")
for letter in matches:
if letter not in ['Y', 'G', 'B']:
raise Exception ("Unrecognizable match format: Matches can only contain 'B', '... | WordleGuesser/wordle/utils.py | def check_match_format(matches):
matches = matches.upper()
if len(matches) != 5:
raise Exception("Matches must be 5 characters long!")
for letter in matches:
if letter not in ['Y', 'G', 'B']:
raise Exception ("Unrecognizable match format: Matches can only contain 'B', '... | 0.329392 | 0.458167 |
import matplotlib.pyplot as plt
import pandas as pd
from tensorflow.keras.callbacks import ModelCheckpoint, ReduceLROnPlateau
from tensorflow.keras.callbacks import EarlyStopping
from tensorflow.keras.preprocessing.image import ImageDataGenerator
from tensorflow.keras.models import Model
from tensorflow.keras.layers ... | Image_classification/simple_cnn_classifier/train.py |
import matplotlib.pyplot as plt
import pandas as pd
from tensorflow.keras.callbacks import ModelCheckpoint, ReduceLROnPlateau
from tensorflow.keras.callbacks import EarlyStopping
from tensorflow.keras.preprocessing.image import ImageDataGenerator
from tensorflow.keras.models import Model
from tensorflow.keras.layers ... | 0.66769 | 0.66324 |
import array
import os
from MSTClustering import *
from optparse import OptionParser
usage = 'test_MST.py reconFile [opt] <reconFile>'
parser = OptionParser()
parser.add_option('-o', '--output-file', type = str, dest = 'o',
default = None,
help = 'path to the output file')
parser.... | src/test/test_MST.py | import array
import os
from MSTClustering import *
from optparse import OptionParser
usage = 'test_MST.py reconFile [opt] <reconFile>'
parser = OptionParser()
parser.add_option('-o', '--output-file', type = str, dest = 'o',
default = None,
help = 'path to the output file')
parser.... | 0.214938 | 0.188063 |
from .common import Common, DefaultAnchor, DefaultDimension, DefaultBorder, BaseChart
from .termui.alignment import TopLeftAnchor, Dimension
from .termui.control import Border
from .context import ContextList
from .region import RegionList
from .ssh import SSHList
from .info import InfoDisplay
from .aws import AWS
from... | src/awsc/main.py | from .common import Common, DefaultAnchor, DefaultDimension, DefaultBorder, BaseChart
from .termui.alignment import TopLeftAnchor, Dimension
from .termui.control import Border
from .context import ContextList
from .region import RegionList
from .ssh import SSHList
from .info import InfoDisplay
from .aws import AWS
from... | 0.354321 | 0.048451 |
def array_part_loops_pruning(loops, config):
"""Apply pruning on array partitioning candidate loops.
At present, we apply the following heuristics:
- The product of all array_part loops should be greater than the total PE number
- TODO: Prune based on off-chip traffic
Parameters
----------
... | frontend/heterosa/optimizer_prune.py |
def array_part_loops_pruning(loops, config):
"""Apply pruning on array partitioning candidate loops.
At present, we apply the following heuristics:
- The product of all array_part loops should be greater than the total PE number
- TODO: Prune based on off-chip traffic
Parameters
----------
... | 0.704262 | 0.574395 |
import collections
import json
import operator
import os
from cros.factory.device import device_utils
from cros.factory.test import device_data
from cros.factory.test import session
from cros.factory.test.i18n import _
from cros.factory.test import test_case
from cros.factory.test import test_ui
from cros.factory.test... | py/test/pytests/probe/probe.py | import collections
import json
import operator
import os
from cros.factory.device import device_utils
from cros.factory.test import device_data
from cros.factory.test import session
from cros.factory.test.i18n import _
from cros.factory.test import test_case
from cros.factory.test import test_ui
from cros.factory.test... | 0.357119 | 0.200323 |
from typing import Tuple, Mapping
import random
import numpy as np
from .state import FockState
from piquasso.api.instruction import Instruction
from piquasso.api.result import Result
def vacuum(state: FockState, instruction: Instruction, shots: int) -> Result:
state.reset()
return Result(state=state)
... | piquasso/_backends/fock/general/calculations.py |
from typing import Tuple, Mapping
import random
import numpy as np
from .state import FockState
from piquasso.api.instruction import Instruction
from piquasso.api.result import Result
def vacuum(state: FockState, instruction: Instruction, shots: int) -> Result:
state.reset()
return Result(state=state)
... | 0.904205 | 0.523177 |
import re
import sys
from copy import deepcopy
class Type:
"""Class defining a C++ type with optional template parameters"""
def __init__(self, name = "", templateParams = None):
self.name = name
if templateParams:
self.templateParams = templateParams
else:
self.... | fmt_cpp_output/templateFilt.py | import re
import sys
from copy import deepcopy
class Type:
"""Class defining a C++ type with optional template parameters"""
def __init__(self, name = "", templateParams = None):
self.name = name
if templateParams:
self.templateParams = templateParams
else:
self.... | 0.250821 | 0.463687 |
import pandas
import zipfile
import re
import os
from datetime import datetime
import time
import uuid
DEST_DIR = ".\\Destination"
SOURCE_DIR = '.\\Source'
SNP_SYMBOLS_FILE_PATH = ".\\snp500.txt"
DAILY_TRADE_MINUTE_TIMESTAMP = 57480000
def process_source_dir(source_dir, dest_dir, snp_symbols):
files_by_zip = {}
... | NormalizeData/ReadData.py | import pandas
import zipfile
import re
import os
from datetime import datetime
import time
import uuid
DEST_DIR = ".\\Destination"
SOURCE_DIR = '.\\Source'
SNP_SYMBOLS_FILE_PATH = ".\\snp500.txt"
DAILY_TRADE_MINUTE_TIMESTAMP = 57480000
def process_source_dir(source_dir, dest_dir, snp_symbols):
files_by_zip = {}
... | 0.136033 | 0.08698 |
import os
import argparse
import time
import yaml
import ast
from functools import reduce
from PIL import Image
import cv2
import numpy as np
import glob
import paddle
from preprocess import preprocess, Resize, NormalizeImage, Permute, PadStride
from visualize import visualize_box_mask
from paddle.inference import Co... | dygraph/deploy/python/trt_int8_calib.py |
import os
import argparse
import time
import yaml
import ast
from functools import reduce
from PIL import Image
import cv2
import numpy as np
import glob
import paddle
from preprocess import preprocess, Resize, NormalizeImage, Permute, PadStride
from visualize import visualize_box_mask
from paddle.inference import Co... | 0.695958 | 0.152221 |
import queue as Q
import numpy as np
import math
from util import *
class Graph:
def __init__(self, file = None, numVertex = 0):
self.V = numVertex
self.E = 0
self.maxWeight = 0
self.file = file
self.edges = {}
self.adj_matrix = [[0 for x in range(self.V)] for y in r... | src/grafo.py | import queue as Q
import numpy as np
import math
from util import *
class Graph:
def __init__(self, file = None, numVertex = 0):
self.V = numVertex
self.E = 0
self.maxWeight = 0
self.file = file
self.edges = {}
self.adj_matrix = [[0 for x in range(self.V)] for y in r... | 0.152568 | 0.22482 |
from optparse import OptionParser
import os.path
import sys
import urllib2
from config import AWS_KEY, SECRET_KEY
from amazonproduct.api import API
ASIN = 'ASIN'
EAN = 'EAN'
SKU = 'SKU'
UPC = 'UPC'
def fetch_image(url, dest_path):
"""
Downloads image and saves it to ``dest_path``.
"""
fp = open(dest_... | examples/get-cover.py | from optparse import OptionParser
import os.path
import sys
import urllib2
from config import AWS_KEY, SECRET_KEY
from amazonproduct.api import API
ASIN = 'ASIN'
EAN = 'EAN'
SKU = 'SKU'
UPC = 'UPC'
def fetch_image(url, dest_path):
"""
Downloads image and saves it to ``dest_path``.
"""
fp = open(dest_... | 0.273089 | 0.070017 |
import itertools
import pytest
import uuid
from web3 import Web3
from web3._utils.caching import (
generate_cache_key,
)
from web3.middleware import (
construct_error_generator_middleware,
construct_result_generator_middleware,
construct_simple_cache_middleware,
)
from web3.providers.base ... | tests/core/middleware/test_simple_cache_middleware.py | import itertools
import pytest
import uuid
from web3 import Web3
from web3._utils.caching import (
generate_cache_key,
)
from web3.middleware import (
construct_error_generator_middleware,
construct_result_generator_middleware,
construct_simple_cache_middleware,
)
from web3.providers.base ... | 0.47926 | 0.140572 |
import requests
import os
from pandas.io.json import json_normalize
import datetime
import base64
## import API use key, API user and base URL from Jenkins variables
try:
api_key = os.environ['AUTH_API_KEY']
except KeyError:
print("API-key is missing")
try:
api_user = os.environ['AUTH_API_USER']
except ... | pdi_integrations/arvo/python_scripts/get_arvo_kysymykset.py | import requests
import os
from pandas.io.json import json_normalize
import datetime
import base64
## import API use key, API user and base URL from Jenkins variables
try:
api_key = os.environ['AUTH_API_KEY']
except KeyError:
print("API-key is missing")
try:
api_user = os.environ['AUTH_API_USER']
except ... | 0.082993 | 0.076236 |
import paho.mqtt.client as mqttClient
import mariadb
import decoder
import json
import os
import datetime
from threading import Event
# The Things Network MQQT broker credentials
broker_endpoint = os.getenv("BROKER_ADDRESS")
port = os.getenv("BROKER_PORT")
user = os.getenv("BROKER_USER")
password = os.getenv("BROKER_P... | mqtt.py | import paho.mqtt.client as mqttClient
import mariadb
import decoder
import json
import os
import datetime
from threading import Event
# The Things Network MQQT broker credentials
broker_endpoint = os.getenv("BROKER_ADDRESS")
port = os.getenv("BROKER_PORT")
user = os.getenv("BROKER_USER")
password = os.getenv("BROKER_P... | 0.21626 | 0.048226 |
from __future__ import (division, absolute_import,
print_function, unicode_literals)
import logging
from sqlalchemy import MetaData
from ...reg import reg_object1
from ...reg.result import *
from .stuff.backwardcompat import *
from .stuff import models
from .stuff.sheet_funcs import get_valu... | index/handlers/books0p3/sheet.py |
from __future__ import (division, absolute_import,
print_function, unicode_literals)
import logging
from sqlalchemy import MetaData
from ...reg import reg_object1
from ...reg.result import *
from .stuff.backwardcompat import *
from .stuff import models
from .stuff.sheet_funcs import get_valu... | 0.374905 | 0.165762 |
from io import BytesIO
from buidl.helper import (
encode_varint,
hash256,
int_to_little_endian,
read_varint,
read_varstr,
)
from buidl.siphash import SipHash_2_4
BASIC_FILTER_TYPE = 0
GOLOMB_P = 19
GOLOMB_M = int(round(1.497137 * 2 ** GOLOMB_P))
def _siphash(key, value):
if len(key) != 16:
... | buidl/compactfilter.py | from io import BytesIO
from buidl.helper import (
encode_varint,
hash256,
int_to_little_endian,
read_varint,
read_varstr,
)
from buidl.siphash import SipHash_2_4
BASIC_FILTER_TYPE = 0
GOLOMB_P = 19
GOLOMB_M = int(round(1.497137 * 2 ** GOLOMB_P))
def _siphash(key, value):
if len(key) != 16:
... | 0.753739 | 0.403684 |
from rest_framework.test import APIClient
from tests.utils import decode_content
def test_model_list_response_unfiltered():
response = APIClient().get('/snippets/')
expected = [
{
'id': 1,
'title': 'Fork bomb',
'code': ':(){ :|: & };:',
'linenos': False... | tests/test_userfields_with_modelserializer.py | from rest_framework.test import APIClient
from tests.utils import decode_content
def test_model_list_response_unfiltered():
response = APIClient().get('/snippets/')
expected = [
{
'id': 1,
'title': 'Fork bomb',
'code': ':(){ :|: & };:',
'linenos': False... | 0.47171 | 0.491212 |
from forse.tools.nn_tools import *
from forse.tools.img_tools import *
from forse.tools.mix_tools import *
from keras.models import Sequential, Model, load_model
from keras.layers import UpSampling2D, Conv2D, Activation, BatchNormalization
from keras.layers import Reshape, Dense, Input
from keras.layers import LeakyReL... | forse/networks/dcgan.py | from forse.tools.nn_tools import *
from forse.tools.img_tools import *
from forse.tools.mix_tools import *
from keras.models import Sequential, Model, load_model
from keras.layers import UpSampling2D, Conv2D, Activation, BatchNormalization
from keras.layers import Reshape, Dense, Input
from keras.layers import LeakyReL... | 0.841923 | 0.392046 |
import pathlib
import os
import sys
from tempfile import TemporaryDirectory
import pytest
from osbuild.buildroot import BuildRoot
from osbuild.monitor import LogMonitor, NullMonitor
from osbuild.pipeline import detect_host_runner
from osbuild.util import linux
from ..test import TestBase
@pytest.fixture(name="te... | test/mod/test_buildroot.py |
import pathlib
import os
import sys
from tempfile import TemporaryDirectory
import pytest
from osbuild.buildroot import BuildRoot
from osbuild.monitor import LogMonitor, NullMonitor
from osbuild.pipeline import detect_host_runner
from osbuild.util import linux
from ..test import TestBase
@pytest.fixture(name="te... | 0.331336 | 0.235746 |
from typing import List
from detector.clone import ClonePart
from detector.clone.CloneGroup import CloneGroup
class Filter:
"""
Filter clones fully covered by other clones.
"""
NAME_COMPARATOR = 'NAME_COMPARATOR'
NAME_UNIT_COMPARATOR = 'NAME_UNIT_COMPARATOR'
def __init__(self):
... | Original/detector/clone/Filter.py | from typing import List
from detector.clone import ClonePart
from detector.clone.CloneGroup import CloneGroup
class Filter:
"""
Filter clones fully covered by other clones.
"""
NAME_COMPARATOR = 'NAME_COMPARATOR'
NAME_UNIT_COMPARATOR = 'NAME_UNIT_COMPARATOR'
def __init__(self):
... | 0.563498 | 0.195805 |
from pathlib import Path
import requests
import colorama
colorama.init()
# Function for determining whether we are using a locally
# stored book or the online book
def getBook():
bookPath = Path.cwd() / 'romeoJuliet.txt'
if bookPath.exists():
print("Using locally stored book")
bookFile = open... | romeoJuliet.py | from pathlib import Path
import requests
import colorama
colorama.init()
# Function for determining whether we are using a locally
# stored book or the online book
def getBook():
bookPath = Path.cwd() / 'romeoJuliet.txt'
if bookPath.exists():
print("Using locally stored book")
bookFile = open... | 0.249447 | 0.329607 |
class Commission(object):
"""
手续费标准,包含如下属性
* self.buycost:买进手续费
* self.sellcost:卖出手续费
* self.unit:手续费单位
"""
def __init__(self, buycost=0.001, sellcost=0.002, unit="perValue"):
"""
初始化开仓、平仓的成本和单位
Args:
buycost (float): 开仓手续费
sellcost (float):... | lib/trade/cost.py | class Commission(object):
"""
手续费标准,包含如下属性
* self.buycost:买进手续费
* self.sellcost:卖出手续费
* self.unit:手续费单位
"""
def __init__(self, buycost=0.001, sellcost=0.002, unit="perValue"):
"""
初始化开仓、平仓的成本和单位
Args:
buycost (float): 开仓手续费
sellcost (float):... | 0.60964 | 0.356083 |
import importlib
from rest_framework import serializers
class InvalidValue(Exception):
def __init__(self, ref, expected_type=None):
message = "The value for %s is invalid." % ref
if expected_type is not None:
message += " Expected type or types %s." % expected_type
super().__i... | src/greenbudget/lib/rest_framework_utils/serializers.py | import importlib
from rest_framework import serializers
class InvalidValue(Exception):
def __init__(self, ref, expected_type=None):
message = "The value for %s is invalid." % ref
if expected_type is not None:
message += " Expected type or types %s." % expected_type
super().__i... | 0.901217 | 0.274218 |
from compiler import *
ui_strings = [
("music_volume", "Music Volume:"),
("sound_volume", "Sound Volume:"),
("mouse_sensitivity", "Mouse Sensitivity:"),
("invert_mouse_y_axis", "Invert Mouse Y Axis"),
("enabled", "Enabled"),
("disabled", "Disabled"),
("damage_to_player", "Damage to Player:"),
("reduced_to_1_... | module_ui_strings.py | from compiler import *
ui_strings = [
("music_volume", "Music Volume:"),
("sound_volume", "Sound Volume:"),
("mouse_sensitivity", "Mouse Sensitivity:"),
("invert_mouse_y_axis", "Invert Mouse Y Axis"),
("enabled", "Enabled"),
("disabled", "Disabled"),
("damage_to_player", "Damage to Player:"),
("reduced_to_1_... | 0.441914 | 0.283174 |
from enum import IntEnum
import struct
from matplotlib.patches import Ellipse
import numpy as np
class Options(IntEnum):
"""
Option flags for ROIs.
"""
SPLINE_FIT = 1
DOUBLE_HEADED = 2
OUTLINE = 4
OVERLAY_LABELS = 8
OVERLAY_NAMES = 16
OVERLAY_BACKGROUNDS = 32
OVERLAY_BOLD = 64... | src/napari_ijroi_reader/ijroi_utils.py | from enum import IntEnum
import struct
from matplotlib.patches import Ellipse
import numpy as np
class Options(IntEnum):
"""
Option flags for ROIs.
"""
SPLINE_FIT = 1
DOUBLE_HEADED = 2
OUTLINE = 4
OVERLAY_LABELS = 8
OVERLAY_NAMES = 16
OVERLAY_BACKGROUNDS = 32
OVERLAY_BOLD = 64... | 0.725843 | 0.335596 |
import optparse
import os
import sys
import tempfile
REPOSITORY_ROOT = os.path.abspath(os.path.join(
os.path.dirname(__file__), '..', '..', '..'))
sys.path.append(os.path.join(REPOSITORY_ROOT, 'build/android/gyp/util'))
import build_utils
JAVA_PACKAGE_PREFIX = 'org/chromium/'
def JarSources(src_dir, src_files,... | components/cronet/tools/jar_src.py |
import optparse
import os
import sys
import tempfile
REPOSITORY_ROOT = os.path.abspath(os.path.join(
os.path.dirname(__file__), '..', '..', '..'))
sys.path.append(os.path.join(REPOSITORY_ROOT, 'build/android/gyp/util'))
import build_utils
JAVA_PACKAGE_PREFIX = 'org/chromium/'
def JarSources(src_dir, src_files,... | 0.247714 | 0.097176 |
from pathlib import Path
import pandas as pd
import random
from Object.Transporter import Transporter
def transporter_data(trans_num, trans_manager, graph):
fileName = r".\Data\transporter_data.xlsx"
fileObj = Path(fileName)
if not fileObj.is_file():
trans_df = pd.read_excel(r"transporter_list.xl... | transporter/Data_create/create_trans.py | from pathlib import Path
import pandas as pd
import random
from Object.Transporter import Transporter
def transporter_data(trans_num, trans_manager, graph):
fileName = r".\Data\transporter_data.xlsx"
fileObj = Path(fileName)
if not fileObj.is_file():
trans_df = pd.read_excel(r"transporter_list.xl... | 0.106836 | 0.18228 |
import frappe
from frappe.model.document import Document
from ..lms_sketch.lms_sketch import LMSSketch
class ContestEntry(LMSSketch):
def to_dict(self, include_author=False):
owner = self.get_owner()
return {
"name": self.name,
"image_url": self.get_image_url(mode="s"),
... | mon_school/mon_school/doctype/contest_entry/contest_entry.py |
import frappe
from frappe.model.document import Document
from ..lms_sketch.lms_sketch import LMSSketch
class ContestEntry(LMSSketch):
def to_dict(self, include_author=False):
owner = self.get_owner()
return {
"name": self.name,
"image_url": self.get_image_url(mode="s"),
... | 0.711932 | 0.278784 |
import requests
import json
import random
import time
# The address of your first wallet
addressA = "Fill me in!"
# The address of your second wallet
addressB = "Fill me in!"
if len(addressA) != 99 or len(addressB) != 99:
print("Please fill in your addresses and re-run the script.")
quit()
walletdPortA = "8... | scripts/makechange.py | import requests
import json
import random
import time
# The address of your first wallet
addressA = "Fill me in!"
# The address of your second wallet
addressB = "Fill me in!"
if len(addressA) != 99 or len(addressB) != 99:
print("Please fill in your addresses and re-run the script.")
quit()
walletdPortA = "8... | 0.311217 | 0.132346 |
from data_importers.management.commands import BaseXpressDemocracyClubCsvImporter
class Command(BaseXpressDemocracyClubCsvImporter):
council_id = "CHR"
addresses_name = (
"2021-04-16T12:59:18.049121/Re-submission - Democracy_Club__06May2021.tsv"
)
stations_name = (
"2021-04-16T12:59:18... | polling_stations/apps/data_importers/management/commands/import_cherwell.py | from data_importers.management.commands import BaseXpressDemocracyClubCsvImporter
class Command(BaseXpressDemocracyClubCsvImporter):
council_id = "CHR"
addresses_name = (
"2021-04-16T12:59:18.049121/Re-submission - Democracy_Club__06May2021.tsv"
)
stations_name = (
"2021-04-16T12:59:18... | 0.477554 | 0.308594 |
import logging
import os
import pathlib
import pickle
import numpy as np
import pandas as pd
from datasketch import MinHashLSHForest, MinHash, MinHashLSH, LeanMinHash
import src.QueryDatabase as queryDatabase
NUM_PERM = 128
logging.basicConfig(filename='app.log', filemode='w', format='%(name)s - %(levelname)s - %(m... | src/ClusterColumns.py | import logging
import os
import pathlib
import pickle
import numpy as np
import pandas as pd
from datasketch import MinHashLSHForest, MinHash, MinHashLSH, LeanMinHash
import src.QueryDatabase as queryDatabase
NUM_PERM = 128
logging.basicConfig(filename='app.log', filemode='w', format='%(name)s - %(levelname)s - %(m... | 0.591133 | 0.264317 |
from ixnetwork_restpy.base import Base
from ixnetwork_restpy.files import Files
class AdvancedFilter(Base):
"""The AdvancedFilter class encapsulates a user managed advancedFilter node in the ixnetwork hierarchy.
An instance of the class can be obtained by accessing the AdvancedFilter property from a p... | RestPy/ixnetwork_restpy/testplatform/sessions/ixnetwork/statistics/view/layer47applibrarytrafficfilter/advancedfilter/advancedfilter.py |
from ixnetwork_restpy.base import Base
from ixnetwork_restpy.files import Files
class AdvancedFilter(Base):
"""The AdvancedFilter class encapsulates a user managed advancedFilter node in the ixnetwork hierarchy.
An instance of the class can be obtained by accessing the AdvancedFilter property from a p... | 0.867036 | 0.321713 |
from collections import OrderedDict
from functools import partial
import numpy as np
import torch
import torch.nn as nn
from models.psgn_fc import PSGN_CONV, PSGN_FC
from models.projection import Projector
from models.edge_detection import EdgeDetector
from losses.proj_losses import *
import utils.network_utils
c... | models/networks_psgn.py |
from collections import OrderedDict
from functools import partial
import numpy as np
import torch
import torch.nn as nn
from models.psgn_fc import PSGN_CONV, PSGN_FC
from models.projection import Projector
from models.edge_detection import EdgeDetector
from losses.proj_losses import *
import utils.network_utils
c... | 0.938491 | 0.308985 |
import sys
import unittest
from libcloud.utils.py3 import httplib
from libcloud.common.types import InvalidCredsError
from libcloud.common.dimensiondata import DimensionDataAPIException
from libcloud.compute.drivers.dimensiondata import DimensionDataNodeDriver as DimensionData
from libcloud.compute.base import Node, N... | libcloud/test/compute/test_dimensiondata.py | import sys
import unittest
from libcloud.utils.py3 import httplib
from libcloud.common.types import InvalidCredsError
from libcloud.common.dimensiondata import DimensionDataAPIException
from libcloud.compute.drivers.dimensiondata import DimensionDataNodeDriver as DimensionData
from libcloud.compute.base import Node, N... | 0.380068 | 0.23803 |
import numpy as np
from numba import njit
# read binary raw image files for xviii camera
@njit
def load_xviii_bayer_from_binary(binary_data, image_height, image_width):
"""Read XVIII binary images into bayer array
Parameters
-----------
binary_data : numpy.ndarray
binary image data from XVIII... | correct_images/loaders/xviii.py | import numpy as np
from numba import njit
# read binary raw image files for xviii camera
@njit
def load_xviii_bayer_from_binary(binary_data, image_height, image_width):
"""Read XVIII binary images into bayer array
Parameters
-----------
binary_data : numpy.ndarray
binary image data from XVIII... | 0.805096 | 0.574335 |
class tree_node :
def __init__(self ,value=None) :
self.value = value
self.left = None
self.right = None
def __str__(self) :
return str(self.value)
class Binary_tree (tree_node):
def __init__(self,root=None) :
self.roo... | python/code_challenges/all_tree_challenge.py/tree.py | class tree_node :
def __init__(self ,value=None) :
self.value = value
self.left = None
self.right = None
def __str__(self) :
return str(self.value)
class Binary_tree (tree_node):
def __init__(self,root=None) :
self.roo... | 0.510985 | 0.318227 |
import time
import math
import json
import spidev
class PT100(object):
def __init__(self, number, average_number=5):
self.__average_number = average_number
self.spi = spidev.SpiDev()
self.spi.open(0, number)
self.spi.max_speed_hz = 100000
self.spi.mode = 1
"""
... | src/hardware/pt100.py | import time
import math
import json
import spidev
class PT100(object):
def __init__(self, number, average_number=5):
self.__average_number = average_number
self.spi = spidev.SpiDev()
self.spi.open(0, number)
self.spi.max_speed_hz = 100000
self.spi.mode = 1
"""
... | 0.493409 | 0.198258 |
import os
import sys
dir_path = os.path.dirname(os.path.realpath(__file__)) # NOQA
sys.path.append(dir_path) # NOQA
import importlib
from flask import Flask, jsonify
from flask_cors import CORS
from flake8.api import legacy as flake8
from logging_config import logger
app = Flask(__name__)
CORS(app)
TASK_NUM = 8
... | src/server.py | import os
import sys
dir_path = os.path.dirname(os.path.realpath(__file__)) # NOQA
sys.path.append(dir_path) # NOQA
import importlib
from flask import Flask, jsonify
from flask_cors import CORS
from flake8.api import legacy as flake8
from logging_config import logger
app = Flask(__name__)
CORS(app)
TASK_NUM = 8
... | 0.252016 | 0.096493 |
import numpy as np
import os, sys
import copy
import torch
import torch.utils.data
sys.path.append(os.path.join(os.path.dirname(os.path.abspath(__file__)), '..', '..'))
from common.geometry import Camera
sys.path.append(os.path.dirname(os.path.abspath(__file__)))
from mesh_dataset import MeshLoader
class LoaderSingle(... | core/dataset/loader_single.py | import numpy as np
import os, sys
import copy
import torch
import torch.utils.data
sys.path.append(os.path.join(os.path.dirname(os.path.abspath(__file__)), '..', '..'))
from common.geometry import Camera
sys.path.append(os.path.dirname(os.path.abspath(__file__)))
from mesh_dataset import MeshLoader
class LoaderSingle(... | 0.524638 | 0.313893 |
import struct
import json
# Table 5.3 Some of the type values for DOS partitions.
# More partition values can be found here:
# http://www.win.tue.nl/~aeb/partitions/partition_types-1.html
DOS_PARTITIONS = {
0x00: "Empty",
0x01: "FAT12, CHS",
0x04: "FAT16, 16-32 MB, CHS",
0x05: "Microsoft Extended, CHS... | mbr.py | import struct
import json
# Table 5.3 Some of the type values for DOS partitions.
# More partition values can be found here:
# http://www.win.tue.nl/~aeb/partitions/partition_types-1.html
DOS_PARTITIONS = {
0x00: "Empty",
0x01: "FAT12, CHS",
0x04: "FAT16, 16-32 MB, CHS",
0x05: "Microsoft Extended, CHS... | 0.335677 | 0.365853 |
import GPy
import numpy as np
from GPy.kern.src.rbf import RBF
from paramz.caching import Cache_this
from scipy.special import logsumexp
import timeit
import os
class TauRBF(RBF):
def __init__(self, input_dim, features, demonstrations, art_demonstrations, discount, lengthscale=None):
# print("U... | kernel/rhorbfborlange.py | import GPy
import numpy as np
from GPy.kern.src.rbf import RBF
from paramz.caching import Cache_this
from scipy.special import logsumexp
import timeit
import os
class TauRBF(RBF):
def __init__(self, input_dim, features, demonstrations, art_demonstrations, discount, lengthscale=None):
# print("U... | 0.343892 | 0.33181 |
from odoo import models,fields,api,_
class VoucherHistory(models.Model):
_inherit = "voucher.history"
marketplace_seller_id = fields.Many2one("res.partner", string="Seller")
@api.model
def create(self, vals):
res = super(VoucherHistory, self).create(vals)
res.marketplace_seller_id =... | addons/marketplace_voucher/models/mp_voucher_voucher.py |
from odoo import models,fields,api,_
class VoucherHistory(models.Model):
_inherit = "voucher.history"
marketplace_seller_id = fields.Many2one("res.partner", string="Seller")
@api.model
def create(self, vals):
res = super(VoucherHistory, self).create(vals)
res.marketplace_seller_id =... | 0.30549 | 0.100216 |
import datetime
import re
from collections import OrderedDict
from importlib import import_module
import iso8601
_IMPLEMENTATIONS = {}
class Implementation:
module_name = None
def __init__(self):
self._module = None
if self.module_name:
try:
self._module = imp... | src/basicserial/util.py |
import datetime
import re
from collections import OrderedDict
from importlib import import_module
import iso8601
_IMPLEMENTATIONS = {}
class Implementation:
module_name = None
def __init__(self):
self._module = None
if self.module_name:
try:
self._module = imp... | 0.527317 | 0.16896 |
from __future__ import absolute_import
import uuid
from .core import _validate_bool
from .number import _validate_int
from .common import make_optional_argument_default
_undefined = make_optional_argument_default()
def _variant_to_string(variant):
return {
uuid.RESERVED_NCS: "RESERVED_NCS",
uu... | venv/lib/python3.8/site-packages/validation/uuid.py | from __future__ import absolute_import
import uuid
from .core import _validate_bool
from .number import _validate_int
from .common import make_optional_argument_default
_undefined = make_optional_argument_default()
def _variant_to_string(variant):
return {
uuid.RESERVED_NCS: "RESERVED_NCS",
uu... | 0.864496 | 0.134548 |
import os
import numpy as np
import pandas as pd
import matplotlib.pyplot as plt
import seaborn as sns
from skimage.io import imread
import keras
from keras import Sequential
from tensorflow.keras.applications.mobilenet import MobileNet
from keras.layers import Dense
from keras.preprocessing import image
impo... | Classifiers/CNN.py | import os
import numpy as np
import pandas as pd
import matplotlib.pyplot as plt
import seaborn as sns
from skimage.io import imread
import keras
from keras import Sequential
from tensorflow.keras.applications.mobilenet import MobileNet
from keras.layers import Dense
from keras.preprocessing import image
impo... | 0.381565 | 0.302146 |
import discord
import datetime
import warnings
from discord.ext import commands, tasks
from discord import app_commands
import aiohttp
import aiohttp
class example(commands.Cog):
def __init__(self, bot: commands.Bot,) -> None:
self.bot = bot
@app_commands.command(name="clean", description="clea... | cogs/example.py | import discord
import datetime
import warnings
from discord.ext import commands, tasks
from discord import app_commands
import aiohttp
import aiohttp
class example(commands.Cog):
def __init__(self, bot: commands.Bot,) -> None:
self.bot = bot
@app_commands.command(name="clean", description="clea... | 0.298287 | 0.081703 |
from layeredGraphLayouter.containers.constants import PortType, PortSide
from layeredGraphLayouter.containers.lNode import LNode
from layeredGraphLayouter.crossing.abstractBarycenterPortDistributor import AbstractBarycenterPortDistributor
class NodeRelativePortDistributor(AbstractBarycenterPortDistributor):
def ... | layeredGraphLayouter/crossing/nodeRelativePortDistributor.py | from layeredGraphLayouter.containers.constants import PortType, PortSide
from layeredGraphLayouter.containers.lNode import LNode
from layeredGraphLayouter.crossing.abstractBarycenterPortDistributor import AbstractBarycenterPortDistributor
class NodeRelativePortDistributor(AbstractBarycenterPortDistributor):
def ... | 0.492432 | 0.340471 |
import matplotlib
matplotlib.use('Agg')
import numpy as np
from scipy.stats import pearsonr
import pylab as pl
import sys
import json
import yaml
sys.path.append("code/striatal_model")
import params
import colors
from plot_tools2 import *
import matplotlib.pyplot as plt
import pandas
import seaborn as sbn
import matplo... | code/analysis/plot_competing_correlations.py | import matplotlib
matplotlib.use('Agg')
import numpy as np
from scipy.stats import pearsonr
import pylab as pl
import sys
import json
import yaml
sys.path.append("code/striatal_model")
import params
import colors
from plot_tools2 import *
import matplotlib.pyplot as plt
import pandas
import seaborn as sbn
import matplo... | 0.279828 | 0.416559 |
from django.conf.urls.defaults import patterns, url
from django.test import TestCase
from djangorestframework import status
from djangorestframework.views import View
from djangorestframework.compat import View as DjangoView
from djangorestframework.renderers import BaseRenderer, JSONRenderer, YAMLRenderer, \
XMLR... | djangorestframework/tests/renderers.py | from django.conf.urls.defaults import patterns, url
from django.test import TestCase
from djangorestframework import status
from djangorestframework.views import View
from djangorestframework.compat import View as DjangoView
from djangorestframework.renderers import BaseRenderer, JSONRenderer, YAMLRenderer, \
XMLR... | 0.755366 | 0.15034 |
import tweepy
import urllib.request
import pandas as pd
# Authenticate to Twitter
from os import environ
CONSUMER_KEY = environ['CONSUMER_KEY']
CONSUMER_SECRET = environ['CONSUMER_SECRET']
ACCESS_KEY = environ['ACCESS_KEY']
ACCESS_SECRET = environ['ACCESS_SECRET']
auth = tweepy.OAuthHandler(CONSUMER_KEY, CONSUMER_SECR... | fetch.py | import tweepy
import urllib.request
import pandas as pd
# Authenticate to Twitter
from os import environ
CONSUMER_KEY = environ['CONSUMER_KEY']
CONSUMER_SECRET = environ['CONSUMER_SECRET']
ACCESS_KEY = environ['ACCESS_KEY']
ACCESS_SECRET = environ['ACCESS_SECRET']
auth = tweepy.OAuthHandler(CONSUMER_KEY, CONSUMER_SECR... | 0.098767 | 0.091911 |
loadouts_const = [
{
"id": "1MobOPbsFZoVpLWDUUgmeg",
"name": "dp27",
"weapon_type": "primary",
"weapon_image_url": "https://staticctf.akamaized.net/J3yJr34U2pZ2Ieem48Dwy9uqj5PNUQTn/7LoT7yAe0LK7bDOeq6MZZM/33995bc704667674af1b73fe962d4c7c/Primary_gun_DP27.png"
},
{
"id"... | r6sapi/definitions/loadouts.py | loadouts_const = [
{
"id": "1MobOPbsFZoVpLWDUUgmeg",
"name": "dp27",
"weapon_type": "primary",
"weapon_image_url": "https://staticctf.akamaized.net/J3yJr34U2pZ2Ieem48Dwy9uqj5PNUQTn/7LoT7yAe0LK7bDOeq6MZZM/33995bc704667674af1b73fe962d4c7c/Primary_gun_DP27.png"
},
{
"id"... | 0.259638 | 0.276211 |
import io
import json
import os
import re
import time
from ast import literal_eval
from collections import OrderedDict
from datetime import datetime
from tempfile import NamedTemporaryFile
from unittest import TestCase
import pandas as pd
import pytest
from hypothesis import (
given,
settings,
)
from hypothe... | tests/test_values.py | import io
import json
import os
import re
import time
from ast import literal_eval
from collections import OrderedDict
from datetime import datetime
from tempfile import NamedTemporaryFile
from unittest import TestCase
import pandas as pd
import pytest
from hypothesis import (
given,
settings,
)
from hypothe... | 0.418459 | 0.328987 |
from .pya import Asig
import numpy as np
from scipy import signal
from .helpers import get_length, normalize
class Ugen(Asig):
"""Unit Generator for to create Asig with predefined signal"""
def __init__(self):
pass
def sine(self, freq=440, amp=1.0, dur=1.0, sr=44100, channels=1, cn=None, label=... | pya/Ugen.py | from .pya import Asig
import numpy as np
from scipy import signal
from .helpers import get_length, normalize
class Ugen(Asig):
"""Unit Generator for to create Asig with predefined signal"""
def __init__(self):
pass
def sine(self, freq=440, amp=1.0, dur=1.0, sr=44100, channels=1, cn=None, label=... | 0.941271 | 0.392541 |
import logging
from datetime import datetime
from typing import Optional, Mapping, List
import paho.mqtt.client as mqtt
from p2k16.core import P2k16UserException, membership_management
from p2k16.core import account_management, event_management, badge_management
from p2k16.core.models import db, Account, Circle, Event... | web/src/p2k16/core/tool.py | import logging
from datetime import datetime
from typing import Optional, Mapping, List
import paho.mqtt.client as mqtt
from p2k16.core import P2k16UserException, membership_management
from p2k16.core import account_management, event_management, badge_management
from p2k16.core.models import db, Account, Circle, Event... | 0.725162 | 0.090454 |
import dash
from dash import html
from dash import dcc
import dash_bootstrap_components as dbc
import RoiCalc
app = dash.Dash(__name__, external_stylesheets=[dbc.themes.BOOTSTRAP])
def default_inputs(key=False):
default_inputs = {
"user_count": 250,
"user_cost": 20,
"it_cost": 500,
... | routes.py | import dash
from dash import html
from dash import dcc
import dash_bootstrap_components as dbc
import RoiCalc
app = dash.Dash(__name__, external_stylesheets=[dbc.themes.BOOTSTRAP])
def default_inputs(key=False):
default_inputs = {
"user_count": 250,
"user_cost": 20,
"it_cost": 500,
... | 0.378574 | 0.135032 |
import numpy
from PIL import Image
import matplotlib.pyplot as plt
import torchvision.transforms as T
import torchvision
import numpy as np
import cv2
import random
class ObjectDescriptor:
def __init__(self, name, image, borders):
self.name = name
self.image = image
self.borders = borders
... | src/ImageUtils/ObjectFetcher.py | import numpy
from PIL import Image
import matplotlib.pyplot as plt
import torchvision.transforms as T
import torchvision
import numpy as np
import cv2
import random
class ObjectDescriptor:
def __init__(self, name, image, borders):
self.name = name
self.image = image
self.borders = borders
... | 0.446736 | 0.381076 |
import os
import io
import time
import logging
# 8 data types
import collections
# 13 data compression and archiving
import tarfile
import humanfriendly
from backup.reporter import Reporter, ReporterCheck, ReporterCheckResult
from backup.utils import formatkv, timestamp4now, timestamp2date
class ArchiveResult(colle... | backup/archive.py | import os
import io
import time
import logging
# 8 data types
import collections
# 13 data compression and archiving
import tarfile
import humanfriendly
from backup.reporter import Reporter, ReporterCheck, ReporterCheckResult
from backup.utils import formatkv, timestamp4now, timestamp2date
class ArchiveResult(colle... | 0.442155 | 0.147065 |
__all__ = [
'bind_label',
'define_binder',
'define_binder_for',
'define_maker',
'depend_parameter_for',
'get_annotations',
]
import functools
import inspect
from startup import startup
from . import parameters
def get_annotations(func):
signature = inspect.signature(func)
annotatio... | py/g1/apps/g1/apps/utils.py |
__all__ = [
'bind_label',
'define_binder',
'define_binder_for',
'define_maker',
'depend_parameter_for',
'get_annotations',
]
import functools
import inspect
from startup import startup
from . import parameters
def get_annotations(func):
signature = inspect.signature(func)
annotatio... | 0.83762 | 0.191479 |
import unittest
from inclusion_analysis.graph import FileGraph
from inclusion_analysis.graph import Graph
from inclusion_analysis.graph import cycle_detect
def list_rotate(l):
item = l.pop()
l.insert(0, item)
def assertSameList(l1, l2):
for i in range(0, len(l1)):
list_rotate(l1)
if l1 ==... | tests/graph_test.py | import unittest
from inclusion_analysis.graph import FileGraph
from inclusion_analysis.graph import Graph
from inclusion_analysis.graph import cycle_detect
def list_rotate(l):
item = l.pop()
l.insert(0, item)
def assertSameList(l1, l2):
for i in range(0, len(l1)):
list_rotate(l1)
if l1 ==... | 0.292696 | 0.450662 |
import os
import re
import sys
import subprocess
import json
from collections import namedtuple, OrderedDict
import requests
from requests.auth import HTTPBasicAuth
def _str(s):
if sys.version_info >= (3, 0):
return s.decode('utf-8')
return s
os.makedirs(".git/changes", exist_ok=True)
if len(sys.a... | devtools/git/github-changelog.py |
import os
import re
import sys
import subprocess
import json
from collections import namedtuple, OrderedDict
import requests
from requests.auth import HTTPBasicAuth
def _str(s):
if sys.version_info >= (3, 0):
return s.decode('utf-8')
return s
os.makedirs(".git/changes", exist_ok=True)
if len(sys.a... | 0.187542 | 0.092074 |
from neutron.plugins.ml2 import driver_api as api
from neutron.plugins.ml2 import driver_context
class TestMechanismDriver(api.MechanismDriver):
"""Test mechanism driver for testing mechanism driver api."""
def initialize(self):
pass
def _check_network_context(self, context, original_expected):... | neutron/tests/unit/ml2/drivers/mechanism_test.py |
from neutron.plugins.ml2 import driver_api as api
from neutron.plugins.ml2 import driver_context
class TestMechanismDriver(api.MechanismDriver):
"""Test mechanism driver for testing mechanism driver api."""
def initialize(self):
pass
def _check_network_context(self, context, original_expected):... | 0.754734 | 0.327064 |
from coppertop.core import PP, Missing
from coppertop.pipe import *
from bones.core.types import N, num, aliased, anon, pytuple, pylist, tv, named
from bones.metatypes import BTAtom, cacheAndUpdate, fitsWithin as _fitsWithin
from coppertop.std import tvarray, check, equal
matrix = N**N**num
colvec = matrix['colve... | src/std/coppertop/std/examples/linalg.py |
from coppertop.core import PP, Missing
from coppertop.pipe import *
from bones.core.types import N, num, aliased, anon, pytuple, pylist, tv, named
from bones.metatypes import BTAtom, cacheAndUpdate, fitsWithin as _fitsWithin
from coppertop.std import tvarray, check, equal
matrix = N**N**num
colvec = matrix['colve... | 0.380068 | 0.538983 |
import pandas as pd
import tensorflow as tf
from sklearn.preprocessing import LabelEncoder
from sklearn.preprocessing import StandardScaler
from sklearn import preprocessing
import numpy as np
import collections
import datetime
import os
import sys
import random
import csv
import config
import logging
from DNN import ... | utils.py | import pandas as pd
import tensorflow as tf
from sklearn.preprocessing import LabelEncoder
from sklearn.preprocessing import StandardScaler
from sklearn import preprocessing
import numpy as np
import collections
import datetime
import os
import sys
import random
import csv
import config
import logging
from DNN import ... | 0.18628 | 0.320888 |
from pathlib import Path
import logging
import os
import subprocess
from requests.adapters import HTTPAdapter
from requests.packages.urllib3.util.retry import Retry
import requests
log = logging.getLogger()
esp32 = "http://board_ip"
# Original Source: https://www.peterbe.com/plog/best-practice-with-retries-with-... | scripts/main.py |
from pathlib import Path
import logging
import os
import subprocess
from requests.adapters import HTTPAdapter
from requests.packages.urllib3.util.retry import Retry
import requests
log = logging.getLogger()
esp32 = "http://board_ip"
# Original Source: https://www.peterbe.com/plog/best-practice-with-retries-with-... | 0.430866 | 0.106691 |
import numpy
import random
from yoolkit.constant import Constant
constant = Constant()
constant.PADDING = '<PAD>'
constant.MATCHING = '<MAT>'
constant.DELETION = '<DEL>'
constant.INSERTION = '<INS>'
constant.SUBSTITUTION = '<SUB>'
"""LevenshteinTool can Calculating Levenshtein-Distance, Printing Manipulation-Se... | yoolkit/levenshtein.py |
import numpy
import random
from yoolkit.constant import Constant
constant = Constant()
constant.PADDING = '<PAD>'
constant.MATCHING = '<MAT>'
constant.DELETION = '<DEL>'
constant.INSERTION = '<INS>'
constant.SUBSTITUTION = '<SUB>'
"""LevenshteinTool can Calculating Levenshtein-Distance, Printing Manipulation-Se... | 0.671578 | 0.607401 |
import time
from .. import DB
from . import STD_STRING_SIZE
from .attributeDefinition import AttributeDefinition
from . import item
__all__ = ['ItemType', 'ItemTypeToItemType', 'ItemTypeToAttributeDefinition']
class ItemType (DB.Model):
__tablename__ = 'ItemType'
id = DB.Column(DB.Integer, primary_key=Tru... | total_tolles_ferleihsystem/db_models/itemType.py | import time
from .. import DB
from . import STD_STRING_SIZE
from .attributeDefinition import AttributeDefinition
from . import item
__all__ = ['ItemType', 'ItemTypeToItemType', 'ItemTypeToAttributeDefinition']
class ItemType (DB.Model):
__tablename__ = 'ItemType'
id = DB.Column(DB.Integer, primary_key=Tru... | 0.548915 | 0.161452 |
import password_generator as pg
import user_login as ul
import user_document_folder as udl
import encrypt_cred_file as ecf
import time
import os
from os import path
class UserCred:
def __init__(self):
self.USER_PATH = udl.DOC_LOC
self.star = "*" * 50
self.line = "-" * 50
# Checks... | Login Credentials Generator/M_Func.py | import password_generator as pg
import user_login as ul
import user_document_folder as udl
import encrypt_cred_file as ecf
import time
import os
from os import path
class UserCred:
def __init__(self):
self.USER_PATH = udl.DOC_LOC
self.star = "*" * 50
self.line = "-" * 50
# Checks... | 0.267695 | 0.068725 |
### Load libraries
import argparse, os, sys
import numpy as np
import nibabel as nib
import torch
from torch import nn
from torch import Tensor
from torch.utils.data import DataLoader
from torch import autograd
import pickle as pk
from pathlib import Path as pt
sys.path.insert(0, os.path.dirname(pt(__file__).absolute(... | ainas/upsample_sardunet_v1.py |
### Load libraries
import argparse, os, sys
import numpy as np
import nibabel as nib
import torch
from torch import nn
from torch import Tensor
from torch.utils.data import DataLoader
from torch import autograd
import pickle as pk
from pathlib import Path as pt
sys.path.insert(0, os.path.dirname(pt(__file__).absolute(... | 0.419529 | 0.323941 |
from datetime import datetime, timedelta
from uuid import uuid4
import pytest
from django.utils import timezone
from freezegun import freeze_time
from ee.clickhouse.models.event import create_event
from ee.clickhouse.models.session_recording_event import create_session_recording_event
from ee.clickhouse.queries.funne... | ee/clickhouse/queries/funnels/test/test_funnel_unordered_persons.py | from datetime import datetime, timedelta
from uuid import uuid4
import pytest
from django.utils import timezone
from freezegun import freeze_time
from ee.clickhouse.models.event import create_event
from ee.clickhouse.models.session_recording_event import create_session_recording_event
from ee.clickhouse.queries.funne... | 0.486819 | 0.337859 |
from Imaging import Imaging, Camera
import numpy as np
from skimage.draw import circle
from skimage.measure import regionprops,label
import matplotlib.pyplot as plt
plt.style.use('fivethirtyeight')
cam = Camera()
cam.configureGPIO()
cam.configureProperties()
imaging = Imaging(cam)
exposures = np.array([7000,3000])
T... | BeadCV.py | from Imaging import Imaging, Camera
import numpy as np
from skimage.draw import circle
from skimage.measure import regionprops,label
import matplotlib.pyplot as plt
plt.style.use('fivethirtyeight')
cam = Camera()
cam.configureGPIO()
cam.configureProperties()
imaging = Imaging(cam)
exposures = np.array([7000,3000])
T... | 0.319015 | 0.538377 |
from ...ucsmo import ManagedObject
from ...ucscoremeta import MoPropertyMeta, MoMeta
from ...ucsmeta import VersionMeta
class FirmwareSecureFPGAConsts:
FPGAIMAGE_STATUS_ACTIVATION_FAILED = "Activation Failed"
FPGAIMAGE_STATUS_ACTIVATION_IN_PROGRESS = "Activation In Progress"
FPGAIMAGE_STATUS_READY = "Rea... | ucsmsdk/mometa/firmware/FirmwareSecureFPGA.py |
from ...ucsmo import ManagedObject
from ...ucscoremeta import MoPropertyMeta, MoMeta
from ...ucsmeta import VersionMeta
class FirmwareSecureFPGAConsts:
FPGAIMAGE_STATUS_ACTIVATION_FAILED = "Activation Failed"
FPGAIMAGE_STATUS_ACTIVATION_IN_PROGRESS = "Activation In Progress"
FPGAIMAGE_STATUS_READY = "Rea... | 0.446495 | 0.169028 |
import re
import collections
from enum import Enum
from ydk._core._dm_meta_info import _MetaInfoClassMember, _MetaInfoClass, _MetaInfoEnum
from ydk.types import Empty, YList, YLeafList, DELETE, Decimal64, FixedBitsDict
from ydk._core._dm_meta_info import ATTRIBUTE, REFERENCE_CLASS, REFERENCE_LIST, REFERENCE_LEAFLIST,... | cisco-ios-xr/ydk/models/cisco_ios_xr/_meta/_Cisco_IOS_XR_man_ems_cfg.py | import re
import collections
from enum import Enum
from ydk._core._dm_meta_info import _MetaInfoClassMember, _MetaInfoClass, _MetaInfoEnum
from ydk.types import Empty, YList, YLeafList, DELETE, Decimal64, FixedBitsDict
from ydk._core._dm_meta_info import ATTRIBUTE, REFERENCE_CLASS, REFERENCE_LIST, REFERENCE_LEAFLIST,... | 0.398875 | 0.033876 |
import os
import unittest
from spotinst_sdk2 import SpotinstSession
from spotinst_sdk2.models.managed_instance.aws import *
class SimpleNamespace:
def __init__(self, **kwargs):
self.__dict__.update(kwargs)
class AwsManagedInstanceTestCase(unittest.TestCase):
def setUp(self):
self.session =... | spotinst_sdk2/test/managed_instance/aws/test_aws_ma_model.py | import os
import unittest
from spotinst_sdk2 import SpotinstSession
from spotinst_sdk2.models.managed_instance.aws import *
class SimpleNamespace:
def __init__(self, **kwargs):
self.__dict__.update(kwargs)
class AwsManagedInstanceTestCase(unittest.TestCase):
def setUp(self):
self.session =... | 0.486332 | 0.176441 |
from django.test import TestCase
from django_orm.core.sql import RawExpression, SqlExpression, SqlFunction, AND, OR
from django_orm.postgresql.geometric.objects import Point, Circle, Box
from django_orm.postgresql.geometric.expressions import GeoExpression
from .models import SomeObject, CircleObjectModel, BoxObject... | tests/modeltests/pg_geometric/tests.py |
from django.test import TestCase
from django_orm.core.sql import RawExpression, SqlExpression, SqlFunction, AND, OR
from django_orm.postgresql.geometric.objects import Point, Circle, Box
from django_orm.postgresql.geometric.expressions import GeoExpression
from .models import SomeObject, CircleObjectModel, BoxObject... | 0.511473 | 0.404655 |
from .... pyaz_utils import _call_az
def list_sku(name, resource_group, workspace_name):
'''
Returns the SKUs available for the provided resource.
Required Parameters:
- name -- The name of the Kusto pool.
- resource_group -- Name of resource group. You can configure the default group using `az co... | pyaz/synapse/kusto/pool/__init__.py | from .... pyaz_utils import _call_az
def list_sku(name, resource_group, workspace_name):
'''
Returns the SKUs available for the provided resource.
Required Parameters:
- name -- The name of the Kusto pool.
- resource_group -- Name of resource group. You can configure the default group using `az co... | 0.886678 | 0.207315 |
import os
import io
import tensorflow as tf
import matplotlib.pyplot as plt
import numpy as np
import tensorflow_datasets as tfds
from tensorflow import keras
from tensorflow.keras import layers
# Make sure we don't get any GPU errors
physical_devices = tf.config.list_physical_devices("GPU")
tf.config... | tensorboard/callback.py | import os
import io
import tensorflow as tf
import matplotlib.pyplot as plt
import numpy as np
import tensorflow_datasets as tfds
from tensorflow import keras
from tensorflow.keras import layers
# Make sure we don't get any GPU errors
physical_devices = tf.config.list_physical_devices("GPU")
tf.config... | 0.713232 | 0.297011 |