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 numpy as np
import matplotlib.pyplot as plt
from ars_lib.ars import ARSAgent, Normalizer, Policy, ParallelWorker
from mini_bullet.minitaur_gym_env import MinitaurBulletEnv
from tg_lib.tg_policy import TGPolicy
import time
import torch
import os
def main():
""" The main() function. """
print("START... | spot_bullet/src/old_eval_scripts/tg_eval.py |
import numpy as np
import matplotlib.pyplot as plt
from ars_lib.ars import ARSAgent, Normalizer, Policy, ParallelWorker
from mini_bullet.minitaur_gym_env import MinitaurBulletEnv
from tg_lib.tg_policy import TGPolicy
import time
import torch
import os
def main():
""" The main() function. """
print("START... | 0.416797 | 0.27558 |
import torch
import torch.nn as nn
import torch.nn.functional as F
from mmdet.models.builder import build_loss, HEADS
from mmcv.cnn import normal_init
from mmcv.cnn import ConvModule
from mmcv.runner import force_fp32, auto_fp16
import cv2
import numpy as np
@HEADS.register_module()
class InstanceMaskAttentionHead(nn... | davarocr/davarocr/davar_spotting/models/seg_heads/instance_mask_att_head.py | import torch
import torch.nn as nn
import torch.nn.functional as F
from mmdet.models.builder import build_loss, HEADS
from mmcv.cnn import normal_init
from mmcv.cnn import ConvModule
from mmcv.runner import force_fp32, auto_fp16
import cv2
import numpy as np
@HEADS.register_module()
class InstanceMaskAttentionHead(nn... | 0.947003 | 0.525734 |
import pprint
import re # noqa: F401
import six
class ItemCounts(object):
"""NOTE: This class is auto generated by the swagger code generator program.
Do not edit the class manually.
"""
"""
Attributes:
swagger_types (dict): The key is attribute name
and the val... | embyapi/models/item_counts.py | import pprint
import re # noqa: F401
import six
class ItemCounts(object):
"""NOTE: This class is auto generated by the swagger code generator program.
Do not edit the class manually.
"""
"""
Attributes:
swagger_types (dict): The key is attribute name
and the val... | 0.621311 | 0.103386 |
class SketchKnowledgeBase(object):
'''
SketchKnowledgeBase
'''
def __init__(self):
super(SketchKnowledgeBase, self).__init__()
self.entities = {}
self.actions = {}
# Reversed IS-A actions
self.asi = {}
self._idcounter = {}
def add_entity(self, entity... | knowledge_repr.py | class SketchKnowledgeBase(object):
'''
SketchKnowledgeBase
'''
def __init__(self):
super(SketchKnowledgeBase, self).__init__()
self.entities = {}
self.actions = {}
# Reversed IS-A actions
self.asi = {}
self._idcounter = {}
def add_entity(self, entity... | 0.414425 | 0.141252 |
from ..builder import DETECTORS
from .gl_two_stage import GLTwoStage
import torch
import torch.nn as nn
import cv2
import numpy as np
import mmcv
@DETECTORS.register_module
class GlobalGLGA(GLTwoStage):
def __init__(self,
p_size,
batch_size,
mode,
... | mmdet/models/detectors/global_gl_ga.py | from ..builder import DETECTORS
from .gl_two_stage import GLTwoStage
import torch
import torch.nn as nn
import cv2
import numpy as np
import mmcv
@DETECTORS.register_module
class GlobalGLGA(GLTwoStage):
def __init__(self,
p_size,
batch_size,
mode,
... | 0.82559 | 0.265803 |
import pkg_resources
import sys
import os
import shutil
import subprocess
import argparse
from .shared_methods import set_up_logging
helpstring = """
Welcome to the ribo try! Here we test the integration of several parts of the
riboSeed pipeline. First, `ribo run` is performed on the included test
dataset. Then, e... | riboSeed/riboTry.py |
import pkg_resources
import sys
import os
import shutil
import subprocess
import argparse
from .shared_methods import set_up_logging
helpstring = """
Welcome to the ribo try! Here we test the integration of several parts of the
riboSeed pipeline. First, `ribo run` is performed on the included test
dataset. Then, e... | 0.346541 | 0.186817 |
import logging
from .base import GeckoAutomationBase
from ..driver import GeckoWatercareProtocolHandler
from ..const import GeckoConstants
_LOGGER = logging.getLogger(__name__)
class GeckoWaterCare(GeckoAutomationBase):
""" Watercare manangement class """
def __init__(self, facade):
super().__init... | gecko/geckolib/automation/watercare.py |
import logging
from .base import GeckoAutomationBase
from ..driver import GeckoWatercareProtocolHandler
from ..const import GeckoConstants
_LOGGER = logging.getLogger(__name__)
class GeckoWaterCare(GeckoAutomationBase):
""" Watercare manangement class """
def __init__(self, facade):
super().__init... | 0.753376 | 0.077518 |
from django.shortcuts import render
from django.contrib.auth.decorators import login_required, permission_required
from django.contrib.auth import get_user_model
# utils
from .utils import get_context, get_hitmans, get_role
from .constants import FAILED, HITMAN, MANAGER, BOSS, COMPLETED
# Models
from .models import Hit... | src/spy_app/views.py | from django.shortcuts import render
from django.contrib.auth.decorators import login_required, permission_required
from django.contrib.auth import get_user_model
# utils
from .utils import get_context, get_hitmans, get_role
from .constants import FAILED, HITMAN, MANAGER, BOSS, COMPLETED
# Models
from .models import Hit... | 0.274157 | 0.090735 |
import decimal
import logging
import enum
import arrow
from dos.parsers import extract_arrow, extract_number
LOGGER = logging.getLogger()
LOGGER.setLevel(logging.CRITICAL)
NO_VALUE = object()
class OpenAPIPropType(enum.Enum):
INTEGER = "integer"
NUMBER = "number"
STRING = "string"
BOOLEAN = "bool... | src/dos/prop.py | import decimal
import logging
import enum
import arrow
from dos.parsers import extract_arrow, extract_number
LOGGER = logging.getLogger()
LOGGER.setLevel(logging.CRITICAL)
NO_VALUE = object()
class OpenAPIPropType(enum.Enum):
INTEGER = "integer"
NUMBER = "number"
STRING = "string"
BOOLEAN = "bool... | 0.599837 | 0.160332 |
import logging
import unittest
import mock
from qgis.core import QgsFeature, QgsFeatureRequest, QgsVectorLayer
from catatom2osm.app import QgsSingleton
from catatom2osm.geo.geometry import Geometry
from catatom2osm.geo.layer.polygon import PolygonLayer
from catatom2osm.geo.point import Point
qgs = QgsSingleton()
m_l... | test/geo/layer/test_polygon.py | import logging
import unittest
import mock
from qgis.core import QgsFeature, QgsFeatureRequest, QgsVectorLayer
from catatom2osm.app import QgsSingleton
from catatom2osm.geo.geometry import Geometry
from catatom2osm.geo.layer.polygon import PolygonLayer
from catatom2osm.geo.point import Point
qgs = QgsSingleton()
m_l... | 0.679498 | 0.516169 |
import pytest
from time import time
from base10.base import Dialect, Metric, Reader, Writer
from base10.exceptions import DialectError
class TestDialects:
def test_dialect_construction(self):
assert isinstance(Dialect(), Dialect)
def test_dialect_from_string_exception(self):
dialect = Dialec... | base10/test/test_base.py | import pytest
from time import time
from base10.base import Dialect, Metric, Reader, Writer
from base10.exceptions import DialectError
class TestDialects:
def test_dialect_construction(self):
assert isinstance(Dialect(), Dialect)
def test_dialect_from_string_exception(self):
dialect = Dialec... | 0.826397 | 0.603172 |
import numpy as np
from tqdm import tqdm
import h5py
from pathlib import Path
from urllib.request import urlretrieve
from zipfile import ZipFile
from scipy.io import loadmat
from hsdatasets.utils import TqdmUpTo
DATASETS_CONFIG = {
'HyKo2-VIS': {
'name': 'vis_annotated.zip',
'url': 'ht... | hsdatasets/groundbased/prep.py | import numpy as np
from tqdm import tqdm
import h5py
from pathlib import Path
from urllib.request import urlretrieve
from zipfile import ZipFile
from scipy.io import loadmat
from hsdatasets.utils import TqdmUpTo
DATASETS_CONFIG = {
'HyKo2-VIS': {
'name': 'vis_annotated.zip',
'url': 'ht... | 0.150216 | 0.207757 |
import sys
import time
import os
import socket
import errno
#----------------------------------------------------------------------
# FlashPolicy
#----------------------------------------------------------------------
class policysvr (object):
def __init__ (self):
self._clients = {}
self._sock4 = None
self._s... | cannon/bin/flashsvr.py | import sys
import time
import os
import socket
import errno
#----------------------------------------------------------------------
# FlashPolicy
#----------------------------------------------------------------------
class policysvr (object):
def __init__ (self):
self._clients = {}
self._sock4 = None
self._s... | 0.0713 | 0.066509 |
from y2h.parser.base import BaseParser
from y2h.parser.factory import ElemParserFactory
TABLE_STYLE_CLASSES = {
'default': 'table',
'striped': 'table table-striped',
'bordered': 'table table-bordered',
'hover': 'table table-hover',
'condensed': 'table table-condensed',
}
... | y2h/parser/elems/table.py | from y2h.parser.base import BaseParser
from y2h.parser.factory import ElemParserFactory
TABLE_STYLE_CLASSES = {
'default': 'table',
'striped': 'table table-striped',
'bordered': 'table table-bordered',
'hover': 'table table-hover',
'condensed': 'table table-condensed',
}
... | 0.444083 | 0.159217 |
from django.test import TestCase
from core import factories, models
from core.models.base import DeadlineFrequency, PieceType, Phase, Season
from core.tests import DiplomacyTestCaseMixin
class TestTurn(TestCase, DiplomacyTestCaseMixin):
def setUp(self):
self.variant = models.Variant.objects.get(id='stan... | core/tests/test_turn.py | from django.test import TestCase
from core import factories, models
from core.models.base import DeadlineFrequency, PieceType, Phase, Season
from core.tests import DiplomacyTestCaseMixin
class TestTurn(TestCase, DiplomacyTestCaseMixin):
def setUp(self):
self.variant = models.Variant.objects.get(id='stan... | 0.570331 | 0.306268 |
from elasticsearch.client.utils import AddonClient, query_params, _make_path, SKIP_IN_PATH
# COPYPASTA ingredient list:
# https://github.com/elastic/elasticsearch-py/blob/1.x/elasticsearch/client/__init__.py#L809
# https://github.com/elastic/elasticsearch-watcher-py/blob/master/elasticsearch_watcher/watcher.py
class... | elasticsearch_delete_by_query/plugin.py | from elasticsearch.client.utils import AddonClient, query_params, _make_path, SKIP_IN_PATH
# COPYPASTA ingredient list:
# https://github.com/elastic/elasticsearch-py/blob/1.x/elasticsearch/client/__init__.py#L809
# https://github.com/elastic/elasticsearch-watcher-py/blob/master/elasticsearch_watcher/watcher.py
class... | 0.920607 | 0.221014 |
from rest_framework import serializers
from .models import Article, Tag
from authors.apps.articles.relations import TagsRelation
class ArticleSerializers(serializers.ModelSerializer):
def format_date(self, date):
return date.strftime('%d %b %Y %H:%M:%S')
def to_representation(self, instance):
... | authors/apps/articles/serializers.py | from rest_framework import serializers
from .models import Article, Tag
from authors.apps.articles.relations import TagsRelation
class ArticleSerializers(serializers.ModelSerializer):
def format_date(self, date):
return date.strftime('%d %b %Y %H:%M:%S')
def to_representation(self, instance):
... | 0.849129 | 0.197232 |
"""Provide tools for managing blade geometries."""
from io import BytesIO
from typing import Iterable, Sequence, Union
import numpy as np
import stl
from numpy.typing import NDArray
from .io import generic_vertex_ordering
from .profile import Airfoil
class Blade:
"""Define a simple, generic blade object."""
... | klingo/blade.py | """Provide tools for managing blade geometries."""
from io import BytesIO
from typing import Iterable, Sequence, Union
import numpy as np
import stl
from numpy.typing import NDArray
from .io import generic_vertex_ordering
from .profile import Airfoil
class Blade:
"""Define a simple, generic blade object."""
... | 0.960676 | 0.643917 |
from mock import MagicMock, patch
from nose.plugins.attrib import attr
from ion.agents.data.handlers.handler_utils import _get_type, list_file_info, \
list_file_info_http, list_file_info_ftp, list_file_info_fs, \
get_time_from_filename, calculate_iteration_count, get_sbuffer
from pyon.util.unit_test import Pyon... | ion/agents/data/handlers/test/test_handler_utils.py | from mock import MagicMock, patch
from nose.plugins.attrib import attr
from ion.agents.data.handlers.handler_utils import _get_type, list_file_info, \
list_file_info_http, list_file_info_ftp, list_file_info_fs, \
get_time_from_filename, calculate_iteration_count, get_sbuffer
from pyon.util.unit_test import Pyon... | 0.516839 | 0.113359 |
from optparse import OptionParser
import pysam
import statistics
class Molecule:
def __init__(self, rname, start, end, \
newMolecID, barcode, \
interArrivals, count, \
mapqMedian, asMedian, nmMedian):
self.rname = rname
self.start = start
... | MolecEst/MolecLenEst.py | from optparse import OptionParser
import pysam
import statistics
class Molecule:
def __init__(self, rname, start, end, \
newMolecID, barcode, \
interArrivals, count, \
mapqMedian, asMedian, nmMedian):
self.rname = rname
self.start = start
... | 0.358016 | 0.195844 |
import sys
from PyQt5 import uic, QtCore, QtGui
from PyQt5.QtWidgets import *
import build_db
import datetime
class CredibilityKnowledge:
def __init__(self):
self.ui = uic.loadUi("./ui/credibility.ui") # 组件名称查看credibility.ui
self.set_ui()
self.show_knowledge('', '') # 展示所有知识
... | sourcecode/credibilityKnowledge.py | import sys
from PyQt5 import uic, QtCore, QtGui
from PyQt5.QtWidgets import *
import build_db
import datetime
class CredibilityKnowledge:
def __init__(self):
self.ui = uic.loadUi("./ui/credibility.ui") # 组件名称查看credibility.ui
self.set_ui()
self.show_knowledge('', '') # 展示所有知识
... | 0.121451 | 0.059565 |
import os
from time import sleep
import subprocess
import logging
import glob
import db
import keystoneclient.v2_0.client as ksclient
from novaclient import client as novaclient
import glanceclient
from credentials import get_keystone_creds
from credentials import get_nova_creds
from dest_credentials import get_dest_k... | main.py |
import os
from time import sleep
import subprocess
import logging
import glob
import db
import keystoneclient.v2_0.client as ksclient
from novaclient import client as novaclient
import glanceclient
from credentials import get_keystone_creds
from credentials import get_nova_creds
from dest_credentials import get_dest_k... | 0.17824 | 0.068475 |
import sqlite3
from time import time
import psutil
import os
from AnkiTools.tools.path import get_collection_path
from AnkiTools.tools.create import AnkiContentCreator
from AnkiTools.tools.write import write_anki_json, write_anki_table, write_anki_schema
from AnkiTools.tools.read import read_anki_json, read_anki_table... | AnkiTools/api/app.py | import sqlite3
from time import time
import psutil
import os
from AnkiTools.tools.path import get_collection_path
from AnkiTools.tools.create import AnkiContentCreator
from AnkiTools.tools.write import write_anki_json, write_anki_table, write_anki_schema
from AnkiTools.tools.read import read_anki_json, read_anki_table... | 0.286269 | 0.166472 |
import discord
import discord.ext.commands as commands
import random
import sys
import os
import requests
import asyncio
import logging
import threading
sys.path.insert(0, "../")
import util
class Streets(commands.Cog):
def __init__(self, bot, timeouts, generic_responses):
self.logger = logging.getLogger... | commands/streets.py | import discord
import discord.ext.commands as commands
import random
import sys
import os
import requests
import asyncio
import logging
import threading
sys.path.insert(0, "../")
import util
class Streets(commands.Cog):
def __init__(self, bot, timeouts, generic_responses):
self.logger = logging.getLogger... | 0.21428 | 0.079353 |
import sys
import click
from . import fplapi
from . import configure as conf
from .cliprinter import out
from .cliprinter import pretty_league
from .cliprinter import pretty_liveleague
from .cliprinter import pretty_leagues
from .cliprinter import pretty_picks_info
from .cliprinter import pretty_picks_players
from .cli... | fplcli/cli.py | import sys
import click
from . import fplapi
from . import configure as conf
from .cliprinter import out
from .cliprinter import pretty_league
from .cliprinter import pretty_liveleague
from .cliprinter import pretty_leagues
from .cliprinter import pretty_picks_info
from .cliprinter import pretty_picks_players
from .cli... | 0.367384 | 0.071949 |
import json
import pytest
from rest_framework import status
from django.conf import settings
from usaspending_api.common.experimental_api_flags import ELASTICSEARCH_HEADER_VALUE, EXPERIMENTAL_API_HEADER
@pytest.mark.django_db
def test_elasticsearch_headers(client, monkeypatch, elasticsearch_transaction_index):
... | usaspending_api/search/tests/integration/spending_by_category/test_elasticsearch_header.py | import json
import pytest
from rest_framework import status
from django.conf import settings
from usaspending_api.common.experimental_api_flags import ELASTICSEARCH_HEADER_VALUE, EXPERIMENTAL_API_HEADER
@pytest.mark.django_db
def test_elasticsearch_headers(client, monkeypatch, elasticsearch_transaction_index):
... | 0.461259 | 0.204521 |
import functools
import os
import time
from absl import logging
from clu import metric_writers
import flax
import jax
import jax.numpy as jnp
import ml_collections
import numpy as np
import tensorflow as tf
from vit_jax import checkpoint
from vit_jax import input_pipeline
from vit_jax import models
from vit_jax impo... | vit_jax/train.py |
import functools
import os
import time
from absl import logging
from clu import metric_writers
import flax
import jax
import jax.numpy as jnp
import ml_collections
import numpy as np
import tensorflow as tf
from vit_jax import checkpoint
from vit_jax import input_pipeline
from vit_jax import models
from vit_jax impo... | 0.747432 | 0.259334 |
import pygame
from settings import *
import random
class Cell:
def __init__(self, game, x, y, bombs):
self.game = game
self.x = x
self.y = y
self.i = x // TILESIZE
self.j = y // TILESIZE
self.revelada = False
self.bomba = False
self.bombas_total = bo... | src/cell.py | import pygame
from settings import *
import random
class Cell:
def __init__(self, game, x, y, bombs):
self.game = game
self.x = x
self.y = y
self.i = x // TILESIZE
self.j = y // TILESIZE
self.revelada = False
self.bomba = False
self.bombas_total = bo... | 0.191101 | 0.337722 |
from torch import nn
from ..layers import TFEncoder, TFDecoder
from ..utils.nn import LabelSmoothingLoss
from . import SimultaneousNMT
class SimultaneousTFNMT(SimultaneousNMT):
def __init__(self, opts):
"""
Creates a SimultaneousNMTTransformer.
:param opts: The options.
"""
... | pysimt/models/snmt_tf.py | from torch import nn
from ..layers import TFEncoder, TFDecoder
from ..utils.nn import LabelSmoothingLoss
from . import SimultaneousNMT
class SimultaneousTFNMT(SimultaneousNMT):
def __init__(self, opts):
"""
Creates a SimultaneousNMTTransformer.
:param opts: The options.
"""
... | 0.951222 | 0.361165 |
from dataclasses import dataclass
from typing import List, Literal, Mapping, Set
from kgdata.wikidata.models.wdentity import WDEntity
import orjson
from kgdata.config import WIKIDATA_DIR
from kgdata.wikidata.models.multilingual import (
MultiLingualString,
MultiLingualStringList,
)
from sm.misc.deser import d... | kgdata/wikidata/models/wdproperty.py | from dataclasses import dataclass
from typing import List, Literal, Mapping, Set
from kgdata.wikidata.models.wdentity import WDEntity
import orjson
from kgdata.config import WIKIDATA_DIR
from kgdata.wikidata.models.multilingual import (
MultiLingualString,
MultiLingualStringList,
)
from sm.misc.deser import d... | 0.826782 | 0.290116 |
"""Client and server classes corresponding to protobuf-defined services."""
import grpc
from github.com.metaprov.modelaapi.services.labelingpipelinerun.v1 import labelingpipelinerun_pb2 as github_dot_com_dot_metaprov_dot_modelaapi_dot_services_dot_labelingpipelinerun_dot_v1_dot_labelingpipelinerun__pb2
class Labelin... | lang/python/github/com/metaprov/modelaapi/services/labelingpipelinerun/v1/labelingpipelinerun_pb2_grpc.py | """Client and server classes corresponding to protobuf-defined services."""
import grpc
from github.com.metaprov.modelaapi.services.labelingpipelinerun.v1 import labelingpipelinerun_pb2 as github_dot_com_dot_metaprov_dot_modelaapi_dot_services_dot_labelingpipelinerun_dot_v1_dot_labelingpipelinerun__pb2
class Labelin... | 0.760562 | 0.093761 |
import sys
import click
from tabulate import tabulate
from . import admin
from ...session import Session, is_legacy_server
from ..pretty import print_error
@admin.command()
@click.option('-i', '--id', 'agent_id', required=True,
help='The agent Id to inspect.')
def agent(agent_id):
'''
Show the... | src/ai/backend/client/cli/admin/agents.py | import sys
import click
from tabulate import tabulate
from . import admin
from ...session import Session, is_legacy_server
from ..pretty import print_error
@admin.command()
@click.option('-i', '--id', 'agent_id', required=True,
help='The agent Id to inspect.')
def agent(agent_id):
'''
Show the... | 0.215351 | 0.122944 |
__author__ = '<NAME> (yy(at)rikkyo.ac.jp)'
__version__= '1.0'
import sys
import os
import inspect
from absl import app, flags
from typing import Union, Dict, List, Tuple
import numpy as np
from astropy.io import fits as iofits
from astropy.coordinates import Angle
from regions import read_ds9 as read_ds9_region
fr... | astro/linux/xismkreg.py |
__author__ = '<NAME> (yy(at)rikkyo.ac.jp)'
__version__= '1.0'
import sys
import os
import inspect
from absl import app, flags
from typing import Union, Dict, List, Tuple
import numpy as np
from astropy.io import fits as iofits
from astropy.coordinates import Angle
from regions import read_ds9 as read_ds9_region
fr... | 0.535098 | 0.356139 |
import os
import logging
import datetime
from dateutil.tz import gettz
import math
from decimal import Decimal
from common import (line, utils)
import members_card_const
# 環境変数の宣言
LIFF_ID = os.getenv('LIFF_ID')
LOGGER_LEVEL = os.getenv("LOGGER_LEVEL")
# ログ出力の設定
logger = logging.getLogger()
if LOG... | backend/APP/members_card/send_message.py | import os
import logging
import datetime
from dateutil.tz import gettz
import math
from decimal import Decimal
from common import (line, utils)
import members_card_const
# 環境変数の宣言
LIFF_ID = os.getenv('LIFF_ID')
LOGGER_LEVEL = os.getenv("LOGGER_LEVEL")
# ログ出力の設定
logger = logging.getLogger()
if LOG... | 0.417271 | 0.171165 |
import unittest
from vgio.quake.tests.basecase import TestCase
from vgio.quake import protocol
class TestProtocolReadWrite(TestCase):
def test_bad_message(self):
protocol.Bad.write(self.buff)
self.buff.seek(0)
protocol.Bad.read(self.buff)
def test_nop_message(self):
protocol.... | vgio/quake/tests/test_protocol.py | import unittest
from vgio.quake.tests.basecase import TestCase
from vgio.quake import protocol
class TestProtocolReadWrite(TestCase):
def test_bad_message(self):
protocol.Bad.write(self.buff)
self.buff.seek(0)
protocol.Bad.read(self.buff)
def test_nop_message(self):
protocol.... | 0.588061 | 0.210807 |
from .client import Client
class Ftp(Client):
"""Ftp管理
"""
def web_ftp_list(self, page='1', limit='15', type='-1', order='id desc', tojs='', search=''):
"""获取网站FTP列表
Args:
page (str, optional): 当前分页. Defaults to '1'.
limit (str, optional): 取出的数据行数. Defaults to '15'... | pybt/ftp.py | from .client import Client
class Ftp(Client):
"""Ftp管理
"""
def web_ftp_list(self, page='1', limit='15', type='-1', order='id desc', tojs='', search=''):
"""获取网站FTP列表
Args:
page (str, optional): 当前分页. Defaults to '1'.
limit (str, optional): 取出的数据行数. Defaults to '15'... | 0.403214 | 0.208864 |
def get_CUDA(vectorSize = 10, momentums = [0.,0.], shifts = [0.35,0.65], sigmas = [0.05, 0.05] , **kwargs):
if len(shifts)%2==1:
print "Must have even number of wavefunctions (pairs). Quitting..."
quit()
if (len(momentums)!= len(shifts)) or (len(momentums)!= len(sigmas)) or (len(shifts)!= len(si... | Code/Initialization/CUDA_Initializations/Default/Gaussians_1D_2P.py | def get_CUDA(vectorSize = 10, momentums = [0.,0.], shifts = [0.35,0.65], sigmas = [0.05, 0.05] , **kwargs):
if len(shifts)%2==1:
print "Must have even number of wavefunctions (pairs). Quitting..."
quit()
if (len(momentums)!= len(shifts)) or (len(momentums)!= len(sigmas)) or (len(shifts)!= len(si... | 0.297266 | 0.45641 |
import os
import numpy
from sklearn.model_selection import train_test_split
from sklearn.base import ClusterMixin
from sklearn.metrics import silhouette_score
from pyquickhelper.loghelper import noLOG
from pyquickhelper.benchhelper import GridBenchMark
class MlGridBenchMark(GridBenchMark):
"""
The class tests... | src/mlstatpy/ml/ml_grid_benchmark.py | import os
import numpy
from sklearn.model_selection import train_test_split
from sklearn.base import ClusterMixin
from sklearn.metrics import silhouette_score
from pyquickhelper.loghelper import noLOG
from pyquickhelper.benchhelper import GridBenchMark
class MlGridBenchMark(GridBenchMark):
"""
The class tests... | 0.782704 | 0.375306 |
import os
import re
from fabric.api import hide, lcd, local, prompt, settings
PROJECT_PATH = os.path.dirname(os.path.realpath(__file__))
def test():
"""Runs the blingalytics test suite."""
os.environ['PYTHONPATH'] = PROJECT_PATH
with settings(hide('warnings'), warn_only=True):
local('python tes... | fabfile.py | import os
import re
from fabric.api import hide, lcd, local, prompt, settings
PROJECT_PATH = os.path.dirname(os.path.realpath(__file__))
def test():
"""Runs the blingalytics test suite."""
os.environ['PYTHONPATH'] = PROJECT_PATH
with settings(hide('warnings'), warn_only=True):
local('python tes... | 0.371023 | 0.090293 |
import sys
from time import sleep
from cadence.clock_decision_context import DEFAULT_VERSION
from cadence.workerfactory import WorkerFactory
from cadence.workflow import workflow_method, Workflow, WorkflowClient
TASK_LIST = "TestWorkflowGetVersion"
DOMAIN = "sample"
v1_hits = 0
v2_hits = 0
version_found_in_v2_step_... | cadence/tests/test_workflow_get_version.py | import sys
from time import sleep
from cadence.clock_decision_context import DEFAULT_VERSION
from cadence.workerfactory import WorkerFactory
from cadence.workflow import workflow_method, Workflow, WorkflowClient
TASK_LIST = "TestWorkflowGetVersion"
DOMAIN = "sample"
v1_hits = 0
v2_hits = 0
version_found_in_v2_step_... | 0.237841 | 0.167015 |
from datetime import datetime, timedelta
import json
import numpy as np
import os
from PIL import Image, ImageTk
import tkinter as tk
from utils.downloading import SH_TCI_retrieve_successor
from utils.utils import rows_to_pairs, consolidate_name
class ImagePanel(tk.Canvas):
def __init__(self, master, img):
... | utils/gui.py |
from datetime import datetime, timedelta
import json
import numpy as np
import os
from PIL import Image, ImageTk
import tkinter as tk
from utils.downloading import SH_TCI_retrieve_successor
from utils.utils import rows_to_pairs, consolidate_name
class ImagePanel(tk.Canvas):
def __init__(self, master, img):
... | 0.334481 | 0.213459 |
import torch
import torch.nn
import torch.nn.functional as F
from typing import Dict, Any
from dataclasses import dataclass
from ..common import separate_output_digits
from ..result import Result
from ..model_interface import ModelInterface
@dataclass
class TupleRunResult(Result):
reference_order: torch.Tensor
... | interfaces/recurrent/tuple_arithmetic.py | import torch
import torch.nn
import torch.nn.functional as F
from typing import Dict, Any
from dataclasses import dataclass
from ..common import separate_output_digits
from ..result import Result
from ..model_interface import ModelInterface
@dataclass
class TupleRunResult(Result):
reference_order: torch.Tensor
... | 0.918224 | 0.497437 |
import logging
import json
from ..contents import *
from azure.iot.device import Message
from azure.iot.device import MethodResponse
logger = logging.getLogger(__name__)
class IoTHubDeviceClient:
def set_iot_hub_device_client(self, client):
self.__iot_hub_device_client = client
async def connect(sel... | mj_azure_iot_pnp_device/device/iothub_device_client.py | import logging
import json
from ..contents import *
from azure.iot.device import Message
from azure.iot.device import MethodResponse
logger = logging.getLogger(__name__)
class IoTHubDeviceClient:
def set_iot_hub_device_client(self, client):
self.__iot_hub_device_client = client
async def connect(sel... | 0.497803 | 0.073099 |
from datetime import datetime
class base():
def identify(self, fields):
return all(elem in fields for elem in list(self.fields_map.keys())[:-4]) # last 4 keys are optional
def txn_from_checking(self, data):
return data == self._from_checking
def txn_currency_conversion(self, data):
... | beancount_paypal/lang.py | from datetime import datetime
class base():
def identify(self, fields):
return all(elem in fields for elem in list(self.fields_map.keys())[:-4]) # last 4 keys are optional
def txn_from_checking(self, data):
return data == self._from_checking
def txn_currency_conversion(self, data):
... | 0.719285 | 0.506958 |
from collections import OrderedDict
import numpy as np
import os
import torch
def create_utt2spkid_pairs(utt2spkid):
_utt2spkid = OrderedDict()
with open(utt2spkid, 'r') as u:
for line in u:
utt, spk = line.split()
_utt2spkid[utt] = int(spk)
return _utt2spkid
def create_u... | espnet2/sid/extractor/utils.py | from collections import OrderedDict
import numpy as np
import os
import torch
def create_utt2spkid_pairs(utt2spkid):
_utt2spkid = OrderedDict()
with open(utt2spkid, 'r') as u:
for line in u:
utt, spk = line.split()
_utt2spkid[utt] = int(spk)
return _utt2spkid
def create_u... | 0.201499 | 0.235361 |
import scipy.signal as s
import numpy as np
import matplotlib.pyplot as plt
import pyabf
from patch_clamp import database as db
QUERY = """SELECT metadata.fname,
metadata.cell_side,
metadata.cell_n,
metadata.mouse_id,
metadata.treatment_group AS treatment,
peaks... | patch_clamp/ap_analysis.py | import scipy.signal as s
import numpy as np
import matplotlib.pyplot as plt
import pyabf
from patch_clamp import database as db
QUERY = """SELECT metadata.fname,
metadata.cell_side,
metadata.cell_n,
metadata.mouse_id,
metadata.treatment_group AS treatment,
peaks... | 0.517571 | 0.429848 |
import http.server
import time
import threading
import io
import subprocess
import os
import numpy as np
from PIL import Image, ImageChops
from selenium import webdriver
# Set to true to create a new set of reference images
CREATE_REF = False
# Run web server
print("Starting web server...")
os.chdir(os.path.dirname... | tests/run_tests.py | import http.server
import time
import threading
import io
import subprocess
import os
import numpy as np
from PIL import Image, ImageChops
from selenium import webdriver
# Set to true to create a new set of reference images
CREATE_REF = False
# Run web server
print("Starting web server...")
os.chdir(os.path.dirname... | 0.378804 | 0.146423 |
import time, pygame, sys, os, shutil, derpapi
os.environ['SDL_VIDEO_WINDOW_POS'] = "%d,%d" % (0,0)
pygame.init()
screen = pygame.display.set_mode([480,320], pygame.NOFRAME)
pygame.display.flip()
derpapi.store('BOOT', data=time.time())
pygame.mouse.set_cursor(*pygame.cursors.diamond)
pygame.mouse.set_visible(... | DerPi/main_os.py | import time, pygame, sys, os, shutil, derpapi
os.environ['SDL_VIDEO_WINDOW_POS'] = "%d,%d" % (0,0)
pygame.init()
screen = pygame.display.set_mode([480,320], pygame.NOFRAME)
pygame.display.flip()
derpapi.store('BOOT', data=time.time())
pygame.mouse.set_cursor(*pygame.cursors.diamond)
pygame.mouse.set_visible(... | 0.038421 | 0.167934 |
import pytest
from support.socket import DummySocketIO
from core.constants import CellEvents, CellExecutionStatus
from ..socket import LocalSocketIO, CellEventsSocket
__author__ = '<NAME> (<EMAIL>)'
@pytest.mark.unit
@pytest.mark.utils
def test_local_socketio(mocker):
gsio = DummySocketIO()
mocked = mocke... | core/utils/tests/test_socket.py | import pytest
from support.socket import DummySocketIO
from core.constants import CellEvents, CellExecutionStatus
from ..socket import LocalSocketIO, CellEventsSocket
__author__ = '<NAME> (<EMAIL>)'
@pytest.mark.unit
@pytest.mark.utils
def test_local_socketio(mocker):
gsio = DummySocketIO()
mocked = mocke... | 0.545528 | 0.4206 |
import os
import serial
import pysynth as ps
import paho.mqtt.client as mqtt
SERIAL_PORT = '/dev/ttyACM0'
SERIAL_RATE = 115200
MQTT_BROKER = "mqtt.eclipse.org"
MQTT_PORT = 1883
MQTT_PUB_TOPIC = "kuviyam/chandrasekar/piano"
keystate0 = [False] * 12
keystate1 = [False] * 12
keystate2 = [False] * 12
oct_cur = 0
oct_... | Arduino-python-piano/python_code/keyboard_mqtt_publish_notes.py |
import os
import serial
import pysynth as ps
import paho.mqtt.client as mqtt
SERIAL_PORT = '/dev/ttyACM0'
SERIAL_RATE = 115200
MQTT_BROKER = "mqtt.eclipse.org"
MQTT_PORT = 1883
MQTT_PUB_TOPIC = "kuviyam/chandrasekar/piano"
keystate0 = [False] * 12
keystate1 = [False] * 12
keystate2 = [False] * 12
oct_cur = 0
oct_... | 0.196441 | 0.187616 |
from kivy.app import App
from kivy.base import runTouchApp
from kivy.lang import Builder
from kivy.properties import (
ObjectProperty,
ListProperty,
StringProperty,
NumericProperty,
Clock,
partial,
)
from kivy.uix.boxlayout import BoxLayout
from kivy.uix.textinput import TextInput
import os
impo... | src/waclient/console.py | from kivy.app import App
from kivy.base import runTouchApp
from kivy.lang import Builder
from kivy.properties import (
ObjectProperty,
ListProperty,
StringProperty,
NumericProperty,
Clock,
partial,
)
from kivy.uix.boxlayout import BoxLayout
from kivy.uix.textinput import TextInput
import os
impo... | 0.406862 | 0.118487 |
import os,sys,json,redis
from ssh import SSH_SSH
from ssh_error import SSHError
import threading
import ssh_settings
r = redis.StrictRedis(host=ssh_settings.redisip, port=ssh_settings.redisport, db=0)
class SSHControler(object):
def __init__(self):
self.SSH = SSH_SSH()
def controler_center(self, para... | devops/ops/views/ssh_module_controller.py | import os,sys,json,redis
from ssh import SSH_SSH
from ssh_error import SSHError
import threading
import ssh_settings
r = redis.StrictRedis(host=ssh_settings.redisip, port=ssh_settings.redisport, db=0)
class SSHControler(object):
def __init__(self):
self.SSH = SSH_SSH()
def controler_center(self, para... | 0.047316 | 0.055336 |
import unittest
import time
from selenium import webdriver
from selenium.webdriver.common.keys import Keys
from selenium.common.exceptions import NoSuchElementException
class TC_Renter_SuccessfulLogin(unittest.TestCase):
@classmethod
def setUp(self):
self.driver = webdriver.Chrome()
def test_aafr... | SeleniumTestScripts/TC_Renter_SuccessfulLogin.py | import unittest
import time
from selenium import webdriver
from selenium.webdriver.common.keys import Keys
from selenium.common.exceptions import NoSuchElementException
class TC_Renter_SuccessfulLogin(unittest.TestCase):
@classmethod
def setUp(self):
self.driver = webdriver.Chrome()
def test_aafr... | 0.244363 | 0.165661 |
from ConfigParser import ConfigParser
import os
import re
import subprocess
import sys
from termcolor import colored
config = ConfigParser()
ANSI_ESCAPE_RE = re.compile(r'\x1b[^m]*m')
RANGE_RE = re.compile(r'(\d+)-(\d+)')
ID_FILE = 'hgnids.txt'
CONFIG_FILE = '.hgnrc'
def fail(msg):
print colored(msg, 'red')
... | hg_number.py |
from ConfigParser import ConfigParser
import os
import re
import subprocess
import sys
from termcolor import colored
config = ConfigParser()
ANSI_ESCAPE_RE = re.compile(r'\x1b[^m]*m')
RANGE_RE = re.compile(r'(\d+)-(\d+)')
ID_FILE = 'hgnids.txt'
CONFIG_FILE = '.hgnrc'
def fail(msg):
print colored(msg, 'red')
... | 0.215351 | 0.131731 |
import numpy as np
import pandas as pd
import matplotlib.pyplot as plt
from scipy.io import loadmat
#Be careful with the file path!
data = loadmat('data/hw4.mat')
from sklearn.preprocessing import OneHotEncoder
encoder = OneHotEncoder(sparse=False, categories='auto')
y_onehot = encoder.fit_transform(data['y'])
def s... | IML_2018_Fall/Project4/hw4.py | import numpy as np
import pandas as pd
import matplotlib.pyplot as plt
from scipy.io import loadmat
#Be careful with the file path!
data = loadmat('data/hw4.mat')
from sklearn.preprocessing import OneHotEncoder
encoder = OneHotEncoder(sparse=False, categories='auto')
y_onehot = encoder.fit_transform(data['y'])
def s... | 0.754373 | 0.714254 |
import os
from collections import OrderedDict
from RouToolPa.Tools.Alignment import LongRanger
from Pipelines.Abstract import Pipeline
class TenXAlignmentPipeline(Pipeline):
def __init__(self, max_threads=1, max_memory=10, longranger_dir=""):
Pipeline.__init__(self, max_threads=max_threads, max_memory=m... | Pipelines/TenX/Alignment.py |
import os
from collections import OrderedDict
from RouToolPa.Tools.Alignment import LongRanger
from Pipelines.Abstract import Pipeline
class TenXAlignmentPipeline(Pipeline):
def __init__(self, max_threads=1, max_memory=10, longranger_dir=""):
Pipeline.__init__(self, max_threads=max_threads, max_memory=m... | 0.398289 | 0.073596 |
import re
from collections import namedtuple
from datetime import datetime, date, time
import times
from dateutil import rrule
from zitkino import parsers
from zitkino.utils import clean_whitespace
from zitkino.models import Cinema, Showtime, ScrapedFilm
from zitkino.scrapers import scrapers, Scraper
cinema = Ci... | zitkino/scrapers/turned_off/kino_lucerna.py |
import re
from collections import namedtuple
from datetime import datetime, date, time
import times
from dateutil import rrule
from zitkino import parsers
from zitkino.utils import clean_whitespace
from zitkino.models import Cinema, Showtime, ScrapedFilm
from zitkino.scrapers import scrapers, Scraper
cinema = Ci... | 0.555676 | 0.264765 |
from pathlib import Path
import os
import pytest
from examples_tests.test_util import SubProcessChecker
working_path = Path(__file__).parent.parent
@pytest.mark.usefixtures("ipu_sparse_ops")
class TestTensorFlowSparseFcBenchmarks(SubProcessChecker):
"""High-level integration tests for TensorFlow dynamic sparse ... | code_examples/tensorflow/kernel_benchmarks/test/test_dynamic_sparse_fc.py | from pathlib import Path
import os
import pytest
from examples_tests.test_util import SubProcessChecker
working_path = Path(__file__).parent.parent
@pytest.mark.usefixtures("ipu_sparse_ops")
class TestTensorFlowSparseFcBenchmarks(SubProcessChecker):
"""High-level integration tests for TensorFlow dynamic sparse ... | 0.581422 | 0.474875 |
from vitamins.geometry import Vec3, Orientation
from vitamins import math
class Location(Vec3):
"""Objects that have a location."""
modified: bool = False
@property
def position(self) -> Vec3:
return Vec3(self.x, self.y, self.z)
@position.setter
def position(self, value: Vec3):
... | vitamins/match/base.py |
from vitamins.geometry import Vec3, Orientation
from vitamins import math
class Location(Vec3):
"""Objects that have a location."""
modified: bool = False
@property
def position(self) -> Vec3:
return Vec3(self.x, self.y, self.z)
@position.setter
def position(self, value: Vec3):
... | 0.970409 | 0.62223 |
import channels
from entity_pb2 import Entity
from entity_pb2 import Player
from world_pb2 import World
from browserquest_broadcast_pb2 import SpawnRequest
from browserquest_broadcast_pb2 import ListRequest
from browserquest_broadcast_pb2 import MoveRequest
from browserquest_broadcast_pb2 import AttackRequest
from br... | session_server/services/browserquest_event.py | import channels
from entity_pb2 import Entity
from entity_pb2 import Player
from world_pb2 import World
from browserquest_broadcast_pb2 import SpawnRequest
from browserquest_broadcast_pb2 import ListRequest
from browserquest_broadcast_pb2 import MoveRequest
from browserquest_broadcast_pb2 import AttackRequest
from br... | 0.429549 | 0.135461 |
import pandas as pd
import requests
import re
import datetime
import json
from pandas import Series
from iex.utils import (param_bool,
parse_date,
validate_date_format,
validate_range_set,
validate_output_format,
... | iex/batch.py | import pandas as pd
import requests
import re
import datetime
import json
from pandas import Series
from iex.utils import (param_bool,
parse_date,
validate_date_format,
validate_range_set,
validate_output_format,
... | 0.555918 | 0.259186 |
from __future__ import unicode_literals
from django.utils.encoding import python_2_unicode_compatible
from django.db import models, IntegrityError, DatabaseError, transaction
from django.db.models import Q
from django.urls import reverse
from django.utils import timezone
try:
from version_utils.rpm import labelC... | gopatch/hosts/models.py |
from __future__ import unicode_literals
from django.utils.encoding import python_2_unicode_compatible
from django.db import models, IntegrityError, DatabaseError, transaction
from django.db.models import Q
from django.urls import reverse
from django.utils import timezone
try:
from version_utils.rpm import labelC... | 0.47098 | 0.089018 |
import math
import torch
import torch.nn as nn
from torch.nn import TransformerEncoder, TransformerEncoderLayer, Linear, TransformerDecoder, TransformerDecoderLayer
from torch.nn.modules.normalization import LayerNorm
from .model import Transformer_EncoderDecoder_Seq2Seq
from quaesita.PositionalEncoding import Position... | quaesita/transformerGANs.py | import math
import torch
import torch.nn as nn
from torch.nn import TransformerEncoder, TransformerEncoderLayer, Linear, TransformerDecoder, TransformerDecoderLayer
from torch.nn.modules.normalization import LayerNorm
from .model import Transformer_EncoderDecoder_Seq2Seq
from quaesita.PositionalEncoding import Position... | 0.934604 | 0.39129 |
from django.db import migrations, models
import django.db.models.deletion
import uuid
class Migration(migrations.Migration):
initial = True
dependencies = [
('sites', '0002_alter_domain_unique'),
]
operations = [
migrations.CreateModel(
name='Attachment',
fi... | site_cms/migrations/0001_initial.py |
from django.db import migrations, models
import django.db.models.deletion
import uuid
class Migration(migrations.Migration):
initial = True
dependencies = [
('sites', '0002_alter_domain_unique'),
]
operations = [
migrations.CreateModel(
name='Attachment',
fi... | 0.428951 | 0.118487 |
import os
from aim.engine.configs import *
def get_experiment_path(repo_path: str, experiment_name: str) -> str:
return os.path.join(repo_path, experiment_name)
def get_experiment_run_path(repo_path: str, experiment_name: str,
run_hash: str) -> str:
path = os.path.join(get_exper... | aim/engine/repo/utils.py | import os
from aim.engine.configs import *
def get_experiment_path(repo_path: str, experiment_name: str) -> str:
return os.path.join(repo_path, experiment_name)
def get_experiment_run_path(repo_path: str, experiment_name: str,
run_hash: str) -> str:
path = os.path.join(get_exper... | 0.533641 | 0.198316 |
import logging
import re
import subprocess
from dataclasses import dataclass
from enum import Enum
from pathlib import Path
from typing import Sequence
from datargs import arg, parse
class PdfEngines(Enum):
pdfroff = "pdfroff"
wkhtmltopdf = "wkhtmltopdf"
weasyprint = "weasyprint"
prince = "prince"
... | programs/scons/convert_markdown.py | import logging
import re
import subprocess
from dataclasses import dataclass
from enum import Enum
from pathlib import Path
from typing import Sequence
from datargs import arg, parse
class PdfEngines(Enum):
pdfroff = "pdfroff"
wkhtmltopdf = "wkhtmltopdf"
weasyprint = "weasyprint"
prince = "prince"
... | 0.753467 | 0.194081 |
from django.conf.urls import url, include
from django.contrib import admin
from django.contrib.auth.views import logout
from django.views.generic import TemplateView
from . import views
from django.conf import settings
from django.conf.urls.static import static
import accounts
handler400 = 'imglnx.views.handler400'... | imglnx/urls.py | from django.conf.urls import url, include
from django.contrib import admin
from django.contrib.auth.views import logout
from django.views.generic import TemplateView
from . import views
from django.conf import settings
from django.conf.urls.static import static
import accounts
handler400 = 'imglnx.views.handler400'... | 0.182863 | 0.045628 |
import os
import json
with open('/etc/config.json') as config_file:
config = json.load(config_file)
# Build paths inside the project like this: os.path.join(BASE_DIR, ...)
BASE_DIR = os.path.dirname(os.path.dirname(os.path.abspath(__file__)))
# Quick-start development settings - unsuitable for production
# Se... | Backend/foodieshoot_api/foodieshoot_api/settings.py | import os
import json
with open('/etc/config.json') as config_file:
config = json.load(config_file)
# Build paths inside the project like this: os.path.join(BASE_DIR, ...)
BASE_DIR = os.path.dirname(os.path.dirname(os.path.abspath(__file__)))
# Quick-start development settings - unsuitable for production
# Se... | 0.293404 | 0.077274 |
response = {
"result": {
"result": {
"order0": {
"ID": "35943",
"TITLE": "7-я Кожуховская ул., 4К1: 104%, 3.6, эт. 12/16, 10.5 -> 16.3 (от собственника)",
"HONORIFIC": None,
"NAME": None,
"SECOND_NAME": None,
... | tests/real_responses/call_single_success.py | response = {
"result": {
"result": {
"order0": {
"ID": "35943",
"TITLE": "7-я Кожуховская ул., 4К1: 104%, 3.6, эт. 12/16, 10.5 -> 16.3 (от собственника)",
"HONORIFIC": None,
"NAME": None,
"SECOND_NAME": None,
... | 0.363873 | 0.308906 |
from django.db.models.query import QuerySet
from wagtail.wagtailsearch.backends.elasticsearch import ElasticsearchSearchBackend, ElasticsearchSearchQuery
from wagtail.wagtailsearch.index import class_is_indexed
class CustomElasticsearchSearchQuery(ElasticsearchSearchQuery):
def __init__(self, queryset, query_stri... | search/custom_elasticsearch.py | from django.db.models.query import QuerySet
from wagtail.wagtailsearch.backends.elasticsearch import ElasticsearchSearchBackend, ElasticsearchSearchQuery
from wagtail.wagtailsearch.index import class_is_indexed
class CustomElasticsearchSearchQuery(ElasticsearchSearchQuery):
def __init__(self, queryset, query_stri... | 0.756447 | 0.159381 |
from __future__ import print_function
import os
import ast
from . import utils
def get_toplevel_imports(module):
"""Get the imports at the top-level of the given Python module.
:param module: An actual module; not the name.
:returns list: The absolute names of everything imported,
"""
path =... | metatools/imports/discovery.py | from __future__ import print_function
import os
import ast
from . import utils
def get_toplevel_imports(module):
"""Get the imports at the top-level of the given Python module.
:param module: An actual module; not the name.
:returns list: The absolute names of everything imported,
"""
path =... | 0.622115 | 0.238961 |
import logging
import tunnel_ctl_service.linode_util as linode_util
import paramiko
log = logging.getLogger("module:" + __name__)
# ssh commands
# databases
is_mysql_installed = "dpkg-query -f '${Status} @@ ${binary:Package}\n' -W | grep -v '^deinstall ok config-files @@ ' | grep '^.* @@ mysql-server$' > /dev/null"
... | tunnel_ctl_service/modules/debian_mysql.py |
import logging
import tunnel_ctl_service.linode_util as linode_util
import paramiko
log = logging.getLogger("module:" + __name__)
# ssh commands
# databases
is_mysql_installed = "dpkg-query -f '${Status} @@ ${binary:Package}\n' -W | grep -v '^deinstall ok config-files @@ ' | grep '^.* @@ mysql-server$' > /dev/null"
... | 0.205814 | 0.048406 |
import re
import random
from apiclient.discovery import build
from apiclient.errors import HttpError
def youtube_search(q):
# TODO: insert developer key
youtube = build("youtube", "v3", developerKey="")
# call the search.list method
search_response = youtube.search().list(
q=q,
part=... | find_videos.py | import re
import random
from apiclient.discovery import build
from apiclient.errors import HttpError
def youtube_search(q):
# TODO: insert developer key
youtube = build("youtube", "v3", developerKey="")
# call the search.list method
search_response = youtube.search().list(
q=q,
part=... | 0.134264 | 0.201283 |
import sys
from glados.es.ws2es.es_util import DefaultMappings
from glados.es.ws2es.denormalization import DenormalizationHandler
from glados.es.ws2es.util import SummableDict
from glados.es.ws2es.denormalization.assay_handler import AssayDenormalizationHandler
from glados.es.ws2es.denormalization.compound_handler impo... | src/glados/es/ws2es/denormalization/activity_handler.py | import sys
from glados.es.ws2es.es_util import DefaultMappings
from glados.es.ws2es.denormalization import DenormalizationHandler
from glados.es.ws2es.util import SummableDict
from glados.es.ws2es.denormalization.assay_handler import AssayDenormalizationHandler
from glados.es.ws2es.denormalization.compound_handler impo... | 0.38341 | 0.122786 |
from random import randint
import json
class Pykemon(object):
pykemon = [
[100, 'Pydiot', 'Pydiot','images/pydiot.png', 'Pydiot is an avian Pykamon with large wings, sharp talons, and a short, hooked beak'],
[90, 'Pytata', 'Pytata', 'images/pytata.png', 'Pytata is cautious in the extreme.... | PlaidCTF/2017/pykemon/pykemon.py | from random import randint
import json
class Pykemon(object):
pykemon = [
[100, 'Pydiot', 'Pydiot','images/pydiot.png', 'Pydiot is an avian Pykamon with large wings, sharp talons, and a short, hooked beak'],
[90, 'Pytata', 'Pytata', 'images/pytata.png', 'Pytata is cautious in the extreme.... | 0.321886 | 0.501709 |
import json
import tempfile
import subprocess
from os import path
from pprint import pformat
from unittest import TestCase
from pathlib import Path
from ..util import setup_temp_dir, SAMPLES_DIR, TEMP_DIR
from gltflib import GLTF
# If set to True, for any models that fail to pass the equality check, this will automat... | tests/e2e/test_roundtrip.py | import json
import tempfile
import subprocess
from os import path
from pprint import pformat
from unittest import TestCase
from pathlib import Path
from ..util import setup_temp_dir, SAMPLES_DIR, TEMP_DIR
from gltflib import GLTF
# If set to True, for any models that fail to pass the equality check, this will automat... | 0.642881 | 0.480601 |
import numpy as np
from numpy import zeros_like
from scipy.linalg import svd
s0 = np.array([[1, 0], [0, 1]])
s1 = np.array([[0, 1], [1, 0]])
s2 = np.array([[0, -1j], [1j, 0]])
s3 = np.array([[1, 0], [0, -1]])
s0T = s0.T
s1T = s1.T
s2T = s2.T
s3T = s3.T
pauli_dict = {0: s0, 1: s1, 2: s2, 3: s3}
def pauli_mat(nbasis... | TB2J/pauli.py | import numpy as np
from numpy import zeros_like
from scipy.linalg import svd
s0 = np.array([[1, 0], [0, 1]])
s1 = np.array([[0, 1], [1, 0]])
s2 = np.array([[0, -1j], [1j, 0]])
s3 = np.array([[1, 0], [0, -1]])
s0T = s0.T
s1T = s1.T
s2T = s2.T
s3T = s3.T
pauli_dict = {0: s0, 1: s1, 2: s2, 3: s3}
def pauli_mat(nbasis... | 0.706089 | 0.691621 |
from copy import deepcopy
from optax import sgd
from .._base.test_case import TestCase
from .._core.stochastic_transition_model import StochasticTransitionModel
from ..utils import get_transition_batch
from ..regularizers import EntropyRegularizer
from ._model_updater import ModelUpdater
class TestModelUpdater(Test... | coax/model_updaters/_model_updater_test.py | from copy import deepcopy
from optax import sgd
from .._base.test_case import TestCase
from .._core.stochastic_transition_model import StochasticTransitionModel
from ..utils import get_transition_batch
from ..regularizers import EntropyRegularizer
from ._model_updater import ModelUpdater
class TestModelUpdater(Test... | 0.715126 | 0.488893 |
import os
import numpy as np
import torch
from .cityscapes.data_loader import load_partition_data_cityscapes
from .coco.segmentation.data_loader import load_partition_data_coco_segmentation
from .pascal_voc_augmented.data_loader import load_partition_data_pascal_voc
import logging
def load(args):
return load_syn... | app/fedcv/object_detection/data/data_loader.py | import os
import numpy as np
import torch
from .cityscapes.data_loader import load_partition_data_cityscapes
from .coco.segmentation.data_loader import load_partition_data_coco_segmentation
from .pascal_voc_augmented.data_loader import load_partition_data_pascal_voc
import logging
def load(args):
return load_syn... | 0.496338 | 0.341473 |
import torch
import torch.nn as nn
import torch.nn.functional as F
# CTR的LR模型
# 主要是用 用户ID和物品ID,将他们进行onehot
class LR(nn.Module):
"""
user_id, movie_id进行embedding的MLP网络模型
user共6040个,movie共3883个
"""
def __init__(self):
super(LR, self).__init__()
# self.user_id_embed = nn.Embedding(... | models/fedavg/movielens/lr.py | import torch
import torch.nn as nn
import torch.nn.functional as F
# CTR的LR模型
# 主要是用 用户ID和物品ID,将他们进行onehot
class LR(nn.Module):
"""
user_id, movie_id进行embedding的MLP网络模型
user共6040个,movie共3883个
"""
def __init__(self):
super(LR, self).__init__()
# self.user_id_embed = nn.Embedding(... | 0.828072 | 0.485051 |
from itertools import cycle
from string import capwords
from fabric.colors import red, green, blue, magenta, white, yellow
class ColorRow(dict):
"""
Ordered collection of column values.
"""
def __init__(self, table, **kwargs):
super(ColorRow, self).__init__(self)
self.table = table
... | gusset/colortable.py | from itertools import cycle
from string import capwords
from fabric.colors import red, green, blue, magenta, white, yellow
class ColorRow(dict):
"""
Ordered collection of column values.
"""
def __init__(self, table, **kwargs):
super(ColorRow, self).__init__(self)
self.table = table
... | 0.888233 | 0.440529 |
import json
import torch
import pandas as pd
import numpy as np
from pathlib import Path
from itertools import repeat
from collections import OrderedDict
from PIL import Image
from scipy.special import softmax
def stat_cuda(msg):
print('--', msg)
print('allocated: %dM, max allocated: %dM, cached: %dM, max cac... | utils/util.py | import json
import torch
import pandas as pd
import numpy as np
from pathlib import Path
from itertools import repeat
from collections import OrderedDict
from PIL import Image
from scipy.special import softmax
def stat_cuda(msg):
print('--', msg)
print('allocated: %dM, max allocated: %dM, cached: %dM, max cac... | 0.610105 | 0.155431 |
import datetime
import logging
from enum import IntEnum
from functools import wraps
from flask import g, request, jsonify
from plugins.ethpassthrough.database.models import db_session, Project
class ApiError(IntEnum):
MISSING_API_KEY = 1
MISSING_PROJECT_ID = 2
PROJECT_NOT_EXIST = 3
PROJE... | plugins/ethpassthrough/middleware.py |
import datetime
import logging
from enum import IntEnum
from functools import wraps
from flask import g, request, jsonify
from plugins.ethpassthrough.database.models import db_session, Project
class ApiError(IntEnum):
MISSING_API_KEY = 1
MISSING_PROJECT_ID = 2
PROJECT_NOT_EXIST = 3
PROJE... | 0.293607 | 0.038035 |
import cv2
import torch
import random
import torch.utils.data
import torch.optim.lr_scheduler as lr_scheduler
import numpy as np
import scipy.io as scio
import os
import time
from PIL import Image
import model as model
import anchor as anchor
from tqdm import tqdm
import random_erasing
import logging
fro... | src/hands2017.py | import cv2
import torch
import random
import torch.utils.data
import torch.optim.lr_scheduler as lr_scheduler
import numpy as np
import scipy.io as scio
import os
import time
from PIL import Image
import model as model
import anchor as anchor
from tqdm import tqdm
import random_erasing
import logging
fro... | 0.24599 | 0.155527 |
from keras.layers import Input, Dense, Flatten, Reshape
from keras.layers.advanced_activations import LeakyReLU
from keras.layers.convolutional import Conv2D
from keras.models import Model
from keras.optimizers import Adam
from ast import literal_eval
from face_swap.PixelShuffler import PixelShuffler
def conv(filter... | face_swap/autoencoder.py | from keras.layers import Input, Dense, Flatten, Reshape
from keras.layers.advanced_activations import LeakyReLU
from keras.layers.convolutional import Conv2D
from keras.models import Model
from keras.optimizers import Adam
from ast import literal_eval
from face_swap.PixelShuffler import PixelShuffler
def conv(filter... | 0.945425 | 0.534187 |
import nltk
from pyvi.pyvi import ViTokenizer
import re
import ast
with open('text/acronym.txt', 'r') as f:
acronym = ast.literal_eval(str(f.read()))
def int_to_vn(num):
d = {0: 'không', 1: 'một', 2: 'hai', 3: 'ba', 4: 'bốn', 5: 'năm', 6: 'sáu', 7: 'bảy', 8: 'tám', 9: 'chín', 10: 'mười'}
if num <= 10: ret... | text_normalization.py | import nltk
from pyvi.pyvi import ViTokenizer
import re
import ast
with open('text/acronym.txt', 'r') as f:
acronym = ast.literal_eval(str(f.read()))
def int_to_vn(num):
d = {0: 'không', 1: 'một', 2: 'hai', 3: 'ba', 4: 'bốn', 5: 'năm', 6: 'sáu', 7: 'bảy', 8: 'tám', 9: 'chín', 10: 'mười'}
if num <= 10: ret... | 0.130092 | 0.349283 |
from pathlib import Path
from collections import Counter, defaultdict
INPUTFILE = "input.txt"
SAMPLE_INPUT = """
16
10
15
5
1
11
7
19
6
12
4
"""
SAMPLE_INPUT2 = """
28
33
18
42
31
14
46
20
48
47
24
23
49
45
19
38
39
11
1
32
25
35
8
17
7
9
4
2
34
10
3
"""
# Utility functions
def load_input(infile):
return fil... | day10/day10.py | from pathlib import Path
from collections import Counter, defaultdict
INPUTFILE = "input.txt"
SAMPLE_INPUT = """
16
10
15
5
1
11
7
19
6
12
4
"""
SAMPLE_INPUT2 = """
28
33
18
42
31
14
46
20
48
47
24
23
49
45
19
38
39
11
1
32
25
35
8
17
7
9
4
2
34
10
3
"""
# Utility functions
def load_input(infile):
return fil... | 0.780035 | 0.430686 |
import argparse
import unittest
from unittest import mock
import tensorflow as tf
import numpy as np
import shared.utils as utils
from Inception_V3 import custom_baseline
from Inception_V3.custom_baseline import build_custom_model
class TestCustomInceptionV3Model(unittest.TestCase):
@classmethod
def setUpC... | Plant_Disease_Detection_Benchmark_models/tests/test_inceptionv3_custom_baseline.py | import argparse
import unittest
from unittest import mock
import tensorflow as tf
import numpy as np
import shared.utils as utils
from Inception_V3 import custom_baseline
from Inception_V3.custom_baseline import build_custom_model
class TestCustomInceptionV3Model(unittest.TestCase):
@classmethod
def setUpC... | 0.850624 | 0.591841 |
import subprocess
import csv
import os
import shutil
import unittest
class TestPlotScript(unittest.TestCase):
RESULTS_DIR = "plot-results"
REMYCC_NAME = os.path.join(os.environ["srcdir"], "RemyCC-2014-100x.dna")
PLOT_SCRIPT = os.path.join(os.environ["srcdir"], "../scripts/plot.py")
ORIGINALS_DIR = os... | tests/run-plot-script.py |
import subprocess
import csv
import os
import shutil
import unittest
class TestPlotScript(unittest.TestCase):
RESULTS_DIR = "plot-results"
REMYCC_NAME = os.path.join(os.environ["srcdir"], "RemyCC-2014-100x.dna")
PLOT_SCRIPT = os.path.join(os.environ["srcdir"], "../scripts/plot.py")
ORIGINALS_DIR = os... | 0.489259 | 0.353428 |
import json
from pathlib import Path
import pickle
BASE_DIR = Path("./Training/SImple_Resturant")
USER_DATABASE = BASE_DIR / "users-information.json"
FOOD_DATABASE = BASE_DIR / "food_menu.json"
class UsersInfo:
__instance = None
def __init__(self):
self.users = dict()
self.keys = ['passwo... | SImple_Resturant/model.py | import json
from pathlib import Path
import pickle
BASE_DIR = Path("./Training/SImple_Resturant")
USER_DATABASE = BASE_DIR / "users-information.json"
FOOD_DATABASE = BASE_DIR / "food_menu.json"
class UsersInfo:
__instance = None
def __init__(self):
self.users = dict()
self.keys = ['passwo... | 0.255251 | 0.080105 |
import requests
from hashlib import md5
from allauth.socialaccount.providers.base import ProviderAccount
from allauth.socialaccount.providers.core.oauth2.provider import OAuth2Provider
class MailRuAccount(ProviderAccount):
def get_profile_url(self):
return self.account.extra_data.get('link')
def get... | allauth/socialaccount/providers/dev_sites/mailru/provider.py | import requests
from hashlib import md5
from allauth.socialaccount.providers.base import ProviderAccount
from allauth.socialaccount.providers.core.oauth2.provider import OAuth2Provider
class MailRuAccount(ProviderAccount):
def get_profile_url(self):
return self.account.extra_data.get('link')
def get... | 0.284974 | 0.136407 |
import unittest
import filecmp
import time
from threading import Event
from rx import *
from TorrentPython.DownloadManager import DownloadManager
from TorrentPython.MetaInfo import MetaInfo
from TorrentPython.RoutingTable import RoutingTable
from TorrentPython.TorrentUtils import TorrentUtils
SAMPLE_TORRENT_PATH = '... | TorrentPython/unittest/DownloadManager_test.py | import unittest
import filecmp
import time
from threading import Event
from rx import *
from TorrentPython.DownloadManager import DownloadManager
from TorrentPython.MetaInfo import MetaInfo
from TorrentPython.RoutingTable import RoutingTable
from TorrentPython.TorrentUtils import TorrentUtils
SAMPLE_TORRENT_PATH = '... | 0.338624 | 0.202148 |
class LDA_original:
@staticmethod
def _convergence_(new, old, epsilon = 1.0e-3):
'''
Check convergence.
'''
delta = abs(new - old)
return np.all(delta) < epsilon
@staticmethod
def _normalization_col(x):
'''
Normalize a matrix.
... | LDA_withoutOPT.py | class LDA_original:
@staticmethod
def _convergence_(new, old, epsilon = 1.0e-3):
'''
Check convergence.
'''
delta = abs(new - old)
return np.all(delta) < epsilon
@staticmethod
def _normalization_col(x):
'''
Normalize a matrix.
... | 0.801042 | 0.545286 |
import sys
_b=sys.version_info[0]<3 and (lambda x:x) or (lambda x:x.encode('latin1'))
from google.protobuf import descriptor as _descriptor
from google.protobuf import message as _message
from google.protobuf import reflection as _reflection
from google.protobuf import symbol_database as _symbol_database
from google.p... | src/onos_grpc_demo/proto/PortProto_pb2.py |
import sys
_b=sys.version_info[0]<3 and (lambda x:x) or (lambda x:x.encode('latin1'))
from google.protobuf import descriptor as _descriptor
from google.protobuf import message as _message
from google.protobuf import reflection as _reflection
from google.protobuf import symbol_database as _symbol_database
from google.p... | 0.211254 | 0.08438 |
from collections import OrderedDict
from django.views.generic import TemplateView
from django.contrib.postgres.fields.jsonb import KeyTextTransform
from django.db.models import (
Case, When, F, Count, Sum, FloatField, Avg, Min, Max, Q
)
from django.db.models.functions import Cast
from rest_framework.views import AP... | sass/views/sass_dashboard_multiple.py | from collections import OrderedDict
from django.views.generic import TemplateView
from django.contrib.postgres.fields.jsonb import KeyTextTransform
from django.db.models import (
Case, When, F, Count, Sum, FloatField, Avg, Min, Max, Q
)
from django.db.models.functions import Cast
from rest_framework.views import AP... | 0.384565 | 0.173726 |
import django_tables2
from django.template.loader import get_template
from django.utils.html import format_html, mark_safe
from django_tables2.utils import Accessor
import help_text
from core.tables import CobwebBaseTable
from projects.models import Claim, Nomination, Project
class ProjectTable(CobwebBaseTable):
... | projects/tables.py | import django_tables2
from django.template.loader import get_template
from django.utils.html import format_html, mark_safe
from django_tables2.utils import Accessor
import help_text
from core.tables import CobwebBaseTable
from projects.models import Claim, Nomination, Project
class ProjectTable(CobwebBaseTable):
... | 0.494141 | 0.089216 |
import pprint
import carla
import time
import numpy as np
import sys
try:
import pygame
from pygame.locals import KMOD_CTRL
from pygame.locals import KMOD_SHIFT
from pygame.locals import K_0
from pygame.locals import K_9
from pygame.locals import K_BACKQUOTE
from pygame.locals import K_BACK... | test_carla_manual.py | import pprint
import carla
import time
import numpy as np
import sys
try:
import pygame
from pygame.locals import KMOD_CTRL
from pygame.locals import KMOD_SHIFT
from pygame.locals import K_0
from pygame.locals import K_9
from pygame.locals import K_BACKQUOTE
from pygame.locals import K_BACK... | 0.479991 | 0.142739 |
from pathlib import Path
import cv2
import numpy as np
import torch
from torch.utils.data import Dataset, DataLoader
from torchvision import transforms
import augmenter
from perception.utils.helpers import get_segmentation_tensor
from perception.utils.segmentation_labels import DEFAULT_CLASSES
class MultiTaskDatase... | perception/custom_datasets.py | from pathlib import Path
import cv2
import numpy as np
import torch
from torch.utils.data import Dataset, DataLoader
from torchvision import transforms
import augmenter
from perception.utils.helpers import get_segmentation_tensor
from perception.utils.segmentation_labels import DEFAULT_CLASSES
class MultiTaskDatase... | 0.858793 | 0.497925 |
from datetime import datetime, timedelta
from airflow.decorators import dag, task
import os, sys
sys.path.append('/opt/airflow/')
from dags.connectors.sf import sf
from dags.utils.vaults_at_risk.setup import _setup
from dags.utils.vaults_at_risk.urns import _fetch_urns
from dags.utils.vaults_at_risk.rates import _fet... | dags/prod_vaults_at_risk.py | from datetime import datetime, timedelta
from airflow.decorators import dag, task
import os, sys
sys.path.append('/opt/airflow/')
from dags.connectors.sf import sf
from dags.utils.vaults_at_risk.setup import _setup
from dags.utils.vaults_at_risk.urns import _fetch_urns
from dags.utils.vaults_at_risk.rates import _fet... | 0.348756 | 0.329607 |
import argparse
import torch
from torch.utils.data.dataloader import DataLoader
from tqdm import tqdm
from data_modules.dataset_factory import DatasetFactory
from data_modules.image_dataset_data_module import ImageDatasetDataModule
from metrics.cw import silverman_rule_of_thumb
def parse_program_args() -> ar... | src/compute_cw_dataset_statistics.py | import argparse
import torch
from torch.utils.data.dataloader import DataLoader
from tqdm import tqdm
from data_modules.dataset_factory import DatasetFactory
from data_modules.image_dataset_data_module import ImageDatasetDataModule
from metrics.cw import silverman_rule_of_thumb
def parse_program_args() -> ar... | 0.678753 | 0.256855 |