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 |
|---|---|---|---|---|
# revision identifiers, used by Alembic.
revision = '0fb66069a81f'
down_revision = '<PASSWORD>'
branch_labels = None
from alembic import op
import sqlalchemy as sa
import textwrap
def postgres_drop_tables():
op.drop_table('maintenance_record')
op.drop_table('fru')
op.drop_table('fru_type')
op.drop_ta... | contrib/database/schema_migration/versions/0fb66069a81f_schema_cleanup_removing_unused_tables.py | # revision identifiers, used by Alembic.
revision = '0fb66069a81f'
down_revision = '<PASSWORD>'
branch_labels = None
from alembic import op
import sqlalchemy as sa
import textwrap
def postgres_drop_tables():
op.drop_table('maintenance_record')
op.drop_table('fru')
op.drop_table('fru_type')
op.drop_ta... | 0.356335 | 0.137996 |
# Import setuptools before distutils so setuptools can monkey-patch distutils.
import setuptools
from setuptools import setup
# Python
import ctypes
import glob
import os
import sys
# Verify that setup is running on the Windows platform.
if sys.platform == 'win32':
# Try to import all the 3rd party libraries re... | setup.py |
# Import setuptools before distutils so setuptools can monkey-patch distutils.
import setuptools
from setuptools import setup
# Python
import ctypes
import glob
import os
import sys
# Verify that setup is running on the Windows platform.
if sys.platform == 'win32':
# Try to import all the 3rd party libraries re... | 0.290176 | 0.098729 |
from pytictoc import TicToc
import numpy as np
pi = np.pi
import matplotlib.pyplot as plt
from utilities import awgn, ls, detectpeaksort, freqsort, load
from uni_esprit import uni_esprit
from relax import relax
from cfh import cfh
from nomp.nomp import nomp
# Define signal parameters
N = 2**7
K = 5
snr = 30
d = 2/N
... | example.py | from pytictoc import TicToc
import numpy as np
pi = np.pi
import matplotlib.pyplot as plt
from utilities import awgn, ls, detectpeaksort, freqsort, load
from uni_esprit import uni_esprit
from relax import relax
from cfh import cfh
from nomp.nomp import nomp
# Define signal parameters
N = 2**7
K = 5
snr = 30
d = 2/N
... | 0.686475 | 0.545891 |
import tempfile
import unittest
import unittest.mock
import requests
import PyFunceble.helpers.exceptions
from PyFunceble.helpers.download import DownloadHelper
class TestDownloadHelper(unittest.TestCase):
"""
Tests of the download helper.
"""
def test_set_url_return(self) -> None:
"""
... | tests/helpers/test_download.py | import tempfile
import unittest
import unittest.mock
import requests
import PyFunceble.helpers.exceptions
from PyFunceble.helpers.download import DownloadHelper
class TestDownloadHelper(unittest.TestCase):
"""
Tests of the download helper.
"""
def test_set_url_return(self) -> None:
"""
... | 0.798344 | 0.741955 |
from diffir.measure import Measure
from scipy import stats
import numpy as np
class TopkMeasure(Measure):
module_name = "topk"
def tauap(self, x, y, decreasing=True):
"""
AP Rank correalation Coefficient
:param x: a list of scores
:param y: another list of scores for comparisi... | diffir/measure/unsupervised.py | from diffir.measure import Measure
from scipy import stats
import numpy as np
class TopkMeasure(Measure):
module_name = "topk"
def tauap(self, x, y, decreasing=True):
"""
AP Rank correalation Coefficient
:param x: a list of scores
:param y: another list of scores for comparisi... | 0.786213 | 0.557604 |
import re
import numpy
from geoh5py.groups import RootGroup
from geoh5py.workspace import Workspace
from ipywidgets.widgets import Button, HBox, Layout, Text, Textarea, VBox
from geoapps.plotting import plot_plan_data_selection
from geoapps.selection import ObjectDataSelection
class Calculator(ObjectDataSelection)... | geoapps/processing/calculator.py |
import re
import numpy
from geoh5py.groups import RootGroup
from geoh5py.workspace import Workspace
from ipywidgets.widgets import Button, HBox, Layout, Text, Textarea, VBox
from geoapps.plotting import plot_plan_data_selection
from geoapps.selection import ObjectDataSelection
class Calculator(ObjectDataSelection)... | 0.750095 | 0.300771 |
from typing import Dict, List, Tuple
from .matrices import ConsensusMatrixContainer
from .performance import timeit
@timeit()
def fill_consensus_position_matrix(
row_count: int,
column_count: int,
start_all: int,
subfams: List[str],
chroms: List[str],
starts: List[int],
stops: List[int],
... | polyA/fill_consensus_position_matrix.py | from typing import Dict, List, Tuple
from .matrices import ConsensusMatrixContainer
from .performance import timeit
@timeit()
def fill_consensus_position_matrix(
row_count: int,
column_count: int,
start_all: int,
subfams: List[str],
chroms: List[str],
starts: List[int],
stops: List[int],
... | 0.795936 | 0.663437 |
from urllib.request import urlopen
from bs4 import BeautifulSoup
import re
_url = 'http://{0}/sts_sci_md00_001.do?schulCode={1}&schulCrseScCode=4&schulKndScScore=04&schYm={2}{3:0>2}'
SEOUL = 'stu.sen.go.kr'
BUSAN = 'stu.pen.go.kr'
DAEGU = 'stu.dge.go.kr'
INCHEON = 'stu.ice.go.kr'
GWANGJU = 'stu.gen.go.kr'
DAEJEON = ... | schapi/api.py | from urllib.request import urlopen
from bs4 import BeautifulSoup
import re
_url = 'http://{0}/sts_sci_md00_001.do?schulCode={1}&schulCrseScCode=4&schulKndScScore=04&schYm={2}{3:0>2}'
SEOUL = 'stu.sen.go.kr'
BUSAN = 'stu.pen.go.kr'
DAEGU = 'stu.dge.go.kr'
INCHEON = 'stu.ice.go.kr'
GWANGJU = 'stu.gen.go.kr'
DAEJEON = ... | 0.419053 | 0.241277 |
import csv;
import datetime
from sqlalchemy import Column, ForeignKey, Integer, String, Date, Boolean
from sqlalchemy import create_engine
from sqlalchemy.ext.declarative import declarative_base
from sqlalchemy.orm import relationship
from sqlalchemy.orm import sessionmaker
from pprint import pprint
SQLITE_CONNECTIO... | bosc020/challenge/teil1/import_csv_data.py | import csv;
import datetime
from sqlalchemy import Column, ForeignKey, Integer, String, Date, Boolean
from sqlalchemy import create_engine
from sqlalchemy.ext.declarative import declarative_base
from sqlalchemy.orm import relationship
from sqlalchemy.orm import sessionmaker
from pprint import pprint
SQLITE_CONNECTIO... | 0.381565 | 0.180359 |
import os
import argparse
import json
import cv2
import pandas as pd
def create_coco(imagefolder, labelfolder, jsonpath):
cocofile = {
"info":{
"year": 2020,
"version": 1,
"description": "VIP CUP 2020"
},
"categories":[
{"id": 0, "name": "veh... | vipcup/yolo_to_coco.py | import os
import argparse
import json
import cv2
import pandas as pd
def create_coco(imagefolder, labelfolder, jsonpath):
cocofile = {
"info":{
"year": 2020,
"version": 1,
"description": "VIP CUP 2020"
},
"categories":[
{"id": 0, "name": "veh... | 0.319015 | 0.214753 |
import boto
import codecs
from oslib.command import Command, OSLibError
import time
import string
import difflib
class Console(Command):
"""This class is used to display the console of an existing instance
"""
object = 'instance'
verb = 'console'
def fill_parser(self, parser):
if self.object =... | oslib/instance/console.py | import boto
import codecs
from oslib.command import Command, OSLibError
import time
import string
import difflib
class Console(Command):
"""This class is used to display the console of an existing instance
"""
object = 'instance'
verb = 'console'
def fill_parser(self, parser):
if self.object =... | 0.139954 | 0.104204 |
import copy as cp
from skmultiflow.core.base import StreamModel
from skmultiflow.classification.lazy.knn_adwin import KNNAdwin
from skmultiflow.core.utils.utils import *
class OzaBagging(StreamModel):
""" OzaBagging Classifier
Oza Bagging is an ensemble learning method first introduced by Oza and
Ru... | src/skmultiflow/classification/meta/oza_bagging.py | import copy as cp
from skmultiflow.core.base import StreamModel
from skmultiflow.classification.lazy.knn_adwin import KNNAdwin
from skmultiflow.core.utils.utils import *
class OzaBagging(StreamModel):
""" OzaBagging Classifier
Oza Bagging is an ensemble learning method first introduced by Oza and
Ru... | 0.752468 | 0.643413 |
# --- imports -----------------------------------------------------------------
import torch.nn as nn
import tensorflow as tf
import torch.nn.functional as F
from network.wrappers.NetworkBase import NetworkBase
class VGG19_tf(NetworkBase):
def __init__(self, network_type, loss, accuracy, lr, framework, trainin... | network/wrappers/VGG19.py |
# --- imports -----------------------------------------------------------------
import torch.nn as nn
import tensorflow as tf
import torch.nn.functional as F
from network.wrappers.NetworkBase import NetworkBase
class VGG19_tf(NetworkBase):
def __init__(self, network_type, loss, accuracy, lr, framework, trainin... | 0.929536 | 0.437042 |
from pybedtools import BedTool
import os
import pandas as pd
class Encode():
def __init__(self, gene_locations_path):
self.gene_locations = pd.read_csv(gene_locations_path, sep='\t')
self.gene_locations.columns = ['chrom', 'txStart', 'txEnd', 'cdsStart', 'cdsEnd', 'symbol', 'name', 'strand']
def get_ts... | miscseq/encode.py | from pybedtools import BedTool
import os
import pandas as pd
class Encode():
def __init__(self, gene_locations_path):
self.gene_locations = pd.read_csv(gene_locations_path, sep='\t')
self.gene_locations.columns = ['chrom', 'txStart', 'txEnd', 'cdsStart', 'cdsEnd', 'symbol', 'name', 'strand']
def get_ts... | 0.383295 | 0.466299 |
from threeML import load_analysis_results
import numpy as np
import pynchrotron
res_spi = load_analysis_results("results/result_pyspi4_syn_grb.fits")
res_gbm = load_analysis_results("results/result_gbm3_syn_grb.fits")
res_both = load_analysis_results("results/result_both3_syn_grb.fits")
num_samples = 300
samples_spi ... | src/figures/model_plot_syn.py | from threeML import load_analysis_results
import numpy as np
import pynchrotron
res_spi = load_analysis_results("results/result_pyspi4_syn_grb.fits")
res_gbm = load_analysis_results("results/result_gbm3_syn_grb.fits")
res_both = load_analysis_results("results/result_both3_syn_grb.fits")
num_samples = 300
samples_spi ... | 0.501953 | 0.446434 |
from collections import OrderedDict
from operator import attrgetter
from . import errors
class Response(object):
def __init__(self, request):
self.meta = {
'pagination': None,
}
self.headers = {}
self.request = request
self.error = None
self.response_... | thorium/response.py |
from collections import OrderedDict
from operator import attrgetter
from . import errors
class Response(object):
def __init__(self, request):
self.meta = {
'pagination': None,
}
self.headers = {}
self.request = request
self.error = None
self.response_... | 0.687525 | 0.0697 |
__author__ = "<NAME>"
__version__ = "0.1"
import os, sys
from contextlib import contextmanager
import numpy as np
import astropy
from astropy import units as u
from astropy.table import QTable, Table, Column
from astropy.io import fits
from colorama import Fore
from colorama import init
init(autoreset=True)
import ... | gleam/main.py | __author__ = "<NAME>"
__version__ = "0.1"
import os, sys
from contextlib import contextmanager
import numpy as np
import astropy
from astropy import units as u
from astropy.table import QTable, Table, Column
from astropy.io import fits
from colorama import Fore
from colorama import init
init(autoreset=True)
import ... | 0.602997 | 0.293658 |
import argparse
import json
import logging
import sys
from datetime import timedelta
from pprint import pprint
import arrow
from blackduck import Client
from blackduck.Utils import get_resource_name
logging.basicConfig(format='%(asctime)s:%(levelname)s:%(message)s', stream=sys.stderr, level=logging.DEBUG)
logging.get... | examples/download_all_scans.py | import argparse
import json
import logging
import sys
from datetime import timedelta
from pprint import pprint
import arrow
from blackduck import Client
from blackduck.Utils import get_resource_name
logging.basicConfig(format='%(asctime)s:%(levelname)s:%(message)s', stream=sys.stderr, level=logging.DEBUG)
logging.get... | 0.192198 | 0.061537 |
import gym
import numpy as np
import paddle
from model import Model
from replay_memory import ReplayMemory
# 定义训练的参数
batch_size = 64 # batch大小
num_episodes = 10000 # 训练次数
memory_size = 10000 # 内存记忆
learning_rate = 1e-3 # 学习率大小
gamma = 1.0 # 奖励系数
e_greed = 0.1 # 探索初始概率
e_greed_decrement = 1e-6 # 在训练过程中,降低探索的概率
u... | DQN-CartPole/train.py | import gym
import numpy as np
import paddle
from model import Model
from replay_memory import ReplayMemory
# 定义训练的参数
batch_size = 64 # batch大小
num_episodes = 10000 # 训练次数
memory_size = 10000 # 内存记忆
learning_rate = 1e-3 # 学习率大小
gamma = 1.0 # 奖励系数
e_greed = 0.1 # 探索初始概率
e_greed_decrement = 1e-6 # 在训练过程中,降低探索的概率
u... | 0.419291 | 0.34392 |
try:
from IPython.core import DataMetadata, RecursiveObject, ReprGetter, get_repr_mimebundle
except ImportError:
from collections import namedtuple
class RecursiveObject:
"""
Default recursive object that provides a recursion repr if needed.
You may register a formatter for this ob... | disp/vendor.py | try:
from IPython.core import DataMetadata, RecursiveObject, ReprGetter, get_repr_mimebundle
except ImportError:
from collections import namedtuple
class RecursiveObject:
"""
Default recursive object that provides a recursion repr if needed.
You may register a formatter for this ob... | 0.817392 | 0.345657 |
from maro.rl.actor.simple_actor import SimpleActor
from maro.rl.agent.abs_agent_manager import AbsAgentManager
from maro.utils import DummyLogger
from .abs_learner import AbsLearner
class SimpleLearner(AbsLearner):
"""A simple implementation of ``AbsLearner``.
Args:
trainable_agents (AbsAgentManage... | maro/rl/learner/simple_learner.py |
from maro.rl.actor.simple_actor import SimpleActor
from maro.rl.agent.abs_agent_manager import AbsAgentManager
from maro.utils import DummyLogger
from .abs_learner import AbsLearner
class SimpleLearner(AbsLearner):
"""A simple implementation of ``AbsLearner``.
Args:
trainable_agents (AbsAgentManage... | 0.925529 | 0.156523 |
import json
import logging
import os
import random
from argparse import (
ArgumentParser,
ArgumentDefaultsHelpFormatter,
)
from pathlib import Path
from subprocess import check_call
from django.core.management import BaseCommand
from morphodict import morphodict_language_pair
from morphodict.lexicon import (
... | src/morphodict/lexicon/management/commands/randomsubset.py | import json
import logging
import os
import random
from argparse import (
ArgumentParser,
ArgumentDefaultsHelpFormatter,
)
from pathlib import Path
from subprocess import check_call
from django.core.management import BaseCommand
from morphodict import morphodict_language_pair
from morphodict.lexicon import (
... | 0.424412 | 0.067117 |
# # Scatterplots (01) - What is a scatterplot
#
# Scatterplots are used to show the relationship between two quantitative (numeric) variables. This relationship can be positive or negative, and they may also show a strong or weak (or non-existent!) correlation.
# ## How are scatterplots created?
#
# Scatterplots ar... | PlotlyandPython/Lessons/(04) Scatterplots/Notebooks/Python Scripts/Scatterplots (01) - What is a scatterplot.py |
# # Scatterplots (01) - What is a scatterplot
#
# Scatterplots are used to show the relationship between two quantitative (numeric) variables. This relationship can be positive or negative, and they may also show a strong or weak (or non-existent!) correlation.
# ## How are scatterplots created?
#
# Scatterplots ar... | 0.902042 | 0.888952 |
from bokeh.plotting import figure
from bokeh.layouts import column, row, Spacer
from bokeh.models import ColumnDataSource, Arrow, Button, Div, NormalHead, LabelSet, Span
from bokeh.io import curdoc
from math import radians, cos, sin, sqrt, pi
from bokeh.models.widgets import DataTable, TableColumn, CheckboxGroup, Numbe... | Complex_Numbers/main.py | from bokeh.plotting import figure
from bokeh.layouts import column, row, Spacer
from bokeh.models import ColumnDataSource, Arrow, Button, Div, NormalHead, LabelSet, Span
from bokeh.io import curdoc
from math import radians, cos, sin, sqrt, pi
from bokeh.models.widgets import DataTable, TableColumn, CheckboxGroup, Numbe... | 0.40157 | 0.704618 |
try:
from collections.abc import Mapping # py3
except ImportError:
from collections import Mapping # py2
# end try
class Singleton(type):
"""
Only one Instance of the class.
Like in Java .getInstance()
Make a class Singleton:
Python 3:
apply with keyword argume... | luckydonaldUtils/clazzes.py | try:
from collections.abc import Mapping # py3
except ImportError:
from collections import Mapping # py2
# end try
class Singleton(type):
"""
Only one Instance of the class.
Like in Java .getInstance()
Make a class Singleton:
Python 3:
apply with keyword argume... | 0.492432 | 0.259537 |
from abc import ABC, abstractmethod
class ApiInterface(ABC):
"""
This interface is dedicated for modules processing image dataset annotations.
Every annotation reader object, which implements these functions, should work properly within the app.
Object implementing this interface should be passed to D... | app/api/api_interface.py | from abc import ABC, abstractmethod
class ApiInterface(ABC):
"""
This interface is dedicated for modules processing image dataset annotations.
Every annotation reader object, which implements these functions, should work properly within the app.
Object implementing this interface should be passed to D... | 0.866048 | 0.489686 |
from django.db import migrations, models
import django.db.models.deletion
class Migration(migrations.Migration):
dependencies = [
('app', '0001_initial'),
]
operations = [
migrations.CreateModel(
name='Department',
fields=[
('id', models.AutoField... | Admin Panal/app/migrations/0002_auto_20210125_0216.py |
from django.db import migrations, models
import django.db.models.deletion
class Migration(migrations.Migration):
dependencies = [
('app', '0001_initial'),
]
operations = [
migrations.CreateModel(
name='Department',
fields=[
('id', models.AutoField... | 0.550487 | 0.154983 |
import sys
import json
import netifaces as ni
from node import Node
from lead import LeadNode
from rpc_server import Server
import time
from uuid import getnode as get_mac
class ClientNode:
def __init__(self, config, debug=False):
self.debug = debug
if debug:
config['lead_ip'] = 'loc... | slave/client_node.py | import sys
import json
import netifaces as ni
from node import Node
from lead import LeadNode
from rpc_server import Server
import time
from uuid import getnode as get_mac
class ClientNode:
def __init__(self, config, debug=False):
self.debug = debug
if debug:
config['lead_ip'] = 'loc... | 0.067064 | 0.11016 |
import torch
import torch.nn as nn
import torch.nn.functional as F
from mmseg.models import build_segmentor
from mmcv.utils import Config
from lib.model.pspnet import pspnet_res18, pspnet_res101
from lib.model.flownet import FlowNets
from lib.model.warpnet import warp
class Accel18(nn.Module):
def __init__(self... | Accel/lib/model/accel.py | import torch
import torch.nn as nn
import torch.nn.functional as F
from mmseg.models import build_segmentor
from mmcv.utils import Config
from lib.model.pspnet import pspnet_res18, pspnet_res101
from lib.model.flownet import FlowNets
from lib.model.warpnet import warp
class Accel18(nn.Module):
def __init__(self... | 0.854339 | 0.309506 |
import pandas as pd
from .transmission_coefficients import transmission_coefficients
import json
class NpEncoder(json.JSONEncoder):
def default(self, obj):
if isinstance(obj, np.integer):
return int(obj)
elif isinstance(obj, np.floating):
return float(obj)
elif isins... | staticInst/default_betas.py | import pandas as pd
from .transmission_coefficients import transmission_coefficients
import json
class NpEncoder(json.JSONEncoder):
def default(self, obj):
if isinstance(obj, np.integer):
return int(obj)
elif isinstance(obj, np.floating):
return float(obj)
elif isins... | 0.205057 | 0.248774 |
from __future__ import print_function
from builtins import range
import subprocess
import numpy as np
import scipy.optimize as spo
import math
import sys
from gpkit.tests.helpers import NullFile
def blind_call(topline, cl, Re, M, max_iter = 100,
pathname = "/usr/local/bin/xfoil"):
if '.dat' in topl... | gpkitmodels/tools/xfoilWrapper.py | from __future__ import print_function
from builtins import range
import subprocess
import numpy as np
import scipy.optimize as spo
import math
import sys
from gpkit.tests.helpers import NullFile
def blind_call(topline, cl, Re, M, max_iter = 100,
pathname = "/usr/local/bin/xfoil"):
if '.dat' in topl... | 0.31216 | 0.146789 |
import datetime
import os
from pathlib import Path
import xarray as xr
import datacube.utils.geometry
from datacube.model import Measurement
from fc.fc_app import tif_filenames, all_files_exist, _get_filename
from fc.fractional_cover import fractional_cover
def test_fractional_cover(sr_filepath, fc_filepath):
#... | tests/test_fractional_cover.py | import datetime
import os
from pathlib import Path
import xarray as xr
import datacube.utils.geometry
from datacube.model import Measurement
from fc.fc_app import tif_filenames, all_files_exist, _get_filename
from fc.fractional_cover import fractional_cover
def test_fractional_cover(sr_filepath, fc_filepath):
#... | 0.345105 | 0.425725 |
import configparser
import math # Ceil's of numbers
import os # Checking existence of config
from tkinter import *
from tkinter import simpledialog
pygameInstalled = True
try:
from pygame import mixer
except ModuleNotFoundError as er:
print("Pygame not installed, required for audio, game will not use any aud... | winSize.py | import configparser
import math # Ceil's of numbers
import os # Checking existence of config
from tkinter import *
from tkinter import simpledialog
pygameInstalled = True
try:
from pygame import mixer
except ModuleNotFoundError as er:
print("Pygame not installed, required for audio, game will not use any aud... | 0.289071 | 0.087097 |
from ..tmdb import TMDBSeries, TMDBPerson
person = {
"cast": [
{
"adult": False,
"backdrop_path": None,
"genre_ids": [18],
"id": 207013,
"original_language": "en",
"original_title": "Henry",
"overview": "Harassed single par... | app/tasks/parsers/tests/test_tmdb.py | from ..tmdb import TMDBSeries, TMDBPerson
person = {
"cast": [
{
"adult": False,
"backdrop_path": None,
"genre_ids": [18],
"id": 207013,
"original_language": "en",
"original_title": "Henry",
"overview": "Harassed single par... | 0.26341 | 0.365896 |
from copy import deepcopy
def dict_to_pairs(d):
out = set()
for key, value in d.items():
out.add([key, value])
return out
class Registry:
def __init__(self):
self.register = dict()
def __getitem__(self, key):
return self.register[key]
def __setitem__(self, key... | classes.py | from copy import deepcopy
def dict_to_pairs(d):
out = set()
for key, value in d.items():
out.add([key, value])
return out
class Registry:
def __init__(self):
self.register = dict()
def __getitem__(self, key):
return self.register[key]
def __setitem__(self, key... | 0.615088 | 0.31936 |
import subprocess
import multiprocessing as mp
import os
import numpy as np
import sys
def parse_ndx( target_grp='Protein' , input_file='residues.ndx' ):
# This function parses the groups of an input index file into a dictionary of residue names
# The input index file must contain:
# - The grou... | scan_interactions.py | import subprocess
import multiprocessing as mp
import os
import numpy as np
import sys
def parse_ndx( target_grp='Protein' , input_file='residues.ndx' ):
# This function parses the groups of an input index file into a dictionary of residue names
# The input index file must contain:
# - The grou... | 0.139572 | 0.187467 |
__all__ = [
"draw_label",
"bbox_polygon",
"draw_mask",
"as_rgb_tuple",
"get_default_font",
]
from icevision.imports import *
from icevision.utils import *
from matplotlib import patches
from PIL import Image, ImageFont, ImageDraw
import PIL
def draw_label(ax, x, y, name, color, fontsize=18):
... | icevision/visualize/utils.py | __all__ = [
"draw_label",
"bbox_polygon",
"draw_mask",
"as_rgb_tuple",
"get_default_font",
]
from icevision.imports import *
from icevision.utils import *
from matplotlib import patches
from PIL import Image, ImageFont, ImageDraw
import PIL
def draw_label(ax, x, y, name, color, fontsize=18):
... | 0.606149 | 0.288892 |
from rest_framework import permissions, viewsets, status
from rest_framework.decorators import api_view
from rest_framework.response import Response
from smtplib import SMTPAuthenticationError
from asset.models import Announcement
from clubs_and_events.settings import EMAIL_NOTIFICATIONS
from community.models import E... | notification/views.py | from rest_framework import permissions, viewsets, status
from rest_framework.decorators import api_view
from rest_framework.response import Response
from smtplib import SMTPAuthenticationError
from asset.models import Announcement
from clubs_and_events.settings import EMAIL_NOTIFICATIONS
from community.models import E... | 0.516839 | 0.063164 |
import tensorflow as tf
import numpy as numpy
import json
from Attention_Modules import Transformer, BahdanauAttention
with open('Hyper_Parameters.json', 'r') as f:
hp_Dict = json.load(f)
with open(hp_Dict['Token_JSON_Path'], 'r') as f:
token_Index_Dict = json.load(f)
class Listner(tf.keras.Model):
def _... | Modules.py | import tensorflow as tf
import numpy as numpy
import json
from Attention_Modules import Transformer, BahdanauAttention
with open('Hyper_Parameters.json', 'r') as f:
hp_Dict = json.load(f)
with open(hp_Dict['Token_JSON_Path'], 'r') as f:
token_Index_Dict = json.load(f)
class Listner(tf.keras.Model):
def _... | 0.725065 | 0.348756 |
import cv2
import numpy as np
import math
'''
检测轮廓
params:
img 原图
cThr 轮廓检测的阈值
showCanny 是否显示计算轮廓的结果
minArea 最小区域
filter 矩形的点数
draw 是否画出轮廓区域
'''
def getContours(img, cThr=[100, 100], showCanny=False, minArea=1000, filter=0, draw=False):
# 键图像边缘化
imgGray = cv2.cvtColor(img, cv2.COLOR_... | bolt_angle_v1/utlis.py | import cv2
import numpy as np
import math
'''
检测轮廓
params:
img 原图
cThr 轮廓检测的阈值
showCanny 是否显示计算轮廓的结果
minArea 最小区域
filter 矩形的点数
draw 是否画出轮廓区域
'''
def getContours(img, cThr=[100, 100], showCanny=False, minArea=1000, filter=0, draw=False):
# 键图像边缘化
imgGray = cv2.cvtColor(img, cv2.COLOR_... | 0.141489 | 0.327278 |
import re
import time
import threading
import subprocess
from collections import deque
from pyinotify import WatchManager, ThreadedNotifier, \
ProcessEvent, ExcludeFilter, IN_DELETE, IN_CREATE, \
IN_CLOSE_WRITE, IN_MOVED_FROM, IN_MOVED_TO
from utils import SyncFiles
from common import SyncConf
from ... | pyisync/file_watch.py | import re
import time
import threading
import subprocess
from collections import deque
from pyinotify import WatchManager, ThreadedNotifier, \
ProcessEvent, ExcludeFilter, IN_DELETE, IN_CREATE, \
IN_CLOSE_WRITE, IN_MOVED_FROM, IN_MOVED_TO
from utils import SyncFiles
from common import SyncConf
from ... | 0.333612 | 0.052497 |
import detectron2
from detectron2.engine.hooks import EvalHook
from detectron2.evaluation import COCOEvaluator
from detectron2.data import build_detection_test_loader , build_detection_train_loader
from .mapper import PersonalMapper
from .configs import load_general_config , load_detectron_config , inject_config
from ... | src/trainer.py | import detectron2
from detectron2.engine.hooks import EvalHook
from detectron2.evaluation import COCOEvaluator
from detectron2.data import build_detection_test_loader , build_detection_train_loader
from .mapper import PersonalMapper
from .configs import load_general_config , load_detectron_config , inject_config
from ... | 0.504883 | 0.224247 |
import datetime
import uuid
import pytest
from declaration import fields, models
class TestFields(object):
def test_base_not_implemented(self):
field = fields.DeclarativeField()
with pytest.raises(NotImplementedError):
field.parse("any value")
with pytest.raises(NotImpleme... | declaration/tests/test_fields.py | import datetime
import uuid
import pytest
from declaration import fields, models
class TestFields(object):
def test_base_not_implemented(self):
field = fields.DeclarativeField()
with pytest.raises(NotImplementedError):
field.parse("any value")
with pytest.raises(NotImpleme... | 0.655997 | 0.660035 |
from datetime import datetime, timedelta
from alertaclient.utils import DateTime
MAX_LATENCY = 2000 # ms
class Heartbeat:
def __init__(self, origin=None, tags=None, create_time=None, timeout=None, customer=None, **kwargs):
self.id = kwargs.get('id', None)
self.origin = origin
self.tags... | alertaclient/models/heartbeat.py | from datetime import datetime, timedelta
from alertaclient.utils import DateTime
MAX_LATENCY = 2000 # ms
class Heartbeat:
def __init__(self, origin=None, tags=None, create_time=None, timeout=None, customer=None, **kwargs):
self.id = kwargs.get('id', None)
self.origin = origin
self.tags... | 0.767777 | 0.093927 |
from django.test import TestCase
from .models import Editor, Article, tags
import datetime as dt
# Create your tests here.
class EditorTestClass(TestCase):
def setUp(self):
self.james = Editor(first_name='James', last_name='Muriuki', email='<EMAIL>')
def test_instance(self):
self.assertTrue(... | news/tests.py | from django.test import TestCase
from .models import Editor, Article, tags
import datetime as dt
# Create your tests here.
class EditorTestClass(TestCase):
def setUp(self):
self.james = Editor(first_name='James', last_name='Muriuki', email='<EMAIL>')
def test_instance(self):
self.assertTrue(... | 0.349311 | 0.34668 |
try:
import urlparse
except ImportError:
# Python 3
import urllib.parse as urlparse
from django.shortcuts import redirect as core_redirect
from django.http import HttpResponseRedirect
from django.utils.encoding import iri_to_uri
from django.conf import settings
def param_name():
return getattr(settin... | uturn/http.py | try:
import urlparse
except ImportError:
# Python 3
import urllib.parse as urlparse
from django.shortcuts import redirect as core_redirect
from django.http import HttpResponseRedirect
from django.utils.encoding import iri_to_uri
from django.conf import settings
def param_name():
return getattr(settin... | 0.693992 | 0.192198 |
import numpy as np
from .coordinates import rotate_axis, polar_coordinates, spherical_coordinates
from .atoms import next_neighbors
from .autosave import autosave_data
from .utils import runningmean
from .pbc import pbc_diff, pbc_points
from .logging import logger
from scipy import spatial
@autosave_data(nargs=2, kw... | mdevaluate/distribution.py | import numpy as np
from .coordinates import rotate_axis, polar_coordinates, spherical_coordinates
from .atoms import next_neighbors
from .autosave import autosave_data
from .utils import runningmean
from .pbc import pbc_diff, pbc_points
from .logging import logger
from scipy import spatial
@autosave_data(nargs=2, kw... | 0.799794 | 0.543833 |
import os
import unittest
import json
from dotenv import load_dotenv
from icecream import ic
from app import create_app
from database import db
from database.movies import Movies
from database.actors import Actors
load_dotenv()
public = ""
casting_assistant = "casting_assistant"
casting_director = "casting_director... | test_app.py | import os
import unittest
import json
from dotenv import load_dotenv
from icecream import ic
from app import create_app
from database import db
from database.movies import Movies
from database.actors import Actors
load_dotenv()
public = ""
casting_assistant = "casting_assistant"
casting_director = "casting_director... | 0.41052 | 0.258022 |
import scrapy
import json
from bs4 import BeautifulSoup
class ImdbScrape(scrapy.Spider):
name = "imdbbot"
def __init__(self):
pass
def start_requests(self):
urls = json.load(open(".././wiki_dump/imdb_ids_1950-1989.json"))
for url in urls:
yield scrapy.Request(url=('https://www.imdb.com/title/' + url), cal... | wiki_bot/wiki_bot/spiders/imdb_scrape.py | import scrapy
import json
from bs4 import BeautifulSoup
class ImdbScrape(scrapy.Spider):
name = "imdbbot"
def __init__(self):
pass
def start_requests(self):
urls = json.load(open(".././wiki_dump/imdb_ids_1950-1989.json"))
for url in urls:
yield scrapy.Request(url=('https://www.imdb.com/title/' + url), cal... | 0.0506 | 0.085404 |
import torch
import torch.nn as nn
from Sublayers import General_Attention, Inception_Temporal_Layer, Non_local_gcn, Local_gcn
from Normalize import Switch_Norm_2D
class Prediction_Model(nn.Module):
def __init__(self, Ks, encoder_in_channel, encoder_out_channel, num_stations, switch):
super(Predic... | Models.py | import torch
import torch.nn as nn
from Sublayers import General_Attention, Inception_Temporal_Layer, Non_local_gcn, Local_gcn
from Normalize import Switch_Norm_2D
class Prediction_Model(nn.Module):
def __init__(self, Ks, encoder_in_channel, encoder_out_channel, num_stations, switch):
super(Predic... | 0.940415 | 0.40028 |
import pytest
from dbt.tests.util import run_dbt
from tests.functional.configs.fixtures import BaseConfigProject
class TestDisabledConfigs(BaseConfigProject):
@pytest.fixture(scope="class")
def dbt_profile_data(self, unique_schema):
return {
"config": {"send_anonymous_usage_stats": False... | tests/functional/configs/test_disabled_configs.py | import pytest
from dbt.tests.util import run_dbt
from tests.functional.configs.fixtures import BaseConfigProject
class TestDisabledConfigs(BaseConfigProject):
@pytest.fixture(scope="class")
def dbt_profile_data(self, unique_schema):
return {
"config": {"send_anonymous_usage_stats": False... | 0.569733 | 0.352536 |
import torch
import torch.utils.data as data
from PIL import Image
from torchvision import datasets, transforms
from torch.utils.data.dataloader import default_collate
from torch.utils.data.sampler import SubsetRandomSampler
import numpy as np
from torch.utils.data import DataLoader
from torchvision import datasets, tr... | data_loader/data_loaders.py | import torch
import torch.utils.data as data
from PIL import Image
from torchvision import datasets, transforms
from torch.utils.data.dataloader import default_collate
from torch.utils.data.sampler import SubsetRandomSampler
import numpy as np
from torch.utils.data import DataLoader
from torchvision import datasets, tr... | 0.913953 | 0.604311 |
import numpy as np
import pandas as pd
from tkinter import *
from tkinter.ttk import *
from tkinter import filedialog
from cctbx import crystal, miller
from cctbx.array_family import flex
from iotbx.reflection_file_reader import any_reflection_file
class GroupReflectionsGUI(LabelFrame):
"""A GUI frame for reflec... | edtools/group_reflections.py | import numpy as np
import pandas as pd
from tkinter import *
from tkinter.ttk import *
from tkinter import filedialog
from cctbx import crystal, miller
from cctbx.array_family import flex
from iotbx.reflection_file_reader import any_reflection_file
class GroupReflectionsGUI(LabelFrame):
"""A GUI frame for reflec... | 0.489503 | 0.144089 |
import argparse
import glob
from point_cloud.robust_estimator import build_estimator
from point_cloud.pipeline_visualizer import Open3DVisualizer
from point_cloud.pipeline_visualizer import PyRenderVisualizer
from point_cloud.pipeline import OnlineRiedonesPipeline
from point_cloud.classifier import HistClassifier
def... | scripts/whole_pipeline.py | import argparse
import glob
from point_cloud.robust_estimator import build_estimator
from point_cloud.pipeline_visualizer import Open3DVisualizer
from point_cloud.pipeline_visualizer import PyRenderVisualizer
from point_cloud.pipeline import OnlineRiedonesPipeline
from point_cloud.classifier import HistClassifier
def... | 0.532182 | 0.196595 |
import tensorflow as tf
import numpy as np
class StochasticPolicyGradientAgent():
"""
A Gaussian Policy Gradient based agent implementation
"""
def __init__(self, env, learning_rate = 0.001, discount_rate = 0.99, batch_size = 1, quiet = True):
self._optimizer = tf.train.AdamOptimizer(l... | agent/stochastic_policy_gradient_agent.py | import tensorflow as tf
import numpy as np
class StochasticPolicyGradientAgent():
"""
A Gaussian Policy Gradient based agent implementation
"""
def __init__(self, env, learning_rate = 0.001, discount_rate = 0.99, batch_size = 1, quiet = True):
self._optimizer = tf.train.AdamOptimizer(l... | 0.721841 | 0.391929 |
import sys
import re
from pathlib import Path
from typing import Dict, List
line_comment_re = re.compile(r'\s*//.*')
sys_include_re = re.compile(r'\s*#\s*include\s+<([^>]+)>\s*')
user_include_re = re.compile(r'\s*#\s*include\s+"([^"]+)"\s*')
def processHeader(dir: Path, path: Path, sys_includes: List[str], processe... | tools/amalgamate.py | import sys
import re
from pathlib import Path
from typing import Dict, List
line_comment_re = re.compile(r'\s*//.*')
sys_include_re = re.compile(r'\s*#\s*include\s+<([^>]+)>\s*')
user_include_re = re.compile(r'\s*#\s*include\s+"([^"]+)"\s*')
def processHeader(dir: Path, path: Path, sys_includes: List[str], processe... | 0.200793 | 0.172015 |
# This program segments Japanese sentences into words.
# This preprosessing is required before using J-MFD.
# Fist, install Anaconda (Python3.6) https://www.anaconda.com/
# Second, install MeCab related packages:
# In the case of Ubuntu: sudo apt-get install mecab libmecab-dev mecab-ipadic-utf8; pip install mecab-pyth... | word_segmentation.py |
# This program segments Japanese sentences into words.
# This preprosessing is required before using J-MFD.
# Fist, install Anaconda (Python3.6) https://www.anaconda.com/
# Second, install MeCab related packages:
# In the case of Ubuntu: sudo apt-get install mecab libmecab-dev mecab-ipadic-utf8; pip install mecab-pyth... | 0.249173 | 0.086439 |
import torch
import numpy as np
from PIL import Image
import json
import argparse
import model_factory
from torch.autograd import Variable
def main():
image_path, checkpoint, top_k, category_names, gpu = get_input_args()
with open(category_names, 'r') as f:
cat_to_name = json.load(f)
model = mo... | predict.py |
import torch
import numpy as np
from PIL import Image
import json
import argparse
import model_factory
from torch.autograd import Variable
def main():
image_path, checkpoint, top_k, category_names, gpu = get_input_args()
with open(category_names, 'r') as f:
cat_to_name = json.load(f)
model = mo... | 0.624294 | 0.320104 |
# In[ ]:
import pandas as pd
import numpy as np
import matplotlib.pyplot as plt
import seaborn as sns
def describeDf(df):
print("Quantitative Data:")
print(df.describe())
print("\n")
print("Qualitative Data:")
print(df.describe(exclude=[np.number]))
print("\n")
print("Smoker/Non-Smoker C... | analysis/scripts/project_functions.py |
# In[ ]:
import pandas as pd
import numpy as np
import matplotlib.pyplot as plt
import seaborn as sns
def describeDf(df):
print("Quantitative Data:")
print(df.describe())
print("\n")
print("Qualitative Data:")
print(df.describe(exclude=[np.number]))
print("\n")
print("Smoker/Non-Smoker C... | 0.544559 | 0.641928 |
import itertools
import warnings
import pytest
from estimagic.batch_evaluators import joblib_batch_evaluator
batch_evaluators = [
joblib_batch_evaluator,
]
n_core_list = [1, 2]
test_cases = list(itertools.product(batch_evaluators, n_core_list))
def double(x):
return 2 * x
def buggy_func(x):
raise A... | tests/test_batch_evaluators.py | import itertools
import warnings
import pytest
from estimagic.batch_evaluators import joblib_batch_evaluator
batch_evaluators = [
joblib_batch_evaluator,
]
n_core_list = [1, 2]
test_cases = list(itertools.product(batch_evaluators, n_core_list))
def double(x):
return 2 * x
def buggy_func(x):
raise A... | 0.620622 | 0.547343 |
# Based on volume_depth.py, but also returns volume and depth of water in the floodplain
# Import Python modules
import os
import math
import pickle
# Import own general modules
import ascraster
from error import *
from iround import *
# Import local modules.
import general_func
import get_dynamic_gridinfo
import i... | A_source_code/core/vol_depth_vel.py |
# Based on volume_depth.py, but also returns volume and depth of water in the floodplain
# Import Python modules
import os
import math
import pickle
# Import own general modules
import ascraster
from error import *
from iround import *
# Import local modules.
import general_func
import get_dynamic_gridinfo
import i... | 0.357904 | 0.31363 |
from bitcoinaddress import Wallet
import os
from multiprocessing import Process
import argparse
import sys
import signal
def handler(signum, frame):
print('Exiting')
sys.exit()
# Set the signal handler
signal.signal(signal.SIGINT, handler)
parser = argparse.ArgumentParser()
parser.add_argument("... | cryptobrute.py | from bitcoinaddress import Wallet
import os
from multiprocessing import Process
import argparse
import sys
import signal
def handler(signum, frame):
print('Exiting')
sys.exit()
# Set the signal handler
signal.signal(signal.SIGINT, handler)
parser = argparse.ArgumentParser()
parser.add_argument("... | 0.11613 | 0.064183 |
from datetime import datetime
import pickle
from tempfile import NamedTemporaryFile
from time import mktime, sleep
from urllib2 import URLError
from mock import patch
import simplejson as json
from bamboo.controllers.datasets import Datasets
from bamboo.lib.datetools import now
from bamboo.lib.jsontools import df_to_... | bamboo/tests/controllers/test_datasets.py | from datetime import datetime
import pickle
from tempfile import NamedTemporaryFile
from time import mktime, sleep
from urllib2 import URLError
from mock import patch
import simplejson as json
from bamboo.controllers.datasets import Datasets
from bamboo.lib.datetools import now
from bamboo.lib.jsontools import df_to_... | 0.528533 | 0.33372 |
import collections
import time
import ocs
from ocs import site_config
def _get_op(op_type, name, encoded, client):
"""Factory for generating matched operations. This will make sure
op.start's docstring is the docstring of the operation.
Parameters:
op_type (str): Operation type, either 'task' or... | ocs/ocs_client.py | import collections
import time
import ocs
from ocs import site_config
def _get_op(op_type, name, encoded, client):
"""Factory for generating matched operations. This will make sure
op.start's docstring is the docstring of the operation.
Parameters:
op_type (str): Operation type, either 'task' or... | 0.717012 | 0.155303 |
import re
def parse_date(data_string):
match_result = re.match('\d{4}-*\d{0,2}-\d{0,2}', data_string)
return match_result.group() if match_result is not None else 0
def parse_scorerNum(scorer_string):
match_result = re.match('\d+', scorer_string.replace('(', '').replace(')', ''))
return match_result... | DataHouse/test/re_test.py | import re
def parse_date(data_string):
match_result = re.match('\d{4}-*\d{0,2}-\d{0,2}', data_string)
return match_result.group() if match_result is not None else 0
def parse_scorerNum(scorer_string):
match_result = re.match('\d+', scorer_string.replace('(', '').replace(')', ''))
return match_result... | 0.261991 | 0.143578 |
from tkinter import *
window = Tk()
window.geometry("400x300+20+10")
window.title('Simple Calculator')
class MyWindow:
def __init__(self,window):
self.lbl1 = Label(window,text="Standard Calculator")
self.lbl1.grid(relx=0.50,y=50,anchor="center")
self.lbl2 = Label(window,text="Inp... | The Grid Manager.py | from tkinter import *
window = Tk()
window.geometry("400x300+20+10")
window.title('Simple Calculator')
class MyWindow:
def __init__(self,window):
self.lbl1 = Label(window,text="Standard Calculator")
self.lbl1.grid(relx=0.50,y=50,anchor="center")
self.lbl2 = Label(window,text="Inp... | 0.422743 | 0.093017 |
import numpy as np
from scipy.special import softmax
from abc import abstractmethod, ABC
class Agent(ABC):
def __init__(self, eps, q0=0):
self.eps = eps
self.q0 = q0
def init(self, actions):
self.actions = actions
self.q = np.full(actions, self.q0, dtype=np.float)
... | 02-multi-armed-bandits/agents.py | import numpy as np
from scipy.special import softmax
from abc import abstractmethod, ABC
class Agent(ABC):
def __init__(self, eps, q0=0):
self.eps = eps
self.q0 = q0
def init(self, actions):
self.actions = actions
self.q = np.full(actions, self.q0, dtype=np.float)
... | 0.770162 | 0.275522 |
# no_of_locations_searched:
search_start_index = 667
retreived_locations = ['Kagyu Samye Dzong London Tibetan Buddhist Meditation Centre',
'Amaravati Buddhist Monastery',
'Buddhapadipa Temple',
'Sasana Ramsi Vihara Theravada Buddhist Temple',
'Martsang Kagyu London Buddhist Centre',
'Chithurst Buddhist Monastery',
'T... | src/scripts/aux/record.py |
# no_of_locations_searched:
search_start_index = 667
retreived_locations = ['Kagyu Samye Dzong London Tibetan Buddhist Meditation Centre',
'Amaravati Buddhist Monastery',
'Buddhapadipa Temple',
'Sasana Ramsi Vihara Theravada Buddhist Temple',
'Martsang Kagyu London Buddhist Centre',
'Chithurst Buddhist Monastery',
'T... | 0.312685 | 0.141163 |
import unittest
from solution2 import build_bridge, get_statistics
STATISTICS = {
"Artificial_intelligence": [8, 19, 13, 198],
"Binyamina_train_station_suicide_bombing": [1, 3, 6, 21],
"Brain": [19, 5, 25, 11],
"Haifa_bus_16_suicide_bombing": [1, 4, 15, 23],
"Hidamari_no_Ki": [1, 5, 5, 35],
"... | 3-webServices/week2/assignment1/test.py |
import unittest
from solution2 import build_bridge, get_statistics
STATISTICS = {
"Artificial_intelligence": [8, 19, 13, 198],
"Binyamina_train_station_suicide_bombing": [1, 3, 6, 21],
"Brain": [19, 5, 25, 11],
"Haifa_bus_16_suicide_bombing": [1, 4, 15, 23],
"Hidamari_no_Ki": [1, 5, 5, 35],
"... | 0.451085 | 0.605449 |
import matplotlib.pyplot as plt
import numpy as np
from scipy.integrate import solve_ivp
def mu(b, I, mu0, mu1):
"""
Recovery rate.
Parameters:
-----------
b
hospital beds per 10,000 persons
I
number of infected
mu0
Minimum recovery rate
mu1
Maximum reco... | EX3/sir_utilities.py | import matplotlib.pyplot as plt
import numpy as np
from scipy.integrate import solve_ivp
def mu(b, I, mu0, mu1):
"""
Recovery rate.
Parameters:
-----------
b
hospital beds per 10,000 persons
I
number of infected
mu0
Minimum recovery rate
mu1
Maximum reco... | 0.856002 | 0.710415 |
from __future__ import unicode_literals
from django.conf import settings
from django.db import migrations, models
import django.db.models.deletion
import orchestra.contrib.domains.utils
import orchestra.contrib.domains.validators
class Migration(migrations.Migration):
replaces = [('domains', '0001_initial'), ('... | orchestra/contrib/domains/migrations/0001_squashed_0010_auto_20210330_1049.py | from __future__ import unicode_literals
from django.conf import settings
from django.db import migrations, models
import django.db.models.deletion
import orchestra.contrib.domains.utils
import orchestra.contrib.domains.validators
class Migration(migrations.Migration):
replaces = [('domains', '0001_initial'), ('... | 0.636466 | 0.150185 |
class TestSystem(object):
"""Abstract base class for test systems, demonstrating how to implement a test system.
Parameters
----------
Attributes
----------
system : simtk.openmm.System
System object for the test system
positions : list
positions of test system
topolog... | src/openmm_systems/test_systems/base.py | class TestSystem(object):
"""Abstract base class for test systems, demonstrating how to implement a test system.
Parameters
----------
Attributes
----------
system : simtk.openmm.System
System object for the test system
positions : list
positions of test system
topolog... | 0.938997 | 0.7368 |
import numpy as np
import torch
from torch.utils import data
from .common import check_ext_mem, check_ram_usage
from .wrapper import CustomTensorDataset
def train_net(optimizer, scheduler, model, criterion, data_loader, reg_coef,
train_ep, device="cpu"):
cur_ep = 0
stats = {"ram": [], "disk": ... | finalists/jun2tong/utils/train_ni.py | import numpy as np
import torch
from torch.utils import data
from .common import check_ext_mem, check_ram_usage
from .wrapper import CustomTensorDataset
def train_net(optimizer, scheduler, model, criterion, data_loader, reg_coef,
train_ep, device="cpu"):
cur_ep = 0
stats = {"ram": [], "disk": ... | 0.604749 | 0.434101 |
rows = 40
row_rule_len = 12
row_rules = [
[0, 0, 0, 0, 0, 5, 7, 3, 5, 1, 2, 10],
[1, 2, 2, 1, 2, 1, 1, 1, 1, 2, 1, 1],
[1, 1, 1, 1, 1, 1, 1, 1, 1, 2, 1, 1],
[0, 0, 0, 1, 1, 1, 1, 1, 1, 3, 2, 2],
[0, 0, 0, 0, 0, 5, 1, 1, 1, 2, 2, 2],
[0, 0, 0, 0, 0, 1, 1, 1, 1, 2, 3, 3],
[0, 0, 0, 1, 1, 1, 1,... | google_or_tools/nonogram_pbn_karate.py | rows = 40
row_rule_len = 12
row_rules = [
[0, 0, 0, 0, 0, 5, 7, 3, 5, 1, 2, 10],
[1, 2, 2, 1, 2, 1, 1, 1, 1, 2, 1, 1],
[1, 1, 1, 1, 1, 1, 1, 1, 1, 2, 1, 1],
[0, 0, 0, 1, 1, 1, 1, 1, 1, 3, 2, 2],
[0, 0, 0, 0, 0, 5, 1, 1, 1, 2, 2, 2],
[0, 0, 0, 0, 0, 1, 1, 1, 1, 2, 3, 3],
[0, 0, 0, 1, 1, 1, 1,... | 0.086423 | 0.897785 |
import copy
import torch
import torch.nn as nn
from .icneck import ICNeck
from ..base import BaseModel
from .icnetencoder import ICNetEncoder
from ...backbones import BuildActivation, BuildNormalization
'''ICNet'''
class ICNet(BaseModel):
def __init__(self, cfg, **kwargs):
super(ICNet, self).__init__(cfg,... | ssseg/modules/models/segmentors/icnet/icnet.py | import copy
import torch
import torch.nn as nn
from .icneck import ICNeck
from ..base import BaseModel
from .icnetencoder import ICNetEncoder
from ...backbones import BuildActivation, BuildNormalization
'''ICNet'''
class ICNet(BaseModel):
def __init__(self, cfg, **kwargs):
super(ICNet, self).__init__(cfg,... | 0.842604 | 0.072472 |
import json
import pkg_resources as pkg
def codebook(data_type: str) -> dict:
"""Load variable codebook
Args:
data_type:
Type of file to get codebook for
- ``bsfab`` (`Beneficiary Summary File, Base segment`_)
- ``med`` (`MedPAR File`_)
- ``opc`` ... | medicare_utils/codebook.py | import json
import pkg_resources as pkg
def codebook(data_type: str) -> dict:
"""Load variable codebook
Args:
data_type:
Type of file to get codebook for
- ``bsfab`` (`Beneficiary Summary File, Base segment`_)
- ``med`` (`MedPAR File`_)
- ``opc`` ... | 0.650467 | 0.473049 |
import copy
import logging
import os
import psutil
import time
import warnings
from operator import gt, lt
from lightgbm.callback import _format_eval_result, EarlyStopException
from autogluon.core.utils.early_stopping import SimpleES
logger = logging.getLogger(__name__)
# TODO: Add option to stop if current run's ... | tabular/src/autogluon/tabular/models/lgb/callbacks.py | import copy
import logging
import os
import psutil
import time
import warnings
from operator import gt, lt
from lightgbm.callback import _format_eval_result, EarlyStopException
from autogluon.core.utils.early_stopping import SimpleES
logger = logging.getLogger(__name__)
# TODO: Add option to stop if current run's ... | 0.500977 | 0.260594 |
from datetime import datetime as dt
from time import sleep
from os import listdir
import struct
# SET THESE VARIABLES
# Convert the files in this folde to .scid files...
FILES_IN = "/home/sc/PRE-SCID"
# ...and output them here
FILES_OUT = "/home/sc/NOW-SCID"
# Set to True to continue updating (text) files or False to... | Text2Scid.py | from datetime import datetime as dt
from time import sleep
from os import listdir
import struct
# SET THESE VARIABLES
# Convert the files in this folde to .scid files...
FILES_IN = "/home/sc/PRE-SCID"
# ...and output them here
FILES_OUT = "/home/sc/NOW-SCID"
# Set to True to continue updating (text) files or False to... | 0.379953 | 0.282314 |
import numpy as np
def decompLU(A):
L = np.eye(np.shape(A)[0]) #matriz L com a dimensao de A com a diagonal principla igual a 1
U = np.zeros(np.shape(A)) #matriz U full zero
lim = np.shape(A)[1] #pegando o tamanho da coluna de A (matriz quadrada)
sum = 0
for i in range(0, lim):
for j in range(0, lim):
su... | LeastSquares-Discreto.py | import numpy as np
def decompLU(A):
L = np.eye(np.shape(A)[0]) #matriz L com a dimensao de A com a diagonal principla igual a 1
U = np.zeros(np.shape(A)) #matriz U full zero
lim = np.shape(A)[1] #pegando o tamanho da coluna de A (matriz quadrada)
sum = 0
for i in range(0, lim):
for j in range(0, lim):
su... | 0.231006 | 0.531027 |
from picamera.array import PiRGBArray
from picamera import PiCamera
import time
import numpy as np
import serial
import cv2
import RPi.GPIO as GPIO
GPIO.setmode(GPIO.BOARD)
GPIO.setwarnings(False)
GPIO.setup(11,GPIO.OUT)
GPIO.setup(13,GPIO.OUT)
GPIO.setup(15,GPIO.OUT)
GPIO.setup(16,GPIO.OUT)
GPIO.setup(32,GPIO.OUT)
G... | Lisans Projeleri/Image Processing Based Search & Rescue Robot/search&rescue.py | from picamera.array import PiRGBArray
from picamera import PiCamera
import time
import numpy as np
import serial
import cv2
import RPi.GPIO as GPIO
GPIO.setmode(GPIO.BOARD)
GPIO.setwarnings(False)
GPIO.setup(11,GPIO.OUT)
GPIO.setup(13,GPIO.OUT)
GPIO.setup(15,GPIO.OUT)
GPIO.setup(16,GPIO.OUT)
GPIO.setup(32,GPIO.OUT)
G... | 0.175256 | 0.133133 |
import datetime
import os
import base64
from cryptography.hazmat.backends import default_backend
from cryptography.hazmat.primitives import serialization
import dateutil.parser
import flask
from jose import jwk
def load_keypairs(keys_dir):
"""
Load a list of all the available keypairs from the given director... | fence/jwt/keys.py | import datetime
import os
import base64
from cryptography.hazmat.backends import default_backend
from cryptography.hazmat.primitives import serialization
import dateutil.parser
import flask
from jose import jwk
def load_keypairs(keys_dir):
"""
Load a list of all the available keypairs from the given director... | 0.806319 | 0.277522 |
from unittest.mock import patch
from django.contrib.auth import get_user_model
from django.core.exceptions import ValidationError
from django.core.files.uploadedfile import SimpleUploadedFile
from django.db.models.fields.files import FieldFile
from django.test import TestCase
from django.utils import timezone
from ap... | apps/experiments/tests/test_models.py | from unittest.mock import patch
from django.contrib.auth import get_user_model
from django.core.exceptions import ValidationError
from django.core.files.uploadedfile import SimpleUploadedFile
from django.db.models.fields.files import FieldFile
from django.test import TestCase
from django.utils import timezone
from ap... | 0.550124 | 0.308672 |
import requests
from bs4 import BeautifulSoup
from exceptions import ThresholdReached
from utils.http import response_sanity_check
class GutenbergCrawler:
def __init__(self, file_types, n_ebooks, langs):
self.file_types = file_types or []
self.n_ebooks = n_ebooks
self.langs = langs or []
... | downloader/crawler.py | import requests
from bs4 import BeautifulSoup
from exceptions import ThresholdReached
from utils.http import response_sanity_check
class GutenbergCrawler:
def __init__(self, file_types, n_ebooks, langs):
self.file_types = file_types or []
self.n_ebooks = n_ebooks
self.langs = langs or []
... | 0.273574 | 0.05694 |
import os
from contextlib import contextmanager
from refabric.context_managers import sudo
from refabric.contrib import blueprints
from .. import git
__all__ = [
'app_root', 'project_home', 'git_root', 'use_virtualenv', 'virtualenv_path',
'git_repository', 'git_repository_path', 'python_path', 'sudo_project'... | blues/application/project.py | import os
from contextlib import contextmanager
from refabric.context_managers import sudo
from refabric.contrib import blueprints
from .. import git
__all__ = [
'app_root', 'project_home', 'git_root', 'use_virtualenv', 'virtualenv_path',
'git_repository', 'git_repository_path', 'python_path', 'sudo_project'... | 0.295738 | 0.041813 |
from __future__ import print_function, absolute_import
import argparse
import os.path as osp
import os
import sys
import pdb
import math
import numpy as np
import matplotlib
import matplotlib.pyplot as plt
from sklearn.cluster import KMeans
def params_cluster(params, Q_values):
# print("The max and min value... | tools/cluster.py |
from __future__ import print_function, absolute_import
import argparse
import os.path as osp
import os
import sys
import pdb
import math
import numpy as np
import matplotlib
import matplotlib.pyplot as plt
from sklearn.cluster import KMeans
def params_cluster(params, Q_values):
# print("The max and min value... | 0.276886 | 0.363223 |
from pytest_bdd import given, when, then
from model.group import Group
import random
@given('A group list', target_fixture='group_list')
def group_list(db):
return db.get_group_list()
@given('A group with <name>, <header>, <footer>', target_fixture='new_group')
def new_group(name, header, footer):
return Gr... | bdd/group_steps.py | from pytest_bdd import given, when, then
from model.group import Group
import random
@given('A group list', target_fixture='group_list')
def group_list(db):
return db.get_group_list()
@given('A group with <name>, <header>, <footer>', target_fixture='new_group')
def new_group(name, header, footer):
return Gr... | 0.590307 | 0.249664 |
from ..xcvr_mem_map import XcvrMemMap
from ...fields.xcvr_field import (
CodeRegField,
DateField,
HexRegField,
NumberRegField,
RegBitField,
RegGroupField,
StringRegField,
)
from ...fields import consts
from ...fields.public.cmis import CableLenField
class CmisMemMap(XcvrMemMap):
def __i... | sonic_platform_base/sonic_xcvr/mem_maps/public/cmis.py | from ..xcvr_mem_map import XcvrMemMap
from ...fields.xcvr_field import (
CodeRegField,
DateField,
HexRegField,
NumberRegField,
RegBitField,
RegGroupField,
StringRegField,
)
from ...fields import consts
from ...fields.public.cmis import CableLenField
class CmisMemMap(XcvrMemMap):
def __i... | 0.446495 | 0.254874 |
from utils.decorators import timer, debug
from utils.task import Task
from utils.load import load_task_json
import numpy as np
from copy import deepcopy
class Node:
def __init__(self, fish_num, parent):
self.parent = parent
if isinstance(fish_num, int):
self.value = fish_num
... | years/AoC2021/task_18.py | from utils.decorators import timer, debug
from utils.task import Task
from utils.load import load_task_json
import numpy as np
from copy import deepcopy
class Node:
def __init__(self, fish_num, parent):
self.parent = parent
if isinstance(fish_num, int):
self.value = fish_num
... | 0.780328 | 0.550305 |
from twisted.plugin import IPlugin
from twisted.words.protocols import irc
from txircd.ircd import ModuleLoadError
from txircd.module_interface import Command, ICommand, IModuleData, ModuleData
from zope.interface import implements
class GlobalLoad(ModuleData):
implements(IPlugin, IModuleData)
name = "GlobalLoad"
... | txircd/modules/extra/globalload.py | from twisted.plugin import IPlugin
from twisted.words.protocols import irc
from txircd.ircd import ModuleLoadError
from txircd.module_interface import Command, ICommand, IModuleData, ModuleData
from zope.interface import implements
class GlobalLoad(ModuleData):
implements(IPlugin, IModuleData)
name = "GlobalLoad"
... | 0.314366 | 0.142829 |
# default python packages
import datetime
import re
import logging
# installed packages
import scrapy
from scrapy.spiders import CrawlSpider, Rule
from scrapy.linkextractors import LinkExtractor
from bs4 import BeautifulSoup
# project modules
from webscraper_for_sophie.items import CondoItem
class WillhabenSpider(scr... | webscraper_for_sophie/spiders/willhaben_spider.py | # default python packages
import datetime
import re
import logging
# installed packages
import scrapy
from scrapy.spiders import CrawlSpider, Rule
from scrapy.linkextractors import LinkExtractor
from bs4 import BeautifulSoup
# project modules
from webscraper_for_sophie.items import CondoItem
class WillhabenSpider(scr... | 0.281998 | 0.229524 |
import numpy as np
import pandas as pd
from sklearn.metrics import precision_score, recall_score
import sklearn.model_selection as skl
import matplotlib.pyplot as plt
from indoorplants.validation import crossvalidate, \
calibration, \
boundaries... | indoorplants/validation/curves.py | import numpy as np
import pandas as pd
from sklearn.metrics import precision_score, recall_score
import sklearn.model_selection as skl
import matplotlib.pyplot as plt
from indoorplants.validation import crossvalidate, \
calibration, \
boundaries... | 0.836588 | 0.559471 |
import argparse
parser = argparse.ArgumentParser("Curriculum Neural Architecture Search.")
parser.add_argument('--mode', type=str, default='CNAS_OP',
help='variants of CNAS ["CNAS_NODE", "CNAS_OP", "CNAS_FIX"]')
parser.add_argument('--search_space', type=str, default='DARTS_SPACE',
... | cnas/search/core/config.py | import argparse
parser = argparse.ArgumentParser("Curriculum Neural Architecture Search.")
parser.add_argument('--mode', type=str, default='CNAS_OP',
help='variants of CNAS ["CNAS_NODE", "CNAS_OP", "CNAS_FIX"]')
parser.add_argument('--search_space', type=str, default='DARTS_SPACE',
... | 0.543106 | 0.062818 |
import numpy as np
def sigmoid(x):
return 1.0/(1 + np.exp(-x))
def sigmoid_derivative(x):
return x * (1.0 - x)
class NeuralNetwork:
def __init__(self, w, x, y, z):
self.w = w
self.x = x
self.y = y
self.input1 = w
... | main/neural.py | import numpy as np
def sigmoid(x):
return 1.0/(1 + np.exp(-x))
def sigmoid_derivative(x):
return x * (1.0 - x)
class NeuralNetwork:
def __init__(self, w, x, y, z):
self.w = w
self.x = x
self.y = y
self.input1 = w
... | 0.660282 | 0.444685 |
import Constants
import Globals
import os.path
import DBFunctions
def InitGlobals():
Globals.CurrentCase = None
Globals.CaseOpen = False
Globals.CurrentCaseFile = ""
Globals.CasePath = ""
Globals.MACFileName = ""
Globals.FileSystemName = ""
#keep all the files in Memory
... | Init.py | import Constants
import Globals
import os.path
import DBFunctions
def InitGlobals():
Globals.CurrentCase = None
Globals.CaseOpen = False
Globals.CurrentCaseFile = ""
Globals.CasePath = ""
Globals.MACFileName = ""
Globals.FileSystemName = ""
#keep all the files in Memory
... | 0.129155 | 0.065635 |
from functools import partial
from twisted.web.resource import Resource
from twisted.web.server import Request
from twisted.web.static import Data
from klein import Klein
from otter.util.http import append_segments
from otter.util.config import config_value
_store = None
Request.defaultContentType = 'application... | otter/rest/application.py | from functools import partial
from twisted.web.resource import Resource
from twisted.web.server import Request
from twisted.web.static import Data
from klein import Klein
from otter.util.http import append_segments
from otter.util.config import config_value
_store = None
Request.defaultContentType = 'application... | 0.744656 | 0.255587 |
import logging
import os
import time
from es_common.utils import data_helper
from es_common.utils.qt import QtGui, QtWidgets
from interaction_manager.view.ui_saveas_dialog import Ui_SaveAsDialog
class UISaveAsController(QtWidgets.QDialog):
def __init__(self, parent=None, serialized_data=None):
super(UI... | interaction_manager/controller/ui_save_as_controller.py |
import logging
import os
import time
from es_common.utils import data_helper
from es_common.utils.qt import QtGui, QtWidgets
from interaction_manager.view.ui_saveas_dialog import Ui_SaveAsDialog
class UISaveAsController(QtWidgets.QDialog):
def __init__(self, parent=None, serialized_data=None):
super(UI... | 0.380759 | 0.043123 |
from unittest import TestCase, mock
from flask import url_for
from dimensigon.web.api_1_0.urls.use_cases import wrap_sudo
from tests.base import TwoNodeMixin, VirtualNetworkMixin
class TestLaunchCommand(VirtualNetworkMixin, TwoNodeMixin, TestCase):
@mock.patch('dimensigon.web.api_1_0.urls.use_cases.subprocess.... | tests/system/web/api_1_0/urls/use_cases/test_launch_command.py | from unittest import TestCase, mock
from flask import url_for
from dimensigon.web.api_1_0.urls.use_cases import wrap_sudo
from tests.base import TwoNodeMixin, VirtualNetworkMixin
class TestLaunchCommand(VirtualNetworkMixin, TwoNodeMixin, TestCase):
@mock.patch('dimensigon.web.api_1_0.urls.use_cases.subprocess.... | 0.60743 | 0.32536 |
IP_1 = '1.1.1.1'
IP_2 = '2.2.2.2'
IP_3 = '3.3.3.3'
IP_4 = '4.4.4.4'
IP_5 = '5.5.5.5'
IP_6 = '6.6.6.6'
IP_7 = '7.7.7.7'
IP_8 = '8.8.8.8'
DISK_ONE = 'disk_number_1'
DISK_TWO = 'disk_number_2'
INSTANCE_TYPE_1 = "instance_type_1"
INSTANCE_TYPE_2 = "instance_type_2"
ONE_NODE_CLOUD = [
{
'roles': ['master', 'databa... | test/test_ip_layouts.py |
IP_1 = '1.1.1.1'
IP_2 = '2.2.2.2'
IP_3 = '3.3.3.3'
IP_4 = '4.4.4.4'
IP_5 = '5.5.5.5'
IP_6 = '6.6.6.6'
IP_7 = '7.7.7.7'
IP_8 = '8.8.8.8'
DISK_ONE = 'disk_number_1'
DISK_TWO = 'disk_number_2'
INSTANCE_TYPE_1 = "instance_type_1"
INSTANCE_TYPE_2 = "instance_type_2"
ONE_NODE_CLOUD = [
{
'roles': ['master', 'databa... | 0.341034 | 0.291548 |
from pathlib import PosixPath
from unittest.mock import patch, mock_open, call
from .test_archive import create_dataflow
from dffml import run
from dffml.util.asynctestcase import AsyncTestCase
from dffml.operation.compression import (
gz_compress,
gz_decompress,
bz2_compress,
bz2_decompress,
xz_c... | tests/operation/test_compression.py | from pathlib import PosixPath
from unittest.mock import patch, mock_open, call
from .test_archive import create_dataflow
from dffml import run
from dffml.util.asynctestcase import AsyncTestCase
from dffml.operation.compression import (
gz_compress,
gz_decompress,
bz2_compress,
bz2_decompress,
xz_c... | 0.471223 | 0.265599 |
from collections import namedtuple
import os
import pickle
import secrets
import numpy as np
from sklearn.ensemble import RandomForestClassifier
from .logger import feature_logger_factory
from .model import Model
from .solution import Solution
SubProblem = namedtuple("SubProblem", ["variables", "status", "model_siz... | ks_engine/feature_kernel.py |
from collections import namedtuple
import os
import pickle
import secrets
import numpy as np
from sklearn.ensemble import RandomForestClassifier
from .logger import feature_logger_factory
from .model import Model
from .solution import Solution
SubProblem = namedtuple("SubProblem", ["variables", "status", "model_siz... | 0.805632 | 0.411288 |