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 json
import re
import subprocess
import yaml
import typer
from pathlib import Path
from typing import Optional, Dict, List
from textwrap import dedent
from .console import console
def create_initial_env_specs(
env_name: str, channel: Optional[str] = None, packages: Optional[List[str]] = None
) -> Dict:
... | ezconda/_utils.py | import json
import re
import subprocess
import yaml
import typer
from pathlib import Path
from typing import Optional, Dict, List
from textwrap import dedent
from .console import console
def create_initial_env_specs(
env_name: str, channel: Optional[str] = None, packages: Optional[List[str]] = None
) -> Dict:
... | 0.712432 | 0.162945 |
import torch
from registry import registry
from models.model_base import Model, StandardTransform, StandardNormalization
from mldb.utils import load_model_state_dict
model_params = {
'resnet18_ssl': { 'arch': 'resnet18',
'eval_batch_size': 256,
'img_crop_size': 224,
... | src/models/semi_supervised_facebook.py | import torch
from registry import registry
from models.model_base import Model, StandardTransform, StandardNormalization
from mldb.utils import load_model_state_dict
model_params = {
'resnet18_ssl': { 'arch': 'resnet18',
'eval_batch_size': 256,
'img_crop_size': 224,
... | 0.577376 | 0.349616 |
import b3
from b3Conditions import *
from b3Actions import *
#### HEALTH
class CheckPotionAndConsumeSEQ(b3.Sequence):
def __init__(self):
childList = [hasPotionCondition(),
ConsumePotion()]
super().__init__(childList)
class CheckBuyPotionGoBuySEQ(b3.Sequence):
def __init__... | b3SubTrees.py | import b3
from b3Conditions import *
from b3Actions import *
#### HEALTH
class CheckPotionAndConsumeSEQ(b3.Sequence):
def __init__(self):
childList = [hasPotionCondition(),
ConsumePotion()]
super().__init__(childList)
class CheckBuyPotionGoBuySEQ(b3.Sequence):
def __init__... | 0.423816 | 0.234615 |
from preprocess import *
import os
def test_find_non_unique_ids_0():
"""
Tests the null case, i.e. no repeated ids.
"""
data = np.array([0, 1, 2, 3, 4, 5, 6, 7, 8, 9, 10])
repeated, positions = find_non_unique_ids(data)
assert repeated.shape == (0,)
assert positions.shape == (0,)
re... | tests/test_preprocess.py | from preprocess import *
import os
def test_find_non_unique_ids_0():
"""
Tests the null case, i.e. no repeated ids.
"""
data = np.array([0, 1, 2, 3, 4, 5, 6, 7, 8, 9, 10])
repeated, positions = find_non_unique_ids(data)
assert repeated.shape == (0,)
assert positions.shape == (0,)
re... | 0.719975 | 0.762247 |
import pickle
from keras.layers import Input, LSTM, Embedding, Dense,Dropout,TimeDistributed
from keras.models import Model
from sklearn.model_selection import train_test_split
from model_file import build
class DumbModel:
def __init__(self,vocab_size=10000,num_of_encoder_tokens,num_of_decoder_tokens):
sel... | run/model.py | import pickle
from keras.layers import Input, LSTM, Embedding, Dense,Dropout,TimeDistributed
from keras.models import Model
from sklearn.model_selection import train_test_split
from model_file import build
class DumbModel:
def __init__(self,vocab_size=10000,num_of_encoder_tokens,num_of_decoder_tokens):
sel... | 0.795062 | 0.450178 |
from django.core.management.base import BaseCommand, CommandError
from django.db.models import Q
from django.core.exceptions import MultipleObjectsReturned
from mighty import functions
from mighty.apps import MightyConfig as conf
from mighty.applications.logger import EnableLogger
import datetime, sys, logging, csv, o... | management/__init__.py | from django.core.management.base import BaseCommand, CommandError
from django.db.models import Q
from django.core.exceptions import MultipleObjectsReturned
from mighty import functions
from mighty.apps import MightyConfig as conf
from mighty.applications.logger import EnableLogger
import datetime, sys, logging, csv, o... | 0.373647 | 0.065545 |
import os
import re
from first import first
from paramiko.config import SSHConfig
import pyeapi
__all__ = ['Device']
_if_shorten_find_patterns = [
r'Ethernet(?P<E2>\d+)/1',
r'Ethernet(?P<E1>\d+)',
r'Management(?P<M1>\d+)',
r'Port-Channel(?P<PO>\d+)',
r'Vlan(?P<V>\d+)'
]
_if_shorten_replace_patt... | nrfupytesteos/eos_device.py |
import os
import re
from first import first
from paramiko.config import SSHConfig
import pyeapi
__all__ = ['Device']
_if_shorten_find_patterns = [
r'Ethernet(?P<E2>\d+)/1',
r'Ethernet(?P<E1>\d+)',
r'Management(?P<M1>\d+)',
r'Port-Channel(?P<PO>\d+)',
r'Vlan(?P<V>\d+)'
]
_if_shorten_replace_patt... | 0.466359 | 0.091992 |
import os
from argparse import ArgumentParser
from pathlib import Path
import random
from collections import Counter
from tqdm import tqdm
import gzip
from lxml import etree as et
import pandas as pd
from frdocs.preprocessing.parsing import parse_reg_xml_tree, FrdocResolver
from frdocs.config import data_dir
'''
This... | preprocessing/compile_parsed.py | import os
from argparse import ArgumentParser
from pathlib import Path
import random
from collections import Counter
from tqdm import tqdm
import gzip
from lxml import etree as et
import pandas as pd
from frdocs.preprocessing.parsing import parse_reg_xml_tree, FrdocResolver
from frdocs.config import data_dir
'''
This... | 0.338186 | 0.165323 |
dist_params = dict(backend='nccl')
log_level = 'INFO'
load_from = None
resume_from = None
syncbn = True
data = dict(
videos_per_gpu=4, # total batch size is 8Gpus*4 == 32
workers_per_gpu=4,
train=dict(
type='CtPDataset',
data_source=dict(
type='JsonClsDataSource',
a... | configs/ctp/pretraining_runtime_ucf.py | dist_params = dict(backend='nccl')
log_level = 'INFO'
load_from = None
resume_from = None
syncbn = True
data = dict(
videos_per_gpu=4, # total batch size is 8Gpus*4 == 32
workers_per_gpu=4,
train=dict(
type='CtPDataset',
data_source=dict(
type='JsonClsDataSource',
a... | 0.477798 | 0.212375 |
import settings
import random as rn
def atBat(pitcher, batter):
""" Function to complete an at bat and output result"""
""" return: [out, hit, extra base, runners advance, bb, mss]"""
print('\n')
print('Pitcher: %s' % (settings.cname(pitcher)))
print('Now batting: %s' % (settings.cname(batter)))
... | atbat.py | import settings
import random as rn
def atBat(pitcher, batter):
""" Function to complete an at bat and output result"""
""" return: [out, hit, extra base, runners advance, bb, mss]"""
print('\n')
print('Pitcher: %s' % (settings.cname(pitcher)))
print('Now batting: %s' % (settings.cname(batter)))
... | 0.236428 | 0.318651 |
import os
import requests
import json
from rich import print
from rich.console import Console
import webbrowser
from tqdm import tqdm
def clear():
if os.name == 'nt':
os.system("cls")
else:
os.system("clear")
def strip(x):
return x.strip()
def manually_filter(publications):
con... | explorer.py | import os
import requests
import json
from rich import print
from rich.console import Console
import webbrowser
from tqdm import tqdm
def clear():
if os.name == 'nt':
os.system("cls")
else:
os.system("clear")
def strip(x):
return x.strip()
def manually_filter(publications):
con... | 0.337531 | 0.11221 |
import importlib.util
import os
import sys
import tempfile
import time
import unittest
from pyflink.common.typeinfo import Types
from pyflink.datastream import StreamExecutionEnvironment
from pyflink.table import StreamTableEnvironment, TableDescriptor, Schema
from dl_on_flink_tensorflow.tf_cluster_config import TFCl... | dl-on-flink-tensorflow-2.x/python/tests/flink_ml_tensorflow/test_tf_utils.py | import importlib.util
import os
import sys
import tempfile
import time
import unittest
from pyflink.common.typeinfo import Types
from pyflink.datastream import StreamExecutionEnvironment
from pyflink.table import StreamTableEnvironment, TableDescriptor, Schema
from dl_on_flink_tensorflow.tf_cluster_config import TFCl... | 0.334372 | 0.172555 |
import logging
import mmln
import mmln.infer
import mmln.ground
class Learner:
def __init__(self, network):
self.n = network
self.all_labels = mmln.get_all_labels(network)
self.logger = logging.getLogger(__name__)
def learn(self, model, inf=None):
raise NotImplementedError('... | mmln/learn.py | import logging
import mmln
import mmln.infer
import mmln.ground
class Learner:
def __init__(self, network):
self.n = network
self.all_labels = mmln.get_all_labels(network)
self.logger = logging.getLogger(__name__)
def learn(self, model, inf=None):
raise NotImplementedError('... | 0.63409 | 0.293265 |
from jsog3 import jsog
import unittest
class TestJSOG(unittest.TestCase):
def test_encode_reference(self):
inner = { "foo": "bar" }
outer = { "inner1": inner, "inner2": inner }
encoded = jsog.encode(outer)
# Python 3.7+ ensures fields are always processed in order,
# however contents of inner1 and inner2 ... | test_jsog.py | from jsog3 import jsog
import unittest
class TestJSOG(unittest.TestCase):
def test_encode_reference(self):
inner = { "foo": "bar" }
outer = { "inner1": inner, "inner2": inner }
encoded = jsog.encode(outer)
# Python 3.7+ ensures fields are always processed in order,
# however contents of inner1 and inner2 ... | 0.472683 | 0.443239 |
import argparse
import logging
from collections import Counter
from dataclasses import dataclass
from typing import List
# Parse Arguments
parser = argparse.ArgumentParser()
parser.add_argument('input_file', help='input file to read')
parser.add_argument('--verbosity', help='specify verbosity level (DEBUG|INFO)')
a... | 2019/day_8/run.py | import argparse
import logging
from collections import Counter
from dataclasses import dataclass
from typing import List
# Parse Arguments
parser = argparse.ArgumentParser()
parser.add_argument('input_file', help='input file to read')
parser.add_argument('--verbosity', help='specify verbosity level (DEBUG|INFO)')
a... | 0.781122 | 0.198122 |
import hashlib,requests,random,string,json
import time
from app import db
from app.model import Device
from app.model import Member
from app.common.libs.Helper import getCurrentDate, getFormatDate
from sqlalchemy import func, desc
class DeviceService():
@staticmethod
def geneSN( info ):
m = hashlib... | app/common/libs/DeviceService.py |
import hashlib,requests,random,string,json
import time
from app import db
from app.model import Device
from app.model import Member
from app.common.libs.Helper import getCurrentDate, getFormatDate
from sqlalchemy import func, desc
class DeviceService():
@staticmethod
def geneSN( info ):
m = hashlib... | 0.422743 | 0.072933 |
import numpy as np
import pandas as pd
from eskapade import process_manager, DataStore, Link, StatusCode
# numeric datatypes get converted to an index, which is then used for value counting
NUMERIC_SUBSTR = [np.dtype('int'), np.dtype('float'), np.dtype('double')]
# string datatype get treated as categories
STRING_SU... | python/eskapade/analysis/histogram_filling.py | import numpy as np
import pandas as pd
from eskapade import process_manager, DataStore, Link, StatusCode
# numeric datatypes get converted to an index, which is then used for value counting
NUMERIC_SUBSTR = [np.dtype('int'), np.dtype('float'), np.dtype('double')]
# string datatype get treated as categories
STRING_SU... | 0.828731 | 0.512266 |
import json
import os.path
import box
import click
import keyring as keyring_module
from ._compat import get_user, OPEN_PARAMETERS
from .appdir import get_filename
from .env import EnvironAttrDict
from .jsonutils import to_json_file, from_json_file
from .pwd import KeyringAttrDict
from .kwargs import group_kwargs_by_... | jsonconfig/core.py | import json
import os.path
import box
import click
import keyring as keyring_module
from ._compat import get_user, OPEN_PARAMETERS
from .appdir import get_filename
from .env import EnvironAttrDict
from .jsonutils import to_json_file, from_json_file
from .pwd import KeyringAttrDict
from .kwargs import group_kwargs_by_... | 0.252845 | 0.046421 |
from rest_framework.generics import get_object_or_404
from rest_framework.pagination import LimitOffsetPagination
from rest_framework.viewsets import ViewSet
from reversion.models import Version
from datahub.core.audit_utils import diff_versions
class AuditViewSet(ViewSet):
"""Generic view set for audit logs.
... | datahub/core/audit.py | from rest_framework.generics import get_object_or_404
from rest_framework.pagination import LimitOffsetPagination
from rest_framework.viewsets import ViewSet
from reversion.models import Version
from datahub.core.audit_utils import diff_versions
class AuditViewSet(ViewSet):
"""Generic view set for audit logs.
... | 0.879341 | 0.232125 |
from unittest import TestCase
from traits.testing.unittest_tools import UnittestTools
from force_bdss.api import DataValue
from surfactant_example.tests.probe_classes.probe_ingredients import (
ProbePrimaryIngredient,
)
from surfactant_example.tests.probe_classes.probe_fragments import (
ProbePrimarySurfacta... | surfactant_example/ingredient/tests/test_ingredient.py | from unittest import TestCase
from traits.testing.unittest_tools import UnittestTools
from force_bdss.api import DataValue
from surfactant_example.tests.probe_classes.probe_ingredients import (
ProbePrimaryIngredient,
)
from surfactant_example.tests.probe_classes.probe_fragments import (
ProbePrimarySurfacta... | 0.678007 | 0.628949 |
import torch
from torch.nn import functional as F
from facade_project import FACADE_ROT_PROPORTIONS
def dice_loss(logits, true, eps=1e-7):
"""
Computes the Sørensen–Dice loss.
Note that PyTorch optimizers minimize a loss. In this
case, we would like to maximize the dice loss so we
return the nega... | facade_project/nn/losses.py | import torch
from torch.nn import functional as F
from facade_project import FACADE_ROT_PROPORTIONS
def dice_loss(logits, true, eps=1e-7):
"""
Computes the Sørensen–Dice loss.
Note that PyTorch optimizers minimize a loss. In this
case, we would like to maximize the dice loss so we
return the nega... | 0.948858 | 0.751261 |
import unittest
from gittoc import mangle_header
class GitTocBasicTestCase(unittest.TestCase):
""" Basic true asserts to see that testing is executed
"""
def setUp(self):
pass
def tearDown(self):
pass
def test_example(self):
self.assertEqual(True, True)
self.asse... | test/basic.py | import unittest
from gittoc import mangle_header
class GitTocBasicTestCase(unittest.TestCase):
""" Basic true asserts to see that testing is executed
"""
def setUp(self):
pass
def tearDown(self):
pass
def test_example(self):
self.assertEqual(True, True)
self.asse... | 0.710327 | 0.716448 |
from .wps_sleep import Sleep
from .wps_meta import Meta
from .wps_preproc_example import PreprocessExample
from .wps_consecdrydays import ConsecDryDays
from .wps_cvdp import CVDP
from .wps_ensclus import EnsClus
from .wps_shapeselect import ShapeSelect
from .wps_blocking import Blocking
from .wps_zmnam import ZMNAM
fro... | c3s_magic_wps/processes/__init__.py | from .wps_sleep import Sleep
from .wps_meta import Meta
from .wps_preproc_example import PreprocessExample
from .wps_consecdrydays import ConsecDryDays
from .wps_cvdp import CVDP
from .wps_ensclus import EnsClus
from .wps_shapeselect import ShapeSelect
from .wps_blocking import Blocking
from .wps_zmnam import ZMNAM
fro... | 0.482185 | 0.101991 |
import argparse
import subprocess
from os import path
from scapy.all import *
from scapy.utils import rdpcap
from br24_driver import multicast_socket
import time
import StringIO
import binascii
import struct
def reassemble_packet(fragment_list):
buffer=StringIO.StringIO()
for pkt in sorted(fragment_list, key =... | replay_pcap.py | import argparse
import subprocess
from os import path
from scapy.all import *
from scapy.utils import rdpcap
from br24_driver import multicast_socket
import time
import StringIO
import binascii
import struct
def reassemble_packet(fragment_list):
buffer=StringIO.StringIO()
for pkt in sorted(fragment_list, key =... | 0.06711 | 0.101145 |
import os
import base64
import random
import string
import functools
from datetime import datetime, timedelta
import jinja2
import jsonschema
from pony.orm import db_session
from werkzeug.exceptions import HTTPException, Forbidden, UnprocessableEntity
from flask import request, current_app, jsonify, make_response, se... | smilepack/views/utils.py |
import os
import base64
import random
import string
import functools
from datetime import datetime, timedelta
import jinja2
import jsonschema
from pony.orm import db_session
from werkzeug.exceptions import HTTPException, Forbidden, UnprocessableEntity
from flask import request, current_app, jsonify, make_response, se... | 0.264833 | 0.054853 |
from pyRMSD.RMSDCalculator import RMSDCalculator
from pyRMSD.condensedMatrix import CondensedMatrix
from pyproct.driver.parameters import ProtocolParameters
class RMSDMatrixBuilder(object):
def __init__(self):
pass
@classmethod
def build(cls, data_handler, matrix_creation_parameters):
"""... | pyproct/data/matrix/protein/cases/rmsd/cartesiansCase.py | from pyRMSD.RMSDCalculator import RMSDCalculator
from pyRMSD.condensedMatrix import CondensedMatrix
from pyproct.driver.parameters import ProtocolParameters
class RMSDMatrixBuilder(object):
def __init__(self):
pass
@classmethod
def build(cls, data_handler, matrix_creation_parameters):
"""... | 0.796965 | 0.646251 |
"""
This module contains the 'password' node menu.
"""
from textwrap import dedent
from evennia.server.models import ServerConfig
from menu.character import (
_text_choose_characters,
_options_choose_characters,
_login)
from menu.email_address import text_email_address
from typeclasses.scri... | menu/password.py | """
This module contains the 'password' node menu.
"""
from textwrap import dedent
from evennia.server.models import ServerConfig
from menu.character import (
_text_choose_characters,
_options_choose_characters,
_login)
from menu.email_address import text_email_address
from typeclasses.scri... | 0.46393 | 0.141489 |
from flask.ext.assets import Bundle
js_filters = ['jsmin']
css_filters = ['cssmin']
js_libs = Bundle(
'js/lib/jquery-1.9.1.min.js',
'js/lib/underscore-min.js',
'js/lib/backbone-min.js',
'js/lib/bootstrap.min.js',
output='gen/js/libs.js'
)
css = Bundle(
'css/bootstrap/css/bootstrap.min.css',
... | flod_aktor_frontend/assetbundle.py | from flask.ext.assets import Bundle
js_filters = ['jsmin']
css_filters = ['cssmin']
js_libs = Bundle(
'js/lib/jquery-1.9.1.min.js',
'js/lib/underscore-min.js',
'js/lib/backbone-min.js',
'js/lib/bootstrap.min.js',
output='gen/js/libs.js'
)
css = Bundle(
'css/bootstrap/css/bootstrap.min.css',
... | 0.432782 | 0.039343 |
import os
import matplotlib.pyplot as plt
import numpy as np
import argparse
import argparse
import cv2
import tensorflow as tf
from tensorflow import keras
os.environ['TF_CPP_MIN_LOG_LEVEL'] = '1'
IMAGE_WIDTH = 300
IMAGE_HEIGHT = 300
model = keras.models.load_model("C:/Users/jrj00/Desktop/tttt/tfg/modeltest/modelPb... | PythonScripts/TensorFlow/tsDetector.py | import os
import matplotlib.pyplot as plt
import numpy as np
import argparse
import argparse
import cv2
import tensorflow as tf
from tensorflow import keras
os.environ['TF_CPP_MIN_LOG_LEVEL'] = '1'
IMAGE_WIDTH = 300
IMAGE_HEIGHT = 300
model = keras.models.load_model("C:/Users/jrj00/Desktop/tttt/tfg/modeltest/modelPb... | 0.429071 | 0.168104 |
import logging
import sys
import os
class Loggable():
'''This class has methods to manage the logger object of its child class instances.'''
def __init__(self):
self.name = None
self.workdir = None
self.logfile_path = None
def _setup_logger(self, name, workdir):
'''Sets up ... | copinicoos/loggable.py | import logging
import sys
import os
class Loggable():
'''This class has methods to manage the logger object of its child class instances.'''
def __init__(self):
self.name = None
self.workdir = None
self.logfile_path = None
def _setup_logger(self, name, workdir):
'''Sets up ... | 0.42668 | 0.06078 |
import numpy as np
from math import log
class StateRelation(object):
"""
Abstract state relation object that contains the generally used atributes
in state relations (b,Dc).
Attributes
----------
b : float
Rate and state empirical parameter b.
Dc : float
Critical slip dista... | rsfmodel/staterelations.py | import numpy as np
from math import log
class StateRelation(object):
"""
Abstract state relation object that contains the generally used atributes
in state relations (b,Dc).
Attributes
----------
b : float
Rate and state empirical parameter b.
Dc : float
Critical slip dista... | 0.888463 | 0.562297 |
import os
from typing import Any, Dict
import torch
from transformers.file_utils import WEIGHTS_NAME
from sparseml.pytorch.optim.manager import ScheduledModifierManager
__all__ = [
"RECIPE_NAME",
"preprocess_state_dict",
"load_recipe",
]
RECIPE_NAME = "recipe.yaml"
def load_recipe(pretrained_model_n... | src/sparseml/transformers/utils/helpers.py | import os
from typing import Any, Dict
import torch
from transformers.file_utils import WEIGHTS_NAME
from sparseml.pytorch.optim.manager import ScheduledModifierManager
__all__ = [
"RECIPE_NAME",
"preprocess_state_dict",
"load_recipe",
]
RECIPE_NAME = "recipe.yaml"
def load_recipe(pretrained_model_n... | 0.669421 | 0.154631 |
from benker.box import Box
#: Default tiles used to draw a :class:`~benker.grid.Grid`.
#:
#: Keys are tuples (*left*, *top*, *right*, *bottom*) : which represent the
#: presence (if ``True``) or absence (if ``False``) : of the border.
#: Values are the string representation of the tiles,
#: "XXXXXXXXX" will be replace... | benker/drawing.py | from benker.box import Box
#: Default tiles used to draw a :class:`~benker.grid.Grid`.
#:
#: Keys are tuples (*left*, *top*, *right*, *bottom*) : which represent the
#: presence (if ``True``) or absence (if ``False``) : of the border.
#: Values are the string representation of the tiles,
#: "XXXXXXXXX" will be replace... | 0.880912 | 0.438244 |
from commandTree import commandTree
import re
import traceback
class msgParse:
def __init__(self):
self._command = commandTree(None, None, None, None)
self._trigger = []
self.registerCommand([(u"help", "Displays the help for registered Commands", self._help)])
pass
def _getPer... | msgParse.py | from commandTree import commandTree
import re
import traceback
class msgParse:
def __init__(self):
self._command = commandTree(None, None, None, None)
self._trigger = []
self.registerCommand([(u"help", "Displays the help for registered Commands", self._help)])
pass
def _getPer... | 0.218253 | 0.067701 |
from dataclasses import dataclass
from logging import getLogger
import cv2
import numpy
from PIL import Image
from app.library.pillow import pil2cv
def matching_template(image, templ, *, method=cv2.TM_CCOEFF_NORMED):
return cv2.matchTemplate(image, templ, method)
def multi_scale_matching_template(image,
... | app/library/matching_template.py | from dataclasses import dataclass
from logging import getLogger
import cv2
import numpy
from PIL import Image
from app.library.pillow import pil2cv
def matching_template(image, templ, *, method=cv2.TM_CCOEFF_NORMED):
return cv2.matchTemplate(image, templ, method)
def multi_scale_matching_template(image,
... | 0.696371 | 0.219651 |
from __future__ import absolute_import, division, print_function, unicode_literals
from builtins import str
from textwrap import dedent
from pants.backend.python.targets.python_library import PythonLibrary
from pants.base.exceptions import TaskError
from pants_test.backend.python.tasks.python_task_test_base import P... | contrib/python/tests/python/pants_test/contrib/python/checks/tasks/checkstyle/test_checker.py |
from __future__ import absolute_import, division, print_function, unicode_literals
from builtins import str
from textwrap import dedent
from pants.backend.python.targets.python_library import PythonLibrary
from pants.base.exceptions import TaskError
from pants_test.backend.python.tasks.python_task_test_base import P... | 0.687735 | 0.189277 |
import pytest
from typing import Dict
import os
from ml_gym.blueprints.component_factory import ComponentFactory, Injector
from outlier_detection.constructables.constructables import CustomDatasetRepositoryConstructable, AtisFactoryConstructable
from outlier_detection.blueprints.mlp_blueprint import MLPCollator
from da... | pytest/preprocessing/atis/test_atis_preprocessing.py | import pytest
from typing import Dict
import os
from ml_gym.blueprints.component_factory import ComponentFactory, Injector
from outlier_detection.constructables.constructables import CustomDatasetRepositoryConstructable, AtisFactoryConstructable
from outlier_detection.blueprints.mlp_blueprint import MLPCollator
from da... | 0.703346 | 0.38743 |
import numpy as np
import matplotlib.pyplot as plt
import matplotlib.animation as animation
import skimage as sk
def show_image(image, figsize=(12,12)):
"""
simply display an Image
"""
plt.figure(figsize=figsize)
plt.imshow(image, cmap='gray')
def grid_view(video, **kwargs):
"""
make ... | scripts/display.py | import numpy as np
import matplotlib.pyplot as plt
import matplotlib.animation as animation
import skimage as sk
def show_image(image, figsize=(12,12)):
"""
simply display an Image
"""
plt.figure(figsize=figsize)
plt.imshow(image, cmap='gray')
def grid_view(video, **kwargs):
"""
make ... | 0.703753 | 0.726231 |
import imp
import os.path
import sys
import unittest
def _GetDirAbove(dirname):
"""Returns the directory "above" this file containing |dirname| (which must
also be "above" this file)."""
path = os.path.abspath(__file__)
while True:
path, tail = os.path.split(path)
assert tail
if tail == dirname:
... | mojo/public/tools/mojom/mojom/generate/generator_unittest.py |
import imp
import os.path
import sys
import unittest
def _GetDirAbove(dirname):
"""Returns the directory "above" this file containing |dirname| (which must
also be "above" this file)."""
path = os.path.abspath(__file__)
while True:
path, tail = os.path.split(path)
assert tail
if tail == dirname:
... | 0.485112 | 0.244831 |
import os
import argparse
from camera_trap_classifier.config.logging import setup_logging
from camera_trap_classifier.data.inventory import DatasetInventoryMaster
# Different functions depending on input values
def csv(args):
""" Import From CSV """
params = {'path': args['path'],
'image_path_c... | camera_trap_classifier/create_dataset_inventory.py | import os
import argparse
from camera_trap_classifier.config.logging import setup_logging
from camera_trap_classifier.data.inventory import DatasetInventoryMaster
# Different functions depending on input values
def csv(args):
""" Import From CSV """
params = {'path': args['path'],
'image_path_c... | 0.466116 | 0.22806 |
import logging
from flask import Blueprint, jsonify
from flask_pydantic import validate
from datastore_version_manager.domain import (
pending_operations,
draft_dataset,
version_bumper,
datastore_versions
)
from datastore_version_manager.exceptions.exceptions import (
ForbiddenOperation
)
from dat... | datastore_version_manager/api/command_api.py | import logging
from flask import Blueprint, jsonify
from flask_pydantic import validate
from datastore_version_manager.domain import (
pending_operations,
draft_dataset,
version_bumper,
datastore_versions
)
from datastore_version_manager.exceptions.exceptions import (
ForbiddenOperation
)
from dat... | 0.33372 | 0.095687 |
from typing import Any, List, Optional, Tuple, Union
import numpy
from QDTK.Operator import OCoef as Coeff
from QDTK.Operator import Operator
from QDTK.Operator import OTerm as Term
from mlxtk.dvr import DVRSpecification
from mlxtk.tools.diagonalize import diagonalize_1b_operator
from mlxtk.tools.operator import get_... | mlxtk/operator/operator_specification.py | from typing import Any, List, Optional, Tuple, Union
import numpy
from QDTK.Operator import OCoef as Coeff
from QDTK.Operator import Operator
from QDTK.Operator import OTerm as Term
from mlxtk.dvr import DVRSpecification
from mlxtk.tools.diagonalize import diagonalize_1b_operator
from mlxtk.tools.operator import get_... | 0.926628 | 0.427337 |
from __future__ import unicode_literals
import frappe
from frappe import _
def execute(filters=None):
columns = get_columns()
conditions = get_conditions(filters)
data = get_data(conditions, filters)
if not data:
return [], [], None, []
chart_data = get_chart_data(data)
return columns, data, None, chart_da... | mindhome_alpha/erpnext/stock/report/item_shortage_report/item_shortage_report.py |
from __future__ import unicode_literals
import frappe
from frappe import _
def execute(filters=None):
columns = get_columns()
conditions = get_conditions(filters)
data = get_data(conditions, filters)
if not data:
return [], [], None, []
chart_data = get_chart_data(data)
return columns, data, None, chart_da... | 0.528777 | 0.259356 |
import hashlib
import os
import random
import re
import numpy as np
from os.path import join, isdir
from scipy.io.wavfile import read, write
from pathlib import Path
MAX_NUM_WAVS_PER_CLASS = 2**27 - 1 # ~134M
UNKNOWN = '_unknown_'
def which_set(filename, validation_percentage, testing_percentage):
"""Determine... | dataset_utils.py | import hashlib
import os
import random
import re
import numpy as np
from os.path import join, isdir
from scipy.io.wavfile import read, write
from pathlib import Path
MAX_NUM_WAVS_PER_CLASS = 2**27 - 1 # ~134M
UNKNOWN = '_unknown_'
def which_set(filename, validation_percentage, testing_percentage):
"""Determine... | 0.591369 | 0.454048 |
from amqplib import client_0_8 as amqp
import sys
import random
import time
from optparse import OptionParser
parser = OptionParser()
parser.add_option("--host", action="store", type="string", dest="host", default="localhost")
parser.add_option("--port", action="store", type="int", dest="port", default=5672)
parser.a... | check_amqp.py | from amqplib import client_0_8 as amqp
import sys
import random
import time
from optparse import OptionParser
parser = OptionParser()
parser.add_option("--host", action="store", type="string", dest="host", default="localhost")
parser.add_option("--port", action="store", type="int", dest="port", default=5672)
parser.a... | 0.142321 | 0.093719 |
import unittest
import vcr
from shapely.geometry import shape
from stactools.core.utils.antimeridian import Strategy
from stactools.landsat.stac import create_stac_item
from tests.data import TEST_GEOMETRY_PATHS
class GeometryTest(unittest.TestCase):
def test_stored_stac(self):
"""Test USGS STAC geomet... | tests/test_geometry.py | import unittest
import vcr
from shapely.geometry import shape
from stactools.core.utils.antimeridian import Strategy
from stactools.landsat.stac import create_stac_item
from tests.data import TEST_GEOMETRY_PATHS
class GeometryTest(unittest.TestCase):
def test_stored_stac(self):
"""Test USGS STAC geomet... | 0.706596 | 0.557002 |
import scipy
import scipy.sparse.linalg
import torch
import torch.nn as nn
from hodgeautograd import HodgeEigensystem
class HodgeNetModel(nn.Module):
"""Main HodgeNet model.
The model inputs a batch of meshes and outputs features per vertex or
pooled to faces or the entire mesh.
"""
def __init_... | hodgenet.py | import scipy
import scipy.sparse.linalg
import torch
import torch.nn as nn
from hodgeautograd import HodgeEigensystem
class HodgeNetModel(nn.Module):
"""Main HodgeNet model.
The model inputs a batch of meshes and outputs features per vertex or
pooled to faces or the entire mesh.
"""
def __init_... | 0.905452 | 0.563978 |
from datetime import datetime
import pytest
from sqlalchemy import create_engine
from sqlalchemy.orm import sessionmaker
from receipt_tracker.repo.models import Seller, Buyer, Receipt
from receipt_tracker.repo.sql_repo import Base
from receipt_tracker.repo.sql_repo import SQLRepo
@pytest.fixture(scope='session')
de... | tests/conftest.py | from datetime import datetime
import pytest
from sqlalchemy import create_engine
from sqlalchemy.orm import sessionmaker
from receipt_tracker.repo.models import Seller, Buyer, Receipt
from receipt_tracker.repo.sql_repo import Base
from receipt_tracker.repo.sql_repo import SQLRepo
@pytest.fixture(scope='session')
de... | 0.421552 | 0.138928 |
from django.db import models
from django.utils import timezone
from django.contrib.auth.models import AbstractBaseUser, PermissionsMixin
from .managers import UserManager
from django.conf import settings
class User(AbstractBaseUser, PermissionsMixin):
objects = UserManager()
userid = models.CharField(default=... | MXXXPXXX/sg/models.py | from django.db import models
from django.utils import timezone
from django.contrib.auth.models import AbstractBaseUser, PermissionsMixin
from .managers import UserManager
from django.conf import settings
class User(AbstractBaseUser, PermissionsMixin):
objects = UserManager()
userid = models.CharField(default=... | 0.593727 | 0.109515 |
import subprocess
from pyprobe.sensors.pegasus.controller import PegasusControllerParser
from pyprobe.sensors.process_helper import get_outputs_of_process
__author__ = '<NAME>'
def reformat_smart_values(data=None):
"""
Reformats the SMART output of the Pegasus device so that it is compatible with the Parser ... | src/pyprobe/sensors/pegasus/helper.py | import subprocess
from pyprobe.sensors.pegasus.controller import PegasusControllerParser
from pyprobe.sensors.process_helper import get_outputs_of_process
__author__ = '<NAME>'
def reformat_smart_values(data=None):
"""
Reformats the SMART output of the Pegasus device so that it is compatible with the Parser ... | 0.603465 | 0.322153 |
import torch as t
import torch.nn as nn
import torch.nn.functional as F
from model.layer import VGG19featureLayer
from functools import reduce
class WGANLoss(nn.Module):
def __init__(self):
super(WGANLoss, self).__init__()
def __call__(self, input, target):
d_loss = (input - target).mean()
... | Image Inpainting/model/loss.py | import torch as t
import torch.nn as nn
import torch.nn.functional as F
from model.layer import VGG19featureLayer
from functools import reduce
class WGANLoss(nn.Module):
def __init__(self):
super(WGANLoss, self).__init__()
def __call__(self, input, target):
d_loss = (input - target).mean()
... | 0.907114 | 0.426381 |
import numpy as np
import cv2 as cv
import glob
import matplotlib.pyplot as plt
import sys
from PIL import Image
import argparse
import os
# convenience code to annotate calibration points by clicking
# python localization.py dataset/beach/map.png dataset/beach/calib_map.txt --click
if '--click' in sys.argv:
input... | localization.py | import numpy as np
import cv2 as cv
import glob
import matplotlib.pyplot as plt
import sys
from PIL import Image
import argparse
import os
# convenience code to annotate calibration points by clicking
# python localization.py dataset/beach/map.png dataset/beach/calib_map.txt --click
if '--click' in sys.argv:
input... | 0.259169 | 0.340239 |
import csv
from etilog.models import ImpactEvent
from etilog.models import SustainabilityDomain, SustainabilityTendency, SustainabilityTag
from etilog.models import Company
from etilog.models import Reference
def exp_csv_nlp(response):
writer = get_csvwriter(response)
header = ['ID',
'date_publ... | impexport/Logic/ViewExport.py | import csv
from etilog.models import ImpactEvent
from etilog.models import SustainabilityDomain, SustainabilityTendency, SustainabilityTag
from etilog.models import Company
from etilog.models import Reference
def exp_csv_nlp(response):
writer = get_csvwriter(response)
header = ['ID',
'date_publ... | 0.278649 | 0.205456 |
import os
import random
import sys
from typing import Tuple
import cv2
import numpy as np
from numpy.lib.financial import ipmt
import pandas as pd
import torch
from torch.utils.data.dataset import Dataset
from easydict import EasyDict as edict
import matplotlib.pyplot as plt
def rand_uniform_strong(min, max):
i... | dataset.py | import os
import random
import sys
from typing import Tuple
import cv2
import numpy as np
from numpy.lib.financial import ipmt
import pandas as pd
import torch
from torch.utils.data.dataset import Dataset
from easydict import EasyDict as edict
import matplotlib.pyplot as plt
def rand_uniform_strong(min, max):
i... | 0.482673 | 0.378115 |
from __future__ import unicode_literals
from ckeditor.fields import RichTextField
from collections import defaultdict
from django.conf import settings
from django.contrib.auth.models import User
from django.db import models
from django.utils.encoding import python_2_unicode_compatible
from enum import Enum, unique
from... | nominations/models.py | from __future__ import unicode_literals
from ckeditor.fields import RichTextField
from collections import defaultdict
from django.conf import settings
from django.contrib.auth.models import User
from django.db import models
from django.utils.encoding import python_2_unicode_compatible
from enum import Enum, unique
from... | 0.452052 | 0.118589 |
from enum import Enum
class MenuCategoryEnum(Enum):
"""
Enum for categories, for item type menu <category name>: <category id>
"""
MENU_TYPE = 'Y2F0ZWdvcnk6MjQ2NQ=='
class MenuItemCategoryEnum(Enum):
"""
Enum for categories, for item type menu item <category name>: <category id>
"""
... | galley/enums.py | from enum import Enum
class MenuCategoryEnum(Enum):
"""
Enum for categories, for item type menu <category name>: <category id>
"""
MENU_TYPE = 'Y2F0ZWdvcnk6MjQ2NQ=='
class MenuItemCategoryEnum(Enum):
"""
Enum for categories, for item type menu item <category name>: <category id>
"""
... | 0.33928 | 0.090253 |
import os
import shutil
################### Directory Helper #############################3
def removeDirectory(path, verbose=True):
if (os.path.isdir(path)):
if (True): # input("are you sure you want to remove this directory? (Y / N): " + path) == "Y" ):
shutil.rmtree(path)
else:
... | utils.py | import os
import shutil
################### Directory Helper #############################3
def removeDirectory(path, verbose=True):
if (os.path.isdir(path)):
if (True): # input("are you sure you want to remove this directory? (Y / N): " + path) == "Y" ):
shutil.rmtree(path)
else:
... | 0.330039 | 0.328233 |
import logging
import sys
import re
import plugins
from version import __version__
from commands import command
logger = logging.getLogger(__name__)
try:
import resource
except ImportError:
logger.warning("resource is unavailable on your system")
def _initialise(bot): pass # prevents commands from being ... | hangupsbot/commands/basic.py | import logging
import sys
import re
import plugins
from version import __version__
from commands import command
logger = logging.getLogger(__name__)
try:
import resource
except ImportError:
logger.warning("resource is unavailable on your system")
def _initialise(bot): pass # prevents commands from being ... | 0.236781 | 0.092115 |
import geopandas as gpd
import pandas as pd
import glob
import os
from rasterstats import zonal_stats
rsterDir=r'C:\Students\Hanan\Thesis_work\Data\Processing\Lebanon\LB_Planet\LB_Rasters'
mydir=r'C:\Students\Hanan\Thesis_work\Data\Processing\Lebanon\LB_Planet\LB_Rasters'
shpDir=r'C:\Students\Hanan\Thesis_work... | Hanan_Stats.py | import geopandas as gpd
import pandas as pd
import glob
import os
from rasterstats import zonal_stats
rsterDir=r'C:\Students\Hanan\Thesis_work\Data\Processing\Lebanon\LB_Planet\LB_Rasters'
mydir=r'C:\Students\Hanan\Thesis_work\Data\Processing\Lebanon\LB_Planet\LB_Rasters'
shpDir=r'C:\Students\Hanan\Thesis_work... | 0.052122 | 0.138345 |
import torch
class Beam(object):
"""Class for managing the internals of the beam search process.
Takes care of beams, back pointers, and scores.
Args:
size (int): Number of beams to use.
pad (int): Magic integer in output vocab.
bos (int): Magic integer in output vocab.
eos... | models/listen_attend_and_spell/beam_search.py | import torch
class Beam(object):
"""Class for managing the internals of the beam search process.
Takes care of beams, back pointers, and scores.
Args:
size (int): Number of beams to use.
pad (int): Magic integer in output vocab.
bos (int): Magic integer in output vocab.
eos... | 0.905766 | 0.398231 |
import os
import sys
from os.path import abspath, dirname, expanduser, getsize, isfile, splitext
from typing import List, TypedDict
from zipfile import ZipFile
ROOT = dirname(dirname(abspath(__file__)))
class ProcessResponse(TypedDict):
download_filename: str
filesize: int
output_filesize: int
outpu... | pdf_compressor/utils.py | import os
import sys
from os.path import abspath, dirname, expanduser, getsize, isfile, splitext
from typing import List, TypedDict
from zipfile import ZipFile
ROOT = dirname(dirname(abspath(__file__)))
class ProcessResponse(TypedDict):
download_filename: str
filesize: int
output_filesize: int
outpu... | 0.612889 | 0.329783 |
from datetime import datetime, timedelta
from random import randrange
from uuid import uuid4
from flask import Blueprint, jsonify, request, url_for
from flask_login import current_user, login_required
from ..helper import admin_required_decorator as admin_required
from ..helper.youtube import build_youtube_api
from .... | tubee/routes/api_channel.py | from datetime import datetime, timedelta
from random import randrange
from uuid import uuid4
from flask import Blueprint, jsonify, request, url_for
from flask_login import current_user, login_required
from ..helper import admin_required_decorator as admin_required
from ..helper.youtube import build_youtube_api
from .... | 0.387227 | 0.061593 |
from .DFNDataReleases import get_relevant_info
from .DFNDataReleases import dir_path as REPO_DIR
from collections import defaultdict
import os
import json
def get_naf_paths(project,language,verbose=0):
"""
Get a dictionary with event type as key and a set of NAF paths as value.
:param project: the project ... | path_utils.py | from .DFNDataReleases import get_relevant_info
from .DFNDataReleases import dir_path as REPO_DIR
from collections import defaultdict
import os
import json
def get_naf_paths(project,language,verbose=0):
"""
Get a dictionary with event type as key and a set of NAF paths as value.
:param project: the project ... | 0.500732 | 0.327695 |
import sqlite3
import glob
class Run:
def __init__(self):
self.n = 0
self.hints = 0
self.solution_grid = None
self.input_grid = None
self.output_grid = None
self.time_millis = 0
def __str__(self):
return "{n = %d, hints = %d, solution = %s, input = %s,... | runs/database.py | import sqlite3
import glob
class Run:
def __init__(self):
self.n = 0
self.hints = 0
self.solution_grid = None
self.input_grid = None
self.output_grid = None
self.time_millis = 0
def __str__(self):
return "{n = %d, hints = %d, solution = %s, input = %s,... | 0.238639 | 0.165796 |
import argparse
import matplotlib as mpl
from matplotlib.backends.backend_pdf import PdfPages
from matplotlib.colors import ListedColormap
import matplotlib.gridspec as gridspec
import matplotlib.patches as patches
import matplotlib.pyplot as plt
import numpy as np
import pandas as pd
import seaborn as sns
import matpl... | GraphClusterLibrary.py | import argparse
import matplotlib as mpl
from matplotlib.backends.backend_pdf import PdfPages
from matplotlib.colors import ListedColormap
import matplotlib.gridspec as gridspec
import matplotlib.patches as patches
import matplotlib.pyplot as plt
import numpy as np
import pandas as pd
import seaborn as sns
import matpl... | 0.291586 | 0.29598 |
import requests
import re
import random
import configparser
from bs4 import BeautifulSoup
from flask import Flask, request, abort
from imgurpython import ImgurClient
from linebot import (
LineBotApi, WebhookHandler
)
from linebot.exceptions import (
InvalidSignatureError
)
from linebot.models import *
app = F... | app.py | import requests
import re
import random
import configparser
from bs4 import BeautifulSoup
from flask import Flask, request, abort
from imgurpython import ImgurClient
from linebot import (
LineBotApi, WebhookHandler
)
from linebot.exceptions import (
InvalidSignatureError
)
from linebot.models import *
app = F... | 0.115224 | 0.053775 |
import json
import math
import os
import pickle
import random
from multiprocessing import Pool
from pathlib import Path
import pandas as pd
import torch
import torch.nn.functional as F
import torch.utils.data
from augmentation.augmentation_methods import \
NoiseAugmentor, RirAugmentor, CodecAugmento... | src/speech_distillation/multilabel_wave_dataset.py | import json
import math
import os
import pickle
import random
from multiprocessing import Pool
from pathlib import Path
import pandas as pd
import torch
import torch.nn.functional as F
import torch.utils.data
from augmentation.augmentation_methods import \
NoiseAugmentor, RirAugmentor, CodecAugmento... | 0.575588 | 0.103477 |
from flask_sqlalchemy import SQLAlchemy
from dataclasses import dataclass
db = SQLAlchemy()
@dataclass
class User(db.Model):
__tablename__ = 'users'
id: int
name: str
email: str
password: str
id = db.Column(db.Integer, primary_key=True)
name = db.Column(db.String(50), unique=True)
ema... | eventapp/models.py | from flask_sqlalchemy import SQLAlchemy
from dataclasses import dataclass
db = SQLAlchemy()
@dataclass
class User(db.Model):
__tablename__ = 'users'
id: int
name: str
email: str
password: str
id = db.Column(db.Integer, primary_key=True)
name = db.Column(db.String(50), unique=True)
ema... | 0.611498 | 0.051797 |
import argparse, os, glob, tqdm, zipfile, webrtcvad
import soundfile as sf
from get_vad import *
class segmentor():
def __init__(self,merge_margin,cut_margin,res_path,vad_setting=0):
self.merge_margin=merge_margin
self.cut_margin=cut_margin
self.vad=webrtcvad.Vad(vad_setting)
sel... | asr/python/gen_asrinput_continuous.py | import argparse, os, glob, tqdm, zipfile, webrtcvad
import soundfile as sf
from get_vad import *
class segmentor():
def __init__(self,merge_margin,cut_margin,res_path,vad_setting=0):
self.merge_margin=merge_margin
self.cut_margin=cut_margin
self.vad=webrtcvad.Vad(vad_setting)
sel... | 0.333829 | 0.064742 |
from typing import List
def findKthLargest(nums: List[int], k: int) -> int:
nums = sorted(nums)
return nums[-k]
# This is the quick select solution, supposedly O(n).
def findKthLargest_partition(nums: List[int], k: int) -> int:
def partition(l: int, r: int) -> int:
if l > r:
... | PythonSolutions/215_kth_largest_element_in_an_array.py | from typing import List
def findKthLargest(nums: List[int], k: int) -> int:
nums = sorted(nums)
return nums[-k]
# This is the quick select solution, supposedly O(n).
def findKthLargest_partition(nums: List[int], k: int) -> int:
def partition(l: int, r: int) -> int:
if l > r:
... | 0.70304 | 0.606265 |
import os
import sys
import requests
import json
from flask import jsonify, request, make_response, send_from_directory
from kazoo import client as kz_client
from flask import request
from flask_pymongo import PyMongo
from flask_jwt_extended import (create_access_token, create_refresh_token,
... | auth_service/index.py | import os
import sys
import requests
import json
from flask import jsonify, request, make_response, send_from_directory
from kazoo import client as kz_client
from flask import request
from flask_pymongo import PyMongo
from flask_jwt_extended import (create_access_token, create_refresh_token,
... | 0.191706 | 0.046899 |
import weakref
from AppKit import *
from vanillaBase import VanillaBaseObject, _breakCycles
from nsSubclasses import getNSSubclass
_edgeMap = {
"left" : NSMinXEdge,
"right" : NSMaxXEdge,
"top" : NSMinYEdge,
"bottom" : NSMaxYEdge
}
try:
NSPopoverBehaviorApplicationDefined
except NameError:
NSPo... | Lib/vanilla/vanillaPopover.py | import weakref
from AppKit import *
from vanillaBase import VanillaBaseObject, _breakCycles
from nsSubclasses import getNSSubclass
_edgeMap = {
"left" : NSMinXEdge,
"right" : NSMaxXEdge,
"top" : NSMinYEdge,
"bottom" : NSMaxYEdge
}
try:
NSPopoverBehaviorApplicationDefined
except NameError:
NSPo... | 0.654895 | 0.301626 |
__author__ = 'schmidm'
import random
def make_html_file(examples, filename):
"""
Visualizes attention of a model in a HTML file.
:param examples:
:param filename:
:return:
"""
def attention_to_rgb(attention):
# red = int(attention * 255)
# green = int(255 - red)
... | asreader/text_comprehension/visualisation.py | __author__ = 'schmidm'
import random
def make_html_file(examples, filename):
"""
Visualizes attention of a model in a HTML file.
:param examples:
:param filename:
:return:
"""
def attention_to_rgb(attention):
# red = int(attention * 255)
# green = int(255 - red)
... | 0.480235 | 0.181934 |
from enum import Enum
from collections import deque
import operator as ops
from helpers import read_input
class State(Enum):
Running = 1
Waiting = 2
Halted = 3
class Computer:
def __init__(self, instructions, ram_size=4096):
self.ram = self.initialize_memory(instructions, ram_size)
s... | python/intcode.py | from enum import Enum
from collections import deque
import operator as ops
from helpers import read_input
class State(Enum):
Running = 1
Waiting = 2
Halted = 3
class Computer:
def __init__(self, instructions, ram_size=4096):
self.ram = self.initialize_memory(instructions, ram_size)
s... | 0.651244 | 0.356167 |
import logging
from logging.handlers import RotatingFileHandler
import os.path
from .utils import (
os_path_exists,
get_encoding,
check_path
)
class LogManager(object):
# noinspection PyUnresolvedReferences
"""Simple log manager for youtube-dl.
This class is mainly used to log the youtu... | youtube_dl_gui/logmanager.py | import logging
from logging.handlers import RotatingFileHandler
import os.path
from .utils import (
os_path_exists,
get_encoding,
check_path
)
class LogManager(object):
# noinspection PyUnresolvedReferences
"""Simple log manager for youtube-dl.
This class is mainly used to log the youtu... | 0.672977 | 0.094177 |
from typing import List, Tuple
import json
import cv2 as cv
import numpy as np
from sklearn.discriminant_analysis import LinearDiscriminantAnalysis
from sklearn.preprocessing import LabelEncoder
from sklearn.random_projection import GaussianRandomProjection
from tornado.web import RequestHandler
from ..types import ... | server/handlers/feature_extraction/image_lda.py |
from typing import List, Tuple
import json
import cv2 as cv
import numpy as np
from sklearn.discriminant_analysis import LinearDiscriminantAnalysis
from sklearn.preprocessing import LabelEncoder
from sklearn.random_projection import GaussianRandomProjection
from tornado.web import RequestHandler
from ..types import ... | 0.896778 | 0.581184 |
class Beautifier:
"""
Class that creates HTML file (_filename) with simple w3-css style from
input dict (_data). Example of input dict:
{ 'WI-FI keys':
[
{'ESSID': 'Burger-king', 'Pass': '<PASSWORD>'},
{'ESSID': 'Neighboring Wi-Fi', 'Pass': '<PASSWORD>'},
{'... | python_source/beautifier.py | class Beautifier:
"""
Class that creates HTML file (_filename) with simple w3-css style from
input dict (_data). Example of input dict:
{ 'WI-FI keys':
[
{'ESSID': 'Burger-king', 'Pass': '<PASSWORD>'},
{'ESSID': 'Neighboring Wi-Fi', 'Pass': '<PASSWORD>'},
{'... | 0.631708 | 0.264996 |
import sphinx_rtd_theme
extensions = [
'sphinx.ext.autodoc',
'sphinx.ext.autosummary',
'sphinx.ext.intersphinx',
'sphinx.ext.imgmath',
'sphinx.ext.viewcode',
]
project = u'pwkit'
version = 'master' # also edit /setup.py, /pwkit/__init__.py!
release = '1.1.0.dev0'
copyright = u'2015-2019, <NAME> ... | docs/source/conf.py |
import sphinx_rtd_theme
extensions = [
'sphinx.ext.autodoc',
'sphinx.ext.autosummary',
'sphinx.ext.intersphinx',
'sphinx.ext.imgmath',
'sphinx.ext.viewcode',
]
project = u'pwkit'
version = 'master' # also edit /setup.py, /pwkit/__init__.py!
release = '1.1.0.dev0'
copyright = u'2015-2019, <NAME> ... | 0.483648 | 0.123577 |
import unittest
from edopi import Chroma
class TestChroma(unittest.TestCase):
def setUp(self):
self.e1 = Chroma(8, 12)
self.e2 = Chroma(5, 12)
def test_is_generator(self):
self.assertFalse(self.e1.is_generator)
self.assertTrue(self.e2.is_generator)
def test_eq(self):... | tests/test_chroma.py | import unittest
from edopi import Chroma
class TestChroma(unittest.TestCase):
def setUp(self):
self.e1 = Chroma(8, 12)
self.e2 = Chroma(5, 12)
def test_is_generator(self):
self.assertFalse(self.e1.is_generator)
self.assertTrue(self.e2.is_generator)
def test_eq(self):... | 0.665302 | 0.770378 |
from django.test import TestCase
from boardinghouse.schema import get_schema_model
from ..models import AwareModel, NaiveModel
Schema = get_schema_model()
class TestPartitioning(TestCase):
def test_aware_objects_are_created_in_active_schema(self):
first = Schema.objects.create(name='first', schema='firs... | tests/tests/test_objects_are_partitioned.py | from django.test import TestCase
from boardinghouse.schema import get_schema_model
from ..models import AwareModel, NaiveModel
Schema = get_schema_model()
class TestPartitioning(TestCase):
def test_aware_objects_are_created_in_active_schema(self):
first = Schema.objects.create(name='first', schema='firs... | 0.419053 | 0.394959 |
import torch
import torch.nn as nn
import torch.nn.functional as F
from six.moves import range
import attention
import math
from loss import cross_entropy, uniform_label_smooth_regulerizer
import utils
from utils import get_seq_mask_by_shape, get_seq_mask
import pdb
class RNNDecoder(torch.nn.Module):
def __init... | src/decoder.py | import torch
import torch.nn as nn
import torch.nn.functional as F
from six.moves import range
import attention
import math
from loss import cross_entropy, uniform_label_smooth_regulerizer
import utils
from utils import get_seq_mask_by_shape, get_seq_mask
import pdb
class RNNDecoder(torch.nn.Module):
def __init... | 0.810929 | 0.241121 |
from typing import Dict
from enums import MeterType, StressType
class Line:
'''Functionality to load, process and store information about specific lines of text.'''
# Available vowels - they signify syllables
VOWELS: str = "АаОоУуЕеИиІіЯяЄєЇїЮю"
# An ord of stress mark that signifies which syllable i... | line.py | from typing import Dict
from enums import MeterType, StressType
class Line:
'''Functionality to load, process and store information about specific lines of text.'''
# Available vowels - they signify syllables
VOWELS: str = "АаОоУуЕеИиІіЯяЄєЇїЮю"
# An ord of stress mark that signifies which syllable i... | 0.792062 | 0.263937 |
owner_users = {
'email': '<EMAIL>',
'password': '<PASSWORD>-'
}
provider_users = {
'<EMAIL>': '<PASSWORD>-',
'<EMAIL>': '<PASSWORD>-',
'<EMAIL>': 'Kapital-Ist',
'<EMAIL>': 'Kapital-Ist',
'<EMAIL>': 'Kapital-Ist'
}
broker = {'url': 'https://prozorro.kapital-ist.kiev.ua'}
# login
... | kapitalist_load/locators.py | owner_users = {
'email': '<EMAIL>',
'password': '<PASSWORD>-'
}
provider_users = {
'<EMAIL>': '<PASSWORD>-',
'<EMAIL>': '<PASSWORD>-',
'<EMAIL>': 'Kapital-Ist',
'<EMAIL>': 'Kapital-Ist',
'<EMAIL>': 'Kapital-Ist'
}
broker = {'url': 'https://prozorro.kapital-ist.kiev.ua'}
# login
... | 0.228845 | 0.065605 |
from abc import abstractmethod
from io import StringIO
from typing import *
import numpy as np
import torch
from torch.utils.data import DataLoader
# The Protocol type does not exist until Python 3.7.
# TODO: Remove the try-except when Python 3.6 support is dropped.
try:
from typing import Protocol
except Impor... | toys/data.py | from abc import abstractmethod
from io import StringIO
from typing import *
import numpy as np
import torch
from torch.utils.data import DataLoader
# The Protocol type does not exist until Python 3.7.
# TODO: Remove the try-except when Python 3.6 support is dropped.
try:
from typing import Protocol
except Impor... | 0.720663 | 0.677261 |
import datetime
import logging
import rx
from rx.core import AnonymousObservable
import xml.etree.ElementTree as ET
from phone_communication_backup_coalescer.files import dir_to_files_mapper
from phone_communication_backup_coalescer import __version__, __name__
def as_list(item):
if not hasattr(item, '__iter__'):
... | phone_communication_backup_coalescer/coalesce.py | import datetime
import logging
import rx
from rx.core import AnonymousObservable
import xml.etree.ElementTree as ET
from phone_communication_backup_coalescer.files import dir_to_files_mapper
from phone_communication_backup_coalescer import __version__, __name__
def as_list(item):
if not hasattr(item, '__iter__'):
... | 0.293506 | 0.090655 |
from sqlalchemy import create_engine
from sqlalchemy.ext.declarative import declarative_base
from sqlalchemy.orm import sessionmaker
from bottle import run
from sqlalchemy import exc
import warnings
from bottle import route, request, HTTPResponse
from model import User, Skill
from utilitiy import search, delete, create... | code/api.py | from sqlalchemy import create_engine
from sqlalchemy.ext.declarative import declarative_base
from sqlalchemy.orm import sessionmaker
from bottle import run
from sqlalchemy import exc
import warnings
from bottle import route, request, HTTPResponse
from model import User, Skill
from utilitiy import search, delete, create... | 0.417509 | 0.104249 |
import time
from etcdb import WAIT_WAIT_TIMEOUT, InternalError
from etcdb.eval_expr import eval_expr
from etcdb.execute.dml.insert import get_table_columns
from etcdb.execute.dml.select import prepare_columns, list_table, \
get_row_by_primary_key, eval_row
from etcdb.resultset import ResultSet, Row
def execute_w... | etcdb/execute/dml/wait.py | import time
from etcdb import WAIT_WAIT_TIMEOUT, InternalError
from etcdb.eval_expr import eval_expr
from etcdb.execute.dml.insert import get_table_columns
from etcdb.execute.dml.select import prepare_columns, list_table, \
get_row_by_primary_key, eval_row
from etcdb.resultset import ResultSet, Row
def execute_w... | 0.253214 | 0.107883 |
import plotly.offline as plotly
import plotly.graph_objs as graph
import sys
import os
outputdir = 'D:/11p/TCC/workspace/tcc/plots'
auto_open_htmls = False
def plot_history(component_type, repoName):
add = []
rem = []
mod = []
dates = []
total = []
component_type = repoName + component_type
f = ... | plots/componentHistoryPlot.py | import plotly.offline as plotly
import plotly.graph_objs as graph
import sys
import os
outputdir = 'D:/11p/TCC/workspace/tcc/plots'
auto_open_htmls = False
def plot_history(component_type, repoName):
add = []
rem = []
mod = []
dates = []
total = []
component_type = repoName + component_type
f = ... | 0.119434 | 0.107555 |
import os
import tempfile
import tkFileDialog
from Tkinter import *
import tkMessageBox
import json
import requests
import subprocess
import maskgen.maskgen_loader
from maskgen.software_loader import getFileName
from tkinter import ttk
from hp.hp_data import orgs
key = os.path.join(os.path.expanduser("~"), "medifor_in... | scripts/python/jtprefs.py | import os
import tempfile
import tkFileDialog
from Tkinter import *
import tkMessageBox
import json
import requests
import subprocess
import maskgen.maskgen_loader
from maskgen.software_loader import getFileName
from tkinter import ttk
from hp.hp_data import orgs
key = os.path.join(os.path.expanduser("~"), "medifor_in... | 0.345768 | 0.091301 |
import sqlite3
class User:
def __init__(self, id, name, authstring):
self.id = id
self.name = name
self.authstring = authstring
@staticmethod
def get_user_by_name(name):
connection = sqlite3.connect('./db.db')
cursor = connection.cursor()
sql = '''SELECT *... | models.py | import sqlite3
class User:
def __init__(self, id, name, authstring):
self.id = id
self.name = name
self.authstring = authstring
@staticmethod
def get_user_by_name(name):
connection = sqlite3.connect('./db.db')
cursor = connection.cursor()
sql = '''SELECT *... | 0.311008 | 0.076857 |
from pathlib import Path
import time
import traceback
from ._base_subcommand import BaseSubcommand
class Subcommand(BaseSubcommand):
help = "Build dirs for pending jobs."
def add_arguments(self, parser):
defaults = self._get_defaults()
parser.add_argument(
'--tag',
he... | mc/houston/subcommands/build_job_dirs.py | from pathlib import Path
import time
import traceback
from ._base_subcommand import BaseSubcommand
class Subcommand(BaseSubcommand):
help = "Build dirs for pending jobs."
def add_arguments(self, parser):
defaults = self._get_defaults()
parser.add_argument(
'--tag',
he... | 0.576542 | 0.085709 |
import io
import pathlib
from abc import ABC, abstractclassmethod
class SerpentFile(ABC):
"""Most basic interface for a Serpent file
Parameters
----------
filename : str, optional
Helpful identifier for the source of data
Attributes
----------
filename : str or None
Name ... | serpentTools/next/base.py | import io
import pathlib
from abc import ABC, abstractclassmethod
class SerpentFile(ABC):
"""Most basic interface for a Serpent file
Parameters
----------
filename : str, optional
Helpful identifier for the source of data
Attributes
----------
filename : str or None
Name ... | 0.78964 | 0.282132 |
# Commented out IPython magic to ensure Python compatibility.
try:
# %tensorflow_version only exists in Colab.
# %tensorflow_version 2.x
except Exception:
pass
import tensorflow as tf
from tensorflow.keras.models import Model
from tensorflow.keras.layers import Input, Flatten, Dense, Dropout, Lambda
from tensorfl... | Main.py |
# Commented out IPython magic to ensure Python compatibility.
try:
# %tensorflow_version only exists in Colab.
# %tensorflow_version 2.x
except Exception:
pass
import tensorflow as tf
from tensorflow.keras.models import Model
from tensorflow.keras.layers import Input, Flatten, Dense, Dropout, Lambda
from tensorfl... | 0.749454 | 0.572185 |
from functools import lru_cache
from typing import List
from datetime import datetime
from fastapi import APIRouter, Depends, Query, Body
from api_v1.estimate.vbm import VBM
from api_v1.residual.residual import Residual
from api_v1.utils.s3_utils import S3
from api_v1.database.db import DatabaseAnalytic
import config
... | src/api_v1/api.py | from functools import lru_cache
from typing import List
from datetime import datetime
from fastapi import APIRouter, Depends, Query, Body
from api_v1.estimate.vbm import VBM
from api_v1.residual.residual import Residual
from api_v1.utils.s3_utils import S3
from api_v1.database.db import DatabaseAnalytic
import config
... | 0.629661 | 0.221193 |
import json, subprocess
from .... pyaz_utils import get_cli_name, get_params
def create(resource_namespace=None, resource_parent=None, resource_type=None, resource_group=None, autoscale_name, condition, scale, profile_name=None, cooldown=None, resource=None, timegrain=None):
params = get_params(locals())
c... | test/pyaz/monitor/autoscale/rule/__init__.py | import json, subprocess
from .... pyaz_utils import get_cli_name, get_params
def create(resource_namespace=None, resource_parent=None, resource_type=None, resource_group=None, autoscale_name, condition, scale, profile_name=None, cooldown=None, resource=None, timegrain=None):
params = get_params(locals())
c... | 0.226014 | 0.057652 |
import http
import requests
_HTTP_CODE_TO_EXCEPTION = {}
def _register(cls):
_HTTP_CODE_TO_EXCEPTION[cls.code] = cls
return cls
class APIError(Exception):
def __init__(self, msg, orig_error=None):
super().__init__(msg)
self.msg = msg
self.orig_error = orig_error
class Client... | mydjango/libs/exceptions.py | import http
import requests
_HTTP_CODE_TO_EXCEPTION = {}
def _register(cls):
_HTTP_CODE_TO_EXCEPTION[cls.code] = cls
return cls
class APIError(Exception):
def __init__(self, msg, orig_error=None):
super().__init__(msg)
self.msg = msg
self.orig_error = orig_error
class Client... | 0.387227 | 0.044101 |
# Imports
import logging
from requests.exceptions import HTTPError
from nltk.parse.corenlp import CoreNLPServer
from nltk.parse.corenlp import CoreNLPServerError
from nltk.parse.corenlp import CoreNLPDependencyParser
# Define type aliases for review summarization
Remark = tuple[str, str] # opinion-feature pair, exa... | summarizer/summarizer.py |
# Imports
import logging
from requests.exceptions import HTTPError
from nltk.parse.corenlp import CoreNLPServer
from nltk.parse.corenlp import CoreNLPServerError
from nltk.parse.corenlp import CoreNLPDependencyParser
# Define type aliases for review summarization
Remark = tuple[str, str] # opinion-feature pair, exa... | 0.821796 | 0.164785 |
from lib.web_data import WebData
def bitcore_claimer_line(n):
src_addr = n['src_addr']
txid = "<%s-airdrop-txid>" % src_addr
priv_key = "%s-private-key" % n['src_addr']
dst_addr = "bitcore-destination-address"
txindex = "<%s-airdrop-txindex>" % src_addr
satoshis = "<%s-airdrop-satoshis>" % src... | lib/coin/bitcore.py |
from lib.web_data import WebData
def bitcore_claimer_line(n):
src_addr = n['src_addr']
txid = "<%s-airdrop-txid>" % src_addr
priv_key = "%s-private-key" % n['src_addr']
dst_addr = "bitcore-destination-address"
txindex = "<%s-airdrop-txindex>" % src_addr
satoshis = "<%s-airdrop-satoshis>" % src... | 0.503662 | 0.15034 |
import os
import datetime
from pathlib import Path
import shutil
from pymediainfo import MediaInfo
from .core import *
class MediaObject(object):
def __init__(self, factory, json_data = None):
self._factory = factory
if json_data is None:
self.load_from_pvr()
else:
self.load_from_json(json_data)
def... | media_manager/mediaobject.py | import os
import datetime
from pathlib import Path
import shutil
from pymediainfo import MediaInfo
from .core import *
class MediaObject(object):
def __init__(self, factory, json_data = None):
self._factory = factory
if json_data is None:
self.load_from_pvr()
else:
self.load_from_json(json_data)
def... | 0.235548 | 0.095602 |
from collections import Counter, defaultdict
import csv
import requests
CSV_URL = 'https://raw.githubusercontent.com/pybites/SouthParkData/master/by-season/Season-{}.csv' # noqa E501
def get_season_csv_file(season):
"""Receives a season int, and downloads loads in its
corresponding CSV_URL"""
with re... | bites/bite090.py | from collections import Counter, defaultdict
import csv
import requests
CSV_URL = 'https://raw.githubusercontent.com/pybites/SouthParkData/master/by-season/Season-{}.csv' # noqa E501
def get_season_csv_file(season):
"""Receives a season int, and downloads loads in its
corresponding CSV_URL"""
with re... | 0.743075 | 0.355901 |