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 collections import namedtuple
from django.conf import settings
from django.db.models import ExpressionWrapper, F, FloatField, IntegerField
ReportColumnFormat = namedtuple('ReportColumnFormat', ['name', 'format', 'attr_name', 'order_field'])
DEFAULTS = {
'SPEEDINFO_TESTS': False,
'SPEEDINFO_CACHED_RESPON... | speedinfo/settings.py |
from collections import namedtuple
from django.conf import settings
from django.db.models import ExpressionWrapper, F, FloatField, IntegerField
ReportColumnFormat = namedtuple('ReportColumnFormat', ['name', 'format', 'attr_name', 'order_field'])
DEFAULTS = {
'SPEEDINFO_TESTS': False,
'SPEEDINFO_CACHED_RESPON... | 0.72952 | 0.084531 |
import os
import uuid
import tempfile
from pathlib import Path
import pytest
from cachetools import TTLCache
boto3 = pytest.importorskip('boto3')
moto = pytest.importorskip('moto')
@pytest.fixture(autouse=True)
def override_aws_credentials(monkeypatch):
with monkeypatch.context() as m:
m.setenv('AWS_AC... | tests/drivers/test_sqlite_remote.py | import os
import uuid
import tempfile
from pathlib import Path
import pytest
from cachetools import TTLCache
boto3 = pytest.importorskip('boto3')
moto = pytest.importorskip('moto')
@pytest.fixture(autouse=True)
def override_aws_credentials(monkeypatch):
with monkeypatch.context() as m:
m.setenv('AWS_AC... | 0.410047 | 0.22396 |
"""Holds the zazu repo subcommand."""
import zazu.imports
zazu.imports.lazy_import(locals(), [
'click',
'functools',
'git',
'os',
'semantic_version',
'socket',
'zazu.config',
'zazu.git_helper',
'zazu.github_helper',
'zazu.util',
])
__author__ = '<NAME>'
__copyright__ = 'Copyrigh... | zazu/repo/commands.py | """Holds the zazu repo subcommand."""
import zazu.imports
zazu.imports.lazy_import(locals(), [
'click',
'functools',
'git',
'os',
'semantic_version',
'socket',
'zazu.config',
'zazu.git_helper',
'zazu.github_helper',
'zazu.util',
])
__author__ = '<NAME>'
__copyright__ = 'Copyrigh... | 0.625896 | 0.143668 |
import math
class QueueNode:
def __init__(self, priority, data=None):
assert type(priority) is int and priority >= 0
self.priority = priority
self.data = data
def __repr__(self):
return str((self.priority, self.data))
class PriorityQueue:
def __init__(self, capacity=100... | python/28_binary_heap/priority_queue.py |
import math
class QueueNode:
def __init__(self, priority, data=None):
assert type(priority) is int and priority >= 0
self.priority = priority
self.data = data
def __repr__(self):
return str((self.priority, self.data))
class PriorityQueue:
def __init__(self, capacity=100... | 0.575469 | 0.376222 |
from datetime import datetime
from django.core.management.base import BaseCommand, CommandError
from legislators.models import State, CongressPerson, ExternalId, Term
from legislators.importer import load_legislators_current, load_legislators_past
date_format = '%Y-%m-%d'
def make_person(bio, name):
person = ... | capitolweb/legislators/management/commands/loadcongress.py | from datetime import datetime
from django.core.management.base import BaseCommand, CommandError
from legislators.models import State, CongressPerson, ExternalId, Term
from legislators.importer import load_legislators_current, load_legislators_past
date_format = '%Y-%m-%d'
def make_person(bio, name):
person = ... | 0.370567 | 0.10725 |
import argparse
import subprocess
from pathlib import Path
import os
import fcntl
import itertools
import sys
MODELS = {
"south-onlp": ["goldstone-platform", "goldstone-component-connection"],
"south-sonic": [
"goldstone-interfaces",
"goldstone-sonic",
"goldstone-vlan",
"goldst... | scripts/gs-yang.py |
import argparse
import subprocess
from pathlib import Path
import os
import fcntl
import itertools
import sys
MODELS = {
"south-onlp": ["goldstone-platform", "goldstone-component-connection"],
"south-sonic": [
"goldstone-interfaces",
"goldstone-sonic",
"goldstone-vlan",
"goldst... | 0.180107 | 0.119382 |
import math
import pickle
import numpy as np
from helper.utils import logger
from tasks import register_task
from tasks.base_task import BaseTask
from dataclass.configs import BaseDataClass
from dataclass.choices import BODY_CHOICES
from dataclasses import dataclass,field
from typing import Optional
from help... | tasks/body.py | import math
import pickle
import numpy as np
from helper.utils import logger
from tasks import register_task
from tasks.base_task import BaseTask
from dataclass.configs import BaseDataClass
from dataclass.choices import BODY_CHOICES
from dataclasses import dataclass,field
from typing import Optional
from help... | 0.537041 | 0.266285 |
import pandas as pd
import numpy as np
import math
from dateutil import relativedelta
import gc
import logging
from .demodulation import level_demodul_121,level_demodul_365
from ..config_features import NUMERICAL_FEATURES,CATEGORICAL_FEATURES,CAT_MAP
from ..config import ALL_STATIONS
def make_dataset(raw_hydro_df: p... | amurlevel_model/features/amur_features.py |
import pandas as pd
import numpy as np
import math
from dateutil import relativedelta
import gc
import logging
from .demodulation import level_demodul_121,level_demodul_365
from ..config_features import NUMERICAL_FEATURES,CATEGORICAL_FEATURES,CAT_MAP
from ..config import ALL_STATIONS
def make_dataset(raw_hydro_df: p... | 0.323915 | 0.53279 |
import cmudict
from difflib import get_close_matches
import warnings
CMU_dict = cmudict.dict()
CMU_keys = CMU_dict.keys()
def DEPREC_fuzzy_CMU_keys(word, tolerance=91):
"""
Returns a list of tuples with fuzzy matching string in tuple[0] and similarity score in tuple[1].
ex: [(fuzzy_string1, similarity_... | FuzzyTerm.py | import cmudict
from difflib import get_close_matches
import warnings
CMU_dict = cmudict.dict()
CMU_keys = CMU_dict.keys()
def DEPREC_fuzzy_CMU_keys(word, tolerance=91):
"""
Returns a list of tuples with fuzzy matching string in tuple[0] and similarity score in tuple[1].
ex: [(fuzzy_string1, similarity_... | 0.609873 | 0.394901 |
from pdf2image import convert_from_path
from datetime import date
import urllib.request
import json
import os
# Average dominant color
import cv2 as cv
import numpy as np
import matplotlib.pyplot as plt
import PIL
# Accepts a string with the location of the params_file
# Returns a dictionary with the parameters
def ... | utils.py | from pdf2image import convert_from_path
from datetime import date
import urllib.request
import json
import os
# Average dominant color
import cv2 as cv
import numpy as np
import matplotlib.pyplot as plt
import PIL
# Accepts a string with the location of the params_file
# Returns a dictionary with the parameters
def ... | 0.326057 | 0.26405 |
import shutil
from os import path
from typing import List, Tuple
from urllib.request import urlopen
import subprocess
import click
here = path.abspath(path.dirname(__file__))
PACKAGE = 'hmsclient'
SUBPACKAGE = 'genthrift'
generated = 'gen-py'
FB303_URL = 'https://raw.githubusercontent.com/apache/thrift/0.11.0/contr... | generate.py | import shutil
from os import path
from typing import List, Tuple
from urllib.request import urlopen
import subprocess
import click
here = path.abspath(path.dirname(__file__))
PACKAGE = 'hmsclient'
SUBPACKAGE = 'genthrift'
generated = 'gen-py'
FB303_URL = 'https://raw.githubusercontent.com/apache/thrift/0.11.0/contr... | 0.494141 | 0.074366 |
import os
# Make sure we're running from the spam/ directory
if os.path.basename(os.getcwd()) == "":
os.chdir("")
from utils import load_unlabeled_spam_dataset
df_train = load_unlabeled_spam_dataset()
ABSTAIN = -1
NOT_SPAM = 0
SPAM = 1
from snorkel.labeling import labeling_function
@labeling_function()
def lf... | Intro_Snorkel/1gettingStart.py | import os
# Make sure we're running from the spam/ directory
if os.path.basename(os.getcwd()) == "":
os.chdir("")
from utils import load_unlabeled_spam_dataset
df_train = load_unlabeled_spam_dataset()
ABSTAIN = -1
NOT_SPAM = 0
SPAM = 1
from snorkel.labeling import labeling_function
@labeling_function()
def lf... | 0.701509 | 0.289296 |
import yaml
from models import VGGNet
import pandas as pd
import os
from random import shuffle
from glob import glob
def get_model(input_shape, setting):
setting['nc'] = len(setting['classes'])
network = VGGNet(name='vgg16', ch=input_shape[-1], imgsz=input_shape, setting=setting)
return network
... | torch/kaggle_RSNA/vgg.py | import yaml
from models import VGGNet
import pandas as pd
import os
from random import shuffle
from glob import glob
def get_model(input_shape, setting):
setting['nc'] = len(setting['classes'])
network = VGGNet(name='vgg16', ch=input_shape[-1], imgsz=input_shape, setting=setting)
return network
... | 0.493409 | 0.193357 |
from __future__ import absolute_import
from stablemanager.models.api_response import ApiResponse
from stablemanager.models.association import Association
from stablemanager.models.horse import Horse
from stablemanager.models.schedule_summary import ScheduleSummary
from . import BaseTestCase
from six import BytesIO
fr... | api/stablemanager/test/test_horse_controller.py |
from __future__ import absolute_import
from stablemanager.models.api_response import ApiResponse
from stablemanager.models.association import Association
from stablemanager.models.horse import Horse
from stablemanager.models.schedule_summary import ScheduleSummary
from . import BaseTestCase
from six import BytesIO
fr... | 0.769167 | 0.249953 |
from typing import Any, Dict, List, Optional, Tuple, Union
from ....core import get_namespace as get_services_namespace
from ....core import run_request
from ....core import same_doc_as
from ..models import ErrorEntity
from ..models import StoreBackupInfo
from ..models import StoreCreate
from ..models import StoreIn... | accelbyte_py_sdk/api/platform/wrappers/_store.py |
from typing import Any, Dict, List, Optional, Tuple, Union
from ....core import get_namespace as get_services_namespace
from ....core import run_request
from ....core import same_doc_as
from ..models import ErrorEntity
from ..models import StoreBackupInfo
from ..models import StoreCreate
from ..models import StoreIn... | 0.754282 | 0.148973 |
import pygame as pg
import os
import constants as c
class GameStatesManager:
"""
Control class for managing game states.
"""
def __init__(self):
self.state_dict = {}
self.state_name = None
self.state = None
def setup(self, state_dict, start_state):
... | quest/tools.py | import pygame as pg
import os
import constants as c
class GameStatesManager:
"""
Control class for managing game states.
"""
def __init__(self):
self.state_dict = {}
self.state_name = None
self.state = None
def setup(self, state_dict, start_state):
... | 0.465873 | 0.250148 |
from pygraphblas import *
from pygraphblas.types import BOOL
from pyformlang.regular_expression import Regex
class Graph:
def __init__(self):
self.labels_adj = dict()
self.start_states = set()
self.final_states = set()
self.size = 0
def set(self, key, value):
self.labe... | src/graph.py | from pygraphblas import *
from pygraphblas.types import BOOL
from pyformlang.regular_expression import Regex
class Graph:
def __init__(self):
self.labels_adj = dict()
self.start_states = set()
self.final_states = set()
self.size = 0
def set(self, key, value):
self.labe... | 0.585812 | 0.387111 |
import itertools
from sqlalchemy.ext.associationproxy import association_proxy
from sqlalchemy.ext.declarative import declared_attr
from anthill.framework.db import db
"""
models.py features a basic, non-hierarchical, non-constrained RBAC data model,
also known as a flat model
-- Ref: http://csrc.nist.gov/rbac/sandhu... | auth/backends/db/models.py | import itertools
from sqlalchemy.ext.associationproxy import association_proxy
from sqlalchemy.ext.declarative import declared_attr
from anthill.framework.db import db
"""
models.py features a basic, non-hierarchical, non-constrained RBAC data model,
also known as a flat model
-- Ref: http://csrc.nist.gov/rbac/sandhu... | 0.61832 | 0.20949 |
import re
def getVisibleLength(text):
# remove ansi escape sequences (coloring!) before getting the length
ansi_escape = re.compile(r'(?:\x1b[^m]*m|\x0f)', re.UNICODE)
return len(ansi_escape.sub('', text).decode('utf-8'))
class Columnar(object):
pos = 0
"""The internal cursor"""
headers = []... | qi/columnar.py | import re
def getVisibleLength(text):
# remove ansi escape sequences (coloring!) before getting the length
ansi_escape = re.compile(r'(?:\x1b[^m]*m|\x0f)', re.UNICODE)
return len(ansi_escape.sub('', text).decode('utf-8'))
class Columnar(object):
pos = 0
"""The internal cursor"""
headers = []... | 0.444685 | 0.421611 |
from app import app, mongo
from bson.json_util import dumps
from bson.objectid import ObjectId
from flask import jsonify, request
from werkzeug.security import generate_password_hash, check_password_hash
# Endpoint for creating new user
@app.route('/add', methods=['POST'])
def add_user():
_json = request.json
... | main.py | from app import app, mongo
from bson.json_util import dumps
from bson.objectid import ObjectId
from flask import jsonify, request
from werkzeug.security import generate_password_hash, check_password_hash
# Endpoint for creating new user
@app.route('/add', methods=['POST'])
def add_user():
_json = request.json
... | 0.326593 | 0.046747 |
import errno
from pathlib import Path
import stat
from mock import patch, call, mock_open
from pytest import raises
import fake_super
def assertSimilar(a, b):
if a != b:
raise AssertionError("Assertion failed:"
" Value mismatch: %r (%s) != %r (%s)"
... | tests/test_30_restore.py | import errno
from pathlib import Path
import stat
from mock import patch, call, mock_open
from pytest import raises
import fake_super
def assertSimilar(a, b):
if a != b:
raise AssertionError("Assertion failed:"
" Value mismatch: %r (%s) != %r (%s)"
... | 0.431345 | 0.118845 |
import datetime
import os
import unittest
import buildscripts.ciconfig.evergreen as _evergreen
# pylint: disable=missing-docstring,protected-access
TEST_FILE_PATH = os.path.join(os.path.dirname(__file__), "evergreen.yml")
class TestEvergreenProjectConfig(unittest.TestCase):
"""Unit tests for the Evergreen for... | buildscripts/tests/ciconfig/test_evergreen.py |
import datetime
import os
import unittest
import buildscripts.ciconfig.evergreen as _evergreen
# pylint: disable=missing-docstring,protected-access
TEST_FILE_PATH = os.path.join(os.path.dirname(__file__), "evergreen.yml")
class TestEvergreenProjectConfig(unittest.TestCase):
"""Unit tests for the Evergreen for... | 0.589835 | 0.498047 |
import argparse
import sys
from biocode import utils
def main():
parser = argparse.ArgumentParser( description='Report coverage gaps/dips from a samtools mpileup file')
## output file to be written
parser.add_argument('-i', '--input_file', type=str, required=True, help='Path to an input mpileup file to ... | sam_bam/report_coverage_gaps.py | import argparse
import sys
from biocode import utils
def main():
parser = argparse.ArgumentParser( description='Report coverage gaps/dips from a samtools mpileup file')
## output file to be written
parser.add_argument('-i', '--input_file', type=str, required=True, help='Path to an input mpileup file to ... | 0.285372 | 0.231603 |
import sqlalchemy as sql
import inflection
from sqlalchemy.types import INT, VARCHAR, FLOAT
from sqlalchemy.sql import func as db_func
from schools3.data.features.features_table import FeaturesTable
from schools3.config.data import db_tables
from schools3.config.data.features import features_config
from schools3.confi... | schools3/data/features/absence_features.py | import sqlalchemy as sql
import inflection
from sqlalchemy.types import INT, VARCHAR, FLOAT
from sqlalchemy.sql import func as db_func
from schools3.data.features.features_table import FeaturesTable
from schools3.config.data import db_tables
from schools3.config.data.features import features_config
from schools3.confi... | 0.563498 | 0.200421 |
import itertools
import regex as re
import warnings
from collections import namedtuple
Match = namedtuple('Match', 'start end cls')
MARKERS = [chr(x) for x in range(0x4DC0, 0x4DFF)]
def generate_options(path: str = 'elisa_dnt/rules.ini') -> dict:
colors = [
'#e3f2fd',
'#bbdefb',
'#90caf... | elisa_dnt/utils.py |
import itertools
import regex as re
import warnings
from collections import namedtuple
Match = namedtuple('Match', 'start end cls')
MARKERS = [chr(x) for x in range(0x4DC0, 0x4DFF)]
def generate_options(path: str = 'elisa_dnt/rules.ini') -> dict:
colors = [
'#e3f2fd',
'#bbdefb',
'#90caf... | 0.310172 | 0.233422 |
from FEMur import *
import sys
import sympy as sy
import numpy as np
import scipy as sc
import matplotlib.pyplot as plt
import matplotlib.tri as tri
import scipy.interpolate
from math import ceil
class Solver(object):
'''
2-dimensional solver top class.
Provides common initialization to all child solver... | FEMur/solver2D.py | from FEMur import *
import sys
import sympy as sy
import numpy as np
import scipy as sc
import matplotlib.pyplot as plt
import matplotlib.tri as tri
import scipy.interpolate
from math import ceil
class Solver(object):
'''
2-dimensional solver top class.
Provides common initialization to all child solver... | 0.429908 | 0.35488 |
import logging
from typing import TYPE_CHECKING, List, Optional, Tuple, Union
import pandas as pd
from datasets import Mode
from datasets._typing import ColumnNames, DataFrameType
from datasets.context import Context
from datasets.dataset_plugin import DatasetPlugin
from datasets.exceptions import InvalidOperationExc... | datasets/plugins/batch/batch_dataset.py | import logging
from typing import TYPE_CHECKING, List, Optional, Tuple, Union
import pandas as pd
from datasets import Mode
from datasets._typing import ColumnNames, DataFrameType
from datasets.context import Context
from datasets.dataset_plugin import DatasetPlugin
from datasets.exceptions import InvalidOperationExc... | 0.837288 | 0.237886 |
import numpy as np
from mxnet import ndarray as nd
def calculate_indexes(current_index, shape, gradients_cumulative, coordinates):
if len(coordinates) == 1:
return gradients_cumulative[current_index] + coordinates[0]
if len(coordinates) == 2:
return gradients_cumulative[current_index] + (coord... | pai/pouw/message_map.py | import numpy as np
from mxnet import ndarray as nd
def calculate_indexes(current_index, shape, gradients_cumulative, coordinates):
if len(coordinates) == 1:
return gradients_cumulative[current_index] + coordinates[0]
if len(coordinates) == 2:
return gradients_cumulative[current_index] + (coord... | 0.515132 | 0.688768 |
import os
import re
import subprocess
from time import sleep
class File(object):
def __init__(self, path):
self.path = path
self.last_update = None
self.existed = True
def updated(self):
if self.existed and not os.path.exists(self.path):
self.existed = ... | docs/monitor.py | import os
import re
import subprocess
from time import sleep
class File(object):
def __init__(self, path):
self.path = path
self.last_update = None
self.existed = True
def updated(self):
if self.existed and not os.path.exists(self.path):
self.existed = ... | 0.1151 | 0.055541 |
# Licensed under the Apache License, Version 2.0 (the "License");
# you may not use this file except in compliance with the License.
# You may obtain a copy of the License at
# http://www.apache.org/licenses/LICENSE-2.0
# Unless required by applicable law or agreed to in writing, software
# distributed under the Lic... | bentoml/server/gunicorn_marshal_server.py |
# Licensed under the Apache License, Version 2.0 (the "License");
# you may not use this file except in compliance with the License.
# You may obtain a copy of the License at
# http://www.apache.org/licenses/LICENSE-2.0
# Unless required by applicable law or agreed to in writing, software
# distributed under the Lic... | 0.863276 | 0.176122 |
from aio2ch import (
Api,
Board,
Thread,
Image,
Video,
Sticker
)
import pytest
@pytest.fixture
async def client():
async with Api(timeout=10.0) as api_client:
yield api_client
@pytest.fixture
async def client_ujson():
from ujson import loads as ujson_loads
async with Ap... | tests/conftest.py | from aio2ch import (
Api,
Board,
Thread,
Image,
Video,
Sticker
)
import pytest
@pytest.fixture
async def client():
async with Api(timeout=10.0) as api_client:
yield api_client
@pytest.fixture
async def client_ujson():
from ujson import loads as ujson_loads
async with Ap... | 0.387574 | 0.32017 |
import torch
import numpy as np
from torch import nn
class BatchRelationalModule(nn.Module):
def __init__(self, input_feature_dim, use_coordinates=False, num_layers=2, num_units=64):
super(BatchRelationalModule, self).__init__()
self.input_feature_dim = input_feature_dim
self.block_dict = ... | pyvideoai/models/epic/BatchRelationalModule1D.py | import torch
import numpy as np
from torch import nn
class BatchRelationalModule(nn.Module):
def __init__(self, input_feature_dim, use_coordinates=False, num_layers=2, num_units=64):
super(BatchRelationalModule, self).__init__()
self.input_feature_dim = input_feature_dim
self.block_dict = ... | 0.792745 | 0.475727 |
r"""
A set of utilities to create/open postgres databases for SQLAlchemy. Note, prior to running this scripts, an empty
database should be available. This may be created with the following instructions:
postgres=# create database <db_name> owner=<user>;
@file sessions_postgres.py
@author <NAME>, <NAME>
"""
from ... | lib/m4db_database/sessions_postgres.py | r"""
A set of utilities to create/open postgres databases for SQLAlchemy. Note, prior to running this scripts, an empty
database should be available. This may be created with the following instructions:
postgres=# create database <db_name> owner=<user>;
@file sessions_postgres.py
@author <NAME>, <NAME>
"""
from ... | 0.684475 | 0.180323 |
from time import sleep
from schedule import clear, every, get_jobs, run_pending
from src.config.constants import INTERNAL_SCHEDULING
from src.scripts.checkin import random_checkin
from src.scripts.checkout import random_checkout
from src.utils.logger import PlxLogger
from src.utils.plextime_session import PlextimeSes... | start.py | from time import sleep
from schedule import clear, every, get_jobs, run_pending
from src.config.constants import INTERNAL_SCHEDULING
from src.scripts.checkin import random_checkin
from src.scripts.checkout import random_checkout
from src.utils.logger import PlxLogger
from src.utils.plextime_session import PlextimeSes... | 0.457864 | 0.207576 |
import os
import pickle
from astropy.table import Table
from jianbing import scatter
from jianbing import wlensing
TOPN_DIR = '/tigress/sh19/work/topn/'
# Lensing data using medium photo-z quality cut
s16a_lensing = os.path.join(TOPN_DIR, 'prepare', 's16a_weak_lensing_medium.hdf5')
# Random
s16a_rand = Table.read(... | script/compute_dsigma_galaxies.py | import os
import pickle
from astropy.table import Table
from jianbing import scatter
from jianbing import wlensing
TOPN_DIR = '/tigress/sh19/work/topn/'
# Lensing data using medium photo-z quality cut
s16a_lensing = os.path.join(TOPN_DIR, 'prepare', 's16a_weak_lensing_medium.hdf5')
# Random
s16a_rand = Table.read(... | 0.456894 | 0.20199 |
import bleach
from flask import Markup
def format_approve_button(s):
messages = {
"INTERNAL_REVIEW": "Save & Send to review",
"DEPARTMENT_REVIEW": "Send to department for review",
"APPROVED": "Approve for publishing",
}
return messages.get(s, "")
def format_friendly_date(dat... | application/cms/filters.py | import bleach
from flask import Markup
def format_approve_button(s):
messages = {
"INTERNAL_REVIEW": "Save & Send to review",
"DEPARTMENT_REVIEW": "Send to department for review",
"APPROVED": "Approve for publishing",
}
return messages.get(s, "")
def format_friendly_date(dat... | 0.569853 | 0.231343 |
import PyQt5.QtWidgets as Qtw
import PyQt5.QtGui as QtGui
import PyQt5.QtCore as QtCore
from PyQt5.QtCore import Qt
from widgets.flow_layout import FlowLayout
class LabelWidget(Qtw.QLabel):
"""
A widget displaying a single label, with it's color
"""
clicked = QtCore.pyqtSignal()
def __init__(se... | widgets/labels.py |
import PyQt5.QtWidgets as Qtw
import PyQt5.QtGui as QtGui
import PyQt5.QtCore as QtCore
from PyQt5.QtCore import Qt
from widgets.flow_layout import FlowLayout
class LabelWidget(Qtw.QLabel):
"""
A widget displaying a single label, with it's color
"""
clicked = QtCore.pyqtSignal()
def __init__(se... | 0.555918 | 0.152158 |
from typing import Tuple, Dict
import numpy as np
from qecsim.model import Decoder
from ...models import ToricCode3D
from ...models import Toric3DPauli
Indexer = Dict[Tuple[int, int, int], int]
class SweepDecoder3D(Decoder):
label: str = 'Toric 3D Sweep Decoder'
_rng: np.random.Generator
max_sweep_factor... | bn3d/decoders/sweepmatch/_sweep_decoder_3d.py | from typing import Tuple, Dict
import numpy as np
from qecsim.model import Decoder
from ...models import ToricCode3D
from ...models import Toric3DPauli
Indexer = Dict[Tuple[int, int, int], int]
class SweepDecoder3D(Decoder):
label: str = 'Toric 3D Sweep Decoder'
_rng: np.random.Generator
max_sweep_factor... | 0.861713 | 0.567637 |
import numpy as np
import pandas as pd
from sklearn.preprocessing import MinMaxScaler
from math import *
from decimal import Decimal
from scipy.spatial import distance
def get_all_params(items):
all_params = {}
for item in items:
params = item['PARAMS']
for param in params:
if all_... | distance.py |
import numpy as np
import pandas as pd
from sklearn.preprocessing import MinMaxScaler
from math import *
from decimal import Decimal
from scipy.spatial import distance
def get_all_params(items):
all_params = {}
for item in items:
params = item['PARAMS']
for param in params:
if all_... | 0.483648 | 0.334562 |
import os
# Build paths inside the project like this: os.path.join(BASE_DIR, ...)
BASE_DIR = os.path.dirname(os.path.dirname(os.path.abspath(__file__)))
MAIN_DIR = os.path.dirname(os.path.dirname(os.path.dirname(__file__)))
SECRET_KEY = 'secret_key'
GOOGLE_API_KEY = 'api_key'
# General security settings
ALLOWED_HOST... | dandeliondiary/dandeliondiary/settings/base.py | import os
# Build paths inside the project like this: os.path.join(BASE_DIR, ...)
BASE_DIR = os.path.dirname(os.path.dirname(os.path.abspath(__file__)))
MAIN_DIR = os.path.dirname(os.path.dirname(os.path.dirname(__file__)))
SECRET_KEY = 'secret_key'
GOOGLE_API_KEY = 'api_key'
# General security settings
ALLOWED_HOST... | 0.378 | 0.052279 |
from __future__ import generator_stop
import csv
import os
from typing import Dict, List, TextIO
import warnings
from ..exceptions import WriteIsatabException, WriteIsatabWarning
from ..constants import investigation_headers
from .helpers import is_ontology_term_ref
from . import models
__author__ = (
"<NAME> <<... | altamisa/isatab/write_investigation.py | from __future__ import generator_stop
import csv
import os
from typing import Dict, List, TextIO
import warnings
from ..exceptions import WriteIsatabException, WriteIsatabWarning
from ..constants import investigation_headers
from .helpers import is_ontology_term_ref
from . import models
__author__ = (
"<NAME> <<... | 0.493164 | 0.22627 |
import logging
import requests
import azure.cosmos.cosmos_client as cosmos_client
import azure.cosmos.errors as errors
import azure.cosmos.documents as documents
import time
from . import models
def load_collection(url, api_key, db_id, collection_id, rows, version):
loader = Loader(url, api_key, db_id, collectio... | SubjectBuilder/database.py | import logging
import requests
import azure.cosmos.cosmos_client as cosmos_client
import azure.cosmos.errors as errors
import azure.cosmos.documents as documents
import time
from . import models
def load_collection(url, api_key, db_id, collection_id, rows, version):
loader = Loader(url, api_key, db_id, collectio... | 0.446977 | 0.096068 |
from channels.generic.websocket import JsonWebsocketConsumer
from asgiref.sync import async_to_sync
from .models import Topic, ChatMessage
from django.contrib.auth.models import User
from django.utils.html import escape
from django.core import serializers
import markdown
import bleach
import re
from django.conf import ... | mainapp/consumers.py | from channels.generic.websocket import JsonWebsocketConsumer
from asgiref.sync import async_to_sync
from .models import Topic, ChatMessage
from django.contrib.auth.models import User
from django.utils.html import escape
from django.core import serializers
import markdown
import bleach
import re
from django.conf import ... | 0.331661 | 0.057071 |
from selenium import webdriver
from bs4 import BeautifulSoup
import string
class StockMarket(object):
def __init__(self, driver, symbols_file=None):
super(StockMarket, self).__init__()
self.driver = driver
if symbols_file is not None:
self.symbols = self.stock_symbols_from_file... | Classes/market.py | from selenium import webdriver
from bs4 import BeautifulSoup
import string
class StockMarket(object):
def __init__(self, driver, symbols_file=None):
super(StockMarket, self).__init__()
self.driver = driver
if symbols_file is not None:
self.symbols = self.stock_symbols_from_file... | 0.428473 | 0.091382 |
from networkx.exception import NetworkXError
import matplotlib.pyplot as plt
class Graph(object):
node_dict_factory = dict
node_attr_dict_factory = dict
adjlist_outer_dict_factory = dict
adjlist_inner_dict_factory = dict
edge_attr_dict_factory = dict
graph_attr_dict_factory = dict
... | graphcu/graph.py | from networkx.exception import NetworkXError
import matplotlib.pyplot as plt
class Graph(object):
node_dict_factory = dict
node_attr_dict_factory = dict
adjlist_outer_dict_factory = dict
adjlist_inner_dict_factory = dict
edge_attr_dict_factory = dict
graph_attr_dict_factory = dict
... | 0.369543 | 0.19235 |
from collections import namedtuple
import logging
import re
import mock
import socket
import sys
from calico.felix.config import Config, ConfigException
if sys.version_info < (2, 7):
import unittest2 as unittest
else:
import unittest
# Logger
log = logging.getLogger(__name__)
class TestConfig(unittest.TestCa... | calico/felix/test/test_config.py | from collections import namedtuple
import logging
import re
import mock
import socket
import sys
from calico.felix.config import Config, ConfigException
if sys.version_info < (2, 7):
import unittest2 as unittest
else:
import unittest
# Logger
log = logging.getLogger(__name__)
class TestConfig(unittest.TestCa... | 0.445288 | 0.179315 |
from ovim.log import logger
from urllib import request
import json
import tarfile
import tempfile
import os
class UbuntuRunner:
homedir = os.path.abspath(os.getenv('HOME'))
local_bin = os.path.join(homedir, '.local', 'bin')
@classmethod
def check_env(cls):
if os.system("curl --version"):
... | ovim/python3/ovim/platform/ubuntu.py | from ovim.log import logger
from urllib import request
import json
import tarfile
import tempfile
import os
class UbuntuRunner:
homedir = os.path.abspath(os.getenv('HOME'))
local_bin = os.path.join(homedir, '.local', 'bin')
@classmethod
def check_env(cls):
if os.system("curl --version"):
... | 0.30054 | 0.04807 |
import numpy as np
import os
import subprocess
import shutil
import multiprocessing
import sys
import copy
from collections import OrderedDict
from pyfoamsetup.coreLibrary import *
import pyfoamsetup.coreLibrary.CaseSetup as CaseSetup
class PropellerSimulation(CaseSetup.CaseSetup):
def __init__(self, runName, c, D, ... | pyfoamsetup/PropellerSimulation/PropellerSimulation.py | import numpy as np
import os
import subprocess
import shutil
import multiprocessing
import sys
import copy
from collections import OrderedDict
from pyfoamsetup.coreLibrary import *
import pyfoamsetup.coreLibrary.CaseSetup as CaseSetup
class PropellerSimulation(CaseSetup.CaseSetup):
def __init__(self, runName, c, D, ... | 0.356111 | 0.241042 |
from numpy.linalg import norm
from numpy import savetxt
from .FDGradient import FDGradient
class FDValidGrad(object):
"""
Finite differences gradient calculation and validation.
"""
def __init__(self, scheme_order, f_pointer, df_pointer, fd_step=1e-6, bounds=None):
"""
Constructor
... | sos_trades_core/tools/grad_solvers/validgrad/FDValidGrad.py |
from numpy.linalg import norm
from numpy import savetxt
from .FDGradient import FDGradient
class FDValidGrad(object):
"""
Finite differences gradient calculation and validation.
"""
def __init__(self, scheme_order, f_pointer, df_pointer, fd_step=1e-6, bounds=None):
"""
Constructor
... | 0.830972 | 0.476519 |
import curses
import logging
import os
from vindauga.constants.command_codes import cmPaste
from vindauga.constants.event_codes import evMouseUp, evKeyDown, evMouseDown, evCommand
from vindauga.constants.option_flags import ofSelectable
from vindauga.constants.keys import *
from vindauga.events.event import Event
from... | vindauga/terminal/terminal_view.py | import curses
import logging
import os
from vindauga.constants.command_codes import cmPaste
from vindauga.constants.event_codes import evMouseUp, evKeyDown, evMouseDown, evCommand
from vindauga.constants.option_flags import ofSelectable
from vindauga.constants.keys import *
from vindauga.events.event import Event
from... | 0.40157 | 0.095265 |
from random import random
from math import log
import numpy as np
def intervalq(point, bounds):
'''find which interval a point lies in given interval bounds
input: point - number to identify bucket for
bounds - list of increasing bucket bounds including ends
output: index such that bo... | keep_backend/privacy/map.py |
from random import random
from math import log
import numpy as np
def intervalq(point, bounds):
'''find which interval a point lies in given interval bounds
input: point - number to identify bucket for
bounds - list of increasing bucket bounds including ends
output: index such that bo... | 0.866881 | 0.760428 |
from constants import *
import sys
import cv2
if sys.version_info[0] == 2:
# Workaround for https://github.com/PythonCharmers/python-future/issues/262
from Tkinter import *
else:
from tkinter import *
from PIL import ImageTk
from PIL import Image
import matplotlib, sys
import matplotlib.pyplot as plt
matplotl... | python/display.py | from constants import *
import sys
import cv2
if sys.version_info[0] == 2:
# Workaround for https://github.com/PythonCharmers/python-future/issues/262
from Tkinter import *
else:
from tkinter import *
from PIL import ImageTk
from PIL import Image
import matplotlib, sys
import matplotlib.pyplot as plt
matplotl... | 0.322846 | 0.25393 |
import warnings
import pulumi
import pulumi.runtime
from typing import Any, Mapping, Optional, Sequence, Union, overload
from .. import _utilities
from . import outputs
from ._inputs import *
__all__ = ['DomainArgs', 'Domain']
@pulumi.input_type
class DomainArgs:
def __init__(__self__, *,
server... | sdk/python/pulumi_aws_native/voiceid/domain.py |
import warnings
import pulumi
import pulumi.runtime
from typing import Any, Mapping, Optional, Sequence, Union, overload
from .. import _utilities
from . import outputs
from ._inputs import *
__all__ = ['DomainArgs', 'Domain']
@pulumi.input_type
class DomainArgs:
def __init__(__self__, *,
server... | 0.861684 | 0.0584 |
import pygame as pg
import numpy as np
import pickle
import time
import itertools
from multiprocessing import Pipe, Process
from importlib import reload
import user_settings as cng
from states import state_config as state_cng
from instances import instance_config as game_cng
from states import state
fro... | states/game_state_online.py | import pygame as pg
import numpy as np
import pickle
import time
import itertools
from multiprocessing import Pipe, Process
from importlib import reload
import user_settings as cng
from states import state_config as state_cng
from instances import instance_config as game_cng
from states import state
fro... | 0.169922 | 0.106412 |
import os
import re
try:
from maya import mel
from maya import cmds
isMaya = True
except ImportError:
isMaya = False
def onMayaDroppedPythonFile(*args, **kwargs):
pass
def _onMayaDropped():
if isMaya:
main()
def getNamePathLang(dir):
dirItemList = os.listdir(dir)
namePat... | hkTools.py |
import os
import re
try:
from maya import mel
from maya import cmds
isMaya = True
except ImportError:
isMaya = False
def onMayaDroppedPythonFile(*args, **kwargs):
pass
def _onMayaDropped():
if isMaya:
main()
def getNamePathLang(dir):
dirItemList = os.listdir(dir)
namePat... | 0.477067 | 0.096153 |
import cv2, math, string, numpy
image = cv2.imread('test_resize.png', -1)
image = numpy.array(image).tolist()
digits = string.digits + string.ascii_letters
#generic helper functions
def dictToArr(dictionary):
arr = [None]*len(dictionary)
for d in dictionary:
arr[dictionary[d]-1] = d
retur... | pictobit.py | import cv2, math, string, numpy
image = cv2.imread('test_resize.png', -1)
image = numpy.array(image).tolist()
digits = string.digits + string.ascii_letters
#generic helper functions
def dictToArr(dictionary):
arr = [None]*len(dictionary)
for d in dictionary:
arr[dictionary[d]-1] = d
retur... | 0.227298 | 0.482917 |
from flask import Flask, request, redirect, session, url_for
from fhirclient import client
from fhirclient.models.medicationorder import MedicationOrder
settings = {
'app_id': 'my_web_app'
}
application = app = Flask('wsgi')
app.debug = True
app.secret_key = 'khsathdnsthjre' # CHANGE ME
def _save_state(state):... | rest-app/app.py |
from flask import Flask, request, redirect, session, url_for
from fhirclient import client
from fhirclient.models.medicationorder import MedicationOrder
settings = {
'app_id': 'my_web_app'
}
application = app = Flask('wsgi')
app.debug = True
app.secret_key = 'khsathdnsthjre' # CHANGE ME
def _save_state(state):... | 0.349533 | 0.050168 |
import numpy as np
def relu(x):
return np.maximum(0, x)
def drelu(x):
return 1 * (x > 0)
def output_layer_activation(x):
return x
def output_layer_activation_derivative(x):
return 1
class NeuralNet():
def __init__(self, X_train, y_train, hidden_layer, lr, ep... | irisneuralnet.py | import numpy as np
def relu(x):
return np.maximum(0, x)
def drelu(x):
return 1 * (x > 0)
def output_layer_activation(x):
return x
def output_layer_activation_derivative(x):
return 1
class NeuralNet():
def __init__(self, X_train, y_train, hidden_layer, lr, ep... | 0.813498 | 0.354126 |
import json
import logging
import pathlib
import shutil
from django.core.mail import send_mail
import environ
import requests
from admin_extension.models import Files
from app_market.models import Catalog, Category, Good, MediaFiles, Seller
from transliterate import translit
from market_place_proj.celery import app
... | market_place_proj/admin_extension/tasks.py | import json
import logging
import pathlib
import shutil
from django.core.mail import send_mail
import environ
import requests
from admin_extension.models import Files
from app_market.models import Catalog, Category, Good, MediaFiles, Seller
from transliterate import translit
from market_place_proj.celery import app
... | 0.17441 | 0.074534 |
import botocore
from click.testing import CliRunner
from s3_credentials.cli import cli
import json
import pytest
from unittest.mock import call, Mock
def test_whoami(mocker):
boto3 = mocker.patch("boto3.client")
boto3().get_user.return_value = {"User": {"username": "name"}}
runner = CliRunner()
with r... | tests/test_s3_credentials.py | import botocore
from click.testing import CliRunner
from s3_credentials.cli import cli
import json
import pytest
from unittest.mock import call, Mock
def test_whoami(mocker):
boto3 = mocker.patch("boto3.client")
boto3().get_user.return_value = {"User": {"username": "name"}}
runner = CliRunner()
with r... | 0.416915 | 0.394726 |
# StatsTest must be imported first in order to get proper ndb monkeypatching.
from stats.analysis import PatchsetReference
from stats.trybot_stats import TrybotReference
from stats.test.stats_test import StatsTest
passed = 'JOB_SUCCEEDED'
failed = 'JOB_FAILED'
running = 'JOB_RUNNING'
test_builder_ppp = {
'maste... | appengine/chromium_cq_status/stats/test/trybot_stats_test.py |
# StatsTest must be imported first in order to get proper ndb monkeypatching.
from stats.analysis import PatchsetReference
from stats.trybot_stats import TrybotReference
from stats.test.stats_test import StatsTest
passed = 'JOB_SUCCEEDED'
failed = 'JOB_FAILED'
running = 'JOB_RUNNING'
test_builder_ppp = {
'maste... | 0.583322 | 0.461017 |
import sys
import os
from random import *
# This file is what it is, I guess I might be able to do this another way, with
# classes maybe (??) But for now, I'm starting out and this works, and I can
# Understand how.
def toInt(In):
'''
this is so if you just write for example d20. it turns the '' in... | Dice Roller 1.2 Eng/Funcs.py | import sys
import os
from random import *
# This file is what it is, I guess I might be able to do this another way, with
# classes maybe (??) But for now, I'm starting out and this works, and I can
# Understand how.
def toInt(In):
'''
this is so if you just write for example d20. it turns the '' in... | 0.309963 | 0.297572 |
import random
from builtins import range
from .facecube import FaceCube
from .cubiecube import CubieCube
from .coordcube import CoordCube
from .color import colors
def verify(s):
"""
Check if the cube definition string s represents a solvable cube.
@param s is the cube definition string , see {@link Fac... | kociemba/pykociemba/tools.py | import random
from builtins import range
from .facecube import FaceCube
from .cubiecube import CubieCube
from .coordcube import CoordCube
from .color import colors
def verify(s):
"""
Check if the cube definition string s represents a solvable cube.
@param s is the cube definition string , see {@link Fac... | 0.772187 | 0.526221 |
class ListNode:
def __init__(self, key, val):
self.key = key
self.val = val
self.next = None
class LRUCache:
def __init__(self, capacity: int):
self.capacity = capacity
self.head = None
self.tail = None
self.data = dict()
def moveToTail(self, node... | leetcode/146-lru-cache.py | class ListNode:
def __init__(self, key, val):
self.key = key
self.val = val
self.next = None
class LRUCache:
def __init__(self, capacity: int):
self.capacity = capacity
self.head = None
self.tail = None
self.data = dict()
def moveToTail(self, node... | 0.684264 | 0.364919 |
import json
from datetime import datetime
import pytest
from pydantic.error_wrappers import ValidationError as PydanticValidationError
from node.blockchain.facade import BlockchainFacade
from node.blockchain.inner_models import (
AccountState, Block, BlockMessageUpdate, GenesisBlockMessage, GenesisSignedChangeReq... | node/blockchain/tests/test_models/test_block/test_genesis.py | import json
from datetime import datetime
import pytest
from pydantic.error_wrappers import ValidationError as PydanticValidationError
from node.blockchain.facade import BlockchainFacade
from node.blockchain.inner_models import (
AccountState, Block, BlockMessageUpdate, GenesisBlockMessage, GenesisSignedChangeReq... | 0.663778 | 0.38027 |
generator."""
import json
import os
import random
TWEETS = None
def _get_tweets(db_path="tweets.json"):
"""Get Trump's tweets, caching after first use."""
global TWEETS
# Cache tweets if they haven't been fetched yet
if TWEETS is None:
# Try to read from a saved file
if os.path.exist... | thedonald/__init__.py | generator."""
import json
import os
import random
TWEETS = None
def _get_tweets(db_path="tweets.json"):
"""Get Trump's tweets, caching after first use."""
global TWEETS
# Cache tweets if they haven't been fetched yet
if TWEETS is None:
# Try to read from a saved file
if os.path.exist... | 0.669313 | 0.20144 |
import gym
import numpy as np
class GymWrapper(gym.Env):
"""OpenAI Gym interface for the source-tracking POMDP.
Args:
sim (SourceTracking): an instance of the SourceTracking class with draw_source = True
stop_t (int, optional): maximum number of timesteps, it should be large enough to (almost... | otto/classes/gymwrapper.py | import gym
import numpy as np
class GymWrapper(gym.Env):
"""OpenAI Gym interface for the source-tracking POMDP.
Args:
sim (SourceTracking): an instance of the SourceTracking class with draw_source = True
stop_t (int, optional): maximum number of timesteps, it should be large enough to (almost... | 0.890972 | 0.468487 |
from os.path import commonprefix
__unittest = True
_MAX_LENGTH = 80
_PLACEHOLDER_LEN = 12
_MIN_BEGIN_LEN = 5
_MIN_END_LEN = 5
_MIN_COMMON_LEN = 5
_MIN_DIFF_LEN = _MAX_LENGTH - \
(_MIN_BEGIN_LEN + _PLACEHOLDER_LEN + _MIN_COMMON_LEN +
_PLACEHOLDER_LEN + _MIN_END_LEN)
assert _MIN_DIFF_LE... | Lib/site-packages/unittest2/util.py |
from os.path import commonprefix
__unittest = True
_MAX_LENGTH = 80
_PLACEHOLDER_LEN = 12
_MIN_BEGIN_LEN = 5
_MIN_END_LEN = 5
_MIN_COMMON_LEN = 5
_MIN_DIFF_LEN = _MAX_LENGTH - \
(_MIN_BEGIN_LEN + _PLACEHOLDER_LEN + _MIN_COMMON_LEN +
_PLACEHOLDER_LEN + _MIN_END_LEN)
assert _MIN_DIFF_LE... | 0.478773 | 0.173919 |
from flask import Flask
from flask_mail import Mail, Message
import pandas as pd
import logging
import requests
import time
from local_settings import *
import datetime
import gc
import pymysql
import warnings
app = Flask(__name__)
email_service = Mail(app)
# ensure info logs are printed
logging.basicConfig(format='%... | weather_api_and_email_service.py | from flask import Flask
from flask_mail import Mail, Message
import pandas as pd
import logging
import requests
import time
from local_settings import *
import datetime
import gc
import pymysql
import warnings
app = Flask(__name__)
email_service = Mail(app)
# ensure info logs are printed
logging.basicConfig(format='%... | 0.247532 | 0.100172 |
import numpy as np
import pandas as pd
from sklearn.model_selection import train_test_split
from sklearn.svm import LinearSVC
from sklearn.linear_model import SGDClassifier
from sklearn.metrics import accuracy_score
from sklearn.preprocessing import PolynomialFeatures
import matplotlib.pyplot as plt
import matplotlib.c... | SUSY_Radon/utils.py | import numpy as np
import pandas as pd
from sklearn.model_selection import train_test_split
from sklearn.svm import LinearSVC
from sklearn.linear_model import SGDClassifier
from sklearn.metrics import accuracy_score
from sklearn.preprocessing import PolynomialFeatures
import matplotlib.pyplot as plt
import matplotlib.c... | 0.420719 | 0.45538 |
"""create_gt_txt_from_mat.py"""
import os
import argparse
import tqdm
import numpy as np
from scipy.io import loadmat
from cython_bbox import bbox_overlaps
_MAP = {
'0': '0--Parade',
'1': '1--Handshaking',
'2': '2--Demonstration',
'3': '3--Riot',
'4': '4--Dancing',
'5': '5--Car_Accident',
'... | research/cv/FaceDetection/infer/dataset_val/create_gt_txt_from_mat.py | """create_gt_txt_from_mat.py"""
import os
import argparse
import tqdm
import numpy as np
from scipy.io import loadmat
from cython_bbox import bbox_overlaps
_MAP = {
'0': '0--Parade',
'1': '1--Handshaking',
'2': '2--Demonstration',
'3': '3--Riot',
'4': '4--Dancing',
'5': '5--Car_Accident',
'... | 0.398641 | 0.242441 |
from openerp.osv import osv,fields
from openerp import models, fields, api, _
class CambioParaleloDetalle(models.Model):
_name="cambio.paralelo.detalle"
_order = "contador asc"
paralelod_id =fields.Many2one('cambio.paralelo',string="Relacion")
contador = fields.Integer(string="Número")
jornada_id=... | hanibal/ans_escuela/cambio_paralelo.py | from openerp.osv import osv,fields
from openerp import models, fields, api, _
class CambioParaleloDetalle(models.Model):
_name="cambio.paralelo.detalle"
_order = "contador asc"
paralelod_id =fields.Many2one('cambio.paralelo',string="Relacion")
contador = fields.Integer(string="Número")
jornada_id=... | 0.160661 | 0.077169 |
import unittest
import numpy as np
import desimeter.transform.radec2tan as radec2tan
class TestRADEC2TAN(unittest.TestCase):
def test_hadec2xy(self):
cha=12
cdec=24
x1 = np.random.uniform(size=3)-0.5
y1 = np.random.uniform(size=3)-0.5
ha1,dec1 = radec2tan.xy2had... | py/desimeter/test/test_radec2tan.py | import unittest
import numpy as np
import desimeter.transform.radec2tan as radec2tan
class TestRADEC2TAN(unittest.TestCase):
def test_hadec2xy(self):
cha=12
cdec=24
x1 = np.random.uniform(size=3)-0.5
y1 = np.random.uniform(size=3)-0.5
ha1,dec1 = radec2tan.xy2had... | 0.548432 | 0.530297 |
""" Base class for all plugin types """
from inspect import currentframe
import os
from typing import Optional
import yaml
from app.exceptions import PluginError # type: ignore
import app.exceptions # type: ignore
class BasePlugin():
""" Base class for plugins """
required_files: list[str] = [] # a list... | plugins/base/plugin_base.py | """ Base class for all plugin types """
from inspect import currentframe
import os
from typing import Optional
import yaml
from app.exceptions import PluginError # type: ignore
import app.exceptions # type: ignore
class BasePlugin():
""" Base class for plugins """
required_files: list[str] = [] # a list... | 0.764364 | 0.209247 |
# windows sdk data file can download here: 'https://github.com/ohjeongwook/windows_sdk_data.git'
import json
import os
result_dict = {}
def parse_winsdk(dir):
def PtrDecl_detect(dic):
param_dict = {}
if dic['data_type'] in ['PtrDecl', 'ArrayDecl']:
return PtrDecl_detect(dic['type'])... | qiling/qiling/extensions/windows_sdk/winsdk_dump.py |
# windows sdk data file can download here: 'https://github.com/ohjeongwook/windows_sdk_data.git'
import json
import os
result_dict = {}
def parse_winsdk(dir):
def PtrDecl_detect(dic):
param_dict = {}
if dic['data_type'] in ['PtrDecl', 'ArrayDecl']:
return PtrDecl_detect(dic['type'])... | 0.278061 | 0.190009 |
class TrieNode(object):
def __init__(self, is_word=False):
# 是否是一个单词,默认为 False
self.is_word = is_word;
# key 是单个字符,value 是下一个节点
self.next = dict()
class Trie:
def __init__(self):
self._root = TrieNode()
# 初始化为 0
self._size = 0
def is_empty(self):
... | maths/L11Trie.py | class TrieNode(object):
def __init__(self, is_word=False):
# 是否是一个单词,默认为 False
self.is_word = is_word;
# key 是单个字符,value 是下一个节点
self.next = dict()
class Trie:
def __init__(self):
self._root = TrieNode()
# 初始化为 0
self._size = 0
def is_empty(self):
... | 0.335242 | 0.345712 |
import pytest
from mock import Mock
from model_mommy import mommy
from bpp.models.zrodlo import Zrodlo, Punktacja_Zrodla
from integrator2.models.lista_ministerialna import ListaMinisterialnaElement
def test_models_lista_ministerialna_input_file_to_dict_stream(lmi):
gen = lmi.input_file_to_dict_stream()
nex... | src/integrator2/tests/test_models_lista_ministerialna.py |
import pytest
from mock import Mock
from model_mommy import mommy
from bpp.models.zrodlo import Zrodlo, Punktacja_Zrodla
from integrator2.models.lista_ministerialna import ListaMinisterialnaElement
def test_models_lista_ministerialna_input_file_to_dict_stream(lmi):
gen = lmi.input_file_to_dict_stream()
nex... | 0.473657 | 0.475423 |
import curses
import sys
import time
import pyfmodex
from pyfmodex.enums import RESULT, SPEAKERMODE, TIMEUNIT
from pyfmodex.exceptions import FmodError
from pyfmodex.flags import MODE
MIN_FMOD_VERSION = 0x00020108
CHOICES = (
"Mono from front left speaker",
"Mono from front right speaker",
"Mono from ce... | docs/sample_code/multiple_speaker.py |
import curses
import sys
import time
import pyfmodex
from pyfmodex.enums import RESULT, SPEAKERMODE, TIMEUNIT
from pyfmodex.exceptions import FmodError
from pyfmodex.flags import MODE
MIN_FMOD_VERSION = 0x00020108
CHOICES = (
"Mono from front left speaker",
"Mono from front right speaker",
"Mono from ce... | 0.443118 | 0.140484 |
import logging
import socket
import asyncio
import voluptuous as vol
import homeassistant.helpers.config_validation as cv
from homeassistant.const import (
CONF_USERNAME, CONF_PASSWORD, CONF_SCAN_INTERVAL)
from homeassistant.helpers import discovery
_LOGGER = logging.getLogger(__name__)
CONF_CLIENT_ID = 'client_i... | custom_components/mind/__init__.py | import logging
import socket
import asyncio
import voluptuous as vol
import homeassistant.helpers.config_validation as cv
from homeassistant.const import (
CONF_USERNAME, CONF_PASSWORD, CONF_SCAN_INTERVAL)
from homeassistant.helpers import discovery
_LOGGER = logging.getLogger(__name__)
CONF_CLIENT_ID = 'client_i... | 0.433502 | 0.055618 |
import re
import requests
from bs4 import BeautifulSoup
class AnavNet:
__url = "http://anavnet.hidrografico.pt/AvisosLocais/AvisosLocais.aspx?Porto="
__keys = {
'num_aviso': 'LabelNoAviso',
'dt_promulgacao': 'DATAPROMULGACAOLabel',
'dt_inicio': 'DATAINICIOLabel',
'dt_fim': 'DA... | anavnet/anavnet.py |
import re
import requests
from bs4 import BeautifulSoup
class AnavNet:
__url = "http://anavnet.hidrografico.pt/AvisosLocais/AvisosLocais.aspx?Porto="
__keys = {
'num_aviso': 'LabelNoAviso',
'dt_promulgacao': 'DATAPROMULGACAOLabel',
'dt_inicio': 'DATAINICIOLabel',
'dt_fim': 'DA... | 0.417746 | 0.149252 |
from __future__ import unicode_literals
import frappe
from frappe import _
import io
import openpyxl
from frappe.utils import cint, get_site_url, get_url
from art_collections.controllers.excel import write_xlsx, attach_file
def on_submit_request_for_quotation(doc, method=None):
_make_excel_attachment(doc.doctype,... | art_collections/controllers/excel/request_for_quotation_excel.py | from __future__ import unicode_literals
import frappe
from frappe import _
import io
import openpyxl
from frappe.utils import cint, get_site_url, get_url
from art_collections.controllers.excel import write_xlsx, attach_file
def on_submit_request_for_quotation(doc, method=None):
_make_excel_attachment(doc.doctype,... | 0.371935 | 0.182991 |
import lxml.objectify
import http.client
import urllib.parse
from .utils.dates import *
from .feeds import InvalidFeed
__all__ = ('ParseError', 'InvalidFeed', 'from_string', 'from_url', 'from_file', 'parse_date')
# TODO: change the feeds to a registration model
from .feeds.atom10 import Atom10Feed
from .feeds.rss20 ... | feedreader/parser.py | import lxml.objectify
import http.client
import urllib.parse
from .utils.dates import *
from .feeds import InvalidFeed
__all__ = ('ParseError', 'InvalidFeed', 'from_string', 'from_url', 'from_file', 'parse_date')
# TODO: change the feeds to a registration model
from .feeds.atom10 import Atom10Feed
from .feeds.rss20 ... | 0.195748 | 0.075448 |
from pyspark import SparkContext, SparkConf, SparkFiles
from pyspark.streaming import StreamingContext
from pyspark.streaming.kafka import KafkaUtils
from msgParser import *
import msgParser
import json
import happybase
import sys
import os
import pika
import time
from influxdb import InfluxDBClient
SPARK_PERIOD_S... | example/dt/7.preprocessor/docker/build/KETI_Preprocessor.py | from pyspark import SparkContext, SparkConf, SparkFiles
from pyspark.streaming import StreamingContext
from pyspark.streaming.kafka import KafkaUtils
from msgParser import *
import msgParser
import json
import happybase
import sys
import os
import pika
import time
from influxdb import InfluxDBClient
SPARK_PERIOD_S... | 0.212477 | 0.125279 |
from pymongo import ASCENDING, DESCENDING
ENTRIES = 20
def validate(revision, revisions_count):
if revision < 0 or revision >= revisions_count:
raise ValueError("revision index out of bound! " + str(revision))
return revision
class ArticlesParams(object):
def __init__(self, from_revision, to_r... | model/params.py | from pymongo import ASCENDING, DESCENDING
ENTRIES = 20
def validate(revision, revisions_count):
if revision < 0 or revision >= revisions_count:
raise ValueError("revision index out of bound! " + str(revision))
return revision
class ArticlesParams(object):
def __init__(self, from_revision, to_r... | 0.619356 | 0.221751 |
import matplotlib
matplotlib.use("Agg")
import matplotlib.pyplot as plt
from keras.callbacks import Callback
class AccHistoryPlot(Callback):
def __init__(self, stage_infos, test_data, data_name, result_save_path, validate=0, plot_epoch_gap=30, verbose=1):
super(AccHistoryPlot, self).__init__()
sel... | sample/utils/acc_history_plot.py | import matplotlib
matplotlib.use("Agg")
import matplotlib.pyplot as plt
from keras.callbacks import Callback
class AccHistoryPlot(Callback):
def __init__(self, stage_infos, test_data, data_name, result_save_path, validate=0, plot_epoch_gap=30, verbose=1):
super(AccHistoryPlot, self).__init__()
sel... | 0.614163 | 0.405684 |
# Make coding more python3-ish
from __future__ import (absolute_import, division, print_function)
__metaclass__ = type
import os
import json
import pytest
from mock import ANY
from ansible.module_utils.network.fortios.fortios import FortiOSHandler
try:
from ansible.modules.network.fortios import fortios_vpn_ssl_... | v6.0.5/vpn_ssl/test_fortios_vpn_ssl_settings.py |
# Make coding more python3-ish
from __future__ import (absolute_import, division, print_function)
__metaclass__ = type
import os
import json
import pytest
from mock import ANY
from ansible.module_utils.network.fortios.fortios import FortiOSHandler
try:
from ansible.modules.network.fortios import fortios_vpn_ssl_... | 0.562417 | 0.148664 |
import os
import shutil
from bbdata.download.download import VideoDownloader
import tensorflow as tf
tf.compat.v1.logging.set_verbosity(tf.compat.v1.logging.WARN)
import tensorflow_io as tfio
from utils import (
call_bash,
force_update,
freeze_cfg,
get_data_dir,
get_frozen_params,
get_params... | bbaction/ingestion/ingest.py | import os
import shutil
from bbdata.download.download import VideoDownloader
import tensorflow as tf
tf.compat.v1.logging.set_verbosity(tf.compat.v1.logging.WARN)
import tensorflow_io as tfio
from utils import (
call_bash,
force_update,
freeze_cfg,
get_data_dir,
get_frozen_params,
get_params... | 0.304765 | 0.16807 |
import copy
import numpy as np
import torch
import torch.nn as nn
import torch.nn.functional as F
import torch.distributions as dist
from core.models.common_layers import get_nddr
from core.utils import AttrDict
from core.tasks import get_tasks
from core.utils.losses import poly, entropy_loss, l1_loss
class General... | core/models/supernet.py | import copy
import numpy as np
import torch
import torch.nn as nn
import torch.nn.functional as F
import torch.distributions as dist
from core.models.common_layers import get_nddr
from core.utils import AttrDict
from core.tasks import get_tasks
from core.utils.losses import poly, entropy_loss, l1_loss
class General... | 0.890181 | 0.246567 |
import functools
import time
import torch
import torch.autograd as autograd
import torch.cuda.comm as comm
import torch.nn as nn
import torch.nn.functional as F
from torch.autograd.function import once_differentiable
class CA_Weight(autograd.Function):
@staticmethod
def forward(ctx, t, f):
# Save con... | Plug-and-play module/attention/CCNet/ccnet.py | import functools
import time
import torch
import torch.autograd as autograd
import torch.cuda.comm as comm
import torch.nn as nn
import torch.nn.functional as F
from torch.autograd.function import once_differentiable
class CA_Weight(autograd.Function):
@staticmethod
def forward(ctx, t, f):
# Save con... | 0.940558 | 0.289692 |
import argparse
import csv
import json
import os
import logging
import yaml
def load_csv_logs(filename):
logs = []
p_fields = set()
with open(filename, 'r' ) as fi:
reader = csv.DictReader(fi)
# Get the full list of p_ fields in this particular log type
p_fields = set([x for x in r... | test_scenarios/jsonl_to_testfile.py | import argparse
import csv
import json
import os
import logging
import yaml
def load_csv_logs(filename):
logs = []
p_fields = set()
with open(filename, 'r' ) as fi:
reader = csv.DictReader(fi)
# Get the full list of p_ fields in this particular log type
p_fields = set([x for x in r... | 0.27048 | 0.139104 |
import random as python_random
from typing import Dict, List, Optional, Sequence, Tuple
import numpy as np
import pandas as pd
from scipy import stats
from sklearn import metrics as skm
import tensorflow as tf
import metrics
import models
import potts_model
import sampling
import solver
import utils
def get_fitne... | experiment.py | import random as python_random
from typing import Dict, List, Optional, Sequence, Tuple
import numpy as np
import pandas as pd
from scipy import stats
from sklearn import metrics as skm
import tensorflow as tf
import metrics
import models
import potts_model
import sampling
import solver
import utils
def get_fitne... | 0.938301 | 0.525978 |
import warnings
from typing import List, Type
from ..optimizers.base_optimizer import BaseOptimizer, BaseOptimizerWithEarlyStopping
from ..parameter_tuning import (
CategoricalSuggestion,
IntegerSuggestion,
LogUniformSuggestion,
Suggestion,
UniformSuggestion,
)
from ..recommenders import (
Asym... | irspack/optimizers/_optimizers.py | import warnings
from typing import List, Type
from ..optimizers.base_optimizer import BaseOptimizer, BaseOptimizerWithEarlyStopping
from ..parameter_tuning import (
CategoricalSuggestion,
IntegerSuggestion,
LogUniformSuggestion,
Suggestion,
UniformSuggestion,
)
from ..recommenders import (
Asym... | 0.870294 | 0.414899 |
import sys
import time
from nlp_toolkit.models import bi_lstm_attention
from nlp_toolkit.models import Transformer
from nlp_toolkit.models import textCNN, DPCNN
from nlp_toolkit.trainer import Trainer
from nlp_toolkit.utilities import logger
from nlp_toolkit.sequence import BasicIterator
from nlp_toolkit.data import Da... | nlp_toolkit/classifier.py | import sys
import time
from nlp_toolkit.models import bi_lstm_attention
from nlp_toolkit.models import Transformer
from nlp_toolkit.models import textCNN, DPCNN
from nlp_toolkit.trainer import Trainer
from nlp_toolkit.utilities import logger
from nlp_toolkit.sequence import BasicIterator
from nlp_toolkit.data import Da... | 0.46223 | 0.199542 |
from airsim import *
from game.car_simulator import CarSimulator
from ml.model import DeepLearningModel
from ml.additional.preprocessing import *
from multiprocessing import Queue, Manager, Lock
import datetime
import glob
import matplotlib.pyplot as plt
class Environment():
ai_sim_car = None
stop_driving = F... | game/environment.py | from airsim import *
from game.car_simulator import CarSimulator
from ml.model import DeepLearningModel
from ml.additional.preprocessing import *
from multiprocessing import Queue, Manager, Lock
import datetime
import glob
import matplotlib.pyplot as plt
class Environment():
ai_sim_car = None
stop_driving = F... | 0.214609 | 0.224087 |
import appdirs
import json
import os
import re
import requests
import socket
import sys
import time
from PyInquirer import prompt
def main():
PRESETS_DIR = appdirs.user_data_dir("wialon_ips", "<NAME>")
if not os.path.exists(PRESETS_DIR):
os.makedirs(PRESETS_DIR)
PRESETS_PATH = os.path.join(PRESETS_DIR, 'wialon... | wialon_ips.py |
import appdirs
import json
import os
import re
import requests
import socket
import sys
import time
from PyInquirer import prompt
def main():
PRESETS_DIR = appdirs.user_data_dir("wialon_ips", "<NAME>")
if not os.path.exists(PRESETS_DIR):
os.makedirs(PRESETS_DIR)
PRESETS_PATH = os.path.join(PRESETS_DIR, 'wialon... | 0.0453 | 0.056705 |
from abc import abstractmethod
from os.path import join
import numpy as np
from scipy.integrate import trapz
from scipy.interpolate import UnivariateSpline
import prince_cr.config as config
class PhotonField(object):
"""Base class for constructing target photon densities.
Derived classes have to implement ... | prince_cr/photonfields.py | from abc import abstractmethod
from os.path import join
import numpy as np
from scipy.integrate import trapz
from scipy.interpolate import UnivariateSpline
import prince_cr.config as config
class PhotonField(object):
"""Base class for constructing target photon densities.
Derived classes have to implement ... | 0.892563 | 0.468669 |
import ctypes
from . import run_solo_function
from . import DataPair, masked_op
from . import aliases
se_copy_bad_flags = aliases['copy_bad_flags']
def copy_bad_flags(input_list_data, bad, dgi_clip_gate=None, boundary_mask=None):
"""
Gives an updated mask based on values in input_list_data that are bad.... | src/pysolo/solo_functions/flags/solo_copy_bad_flags.py | import ctypes
from . import run_solo_function
from . import DataPair, masked_op
from . import aliases
se_copy_bad_flags = aliases['copy_bad_flags']
def copy_bad_flags(input_list_data, bad, dgi_clip_gate=None, boundary_mask=None):
"""
Gives an updated mask based on values in input_list_data that are bad.... | 0.844601 | 0.409545 |
import sys
import io
import time
import pprint
input_txt = """
100
"""
sys.stdin = io.StringIO(input_txt);input()
#sys.stdin = open('in.test')
start_time = time.time()
# copy the below part and paste to the submission form.
# ---------function------------
import math
from collections import defaultdict... | python/ABC114/ABC114_D.py | import sys
import io
import time
import pprint
input_txt = """
100
"""
sys.stdin = io.StringIO(input_txt);input()
#sys.stdin = open('in.test')
start_time = time.time()
# copy the below part and paste to the submission form.
# ---------function------------
import math
from collections import defaultdict... | 0.138113 | 0.278128 |
import random
import numpy as np
from tqdm import tqdm
import gensim
import time
import pkg_resources
def parallel_generate_walks(d_graph: dict, global_walk_length: int, num_walks: int, cpu_num: int,
sampling_strategy: dict = None, num_walks_key: str = None, walk_length_key: str = None,
... | cepy/parallel.py | import random
import numpy as np
from tqdm import tqdm
import gensim
import time
import pkg_resources
def parallel_generate_walks(d_graph: dict, global_walk_length: int, num_walks: int, cpu_num: int,
sampling_strategy: dict = None, num_walks_key: str = None, walk_length_key: str = None,
... | 0.683947 | 0.364891 |
from boto3 import Session
from boto3.s3.transfer import S3Transfer
from .compression.uncompressfile import UncompressFile
from .encryption.decryptedfile import DecryptedFile, EncryptionContextMismatch
import os
from ..cli import cli_library
class RestoreFile:
def __init__(self, s3_bucket, timestamp, backup_file, ... | cloud_backup/backup/restorefile.py | from boto3 import Session
from boto3.s3.transfer import S3Transfer
from .compression.uncompressfile import UncompressFile
from .encryption.decryptedfile import DecryptedFile, EncryptionContextMismatch
import os
from ..cli import cli_library
class RestoreFile:
def __init__(self, s3_bucket, timestamp, backup_file, ... | 0.407569 | 0.061003 |