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 os
import traceback
from collections import namedtuple
from django.conf import settings
from django.contrib.auth.models import User
from django.core.cache import cache
from django.http import JsonResponse
from django.shortcuts import redirect
from django.utils.decorators import method_decorator
from django.view... | site_config/views.py | import os
import traceback
from collections import namedtuple
from django.conf import settings
from django.contrib.auth.models import User
from django.core.cache import cache
from django.http import JsonResponse
from django.shortcuts import redirect
from django.utils.decorators import method_decorator
from django.view... | 0.563378 | 0.135146 |
import logging
from typing import Callable, Protocol, Sequence
from scipy.integrate import nquad
from scipy.stats import dirichlet
# this is the currently supported way to annotate callables with *args of a certain type,
# see https://mypy.readthedocs.io/en/latest/protocols.html#callback-protocols
# hopefully at som... | src/kyle/integrals.py | import logging
from typing import Callable, Protocol, Sequence
from scipy.integrate import nquad
from scipy.stats import dirichlet
# this is the currently supported way to annotate callables with *args of a certain type,
# see https://mypy.readthedocs.io/en/latest/protocols.html#callback-protocols
# hopefully at som... | 0.907897 | 0.647088 |
import copy
import os
from typing import Any, AnyStr, Optional # noqa: F401
import numpy as np
import torch
import thelper
from tests.train.train_utils import ( # noqa: F401 isort:skip
mnist_config, test_classif_mnist_ft_path, test_classif_mnist_name,
test_classif_mnist_path, test_save_path
)
config = mni... | tests/train/test_classif_mnist.py | import copy
import os
from typing import Any, AnyStr, Optional # noqa: F401
import numpy as np
import torch
import thelper
from tests.train.train_utils import ( # noqa: F401 isort:skip
mnist_config, test_classif_mnist_ft_path, test_classif_mnist_name,
test_classif_mnist_path, test_save_path
)
config = mni... | 0.61855 | 0.329796 |
import argparse
import os
import pickle
import numpy as np
import pandas as pd
import torch
from PIL import PngImagePlugin
from torch.utils.data import DataLoader
from tqdm import tqdm
from benchmarks.wit.dataset_class import FoodiMLDataset
from benchmarks.wit.evaluator import adapter, compute_valid_answers
from benc... | benchmarks/wit/evaluate_network_bigdata.py | import argparse
import os
import pickle
import numpy as np
import pandas as pd
import torch
from PIL import PngImagePlugin
from torch.utils.data import DataLoader
from tqdm import tqdm
from benchmarks.wit.dataset_class import FoodiMLDataset
from benchmarks.wit.evaluator import adapter, compute_valid_answers
from benc... | 0.889205 | 0.343741 |
import numpy as np
import torch
import torch.nn as nn
class MultiHeadSelfAttention(nn.Module):
"""Self-attention module by <NAME>, et al. ICLR 2017"""
def __init__(self, n_head, d_in, d_hidden):
super(MultiHeadSelfAttention, self).__init__()
self.n_head = n_head
self.w_1 = nn.Linear... | models/pie_model.py | import numpy as np
import torch
import torch.nn as nn
class MultiHeadSelfAttention(nn.Module):
"""Self-attention module by <NAME>, et al. ICLR 2017"""
def __init__(self, n_head, d_in, d_hidden):
super(MultiHeadSelfAttention, self).__init__()
self.n_head = n_head
self.w_1 = nn.Linear... | 0.933355 | 0.344581 |
import assignment_module_1
import assignment_module_2
import conll
def first_assignment():
print("---start first assignment---")
text = assignment_module_1.clean_text("data/text.txt")
test_sentence = text[4]
paths = assignment_module_1.extract_paths_to_tokens(test_sentence)
for tok... | main.py | import assignment_module_1
import assignment_module_2
import conll
def first_assignment():
print("---start first assignment---")
text = assignment_module_1.clean_text("data/text.txt")
test_sentence = text[4]
paths = assignment_module_1.extract_paths_to_tokens(test_sentence)
for tok... | 0.195902 | 0.395543 |
from pixiedust.display.app import *
from pixiedust.apps.gateway import BaseGatewayApp
from pixiedust.utils import Logger
from pixiedust.utils.shellAccess import ShellAccess
from pixiedust.utils.userPreferences import setUserPreference
from IPython.utils.io import capture_output
import requests
@PixieApp
@Logger()
clas... | pixiedust/apps/gateway/share.py | from pixiedust.display.app import *
from pixiedust.apps.gateway import BaseGatewayApp
from pixiedust.utils import Logger
from pixiedust.utils.shellAccess import ShellAccess
from pixiedust.utils.userPreferences import setUserPreference
from IPython.utils.io import capture_output
import requests
@PixieApp
@Logger()
clas... | 0.243642 | 0.096025 |
#!/usr/bin/env python
# coding=UTF-8
import pymysql
import re
import os
import sys
import csv
# Open the relevant files.
def main():
#Query
db = pymysql.connect("localhost","root","admin","newoverheaddb")
c=db.cursor()
##The naming conventions for this code foll... | MDCB_Overhead_08222016.py | #!/usr/bin/env python
# coding=UTF-8
import pymysql
import re
import os
import sys
import csv
# Open the relevant files.
def main():
#Query
db = pymysql.connect("localhost","root","admin","newoverheaddb")
c=db.cursor()
##The naming conventions for this code foll... | 0.153676 | 0.046443 |
import sys
import numpy as np
from scipy.fftpack import fft
from scipy.signal import detrend
from DataNexus.datahandler import DataHandler
class Fourier:
def __init__(self):
pass
@staticmethod
def monofourier(rawdata):
""" Apply FFT on the whole sample and return the resulting instance (... | DataNexus/fourier.py | import sys
import numpy as np
from scipy.fftpack import fft
from scipy.signal import detrend
from DataNexus.datahandler import DataHandler
class Fourier:
def __init__(self):
pass
@staticmethod
def monofourier(rawdata):
""" Apply FFT on the whole sample and return the resulting instance (... | 0.629661 | 0.436682 |
from ontobio.golr.golr_query import GolrAssociationQuery, M
class BeaconAssociationQuery(GolrAssociationQuery):
"""
A query object for performing the beacon association search functionality.
Note that such searches are directionless: sources and targets have a
different meaning from subjects and object... | ontobio/golr/beacon_query.py | from ontobio.golr.golr_query import GolrAssociationQuery, M
class BeaconAssociationQuery(GolrAssociationQuery):
"""
A query object for performing the beacon association search functionality.
Note that such searches are directionless: sources and targets have a
different meaning from subjects and object... | 0.771155 | 0.579162 |
from torch.utils.data import DataLoader
from tqdm import tqdm
import random
import torch.optim as optim
import os
from UNET import UNET
from dataset import SliceDataset
import torch
import math
from DiceLoss import myDiceLoss
from transform import transforms
from utils import (
load_checkpoint,
save_checkpoint,... | beta/train.py | from torch.utils.data import DataLoader
from tqdm import tqdm
import random
import torch.optim as optim
import os
from UNET import UNET
from dataset import SliceDataset
import torch
import math
from DiceLoss import myDiceLoss
from transform import transforms
from utils import (
load_checkpoint,
save_checkpoint,... | 0.511473 | 0.238229 |
import os
import numpy as np
from joblib import Parallel
from joblib import delayed
from config import *
from utils import ProgressBar
from utils import equally_divide_list
from utils import to_vec_add
from utils import to_vec_dot
from utils import to_vec_sub
from utils import to_vec_times
from utils import vlen
de... | dp_star/mdl.py | import os
import numpy as np
from joblib import Parallel
from joblib import delayed
from config import *
from utils import ProgressBar
from utils import equally_divide_list
from utils import to_vec_add
from utils import to_vec_dot
from utils import to_vec_sub
from utils import to_vec_times
from utils import vlen
de... | 0.603698 | 0.402451 |
import inspect
import pytest
from CybORG import CybORG
from CybORG.Agents.Wrappers import FixedFlatWrapper
from CybORG.Shared import Results
from CybORG.Shared.Actions.Action import Action
from CybORG.Shared.Observation import Observation
@pytest.fixture(params=['Red'])
def create_agent_interface(request):
path... | CybORG/CybORG/Tests/test_sim/test_AgentInterface.py | import inspect
import pytest
from CybORG import CybORG
from CybORG.Agents.Wrappers import FixedFlatWrapper
from CybORG.Shared import Results
from CybORG.Shared.Actions.Action import Action
from CybORG.Shared.Observation import Observation
@pytest.fixture(params=['Red'])
def create_agent_interface(request):
path... | 0.357231 | 0.49109 |
import os
import zipfile
from StringIO import StringIO
import shutil
from django import forms
from django.utils.translation import ugettext as _
from django.contrib.sites.models import Site
from django.conf import settings
from superhero.fields import FileMultiField
from superhero.models import Superhero
class Impo... | superhero/forms.py | import os
import zipfile
from StringIO import StringIO
import shutil
from django import forms
from django.utils.translation import ugettext as _
from django.contrib.sites.models import Site
from django.conf import settings
from superhero.fields import FileMultiField
from superhero.models import Superhero
class Impo... | 0.320609 | 0.071624 |
import pytest
from flask_praetorian.utilities import (
add_jwt_data_to_app_context,
current_user,
current_user_id,
current_rolenames,
)
from flask_praetorian.exceptions import PraetorianError
class TestPraetorianUtilities:
def test_current_user_id(self, user_class, db, default_guard):
""... | tests/test_utilities.py | import pytest
from flask_praetorian.utilities import (
add_jwt_data_to_app_context,
current_user,
current_user_id,
current_rolenames,
)
from flask_praetorian.exceptions import PraetorianError
class TestPraetorianUtilities:
def test_current_user_id(self, user_class, db, default_guard):
""... | 0.534127 | 0.338733 |
import dash
import dash_core_components as dcc
import dash_html_components as html
from dash.dependencies import Input, Output, State
import dash_table
import base64
import datetime
import io
import pandas as pd
external_stylesheets = ['https://codepen.io/chriddyp/pen/bWLwgP.css']
app = dash.Dash(__name__, external_... | Dash.py | import dash
import dash_core_components as dcc
import dash_html_components as html
from dash.dependencies import Input, Output, State
import dash_table
import base64
import datetime
import io
import pandas as pd
external_stylesheets = ['https://codepen.io/chriddyp/pen/bWLwgP.css']
app = dash.Dash(__name__, external_... | 0.31237 | 0.080177 |
import logging
import pathlib
#==========================================================================
def add_log(log_id=None, log_directory=None, log_level='DEBUG', on_screen=True, prefix='log_ekostat'):
"""
log_id: Id of the logger. Typically a UUID
log_directory: Directory to... | core/logger.py | import logging
import pathlib
#==========================================================================
def add_log(log_id=None, log_directory=None, log_level='DEBUG', on_screen=True, prefix='log_ekostat'):
"""
log_id: Id of the logger. Typically a UUID
log_directory: Directory to... | 0.2587 | 0.08374 |
import os
from doxhooks.errors import (
DoxhooksImportError, DoxhooksForbiddenLookupError, DoxhooksLookupError,
DoxhooksValueError)
from doxhooks.functions import findvalue, importattr
from pytest import mark
from doxhooks_pytest import withraises
class ExampleGetNamedValue(dict):
pass
class BaseTestF... | tests/unit_tests/test_functions.py | import os
from doxhooks.errors import (
DoxhooksImportError, DoxhooksForbiddenLookupError, DoxhooksLookupError,
DoxhooksValueError)
from doxhooks.functions import findvalue, importattr
from pytest import mark
from doxhooks_pytest import withraises
class ExampleGetNamedValue(dict):
pass
class BaseTestF... | 0.659076 | 0.376766 |
from __future__ import absolute_import, division, print_function
import six
import warnings
from tabulate import tabulate
from argparse import Namespace
from . import cm_utils, part_connect
class RevisionError(Exception):
def __init__(self, hpn):
# Call the base class constructor with the parameters it ... | hera_mc/cm_revisions.py | from __future__ import absolute_import, division, print_function
import six
import warnings
from tabulate import tabulate
from argparse import Namespace
from . import cm_utils, part_connect
class RevisionError(Exception):
def __init__(self, hpn):
# Call the base class constructor with the parameters it ... | 0.756447 | 0.19727 |
from mamonsu.plugins.pgsql.plugin import PgsqlPlugin as Plugin
from .pool import Pooler
from mamonsu.lib.plugin import PluginDisableException
class RelationsSize(Plugin):
DEFAULT_CONFIG = {'enabled': 'False'}
key_rel_size_discovery = "pgsql.relation.size{0}"
def __init__(self, config):
super(Plu... | mamonsu/plugins/pgsql/relations_size.py |
from mamonsu.plugins.pgsql.plugin import PgsqlPlugin as Plugin
from .pool import Pooler
from mamonsu.lib.plugin import PluginDisableException
class RelationsSize(Plugin):
DEFAULT_CONFIG = {'enabled': 'False'}
key_rel_size_discovery = "pgsql.relation.size{0}"
def __init__(self, config):
super(Plu... | 0.375248 | 0.093761 |
import numpy as np
import matplotlib.pyplot as plt
import moose
from collections import namedtuple
EREST_ACT = -70e-3 #: Resting membrane potential
TauInfMinChannelParams = namedtuple('TauInfMinChannelParams', 'T_min T_vdep T_vhalf T_vslope SS_min SS_vdep SS_vhalf SS_vslope')
AlphaBetaChannelParams = name... | projchanparamssFINAL.py | import numpy as np
import matplotlib.pyplot as plt
import moose
from collections import namedtuple
EREST_ACT = -70e-3 #: Resting membrane potential
TauInfMinChannelParams = namedtuple('TauInfMinChannelParams', 'T_min T_vdep T_vhalf T_vslope SS_min SS_vdep SS_vhalf SS_vslope')
AlphaBetaChannelParams = name... | 0.291687 | 0.37843 |
import argparse
import logging
import os
import time
import torch
import transformers
from tensorboardX import SummaryWriter
from tqdm import tqdm
from model import SpanDomainModel, CRFModel, SoftmaxModel
from data_processor import SpanProcessor, CRFProcessor, SoftMaxProcessor
from utils import set_seed, calculate
#... | multi_domain/multi_domain_ner.py | import argparse
import logging
import os
import time
import torch
import transformers
from tensorboardX import SummaryWriter
from tqdm import tqdm
from model import SpanDomainModel, CRFModel, SoftmaxModel
from data_processor import SpanProcessor, CRFProcessor, SoftMaxProcessor
from utils import set_seed, calculate
#... | 0.385143 | 0.242458 |
# $Id$
# configxml.py - module to read and parse config.xml, run_state.xml
'''
SYNOPSIS: parses and writes config.xml and run_state.xml
USAGE: from Boinc import configxml
config = configxml.ConfigFile().read()
run_state = configxml.RunStateFile().read()
print config.config.db_n... | boinc/py/Boinc/configxml.py |
# $Id$
# configxml.py - module to read and parse config.xml, run_state.xml
'''
SYNOPSIS: parses and writes config.xml and run_state.xml
USAGE: from Boinc import configxml
config = configxml.ConfigFile().read()
run_state = configxml.RunStateFile().read()
print config.config.db_n... | 0.173183 | 0.071397 |
import pendulum
from django.db import models
from django.utils import timezone
from django.utils.translation import ugettext_lazy as _
from jsonfield import JSONField
class Epidemic(models.Model):
epidemics = JSONField()
crawled_at = models.DateTimeField(
_("crawled datetime"), db_index=True, editable... | ncov/apps/peopleapp/models.py | import pendulum
from django.db import models
from django.utils import timezone
from django.utils.translation import ugettext_lazy as _
from jsonfield import JSONField
class Epidemic(models.Model):
epidemics = JSONField()
crawled_at = models.DateTimeField(
_("crawled datetime"), db_index=True, editable... | 0.506347 | 0.059401 |
from tracking_model.qp import qp_solver
from random import randint, choices, uniform, sample
import pandas as pd
import numpy as np
from time import time
def track_index(
data:pd.DataFrame,
K:int,
index_name:str,
P:int=15,
cross:float=1,
mut:float=0.85,
cut:int=4,
weight_limits:np.ndarr... | tracking_model/model.py | from tracking_model.qp import qp_solver
from random import randint, choices, uniform, sample
import pandas as pd
import numpy as np
from time import time
def track_index(
data:pd.DataFrame,
K:int,
index_name:str,
P:int=15,
cross:float=1,
mut:float=0.85,
cut:int=4,
weight_limits:np.ndarr... | 0.805173 | 0.616618 |
import os
import time
import torch
from .callback import Callback
import torch.distributed as dist
class CheckpointCallback(Callback):
def __init__(self, interval=1,
out_dir=os.path.join('.', 'checkpoints'),
mpi_comm=None):
"""
Checkpoint interface for saving dicti... | molecules/ml/callbacks/checkpoint_callback.py | import os
import time
import torch
from .callback import Callback
import torch.distributed as dist
class CheckpointCallback(Callback):
def __init__(self, interval=1,
out_dir=os.path.join('.', 'checkpoints'),
mpi_comm=None):
"""
Checkpoint interface for saving dicti... | 0.794185 | 0.171789 |
# pylint: disable=super-init-not-called
import itertools
from .loose import call, set_defaults
from .match import Match, Matches
from .pattern import Pattern, filter_match_kwargs
from .remodule import re
class _InvalidChainException(Exception):
"""
Internal exception raised when a chain is not valid
"""
... | Contents/Libraries/Shared/rebulk/chain.py | # pylint: disable=super-init-not-called
import itertools
from .loose import call, set_defaults
from .match import Match, Matches
from .pattern import Pattern, filter_match_kwargs
from .remodule import re
class _InvalidChainException(Exception):
"""
Internal exception raised when a chain is not valid
"""
... | 0.685739 | 0.172067 |
import delamo.CADwrap
import os
# Fix file path
os.chdir(os.path.dirname(os.path.realpath(__file__)))
# Set layer thickness
thickness = 0.199
cad_file_name = "ACIS_Example03.sat"
# Create the NURBS mold surface
mold = delamo.CADwrap.NURBSd()
mold.degree_u = 3
mold.degree_v = 3
mold.knotvector_u = [ 0, 0, 0, 0, 1, 2,... | examples/non_abaqus/15_StiffenerBlock_Layup_Generate_SAT.py | import delamo.CADwrap
import os
# Fix file path
os.chdir(os.path.dirname(os.path.realpath(__file__)))
# Set layer thickness
thickness = 0.199
cad_file_name = "ACIS_Example03.sat"
# Create the NURBS mold surface
mold = delamo.CADwrap.NURBSd()
mold.degree_u = 3
mold.degree_v = 3
mold.knotvector_u = [ 0, 0, 0, 0, 1, 2,... | 0.384334 | 0.179585 |
import pytest
from testing_config import BaseTestConfig
from tests.fixtures import xumm_api as test_fixtures
from unittest.mock import Mock, patch
import xumm
class TestPayloadCancel(BaseTestConfig):
@classmethod
def setUp(cls):
cls.sdk = xumm.XummSdk(
cls.json_fixtures['api']['key'],
... | tests/test_payload_cancel.py |
import pytest
from testing_config import BaseTestConfig
from tests.fixtures import xumm_api as test_fixtures
from unittest.mock import Mock, patch
import xumm
class TestPayloadCancel(BaseTestConfig):
@classmethod
def setUp(cls):
cls.sdk = xumm.XummSdk(
cls.json_fixtures['api']['key'],
... | 0.454472 | 0.21036 |
class Aff:
def __init__(self, filename):
self.fname = filename
self.parse(filename)
self.pfx = {}
self.sfx = {}
self.sfx_cross = {}
self.pfx_cross = {}
def parse(self, filename):
with open(filename) as inf:
lines = list(inf.readlines)
... | lib/sldr/hunspell.py |
class Aff:
def __init__(self, filename):
self.fname = filename
self.parse(filename)
self.pfx = {}
self.sfx = {}
self.sfx_cross = {}
self.pfx_cross = {}
def parse(self, filename):
with open(filename) as inf:
lines = list(inf.readlines)
... | 0.298185 | 0.175573 |
import math
import matplotlib.pyplot as plt
from .Generaldistribution import Distribution
class Binomial(Distribution):
"""Binomial distribution class for analysing a Binomial probability distribution.
Attributes:
mean (float) representing the mean value of the distribution
stdev ... | probabilipy/Binomialdistribution.py | import math
import matplotlib.pyplot as plt
from .Generaldistribution import Distribution
class Binomial(Distribution):
"""Binomial distribution class for analysing a Binomial probability distribution.
Attributes:
mean (float) representing the mean value of the distribution
stdev ... | 0.889481 | 0.808483 |
from JumpScale import j
app = j.tools.cuisine._getBaseAppClass()
class CuisineG8OSFs(app):
"""
fuse based filesystem for our g8OS, but can be used in other context too
"""
NAME = 'fs'
def build(self, start=False, install=True, reset=False):
if reset is False and self.isInstalled():
... | lib/JumpScale/tools/cuisine/systemservices/CuisineG8OSFs.py | from JumpScale import j
app = j.tools.cuisine._getBaseAppClass()
class CuisineG8OSFs(app):
"""
fuse based filesystem for our g8OS, but can be used in other context too
"""
NAME = 'fs'
def build(self, start=False, install=True, reset=False):
if reset is False and self.isInstalled():
... | 0.398055 | 0.098469 |
import os
import time
import pandas as pd
from six import string_types
from quilt.nodes import GroupNode, DataNode
from quilt.tools import command
from quilt.tools.const import PACKAGE_DIR_NAME
from quilt.tools.package import Package, PackageException
from quilt.tools.store import PackageStore
from .utils import patc... | compiler/quilt/test/test_import.py | import os
import time
import pandas as pd
from six import string_types
from quilt.nodes import GroupNode, DataNode
from quilt.tools import command
from quilt.tools.const import PACKAGE_DIR_NAME
from quilt.tools.package import Package, PackageException
from quilt.tools.store import PackageStore
from .utils import patc... | 0.608245 | 0.512022 |
import hashlib
import io
import os
import requests
from datetime import datetime
from ..messages import *
# Manifest creation relies on these data structures.
# Add to them whenever new types of data files are created.
knownFiles = [
"biblio-keys.json",
"biblio-numeric-suffixes.json",
"bikeshed-version.... | bikeshed/update/manifest.py |
import hashlib
import io
import os
import requests
from datetime import datetime
from ..messages import *
# Manifest creation relies on these data structures.
# Add to them whenever new types of data files are created.
knownFiles = [
"biblio-keys.json",
"biblio-numeric-suffixes.json",
"bikeshed-version.... | 0.366023 | 0.156652 |
from pprint import pformat
from six import iteritems
import re
import json
from ..utils import sanitize_for_serialization
class HistoricalAdherenceExceptionInfo(object):
"""
NOTE: This class is auto generated by the swagger code generator program.
Do not edit the class manually.
"""
def __init__(s... | build/PureCloudPlatformClientV2/models/historical_adherence_exception_info.py | from pprint import pformat
from six import iteritems
import re
import json
from ..utils import sanitize_for_serialization
class HistoricalAdherenceExceptionInfo(object):
"""
NOTE: This class is auto generated by the swagger code generator program.
Do not edit the class manually.
"""
def __init__(s... | 0.681833 | 0.171616 |
from django.shortcuts import render, redirect
from django.http import HttpResponse
from django.contrib.auth.forms import UserCreationForm, AuthenticationForm, User
from django.contrib.auth import login, logout, authenticate
from django.contrib import messages
from accounts.forms import RegistrationForm
from .models imp... | Working Files/unite/prototype/accounts/views.py | from django.shortcuts import render, redirect
from django.http import HttpResponse
from django.contrib.auth.forms import UserCreationForm, AuthenticationForm, User
from django.contrib.auth import login, logout, authenticate
from django.contrib import messages
from accounts.forms import RegistrationForm
from .models imp... | 0.36693 | 0.075824 |
import xarray as xr
import numpy as np
import pandas as pd
import matplotlib.pyplot as plt
""" Returns statistics (mean/median) of the training set """
store = pd.HDFStore("/m100_work/FUAC5_GKNN/camille/results2/training_gen5_7D_pedformreg8_filter11.h5.1")
efeTEM_GB = store["/output/efeTEM_GB"].mean()
efiTEM_GB_div_e... | camille-scripts/output_statistics.py | import xarray as xr
import numpy as np
import pandas as pd
import matplotlib.pyplot as plt
""" Returns statistics (mean/median) of the training set """
store = pd.HDFStore("/m100_work/FUAC5_GKNN/camille/results2/training_gen5_7D_pedformreg8_filter11.h5.1")
efeTEM_GB = store["/output/efeTEM_GB"].mean()
efiTEM_GB_div_e... | 0.326593 | 0.388792 |
import os
import h5py
import logging
import numpy as np
from bmtk.utils.sonata.utils import add_hdf5_magic, add_hdf5_version
def _create_output_h5(input_file, output_file, edges_root, n_edges):
mode = 'r+' if os.path.exists(output_file) else 'w'
out_h5 = h5py.File(output_file, mode=mode)
add_hdf5_version... | bmtk/builder/edges_sorter/memory_sorter.py | import os
import h5py
import logging
import numpy as np
from bmtk.utils.sonata.utils import add_hdf5_magic, add_hdf5_version
def _create_output_h5(input_file, output_file, edges_root, n_edges):
mode = 'r+' if os.path.exists(output_file) else 'w'
out_h5 = h5py.File(output_file, mode=mode)
add_hdf5_version... | 0.242116 | 0.211498 |
import os
from googleapiclient.discovery import build
from google.appengine.api import app_identity
import json
from googleapiclient.errors import HttpError
import resources
import common
import gcs_utils
import time
import logging
BQ_DEFAULT_RETRY_COUNT = 10
# Maximum results returned by list_tables (API has a low... | data_steward/bq_utils.py | import os
from googleapiclient.discovery import build
from google.appengine.api import app_identity
import json
from googleapiclient.errors import HttpError
import resources
import common
import gcs_utils
import time
import logging
BQ_DEFAULT_RETRY_COUNT = 10
# Maximum results returned by list_tables (API has a low... | 0.364551 | 0.153613 |
import pytorch_lightning as pl
import torch
import wandb
import glob
from pytorch_lightning.callbacks.early_stopping import EarlyStopping
from pytorch_lightning.callbacks.model_checkpoint import ModelCheckpoint
from pytorch_lightning.loggers import TensorBoardLogger
from pytorch_lightning.loggers import WandbLogger
fr... | autonmt/toolkits/autonmt_v2.py | import pytorch_lightning as pl
import torch
import wandb
import glob
from pytorch_lightning.callbacks.early_stopping import EarlyStopping
from pytorch_lightning.callbacks.model_checkpoint import ModelCheckpoint
from pytorch_lightning.loggers import TensorBoardLogger
from pytorch_lightning.loggers import WandbLogger
fr... | 0.735831 | 0.394667 |
import pandas as pd
"""
@file_name: report_writer.py
@author: Dylan "dyl-m" Monfret
Objective: Automatically write report notes for future posts on Twitter.
- Summary -
1. Retrieve information from Excel files
2. Iterate on it to get the TOP 3.
3. Write the results in .txt format.
"""
""" - LOCAL FUNCTIONS - """... | code/report_writer.py |
import pandas as pd
"""
@file_name: report_writer.py
@author: Dylan "dyl-m" Monfret
Objective: Automatically write report notes for future posts on Twitter.
- Summary -
1. Retrieve information from Excel files
2. Iterate on it to get the TOP 3.
3. Write the results in .txt format.
"""
""" - LOCAL FUNCTIONS - """... | 0.442396 | 0.205057 |
import inspect
import json
import pickle
import yaml
import numpy as np
basic_types = (int, float, bool, str, type(None))
basic_types_and_sequences = (int, float, bool, str, list, tuple, type(None))
def write_pickle(filename, obj):
"""Write object to pickle format.
Parameters
----------
filename : ... | movement_primitives/io.py | import inspect
import json
import pickle
import yaml
import numpy as np
basic_types = (int, float, bool, str, type(None))
basic_types_and_sequences = (int, float, bool, str, list, tuple, type(None))
def write_pickle(filename, obj):
"""Write object to pickle format.
Parameters
----------
filename : ... | 0.811564 | 0.255018 |
import os
import tempfile
import unittest
import logging
from pyidf import ValidationLevel
import pyidf
from pyidf.idf import IDF
from pyidf.humidifiers_and_dehumidifiers import DehumidifierDesiccantNoFans
log = logging.getLogger(__name__)
class TestDehumidifierDesiccantNoFans(unittest.TestCase):
def setUp(self)... | tests/test_dehumidifierdesiccantnofans.py | import os
import tempfile
import unittest
import logging
from pyidf import ValidationLevel
import pyidf
from pyidf.idf import IDF
from pyidf.humidifiers_and_dehumidifiers import DehumidifierDesiccantNoFans
log = logging.getLogger(__name__)
class TestDehumidifierDesiccantNoFans(unittest.TestCase):
def setUp(self)... | 0.422981 | 0.19216 |
import time
STG = "[ANALYSIS] "
def combobulate_min(pkgs):
for x in pkgs:
test_exists(x)
def combobulate_heur(pkgs):
for x in pkgs:
test_exists(x)
if x.exists == True:
test_score(x)
test_timestamp(x)
test_verCount(x)
stats_exists(pkgs)
def test... | src/analysis/heuristics.py | import time
STG = "[ANALYSIS] "
def combobulate_min(pkgs):
for x in pkgs:
test_exists(x)
def combobulate_heur(pkgs):
for x in pkgs:
test_exists(x)
if x.exists == True:
test_score(x)
test_timestamp(x)
test_verCount(x)
stats_exists(pkgs)
def test... | 0.149531 | 0.518668 |
import codecs
import json
import sqlite3
from sqlite3 import Error
from bs4 import BeautifulSoup
def load_dta_xml(f_paths, save_as_json=True, verbose=True):
'''
Load texts of the German Text Archive (Deutsches Textarchiv (DTA)).
The texts are stored in XML (TEI).
TEI documentation (in German): http... | qurator/sbb_ocr_postcorrection/misc/heuristics/data.py | import codecs
import json
import sqlite3
from sqlite3 import Error
from bs4 import BeautifulSoup
def load_dta_xml(f_paths, save_as_json=True, verbose=True):
'''
Load texts of the German Text Archive (Deutsches Textarchiv (DTA)).
The texts are stored in XML (TEI).
TEI documentation (in German): http... | 0.305905 | 0.162746 |
from . import gxapi_cy
from geosoft.gxapi import GXContext, float_ref, int_ref, str_ref
### endblock ClassImports
### block Header
# NOTICE: The code generator will not replace the code in this block
### endblock Header
### block ClassImplementation
# NOTICE: Do not edit anything here, it is generated code
class GX... | geosoft/gxapi/GXPDF3D.py | from . import gxapi_cy
from geosoft.gxapi import GXContext, float_ref, int_ref, str_ref
### endblock ClassImports
### block Header
# NOTICE: The code generator will not replace the code in this block
### endblock Header
### block ClassImplementation
# NOTICE: Do not edit anything here, it is generated code
class GX... | 0.74008 | 0.308464 |
import json
from indy import anoncreds, did
import pytest
from test_scripts.functional_tests.anoncreds.anoncreds_test_base \
import AnoncredsTestBase
from utilities import utils, constant, common
class TestProverStoreClaimOfferWithValidData(AnoncredsTestBase):
@pytest.mark.skip
# Method under test is d... | test_scripts/functional_tests/anoncreds/anoncreds_prover_store_claim_offer_works_with_valid_data_test.py | import json
from indy import anoncreds, did
import pytest
from test_scripts.functional_tests.anoncreds.anoncreds_test_base \
import AnoncredsTestBase
from utilities import utils, constant, common
class TestProverStoreClaimOfferWithValidData(AnoncredsTestBase):
@pytest.mark.skip
# Method under test is d... | 0.340595 | 0.263019 |
import numpy as np
import math, copy, time
import os
import itertools
import spacy
import json
from collections import Counter, defaultdict
import ftfy
import re
import pickle
import argparse
import sys
# pytorch libraries
import torch
import torch.nn as nn
import torch.nn.functional as F
from torchtext import data, d... | src/models/finetune.py | import numpy as np
import math, copy, time
import os
import itertools
import spacy
import json
from collections import Counter, defaultdict
import ftfy
import re
import pickle
import argparse
import sys
# pytorch libraries
import torch
import torch.nn as nn
import torch.nn.functional as F
from torchtext import data, d... | 0.519034 | 0.133472 |
import numpy as np
from lib import *
import os
import matplotlib.pyplot as plt
import cPickle
import time
file_path = os.path.dirname(os.path.realpath(__file__))
data_dir = os.path.join(file_path,'cifar-10-batches-py')
X_train,Y_train,X_test,Y_test = load_CIFAR10(data_dir)
del X_train
del Y_train
image = X_test[0]
m,n... | test.py | import numpy as np
from lib import *
import os
import matplotlib.pyplot as plt
import cPickle
import time
file_path = os.path.dirname(os.path.realpath(__file__))
data_dir = os.path.join(file_path,'cifar-10-batches-py')
X_train,Y_train,X_test,Y_test = load_CIFAR10(data_dir)
del X_train
del Y_train
image = X_test[0]
m,n... | 0.220762 | 0.260851 |
import datetime
import os
import MySQLdb
import urllib
class HtmlOutputer(object):
def __init__(self):
self.datas = []
self.title=''
def collect_data(self,new_title,data):#收集数据
print "正在收集数据..."
if data is None:
return
for dat in data:
... | html_outputer.py | import datetime
import os
import MySQLdb
import urllib
class HtmlOutputer(object):
def __init__(self):
self.datas = []
self.title=''
def collect_data(self,new_title,data):#收集数据
print "正在收集数据..."
if data is None:
return
for dat in data:
... | 0.051095 | 0.087876 |
import numpy as np
import pytorch_lightning as pl
import torch
from pytorch_lightning import _logger as log
from pytorch_lightning.core.memory import ModelSummary
from sklearn.metrics import average_precision_score
from torch import nn
from torch.autograd import Variable
from torch.optim.lr_scheduler import ReduceLROnP... | models/lightningclassifier.py | import numpy as np
import pytorch_lightning as pl
import torch
from pytorch_lightning import _logger as log
from pytorch_lightning.core.memory import ModelSummary
from sklearn.metrics import average_precision_score
from torch import nn
from torch.autograd import Variable
from torch.optim.lr_scheduler import ReduceLROnP... | 0.935707 | 0.565839 |
from __future__ import annotations
from typing import Any, Optional
from psion.oauth2.exceptions import (
AccessDenied,
FatalError,
InvalidRequest,
OAuth2Error,
UnauthorizedClient,
UnsupportedResponseType,
)
from psion.oauth2.grants.base import BaseGrant
from psion.oauth2.mixins import ClientM... | src/psion/oauth2/endpoints/authorization.py | from __future__ import annotations
from typing import Any, Optional
from psion.oauth2.exceptions import (
AccessDenied,
FatalError,
InvalidRequest,
OAuth2Error,
UnauthorizedClient,
UnsupportedResponseType,
)
from psion.oauth2.grants.base import BaseGrant
from psion.oauth2.mixins import ClientM... | 0.920522 | 0.156266 |
# # Sets
# In[16]:
import random
set1 = []
set2 = []
for _i in range(0,10):
set1.append(random.randint(0,10))
for _i in range(0, 10):
set2.append(random.randint(0,10))
set1 = set(set1)
print(set1)
set2 = set(set2)
print(set2)
both = set1 & set2
print(both)
# In[17]:
a = {1,2,3,5,1,2,5,1,4}
b = ... | Sorting_Searching/sorting_searching.py |
# # Sets
# In[16]:
import random
set1 = []
set2 = []
for _i in range(0,10):
set1.append(random.randint(0,10))
for _i in range(0, 10):
set2.append(random.randint(0,10))
set1 = set(set1)
print(set1)
set2 = set(set2)
print(set2)
both = set1 & set2
print(both)
# In[17]:
a = {1,2,3,5,1,2,5,1,4}
b = ... | 0.362292 | 0.344829 |
import pandas as pd
from sklearn.decomposition import PCA
from sklearn.ensemble import GradientBoostingClassifier, RandomForestClassifier
from sklearn.feature_selection import SelectKBest, mutual_info_classif
from skopt.space import Real, Integer, Categorical
from xgboost import XGBClassifier
from imblearn.pipeline imp... | second_example_binary.py | import pandas as pd
from sklearn.decomposition import PCA
from sklearn.ensemble import GradientBoostingClassifier, RandomForestClassifier
from sklearn.feature_selection import SelectKBest, mutual_info_classif
from skopt.space import Real, Integer, Categorical
from xgboost import XGBClassifier
from imblearn.pipeline imp... | 0.719679 | 0.368747 |
import os
import random
import asyncio
from dataIO import dataIO
from discord.ext import commands
import Checker
class Russianroulette:
"""Allows 6 players to play Russian Roulette"""
def __init__(self, bot):
self.bot = bot
self.file_path = "data/roulette/rrgame.json"
self.rrgame = da... | cogs/russianroulette.py | import os
import random
import asyncio
from dataIO import dataIO
from discord.ext import commands
import Checker
class Russianroulette:
"""Allows 6 players to play Russian Roulette"""
def __init__(self, bot):
self.bot = bot
self.file_path = "data/roulette/rrgame.json"
self.rrgame = da... | 0.201892 | 0.12787 |
class Solution1:
def maxAncestorDiff(self, root: TreeNode) -> int:
"""Time limit exceeded solution
"""
maxDiff = float('-inf')
def dfs(node, ancestors):
nonlocal maxDiff
if node is None:
return
for ancestor... | python/1026_Maximum_Difference_Between_Node_and_Ancestor.py | class Solution1:
def maxAncestorDiff(self, root: TreeNode) -> int:
"""Time limit exceeded solution
"""
maxDiff = float('-inf')
def dfs(node, ancestors):
nonlocal maxDiff
if node is None:
return
for ancestor... | 0.886893 | 0.581838 |
import re
import sys
from setuptools import find_packages, setup
# Using numpy 1.20.0 requires python >= 3.7
if sys.version_info[:2] < (3, 7):
raise ImportError("""
This version of coredotfinance no supports python versions less than 3.7.0.
""")
def find_version(fname):
"""Attempts to find the versio... | setup.py | import re
import sys
from setuptools import find_packages, setup
# Using numpy 1.20.0 requires python >= 3.7
if sys.version_info[:2] < (3, 7):
raise ImportError("""
This version of coredotfinance no supports python versions less than 3.7.0.
""")
def find_version(fname):
"""Attempts to find the versio... | 0.306838 | 0.23456 |
from yaml import load_all
from log import log
import sys
import os
class RheaYAML(object):
def __init__(self, filename=None):
if filename:
self.filestream = self.openfile(filename)
if self.filestream:
self.configs = self.loadconfig(self.filestream)
els... | RheaFlow/RheaYAML.py |
from yaml import load_all
from log import log
import sys
import os
class RheaYAML(object):
def __init__(self, filename=None):
if filename:
self.filestream = self.openfile(filename)
if self.filestream:
self.configs = self.loadconfig(self.filestream)
els... | 0.376165 | 0.104752 |
__author__ = 'mnowotka'
# ----------------------------------------------------------------------------------------------------------------------
import os
import tempfile
import io
from rdkit import Chem
from beaker.utils.functional import _apply, _call
import beaker.utils.chemical_transformation as ct
from chembl_st... | src/chembl_beaker/beaker/utils/io.py | __author__ = 'mnowotka'
# ----------------------------------------------------------------------------------------------------------------------
import os
import tempfile
import io
from rdkit import Chem
from beaker.utils.functional import _apply, _call
import beaker.utils.chemical_transformation as ct
from chembl_st... | 0.327776 | 0.182644 |
import tensorflow as tf
import utils.util as util
import sys
def flat_config(config):
"""flat config to a dict"""
f_config = {}
category = ['data', 'model', 'train', 'info']
for cate in category:
for key, val in config[cate].items():
f_config[key] = val
return f_config
def cre... | examples/notebooks/xDeepFM/config_utils.py | import tensorflow as tf
import utils.util as util
import sys
def flat_config(config):
"""flat config to a dict"""
f_config = {}
category = ['data', 'model', 'train', 'info']
for cate in category:
for key, val in config[cate].items():
f_config[key] = val
return f_config
def cre... | 0.415966 | 0.087252 |
import subprocess
import os
import tempfile
# File system parameters
HOST_DIR = os.path.abspath("tmp_src")
MNT_DIR = "/usr/src/app"
# Interpreted language runtimes
RUNTIMES = {
"py": "python:latest python",
"js": "node:latest node",
"rb": "ruby:latest ruby"
}
# Docker run template
RUN_CMD = "docker run... | runtime_utils.py | import subprocess
import os
import tempfile
# File system parameters
HOST_DIR = os.path.abspath("tmp_src")
MNT_DIR = "/usr/src/app"
# Interpreted language runtimes
RUNTIMES = {
"py": "python:latest python",
"js": "node:latest node",
"rb": "ruby:latest ruby"
}
# Docker run template
RUN_CMD = "docker run... | 0.425367 | 0.082143 |
from sqlalchemy import Column, Integer, Float, String, DateTime, Boolean, ForeignKey, create_engine, Table
from sqlalchemy.schema import UniqueConstraint
from sqlalchemy.orm import sessionmaker, relationship
from sqlalchemy.ext.declarative import declarative_base
from sqlalchemy.orm.exc import NoResultFound
from sqlalc... | core/models.py | from sqlalchemy import Column, Integer, Float, String, DateTime, Boolean, ForeignKey, create_engine, Table
from sqlalchemy.schema import UniqueConstraint
from sqlalchemy.orm import sessionmaker, relationship
from sqlalchemy.ext.declarative import declarative_base
from sqlalchemy.orm.exc import NoResultFound
from sqlalc... | 0.349089 | 0.086671 |
import torch
t = torch
import torch.nn as nn
import torch.nn.functional as F
from torchcv.models.dsod.densenet import DenseNet
from torch.autograd import Variable
import torch
import torch.nn as nn
from torch.autograd import Function
from torch.autograd import Variable
import torch.nn.init as init
class L2Norm(nn.Mod... | torchcv/models/dsod/dsod.py | import torch
t = torch
import torch.nn as nn
import torch.nn.functional as F
from torchcv.models.dsod.densenet import DenseNet
from torch.autograd import Variable
import torch
import torch.nn as nn
from torch.autograd import Function
from torch.autograd import Variable
import torch.nn.init as init
class L2Norm(nn.Mod... | 0.879257 | 0.471649 |
import sys
import os
import json
import matplotlib.pyplot as plt
import warnings
warnings.simplefilter("ignore")
DIR = sys.argv[1]
max_scaling_factor_query_evaluation = int(sys.argv[2])
use_cases = ["uniprot", "social-network", "bib", "shop"]
participants = ["DO", "U", "QT", "SE", "AT"]
lists_go = {} # dict used to ... | script-plot.py | import sys
import os
import json
import matplotlib.pyplot as plt
import warnings
warnings.simplefilter("ignore")
DIR = sys.argv[1]
max_scaling_factor_query_evaluation = int(sys.argv[2])
use_cases = ["uniprot", "social-network", "bib", "shop"]
participants = ["DO", "U", "QT", "SE", "AT"]
lists_go = {} # dict used to ... | 0.152379 | 0.31883 |
from numpy import array, all, ones_like
from pynucastro.nucdata import PartitionFunctionTable, PartitionFunctionCollection
import os
nucdata_dir = os.path.dirname(os.path.dirname(os.path.realpath(__file__)))
pf_dir = os.path.join(nucdata_dir, 'PartitionFunction')
dir_etfsiq_low = os.path.join(pf_dir, 'etfsiq_low.txt'... | pynucastro/nucdata/tests/test_partition.py | from numpy import array, all, ones_like
from pynucastro.nucdata import PartitionFunctionTable, PartitionFunctionCollection
import os
nucdata_dir = os.path.dirname(os.path.dirname(os.path.realpath(__file__)))
pf_dir = os.path.join(nucdata_dir, 'PartitionFunction')
dir_etfsiq_low = os.path.join(pf_dir, 'etfsiq_low.txt'... | 0.335351 | 0.224225 |
def _check_binary(binary):
if isinstance(binary , str):
binary = list(binary)
if isinstance(binary , list) == False:
raise SyntaxError("Values should be in list or string format!")
if isinstance(binary[0] , int):
valid_values = [0 , 1]
else:
valid_values = ['0' , '1... | LogicPy/conversion.py | def _check_binary(binary):
if isinstance(binary , str):
binary = list(binary)
if isinstance(binary , list) == False:
raise SyntaxError("Values should be in list or string format!")
if isinstance(binary[0] , int):
valid_values = [0 , 1]
else:
valid_values = ['0' , '1... | 0.538255 | 0.175397 |
from argparse import ArgumentParser
import os
import sys
from tempfile import TemporaryDirectory
from ipykernel.kernelspec import RESOURCES, get_kernel_dict
from jupyter_client import AsyncKernelManager
from jupyter_client.kernelspec import KernelSpecManager
from nbclient import NotebookClient
from nbclient.exceptions... | princess.py | from argparse import ArgumentParser
import os
import sys
from tempfile import TemporaryDirectory
from ipykernel.kernelspec import RESOURCES, get_kernel_dict
from jupyter_client import AsyncKernelManager
from jupyter_client.kernelspec import KernelSpecManager
from nbclient import NotebookClient
from nbclient.exceptions... | 0.386648 | 0.112844 |
from django.conf import settings
from django.db import migrations, models
import django.db.models.deletion
class Migration(migrations.Migration):
dependencies = [
migrations.swappable_dependency(settings.AUTH_USER_MODEL),
('CyberUser', '0005_remove_news_comments'),
]
operations = [
... | CyberProject/CyberUser/migrations/0006_auto_20210219_2041.py |
from django.conf import settings
from django.db import migrations, models
import django.db.models.deletion
class Migration(migrations.Migration):
dependencies = [
migrations.swappable_dependency(settings.AUTH_USER_MODEL),
('CyberUser', '0005_remove_news_comments'),
]
operations = [
... | 0.546012 | 0.095729 |
from argparse import ArgumentParser
from collections import defaultdict
import glob
from importlib import import_module
import logging
from pathlib import Path
import re
import string
import time
from gensim import corpora
from gensim.models.doc2vec import Doc2Vec, TaggedDocument
from gensim.models.callbacks import Ca... | lc_etl/train_doc2vec.py | from argparse import ArgumentParser
from collections import defaultdict
import glob
from importlib import import_module
import logging
from pathlib import Path
import re
import string
import time
from gensim import corpora
from gensim.models.doc2vec import Doc2Vec, TaggedDocument
from gensim.models.callbacks import Ca... | 0.455199 | 0.155463 |
import asyncio
import discord
from discord.ext.commands import BadArgument
import typing
from redbot.core import Config, commands
from redbot.core.utils.predicates import MessagePredicate
from redbot.core.utils.menus import start_adding_reactions
from redbot.core.commands.converter import parse_timedelta
from ... | simplesanction/simplesanction.py | import asyncio
import discord
from discord.ext.commands import BadArgument
import typing
from redbot.core import Config, commands
from redbot.core.utils.predicates import MessagePredicate
from redbot.core.utils.menus import start_adding_reactions
from redbot.core.commands.converter import parse_timedelta
from ... | 0.413714 | 0.169715 |
from __future__ import print_function
import numpy as np
import regreg.api as rr
from ...tests.instance import logistic_instance, gaussian_instance
from ..selection_map import M_estimator_map
from ..ci_approx_density import approximate_conditional_density
from ...randomized.query import naive_confidence_intervals
from... | selectinf/sandbox/approx_ci/tests/test_glm.py | from __future__ import print_function
import numpy as np
import regreg.api as rr
from ...tests.instance import logistic_instance, gaussian_instance
from ..selection_map import M_estimator_map
from ..ci_approx_density import approximate_conditional_density
from ...randomized.query import naive_confidence_intervals
from... | 0.712132 | 0.37359 |
import copy
from pathlib import Path
import matplotlib.pyplot as plt
from target_extraction.data_types import TargetTextCollection, TargetText
from target_extraction.tokenizers import whitespace
from target_extraction.analysis.dataset_plots import target_length_plot
from target_extraction.analysis.dataset_plots impor... | tests/analysis/dataset_plots_test.py | import copy
from pathlib import Path
import matplotlib.pyplot as plt
from target_extraction.data_types import TargetTextCollection, TargetText
from target_extraction.tokenizers import whitespace
from target_extraction.analysis.dataset_plots import target_length_plot
from target_extraction.analysis.dataset_plots impor... | 0.562898 | 0.470737 |
from ansys.dpf.post.result_object import Result
class Tensor(Result):
"""Child class of the Result one.
Implements a tensor result (stress, strain).
"""
@property
def xx(self):
"""Returns XX component of the tensor as a ResultData."""
return super()._get_result_data(
... | ansys/dpf/post/tensor.py |
from ansys.dpf.post.result_object import Result
class Tensor(Result):
"""Child class of the Result one.
Implements a tensor result (stress, strain).
"""
@property
def xx(self):
"""Returns XX component of the tensor as a ResultData."""
return super()._get_result_data(
... | 0.971618 | 0.527377 |
import numpy as np
import torch
import torch.nn as nn
import sys
sys.path.append("../")
from rnn_wrap import RNNwrap
# Define RNN model
class MyRNN(nn.Module):
"""RNN model for sine generation"""
def __init__(self, rnn_type='LSTM', hidden_size=200, num_layers=1, K=100, init='henaff'):
super(MyRNN, sel... | sine-generator/sine_generator.py | import numpy as np
import torch
import torch.nn as nn
import sys
sys.path.append("../")
from rnn_wrap import RNNwrap
# Define RNN model
class MyRNN(nn.Module):
"""RNN model for sine generation"""
def __init__(self, rnn_type='LSTM', hidden_size=200, num_layers=1, K=100, init='henaff'):
super(MyRNN, sel... | 0.725357 | 0.643665 |
import os
from os import listdir
from os.path import isdir, isfile
import sys
import re
def splitpath( path, maxdepth=20 ):
(head, tail) = os.path.split(path)
return splitpath(head, maxdepth - 1) + [tail] if maxdepth and head and head != path else [head or tail]
def title_from_path(path):
num_temp = re.su... | tools/summary.py | import os
from os import listdir
from os.path import isdir, isfile
import sys
import re
def splitpath( path, maxdepth=20 ):
(head, tail) = os.path.split(path)
return splitpath(head, maxdepth - 1) + [tail] if maxdepth and head and head != path else [head or tail]
def title_from_path(path):
num_temp = re.su... | 0.302597 | 0.248352 |
import torch
import json
from torch.utils.data import Dataset
import os
import numpy as np
from utils import OrderedSet
from data_retriever import make_single_loader
class ReaderData(Dataset):
# get the input data item for the reader model
def __init__(self,
tokenizer,
sample... | data_reader.py | import torch
import json
from torch.utils.data import Dataset
import os
import numpy as np
from utils import OrderedSet
from data_retriever import make_single_loader
class ReaderData(Dataset):
# get the input data item for the reader model
def __init__(self,
tokenizer,
sample... | 0.588298 | 0.3534 |
from settings import *
import numpy as np
from tensorflow.keras.utils import Sequence
import cv2 as cv
src_train_folder = os.path.join(data_folder, 'IM_SAT_TRAIN', 'img')
src_train_folder_gt = os.path.join(data_folder, 'IM_SAT_TRAIN', 'gt')
src_test_folder = os.path.join(data_folder, 'IM_SAT_VAL_SMALL', 'img')
src_t... | inria-aerial-image-labeling/data.py | from settings import *
import numpy as np
from tensorflow.keras.utils import Sequence
import cv2 as cv
src_train_folder = os.path.join(data_folder, 'IM_SAT_TRAIN', 'img')
src_train_folder_gt = os.path.join(data_folder, 'IM_SAT_TRAIN', 'gt')
src_test_folder = os.path.join(data_folder, 'IM_SAT_VAL_SMALL', 'img')
src_t... | 0.543348 | 0.405154 |
from django.core.paginator import Paginator
from django.core.serializers import serialize
from django.db.models import Count
from django.db.models.functions import TruncMonth
from django.http import JsonResponse, HttpResponseForbidden, HttpResponse, HttpRequest
from django.shortcuts import get_object_or_404
from dashb... | dashboard/views/api.py | from django.core.paginator import Paginator
from django.core.serializers import serialize
from django.db.models import Count
from django.db.models.functions import TruncMonth
from django.http import JsonResponse, HttpResponseForbidden, HttpResponse, HttpRequest
from django.shortcuts import get_object_or_404
from dashb... | 0.874587 | 0.338924 |
import argparse
import matplotlib
import pandas as pd
import matplotlib.pyplot as plt
from warnings import warn
from spectral_analyse import *
params = {
"axes.titlesize" : 16,
'axes.labelsize': 16,
'font.size': 16,
'legend.fontsize': 16,
'xtick.labelsize': 16,
'ytick.labelsize': 16,
'xtick... | quantifying-aliasing/generate_plots.py | import argparse
import matplotlib
import pandas as pd
import matplotlib.pyplot as plt
from warnings import warn
from spectral_analyse import *
params = {
"axes.titlesize" : 16,
'axes.labelsize': 16,
'font.size': 16,
'legend.fontsize': 16,
'xtick.labelsize': 16,
'ytick.labelsize': 16,
'xtick... | 0.608129 | 0.41561 |
import unittest
from flask import json
from ..apis.hcp import app
from . import client_get, now, now_minus_24hrs
get = client_get(app)
class HCPTestCase(unittest.TestCase):
def test_root_not_allowed(self):
rv = get('/')
self.assertEqual(rv.status_code, 404)
def test_all_top_objects_should_p... | unified/tests/test_hcp.py | import unittest
from flask import json
from ..apis.hcp import app
from . import client_get, now, now_minus_24hrs
get = client_get(app)
class HCPTestCase(unittest.TestCase):
def test_root_not_allowed(self):
rv = get('/')
self.assertEqual(rv.status_code, 404)
def test_all_top_objects_should_p... | 0.309545 | 0.248335 |
import tensorflow as tf
from tensorflow import keras
import numpy as np
import time
import os
from globalemu.models import network_models
from globalemu.losses import loss_functions
class nn():
r"""
**kwargs:**
batch_size: **int / default: 100**
| The batch size used by ``tensorflow`` w... | globalemu/network.py | import tensorflow as tf
from tensorflow import keras
import numpy as np
import time
import os
from globalemu.models import network_models
from globalemu.losses import loss_functions
class nn():
r"""
**kwargs:**
batch_size: **int / default: 100**
| The batch size used by ``tensorflow`` w... | 0.918118 | 0.730782 |
import dash
import dash_core_components as dcc
import dash_html_components as html
from dash.dependencies import Input, Output, State
from plotly import graph_objs as go
from plotly.graph_objs import *
from plotly.subplots import make_subplots
import shapefile
import numpy as np
import json
import time
import pickle
... | app/app.py | import dash
import dash_core_components as dcc
import dash_html_components as html
from dash.dependencies import Input, Output, State
from plotly import graph_objs as go
from plotly.graph_objs import *
from plotly.subplots import make_subplots
import shapefile
import numpy as np
import json
import time
import pickle
... | 0.595845 | 0.209187 |
import re
import os.path
import datetime
import base.Const
import base.StringUtils
import base.SearchRule
import base.SearchRuleList
class TextProcessor:
'''A processor for finding/modifying text.
'''
def __init__(self, logger):
self._filename = None
self._lines = None
self._logg... | base/TextProcessor.py | import re
import os.path
import datetime
import base.Const
import base.StringUtils
import base.SearchRule
import base.SearchRuleList
class TextProcessor:
'''A processor for finding/modifying text.
'''
def __init__(self, logger):
self._filename = None
self._lines = None
self._logg... | 0.622115 | 0.144903 |
from datetime import datetime
from datetime import timedelta
from os import environ
from unittest.case import SkipTest
from hubspot.connection import APIKey
from hubspot.connection import PortalConnection
from nose.tools import assert_in
from nose.tools import assert_is_none
from nose.tools import assert_items_equal
... | tests/smoke_tests.py |
from datetime import datetime
from datetime import timedelta
from os import environ
from unittest.case import SkipTest
from hubspot.connection import APIKey
from hubspot.connection import PortalConnection
from nose.tools import assert_in
from nose.tools import assert_is_none
from nose.tools import assert_items_equal
... | 0.638272 | 0.122392 |
import os, sys
import re
abstractions = ['FileList', 'File',
'TemplateList', 'Template',
'UntrainableTransform',
'MetaTransform', 'UntrainableMetaTransform',
'MetadataTransform', 'UntrainableMetadataTransform',
'TimeVaryingTransform',
... | docs/scripts/generate_plugin_docs.py | import os, sys
import re
abstractions = ['FileList', 'File',
'TemplateList', 'Template',
'UntrainableTransform',
'MetaTransform', 'UntrainableMetaTransform',
'MetadataTransform', 'UntrainableMetadataTransform',
'TimeVaryingTransform',
... | 0.285571 | 0.225971 |
class RobotFrameworkFacade(object):
"""
Nothing on Robot Framework is currently typed, so, this is a facade
to help to deal with it so that we don't add lots of things to ignore its
imports/typing.
"""
@property
def get_model(self):
from robot.api import get_model # type:ignore
... | robotframework-interactive/src/robotframework_interactive/robotfacade.py | class RobotFrameworkFacade(object):
"""
Nothing on Robot Framework is currently typed, so, this is a facade
to help to deal with it so that we don't add lots of things to ignore its
imports/typing.
"""
@property
def get_model(self):
from robot.api import get_model # type:ignore
... | 0.737064 | 0.359701 |
import machine
import math
import network
import os
import time
import utime
import gc
import pycom
from machine import RTC
from machine import SD
from L76GNSS import L76GNSS
from pytrack import Pytrack
import struct
def blink(seconds, rgb):
pycom.rgbled(rgb)
time.sleep(seconds/2)
pycom.rgbled(0x000000) ... | uPython/pytrackHelper.py |
import machine
import math
import network
import os
import time
import utime
import gc
import pycom
from machine import RTC
from machine import SD
from L76GNSS import L76GNSS
from pytrack import Pytrack
import struct
def blink(seconds, rgb):
pycom.rgbled(rgb)
time.sleep(seconds/2)
pycom.rgbled(0x000000) ... | 0.392686 | 0.30862 |
from django.utils.translation import ugettext_lazy as _
from oslo_serialization import jsonutils as json
from horizon import exceptions
from horizon import forms
from saharaclient.api import base as api_base
from sahara_dashboard.api import sahara as saharaclient
import sahara_dashboard.content.data_processing. \
... | sahara_dashboard/content/data_processing/clusters/cluster_templates/forms/import_forms.py |
from django.utils.translation import ugettext_lazy as _
from oslo_serialization import jsonutils as json
from horizon import exceptions
from horizon import forms
from saharaclient.api import base as api_base
from sahara_dashboard.api import sahara as saharaclient
import sahara_dashboard.content.data_processing. \
... | 0.494873 | 0.096748 |
import Gnome, random
class Gnomes(object):
"""
Gnomes class:
Represents a specified collection of Gnomes
This class is constructed for solving TSP using a genetic algorithm
"""
# Constructor
# NOTE: numCells is the number of unique cells, not the length of the gnome
def __i... | TSPGeneticAlgorithm/TSPGeneticAlgorithm/Gnomes.py | import Gnome, random
class Gnomes(object):
"""
Gnomes class:
Represents a specified collection of Gnomes
This class is constructed for solving TSP using a genetic algorithm
"""
# Constructor
# NOTE: numCells is the number of unique cells, not the length of the gnome
def __i... | 0.538012 | 0.483648 |
import datetime
from south.db import db
from south.v2 import SchemaMigration
from django.db import models
class Migration(SchemaMigration):
def forwards(self, orm):
# Adding model 'Project'
db.create_table(u'scrum_project', (
(u'id', self.gf('django.db.models.fields.AutoField')(primar... | scrum/migrations/0001_initial.py | import datetime
from south.db import db
from south.v2 import SchemaMigration
from django.db import models
class Migration(SchemaMigration):
def forwards(self, orm):
# Adding model 'Project'
db.create_table(u'scrum_project', (
(u'id', self.gf('django.db.models.fields.AutoField')(primar... | 0.425367 | 0.120077 |
import torch
import torch.nn as nn
import torch.nn.functional as F
import math
class Gaussian(object):
def __init__(self, mu, rho):
super().__init__()
self.mu = mu
self.rho = rho
self.normal = torch.distributions.Normal(0,1)
@property
def sigma(self):
return tor... | src/BayesModels.py | import torch
import torch.nn as nn
import torch.nn.functional as F
import math
class Gaussian(object):
def __init__(self, mu, rho):
super().__init__()
self.mu = mu
self.rho = rho
self.normal = torch.distributions.Normal(0,1)
@property
def sigma(self):
return tor... | 0.944305 | 0.53437 |
from howfairis.readme import Readme
from howfairis.readme_format import ReadmeFormat
from tests.helpers.load_snippets_from_local_data import load_snippets_from_local_data
def test_1():
rst_filename = "1-original.rst"
snippets = load_snippets_from_local_data(__file__)
original_text = snippets["/" + rst_fil... | tests/remove_comments_rst/test_remove_comments_rst.py | from howfairis.readme import Readme
from howfairis.readme_format import ReadmeFormat
from tests.helpers.load_snippets_from_local_data import load_snippets_from_local_data
def test_1():
rst_filename = "1-original.rst"
snippets = load_snippets_from_local_data(__file__)
original_text = snippets["/" + rst_fil... | 0.724383 | 0.601594 |
import itertools
import sys
import pandas as pd
from ic_graph import IC_Graph
from sample_set import SampleSet
def is_goal_influenced(ic_graph, directed_all, goal):
influenced_columns = [t[2] for t in directed_all]
return goal in influenced_columns
def get_influencer(t):
if t[0] == t[2]:
return t... | lemidata.py | import itertools
import sys
import pandas as pd
from ic_graph import IC_Graph
from sample_set import SampleSet
def is_goal_influenced(ic_graph, directed_all, goal):
influenced_columns = [t[2] for t in directed_all]
return goal in influenced_columns
def get_influencer(t):
if t[0] == t[2]:
return t... | 0.289573 | 0.200636 |
import os
import cPickle
import glob
from numpy import ogrid, zeros, conj
import numpy
def process(process_id, result_directory, config, parameter_setting):
""" Perform computation for specific configuration and store results.
This function is called once per process for the specific configuration.
... | pySPACE/run/scripts/mandelbrot_set.py | import os
import cPickle
import glob
from numpy import ogrid, zeros, conj
import numpy
def process(process_id, result_directory, config, parameter_setting):
""" Perform computation for specific configuration and store results.
This function is called once per process for the specific configuration.
... | 0.658198 | 0.45302 |
import http
from django.http import HttpResponse
from turbo_response import (
TurboStream,
TurboStreamResponse,
TurboStreamStreamingResponse,
)
from turbo_response.decorators import turbo_stream_response
class TestTurboStreamResponse:
def test_view_returns_response(self, rf):
req = rf.get("/... | tests/test_decorators.py | import http
from django.http import HttpResponse
from turbo_response import (
TurboStream,
TurboStreamResponse,
TurboStreamStreamingResponse,
)
from turbo_response.decorators import turbo_stream_response
class TestTurboStreamResponse:
def test_view_returns_response(self, rf):
req = rf.get("/... | 0.562898 | 0.181372 |
import os
import logging
from .helpers import log_exception
from .config_readers.yaml_config_reader import YamlConfigReader
from .config_readers.json_config_reader import JsonConfigReader
def _convert_color(color):
if isinstance(color, int):
return ''.join(['#', hex(color)[2:].rjust(3, '0')])
return c... | urwim/config.py |
import os
import logging
from .helpers import log_exception
from .config_readers.yaml_config_reader import YamlConfigReader
from .config_readers.json_config_reader import JsonConfigReader
def _convert_color(color):
if isinstance(color, int):
return ''.join(['#', hex(color)[2:].rjust(3, '0')])
return c... | 0.189184 | 0.054224 |
from __future__ import print_function, absolute_import
import cStringIO
import json
import logging
import os
import tarfile
import time
import couchdb
from orderportal import constants
from orderportal import settings
from orderportal import utils
def dump(db, filepath):
"""Dump contents of the database to a t... | orderportal/dump.py | from __future__ import print_function, absolute_import
import cStringIO
import json
import logging
import os
import tarfile
import time
import couchdb
from orderportal import constants
from orderportal import settings
from orderportal import utils
def dump(db, filepath):
"""Dump contents of the database to a t... | 0.376623 | 0.092115 |
from collections import defaultdict
import torch
import torch.nn as nn
from mighty.monitor.accuracy import AccuracyEmbedding
from mighty.trainer import TrainerEmbedding, TrainerGrad
from mighty.utils.common import batch_to_cuda, clone_cpu
from mighty.utils.data import DataLoader
from mighty.utils.stub import Optimize... | nn/trainer.py | from collections import defaultdict
import torch
import torch.nn as nn
from mighty.monitor.accuracy import AccuracyEmbedding
from mighty.trainer import TrainerEmbedding, TrainerGrad
from mighty.utils.common import batch_to_cuda, clone_cpu
from mighty.utils.data import DataLoader
from mighty.utils.stub import Optimize... | 0.934492 | 0.240306 |
import json
from django.contrib.auth import get_user_model
from django.test import Client, TestCase
from rest_framework import status
from rest_framework.reverse import reverse
from rest_framework.test import APITestCase
from apps.utils.test_util import TestMixin
from .models import S3File
from .utils import *
use... | server/apps/s3file/tests.py | import json
from django.contrib.auth import get_user_model
from django.test import Client, TestCase
from rest_framework import status
from rest_framework.reverse import reverse
from rest_framework.test import APITestCase
from apps.utils.test_util import TestMixin
from .models import S3File
from .utils import *
use... | 0.397237 | 0.236825 |
class BasicTextReports:
def __init__(self, multiple_reports_dictionary, single_reports_dictionary, sample_data):
self.multiple_reports_dictionary = multiple_reports_dictionary
self.single_reports_dictionary = single_reports_dictionary
self.sample_data = sample_data
self.basic_text_r... | Rover_Source_Code/Post_Generate/post_generate_basic_text_report_methods.py | class BasicTextReports:
def __init__(self, multiple_reports_dictionary, single_reports_dictionary, sample_data):
self.multiple_reports_dictionary = multiple_reports_dictionary
self.single_reports_dictionary = single_reports_dictionary
self.sample_data = sample_data
self.basic_text_r... | 0.520253 | 0.319785 |