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 dataclasses import dataclass, field as _field
from ...config import custom_scalars, datetime
from gql_client.runtime.variables import encode_variables
from gql import gql, Client
from gql.transport.exceptions import TransportQueryError
from functools import partial
from numbers import Number
from typing import An... | cli/psym/graphql/query/links.py |
from dataclasses import dataclass, field as _field
from ...config import custom_scalars, datetime
from gql_client.runtime.variables import encode_variables
from gql import gql, Client
from gql.transport.exceptions import TransportQueryError
from functools import partial
from numbers import Number
from typing import An... | 0.831622 | 0.184547 |
import numpy as np
import torch.nn as nn
from .model_transformer import PositionWiseFeedForward, ScaledDotProductAttention
class CrossMultiHeadAttention(nn.Module):
'''
Multi-Head Attention module
'''
def __init__(self, n_head, d_model_q, d_model_kv, d_k, d_v, dropout=0.1):
super().__init__(... | maskrcnn_benchmark/modeling/roi_heads/relation_head/model_cross_transformer.py | import numpy as np
import torch.nn as nn
from .model_transformer import PositionWiseFeedForward, ScaledDotProductAttention
class CrossMultiHeadAttention(nn.Module):
'''
Multi-Head Attention module
'''
def __init__(self, n_head, d_model_q, d_model_kv, d_k, d_v, dropout=0.1):
super().__init__(... | 0.92253 | 0.273941 |
import json
from lumber.handler import Handler
from django.shortcuts import get_object_or_404, render
from django.http.response import Http404, HttpResponse
from django.views.generic.base import View
from django.contrib.auth.mixins import LoginRequiredMixin
from django.db.models import Q
from rest_framework import au... | lumber/views.py | import json
from lumber.handler import Handler
from django.shortcuts import get_object_or_404, render
from django.http.response import Http404, HttpResponse
from django.views.generic.base import View
from django.contrib.auth.mixins import LoginRequiredMixin
from django.db.models import Q
from rest_framework import au... | 0.44071 | 0.08548 |
import dd_app.dd_calc as dd
class Merger(object):
AGING = 1.0
TRASH = 1.0
UPGRADES = {}
QUALITY = 100
def __init__(self, jargs, fulldupe=False):
self.args = jargs
self.fulldupe = fulldupe
# setup tokens
for t in self._extract_types(self.args['db_map'], self.args['pr... | dd_app/dd_merger.py | import dd_app.dd_calc as dd
class Merger(object):
AGING = 1.0
TRASH = 1.0
UPGRADES = {}
QUALITY = 100
def __init__(self, jargs, fulldupe=False):
self.args = jargs
self.fulldupe = fulldupe
# setup tokens
for t in self._extract_types(self.args['db_map'], self.args['pr... | 0.559049 | 0.161519 |
import sys
import unittest
import libsbml
class TestCopyAndClone(unittest.TestCase):
def test_CompartmentType_assignmentOperator(self):
o1 = libsbml.CompartmentType(2,4)
o1.setId("c")
self.assert_( o1.getId() == "c" )
o2 = libsbml.CompartmentType(2,4)
o2 = o1
self.assert_( o2.getId() == "... | external/sbml/bindings/python/test/sbml/TestCopyAndClone.py | import sys
import unittest
import libsbml
class TestCopyAndClone(unittest.TestCase):
def test_CompartmentType_assignmentOperator(self):
o1 = libsbml.CompartmentType(2,4)
o1.setId("c")
self.assert_( o1.getId() == "c" )
o2 = libsbml.CompartmentType(2,4)
o2 = o1
self.assert_( o2.getId() == "... | 0.213377 | 0.41182 |
import hashlib
import synapse.exc as s_exc
import synapse.common as s_common
import synapse.tests.utils as s_t_utils
BITS = 2048
HEXSTR_MODULUS = '<KEY>' \
'b500a06247ec2f3294891a8e62c317ee648f933ec1bf760a9d7e9a5ea4706b2a2c3f6376079114ddcc7a15d3fecf001458f' \
'22f0551802a25ef95cf46... | synapse/tests/test_model_crypto.py | import hashlib
import synapse.exc as s_exc
import synapse.common as s_common
import synapse.tests.utils as s_t_utils
BITS = 2048
HEXSTR_MODULUS = '<KEY>' \
'b500a06247ec2f3294891a8e62c317ee648f933ec1bf760a9d7e9a5ea4706b2a2c3f6376079114ddcc7a15d3fecf001458f' \
'22f0551802a25ef95cf46... | 0.381911 | 0.180648 |
from __future__ import unicode_literals
import urllib
import logging
from google.appengine.ext import ndb
from typing import Optional, List
from mcfw.rpc import returns, arguments
from rogerthat.bizz.communities.models import CommunityMapSettings
from rogerthat.bizz.maps.poi.models import PointOfInterest
from rogert... | src/rogerthat/bizz/maps/poi/map.py | from __future__ import unicode_literals
import urllib
import logging
from google.appengine.ext import ndb
from typing import Optional, List
from mcfw.rpc import returns, arguments
from rogerthat.bizz.communities.models import CommunityMapSettings
from rogerthat.bizz.maps.poi.models import PointOfInterest
from rogert... | 0.645232 | 0.06354 |
import urllib
import flask.scaffold
flask.helpers._endpoint_from_view_func = flask.scaffold._endpoint_from_view_func
import flask_restful
from flask import Blueprint, jsonify, url_for
from flask_restful import reqparse
from app import app
from app.resources.ConfigEndpoint import ConfigEndpoint
from app.resources.Rela... | backend/app/views.py | import urllib
import flask.scaffold
flask.helpers._endpoint_from_view_func = flask.scaffold._endpoint_from_view_func
import flask_restful
from flask import Blueprint, jsonify, url_for
from flask_restful import reqparse
from app import app
from app.resources.ConfigEndpoint import ConfigEndpoint
from app.resources.Rela... | 0.310694 | 0.031739 |
import rosegraphics as rg
def main():
""" Calls the other functions to test them. """
run_test_draw_upside_down_wall()
def run_test_draw_upside_down_wall():
""" Tests the draw_upside_down_wall function. """
# Tests 1 and 2 are ALREADY DONE (here).
window = rg.RoseWindow(550, 300, 'Upside-... | src/m2_more_nested_loops_in_graphics.py |
import rosegraphics as rg
def main():
""" Calls the other functions to test them. """
run_test_draw_upside_down_wall()
def run_test_draw_upside_down_wall():
""" Tests the draw_upside_down_wall function. """
# Tests 1 and 2 are ALREADY DONE (here).
window = rg.RoseWindow(550, 300, 'Upside-... | 0.717408 | 0.641956 |
import torch
from torch import nn
import torch.nn.functional as F
from torch.utils.data import DataLoader
from torch.optim.optimizer import Optimizer
import matplotlib.pyplot as plt
from uncertify.common import DATA_DIR_PATH
from uncertify.utils.custom_types import Tensor
from typing import Tuple
from uncertify.visu... | uncertify/tutorials/variational_auto_encoder.py | import torch
from torch import nn
import torch.nn.functional as F
from torch.utils.data import DataLoader
from torch.optim.optimizer import Optimizer
import matplotlib.pyplot as plt
from uncertify.common import DATA_DIR_PATH
from uncertify.utils.custom_types import Tensor
from typing import Tuple
from uncertify.visu... | 0.900329 | 0.710264 |
from base64 import b64encode
from smtplib import (
SMTP as SMTPClient,
)
from typing import Callable, Tuple
import pytest
from aiosmtpd.testing.statuscodes import SMTP_STATUS_CODES as S
class _CommonMethods:
"""Contain snippets that keep being performed again and again and again..."""
def _helo(self, cl... | ModernRelay/tests/test_auth.py | from base64 import b64encode
from smtplib import (
SMTP as SMTPClient,
)
from typing import Callable, Tuple
import pytest
from aiosmtpd.testing.statuscodes import SMTP_STATUS_CODES as S
class _CommonMethods:
"""Contain snippets that keep being performed again and again and again..."""
def _helo(self, cl... | 0.681515 | 0.433022 |
import arcade
from inac8hr.gui import PaneTile, Point
from ..graphics import Sprite
from i18n.loc import LocalizedText
from inac8hr.globals import GAME_PREFS
from . import PaperShredderUnit, CalculatorUnit
VALID_PLACEMENT = 1
INVALID_PLACEMENT = 0
class UnitInfo:
"""
Contains each Defender unit informati... | inac8hr/entities/info.py | import arcade
from inac8hr.gui import PaneTile, Point
from ..graphics import Sprite
from i18n.loc import LocalizedText
from inac8hr.globals import GAME_PREFS
from . import PaperShredderUnit, CalculatorUnit
VALID_PLACEMENT = 1
INVALID_PLACEMENT = 0
class UnitInfo:
"""
Contains each Defender unit informati... | 0.596198 | 0.211763 |
from __future__ import absolute_import
from __future__ import division
from __future__ import print_function
# pylint: skip-file
import os
import sys
import networkx as nx
import numpy as np
from collections import defaultdict
from tqdm import tqdm
def get_node_map(nodelist, shift=0):
node_map = {}
for i, x... | bigg/bigg/data_process/data_util.py |
from __future__ import absolute_import
from __future__ import division
from __future__ import print_function
# pylint: skip-file
import os
import sys
import networkx as nx
import numpy as np
from collections import defaultdict
from tqdm import tqdm
def get_node_map(nodelist, shift=0):
node_map = {}
for i, x... | 0.391522 | 0.247942 |
from testtools import TestCase
from kmip.core.messages.contents import ProtocolVersion
from kmip.core.utils import BytearrayStream
class TestProtocolVersion(TestCase):
def setUp(self):
super(TestProtocolVersion, self).setUp()
self.major_default = ProtocolVersion.ProtocolVersionMajor()
... | kmip/tests/unit/core/messages/contents/test_protocol_version.py |
from testtools import TestCase
from kmip.core.messages.contents import ProtocolVersion
from kmip.core.utils import BytearrayStream
class TestProtocolVersion(TestCase):
def setUp(self):
super(TestProtocolVersion, self).setUp()
self.major_default = ProtocolVersion.ProtocolVersionMajor()
... | 0.729616 | 0.517388 |
import unittest
import munch
import basecrm
from basecrm.test.testutils import BaseTestCase
class ProductsServiceTests(BaseTestCase):
def test_service_property_exists(self):
self.assertTrue(hasattr(self.client, 'products'))
def test_method_list_exists(self):
self.assertTrue(hasattr(self.clie... | basecrm/test/test_products_service.py | import unittest
import munch
import basecrm
from basecrm.test.testutils import BaseTestCase
class ProductsServiceTests(BaseTestCase):
def test_service_property_exists(self):
self.assertTrue(hasattr(self.client, 'products'))
def test_method_list_exists(self):
self.assertTrue(hasattr(self.clie... | 0.379034 | 0.40987 |
import enum
class PrivilegeValues(enum.Enum):
SE_CREATE_TOKEN = 2
SE_ASSIGNPRIMARYTOKEN = 3
SE_LOCK_MEMORY=4
SE_INCREASE_QUOTA=5
SE_UNSOLICITED_INPUT=6
SE_TCB=7
SE_SECURITY=8
SE_TAKE_OWNERSHIP=9
SE_LOAD_DRIVER=10
SE_SYSTEM_PROFILE=11
SE_SYSTEMTIME=12
SE_PROF_SINGLE_PROCESS=13
SE_INC_BASE_PRIORITY=14
SE_... | pypykatz/commons/winapi/local/function_defs/privileges_types.py |
import enum
class PrivilegeValues(enum.Enum):
SE_CREATE_TOKEN = 2
SE_ASSIGNPRIMARYTOKEN = 3
SE_LOCK_MEMORY=4
SE_INCREASE_QUOTA=5
SE_UNSOLICITED_INPUT=6
SE_TCB=7
SE_SECURITY=8
SE_TAKE_OWNERSHIP=9
SE_LOAD_DRIVER=10
SE_SYSTEM_PROFILE=11
SE_SYSTEMTIME=12
SE_PROF_SINGLE_PROCESS=13
SE_INC_BASE_PRIORITY=14
SE_... | 0.379953 | 0.107578 |
from django.conf import settings
from django.db import migrations, models
import django.db.models.deletion
import django.utils.timezone
import indieweb.models
import model_utils.fields
class Migration(migrations.Migration):
initial = True
dependencies = [migrations.swappable_dependency(settings.AUTH_USER_M... | indieweb/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 indieweb.models
import model_utils.fields
class Migration(migrations.Migration):
initial = True
dependencies = [migrations.swappable_dependency(settings.AUTH_USER_M... | 0.458106 | 0.124959 |
import requests
from bs4 import BeautifulSoup
import json
import pandas as pd
import matplotlib.pyplot as plt
import seaborn as sns
import warnings
warnings.filterwarnings('ignore')
def xg_time_map(match_id='dummy', figname='fig.png', display=True, save=True):
df=scraper(match_id, save=False)
plotter(df, sa... | fbviz/understat.py | import requests
from bs4 import BeautifulSoup
import json
import pandas as pd
import matplotlib.pyplot as plt
import seaborn as sns
import warnings
warnings.filterwarnings('ignore')
def xg_time_map(match_id='dummy', figname='fig.png', display=True, save=True):
df=scraper(match_id, save=False)
plotter(df, sa... | 0.144662 | 0.233728 |
import logging
from django.contrib.auth.decorators import login_required
from django.http import JsonResponse
from django.shortcuts import render
from django.views.decorators.csrf import csrf_exempt
from git_manager.helpers.github_helper import get_github_helper
from helpers.helper import get_package_or_experiment
f... | coverage_manager/views.py | import logging
from django.contrib.auth.decorators import login_required
from django.http import JsonResponse
from django.shortcuts import render
from django.views.decorators.csrf import csrf_exempt
from git_manager.helpers.github_helper import get_github_helper
from helpers.helper import get_package_or_experiment
f... | 0.50952 | 0.141193 |
import sys
import os
import shutil
from lithops.utils import version_str
from lithops import __version__
from lithops.constants import TEMP
BUILD_DIR = os.path.join(TEMP, 'AzureRuntimeBuild')
ACTION_DIR = 'lithops_handler'
ACTION_MODULES_DIR = os.path.join('.python_packages', 'lib', 'site-packages')
FH_ZIP_LOCATION ... | lithops/serverless/backends/azure_functions/config.py |
import sys
import os
import shutil
from lithops.utils import version_str
from lithops import __version__
from lithops.constants import TEMP
BUILD_DIR = os.path.join(TEMP, 'AzureRuntimeBuild')
ACTION_DIR = 'lithops_handler'
ACTION_MODULES_DIR = os.path.join('.python_packages', 'lib', 'site-packages')
FH_ZIP_LOCATION ... | 0.324449 | 0.109254 |
from django.shortcuts import render
from django.http import JsonResponse
from . import tasks
import storage.rcache as rcache
# Create your views here.
def update_stock_info(request):
resp_dict = {}
if request.method == 'POST' and request.is_ajax():
resp_dict['status'] = '成功'
tasks.update_sto... | storage/views.py | from django.shortcuts import render
from django.http import JsonResponse
from . import tasks
import storage.rcache as rcache
# Create your views here.
def update_stock_info(request):
resp_dict = {}
if request.method == 'POST' and request.is_ajax():
resp_dict['status'] = '成功'
tasks.update_sto... | 0.334155 | 0.106691 |
import redis
from functools import wraps
import multiprocessing as mp
from includes import *
'''
python -m RLTest --test tests_sanitizer.py --module path/to/redisai.so
'''
def test_sanitizer_dagrun_mobilenet_v1(env):
if (not TEST_TF or not TEST_PT):
return
con = get_connection(env, '{s}')
mem_all... | tests/flow/tests_sanitizer.py | import redis
from functools import wraps
import multiprocessing as mp
from includes import *
'''
python -m RLTest --test tests_sanitizer.py --module path/to/redisai.so
'''
def test_sanitizer_dagrun_mobilenet_v1(env):
if (not TEST_TF or not TEST_PT):
return
con = get_connection(env, '{s}')
mem_all... | 0.438545 | 0.171685 |
import os
import configparser
from aliyunsdkcore.request import RpcRequest
from aliyunsdkcore import client
class TestEndpoint(object):
acs_client = None
@classmethod
def setup_class(cls):
cf = configparser.ConfigParser()
config_file = os.path.expanduser('~') + "/aliyun-sdk.ini"
... | aliyun-python-sdk-core-v3/tests/test_endpoint.py |
import os
import configparser
from aliyunsdkcore.request import RpcRequest
from aliyunsdkcore import client
class TestEndpoint(object):
acs_client = None
@classmethod
def setup_class(cls):
cf = configparser.ConfigParser()
config_file = os.path.expanduser('~') + "/aliyun-sdk.ini"
... | 0.415254 | 0.055849 |
import train_synth.config as config
from train_synth.dataloader import DataLoaderSYNTH
from src.utils.parallel import DataParallelModel, DataParallelCriterion
from src.utils.utils import calculate_batch_fscore, generate_word_bbox_batch, _init_fn
from src.generic_model import Criterian
from src.utils.data_manipulation i... | train_synth/test.py | import train_synth.config as config
from train_synth.dataloader import DataLoaderSYNTH
from src.utils.parallel import DataParallelModel, DataParallelCriterion
from src.utils.utils import calculate_batch_fscore, generate_word_bbox_batch, _init_fn
from src.generic_model import Criterian
from src.utils.data_manipulation i... | 0.649134 | 0.398055 |
import operator as op
from typing import (AbstractSet, Any, Callable, Generic, Mapping, Set,
SupportsInt, T, Tuple, Union)
import pytest
from .. import (NeuroLangTypeException, Unknown, get_args, get_origin,
infer_type, is_leq_informative, is_parameterized,
is_param... | neurolang/type_system/tests/test_gradual_typing.py | import operator as op
from typing import (AbstractSet, Any, Callable, Generic, Mapping, Set,
SupportsInt, T, Tuple, Union)
import pytest
from .. import (NeuroLangTypeException, Unknown, get_args, get_origin,
infer_type, is_leq_informative, is_parameterized,
is_param... | 0.861072 | 0.726207 |
"""revelation setup file"""
import os
import re
from setuptools import find_packages, setup
PACKAGE = "revelation"
REQUIREMENTS = [
"Jinja2==2.10",
"Werkzeug==0.14.1",
"click==6.7",
"gevent-websocket==0.10.1",
"gevent==1.3.6",
"watchdog==0.8.3",
]
TEST_REQUIREMENTS = [
"coverage==4.5.1",
... | setup.py | """revelation setup file"""
import os
import re
from setuptools import find_packages, setup
PACKAGE = "revelation"
REQUIREMENTS = [
"Jinja2==2.10",
"Werkzeug==0.14.1",
"click==6.7",
"gevent-websocket==0.10.1",
"gevent==1.3.6",
"watchdog==0.8.3",
]
TEST_REQUIREMENTS = [
"coverage==4.5.1",
... | 0.32146 | 0.338023 |
import multiprocessing
import random
import string
from contextlib import contextmanager
from elasticsearch import Elasticsearch
from elasticsearch.exceptions import RequestError
from functools import partial
from .util import load_json
@contextmanager
def temporary_search_template(es, template_file, template_id_in_... | Machine Learning/Query Optimization/qopt/search.py | import multiprocessing
import random
import string
from contextlib import contextmanager
from elasticsearch import Elasticsearch
from elasticsearch.exceptions import RequestError
from functools import partial
from .util import load_json
@contextmanager
def temporary_search_template(es, template_file, template_id_in_... | 0.55447 | 0.289447 |
import asyncio
import json
import logging
import os.path
from pathlib import Path
from typing import Optional, List, Union, Dict, Any
from checkov.common.bridgecrew.platform_integration import bc_integration
from checkov.common.bridgecrew.vulnerability_scanning.image_scanner import image_scanner, TWISTCLI_FILE_NAME
fr... | checkov/sca_image/runner.py | import asyncio
import json
import logging
import os.path
from pathlib import Path
from typing import Optional, List, Union, Dict, Any
from checkov.common.bridgecrew.platform_integration import bc_integration
from checkov.common.bridgecrew.vulnerability_scanning.image_scanner import image_scanner, TWISTCLI_FILE_NAME
fr... | 0.719876 | 0.154026 |
from UM.Logger import LogOutput
from typing import Set
import logging
try:
from colorlog import ColoredFormatter
logging_formatter = ColoredFormatter("%(purple)s%(asctime)s%(reset)s - %(log_color)s%(levelname)s%(reset)s - %(white)s%(message)s%(reset)s",
log_colors = {... | Cura/Uranium/plugins/ConsoleLogger/ConsoleLogger.py |
from UM.Logger import LogOutput
from typing import Set
import logging
try:
from colorlog import ColoredFormatter
logging_formatter = ColoredFormatter("%(purple)s%(asctime)s%(reset)s - %(log_color)s%(levelname)s%(reset)s - %(white)s%(message)s%(reset)s",
log_colors = {... | 0.505859 | 0.101189 |
import platform
import time
if 'Windows' in platform.system():
import ctypes, sys
STD_INPUT_HANDLE = -10
STD_OUTPUT_HANDLE = -11
STD_ERROR_HANDLE = -12
# 字体颜色定义 text colors
FOREGROUND_BLUE = 0x09 # blue.
FOREGROUND_GREEN = 0x0a # green.
FOREGROUND_DEEPGREEN = 0x02 # dark green.
... | Config/config_print.py | import platform
import time
if 'Windows' in platform.system():
import ctypes, sys
STD_INPUT_HANDLE = -10
STD_OUTPUT_HANDLE = -11
STD_ERROR_HANDLE = -12
# 字体颜色定义 text colors
FOREGROUND_BLUE = 0x09 # blue.
FOREGROUND_GREEN = 0x0a # green.
FOREGROUND_DEEPGREEN = 0x02 # dark green.
... | 0.155078 | 0.081374 |
# In[1]:
import numpy as np
import sys
sys.path.insert(0, '..')
from algorithms.dbscan_gmm import DBSCAN_GMM
from algorithms.grid_based_dbscan import GridBasedDBSCAN
from algorithms.grid_based_dbscan_gmm import GridBasedDBSCAN_GMM
from utilities.plot_utils import *
from utility import Skills, ScatterDetection
import... | plotters.py/simulate.py |
# In[1]:
import numpy as np
import sys
sys.path.insert(0, '..')
from algorithms.dbscan_gmm import DBSCAN_GMM
from algorithms.grid_based_dbscan import GridBasedDBSCAN
from algorithms.grid_based_dbscan_gmm import GridBasedDBSCAN_GMM
from utilities.plot_utils import *
from utility import Skills, ScatterDetection
import... | 0.270384 | 0.431944 |
import unittest
from fysom import Fysom, FysomError
class FysomStateTests(unittest.TestCase):
def setUp(self):
self.fsm = Fysom({
'initial': 'green',
'events': [
{'name': 'warn', 'src': 'green', 'dst': 'yellow'},
{'name': 'panic', 'src': 'yellow',... | src/unittest/python/test_state.py |
import unittest
from fysom import Fysom, FysomError
class FysomStateTests(unittest.TestCase):
def setUp(self):
self.fsm = Fysom({
'initial': 'green',
'events': [
{'name': 'warn', 'src': 'green', 'dst': 'yellow'},
{'name': 'panic', 'src': 'yellow',... | 0.732592 | 0.605158 |
import functools
import json
from django.contrib.auth import authenticate
from django.contrib.auth import login as auth_login
from django.contrib.auth import logout as auth_logout
from django.contrib.auth.decorators import login_required
from django.http import HttpResponse, HttpResponseNotFound, HttpResponseRedirect
... | order/views.py | import functools
import json
from django.contrib.auth import authenticate
from django.contrib.auth import login as auth_login
from django.contrib.auth import logout as auth_logout
from django.contrib.auth.decorators import login_required
from django.http import HttpResponse, HttpResponseNotFound, HttpResponseRedirect
... | 0.445047 | 0.067209 |
from torch import nn
from .module import *
def gen_init_conv_bn(in_channels: int, out_channels: int, stride: int):
return nn.Sequential(
nn.Conv2d(in_channels, out_channels, 3, stride, 1, bias=False),
nn.BatchNorm2d(out_channels),
HardSwish()
)
def gen_block_layer(config: list):
... | ipalm/net/mobilenetv3.py | from torch import nn
from .module import *
def gen_init_conv_bn(in_channels: int, out_channels: int, stride: int):
return nn.Sequential(
nn.Conv2d(in_channels, out_channels, 3, stride, 1, bias=False),
nn.BatchNorm2d(out_channels),
HardSwish()
)
def gen_block_layer(config: list):
... | 0.943178 | 0.344747 |
import numpy as np
import theano
import theano.tensor as T
import theano.tensor.nnet.bn as bn
eps = np.float32(1e-6)
zero = np.float32(0.)
one = np.float32(1.)
def bn_shared(params, outFilters, index):
''' Setup BN shared variables.
'''
normParam = {}
template = np.ones((outFilters,)... | gpu_ver/refcode/models/layers/batchnorm.py | import numpy as np
import theano
import theano.tensor as T
import theano.tensor.nnet.bn as bn
eps = np.float32(1e-6)
zero = np.float32(0.)
one = np.float32(1.)
def bn_shared(params, outFilters, index):
''' Setup BN shared variables.
'''
normParam = {}
template = np.ones((outFilters,)... | 0.466359 | 0.280795 |
import logging
import asyncio
from typing import Optional
from asyncio import Queue
import gi
from gi.repository import Gst, GObject, GLib
from xbox.nano.render.client.base import Client
from xbox.nano.render.audio.aac import AACFrame, AACProfile
gi.require_version('Gst', '1.0')
log = logging.getLogger(__name__)
c... | xbox/nano/render/client/gst.py | import logging
import asyncio
from typing import Optional
from asyncio import Queue
import gi
from gi.repository import Gst, GObject, GLib
from xbox.nano.render.client.base import Client
from xbox.nano.render.audio.aac import AACFrame, AACProfile
gi.require_version('Gst', '1.0')
log = logging.getLogger(__name__)
c... | 0.563378 | 0.103976 |
import random
seed = 7
random.seed(seed)
randI = random.sample(range(1,16), 15)
randI = [str(i) for i in randI]
# print(randI)
import os
import torch
import re
import shutil
from PIL import Image
def tiff2jpeg(namef, nameS, c, image_tiff):
# Check directory exists or not
directory = os.path.d... | BOE_dataset_split.py | import random
seed = 7
random.seed(seed)
randI = random.sample(range(1,16), 15)
randI = [str(i) for i in randI]
# print(randI)
import os
import torch
import re
import shutil
from PIL import Image
def tiff2jpeg(namef, nameS, c, image_tiff):
# Check directory exists or not
directory = os.path.d... | 0.117054 | 0.088387 |
from pwn import *
#r = process("./idol")
r = remote("172.16.58.3", 31337)
def register(ID, PW):
r.send("3\n")
print r.recvuntil("): ")
r.send(ID)
print r.recvuntil("): ")
r.send(PW)
print r.recvuntil("name: ")
r.send("mathboy7\n")
print r.recvuntil("> ")
def login(ID, PW):
r.send("1\n")
print r.recvuntil("... | secuinside-2017/IdolMaster/idol.py | from pwn import *
#r = process("./idol")
r = remote("172.16.58.3", 31337)
def register(ID, PW):
r.send("3\n")
print r.recvuntil("): ")
r.send(ID)
print r.recvuntil("): ")
r.send(PW)
print r.recvuntil("name: ")
r.send("mathboy7\n")
print r.recvuntil("> ")
def login(ID, PW):
r.send("1\n")
print r.recvuntil("... | 0.095081 | 0.097734 |
import sys
import log, stuff
def loadalltemplates(folder, templates):
loaded = {}
templatefiles = stuff.findfiles('*.yaml', folder)
entries = {}
for templatefile in templatefiles:
namespace = stuff.filename(templatefile, ext=False).lower()
content = stuff.restore(templatefile)
... | template.py | import sys
import log, stuff
def loadalltemplates(folder, templates):
loaded = {}
templatefiles = stuff.findfiles('*.yaml', folder)
entries = {}
for templatefile in templatefiles:
namespace = stuff.filename(templatefile, ext=False).lower()
content = stuff.restore(templatefile)
... | 0.167015 | 0.098296 |
import os
import re
from scarab_globals import *
from scarab_globals.scarab_batch_types import *
# Set the following variables before running.
CHECKPOINT_DESCRIPTOR_PATH = ''
OUTPUT_DIR = ''
SUITE_NAME = ''
def checkpoint_start_rip(path):
with open (path + '/main') as f:
for line in f:
m = re.match('\s*... | bin/checkpoint/convert_checkpoints_to_traces.py |
import os
import re
from scarab_globals import *
from scarab_globals.scarab_batch_types import *
# Set the following variables before running.
CHECKPOINT_DESCRIPTOR_PATH = ''
OUTPUT_DIR = ''
SUITE_NAME = ''
def checkpoint_start_rip(path):
with open (path + '/main') as f:
for line in f:
m = re.match('\s*... | 0.459804 | 0.169337 |
from __future__ import unicode_literals
from django.db import migrations, models
import datetime
from django.conf import settings
from django.utils.timezone import utc
class Migration(migrations.Migration):
dependencies = [
migrations.swappable_dependency(settings.AUTH_USER_MODEL),
]
operations... | Xchange_master/system/migrations/0001_initial.py | from __future__ import unicode_literals
from django.db import migrations, models
import datetime
from django.conf import settings
from django.utils.timezone import utc
class Migration(migrations.Migration):
dependencies = [
migrations.swappable_dependency(settings.AUTH_USER_MODEL),
]
operations... | 0.476823 | 0.119819 |
from Tea.model import TeaModel
class RemoveClusterFromServiceMeshRequest(TeaModel):
def __init__(self, service_mesh_id=None, cluster_id=None):
self.service_mesh_id = service_mesh_id
self.cluster_id = cluster_id
def validate(self):
self.validate_required(self.service_mesh_id, 'service_... | servicemesh-20200111/python/alibabacloud_servicemesh20200111/models.py | from Tea.model import TeaModel
class RemoveClusterFromServiceMeshRequest(TeaModel):
def __init__(self, service_mesh_id=None, cluster_id=None):
self.service_mesh_id = service_mesh_id
self.cluster_id = cluster_id
def validate(self):
self.validate_required(self.service_mesh_id, 'service_... | 0.569613 | 0.060863 |
import sys, os
import argparse
import shutil
import warnings
from itertools import cycle
from collections import defaultdict
from collections import Counter
import numpy as np
import scipy
import scipy.cluster
import scipy.cluster.hierarchy as hier
from Utils import *
def parse_args(args):
description = "Infe... | src/chisel/Cloner.py |
import sys, os
import argparse
import shutil
import warnings
from itertools import cycle
from collections import defaultdict
from collections import Counter
import numpy as np
import scipy
import scipy.cluster
import scipy.cluster.hierarchy as hier
from Utils import *
def parse_args(args):
description = "Infe... | 0.476092 | 0.287055 |
import pytest
from django.utils import timezone
from django.test import TestCase
from django import forms
from feed.models import Channel, Episode, Subscription, Like, MstCollection
from accounts.models import LogueUser
class ChannelModelTest(TestCase):
"""
チャンネルモデル
"""
def test_save(self):
... | feed/tests/test_models.py | import pytest
from django.utils import timezone
from django.test import TestCase
from django import forms
from feed.models import Channel, Episode, Subscription, Like, MstCollection
from accounts.models import LogueUser
class ChannelModelTest(TestCase):
"""
チャンネルモデル
"""
def test_save(self):
... | 0.529507 | 0.457258 |
import os
import sys
import boto3
import shutil
import pathlib
import subprocess
import json
def main(argv):
config_file = 'remote_config.json'
with open(config_file) as f:
configs = json.load(f)
session = boto3.session.Session(
configs['access_key_id'],
configs['secret_access_... | 02_service/service/service.py |
import os
import sys
import boto3
import shutil
import pathlib
import subprocess
import json
def main(argv):
config_file = 'remote_config.json'
with open(config_file) as f:
configs = json.load(f)
session = boto3.session.Session(
configs['access_key_id'],
configs['secret_access_... | 0.125614 | 0.060197 |
import socket
import string
import sys
import types
from impacket import uuid, ntlm, version
from impacket.dcerpc import dcerpc_v4, dcerpc, transport, lsarpc
import argparse
class LSALookupSid:
KNOWN_PROTOCOLS = {
'139/SMB': (r'ncacn_np:%s[\pipe\lsarpc]', 139),
'445/SMB': (r'ncacn_np:%s[\pipe\lsa... | examples/lookupsid.py |
import socket
import string
import sys
import types
from impacket import uuid, ntlm, version
from impacket.dcerpc import dcerpc_v4, dcerpc, transport, lsarpc
import argparse
class LSALookupSid:
KNOWN_PROTOCOLS = {
'139/SMB': (r'ncacn_np:%s[\pipe\lsarpc]', 139),
'445/SMB': (r'ncacn_np:%s[\pipe\lsa... | 0.270769 | 0.063802 |
try:
# Try python 3.+ libs
from tkinter import Tk, Menu, Listbox, Button, filedialog, Label, StringVar, OptionMenu
from tkinter import END, RIGHT, LEFT, TOP, BOTTOM, BOTH, N, W, E, S, X
except (ImportError):
# Or python 2.7+ libs
from Tkinter import Tk, Menu, Listbox, Button, tkFileDialog, Label, St... | masfir.py | try:
# Try python 3.+ libs
from tkinter import Tk, Menu, Listbox, Button, filedialog, Label, StringVar, OptionMenu
from tkinter import END, RIGHT, LEFT, TOP, BOTTOM, BOTH, N, W, E, S, X
except (ImportError):
# Or python 2.7+ libs
from Tkinter import Tk, Menu, Listbox, Button, tkFileDialog, Label, St... | 0.384681 | 0.076511 |
from abc import ABC, abstractmethod
from datetime import datetime
from dataclasses import dataclass
from nbformat.notebooknode import NotebookNode
from typing import Optional
from nbclient.client import NotebookClient
from nbclient.exceptions import CellExecutionError, CellTimeoutError
import logging
from opentelemetry... | src/jupyrest/jupyrest/executors.py | from abc import ABC, abstractmethod
from datetime import datetime
from dataclasses import dataclass
from nbformat.notebooknode import NotebookNode
from typing import Optional
from nbclient.client import NotebookClient
from nbclient.exceptions import CellExecutionError, CellTimeoutError
import logging
from opentelemetry... | 0.895111 | 0.17765 |
"""Tests for dual encoder network."""
from __future__ import absolute_import
from __future__ import division
from __future__ import print_function
# Import libraries
from absl.testing import parameterized
import tensorflow as tf
from tensorflow.python.keras import keras_parameterized # pylint: disable=g-direct-tens... | official/nlp/modeling/models/dual_encoder_test.py | """Tests for dual encoder network."""
from __future__ import absolute_import
from __future__ import division
from __future__ import print_function
# Import libraries
from absl.testing import parameterized
import tensorflow as tf
from tensorflow.python.keras import keras_parameterized # pylint: disable=g-direct-tens... | 0.940538 | 0.553385 |
import numpy as np
from agents.agent import *
class BTS(Agent):
def __init__(self, sample, nactions):
'''
Description
-----------
thompson sampling for bernoulli bandit environments
Parameters
----------
sample (func) - samples rewards
... | agents/ts.py | import numpy as np
from agents.agent import *
class BTS(Agent):
def __init__(self, sample, nactions):
'''
Description
-----------
thompson sampling for bernoulli bandit environments
Parameters
----------
sample (func) - samples rewards
... | 0.763043 | 0.391842 |
import warnings
import pulumi
import pulumi.runtime
from typing import Any, Mapping, Optional, Sequence, Union, overload
from ... import _utilities
from . import outputs
from ._inputs import *
__all__ = ['WebhookArgs', 'Webhook']
@pulumi.input_type
class WebhookArgs:
def __init__(__self__, *,
ag... | sdk/python/pulumi_google_native/dialogflow/v3/webhook.py |
import warnings
import pulumi
import pulumi.runtime
from typing import Any, Mapping, Optional, Sequence, Union, overload
from ... import _utilities
from . import outputs
from ._inputs import *
__all__ = ['WebhookArgs', 'Webhook']
@pulumi.input_type
class WebhookArgs:
def __init__(__self__, *,
ag... | 0.856902 | 0.052376 |
import sys, random
from PyQt5.QtWidgets import QApplication, QWidget, QPushButton, QMainWindow, QDesktopWidget, QFrame, QMessageBox, QAction, QLineEdit, QGridLayout, QLabel
from PyQt5.QtCore import Qt, QBasicTimer, pyqtSignal
from PyQt5.QtGui import QIcon, QColor, QPainter
import datetime
class Connect4(QMainWindow):
... | Connect_4/Connect_4.py | import sys, random
from PyQt5.QtWidgets import QApplication, QWidget, QPushButton, QMainWindow, QDesktopWidget, QFrame, QMessageBox, QAction, QLineEdit, QGridLayout, QLabel
from PyQt5.QtCore import Qt, QBasicTimer, pyqtSignal
from PyQt5.QtGui import QIcon, QColor, QPainter
import datetime
class Connect4(QMainWindow):
... | 0.112881 | 0.15444 |
from functools import wraps
import pandas as pd
from ..common import (
_get,
_getAsync,
_raiseIfNotStr,
_reindex,
_strOrDate,
_strToList,
_toDatetime,
json_normalize,
)
def iexTops(symbols=None, token="", version="stable", format="json"):
"""TOPS provides IEX’s aggregated best qu... | pyEX/stocks/iex.py | from functools import wraps
import pandas as pd
from ..common import (
_get,
_getAsync,
_raiseIfNotStr,
_reindex,
_strOrDate,
_strToList,
_toDatetime,
json_normalize,
)
def iexTops(symbols=None, token="", version="stable", format="json"):
"""TOPS provides IEX’s aggregated best qu... | 0.81946 | 0.320875 |
from audioop import add
from cgitb import reset
from curses.ascii import HT
from re import U
from attr import attr
from django.shortcuts import render
from django.http import HttpResponse
import requests
from bs4 import BeautifulSoup
from selenium import webdriver
from selenium.webdriver.common.by import By
from seleni... | chartapp/views.py | from audioop import add
from cgitb import reset
from curses.ascii import HT
from re import U
from attr import attr
from django.shortcuts import render
from django.http import HttpResponse
import requests
from bs4 import BeautifulSoup
from selenium import webdriver
from selenium.webdriver.common.by import By
from seleni... | 0.379493 | 0.091829 |
import mock
from cloudferry.actions.filter.filter_similar_vms_from_dst import \
FilterSimilarVMsFromDST
from tests import test
class FilterSimilarVMsFromDSTTestCase(test.TestCase):
def test_make_tenant_ip_to_instance_id_dict(self):
instances = {'id1': {'instance': {'id': 'id1',
... | tests/lib/os/actions/test_filter_similar_vms_from_dst.py |
import mock
from cloudferry.actions.filter.filter_similar_vms_from_dst import \
FilterSimilarVMsFromDST
from tests import test
class FilterSimilarVMsFromDSTTestCase(test.TestCase):
def test_make_tenant_ip_to_instance_id_dict(self):
instances = {'id1': {'instance': {'id': 'id1',
... | 0.553264 | 0.12297 |
from pathlib import Path
import environ
from redis import ConnectionPool
from mastodon import Mastodon
import requests
# Build paths inside the project like this: BASE_DIR / 'subdir'.
BASE_DIR = Path(__file__).resolve().parent.parent
env = environ.Env()
# reading .env file
environ.Env.read_env(env_file... | derbot/settings.py | from pathlib import Path
import environ
from redis import ConnectionPool
from mastodon import Mastodon
import requests
# Build paths inside the project like this: BASE_DIR / 'subdir'.
BASE_DIR = Path(__file__).resolve().parent.parent
env = environ.Env()
# reading .env file
environ.Env.read_env(env_file... | 0.537041 | 0.109254 |
from aws_cdk import aws_codepipeline as codepipeline
from aws_cdk import aws_codepipeline_actions as cpactions
from aws_cdk import core as cdk
from aws_cdk.pipelines import CdkPipeline, SimpleSynthAction
from explainbot_stage import ExplainSlackBotStage
class ExplainSlackBotPipelineStack(cdk.Stack):
def __init__... | explainbot_pipeline_stack.py | from aws_cdk import aws_codepipeline as codepipeline
from aws_cdk import aws_codepipeline_actions as cpactions
from aws_cdk import core as cdk
from aws_cdk.pipelines import CdkPipeline, SimpleSynthAction
from explainbot_stage import ExplainSlackBotStage
class ExplainSlackBotPipelineStack(cdk.Stack):
def __init__... | 0.718496 | 0.146423 |
from spack import *
class Tkrzw(AutotoolsPackage):
"""Tkrzw is a C++ library implementing database managers with various algorithms."""
homepage = "https://dbmx.net/tkrzw/"
url = "https://dbmx.net/tkrzw/pkg/tkrzw-0.9.22.tar.gz"
git = "https://github.com/estraier/tkrzw.git"
version('ma... | var/spack/repos/builtin/packages/tkrzw/package.py |
from spack import *
class Tkrzw(AutotoolsPackage):
"""Tkrzw is a C++ library implementing database managers with various algorithms."""
homepage = "https://dbmx.net/tkrzw/"
url = "https://dbmx.net/tkrzw/pkg/tkrzw-0.9.22.tar.gz"
git = "https://github.com/estraier/tkrzw.git"
version('ma... | 0.738103 | 0.245644 |
import numpy as np
import pylab as P
from rfwrapper import rf
import matplotlib.patches
import matplotlib.cm
from units import *
import os, sys
cosmo = rf.experiments.cosmo
#names = ['SKA1MIDfull', 'SKA1MIDfull2', 'iSKA1MIDfull1', 'iSKA1MIDfull2', 'fSKA1SURfull1', 'fSKA1SURfull2']
names = ['SKA0MID', 'SKA0SUR', 'SKA... | plotting/plot_pk_scales.py | import numpy as np
import pylab as P
from rfwrapper import rf
import matplotlib.patches
import matplotlib.cm
from units import *
import os, sys
cosmo = rf.experiments.cosmo
#names = ['SKA1MIDfull', 'SKA1MIDfull2', 'iSKA1MIDfull1', 'iSKA1MIDfull2', 'fSKA1SURfull1', 'fSKA1SURfull2']
names = ['SKA0MID', 'SKA0SUR', 'SKA... | 0.276788 | 0.409929 |
import time
import math
#分页
def paginate(query, page, per_page):
#总页数
total_count = query.count()
total_page = math.ceil(total_count/per_page)
if page < 1:
items = []
else:
items = query.limit(per_page).offset((page-1) * per_page).all()
current_page = page
pagination = {'tot... | base/helpers.py | import time
import math
#分页
def paginate(query, page, per_page):
#总页数
total_count = query.count()
total_page = math.ceil(total_count/per_page)
if page < 1:
items = []
else:
items = query.limit(per_page).offset((page-1) * per_page).all()
current_page = page
pagination = {'tot... | 0.070989 | 0.127408 |
from jig.visualizer.module_dependency.domain.value.edge_style import EdgeStyle
from jig.visualizer.module_dependency.domain.value.module_edge import ModuleEdge
from jig.visualizer.module_dependency.domain.value.module_node import ModuleNode
from jig.visualizer.module_dependency.domain.model.hide_filter import HideFilt... | tests/visualizer/module_dependency/domain/model/test_hide_filter.py | from jig.visualizer.module_dependency.domain.value.edge_style import EdgeStyle
from jig.visualizer.module_dependency.domain.value.module_edge import ModuleEdge
from jig.visualizer.module_dependency.domain.value.module_node import ModuleNode
from jig.visualizer.module_dependency.domain.model.hide_filter import HideFilt... | 0.778313 | 0.570511 |
from functools import reduce
from functools import lru_cache
from os.path import join, dirname
import numpy as np
import xarray as xr
import pandas as pd
from .__init__ import Bunch
path_here = dirname(dirname(__file__))
def load_file(name):
""" Return a requested data file. """
data = pd.read_csv(join(path... | tensordata/alter.py | from functools import reduce
from functools import lru_cache
from os.path import join, dirname
import numpy as np
import xarray as xr
import pandas as pd
from .__init__ import Bunch
path_here = dirname(dirname(__file__))
def load_file(name):
""" Return a requested data file. """
data = pd.read_csv(join(path... | 0.677474 | 0.308646 |
dbutils.widgets.text("infilefolder", "", "In - Folder Path")
infilefolder = dbutils.widgets.get("infilefolder")
dbutils.widgets.text("loadid", "", "Load Id")
loadid = dbutils.widgets.get("loadid")
# COMMAND ----------
from applicationinsights import TelemetryClient
tc = TelemetryClient(dbutils.secrets.get(scope = "s... | e2e_samples/parking_sensors/databricks/notebooks/02_standardize.py | dbutils.widgets.text("infilefolder", "", "In - Folder Path")
infilefolder = dbutils.widgets.get("infilefolder")
dbutils.widgets.text("loadid", "", "Load Id")
loadid = dbutils.widgets.get("loadid")
# COMMAND ----------
from applicationinsights import TelemetryClient
tc = TelemetryClient(dbutils.secrets.get(scope = "s... | 0.276691 | 0.115112 |
"""Test the SystemVerilog translator implementation."""
import pytest
from pymtl3.passes.backends.verilog.util.utility import verilog_reserved
from pymtl3.passes.rtlir import BehavioralRTLIRGenPass, BehavioralRTLIRTypeCheckPass
from ....testcases import (
CaseElifBranchComp,
CaseFixedSizeSliceComp,
CaseF... | pymtl3/passes/backends/verilog/translation/behavioral/test/VBehavioralTranslatorL2_test.py | """Test the SystemVerilog translator implementation."""
import pytest
from pymtl3.passes.backends.verilog.util.utility import verilog_reserved
from pymtl3.passes.rtlir import BehavioralRTLIRGenPass, BehavioralRTLIRTypeCheckPass
from ....testcases import (
CaseElifBranchComp,
CaseFixedSizeSliceComp,
CaseF... | 0.491944 | 0.417865 |
import sys
import rospy
import smach
import smach_ros
import time
import rospkg
from std_msgs.msg import Bool
rospack = rospkg.RosPack()
mission_control_path = rospack.get_path('mission_control')
sys.path.append("%s/src" % mission_control_path)
import mission_control_utils
from mission_control_utils_constants import ... | examples/scripts/use_case_recharge.py | import sys
import rospy
import smach
import smach_ros
import time
import rospkg
from std_msgs.msg import Bool
rospack = rospkg.RosPack()
mission_control_path = rospack.get_path('mission_control')
sys.path.append("%s/src" % mission_control_path)
import mission_control_utils
from mission_control_utils_constants import ... | 0.311008 | 0.081191 |
import os
# https://preslav.me/2019/01/09/dotenv-files-python/
from dotenv import load_dotenv
from flask import request
from flask_restful import Resource
from googleapiclient.discovery import build
from .constants import countries, file_types, languages
__title__ = 'stimson-web-api'
__author__ = '<NAME>'
__license__... | app/app/api/search.py | import os
# https://preslav.me/2019/01/09/dotenv-files-python/
from dotenv import load_dotenv
from flask import request
from flask_restful import Resource
from googleapiclient.discovery import build
from .constants import countries, file_types, languages
__title__ = 'stimson-web-api'
__author__ = '<NAME>'
__license__... | 0.546738 | 0.206514 |
#This only works for CourseOffering
#This script is meant for debugging purposes. It is not produciton quality
import hashlib
import sys
import xml.etree.cElementTree as et
import re
whitespaceToStrip = ' \t\n'
def initData(data):
data["count"] = 0
data["dup"] = 0
data["hashes"] = {}
data["dupXML"] = {}
def g... | tools/troubleshooting/findCourseOfferingDups.py |
#This only works for CourseOffering
#This script is meant for debugging purposes. It is not produciton quality
import hashlib
import sys
import xml.etree.cElementTree as et
import re
whitespaceToStrip = ' \t\n'
def initData(data):
data["count"] = 0
data["dup"] = 0
data["hashes"] = {}
data["dupXML"] = {}
def g... | 0.04467 | 0.18159 |
from __future__ import print_function
from builtins import input
import numpy
import sys
import pmagpy.pmag as pmag
def main():
"""
NAME
cart_dir.py
DESCRIPTION
converts cartesian coordinates to geomagnetic elements
INPUT (COMMAND LINE ENTRY)
x1 x2 x3
if onl... | programs/cart_dir.py | from __future__ import print_function
from builtins import input
import numpy
import sys
import pmagpy.pmag as pmag
def main():
"""
NAME
cart_dir.py
DESCRIPTION
converts cartesian coordinates to geomagnetic elements
INPUT (COMMAND LINE ENTRY)
x1 x2 x3
if onl... | 0.204302 | 0.181209 |
import base64
from xdrlib import Packer, Unpacker
from .fee_bump_transaction_ext import FeeBumpTransactionExt
from .fee_bump_transaction_inner_tx import FeeBumpTransactionInnerTx
from .int64 import Int64
from .muxed_account import MuxedAccount
__all__ = ["FeeBumpTransaction"]
class FeeBumpTransaction:
"""
X... | stellar_sdk/xdr/fee_bump_transaction.py | import base64
from xdrlib import Packer, Unpacker
from .fee_bump_transaction_ext import FeeBumpTransactionExt
from .fee_bump_transaction_inner_tx import FeeBumpTransactionInnerTx
from .int64 import Int64
from .muxed_account import MuxedAccount
__all__ = ["FeeBumpTransaction"]
class FeeBumpTransaction:
"""
X... | 0.651798 | 0.12166 |
import os
from bento.core.pkg_objects \
import \
Extension
def translate_name(name, ref_node, from_node):
if from_node != ref_node:
parent_pkg = ref_node.path_from(from_node).replace(os.sep, ".")
return ".".join([parent_pkg, name])
else:
return name
class NodeDataFiles(obj... | bento/core/node_package.py | import os
from bento.core.pkg_objects \
import \
Extension
def translate_name(name, ref_node, from_node):
if from_node != ref_node:
parent_pkg = ref_node.path_from(from_node).replace(os.sep, ".")
return ".".join([parent_pkg, name])
else:
return name
class NodeDataFiles(obj... | 0.435902 | 0.117294 |
import argparse
import os
import numpy as np
import tensorflow as tf
import multiprocessing as mp
import json
import os
from cddd.input_pipeline import InputPipelineInferEncode, InputPipelineInferDecode
from cddd.hyperparameters import add_arguments, create_hparams
from cddd.model_helper import build_models
f... | cddd/inference.py | import argparse
import os
import numpy as np
import tensorflow as tf
import multiprocessing as mp
import json
import os
from cddd.input_pipeline import InputPipelineInferEncode, InputPipelineInferDecode
from cddd.hyperparameters import add_arguments, create_hparams
from cddd.model_helper import build_models
f... | 0.714728 | 0.218128 |
from __future__ import unicode_literals
from django.db import migrations, models
import django.db.models.deletion
class Migration(migrations.Migration):
dependencies = [
('activityinfo', '0087_auto_20190524_1401'),
]
operations = [
migrations.CreateModel(
name='Sites',
... | internos/activityinfo/migrations/0088_auto_20190524_2225.py | from __future__ import unicode_literals
from django.db import migrations, models
import django.db.models.deletion
class Migration(migrations.Migration):
dependencies = [
('activityinfo', '0087_auto_20190524_1401'),
]
operations = [
migrations.CreateModel(
name='Sites',
... | 0.585694 | 0.135747 |
from __future__ import unicode_literals
from textwrap import dedent
import pytest
def test_resolve_main(mocker):
from sampleproject.toolkit.proctitle import compute_main_module_name
mod = mocker.Mock(__package__='my', __name__='module')
assert 'my.module' == compute_main_module_name(mod)
mod = moc... | tests/test_proctitle.py | from __future__ import unicode_literals
from textwrap import dedent
import pytest
def test_resolve_main(mocker):
from sampleproject.toolkit.proctitle import compute_main_module_name
mod = mocker.Mock(__package__='my', __name__='module')
assert 'my.module' == compute_main_module_name(mod)
mod = moc... | 0.591251 | 0.260798 |
import atexit
from time import sleep
from datetime import datetime
from influxdb_client import InfluxDBClient, Point
from influxdb_client.client.write_api import SYNCHRONOUS
import minimalmodbus
import functools
total_count = 0
error_count = 0
def retry_decorator(func):
@functools.wraps(func)
def wrapper(*a... | sun-logger/core.py |
import atexit
from time import sleep
from datetime import datetime
from influxdb_client import InfluxDBClient, Point
from influxdb_client.client.write_api import SYNCHRONOUS
import minimalmodbus
import functools
total_count = 0
error_count = 0
def retry_decorator(func):
@functools.wraps(func)
def wrapper(*a... | 0.491456 | 0.100657 |
import requests
import argparse
import json
import pydash as _
import getpass
parser = argparse.ArgumentParser()
parser.add_argument("--UG", nargs='?' , type=str , help="Github Username")
parser.add_argument("--PG", nargs='?' , type=str , help="Github Password")
args = parser.parse_args()
# print(args.username)
usern... | python/app.py | import requests
import argparse
import json
import pydash as _
import getpass
parser = argparse.ArgumentParser()
parser.add_argument("--UG", nargs='?' , type=str , help="Github Username")
parser.add_argument("--PG", nargs='?' , type=str , help="Github Password")
args = parser.parse_args()
# print(args.username)
usern... | 0.069882 | 0.071041 |
import copy
import logging
from hdx.utilities.downloader import DownloadError
from .helpers import hxl_names
logger = logging.getLogger(__name__)
class RequirementsFundingCluster:
def __init__(self, downloader, planidswithonelocation, clusterlevel=""):
self.downloader = downloader
self.planidsw... | fts/requirements_funding_cluster.py | import copy
import logging
from hdx.utilities.downloader import DownloadError
from .helpers import hxl_names
logger = logging.getLogger(__name__)
class RequirementsFundingCluster:
def __init__(self, downloader, planidswithonelocation, clusterlevel=""):
self.downloader = downloader
self.planidsw... | 0.35354 | 0.07579 |
STATE = 10
# Regierungsbezirk
ADMINISTRATIVE_DISTRICT = 20
# Region
REGION = 30
# Kreis
CT_ABSTRACT = 40
# Kreisfreie Stadt
CT_URBAN_MUNICIPALITY = 41
# Stadtkreis
CT_METROPOLITAN_AREA = 42
# Kreis
CT_COUNTY = 43
# Landkreis
CT_RURAL_COUNTY = 44
# Regionalverband
CT_COLLECTIVE_COUNTY = 45
# verbandsfreie Gemeinde
MU_UN... | src/gvz/constants.py | STATE = 10
# Regierungsbezirk
ADMINISTRATIVE_DISTRICT = 20
# Region
REGION = 30
# Kreis
CT_ABSTRACT = 40
# Kreisfreie Stadt
CT_URBAN_MUNICIPALITY = 41
# Stadtkreis
CT_METROPOLITAN_AREA = 42
# Kreis
CT_COUNTY = 43
# Landkreis
CT_RURAL_COUNTY = 44
# Regionalverband
CT_COLLECTIVE_COUNTY = 45
# verbandsfreie Gemeinde
MU_UN... | 0.22093 | 0.182535 |
"""oauthlib.openid.connect.core.request_validator ~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~
"""
from __future__ import absolute_import, unicode_literals
import logging
from oauthlib.oauth2.rfc6749.request_validator import RequestValidator as OAuth2RequestValidator
log = logging.getLogger(__name__)
class Reque... | mac/google-cloud-sdk/lib/third_party/oauthlib/openid/connect/core/request_validator.py | """oauthlib.openid.connect.core.request_validator ~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~
"""
from __future__ import absolute_import, unicode_literals
import logging
from oauthlib.oauth2.rfc6749.request_validator import RequestValidator as OAuth2RequestValidator
log = logging.getLogger(__name__)
class Reque... | 0.87397 | 0.215588 |
import os
import subprocess
import argparse
# the directory to mount the sd card to
BOOT_MNT = '/mnt/zynq/boot/'
GAMES_MNT = '/mnt/zynq/games'
# the names to copy the boot and mes files to on the sd card
BOOT_FILE = 'BOOT.bin'
MES_FILE = 'MES.bin'
def copy_file(src, dst):
"""
This function copies a files f... | tools/deploySystem.py |
import os
import subprocess
import argparse
# the directory to mount the sd card to
BOOT_MNT = '/mnt/zynq/boot/'
GAMES_MNT = '/mnt/zynq/games'
# the names to copy the boot and mes files to on the sd card
BOOT_FILE = 'BOOT.bin'
MES_FILE = 'MES.bin'
def copy_file(src, dst):
"""
This function copies a files f... | 0.326808 | 0.169131 |
import requests
import threading
import time
from azure.cognitiveservices.speech import SpeechConfig, SpeechRecognizer, SpeechSynthesizer
speech_api_key = '<key>'
location = '<location>'
language = '<language>'
recognizer_config = SpeechConfig(subscription=speech_api_key,
region=locat... | 6-consumer/lessons/3-spoken-feedback/code-spoken-response/virtual-iot-device/smart-timer/app.py | import requests
import threading
import time
from azure.cognitiveservices.speech import SpeechConfig, SpeechRecognizer, SpeechSynthesizer
speech_api_key = '<key>'
location = '<location>'
language = '<language>'
recognizer_config = SpeechConfig(subscription=speech_api_key,
region=locat... | 0.374905 | 0.100084 |
from typing import Any, Optional, List, Tuple
from pybag.enum import Orient2D
from pybag.core import BBox
from bag.util.math import HalfInt
from bag.util.immutable import ImmutableSortedDict
from bag.layout.routing.grid import TrackSpec
from bag.layout.tech import TechInfo
from xbase.layout.data import LayoutInfo, ... | src/templates_cds_ff_mpt/res/tech.py |
from typing import Any, Optional, List, Tuple
from pybag.enum import Orient2D
from pybag.core import BBox
from bag.util.math import HalfInt
from bag.util.immutable import ImmutableSortedDict
from bag.layout.routing.grid import TrackSpec
from bag.layout.tech import TechInfo
from xbase.layout.data import LayoutInfo, ... | 0.898844 | 0.306929 |
from __future__ import absolute_import
from __future__ import division
from __future__ import print_function
from struct2tensor import expression
from struct2tensor import path
from struct2tensor import prensor
from struct2tensor.calculate_options import Options
from typing import FrozenSet, Mapping, Optional, Seq... | struct2tensor/expression_add.py | from __future__ import absolute_import
from __future__ import division
from __future__ import print_function
from struct2tensor import expression
from struct2tensor import path
from struct2tensor import prensor
from struct2tensor.calculate_options import Options
from typing import FrozenSet, Mapping, Optional, Seq... | 0.937455 | 0.366306 |
import torndb
conn = torndb.Connection(
host='127.0.0.1',
database='tornado_20191203',
user='root',
password='<PASSWORD>',
time_zone="+8:00" # 设置时区,不然有8小时的时差
)
# 插入单条记录
def insert_user(u_name, pwd):
row_id = conn.insert('insert into t_user values(null,"{0}","{1}",sysdate())'.format(u_name, ... | demos/12_torndb.py | import torndb
conn = torndb.Connection(
host='127.0.0.1',
database='tornado_20191203',
user='root',
password='<PASSWORD>',
time_zone="+8:00" # 设置时区,不然有8小时的时差
)
# 插入单条记录
def insert_user(u_name, pwd):
row_id = conn.insert('insert into t_user values(null,"{0}","{1}",sysdate())'.format(u_name, ... | 0.167083 | 0.131703 |
import pickle
from abc import abstractmethod
from threading import Thread
import pyrin.database.bulk.services as bulk_services
import pyrin.logging.services as logging_services
import pyrin.configuration.services as config_services
import pyrin.globalization.datetime.services as datetime_services
from pyrin.caching.... | src/pyrin/caching/local/handlers/base.py | import pickle
from abc import abstractmethod
from threading import Thread
import pyrin.database.bulk.services as bulk_services
import pyrin.logging.services as logging_services
import pyrin.configuration.services as config_services
import pyrin.globalization.datetime.services as datetime_services
from pyrin.caching.... | 0.731634 | 0.115711 |
import json
import sys
with open(sys.argv[1], "r") as f:
workflowresult = json.loads(f.read())
assert len(workflowresult.keys()) == 5
found_template = False
for key in workflowresult.keys():
if workflowresult[key]["class"] == "interpolate-qubit-operators":
found_template = True
assert workfl... | testing/data_validation/interpolate-qubit-operators.py | import json
import sys
with open(sys.argv[1], "r") as f:
workflowresult = json.loads(f.read())
assert len(workflowresult.keys()) == 5
found_template = False
for key in workflowresult.keys():
if workflowresult[key]["class"] == "interpolate-qubit-operators":
found_template = True
assert workfl... | 0.317426 | 0.34762 |
import torch
import torch.nn.functional as F
from torch.testing import assert_close
EPS = 1e-3
def batch_inner(x, y):
assert x.ndim == 2
assert x.shape == y.shape
return torch.einsum('bd,bd->b', x, y)
class IFVP():
def __init__(self, grads, block_size, damping, check=False):
assert grads.nd... | references/classification/ifvp.py | import torch
import torch.nn.functional as F
from torch.testing import assert_close
EPS = 1e-3
def batch_inner(x, y):
assert x.ndim == 2
assert x.shape == y.shape
return torch.einsum('bd,bd->b', x, y)
class IFVP():
def __init__(self, grads, block_size, damping, check=False):
assert grads.nd... | 0.692538 | 0.626238 |
from django.core.exceptions import PermissionDenied
from rest_framework import serializers
from rest_framework.relations import PrimaryKeyRelatedField
from api.models.role import Role
from api.models.user_profile import UserProfile
from api.services.user import update_roles, create_default_user_notification_settings
f... | backend/api/serializers/user.py | from django.core.exceptions import PermissionDenied
from rest_framework import serializers
from rest_framework.relations import PrimaryKeyRelatedField
from api.models.role import Role
from api.models.user_profile import UserProfile
from api.services.user import update_roles, create_default_user_notification_settings
f... | 0.710829 | 0.105441 |
from typing import Any, Dict
from ..convert.JsonConverter import JsonConverter
from ..validate import ValidationResultType
class ValidationResult:
"""
Result generated by schema validation
"""
def __init__(self, path: str = None, type: ValidationResultType = None, code: str = None, message: str = No... | pip_services3_commons/validate/ValidationResult.py | from typing import Any, Dict
from ..convert.JsonConverter import JsonConverter
from ..validate import ValidationResultType
class ValidationResult:
"""
Result generated by schema validation
"""
def __init__(self, path: str = None, type: ValidationResultType = None, code: str = None, message: str = No... | 0.932369 | 0.479626 |
import re
import six
import unittest
from geodata.addresses.entrances import *
from geodata.addresses.floors import *
from geodata.intersections.query import *
from geodata.addresses.po_boxes import *
from geodata.addresses.postcodes import *
from geodata.addresses.staircases import *
from geodata.addresses.units impo... | scripts/geodata/tests/test_address_configs.py | import re
import six
import unittest
from geodata.addresses.entrances import *
from geodata.addresses.floors import *
from geodata.intersections.query import *
from geodata.addresses.po_boxes import *
from geodata.addresses.postcodes import *
from geodata.addresses.staircases import *
from geodata.addresses.units impo... | 0.497803 | 0.553747 |
from __future__ import (
unicode_literals,
absolute_import,
print_function,
division,
)
import os
import io
import binascii
import unittest
import avb
import avb.utils
import glob
def iter_chunks(chunk_type):
chunk_dir = os.path.join(os.path.dirname(__file__), 'chunks', chunk_type, '*.chunk')
... | tests/test_chunks.py | from __future__ import (
unicode_literals,
absolute_import,
print_function,
division,
)
import os
import io
import binascii
import unittest
import avb
import avb.utils
import glob
def iter_chunks(chunk_type):
chunk_dir = os.path.join(os.path.dirname(__file__), 'chunks', chunk_type, '*.chunk')
... | 0.277082 | 0.167661 |
from flask import Blueprint, render_template, request, redirect, url_for, flash
from models import Food, Log, log_food
from datetime import datetime
main = Blueprint("main", __name__)
@main.route('/')
def index():
logs = Log.select().order_by(Log.date.desc())
log_info = []
for log in logs:
... | main/routes.py | from flask import Blueprint, render_template, request, redirect, url_for, flash
from models import Food, Log, log_food
from datetime import datetime
main = Blueprint("main", __name__)
@main.route('/')
def index():
logs = Log.select().order_by(Log.date.desc())
log_info = []
for log in logs:
... | 0.242744 | 0.08292 |
import santa
john = santa.Person('<NAME>', '<EMAIL>')
sally = santa.Person('<NAME>', '<EMAIL>')
linus = santa.Person('<NAME>', '<EMAIL>')
guido = santa.Person('<NAME>', '<EMAIL>')
def test_personhood():
names = ('<NAME>', '<NAME>', '<NAME>', '<NAME>')
addresses = ('<EMAIL>', '<EMAIL>', '<EMAIL>', '<EMAIL>')
... | tests.py | import santa
john = santa.Person('<NAME>', '<EMAIL>')
sally = santa.Person('<NAME>', '<EMAIL>')
linus = santa.Person('<NAME>', '<EMAIL>')
guido = santa.Person('<NAME>', '<EMAIL>')
def test_personhood():
names = ('<NAME>', '<NAME>', '<NAME>', '<NAME>')
addresses = ('<EMAIL>', '<EMAIL>', '<EMAIL>', '<EMAIL>')
... | 0.454714 | 0.496155 |
import math
import subprocess
import urllib.request
import os.path
import os
import shutil
def deg2num(lat_deg, lon_deg, zoom):
lat_rad = math.radians(lat_deg)
n = 2.0 ** zoom
xtile = int((lon_deg + 180.0) / 360.0 * n)
ytile = int((1.0 - math.asinh(math.tan(lat_rad)) / math.pi) / 2.0 * n)
return (xtile, yti... | OpenTopoMapDownloader.py |
import math
import subprocess
import urllib.request
import os.path
import os
import shutil
def deg2num(lat_deg, lon_deg, zoom):
lat_rad = math.radians(lat_deg)
n = 2.0 ** zoom
xtile = int((lon_deg + 180.0) / 360.0 * n)
ytile = int((1.0 - math.asinh(math.tan(lat_rad)) / math.pi) / 2.0 * n)
return (xtile, yti... | 0.341363 | 0.308763 |
from game_types import Player
from game_types import Move
from game_types import Point
from agents.human import Human
from agents.zero_agent import ZeroAgent
import utils
import game_types as game_types
DEBUG = False
class TestMCTS:
def __init__(self):
game_type = "MiniOmok"
rule_type = "OmokFree... | codes/tests/test_agent.py | from game_types import Player
from game_types import Move
from game_types import Point
from agents.human import Human
from agents.zero_agent import ZeroAgent
import utils
import game_types as game_types
DEBUG = False
class TestMCTS:
def __init__(self):
game_type = "MiniOmok"
rule_type = "OmokFree... | 0.558327 | 0.391522 |
from flask_wtf import FlaskForm
from flask_appbuilder.forms import DynamicForm
from wtforms import StringField, SubmitField, PasswordField, RadioField, HiddenField, SelectMultipleField, SelectField, IntegerField, TextAreaField
from wtforms.validators import Required, DataRequired, Length, EqualTo
class LoginForm(Flask... | ui/forms.py | from flask_wtf import FlaskForm
from flask_appbuilder.forms import DynamicForm
from wtforms import StringField, SubmitField, PasswordField, RadioField, HiddenField, SelectMultipleField, SelectField, IntegerField, TextAreaField
from wtforms.validators import Required, DataRequired, Length, EqualTo
class LoginForm(Flask... | 0.412175 | 0.238268 |
from math import sqrt, pi
import sys
from functions import *
class structure:
""" Element to create the parsing tree."""
def __init__(self):
""" Create a new structure with a list of deeper level entries. """
self.li = list()
self.counter = -1
def append(self, item, depth):
... | code/parser.py |
from math import sqrt, pi
import sys
from functions import *
class structure:
""" Element to create the parsing tree."""
def __init__(self):
""" Create a new structure with a list of deeper level entries. """
self.li = list()
self.counter = -1
def append(self, item, depth):
... | 0.54819 | 0.498779 |
class PetriNet():
def __init__(self):
self.places = []
self.transitions = []
self.input = []
self.output = []
def __str__(self):
pn = []
pn.append("Places: {}".format(self.places))
pn.append("Transitions: {}".format(self.transitions))
pn.appen... | pyalpha/petri_net.py | class PetriNet():
def __init__(self):
self.places = []
self.transitions = []
self.input = []
self.output = []
def __str__(self):
pn = []
pn.append("Places: {}".format(self.places))
pn.append("Transitions: {}".format(self.transitions))
pn.appen... | 0.352425 | 0.209066 |
import torch
import numpy as np
import rdkit.Chem as Chem
import class_predictor.graph.mol_features as mol_features
import pdb
# Supress warnings from rdkit
from rdkit import rdBase
from rdkit import RDLogger
rdBase.DisableLog('rdApp.error')
lg = RDLogger.logger()
lg.setLevel(RDLogger.ERROR)
class Atom:
def __... | class_predictor/graph/mol_graph.py | import torch
import numpy as np
import rdkit.Chem as Chem
import class_predictor.graph.mol_features as mol_features
import pdb
# Supress warnings from rdkit
from rdkit import rdBase
from rdkit import RDLogger
rdBase.DisableLog('rdApp.error')
lg = RDLogger.logger()
lg.setLevel(RDLogger.ERROR)
class Atom:
def __... | 0.830491 | 0.467575 |
from __future__ import absolute_import, division, print_function
from itertools import groupby
from beets import config
from beets.dbcore import Query, MatchQuery, AndQuery, OrQuery
from beets.dbcore.query import NotQuery
from beets.library import Album, Item, parse_query_string
from beets.plugins import BeetsPlugin
... | beetsplug/crossquery.py | from __future__ import absolute_import, division, print_function
from itertools import groupby
from beets import config
from beets.dbcore import Query, MatchQuery, AndQuery, OrQuery
from beets.dbcore.query import NotQuery
from beets.library import Album, Item, parse_query_string
from beets.plugins import BeetsPlugin
... | 0.797281 | 0.129816 |
import gym
from gym import spaces
import numpy as np
import os
from stable_baselines.results_plotter import load_results, ts2xy
from stable_baselines.common.callbacks import BaseCallback
class SaveOnBestTrainingRewardCallback(BaseCallback):
"""
Callback for saving a model (the check is done every ``check_freq`` s... | utils.py | import gym
from gym import spaces
import numpy as np
import os
from stable_baselines.results_plotter import load_results, ts2xy
from stable_baselines.common.callbacks import BaseCallback
class SaveOnBestTrainingRewardCallback(BaseCallback):
"""
Callback for saving a model (the check is done every ``check_freq`` s... | 0.683525 | 0.395981 |