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 unittest
from tests import util
class TestComputeManagement(unittest.TestCase):
def setUp(self):
pass
def test_compute_management(self):
result = util.invoke_command(['compute-management'])
assert 'instance-configuration' in result.output
assert 'instance-pool' in resu... | services/core/tests/unit/test_computemanagement_cli_extended.py |
import unittest
from tests import util
class TestComputeManagement(unittest.TestCase):
def setUp(self):
pass
def test_compute_management(self):
result = util.invoke_command(['compute-management'])
assert 'instance-configuration' in result.output
assert 'instance-pool' in resu... | 0.625896 | 0.57946 |
import sys
reload(sys)
sys.setdefaultencoding('utf8')
sys.path.append("/home/dev/Repository/news/")
from lxml import etree
import gc
import time
from Tegenaria.tSpider.tSpider.browserRequest import BrowserRequest
from Tegenaria.tSpider.tSpider.settings import Settings
from Tegenaria.tSpider.tSpider.middlewares.fileIOMi... | Tegenaria/tSpider/tSpider/middlewares/spiderBone.py | import sys
reload(sys)
sys.setdefaultencoding('utf8')
sys.path.append("/home/dev/Repository/news/")
from lxml import etree
import gc
import time
from Tegenaria.tSpider.tSpider.browserRequest import BrowserRequest
from Tegenaria.tSpider.tSpider.settings import Settings
from Tegenaria.tSpider.tSpider.middlewares.fileIOMi... | 0.151278 | 0.04879 |
from django.core.management.base import BaseCommand, CommandError
from django.conf import settings
from optparse import make_option
import os
import sys
import glob
import shutil
try:
set
except NameError:
from sets import Set as set # Python 2.3 fallback
# Based on the collectmedia management command by <NAME... | apps/misc/management/commands/build_media.py | from django.core.management.base import BaseCommand, CommandError
from django.conf import settings
from optparse import make_option
import os
import sys
import glob
import shutil
try:
set
except NameError:
from sets import Set as set # Python 2.3 fallback
# Based on the collectmedia management command by <NAME... | 0.411347 | 0.070688 |
import pytest
from conftest import get_fpga, get_routing_ctx
from ops import Pop, Push
from program import CHANNELS_PER_FPGA, FPGA, Program
from routing_table import NoRouteFound, ckr_routing_table, \
cks_routing_tables
def check_fpga_tables(fpga, tables, expected):
assert len(tables) == len(expected)
as... | codegen/tests/test_routing_table.py | import pytest
from conftest import get_fpga, get_routing_ctx
from ops import Pop, Push
from program import CHANNELS_PER_FPGA, FPGA, Program
from routing_table import NoRouteFound, ckr_routing_table, \
cks_routing_tables
def check_fpga_tables(fpga, tables, expected):
assert len(tables) == len(expected)
as... | 0.388734 | 0.450903 |
import os
import cv2
import torch
from torchvision import transforms
from tqdm import tqdm
from rt_gene.estimate_gaze_base import GazeEstimatorBase
from rt_gene.gaze_estimation_models_pytorch import GazeEstimationModelVGG, GazeEstimationModelResnet18
from rt_gene.download_tools import download_gaze_pytorch_models, m... | rt_gene/rt_gene/src/rt_gene/estimate_gaze_pytorch.py |
import os
import cv2
import torch
from torchvision import transforms
from tqdm import tqdm
from rt_gene.estimate_gaze_base import GazeEstimatorBase
from rt_gene.gaze_estimation_models_pytorch import GazeEstimationModelVGG, GazeEstimationModelResnet18
from rt_gene.download_tools import download_gaze_pytorch_models, m... | 0.677154 | 0.371621 |
from datetime import date, timedelta
from .classcharts_client import ClasschartsClient
from .limited_trello_client import LimitedTrelloClient
from .os_config import get_environment_config
def sync_data(*args, **kwargs):
config = get_environment_config()
classcharts_client = ClasschartsClient(
userna... | classcharts_trello_sync/sync.py | from datetime import date, timedelta
from .classcharts_client import ClasschartsClient
from .limited_trello_client import LimitedTrelloClient
from .os_config import get_environment_config
def sync_data(*args, **kwargs):
config = get_environment_config()
classcharts_client = ClasschartsClient(
userna... | 0.374905 | 0.057019 |
import logging
import fsl.data.image as fslimage
import fsleyes_props as props
import fsleyes_widgets as fwidgets
log = logging.getLogger(__name__)
class ActionDisabledError(Exception):
"""Exception raised when an attempt is made to call a disabled
:class:`Action`.
"""
class BoundWidget(object):
... | fsleyes/actions/base.py | import logging
import fsl.data.image as fslimage
import fsleyes_props as props
import fsleyes_widgets as fwidgets
log = logging.getLogger(__name__)
class ActionDisabledError(Exception):
"""Exception raised when an attempt is made to call a disabled
:class:`Action`.
"""
class BoundWidget(object):
... | 0.587115 | 0.221372 |
# This is the setup.py for for all packages in the repo.
# The package to be installed is selected by copying $PACKAGE/setup.cfg file to setup.cfg.
# This is necessary because pip does not practically allow us to use alternate names for the setup files.
from configparser import ConfigParser
from itertools import chai... | setup.py |
# This is the setup.py for for all packages in the repo.
# The package to be installed is selected by copying $PACKAGE/setup.cfg file to setup.cfg.
# This is necessary because pip does not practically allow us to use alternate names for the setup files.
from configparser import ConfigParser
from itertools import chai... | 0.632616 | 0.099121 |
from dataclasses import dataclass
from datetime import datetime
from os import environ
from typing import Union, Dict, List
from unittest import TestCase, skipIf
from dataclasses_serialization.serializer_base import DeserializationError
try:
import bson
bson_installed = True
except ImportError:
bson_inst... | tests/test_bson.py | from dataclasses import dataclass
from datetime import datetime
from os import environ
from typing import Union, Dict, List
from unittest import TestCase, skipIf
from dataclasses_serialization.serializer_base import DeserializationError
try:
import bson
bson_installed = True
except ImportError:
bson_inst... | 0.72487 | 0.275405 |
import numpy as np
import torch
import torch.nn as nn
import torch.nn.functional as F
import torch.utils.data
from scipy.ndimage import zoom
from cath.util import lr_schedulers
from se3cnn.image.filter import low_pass_filter
from se3cnn.image.gated_block import GatedBlock
from se3cnn.image.utils import rotate_scalar
f... | examples/image/tetris.py | import numpy as np
import torch
import torch.nn as nn
import torch.nn.functional as F
import torch.utils.data
from scipy.ndimage import zoom
from cath.util import lr_schedulers
from se3cnn.image.filter import low_pass_filter
from se3cnn.image.gated_block import GatedBlock
from se3cnn.image.utils import rotate_scalar
f... | 0.884657 | 0.6025 |
DB_CREATE_TRADE_TYPE = """
CREATE TABLE IF NOT EXISTS trade_type (
type CHAR(1) PRIMARY KEY NOT NULL,
seq INTEGER UNIQUE
);
/* Buy Type */
INSERT OR IGNORE INTO trade_type(type, seq) VALUES ('A', 1);
/* Sell Type */
INSERT OR IGNORE INTO trade_type(type, seq) VALUES ('B', 2);
/* Settlement Buy Type */
... | rotkehlchen/db/schema.py | DB_CREATE_TRADE_TYPE = """
CREATE TABLE IF NOT EXISTS trade_type (
type CHAR(1) PRIMARY KEY NOT NULL,
seq INTEGER UNIQUE
);
/* Buy Type */
INSERT OR IGNORE INTO trade_type(type, seq) VALUES ('A', 1);
/* Sell Type */
INSERT OR IGNORE INTO trade_type(type, seq) VALUES ('B', 2);
/* Settlement Buy Type */
... | 0.375134 | 0.03775 |
import matplotlib as mpl
import matplotlib.pyplot as plt
import numpy as np
from read_logs import get_resolutions_in_pixels, get_resolutions_in_labels
from architecture_config import config as arch_conf
class PerformancePlot:
def __init__(self):
self.pi = arch_conf['maxflops_sisd']
self.pi_simd =... | plots_lib/performance_plots.py | import matplotlib as mpl
import matplotlib.pyplot as plt
import numpy as np
from read_logs import get_resolutions_in_pixels, get_resolutions_in_labels
from architecture_config import config as arch_conf
class PerformancePlot:
def __init__(self):
self.pi = arch_conf['maxflops_sisd']
self.pi_simd =... | 0.668339 | 0.345519 |
import pytest
def test_timeit_plain(testdir):
testdir.makepyfile("""
import pytest
@pytest.mark.timeit(n=10)
def test_something():
assert 1 == 1
""")
result = testdir.runpytest()
result.assert_outcomes(passed=30)
assert result.ret == 0
def test_timeit_plain_r... | tests/test_pytest_timeit.py | import pytest
def test_timeit_plain(testdir):
testdir.makepyfile("""
import pytest
@pytest.mark.timeit(n=10)
def test_something():
assert 1 == 1
""")
result = testdir.runpytest()
result.assert_outcomes(passed=30)
assert result.ret == 0
def test_timeit_plain_r... | 0.458106 | 0.877529 |
import sys
from collections import defaultdict
import numpy as np
from ..dimension import dimension_name
from ..util import isscalar, unique_iterator, pd, unique_array
from .interface import DataError, Interface
from .multipath import MultiInterface, ensure_ring
from .pandas import PandasInterface
class SpatialPan... | holoviews/core/data/spatialpandas.py | import sys
from collections import defaultdict
import numpy as np
from ..dimension import dimension_name
from ..util import isscalar, unique_iterator, pd, unique_array
from .interface import DataError, Interface
from .multipath import MultiInterface, ensure_ring
from .pandas import PandasInterface
class SpatialPan... | 0.491456 | 0.50354 |
from CIM15.IEC61970.Generation.GenerationDynamics.SteamSupply import SteamSupply
class PWRSteamSupply(SteamSupply):
"""Pressurized water reactor used as a steam supply to a steam turbinePressurized water reactor used as a steam supply to a steam turbine
"""
def __init__(self, coreNeutronicsHT=0.0, steamF... | CIM15/IEC61970/Generation/GenerationDynamics/PWRSteamSupply.py |
from CIM15.IEC61970.Generation.GenerationDynamics.SteamSupply import SteamSupply
class PWRSteamSupply(SteamSupply):
"""Pressurized water reactor used as a steam supply to a steam turbinePressurized water reactor used as a steam supply to a steam turbine
"""
def __init__(self, coreNeutronicsHT=0.0, steamF... | 0.700383 | 0.296731 |
from collections import OrderedDict
from abstract_device_api.abstract_device_xsd import *
import db
from dm_utils import DMUtils
from feature_base import FeatureBase
class UnderlayIpClosFeature(FeatureBase):
@classmethod
def feature_name(cls):
return 'underlay-ip-clos'
# end feature_name
de... | src/config/device-manager/device_manager/plugins/feature/underlay_ip_clos_feature.py | from collections import OrderedDict
from abstract_device_api.abstract_device_xsd import *
import db
from dm_utils import DMUtils
from feature_base import FeatureBase
class UnderlayIpClosFeature(FeatureBase):
@classmethod
def feature_name(cls):
return 'underlay-ip-clos'
# end feature_name
de... | 0.586996 | 0.062274 |
import argparse
import os
from datetime import datetime
import requests
GEMOJI_RELEASE_URL = 'https://api.github.com/repos/github/gemoji/releases'
GEMOJI_JSON_DB_URL = 'https://raw.githubusercontent.com/github/gemoji/{tag}/db/emoji.json'
def get_lastest_release():
req = requests.get(GEMOJI_RELEASE_URL)
req... | jogo_da_velha/venv/Lib/site-packages/emojis/db/generator.py | import argparse
import os
from datetime import datetime
import requests
GEMOJI_RELEASE_URL = 'https://api.github.com/repos/github/gemoji/releases'
GEMOJI_JSON_DB_URL = 'https://raw.githubusercontent.com/github/gemoji/{tag}/db/emoji.json'
def get_lastest_release():
req = requests.get(GEMOJI_RELEASE_URL)
req... | 0.381565 | 0.071982 |
import time
import numpy as np
import yaml
import matplotlib.pyplot as plt
from sklearn.metrics import confusion_matrix, accuracy_score, cohen_kappa_score
def plot_full_barchart(test_score, n_pilots, title="Test accuracy - BCIC IV 2a", fig=None, ax_idx=0):
if fig:
ax = fig.get_axes()[ax_idx]
else:
... | code/src/metric_visualizers.py | import time
import numpy as np
import yaml
import matplotlib.pyplot as plt
from sklearn.metrics import confusion_matrix, accuracy_score, cohen_kappa_score
def plot_full_barchart(test_score, n_pilots, title="Test accuracy - BCIC IV 2a", fig=None, ax_idx=0):
if fig:
ax = fig.get_axes()[ax_idx]
else:
... | 0.689306 | 0.551272 |
from typing import Dict,Sequence,List
from dmt.entity import Entity
from dmt.blueprint import Blueprint
from .blueprints.simascript import SIMAScriptBlueprint
from typing import Dict
from sima.sima.namedobject import NamedObject
from sima.sima.scriptablevalue import ScriptableValue
from sima.sima.simascriptcontext impo... | src/sima/sima/simascript.py | from typing import Dict,Sequence,List
from dmt.entity import Entity
from dmt.blueprint import Blueprint
from .blueprints.simascript import SIMAScriptBlueprint
from typing import Dict
from sima.sima.namedobject import NamedObject
from sima.sima.scriptablevalue import ScriptableValue
from sima.sima.simascriptcontext impo... | 0.749729 | 0.205535 |
from datetime import datetime, timedelta
from resource_management import Execute, File
from tempfile import mkstemp
import os
import ambari_simplejson as json # simplejson is much faster comparing to Python 2.6 json module and has the same functions set.
FILE_TYPE_XML = 'XML'
FILE_TYPE_PROPERTIES = 'PROPERTIES'
FILE_T... | ambari-common/src/main/python/resource_management/libraries/functions/security_commons.py | from datetime import datetime, timedelta
from resource_management import Execute, File
from tempfile import mkstemp
import os
import ambari_simplejson as json # simplejson is much faster comparing to Python 2.6 json module and has the same functions set.
FILE_TYPE_XML = 'XML'
FILE_TYPE_PROPERTIES = 'PROPERTIES'
FILE_T... | 0.545044 | 0.397997 |
from __future__ import absolute_import, print_function
import itertools as it
import logging
from click import echo, style as st_
import click
import networkx as nx
from ..load import load
from six.moves import map
from six.moves import zip
logger = logging.getLogger(__name__)
def info(chip_file, ou... | src/dmf_chip/bin/info.py | from __future__ import absolute_import, print_function
import itertools as it
import logging
from click import echo, style as st_
import click
import networkx as nx
from ..load import load
from six.moves import map
from six.moves import zip
logger = logging.getLogger(__name__)
def info(chip_file, ou... | 0.489259 | 0.082957 |
import argparse
import copy
import os
import time
from flax import linen as nn
from flax import optim
import jax
import jax.numpy as jnp
import numpy as np
import ray
from alpa import (parallelize, global_config, set_parallelize_options, testing,
DeviceCluster, LocalPhysicalDeviceMesh)
from alpa.mo... | benchmark/alpa/old_backup/benchmark_transformer_layer_2d.py | import argparse
import copy
import os
import time
from flax import linen as nn
from flax import optim
import jax
import jax.numpy as jnp
import numpy as np
import ray
from alpa import (parallelize, global_config, set_parallelize_options, testing,
DeviceCluster, LocalPhysicalDeviceMesh)
from alpa.mo... | 0.677261 | 0.202049 |
dict_psf_150pc = {'IC5332': 3.43393120433962,
'NGC0628': 3.1442805342769633,
'NGC1087': 1.952032819711232,
'NGC1300': 1.6292638920470441,
'NGC1365': 1.5809770781574026,
'NGC1385': 1.7967318333787632,
'NGC1433': ... | src/pmuse_utils/dict/psf_dictionary_v6.py |
dict_psf_150pc = {'IC5332': 3.43393120433962,
'NGC0628': 3.1442805342769633,
'NGC1087': 1.952032819711232,
'NGC1300': 1.6292638920470441,
'NGC1365': 1.5809770781574026,
'NGC1385': 1.7967318333787632,
'NGC1433': ... | 0.359252 | 0.462898 |
import logging
import os
import pytest
from sciencebeam_parser.document.layout_document import (
LayoutBlock,
LayoutDocument,
LayoutGraphic,
LayoutPage,
LayoutPageCoordinates
)
from sciencebeam_parser.document.semantic_document import (
SemanticAffiliationAddress,
SemanticAuthor,
Seman... | tests/processors/fulltext/processor_test.py | import logging
import os
import pytest
from sciencebeam_parser.document.layout_document import (
LayoutBlock,
LayoutDocument,
LayoutGraphic,
LayoutPage,
LayoutPageCoordinates
)
from sciencebeam_parser.document.semantic_document import (
SemanticAffiliationAddress,
SemanticAuthor,
Seman... | 0.616359 | 0.173148 |
from ... import TestUnitBase
class TestISAAC(TestUnitBase):
def test_randseed(self):
# There are no specific instructions on how the random state would be used as
# a key stream in the cryptographic application of ISAAC. This implementation
# opts to use the bytes as given in the only off... | test/units/crypto/cipher/test_isaac.py | from ... import TestUnitBase
class TestISAAC(TestUnitBase):
def test_randseed(self):
# There are no specific instructions on how the random state would be used as
# a key stream in the cryptographic application of ISAAC. This implementation
# opts to use the bytes as given in the only off... | 0.518546 | 0.411879 |
import numpy as np
import pandas as pd
import logging
from typing import Optional, List, Tuple, Set
from ..structs.interval import Interval, IntervalAnnotation, interval_annotations_dtypes, interval_annotations_dict
from .. import types
from . import io_commons
from . import io_consts
_logger = logging.getLogger(__na... | src/main/python/org/broadinstitute/hellbender/gcnvkernel/io/io_intervals_and_counts.py | import numpy as np
import pandas as pd
import logging
from typing import Optional, List, Tuple, Set
from ..structs.interval import Interval, IntervalAnnotation, interval_annotations_dtypes, interval_annotations_dict
from .. import types
from . import io_commons
from . import io_consts
_logger = logging.getLogger(__na... | 0.909209 | 0.370311 |
import os, glob
import numpy as np
import pandas as pd
import Bio
from Bio.Seq import MutableSeq, Seq
from Bio import SeqIO
from Bio.SeqUtils import GC
from typing import Tuple
def degenerate_primer(primer:'Bio.Seq.MutableSeq') -> str:
forward = (str(primer),)
for i in range(0, len(primer)):
for j in r... | libs/.ipynb_checkpoints/primer-checkpoint.py | import os, glob
import numpy as np
import pandas as pd
import Bio
from Bio.Seq import MutableSeq, Seq
from Bio import SeqIO
from Bio.SeqUtils import GC
from typing import Tuple
def degenerate_primer(primer:'Bio.Seq.MutableSeq') -> str:
forward = (str(primer),)
for i in range(0, len(primer)):
for j in r... | 0.396419 | 0.224757 |
import csv
from os import walk
from common import \
make_item_name, make_class_name, make_file_name_without_extension, ConsoleColors, output_folder, data_folder, get_filenames_of_type, FileTypes, \
auto_generation_header
class Columns:
IS_IMPLEMENTED = 0
IS_UP_TO_DATE = 1
ITEM_NAME = 2
CUSTOMI... | src/crowcraft/data-parser/item_files_generator/item_customizations_generator.py | import csv
from os import walk
from common import \
make_item_name, make_class_name, make_file_name_without_extension, ConsoleColors, output_folder, data_folder, get_filenames_of_type, FileTypes, \
auto_generation_header
class Columns:
IS_IMPLEMENTED = 0
IS_UP_TO_DATE = 1
ITEM_NAME = 2
CUSTOMI... | 0.333286 | 0.160135 |
import logging
import os.path
import socket
import sys
from openmdao.main.api import Assembly, Component, enable_console
from openmdao.main.datatypes.api import Float
from openmdao.main.resource import ResourceAllocationManager as RAM
from openmdao.main.resource import ClusterAllocator, ClusterHost
from openmdao.lib.... | openmdao.main/src/openmdao/main/test/ec2_test.py | import logging
import os.path
import socket
import sys
from openmdao.main.api import Assembly, Component, enable_console
from openmdao.main.datatypes.api import Float
from openmdao.main.resource import ResourceAllocationManager as RAM
from openmdao.main.resource import ClusterAllocator, ClusterHost
from openmdao.lib.... | 0.300848 | 0.114864 |
import pyzed.sl as sl
import math
import numpy as np
import sys
def main():
# Create a Camera object
zed = sl.Camera()
# Create a InitParameters object and set configuration parameters
init_params = sl.InitParameters()
init_params.depth_mode = sl.DEPTH_MODE.PERFORMANCE # Use PERFORMANCE depth mo... | tutorials/tutorial 3 - depth sensing/python/depth_sensing.py |
import pyzed.sl as sl
import math
import numpy as np
import sys
def main():
# Create a Camera object
zed = sl.Camera()
# Create a InitParameters object and set configuration parameters
init_params = sl.InitParameters()
init_params.depth_mode = sl.DEPTH_MODE.PERFORMANCE # Use PERFORMANCE depth mo... | 0.48121 | 0.371849 |
import asyncio
from asyncio import Event
from collections import defaultdict
from datetime import datetime, timedelta
from itertools import count
from typing import Dict, Tuple, Union, Optional, List
from weakref import WeakValueDictionary
from aiohttp import WSCloseCode
from aiohttp.web_ws import WebSocketResponse
fr... | server/service/manager/bike_connection_manager.py | import asyncio
from asyncio import Event
from collections import defaultdict
from datetime import datetime, timedelta
from itertools import count
from typing import Dict, Tuple, Union, Optional, List
from weakref import WeakValueDictionary
from aiohttp import WSCloseCode
from aiohttp.web_ws import WebSocketResponse
fr... | 0.856647 | 0.282635 |
import sys
from typing import Callable, List, Optional, Sequence, Tuple, cast
from typing_extensions import Literal
from typing import Type as typing_Type
from mypy.plugin import Plugin, FunctionContext, MethodContext, CheckerPluginInterface
from mypy.nodes import (
ARG_POS,
ARG_STAR,
TypeInfo,
Context,... | trio_typing/plugin.py | import sys
from typing import Callable, List, Optional, Sequence, Tuple, cast
from typing_extensions import Literal
from typing import Type as typing_Type
from mypy.plugin import Plugin, FunctionContext, MethodContext, CheckerPluginInterface
from mypy.nodes import (
ARG_POS,
ARG_STAR,
TypeInfo,
Context,... | 0.697609 | 0.228942 |
import random
class Expression:
def __init__(self, value, left=None, right=None):
self.left = left
self.right = right
if left is None and right is None:
self.value = value
elif left is not None and right is not None:
self.op = value
else:
... | rsa/arithmetic.py |
import random
class Expression:
def __init__(self, value, left=None, right=None):
self.left = left
self.right = right
if left is None and right is None:
self.value = value
elif left is not None and right is not None:
self.op = value
else:
... | 0.832475 | 0.46393 |
from datetime import timedelta
from fastapi import APIRouter, Body, Depends
from starlette.exceptions import HTTPException
from starlette.status import HTTP_201_CREATED, HTTP_400_BAD_REQUEST
from ....core.config import ACCESS_TOKEN_EXPIRE_MINUTES
from ....core.jwt import create_access_token
from ....crud.shortcuts im... | backend/app/app/api/api_v1/endpoints/authenticaion.py | from datetime import timedelta
from fastapi import APIRouter, Body, Depends
from starlette.exceptions import HTTPException
from starlette.status import HTTP_201_CREATED, HTTP_400_BAD_REQUEST
from ....core.config import ACCESS_TOKEN_EXPIRE_MINUTES
from ....core.jwt import create_access_token
from ....crud.shortcuts im... | 0.555194 | 0.054074 |
import copy
import io
import os
import sys
import mock
import six
import unittest
import uuid
from yardstick.benchmark.contexts import dummy
from yardstick.benchmark.core import task
from yardstick.common import constants as consts
from yardstick.common import exceptions
from yardstick.common import task_template
fr... | yardstick/tests/unit/benchmark/core/test_task.py |
import copy
import io
import os
import sys
import mock
import six
import unittest
import uuid
from yardstick.benchmark.contexts import dummy
from yardstick.benchmark.core import task
from yardstick.common import constants as consts
from yardstick.common import exceptions
from yardstick.common import task_template
fr... | 0.478041 | 0.196344 |
from elasticsearch import Elasticsearch
from openpyxl import load_workbook
from datetime import date
import re
import os
import logging
import requests
# these will not change.
INTERNAL_NOTE = 'It was possible to publish this article open access thanks ' \
'to a Swiss National Licence with the Publish... | national-licence-enrichment.py | from elasticsearch import Elasticsearch
from openpyxl import load_workbook
from datetime import date
import re
import os
import logging
import requests
# these will not change.
INTERNAL_NOTE = 'It was possible to publish this article open access thanks ' \
'to a Swiss National Licence with the Publish... | 0.429549 | 0.129046 |
from datetime import datetime, timedelta
from unittest import TestCase
from trange import trange, ForwardTimeRange, BackwardTimeRange
class TestTRange(TestCase):
def test_simple(self):
d1 = datetime(year=2019, month=1, day=1, hour=12, minute=0, second=0,
microsecond=0)
d2 = ... | test_trange.py | from datetime import datetime, timedelta
from unittest import TestCase
from trange import trange, ForwardTimeRange, BackwardTimeRange
class TestTRange(TestCase):
def test_simple(self):
d1 = datetime(year=2019, month=1, day=1, hour=12, minute=0, second=0,
microsecond=0)
d2 = ... | 0.816113 | 0.696226 |
from oslo_log import versionutils
from oslo_policy import policy
from keystone.common.policies import base
RULE_TRUSTOR = 'user_id:%(target.trust.trustor_user_id)s'
RULE_TRUSTEE = 'user_id:%(target.trust.trustee_user_id)s'
SYSTEM_READER_OR_TRUSTOR_OR_TRUSTEE = (
base.SYSTEM_READER + ' or ' + RULE_TRUSTOR + ' or ... | keystone/common/policies/trust.py |
from oslo_log import versionutils
from oslo_policy import policy
from keystone.common.policies import base
RULE_TRUSTOR = 'user_id:%(target.trust.trustor_user_id)s'
RULE_TRUSTEE = 'user_id:%(target.trust.trustee_user_id)s'
SYSTEM_READER_OR_TRUSTOR_OR_TRUSTEE = (
base.SYSTEM_READER + ' or ' + RULE_TRUSTOR + ' or ... | 0.253584 | 0.049889 |
import pandas as pd
import argparse
import os
import sys
DEBUG=True
if __name__ == '__main__':
DEBUG = False
parser = argparse.ArgumentParser(description='Dump ods files tab(s) to .tsv files, to the (default output) path')
parser.add_argument('inputfiles', type=str, nargs='*', help='name of ods-file to process... | xl2tsv.py |
import pandas as pd
import argparse
import os
import sys
DEBUG=True
if __name__ == '__main__':
DEBUG = False
parser = argparse.ArgumentParser(description='Dump ods files tab(s) to .tsv files, to the (default output) path')
parser.add_argument('inputfiles', type=str, nargs='*', help='name of ods-file to process... | 0.186243 | 0.063715 |
from netmiko import ConnectHandler
from getpass import getpass
import threading
import time
class ThreadedDevice(threading.Thread):
""" Generic Network Device polling with threading """
def __init__(self, device_type, ip, port, username, password):
""" initialise threading and then connect to a devic... | class4/ex9.py | from netmiko import ConnectHandler
from getpass import getpass
import threading
import time
class ThreadedDevice(threading.Thread):
""" Generic Network Device polling with threading """
def __init__(self, device_type, ip, port, username, password):
""" initialise threading and then connect to a devic... | 0.533641 | 0.084644 |
import fnmatch, os, shutil, run, time
from suite_subprocess import suite_subprocess
from wiredtiger import stat, WiredTigerError
from wtscenario import make_scenarios
import wttest
class test_cursor08(wttest.WiredTigerTestCase, suite_subprocess):
logmax = "100K"
tablename = 'test_cursor08'
uri = 'table:' ... | src/third_party/wiredtiger/test/suite/test_cursor08.py |
import fnmatch, os, shutil, run, time
from suite_subprocess import suite_subprocess
from wiredtiger import stat, WiredTigerError
from wtscenario import make_scenarios
import wttest
class test_cursor08(wttest.WiredTigerTestCase, suite_subprocess):
logmax = "100K"
tablename = 'test_cursor08'
uri = 'table:' ... | 0.382718 | 0.094594 |
import io
from apps.bot.classes.Command import Command
from apps.bot.classes.consts.Consts import Role, Platform
from apps.bot.utils.DoTheLinuxComand import do_the_linux_command
from apps.bot.utils.utils import draw_text_on_image
from petrovich.settings import BASE_DIR
class Logs(Command):
name = "логи"
name... | apps/bot/commands/ModeratorCommands/Logs.py | import io
from apps.bot.classes.Command import Command
from apps.bot.classes.consts.Consts import Role, Platform
from apps.bot.utils.DoTheLinuxComand import do_the_linux_command
from apps.bot.utils.utils import draw_text_on_image
from petrovich.settings import BASE_DIR
class Logs(Command):
name = "логи"
name... | 0.274449 | 0.165627 |
import torch
import torch.nn as nn
import torch.nn.functional as F
from torch.autograd import Variable
import torch.optim as optim
import os
import numpy as np
import random
import sys
parentPath = os.path.abspath("..")
sys.path.insert(0, parentPath)# add parent folder to path so as to import common modules
from helpe... | models/dialogwae.py | import torch
import torch.nn as nn
import torch.nn.functional as F
from torch.autograd import Variable
import torch.optim as optim
import os
import numpy as np
import random
import sys
parentPath = os.path.abspath("..")
sys.path.insert(0, parentPath)# add parent folder to path so as to import common modules
from helpe... | 0.736116 | 0.211926 |
from .quiz import Quiz, Question, GroupStart, GroupEnd, TextRegion
BEFORE_ITEMS = '''\
<?xml version="1.0" encoding="UTF-8"?>
<questestinterop xmlns="http://www.imsglobal.org/xsd/ims_qtiasiv1p2" xmlns:xsi="http://www.w3.org/2001/XMLSchema-instance" xsi:schemaLocation="http://www.imsglobal.org/xsd/ims_qtiasiv1p2 htt... | text2qti/xml_assessment.py |
from .quiz import Quiz, Question, GroupStart, GroupEnd, TextRegion
BEFORE_ITEMS = '''\
<?xml version="1.0" encoding="UTF-8"?>
<questestinterop xmlns="http://www.imsglobal.org/xsd/ims_qtiasiv1p2" xmlns:xsi="http://www.w3.org/2001/XMLSchema-instance" xsi:schemaLocation="http://www.imsglobal.org/xsd/ims_qtiasiv1p2 htt... | 0.3512 | 0.072768 |
import sys
IS_PY3 = sys.version_info[0] == 3
string_types = (str, ) if IS_PY3 else (basestring, )
text_type = str if IS_PY3 else unicode
_identity = lambda x: x
if IS_PY3:
from urllib.parse import urljoin, urlunsplit, urlsplit
implements_to_string = _identity
else:
from urlparse import ur... | bin/sa_haveibeenpwned/aob_py3/jsl/_compat/__init__.py | import sys
IS_PY3 = sys.version_info[0] == 3
string_types = (str, ) if IS_PY3 else (basestring, )
text_type = str if IS_PY3 else unicode
_identity = lambda x: x
if IS_PY3:
from urllib.parse import urljoin, urlunsplit, urlsplit
implements_to_string = _identity
else:
from urlparse import ur... | 0.324985 | 0.197077 |
import math
from decimal import localcontext, Decimal
from typing import List, Optional
from functools import partial
from refinery.units.crypto.cipher import StandardBlockCipherUnit, Arg
from refinery.lib import chunks
from refinery.lib.crypto import (
rotr,
rotl,
BlockCipher,
BlockCipherFactory,
... | refinery/units/crypto/cipher/rc5.py | import math
from decimal import localcontext, Decimal
from typing import List, Optional
from functools import partial
from refinery.units.crypto.cipher import StandardBlockCipherUnit, Arg
from refinery.lib import chunks
from refinery.lib.crypto import (
rotr,
rotl,
BlockCipher,
BlockCipherFactory,
... | 0.808823 | 0.370026 |
import numpy as np
import mpl_toolkits.mplot3d as plt3d
import matplotlib.colors as mpl_colors
class Plane(object):
def __init__(self, data=None):
self.eq = None
if data is not None:
self.fit(data)
@property
def min_sample_size(self):
return 3
def fit(self, data)... | arse/pme/plane.py | import numpy as np
import mpl_toolkits.mplot3d as plt3d
import matplotlib.colors as mpl_colors
class Plane(object):
def __init__(self, data=None):
self.eq = None
if data is not None:
self.fit(data)
@property
def min_sample_size(self):
return 3
def fit(self, data)... | 0.617859 | 0.581244 |
import numpy as np
import chainer
from chainer import cuda
from chainer.cuda import cupy
from chainer import function
if chainer.cuda.available:
# x will be flattened in C-order
# y will be flattened in C-order
gpu_graphpool_fwd = cupy.ElementwiseKernel(
'I p, I p_dim, raw I pooling_inds, raw T x... | lib/functions/pooling/graph_max_pooling.py |
import numpy as np
import chainer
from chainer import cuda
from chainer.cuda import cupy
from chainer import function
if chainer.cuda.available:
# x will be flattened in C-order
# y will be flattened in C-order
gpu_graphpool_fwd = cupy.ElementwiseKernel(
'I p, I p_dim, raw I pooling_inds, raw T x... | 0.861013 | 0.305108 |
import random
import unittest
import csp
class TestConsistency(unittest.TestCase):
def setUp(self):
colors = {"red", "green"}
names = {"wa", "nt", "q", "nsw", "v", "sa", "t"}
self.name_to_variable_map = csp.Variable.from_names_to_equal_domain(names, colors)
const1 = csp.Constraint... | tests/test_consistency.py | import random
import unittest
import csp
class TestConsistency(unittest.TestCase):
def setUp(self):
colors = {"red", "green"}
names = {"wa", "nt", "q", "nsw", "v", "sa", "t"}
self.name_to_variable_map = csp.Variable.from_names_to_equal_domain(names, colors)
const1 = csp.Constraint... | 0.468791 | 0.526586 |
import logging
import requests
import sqlalchemy
import datetime as dt
from flask import current_app
from virus_total_apis import PublicApi as VirusTotalPublicApi
from polylogyx.db.database import db
from polylogyx.db.models import ResultLogScan, Settings, ThreatIntelCredentials, VirusTotalAvEngines
from polylogyx.ut... | plgx-esp/polylogyx/plugins/intel/virustotal.py | import logging
import requests
import sqlalchemy
import datetime as dt
from flask import current_app
from virus_total_apis import PublicApi as VirusTotalPublicApi
from polylogyx.db.database import db
from polylogyx.db.models import ResultLogScan, Settings, ThreatIntelCredentials, VirusTotalAvEngines
from polylogyx.ut... | 0.195902 | 0.10316 |
import uuid
import logging
from requests.models import Response
from six.moves.urllib import parse as urlparse
from localstack.utils.common import to_str
from localstack.utils.cloudformation import template_deployer
from localstack.services.generic_proxy import ProxyListener
XMLNS_CLOUDFORMATION = 'http://cloudformati... | localstack/services/cloudformation/cloudformation_listener.py | import uuid
import logging
from requests.models import Response
from six.moves.urllib import parse as urlparse
from localstack.utils.common import to_str
from localstack.utils.cloudformation import template_deployer
from localstack.services.generic_proxy import ProxyListener
XMLNS_CLOUDFORMATION = 'http://cloudformati... | 0.466359 | 0.069258 |
"""Tests for rate_curve.py."""
from absl.testing import parameterized
import numpy as np
import tensorflow.compat.v2 as tf
import tf_quant_finance as tff
from tensorflow.python.framework import test_util # pylint: disable=g-direct-tensorflow-import
dates = tff.datetime
instruments = tff.experimental.instruments
@... | tf_quant_finance/experimental/instruments/rate_curve_test.py | """Tests for rate_curve.py."""
from absl.testing import parameterized
import numpy as np
import tensorflow.compat.v2 as tf
import tf_quant_finance as tff
from tensorflow.python.framework import test_util # pylint: disable=g-direct-tensorflow-import
dates = tff.datetime
instruments = tff.experimental.instruments
@... | 0.86778 | 0.595728 |
import abc
import time
from typing import Any, Callable, Dict, Iterator, List, Optional, Tuple, Type, TypeVar
from pyvisa import attributes, constants, logger, rname
from pyvisa.constants import ResourceAttribute, StatusCode
from pyvisa.typing import VISARMSession
from .common import int_to_byte
#: Type var used whe... | pyvisa_py/sessions.py | import abc
import time
from typing import Any, Callable, Dict, Iterator, List, Optional, Tuple, Type, TypeVar
from pyvisa import attributes, constants, logger, rname
from pyvisa.constants import ResourceAttribute, StatusCode
from pyvisa.typing import VISARMSession
from .common import int_to_byte
#: Type var used whe... | 0.895082 | 0.203965 |
from typing import (
List,
Tuple,
)
from eth.rlp.blocks import BaseBlock
from eth.rlp.headers import BlockHeader
from eth.rlp.receipts import Receipt
from p2p.kademlia import (
Node,
)
from trinity.protocol.common.events import (
HasRemoteEvent,
PeerPoolMessageEvent,
)
# Events flowing from Peer... | trinity/protocol/eth/events.py | from typing import (
List,
Tuple,
)
from eth.rlp.blocks import BaseBlock
from eth.rlp.headers import BlockHeader
from eth.rlp.receipts import Receipt
from p2p.kademlia import (
Node,
)
from trinity.protocol.common.events import (
HasRemoteEvent,
PeerPoolMessageEvent,
)
# Events flowing from Peer... | 0.884769 | 0.353568 |
__all__ = ['StateData']
from direct.directnotify.DirectNotifyGlobal import directNotify
from direct.showbase.DirectObject import DirectObject
from direct.directnotify import DirectNotifyGlobal
class StateData(DirectObject):
"""
A StateData is a base class for a single state within a Finite
State Machine... | dev/tools/leveleditor/direct/fsm/StateData.py |
__all__ = ['StateData']
from direct.directnotify.DirectNotifyGlobal import directNotify
from direct.showbase.DirectObject import DirectObject
from direct.directnotify import DirectNotifyGlobal
class StateData(DirectObject):
"""
A StateData is a base class for a single state within a Finite
State Machine... | 0.479504 | 0.286518 |
import copy
import mock
import pytest
from datadog_checks import aerospike
from . import common
pytestmark = pytest.mark.unit
METRICS = [
'aerospike.datacenter.dc_timelag',
'aerospike.datacenter.dc_rec_ship_attempts',
'aerospike.datacenter.dc_delete_ship_attempts',
'aerospike.datacenter.dc_remote_s... | aerospike/tests/test_unit.py | import copy
import mock
import pytest
from datadog_checks import aerospike
from . import common
pytestmark = pytest.mark.unit
METRICS = [
'aerospike.datacenter.dc_timelag',
'aerospike.datacenter.dc_rec_ship_attempts',
'aerospike.datacenter.dc_delete_ship_attempts',
'aerospike.datacenter.dc_remote_s... | 0.482917 | 0.26066 |
# %% Imports
import crcengine
import numpy as np
from time import sleep
from Crypto.Util.number import long_to_bytes
import FiniteFieldAlgebra as Field
import itertools
# %% Functions
# Based on: https://www.cosc.canterbury.ac.nz/greg.ewing/essays/CRC-Reverse-Engineering.html
def reverse_poly(string_p... | old/crc-reversing.py | # %% Imports
import crcengine
import numpy as np
from time import sleep
from Crypto.Util.number import long_to_bytes
import FiniteFieldAlgebra as Field
import itertools
# %% Functions
# Based on: https://www.cosc.canterbury.ac.nz/greg.ewing/essays/CRC-Reverse-Engineering.html
def reverse_poly(string_p... | 0.274449 | 0.348673 |
from typing import TextIO
from typing import Tuple
from textwrap import dedent, indent
import logging
import sys
import re
from .model import (ArrayField, CompositeField, EnumField,
PrimitiveField, Service)
logger = logging.getLogger(__name__)
# The following words need to be changed, otherwise t... | contrib/msggen/msggen/rust.py | from typing import TextIO
from typing import Tuple
from textwrap import dedent, indent
import logging
import sys
import re
from .model import (ArrayField, CompositeField, EnumField,
PrimitiveField, Service)
logger = logging.getLogger(__name__)
# The following words need to be changed, otherwise t... | 0.659076 | 0.162712 |
from unittest import TestCase, main
from io import StringIO
from os.path import join, dirname, abspath
import skbio
import numpy as np
from deblur.sequence import Sequence
from deblur.workflow import sequence_generator
from deblur.deblurring import get_sequences, deblur, get_default_error_profile
class DeblurringT... | deblur/test/test_deblurring.py |
from unittest import TestCase, main
from io import StringIO
from os.path import join, dirname, abspath
import skbio
import numpy as np
from deblur.sequence import Sequence
from deblur.workflow import sequence_generator
from deblur.deblurring import get_sequences, deblur, get_default_error_profile
class DeblurringT... | 0.595963 | 0.30288 |
from aiida_nanotech_empa.utils import common_utils
import numpy as np
from aiida.engine import WorkChain, ExitCode, calcfunction, ToContext, if_
from aiida.orm import Int, Str, Bool, Code, List, Float, Dict
from aiida.orm import StructureData
from aiida.plugins import WorkflowFactory
Cp2kMoleculeGwWorkChain = Workf... | aiida_nanotech_empa/workflows/cp2k/adsorbed_gw_ic_workchain.py | from aiida_nanotech_empa.utils import common_utils
import numpy as np
from aiida.engine import WorkChain, ExitCode, calcfunction, ToContext, if_
from aiida.orm import Int, Str, Bool, Code, List, Float, Dict
from aiida.orm import StructureData
from aiida.plugins import WorkflowFactory
Cp2kMoleculeGwWorkChain = Workf... | 0.682785 | 0.411584 |
from math import sqrt, floor
import sys
import platform
def prob_1(n):
return n % 2 == 0
def prob_2(n):
return (n-32)*(5/9)
def prob_3(n, b):
if b == 0:
return 1
return n * prob_3(n, b-1)
def prob_4(c, l: int):
size = len(c)
final = ""
if size == l:
return c
elif... | solutions.py | from math import sqrt, floor
import sys
import platform
def prob_1(n):
return n % 2 == 0
def prob_2(n):
return (n-32)*(5/9)
def prob_3(n, b):
if b == 0:
return 1
return n * prob_3(n, b-1)
def prob_4(c, l: int):
size = len(c)
final = ""
if size == l:
return c
elif... | 0.236428 | 0.412974 |
__author__ = 'whos'
from datetime import datetime
from django.utils import timezone
import time
import random
import hashlib
def time_string(time_):
if time_ is None:
return ''
try:
return time_.strftime('%Y-%m-%d %H:%M:%S')
except ValueError:
return ''
def dat... | web_site/base/utils.py | __author__ = 'whos'
from datetime import datetime
from django.utils import timezone
import time
import random
import hashlib
def time_string(time_):
if time_ is None:
return ''
try:
return time_.strftime('%Y-%m-%d %H:%M:%S')
except ValueError:
return ''
def dat... | 0.302803 | 0.147371 |
import sys, os, re, time
import threading
import bisect
import contextlib
import signal
import json
import sqlite3
import websocket_server
import instabot
NICKNAME = 'Scribe'
VERSION = instabot.VERSION
MAXLEN = None
PING_DELAY = 3600 # 1 h
MAX_PINGS = 3
def parse_version(s):
if isinstance(s, float): s = str(s)... | script/scribe.py | import sys, os, re, time
import threading
import bisect
import contextlib
import signal
import json
import sqlite3
import websocket_server
import instabot
NICKNAME = 'Scribe'
VERSION = instabot.VERSION
MAXLEN = None
PING_DELAY = 3600 # 1 h
MAX_PINGS = 3
def parse_version(s):
if isinstance(s, float): s = str(s)... | 0.339061 | 0.071106 |
import torch
import torch.nn as nn
import torch.nn.functional as F
class PSPModule(nn.Module):
def __init__(self, features, out_features=1024, sizes=(1, 2, 3, 6)):
super().__init__()
self.stages = []
self.stages = nn.ModuleList([self._make_stage(features, size) for size in sizes])
s... | models/segwithskip_pspnet.py | import torch
import torch.nn as nn
import torch.nn.functional as F
class PSPModule(nn.Module):
def __init__(self, features, out_features=1024, sizes=(1, 2, 3, 6)):
super().__init__()
self.stages = []
self.stages = nn.ModuleList([self._make_stage(features, size) for size in sizes])
s... | 0.929087 | 0.496826 |
def scroller(index, quantity, timerange=timedelta(days=0), startdt="", enddt=""):
print("Starting to scroll", end='')
# Retrieve the datetimes, note that timerange has a higher priority
if timerange.total_seconds() > 0:
now = datetime.utcnow().replace(tzinfo=pytz.UTC)
startdt = (now - timera... | extra/Getting_Started/scroller.py | def scroller(index, quantity, timerange=timedelta(days=0), startdt="", enddt=""):
print("Starting to scroll", end='')
# Retrieve the datetimes, note that timerange has a higher priority
if timerange.total_seconds() > 0:
now = datetime.utcnow().replace(tzinfo=pytz.UTC)
startdt = (now - timera... | 0.215021 | 0.442938 |
import scipy as sp
import struct
def write_3darray(fn, arr):
""" write 3d-array to ascii file
@param
@return
"""
with open(fn, "w") as fo:
for w0 in range(arr.shape[0]):
fo.write( "{}\n".format(w0) )
for w1 in range(arr.shape[1]):
for w2 in range(ar... | utils/array/ndarray_utils.py | import scipy as sp
import struct
def write_3darray(fn, arr):
""" write 3d-array to ascii file
@param
@return
"""
with open(fn, "w") as fo:
for w0 in range(arr.shape[0]):
fo.write( "{}\n".format(w0) )
for w1 in range(arr.shape[1]):
for w2 in range(ar... | 0.362969 | 0.370112 |
from __future__ import print_function
import logging
import sys
from sqlalchemy import Index, MetaData, Table
from sqlalchemy.orm import scoped_session, sessionmaker
log = logging.getLogger( __name__ )
log.setLevel(logging.DEBUG)
handler = logging.StreamHandler( sys.stdout )
format = "%(name)s %(levelname)s %(asctim... | lib/galaxy/model/migrate/versions/0006_change_qual_datatype.py | from __future__ import print_function
import logging
import sys
from sqlalchemy import Index, MetaData, Table
from sqlalchemy.orm import scoped_session, sessionmaker
log = logging.getLogger( __name__ )
log.setLevel(logging.DEBUG)
handler = logging.StreamHandler( sys.stdout )
format = "%(name)s %(levelname)s %(asctim... | 0.39257 | 0.04904 |
from chainer.backends import cuda
from chainer import function_node
from chainer.utils import collections_abc
from chainer.utils import conv
from chainer.utils import type_check
if cuda.cudnn_enabled:
cudnn = cuda.cudnn
def _pair(x):
if isinstance(x, collections_abc.Iterable):
return x
return x, ... | chainer/functions/pooling/pooling_2d.py | from chainer.backends import cuda
from chainer import function_node
from chainer.utils import collections_abc
from chainer.utils import conv
from chainer.utils import type_check
if cuda.cudnn_enabled:
cudnn = cuda.cudnn
def _pair(x):
if isinstance(x, collections_abc.Iterable):
return x
return x, ... | 0.876397 | 0.312672 |
def solve():
'''
By replacing the 1st digit of *57, it turns out that six of the possible values: 157, 257, 457, 557, 757, and 857, are all prime.
By replacing the 3rd and 4th digits of 56**3 with the same digit, this 5-digit number is the first example having seven primes, yielding the family: 56003, ... | pythran/tests/euler/euler51.py | def solve():
'''
By replacing the 1st digit of *57, it turns out that six of the possible values: 157, 257, 457, 557, 757, and 857, are all prime.
By replacing the 3rd and 4th digits of 56**3 with the same digit, this 5-digit number is the first example having seven primes, yielding the family: 56003, ... | 0.64512 | 0.697525 |
from server.extensions import db
from sqlalchemy import Numeric
from sqlalchemy.dialects.postgresql import JSONB, UUID
from server.models.mixin import TimestampMixin
from sqlalchemy import (
UniqueConstraint,
)
class Portfolio(db.Model, TimestampMixin):
__tablename__ = "portfolio"
id = db.Column(db.Integ... | server/models/portfolio.py | from server.extensions import db
from sqlalchemy import Numeric
from sqlalchemy.dialects.postgresql import JSONB, UUID
from server.models.mixin import TimestampMixin
from sqlalchemy import (
UniqueConstraint,
)
class Portfolio(db.Model, TimestampMixin):
__tablename__ = "portfolio"
id = db.Column(db.Integ... | 0.684053 | 0.190705 |
from __future__ import annotations
from pathlib import Path
import os
import json
import stat
import shutil
import tempfile
import hashlib
import datetime
import typing
from typing import (
Union,
Sequence,
Dict,
Generator,
Tuple,
Any,
TypeVar,
NewType,
Callable,
)
import attr
... | archivo/archivo.py | from __future__ import annotations
from pathlib import Path
import os
import json
import stat
import shutil
import tempfile
import hashlib
import datetime
import typing
from typing import (
Union,
Sequence,
Dict,
Generator,
Tuple,
Any,
TypeVar,
NewType,
Callable,
)
import attr
... | 0.523908 | 0.167185 |
import abc
import torch
from torch import Tensor
class Viewer(abc.ABC):
'''
The Viewer class represents an viewing model.
'''
@abc.abstractmethod
def directions(self, points: Tensor) -> Tensor:
'''
Returns the outbound directions of this Viewer with respect to the given points.
... | project/viewer.py | import abc
import torch
from torch import Tensor
class Viewer(abc.ABC):
'''
The Viewer class represents an viewing model.
'''
@abc.abstractmethod
def directions(self, points: Tensor) -> Tensor:
'''
Returns the outbound directions of this Viewer with respect to the given points.
... | 0.941788 | 0.76769 |
from .test_computation import setup_tests
from .conftest import *
from .utils import *
def test_patterns(setup_tests):
storage, cts = setup_tests
storage:Storage
with context(storage=storage):
@op()
def add_1(x:Array) -> Array:
res = x + 1
return AsTransient(re... | mandala/tests/test_integration.py | from .test_computation import setup_tests
from .conftest import *
from .utils import *
def test_patterns(setup_tests):
storage, cts = setup_tests
storage:Storage
with context(storage=storage):
@op()
def add_1(x:Array) -> Array:
res = x + 1
return AsTransient(re... | 0.566378 | 0.616965 |
from json import dumps
from pandas import DataFrame
from requests import Session
import re
import logging
from . import api_globals
from .api_exceptions import AuthError, DatabaseError, ProgrammingError, CursorClosedException, \
ConnectionClosedException
apilevel = '2.0'
threadsafety = 3
paramstyle = 'qmark'
defau... | sqlalchemy_drill/drilldbapi/_drilldbapi.py | from json import dumps
from pandas import DataFrame
from requests import Session
import re
import logging
from . import api_globals
from .api_exceptions import AuthError, DatabaseError, ProgrammingError, CursorClosedException, \
ConnectionClosedException
apilevel = '2.0'
threadsafety = 3
paramstyle = 'qmark'
defau... | 0.46393 | 0.096834 |
# ==============================================================================
# SBEMimage, ver. 2.0
# Acquisition control software for serial block-face electron microscopy
# (c) 2018-2019 <NAME> Institute for Biomedical Research, Basel.
# Author(s): <NAME> (<EMAIL>),
# https://github.com/SBEMimage/SBEMim... | src/sbemimage.py |
# ==============================================================================
# SBEMimage, ver. 2.0
# Acquisition control software for serial block-face electron microscopy
# (c) 2018-2019 <NAME> Institute for Biomedical Research, Basel.
# Author(s): <NAME> (<EMAIL>),
# https://github.com/SBEMimage/SBEMim... | 0.425844 | 0.08438 |
"""Object Value Model"""
from __future__ import (absolute_import, print_function,
division, unicode_literals)
from sqlalchemy import Column, Integer, Text
from sqlalchemy import PrimaryKeyConstraint, ForeignKeyConstraint
from sqlalchemy import CheckConstraint
from .. import relational, conten... | now/persistence/models/object_value.py |
"""Object Value Model"""
from __future__ import (absolute_import, print_function,
division, unicode_literals)
from sqlalchemy import Column, Integer, Text
from sqlalchemy import PrimaryKeyConstraint, ForeignKeyConstraint
from sqlalchemy import CheckConstraint
from .. import relational, conten... | 0.61878 | 0.211946 |
import math
class entropyDecisionTreeClassifier:
def __init__(self):
self.dt = None
class tree:
def __init__(self):
self.colname = None
self.thisclass = None
self.isdecisive = False
self.availablecols = []
self.trees = {}
def entr... | tree.py | import math
class entropyDecisionTreeClassifier:
def __init__(self):
self.dt = None
class tree:
def __init__(self):
self.colname = None
self.thisclass = None
self.isdecisive = False
self.availablecols = []
self.trees = {}
def entr... | 0.469763 | 0.29209 |
import gdsfactory as gf
from gdsfactory.component import Component
from gdsfactory.components.bend_circular import bend_circular
from gdsfactory.components.bend_euler import bend_euler
from gdsfactory.components.straight import straight
from gdsfactory.cross_section import strip
from gdsfactory.types import ComponentFa... | gdsfactory/components/coupler90.py | import gdsfactory as gf
from gdsfactory.component import Component
from gdsfactory.components.bend_circular import bend_circular
from gdsfactory.components.bend_euler import bend_euler
from gdsfactory.components.straight import straight
from gdsfactory.cross_section import strip
from gdsfactory.types import ComponentFa... | 0.562777 | 0.325574 |
import dpctl
import numpy as np
from numba import float32
import numba_dppy as dppy
def no_arg_barrier_support():
"""
This example demonstrates the usage of numba_dppy's ``barrier``
intrinsic function. The ``barrier`` function is usable only inside
a ``kernel`` and is equivalent to OpenCL's ``barrie... | numba_dppy/examples/barrier.py |
import dpctl
import numpy as np
from numba import float32
import numba_dppy as dppy
def no_arg_barrier_support():
"""
This example demonstrates the usage of numba_dppy's ``barrier``
intrinsic function. The ``barrier`` function is usable only inside
a ``kernel`` and is equivalent to OpenCL's ``barrie... | 0.757525 | 0.620909 |
from conan.tools.microsoft.visual import vcvars_command
def check_vs_runtime(artifact, client, vs_version, build_type, architecture="amd64",
static_runtime=False):
vcvars = vcvars_command(version=vs_version, architecture=architecture)
normalized_path = artifact.replace("/", "\\")
stat... | conans/test/functional/utils.py | from conan.tools.microsoft.visual import vcvars_command
def check_vs_runtime(artifact, client, vs_version, build_type, architecture="amd64",
static_runtime=False):
vcvars = vcvars_command(version=vs_version, architecture=architecture)
normalized_path = artifact.replace("/", "\\")
stat... | 0.38318 | 0.263422 |
import os
import datetime
# change your parent dir accordingly
try:
directory = "ExDirFiles"
parent_dir = "E:/GitHub/1) Git_Tutorials_Repo_Projects/core-python/Core_Python/"
path = os.path.join(parent_dir,directory)
''' mode is set to '0o666' which allowed both read and write functionality for the
... | core-python/Core_Python/file/DirMethods.py | import os
import datetime
# change your parent dir accordingly
try:
directory = "ExDirFiles"
parent_dir = "E:/GitHub/1) Git_Tutorials_Repo_Projects/core-python/Core_Python/"
path = os.path.join(parent_dir,directory)
''' mode is set to '0o666' which allowed both read and write functionality for the
... | 0.075536 | 0.13201 |
# Python standard library imports
import csv
import os
def main():
costs = []
for file in os.listdir("reformatted/"):
print 'getting data from.. ' + file
cost_total = []
cost_2000 = []
cost_2001 = []
cost_2002 = []
cost_2003 = []
cost_2004 = []
... | Data/PVdata/add_costs_per_size_perdate.py | # Python standard library imports
import csv
import os
def main():
costs = []
for file in os.listdir("reformatted/"):
print 'getting data from.. ' + file
cost_total = []
cost_2000 = []
cost_2001 = []
cost_2002 = []
cost_2003 = []
cost_2004 = []
... | 0.209793 | 0.20947 |
# This import verifies that the dependencies are available.
import uuid
from metadata.generated.schema.entity.data.database import Database
from metadata.generated.schema.entity.services.databaseService import DatabaseServiceType
from metadata.generated.schema.type.entityReference import EntityReference
from metadata.... | ingestion/src/metadata/ingestion/source/postgres.py |
# This import verifies that the dependencies are available.
import uuid
from metadata.generated.schema.entity.data.database import Database
from metadata.generated.schema.entity.services.databaseService import DatabaseServiceType
from metadata.generated.schema.type.entityReference import EntityReference
from metadata.... | 0.643889 | 0.088702 |
import random
from typing import List
from network_simulator.BloodType import BloodType
from network_simulator.Network import Network
from network_simulator.Patient import Patient
from network_simulator.WaitList import WaitList
from network_simulator.compatibility_markers import OrganType, BloodTypeLetter, Bloo... | network_simulator/PatientGenerator.py | import random
from typing import List
from network_simulator.BloodType import BloodType
from network_simulator.Network import Network
from network_simulator.Patient import Patient
from network_simulator.WaitList import WaitList
from network_simulator.compatibility_markers import OrganType, BloodTypeLetter, Bloo... | 0.69451 | 0.500549 |
from __future__ import division
import scipy.interpolate
from matplotlib import cm
import numpy as np
def bipolar(lutsize=256, n=0.333, interp=[]):
"""
Bipolar hot/cold colormap, with neutral central color.
This colormap is meant for visualizing diverging data; positive
and negative deviations from a ... | chroma/bipolar.py | from __future__ import division
import scipy.interpolate
from matplotlib import cm
import numpy as np
def bipolar(lutsize=256, n=0.333, interp=[]):
"""
Bipolar hot/cold colormap, with neutral central color.
This colormap is meant for visualizing diverging data; positive
and negative deviations from a ... | 0.93992 | 0.748467 |
import tkinter as tk
from tkinter import filedialog
from xls_summary.summarize import do_a_summary
class Application(tk.Frame):
def __init__(self, master=None):
tk.Frame.__init__(self, master)
self.pack()
self.createWidgets()
self.dir = None
def createWidgets(self):
sel... | app.py | import tkinter as tk
from tkinter import filedialog
from xls_summary.summarize import do_a_summary
class Application(tk.Frame):
def __init__(self, master=None):
tk.Frame.__init__(self, master)
self.pack()
self.createWidgets()
self.dir = None
def createWidgets(self):
sel... | 0.31363 | 0.077378 |
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... | env/lib/python3.5/site-packages/google/api/monitoring_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.185984 | 0.084871 |
import argparse
import json
import message_ix
import os
import shutil
import tempfile
import zipfile
from six.moves.urllib.request import urlretrieve
from message_ix.default_path_constants import CONFIG_PATH, DEFAULT_MODEL_PATH
from message_ix.utils import logger
def recursive_copy(src, dst, overwrite=False, skip_... | message_ix/cli.py | import argparse
import json
import message_ix
import os
import shutil
import tempfile
import zipfile
from six.moves.urllib.request import urlretrieve
from message_ix.default_path_constants import CONFIG_PATH, DEFAULT_MODEL_PATH
from message_ix.utils import logger
def recursive_copy(src, dst, overwrite=False, skip_... | 0.249173 | 0.087175 |
import broadlink, configparser
import sys, getopt
import time, binascii
import netaddr
import Settings
import web
from os import path
from Crypto.Cipher import AES
SettingsFile = configparser.ConfigParser()
SettingsFile.optionxform = str
SettingsFile.read(Settings.BlackBeanControlSettings)
DeviceName=''
DeviceIPAddr... | WebControl.py |
import broadlink, configparser
import sys, getopt
import time, binascii
import netaddr
import Settings
import web
from os import path
from Crypto.Cipher import AES
SettingsFile = configparser.ConfigParser()
SettingsFile.optionxform = str
SettingsFile.read(Settings.BlackBeanControlSettings)
DeviceName=''
DeviceIPAddr... | 0.287168 | 0.041989 |
import warnings
import pulumi
import pulumi.runtime
from typing import Any, Mapping, Optional, Sequence, Union, overload
from .. import _utilities
from . import outputs
__all__ = [
'LifecyclePolicyPolicyDetails',
'LifecyclePolicyPolicyDetailsSchedule',
'LifecyclePolicyPolicyDetailsScheduleCreateRule',
... | sdk/python/pulumi_aws/dlm/outputs.py |
import warnings
import pulumi
import pulumi.runtime
from typing import Any, Mapping, Optional, Sequence, Union, overload
from .. import _utilities
from . import outputs
__all__ = [
'LifecyclePolicyPolicyDetails',
'LifecyclePolicyPolicyDetailsSchedule',
'LifecyclePolicyPolicyDetailsScheduleCreateRule',
... | 0.882174 | 0.090173 |
import sys,os
import glob,time
from nlptk.postagging.taggers import get_tagger
from nlptk.junk.preprocess import Preprocessor
from nlptk.junk.vocabulary import (Stream,
BaseCorpus,
PlainCorpus,
Te... | nlptk/junk/main.py | import sys,os
import glob,time
from nlptk.postagging.taggers import get_tagger
from nlptk.junk.preprocess import Preprocessor
from nlptk.junk.vocabulary import (Stream,
BaseCorpus,
PlainCorpus,
Te... | 0.073465 | 0.085556 |
from collections import OrderedDict
import functools
import re
from typing import Dict, Sequence, Tuple, Type, Union
import pkg_resources
import google.api_core.client_options as ClientOptions # type: ignore
from google.api_core import exceptions as core_exceptions # type: ignore
from google.api_core import gapic_v1 ... | google/cloud/retail/v2alpha/retail-v2alpha-py/google/cloud/retail_v2alpha/services/catalog_service/async_client.py | from collections import OrderedDict
import functools
import re
from typing import Dict, Sequence, Tuple, Type, Union
import pkg_resources
import google.api_core.client_options as ClientOptions # type: ignore
from google.api_core import exceptions as core_exceptions # type: ignore
from google.api_core import gapic_v1 ... | 0.742141 | 0.097519 |
import unittest
import zserio
from testutils import getZserioApi
class BitAlignmentTest(unittest.TestCase):
@classmethod
def setUpClass(cls):
cls.api = getZserioApi(__file__, "alignment.zs").bit_alignment
def testBitSizeOf(self):
bitAlignment = self._createBitAlignment()
self.asse... | test/language/alignment/python/BitAlignmentTest.py | import unittest
import zserio
from testutils import getZserioApi
class BitAlignmentTest(unittest.TestCase):
@classmethod
def setUpClass(cls):
cls.api = getZserioApi(__file__, "alignment.zs").bit_alignment
def testBitSizeOf(self):
bitAlignment = self._createBitAlignment()
self.asse... | 0.614047 | 0.275647 |
import threading
import datetime
import schedule
import asyncio
import logging
import time
from flask import Flask, json, request, Response
from werkzeug.wsgi import DispatcherMiddleware
from .utils import AttrDict, TaggedDict, mangle_name, join_url, _APIWrapper, IdioticEncoder
from .dispatch import Dispatcher
from .ve... | idiotic/__init__.py | import threading
import datetime
import schedule
import asyncio
import logging
import time
from flask import Flask, json, request, Response
from werkzeug.wsgi import DispatcherMiddleware
from .utils import AttrDict, TaggedDict, mangle_name, join_url, _APIWrapper, IdioticEncoder
from .dispatch import Dispatcher
from .ve... | 0.356447 | 0.061876 |
r"""
ECEI2D
=======
contains 2D version of synthetic Electron Cyclotron
Emission Imaging Diagnostic.
Unit Conventions
-----------------
In ECEI2D, Gaussian unit is used by default. The units for common quantities
are:
length:
centi-meter
time:
second
mass:
gram
magnetic field:
Gauss
temperature:
... | src/python2/sdp/diagnostic/ecei/ecei2d/__init__.py | r"""
ECEI2D
=======
contains 2D version of synthetic Electron Cyclotron
Emission Imaging Diagnostic.
Unit Conventions
-----------------
In ECEI2D, Gaussian unit is used by default. The units for common quantities
are:
length:
centi-meter
time:
second
mass:
gram
magnetic field:
Gauss
temperature:
... | 0.942441 | 0.796807 |
import numpy
import struct
import sys
## Standard size:
## short is 8 bits
## int and long are 32 bits
## long long is 64 bits
class BadMagicNumber( IOError ):
pass
class BinaryFileReader( object ):
"""
Wrapper for doing binary reads on any file like object.
Currently this is not heavily optimiz... | jgem/bxbbi/binary_file.py | import numpy
import struct
import sys
## Standard size:
## short is 8 bits
## int and long are 32 bits
## long long is 64 bits
class BadMagicNumber( IOError ):
pass
class BinaryFileReader( object ):
"""
Wrapper for doing binary reads on any file like object.
Currently this is not heavily optimiz... | 0.420838 | 0.466603 |
from __future__ import annotations
from xknx.exceptions import ConversionError
from .dpt import DPTNumeric
class DPT2ByteFloat(DPTNumeric):
"""
Abstraction for KNX 2 Octet Floating Point Numbers.
DPT 9.***
"""
dpt_main_number = 9
dpt_sub_number: int | None = None
value_type = "2byte_fl... | xknx/dpt/dpt_2byte_float.py | from __future__ import annotations
from xknx.exceptions import ConversionError
from .dpt import DPTNumeric
class DPT2ByteFloat(DPTNumeric):
"""
Abstraction for KNX 2 Octet Floating Point Numbers.
DPT 9.***
"""
dpt_main_number = 9
dpt_sub_number: int | None = None
value_type = "2byte_fl... | 0.864782 | 0.433921 |
import os
from typing import Dict, Any, Tuple, List
import json
import numpy as np
import networkx as nx
def load_json(filename):
with open(filename, 'r') as f:
return json.load(f)
def save_downstream_data(filename, pos_data, neg_data):
with open(filename, 'w') as f:
for x in pos_data:
... | paccmann_polymer/topologically_regularized_models/experiments/chem_reactions/downstream_preprocessing.py | import os
from typing import Dict, Any, Tuple, List
import json
import numpy as np
import networkx as nx
def load_json(filename):
with open(filename, 'r') as f:
return json.load(f)
def save_downstream_data(filename, pos_data, neg_data):
with open(filename, 'w') as f:
for x in pos_data:
... | 0.582966 | 0.387459 |
from __future__ import annotations
import typing
import matplotlib.pyplot as plt
from . import conf, _helpers
from .stagyydata import StagyyData
if typing.TYPE_CHECKING:
from ._step import Step, _Rprofs
def plot_rprofs(rprofs: _Rprofs, names: str) -> None:
"""Plot requested radial profiles.
Args:
... | stagpy/rprof.py |
from __future__ import annotations
import typing
import matplotlib.pyplot as plt
from . import conf, _helpers
from .stagyydata import StagyyData
if typing.TYPE_CHECKING:
from ._step import Step, _Rprofs
def plot_rprofs(rprofs: _Rprofs, names: str) -> None:
"""Plot requested radial profiles.
Args:
... | 0.924449 | 0.401453 |
"""Tests for uisrnn.py."""
import tempfile
import unittest
import numpy as np
import uisrnn
class TestUISRNN(unittest.TestCase):
"""Test the UISRNN class."""
def test_fit_concatenated_and_predict_single_label(self):
"""Train and test model while training dataset has single label.
Training ... | uisrnn/tests/uisrnn_test.py | """Tests for uisrnn.py."""
import tempfile
import unittest
import numpy as np
import uisrnn
class TestUISRNN(unittest.TestCase):
"""Test the UISRNN class."""
def test_fit_concatenated_and_predict_single_label(self):
"""Train and test model while training dataset has single label.
Training ... | 0.799286 | 0.784071 |