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 json
import time
import gear
from gearhorn import util
from gearhorn.store import sqla
class GearhornWorker(gear.Worker):
subscribe_name = 'subscribe_fanout'
unsubscribe_name = 'unsubscribe_fanout'
fanout_name = 'fanout'
foreground_timeout = 30
def __init__(self, client_id=None, worker_i... | gearhorn/worker.py | import json
import time
import gear
from gearhorn import util
from gearhorn.store import sqla
class GearhornWorker(gear.Worker):
subscribe_name = 'subscribe_fanout'
unsubscribe_name = 'unsubscribe_fanout'
fanout_name = 'fanout'
foreground_timeout = 30
def __init__(self, client_id=None, worker_i... | 0.203312 | 0.041365 |
import numpy as np
from astropy.modeling import Model
from asdf.extension import Converter
class DISPXY_Model(Model):
n_inputs = 3
n_outputs = 1
inputs = ("x", "y", "t")
outputs = ("variable",)
_tag = "tag:stsci.edu:grismstuff/dispxy_model-1.0.0"
_name = "DISPXY_Model"
def __init__(self,... | astrogrism/HST/dispersion_models.py | import numpy as np
from astropy.modeling import Model
from asdf.extension import Converter
class DISPXY_Model(Model):
n_inputs = 3
n_outputs = 1
inputs = ("x", "y", "t")
outputs = ("variable",)
_tag = "tag:stsci.edu:grismstuff/dispxy_model-1.0.0"
_name = "DISPXY_Model"
def __init__(self,... | 0.735262 | 0.563258 |
from examples.contrib_schematics import app
def test_main_view():
request, response = app.test_client.get('/')
assert response.status == 200
assert response.text == 'Hi mate!'
def test_post_json_ok():
data = {
'id': 2,
'extra-data': 'ignored data'
}
headers = {
'x-tes... | tests/examples/test_contrib_schematics.py | from examples.contrib_schematics import app
def test_main_view():
request, response = app.test_client.get('/')
assert response.status == 200
assert response.text == 'Hi mate!'
def test_post_json_ok():
data = {
'id': 2,
'extra-data': 'ignored data'
}
headers = {
'x-tes... | 0.757794 | 0.508483 |
import torch
import torch.nn as nn
def DownConvolution(in_channels, out_channels):
conv = nn.Sequential(nn.Conv3d(in_channels, out_channels,stride=1, kernel_size=3, padding=1),
nn.ReLU(inplace=False),
nn.Conv3d(out_channels, out_channels, stride=1, kernel_size=3, p... | models/unet3d.py | import torch
import torch.nn as nn
def DownConvolution(in_channels, out_channels):
conv = nn.Sequential(nn.Conv3d(in_channels, out_channels,stride=1, kernel_size=3, padding=1),
nn.ReLU(inplace=False),
nn.Conv3d(out_channels, out_channels, stride=1, kernel_size=3, p... | 0.933416 | 0.482307 |
import pandas as pd
import dynamicIndicatorDemo_run as mdd
from cnx import pyalg_utils
from cnx import dataFramefeed
from pyalgotrade import plotter, bar
from pyalgotrade.tools import resample
from pyalgotrade.stratanalyzer import returns, sharpe
def bolling_trans_data():
dat = pd.read_csv("../../api/stock/csv/6... | samples/mysample/dynamicIndicatorDemo.py | import pandas as pd
import dynamicIndicatorDemo_run as mdd
from cnx import pyalg_utils
from cnx import dataFramefeed
from pyalgotrade import plotter, bar
from pyalgotrade.tools import resample
from pyalgotrade.stratanalyzer import returns, sharpe
def bolling_trans_data():
dat = pd.read_csv("../../api/stock/csv/6... | 0.326808 | 0.220468 |
import time
import subprocess
file_name = "output.txt"
threshold = 30
vm_list = []
vm_cpuUtilization = {}
def readGanglia():
"""
This function open and reads data file from ganglia
The data file is of the format ip_addr||cpu_utilization
It parses the file and if at any point the cpu_utili... | replace.py | import time
import subprocess
file_name = "output.txt"
threshold = 30
vm_list = []
vm_cpuUtilization = {}
def readGanglia():
"""
This function open and reads data file from ganglia
The data file is of the format ip_addr||cpu_utilization
It parses the file and if at any point the cpu_utili... | 0.090409 | 0.316396 |
from datetime import datetime
import time
from app.models import Comment
def format_default_timestamp_single(user_item):
now = datetime.now()
return now.strftime("%m/%d/%Y, %H:%M:%S")
def convert_ids_string_to_array(ids_str: str):
if ids_str != "":
ids_array = []
split_str = ids_str.spl... | app/utils.py | from datetime import datetime
import time
from app.models import Comment
def format_default_timestamp_single(user_item):
now = datetime.now()
return now.strftime("%m/%d/%Y, %H:%M:%S")
def convert_ids_string_to_array(ids_str: str):
if ids_str != "":
ids_array = []
split_str = ids_str.spl... | 0.387227 | 0.215908 |
import io
import tarfile
import subprocess
import json
import re
import os
import itertools
import requests
import ccr
import aur
from chaser import pacman
from aur2ccr import archpkg
SRC_URL = "https://aur.archlinux.org/cgit/aur.git/snapshot/{pkgname}.tar.gz"
def get_source_files(pkgname, workingdir="."):
"""D... | aur2ccr/aur2ccr.py | import io
import tarfile
import subprocess
import json
import re
import os
import itertools
import requests
import ccr
import aur
from chaser import pacman
from aur2ccr import archpkg
SRC_URL = "https://aur.archlinux.org/cgit/aur.git/snapshot/{pkgname}.tar.gz"
def get_source_files(pkgname, workingdir="."):
"""D... | 0.292696 | 0.066357 |
import json
from django.core.exceptions import ObjectDoesNotExist
from rest_framework import serializers
from .exceptions import *
from .static import *
from .models import *
# Model serializers
class JSONField(serializers.Field):
def _loads_data(self, data):
try:
value = json.loads(data)
... | modules/msa/msa/contrib/uniqauth/serializers.py | import json
from django.core.exceptions import ObjectDoesNotExist
from rest_framework import serializers
from .exceptions import *
from .static import *
from .models import *
# Model serializers
class JSONField(serializers.Field):
def _loads_data(self, data):
try:
value = json.loads(data)
... | 0.516108 | 0.115811 |
from transitions.extensions import GraphMachine
import telegram
bot = telegram.Bot(token='450660612:<KEY>')
my_id = 382468305
class TocMachine(GraphMachine):
def __init__(self, **machine_configs):
self.machine = GraphMachine(
model = self,
**machine_configs
)
self.to... | fsm.py | from transitions.extensions import GraphMachine
import telegram
bot = telegram.Bot(token='450660612:<KEY>')
my_id = 382468305
class TocMachine(GraphMachine):
def __init__(self, **machine_configs):
self.machine = GraphMachine(
model = self,
**machine_configs
)
self.to... | 0.26322 | 0.094594 |
# ROS packages required
import rospy
from eager_core.eager_env import BaseEagerEnv
from eager_core.objects import Object
from eager_core.wrappers.flatten import Flatten
from eager_bridge_webots.webots_engine import WebotsEngine # noqa: F401
from eager_bridge_pybullet.pybullet_engine import PyBulletEngine # noqa: F40... | examples/eager_examples/scripts/example_switch_engine.py |
# ROS packages required
import rospy
from eager_core.eager_env import BaseEagerEnv
from eager_core.objects import Object
from eager_core.wrappers.flatten import Flatten
from eager_bridge_webots.webots_engine import WebotsEngine # noqa: F401
from eager_bridge_pybullet.pybullet_engine import PyBulletEngine # noqa: F40... | 0.761982 | 0.329634 |
import filecmp
import json
import os
import sys
import time
import traceback
import urllib
import requests
from requests.exceptions import RequestException
ES_LB = os.getenv('ELASTICSEARCH_LB', 'false').lower() in ['true', '1', 't']
ES_URLS = os.getenv('ELASTICSEARCH_URLS').split(',')
SLEEP_TIME = float(os.getenv('S... | dockerfiles/logstash/elastic_watchdog.py | import filecmp
import json
import os
import sys
import time
import traceback
import urllib
import requests
from requests.exceptions import RequestException
ES_LB = os.getenv('ELASTICSEARCH_LB', 'false').lower() in ['true', '1', 't']
ES_URLS = os.getenv('ELASTICSEARCH_URLS').split(',')
SLEEP_TIME = float(os.getenv('S... | 0.233619 | 0.07343 |
class ModelArg():
"""A class to mimic the command line parser.
----------------EXPERIMENT------------------
:name: an alias to the experiment
:model_save_to: path of the saved file, including log and parameters
------------------DATASET------------------
:val_split_ratio: percentage of the valid... | src/utils/model_arg.py | class ModelArg():
"""A class to mimic the command line parser.
----------------EXPERIMENT------------------
:name: an alias to the experiment
:model_save_to: path of the saved file, including log and parameters
------------------DATASET------------------
:val_split_ratio: percentage of the valid... | 0.842313 | 0.658102 |
import xcb.xproto
import xpybutil.ewmh as ewmh
import xpybutil.window as window
def rect_intersect_area(r1, r2):
"""
Returns the area of the intersection of two rectangles. If the rectangles
do not intersect, the area returned is 0.
:param r1: A 4-tuple representing a rectangle:
(top_... | xpybutil/rect.py | import xcb.xproto
import xpybutil.ewmh as ewmh
import xpybutil.window as window
def rect_intersect_area(r1, r2):
"""
Returns the area of the intersection of two rectangles. If the rectangles
do not intersect, the area returned is 0.
:param r1: A 4-tuple representing a rectangle:
(top_... | 0.876132 | 0.670871 |
from __future__ import unicode_literals
from django.db import models, migrations
import open_connect.connect_core.utils.models
import django_extensions.db.fields
import django.utils.timezone
from django.conf import settings
from pytz import common_timezones
from open_connect.connect_core.utils.location import STATES
i... | open_connect/accounts/migrations/0001_initial.py | from __future__ import unicode_literals
from django.db import models, migrations
import open_connect.connect_core.utils.models
import django_extensions.db.fields
import django.utils.timezone
from django.conf import settings
from pytz import common_timezones
from open_connect.connect_core.utils.location import STATES
i... | 0.534612 | 0.136263 |
import ErrorChecker
from collections import defaultdict
import random
import TableBotExceptions
import UtilityFunctions
import UserDataProcessing
tableColorPairs = [("#244f96", "#cce7e8"),
("#D11425","#E8EE28"),
("#E40CA6","#ADCFCD"),
("#2EFF04","#FF04... | War.py | import ErrorChecker
from collections import defaultdict
import random
import TableBotExceptions
import UtilityFunctions
import UserDataProcessing
tableColorPairs = [("#244f96", "#cce7e8"),
("#D11425","#E8EE28"),
("#E40CA6","#ADCFCD"),
("#2EFF04","#FF04... | 0.226441 | 0.100481 |
from sqlalchemy import Table, select
import sqlalchemy
from sqlalchemy.sql.expression import BinaryExpression
import asyncio
import datetime
from sqlalchemy.engine.base import Connection
class eventTriggerRepo():
__eventTriggerTable: Table
__context: Connection
def __init__(self, eventTriggerTable: Table... | Repository/eventTriggerRepo.py | from sqlalchemy import Table, select
import sqlalchemy
from sqlalchemy.sql.expression import BinaryExpression
import asyncio
import datetime
from sqlalchemy.engine.base import Connection
class eventTriggerRepo():
__eventTriggerTable: Table
__context: Connection
def __init__(self, eventTriggerTable: Table... | 0.315525 | 0.138637 |
import constants as CONST
import datetime
from selenium.webdriver.common.by import By
from web_driver import WebDriver
class ZalandoBot:
def __init__(self, timeout):
self.timeout = timeout
def log(self, message, severity):
now = datetime.now()
current_time = now.strftime("%H:%M:%S")
... | zalando_bot.py | import constants as CONST
import datetime
from selenium.webdriver.common.by import By
from web_driver import WebDriver
class ZalandoBot:
def __init__(self, timeout):
self.timeout = timeout
def log(self, message, severity):
now = datetime.now()
current_time = now.strftime("%H:%M:%S")
... | 0.191706 | 0.044514 |
import subprocess
from typing import List, Tuple
from pathlib import Path
import sys
from lxml import etree
EVAL_DIR = Path("/tmp/eval")
def prepare_filesystem():
if EVAL_DIR.exists():
for file in EVAL_DIR.glob("./*"):
file.unlink()
else:
EVAL_DIR.mkdir(parents=True, exist_ok=Tru... | ocr4all_helper_scripts/helpers/calamari_eval_helper.py | import subprocess
from typing import List, Tuple
from pathlib import Path
import sys
from lxml import etree
EVAL_DIR = Path("/tmp/eval")
def prepare_filesystem():
if EVAL_DIR.exists():
for file in EVAL_DIR.glob("./*"):
file.unlink()
else:
EVAL_DIR.mkdir(parents=True, exist_ok=Tru... | 0.328745 | 0.127598 |
import PySimpleGUI as sg
from datetime import datetime
from time import sleep
sg.theme('black')
class Gui:
def __init__(self):
self.layout=[[sg.Graph(canvas_size=(215,130), graph_bottom_left=(0,0), graph_top_right=(215,130), background_color='gray', key='graph')],
[ sg.Text('Bin Clock ... | BinaryClock.py | import PySimpleGUI as sg
from datetime import datetime
from time import sleep
sg.theme('black')
class Gui:
def __init__(self):
self.layout=[[sg.Graph(canvas_size=(215,130), graph_bottom_left=(0,0), graph_top_right=(215,130), background_color='gray', key='graph')],
[ sg.Text('Bin Clock ... | 0.209712 | 0.1661 |
from thrift.Thrift import TType, TMessageType, TFrozenDict, TException, TApplicationException
from thrift.protocol.TProtocol import TProtocolException
import sys
import logging
from .ttypes import *
from thrift.Thrift import TProcessor
from thrift.transport import TTransport
class Iface(object):
def ping(self):
... | py/invoke/gen-py/map_service/MapService.py |
from thrift.Thrift import TType, TMessageType, TFrozenDict, TException, TApplicationException
from thrift.protocol.TProtocol import TProtocolException
import sys
import logging
from .ttypes import *
from thrift.Thrift import TProcessor
from thrift.transport import TTransport
class Iface(object):
def ping(self):
... | 0.525369 | 0.09782 |
import warnings
import pulumi
import pulumi.runtime
from typing import Any, Mapping, Optional, Sequence, Union, overload
from .. import _utilities
from . import outputs
__all__ = [
'GetUserResult',
'AwaitableGetUserResult',
'get_user',
'get_user_output',
]
@pulumi.output_type
class GetUserResult:
... | sdk/python/pulumi_aws_native/transfer/get_user.py |
import warnings
import pulumi
import pulumi.runtime
from typing import Any, Mapping, Optional, Sequence, Union, overload
from .. import _utilities
from . import outputs
__all__ = [
'GetUserResult',
'AwaitableGetUserResult',
'get_user',
'get_user_output',
]
@pulumi.output_type
class GetUserResult:
... | 0.73077 | 0.054651 |
from ebcli.lib import elasticbeanstalk
from ebcli.core import io, fileoperations
from ebcli.objects.environmentsettings import EnvironmentSettings
from ebcli.objects.exceptions import InvalidSyntaxError
from ebcli.resources.strings import prompts, strings
from ebcli.operations import commonops
from urllib.parse impor... | venv/Lib/site-packages/ebcli/operations/configops.py |
from ebcli.lib import elasticbeanstalk
from ebcli.core import io, fileoperations
from ebcli.objects.environmentsettings import EnvironmentSettings
from ebcli.objects.exceptions import InvalidSyntaxError
from ebcli.resources.strings import prompts, strings
from ebcli.operations import commonops
from urllib.parse impor... | 0.374333 | 0.080285 |
import numpy as np
import pandas as pd
def dataframe_config_prop(data_frame, cols):
'''
The purpose of this method is to return a boolean of
true if and only if three things happen:
1) columns of data_frame match the column in "columns"
2) the values in each column are of the same type
3) there... | df_test.py | import numpy as np
import pandas as pd
def dataframe_config_prop(data_frame, cols):
'''
The purpose of this method is to return a boolean of
true if and only if three things happen:
1) columns of data_frame match the column in "columns"
2) the values in each column are of the same type
3) there... | 0.506836 | 0.681924 |
import unittest
from unittest.case import SkipTest
from SBTi.interfaces import (
EScope,
ETimeFrames,
IDataProviderCompany,
IDataProviderTarget,
PortfolioCompany,
)
from SBTi.temperature_score import (
EngagementType,
Scenario,
TemperatureScore,
)
from SBTi.portfolio_aggregation import ... | test/test_edge_cases.py | import unittest
from unittest.case import SkipTest
from SBTi.interfaces import (
EScope,
ETimeFrames,
IDataProviderCompany,
IDataProviderTarget,
PortfolioCompany,
)
from SBTi.temperature_score import (
EngagementType,
Scenario,
TemperatureScore,
)
from SBTi.portfolio_aggregation import ... | 0.745769 | 0.446615 |
from typing import Dict
import httpx
import pytest
from starlette import status
@pytest.mark.asyncio
async def test_get(test_client_all_sensitive: httpx.AsyncClient):
response = await test_client_all_sensitive.get("/get")
assert response.status_code == status.HTTP_200_OK
assert "csrftoken" in response.... | tests/test_middleware.py | from typing import Dict
import httpx
import pytest
from starlette import status
@pytest.mark.asyncio
async def test_get(test_client_all_sensitive: httpx.AsyncClient):
response = await test_client_all_sensitive.get("/get")
assert response.status_code == status.HTTP_200_OK
assert "csrftoken" in response.... | 0.703142 | 0.433262 |
import math
import numpy as np
import tensorflow as tf
from datetime import datetime
from utils.data_prep import train_validation
def optimize(
num_iterations,
train_batch_size,
input_train,
output_train,
session,
x,
y_true,
optimizer,
accuracy,
cost,
prob
):
# Start t... | src/ssh-kd/utils/optimize.py | import math
import numpy as np
import tensorflow as tf
from datetime import datetime
from utils.data_prep import train_validation
def optimize(
num_iterations,
train_batch_size,
input_train,
output_train,
session,
x,
y_true,
optimizer,
accuracy,
cost,
prob
):
# Start t... | 0.778733 | 0.390708 |
import maya.cmds as cmds
from mop.vendor.Qt import QtWidgets
class SpinBox(QtWidgets.QSpinBox):
def __init__(self, field, *args, **kwargs):
super(SpinBox, self).__init__(*args, **kwargs)
self.field = field
minValue = field.min_value
maxValue = field.max_value
if minValue i... | mop/ui/fieldwidgets.py | import maya.cmds as cmds
from mop.vendor.Qt import QtWidgets
class SpinBox(QtWidgets.QSpinBox):
def __init__(self, field, *args, **kwargs):
super(SpinBox, self).__init__(*args, **kwargs)
self.field = field
minValue = field.min_value
maxValue = field.max_value
if minValue i... | 0.593609 | 0.122812 |
from openpyxl import Workbook
from openpyxl.styles import PatternFill
from openpyxl.styles.borders import Border, Side
from openpyxl.styles.colors import Color
from openpyxl.comments import Comment
from openpyxl.utils import get_column_letter
import collections
from cross2sheet.grid_features import *
class _CellStyle:... | cross2sheet/excel.py | from openpyxl import Workbook
from openpyxl.styles import PatternFill
from openpyxl.styles.borders import Border, Side
from openpyxl.styles.colors import Color
from openpyxl.comments import Comment
from openpyxl.utils import get_column_letter
import collections
from cross2sheet.grid_features import *
class _CellStyle:... | 0.5083 | 0.175786 |
import numpy as np
class _InitializerDeclarationDict(dict):
"""
Custom Dictionary class for Initializers. It stores registered initializers.
"""
def __getitem__(self, key):
try:
return self.__dict__[key]
except KeyError as e:
msg = f"The Initializer `{key}` i... | gNet/initializer.py | import numpy as np
class _InitializerDeclarationDict(dict):
"""
Custom Dictionary class for Initializers. It stores registered initializers.
"""
def __getitem__(self, key):
try:
return self.__dict__[key]
except KeyError as e:
msg = f"The Initializer `{key}` i... | 0.72331 | 0.312449 |
import math
import torch
import torch.nn as nn
import torch.nn.functional as F
class deeplabv3plus(nn.Module):
def __init__(self, n_classes=21):
super(deeplabv3plus, self).__init__()
# Atrous Conv
self.xception_features = Xception()
# ASPP
rates = [1, 6, 12, 18]
... | lib/model/deeplabv3plus.py | import math
import torch
import torch.nn as nn
import torch.nn.functional as F
class deeplabv3plus(nn.Module):
def __init__(self, n_classes=21):
super(deeplabv3plus, self).__init__()
# Atrous Conv
self.xception_features = Xception()
# ASPP
rates = [1, 6, 12, 18]
... | 0.888218 | 0.460532 |
# pylint: disable=C0103
import numpy as np
from scipy.integrate import quad as integ
from anaflow.tools.laplace import get_lap_inv
from anaflow.flow.laplace import grf_laplace
from anaflow.tools.special import Shaper, sph_surf
__all__ = ["ext_grf", "ext_grf_steady"]
def ext_grf(
time,
rad,
S_part,
K... | anaflow/flow/ext_grf_model.py | # pylint: disable=C0103
import numpy as np
from scipy.integrate import quad as integ
from anaflow.tools.laplace import get_lap_inv
from anaflow.flow.laplace import grf_laplace
from anaflow.tools.special import Shaper, sph_surf
__all__ = ["ext_grf", "ext_grf_steady"]
def ext_grf(
time,
rad,
S_part,
K... | 0.917196 | 0.561395 |
import utils
from utils import *
import time
from selenium.webdriver.common.action_chains import ActionChains
from selenium.webdriver.common.keys import Keys
class Francetv(Chaine):
def __init__(self):
super().__init__("https://www.france.tv/")
self.tousLesNoeuds = {}
mytuple = ... | francetv.py | import utils
from utils import *
import time
from selenium.webdriver.common.action_chains import ActionChains
from selenium.webdriver.common.keys import Keys
class Francetv(Chaine):
def __init__(self):
super().__init__("https://www.france.tv/")
self.tousLesNoeuds = {}
mytuple = ... | 0.076102 | 0.115836 |
import time
import os
from celery import Celery
from celery.bin import worker
import en_core_web_sm
from bots.chat_client import ChatClient
from bots.lib.bot_helper import *
celery_app = Celery('tasks', broker=os.environ['REDIS_URL'])
nlp = None
def load_nlp():
global nlp
if nlp is None:
print("Load... | tasks.py | import time
import os
from celery import Celery
from celery.bin import worker
import en_core_web_sm
from bots.chat_client import ChatClient
from bots.lib.bot_helper import *
celery_app = Celery('tasks', broker=os.environ['REDIS_URL'])
nlp = None
def load_nlp():
global nlp
if nlp is None:
print("Load... | 0.265404 | 0.083553 |
import tensorflow as tf
from tensorflow.examples.tutorials.mnist import input_data
mnist = input_data.read_data_sets("./mnist/data/", one_hot=True)
lr = 0.01
epochs = 10
batch_size = 100
display_step = 1
def inference(x):
tf.constant_initializer(value=0)
W = tf.get_variable("W",[784,10])
b = t... | others/mnist_tensorflow.py | import tensorflow as tf
from tensorflow.examples.tutorials.mnist import input_data
mnist = input_data.read_data_sets("./mnist/data/", one_hot=True)
lr = 0.01
epochs = 10
batch_size = 100
display_step = 1
def inference(x):
tf.constant_initializer(value=0)
W = tf.get_variable("W",[784,10])
b = t... | 0.762159 | 0.523725 |
import os
import re
import fnmatch
import zipfile
import shutil
import getpass
import glob
PATH = "/Users/"+ getpass.getuser() + "/Downloads"
ProtectImagePath = "/Users/wzg/Downloads/testimage/help_images"
prefix = "FS_HelpGuide_"
#获取替换文件的路径
def realProtectImagePath():
global ProtectImagePath
if os.path.isdi... | Python/Script/relaceGuideImages.py | import os
import re
import fnmatch
import zipfile
import shutil
import getpass
import glob
PATH = "/Users/"+ getpass.getuser() + "/Downloads"
ProtectImagePath = "/Users/wzg/Downloads/testimage/help_images"
prefix = "FS_HelpGuide_"
#获取替换文件的路径
def realProtectImagePath():
global ProtectImagePath
if os.path.isdi... | 0.043346 | 0.059346 |
import pprint
import re # noqa: F401
import six
from signing_today_client.configuration import Configuration
class DeviceAuthorizationResponse(object):
"""NOTE: This class is auto generated by OpenAPI Generator.
Ref: https://openapi-generator.tech
Do not edit the class manually.
"""
"""
A... | signing_today_client/models/device_authorization_response.py | import pprint
import re # noqa: F401
import six
from signing_today_client.configuration import Configuration
class DeviceAuthorizationResponse(object):
"""NOTE: This class is auto generated by OpenAPI Generator.
Ref: https://openapi-generator.tech
Do not edit the class manually.
"""
"""
A... | 0.685634 | 0.093099 |
from __future__ import absolute_import, print_function, division
import numpy as np
from scipy.stats import norm
from ..basics.classifier_characteristics import ClassifierCharacteristics
def feature_importance_mad(clf,
alpha=0.05,
ignored_percentile=None):
"... | disteval/evaluation/feature_importance_test.py | from __future__ import absolute_import, print_function, division
import numpy as np
from scipy.stats import norm
from ..basics.classifier_characteristics import ClassifierCharacteristics
def feature_importance_mad(clf,
alpha=0.05,
ignored_percentile=None):
"... | 0.883355 | 0.708712 |
import os
import multiprocessing
from pulp import *
import csv
import numpy as np
import random
import pandas as pd
from optparse import OptionParser
from itertools import permutations
# Create some arguments to make script more flexible - can now specify whether we want a full team refresh (time intensive)
... | python/premier_league_picker.py | import os
import multiprocessing
from pulp import *
import csv
import numpy as np
import random
import pandas as pd
from optparse import OptionParser
from itertools import permutations
# Create some arguments to make script more flexible - can now specify whether we want a full team refresh (time intensive)
... | 0.311008 | 0.233521 |
import os
import random
from bokeh.plotting import figure, show
def print_table(x, y, parameter):
"""
This function prints a table and gives a format to it. This functions
is base to print f(x) functions so recibes de following parameters.
params: x type list
y type list
... | src/lib/prints.py | import os
import random
from bokeh.plotting import figure, show
def print_table(x, y, parameter):
"""
This function prints a table and gives a format to it. This functions
is base to print f(x) functions so recibes de following parameters.
params: x type list
y type list
... | 0.307462 | 0.576482 |
from __future__ import print_function
import sys
import os
import pprint
import urllib
import random
import uuid
import time
import json
import decimal
import boto3
import unittest
import testenv
import requests
from requests_aws4auth import AWS4Auth
from common import get_msgs
import botocore.exceptions
class Te... | test/test_sessions.py | from __future__ import print_function
import sys
import os
import pprint
import urllib
import random
import uuid
import time
import json
import decimal
import boto3
import unittest
import testenv
import requests
from requests_aws4auth import AWS4Auth
from common import get_msgs
import botocore.exceptions
class Te... | 0.157785 | 0.157525 |
import hashlib
import os
import pathlib
import shutil
import stat
from ..constants import (
root_node,
bin_node,
shims_node,
multi_bin_node,
multi_shims_node,
multi_shim_node,
)
from ._internal import load_yaml_document
from .reference import Reference
SHIM_TEMPLATE = """\
#!/usr/bin/env bash
... | sashimmi/models/shim.py | import hashlib
import os
import pathlib
import shutil
import stat
from ..constants import (
root_node,
bin_node,
shims_node,
multi_bin_node,
multi_shims_node,
multi_shim_node,
)
from ._internal import load_yaml_document
from .reference import Reference
SHIM_TEMPLATE = """\
#!/usr/bin/env bash
... | 0.299925 | 0.091585 |
import pytest
from AIPscan.conftest import AIP_CREATION_TIME, INGEST_EVENT_CREATION_TIME
from AIPscan.Data import fields, report_data
@pytest.mark.parametrize(
"storage_id, storage_name, location_id, location_name, number_of_ingests, aip_uuid, aip_name, user_name, ingest_date, aip_creation_date",
[
#... | AIPscan/Data/tests/test_agents_transfers.py | import pytest
from AIPscan.conftest import AIP_CREATION_TIME, INGEST_EVENT_CREATION_TIME
from AIPscan.Data import fields, report_data
@pytest.mark.parametrize(
"storage_id, storage_name, location_id, location_name, number_of_ingests, aip_uuid, aip_name, user_name, ingest_date, aip_creation_date",
[
#... | 0.652463 | 0.498352 |
import matplotlib
matplotlib.use('Agg')
import matplotlib.pyplot as plt
import numpy as np
import os
import sys
import scipy
data_path = 'C:\Users\Kevin\Desktop\workStuff\LDA\data' + "\\"
def createDataFrame(vbfMEList, ttbarMEList, path = data_path):
data_vbfME = np.asarray([0])
data_ttbarME = np.asarray([0]... | gen_plots.py | import matplotlib
matplotlib.use('Agg')
import matplotlib.pyplot as plt
import numpy as np
import os
import sys
import scipy
data_path = 'C:\Users\Kevin\Desktop\workStuff\LDA\data' + "\\"
def createDataFrame(vbfMEList, ttbarMEList, path = data_path):
data_vbfME = np.asarray([0])
data_ttbarME = np.asarray([0]... | 0.273574 | 0.458652 |
import itertools
from collections import Counter
from dataclasses import dataclass
from aocd import get_data
@dataclass
class Polymer:
name: str
total: int = 0
def part2_rule_keyset(original_data: list) -> dict:
rules = {}
spacer = data.index('')
for rule_letters in [original_data[:spacer], ori... | day14.py | import itertools
from collections import Counter
from dataclasses import dataclass
from aocd import get_data
@dataclass
class Polymer:
name: str
total: int = 0
def part2_rule_keyset(original_data: list) -> dict:
rules = {}
spacer = data.index('')
for rule_letters in [original_data[:spacer], ori... | 0.574156 | 0.306307 |
try:
import simplejson as json
except ImportError:
import json
try:
import unittest2 as unittest
except ImportError:
import sys
assert sys.version.startswith('2.7')
import unittest
from sheet.ui_jsonifier import sheet_to_ui_json_grid_data, sheet_to_ui_json_meta_data
from sheet.cell import C... | dirigible/sheet/tests/test_ui_jsonifier.py |
try:
import simplejson as json
except ImportError:
import json
try:
import unittest2 as unittest
except ImportError:
import sys
assert sys.version.startswith('2.7')
import unittest
from sheet.ui_jsonifier import sheet_to_ui_json_grid_data, sheet_to_ui_json_meta_data
from sheet.cell import C... | 0.320077 | 0.589244 |
import pytest
from unittest import mock
from keep_current_storage.domain.document import Document
from keep_current_storage.use_cases import request_objects as ro
from keep_current_storage.use_cases import document_use_cases as uc
from keep_current_storage.shared import response_object as res
def test_document_insert... | tests/use_cases/test_document_insert_use_case.py | import pytest
from unittest import mock
from keep_current_storage.domain.document import Document
from keep_current_storage.use_cases import request_objects as ro
from keep_current_storage.use_cases import document_use_cases as uc
from keep_current_storage.shared import response_object as res
def test_document_insert... | 0.564699 | 0.266202 |
import os
from multiprocessing import cpu_count
import numpy as np
import pandas as pd
from IPython.display import display
from joblib import Parallel, delayed
import src.feature_helpers as fh
from src.geopandas_helpers import get_distance
def check_properties(
df,
distance_percs_to_show=[
0.01,
... | src/workflow_helpers.py |
import os
from multiprocessing import cpu_count
import numpy as np
import pandas as pd
from IPython.display import display
from joblib import Parallel, delayed
import src.feature_helpers as fh
from src.geopandas_helpers import get_distance
def check_properties(
df,
distance_percs_to_show=[
0.01,
... | 0.286668 | 0.484136 |
from __future__ import unicode_literals
import logging
from django.contrib import messages
from django.contrib.admin.templatetags.admin_urls import add_preserved_filters
from django.core.urlresolvers import reverse
from django.http import Http404
from django.shortcuts import redirect
from django.utils.encoding import... | tech_project/lib/python2.7/site-packages/connected_accounts/views.py | from __future__ import unicode_literals
import logging
from django.contrib import messages
from django.contrib.admin.templatetags.admin_urls import add_preserved_filters
from django.core.urlresolvers import reverse
from django.http import Http404
from django.shortcuts import redirect
from django.utils.encoding import... | 0.707405 | 0.046227 |
from shared.defines import *
from shared.environ import *
from shared.loggers import Logger
from shared.database import Database
from shared.document import Document
from shared.storage import S3Uri
from shared.machine import Machine
from shared.bus import Bus
from os.path import splitext
def ingestDocumentF... | source/lambdas/trigger/s3/handler.py |
from shared.defines import *
from shared.environ import *
from shared.loggers import Logger
from shared.database import Database
from shared.document import Document
from shared.storage import S3Uri
from shared.machine import Machine
from shared.bus import Bus
from os.path import splitext
def ingestDocumentF... | 0.511473 | 0.170335 |
import requests
from flask import Blueprint
from ..jwt_wrapper import check_jwt_validity
from ..objects import redis_controller
# Flask related.
blueprint = Blueprint(name="jobs", import_name=__name__)
URL_PREFIX = "/v1/jobs"
# Api functions.
@blueprint.route(f"{URL_PREFIX}/queue", methods=["GET"])
@check_jwt_... | maro/cli/grass/lib/services/master_api_server/blueprints/jobs.py |
import requests
from flask import Blueprint
from ..jwt_wrapper import check_jwt_validity
from ..objects import redis_controller
# Flask related.
blueprint = Blueprint(name="jobs", import_name=__name__)
URL_PREFIX = "/v1/jobs"
# Api functions.
@blueprint.route(f"{URL_PREFIX}/queue", methods=["GET"])
@check_jwt_... | 0.600657 | 0.087291 |
import argparse
import os
import pathlib
import pprint
import sys
import github
import prettytable
from dataclasses import dataclass, asdict
from jinja2 import Environment
from jinja2.loaders import FileSystemLoader
from pathlib import Path
from typing import List, Mapping, NewType
from ackdiscover import awssdkgo, ... | docs/scripts/gen_services.py |
import argparse
import os
import pathlib
import pprint
import sys
import github
import prettytable
from dataclasses import dataclass, asdict
from jinja2 import Environment
from jinja2.loaders import FileSystemLoader
from pathlib import Path
from typing import List, Mapping, NewType
from ackdiscover import awssdkgo, ... | 0.489992 | 0.143668 |
import sys
class Krona2CSVPlugin:
def input(self, filename):
self.myPhylum = dict()
self.myClass = dict()
self.myOrder = dict()
self.myFamily = dict()
self.myGenus = dict()
self.mySpecies = dict()
self.myStrain = dict()
#total = 0.0
self.kronafile = ope... | Krona2CSVPlugin.py | import sys
class Krona2CSVPlugin:
def input(self, filename):
self.myPhylum = dict()
self.myClass = dict()
self.myOrder = dict()
self.myFamily = dict()
self.myGenus = dict()
self.mySpecies = dict()
self.myStrain = dict()
#total = 0.0
self.kronafile = ope... | 0.029633 | 0.201833 |
from typing import Tuple
from alembic import op
import sqlalchemy as sa
# revision identifiers, used by Alembic
revision = '7<PASSWORD>'
down_revision = None
branch_labels = None
depends_on = None
def create_updated_at_trigger() -> None:
op.execute(
"""
CREATE OR REPLACE FUNCTION update_updated_... | backend/app/db/migrations/versions/7410eb7efa12_create_main_tables.py | from typing import Tuple
from alembic import op
import sqlalchemy as sa
# revision identifiers, used by Alembic
revision = '7<PASSWORD>'
down_revision = None
branch_labels = None
depends_on = None
def create_updated_at_trigger() -> None:
op.execute(
"""
CREATE OR REPLACE FUNCTION update_updated_... | 0.561455 | 0.226944 |
from django.test import TestCase
from django.contrib.auth import get_user_model
from django.urls import reverse
from rest_framework import status
from rest_framework.test import APIClient
from core.models import Recipe, Ingredient, Tag
from recipe.serializers import RecipeSerializer, RecipeDetailSerializer
RECIPES_... | app/recipe/tests/test_recipe_api.py | from django.test import TestCase
from django.contrib.auth import get_user_model
from django.urls import reverse
from rest_framework import status
from rest_framework.test import APIClient
from core.models import Recipe, Ingredient, Tag
from recipe.serializers import RecipeSerializer, RecipeDetailSerializer
RECIPES_... | 0.697815 | 0.347454 |
from ..common_descs import *
from .objs.tag import *
from supyr_struct.defs.tag_def import TagDef
jpt__category = (
"none",
"falling",
"bullet",
"grenade",
"high_explosive",
"sniper",
"melee",
"flame",
"mounted_weapon",
"vehicle",
"plasma",
"needle",
... | h3/defs/jpt_.py |
from ..common_descs import *
from .objs.tag import *
from supyr_struct.defs.tag_def import TagDef
jpt__category = (
"none",
"falling",
"bullet",
"grenade",
"high_explosive",
"sniper",
"melee",
"flame",
"mounted_weapon",
"vehicle",
"plasma",
"needle",
... | 0.387806 | 0.161419 |
import os.path
import random
import cv2
import numpy as np
from ..builder import PIPELINES
def load_pascal_occluders(occluders_file):
"""load pascal occluders from the occluder file."""
if os.path.isfile(occluders_file):
return np.load(occluders_file, allow_pickle=True)
else:
raise NotI... | mmhuman3d/data/datasets/pipelines/synthetic_occlusion_augmentation.py | import os.path
import random
import cv2
import numpy as np
from ..builder import PIPELINES
def load_pascal_occluders(occluders_file):
"""load pascal occluders from the occluder file."""
if os.path.isfile(occluders_file):
return np.load(occluders_file, allow_pickle=True)
else:
raise NotI... | 0.856842 | 0.449876 |
from PySide2.QtCore import QObject, Signal
from hexrd.ui.hexrd_config import HexrdConfig
from hexrd.ui.ui_loader import UiLoader
class ImageModeWidget(QObject):
# The string indicates which tab was selected
tab_changed = Signal(str)
# Tell the image canvas to show the snip1d
polar_show_snip1d = Sig... | hexrd/ui/image_mode_widget.py | from PySide2.QtCore import QObject, Signal
from hexrd.ui.hexrd_config import HexrdConfig
from hexrd.ui.ui_loader import UiLoader
class ImageModeWidget(QObject):
# The string indicates which tab was selected
tab_changed = Signal(str)
# Tell the image canvas to show the snip1d
polar_show_snip1d = Sig... | 0.6508 | 0.232975 |
import sys
import platform
from PySide2 import QtCore, QtGui, QtWidgets
from PySide2.QtCore import (
QCoreApplication, QPropertyAnimation, QDate, QDateTime, QMetaObject,
QObject, QPoint, QRect, QSize, QTime, QUrl, Qt, QEvent
)
from PySide2.QtGui import (
QBrush, QColor, QConicalGradient, QCursor, QFont, QF... | main.py | import sys
import platform
from PySide2 import QtCore, QtGui, QtWidgets
from PySide2.QtCore import (
QCoreApplication, QPropertyAnimation, QDate, QDateTime, QMetaObject,
QObject, QPoint, QRect, QSize, QTime, QUrl, Qt, QEvent
)
from PySide2.QtGui import (
QBrush, QColor, QConicalGradient, QCursor, QFont, QF... | 0.278355 | 0.084304 |
from selenium import webdriver
import xlsxwriter
import json
import http.client
def checkUrl(url):
conn = http.client.HTTPConnection("www.izbori.ba")
conn.request("GET", url)
r1 = conn.getresponse()
return r1.status < 400
chrome_path = r"chromedriver_win32\chromedriver.exe"
driver = webdriver.Chrome(ch... | votes-2008.py | from selenium import webdriver
import xlsxwriter
import json
import http.client
def checkUrl(url):
conn = http.client.HTTPConnection("www.izbori.ba")
conn.request("GET", url)
r1 = conn.getresponse()
return r1.status < 400
chrome_path = r"chromedriver_win32\chromedriver.exe"
driver = webdriver.Chrome(ch... | 0.103075 | 0.085061 |
__copyright__ = \
"""
Copyright (C) 2012-2017 Oracle Corporation
This file is part of VirtualBox Open Source Edition (OSE), as
available from http://www.virtualbox.org. This file is free software;
you can redistribute it and/or modify it under the terms of the GNU
General Public License (GPL) as published by the Free ... | vbox/src/VBox/ValidationKit/testmanager/webui/wuiadmintestbox.py | __copyright__ = \
"""
Copyright (C) 2012-2017 Oracle Corporation
This file is part of VirtualBox Open Source Edition (OSE), as
available from http://www.virtualbox.org. This file is free software;
you can redistribute it and/or modify it under the terms of the GNU
General Public License (GPL) as published by the Free ... | 0.382141 | 0.139045 |
import sys
import yaml
from tqdm import tqdm
import numpy as np
import torch
from sync_batchnorm import DataParallelWithCallback
from modules.generator import OcclusionAwareGenerator
from modules.keypoint_detector import KPDetector
from animate import normalize_kp
if sys.version_info[0] < 3:
raise Exception("Yo... | use_model.py | import sys
import yaml
from tqdm import tqdm
import numpy as np
import torch
from sync_batchnorm import DataParallelWithCallback
from modules.generator import OcclusionAwareGenerator
from modules.keypoint_detector import KPDetector
from animate import normalize_kp
if sys.version_info[0] < 3:
raise Exception("Yo... | 0.422266 | 0.187672 |
import sys
import struct
if len(sys.argv) < 3:
print "usage {0} inFile.bd out [-v]".format(sys.argv[0])
exit(-1)
csm_file = open(sys.argv[1])
code_file = open(sys.argv[2], "wb")
def pack(a):
return struct.pack("I", a)
def both_reg(op1, op2):
return op1 in ["r0","r1","r2","r3"] and op2 in ["r0","r1",... | assembler.py | import sys
import struct
if len(sys.argv) < 3:
print "usage {0} inFile.bd out [-v]".format(sys.argv[0])
exit(-1)
csm_file = open(sys.argv[1])
code_file = open(sys.argv[2], "wb")
def pack(a):
return struct.pack("I", a)
def both_reg(op1, op2):
return op1 in ["r0","r1","r2","r3"] and op2 in ["r0","r1",... | 0.052674 | 0.437884 |
import os
import numpy as np
import matplotlib.pyplot as plt
import matplotlib.animation as animation
from PIL import Image
from . import events
from . import utils
from . import widgets
from .slider_manager import SliderManager, MiniManager, Val
class GUI(object):
"""
main GUI object that... | rain_table/rain_table.py | import os
import numpy as np
import matplotlib.pyplot as plt
import matplotlib.animation as animation
from PIL import Image
from . import events
from . import utils
from . import widgets
from .slider_manager import SliderManager, MiniManager, Val
class GUI(object):
"""
main GUI object that... | 0.306942 | 0.118845 |
import asyncio
import inspect
import argparse
from functools import wraps
from typing import Dict, Optional
from .protocol import BaseProtocol
from . import message, const
class ClientHandler(BaseProtocol):
def __init__(self, server):
self.name = ''
self.identified = False
self.server = ... | asyncirc/server.py | import asyncio
import inspect
import argparse
from functools import wraps
from typing import Dict, Optional
from .protocol import BaseProtocol
from . import message, const
class ClientHandler(BaseProtocol):
def __init__(self, server):
self.name = ''
self.identified = False
self.server = ... | 0.700997 | 0.057361 |
STATUS_QUERY = """
SELECT
p.address,
p.city,
p.price,
p.description,
s.name,
p.year
FROM status_history sh
LEFT JOIN status s ON s.id = sh.status_id
LEFT JOIN property p ON p.id = sh.property_id
WHERE s.name='{}'
AND (p.address IS NOT NULL OR p.address <> "")
AND (p.year IS NOT NULL OR p.year <>... | database/queries.py | STATUS_QUERY = """
SELECT
p.address,
p.city,
p.price,
p.description,
s.name,
p.year
FROM status_history sh
LEFT JOIN status s ON s.id = sh.status_id
LEFT JOIN property p ON p.id = sh.property_id
WHERE s.name='{}'
AND (p.address IS NOT NULL OR p.address <> "")
AND (p.year IS NOT NULL OR p.year <>... | 0.266357 | 0.085442 |
from typing import List, Tuple, TYPE_CHECKING, Optional
from .util import get_message_mentions
from twitchbot.channel import Channel, channels
from .irc import Irc
from .regex import RE_PRIVMSG, RE_WHISPER, RE_JOINED_CHANNEL, RE_USERNOTICE
from .enums import MessageType
from .util import split_message
from .tags import... | twitchbot/message.py | from typing import List, Tuple, TYPE_CHECKING, Optional
from .util import get_message_mentions
from twitchbot.channel import Channel, channels
from .irc import Irc
from .regex import RE_PRIVMSG, RE_WHISPER, RE_JOINED_CHANNEL, RE_USERNOTICE
from .enums import MessageType
from .util import split_message
from .tags import... | 0.754056 | 0.187188 |
"""Classes that roughly correspond to Clang AST node types."""
import collections
import dataclasses
import re
from typing import Dict, Optional, Sequence, Tuple, Union
# We are relying on Clang to do the actual source parsing and are only doing
# a little bit of extra parsing of function parameter type declarations ... | introspect/ast_nodes.py | """Classes that roughly correspond to Clang AST node types."""
import collections
import dataclasses
import re
from typing import Dict, Optional, Sequence, Tuple, Union
# We are relying on Clang to do the actual source parsing and are only doing
# a little bit of extra parsing of function parameter type declarations ... | 0.908709 | 0.408631 |
import os
import shutil
import tempfile
import time
import unittest
from Queue import Queue
from threading import Event, Thread
import genbankfs
from genbankfs import GenbankCache
def get_download_mock(download_trigger):
class DownloadMock(object):
def __init__(self, *args, **kwargs):
self.temp_files =... | genbankfs/tests/test_cache.py |
import os
import shutil
import tempfile
import time
import unittest
from Queue import Queue
from threading import Event, Thread
import genbankfs
from genbankfs import GenbankCache
def get_download_mock(download_trigger):
class DownloadMock(object):
def __init__(self, *args, **kwargs):
self.temp_files =... | 0.458106 | 0.195134 |
# curl -o filename-u username:password https://salesforce.easydita.com/rest/all-files/$bundle_id/bundle
fake_webhook_body_doc_A = {
"event_id": "dita-ot-publish-complete",
"event_data": {
"publish-result": "success",
"output-uuid": "9e1e2bc0-8276-11e9-b28c-42010af00002",
"description": ... | sfdoc/publish/tests/fake_easydita.py |
# curl -o filename-u username:password https://salesforce.easydita.com/rest/all-files/$bundle_id/bundle
fake_webhook_body_doc_A = {
"event_id": "dita-ot-publish-complete",
"event_data": {
"publish-result": "success",
"output-uuid": "9e1e2bc0-8276-11e9-b28c-42010af00002",
"description": ... | 0.533884 | 0.334263 |
import time
class Timer():
def __init__(self):
self.start = int(round(time.time() * 1000))
self.passed = 0
self.duration = 0
self.action = None
self.done = False
def cancel(self):
self.done = True
def update(self):
if not self.done:
cur... | PyShooter/timer.py | import time
class Timer():
def __init__(self):
self.start = int(round(time.time() * 1000))
self.passed = 0
self.duration = 0
self.action = None
self.done = False
def cancel(self):
self.done = True
def update(self):
if not self.done:
cur... | 0.205456 | 0.129155 |
from tensorflow.python.keras.models import Sequential
from tensorflow.python.keras.models import Model
from tensorflow.python.keras import backend as K
from tensorflow.python.keras.layers import Conv2D, MaxPooling2D, UpSampling2D, Layer
from tensorflow.python.keras.layers import Activation, Dropout, Flatten, Dense, Inp... | generate2.py | from tensorflow.python.keras.models import Sequential
from tensorflow.python.keras.models import Model
from tensorflow.python.keras import backend as K
from tensorflow.python.keras.layers import Conv2D, MaxPooling2D, UpSampling2D, Layer
from tensorflow.python.keras.layers import Activation, Dropout, Flatten, Dense, Inp... | 0.828523 | 0.381076 |
import requests
import pandas as pd
from io import StringIO
import logging
from ynab_sdk import YNAB
from ynab_sdk.api.models.requests.transaction import TransactionRequest
class BrimImporter:
def __init__(self, secrets):
self.brim_username = secrets.getSecret('brim.username').strip()
self.brim_pa... | importers/brim.py | import requests
import pandas as pd
from io import StringIO
import logging
from ynab_sdk import YNAB
from ynab_sdk.api.models.requests.transaction import TransactionRequest
class BrimImporter:
def __init__(self, secrets):
self.brim_username = secrets.getSecret('brim.username').strip()
self.brim_pa... | 0.317744 | 0.143278 |
from django.contrib import admin
from django import forms
from . import models
# Register your models here.
from .models import VegetationStructure, Survey
class SourceAdmin(admin.ModelAdmin):
list_display = ('name',)
ordering = ('name',)
search_fields = ('name',)
class SiteAdmin(admin.ModelAdmin):
... | WildlifeObservations/observations/admin.py | from django.contrib import admin
from django import forms
from . import models
# Register your models here.
from .models import VegetationStructure, Survey
class SourceAdmin(admin.ModelAdmin):
list_display = ('name',)
ordering = ('name',)
search_fields = ('name',)
class SiteAdmin(admin.ModelAdmin):
... | 0.551332 | 0.165965 |
import sys
import typing as t
import contextlib
import sqlalchemy.exc
import click
from flask_postgres._compat import psycopg
from flask_postgres._compat import errors
from flask_postgres.utils import echo
from flask_postgres.utils import echo_error_as_warning
from flask_postgres.exceptions import CommandLineModeNotA... | flask_postgres/ops.py | import sys
import typing as t
import contextlib
import sqlalchemy.exc
import click
from flask_postgres._compat import psycopg
from flask_postgres._compat import errors
from flask_postgres.utils import echo
from flask_postgres.utils import echo_error_as_warning
from flask_postgres.exceptions import CommandLineModeNotA... | 0.148911 | 0.058292 |
from django.contrib import messages
from django.contrib.admin.utils import unquote
from django.contrib.auth import logout, login, authenticate, get_user_model
from django.contrib.auth.decorators import login_required
from django.contrib.auth.models import Group
from django.http import Http404
from django.http import Ht... | src/authentication/views.py | from django.contrib import messages
from django.contrib.admin.utils import unquote
from django.contrib.auth import logout, login, authenticate, get_user_model
from django.contrib.auth.decorators import login_required
from django.contrib.auth.models import Group
from django.http import Http404
from django.http import Ht... | 0.44553 | 0.055695 |
import numpy as np
import wfdb
from scipy.signal import resample
from decision import *
import os,sys
os.environ["CUDA_VISIBLE_DEVICES"] = "-1"
try:
from keras.models import model_from_json
except:
from tensorflow.keras.models import model_from_json
'''
Written by: <NAME>
School of Medical Instrume... | score.py | import numpy as np
import wfdb
from scipy.signal import resample
from decision import *
import os,sys
os.environ["CUDA_VISIBLE_DEVICES"] = "-1"
try:
from keras.models import model_from_json
except:
from tensorflow.keras.models import model_from_json
'''
Written by: <NAME>
School of Medical Instrume... | 0.209793 | 0.161684 |
from abc import ABCMeta, abstractmethod
from bisect import bisect_right
from random import uniform
import numpy as np
from numpy.random import choice
from pandas import Series
from generative_models.data_synthesiser_utils.utils import normalize_given_distribution
class AbstractAttribute(object):
__metaclass__ =... | generative_models/data_synthesiser_utils/datatypes/AbstractAttribute.py | from abc import ABCMeta, abstractmethod
from bisect import bisect_right
from random import uniform
import numpy as np
from numpy.random import choice
from pandas import Series
from generative_models.data_synthesiser_utils.utils import normalize_given_distribution
class AbstractAttribute(object):
__metaclass__ =... | 0.885977 | 0.424233 |
from DockerENT import utils
import logging
_log = logging.getLogger(__name__)
_plugin_name_ = 'plaintext-passwords'
def scan(container, output_queue, audit=False, audit_queue=None):
"""Docker plaintext password scan plugin.
:param container: container instance.
:type container: docker.models.containers... | DockerENT/docker_plugins/docker_plaintext_password_info.py | from DockerENT import utils
import logging
_log = logging.getLogger(__name__)
_plugin_name_ = 'plaintext-passwords'
def scan(container, output_queue, audit=False, audit_queue=None):
"""Docker plaintext password scan plugin.
:param container: container instance.
:type container: docker.models.containers... | 0.52902 | 0.148973 |
import datetime
from django.db import models
class SellOrder(models.Model):
"""销售订单"""
SELL_ORDER_CHOICES = (
(0, '普通发票'),
(1, '退换货')
)
SO_STATUS_CHOICES = (
(0, '草稿'),
(1, '已审批')
)
id = models.AutoField(primary_key=True)
so_identify = models.CharField(max_l... | sell/models.py | import datetime
from django.db import models
class SellOrder(models.Model):
"""销售订单"""
SELL_ORDER_CHOICES = (
(0, '普通发票'),
(1, '退换货')
)
SO_STATUS_CHOICES = (
(0, '草稿'),
(1, '已审批')
)
id = models.AutoField(primary_key=True)
so_identify = models.CharField(max_l... | 0.294824 | 0.088899 |
import os
import glob
import pandas as pd
import numpy as np
import PIL
from PIL import Image, ImageColor, ImageOps
import cv2
import fontTools.ttLib
import skimage.filters
import randomcolor
from colormath.color_objects import sRGBColor, LabColor
from colormath.color_conversions import convert_color as colormath_c... | omniprint/utils.py | import os
import glob
import pandas as pd
import numpy as np
import PIL
from PIL import Image, ImageColor, ImageOps
import cv2
import fontTools.ttLib
import skimage.filters
import randomcolor
from colormath.color_objects import sRGBColor, LabColor
from colormath.color_conversions import convert_color as colormath_c... | 0.564819 | 0.238395 |
import copy
import datetime
import logging
import math
import time
import pandas as pd
from celery import shared_task
from celery.schedules import crontab
from datamanage import celery_app
from datamanage.pro.datastocktake.views import SCORE_DICT
from datamanage.pro.lifecycle.utils import generate_influxdb_time_range,... | src/api/datamanage/pro/lifecycle/tasks.py | import copy
import datetime
import logging
import math
import time
import pandas as pd
from celery import shared_task
from celery.schedules import crontab
from datamanage import celery_app
from datamanage.pro.datastocktake.views import SCORE_DICT
from datamanage.pro.lifecycle.utils import generate_influxdb_time_range,... | 0.260672 | 0.213849 |
# Licensed under the GPL: https://www.gnu.org/licenses/old-licenses/gpl-2.0.html
# For details: https://github.com/PyCQA/pylint/blob/master/COPYING
"""Unittest for the logging checker."""
import astroid
from pylint.checkers import logging
from pylint.testutils import CheckerTestCase, Message, set_config
class Test... | env/lib/python3.5/site-packages/pylint/test/unittest_checker_logging.py |
# Licensed under the GPL: https://www.gnu.org/licenses/old-licenses/gpl-2.0.html
# For details: https://github.com/PyCQA/pylint/blob/master/COPYING
"""Unittest for the logging checker."""
import astroid
from pylint.checkers import logging
from pylint.testutils import CheckerTestCase, Message, set_config
class Test... | 0.864754 | 0.388096 |
from pycocotools import mask as maskUtils
import numpy as np
def annsToSeg(anns, coco_instance):
'''
converts COCO-format annotations of a given image to a PASCAL-VOC segmentation style label
!!!No guarantees where segmentations overlap - might lead to loss of objects!!!
:param anns: COCO annotations as returned... | deeplab/datasets/coco2voc/coco2voc_aux.py | from pycocotools import mask as maskUtils
import numpy as np
def annsToSeg(anns, coco_instance):
'''
converts COCO-format annotations of a given image to a PASCAL-VOC segmentation style label
!!!No guarantees where segmentations overlap - might lead to loss of objects!!!
:param anns: COCO annotations as returned... | 0.588771 | 0.571229 |
import argparse
import json
import logging
import os
import time
import sys
from functools import reduce
from pathlib import Path
from typing import Tuple
from urllib import parse
import requests
from requests.adapters import HTTPAdapter, TimeoutSauce
from tqdm import tqdm
from urllib3.util import Retry
BASE_URL = os... | api_downloader.py | import argparse
import json
import logging
import os
import time
import sys
from functools import reduce
from pathlib import Path
from typing import Tuple
from urllib import parse
import requests
from requests.adapters import HTTPAdapter, TimeoutSauce
from tqdm import tqdm
from urllib3.util import Retry
BASE_URL = os... | 0.45302 | 0.089415 |
import torch
import numpy as np
import torch.nn as nn
class PoswiseFeedForwardNet(nn.Module):
def __init__(self, source_dims, hidden_cnt):
super(PoswiseFeedForwardNet, self).__init__()
self.conv1 = nn.Conv1d(in_channels=source_dims, out_channels=hidden_cnt, kernel_size=1)
self.conv2 = nn.C... | attachments/ros_ws/local_planner_py/scripts/crowd_nav/common/naive_transformer.py | import torch
import numpy as np
import torch.nn as nn
class PoswiseFeedForwardNet(nn.Module):
def __init__(self, source_dims, hidden_cnt):
super(PoswiseFeedForwardNet, self).__init__()
self.conv1 = nn.Conv1d(in_channels=source_dims, out_channels=hidden_cnt, kernel_size=1)
self.conv2 = nn.C... | 0.891927 | 0.505981 |
from functools import total_ordering
import pymysql, argparse, getpass, sys, csv
_stupidPhasing = {
'One': 1,
'Two': 2,
'Three': 3,
'Four': 4,
'Five': 5
}
@total_ordering
class BiomarkerDetail(object):
def __init__(self, name, organ, protocolID, phase, pi):
self.name, self.organ, se... | src/edrn/bmdb/correlation.py |
from functools import total_ordering
import pymysql, argparse, getpass, sys, csv
_stupidPhasing = {
'One': 1,
'Two': 2,
'Three': 3,
'Four': 4,
'Five': 5
}
@total_ordering
class BiomarkerDetail(object):
def __init__(self, name, organ, protocolID, phase, pi):
self.name, self.organ, se... | 0.282691 | 0.201283 |
import json
import subprocess
import time
import pytest
from tornado import httpclient
from .conftest import CI, DARWIN, LINUX, PYPY
if CI and DARWIN: # pragma: no cover
pytest.skip("skipping flaky MacOS tests", allow_module_level=True)
if CI and LINUX and PYPY: # pragma: no cover
pytest.skip("skipping f... | py/jupyterlite/src/jupyterlite/tests/test_serve.py |
import json
import subprocess
import time
import pytest
from tornado import httpclient
from .conftest import CI, DARWIN, LINUX, PYPY
if CI and DARWIN: # pragma: no cover
pytest.skip("skipping flaky MacOS tests", allow_module_level=True)
if CI and LINUX and PYPY: # pragma: no cover
pytest.skip("skipping f... | 0.218003 | 0.216074 |
from __future__ import absolute_import
from __future__ import unicode_literals
import logging
from datetime import datetime
from celery.task import periodic_task
from celery.schedules import crontab
from corehq.util.datadog.gauges import datadog_counter
from corehq.blobs.models import BlobExpiration, BlobMeta
from c... | corehq/blobs/tasks.py | from __future__ import absolute_import
from __future__ import unicode_literals
import logging
from datetime import datetime
from celery.task import periodic_task
from celery.schedules import crontab
from corehq.util.datadog.gauges import datadog_counter
from corehq.blobs.models import BlobExpiration, BlobMeta
from c... | 0.493409 | 0.065157 |
from datetime import datetime
import json
import six
import pytest
from urlobject import URLObject
from nylas.client.restful_models import Message
from nylas.utils import timestamp_from_dt
import pytz
@pytest.mark.usefixtures("mock_messages")
def test_messages(api_client):
message = api_client.messages.first()
... | tests/test_messages.py | from datetime import datetime
import json
import six
import pytest
from urlobject import URLObject
from nylas.client.restful_models import Message
from nylas.utils import timestamp_from_dt
import pytz
@pytest.mark.usefixtures("mock_messages")
def test_messages(api_client):
message = api_client.messages.first()
... | 0.661267 | 0.444625 |
import librosa
import os
import soundfile as sf
audio_path = '../../200_download/separated_data/audio'
normalize_audio_path = '../../200_download/norm_data/audio'
mix_path = '../../200_download/mixture_data/audio'
nparray_path = '../../200_download/separated_data/nparray'
SR = 16000
audio_num = 200
def audio_merge(np... | src/audio_merge.py | import librosa
import os
import soundfile as sf
audio_path = '../../200_download/separated_data/audio'
normalize_audio_path = '../../200_download/norm_data/audio'
mix_path = '../../200_download/mixture_data/audio'
nparray_path = '../../200_download/separated_data/nparray'
SR = 16000
audio_num = 200
def audio_merge(np... | 0.156362 | 0.136637 |
import warnings
import pulumi
import pulumi.runtime
from typing import Any, Mapping, Optional, Sequence, Union
from ... import _utilities, _tables
__all__ = [
'ApiKeyResponseResult',
]
@pulumi.output_type
class ApiKeyResponseResult(dict):
"""
An API key used for authenticating with a configuration store ... | sdk/python/pulumi_azure_native/appconfiguration/v20190201preview/outputs.py |
import warnings
import pulumi
import pulumi.runtime
from typing import Any, Mapping, Optional, Sequence, Union
from ... import _utilities, _tables
__all__ = [
'ApiKeyResponseResult',
]
@pulumi.output_type
class ApiKeyResponseResult(dict):
"""
An API key used for authenticating with a configuration store ... | 0.863204 | 0.071656 |
import rospy
import struct
import baxter_interface
from geometry_msgs.msg import (
PoseStamped,
Pose,
Point,
Quaternion,
)
from std_msgs.msg import Header
from baxter_core_msgs.srv import (
SolvePositionIK,
SolvePositionIKRequest,
)
def connect_service(side):
ns = "ExternalTools/"+side+"/Po... | scripts/ik_command.py | import rospy
import struct
import baxter_interface
from geometry_msgs.msg import (
PoseStamped,
Pose,
Point,
Quaternion,
)
from std_msgs.msg import Header
from baxter_core_msgs.srv import (
SolvePositionIK,
SolvePositionIKRequest,
)
def connect_service(side):
ns = "ExternalTools/"+side+"/Po... | 0.327561 | 0.16175 |
import unittest
from Products.PluginIndexes.TopicIndex.TopicIndex import TopicIndex
class Obj(object):
def __init__(self, id, meta_type=''):
self.id = id
self.meta_type = meta_type
def getId(self):
return self.id
def getPhysicalPath(self):
return self.id
class TestBas... | src/Products/PluginIndexes/TopicIndex/tests.py | import unittest
from Products.PluginIndexes.TopicIndex.TopicIndex import TopicIndex
class Obj(object):
def __init__(self, id, meta_type=''):
self.id = id
self.meta_type = meta_type
def getId(self):
return self.id
def getPhysicalPath(self):
return self.id
class TestBas... | 0.58818 | 0.591959 |
from enum import Enum
class RegionMode(Enum):
CUBE = 1
SPHERE = 2
# Filter cube or spherical regions? -> Spheres will (possible) require less domains
_REGION_MODE = RegionMode.CUBE
#_REGION_MODE = RegionMode.SPHERE
def main(path, ioutput, txt_fname, out_fname=None, REGION_MODE=_REGION_MODE):
'''
Reads... | scripts/compute_required_domains.py | from enum import Enum
class RegionMode(Enum):
CUBE = 1
SPHERE = 2
# Filter cube or spherical regions? -> Spheres will (possible) require less domains
_REGION_MODE = RegionMode.CUBE
#_REGION_MODE = RegionMode.SPHERE
def main(path, ioutput, txt_fname, out_fname=None, REGION_MODE=_REGION_MODE):
'''
Reads... | 0.58059 | 0.217213 |
import re
from zomboid.java import ArrayList, HashMap
from .base import BaseScriptObject
class Result:
type : str = None
count : int = 1
drainableCount : int = 0
module : str = None
def getType(self) -> str:
return self.type
def getCount(self) -> int:
return self.count
... | zomboid/scripting/objects/recipe.py | import re
from zomboid.java import ArrayList, HashMap
from .base import BaseScriptObject
class Result:
type : str = None
count : int = 1
drainableCount : int = 0
module : str = None
def getType(self) -> str:
return self.type
def getCount(self) -> int:
return self.count
... | 0.375363 | 0.359224 |
import logging
from .defaults import ZiaApiBase
class CertificateSigningRequest(ZiaApiBase):
def download(self, csr):
"""
Downloads a Certificate Signing Request (CSR)
"""
path = "sslSettings/downloadcsr"
return self._session.get(path, csr)
def generate(self, csr):
... | zia/ssl_inspection_settings.py | import logging
from .defaults import ZiaApiBase
class CertificateSigningRequest(ZiaApiBase):
def download(self, csr):
"""
Downloads a Certificate Signing Request (CSR)
"""
path = "sslSettings/downloadcsr"
return self._session.get(path, csr)
def generate(self, csr):
... | 0.695338 | 0.131814 |
import numpy as np
def load_sample_data_pca():
np.random.seed(3)
eps=0.5
n=30
x=np.random.uniform(-1,1,n)
y=x+eps*np.random.uniform(-1,1,n)
x=x-np.mean(x)
y=y-np.mean(y)
data=np.vstack((x,y)).transpose()
return data
def load_multidimensional_data_pca(n_data, n_vec, dim,... | utils/routines.py | import numpy as np
def load_sample_data_pca():
np.random.seed(3)
eps=0.5
n=30
x=np.random.uniform(-1,1,n)
y=x+eps*np.random.uniform(-1,1,n)
x=x-np.mean(x)
y=y-np.mean(y)
data=np.vstack((x,y)).transpose()
return data
def load_multidimensional_data_pca(n_data, n_vec, dim,... | 0.370225 | 0.458531 |
import os
import json
import argparse
def get_machines():
with open("../_config.ini") as f:
for line in f:
if line.startswith("servers"):
line = line.replace("\n", "")
return line.split(" ")[1:]
return []
MACHINES = get_machines()
print(MACHINES)
parser = a... | ss/update_ss.py | import os
import json
import argparse
def get_machines():
with open("../_config.ini") as f:
for line in f:
if line.startswith("servers"):
line = line.replace("\n", "")
return line.split(" ")[1:]
return []
MACHINES = get_machines()
print(MACHINES)
parser = a... | 0.233357 | 0.081776 |
import socket
from .. import cipher
# Parent class for Client and Server
class Connection(object):
def __init__(self, ip="", port=0):
# Construct the object
self.ip = ip
self.port = port
self.sock = socket.socket()
self.sock.setsockopt(socket.SOL_SOCKET, socket.SO_REUSEADDR... | packages/networking/Connection.py | import socket
from .. import cipher
# Parent class for Client and Server
class Connection(object):
def __init__(self, ip="", port=0):
# Construct the object
self.ip = ip
self.port = port
self.sock = socket.socket()
self.sock.setsockopt(socket.SOL_SOCKET, socket.SO_REUSEADDR... | 0.468304 | 0.138724 |