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 random as rand
import matplotlib.pyplot as plt
class component:
def __init__(self,num_node):
self.num_node = num_node
self.parent = [i for i in range(num_node)]
self.weight = [0 for i in range(num_node)]
self.size = [1 for i in range(num_node)]
def find(... | segmentation/Component.py | import numpy as np
import random as rand
import matplotlib.pyplot as plt
class component:
def __init__(self,num_node):
self.num_node = num_node
self.parent = [i for i in range(num_node)]
self.weight = [0 for i in range(num_node)]
self.size = [1 for i in range(num_node)]
def find(... | 0.101233 | 0.418103 |
from typing import TypeVar, Any
from abc import ABC, abstractmethod
import eagerpy as ep
T = TypeVar("T")
class Criterion(ABC):
"""Abstract base class to implement new criteria."""
@abstractmethod
def __repr__(self) -> str:
...
@abstractmethod
def __call__(self, perturbed: T, outputs: ... | foolbox/criteria.py | from typing import TypeVar, Any
from abc import ABC, abstractmethod
import eagerpy as ep
T = TypeVar("T")
class Criterion(ABC):
"""Abstract base class to implement new criteria."""
@abstractmethod
def __repr__(self) -> str:
...
@abstractmethod
def __call__(self, perturbed: T, outputs: ... | 0.963618 | 0.40869 |
from __future__ import unicode_literals
from binascii import crc32
from wxpy.utils import start_new_thread
emojis = \
'😀😁😂🤣😃😄😅😆😉😊😋😎😍😘😗😙😚🙂🤗🤔😐😑😶🙄😏😣😥😮🤐😯' \
'😪😫😴😌🤓😛😜😝🤤😒😓😔😕🙃🤑😲😇🤠🤡🤥😺😸😹😻😼😽🙀😿😾🙈' \
'🙉🙊🌱🌲🌳🌴🌵🌾🌿🍀🍁🍂🍃🍇🍈🍉🍊🍋🍌🍍🍏🍐🍑🍒🍓🥝🍅🥑... | wxpy/ext/sync_message_in_groups.py | from __future__ import unicode_literals
from binascii import crc32
from wxpy.utils import start_new_thread
emojis = \
'😀😁😂🤣😃😄😅😆😉😊😋😎😍😘😗😙😚🙂🤗🤔😐😑😶🙄😏😣😥😮🤐😯' \
'😪😫😴😌🤓😛😜😝🤤😒😓😔😕🙃🤑😲😇🤠🤡🤥😺😸😹😻😼😽🙀😿😾🙈' \
'🙉🙊🌱🌲🌳🌴🌵🌾🌿🍀🍁🍂🍃🍇🍈🍉🍊🍋🍌🍍🍏🍐🍑🍒🍓🥝🍅🥑... | 0.407687 | 0.363675 |
import nextcord as discord
from nextcord.ext import tasks, commands
from nextcord.utils import utcnow
from datetime import timedelta
import sys
import random
from random import choice
import asyncio
import time
import datetime
import pymongo
sys.path.append("..")
from functions import functions as funs
import config
... | Cog/moderation.py | import nextcord as discord
from nextcord.ext import tasks, commands
from nextcord.utils import utcnow
from datetime import timedelta
import sys
import random
from random import choice
import asyncio
import time
import datetime
import pymongo
sys.path.append("..")
from functions import functions as funs
import config
... | 0.253122 | 0.147371 |
import csv
import os
import re
import sqlite3
import sys
class Asset():
def __init__(self, filename, md5, bytes):
self.filename = filename
self.md5 = md5
self.bytes = int(bytes)
def found(self, cursor):
fb_query = """SELECT * FROM files
WHERE filenam... | verifier/prange.py |
import csv
import os
import re
import sqlite3
import sys
class Asset():
def __init__(self, filename, md5, bytes):
self.filename = filename
self.md5 = md5
self.bytes = int(bytes)
def found(self, cursor):
fb_query = """SELECT * FROM files
WHERE filenam... | 0.23467 | 0.119537 |
from keras import backend as K
from keras.applications.vgg16 import VGG16
from keras.models import Model
def vgg16_feature_model(flayers, weights='imagenet'):
"""
Feature exctraction VGG16 model.
# Arguments
flayers: list of strings with names of layers to get the features for.
Th... | inpainter_utils/pconv2d_loss.py | from keras import backend as K
from keras.applications.vgg16 import VGG16
from keras.models import Model
def vgg16_feature_model(flayers, weights='imagenet'):
"""
Feature exctraction VGG16 model.
# Arguments
flayers: list of strings with names of layers to get the features for.
Th... | 0.947854 | 0.545104 |
def read_input(path: str):
"""
Read game board file from path.
Return list of str.
>>> read_input("check.txt")
['***21**', '452453*', '423145*', '*543215', '*35214*', '*41532*', '*2*1***']
"""
with open(path, "r", encoding="utf-8") as file:
lst = file.readlines()
for i in ra... | skyscraper.py | def read_input(path: str):
"""
Read game board file from path.
Return list of str.
>>> read_input("check.txt")
['***21**', '452453*', '423145*', '*543215', '*35214*', '*41532*', '*2*1***']
"""
with open(path, "r", encoding="utf-8") as file:
lst = file.readlines()
for i in ra... | 0.717705 | 0.405272 |
from os import getcwd
import argparse
import json
from typing import Dict, List, Union, MutableMapping
import sys
from idol.generator import GeneratorParams
from idol.functional import OrderedObj
from idol.__idol__ import Map
from idol.py.schema.module import Module
class CliConfig:
flags: Dict[str, str]
ar... | src/lib/idol/cli.py | from os import getcwd
import argparse
import json
from typing import Dict, List, Union, MutableMapping
import sys
from idol.generator import GeneratorParams
from idol.functional import OrderedObj
from idol.__idol__ import Map
from idol.py.schema.module import Module
class CliConfig:
flags: Dict[str, str]
ar... | 0.526343 | 0.156105 |
import asyncio
import motor.motor_asyncio
try:
import ujson as json
except ImportError: # pragma no cover
import json
from urllib.parse import urlparse
from .model import APITest
from .exceptions import ApitestConnectionError
async def _do_mongodb_query(col, query: dict): # pragma no cover
"""
Do ... | refactor/old/apitest/core/loaders.py | import asyncio
import motor.motor_asyncio
try:
import ujson as json
except ImportError: # pragma no cover
import json
from urllib.parse import urlparse
from .model import APITest
from .exceptions import ApitestConnectionError
async def _do_mongodb_query(col, query: dict): # pragma no cover
"""
Do ... | 0.655005 | 0.301677 |
CHARS = {
'sp':0x20,
'apb':0x08, # active position back
'apf':0x09, # active position forward
'apd':0x0a, # active position down
'apu':0x0b, # active position up
'cs':0x0c, # clear screen
'apr':0x0d, # active position return
'si':0x0e, # shift in
'so':0x0f, # shift out
'con':0x11,... | cept.py |
CHARS = {
'sp':0x20,
'apb':0x08, # active position back
'apf':0x09, # active position forward
'apd':0x0a, # active position down
'apu':0x0b, # active position up
'cs':0x0c, # clear screen
'apr':0x0d, # active position return
'si':0x0e, # shift in
'so':0x0f, # shift out
'con':0x11,... | 0.35488 | 0.109658 |
from slepc4py import SLEPc
from petsc4py import PETSc
import unittest
# --------------------------------------------------------------------
class BaseTestObject(object):
CLASS, FACTORY = None, 'create'
TARGS, KARGS = (), {}
BUILD = None
def setUp(self):
self.obj = self.CLASS()
getatt... | test/test_object.py | from slepc4py import SLEPc
from petsc4py import PETSc
import unittest
# --------------------------------------------------------------------
class BaseTestObject(object):
CLASS, FACTORY = None, 'create'
TARGS, KARGS = (), {}
BUILD = None
def setUp(self):
self.obj = self.CLASS()
getatt... | 0.453988 | 0.394667 |
import copy
import json
from django.utils.translation import ugettext_lazy as _
from apps.utils.db import array_group
from apps.exceptions import ValidationError
from apps.utils.log import logger
from apps.log_databus.constants import EtlConfig
from apps.log_databus.handlers.etl_storage import EtlStorage
from apps.lo... | apps/log_databus/handlers/etl_storage/bk_log_delimiter.py | import copy
import json
from django.utils.translation import ugettext_lazy as _
from apps.utils.db import array_group
from apps.exceptions import ValidationError
from apps.utils.log import logger
from apps.log_databus.constants import EtlConfig
from apps.log_databus.handlers.etl_storage import EtlStorage
from apps.lo... | 0.274935 | 0.151467 |
import asyncio
import pytest
import time
from asynctest import MagicMock
from aiohttp import ClientConnectionError
from kin_base.keypair import Keypair
from kin_base.operation import *
from kin_base.horizon import Horizon
from kin_base.exceptions import HorizonRequestError
from kin_base.transaction import Transaction... | tests/test_horizon.py | import asyncio
import pytest
import time
from asynctest import MagicMock
from aiohttp import ClientConnectionError
from kin_base.keypair import Keypair
from kin_base.operation import *
from kin_base.horizon import Horizon
from kin_base.exceptions import HorizonRequestError
from kin_base.transaction import Transaction... | 0.651909 | 0.296463 |
from hachoir_parser import Parser
from hachoir_core.field import FieldSet, UInt8, UInt16, Enum, RawBytes
from hachoir_core.endian import LITTLE_ENDIAN
from hachoir_parser.image.common import PaletteRGB
class Line(FieldSet):
def __init__(self, *args):
FieldSet.__init__(self, *args)
self._size = self... | .modules/.metagoofil/hachoir_parser/image/tga.py | from hachoir_parser import Parser
from hachoir_core.field import FieldSet, UInt8, UInt16, Enum, RawBytes
from hachoir_core.endian import LITTLE_ENDIAN
from hachoir_parser.image.common import PaletteRGB
class Line(FieldSet):
def __init__(self, *args):
FieldSet.__init__(self, *args)
self._size = self... | 0.605566 | 0.15444 |
CDED = [
{"name":"fileName", "length":40, "description":None},
{"name":"responsabilityCenter", "length":60, "description":None},
{"name":"filler", "length":9, "description":None},
{"name":"seGeographicCorner", "length":26, "description... | cdedtools/translationtables.py | CDED = [
{"name":"fileName", "length":40, "description":None},
{"name":"responsabilityCenter", "length":60, "description":None},
{"name":"filler", "length":9, "description":None},
{"name":"seGeographicCorner", "length":26, "description... | 0.53437 | 0.473779 |
""" Tests of DifferenceBetweenAdjacentGridSquares plugin."""
import unittest
import iris
import numpy as np
from iris.coords import CellMethod
from iris.cube import Cube
from iris.tests import IrisTest
from numpy import ma
from improver.synthetic_data.set_up_test_cubes import set_up_variable_cube
from improver.utili... | improver_tests/utilities/test_DifferenceBetweenAdjacentGridSquares.py | """ Tests of DifferenceBetweenAdjacentGridSquares plugin."""
import unittest
import iris
import numpy as np
from iris.coords import CellMethod
from iris.cube import Cube
from iris.tests import IrisTest
from numpy import ma
from improver.synthetic_data.set_up_test_cubes import set_up_variable_cube
from improver.utili... | 0.88382 | 0.826572 |
from telegram import Update, ForceReply, ReplyKeyboardMarkup
from telegram.ext import Updater, CommandHandler, MessageHandler, Filters, CallbackContext, ConversationHandler
import logging
from RoutePlanner import RoutePlanner
from WeatherForecaster import WeatherForecaster
from RouteWeatherEvaluator import RouteWeather... | src/Bot.py | from telegram import Update, ForceReply, ReplyKeyboardMarkup
from telegram.ext import Updater, CommandHandler, MessageHandler, Filters, CallbackContext, ConversationHandler
import logging
from RoutePlanner import RoutePlanner
from WeatherForecaster import WeatherForecaster
from RouteWeatherEvaluator import RouteWeather... | 0.436142 | 0.084191 |
from pandas import DataFrame
from .atr import atr
from ..overlap.hlc3 import hlc3
from ..overlap.sma import sma
from ..utils import get_offset, non_zero_range, verify_series
def aberration(high, low, close, length=None, atr_length=None, offset=None, **kwargs):
"""Indicator: Aberration (ABER)"""
# Validate argu... | pandas_ta/volatility/aberration.py | from pandas import DataFrame
from .atr import atr
from ..overlap.hlc3 import hlc3
from ..overlap.sma import sma
from ..utils import get_offset, non_zero_range, verify_series
def aberration(high, low, close, length=None, atr_length=None, offset=None, **kwargs):
"""Indicator: Aberration (ABER)"""
# Validate argu... | 0.592667 | 0.385404 |
import os
import logging
import logging.config
from functools import wraps
def setup_logging(root: str) -> object:
"""configure logging protocol.
Defines the configuration for the python logging objects. At level debug
it will only log to the console. At info level it will log to the
projects log file... | utilities.py | import os
import logging
import logging.config
from functools import wraps
def setup_logging(root: str) -> object:
"""configure logging protocol.
Defines the configuration for the python logging objects. At level debug
it will only log to the console. At info level it will log to the
projects log file... | 0.419172 | 0.115187 |
import unittest
from unittest import mock
import pytest
import string
import dbt.exceptions
import dbt.graph.selector as graph_selector
import dbt.graph.cli as graph_cli
from dbt.node_types import NodeType
import networkx as nx
def _get_graph():
integer_graph = nx.balanced_tree(2, 2, nx.DiGraph())
package... | test/unit/test_graph_selection.py | import unittest
from unittest import mock
import pytest
import string
import dbt.exceptions
import dbt.graph.selector as graph_selector
import dbt.graph.cli as graph_cli
from dbt.node_types import NodeType
import networkx as nx
def _get_graph():
integer_graph = nx.balanced_tree(2, 2, nx.DiGraph())
package... | 0.540439 | 0.374476 |
import distiller
from .ranked_structures_pruner import *
class SensitivityPruner(object):
"""Use algorithm from "Learning both Weights and Connections for Efficient
Neural Networks" - https://arxiv.org/pdf/1506.02626v3.pdf
I.e.: "The pruning threshold is chosen as a quality parameter multiplied
by ... | distiller/pruning/sensitivity_pruner.py |
import distiller
from .ranked_structures_pruner import *
class SensitivityPruner(object):
"""Use algorithm from "Learning both Weights and Connections for Efficient
Neural Networks" - https://arxiv.org/pdf/1506.02626v3.pdf
I.e.: "The pruning threshold is chosen as a quality parameter multiplied
by ... | 0.852675 | 0.602617 |
import os
from rlbot.agents.base_agent import BOT_NAME_KEY, BOT_CONFIG_LOADOUT_HEADER, BOT_CONFIG_MODULE_HEADER
from rlbot.gui.presets import AgentPreset, LoadoutPreset
from rlbot.parsing.agent_config_parser import PARTICIPANT_CONFIGURATION_HEADER, PARTICIPANT_CONFIG_KEY, \
PARTICIPANT_BOT_SKILL_KEY, PARTICIPANT_T... | src/main/python/rlbot/gui/gui_agent.py | import os
from rlbot.agents.base_agent import BOT_NAME_KEY, BOT_CONFIG_LOADOUT_HEADER, BOT_CONFIG_MODULE_HEADER
from rlbot.gui.presets import AgentPreset, LoadoutPreset
from rlbot.parsing.agent_config_parser import PARTICIPANT_CONFIGURATION_HEADER, PARTICIPANT_CONFIG_KEY, \
PARTICIPANT_BOT_SKILL_KEY, PARTICIPANT_T... | 0.407805 | 0.073897 |
import json
import logging
import boto3
from boto3.dynamodb.conditions import Key
logger = logging.getLogger()
logger.setLevel(logging.DEBUG)
q_name = "travel-invitation-mq"
user_table = boto3.resource('dynamodb').Table('userTable')
sender_email="<EMAIL>"
authUrl="http://localhost:8080/#/accept/schedule/"
def get_ta... | travel-planner-backend/handlers/proj_send_invitation.py | import json
import logging
import boto3
from boto3.dynamodb.conditions import Key
logger = logging.getLogger()
logger.setLevel(logging.DEBUG)
q_name = "travel-invitation-mq"
user_table = boto3.resource('dynamodb').Table('userTable')
sender_email="<EMAIL>"
authUrl="http://localhost:8080/#/accept/schedule/"
def get_ta... | 0.176459 | 0.094636 |
import os
from tika import detector
from tika import parser
import subprocess
import re
import json
from tika.parser import _parse
from tika.tika import callServer, ServerEndpoint
# Path for directory containing files to be processed
path = "/Users/charanshampur/newAwsDump/testFiles2"
# Path for Google Scholar Api Pr... | 3.NER_GeoTopic/grobidParser.py | import os
from tika import detector
from tika import parser
import subprocess
import re
import json
from tika.parser import _parse
from tika.tika import callServer, ServerEndpoint
# Path for directory containing files to be processed
path = "/Users/charanshampur/newAwsDump/testFiles2"
# Path for Google Scholar Api Pr... | 0.203114 | 0.074131 |
from transbank.common.options import WebpayOptions
from transbank.common.request_service import RequestService
from transbank.common.api_constants import ApiConstants
from transbank.common.integration_commerce_codes import IntegrationCommerceCodes
from transbank.common.webpay_transaction import WebpayTransaction
from t... | transbank/webpay/webpay_plus/mall_transaction.py | from transbank.common.options import WebpayOptions
from transbank.common.request_service import RequestService
from transbank.common.api_constants import ApiConstants
from transbank.common.integration_commerce_codes import IntegrationCommerceCodes
from transbank.common.webpay_transaction import WebpayTransaction
from t... | 0.546012 | 0.103024 |
ANSIBLE_METADATA = {
'metadata_version': '1.1',
'status': ['preview'],
'supported_by': 'community'
}
DOCUMENTATION = '''
---
module: loop_protect
short_description: implements loop-protect rest api
version_added: "2.6"
description:
- "This configures loop protect on device over vlan or port"
exten... | aruba_module_installer/library/modules/network/arubaoss/arubaoss_loop_protect.py |
ANSIBLE_METADATA = {
'metadata_version': '1.1',
'status': ['preview'],
'supported_by': 'community'
}
DOCUMENTATION = '''
---
module: loop_protect
short_description: implements loop-protect rest api
version_added: "2.6"
description:
- "This configures loop protect on device over vlan or port"
exten... | 0.477798 | 0.257367 |
import os
from os.path import join, exists
import numpy as np
from pgl.utils.data.dataloader import Dataloader
from pahelix.utils.data_utils import save_data_list_to_npz, load_npz_to_data_list
__all__ = ['InMemoryDataset']
class InMemoryDataset(object):
"""
The InMemoryDataset manages :attr:`data_list` wh... | pahelix/datasets/inmemory_dataset.py | import os
from os.path import join, exists
import numpy as np
from pgl.utils.data.dataloader import Dataloader
from pahelix.utils.data_utils import save_data_list_to_npz, load_npz_to_data_list
__all__ = ['InMemoryDataset']
class InMemoryDataset(object):
"""
The InMemoryDataset manages :attr:`data_list` wh... | 0.730674 | 0.42316 |
import time
import pytest
from selenium import webdriver
from selenium.webdriver.support.wait import WebDriverWait
from selenium.webdriver.support import expected_conditions as EC
from selenium.webdriver.common.by import By
from selenium.webdriver.common.action_chains import ActionChains
@pytest.fixture(scope="ses... | task_7/main.py | import time
import pytest
from selenium import webdriver
from selenium.webdriver.support.wait import WebDriverWait
from selenium.webdriver.support import expected_conditions as EC
from selenium.webdriver.common.by import By
from selenium.webdriver.common.action_chains import ActionChains
@pytest.fixture(scope="ses... | 0.181263 | 0.06663 |
# (C) Copyright 2020 Hewlett Packard Enterprise Development LP.
# GNU General Public License v3.0+
# (see COPYING or https://www.gnu.org/licenses/gpl-3.0.txt)
from __future__ import (absolute_import, division, print_function)
__metaclass__ = type
ANSIBLE_METADATA = {
'metadata_version': '1.1',
'status': ['... | plugins/modules/aoscx_command.py |
# (C) Copyright 2020 Hewlett Packard Enterprise Development LP.
# GNU General Public License v3.0+
# (see COPYING or https://www.gnu.org/licenses/gpl-3.0.txt)
from __future__ import (absolute_import, division, print_function)
__metaclass__ = type
ANSIBLE_METADATA = {
'metadata_version': '1.1',
'status': ['... | 0.790166 | 0.383064 |
import unittest
import testing_config # Must be imported before the module under test.
import flask
import mock
import werkzeug.exceptions # Flask HTTP stuff.
from framework import csp
test_app = flask.Flask(__name__)
class CspTest(unittest.TestCase):
def setUp(self):
csp.ENABLED = True
csp.REPORT... | framework/csp_test.py |
import unittest
import testing_config # Must be imported before the module under test.
import flask
import mock
import werkzeug.exceptions # Flask HTTP stuff.
from framework import csp
test_app = flask.Flask(__name__)
class CspTest(unittest.TestCase):
def setUp(self):
csp.ENABLED = True
csp.REPORT... | 0.54359 | 0.397471 |
from unittest import TestCase
from docutils import nodes
from mock import patch
from sphinx import jinja2glue
from sphinx_testing import TestApp
from hieroglyph.tests import util
from hieroglyph.builder import SlideBuilder
from hieroglyph.writer import (
SlideData,
BaseSlideTranslator,
SlideTranslator,
)... | v/lib/python2.7/site-packages/hieroglyph/tests/test_translator.py | from unittest import TestCase
from docutils import nodes
from mock import patch
from sphinx import jinja2glue
from sphinx_testing import TestApp
from hieroglyph.tests import util
from hieroglyph.builder import SlideBuilder
from hieroglyph.writer import (
SlideData,
BaseSlideTranslator,
SlideTranslator,
)... | 0.744471 | 0.306138 |
from __future__ import absolute_import
import unittest
from helpers import xroad
from main.maincontroller import MainController
from tests.xroad_client_registration_in_ss_221 import client_registration_in_ss
class XroadSecurityServerClientDeletion(unittest.TestCase):
"""
MEMBER_14 Delete an X-Road Member's ... | common/xrd-ui-tests-python/tests/xroad_client_registration_in_ss_221/XroadSecurityServerClientDeletion.py | from __future__ import absolute_import
import unittest
from helpers import xroad
from main.maincontroller import MainController
from tests.xroad_client_registration_in_ss_221 import client_registration_in_ss
class XroadSecurityServerClientDeletion(unittest.TestCase):
"""
MEMBER_14 Delete an X-Road Member's ... | 0.547948 | 0.079567 |
import numpy as np
def strain_to_stress(strain, mu, nu):
"""
Compute stress given strain like:
stress = 2 * mu * strain + lambda * Id(3) * trace(strain)
Parameters
----------
strain : {array-like}, shape (n_tensors, 6)
The strain tensors ordered like (e_xx, e_yy, e_zz, e_xy, e_xz,... | cutde/geometry.py | import numpy as np
def strain_to_stress(strain, mu, nu):
"""
Compute stress given strain like:
stress = 2 * mu * strain + lambda * Id(3) * trace(strain)
Parameters
----------
strain : {array-like}, shape (n_tensors, 6)
The strain tensors ordered like (e_xx, e_yy, e_zz, e_xy, e_xz,... | 0.965103 | 0.821546 |
import time
from kbcstorage.base import Endpoint
class Jobs(Endpoint):
"""
Jobs are objects that manage asynchronous tasks, these are all
potentially long-running actions such as loading table data,
snapshotting, table structure modifications. Jobs are created by
actions on target resources.
... | kbcstorage/jobs.py | import time
from kbcstorage.base import Endpoint
class Jobs(Endpoint):
"""
Jobs are objects that manage asynchronous tasks, these are all
potentially long-running actions such as loading table data,
snapshotting, table structure modifications. Jobs are created by
actions on target resources.
... | 0.828141 | 0.420957 |
from types import FunctionType
from typing import Tuple
from axelrod._strategy_utils import thue_morse_generator
from axelrod.action import Action
from axelrod.player import Player
C, D = Action.C, Action.D
class SequencePlayer(Player):
"""Abstract base class for players that use a generated sequence to
det... | axelrod/strategies/sequence_player.py | from types import FunctionType
from typing import Tuple
from axelrod._strategy_utils import thue_morse_generator
from axelrod.action import Action
from axelrod.player import Player
C, D = Action.C, Action.D
class SequencePlayer(Player):
"""Abstract base class for players that use a generated sequence to
det... | 0.927396 | 0.374991 |
from jina.peapods.runtimes.head import HeadRuntime
if False:
from argparse import Namespace
def pod(args: 'Namespace'):
"""
Start a Pod
:param args: arguments coming from the CLI.
"""
from jina.peapods.pods import Pod
try:
with Pod(args) as p:
p.join()
except Key... | cli/api.py | from jina.peapods.runtimes.head import HeadRuntime
if False:
from argparse import Namespace
def pod(args: 'Namespace'):
"""
Start a Pod
:param args: arguments coming from the CLI.
"""
from jina.peapods.pods import Pod
try:
with Pod(args) as p:
p.join()
except Key... | 0.72662 | 0.264905 |
from __future__ import print_function
import codecs
import os
import sys
import shutil
import re
from bs4 import BeautifulSoup
import commons
LS_URL = u'http://zgdwz.lifescience.com.cn/ashx/searchinfo.ashx?key={}'
LS_INFO_URL = u'http://zgdwz.lifescience.com.cn/info/{}'
BD_URL = u'https://baike.baidu.com/item/{}'
BD_H... | labs/fish_details_fetch.py | from __future__ import print_function
import codecs
import os
import sys
import shutil
import re
from bs4 import BeautifulSoup
import commons
LS_URL = u'http://zgdwz.lifescience.com.cn/ashx/searchinfo.ashx?key={}'
LS_INFO_URL = u'http://zgdwz.lifescience.com.cn/info/{}'
BD_URL = u'https://baike.baidu.com/item/{}'
BD_H... | 0.177526 | 0.062674 |
import sys
import cdsapi
year= int(sys.argv[1])
#month= sys.argv[2]
print('/home/smartmet/data/ec-sf_%s-%s_all-24h-euro.grib'%(year,year+2))
c = cdsapi.Client()
c.retrieve(
'seasonal-original-single-levels',
{
'format': 'grib',
'originating_centre': 'ecmwf',
'system': '5',
'va... | bin/cds-sf-tp-24h-stats.py | import sys
import cdsapi
year= int(sys.argv[1])
#month= sys.argv[2]
print('/home/smartmet/data/ec-sf_%s-%s_all-24h-euro.grib'%(year,year+2))
c = cdsapi.Client()
c.retrieve(
'seasonal-original-single-levels',
{
'format': 'grib',
'originating_centre': 'ecmwf',
'system': '5',
'va... | 0.121035 | 0.271729 |
import os
import dgl
import torch
import numpy as np
from dgl.data import DGLDataset
class Polar(DGLDataset):
def __init__(self, root, split, num_nodes=189):
# super(Polar, self).__init__()
self.root = root
self.split = split
self.num_nodes = num_nodes
self.graphs_base = os.path.join(self.root, "graphs", ... | dataloader.py | import os
import dgl
import torch
import numpy as np
from dgl.data import DGLDataset
class Polar(DGLDataset):
def __init__(self, root, split, num_nodes=189):
# super(Polar, self).__init__()
self.root = root
self.split = split
self.num_nodes = num_nodes
self.graphs_base = os.path.join(self.root, "graphs", ... | 0.346099 | 0.261128 |
import datetime as dt
import urllib.parse
from typing import Dict, Union
from utils.database import tibiaDatabase
from utils.general import get_local_timezone
from utils.tibia import get_tibia_time_zone
WIKI_ICON = "https://vignette.wikia.nocookie.net/tibia/images/b/bc/Wiki.png/revision/latest?path-prefix=en"
def g... | utils/tibiawiki.py | import datetime as dt
import urllib.parse
from typing import Dict, Union
from utils.database import tibiaDatabase
from utils.general import get_local_timezone
from utils.tibia import get_tibia_time_zone
WIKI_ICON = "https://vignette.wikia.nocookie.net/tibia/images/b/bc/Wiki.png/revision/latest?path-prefix=en"
def g... | 0.727589 | 0.254087 |
from dypac.embeddings import Embedding
from sklearn.preprocessing import OneHotEncoder
from nilearn.image import resample_to_img
from nilearn.input_data import NiftiMasker
class BaseMasker:
def __init__(self):
"""
Build a Dypac-like masker from labels.
Parameters
----------
... | cneuromod_embeddings/dypac_masker.py | from dypac.embeddings import Embedding
from sklearn.preprocessing import OneHotEncoder
from nilearn.image import resample_to_img
from nilearn.input_data import NiftiMasker
class BaseMasker:
def __init__(self):
"""
Build a Dypac-like masker from labels.
Parameters
----------
... | 0.953242 | 0.644029 |
import unittest
import os
import opentimelineio as otio
from tests import baseline_reader
"""Unit tests for the schemadef plugin system."""
SCHEMADEF_NAME = "schemadef_example"
EXAMPLE_ARG = "exampleArg"
EXCLASS = "<class 'opentimelineio.schemadef.example_schemadef.exampleSchemaDef'>"
TEST_STRING = """
{
"OTIO_... | tests/test_schemadef_plugin.py | import unittest
import os
import opentimelineio as otio
from tests import baseline_reader
"""Unit tests for the schemadef plugin system."""
SCHEMADEF_NAME = "schemadef_example"
EXAMPLE_ARG = "exampleArg"
EXCLASS = "<class 'opentimelineio.schemadef.example_schemadef.exampleSchemaDef'>"
TEST_STRING = """
{
"OTIO_... | 0.563978 | 0.251523 |
import pandas as pd
from warnings import warn
from google.api_core.exceptions import NotFound
from carto.exceptions import CartoException
from ...clients.bigquery_client import BigQueryClient
from ....auth import Credentials, defaults
try:
from abc import ABC
except ImportError:
from abc import ABCMeta
... | cartoframes/data/observatory/catalog/entity.py | import pandas as pd
from warnings import warn
from google.api_core.exceptions import NotFound
from carto.exceptions import CartoException
from ...clients.bigquery_client import BigQueryClient
from ....auth import Credentials, defaults
try:
from abc import ABC
except ImportError:
from abc import ABCMeta
... | 0.557123 | 0.125977 |
from __future__ import annotations
import itertools
from typing import Any, Tuple
from collections.abc import Iterable
import pandas as pd
import numpy as np
ITEMID = "item_id"
TIMESTAMP = "timestamp"
class TimeSeriesDataFrame(pd.DataFrame):
"""TimeSeriesDataFrame to represent time-series dataset.
Parame... | forecasting/src/autogluon/forecasting/dataset/ts_dataframe.py | from __future__ import annotations
import itertools
from typing import Any, Tuple
from collections.abc import Iterable
import pandas as pd
import numpy as np
ITEMID = "item_id"
TIMESTAMP = "timestamp"
class TimeSeriesDataFrame(pd.DataFrame):
"""TimeSeriesDataFrame to represent time-series dataset.
Parame... | 0.815416 | 0.435241 |
from abc import ABC, abstractmethod
from collections import defaultdict
from pathlib import Path
from typing import Dict, List, Tuple
from brainframe.api import BrainFrameAPI
from brainframe.api.bf_codecs import Identity
VECTOR = List[float]
# TODO: Use @dataclass decorator in Python3.7
class IdentityPrototype:
... | brainframe_qt/api_utils/identities/identity_finder.py | from abc import ABC, abstractmethod
from collections import defaultdict
from pathlib import Path
from typing import Dict, List, Tuple
from brainframe.api import BrainFrameAPI
from brainframe.api.bf_codecs import Identity
VECTOR = List[float]
# TODO: Use @dataclass decorator in Python3.7
class IdentityPrototype:
... | 0.696268 | 0.351784 |
import rospy
import cv2
from sensor_msgs.msg import Image
from cv_bridge import CvBridge, CvBridgeError
import ast
from mil_vision_tools import CentroidObjectsTracker, TrackedObject
from vision_utils import centroid
from overlay import Overlay
from mil_msgs.msg import ObjectsInImage, ObjectInImage
import numpy as np... | perception/mil_vision/src/mil_unified_vision_interface/image_object_tracker.py |
import rospy
import cv2
from sensor_msgs.msg import Image
from cv_bridge import CvBridge, CvBridgeError
import ast
from mil_vision_tools import CentroidObjectsTracker, TrackedObject
from vision_utils import centroid
from overlay import Overlay
from mil_msgs.msg import ObjectsInImage, ObjectInImage
import numpy as np... | 0.414069 | 0.183557 |
from __future__ import absolute_import, division, print_function
from elasticsearch import Elasticsearch
import brorig.log as log
class SearchManager:
def __init__(self, index):
self.index = "brorig_%s" % index.lower()
self.es = Elasticsearch()
if not self.es.ping():
log.wa... | brorig/search.py |
from __future__ import absolute_import, division, print_function
from elasticsearch import Elasticsearch
import brorig.log as log
class SearchManager:
def __init__(self, index):
self.index = "brorig_%s" % index.lower()
self.es = Elasticsearch()
if not self.es.ping():
log.wa... | 0.596433 | 0.195536 |
import numpy as np
import matplotlib.pyplot as plt
import pandas as pd
df=pd.read_csv("ex2data1.txt",header=None)
X=df.iloc[:,:-1].values
y=df.iloc[:,-1].values
def sigmoid(z):
return 1 / (1 + np.exp(-z))
def costFunction(theta, X, y):
"""
Takes in numpy array theta, x and y and return the logistic regr... | and.py | import numpy as np
import matplotlib.pyplot as plt
import pandas as pd
df=pd.read_csv("ex2data1.txt",header=None)
X=df.iloc[:,:-1].values
y=df.iloc[:,-1].values
def sigmoid(z):
return 1 / (1 + np.exp(-z))
def costFunction(theta, X, y):
"""
Takes in numpy array theta, x and y and return the logistic regr... | 0.295027 | 0.710402 |
from __future__ import print_function
import numpy as np
import sys
import matplotlib.pyplot as plt
import matplotlib.pylab as pylab
params = {'legend.fontsize': 'x-large',
'figure.figsize': (13, 6),
'figure.autolayout': True,
'axes.labelsize': 'x-large',
'axes.titlesize':'x-lar... | Plots/plot_timing_histo.py |
from __future__ import print_function
import numpy as np
import sys
import matplotlib.pyplot as plt
import matplotlib.pylab as pylab
params = {'legend.fontsize': 'x-large',
'figure.figsize': (13, 6),
'figure.autolayout': True,
'axes.labelsize': 'x-large',
'axes.titlesize':'x-lar... | 0.396769 | 0.415551 |
from os import _exit
from traceback import print_exception
import os
import sys
try:
_FLAGS = None
# In the pip module the library also exports the clingo symbols, which
# should be globally available for other libraries depending on clingo.
if hasattr(sys, 'setdlopenflags'):
_FLAGS = sys.getdlo... | libpyclingo/clingo/_internal.py | from os import _exit
from traceback import print_exception
import os
import sys
try:
_FLAGS = None
# In the pip module the library also exports the clingo symbols, which
# should be globally available for other libraries depending on clingo.
if hasattr(sys, 'setdlopenflags'):
_FLAGS = sys.getdlo... | 0.401923 | 0.075109 |
import os
import sys
import copy
import json
from matplotlib import rc,rcParams
from pathlib import Path
class PlotSettings(object):
""" Class which holds configuration settings for graphdata."""
def __init__(self):
self._G = self.loadsettings()
self._LSoptions = {'basic':['k-o','k--d','k-.s',... | graphdata/settings/settings.py |
import os
import sys
import copy
import json
from matplotlib import rc,rcParams
from pathlib import Path
class PlotSettings(object):
""" Class which holds configuration settings for graphdata."""
def __init__(self):
self._G = self.loadsettings()
self._LSoptions = {'basic':['k-o','k--d','k-.s',... | 0.449634 | 0.13134 |
import glob
import multiprocessing.pool
import os
import tarfile
import urllib.request
import warnings
from setuptools import setup, find_packages, distutils
from torch.utils.cpp_extension import BuildExtension
from torch.utils.cpp_extension import CppExtension, include_paths
def download_extract(url, dl_path):
... | setup.py | import glob
import multiprocessing.pool
import os
import tarfile
import urllib.request
import warnings
from setuptools import setup, find_packages, distutils
from torch.utils.cpp_extension import BuildExtension
from torch.utils.cpp_extension import CppExtension, include_paths
def download_extract(url, dl_path):
... | 0.379608 | 0.073997 |
from __future__ import division, print_function, absolute_import
import weakref
import numpy as np
# -------------------------------------
# Dictionary
# -------------------------------------
class LazyDict(dict):
def get(self, k, d=None, *args):
return self[k] if k in self else d(*args) if callable(d) e... | rlpy/auxiliary/collection_ext.py | from __future__ import division, print_function, absolute_import
import weakref
import numpy as np
# -------------------------------------
# Dictionary
# -------------------------------------
class LazyDict(dict):
def get(self, k, d=None, *args):
return self[k] if k in self else d(*args) if callable(d) e... | 0.757436 | 0.19046 |
from actioners.interfaces.i_login_control import ILoginControl
from actioners.navigator import Navigator
import time
class LoginControl(ILoginControl):
def __init__(self, wd, login_ui):
self.wd = wd
self.login_ui = login_ui
self.login_page_url = "https://www.stockopedia.com/auth/login/"
... | src/actioners/login_control.py | from actioners.interfaces.i_login_control import ILoginControl
from actioners.navigator import Navigator
import time
class LoginControl(ILoginControl):
def __init__(self, wd, login_ui):
self.wd = wd
self.login_ui = login_ui
self.login_page_url = "https://www.stockopedia.com/auth/login/"
... | 0.304765 | 0.055311 |
import contextlib
import gettext
import os
import babel
import babel.support
import six
import speaklater
from morphi.libs import packages
class Manager(object):
"""Manages translations"""
def __init__(self, dirname=None, locales=None, domain=None, package_name=None):
self._locales = None
s... | morphi/messages/manager.py | import contextlib
import gettext
import os
import babel
import babel.support
import six
import speaklater
from morphi.libs import packages
class Manager(object):
"""Manages translations"""
def __init__(self, dirname=None, locales=None, domain=None, package_name=None):
self._locales = None
s... | 0.510985 | 0.101233 |
import os
import logging
import random
import json
import numpy as np
import torch
import sklearn.metrics
from torch.utils.data import TensorDataset, DataLoader, RandomSampler, SequentialSampler
from pytorch_pretrained_bert.tokenization import BertTokenizer
from pytorch_pretrained_bert.modeling import BertForSeque... | asclab/adaweight.py |
import os
import logging
import random
import json
import numpy as np
import torch
import sklearn.metrics
from torch.utils.data import TensorDataset, DataLoader, RandomSampler, SequentialSampler
from pytorch_pretrained_bert.tokenization import BertTokenizer
from pytorch_pretrained_bert.modeling import BertForSeque... | 0.606032 | 0.304274 |
import sys
from http import HTTPStatus
import requests
from rich import box
from rich.panel import Panel
from rich.table import Table
from starwhale.utils import console, fmt_http_server
from starwhale.consts import UserRoleType, SW_API_VERSION, STANDALONE_INSTANCE
from starwhale.base.view import BaseTermView
from st... | client/starwhale/core/instance/view.py | import sys
from http import HTTPStatus
import requests
from rich import box
from rich.panel import Panel
from rich.table import Table
from starwhale.utils import console, fmt_http_server
from starwhale.consts import UserRoleType, SW_API_VERSION, STANDALONE_INSTANCE
from starwhale.base.view import BaseTermView
from st... | 0.192198 | 0.101545 |
from typing import Dict, MutableMapping, Mapping, TypeVar, List
from antu.io.vocabulary import Vocabulary
from antu.io.fields.field import Field
Indices = TypeVar("Indices", List[int], List[List[int]])
class Instance(Mapping[str, Field]):
"""
An ``Instance`` is a collection (list) of multiple data fields.
... | antu/io/instance.py | from typing import Dict, MutableMapping, Mapping, TypeVar, List
from antu.io.vocabulary import Vocabulary
from antu.io.fields.field import Field
Indices = TypeVar("Indices", List[int], List[List[int]])
class Instance(Mapping[str, Field]):
"""
An ``Instance`` is a collection (list) of multiple data fields.
... | 0.932905 | 0.548794 |
import torch
from sklearn.metrics import accuracy_score
from torch.nn import Linear
from torch.nn.functional import relu, dropout, log_softmax, nll_loss, leaky_relu
from torch_geometric.nn import APPNP
from torch_geometric.utils.num_nodes import maybe_num_nodes
from torch_sparse import coalesce
from Result import Resu... | ModelAPPNP2.py | import torch
from sklearn.metrics import accuracy_score
from torch.nn import Linear
from torch.nn.functional import relu, dropout, log_softmax, nll_loss, leaky_relu
from torch_geometric.nn import APPNP
from torch_geometric.utils.num_nodes import maybe_num_nodes
from torch_sparse import coalesce
from Result import Resu... | 0.918435 | 0.561636 |
import sys, os
root_dir = os.path.join(os.path.dirname(__file__),'..')
if root_dir not in sys.path:
sys.path.insert(0, root_dir)
from dataset.image_base import *
from config import args
set_names = {'all':['train','val','test'],'test':['test'],'val':['train','val','test']}
class PW3D(Image_base):
def __init__... | src/lib/dataset/pw3d.py | import sys, os
root_dir = os.path.join(os.path.dirname(__file__),'..')
if root_dir not in sys.path:
sys.path.insert(0, root_dir)
from dataset.image_base import *
from config import args
set_names = {'all':['train','val','test'],'test':['test'],'val':['train','val','test']}
class PW3D(Image_base):
def __init__... | 0.276886 | 0.205795 |
import time
import random
from qtpy.QtCore import Signal, QByteArray, QPoint, QRect, QSize, QTimer, Qt, QObject, QUrl
from qtpy.QtGui import QBrush, QColor, QFont, QImage, QPainter
from qtpy.QtWidgets import QWidget
from qtpy.QtNetwork import QNetworkRequest, QNetworkAccessManager
class Downloader(QObject):
imag... | microscope/microscope.py | import time
import random
from qtpy.QtCore import Signal, QByteArray, QPoint, QRect, QSize, QTimer, Qt, QObject, QUrl
from qtpy.QtGui import QBrush, QColor, QFont, QImage, QPainter
from qtpy.QtWidgets import QWidget
from qtpy.QtNetwork import QNetworkRequest, QNetworkAccessManager
class Downloader(QObject):
imag... | 0.429429 | 0.275958 |
import re
from typing import Iterator, Optional
from google.cloud import storage
from ..config import get_config_value
from ..key import StairlightConfigKey
from .base import Template, TemplateSource, TemplateSourceType
from .controller import GCS_URI_SCHEME
class GcsTemplate(Template):
def __init__(
se... | src/stairlight/source/gcs.py | import re
from typing import Iterator, Optional
from google.cloud import storage
from ..config import get_config_value
from ..key import StairlightConfigKey
from .base import Template, TemplateSource, TemplateSourceType
from .controller import GCS_URI_SCHEME
class GcsTemplate(Template):
def __init__(
se... | 0.818592 | 0.079782 |
from solentware_grid.gui.datadelete import DataDelete
from solentware_misc.gui.exceptionhandler import ExceptionHandler
from pgn_read.core.parser import PGN
from ..core.constants import TAG_OPENING
from .repertoiretoplevel import RepertoireToplevel
from .toplevelpgn import DeletePGN
class RepertoireDbDelete(Except... | chesstab/gui/repertoiredbdelete.py | from solentware_grid.gui.datadelete import DataDelete
from solentware_misc.gui.exceptionhandler import ExceptionHandler
from pgn_read.core.parser import PGN
from ..core.constants import TAG_OPENING
from .repertoiretoplevel import RepertoireToplevel
from .toplevelpgn import DeletePGN
class RepertoireDbDelete(Except... | 0.639961 | 0.347316 |
from PIL import Image
from keras.layers import Dense, Input, Conv2D, LSTM, MaxPool2D, UpSampling2D
from sklearn.model_selection import train_test_split
from keras.callbacks import EarlyStopping
from keras.utils import to_categorical
from numpy import argmax, array_equal
import matplotlib.pyplot as plt
from keras.models... | modeling/deep_learning/auto_encoder/image_reconstruction.py | from PIL import Image
from keras.layers import Dense, Input, Conv2D, LSTM, MaxPool2D, UpSampling2D
from sklearn.model_selection import train_test_split
from keras.callbacks import EarlyStopping
from keras.utils import to_categorical
from numpy import argmax, array_equal
import matplotlib.pyplot as plt
from keras.models... | 0.867134 | 0.492859 |
from __future__ import absolute_import, division, print_function
__author__ = "<NAME>"
__license__ = """Copyright 2017-2019 <NAME> and <NAME>
Licensed under the Apache License, Version 2.0 (the "License");
you may not use this file except in compliance with the License.
You may obtain a copy of the License at
ht... | retro/i3reco.py | from __future__ import absolute_import, division, print_function
__author__ = "<NAME>"
__license__ = """Copyright 2017-2019 <NAME> and <NAME>
Licensed under the Apache License, Version 2.0 (the "License");
you may not use this file except in compliance with the License.
You may obtain a copy of the License at
ht... | 0.675444 | 0.103794 |
import logging
import math
import random
import re
from contextlib import contextmanager
from datetime import datetime, timedelta, timezone
from typing import Optional, Tuple
from sqlalchemy import create_engine
from sqlalchemy.orm import Session, sessionmaker
from telegram import (Bot, ChatPermissions, InlineKeyboard... | gatebot/bot.py | import logging
import math
import random
import re
from contextlib import contextmanager
from datetime import datetime, timedelta, timezone
from typing import Optional, Tuple
from sqlalchemy import create_engine
from sqlalchemy.orm import Session, sessionmaker
from telegram import (Bot, ChatPermissions, InlineKeyboard... | 0.727395 | 0.066569 |
from flask import Blueprint, redirect, url_for
from flask_babel import gettext
from flask_login import current_user, login_required
from werkzeug.exceptions import BadRequest
import critiquebrainz.db.review as db_review
from critiquebrainz.frontend import flash
from critiquebrainz.frontend.forms.rate import RatingEdi... | critiquebrainz/frontend/views/rate.py |
from flask import Blueprint, redirect, url_for
from flask_babel import gettext
from flask_login import current_user, login_required
from werkzeug.exceptions import BadRequest
import critiquebrainz.db.review as db_review
from critiquebrainz.frontend import flash
from critiquebrainz.frontend.forms.rate import RatingEdi... | 0.295535 | 0.055413 |
import contextlib
import inspect
import itertools
import functools
import warnings
from lisa.analysis.base import TraceAnalysisBase
from lisa.utils import Loggable, sig_bind
class _AnalysisPreset:
def __init__(self, instance, params):
self._instance = instance
self._params = params
def __get... | lisa/analysis/_proxy.py | import contextlib
import inspect
import itertools
import functools
import warnings
from lisa.analysis.base import TraceAnalysisBase
from lisa.utils import Loggable, sig_bind
class _AnalysisPreset:
def __init__(self, instance, params):
self._instance = instance
self._params = params
def __get... | 0.655777 | 0.145267 |
import numpy as np
from numpy.core.records import fromarrays
from scipy.io import savemat
from .utils import cart_to_eeglab
def export_set(fname, data, sfreq, ch_names, ch_locs=None, annotations=None,
ref_channels="common"):
"""Export continuous raw data to EEGLAB's .set format.
Parameters
... | eeglabio/raw.py | import numpy as np
from numpy.core.records import fromarrays
from scipy.io import savemat
from .utils import cart_to_eeglab
def export_set(fname, data, sfreq, ch_names, ch_locs=None, annotations=None,
ref_channels="common"):
"""Export continuous raw data to EEGLAB's .set format.
Parameters
... | 0.887449 | 0.539347 |
import datetime
import pandas as pd
from pandas import DataFrame
from tabulate import tabulate
from base import BaseObject
from datamongo import BaseMongoClient
from datamongo import CendantCollection
class CountMongoCollections(BaseObject):
""" Provide a convenient way to count the total records in MongoDB c... | python/taskadmin/core/svc/count_mongo_collections.py |
import datetime
import pandas as pd
from pandas import DataFrame
from tabulate import tabulate
from base import BaseObject
from datamongo import BaseMongoClient
from datamongo import CendantCollection
class CountMongoCollections(BaseObject):
""" Provide a convenient way to count the total records in MongoDB c... | 0.700075 | 0.179531 |
import argparse
import csv
import logging
import sys
from src.utils.predict_entailment import PredictEntailment
class PredictMnliEntailment:
"""
Entailment task predictor for MNLI Tsv dataset
"""
def __init__(self, prediction_csv_file, outputfile, model_or_path, tokenisor_or_path,
d... | src/utils/predict_mnli_entailment.py | import argparse
import csv
import logging
import sys
from src.utils.predict_entailment import PredictEntailment
class PredictMnliEntailment:
"""
Entailment task predictor for MNLI Tsv dataset
"""
def __init__(self, prediction_csv_file, outputfile, model_or_path, tokenisor_or_path,
d... | 0.591251 | 0.256891 |
import asyncio
import logging
# XXX: REMOVE THIS LINE IN PRODUCTION!
logging.basicConfig(format='%(asctime)s %(lineno)d %(levelname)s:%(message)s', level=logging.DEBUG)
logger = logging.getLogger(__name__)
# Connected client records
clients = dict()
async def show_tasks():
"""FOR DEBUGGING"""
while True:
... | asyncio/asyncio_socket_server.py | import asyncio
import logging
# XXX: REMOVE THIS LINE IN PRODUCTION!
logging.basicConfig(format='%(asctime)s %(lineno)d %(levelname)s:%(message)s', level=logging.DEBUG)
logger = logging.getLogger(__name__)
# Connected client records
clients = dict()
async def show_tasks():
"""FOR DEBUGGING"""
while True:
... | 0.282196 | 0.067362 |
from numpy.random import randn
from numpy import *
# generate some overlapping training vectors
num_vectors=5
vec_distance=1
traindat=concatenate((randn(2,num_vectors)-vec_distance,
randn(2,num_vectors)+vec_distance), axis=1)
label_traindat=concatenate((-ones(num_vectors), ones(num_vectors)));
parameter_list = [[tr... | examples/undocumented/python_modular/evaluation_cross_validation_mkl_weight_storage.py |
from numpy.random import randn
from numpy import *
# generate some overlapping training vectors
num_vectors=5
vec_distance=1
traindat=concatenate((randn(2,num_vectors)-vec_distance,
randn(2,num_vectors)+vec_distance), axis=1)
label_traindat=concatenate((-ones(num_vectors), ones(num_vectors)));
parameter_list = [[tr... | 0.46952 | 0.303029 |
# # Programación funcional en Python
# Veamos a nuestros nuevos amigos. He aquí una lista con una descripción increíblemente útil. Posteriormente los veremos en acción.
#
# 1. ```lambda``` : Declarar una función anónima.
# 2. ```map``` : Mapear, se especifica primero la función y después el objeto.
# 3. ```filter```... | Ejercicios_funcionales.py |
# # Programación funcional en Python
# Veamos a nuestros nuevos amigos. He aquí una lista con una descripción increíblemente útil. Posteriormente los veremos en acción.
#
# 1. ```lambda``` : Declarar una función anónima.
# 2. ```map``` : Mapear, se especifica primero la función y después el objeto.
# 3. ```filter```... | 0.520009 | 0.962883 |
import json
import networkx as nx
from typing import List, Set, Tuple
from nltk.corpus import stopwords
from collections import defaultdict, Counter
def tuple_contains(tup1: Tuple, tup2: Tuple) -> Tuple[bool, int]:
"""Check whether tuple 1 contains tuple 2"""
len_tup1, len_tup2 = len(tup1), len(tup2)
for ... | labelset_hierarchy.py | import json
import networkx as nx
from typing import List, Set, Tuple
from nltk.corpus import stopwords
from collections import defaultdict, Counter
def tuple_contains(tup1: Tuple, tup2: Tuple) -> Tuple[bool, int]:
"""Check whether tuple 1 contains tuple 2"""
len_tup1, len_tup2 = len(tup1), len(tup2)
for ... | 0.580233 | 0.343452 |
import weakref
from typing import Any, Mapping, Sequence, TypeVar, Union
from annotypes import Anno, Array
from malcolm.core import Context, Hook, Part
from .infos import LayoutInfo, PortInfo
from .util import LayoutTable
with Anno("The part that has attached to the Hook"):
APart = Part
with Anno("Context that ... | malcolm/modules/builtin/hooks.py | import weakref
from typing import Any, Mapping, Sequence, TypeVar, Union
from annotypes import Anno, Array
from malcolm.core import Context, Hook, Part
from .infos import LayoutInfo, PortInfo
from .util import LayoutTable
with Anno("The part that has attached to the Hook"):
APart = Part
with Anno("Context that ... | 0.880784 | 0.288958 |
from keras.layers import concatenate
from keras import optimizers
from keras.callbacks import EarlyStopping, ModelCheckpoint
import numpy as np
import json
from sanspy.utils import get_df, alias, mem_usage
from sanspy.callbacks import SaveHistoryEpochEnd
class Model(object):
"""
Model class as a wrapper for Keras. C... | sanspy/model.py | from keras.layers import concatenate
from keras import optimizers
from keras.callbacks import EarlyStopping, ModelCheckpoint
import numpy as np
import json
from sanspy.utils import get_df, alias, mem_usage
from sanspy.callbacks import SaveHistoryEpochEnd
class Model(object):
"""
Model class as a wrapper for Keras. C... | 0.879406 | 0.433682 |
import numpy as np
from scipy.stats import norm
import matplotlib.pyplot as plt
class BayesModel:
def __init__(self, data, prior_range):
self.data = data
def pdata(data, mu):
r"""
Probability of :math:`x` given :math:`theta`, assuming :math:`\sigma = 1`.
"""
return norm.pdf(data, loc=mu).prod()
self... | MCMC/bayes.py | import numpy as np
from scipy.stats import norm
import matplotlib.pyplot as plt
class BayesModel:
def __init__(self, data, prior_range):
self.data = data
def pdata(data, mu):
r"""
Probability of :math:`x` given :math:`theta`, assuming :math:`\sigma = 1`.
"""
return norm.pdf(data, loc=mu).prod()
self... | 0.673406 | 0.714055 |
from PyQt5 import QtWidgets, uic, QtGui
from PyQt5.QtWidgets import *
from resultCal import ResultCalculator
courses = 0
def nextPage():
clear()
result.hide()
ask.hide()
table.show()
returnRowCount()
def back():
result.hide()
ask.show()
table.hide()
def returnRowCount():
... | MainCal.py | from PyQt5 import QtWidgets, uic, QtGui
from PyQt5.QtWidgets import *
from resultCal import ResultCalculator
courses = 0
def nextPage():
clear()
result.hide()
ask.hide()
table.show()
returnRowCount()
def back():
result.hide()
ask.show()
table.hide()
def returnRowCount():
... | 0.319971 | 0.262738 |
# This file is included by CMakeLists.txt.
#[[
import importlib
import glob
import os
import subprocess
import sys
from test_case import TestCase
class Generator(object):
def __init__(self, dirname, filename, fail=False):
self.dirname = dirname
self.category = dirname.replace('/', '_')
... | scripts/elichika_tests.py |
# This file is included by CMakeLists.txt.
#[[
import importlib
import glob
import os
import subprocess
import sys
from test_case import TestCase
class Generator(object):
def __init__(self, dirname, filename, fail=False):
self.dirname = dirname
self.category = dirname.replace('/', '_')
... | 0.36693 | 0.160102 |
"""Test suite for demoproject.download."""
from django.test import TestCase
try:
from django.urls import reverse
except ImportError:
from django.core.urlresolvers import reverse
from django_anysign import api as django_anysign
class HomeURLTestCase(TestCase):
"""Test homepage."""
def test_get(self):
... | demo/django_anysign_demo/tests.py | """Test suite for demoproject.download."""
from django.test import TestCase
try:
from django.urls import reverse
except ImportError:
from django.core.urlresolvers import reverse
from django_anysign import api as django_anysign
class HomeURLTestCase(TestCase):
"""Test homepage."""
def test_get(self):
... | 0.718199 | 0.275687 |
from .api import grid_pull
from .utils import make_list, meshgrid_ij
import torch
def resize(image, factor=None, shape=None, anchor='c',
interpolation=1, prefilter=True, **kwargs):
"""Resize an image by a factor or to a specific shape.
Notes
-----
.. A least one of `factor` and `shape` mus... | interpol/resize.py | from .api import grid_pull
from .utils import make_list, meshgrid_ij
import torch
def resize(image, factor=None, shape=None, anchor='c',
interpolation=1, prefilter=True, **kwargs):
"""Resize an image by a factor or to a specific shape.
Notes
-----
.. A least one of `factor` and `shape` mus... | 0.913869 | 0.44903 |
# http://www.apache.org/licenses/LICENSE-2.0.html
# Unless required by applicable law or agreed to in writing, software
# distributed under the License is distributed on an "AS IS" BASIS,
# WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
# See the License for the specific language gover... | Model/lookalike-model/lookalike_model/pipeline/main_keywords.py |
# http://www.apache.org/licenses/LICENSE-2.0.html
# Unless required by applicable law or agreed to in writing, software
# distributed under the License is distributed on an "AS IS" BASIS,
# WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
# See the License for the specific language gover... | 0.631935 | 0.318485 |
import os
import numpy as np
import pandas as pd
from collections import Counter
from sklearn.model_selection import train_test_split
from sklearn.externals import joblib
import json
import cv2
from time import time
import threading
import math
DATASET={'CCT':'iWildCam_2019_CCT','iNat':'iWildCam_2019_iNat_Idaho','IDFG... | prep_data.py | import os
import numpy as np
import pandas as pd
from collections import Counter
from sklearn.model_selection import train_test_split
from sklearn.externals import joblib
import json
import cv2
from time import time
import threading
import math
DATASET={'CCT':'iWildCam_2019_CCT','iNat':'iWildCam_2019_iNat_Idaho','IDFG... | 0.045205 | 0.124985 |
import torch
import torch.nn as nn
import torch.nn.functional as F
from data.scaling import DataScaler
class ResidualOutputModule(nn.Module):
def __init__(self, model, learn_residuals, scalings_lr=None, scalings_hr=None, interpolation_mode='bicubic'):
super(ResidualOutputModule, self).__init__()
s... | networks/modular_downscaling_model/output_modules/ResidualOutputModule.py | import torch
import torch.nn as nn
import torch.nn.functional as F
from data.scaling import DataScaler
class ResidualOutputModule(nn.Module):
def __init__(self, model, learn_residuals, scalings_lr=None, scalings_hr=None, interpolation_mode='bicubic'):
super(ResidualOutputModule, self).__init__()
s... | 0.915992 | 0.331607 |
# GNU General Public License v3.0+ (see COPYING or https://www.gnu.org/licenses/gpl-3.0.txt)
from __future__ import absolute_import, division, print_function
__metaclass__ = type
DOCUMENTATION = '''
---
module: zabbix_action
short_description: Create/Delete/Update Zabbix actions
description:
- This module a... | venv/lib/python3.6/site-packages/ansible_collections/community/zabbix/plugins/modules/zabbix_action.py |
# GNU General Public License v3.0+ (see COPYING or https://www.gnu.org/licenses/gpl-3.0.txt)
from __future__ import absolute_import, division, print_function
__metaclass__ = type
DOCUMENTATION = '''
---
module: zabbix_action
short_description: Create/Delete/Update Zabbix actions
description:
- This module a... | 0.827724 | 0.260196 |
import re
import socket
from cfgm_common import PERMS_RX
from vnc_api.gen.resource_common import VirtualDns
from vnc_cfg_api_server.resources._resource_base import ResourceMixin
class VirtualDnsServer(ResourceMixin, VirtualDns):
@classmethod
def pre_dbe_create(cls, tenant_name, obj_dict, db_conn):
... | src/config/api-server/vnc_cfg_api_server/resources/virtual_dns.py |
import re
import socket
from cfgm_common import PERMS_RX
from vnc_api.gen.resource_common import VirtualDns
from vnc_cfg_api_server.resources._resource_base import ResourceMixin
class VirtualDnsServer(ResourceMixin, VirtualDns):
@classmethod
def pre_dbe_create(cls, tenant_name, obj_dict, db_conn):
... | 0.45641 | 0.054955 |
import sys
from setuptools import setup
# load __version__
exec(open("pyrender/version.py").read())
def get_imageio_dep():
if sys.version[0] == "2":
return "imageio<=2.6.1"
return "imageio"
requirements = [
"freetype-py", # For font loading
get_imageio_dep(), # For Image I/O
"networkx... | setup.py | import sys
from setuptools import setup
# load __version__
exec(open("pyrender/version.py").read())
def get_imageio_dep():
if sys.version[0] == "2":
return "imageio<=2.6.1"
return "imageio"
requirements = [
"freetype-py", # For font loading
get_imageio_dep(), # For Image I/O
"networkx... | 0.316792 | 0.287112 |
import os
import tqdm
import numpy as np
import tensorflow as tf
gpu_id='2'
class Config:
train_path='/data/dataset/pinyin2hanzi/py2hz_train.tsv'
hz2id_dict='/data/dataset/dict/hz2id_dict.txt'
test_path='/data/dataset/pinyin2hanzi/py2hz_test.tsv'
dev_path='/data/dataset/pinyin2hanzi/py2hz_dev.tsv'
p... | language_model/CBHG_self.py | import os
import tqdm
import numpy as np
import tensorflow as tf
gpu_id='2'
class Config:
train_path='/data/dataset/pinyin2hanzi/py2hz_train.tsv'
hz2id_dict='/data/dataset/dict/hz2id_dict.txt'
test_path='/data/dataset/pinyin2hanzi/py2hz_test.tsv'
dev_path='/data/dataset/pinyin2hanzi/py2hz_dev.tsv'
p... | 0.608361 | 0.268797 |
from __future__ import absolute_import
from __future__ import division
from __future__ import print_function
import numpy as np
def median_filter(x, y, num_bins, bin_width=None, x_min=None, x_max=None):
"""Computes the median y-value in uniform intervals (bins) along the x-axis.
The interval [x_min, x_max) is d... | research/astronet/light_curve_util/median_filter.py | from __future__ import absolute_import
from __future__ import division
from __future__ import print_function
import numpy as np
def median_filter(x, y, num_bins, bin_width=None, x_min=None, x_max=None):
"""Computes the median y-value in uniform intervals (bins) along the x-axis.
The interval [x_min, x_max) is d... | 0.909459 | 0.691758 |
import sys
import argparse
import time
import threading
import os
import logging
import power_reader
from argparse import RawTextHelpFormatter
scriptLocation = os.path.dirname(os.path.realpath(__file__))
def rebootThread(waitTime, stop_event):
logging.debug('Starting reboot thread, booting in ' + str(waitTime) +... | power-supervisor.py |
import sys
import argparse
import time
import threading
import os
import logging
import power_reader
from argparse import RawTextHelpFormatter
scriptLocation = os.path.dirname(os.path.realpath(__file__))
def rebootThread(waitTime, stop_event):
logging.debug('Starting reboot thread, booting in ' + str(waitTime) +... | 0.233881 | 0.066206 |
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... | pgoapi/protos/pogoprotos/data/gym/gym_battle_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.160529 | 0.169922 |
import string
def translate(self, symbol_table):
return ''.join([symbol_table.get(c, c) for c in self])
def as_rest_table(data, full=False):
"""
>>> from report_table import as_rest_table
>>> data = [('what', 'how', 'who'),
... ('lorem', 'that is a long value', 3.1415),
... ... | docs/source/exts/rst_table.py |
import string
def translate(self, symbol_table):
return ''.join([symbol_table.get(c, c) for c in self])
def as_rest_table(data, full=False):
"""
>>> from report_table import as_rest_table
>>> data = [('what', 'how', 'who'),
... ('lorem', 'that is a long value', 3.1415),
... ... | 0.446736 | 0.39129 |
import lxmls.readers.simple_data_set as sds
import lxmls.classifiers.linear_classifier as lcc
import lxmls.classifiers.naive_bayes as nbc
import lxmls.classifiers.perceptron as percc
import lxmls.classifiers.svm as svmc
import lxmls.classifiers.mira as mirac
import lxmls.classifiers.max_ent_batch as mec_batch
import lx... | lxmls/run_all_classifiers.py | import lxmls.readers.simple_data_set as sds
import lxmls.classifiers.linear_classifier as lcc
import lxmls.classifiers.naive_bayes as nbc
import lxmls.classifiers.perceptron as percc
import lxmls.classifiers.svm as svmc
import lxmls.classifiers.mira as mirac
import lxmls.classifiers.max_ent_batch as mec_batch
import lx... | 0.361954 | 0.358241 |
import re
import datetime
# Logger:
import logging
logging.basicConfig(filename='cstats.log', filemode='w', level='DEBUG',format='%(asctime)s - %(name)s [%(levelname)s] %(message)s', datefmt='%d-%b-%y %H:%M:%S')
class Convertor():
def cleanup():
"""
Removing the first couple of lines, because ... | python/parsetext.py | import re
import datetime
# Logger:
import logging
logging.basicConfig(filename='cstats.log', filemode='w', level='DEBUG',format='%(asctime)s - %(name)s [%(levelname)s] %(message)s', datefmt='%d-%b-%y %H:%M:%S')
class Convertor():
def cleanup():
"""
Removing the first couple of lines, because ... | 0.324342 | 0.137446 |
testA = [ 2, 1, 5, 3, 4 ];
testB = [ 2, 5, 1, 3, 4 ];
testC = [ 2,
1,
4,
5,
3,
8,
7,
10,
6,
12,
11,
9,
15,
13,
16,
18,
14,
19,
21,
17,
23,
22,
20,
26,
24,
27,
25,
29,
28,
31,
30,
34,
32,
36,
35,
38,
33,
40,
39,
37,
43,
42,
41,
46,
4... | coding-challenges/hacker-rank/algorithms/NewYearsChaos.py | testA = [ 2, 1, 5, 3, 4 ];
testB = [ 2, 5, 1, 3, 4 ];
testC = [ 2,
1,
4,
5,
3,
8,
7,
10,
6,
12,
11,
9,
15,
13,
16,
18,
14,
19,
21,
17,
23,
22,
20,
26,
24,
27,
25,
29,
28,
31,
30,
34,
32,
36,
35,
38,
33,
40,
39,
37,
43,
42,
41,
46,
4... | 0.155431 | 0.288156 |
import requests
import argparse
import json
SCRYFALL_CARDS_API = "https://api.scryfall.com/cards"
SCRYFALL_SETS_API = "https://api.scryfall.com/sets"
SCRYFALL_SET_CONVERSION = {
'G18' : 'M19'
}
def normalize_set(set_id):
return SCRYFALL_SET_CONVERSION.get(set_id, set_id)
class ScryfallError(ValueError):
... | scryfall.py | import requests
import argparse
import json
SCRYFALL_CARDS_API = "https://api.scryfall.com/cards"
SCRYFALL_SETS_API = "https://api.scryfall.com/sets"
SCRYFALL_SET_CONVERSION = {
'G18' : 'M19'
}
def normalize_set(set_id):
return SCRYFALL_SET_CONVERSION.get(set_id, set_id)
class ScryfallError(ValueError):
... | 0.263789 | 0.071786 |
import tensorflow as tf
from tensorflow.keras import Input
from tensorflow.keras.layers import Dropout
from tensorflow.keras.optimizers import Adam
from tensorflow.keras import regularizers
from tensorflow.keras.losses import SparseCategoricalCrossentropy
from graphgallery.nn.layers.tensorflow import GCNConv
f... | graphgallery/gallery/nodeclas/tensorflow/experimental/s_obvat.py | import tensorflow as tf
from tensorflow.keras import Input
from tensorflow.keras.layers import Dropout
from tensorflow.keras.optimizers import Adam
from tensorflow.keras import regularizers
from tensorflow.keras.losses import SparseCategoricalCrossentropy
from graphgallery.nn.layers.tensorflow import GCNConv
f... | 0.865565 | 0.500732 |
from django.contrib.contenttypes.models import ContentType
from django.urls import reverse
from rest_framework import status
from dcim.choices import SiteStatusChoices
from dcim.models import Site
from extras.choices import *
from extras.models import CustomField, ObjectChange, Tag
from utilities.testing import APITes... | netbox/extras/tests/test_changelog.py | from django.contrib.contenttypes.models import ContentType
from django.urls import reverse
from rest_framework import status
from dcim.choices import SiteStatusChoices
from dcim.models import Site
from extras.choices import *
from extras.models import CustomField, ObjectChange, Tag
from utilities.testing import APITes... | 0.623835 | 0.344443 |
import typing
import csv
from pathlib import Path
import pandas as pd
import matchzoo
from matchzoo.engine.base_task import BaseTask
_url = "https://download.microsoft.com/download/E/5/F/" \
"E5FCFCEE-7005-4814-853D-DAA7C66507E0/WikiQACorpus.zip"
def load_data(
stage: str = 'train',
task: typing.Un... | matchzoo/datasets/wiki_qa/load_data.py |
import typing
import csv
from pathlib import Path
import pandas as pd
import matchzoo
from matchzoo.engine.base_task import BaseTask
_url = "https://download.microsoft.com/download/E/5/F/" \
"E5FCFCEE-7005-4814-853D-DAA7C66507E0/WikiQACorpus.zip"
def load_data(
stage: str = 'train',
task: typing.Un... | 0.716615 | 0.39356 |