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 pandas as pd
import numpy as np
import sys
import os
import random
from pathlib import Path
import imageio
import skimage
import skimage.io
import skimage.transform
# ML
import scipy
from sklearn.model_selection import train_test_split
from sklearn import metrics
#tensorflow
import tensorflow
from tensorflo... | models/health_classifier.py | import pandas as pd
import numpy as np
import sys
import os
import random
from pathlib import Path
import imageio
import skimage
import skimage.io
import skimage.transform
# ML
import scipy
from sklearn.model_selection import train_test_split
from sklearn import metrics
#tensorflow
import tensorflow
from tensorflo... | 0.598899 | 0.374076 |
from yggdrasil.drivers.ConnectionDriver import ConnectionDriver, run_remotely
from yggdrasil.drivers.RPCResponseDriver import RPCResponseDriver
from yggdrasil.communication import CommBase
# ----
# Client sends resquest to local client output comm
# Client recvs response from local client input comm
# ----
# Client re... | yggdrasil/drivers/RPCRequestDriver.py | from yggdrasil.drivers.ConnectionDriver import ConnectionDriver, run_remotely
from yggdrasil.drivers.RPCResponseDriver import RPCResponseDriver
from yggdrasil.communication import CommBase
# ----
# Client sends resquest to local client output comm
# Client recvs response from local client input comm
# ----
# Client re... | 0.753648 | 0.150216 |
import requests
import json
from falcon_jinja2 import FalconTemplate
from os import getenv
from urllib.parse import urlunparse
class OAuthCallbackResource(object):
"""
Handles the callback from the IDP
"""
ft = FalconTemplate()
@ft.render("/callback/index.html")
def on_get(self, req, resp):
... | src/resources/OAuthCallback.py | import requests
import json
from falcon_jinja2 import FalconTemplate
from os import getenv
from urllib.parse import urlunparse
class OAuthCallbackResource(object):
"""
Handles the callback from the IDP
"""
ft = FalconTemplate()
@ft.render("/callback/index.html")
def on_get(self, req, resp):
... | 0.431584 | 0.141608 |
import logging
from typing import Optional
import osm2geojson
import requests
from django.db import IntegrityError
from mainapp.models import SearchStreet, Location, Body
overpass_api = "http://overpass-api.de/api/interpreter"
logger = logging.getLogger(__name__)
streets_query_template = """
[out:json];area["de:am... | mainapp/functions/citytools.py | import logging
from typing import Optional
import osm2geojson
import requests
from django.db import IntegrityError
from mainapp.models import SearchStreet, Location, Body
overpass_api = "http://overpass-api.de/api/interpreter"
logger = logging.getLogger(__name__)
streets_query_template = """
[out:json];area["de:am... | 0.676727 | 0.168002 |
from __future__ import unicode_literals
import django.core.validators
from django.db import migrations, models
class Migration(migrations.Migration):
dependencies = [
('bpay', '0006_auto_20160912_1134'),
]
operations = [
migrations.AlterField(
model_name='bpayfile',
... | ledger/payments/bpay/migrations/0007_auto_20170106_1600.py | from __future__ import unicode_literals
import django.core.validators
from django.db import migrations, models
class Migration(migrations.Migration):
dependencies = [
('bpay', '0006_auto_20160912_1134'),
]
operations = [
migrations.AlterField(
model_name='bpayfile',
... | 0.670716 | 0.132992 |
import numpy as np
import pandas as pd
from base import BaseFeature
from utils import reduce_mem_usage
from typing import Optional, List, Tuple
from sklearn.model_selection import StratifiedKFold
import tempfile
import os
FOLD = 3
RANDOM_STATE = 71
SHUFFLE = True
class TimeGroupKFold(BaseFeature):
def import_co... | features/time_groupk_fold.py | import numpy as np
import pandas as pd
from base import BaseFeature
from utils import reduce_mem_usage
from typing import Optional, List, Tuple
from sklearn.model_selection import StratifiedKFold
import tempfile
import os
FOLD = 3
RANDOM_STATE = 71
SHUFFLE = True
class TimeGroupKFold(BaseFeature):
def import_co... | 0.586996 | 0.270905 |
#==========================================================
# imports
import rospy
import smach, smach_ros
from geometry_msgs.msg import PoseStamped
"""
Naming conventions:
STATE_NAME
StateNameClass()
outcome_*
kStateMachineDataKey
sStateDataKey
"""
class MoveBaseState(smach.State):
def __init__(self):
smach.S... | navigation/robust_controller/src/smach_test.py |
#==========================================================
# imports
import rospy
import smach, smach_ros
from geometry_msgs.msg import PoseStamped
"""
Naming conventions:
STATE_NAME
StateNameClass()
outcome_*
kStateMachineDataKey
sStateDataKey
"""
class MoveBaseState(smach.State):
def __init__(self):
smach.S... | 0.336113 | 0.063744 |
import math
import torch
from e3nn import o3, rs, rsh
from e3nn.linear_mod import KernelLinear
def kernel_geometric(Rs_in, Rs_out, selection_rule=o3.selection_rule_in_out_sh, normalization='component'):
# Compute Clebsh-Gordan coefficients
Rs_f, Q = rs.tensor_product(Rs_in, selection_rule, Rs_out, normaliza... | e3nn/kernel_mod.py | import math
import torch
from e3nn import o3, rs, rsh
from e3nn.linear_mod import KernelLinear
def kernel_geometric(Rs_in, Rs_out, selection_rule=o3.selection_rule_in_out_sh, normalization='component'):
# Compute Clebsh-Gordan coefficients
Rs_f, Q = rs.tensor_product(Rs_in, selection_rule, Rs_out, normaliza... | 0.922696 | 0.498596 |
from datetime import datetime
class __Git_Repo:
def __init__(self, root):
from git import Repo, InvalidGitRepositoryError
try:
self.repo = Repo(root)
except InvalidGitRepositoryError:
self.repo = Repo.init(root)
except:
raise Exception(f"Unable... | pygitit/repo.py |
from datetime import datetime
class __Git_Repo:
def __init__(self, root):
from git import Repo, InvalidGitRepositoryError
try:
self.repo = Repo(root)
except InvalidGitRepositoryError:
self.repo = Repo.init(root)
except:
raise Exception(f"Unable... | 0.577138 | 0.201833 |
import dlpoly as dlp
import unittest
class ConfigTest(unittest.TestCase):
def setUp(self):
self.config = ConfigTest.config
@classmethod
def setUpClass(cls):
super(ConfigTest, cls).setUpClass()
cls.config = dlp.DLPoly(config="tests/CONFIG").config
def test_config_natoms(self)... | tests/test_config.py | import dlpoly as dlp
import unittest
class ConfigTest(unittest.TestCase):
def setUp(self):
self.config = ConfigTest.config
@classmethod
def setUpClass(cls):
super(ConfigTest, cls).setUpClass()
cls.config = dlp.DLPoly(config="tests/CONFIG").config
def test_config_natoms(self)... | 0.577734 | 0.496033 |
import os
import re
import sys
import html
import json
from collections import defaultdict
from xmi_document import xmi_document
try:
fn = sys.argv[1]
try:
OUTPUT = open(sys.argv[2], "w", encoding='utf-8')
except IndexError as e:
OUTPUT = sys.stdout
except:
print("Usage: python to_po.... | scripts/to_bsdd.py | import os
import re
import sys
import html
import json
from collections import defaultdict
from xmi_document import xmi_document
try:
fn = sys.argv[1]
try:
OUTPUT = open(sys.argv[2], "w", encoding='utf-8')
except IndexError as e:
OUTPUT = sys.stdout
except:
print("Usage: python to_po.... | 0.129926 | 0.139162 |
import logging
import os
from datetime import date
from pathlib import Path
from typing import Any, Dict, List, Set, cast
from rp2.abstract_country import AbstractCountry
from rp2.computed_data import ComputedData
from rp2.in_transaction import InTransaction
from rp2.logger import create_logger
from rp2.plugin.report... | src/rp2/plugin/report/us/open_positions.py |
import logging
import os
from datetime import date
from pathlib import Path
from typing import Any, Dict, List, Set, cast
from rp2.abstract_country import AbstractCountry
from rp2.computed_data import ComputedData
from rp2.in_transaction import InTransaction
from rp2.logger import create_logger
from rp2.plugin.report... | 0.672332 | 0.204084 |
# Copyright: (c) 2017, Ansible Project
# Copyright: (c) 2017, <NAME> (<EMAIL>)
# GNU General Public License v3.0+ (see COPYING or https://www.gnu.org/licenses/gpl-3.0.txt)
from __future__ import (absolute_import, division, print_function)
__metaclass__ = type
class ModuleDocFragment(object):
# Parameters for in... | kubernetes-the-hard-way/system/collections/ansible_collections/community/general/plugins/doc_fragments/influxdb.py |
# Copyright: (c) 2017, Ansible Project
# Copyright: (c) 2017, <NAME> (<EMAIL>)
# GNU General Public License v3.0+ (see COPYING or https://www.gnu.org/licenses/gpl-3.0.txt)
from __future__ import (absolute_import, division, print_function)
__metaclass__ = type
class ModuleDocFragment(object):
# Parameters for in... | 0.781289 | 0.154535 |
import click
import operator
import os
import time
import yaml
from . import util
from .chute import chute_find_field, chute_resolve_source
from .controller_client import ControllerClient
@click.group('store')
@click.pass_context
def root(ctx):
"""
Publish and install from the public chute store.
By def... | tools/pdtools/pdtools/store.py | import click
import operator
import os
import time
import yaml
from . import util
from .chute import chute_find_field, chute_resolve_source
from .controller_client import ControllerClient
@click.group('store')
@click.pass_context
def root(ctx):
"""
Publish and install from the public chute store.
By def... | 0.478041 | 0.114864 |
import config
import contextlib
import codecs
import datetime
import defusedxml.ElementTree
import email
import email.header
import gzip
import imaplib
import io
import sys
import zipfile
CONTENT_ZIP = ["application/zip", "application/x-zip-compressed"]
CONTENT_GZIP = ["application/gzip"]
CONTENT_IGNORE = ["multipart/... | main.py | import config
import contextlib
import codecs
import datetime
import defusedxml.ElementTree
import email
import email.header
import gzip
import imaplib
import io
import sys
import zipfile
CONTENT_ZIP = ["application/zip", "application/x-zip-compressed"]
CONTENT_GZIP = ["application/gzip"]
CONTENT_IGNORE = ["multipart/... | 0.179099 | 0.080828 |
import pandas as pd
import numpy as np
def sigmoid(x):
"""
Calculate sigmoid
"""
return 1 / (1 + np.exp(-x))
def sigmoid_prime(x):
"""
# Derivative of the sigmoid function
"""
return sigmoid(x) * (1 - sigmoid(x))
# Define the learning rate and inputs/result for our example
learnrat... | deep_learning/gradient_descent.py | import pandas as pd
import numpy as np
def sigmoid(x):
"""
Calculate sigmoid
"""
return 1 / (1 + np.exp(-x))
def sigmoid_prime(x):
"""
# Derivative of the sigmoid function
"""
return sigmoid(x) * (1 - sigmoid(x))
# Define the learning rate and inputs/result for our example
learnrat... | 0.689201 | 0.738504 |
import numpy as np
import matplotlib.pyplot as plt
import string
import os
from collections import defaultdict
import pdb
from nltk.corpus import stopwords
from nltk.tokenize import word_tokenize
from sklearn.ensemble import RandomForestClassifier
from sklearn.metrics import precision_recall_fscore_support
from sklea... | src/driver.py | import numpy as np
import matplotlib.pyplot as plt
import string
import os
from collections import defaultdict
import pdb
from nltk.corpus import stopwords
from nltk.tokenize import word_tokenize
from sklearn.ensemble import RandomForestClassifier
from sklearn.metrics import precision_recall_fscore_support
from sklea... | 0.159708 | 0.256267 |
from time import time
import requests
from bs4 import BeautifulSoup as BS
import csv
import sys
# training website
INPUT = "https://volby.cz/pls/ps2017nss/ps3?xjazyk=CZ"
def get_districts(web):
"""
Přijímá webovku a vrátí extrahovaný seznam odkazů na stránky volebních
okresů + základní webov... | Web_scraper.py | from time import time
import requests
from bs4 import BeautifulSoup as BS
import csv
import sys
# training website
INPUT = "https://volby.cz/pls/ps2017nss/ps3?xjazyk=CZ"
def get_districts(web):
"""
Přijímá webovku a vrátí extrahovaný seznam odkazů na stránky volebních
okresů + základní webov... | 0.257859 | 0.290327 |
import os
from os.path import abspath, dirname, exists, join
import matplotlib.pyplot as plt
import numpy as np
import pandas as pd
from utils import (
clustering,
dimension_reduction,
preprocessing,
to_dataframe,
vectorizer,
)
def visualize_vectorizer(
vec="tfidf", dim_reduc="PCA", stopword=... | src/utils/visualizer.py | import os
from os.path import abspath, dirname, exists, join
import matplotlib.pyplot as plt
import numpy as np
import pandas as pd
from utils import (
clustering,
dimension_reduction,
preprocessing,
to_dataframe,
vectorizer,
)
def visualize_vectorizer(
vec="tfidf", dim_reduc="PCA", stopword=... | 0.64131 | 0.414958 |
import subprocess
EXPECT_FAIL_65 = [
'prefix_operator',
'grouping',
'infix_operator',
'to_this',
'inherit_self',
'local_inherit_self',
'return_value',
'parenthesized_superclass',
'missing_argument',
'var_in_body',
'fun_in_body',
'class_in_body',
'trailing_dot',
'... | tests/operator/test_operator.py | import subprocess
EXPECT_FAIL_65 = [
'prefix_operator',
'grouping',
'infix_operator',
'to_this',
'inherit_self',
'local_inherit_self',
'return_value',
'parenthesized_superclass',
'missing_argument',
'var_in_body',
'fun_in_body',
'class_in_body',
'trailing_dot',
'... | 0.360039 | 0.198646 |
import torch
import numpy as np
import yaml
from dataset import public_transforms as T
from tqdm import tqdm
from dataset.voc import Voc
from dataset.coco import Coco
from torch.utils.data import DataLoader
# 配置文件
CFG = {
"input_size": 608,
"dataset": "voc", # "voc" or "coco"
"batch_size": 8,
"ma... | kmeans.py | import torch
import numpy as np
import yaml
from dataset import public_transforms as T
from tqdm import tqdm
from dataset.voc import Voc
from dataset.coco import Coco
from torch.utils.data import DataLoader
# 配置文件
CFG = {
"input_size": 608,
"dataset": "voc", # "voc" or "coco"
"batch_size": 8,
"ma... | 0.531453 | 0.331174 |
from web import app, config, tcgplayer
from flasktools import params_to_dict
from flasktools.celery import setup_celery
from flasktools.db import mutate_query
import rollbar
from celery.signals import task_failure
celery = setup_celery(app)
QUEUE = 'cardscraper'
@task_failure.connect
def handle_task_failure(**kwargs... | web/asynchro.py | from web import app, config, tcgplayer
from flasktools import params_to_dict
from flasktools.celery import setup_celery
from flasktools.db import mutate_query
import rollbar
from celery.signals import task_failure
celery = setup_celery(app)
QUEUE = 'cardscraper'
@task_failure.connect
def handle_task_failure(**kwargs... | 0.38769 | 0.148263 |
import nexusformat.nexus as nx
import xarray as xr
@xr.register_dataarray_accessor("nxr")
class _nxrDataArray:
'''nxarray class extending xarray DataArray
'''
def __init__(self, xarray_dataarray):
self._datarr = xarray_dataarray
@xr.register_dataset_accessor("nxr")
class _nxrDataset:
'''nxarr... | nxarray/_accessors.py | import nexusformat.nexus as nx
import xarray as xr
@xr.register_dataarray_accessor("nxr")
class _nxrDataArray:
'''nxarray class extending xarray DataArray
'''
def __init__(self, xarray_dataarray):
self._datarr = xarray_dataarray
@xr.register_dataset_accessor("nxr")
class _nxrDataset:
'''nxarr... | 0.529507 | 0.54353 |
import contextlib
import logging
import pprint
import sys
import click
import lnt.formats
from lnt.lnttool.common import submit_options, init_logger
from lnt.server.db.rules_manager import register_hooks
@click.command("import")
@click.argument("instance_path", type=click.UNPROCESSED)
@click.argument("files", nargs... | lnt/lnttool/import_data.py | import contextlib
import logging
import pprint
import sys
import click
import lnt.formats
from lnt.lnttool.common import submit_options, init_logger
from lnt.server.db.rules_manager import register_hooks
@click.command("import")
@click.argument("instance_path", type=click.UNPROCESSED)
@click.argument("files", nargs... | 0.24963 | 0.079068 |
# :license: MIT, see LICENSE for more details.
import webbrowser
import configparser
import json
import os.path
import requests
import click
import SoftLayer
from SoftLayer.CLI.command import SLCommand as SLCommand
from SoftLayer.CLI import config
from SoftLayer.CLI import environment
from SoftLayer.CLI import excep... | SoftLayer/CLI/config/setup.py | # :license: MIT, see LICENSE for more details.
import webbrowser
import configparser
import json
import os.path
import requests
import click
import SoftLayer
from SoftLayer.CLI.command import SLCommand as SLCommand
from SoftLayer.CLI import config
from SoftLayer.CLI import environment
from SoftLayer.CLI import excep... | 0.451568 | 0.081191 |
# algorithms and losses
from collections import deque
import torch
def monte_carlo(values, returns):
return returns, returns - values
def temporal_difference(values, returns, rewards, lmb, gamma):
target_values = deque([returns[:, -1]])
for i in range(values.size(1) - 2, -1, -1):
reward = rew... | handyrl/losses.py |
# algorithms and losses
from collections import deque
import torch
def monte_carlo(values, returns):
return returns, returns - values
def temporal_difference(values, returns, rewards, lmb, gamma):
target_values = deque([returns[:, -1]])
for i in range(values.size(1) - 2, -1, -1):
reward = rew... | 0.820901 | 0.665356 |
import warnings
warnings.filterwarnings('ignore')
import sys
import os
from astroquery.skyview import SkyView
from astropy.coordinates import SkyCoord
import astropy.units as u
import aplpy
import matplotlib.pyplot as plt
from astropy.io import fits
import astropy
def coords_from_name(field_name):
"""Get ra, dec c... | iaa_skyview_func.py | import warnings
warnings.filterwarnings('ignore')
import sys
import os
from astroquery.skyview import SkyView
from astropy.coordinates import SkyCoord
import astropy.units as u
import aplpy
import matplotlib.pyplot as plt
from astropy.io import fits
import astropy
def coords_from_name(field_name):
"""Get ra, dec c... | 0.61682 | 0.428652 |
import torch
import numpy as np
class Beam(object):
def __init__(self, size,sos,eos,prob):
self.size = size
topk=prob.shape[-1]
self.tt = torch.cuda
# The score for each translation on the beam.
self.scores = self.tt.FloatTensor(size*topk).zero_()
self.scores=self.s... | generator/beam.py |
import torch
import numpy as np
class Beam(object):
def __init__(self, size,sos,eos,prob):
self.size = size
topk=prob.shape[-1]
self.tt = torch.cuda
# The score for each translation on the beam.
self.scores = self.tt.FloatTensor(size*topk).zero_()
self.scores=self.s... | 0.692226 | 0.421671 |
from email.utils import parseaddr
from django.conf import settings
from django.contrib.auth import get_user_model
from rest_framework import exceptions, serializers
from drf_keyed_list import KeyedListSerializer
from projectroles.models import (
Project,
Role,
RoleAssignment,
ProjectInvite,
SODA... | projectroles/serializers.py |
from email.utils import parseaddr
from django.conf import settings
from django.contrib.auth import get_user_model
from rest_framework import exceptions, serializers
from drf_keyed_list import KeyedListSerializer
from projectroles.models import (
Project,
Role,
RoleAssignment,
ProjectInvite,
SODA... | 0.643217 | 0.088308 |
class WordCache:
def __init__(self):
self.cache = set()
self.build_cache()
def build_cache(self):
file_paths = ["/usr/share/dict/words", "one_hundred_most_common_words.txt", ]
n = len(file_paths)
for i in range(n):
with open(file_paths[i]) as input_dictionar... | pycomplete/autocomplete.py | class WordCache:
def __init__(self):
self.cache = set()
self.build_cache()
def build_cache(self):
file_paths = ["/usr/share/dict/words", "one_hundred_most_common_words.txt", ]
n = len(file_paths)
for i in range(n):
with open(file_paths[i]) as input_dictionar... | 0.517327 | 0.188585 |
from flask_wtf import FlaskForm, RecaptchaField
from flask_wtf.file import FileField, FileAllowed
from wtforms import StringField, PasswordField, SubmitField, BooleanField, RadioField, IntegerField, SelectField
from wtforms.fields.html5 import DateField
from wtforms.validators import DataRequired, Length, Email, EqualT... | app/users/forms.py | from flask_wtf import FlaskForm, RecaptchaField
from flask_wtf.file import FileField, FileAllowed
from wtforms import StringField, PasswordField, SubmitField, BooleanField, RadioField, IntegerField, SelectField
from wtforms.fields.html5 import DateField
from wtforms.validators import DataRequired, Length, Email, EqualT... | 0.320396 | 0.107461 |
from django.test import TestCase, override_settings
from django.apps import apps
from django.urls import re_path
from maestro.backends.django.contrib.factory import create_django_data_store
from maestro.backends.django.contrib.model_dependencies import get_model_dependencies
from maestro.backends.django.contrib.signals... | tests/django/test_app_settings.py | from django.test import TestCase, override_settings
from django.apps import apps
from django.urls import re_path
from maestro.backends.django.contrib.factory import create_django_data_store
from maestro.backends.django.contrib.model_dependencies import get_model_dependencies
from maestro.backends.django.contrib.signals... | 0.416678 | 0.101812 |
import numpy as np
import Utils
from copy import deepcopy
class CSDS:
def __init__(self, total_num, global_positions):
self.global_positions = deepcopy(global_positions)
self.remain_positions = deepcopy(self.global_positions)
self.total_num = total_num
self.remain_lis... | Traditional_Algorithm/CSDS.py | import numpy as np
import Utils
from copy import deepcopy
class CSDS:
def __init__(self, total_num, global_positions):
self.global_positions = deepcopy(global_positions)
self.remain_positions = deepcopy(self.global_positions)
self.total_num = total_num
self.remain_lis... | 0.134378 | 0.086671 |
import os, sys, re
from aifc import Error
class NoArgumentsError(Error):
pass
class TooManyArgumentsError(Error):
pass
def redirect_in(cmd):
pid = os.getpid()
return_code = os.fork()
if return_code < 0:
os.write(2, ("Failed to fork, returning").encode())
sys.exit(1)
elif return... | shell/Shell.py | import os, sys, re
from aifc import Error
class NoArgumentsError(Error):
pass
class TooManyArgumentsError(Error):
pass
def redirect_in(cmd):
pid = os.getpid()
return_code = os.fork()
if return_code < 0:
os.write(2, ("Failed to fork, returning").encode())
sys.exit(1)
elif return... | 0.098729 | 0.09236 |
import json
class WorkTemplate(object):
def __init__(self, str_in=None):
self.obj = None
if not str_in is None:
self.obj = json.loads(str_in)
def set(self, obj_in):
self.obj = obj_in
def set_answers(self, obj_in):
self.answers = obj_in
def load(self, str_i... | turk/worktmp.py | import json
class WorkTemplate(object):
def __init__(self, str_in=None):
self.obj = None
if not str_in is None:
self.obj = json.loads(str_in)
def set(self, obj_in):
self.obj = obj_in
def set_answers(self, obj_in):
self.answers = obj_in
def load(self, str_i... | 0.348978 | 0.06492 |
import os
import os.path
import serial, time
import array
import sys, getopt
class bootdownload(object):
'''
Hisilicon boot downloader
>>> downloader = bootdownload()
>>> downloader.download(filename)
'''
# crctab calculated by <NAME>, Network Systems Corporation
crctable = [
0x... | hisi-idt.py |
import os
import os.path
import serial, time
import array
import sys, getopt
class bootdownload(object):
'''
Hisilicon boot downloader
>>> downloader = bootdownload()
>>> downloader.download(filename)
'''
# crctab calculated by <NAME>, Network Systems Corporation
crctable = [
0x... | 0.210848 | 0.227169 |
from __future__ import unicode_literals
import random
import uuid
from datetime import datetime, timedelta, date
from django.db import models
from django.utils import timezone
from md5 import md5
from model_utils.models import TimeStampedModel
from common import constants
class UploadedFile(TimeStampedModel):
u... | original/misc/models.py | from __future__ import unicode_literals
import random
import uuid
from datetime import datetime, timedelta, date
from django.db import models
from django.utils import timezone
from md5 import md5
from model_utils.models import TimeStampedModel
from common import constants
class UploadedFile(TimeStampedModel):
u... | 0.297266 | 0.102889 |
import json
from pathlib import Path
from datetime import datetime
from typing import Callable, Dict, Optional
DIRNAME = Path(__file__).parents[1].resolve()/'weights'
class ModelBase:
def __init__(self, dataset_cls:type, network_fn:Callable,
dataset_args:dict=None, network_args:Dict=None):
... | MedSemanticSearch/medsearch/models/base.py | import json
from pathlib import Path
from datetime import datetime
from typing import Callable, Dict, Optional
DIRNAME = Path(__file__).parents[1].resolve()/'weights'
class ModelBase:
def __init__(self, dataset_cls:type, network_fn:Callable,
dataset_args:dict=None, network_args:Dict=None):
... | 0.796372 | 0.134037 |
# EXT
import luigi
# PROJECT
from bwg.decorators import time_function
from bwg.mixins import ArticleProcessingMixin
from bwg.serializing import serialize_relation
from bwg.tasks.naive_ore import NaiveOpenRelationExtractionTask
from bwg.tasks.participation_extraction import ParticipationExtractionTask
class RelationM... | backend/bwg/tasks/relation_merging.py | # EXT
import luigi
# PROJECT
from bwg.decorators import time_function
from bwg.mixins import ArticleProcessingMixin
from bwg.serializing import serialize_relation
from bwg.tasks.naive_ore import NaiveOpenRelationExtractionTask
from bwg.tasks.participation_extraction import ParticipationExtractionTask
class RelationM... | 0.582135 | 0.169475 |
import pygame
import random
from objects import Snake
from objects import Segment
from objects import Apple
pygame.init()
clock = pygame.time.Clock()
screen = pygame.display.set_mode((260, 240))
pygame.display.set_caption("Snake")
width = 20
height = 15
side = 10 #px
margin = 2 #px
highscore = 0
fps = 15
font = pygame... | Snake AI/play.py | import pygame
import random
from objects import Snake
from objects import Segment
from objects import Apple
pygame.init()
clock = pygame.time.Clock()
screen = pygame.display.set_mode((260, 240))
pygame.display.set_caption("Snake")
width = 20
height = 15
side = 10 #px
margin = 2 #px
highscore = 0
fps = 15
font = pygame... | 0.336767 | 0.247192 |
import sys
from workflow import Workflow
#map of digit to their base 10 value
chars = map(str, range(0,10)) + ['A', 'B', 'C', 'D', 'E', 'F', 'G', 'H', 'I', 'J', 'K', 'L', 'M', 'N', 'O', 'P', 'Q', 'R', 'S', 'T', 'U', 'V', 'W', 'X', 'Y', 'Z']
def main(wf):
try:
query = wf.args[0]
result = convert(q... | baseconvert.py | import sys
from workflow import Workflow
#map of digit to their base 10 value
chars = map(str, range(0,10)) + ['A', 'B', 'C', 'D', 'E', 'F', 'G', 'H', 'I', 'J', 'K', 'L', 'M', 'N', 'O', 'P', 'Q', 'R', 'S', 'T', 'U', 'V', 'W', 'X', 'Y', 'Z']
def main(wf):
try:
query = wf.args[0]
result = convert(q... | 0.207696 | 0.384248 |
import sys
import re
import pprint
my_name = sys.argv[0]
print("my_name:", my_name)
day_nr = re.search(r"\d+", my_name).group()
print("day_nr:", day_nr)
def read_input():
_all = list()
for line in sys.stdin:
_cmd, _arg = line.strip().split()
_all.append((_cmd, int(_arg)))
return _all
... | day_08.py | import sys
import re
import pprint
my_name = sys.argv[0]
print("my_name:", my_name)
day_nr = re.search(r"\d+", my_name).group()
print("day_nr:", day_nr)
def read_input():
_all = list()
for line in sys.stdin:
_cmd, _arg = line.strip().split()
_all.append((_cmd, int(_arg)))
return _all
... | 0.050278 | 0.132374 |
from multiprocessing import Process, Manager
from imageio import imread
import pickle
import numpy as np
import os
import cv2
fake_path = 'dataset-dist/phase-01/training/fake/'
pristine_path = 'dataset-dist/phase-01/training/pristine/'
mask_path = fake_path + 'masks/'
def count_255(mask):
i=0
for... | sample_fake_binaries.py | from multiprocessing import Process, Manager
from imageio import imread
import pickle
import numpy as np
import os
import cv2
fake_path = 'dataset-dist/phase-01/training/fake/'
pristine_path = 'dataset-dist/phase-01/training/pristine/'
mask_path = fake_path + 'masks/'
def count_255(mask):
i=0
for... | 0.346099 | 0.123445 |
import subprocess
import docker
from ipaddress import ip_network
client = docker.from_env()
def manage_ufw():
for event in client.events(decode=True):
event_type = event.get('status')
# container network is attached on start or stop event
if event_type == 'start' or event_type == 'kill'... | src/ufw-docker-automated.py | import subprocess
import docker
from ipaddress import ip_network
client = docker.from_env()
def manage_ufw():
for event in client.events(decode=True):
event_type = event.get('status')
# container network is attached on start or stop event
if event_type == 'start' or event_type == 'kill'... | 0.349644 | 0.084758 |
import ines, os, sys
from binascii import a2b_hex
# [0]: Output file
# [1]: ROM file for first half of bank
# [2]: Address of 16-byte reset patch in first half (in $8000-$BFE0)
# [3]: ROM file for second half of bank
submultis = [
(
'../submulti/SM_JupiterScope2_SuperTiltBro.nes',
'../revised3/jup... | tools/autosubmulti.py | import ines, os, sys
from binascii import a2b_hex
# [0]: Output file
# [1]: ROM file for first half of bank
# [2]: Address of 16-byte reset patch in first half (in $8000-$BFE0)
# [3]: ROM file for second half of bank
submultis = [
(
'../submulti/SM_JupiterScope2_SuperTiltBro.nes',
'../revised3/jup... | 0.185873 | 0.330417 |
import os
from ASR.HuggingfaceASR import HuggingfaceASR
from VAD.webrtc import WebrtcVAD
from IntentDetector.sentence_transformer import SentenceTransformerIntents
from Recorder.localfile import LocalfileRecorder
from Recorder.pyaudio import PyaudioRecorder
from VAD.pyannote import PyannoteVAD
import sounddevice as sd
... | Alv/alv.py | import os
from ASR.HuggingfaceASR import HuggingfaceASR
from VAD.webrtc import WebrtcVAD
from IntentDetector.sentence_transformer import SentenceTransformerIntents
from Recorder.localfile import LocalfileRecorder
from Recorder.pyaudio import PyaudioRecorder
from VAD.pyannote import PyannoteVAD
import sounddevice as sd
... | 0.358915 | 0.110423 |
import time, threading
import math
import datetime
import mufadb as db
import mufabattle as mb
import mufagenerator as mg
StartTime=time.time()
def hourly_content_generation():
mg.generate_random_dungeons()
mg.dungeon_monsters_generate()
mg.global_monsters_generate()
def action() :
print('action ! -... | mufaintervals.py | import time, threading
import math
import datetime
import mufadb as db
import mufabattle as mb
import mufagenerator as mg
StartTime=time.time()
def hourly_content_generation():
mg.generate_random_dungeons()
mg.dungeon_monsters_generate()
mg.global_monsters_generate()
def action() :
print('action ! -... | 0.079284 | 0.109159 |
import pygame
from .cell import Cell
from .demineur import Demineur
display_width = 800
display_height = 900
black = (0, 0, 0)
white = (255, 255, 255)
red = (255, 0, 0)
grey = (125, 125, 125)
gameDisplay = pygame.display.set_mode((display_width, display_height))
def text_objects(text, font):
text_surface = fon... | src/graphical.py | import pygame
from .cell import Cell
from .demineur import Demineur
display_width = 800
display_height = 900
black = (0, 0, 0)
white = (255, 255, 255)
red = (255, 0, 0)
grey = (125, 125, 125)
gameDisplay = pygame.display.set_mode((display_width, display_height))
def text_objects(text, font):
text_surface = fon... | 0.260766 | 0.246165 |
from django.test import TestCase
from glyke_back.models import *
from glyke_back.forms import *
class AddProductFormTest(TestCase):
@classmethod
def setUpTestData(cls):
cls.correct_field_list = ['cost_price', 'selling_price', 'discount_percent', 'name', 'description', 'created_by', 'tags', 'stock', '... | tests/glyke_tests/tests_glyke_forms.py | from django.test import TestCase
from glyke_back.models import *
from glyke_back.forms import *
class AddProductFormTest(TestCase):
@classmethod
def setUpTestData(cls):
cls.correct_field_list = ['cost_price', 'selling_price', 'discount_percent', 'name', 'description', 'created_by', 'tags', 'stock', '... | 0.693058 | 0.498535 |
import pandas as pd
import src.utils as utils
from scipy.sparse import csr_matrix, hstack
from src.core.states import RunningState
from .base import Callback, CallbackOrder
# on_split_start
class CheckDataFrameCallback(Callback):
signature = "split"
calback_order = CallbackOrder.ASSERTION
def on_split... | src/core/callbacks/split.py | import pandas as pd
import src.utils as utils
from scipy.sparse import csr_matrix, hstack
from src.core.states import RunningState
from .base import Callback, CallbackOrder
# on_split_start
class CheckDataFrameCallback(Callback):
signature = "split"
calback_order = CallbackOrder.ASSERTION
def on_split... | 0.479991 | 0.240061 |
import copy
import math
import torch
from torch.utils.data import DistributedSampler as _DistributedSampler
class BalancedDistributedSampler(_DistributedSampler):
def __init__(self, dataset, num_replicas=None, rank=None, shuffle=True, num_instances=1):
super().__init__(dataset, num_replicas=num_replicas,... | mmaction/datasets/samplers/balanced_distributed_sampler.py | import copy
import math
import torch
from torch.utils.data import DistributedSampler as _DistributedSampler
class BalancedDistributedSampler(_DistributedSampler):
def __init__(self, dataset, num_replicas=None, rank=None, shuffle=True, num_instances=1):
super().__init__(dataset, num_replicas=num_replicas,... | 0.627267 | 0.449513 |
import numpy as np
import matplotlib.pyplot as plt
import EMStatics as EM
plt.close("all")
Charge = 1
Size = np.array([49, 49, 49], dtype = int)
approx_n = 0.1
exact = False
x0 = np.array([-1, -1, -1], dtype = float)
delta_x = np.array([2, 2, 2], dtype = float)
# Create J function
def J(dx, N, x0, c, mu0):
J_Arr... | OldExamples/StaticsPointCharge.py | import numpy as np
import matplotlib.pyplot as plt
import EMStatics as EM
plt.close("all")
Charge = 1
Size = np.array([49, 49, 49], dtype = int)
approx_n = 0.1
exact = False
x0 = np.array([-1, -1, -1], dtype = float)
delta_x = np.array([2, 2, 2], dtype = float)
# Create J function
def J(dx, N, x0, c, mu0):
J_Arr... | 0.804406 | 0.712023 |
"""Support for image defects"""
__all__ = ("Defects",)
import logging
import itertools
import contextlib
import numpy as np
import math
import numbers
import astropy.table
import libcosmicRays.geom as geom
import libcosmicRays.afw.table as afwTable
import libcosmicRays.afw.detection as afwDetection
import libcosmicR... | python/cosmicRays/defects.py | """Support for image defects"""
__all__ = ("Defects",)
import logging
import itertools
import contextlib
import numpy as np
import math
import numbers
import astropy.table
import libcosmicRays.geom as geom
import libcosmicRays.afw.table as afwTable
import libcosmicRays.afw.detection as afwDetection
import libcosmicR... | 0.84941 | 0.364099 |
import importlib
import argparse
import os
from os.path import join, isdir
from itertools import chain
import torch as pt
import torch.nn as nn
from torch.nn import init
from torch.utils.data import DataLoader
import numpy as np
from optimizer import OptimizerCollection
def load_config(file):
"""
initialize... | train_without_trainer.py | import importlib
import argparse
import os
from os.path import join, isdir
from itertools import chain
import torch as pt
import torch.nn as nn
from torch.nn import init
from torch.utils.data import DataLoader
import numpy as np
from optimizer import OptimizerCollection
def load_config(file):
"""
initialize... | 0.756987 | 0.238445 |
from det3d.core.utils.scatter import scatter_mean
from torch.nn import functional as F
from ..registry import READERS
from torch import nn
import numpy as np
import torch
def voxelization(points, pc_range, voxel_size):
keep = (points[:, 0] >= pc_range[0]) & (points[:, 0] <= pc_range[3]) & \
(points[:,... | det3d/models/readers/dynamic_voxel_encoder.py | from det3d.core.utils.scatter import scatter_mean
from torch.nn import functional as F
from ..registry import READERS
from torch import nn
import numpy as np
import torch
def voxelization(points, pc_range, voxel_size):
keep = (points[:, 0] >= pc_range[0]) & (points[:, 0] <= pc_range[3]) & \
(points[:,... | 0.588298 | 0.573738 |
import logging
import sys
import getpass
from kubernetes import config
from kubernetes.client import Configuration
from kubernetes.client.api import core_v1_api
from kubernetes.client.rest import ApiException
from kubernetes.stream import stream
LOGGER = logging.getLogger('support_bundles')
def init_logging():
... | utils/support-bundles.py |
import logging
import sys
import getpass
from kubernetes import config
from kubernetes.client import Configuration
from kubernetes.client.api import core_v1_api
from kubernetes.client.rest import ApiException
from kubernetes.stream import stream
LOGGER = logging.getLogger('support_bundles')
def init_logging():
... | 0.308398 | 0.056314 |
from datetime import datetime
import os
from subprocess import call
import numpy as np
import pandas as pd
from . import xray
def load_dataset_from_files(db, uid):
def load_adc_trace(filename=''):
df=pd.DataFrame()
keys = ['times', 'timens', 'counter', 'adc']
if os.path.isfile(filename):
... | xas/file_io.py | from datetime import datetime
import os
from subprocess import call
import numpy as np
import pandas as pd
from . import xray
def load_dataset_from_files(db, uid):
def load_adc_trace(filename=''):
df=pd.DataFrame()
keys = ['times', 'timens', 'counter', 'adc']
if os.path.isfile(filename):
... | 0.14685 | 0.150029 |
import unittest
import copy
import os
import shutil
from fv3config import ConfigError
from fv3config._tables import update_diag_table_for_config
from fv3config.config.derive import (
get_current_date,
_get_current_date_from_coupler_res,
_get_coupler_res_filename,
)
from fv3config._datastore import (
get... | tests/test_tables.py | import unittest
import copy
import os
import shutil
from fv3config import ConfigError
from fv3config._tables import update_diag_table_for_config
from fv3config.config.derive import (
get_current_date,
_get_current_date_from_coupler_res,
_get_coupler_res_filename,
)
from fv3config._datastore import (
get... | 0.45302 | 0.192293 |
import os
from attrdict import AttrDict
from deepsense import neptune
from utils import read_params, safe_eval
ctx = neptune.Context()
params = read_params(ctx)
CATEGORICAL_COLUMNS = ['CODE_GENDER',
'EMERGENCYSTATE_MODE',
'FLAG_CONT_MOBILE',
'FLAG... | pipeline_config.py | import os
from attrdict import AttrDict
from deepsense import neptune
from utils import read_params, safe_eval
ctx = neptune.Context()
params = read_params(ctx)
CATEGORICAL_COLUMNS = ['CODE_GENDER',
'EMERGENCYSTATE_MODE',
'FLAG_CONT_MOBILE',
'FLAG... | 0.237222 | 0.076996 |
\file GenerateRueMadameDataSet.py
\brief Script to generate the rue madame dataset.
\copyright Copyright (c) 2019 Visual Computing group of Ulm University,
Germany. See the LICENSE file at the top-level directory of
this distribution.
\author <NAME> (<EMAIL>)
''''''... | GenerateRueMadameDataSet.py | \file GenerateRueMadameDataSet.py
\brief Script to generate the rue madame dataset.
\copyright Copyright (c) 2019 Visual Computing group of Ulm University,
Germany. See the LICENSE file at the top-level directory of
this distribution.
\author <NAME> (<EMAIL>)
''''''... | 0.382949 | 0.254382 |
import os
import base64
import cv2
import pyotp
import pyqrcode
import png
from pyzbar import pyzbar
from cryptography.fernet import Fernet
from config import ConfigTempAccess
class OneTimePassword():
def __init__(self):
self.totp = pyotp.TOTP(ConfigTempAccess.BASE_32_KEY)
def get_new_base32_key(self... | temp_access.py | import os
import base64
import cv2
import pyotp
import pyqrcode
import png
from pyzbar import pyzbar
from cryptography.fernet import Fernet
from config import ConfigTempAccess
class OneTimePassword():
def __init__(self):
self.totp = pyotp.TOTP(ConfigTempAccess.BASE_32_KEY)
def get_new_base32_key(self... | 0.340595 | 0.128061 |
import h5py
import numpy as np
import os
import glob
import cv2
from matplotlib import pyplot
from sklearn.model_selection import train_test_split, cross_val_score
from sklearn.model_selection import KFold, StratifiedKFold, StratifiedShuffleSplit
from sklearn.model_selection import GridSearchCV
from sklearn.linear_mode... | pca_train_test.py | import h5py
import numpy as np
import os
import glob
import cv2
from matplotlib import pyplot
from sklearn.model_selection import train_test_split, cross_val_score
from sklearn.model_selection import KFold, StratifiedKFold, StratifiedShuffleSplit
from sklearn.model_selection import GridSearchCV
from sklearn.linear_mode... | 0.7324 | 0.325119 |
from discord import Embed
from discord.ext.commands import Cog, AutoShardedBot, group, Context, guild_only, has_permissions
from utils import get_prefix, get_language_config_by_id, get_language, get_translation, get_possible_translations, \
get_default_bible_translation
from config import config
import os
import ya... | cogs/settings.py | from discord import Embed
from discord.ext.commands import Cog, AutoShardedBot, group, Context, guild_only, has_permissions
from utils import get_prefix, get_language_config_by_id, get_language, get_translation, get_possible_translations, \
get_default_bible_translation
from config import config
import os
import ya... | 0.545528 | 0.065545 |
import datetime as dt
from decimal import Decimal
from django.core.exceptions import ValidationError
from django.test import RequestFactory, TestCase
from django.utils.translation import deactivate_all
from workbench import factories
from workbench.accounts.models import User
from workbench.planning import reporting
... | workbench/planning/test_planning.py | import datetime as dt
from decimal import Decimal
from django.core.exceptions import ValidationError
from django.test import RequestFactory, TestCase
from django.utils.translation import deactivate_all
from workbench import factories
from workbench.accounts.models import User
from workbench.planning import reporting
... | 0.350088 | 0.378746 |
from djblets.testing.decorators import add_fixtures
from reviewboard.deprecation import RemovedInReviewBoard50Warning
from reviewboard.diffviewer.parser import (BaseDiffParser,
DiffParser,
ParsedDiff,
... | reviewboard/diffviewer/tests/test_diff_parser.py |
from djblets.testing.decorators import add_fixtures
from reviewboard.deprecation import RemovedInReviewBoard50Warning
from reviewboard.diffviewer.parser import (BaseDiffParser,
DiffParser,
ParsedDiff,
... | 0.778649 | 0.527925 |
from functools import wraps
import traceback
from typing import TYPE_CHECKING, Callable, Optional
from flask import jsonify
import sentry_sdk
from expr.errors import Gibberish, NumberOverflow, UnknownPointer
import requests
from squid.bot.errors import CheckFailure, CommandFailed, SquidError
from squid.models.commands ... | squid/bot/bot.py | from functools import wraps
import traceback
from typing import TYPE_CHECKING, Callable, Optional
from flask import jsonify
import sentry_sdk
from expr.errors import Gibberish, NumberOverflow, UnknownPointer
import requests
from squid.bot.errors import CheckFailure, CommandFailed, SquidError
from squid.models.commands ... | 0.813831 | 0.137677 |
revision = '523c20aa695'
down_revision = None
branch_labels = None
depends_on = None
from alembic import op
import sqlalchemy as sa
def upgrade():
op.create_table('companies',
sa.Column('id', sa.Integer(), nullable=False),
sa.Column('name', sa.Unicode(length=200), nullable=False),
sa.Prim... | docs/testing/migrations/alembic/versions/523c20aa695_first_migration.py | revision = '523c20aa695'
down_revision = None
branch_labels = None
depends_on = None
from alembic import op
import sqlalchemy as sa
def upgrade():
op.create_table('companies',
sa.Column('id', sa.Integer(), nullable=False),
sa.Column('name', sa.Unicode(length=200), nullable=False),
sa.Prim... | 0.418459 | 0.129761 |
import board
import neopixel
import time
COUNTDOWN_BG = (0, 0, 255)
COUNTDOWN_FG = (0, 255, 255)
SUCCESS_MIN = (0, 17, 0)
SUCCESS_MAX = (0, 255, 0)
CONNECTING_BG = (38, 22, 81)
CONNECTING_FG = (116, 66, 244)
EFFECT_CONNECTING = 'Connecting'
EFFECT_COUNTDOWN = 'Countdown'
EFFECT_SUCCESS = 'Success'
EFFECT_MANUAL = 'M... | src/ring.py | import board
import neopixel
import time
COUNTDOWN_BG = (0, 0, 255)
COUNTDOWN_FG = (0, 255, 255)
SUCCESS_MIN = (0, 17, 0)
SUCCESS_MAX = (0, 255, 0)
CONNECTING_BG = (38, 22, 81)
CONNECTING_FG = (116, 66, 244)
EFFECT_CONNECTING = 'Connecting'
EFFECT_COUNTDOWN = 'Countdown'
EFFECT_SUCCESS = 'Success'
EFFECT_MANUAL = 'M... | 0.478041 | 0.185799 |
from marshmallow import Schema, fields
class PassengerSchema(Schema):
ps_id = fields.Number()
ps_token_id = fields.Str()
passenger_name = fields.Str()
passenger_email = fields.Str()
prof_pic = fields.Str()
is_ontrip = fields.Str()
crea... | schemas.py | from marshmallow import Schema, fields
class PassengerSchema(Schema):
ps_id = fields.Number()
ps_token_id = fields.Str()
passenger_name = fields.Str()
passenger_email = fields.Str()
prof_pic = fields.Str()
is_ontrip = fields.Str()
crea... | 0.413359 | 0.062732 |
import pandas as pd
import numpy as np
from rdtools import energy_from_power
import pytest
@pytest.fixture
def times():
return pd.date_range(start='20200101 12:00', end='20200101 13:00', freq='15T')
@pytest.fixture
def power(times):
return pd.Series([1.0, 2.0, 3.0, 2.0, 1.0], index=times)
def test_energy_... | rdtools/test/energy_from_power_test.py | import pandas as pd
import numpy as np
from rdtools import energy_from_power
import pytest
@pytest.fixture
def times():
return pd.date_range(start='20200101 12:00', end='20200101 13:00', freq='15T')
@pytest.fixture
def power(times):
return pd.Series([1.0, 2.0, 3.0, 2.0, 1.0], index=times)
def test_energy_... | 0.778902 | 0.820757 |
import numpy as np
from GPy.core import SparseGP
from GPy.likelihoods import Gaussian
from GPy.inference.latent_function_inference import VarDTC
from paramz.transformations import Logexp
from GPy.core.parameterization import Param
from kb_learning.kernel import KilobotEnvKernel
import logging
logger = logging.getLogg... | kb_learning/ac_reps/gpy_spwgp.py | import numpy as np
from GPy.core import SparseGP
from GPy.likelihoods import Gaussian
from GPy.inference.latent_function_inference import VarDTC
from paramz.transformations import Logexp
from GPy.core.parameterization import Param
from kb_learning.kernel import KilobotEnvKernel
import logging
logger = logging.getLogg... | 0.880019 | 0.442155 |
import os
import logging
import csv
from core.general.exceptions import SIDException
from core.general.sidhelper import generate_filename, convert_field
class Reader():
"""
The class responsiblities are:
Read csv file, header record etc
if you want to use this class on its o... | src/core/connectors/file/reader.py | import os
import logging
import csv
from core.general.exceptions import SIDException
from core.general.sidhelper import generate_filename, convert_field
class Reader():
"""
The class responsiblities are:
Read csv file, header record etc
if you want to use this class on its o... | 0.313105 | 0.0524 |
from lib.elbo_depth import gaussian_log_prob, laplacian_log_prob
from lib.utils.torch_utils import apply_dropout
from tqdm import tqdm
import torch
import numpy as np
import cv2
import matplotlib.pyplot as plt
from time import time
def _compute_runtime_mcd_depth(model, X_test, S=50):
model.eval()
model.apply(apply_... | lib/utils/mcd_depth_utils.py | from lib.elbo_depth import gaussian_log_prob, laplacian_log_prob
from lib.utils.torch_utils import apply_dropout
from tqdm import tqdm
import torch
import numpy as np
import cv2
import matplotlib.pyplot as plt
from time import time
def _compute_runtime_mcd_depth(model, X_test, S=50):
model.eval()
model.apply(apply_... | 0.467575 | 0.319241 |
from __future__ import division
import numpy as np
from .. import sympix_mg
from ....sphere import sympix, beams, scatter_l_to_lm, sharp
def hammer(n, m, op):
u = np.zeros(m)
out = np.zeros((n, m))
for j in range(m):
u[j] = 1
out[:, j] = op(u)
u[j] = 0
return out
def as_dens... | test_sympix_mg.py | from __future__ import division
import numpy as np
from .. import sympix_mg
from ....sphere import sympix, beams, scatter_l_to_lm, sharp
def hammer(n, m, op):
u = np.zeros(m)
out = np.zeros((n, m))
for j in range(m):
u[j] = 1
out[:, j] = op(u)
u[j] = 0
return out
def as_dens... | 0.550124 | 0.312042 |
import uuid
import django.db.models.deletion
from django.conf import settings
from django.db import migrations, models
from tahoe_sites import zd_helpers
class Migration(migrations.Migration):
initial = True
dependencies = [
('organizations', '0011_historicalorganization_edx_uuid'),
migra... | tahoe_sites/migrations/0001_initial.py |
import uuid
import django.db.models.deletion
from django.conf import settings
from django.db import migrations, models
from tahoe_sites import zd_helpers
class Migration(migrations.Migration):
initial = True
dependencies = [
('organizations', '0011_historicalorganization_edx_uuid'),
migra... | 0.516352 | 0.127625 |
from bigquery_views_manager.view_template import ViewTemplate
TEMPLATE_1 = "SELECT * FROM `{project}.{dataset}.table1"
DATASET = "dataset1"
VIEW_1 = "table1"
VIEW_2 = "table2"
VIEW_TO_DATASET_MAPPING = {VIEW_1: DATASET, VIEW_2: DATASET}
class TestViewTemplate:
def test_should_replace_multiple_project_and_datase... | tests/view_template_test.py | from bigquery_views_manager.view_template import ViewTemplate
TEMPLATE_1 = "SELECT * FROM `{project}.{dataset}.table1"
DATASET = "dataset1"
VIEW_1 = "table1"
VIEW_2 = "table2"
VIEW_TO_DATASET_MAPPING = {VIEW_1: DATASET, VIEW_2: DATASET}
class TestViewTemplate:
def test_should_replace_multiple_project_and_datase... | 0.657098 | 0.305289 |
from powerapi.message import UnknowMessageTypeException
from powerapi.handler import Handler
from powerapi.actor import Supervisor
class TimeoutHandler(Handler):
"""
Handler used when a timeout occurs
"""
def handle(self, msg, state):
"""
ignore the timeout and return the actual actor... | powerapi/actor/state.py | from powerapi.message import UnknowMessageTypeException
from powerapi.handler import Handler
from powerapi.actor import Supervisor
class TimeoutHandler(Handler):
"""
Handler used when a timeout occurs
"""
def handle(self, msg, state):
"""
ignore the timeout and return the actual actor... | 0.773601 | 0.204401 |
import socketserver
from http.server import HTTPServer, BaseHTTPRequestHandler
from w1thermsensor import W1ThermSensor
SENSORS = None
def rescan_sensors():
global SENSORS
SENSORS = W1ThermSensor.get_available_sensors()
rescan_sensors()
class Exporter(BaseHTTPRequestHandler):
METRIC_HEADER = ('# HELP w1... | w1therm_prometheus_exporter.py |
import socketserver
from http.server import HTTPServer, BaseHTTPRequestHandler
from w1thermsensor import W1ThermSensor
SENSORS = None
def rescan_sensors():
global SENSORS
SENSORS = W1ThermSensor.get_available_sensors()
rescan_sensors()
class Exporter(BaseHTTPRequestHandler):
METRIC_HEADER = ('# HELP w1... | 0.663778 | 0.117218 |
import datetime
import json
from django.db import models
from django.contrib.auth import get_user_model
from crum import get_current_user
from django.utils.timezone import utc
import django.core.exceptions as ex
import string
import random
# Create your models here.
max_links = 3
id_length = 20
MAX = 2000
def get... | DevOlogy/core/models.py | import datetime
import json
from django.db import models
from django.contrib.auth import get_user_model
from crum import get_current_user
from django.utils.timezone import utc
import django.core.exceptions as ex
import string
import random
# Create your models here.
max_links = 3
id_length = 20
MAX = 2000
def get... | 0.39222 | 0.111048 |
from django.conf.urls import patterns, url
from wijn import views
urlpatterns = patterns('',
url(r'^$', views.index, name='index'),
url(r'^subregio/(?P<regio>[\w -]+)$', views.subregio, name='subregio'),
url(r'^subregio$', views.regiokiezer, {'next': 'subregio'}, name='regiokiezer-subregio'),
url(r'^k... | wijn/urls.py | from django.conf.urls import patterns, url
from wijn import views
urlpatterns = patterns('',
url(r'^$', views.index, name='index'),
url(r'^subregio/(?P<regio>[\w -]+)$', views.subregio, name='subregio'),
url(r'^subregio$', views.regiokiezer, {'next': 'subregio'}, name='regiokiezer-subregio'),
url(r'^k... | 0.189259 | 0.103205 |
from __future__ import annotations
import json
import sys
from pathlib import Path
from typing import Any, Callable, Generator
from meilisearch.client import Client
from meilisearch.config import Config
from meilisearch.errors import MeiliSearchApiError, MeiliSearchError
from meilisearch.index import Index
from meili... | meilisearch_cli/_helpers.py | from __future__ import annotations
import json
import sys
from pathlib import Path
from typing import Any, Callable, Generator
from meilisearch.client import Client
from meilisearch.config import Config
from meilisearch.errors import MeiliSearchApiError, MeiliSearchError
from meilisearch.index import Index
from meili... | 0.394434 | 0.164483 |
import argparse
import json
import os
import sys
import warnings
from pathlib import Path
import dill as pkl
import numpy as np
import pandas as pd
from sklearn.exceptions import UndefinedMetricWarning
from sklearn.metrics import f1_score
from aaai20.exp import collect_results, collect_timings
from aaai20.io import (... | cli/fit/fit_pxs.py | import argparse
import json
import os
import sys
import warnings
from pathlib import Path
import dill as pkl
import numpy as np
import pandas as pd
from sklearn.exceptions import UndefinedMetricWarning
from sklearn.metrics import f1_score
from aaai20.exp import collect_results, collect_timings
from aaai20.io import (... | 0.442155 | 0.131062 |
import json
import sys
sys.dont_write_bytecode = True
import numpy as np
import datetime
import random
import math
import core
def run(debug):
# this strategy works best at 1hr intervals
# 1. the idea is based on calculating the slope of the current price (which is a random price at interval 't') against the... | backtest/algos/trash/algo_asteria_v1.py | import json
import sys
sys.dont_write_bytecode = True
import numpy as np
import datetime
import random
import math
import core
def run(debug):
# this strategy works best at 1hr intervals
# 1. the idea is based on calculating the slope of the current price (which is a random price at interval 't') against the... | 0.094658 | 0.298127 |
try:
import vim
except:
print("No vim module available outside vim")
pass
import json
import openai
from os import path
with open(path.expanduser("~/.openai/credentials.json")) as f:
config = json.load(f)
openai.organization = config["organizationId"]
openai.api_key = config["secretKey"]
MAX_SUPPOR... | python/plugin.py | try:
import vim
except:
print("No vim module available outside vim")
pass
import json
import openai
from os import path
with open(path.expanduser("~/.openai/credentials.json")) as f:
config = json.load(f)
openai.organization = config["organizationId"]
openai.api_key = config["secretKey"]
MAX_SUPPOR... | 0.16248 | 0.092319 |
from typing import Any, TypeVar, List, Set, Dict, Tuple, Optional, Union
from grapl_analyzerlib.analyzer import OneOrMany
from grapl_analyzerlib.node_types import (
EdgeT,
PropType,
)
from grapl_analyzerlib.nodes.entity import EntityQuery, EntityView, EntitySchema
from grapl_analyzerlib.queryable import (
... | src/python/grapl_analyzerlib/grapl_analyzerlib/nodes/process.py | from typing import Any, TypeVar, List, Set, Dict, Tuple, Optional, Union
from grapl_analyzerlib.analyzer import OneOrMany
from grapl_analyzerlib.node_types import (
EdgeT,
PropType,
)
from grapl_analyzerlib.nodes.entity import EntityQuery, EntityView, EntitySchema
from grapl_analyzerlib.queryable import (
... | 0.903204 | 0.292292 |
import pandas as pd
SEPORATOR = "\n> "
# stores the card's data and output it
class Card:
def __init__(self, CardName):
# This way I don't need to upload to linux virtual machine
df = pd.read_csv("./data/CardData.csv")
df.fillna(0, inplace=True)
df["Name"] = df["Name"].str.lower()... | CustomClasses/CardData.py | import pandas as pd
SEPORATOR = "\n> "
# stores the card's data and output it
class Card:
def __init__(self, CardName):
# This way I don't need to upload to linux virtual machine
df = pd.read_csv("./data/CardData.csv")
df.fillna(0, inplace=True)
df["Name"] = df["Name"].str.lower()... | 0.225843 | 0.189671 |
import numpy as np
from diffpriv_laplace.statistics import DiffPrivStatistics
class DiffPrivSequentialStatisticsQuery(object):
"""
The sequential composition statistics query class.
"""
@classmethod
def query_count(cls, kinds):
"""
Determines the amount of queries to perform.
... | diffpriv_laplace/query/sequential_statistics.py | import numpy as np
from diffpriv_laplace.statistics import DiffPrivStatistics
class DiffPrivSequentialStatisticsQuery(object):
"""
The sequential composition statistics query class.
"""
@classmethod
def query_count(cls, kinds):
"""
Determines the amount of queries to perform.
... | 0.941835 | 0.744981 |
import tensorflow as tf
import logging
from tensorflow.contrib.layers import flatten
from .general_utils import batch_normalization
# configure the logger
logging.basicConfig(level=logging.INFO)
logger = logging.getLogger(__name__)
class VGG(object):
def __init__(self, training, keep_prob=1.0, num_layers=19,
... | core/vgg.py | import tensorflow as tf
import logging
from tensorflow.contrib.layers import flatten
from .general_utils import batch_normalization
# configure the logger
logging.basicConfig(level=logging.INFO)
logger = logging.getLogger(__name__)
class VGG(object):
def __init__(self, training, keep_prob=1.0, num_layers=19,
... | 0.88707 | 0.21984 |
import math
from ..constants import CONSUMERS_PER_PAGE
def paginate_result_list_by_changing_excess_data_to_ids(result_list, rqst_page_no, base_url):
page_urls = []
def remove_all_keys_from_db_instance_info_dict_except_db_id(db_instance_info_dict):
for key in list(db_instance_info_dict):
i... | picbackend/views/v2/consumer_views/tools/read.py | import math
from ..constants import CONSUMERS_PER_PAGE
def paginate_result_list_by_changing_excess_data_to_ids(result_list, rqst_page_no, base_url):
page_urls = []
def remove_all_keys_from_db_instance_info_dict_except_db_id(db_instance_info_dict):
for key in list(db_instance_info_dict):
i... | 0.176494 | 0.088151 |
import requests
import sys
import re
device_host = "http://192.168.42.253"
paths = {
"deviceInfo": {
"path": "/html/status/deviceinfo.asp",
"regex": r"(?:stDeviceInfo\(\".*)(?:\",\")(?P<ProductType>.*)(?:\",\")(?P<DeviceID1>.*)(?:\",\")(?P<HardwareVersion>.*)(?:\",\")(?P<SoftwareVersion>.*)(?:\",... | main.py | import requests
import sys
import re
device_host = "http://192.168.42.253"
paths = {
"deviceInfo": {
"path": "/html/status/deviceinfo.asp",
"regex": r"(?:stDeviceInfo\(\".*)(?:\",\")(?P<ProductType>.*)(?:\",\")(?P<DeviceID1>.*)(?:\",\")(?P<HardwareVersion>.*)(?:\",\")(?P<SoftwareVersion>.*)(?:\",... | 0.197058 | 0.251039 |
import unittest
import opticalglass.glassfactory as gf
class TransmissionTestCase(unittest.TestCase):
def compare_transmission(self, glass, wl1, t1, wl2, t2, num_t, tol=5e-4):
t_data = glass.transmission_data()
self.assertEqual(wl1, t_data[0][0])
self.assertAlmostEqual(t1, t_data[0][1], d... | opticalglass/test/test_transmission.py | import unittest
import opticalglass.glassfactory as gf
class TransmissionTestCase(unittest.TestCase):
def compare_transmission(self, glass, wl1, t1, wl2, t2, num_t, tol=5e-4):
t_data = glass.transmission_data()
self.assertEqual(wl1, t_data[0][0])
self.assertAlmostEqual(t1, t_data[0][1], d... | 0.135018 | 0.554712 |
from django.db import models
class PartsAuthority(models.Model):
id = models.BigAutoField('Id', primary_key=True)
line = models.CharField('Line', max_length=100, blank=True, null=True)
part = models.CharField('Part', max_length=100, blank=True, null=True)
cost = models.CharField('Cost',max_length=100, blank=True,n... | apps/import_excel/models/import_excel.py | from django.db import models
class PartsAuthority(models.Model):
id = models.BigAutoField('Id', primary_key=True)
line = models.CharField('Line', max_length=100, blank=True, null=True)
part = models.CharField('Part', max_length=100, blank=True, null=True)
cost = models.CharField('Cost',max_length=100, blank=True,n... | 0.463444 | 0.237808 |
import librosa
import numpy as np
import torch
class LibrosaMelSpectrogram:
"""
Defining and computing a mel-spectrogram transform using pre-defined parameters
Input:
init args:
sr: sample rate
n_mels: number of mel frequency bins
fmin: minimum frequency
... | soundbay/utils/signal_processing.py | import librosa
import numpy as np
import torch
class LibrosaMelSpectrogram:
"""
Defining and computing a mel-spectrogram transform using pre-defined parameters
Input:
init args:
sr: sample rate
n_mels: number of mel frequency bins
fmin: minimum frequency
... | 0.780621 | 0.549459 |
import os
class Cryto:
@property
def Description(self):
return('加解密工具')
def decryp_Vige():
cyphertext = input("cyphertext=")
key = input("key=")
print("plaintext=", end='')
j = 0
for i in cyphertext:
c = ord(key[j])
if c < 97:
... | source/functions/encryption.py | import os
class Cryto:
@property
def Description(self):
return('加解密工具')
def decryp_Vige():
cyphertext = input("cyphertext=")
key = input("key=")
print("plaintext=", end='')
j = 0
for i in cyphertext:
c = ord(key[j])
if c < 97:
... | 0.150309 | 0.193376 |
from django.conf import settings
from pathlib import Path
import os
import datetime
import logging
import time
import threading
import re
from django.urls import reverse
import markdown
import subprocess
def mimetype_to_icon(mimetype):
type2icon = {
'image': 'file-picture',
'audio': 'file-music',
... | joplin_vieweb/utils.py | from django.conf import settings
from pathlib import Path
import os
import datetime
import logging
import time
import threading
import re
from django.urls import reverse
import markdown
import subprocess
def mimetype_to_icon(mimetype):
type2icon = {
'image': 'file-picture',
'audio': 'file-music',
... | 0.292797 | 0.102979 |
import os
os.chdir(os.path.dirname(os.path.realpath(__file__)))
import numpy as np
import torch
from torch.autograd import Variable
import torch.nn.functional as F
import random
# MNIST classifier for test of concept
class classifierMNISTCNN(torch.nn.Module):
def __init__ (self, initus, exitus, bias=False, lr=0... | networks.py | import os
os.chdir(os.path.dirname(os.path.realpath(__file__)))
import numpy as np
import torch
from torch.autograd import Variable
import torch.nn.functional as F
import random
# MNIST classifier for test of concept
class classifierMNISTCNN(torch.nn.Module):
def __init__ (self, initus, exitus, bias=False, lr=0... | 0.839898 | 0.462048 |
from os import listdir, path
from urllib.parse import urlunsplit
import xyzzyy
from elp.session import Student
from flask import Flask, jsonify, request, send_file, send_from_directory
app = Flask(
__name__, static_url_path="/node_modules", static_folder="node_modules"
)
@app.route("/")
def index():
return ... | app.py | from os import listdir, path
from urllib.parse import urlunsplit
import xyzzyy
from elp.session import Student
from flask import Flask, jsonify, request, send_file, send_from_directory
app = Flask(
__name__, static_url_path="/node_modules", static_folder="node_modules"
)
@app.route("/")
def index():
return ... | 0.350755 | 0.069352 |
from __future__ import absolute_import
import unittest
import swagger_client
from swagger_client.api.asset_group_api import AssetGroupApi # noqa: E501
from swagger_client.rest import ApiException
class TestAssetGroupApi(unittest.TestCase):
"""AssetGroupApi unit test stubs"""
def setUp(self):
self.... | test/test_asset_group_api.py | from __future__ import absolute_import
import unittest
import swagger_client
from swagger_client.api.asset_group_api import AssetGroupApi # noqa: E501
from swagger_client.rest import ApiException
class TestAssetGroupApi(unittest.TestCase):
"""AssetGroupApi unit test stubs"""
def setUp(self):
self.... | 0.576661 | 0.107625 |
import time
import Inthrm1
import conf
import sys
import numpy
import random
import casrs
def CASRES(NEVENT,IBADTT1,IBAD1):
# IMPLICIT #real*8 (A-H,O-Z)
# IMPLICIT #integer*8 (I-N)
def get_globals():
NPTP=conf.NPTP
EPPST=conf.EPPST
XPP=conf.XPP
YPP=conf.YPP
ZPP=conf.ZPP
DRXPP=conf.DRXPP
DRYPP=conf.DR... | Casres.py | import time
import Inthrm1
import conf
import sys
import numpy
import random
import casrs
def CASRES(NEVENT,IBADTT1,IBAD1):
# IMPLICIT #real*8 (A-H,O-Z)
# IMPLICIT #integer*8 (I-N)
def get_globals():
NPTP=conf.NPTP
EPPST=conf.EPPST
XPP=conf.XPP
YPP=conf.YPP
ZPP=conf.ZPP
DRXPP=conf.DRXPP
DRYPP=conf.DR... | 0.032146 | 0.069985 |
from __future__ import division
from collections import namedtuple
import math
import numpy as np
import torch
import torch.nn as nn
import torch.nn.functional as F
from torch.autograd.function import InplaceFunction, Function
"""
Tensor-wise Dynamic Fixed-Point
"""
class Quantization(InplaceFunction):
'''
Fo... | modules/dfx.py | from __future__ import division
from collections import namedtuple
import math
import numpy as np
import torch
import torch.nn as nn
import torch.nn.functional as F
from torch.autograd.function import InplaceFunction, Function
"""
Tensor-wise Dynamic Fixed-Point
"""
class Quantization(InplaceFunction):
'''
Fo... | 0.897201 | 0.363096 |