code stringlengths 2k 1.04M | repo_path stringlengths 5 517 | parsed_code stringlengths 0 1.04M | quality_prob float64 0.02 0.95 | learning_prob float64 0.02 0.93 |
|---|---|---|---|---|
from django.urls import path, include
from rest_framework.routers import DefaultRouter
from formulaire import views
router = DefaultRouter()
router.register('formulaires', views.FormulaireViewSet)
router.register('entreprises', views.EntrepriseViewSet)
router.register('operateurs', views.OperateurViewSet)
router.reg... | app/formulaire/urls.py | from django.urls import path, include
from rest_framework.routers import DefaultRouter
from formulaire import views
router = DefaultRouter()
router.register('formulaires', views.FormulaireViewSet)
router.register('entreprises', views.EntrepriseViewSet)
router.register('operateurs', views.OperateurViewSet)
router.reg... | 0.391406 | 0.112844 |
## Zemberek: Document Correction Example
# Documentation: https://github.com/ahmetaa/zemberek-nlp/tree/master/normalization
# Java Code Example: https://github.com/ahmetaa/zemberek-nlp/blob/master/examples/src/main/java/zemberek/examples/normalization/CorrectDocument.java
import jpype as jp
# Relative path to Zember... | py-work/pipeline/zemberek/examples/normalization/document_correction.py |
## Zemberek: Document Correction Example
# Documentation: https://github.com/ahmetaa/zemberek-nlp/tree/master/normalization
# Java Code Example: https://github.com/ahmetaa/zemberek-nlp/blob/master/examples/src/main/java/zemberek/examples/normalization/CorrectDocument.java
import jpype as jp
# Relative path to Zember... | 0.556038 | 0.507995 |
# For example,
# 123 -> "One Hundred Twenty Three"
# 12345 -> "Twelve Thousand Three Hundred Forty Five"
# 1234567 -> "One Million Two Hundred Thirty Four Thousand Five Hundred Sixty Seven"
class Solution(object):
def __init__(self):
### init_1
# self.lessThan20 = ["","One","Two","Three","Fo... | source-code/Integer to English Words 273.py |
# For example,
# 123 -> "One Hundred Twenty Three"
# 12345 -> "Twelve Thousand Three Hundred Forty Five"
# 1234567 -> "One Million Two Hundred Thirty Four Thousand Five Hundred Sixty Seven"
class Solution(object):
def __init__(self):
### init_1
# self.lessThan20 = ["","One","Two","Three","Fo... | 0.587943 | 0.327104 |
from pymongo import MongoClient, ASCENDING
import time
import random
class MongoTest:
def __init__(self, collection: str, recreate: bool):
mongo_cli = MongoClient('127.0.0.1', 27017)
self.db = mongo_cli.test
if recreate:
self.db[collection].drop()
def test_inserts_efficie... | efficiency-tests/mongodb_test.py | from pymongo import MongoClient, ASCENDING
import time
import random
class MongoTest:
def __init__(self, collection: str, recreate: bool):
mongo_cli = MongoClient('127.0.0.1', 27017)
self.db = mongo_cli.test
if recreate:
self.db[collection].drop()
def test_inserts_efficie... | 0.33939 | 0.164852 |
# =======
# Imports
# =======
import numpy
# ========================
# Generate Basis Functions
# ========================
def generate_basis_functions(n, m):
"""
Generates a sample design matrix (also called basis functions).
:param n: Nmber of rows of the design matrix.
:type n: int
:para... | examples/_utilities/data_utilities.py |
# =======
# Imports
# =======
import numpy
# ========================
# Generate Basis Functions
# ========================
def generate_basis_functions(n, m):
"""
Generates a sample design matrix (also called basis functions).
:param n: Nmber of rows of the design matrix.
:type n: int
:para... | 0.920415 | 0.869105 |
import urwid
from .line_base import LineBase
class LineProgress(LineBase):
def __init__(
self,
loop,
caption,
initial_value = 0,
max_value = 100,
caption_style = "highlight_color",
value_style = "normal_color",
completed_style = "completed_progre... | termapp/line_progress.py | import urwid
from .line_base import LineBase
class LineProgress(LineBase):
def __init__(
self,
loop,
caption,
initial_value = 0,
max_value = 100,
caption_style = "highlight_color",
value_style = "normal_color",
completed_style = "completed_progre... | 0.203787 | 0.098773 |
from printer import *
import os
import time
import glob
import threading
import subprocess
class SoundModuleSimulatorWrapper:
def __init__(self, parent):
self.parent = parent
self.sms_thread = None
self.sms_proc = None
self.mp_thread = None
self.mp_proc = None
self.abort_signal = False
self.exit_progra... | plugin-builder-tool/soundModuleSimulatorWrapper.py | from printer import *
import os
import time
import glob
import threading
import subprocess
class SoundModuleSimulatorWrapper:
def __init__(self, parent):
self.parent = parent
self.sms_thread = None
self.sms_proc = None
self.mp_thread = None
self.mp_proc = None
self.abort_signal = False
self.exit_progra... | 0.109992 | 0.06832 |
#! This file models a cylinder that is fixed at one end while the
#! second end has a specified displacement of 0.02 in the x direction
#! (this boundary condition is named PerturbedSurface).
#! The output is the displacement for each node, saved by default to
#! simple_out.vtk. The material is linear elastic.
from s... | examples/linear_elasticity/linear_elastic_up.py |
#! This file models a cylinder that is fixed at one end while the
#! second end has a specified displacement of 0.02 in the x direction
#! (this boundary condition is named PerturbedSurface).
#! The output is the displacement for each node, saved by default to
#! simple_out.vtk. The material is linear elastic.
from s... | 0.659076 | 0.427277 |
import json
import dml
import prov.model
import datetime
import pandas as pd
import uuid
class mergedList(dml.Algorithm):
contributor = 'ashwini_gdukuray_justini_utdesai'
reads = ['ashwini_gdukuray_justini_utdesai.masterList', 'ashwini_gdukuray_justini_utdesai.nonMBEmasterList']
writes = ['ashwini_gdukura... | mergedList.py | import json
import dml
import prov.model
import datetime
import pandas as pd
import uuid
class mergedList(dml.Algorithm):
contributor = 'ashwini_gdukuray_justini_utdesai'
reads = ['ashwini_gdukuray_justini_utdesai.masterList', 'ashwini_gdukuray_justini_utdesai.nonMBEmasterList']
writes = ['ashwini_gdukura... | 0.434701 | 0.247328 |
from __future__ import annotations
from dataclasses import dataclass
from typing import Any, Dict, List
import torch
from nuplan.planning.training.preprocessing.features.abstract_model_feature import (
AbstractModelFeature,
FeatureDataType,
to_tensor,
)
@dataclass
class AgentsTrajectories(AbstractModel... | nuplan/planning/training/preprocessing/features/agents_trajectories.py | from __future__ import annotations
from dataclasses import dataclass
from typing import Any, Dict, List
import torch
from nuplan.planning.training.preprocessing.features.abstract_model_feature import (
AbstractModelFeature,
FeatureDataType,
to_tensor,
)
@dataclass
class AgentsTrajectories(AbstractModel... | 0.96614 | 0.826922 |
import numpy as np
from scipy import signal
from skimage.transform import resize
from scipy.ndimage import gaussian_filter
def concat_zpad(arr1, arr2):
diff_dims = np.array(arr1.shape) - np.array(arr2.shape)
for i in range(1, diff_dims):
pad_size = np.zeros(size=(arr1.ndim, 2))
pad_size[i, 0]... | data/transforms/mrirandphasebig.py | import numpy as np
from scipy import signal
from skimage.transform import resize
from scipy.ndimage import gaussian_filter
def concat_zpad(arr1, arr2):
diff_dims = np.array(arr1.shape) - np.array(arr2.shape)
for i in range(1, diff_dims):
pad_size = np.zeros(size=(arr1.ndim, 2))
pad_size[i, 0]... | 0.790369 | 0.569015 |
from django.contrib.auth import get_user_model
from django import forms
from django.utils.translation import ugettext_lazy as _
from django.conf import settings
from timtec.settings import ACCOUNT_REQUIRED_FIELDS as fields
from accounts.models import UserSocialAccount
User = get_user_model()
class BaseProfileEditFo... | accounts/forms.py | from django.contrib.auth import get_user_model
from django import forms
from django.utils.translation import ugettext_lazy as _
from django.conf import settings
from timtec.settings import ACCOUNT_REQUIRED_FIELDS as fields
from accounts.models import UserSocialAccount
User = get_user_model()
class BaseProfileEditFo... | 0.519765 | 0.065336 |
import sys
import openpyxl
import argparse
import pandas as pd
import numpy as np
# script to covert extended sample sheet to standard illumina's sheet
# template of the extended_sample_sheet.xlsx can be found here:
# solo-in-drops/assets/extended_sample_sheet_template.xlsx
def convert_to_samplesheet(in_file, out_fil... | bin/convert_to_samplesheet.py | import sys
import openpyxl
import argparse
import pandas as pd
import numpy as np
# script to covert extended sample sheet to standard illumina's sheet
# template of the extended_sample_sheet.xlsx can be found here:
# solo-in-drops/assets/extended_sample_sheet_template.xlsx
def convert_to_samplesheet(in_file, out_fil... | 0.194597 | 0.255936 |
import json
import mock
from tabulate import tabulate
import databricks_cli.jobs.cli as cli
from databricks_cli.utils import pretty_format
from tests.utils import get_callback
CREATE_RETURN = {'job_id': 5}
CREATE_JSON = '{"name": "test_job"}'
def test_create_cli_json():
with mock.patch('databricks_cli.jobs.cli... | tests/jobs/test_cli.py |
import json
import mock
from tabulate import tabulate
import databricks_cli.jobs.cli as cli
from databricks_cli.utils import pretty_format
from tests.utils import get_callback
CREATE_RETURN = {'job_id': 5}
CREATE_JSON = '{"name": "test_job"}'
def test_create_cli_json():
with mock.patch('databricks_cli.jobs.cli... | 0.388966 | 0.152758 |
from random import choice, randint, random
from cell import *
class Board():
def __init__(self, can, sample = []):
self.can = can
self.grid = []
for i in range(4):
self.grid.append([])
for j in range(4):
self.grid[i].append(0)
if not sampl... | board.py | from random import choice, randint, random
from cell import *
class Board():
def __init__(self, can, sample = []):
self.can = can
self.grid = []
for i in range(4):
self.grid.append([])
for j in range(4):
self.grid[i].append(0)
if not sampl... | 0.255622 | 0.180865 |
import logging
import numpy
from orion.algo.base import BaseAlgorithm
from orion.algo.space import check_random_state
from skopt import Optimizer, Space
from skopt.learning import GaussianProcessRegressor
from skopt.space import Real
log = logging.getLogger(__name__)
def orion_space_to_skopt_space(orion_space):
... | src/orion/algo/skopt/bayes.py | import logging
import numpy
from orion.algo.base import BaseAlgorithm
from orion.algo.space import check_random_state
from skopt import Optimizer, Space
from skopt.learning import GaussianProcessRegressor
from skopt.space import Real
log = logging.getLogger(__name__)
def orion_space_to_skopt_space(orion_space):
... | 0.904692 | 0.615117 |
import sys, os, string, math, arcpy, traceback
# Allow output file to overwrite any existing file of the same name
arcpy.env.overwriteOutput = True
try:
# Request user inputs, name variables
nameOfInputShapefile1 = arcpy.GetParameterAsText(0)
yearField1 = arcpy.GetParameterAsText(1)
year... | nc-pt2.py | import sys, os, string, math, arcpy, traceback
# Allow output file to overwrite any existing file of the same name
arcpy.env.overwriteOutput = True
try:
# Request user inputs, name variables
nameOfInputShapefile1 = arcpy.GetParameterAsText(0)
yearField1 = arcpy.GetParameterAsText(1)
year... | 0.375477 | 0.288387 |
import unittest
from day23 import Computer
class TestComputer(unittest.TestCase):
def setUp(self):
self.computer = Computer()
def test_has_registers(self):
self.assertEqual(self.computer.a, 0)
self.assertEqual(self.computer.b, 0)
def test_has_instruction_pointer(self):
... | day23/test.py |
import unittest
from day23 import Computer
class TestComputer(unittest.TestCase):
def setUp(self):
self.computer = Computer()
def test_has_registers(self):
self.assertEqual(self.computer.a, 0)
self.assertEqual(self.computer.b, 0)
def test_has_instruction_pointer(self):
... | 0.558568 | 0.610453 |
import logging
from datetime import timedelta
import homeassistant.helpers.config_validation as cv
import voluptuous as vol
from homeassistant.components.sensor import PLATFORM_SCHEMA
from homeassistant.const import (
CONF_NAME,
CONF_DEVICES,
CONF_ADDRESS,
CONF_TYPE,
CONF_UNIT_OF_MEASUREMENT,
... | home-assistant-plugin/custom_components/buspro/sensor.py | import logging
from datetime import timedelta
import homeassistant.helpers.config_validation as cv
import voluptuous as vol
from homeassistant.components.sensor import PLATFORM_SCHEMA
from homeassistant.const import (
CONF_NAME,
CONF_DEVICES,
CONF_ADDRESS,
CONF_TYPE,
CONF_UNIT_OF_MEASUREMENT,
... | 0.78572 | 0.106598 |
import colorama
from colorama import init
from colorama import Fore, Back, Style
colorama.init()
def Apache():
print Fore.GREEN + "CVE-2013-2187"
print Fore.CYAN + "Apache : Archiva 1.3 to Archiva 1.3.6"
print "http://cve.mitre.org/cgi-bin/cvename.cgi?name=CVE-2013-2187"
print ""
print Fore.GREE... | cve.py |
import colorama
from colorama import init
from colorama import Fore, Back, Style
colorama.init()
def Apache():
print Fore.GREEN + "CVE-2013-2187"
print Fore.CYAN + "Apache : Archiva 1.3 to Archiva 1.3.6"
print "http://cve.mitre.org/cgi-bin/cvename.cgi?name=CVE-2013-2187"
print ""
print Fore.GREE... | 0.423816 | 0.057785 |
import numpy as np
import torch.utils.data
class Dataset(torch.utils.data.Dataset):
def __init__(self, args, set_):
self.hw = args.hw
self.set_ = set_
self.select_features = getattr(args, "select_features", None)
self.item_list = getattr(args, "item_list", [])
self.getfunc_... | datasets/dataset.py | import numpy as np
import torch.utils.data
class Dataset(torch.utils.data.Dataset):
def __init__(self, args, set_):
self.hw = args.hw
self.set_ = set_
self.select_features = getattr(args, "select_features", None)
self.item_list = getattr(args, "item_list", [])
self.getfunc_... | 0.642208 | 0.281097 |
import locale
import os
import re
import urllib.request
import urllib.parse
from datetime import datetime
from tkinter import Tk, Menu, messagebox, END, Toplevel, Frame, TOP, Label, LEFT, Entry, Scrollbar, Y, RIGHT, Listbox, \
BOTTOM, BOTH, Spinbox
from bs4 import BeautifulSoup
from whoosh.fields import Schema, TE... | PracticaEvaluableWhoosh/practica-fixed-fecha-entry.py | import locale
import os
import re
import urllib.request
import urllib.parse
from datetime import datetime
from tkinter import Tk, Menu, messagebox, END, Toplevel, Frame, TOP, Label, LEFT, Entry, Scrollbar, Y, RIGHT, Listbox, \
BOTTOM, BOTH, Spinbox
from bs4 import BeautifulSoup
from whoosh.fields import Schema, TE... | 0.249082 | 0.112942 |
import numpy as np
import numpy.linalg as la
import tensorflow as tf
import sys, os
import time
import utils.train
class LISTA_base (object):
"""
Implementation of deep neural network model.
"""
def __init__ (self):
pass
def setup_layers (self):
pass
def... | models/LISTA_base.py | import numpy as np
import numpy.linalg as la
import tensorflow as tf
import sys, os
import time
import utils.train
class LISTA_base (object):
"""
Implementation of deep neural network model.
"""
def __init__ (self):
pass
def setup_layers (self):
pass
def... | 0.364212 | 0.268102 |
import itertools
from collections import OrderedDict
from django.conf import settings
import mock
from nose.tools import eq_, ok_
import mkt.site.tests
from mkt.constants.features import (APP_FEATURES, FeaturesBitField,
FeatureProfile)
MOCK_APP_FEATURES_LIMIT = 45
MOCK_APP_FEATU... | mkt/constants/tests/test_features.py | import itertools
from collections import OrderedDict
from django.conf import settings
import mock
from nose.tools import eq_, ok_
import mkt.site.tests
from mkt.constants.features import (APP_FEATURES, FeaturesBitField,
FeatureProfile)
MOCK_APP_FEATURES_LIMIT = 45
MOCK_APP_FEATU... | 0.452052 | 0.343507 |
from passwordLoker import User,Credentials
import unittest
class TestPassword(unittest.TestCase):
def setUp(self):
self.new_user = User("<NAME>","JG","5678")
self.new_credentials = Credentials("facebook","JG","5678")
def tearDown(self):
User.users_list = []
Credentials.creden... | passwordLockerTest.py | from passwordLoker import User,Credentials
import unittest
class TestPassword(unittest.TestCase):
def setUp(self):
self.new_user = User("<NAME>","JG","5678")
self.new_credentials = Credentials("facebook","JG","5678")
def tearDown(self):
User.users_list = []
Credentials.creden... | 0.31321 | 0.167627 |
import datetime
from datetime import date as std_date
from enum import Enum, auto
from typing import Dict, Optional
from django.contrib.auth import get_user_model
from django.db import models
from django.db.models import F
from ctrack.caf.models import CAF
from ctrack.organisations.models import Person
from ctrack.us... | ctrack/register/models.py | import datetime
from datetime import date as std_date
from enum import Enum, auto
from typing import Dict, Optional
from django.contrib.auth import get_user_model
from django.db import models
from django.db.models import F
from ctrack.caf.models import CAF
from ctrack.organisations.models import Person
from ctrack.us... | 0.572364 | 0.115112 |
import sys
import numpy as np
import pandas as pd
from sklearn.preprocessing import StandardScaler
from sklearn.decomposition import PCA
from sklearn.model_selection import GridSearchCV
from sklearn.linear_model import Ridge
# Define list of states for loop
state2fips = {'AL': 1,
'AK': 2,
'... | archive/CODE/back_end/feature_analysis_pipeline/feature_pipeline.py | import sys
import numpy as np
import pandas as pd
from sklearn.preprocessing import StandardScaler
from sklearn.decomposition import PCA
from sklearn.model_selection import GridSearchCV
from sklearn.linear_model import Ridge
# Define list of states for loop
state2fips = {'AL': 1,
'AK': 2,
'... | 0.536799 | 0.320515 |
from __future__ import absolute_import
import pytest
import schematec.schema
import schematec.converters as converters
import schematec.validators as validators
import schematec.exc as exc
def test_empty_schema_with_empty_value():
schema = schematec.schema.array()
assert schema([]) == []
def test_empty_sc... | tests/test_schema_array.py | from __future__ import absolute_import
import pytest
import schematec.schema
import schematec.converters as converters
import schematec.validators as validators
import schematec.exc as exc
def test_empty_schema_with_empty_value():
schema = schematec.schema.array()
assert schema([]) == []
def test_empty_sc... | 0.683842 | 0.520801 |
from __future__ import absolute_import
import argparse
import os
import unittest
import pytest
from artman.cli import support
class ParseGitHubCredentialsTests(unittest.TestCase):
def test_read_from_config_file(self):
user_config = {'username': 'foo', 'token': 'bar'}
flags = argparse.Namespace(... | test/cli/test_support.py |
from __future__ import absolute_import
import argparse
import os
import unittest
import pytest
from artman.cli import support
class ParseGitHubCredentialsTests(unittest.TestCase):
def test_read_from_config_file(self):
user_config = {'username': 'foo', 'token': 'bar'}
flags = argparse.Namespace(... | 0.516352 | 0.294392 |
import numbers
import datetime
from operator import attrgetter
import os
import dateutil.parser
from lxml import etree
import libtaxii.messages_11 as tm11
from .common import TAXIIBase
from .validation import (do_check, uri_regex, targeting_expression_regex)
from .constants import *
import six
class CapabilityModu... | libtaxii/taxii_default_query.py | import numbers
import datetime
from operator import attrgetter
import os
import dateutil.parser
from lxml import etree
import libtaxii.messages_11 as tm11
from .common import TAXIIBase
from .validation import (do_check, uri_regex, targeting_expression_regex)
from .constants import *
import six
class CapabilityModu... | 0.722821 | 0.21713 |
print ("Importing...")
import alpaca_trade_api as tradeapi
import time
from Basics import ConvertJson, stockCalc
from config import *
import datetime
if input('Override Market Wait?') == 'n':
print("Waiting for market open...")
while True:
now = datetime.datetime.now()
current_time = int(now.strftime("%H%... | Version-1/main.py | print ("Importing...")
import alpaca_trade_api as tradeapi
import time
from Basics import ConvertJson, stockCalc
from config import *
import datetime
if input('Override Market Wait?') == 'n':
print("Waiting for market open...")
while True:
now = datetime.datetime.now()
current_time = int(now.strftime("%H%... | 0.127925 | 0.126165 |
from proxmoxer import ProxmoxAPI
import json
# IMPORTANT: Target Machine needs to have a package named qemu-guest-agent.
# After installing this package, Enable agent on web interface (Options > Qemu Guest Agent)
with open('config.json') as json_file:
data = json.load(json_file)
# Give kvm input 0 for first node... | agent.py | from proxmoxer import ProxmoxAPI
import json
# IMPORTANT: Target Machine needs to have a package named qemu-guest-agent.
# After installing this package, Enable agent on web interface (Options > Qemu Guest Agent)
with open('config.json') as json_file:
data = json.load(json_file)
# Give kvm input 0 for first node... | 0.485112 | 0.151592 |
from twisted.trial.unittest import TestCase
from axiom.store import Store
from axiom.item import Item
from axiom.attributes import integer, compoundIndex
from axiom.test.util import QueryCounter
class SingleColumnSortHelper(Item):
mainColumn = integer(indexed=True)
other = integer()
compoundIndex(mainCo... | axiom/test/test_paginate.py | from twisted.trial.unittest import TestCase
from axiom.store import Store
from axiom.item import Item
from axiom.attributes import integer, compoundIndex
from axiom.test.util import QueryCounter
class SingleColumnSortHelper(Item):
mainColumn = integer(indexed=True)
other = integer()
compoundIndex(mainCo... | 0.674158 | 0.534795 |
from datetime import datetime
import pytest
from astranslate import PBbool, PBdate, PBdict, PBlist, PBnumber, PBstring
def test_PBBool_ToApplescript_GivenBoolean_ReturnsBooleanString():
assert PBbool.to_applescript(True) == "True"
def test_PBBool_ToApplescript_GivenNumber_ReturnsNumberAsString():
assert PBbool.... | pastybridge/test/test_pastybridge.py | from datetime import datetime
import pytest
from astranslate import PBbool, PBdate, PBdict, PBlist, PBnumber, PBstring
def test_PBBool_ToApplescript_GivenBoolean_ReturnsBooleanString():
assert PBbool.to_applescript(True) == "True"
def test_PBBool_ToApplescript_GivenNumber_ReturnsNumberAsString():
assert PBbool.... | 0.703957 | 0.58676 |
import numpy as np
class Item(object):
def __init__(self, pos_x, pos_y):
self.x = pos_x
self.y = pos_y
class MovableItem(Item):
def __init__(self, pos_x, pos_y):
super().__init__(pos_x, pos_y)
self.initial_x = pos_x
self.initial_y = pos_y
def move(self, x, y):... | env/items.py |
import numpy as np
class Item(object):
def __init__(self, pos_x, pos_y):
self.x = pos_x
self.y = pos_y
class MovableItem(Item):
def __init__(self, pos_x, pos_y):
super().__init__(pos_x, pos_y)
self.initial_x = pos_x
self.initial_y = pos_y
def move(self, x, y):... | 0.481454 | 0.248272 |
import pytest
import os
# Keep import for _CONFIGPATH - otherwise get_path fails because cimpyorm/__init__.py locals aren't present
from cimpyorm.auxiliary import log, get_path
@pytest.fixture(scope="session")
def full_grid():
try:
path = os.path.join(get_path("DATASETROOT"), "FullGrid")
except KeyE... | cimpyorm/Test/conftest.py | import pytest
import os
# Keep import for _CONFIGPATH - otherwise get_path fails because cimpyorm/__init__.py locals aren't present
from cimpyorm.auxiliary import log, get_path
@pytest.fixture(scope="session")
def full_grid():
try:
path = os.path.join(get_path("DATASETROOT"), "FullGrid")
except KeyE... | 0.400867 | 0.204064 |
import warnings
import pulumi
import pulumi.runtime
from typing import Any, Mapping, Optional, Sequence, Union, overload
from . import _utilities
__all__ = ['ServerNetworkArgs', 'ServerNetwork']
@pulumi.input_type
class ServerNetworkArgs:
def __init__(__self__, *,
server_id: pulumi.Input[int],
... | sdk/python/pulumi_hcloud/server_network.py |
import warnings
import pulumi
import pulumi.runtime
from typing import Any, Mapping, Optional, Sequence, Union, overload
from . import _utilities
__all__ = ['ServerNetworkArgs', 'ServerNetwork']
@pulumi.input_type
class ServerNetworkArgs:
def __init__(__self__, *,
server_id: pulumi.Input[int],
... | 0.841289 | 0.136493 |
import cplex
from docplex.mp.callbacks.cb_mixin import ConstraintCallbackMixin
from docplex.mp.model import Model as _Model
import numpy as np
class Model(_Model):
"""Convenience class to add Numpy variable arrays to docplex.mp."""
def _var_array(self, vartype, shape=(), *args, **kwargs):
size = np.p... | dorado/scheduling/schedulers/__init__.py | import cplex
from docplex.mp.callbacks.cb_mixin import ConstraintCallbackMixin
from docplex.mp.model import Model as _Model
import numpy as np
class Model(_Model):
"""Convenience class to add Numpy variable arrays to docplex.mp."""
def _var_array(self, vartype, shape=(), *args, **kwargs):
size = np.p... | 0.852905 | 0.199425 |
from django.conf import settings
from django.db import migrations, models
import django.db.models.deletion
import django.utils.timezone
import functools
import organizations.fields
import purpleserver.core.models.base
class Migration(migrations.Migration):
initial = True
dependencies = [
('graph', ... | apps/orgs/purpleserver/orgs/migrations/0001_initial.py |
from django.conf import settings
from django.db import migrations, models
import django.db.models.deletion
import django.utils.timezone
import functools
import organizations.fields
import purpleserver.core.models.base
class Migration(migrations.Migration):
initial = True
dependencies = [
('graph', ... | 0.523908 | 0.094803 |
from .custom_exceptions import GeneralPogoException
from .location import Location
from .pgoapi import pgoapi
from .session import PogoSession
from .util import get_encryption_lib_path
# Callbacks and Constants
API_URL = 'https://pgorelease.nianticlabs.com/plfe/rpc'
LOGIN_URL = 'https://sso.pokemon.com/sso/login?servic... | pogo/pogoBot/pogoAPI/api.py | from .custom_exceptions import GeneralPogoException
from .location import Location
from .pgoapi import pgoapi
from .session import PogoSession
from .util import get_encryption_lib_path
# Callbacks and Constants
API_URL = 'https://pgorelease.nianticlabs.com/plfe/rpc'
LOGIN_URL = 'https://sso.pokemon.com/sso/login?servic... | 0.340705 | 0.121295 |
import os
import random
import shutil
import unittest
import numpy
from ont_fast5_api.fast5_file import Fast5File
from ont_fast5_api.fast5_read import Fast5Read
from ont_fast5_api.multi_fast5 import MultiFast5File
hexdigits = "0123456789abcdef"
save_path = os.path.join(os.path.dirname(__file__), 'tmp')
class TestM... | submodules/ont_fast5_api/test/test_multi_fast5.py | import os
import random
import shutil
import unittest
import numpy
from ont_fast5_api.fast5_file import Fast5File
from ont_fast5_api.fast5_read import Fast5Read
from ont_fast5_api.multi_fast5 import MultiFast5File
hexdigits = "0123456789abcdef"
save_path = os.path.join(os.path.dirname(__file__), 'tmp')
class TestM... | 0.425367 | 0.373362 |
import config
import datapane as dp
import logging
import pandas as pd
import plotly.express as px
import plotly.figure_factory as ff
import plotly.graph_objs as go
import streamlit as st
import utils
logging.basicConfig(format='%(asctime)s - %(name)s - %(levelname)s - %(message)s', level=logging.INFO)
logger = loggi... | traffic_density_hourly.py |
import config
import datapane as dp
import logging
import pandas as pd
import plotly.express as px
import plotly.figure_factory as ff
import plotly.graph_objs as go
import streamlit as st
import utils
logging.basicConfig(format='%(asctime)s - %(name)s - %(levelname)s - %(message)s', level=logging.INFO)
logger = loggi... | 0.740644 | 0.49585 |
import pytest
from connect.client.models import (
Action,
AsyncAction,
AsyncCollection,
AsyncNS,
AsyncResource,
AsyncResourceSet,
Collection,
NS,
Resource,
ResourceSet,
)
@pytest.fixture
def async_client_mock(async_mocker):
def _async_client_mock(methods=None):
met... | tests/fixtures/client_models.py | import pytest
from connect.client.models import (
Action,
AsyncAction,
AsyncCollection,
AsyncNS,
AsyncResource,
AsyncResourceSet,
Collection,
NS,
Resource,
ResourceSet,
)
@pytest.fixture
def async_client_mock(async_mocker):
def _async_client_mock(methods=None):
met... | 0.631367 | 0.115536 |
from .... pyaz_utils import _call_az
def set(account_name, container_name, tags, allow_protected_append_writes_all=None, resource_group=None):
'''
Set legal hold tags.
Required Parameters:
- account_name -- Storage account name. Related environment variable: AZURE_STORAGE_ACCOUNT.
- container_name... | pyaz/storage/container/legal_hold/__init__.py | from .... pyaz_utils import _call_az
def set(account_name, container_name, tags, allow_protected_append_writes_all=None, resource_group=None):
'''
Set legal hold tags.
Required Parameters:
- account_name -- Storage account name. Related environment variable: AZURE_STORAGE_ACCOUNT.
- container_name... | 0.757436 | 0.144964 |
from __future__ import absolute_import, division, print_function
__metaclass__ = type
from ansible_collections.willguibr.zpacloud.plugins.module_utils.zpa_client import (
ZPAClientHelper,
delete_none,
)
class PostureProfileService:
def __init__(self, module, customer_id):
self.module = module
... | plugins/module_utils/zpa_posture_profile.py | from __future__ import absolute_import, division, print_function
__metaclass__ = type
from ansible_collections.willguibr.zpacloud.plugins.module_utils.zpa_client import (
ZPAClientHelper,
delete_none,
)
class PostureProfileService:
def __init__(self, module, customer_id):
self.module = module
... | 0.616012 | 0.101589 |
class FailedTest:
def __init__(
self,
job_name: str,
build_number: int,
name: str,
traceback: str = '',
timestamp: int = 0
):
self.job_name = job_name
self.build_number = build_number
self.name = name
self.tr... | jenkins_flaky/test_report.py | class FailedTest:
def __init__(
self,
job_name: str,
build_number: int,
name: str,
traceback: str = '',
timestamp: int = 0
):
self.job_name = job_name
self.build_number = build_number
self.name = name
self.tr... | 0.700075 | 0.254266 |
from hkube_python_wrapper.communication.streaming.StreamingManager import StreamingManager
from hkube_python_wrapper.communication.streaming.MessageListener import MessageListener
from hkube_python_wrapper.communication.streaming.MessageProducer import MessageProducer
import time
parsedFlows = {
'analyze': [{'sour... | tests/test_streaming.py | from hkube_python_wrapper.communication.streaming.StreamingManager import StreamingManager
from hkube_python_wrapper.communication.streaming.MessageListener import MessageListener
from hkube_python_wrapper.communication.streaming.MessageProducer import MessageProducer
import time
parsedFlows = {
'analyze': [{'sour... | 0.36625 | 0.25773 |
from __future__ import print_function
import argparse
import claudio
import logging
import matplotlib
import numpy as np
import os
import pandas as pd
import pprint
import sys
import time
import matplotlib.pyplot as plt
import minst.logger
import minst.signal as S
import minst.utils as utils
matplotlib.use("TkAGG")
... | scripts/annotate.py | from __future__ import print_function
import argparse
import claudio
import logging
import matplotlib
import numpy as np
import os
import pandas as pd
import pprint
import sys
import time
import matplotlib.pyplot as plt
import minst.logger
import minst.signal as S
import minst.utils as utils
matplotlib.use("TkAGG")
... | 0.61855 | 0.193243 |
rule_map = {
"page":{
"/": "index",
'/new': 'new',
'/piece/(\d+)': 'piece',
'/people/(\d+)': 'people',
'/login': 'login',
'/logout': 'logout',
'/tools': 'tools',
'/about': 'about',
'/app': 'app',
'/bookmarklet': 'bookmarklet',
'... | config/routes.py | rule_map = {
"page":{
"/": "index",
'/new': 'new',
'/piece/(\d+)': 'piece',
'/people/(\d+)': 'people',
'/login': 'login',
'/logout': 'logout',
'/tools': 'tools',
'/about': 'about',
'/app': 'app',
'/bookmarklet': 'bookmarklet',
'... | 0.146423 | 0.145874 |
import mock
from nose.tools import eq_
import test_utils
from ..client import (Client, ClientMock, ClientProxy, dict_to_mock,
get_client, response_to_dict)
from ..constants import OK, ACCESS_DENIED
from ..errors import AuthError, BangoError, ProxyError
import samples
class TestClient(test_util... | lib/bango/tests/test_client.py | import mock
from nose.tools import eq_
import test_utils
from ..client import (Client, ClientMock, ClientProxy, dict_to_mock,
get_client, response_to_dict)
from ..constants import OK, ACCESS_DENIED
from ..errors import AuthError, BangoError, ProxyError
import samples
class TestClient(test_util... | 0.68342 | 0.28655 |
import os
import re
import sys
import json
import time
import codecs
import base64
import asyncio
import aiohttp
import chardet
import aiofiles
import binascii
from http import cookiejar
from printer import Printer
from Crypto.Cipher import AES
from contextlib import closing
MAX_SEMAPHORE = asyncio.Semaphore(10)
cl... | netease.py | import os
import re
import sys
import json
import time
import codecs
import base64
import asyncio
import aiohttp
import chardet
import aiofiles
import binascii
from http import cookiejar
from printer import Printer
from Crypto.Cipher import AES
from contextlib import closing
MAX_SEMAPHORE = asyncio.Semaphore(10)
cl... | 0.313735 | 0.080394 |
from custom import *
data = np.load('norings-save.npz')
standards = data['standards']
target = data['target']
airmass = data['airmass']
exptime = data['exptime']
time = data['opentime']
error = data['error']
target_centroid = data['target_centroid']
standard_centroid = data['standard_centroid']
coords = d... | examples/do_not/analyze.py | from custom import *
data = np.load('norings-save.npz')
standards = data['standards']
target = data['target']
airmass = data['airmass']
exptime = data['exptime']
time = data['opentime']
error = data['error']
target_centroid = data['target_centroid']
standard_centroid = data['standard_centroid']
coords = d... | 0.36625 | 0.349644 |
import pandas as pd
import seaborn as sns
import matplotlib.pyplot as plt
from sklearn.manifold import MDS
import matplotlib.pyplot as plt
import numpy as np
from sklearn.metrics import silhouette_samples, silhouette_score
import matplotlib.cm as cm
class RibosomeGene:
def __init__(self, accession, header, sequen... | Machine Learning/kmeans from scratch/utilities.py | import pandas as pd
import seaborn as sns
import matplotlib.pyplot as plt
from sklearn.manifold import MDS
import matplotlib.pyplot as plt
import numpy as np
from sklearn.metrics import silhouette_samples, silhouette_score
import matplotlib.cm as cm
class RibosomeGene:
def __init__(self, accession, header, sequen... | 0.524882 | 0.514095 |
import genologics_sql.tables as t
from sqlalchemy import or_, and_, func
from sqlalchemy.orm.util import aliased
def format_date(date):
if date:
return date.isoformat()
return None
def add_filters(q, **kwargs):
if kwargs.get('project_name'):
q = q.filter(t.Project.name == kwargs.get('pro... | rest_api/limsdb/queries/__init__.py | import genologics_sql.tables as t
from sqlalchemy import or_, and_, func
from sqlalchemy.orm.util import aliased
def format_date(date):
if date:
return date.isoformat()
return None
def add_filters(q, **kwargs):
if kwargs.get('project_name'):
q = q.filter(t.Project.name == kwargs.get('pro... | 0.488283 | 0.149749 |
from . import db
from werkzeug.security import generate_password_hash, check_password_hash
from flask_login import UserMixin
from . import login_manager
from datetime import datetime
from sqlalchemy.sql import func
@login_manager.user_loader
def load_user(user_id):
'''
@login_manager.user_loader Passes in a u... | app/models.py | from . import db
from werkzeug.security import generate_password_hash, check_password_hash
from flask_login import UserMixin
from . import login_manager
from datetime import datetime
from sqlalchemy.sql import func
@login_manager.user_loader
def load_user(user_id):
'''
@login_manager.user_loader Passes in a u... | 0.489503 | 0.090494 |
from warcio.limitreader import LimitReader
from pywb.webagg.utils import load_config
from contextlib import contextmanager
import gevent
# ============================================================================
def load_wr_config():
return load_config('WR_CONFIG', 'pkg://webrecorder/config/wr.yaml', 'WR_USER... | webrecorder/webrecorder/utils.py | from warcio.limitreader import LimitReader
from pywb.webagg.utils import load_config
from contextlib import contextmanager
import gevent
# ============================================================================
def load_wr_config():
return load_config('WR_CONFIG', 'pkg://webrecorder/config/wr.yaml', 'WR_USER... | 0.606032 | 0.102664 |
import configparser
from jinja2 import (Environment, FileSystemLoader, PackageLoader,
select_autoescape)
import logging
import os
import pathlib
from PIL import Image
import re
import sqlite3
import stat
import subprocess
import sys
from photo_album import (Album, Package, CustomArgumentParser)
logger = loggi... | photo_album/mkgallerytiff.py | import configparser
from jinja2 import (Environment, FileSystemLoader, PackageLoader,
select_autoescape)
import logging
import os
import pathlib
from PIL import Image
import re
import sqlite3
import stat
import subprocess
import sys
from photo_album import (Album, Package, CustomArgumentParser)
logger = loggi... | 0.360264 | 0.107087 |
import argparse
import os
import sys
from datetime import date
from sqlalchemy import create_engine
from sqlalchemy.orm import sessionmaker
from tasker import Tasker, InvalidStartDateException, DuplicateNameException, InvalidCadenceException
from models import Base
from intervals.interval_factory import IntervalFacto... | src/cli.py | import argparse
import os
import sys
from datetime import date
from sqlalchemy import create_engine
from sqlalchemy.orm import sessionmaker
from tasker import Tasker, InvalidStartDateException, DuplicateNameException, InvalidCadenceException
from models import Base
from intervals.interval_factory import IntervalFacto... | 0.288168 | 0.101723 |
import os, sys, shutil, json, zipfile
real_path = os.path.realpath(__file__)
LYNDOR_PATH = real_path[:real_path.find('install.py')]
def check_os():
'''Check operating system'''
platform = sys.platform.lower()
if platform == 'darwin':
return 'macos'
elif platform == 'win32':
retur... | install.py | import os, sys, shutil, json, zipfile
real_path = os.path.realpath(__file__)
LYNDOR_PATH = real_path[:real_path.find('install.py')]
def check_os():
'''Check operating system'''
platform = sys.platform.lower()
if platform == 'darwin':
return 'macos'
elif platform == 'win32':
retur... | 0.130202 | 0.058453 |
import sys
sys.path.append("../model")
sys.path.append('./model')
import os
from os.path import isfile, isdir, join, splitext
import glob
import shutil
import pandas as pd
import numpy as np
import matplotlib.pyplot as plt
from collections import Counter, defaultdict
import datetime
# custom
from process_raw_price... | process_data/process_data.py | import sys
sys.path.append("../model")
sys.path.append('./model')
import os
from os.path import isfile, isdir, join, splitext
import glob
import shutil
import pandas as pd
import numpy as np
import matplotlib.pyplot as plt
from collections import Counter, defaultdict
import datetime
# custom
from process_raw_price... | 0.38318 | 0.233881 |
from approaches.approach import Multiclass_Logistic_Regression, Perceptron, Sklearn_SVM
import comp_vis.calibration_tools as ct
import comp_vis.data_tools as dt
import comp_vis.img_tools as it
import comp_vis.live_tools as lt
import numpy as np
import os
import random
import sys
import time
already_cropped = True
# ... | live_demo.py | from approaches.approach import Multiclass_Logistic_Regression, Perceptron, Sklearn_SVM
import comp_vis.calibration_tools as ct
import comp_vis.data_tools as dt
import comp_vis.img_tools as it
import comp_vis.live_tools as lt
import numpy as np
import os
import random
import sys
import time
already_cropped = True
# ... | 0.543348 | 0.341665 |
import os
import contextlib
import logging
import pprint
import requests
__version__ = '0.2.1'
CONFIG_URL = "https://tech.lds.org/mobile/ldstools/config.json"
ENV_USERNAME = 'LDSORG_USERNAME'
ENV_PASSWORD = '<PASSWORD>'
logger = logging.getLogger("lds-org")
class Error(Exception):
"""Exceptions for module logic... | lds_org.py | import os
import contextlib
import logging
import pprint
import requests
__version__ = '0.2.1'
CONFIG_URL = "https://tech.lds.org/mobile/ldstools/config.json"
ENV_USERNAME = 'LDSORG_USERNAME'
ENV_PASSWORD = '<PASSWORD>'
logger = logging.getLogger("lds-org")
class Error(Exception):
"""Exceptions for module logic... | 0.631708 | 0.129375 |
# use tdklib library,which provides a wrapper for tdk testcase script
import tdklib;
from tdkbVariables import *;
#Test component to be tested
obj = tdklib.TDKScriptingLibrary("halplatform","1");
obj1 = tdklib.TDKScriptingLibrary("sysutil","1")
#IP and Port of box, No need to change,
#This will be replaced with corres... | testscripts/RDKB/component/HAL_Platform/TS_platform_stub_hal_SetFactoryCmVariant.py | # use tdklib library,which provides a wrapper for tdk testcase script
import tdklib;
from tdkbVariables import *;
#Test component to be tested
obj = tdklib.TDKScriptingLibrary("halplatform","1");
obj1 = tdklib.TDKScriptingLibrary("sysutil","1")
#IP and Port of box, No need to change,
#This will be replaced with corres... | 0.305076 | 0.231061 |
import os
import struct
import binascii
import socket
import threading
import datetime
from time import time, sleep
from json import load, loads, dumps
from src.utils import *
from src.db_worker import *
from src.logs.log_config import logger
from src.protocols.Teltonika.crc import crc16
class Teltonika:
BASE_PAT... | src/protocols/Teltonika/Teltonika.py | import os
import struct
import binascii
import socket
import threading
import datetime
from time import time, sleep
from json import load, loads, dumps
from src.utils import *
from src.db_worker import *
from src.logs.log_config import logger
from src.protocols.Teltonika.crc import crc16
class Teltonika:
BASE_PAT... | 0.059285 | 0.100525 |
import torch
import cv2
import math
from .conversions import *
from .io import torch2numpy, numpy2torch
from .tangent_images import get_valid_coordinates, convert_tangent_image_coordinates_to_spherical
import _spherical_distortion_ext._mesh as _mesh
def compute_sift_keypoints(img,
nfeature... | layers/util/image_ops.py | import torch
import cv2
import math
from .conversions import *
from .io import torch2numpy, numpy2torch
from .tangent_images import get_valid_coordinates, convert_tangent_image_coordinates_to_spherical
import _spherical_distortion_ext._mesh as _mesh
def compute_sift_keypoints(img,
nfeature... | 0.882675 | 0.542379 |
import numpy as np
import matplotlib.pyplot as plt
from matplotlib.colors import ListedColormap
from dateutil.relativedelta import relativedelta
from datetime import datetime
import pickle
from scipy.spatial.distance import jensenshannon
from scipy.stats import entropy
import networkx as nx
from wordcloud import WordCl... | efwebsite/bkp-files/visualize_tagging.py | import numpy as np
import matplotlib.pyplot as plt
from matplotlib.colors import ListedColormap
from dateutil.relativedelta import relativedelta
from datetime import datetime
import pickle
from scipy.spatial.distance import jensenshannon
from scipy.stats import entropy
import networkx as nx
from wordcloud import WordCl... | 0.477311 | 0.450057 |
import os
import argparse
import traceback
from latexcompiler.utils.compile_tex_files import compile_tex_files
def compile_document(tex_engine, bib_engine, no_bib, path, folder_name):
r"""This function compiles .tex files into .pdf files using the submitted information.
NOTE: It can especially be used for ... | latexcompiler/LC.py | import os
import argparse
import traceback
from latexcompiler.utils.compile_tex_files import compile_tex_files
def compile_document(tex_engine, bib_engine, no_bib, path, folder_name):
r"""This function compiles .tex files into .pdf files using the submitted information.
NOTE: It can especially be used for ... | 0.49585 | 0.174445 |
import unittest
from tests.utilities import BaseTest
from accessors import mongo_db_accessor
from mock import MagicMock, patch
from ddt import data, ddt, unpack
@ddt
class PaginatorTest(BaseTest):
import_route = 'accessors.mongo_db_accessor'
def setUp(self):
self.mock_collection = MagicMock()
de... | tests/test_mongodb_accessor.py | import unittest
from tests.utilities import BaseTest
from accessors import mongo_db_accessor
from mock import MagicMock, patch
from ddt import data, ddt, unpack
@ddt
class PaginatorTest(BaseTest):
import_route = 'accessors.mongo_db_accessor'
def setUp(self):
self.mock_collection = MagicMock()
de... | 0.649467 | 0.299515 |
from django.forms import widgets
from rest_framework import serializers
from links.models import Link
from django.contrib.auth.models import User
import logging
class Wikifetch(object):
def __init__(self, title, description, url):
self.title = title
# self.submitter = submitter
self.descrip... | links/serializers.py | from django.forms import widgets
from rest_framework import serializers
from links.models import Link
from django.contrib.auth.models import User
import logging
class Wikifetch(object):
def __init__(self, title, description, url):
self.title = title
# self.submitter = submitter
self.descrip... | 0.676513 | 0.058885 |
import numpy as np
from astropy.io import fits
from numpy.testing import assert_allclose
from astropy.tests.helper import pytest
from astropy.utils import NumpyRNGContext
from ..ccdproc import *
import os
DATA_SCALE = 5.3
NCRAYS = 30
def add_cosmicrays(data, scale, threshold, ncrays=NCRAYS):
size = data.shap... | ccdproc/tests/test_cosmicray.py |
import numpy as np
from astropy.io import fits
from numpy.testing import assert_allclose
from astropy.tests.helper import pytest
from astropy.utils import NumpyRNGContext
from ..ccdproc import *
import os
DATA_SCALE = 5.3
NCRAYS = 30
def add_cosmicrays(data, scale, threshold, ncrays=NCRAYS):
size = data.shap... | 0.717903 | 0.58747 |
import os,sys
nrpy_dir_path = os.path.join("..")
if nrpy_dir_path not in sys.path:
sys.path.append(nrpy_dir_path)
giraffefood_dir_path = os.path.join("GiRaFFEfood_NRPy")
if giraffefood_dir_path not in sys.path:
sys.path.append(giraffefood_dir_path)
# Step 0: Import the NRPy+ core modules and set the reference ... | in_progress/GiRaFFEfood_NRPy/GiRaFFEfood_NRPy.py | import os,sys
nrpy_dir_path = os.path.join("..")
if nrpy_dir_path not in sys.path:
sys.path.append(nrpy_dir_path)
giraffefood_dir_path = os.path.join("GiRaFFEfood_NRPy")
if giraffefood_dir_path not in sys.path:
sys.path.append(giraffefood_dir_path)
# Step 0: Import the NRPy+ core modules and set the reference ... | 0.314156 | 0.319918 |
from pacman.model.routing_tables.multicast_routing_table import \
MulticastRoutingTable
from pacman.model.routing_tables.multicast_routing_tables import \
MulticastRoutingTables
from spinn_machine.multicast_routing_entry import MulticastRoutingEntry
from spinn_machine.utilities.progress_bar import ProgressBar
... | src/spinnaker_ros_lsm/venv/lib/python2.7/site-packages/pacman/operations/routing_table_generators/basic_routing_table_generator.py | from pacman.model.routing_tables.multicast_routing_table import \
MulticastRoutingTable
from pacman.model.routing_tables.multicast_routing_tables import \
MulticastRoutingTables
from spinn_machine.multicast_routing_entry import MulticastRoutingEntry
from spinn_machine.utilities.progress_bar import ProgressBar
... | 0.731346 | 0.293465 |
import argparse
import os
import sys
from tqdm import tqdm
import numpy as np
import cv2
import json
import keras
import tensorflow as tf
# Allow relative imports when being executed as script.
if __name__ == "__main__" and __package__ is None:
sys.path.insert(0, os.path.join(os.path.dirname(__file__), '..', '..'... | keras_retinanet/bin/predict.py | import argparse
import os
import sys
from tqdm import tqdm
import numpy as np
import cv2
import json
import keras
import tensorflow as tf
# Allow relative imports when being executed as script.
if __name__ == "__main__" and __package__ is None:
sys.path.insert(0, os.path.join(os.path.dirname(__file__), '..', '..'... | 0.422386 | 0.124346 |
# Licensed under the Apache License, Version 2.0 (the "License");
# you may not use this file except in compliance with the License.
# You may obtain a copy of the License at
# http://www.apache.org/licenses/LICENSE-2.0
# Unless required by applicable law or agreed to in writing, software
# distributed under the... | mesonbuild/scripts/depscan.py |
# Licensed under the Apache License, Version 2.0 (the "License");
# you may not use this file except in compliance with the License.
# You may obtain a copy of the License at
# http://www.apache.org/licenses/LICENSE-2.0
# Unless required by applicable law or agreed to in writing, software
# distributed under the... | 0.687315 | 0.183703 |
from django.template.defaultfilters import capfirst
from django.utils.html import format_html
from django.utils.translation import gettext as _
from .css import merge_css_classes
from .html import render_tag
from .size import DEFAULT_SIZE, SIZE_MD, get_size_class
ALERT_TYPES = ["primary", "secondary", "success", "dan... | virtual/lib/python3.8/site-packages/django_bootstrap5/components.py | from django.template.defaultfilters import capfirst
from django.utils.html import format_html
from django.utils.translation import gettext as _
from .css import merge_css_classes
from .html import render_tag
from .size import DEFAULT_SIZE, SIZE_MD, get_size_class
ALERT_TYPES = ["primary", "secondary", "success", "dan... | 0.592667 | 0.115986 |
from pathlib import Path
import numpy as np
from .base_dataset import BaseDataset
from .builder import DATASETS
@DATASETS.register_module()
class GoalClassification(BaseDataset):
"""
进球判定数据集
"""
def load_annotations(self):
"""
0是负样本:没进球
1是正样本:进球了
Re... | mmcls/datasets/goal_classification.py | from pathlib import Path
import numpy as np
from .base_dataset import BaseDataset
from .builder import DATASETS
@DATASETS.register_module()
class GoalClassification(BaseDataset):
"""
进球判定数据集
"""
def load_annotations(self):
"""
0是负样本:没进球
1是正样本:进球了
Re... | 0.33231 | 0.263863 |
import pprint
import re # noqa: F401
import six
class PageElement(object):
"""NOTE: This class is auto generated by the swagger code generator program.
Do not edit the class manually.
"""
"""
Attributes:
swagger_types (dict): The key is attribute name
and the ... | uptrends/models/page_element.py | import pprint
import re # noqa: F401
import six
class PageElement(object):
"""NOTE: This class is auto generated by the swagger code generator program.
Do not edit the class manually.
"""
"""
Attributes:
swagger_types (dict): The key is attribute name
and the ... | 0.73173 | 0.11864 |
import boto3
import hashlib
import os
import json
import base64
from google.oauth2 import service_account
from google.cloud import firestore
# Initialize clents for AWS
local_dynamodb_client = boto3.client('dynamodb')
secrets_client = boto3.client("secretsmanager")
# Load the GCP credential from AWS secrets manager... | dynamodb-firestore/streaming-replication/lambda-func/sync-from-stream.py |
import boto3
import hashlib
import os
import json
import base64
from google.oauth2 import service_account
from google.cloud import firestore
# Initialize clents for AWS
local_dynamodb_client = boto3.client('dynamodb')
secrets_client = boto3.client("secretsmanager")
# Load the GCP credential from AWS secrets manager... | 0.292899 | 0.076615 |
import random
import json
from maze import Maze
class MazeReaderException(Exception):
pass
class MazeReader(object):
""" Read a maze from different input sources """
STDIN = 0
FILE = 1
SOCKET = 2
def __init__(self):
self.maze_rows = []
pass
def readStdin(self):
"... | pyconindia2017concurrency/maze/mazefactory.py | import random
import json
from maze import Maze
class MazeReaderException(Exception):
pass
class MazeReader(object):
""" Read a maze from different input sources """
STDIN = 0
FILE = 1
SOCKET = 2
def __init__(self):
self.maze_rows = []
pass
def readStdin(self):
"... | 0.5794 | 0.228651 |
from typing import List
from threading import Thread
from time import sleep
from pygame import mixer, time
from src.internal.app.interfaces.player import Player
from src.internal.domain.music.playlist import Playlist
from src.internal.domain.music.song import Song
CONTINUOUS_LOOP = 1000000
class LocalPlayer(Player... | src/internal/adapters/local_player.py | from typing import List
from threading import Thread
from time import sleep
from pygame import mixer, time
from src.internal.app.interfaces.player import Player
from src.internal.domain.music.playlist import Playlist
from src.internal.domain.music.song import Song
CONTINUOUS_LOOP = 1000000
class LocalPlayer(Player... | 0.701917 | 0.199503 |
from . import user
from . import exception, utils
import requests
import re
import json
from .utils import Get, Post
import math
headers = utils.default_headers
apis = utils.get_apis()
class SendDynamic:
def __init__(self, text: str, verify: utils.Verify):
self.verify = verify
self._text = ""
... | bilibili_api/src/dynamic.py | from . import user
from . import exception, utils
import requests
import re
import json
from .utils import Get, Post
import math
headers = utils.default_headers
apis = utils.get_apis()
class SendDynamic:
def __init__(self, text: str, verify: utils.Verify):
self.verify = verify
self._text = ""
... | 0.362179 | 0.16502 |
from functools import partial
from typing import TYPE_CHECKING, List, Optional, Union
from anyio import to_thread
from prefect import get_run_logger, task
if TYPE_CHECKING:
from tweepy import Status
from prefect_twitter import TwitterCredentials
@task
async def update_status(
twitter_credentials: "Twi... | prefect_twitter/tweets.py |
from functools import partial
from typing import TYPE_CHECKING, List, Optional, Union
from anyio import to_thread
from prefect import get_run_logger, task
if TYPE_CHECKING:
from tweepy import Status
from prefect_twitter import TwitterCredentials
@task
async def update_status(
twitter_credentials: "Twi... | 0.899467 | 0.375563 |
import os
import datetime
from decimal import Decimal
import sqlite3
import freezegun
import market_data.data_adapter as data_adapter
from market_data.data import EquityData, InvalidTickerError, InvalidDateError
def adapt_date(dt):
return dt.strftime('%Y-%m-%d')
sqlite3.register_adapter(Decimal, lambda d: str(d... | market_data/sqlite3_data_adapter.py | import os
import datetime
from decimal import Decimal
import sqlite3
import freezegun
import market_data.data_adapter as data_adapter
from market_data.data import EquityData, InvalidTickerError, InvalidDateError
def adapt_date(dt):
return dt.strftime('%Y-%m-%d')
sqlite3.register_adapter(Decimal, lambda d: str(d... | 0.343672 | 0.160957 |
import sys
import os
from .base import InvalidInput
import libyang as ly
import sysrepo as sr
from .common import sysrepo_wrap
from tabulate import tabulate
import logging
from natsort import natsorted
logger = logging.getLogger(__name__)
stdout = logging.getLogger("stdout")
stderr = logging.getLogger("stderr")
def... | src/north/cli/gscli/onlp.py | import sys
import os
from .base import InvalidInput
import libyang as ly
import sysrepo as sr
from .common import sysrepo_wrap
from tabulate import tabulate
import logging
from natsort import natsorted
logger = logging.getLogger(__name__)
stdout = logging.getLogger("stdout")
stderr = logging.getLogger("stderr")
def... | 0.280124 | 0.111386 |
import pytest
from samwell import sam
from samwell.sam.sambuilder import SamBuilder
def test_add_pair_all_fields() -> None:
builder = SamBuilder()
builder.add_pair(
name="q1",
chrom="chr1",
bases1="ACGTG",
quals1=[20, 21, 22, 23, 24],
start1=10000,
cigar1="5M"... | samwell/sam/tests/test_sambuilder.py |
import pytest
from samwell import sam
from samwell.sam.sambuilder import SamBuilder
def test_add_pair_all_fields() -> None:
builder = SamBuilder()
builder.add_pair(
name="q1",
chrom="chr1",
bases1="ACGTG",
quals1=[20, 21, 22, 23, 24],
start1=10000,
cigar1="5M"... | 0.569613 | 0.66497 |
import os
import sys
import codecs
import logging
class GenHand(object):
'''
generate handcraft class
'''
def __init__(self, basepath, outfile, logger):
self.basepath = basepath
self.of = outfile
self.cf = []
self.logging = logger
self.filecheck()
def filecheck(self):
pwfs = sorted(os.listdir(os.... | ferup_generateHand.py |
import os
import sys
import codecs
import logging
class GenHand(object):
'''
generate handcraft class
'''
def __init__(self, basepath, outfile, logger):
self.basepath = basepath
self.of = outfile
self.cf = []
self.logging = logger
self.filecheck()
def filecheck(self):
pwfs = sorted(os.listdir(os.... | 0.125654 | 0.076339 |
import argparse
from pathlib import Path
import pandas as pd
from hp_transfer_aa_experiments.analyse._plot_utils import plot_aggregates
from hp_transfer_aa_experiments.analyse._plot_utils import plot_global_aggregates
from hp_transfer_aa_experiments.analyse.read_results import get_approach_data
from hp_transfer_aa_e... | hp_transfer_aa_experiments/analyse/plot_improvements.py | import argparse
from pathlib import Path
import pandas as pd
from hp_transfer_aa_experiments.analyse._plot_utils import plot_aggregates
from hp_transfer_aa_experiments.analyse._plot_utils import plot_global_aggregates
from hp_transfer_aa_experiments.analyse.read_results import get_approach_data
from hp_transfer_aa_e... | 0.672977 | 0.345243 |
import io
import logging
import multiprocessing as mp
import os
import types
from datetime import datetime, timedelta
import humanfriendly
import psutil
import tqdm
from sdgym.data import load_dataset
from sdgym.evaluate import compute_scores
from sdgym.results import make_leaderboard
from sdgym.synthesizers.base im... | sdgym/benchmark.py |
import io
import logging
import multiprocessing as mp
import os
import types
from datetime import datetime, timedelta
import humanfriendly
import psutil
import tqdm
from sdgym.data import load_dataset
from sdgym.evaluate import compute_scores
from sdgym.results import make_leaderboard
from sdgym.synthesizers.base im... | 0.69035 | 0.177811 |
from app import app
from db_config import *
from flask import jsonify, request
@app.route("/api/Admin/view/items_sold_unsold", methods=["GET"])
def sold_unsold_items():
conn = mysql.connection
cursor = conn.cursor()
try:
sql = f"""-- sql
SELECT `Sold`.`Product ID` AS `IID`, `Sol... | Backend Server/AdminRoutes/admin_frontpage.py | from app import app
from db_config import *
from flask import jsonify, request
@app.route("/api/Admin/view/items_sold_unsold", methods=["GET"])
def sold_unsold_items():
conn = mysql.connection
cursor = conn.cursor()
try:
sql = f"""-- sql
SELECT `Sold`.`Product ID` AS `IID`, `Sol... | 0.298594 | 0.05634 |
from uuid import uuid4
from django.core.cache import cache
from drf_yasg.views import get_schema_view
from drf_yasg import openapi
from rest_framework import permissions, authentication
from rest_framework.response import Response
from rest_framework.views import APIView
from rest_framework.viewsets import GenericViewS... | core/views.py | from uuid import uuid4
from django.core.cache import cache
from drf_yasg.views import get_schema_view
from drf_yasg import openapi
from rest_framework import permissions, authentication
from rest_framework.response import Response
from rest_framework.views import APIView
from rest_framework.viewsets import GenericViewS... | 0.595845 | 0.071591 |
from cloudcafe.common.models.configuration import ConfigSectionInterface
class AutoscaleConfig(ConfigSectionInterface):
"""
Defines the config values for autoscale
"""
SECTION_NAME = 'autoscale'
@property
def tenant_id(self):
"""
Tenant ID of the account
"""
re... | autoscale_cloudcafe/autoscale/config.py | from cloudcafe.common.models.configuration import ConfigSectionInterface
class AutoscaleConfig(ConfigSectionInterface):
"""
Defines the config values for autoscale
"""
SECTION_NAME = 'autoscale'
@property
def tenant_id(self):
"""
Tenant ID of the account
"""
re... | 0.895603 | 0.15034 |
import copy
import io
import os
import time
import warnings
from collections import namedtuple
import matplotlib
import utils.file_utils as file_utils
from codescan_interface import CodescanInterface
matplotlib.use('agg')
from matplotlib.pyplot import clf
from pylab import savefig, close
class PlotBase(object):
... | plot_base.py | import copy
import io
import os
import time
import warnings
from collections import namedtuple
import matplotlib
import utils.file_utils as file_utils
from codescan_interface import CodescanInterface
matplotlib.use('agg')
from matplotlib.pyplot import clf
from pylab import savefig, close
class PlotBase(object):
... | 0.645902 | 0.273793 |
from __future__ import division, absolute_import, print_function
"""
File list functions.
Provided functions
------------------
fullnames Filenames with absolute paths in local directories.
fullnames_dates Filenames with absolute paths and modification times in local ... | jams/files/__init__.py | from __future__ import division, absolute_import, print_function
"""
File list functions.
Provided functions
------------------
fullnames Filenames with absolute paths in local directories.
fullnames_dates Filenames with absolute paths and modification times in local ... | 0.5564 | 0.126273 |
from typing import Dict
from ir_datasets import registry
from ir_datasets.datasets.base import Dataset, YamlDocumentation
from ir_datasets.formats import ToucheQueries, ToucheQrels
from ir_datasets.formats.touche import ToucheQualityQrels
from ir_datasets.util import DownloadConfig, home_path, Cache, ZipExtract
NAME ... | ir_datasets/datasets/touche.py | from typing import Dict
from ir_datasets import registry
from ir_datasets.datasets.base import Dataset, YamlDocumentation
from ir_datasets.formats import ToucheQueries, ToucheQrels
from ir_datasets.formats.touche import ToucheQualityQrels
from ir_datasets.util import DownloadConfig, home_path, Cache, ZipExtract
NAME ... | 0.770853 | 0.423696 |
from datetime import datetime, timedelta
import html2text
import json
from langdetect import detect, DetectorFactory
from multiprocessing import Pool
import pandas as pd
import re
import scraper
import string
import sys
from urllib.parse import quote
import utils
def review(bloglist_file, api_key, request_rate=0.25, o... | tools/scraper/reviews.py | from datetime import datetime, timedelta
import html2text
import json
from langdetect import detect, DetectorFactory
from multiprocessing import Pool
import pandas as pd
import re
import scraper
import string
import sys
from urllib.parse import quote
import utils
def review(bloglist_file, api_key, request_rate=0.25, o... | 0.125909 | 0.092074 |
from girder.api import access
from girder.api.describe import Description, describeRoute
from girder.api.rest import Resource, filtermodel
class Fib(Resource):
def __init__(self):
super(Fib, self).__init__()
self.resourceName = 'fib'
self.route('POST', (), self.run_fib_sequence)
se... | packages/girder_worker/devops/ansible/examples/etc/fibonacci_plugin/server/__init__.py | from girder.api import access
from girder.api.describe import Description, describeRoute
from girder.api.rest import Resource, filtermodel
class Fib(Resource):
def __init__(self):
super(Fib, self).__init__()
self.resourceName = 'fib'
self.route('POST', (), self.run_fib_sequence)
se... | 0.573917 | 0.101456 |
import argparse
from collections import defaultdict
from tqdm import tqdm
from util import read_jsonl, write_jsonl
def read_records(file_name, min_agreement=0.69, task="simple"):
orig_records = read_jsonl(file_name)
records = []
for r in tqdm(orig_records):
if float(r[task + "_agreement"]) < min... | headline_cause/crowd/split.py | import argparse
from collections import defaultdict
from tqdm import tqdm
from util import read_jsonl, write_jsonl
def read_records(file_name, min_agreement=0.69, task="simple"):
orig_records = read_jsonl(file_name)
records = []
for r in tqdm(orig_records):
if float(r[task + "_agreement"]) < min... | 0.437343 | 0.328583 |
import os
import glob
import json
import boto3
import config
import tarfile
import logging
import logging.config
import argparse
import requests
logging.config.dictConfig(config.LOGGING)
logger = logging.getLogger()
def parse_visualizations(dashboard):
"""
Parse the visualizations from a dashboard
:param ... | kibtools/dashboard.py | import os
import glob
import json
import boto3
import config
import tarfile
import logging
import logging.config
import argparse
import requests
logging.config.dictConfig(config.LOGGING)
logger = logging.getLogger()
def parse_visualizations(dashboard):
"""
Parse the visualizations from a dashboard
:param ... | 0.498535 | 0.196325 |
import copy
import random
from functools import wraps,partial
import torch
from torch import nn
import torch.nn.functional as F
from torchvision import transforms as T
# helper functions
def default(val, def_val):
return def_val if val is None else val
def flatten(t):
return t.reshape(t.shape... | Pixel/pixcl.py | import copy
import random
from functools import wraps,partial
import torch
from torch import nn
import torch.nn.functional as F
from torchvision import transforms as T
# helper functions
def default(val, def_val):
return def_val if val is None else val
def flatten(t):
return t.reshape(t.shape... | 0.853211 | 0.217109 |
from __future__ import annotations
import disnake
import pandas as pd
from disnake.ext import commands
from discordbot.config_discordbot import logger
from discordbot.stocks.technical_analysis.ad import ad_command
from discordbot.stocks.technical_analysis.adosc import adosc_command
from discordbot.stocks.technical_an... | discordbot/cmds/ta_cmds.py | from __future__ import annotations
import disnake
import pandas as pd
from disnake.ext import commands
from discordbot.config_discordbot import logger
from discordbot.stocks.technical_analysis.ad import ad_command
from discordbot.stocks.technical_analysis.adosc import adosc_command
from discordbot.stocks.technical_an... | 0.75037 | 0.201813 |