code stringlengths 2k 1.04M | repo_path stringlengths 5 517 | parsed_code stringlengths 0 1.04M | quality_prob float64 0.02 0.95 | learning_prob float64 0.02 0.93 |
|---|---|---|---|---|
from __future__ import print_function
# summary provider for CF(Mutable)BitVector
import lldb
import ctypes
import lldb.runtime.objc.objc_runtime
import lldb.formatters.metrics
import lldb.formatters.Logger
# first define some utility functions
def byte_index(abs_pos):
logger = lldb.formatters.Logger.Logger()
... | lldb/examples/summaries/cocoa/CFBitVector.py | from __future__ import print_function
# summary provider for CF(Mutable)BitVector
import lldb
import ctypes
import lldb.runtime.objc.objc_runtime
import lldb.formatters.metrics
import lldb.formatters.Logger
# first define some utility functions
def byte_index(abs_pos):
logger = lldb.formatters.Logger.Logger()
... | 0.587943 | 0.32748 |
import re
import math
from time import time
HEX_RE = re.compile("#([0-9a-fA-F]{3}|[0-9a-fA-F]{6})")
class Py3status:
"""
"""
# available configuration parameters
cycle_time = 1
force = False
format = "{output}"
gradient = [
"#FF0000",
"#FFFF00",
"#00FF00",
... | py3status/modules/rainbow.py | import re
import math
from time import time
HEX_RE = re.compile("#([0-9a-fA-F]{3}|[0-9a-fA-F]{6})")
class Py3status:
"""
"""
# available configuration parameters
cycle_time = 1
force = False
format = "{output}"
gradient = [
"#FF0000",
"#FFFF00",
"#00FF00",
... | 0.425367 | 0.282668 |
import os
from PyQt5.QtCore import Qt, pyqtSignal
from PyQt5.QtGui import QPixmap
from PyQt5.QtWidgets import (QDialog, QLabel, QDialogButtonBox, QLineEdit, QCheckBox,
QHBoxLayout, QVBoxLayout, QFormLayout, QFileDialog)
from lanzou.gui.qss import dialog_qss_style
from lanzou.gui.others imp... | lanzou/gui/dialogs/setting.py | import os
from PyQt5.QtCore import Qt, pyqtSignal
from PyQt5.QtGui import QPixmap
from PyQt5.QtWidgets import (QDialog, QLabel, QDialogButtonBox, QLineEdit, QCheckBox,
QHBoxLayout, QVBoxLayout, QFormLayout, QFileDialog)
from lanzou.gui.qss import dialog_qss_style
from lanzou.gui.others imp... | 0.22051 | 0.08292 |
import os
import platform
import argparse
class Common():
def __init__(self, sudo_cmd):
# Assumption is nvidia-smi is installed on systems with gpu
self.is_gpu_instance = True if os.system("nvidia-smi") == 0 else False
self.torch_stable_url = "https://download.pytorch.org/whl/torch_stable.... | ts_scripts/install_dependencies.py | import os
import platform
import argparse
class Common():
def __init__(self, sudo_cmd):
# Assumption is nvidia-smi is installed on systems with gpu
self.is_gpu_instance = True if os.system("nvidia-smi") == 0 else False
self.torch_stable_url = "https://download.pytorch.org/whl/torch_stable.... | 0.294114 | 0.097648 |
import pytest
import numpy as np
from shapely.geometry import Polygon, Point, LineString
import geopandas as gpd
import earthpy.clip as cl
@pytest.fixture
def point_gdf():
"""Create a point GeoDataFrame."""
pts = np.array([[2, 2], [3, 4], [9, 8], [-12, -15]])
gdf = gpd.GeoDataFrame(
[Point(xy) fo... | earthpy/tests/test_clip.py |
import pytest
import numpy as np
from shapely.geometry import Polygon, Point, LineString
import geopandas as gpd
import earthpy.clip as cl
@pytest.fixture
def point_gdf():
"""Create a point GeoDataFrame."""
pts = np.array([[2, 2], [3, 4], [9, 8], [-12, -15]])
gdf = gpd.GeoDataFrame(
[Point(xy) fo... | 0.845879 | 0.687172 |
"""Layer for modelling and scoring secondary structure."""
import os
from absl import logging
import numpy as np
import tensorflow as tf # pylint: disable=g-explicit-tensorflow-version-import
# 8-class classes (Q8)
SECONDARY_STRUCTURES = '-HETSGBI'
# Equivalence classes for 3-class (Q3) from Li & Yu 2016.
# See h... | alphafold_casp13/secstruct.py | """Layer for modelling and scoring secondary structure."""
import os
from absl import logging
import numpy as np
import tensorflow as tf # pylint: disable=g-explicit-tensorflow-version-import
# 8-class classes (Q8)
SECONDARY_STRUCTURES = '-HETSGBI'
# Equivalence classes for 3-class (Q3) from Li & Yu 2016.
# See h... | 0.858881 | 0.445107 |
from enum import Enum
from typing import Any, Dict, List
from mypy_extensions import TypedDict
from typing_extensions import Protocol
from openslides_backend.shared.interfaces import Filter
from openslides_backend.shared.patterns import Collection, FullQualifiedId
PartialModel = Dict[str, Any]
Found = TypedDict("Fou... | openslides_backend/services/database/adapter/interface.py | from enum import Enum
from typing import Any, Dict, List
from mypy_extensions import TypedDict
from typing_extensions import Protocol
from openslides_backend.shared.interfaces import Filter
from openslides_backend.shared.patterns import Collection, FullQualifiedId
PartialModel = Dict[str, Any]
Found = TypedDict("Fou... | 0.857067 | 0.213172 |
import base64
import jwt
from allauth.socialaccount.providers.oauth2.views import OAuth2Adapter, OAuth2CallbackView, OAuth2LoginView
from cryptography import x509
from cryptography.hazmat.backends import default_backend
from .provider import EspooADFSProvider, HelsinkiADFSProvider
x509_backend = default_backend()
... | adfs_provider/views.py | import base64
import jwt
from allauth.socialaccount.providers.oauth2.views import OAuth2Adapter, OAuth2CallbackView, OAuth2LoginView
from cryptography import x509
from cryptography.hazmat.backends import default_backend
from .provider import EspooADFSProvider, HelsinkiADFSProvider
x509_backend = default_backend()
... | 0.396419 | 0.104752 |
# For parsing cli arguments
import argparse
# For parsing JSON files
import json
# Plotting library
import matplotlib as plt
plt.use('Agg')
import matplotlib.pyplot as pyplot
# To access more matplotlib functionality, i.e., default calculated figure
# size
from pylab import rcParams
_version = 0.2
def getVersion(... | benchmark_visualizer.py |
# For parsing cli arguments
import argparse
# For parsing JSON files
import json
# Plotting library
import matplotlib as plt
plt.use('Agg')
import matplotlib.pyplot as pyplot
# To access more matplotlib functionality, i.e., default calculated figure
# size
from pylab import rcParams
_version = 0.2
def getVersion(... | 0.654453 | 0.327144 |
import numpy as np
import logging
from ..common.utils import get_command_args, configure_logger
from ..common.gen_samples import read_anomaly_dataset
from .aad_globals import (
IFOR_SCORE_TYPE_NEG_PATH_LEN, ENSEMBLE_SCORE_LINEAR, AAD_IFOREST, INIT_UNIF
)
from .data_stream import DataStream, IdServer
from .random... | ad_examples/aad/test_concept_drift.py | import numpy as np
import logging
from ..common.utils import get_command_args, configure_logger
from ..common.gen_samples import read_anomaly_dataset
from .aad_globals import (
IFOR_SCORE_TYPE_NEG_PATH_LEN, ENSEMBLE_SCORE_LINEAR, AAD_IFOREST, INIT_UNIF
)
from .data_stream import DataStream, IdServer
from .random... | 0.384565 | 0.200734 |
import gzip
import itertools
import numpy as np
import pandas as pd
from scipy import stats
import six.moves.cPickle as pickle
def df_to_struct(df):
"""Converts a DataFrame to RPy-compatible structured array."""
struct_array = df.to_records()
arr_dtype = struct_array.dtype.descr
for i, dtype in enume... | moss/misc.py | import gzip
import itertools
import numpy as np
import pandas as pd
from scipy import stats
import six.moves.cPickle as pickle
def df_to_struct(df):
"""Converts a DataFrame to RPy-compatible structured array."""
struct_array = df.to_records()
arr_dtype = struct_array.dtype.descr
for i, dtype in enume... | 0.771069 | 0.400046 |
from password import Password
def create_password(flo,me,beat,joby):
new_password = Password(flo,me,beat,joby)
return new_password
def save_passwords(password):
password.save_Password()
def del_password(password):
password.delete_password()
def find_password(user_name):
return Password.find... | run.py |
from password import Password
def create_password(flo,me,beat,joby):
new_password = Password(flo,me,beat,joby)
return new_password
def save_passwords(password):
password.save_Password()
def del_password(password):
password.delete_password()
def find_password(user_name):
return Password.find... | 0.276105 | 0.118998 |
from functools import partial
from typing import Callable, List
from pyglet.window import mouse
from engine.models.ship import ShipModel
from engine.views.ship_parts.factories import ConfigViewFactory
from .base import BaseMenu, BaseButton
from .drydock import ControlConfiguration
class ControlConfigMenu(BaseMenu):... | engine/views/menus/control_config.py | from functools import partial
from typing import Callable, List
from pyglet.window import mouse
from engine.models.ship import ShipModel
from engine.views.ship_parts.factories import ConfigViewFactory
from .base import BaseMenu, BaseButton
from .drydock import ControlConfiguration
class ControlConfigMenu(BaseMenu):... | 0.707405 | 0.161221 |
import sys
import argparse
from workflow import Workflow, ICON_WEB, ICON_WARNING, ICON_NOTE, web, PasswordNotFound, Workflow3
def main(wf):
def googleFilter(filename):
return 'google' in filename
def exchangeFilter(filename):
return 'exchange' in filename
import os
from workflow.notif... | src/store_data.py | import sys
import argparse
from workflow import Workflow, ICON_WEB, ICON_WARNING, ICON_NOTE, web, PasswordNotFound, Workflow3
def main(wf):
def googleFilter(filename):
return 'google' in filename
def exchangeFilter(filename):
return 'exchange' in filename
import os
from workflow.notif... | 0.107601 | 0.111 |
import os
import torch
import torch.utils.data as data
import torchvision.transforms as transforms
import torchvision.datasets as datasets
from .misc import get_cifar_models
from collections import OrderedDict
__all__ = [
'load_optimizer',
'load_learning_rate_schedule',
'load_checkpoint',
# cifar
'... | utils/loaders.py | import os
import torch
import torch.utils.data as data
import torchvision.transforms as transforms
import torchvision.datasets as datasets
from .misc import get_cifar_models
from collections import OrderedDict
__all__ = [
'load_optimizer',
'load_learning_rate_schedule',
'load_checkpoint',
# cifar
'... | 0.79657 | 0.365372 |
from ._fitting import __fit_single_decay__, __fit_triple_decay__
from numpy import array, unique
from pandas import Series, concat
from tqdm import tqdm
def fit_relaxation(flevel, seq_time, seq, datetime, blank=0, sat_len=100, rel_len=60, sat_flashlets=None, single_decay=False, bounds=True, single_lims=[100,50000], t... | phyto_photo_utils/_relaxation.py |
from ._fitting import __fit_single_decay__, __fit_triple_decay__
from numpy import array, unique
from pandas import Series, concat
from tqdm import tqdm
def fit_relaxation(flevel, seq_time, seq, datetime, blank=0, sat_len=100, rel_len=60, sat_flashlets=None, single_decay=False, bounds=True, single_lims=[100,50000], t... | 0.864353 | 0.577972 |
import re
import sys
import os
from io import StringIO
import tkinter
import IPython
from functools import reduce
#Works by itself, but not able to import it into the GUI at this time.
class IterableIPShell:
def __init__(self,argv=None,user_ns=None,user_global_ns=None,
cin=None, cout=None,cerr=None, i... | jade2/pyrosetta_toolkit/window_modules/interactive_terminal/interactive_terminal.py | import re
import sys
import os
from io import StringIO
import tkinter
import IPython
from functools import reduce
#Works by itself, but not able to import it into the GUI at this time.
class IterableIPShell:
def __init__(self,argv=None,user_ns=None,user_global_ns=None,
cin=None, cout=None,cerr=None, i... | 0.192615 | 0.089177 |
import django.db.models.deletion
from django.db import migrations, models
class Migration(migrations.Migration):
dependencies = [
("core", "0023_add_referral_answer_attachment_with_base_class"),
]
operations = [
migrations.CreateModel(
name="ReferralUrgency",
fie... | src/backend/partaj/core/migrations/0024_add_urgency_model.py |
import django.db.models.deletion
from django.db import migrations, models
class Migration(migrations.Migration):
dependencies = [
("core", "0023_add_referral_answer_attachment_with_base_class"),
]
operations = [
migrations.CreateModel(
name="ReferralUrgency",
fie... | 0.509276 | 0.156362 |
import cs_grading as CS
import os
text_editor = 'subl'
#Options for p5
run_p5_test = 1 # Change to 0 to turn off these tests .
p5_use_valgrind = 1 # Change to 0 if you don't want valgrind to be run.
p5_source_files = '../barry.cpp' # The name and location of the student's solution file rel... | CSCI-104/homework-resources/hw1-test/hw1-checker.py | import cs_grading as CS
import os
text_editor = 'subl'
#Options for p5
run_p5_test = 1 # Change to 0 to turn off these tests .
p5_use_valgrind = 1 # Change to 0 if you don't want valgrind to be run.
p5_source_files = '../barry.cpp' # The name and location of the student's solution file rel... | 0.095592 | 0.131675 |
import numpy as np
import tvm
import topi
def verify_expand_dims(in_shape, out_shape, axis, num_newaxis):
A = tvm.placeholder(shape=in_shape, name="A")
B = topi.cpp.expand_dims(A, axis, num_newaxis)
def check_device(device):
ctx = tvm.context(device, 0)
if not ctx.exist:
print("... | topi/tests/python_cpp/test_topi_transform.py | import numpy as np
import tvm
import topi
def verify_expand_dims(in_shape, out_shape, axis, num_newaxis):
A = tvm.placeholder(shape=in_shape, name="A")
B = topi.cpp.expand_dims(A, axis, num_newaxis)
def check_device(device):
ctx = tvm.context(device, 0)
if not ctx.exist:
print("... | 0.346541 | 0.436622 |
import numpy
import talib
class ChartFeature(object):
def __init__(self, selector):
self.selector = selector
self.supported = {"ROCP", "OROCP", "HROCP", "LROCP", "MACD", "RSI", "VROCP", "BOLL", "MA", "VMA", "PRICE_VOLUME"}
self.feature = []
def moving_extract(self, window=30, open_pr... | chart.py |
import numpy
import talib
class ChartFeature(object):
def __init__(self, selector):
self.selector = selector
self.supported = {"ROCP", "OROCP", "HROCP", "LROCP", "MACD", "RSI", "VROCP", "BOLL", "MA", "VMA", "PRICE_VOLUME"}
self.feature = []
def moving_extract(self, window=30, open_pr... | 0.252661 | 0.348091 |
import string
from collections import defaultdict
import torch
import torch.nn as nn
from citextract.utils.model import load_model_params
class TitleTagging(nn.Module):
"""TitleTagging model."""
def __init__(self, input_size, hidden_size, n_layers, n_classes, device):
"""Initialize the model.
... | citextract/models/titlextract.py | import string
from collections import defaultdict
import torch
import torch.nn as nn
from citextract.utils.model import load_model_params
class TitleTagging(nn.Module):
"""TitleTagging model."""
def __init__(self, input_size, hidden_size, n_layers, n_classes, device):
"""Initialize the model.
... | 0.937304 | 0.602354 |
#%%
import cv2
from pathlib import Path
import matplotlib.pyplot as plt
from collections import defaultdict
import numpy as np
PATTERN_SIZE = (9, 6)
SQUARE_SIZE_CM = 3.4 # Measured from my source checkerboard
ROTATE_CAMERA_180 = True
im_paths = list(Path('./calib_data').glob('*.png'))
ims = [cv2.imread(str(p)) for... | calib.py |
#%%
import cv2
from pathlib import Path
import matplotlib.pyplot as plt
from collections import defaultdict
import numpy as np
PATTERN_SIZE = (9, 6)
SQUARE_SIZE_CM = 3.4 # Measured from my source checkerboard
ROTATE_CAMERA_180 = True
im_paths = list(Path('./calib_data').glob('*.png'))
ims = [cv2.imread(str(p)) for... | 0.439507 | 0.515559 |
import ipaddress
import json
import logging
import re
from tests.common.devices.base import AnsibleHostBase
logger = logging.getLogger(__name__)
def _raise_err(msg):
logger.error(msg)
raise Exception(msg)
class EosHost(AnsibleHostBase):
"""
@summary: Class for Eos switch
For run... | tests/common/devices/eos.py | import ipaddress
import json
import logging
import re
from tests.common.devices.base import AnsibleHostBase
logger = logging.getLogger(__name__)
def _raise_err(msg):
logger.error(msg)
raise Exception(msg)
class EosHost(AnsibleHostBase):
"""
@summary: Class for Eos switch
For run... | 0.451206 | 0.131452 |
import requests
from typing import List
from bs4 import BeautifulSoup
from src.lyrics.entity import Lyrics
class LyricsSearcher:
def __init__(self, albums_searcher, track_searcher, configurations):
self.albums_searcher = albums_searcher
self.track_searcher = track_searcher
self.__genius... | src/lyrics/searchers/lyrics_searcher.py | import requests
from typing import List
from bs4 import BeautifulSoup
from src.lyrics.entity import Lyrics
class LyricsSearcher:
def __init__(self, albums_searcher, track_searcher, configurations):
self.albums_searcher = albums_searcher
self.track_searcher = track_searcher
self.__genius... | 0.687735 | 0.083965 |
"""Generated protocol buffer code."""
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
# @@protoc_insertion_point(imports)
_sym_db = _symbol_databas... | ml2/tools/nuxmv/nuxmv_pb2.py | """Generated protocol buffer code."""
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
# @@protoc_insertion_point(imports)
_sym_db = _symbol_databas... | 0.36693 | 0.077413 |
import os
from requests_cache.backends.sqlite import DbDict, DbPickleDict
class BaseCustomDictTestCase(object):
dict_class = DbDict
pickled_dict_class = DbPickleDict
NAMESPACE = 'requests-cache-temporary-db-test-will-be-deleted'
TABLES = ['table%s' % i for i in range(5)]
def tearDown(self):
... | tests/test_custom_dict.py | import os
from requests_cache.backends.sqlite import DbDict, DbPickleDict
class BaseCustomDictTestCase(object):
dict_class = DbDict
pickled_dict_class = DbPickleDict
NAMESPACE = 'requests-cache-temporary-db-test-will-be-deleted'
TABLES = ['table%s' % i for i in range(5)]
def tearDown(self):
... | 0.278061 | 0.281198 |
class OptionalFeatures(object):
def __init__(self, conn, scenario_id):
"""
:param cursor:
:param scenario_id:
"""
of_column_names = [
n for n in get_scenario_table_columns(conn=conn)
if n.startswith("of_")
]
for of in of_column_names:... | gridpath/auxiliary/scenario_chars.py | class OptionalFeatures(object):
def __init__(self, conn, scenario_id):
"""
:param cursor:
:param scenario_id:
"""
of_column_names = [
n for n in get_scenario_table_columns(conn=conn)
if n.startswith("of_")
]
for of in of_column_names:... | 0.639286 | 0.345381 |
from io import BytesIO
import sys
import os
import zipfile
import argparse
import subprocess
import requests
import xml.etree.ElementTree as etree
def request_data(root, tile_id, output_folder, verbose=False):
namespaces = {"xmlns": "http://www.w3.org/2005/Atom",
"xmlns:georss": "http://www.geor... | scripts/ahn2_download/ahn2_downloader.py | from io import BytesIO
import sys
import os
import zipfile
import argparse
import subprocess
import requests
import xml.etree.ElementTree as etree
def request_data(root, tile_id, output_folder, verbose=False):
namespaces = {"xmlns": "http://www.w3.org/2005/Atom",
"xmlns:georss": "http://www.geor... | 0.345216 | 0.132066 |
from nltk.stem.porter import PorterStemmer
import os
def __stem_Tokens(words):
porter_stemmer = PorterStemmer()
return [porter_stemmer.stem(x) for x in words.split(" ")]
def same_pre_post(tokens1, tokens2):
if tokens1[0] == tokens2[0] or tokens1[-1] == tokens2[-1]:
return True
return False
... | SENET/result/mergeRQ1.1ANDRQ1.2BySelectNonHeuristic(OriginVerisionIncluded)/not_filter_result/filter_result.py | from nltk.stem.porter import PorterStemmer
import os
def __stem_Tokens(words):
porter_stemmer = PorterStemmer()
return [porter_stemmer.stem(x) for x in words.split(" ")]
def same_pre_post(tokens1, tokens2):
if tokens1[0] == tokens2[0] or tokens1[-1] == tokens2[-1]:
return True
return False
... | 0.448909 | 0.275635 |
from app.extensions.redis.redis_utils import redis_db
from app.extensions.redis.redis_operation import set_multi_hash_in_redis
from app.extensions.redis.redis_operation import set_single_hash_in_redis
from app.extensions.redis.redis_operation import update_single_hash_in_redis
from app.extensions.redis.redis_operation... | echecs_hall/app/data_bridge/mj_hall_bridge.py |
from app.extensions.redis.redis_utils import redis_db
from app.extensions.redis.redis_operation import set_multi_hash_in_redis
from app.extensions.redis.redis_operation import set_single_hash_in_redis
from app.extensions.redis.redis_operation import update_single_hash_in_redis
from app.extensions.redis.redis_operation... | 0.41052 | 0.110807 |
import os
import time
import pytest
import zmq
from jina.excepts import RuntimeFailToStart, RuntimeRunForeverEarlyError
from jina.executors import BaseExecutor
from jina.parsers import set_gateway_parser, set_pea_parser
from jina.peapods import Pea
from jina.peapods.runtimes.zmq.zed import ZEDRuntime
from jina.types.... | tests/unit/peapods/peas/test_pea.py | import os
import time
import pytest
import zmq
from jina.excepts import RuntimeFailToStart, RuntimeRunForeverEarlyError
from jina.executors import BaseExecutor
from jina.parsers import set_gateway_parser, set_pea_parser
from jina.peapods import Pea
from jina.peapods.runtimes.zmq.zed import ZEDRuntime
from jina.types.... | 0.481698 | 0.190329 |
import sys, time, array
import png
import weave
from weave.base_info import custom_info
import numpy as np
from zope.interface import implements
from twisted.internet import defer, reactor
from twisted.internet.interfaces import IPushProducer
import asynqueue
from asynqueue.threads import Consumerator
from mcmandel... | mcmandelbrot/valuer.py | import sys, time, array
import png
import weave
from weave.base_info import custom_info
import numpy as np
from zope.interface import implements
from twisted.internet import defer, reactor
from twisted.internet.interfaces import IPushProducer
import asynqueue
from asynqueue.threads import Consumerator
from mcmandel... | 0.648244 | 0.421135 |
from pathlib import Path
class Handheld:
def __init__(self, instruction_file):
self.accumulator = 0
# parse to function eval format
self.instructions = [(inst.split()[0], inst.split()[1]) for inst in Path(input_file).read_text().splitlines()]
self.instruction_counter = [0] ... | 2020/day8/solve.py | from pathlib import Path
class Handheld:
def __init__(self, instruction_file):
self.accumulator = 0
# parse to function eval format
self.instructions = [(inst.split()[0], inst.split()[1]) for inst in Path(input_file).read_text().splitlines()]
self.instruction_counter = [0] ... | 0.424173 | 0.278186 |
import tempfile
import unittest
import mock
import yaml
from py import release
class ReleaseTest(unittest.TestCase):
@mock.patch("py.release.os.makedirs")
@mock.patch("py.release.os.symlink")
@mock.patch("py.release.util.install_go_deps")
@mock.patch("py.release.util.clone_repo")
@mock.patch("py.release.b... | py/release_test.py | import tempfile
import unittest
import mock
import yaml
from py import release
class ReleaseTest(unittest.TestCase):
@mock.patch("py.release.os.makedirs")
@mock.patch("py.release.os.symlink")
@mock.patch("py.release.util.install_go_deps")
@mock.patch("py.release.util.clone_repo")
@mock.patch("py.release.b... | 0.44553 | 0.241389 |
# coding=utf-8
import time
from datetime import datetime
from django.db import models
from climate.models import TempHumidValue
from plugins.arduino.models import Arduino, set_command
from events.utils import event_setter
MODEL = 'SensorDS18D20'
LOCATION_TYPES = (
('inside', 'В помещении'),
('outside', 'На ... | Servus/plugins/arduino_ds18d20/models.py | # coding=utf-8
import time
from datetime import datetime
from django.db import models
from climate.models import TempHumidValue
from plugins.arduino.models import Arduino, set_command
from events.utils import event_setter
MODEL = 'SensorDS18D20'
LOCATION_TYPES = (
('inside', 'В помещении'),
('outside', 'На ... | 0.309232 | 0.199522 |
from pyspark.context import SparkContext
from pyspark.sql.dataframe import DataFrame
from pyspark.rdd import RDD
from pyspark.sql import SparkSession
from h2o.frame import H2OFrame
from pysparkling.initializer import Initializer
from pysparkling.conf import H2OConf
import h2o
from pysparkling.conversions import FrameCo... | py/pysparkling/context.py | from pyspark.context import SparkContext
from pyspark.sql.dataframe import DataFrame
from pyspark.rdd import RDD
from pyspark.sql import SparkSession
from h2o.frame import H2OFrame
from pysparkling.initializer import Initializer
from pysparkling.conf import H2OConf
import h2o
from pysparkling.conversions import FrameCo... | 0.596081 | 0.267242 |
from __future__ import absolute_import
from __future__ import division
from __future__ import print_function
import argparse
import numpy as np
import tensorflow as tf
from Model import Model
class Classifier(object):
def __init__(self):
self.graph = None
self.output_operation = None
se... | classifier/Classifier.py | from __future__ import absolute_import
from __future__ import division
from __future__ import print_function
import argparse
import numpy as np
import tensorflow as tf
from Model import Model
class Classifier(object):
def __init__(self):
self.graph = None
self.output_operation = None
se... | 0.641198 | 0.105487 |
from datetime import datetime as _pydatetime, \
tzinfo as _pytzinfo
import re
class datetime(_pydatetime):
"""Customized datetime class with ISO format parsing."""
_reiso = re.compile('(?P<year>[0-9]{4})'
'-(?P<month>[0-9]{1,2})'
'-(?P<day>[0-9... | tmdb3/tmdb_auth.py |
from datetime import datetime as _pydatetime, \
tzinfo as _pytzinfo
import re
class datetime(_pydatetime):
"""Customized datetime class with ISO format parsing."""
_reiso = re.compile('(?P<year>[0-9]{4})'
'-(?P<month>[0-9]{1,2})'
'-(?P<day>[0-9... | 0.511229 | 0.183064 |
import random
from pathlib import Path
import pyglet
TILE_SIZE = 64
TILES_DIRECTORY = Path('static/snake-tiles')
class State:
def __init__(self):
self.snake = [(0, 0), (1, 0)]
self.snake_direction = 0, 1
self.width = 10
self.height = 10
self.food = []
self.add_food... | lessons/projects/snake/snake_game.py | import random
from pathlib import Path
import pyglet
TILE_SIZE = 64
TILES_DIRECTORY = Path('static/snake-tiles')
class State:
def __init__(self):
self.snake = [(0, 0), (1, 0)]
self.snake_direction = 0, 1
self.width = 10
self.height = 10
self.food = []
self.add_food... | 0.31542 | 0.192407 |
import os
import glob
import re
import sys
import socket
import couchdb
import logging
import argparse
import ConfigParser
import yaml
import json
import distance
import operator
CONFIG = {}
logger = logging.getLogger(__name__)
def associete_samples(samples_name, mode):
couch = setupServer(CONFIG)
p... | userName2NGIname_finder.py | import os
import glob
import re
import sys
import socket
import couchdb
import logging
import argparse
import ConfigParser
import yaml
import json
import distance
import operator
CONFIG = {}
logger = logging.getLogger(__name__)
def associete_samples(samples_name, mode):
couch = setupServer(CONFIG)
p... | 0.158532 | 0.061368 |
import copy
import json
default_config = """{
"listeners": [
{"iface": "127.0.0.1", "port": 8080}
],
"proxy": {"use_proxy": false, "host": "", "port": 0, "is_socks": false}
}"""
class ProxyConfig:
def __init__(self):
self._listeners = [('127.0.0.1', 8080, None)]
self._pro... | pappyproxy/config.py | import copy
import json
default_config = """{
"listeners": [
{"iface": "127.0.0.1", "port": 8080}
],
"proxy": {"use_proxy": false, "host": "", "port": 0, "is_socks": false}
}"""
class ProxyConfig:
def __init__(self):
self._listeners = [('127.0.0.1', 8080, None)]
self._pro... | 0.411584 | 0.07373 |
import torch
import torch.nn as nn
from torch.autograd import Variable
import torch.nn.functional as F
import numpy as np
class Attn(nn.Module):
def __init__(self, method, hidden_size):
super(Attn, self).__init__()
self.use_cuda = torch.cuda.is_available()
self.method = method
sel... | models.py | import torch
import torch.nn as nn
from torch.autograd import Variable
import torch.nn.functional as F
import numpy as np
class Attn(nn.Module):
def __init__(self, method, hidden_size):
super(Attn, self).__init__()
self.use_cuda = torch.cuda.is_available()
self.method = method
sel... | 0.931641 | 0.461077 |
from typing import Any, Optional, Sequence
from websockets.datastructures import Headers, HeadersLike
from websockets.exceptions import (
InvalidHeader,
InvalidStatusCode,
NegotiationError,
RedirectHandshake,
)
from websockets.extensions import ClientExtensionFactory
from websockets.headers i... | ws_auth/protocol.py | from typing import Any, Optional, Sequence
from websockets.datastructures import Headers, HeadersLike
from websockets.exceptions import (
InvalidHeader,
InvalidStatusCode,
NegotiationError,
RedirectHandshake,
)
from websockets.extensions import ClientExtensionFactory
from websockets.headers i... | 0.843331 | 0.053231 |
# Python modules
from threading import Lock
import operator
# Third-party modules
from django.db import models
import cachetools
# NOC modules
from noc.config import config
from noc.core.model.base import NOCModel
from noc.core.model.decorator import on_init
from noc.main.models.notificationgroup import Notification... | dns/models/dnszoneprofile.py |
# Python modules
from threading import Lock
import operator
# Third-party modules
from django.db import models
import cachetools
# NOC modules
from noc.config import config
from noc.core.model.base import NOCModel
from noc.core.model.decorator import on_init
from noc.main.models.notificationgroup import Notification... | 0.749912 | 0.123709 |
from django.shortcuts import render, redirect
from django.contrib.auth.decorators import permission_required
from django.http import JsonResponse
from hknweb.coursesemester.models import Course
from .models import (
CoursePreference,
Slot,
Tutor,
TutorCourse,
TimeSlot,
TimeSlotPreference,
Ro... | hknweb/tutoring/views.py | from django.shortcuts import render, redirect
from django.contrib.auth.decorators import permission_required
from django.http import JsonResponse
from hknweb.coursesemester.models import Course
from .models import (
CoursePreference,
Slot,
Tutor,
TutorCourse,
TimeSlot,
TimeSlotPreference,
Ro... | 0.262936 | 0.287318 |
from __future__ import print_function
import datetime
import subprocess
import sys
import os
import numpy as np
import pytz
import pygrib
from pyiem.plot import MapPlot
import pyiem.reference as ref
from pyiem.util import utc
HOURS = [
36, 18, 18, 18, 18, 18,
36, 18, 18, 18, 18, 18,
36, 18, 18, 18, 18, 18,... | scripts/hrrr/plot_ref.py | from __future__ import print_function
import datetime
import subprocess
import sys
import os
import numpy as np
import pytz
import pygrib
from pyiem.plot import MapPlot
import pyiem.reference as ref
from pyiem.util import utc
HOURS = [
36, 18, 18, 18, 18, 18,
36, 18, 18, 18, 18, 18,
36, 18, 18, 18, 18, 18,... | 0.329392 | 0.237653 |
from __future__ import print_function
import argparse
import os
import webbrowser
from shutil import copyfile
from urllib import pathname2url
import pdfkit
from os.path import join, dirname
from rope.base.pyobjectsdef import _AssignVisitor
p = argparse.ArgumentParser()
p.add_argument('--root', help="The root folde... | scripts/i12-eval/report.py | from __future__ import print_function
import argparse
import os
import webbrowser
from shutil import copyfile
from urllib import pathname2url
import pdfkit
from os.path import join, dirname
from rope.base.pyobjectsdef import _AssignVisitor
p = argparse.ArgumentParser()
p.add_argument('--root', help="The root folde... | 0.163646 | 0.119511 |
import json, time, zlib
from sims4.gsi.schema import GsiSchema, CLIENT_GSI_ARCHIVE_UID_FIX
from uid import UniqueIdGenerator
import sims4.gsi.dispatcher, sims4.log, sims4.reload, sims4.zone_utils
logger = sims4.log.Logger('GSI')
with sims4.reload.protected(globals()):
archive_data = {}
archive_schemas = {}
... | Scripts/core/sims4/gsi/archive.py | import json, time, zlib
from sims4.gsi.schema import GsiSchema, CLIENT_GSI_ARCHIVE_UID_FIX
from uid import UniqueIdGenerator
import sims4.gsi.dispatcher, sims4.log, sims4.reload, sims4.zone_utils
logger = sims4.log.Logger('GSI')
with sims4.reload.protected(globals()):
archive_data = {}
archive_schemas = {}
... | 0.472927 | 0.112089 |
from __future__ import absolute_import
from cdsl.formats import InstructionFormat
from cdsl.operands import VALUE, VARIABLE_ARGS
from .immediates import imm64, uimm8, uimm32, ieee32, ieee64, offset32
from .immediates import boolean, intcc, floatcc, memflags, regunit, trapcode
from . import entities
from .entities impor... | cranelift-codegen/meta-python/base/formats.py | from __future__ import absolute_import
from cdsl.formats import InstructionFormat
from cdsl.operands import VALUE, VARIABLE_ARGS
from .immediates import imm64, uimm8, uimm32, ieee32, ieee64, offset32
from .immediates import boolean, intcc, floatcc, memflags, regunit, trapcode
from . import entities
from .entities impor... | 0.676727 | 0.141815 |
from __future__ import absolute_import
from __future__ import division
from __future__ import print_function
from absl.testing import parameterized
import numpy as np
import tensorflow as tf # pylint: disable=g-explicit-tensorflow-version-import
from tf_agents.keras_layers import dynamic_unroll_layer
from tensorflo... | tf_agents/keras_layers/dynamic_unroll_layer_test.py | from __future__ import absolute_import
from __future__ import division
from __future__ import print_function
from absl.testing import parameterized
import numpy as np
import tensorflow as tf # pylint: disable=g-explicit-tensorflow-version-import
from tf_agents.keras_layers import dynamic_unroll_layer
from tensorflo... | 0.857664 | 0.370539 |
from __future__ import annotations
from abc import abstractmethod, ABC
import typing
from opentrons import types
from opentrons.hardware_control.dev_types import PipetteDict
from opentrons.protocols.api_support.util import Clearances, PlungerSpeeds, \
FlowRates
from opentrons.protocols.implementations.well import... | api/src/opentrons/protocols/implementations/interfaces/instrument_context.py | from __future__ import annotations
from abc import abstractmethod, ABC
import typing
from opentrons import types
from opentrons.hardware_control.dev_types import PipetteDict
from opentrons.protocols.api_support.util import Clearances, PlungerSpeeds, \
FlowRates
from opentrons.protocols.implementations.well import... | 0.871939 | 0.439266 |
from pathlib import Path
from astrality.actions import ImportContextAction
from astrality.context import Context
def test_null_object_pattern():
"""Test initializing action with no behaviour."""
import_context_action = ImportContextAction(
options={},
directory=Path('/'),
replacer=la... | astrality/tests/actions/test_import_context_action.py |
from pathlib import Path
from astrality.actions import ImportContextAction
from astrality.context import Context
def test_null_object_pattern():
"""Test initializing action with no behaviour."""
import_context_action = ImportContextAction(
options={},
directory=Path('/'),
replacer=la... | 0.8709 | 0.345436 |
from knack.arguments import ArgumentsContext
from knack.commands import CLICommandsLoader, CommandGroup
class SuperBenchCommandsLoader(CLICommandsLoader):
"""SuperBench CLI commands loader."""
def load_command_table(self, args):
"""Load commands into the command table.
Args:
args ... | superbench/cli/_commands.py | from knack.arguments import ArgumentsContext
from knack.commands import CLICommandsLoader, CommandGroup
class SuperBenchCommandsLoader(CLICommandsLoader):
"""SuperBench CLI commands loader."""
def load_command_table(self, args):
"""Load commands into the command table.
Args:
args ... | 0.873134 | 0.095856 |
point = {
"type": "Point",
"coordinates": [100.0, 0.0]
}
linestring = {
"type": "LineString",
"coordinates": [
[100.0, 0.0],
[101.0, 1.0]
]
}
polygon = {
"type": "Polygon",
"coordinates": [
[
[100.0, 0.0],
[101.0, 0.0],
[101.0, 1.... | stac_api_validator/geometries.py | point = {
"type": "Point",
"coordinates": [100.0, 0.0]
}
linestring = {
"type": "LineString",
"coordinates": [
[100.0, 0.0],
[101.0, 1.0]
]
}
polygon = {
"type": "Polygon",
"coordinates": [
[
[100.0, 0.0],
[101.0, 0.0],
[101.0, 1.... | 0.553264 | 0.698728 |
import logging
import os
import subprocess
import sys
import impersonate
import proc_util
import uac
class UpdaterTestRPCHandler():
def echo(self, message):
"""Test method to check if server is reachable."""
return message
def RunAsSystem(self, command, env=None, cwd=None, timeout=30):
"""Runs the ... | chrome/updater/test/service/win/rpc_handler.py |
import logging
import os
import subprocess
import sys
import impersonate
import proc_util
import uac
class UpdaterTestRPCHandler():
def echo(self, message):
"""Test method to check if server is reachable."""
return message
def RunAsSystem(self, command, env=None, cwd=None, timeout=30):
"""Runs the ... | 0.52902 | 0.110279 |
from pprint import pformat
from six import iteritems
import re
class WorkflowTaskMeta(object):
"""
NOTE: This class is auto generated by the swagger code generator program.
Do not edit the class manually.
"""
"""
Attributes:
swagger_types (dict): The key is attribute name
... | intersight/models/workflow_task_meta.py | from pprint import pformat
from six import iteritems
import re
class WorkflowTaskMeta(object):
"""
NOTE: This class is auto generated by the swagger code generator program.
Do not edit the class manually.
"""
"""
Attributes:
swagger_types (dict): The key is attribute name
... | 0.489015 | 0.099121 |
import matplotlib.pyplot as plt
import numpy as np
from scipy.integrate import solve_ivp
import csv
def red_blue_ode(t, p):
r, b, rt, bt = p
dp = [0, 0, 0, 0]
lambda_a = 1.0
lambda_t = 1.0
p_t = 0.5
p_c = 0.5
k = 10.0
flag_r_0 = 1.0 if r > 0 else 0.0
flag_b_0 = 1.0 if b > 0 else 0.... | plotscript/plot_rb_files.py | import matplotlib.pyplot as plt
import numpy as np
from scipy.integrate import solve_ivp
import csv
def red_blue_ode(t, p):
r, b, rt, bt = p
dp = [0, 0, 0, 0]
lambda_a = 1.0
lambda_t = 1.0
p_t = 0.5
p_c = 0.5
k = 10.0
flag_r_0 = 1.0 if r > 0 else 0.0
flag_b_0 = 1.0 if b > 0 else 0.... | 0.314156 | 0.477371 |
import keras
from keras.models import Sequential, Model
from keras.layers import Activation, Merge, Reshape
from keras.layers import Input, Embedding, Dense, dot
from keras.layers.core import Lambda
from keras import optimizers
from keras import backend as K
import numpy as np
import random
import utils.process as pro... | keras_item2vec.py | import keras
from keras.models import Sequential, Model
from keras.layers import Activation, Merge, Reshape
from keras.layers import Input, Embedding, Dense, dot
from keras.layers.core import Lambda
from keras import optimizers
from keras import backend as K
import numpy as np
import random
import utils.process as pro... | 0.425247 | 0.271336 |
from __future__ import absolute_import
from __future__ import division
from __future__ import print_function
from __future__ import unicode_literals
import functools
import json
import logging
from datetime import datetime
import parsedatetime
from dateutil.parser import parse
from flask import flash, Markup
from fla... | caravel/utils.py | from __future__ import absolute_import
from __future__ import division
from __future__ import print_function
from __future__ import unicode_literals
import functools
import json
import logging
from datetime import datetime
import parsedatetime
from dateutil.parser import parse
from flask import flash, Markup
from fla... | 0.728169 | 0.157752 |
from sklearn import metrics
import numpy as np
import matplotlib.pyplot as plt
import matplotlib
import matplotlib.colors as colors
import itertools
import pandas as pd
from imblearn.metrics import sensitivity_specificity_support
import os
def multiclass_predict_1d_to_nd(y_, unique_labels):
if(len(np.unique(y_)) ... | pyaiutils/__init__.py | from sklearn import metrics
import numpy as np
import matplotlib.pyplot as plt
import matplotlib
import matplotlib.colors as colors
import itertools
import pandas as pd
from imblearn.metrics import sensitivity_specificity_support
import os
def multiclass_predict_1d_to_nd(y_, unique_labels):
if(len(np.unique(y_)) ... | 0.518546 | 0.368264 |
from aliyunsdkcore.request import RpcRequest
from aliyunsdkmse.endpoint import endpoint_data
class UpdateConfigRequest(RpcRequest):
def __init__(self):
RpcRequest.__init__(self, 'mse', '2019-05-31', 'UpdateConfig')
self.set_method('POST')
if hasattr(self, "endpoint_map"):
setattr(self, "endpoint_map", e... | aliyun-python-sdk-mse/aliyunsdkmse/request/v20190531/UpdateConfigRequest.py |
from aliyunsdkcore.request import RpcRequest
from aliyunsdkmse.endpoint import endpoint_data
class UpdateConfigRequest(RpcRequest):
def __init__(self):
RpcRequest.__init__(self, 'mse', '2019-05-31', 'UpdateConfig')
self.set_method('POST')
if hasattr(self, "endpoint_map"):
setattr(self, "endpoint_map", e... | 0.490724 | 0.050588 |
from pathlib import Path
from pymongo import MongoClient
import os
import csv
client = MongoClient("localhost", 27017)
cursor = client["dvdrental"]["customer"].aggregate(
[
{
u"$project": {
u"_id": 0,
u"customer": u"$$ROOT"
}
},
{
... | 1/queries/4.py | from pathlib import Path
from pymongo import MongoClient
import os
import csv
client = MongoClient("localhost", 27017)
cursor = client["dvdrental"]["customer"].aggregate(
[
{
u"$project": {
u"_id": 0,
u"customer": u"$$ROOT"
}
},
{
... | 0.282394 | 0.251429 |
import json
import os
import pickle
import warnings
from operator import itemgetter
from pathlib import Path
from timeit import default_timer as timer
import matplotlib.pyplot as plt
import networkx as nx
import numpy as np
import pandas as pd
import seaborn as sns
from joblib import Parallel, delayed
from joblib.para... | notebooks/49.0-BDP-divisive-clust-hsbm.py | import json
import os
import pickle
import warnings
from operator import itemgetter
from pathlib import Path
from timeit import default_timer as timer
import matplotlib.pyplot as plt
import networkx as nx
import numpy as np
import pandas as pd
import seaborn as sns
from joblib import Parallel, delayed
from joblib.para... | 0.532182 | 0.26944 |
import clr
import clr
# Copyright (c) 2011 AlphaSierraPapa for the SharpDevelop Team
#
# Permission is hereby granted, free of charge, to any person obtaining a copy of this
# software and associated documentation files (the "Software"), to deal in the Software
# without restriction, including without limitation ... | ILSpy.ConvertedToPython/SearchPane.py | import clr
import clr
# Copyright (c) 2011 AlphaSierraPapa for the SharpDevelop Team
#
# Permission is hereby granted, free of charge, to any person obtaining a copy of this
# software and associated documentation files (the "Software"), to deal in the Software
# without restriction, including without limitation ... | 0.41052 | 0.058831 |
import pandas as pd
# Carga del dataset completo. Elimino clasificador y otros atributos que no
# son necesarios
spy_full = pd.read_csv("SPYV3.csv", sep=',')
spy_full = spy_full.drop(['FECHA','OPEN', 'MAX', 'MIN', 'CLOSE','CLASIFICADOR',
... | PCA_2.py | import pandas as pd
# Carga del dataset completo. Elimino clasificador y otros atributos que no
# son necesarios
spy_full = pd.read_csv("SPYV3.csv", sep=',')
spy_full = spy_full.drop(['FECHA','OPEN', 'MAX', 'MIN', 'CLOSE','CLASIFICADOR',
... | 0.325842 | 0.26917 |
import mox
import testtools
from oslo.config import cfg
from rack import exception
from rack import service
from rack import test
from rack.tests import utils
from rack import wsgi
test_service_opts = [
cfg.StrOpt("fake_manager",
default="rack.tests.test_service.FakeManager",
help=... | rack/tests/test_service.py |
import mox
import testtools
from oslo.config import cfg
from rack import exception
from rack import service
from rack import test
from rack.tests import utils
from rack import wsgi
test_service_opts = [
cfg.StrOpt("fake_manager",
default="rack.tests.test_service.FakeManager",
help=... | 0.47098 | 0.332554 |
import email
import os
import shutil
from digestparser.objects import Digest, Image
from provider.article import article
def create_folder(folder):
if not os.path.exists(folder):
os.makedirs(folder)
def delete_folder(folder, recursively=False):
if recursively:
shutil.rmtree(folder)
else:... | tests/activity/helpers.py | import email
import os
import shutil
from digestparser.objects import Digest, Image
from provider.article import article
def create_folder(folder):
if not os.path.exists(folder):
os.makedirs(folder)
def delete_folder(folder, recursively=False):
if recursively:
shutil.rmtree(folder)
else:... | 0.240329 | 0.099514 |
from torch.nn.modules.loss import _Loss
from package_core.losses import VariationLoss, L1Loss, PerceptualLoss
from package_core.image_proc import *
# L2 loss
def MSE(para):
return nn.MSELoss()
# L1 loss
def L1(para):
return nn.L1Loss()
def MaskedL1(para):
return L1Loss()
# Varianc... | train/loss.py | from torch.nn.modules.loss import _Loss
from package_core.losses import VariationLoss, L1Loss, PerceptualLoss
from package_core.image_proc import *
# L2 loss
def MSE(para):
return nn.MSELoss()
# L1 loss
def L1(para):
return nn.L1Loss()
def MaskedL1(para):
return L1Loss()
# Varianc... | 0.873701 | 0.492127 |
from ui.pfdview import *
from data.parameter import *
import math
class AltitudeCalibrationView(Dialog):
newSLP = None
surfaceWidth = 300
surfaceHeight = 200
def __init__(self):
Dialog.__init__(self,self.surfaceWidth,self.surfaceHeight)
size = 40
up = '\u2191' # Unicode up ar... | ui/dialogs/baroset.py | from ui.pfdview import *
from data.parameter import *
import math
class AltitudeCalibrationView(Dialog):
newSLP = None
surfaceWidth = 300
surfaceHeight = 200
def __init__(self):
Dialog.__init__(self,self.surfaceWidth,self.surfaceHeight)
size = 40
up = '\u2191' # Unicode up ar... | 0.410756 | 0.119152 |
import time
import numpy as np
import matplotlib
import matplotlib.pyplot as plt
from sklearn import svm
from sklearn.datasets import make_moons, make_blobs
from sklearn.covariance import EllipticEnvelope
from sklearn.ensemble import IsolationForest
from sklearn.neighbors import LocalOutlierFactor
matplotlib.rcParam... | _unittests/ut_testing/data/plot_anomaly_comparison.py | import time
import numpy as np
import matplotlib
import matplotlib.pyplot as plt
from sklearn import svm
from sklearn.datasets import make_moons, make_blobs
from sklearn.covariance import EllipticEnvelope
from sklearn.ensemble import IsolationForest
from sklearn.neighbors import LocalOutlierFactor
matplotlib.rcParam... | 0.78695 | 0.623033 |
# Lint as: python3
"""LintReport implementation that outputs to the terminal."""
import logging
import os
import sys
import textwrap
from typing import Optional
import blessings
from gcp_doctor import config, lint, models
OUTPUT_WIDTH = 68
def _emoji_wrap(char):
if os.getenv('CLOUD_SHELL'):
# emoji not dis... | gcp_doctor/lint/report_terminal.py |
# Lint as: python3
"""LintReport implementation that outputs to the terminal."""
import logging
import os
import sys
import textwrap
from typing import Optional
import blessings
from gcp_doctor import config, lint, models
OUTPUT_WIDTH = 68
def _emoji_wrap(char):
if os.getenv('CLOUD_SHELL'):
# emoji not dis... | 0.67104 | 0.099689 |
import sys
import argparse
def reduce(txt_char, key_char, charset, binop):
letter = binop(charset.index(txt_char), charset.index(key_char))
letter %= len(charset)
return charset[letter]
def opcrypt(txt, key, charset, binop):
return "".join(reduce(txt_char=i, key_char=j, charset=charset, binop=binop... | otp.py | import sys
import argparse
def reduce(txt_char, key_char, charset, binop):
letter = binop(charset.index(txt_char), charset.index(key_char))
letter %= len(charset)
return charset[letter]
def opcrypt(txt, key, charset, binop):
return "".join(reduce(txt_char=i, key_char=j, charset=charset, binop=binop... | 0.305386 | 0.115187 |
import rospy
import rospkg
import cv2
import tf
import io
import os
import numpy as np
import json
from sensor_msgs.msg import Image
from cv_bridge import CvBridge, CvBridgeError
class PushestDatasetJsonWriter:
def __init__(self):
self.tf_listener = tf.TransformListener()
self.bridge = CvBridg... | data_collection/digit_pushing/src/PushestDatasetJsonWriter.py |
import rospy
import rospkg
import cv2
import tf
import io
import os
import numpy as np
import json
from sensor_msgs.msg import Image
from cv_bridge import CvBridge, CvBridgeError
class PushestDatasetJsonWriter:
def __init__(self):
self.tf_listener = tf.TransformListener()
self.bridge = CvBridg... | 0.491944 | 0.176405 |
import sys, getopt
import glob, os
import numpy as np
from fastq_reader import Fastq_Reader
help_message = 'usage example: python intermediate_read_clusters.py -r 1 -i /project/home/hashed_reads/ -o /project/home/cluster_vectors/'
if __name__ == "__main__":
try:
opts, args = getopt.getopt(sys.argv[1:],'hr:i:o:',[... | misc/intermediate_read_clusters.py |
import sys, getopt
import glob, os
import numpy as np
from fastq_reader import Fastq_Reader
help_message = 'usage example: python intermediate_read_clusters.py -r 1 -i /project/home/hashed_reads/ -o /project/home/cluster_vectors/'
if __name__ == "__main__":
try:
opts, args = getopt.getopt(sys.argv[1:],'hr:i:o:',[... | 0.096219 | 0.07521 |
from enum import Enum
import logging
from ..services import game_service, game_message_service, rcon_service, status_service
from ..exceptions import InvalidOperationException
from ..services.status_service import Status
IDLE_TRACKERS = {}
PREVIOUS_IDLE_STATUSES = {}
async def auto_shutdown_loop(bot):
logging.i... | bot/services/inactivity_service.py | from enum import Enum
import logging
from ..services import game_service, game_message_service, rcon_service, status_service
from ..exceptions import InvalidOperationException
from ..services.status_service import Status
IDLE_TRACKERS = {}
PREVIOUS_IDLE_STATUSES = {}
async def auto_shutdown_loop(bot):
logging.i... | 0.387574 | 0.070816 |
from headers.static_values import *
from worker import *
from utils import *
import requests
class Forwarded():
def __init__(self, destination):
self.destination = destination
self.mime_types = MimeTypes.get_mime_list()
self.payloads = Payloads.get_payload_list(Config... | headers/forwarded.py | from headers.static_values import *
from worker import *
from utils import *
import requests
class Forwarded():
def __init__(self, destination):
self.destination = destination
self.mime_types = MimeTypes.get_mime_list()
self.payloads = Payloads.get_payload_list(Config... | 0.427516 | 0.133049 |
from corpus.event import EventManager, EventSeriesManager, EventStorage
from corpus.config import EventDataSourceConfig
from corpus.quality.rating import RatingManager
from corpus.datasources.download import Download
class EventDataSource(object):
'''
a data source for events
'''
def _... | corpus/eventcorpus.py | from corpus.event import EventManager, EventSeriesManager, EventStorage
from corpus.config import EventDataSourceConfig
from corpus.quality.rating import RatingManager
from corpus.datasources.download import Download
class EventDataSource(object):
'''
a data source for events
'''
def _... | 0.374562 | 0.128908 |
import dash
import dash_core_components as dcc
import dash_html_components as html
from dash.dependencies import Input, Output
import altair as alt
import pandas as pd
import pandas as pd
import altair as alt
from vega_datasets import data
import dash_bootstrap_components as dbc
app = dash.Dash(__name__, assets_folder... | app.py | import dash
import dash_core_components as dcc
import dash_html_components as html
from dash.dependencies import Input, Output
import altair as alt
import pandas as pd
import pandas as pd
import altair as alt
from vega_datasets import data
import dash_bootstrap_components as dbc
app = dash.Dash(__name__, assets_folder... | 0.6705 | 0.361362 |
import random
import numpy as np
import cv2
import scipy.ndimage as ndimage
from scipy.interpolate import RegularGridInterpolator
from scipy.ndimage.filters import gaussian_filter
class RandomChoice(object):
"""
choose a random tranform from list an apply
transforms: tranforms to apply
p: probability
... | src/seg_model_utils/augmentations3d.py | import random
import numpy as np
import cv2
import scipy.ndimage as ndimage
from scipy.interpolate import RegularGridInterpolator
from scipy.ndimage.filters import gaussian_filter
class RandomChoice(object):
"""
choose a random tranform from list an apply
transforms: tranforms to apply
p: probability
... | 0.763219 | 0.46794 |
import time
from oslo_log import log as logging
from tempest import clients
from oswin_tempest_plugin import config
from oswin_tempest_plugin.tests import test_base
CONF = config.CONF
LOG = logging.getLogger(__name__)
class ClientManager(clients.Manager):
def __init__(self, *args, **kwargs):
super(Cl... | oswin_tempest_plugin/tests/scenario/test_metrics_collection.py |
import time
from oslo_log import log as logging
from tempest import clients
from oswin_tempest_plugin import config
from oswin_tempest_plugin.tests import test_base
CONF = config.CONF
LOG = logging.getLogger(__name__)
class ClientManager(clients.Manager):
def __init__(self, *args, **kwargs):
super(Cl... | 0.634883 | 0.285476 |
import sys
import tempfile
from antlir.compiler.requires_provides import (
ProvidesSymlink,
RequireDirectory,
RequireFile,
)
from antlir.fs_utils import Path
from antlir.subvol_utils import TempSubvolumes
from ..install_file import InstallFileItem
from ..symlink import SymlinkToDirItem, SymlinkToFileItem... | antlir/compiler/items/tests/test_symlink.py |
import sys
import tempfile
from antlir.compiler.requires_provides import (
ProvidesSymlink,
RequireDirectory,
RequireFile,
)
from antlir.fs_utils import Path
from antlir.subvol_utils import TempSubvolumes
from ..install_file import InstallFileItem
from ..symlink import SymlinkToDirItem, SymlinkToFileItem... | 0.379263 | 0.215846 |
import numpy as np
import pytest
from pyrado.environment_wrappers.observation_velfilter import ObsVelFiltWrapper
from pyrado.environments.pysim.quanser_qube import QQubeSwingUpSim
from pyrado.policies.feed_forward.dummy import IdlePolicy
from pyrado.sampling.rollout import rollout
from pyrado.spaces.singular import S... | Pyrado/tests/environment_wrappers/test_observation_velfilt.py |
import numpy as np
import pytest
from pyrado.environment_wrappers.observation_velfilter import ObsVelFiltWrapper
from pyrado.environments.pysim.quanser_qube import QQubeSwingUpSim
from pyrado.policies.feed_forward.dummy import IdlePolicy
from pyrado.sampling.rollout import rollout
from pyrado.spaces.singular import S... | 0.791015 | 0.636805 |
import json
import copy
import pandas as pd
import spacy
from sklearn.model_selection import train_test_split
class DataSet:
'''Representation of a data set for text classification pipeline
Attributes:
input_: Input dataset if not pre-split in train and test set. This can be a
pandas.DataFrame o... | smapp_text_classifier/data.py | import json
import copy
import pandas as pd
import spacy
from sklearn.model_selection import train_test_split
class DataSet:
'''Representation of a data set for text classification pipeline
Attributes:
input_: Input dataset if not pre-split in train and test set. This can be a
pandas.DataFrame o... | 0.698535 | 0.522994 |
import re
from functools import lru_cache
from io import StringIO
from pathlib import Path
from typing import Any, Set, Tuple
import geopandas as gpd
import pandas as pd
from shapely.geometry import MultiPoint
from shapely.ops import unary_union
from ....data import nm_navaids
from .airspaces import NMAirspaceParser... | traffic/data/eurocontrol/ddr/freeroute.py | import re
from functools import lru_cache
from io import StringIO
from pathlib import Path
from typing import Any, Set, Tuple
import geopandas as gpd
import pandas as pd
from shapely.geometry import MultiPoint
from shapely.ops import unary_union
from ....data import nm_navaids
from .airspaces import NMAirspaceParser... | 0.762114 | 0.413004 |
from flask_socketio import SocketIO
from flask import Flask, render_template, request
from random import random
import threading
from threading import Thread, Event
app = Flask(__name__)
app.config['SECRET_KEY'] = 'secret!'
app.config['DEBUG'] = True
# Turn the flask app into a SocketIO app
socket_io = SocketIO(app, ... | application.py | from flask_socketio import SocketIO
from flask import Flask, render_template, request
from random import random
import threading
from threading import Thread, Event
app = Flask(__name__)
app.config['SECRET_KEY'] = 'secret!'
app.config['DEBUG'] = True
# Turn the flask app into a SocketIO app
socket_io = SocketIO(app, ... | 0.499268 | 0.06389 |
import math
from django import template
from django.utils.safestring import mark_safe
from django.contrib.humanize.templatetags.humanize import intcomma
from django.contrib.staticfiles.storage import staticfiles_storage
from django.utils import timezone
register = template.Library()
@register.simple_tag(takes_cont... | openprescribing/frontend/templatetags/template_extras.py | import math
from django import template
from django.utils.safestring import mark_safe
from django.contrib.humanize.templatetags.humanize import intcomma
from django.contrib.staticfiles.storage import staticfiles_storage
from django.utils import timezone
register = template.Library()
@register.simple_tag(takes_cont... | 0.414306 | 0.239572 |
# # QCM Analysis
# ## Imports
import logging
import numpy as np
import pandas as pd
import matplotlib as mpl
import matplotlib.pyplot as plt
from bric_analysis_libraries import standard_functions as std
# # Analysis
def sauerbrey( freq, f0, density = 2.648, shear = 2.947e11 ):
"""
The Sauerbrey equati... | bric_analysis_libraries/misc/qcm_analysis.py |
# # QCM Analysis
# ## Imports
import logging
import numpy as np
import pandas as pd
import matplotlib as mpl
import matplotlib.pyplot as plt
from bric_analysis_libraries import standard_functions as std
# # Analysis
def sauerbrey( freq, f0, density = 2.648, shear = 2.947e11 ):
"""
The Sauerbrey equati... | 0.785966 | 0.723236 |
from torchvision.datasets import CIFAR100
from torch.utils.data import DataLoader
import torchvision.transforms as transforms
import os.path as pt
import torch
import numpy as np
def ceil(x: float):
return int(np.ceil(x))
class MYCIFAR100(CIFAR100):
""" Reimplements get_item to transform tensor input to pil... | python/fcdd/datasets/outlier_exposure/cifar100.py | from torchvision.datasets import CIFAR100
from torch.utils.data import DataLoader
import torchvision.transforms as transforms
import os.path as pt
import torch
import numpy as np
def ceil(x: float):
return int(np.ceil(x))
class MYCIFAR100(CIFAR100):
""" Reimplements get_item to transform tensor input to pil... | 0.903882 | 0.725089 |
import sys
import math
import pandas as pd
import matplotlib.pyplot as plt
import matplotlib as mpl
import matplotlib
import numpy as np
from random import randint
from matplotlib.backends.backend_pdf import PdfPages
from matplotlib.backends.backend_pdf import PdfPages
from palettable.colorbrewer.sequential import Yl... | TB-scheduler/deprecated/pdp_pipeline.py | import sys
import math
import pandas as pd
import matplotlib.pyplot as plt
import matplotlib as mpl
import matplotlib
import numpy as np
from random import randint
from matplotlib.backends.backend_pdf import PdfPages
from matplotlib.backends.backend_pdf import PdfPages
from palettable.colorbrewer.sequential import Yl... | 0.400984 | 0.422266 |
# C major scale
song1_tempo = 220
song1 = [
["Cn", 2, 1],
["Dn", 2, 1],
["En", 2, 1],
["Fn", 2, 1],
["Gn", 2, 1],
["An", 2, 1],
["Bn", 2, 1],
["Cn", 3, 1],
["Bn", 2, 1],
["An", 2, 1],
["Gn", 2, 1],
["Fn", 2, 1],
["En", 2, 1],
["Dn", 2, 1],
["Cn", 2, 1]
]
# Imperial March
song2_tempo = 104 * 8
song2 = [... | player/python/songs.py |
# C major scale
song1_tempo = 220
song1 = [
["Cn", 2, 1],
["Dn", 2, 1],
["En", 2, 1],
["Fn", 2, 1],
["Gn", 2, 1],
["An", 2, 1],
["Bn", 2, 1],
["Cn", 3, 1],
["Bn", 2, 1],
["An", 2, 1],
["Gn", 2, 1],
["Fn", 2, 1],
["En", 2, 1],
["Dn", 2, 1],
["Cn", 2, 1]
]
# Imperial March
song2_tempo = 104 * 8
song2 = [... | 0.205296 | 0.511534 |
import ipaddress
from django.conf import settings
from django.test import TestCase
from peering.constants import (
BGP_RELATIONSHIP_PRIVATE_PEERING,
COMMUNITY_TYPE_INGRESS,
COMMUNITY_TYPE_EGRESS,
PLATFORM_IOSXR,
PLATFORM_JUNOS,
PLATFORM_NONE,
ROUTING_POLICY_TYPE_EXPORT,
ROUTING_POLICY_... | peering/tests/test_models.py | import ipaddress
from django.conf import settings
from django.test import TestCase
from peering.constants import (
BGP_RELATIONSHIP_PRIVATE_PEERING,
COMMUNITY_TYPE_INGRESS,
COMMUNITY_TYPE_EGRESS,
PLATFORM_IOSXR,
PLATFORM_JUNOS,
PLATFORM_NONE,
ROUTING_POLICY_TYPE_EXPORT,
ROUTING_POLICY_... | 0.602296 | 0.297508 |
import logging
from collections import defaultdict
import matplotlib.pyplot as plt
from tqdm import tqdm
from social_media_buzz.src.constants import ACCURACY, R2, RANK_SIZE
from social_media_buzz.src.data import (
get_candidate_features, prepare_dataset,
show_rank, write_results,
)
from social_media_buzz.src.... | social_media_buzz/src/analysis.py | import logging
from collections import defaultdict
import matplotlib.pyplot as plt
from tqdm import tqdm
from social_media_buzz.src.constants import ACCURACY, R2, RANK_SIZE
from social_media_buzz.src.data import (
get_candidate_features, prepare_dataset,
show_rank, write_results,
)
from social_media_buzz.src.... | 0.738009 | 0.266462 |
from __future__ import annotations
import logging
from datetime import timedelta
from functools import cached_property
from typing import Any
from homeassistant.components.climate.const import PRESET_BOOST, PRESET_NONE
from homeassistant.components.fan import FanEntityDescription, FanEntity, SUPPORT_SET_SPEED, SUPPOR... | custom_components/tion/fan.py | from __future__ import annotations
import logging
from datetime import timedelta
from functools import cached_property
from typing import Any
from homeassistant.components.climate.const import PRESET_BOOST, PRESET_NONE
from homeassistant.components.fan import FanEntityDescription, FanEntity, SUPPORT_SET_SPEED, SUPPOR... | 0.821975 | 0.115736 |
import init_file as variables
import cj_function_lib as cj
from datetime import datetime
bsn_table = cj.extract_table_from_mdb(variables.ProjMDB, "bsn", variables.path + "\\bsn.tmp~")
bsn_params = bsn_table[0].split(",")
now = datetime.now()
DateAndTime = str(now.month) + "/" + str(now.day) + "/" + \
str(now.yea... | workflow_lib/bsn.py | import init_file as variables
import cj_function_lib as cj
from datetime import datetime
bsn_table = cj.extract_table_from_mdb(variables.ProjMDB, "bsn", variables.path + "\\bsn.tmp~")
bsn_params = bsn_table[0].split(",")
now = datetime.now()
DateAndTime = str(now.month) + "/" + str(now.day) + "/" + \
str(now.yea... | 0.147371 | 0.062075 |
from _pytest.pytester import Testdir as TD, LineMatcher
from contextlib import contextmanager
from textwrap import dedent
import subprocess
import tempfile
import asyncio
import socket
import signal
import pytest
import shutil
import sys
import py
import os
this_dir = os.path.dirname(__file__)
@contextmanager
def l... | tests/test_examples.py |
from _pytest.pytester import Testdir as TD, LineMatcher
from contextlib import contextmanager
from textwrap import dedent
import subprocess
import tempfile
import asyncio
import socket
import signal
import pytest
import shutil
import sys
import py
import os
this_dir = os.path.dirname(__file__)
@contextmanager
def l... | 0.440469 | 0.316581 |
from coecms.regrid import esmf_generate_weights, regrid
import argparse
import xarray
import iris
from dask.diagnostics import ProgressBar
def main():
parser = argparse.ArgumentParser(description=__doc__)
parser.add_argument('--start-date', help='ISO-formatted start date')
parser.add_argument('--end-date',... | scripts/um/era_sst.py | from coecms.regrid import esmf_generate_weights, regrid
import argparse
import xarray
import iris
from dask.diagnostics import ProgressBar
def main():
parser = argparse.ArgumentParser(description=__doc__)
parser.add_argument('--start-date', help='ISO-formatted start date')
parser.add_argument('--end-date',... | 0.569972 | 0.16944 |
import io
import unittest
from contextlib import redirect_stdout
import solution
class TestQ(unittest.TestCase):
def test_case_0(self):
text_trap = io.StringIO()
with redirect_stdout(text_trap):
lns = [5, 3, 5]
inputs = [
[16, 12, 4, 2, 5],
... | hackerrank/Data Structures/Print in Reverse/test.py | import io
import unittest
from contextlib import redirect_stdout
import solution
class TestQ(unittest.TestCase):
def test_case_0(self):
text_trap = io.StringIO()
with redirect_stdout(text_trap):
lns = [5, 3, 5]
inputs = [
[16, 12, 4, 2, 5],
... | 0.327453 | 0.263991 |
import classad
import htcondor
import logging
import os
import shutil
import subprocess
import time
from ornithology import *
from pathlib import Path
logger = logging.getLogger(__name__)
logger.setLevel(logging.DEBUG)
@standup
def config_dir(test_dir):
config_dir = test_dir / "condor" / "config.d"
Path(co... | src/condor_tests/test_auth_protocol_token.py |
import classad
import htcondor
import logging
import os
import shutil
import subprocess
import time
from ornithology import *
from pathlib import Path
logger = logging.getLogger(__name__)
logger.setLevel(logging.DEBUG)
@standup
def config_dir(test_dir):
config_dir = test_dir / "condor" / "config.d"
Path(co... | 0.282097 | 0.218878 |
import os
import glob
import sys
import functools
import jsonpickle
from collections import OrderedDict
from Orange.widgets import widget, gui, settings
import Orange.data
from Orange.data.io import FileFormat
from DockerClient import DockerClient
from BwBase import OWBwBWidget, ConnectionDict, BwbGuiElements, getIconN... | biodepot/Jupyter/OWjupyter_sleuth.py | import os
import glob
import sys
import functools
import jsonpickle
from collections import OrderedDict
from Orange.widgets import widget, gui, settings
import Orange.data
from Orange.data.io import FileFormat
from DockerClient import DockerClient
from BwBase import OWBwBWidget, ConnectionDict, BwbGuiElements, getIconN... | 0.158956 | 0.099426 |