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 tensorflow as tf
def weight_variable(name, shape):
"""
Create a weight variable with appropriate initialization
:param name: weight name
:param shape: weight shape
:return: initialized weight variable
"""
initer = tf.contrib.layers.xavier_initializer(uniform=False)
return tf.get... | segmentation/model/model_2D/ops_enet.py | import tensorflow as tf
def weight_variable(name, shape):
"""
Create a weight variable with appropriate initialization
:param name: weight name
:param shape: weight shape
:return: initialized weight variable
"""
initer = tf.contrib.layers.xavier_initializer(uniform=False)
return tf.get... | 0.933817 | 0.692924 |
from __future__ import absolute_import
from __future__ import unicode_literals
import pytest
from compose.config.environment import Environment
from compose.config.interpolation import interpolate_environment_variables
from compose.config.interpolation import Interpolator
from compose.config.interpolation import Inva... | tests/unit/config/interpolation_test.py | from __future__ import absolute_import
from __future__ import unicode_literals
import pytest
from compose.config.environment import Environment
from compose.config.interpolation import interpolate_environment_variables
from compose.config.interpolation import Interpolator
from compose.config.interpolation import Inva... | 0.625896 | 0.347067 |
import unittest
import os
import tarfile
import shutil
import datetime
import cheddar
ASSET_TAR = (
os.path.dirname(os.path.abspath( __file__ )) + os.path.sep +
"assets.tar.gz"
)
ASSET_DIR = '.'.join(ASSET_TAR.split('.')[:-2])
class TestMediaAttributes(unittest.TestCase):
@classmethod
def setUpClas... | tests/test_library.py | import unittest
import os
import tarfile
import shutil
import datetime
import cheddar
ASSET_TAR = (
os.path.dirname(os.path.abspath( __file__ )) + os.path.sep +
"assets.tar.gz"
)
ASSET_DIR = '.'.join(ASSET_TAR.split('.')[:-2])
class TestMediaAttributes(unittest.TestCase):
@classmethod
def setUpClas... | 0.498779 | 0.431405 |
import pandas as pd
import numpy as np
def cr_uplift(control, variant, round=None):
"""
Compute uplift
Parameters
----------
control : float
Proportion in control group
variant : float
Proportion in variant group
round
If int rounds the results to this number of de... | abtest/utils.py | import pandas as pd
import numpy as np
def cr_uplift(control, variant, round=None):
"""
Compute uplift
Parameters
----------
control : float
Proportion in control group
variant : float
Proportion in variant group
round
If int rounds the results to this number of de... | 0.928906 | 0.612484 |
from __future__ import division, absolute_import
import simplejson
from twisted.application.internet import TCPClient
from twisted.internet import defer
from twisted.trial import unittest
from udplog import redis
from udplog.twisted import Dispatcher
class FakeRedisClient(object):
def __init__(self):
s... | udplog/test/test_redis.py | from __future__ import division, absolute_import
import simplejson
from twisted.application.internet import TCPClient
from twisted.internet import defer
from twisted.trial import unittest
from udplog import redis
from udplog.twisted import Dispatcher
class FakeRedisClient(object):
def __init__(self):
s... | 0.568895 | 0.179674 |
# by <NAME> and <NAME>, 2018 <<EMAIL>>
import copy
import numpy as np
import os
import sys
from sklearn.ensemble import AdaBoostClassifier
from sklearn.ensemble import BaggingClassifier
from sklearn.ensemble import ExtraTreesClassifier
from sklearn.ensemble import GradientBoostingClassifier
from sklearn.ensemble imp... | src/classification-test.py |
# by <NAME> and <NAME>, 2018 <<EMAIL>>
import copy
import numpy as np
import os
import sys
from sklearn.ensemble import AdaBoostClassifier
from sklearn.ensemble import BaggingClassifier
from sklearn.ensemble import ExtraTreesClassifier
from sklearn.ensemble import GradientBoostingClassifier
from sklearn.ensemble imp... | 0.386648 | 0.31254 |
import json
from contextlib import contextmanager
from datetime import date, datetime, timedelta
from itertools import count
from typing import Any, Callable, Iterable, Iterator, List, Optional, TypeVar, Union
import httpx
from loguru import logger
from pydantic import BaseModel, validator
T = TypeVar("T")
class Us... | clickup_to_sqlite/clickup_client.py | import json
from contextlib import contextmanager
from datetime import date, datetime, timedelta
from itertools import count
from typing import Any, Callable, Iterable, Iterator, List, Optional, TypeVar, Union
import httpx
from loguru import logger
from pydantic import BaseModel, validator
T = TypeVar("T")
class Us... | 0.604866 | 0.314195 |
from tenable.errors import *
from ..checker import check
import pytest, os
def test_organizations_constructor_name_typeerror(sc):
with pytest.raises(TypeError):
sc.organizations._constructor(name=1)
def test_organizations_constructor_description_typeerror(sc):
with pytest.raises(TypeError):
sc... | tests/sc/test_organizations.py | from tenable.errors import *
from ..checker import check
import pytest, os
def test_organizations_constructor_name_typeerror(sc):
with pytest.raises(TypeError):
sc.organizations._constructor(name=1)
def test_organizations_constructor_description_typeerror(sc):
with pytest.raises(TypeError):
sc... | 0.451568 | 0.640509 |
from __future__ import division
import rospy
from geometry_msgs.msg import Quaternion
from geometry_msgs.msg import Twist
from nav_msgs.msg import Odometry
from std_msgs.msg import Int32
from geometry_msgs.msg import PoseWithCovarianceStamped
from tf.broadcaster import TransformBroadcaster
from tf.transformations impo... | ros/deneme.py | from __future__ import division
import rospy
from geometry_msgs.msg import Quaternion
from geometry_msgs.msg import Twist
from nav_msgs.msg import Odometry
from std_msgs.msg import Int32
from geometry_msgs.msg import PoseWithCovarianceStamped
from tf.broadcaster import TransformBroadcaster
from tf.transformations impo... | 0.638948 | 0.122366 |
from datetime import datetime
from django.db.models import Q
from contest.contest_info import get_running_contests, \
get_freeze_time_datetime, get_contestant
from contest.models import Contest
from problem.models import Problem, Submission, SubmissionDetail
from users.models import User
from utils.user_info impor... | status/status_info.py | from datetime import datetime
from django.db.models import Q
from contest.contest_info import get_running_contests, \
get_freeze_time_datetime, get_contestant
from contest.models import Contest
from problem.models import Problem, Submission, SubmissionDetail
from users.models import User
from utils.user_info impor... | 0.570571 | 0.098642 |
import torch
from torch.autograd import Variable
import torch.nn.functional as F
import collections
import numpy as np
class word2vec(torch.nn.Module):
def __init__(self, vocab_size, embedding_dim, negative_samples, ns, model_type):
super(word2vec, self).__init__()
self.ns = ns
self.negativ... | gdp/word2vec.py | import torch
from torch.autograd import Variable
import torch.nn.functional as F
import collections
import numpy as np
class word2vec(torch.nn.Module):
def __init__(self, vocab_size, embedding_dim, negative_samples, ns, model_type):
super(word2vec, self).__init__()
self.ns = ns
self.negativ... | 0.871721 | 0.349144 |
import os
import pandas as pd
import numpy as np
from tqdm import tqdm
import math
from time import time
np.set_printoptions(suppress=True)
def remove_forts():
"""this part is to remove the unneccessary files at the end of the simulation. Our purpose is to combine this part with the start of machine learning... | remove_forts.py | import os
import pandas as pd
import numpy as np
from tqdm import tqdm
import math
from time import time
np.set_printoptions(suppress=True)
def remove_forts():
"""this part is to remove the unneccessary files at the end of the simulation. Our purpose is to combine this part with the start of machine learning... | 0.169956 | 0.054299 |
from sqlalchemy import (Column, ForeignKey, Integer,
String, Boolean, UniqueConstraint)
from sqlalchemy.ext.declarative import declarative_base
from sqlalchemy.orm import relationship
from sqlalchemy import create_engine
Base = declarative_base()
class User(Base):
__tablename__ = "user"
... | setup.py | from sqlalchemy import (Column, ForeignKey, Integer,
String, Boolean, UniqueConstraint)
from sqlalchemy.ext.declarative import declarative_base
from sqlalchemy.orm import relationship
from sqlalchemy import create_engine
Base = declarative_base()
class User(Base):
__tablename__ = "user"
... | 0.757705 | 0.158012 |
# This program is free software: you can redistribute it and/or modify
# it under the terms of the GNU General Public License as published by
# the Free Software Foundation, either version 3 of the License, or
# (at your option) any later version.
# This program is distributed in the hope that it will be useful,
# bu... | fylm/fylmlib/pushover.py |
# This program is free software: you can redistribute it and/or modify
# it under the terms of the GNU General Public License as published by
# the Free Software Foundation, either version 3 of the License, or
# (at your option) any later version.
# This program is distributed in the hope that it will be useful,
# bu... | 0.722527 | 0.116764 |
from typing import List, Optional
from fastapi import FastAPI, File, UploadFile, Security, Depends, HTTPException
from fastapi.security.api_key import APIKeyQuery, APIKey
from pydantic import BaseModel
from starlette.status import HTTP_403_FORBIDDEN
from skimage.metrics import structural_similarity as ssim
... | main.py | from typing import List, Optional
from fastapi import FastAPI, File, UploadFile, Security, Depends, HTTPException
from fastapi.security.api_key import APIKeyQuery, APIKey
from pydantic import BaseModel
from starlette.status import HTTP_403_FORBIDDEN
from skimage.metrics import structural_similarity as ssim
... | 0.668988 | 0.132262 |
import json
import requests
import os
from fastapi import Security, HTTPException, status
from fastapi.security.api_key import APIKeyHeader
from functools import wraps
from jose import jwt
AUTH0_DOMAIN = os.getenv("AUTH0_DOMAIN", "Auth0 Domain undefined")
API_AUDIENCE = os.getenv("API_AUDIENCE", "Auth0 Api audience un... | backend/app/core/authentication/authentication.py | import json
import requests
import os
from fastapi import Security, HTTPException, status
from fastapi.security.api_key import APIKeyHeader
from functools import wraps
from jose import jwt
AUTH0_DOMAIN = os.getenv("AUTH0_DOMAIN", "Auth0 Domain undefined")
API_AUDIENCE = os.getenv("API_AUDIENCE", "Auth0 Api audience un... | 0.345878 | 0.044953 |
'Arguments shared between `snapshot-repo` and `snapshot-repos`.'
from .common import Path, RpmShard
from .storage import Storage
from .db_connection import DBConnectionContext
# BEWARE: If your script calls this helper, it is responsible for supporting
# **all** of its arguments. Just go through the code and make su... | fs_image/rpm/common_args.py | 'Arguments shared between `snapshot-repo` and `snapshot-repos`.'
from .common import Path, RpmShard
from .storage import Storage
from .db_connection import DBConnectionContext
# BEWARE: If your script calls this helper, it is responsible for supporting
# **all** of its arguments. Just go through the code and make su... | 0.682997 | 0.200734 |
import numpy as np
import imageio
# For image operation
from library.image_tool_box import *
# For math/statistic operation
from library.math_tool_box import StatMaker
import math
### 1. Downlaod and unpack those 4 test data from MNIST database.
# train-images-idx3-ubyte.gz: training set images (9912422 bytes... | mAiLab003.py | import numpy as np
import imageio
# For image operation
from library.image_tool_box import *
# For math/statistic operation
from library.math_tool_box import StatMaker
import math
### 1. Downlaod and unpack those 4 test data from MNIST database.
# train-images-idx3-ubyte.gz: training set images (9912422 bytes... | 0.385375 | 0.427935 |
import functools
from io import StringIO
import json
import pickle
import sys
from dysart.feature import exposed, CallRecord
from dysart.records import RequestRecord
import dysart.messages.messages as messages
from dysart.messages.errors import *
import dysart.project as project
import dysart.services.service as servi... | dysart/services/dyserver.py | import functools
from io import StringIO
import json
import pickle
import sys
from dysart.feature import exposed, CallRecord
from dysart.records import RequestRecord
import dysart.messages.messages as messages
from dysart.messages.errors import *
import dysart.project as project
import dysart.services.service as servi... | 0.354433 | 0.09426 |
import os
from setuptools import setup
from setuptools.command.sdist import sdist
from setuptools.command.develop import develop
from distutils.command.build import build
from distutils import log
from subprocess import call
SETUP_PATH = os.path.dirname(os.path.abspath(__file__))
DRAFTER_PATH = os.path.join(SETUP_PATH... | setup.py | import os
from setuptools import setup
from setuptools.command.sdist import sdist
from setuptools.command.develop import develop
from distutils.command.build import build
from distutils import log
from subprocess import call
SETUP_PATH = os.path.dirname(os.path.abspath(__file__))
DRAFTER_PATH = os.path.join(SETUP_PATH... | 0.4206 | 0.10961 |
import numpy as np
def l96StepRK2(u,Sim):
utmp = u.copy()
source = u[Sim['im'],:] * (u[Sim['ip'],:] - u[Sim['im2'],:]) + Sim['R'] - u
k1 = utmp + Sim['Timestep'] * 0.5 * source
source = k1[Sim['im'],:] * (k1[Sim['ip'],:] - k1[Sim['im2'],:]) + Sim['R'] - k1
u = utmp + Sim['Timestep'] * sourc... | Generative/MAKEDATA/util/integrator.py | import numpy as np
def l96StepRK2(u,Sim):
utmp = u.copy()
source = u[Sim['im'],:] * (u[Sim['ip'],:] - u[Sim['im2'],:]) + Sim['R'] - u
k1 = utmp + Sim['Timestep'] * 0.5 * source
source = k1[Sim['im'],:] * (k1[Sim['ip'],:] - k1[Sim['im2'],:]) + Sim['R'] - k1
u = utmp + Sim['Timestep'] * sourc... | 0.118423 | 0.281072 |
import random
import statistics
import time
import sys
from bisect import bisect_left
from math import exp
class Chromosome:
def __init__(self, genes, fitness):
self.Genes = genes
self.Fitness = fitness
self.Age = 0
class Benchmark:
@staticmethod
def run(function):
... | Chapter-11/genetic.py | import random
import statistics
import time
import sys
from bisect import bisect_left
from math import exp
class Chromosome:
def __init__(self, genes, fitness):
self.Genes = genes
self.Fitness = fitness
self.Age = 0
class Benchmark:
@staticmethod
def run(function):
... | 0.380183 | 0.387111 |
from __future__ import absolute_import, print_function, unicode_literals
from decimal import Decimal
def quote(msg):
"""
Similar to urllib.quote but for glibs GMarkup
@param msg: string to quote
@returns: quoted string
"""
msg = msg.replace('&', '&')
msg = msg.repla... | dist-packages/xdiagnose/utils/text.py | from __future__ import absolute_import, print_function, unicode_literals
from decimal import Decimal
def quote(msg):
"""
Similar to urllib.quote but for glibs GMarkup
@param msg: string to quote
@returns: quoted string
"""
msg = msg.replace('&', '&')
msg = msg.repla... | 0.434221 | 0.279736 |
def create_affiliation_model_temp(average_node_degree,
lambda_block_parameter,
dispersion_parameter_vect,
class_size_vect):
# total number of nodes
N = np.sum(class_size_vect)
### BLOCK STRUCTURE
## def... | code/functions/create_affiliation_model_temp.py | def create_affiliation_model_temp(average_node_degree,
lambda_block_parameter,
dispersion_parameter_vect,
class_size_vect):
# total number of nodes
N = np.sum(class_size_vect)
### BLOCK STRUCTURE
## def... | 0.197832 | 0.362828 |
table_3_1 = {
'0':'Latitude/Longitude (See Template 3.0) Also called Equidistant Cylindrical or Plate Caree',
'1':'Rotated Latitude/Longitude (See Template 3.1)',
'2':'Stretched Latitude/Longitude (See Template 3.2)',
'3':'Rotated and Stretched Latitude/Longitude (See Template 3.3)',
'4':'Variable Resolution Latitude/l... | grib2io/tables/section3.py | table_3_1 = {
'0':'Latitude/Longitude (See Template 3.0) Also called Equidistant Cylindrical or Plate Caree',
'1':'Rotated Latitude/Longitude (See Template 3.1)',
'2':'Stretched Latitude/Longitude (See Template 3.2)',
'3':'Rotated and Stretched Latitude/Longitude (See Template 3.3)',
'4':'Variable Resolution Latitude/l... | 0.689933 | 0.468851 |
from datetime import datetime, timedelta
import docker
import logging
import os
import signal
import subprocess
import time
HOST_PORT = '5000/tcp'
class ContainerMonitor(object):
"""
Monitors volume mount/unmount events and creates notifiers for mounts matching patterns (vsync.enable=true).
"""
def _... | vsync/container_monitor.py | from datetime import datetime, timedelta
import docker
import logging
import os
import signal
import subprocess
import time
HOST_PORT = '5000/tcp'
class ContainerMonitor(object):
"""
Monitors volume mount/unmount events and creates notifiers for mounts matching patterns (vsync.enable=true).
"""
def _... | 0.363534 | 0.090937 |
from typing import Dict, List, Optional
from overrides import overrides
from allennlp.training.metrics.metric import Metric
from allennlp_semparse.domain_languages.domain_language import ExecutionError
from .nla_language import NlaLanguage
@Metric.register("nla_metric")
class NlaMetric(Metric):
"""
Metric f... | nla_semparse/nla_semparse/nla_metric.py | from typing import Dict, List, Optional
from overrides import overrides
from allennlp.training.metrics.metric import Metric
from allennlp_semparse.domain_languages.domain_language import ExecutionError
from .nla_language import NlaLanguage
@Metric.register("nla_metric")
class NlaMetric(Metric):
"""
Metric f... | 0.925129 | 0.352592 |
from isfdb import *
from isfdblib import *
from library import *
from SQLparsing import *
from viewers import DisplayNewLanguage
class Language():
def __init__(self):
self.name = ''
self.code = ''
self.latin = ''
def cgi2obj(self):
self.form = cgi.F... | edit/submit_new_language.py |
from isfdb import *
from isfdblib import *
from library import *
from SQLparsing import *
from viewers import DisplayNewLanguage
class Language():
def __init__(self):
self.name = ''
self.code = ''
self.latin = ''
def cgi2obj(self):
self.form = cgi.F... | 0.255622 | 0.070624 |
import tensorflow as tf
import crop_pad
import os
FLAGS = tf.app.flags.FLAGS
def decode_jpeg(image_buffer, channels, scope=None):
"""Decode a JPEG string into one 3-D float image Tensor.
Args:
image_buffer: scalar string Tensor.
scope: Optional scope for name_scope.
Returns:
3-D floa... | ssd_lite/input.py | import tensorflow as tf
import crop_pad
import os
FLAGS = tf.app.flags.FLAGS
def decode_jpeg(image_buffer, channels, scope=None):
"""Decode a JPEG string into one 3-D float image Tensor.
Args:
image_buffer: scalar string Tensor.
scope: Optional scope for name_scope.
Returns:
3-D floa... | 0.893158 | 0.319015 |
from rx.core import ObservableBase, ObserverBase
from rx.concurrency import current_thread_scheduler
from rx.disposables import CompositeDisposable
class WindowedObserver(ObserverBase):
def __init__(self, observer, observable, cancel, scheduler):
self.observer = observer
self.observable = observab... | rx/backpressure/windowedobservable.py | from rx.core import ObservableBase, ObserverBase
from rx.concurrency import current_thread_scheduler
from rx.disposables import CompositeDisposable
class WindowedObserver(ObserverBase):
def __init__(self, observer, observable, cancel, scheduler):
self.observer = observer
self.observable = observab... | 0.870817 | 0.117927 |
from django.db import models
import os
import uuid
class Mesh(models.Model):
class Meta:
verbose_name = "mesh"
verbose_name_plural = "meshes"
def get_upload_place(instance, filename):
filename, fileExtension = os.path.splitext(filename)
randomID = uuid.uuid4()
return 'gfx/static/gfx/mesh/' + random... | gfx/models.py | from django.db import models
import os
import uuid
class Mesh(models.Model):
class Meta:
verbose_name = "mesh"
verbose_name_plural = "meshes"
def get_upload_place(instance, filename):
filename, fileExtension = os.path.splitext(filename)
randomID = uuid.uuid4()
return 'gfx/static/gfx/mesh/' + random... | 0.248261 | 0.13288 |
import wandb
import time
from copy import deepcopy
from tqdm import tqdm
from torch.utils.data import DataLoader
from fedhf.model import build_criterion, build_optimizer
from .base_trainer import BaseTrainer
class Trainer(BaseTrainer):
def __init__(self, args) -> None:
super(Trainer, self).__init__(args... | fedhf/component/trainer/trainer.py |
import wandb
import time
from copy import deepcopy
from tqdm import tqdm
from torch.utils.data import DataLoader
from fedhf.model import build_criterion, build_optimizer
from .base_trainer import BaseTrainer
class Trainer(BaseTrainer):
def __init__(self, args) -> None:
super(Trainer, self).__init__(args... | 0.69233 | 0.201322 |
from csv import DictWriter
from datetime import datetime, timedelta
import logging
from pathlib import Path
import shutil
from typing import List, Optional, Tuple, Type
from ..graph import AS, BGPDAG
# Can't import into class due to mypy issue:
# https://github.com/python/mypy/issues/7045
# File funcs
from .file_rea... | lib_caida_collector/caida_collector/caida_collector.py | from csv import DictWriter
from datetime import datetime, timedelta
import logging
from pathlib import Path
import shutil
from typing import List, Optional, Tuple, Type
from ..graph import AS, BGPDAG
# Can't import into class due to mypy issue:
# https://github.com/python/mypy/issues/7045
# File funcs
from .file_rea... | 0.749729 | 0.124852 |
import os
import numpy as np
from scipy.ndimage import gaussian_filter
from ..field import Field, Rock, States, Wells
from .utils import get_config, STATES_KEYWORD
def _apply_uncorrelated_noise(arr, std):
noise = np.random.randn(*arr.shape) * std
return arr + noise
def _apply_correlated_noise(arr, std, fr... | deepfield/datasets/randomize.py | import os
import numpy as np
from scipy.ndimage import gaussian_filter
from ..field import Field, Rock, States, Wells
from .utils import get_config, STATES_KEYWORD
def _apply_uncorrelated_noise(arr, std):
noise = np.random.randn(*arr.shape) * std
return arr + noise
def _apply_correlated_noise(arr, std, fr... | 0.76074 | 0.255994 |
import pytest
pytestmark = pytest.mark.django_db
@pytest.fixture
def generate_dependency_usages(dependency_usage_factory):
dependency_usage_factory(
id=1,
dependency__id=34,
dependency__name="graphql",
dependency__type="Python Library",
major_version=3,
minor_versi... | test/api/query/test_dependencies.py | import pytest
pytestmark = pytest.mark.django_db
@pytest.fixture
def generate_dependency_usages(dependency_usage_factory):
dependency_usage_factory(
id=1,
dependency__id=34,
dependency__name="graphql",
dependency__type="Python Library",
major_version=3,
minor_versi... | 0.346984 | 0.264732 |
from sklearn.model_selection import train_test_split
from app.preprocess import create_preprocessor
import numpy as np
from app.model.nmt import create_nmt_model
def run(input_series,
output_series,
max_input_length=118,
max_output_length=28,
number_of_words=10000,
epochs=3,
test_size=.05,
validation_... | app/train.py | from sklearn.model_selection import train_test_split
from app.preprocess import create_preprocessor
import numpy as np
from app.model.nmt import create_nmt_model
def run(input_series,
output_series,
max_input_length=118,
max_output_length=28,
number_of_words=10000,
epochs=3,
test_size=.05,
validation_... | 0.558568 | 0.316898 |
import csv
from django.db.models import Count
from django.http import HttpResponse
from django.shortcuts import render, redirect
from main.forms import GetDateForm, PurchasesForm
from main.models import Purchases, Promo
def index(request):
"""Главная страница"""
return render(request, 'index.html')
def cr... | billing/main/views.py | import csv
from django.db.models import Count
from django.http import HttpResponse
from django.shortcuts import render, redirect
from main.forms import GetDateForm, PurchasesForm
from main.models import Purchases, Promo
def index(request):
"""Главная страница"""
return render(request, 'index.html')
def cr... | 0.268366 | 0.075244 |
input_parameters = []
list_notebooks = []
notes_to_print = []
"""
input_parameters
Contains the number of pages for a book, the number of pages in a notebook, and a Boolean True or False for
separation of functionality.
list_notebooks
List of book pages distributed on a notebook
notes_to_print
List of not... | print_queue.py | input_parameters = []
list_notebooks = []
notes_to_print = []
"""
input_parameters
Contains the number of pages for a book, the number of pages in a notebook, and a Boolean True or False for
separation of functionality.
list_notebooks
List of book pages distributed on a notebook
notes_to_print
List of not... | 0.334263 | 0.470858 |
import scipy.integrate as integrate
from numpy import sqrt, sin, cos, pi
from pylab import *
from mpl_toolkits.axes_grid1 import make_axes_locatable
import numpy as np
from scipy import interpolate
from scipy.integrate import simps
def load_var(dir, t, var, nx, ny, nz, xx, yy):
x, y, n, dataRaw = np.loadtxt(dir + ... | python/shear_stress_enthalpy_norm.py | import scipy.integrate as integrate
from numpy import sqrt, sin, cos, pi
from pylab import *
from mpl_toolkits.axes_grid1 import make_axes_locatable
import numpy as np
from scipy import interpolate
from scipy.integrate import simps
def load_var(dir, t, var, nx, ny, nz, xx, yy):
x, y, n, dataRaw = np.loadtxt(dir + ... | 0.373076 | 0.388444 |
import requests
import json
import re
import hashlib
from django.conf import settings
MAILCHIMP_API_KEY = getattr(settings, 'MAILCHIMP_API_KEY', None)
if MAILCHIMP_API_KEY is None:
raise NotImplementedError("MAILCHIMP_API_KEY must be set in the settings")
MAILCHIMP_DATA_CENTER = getattr(settings, 'MAILCHIMP_DAT... | src/marketing/utils.py | import requests
import json
import re
import hashlib
from django.conf import settings
MAILCHIMP_API_KEY = getattr(settings, 'MAILCHIMP_API_KEY', None)
if MAILCHIMP_API_KEY is None:
raise NotImplementedError("MAILCHIMP_API_KEY must be set in the settings")
MAILCHIMP_DATA_CENTER = getattr(settings, 'MAILCHIMP_DAT... | 0.435902 | 0.056288 |
import pytest
from ..replacement import ReplacementGroup
from ..span import SpanGroup
from ..label_propagation import (
propagate_by_replacement_group,
reduce_by_span_group,
expand_by_span_group,
)
test_cases = [
pytest.param(
[1, 1, 1, 0, 0, 3, 0, 2, 2],
ReplacementGroup.add_all([(0,... | uttut/pipeline/edit/tests/test_label_propagation.py | import pytest
from ..replacement import ReplacementGroup
from ..span import SpanGroup
from ..label_propagation import (
propagate_by_replacement_group,
reduce_by_span_group,
expand_by_span_group,
)
test_cases = [
pytest.param(
[1, 1, 1, 0, 0, 3, 0, 2, 2],
ReplacementGroup.add_all([(0,... | 0.603581 | 0.575648 |
from PyQt5.QtWidgets import QMainWindow, QApplication, QTextEdit, QStyleFactory, QHBoxLayout, QDockWidget, QWidget, \
QListWidget, QVBoxLayout, QAction
from PyQt5.QtGui import QPalette, QColor
from PyQt5.QtCore import Qt
import sys
from tab_widget import TabWidget
from toolbox import ToolBox
from status_bar import... | src/main.py | from PyQt5.QtWidgets import QMainWindow, QApplication, QTextEdit, QStyleFactory, QHBoxLayout, QDockWidget, QWidget, \
QListWidget, QVBoxLayout, QAction
from PyQt5.QtGui import QPalette, QColor
from PyQt5.QtCore import Qt
import sys
from tab_widget import TabWidget
from toolbox import ToolBox
from status_bar import... | 0.417034 | 0.077274 |
from data import word_frequencies
from data.graph import bloom_node, ngram, regex, walk
from spec.mamba import *
comparison = perf.Perf('trie v regex', ['trie', 'regex'])
def get_words(
length_mask: int = None,
file: str = 'data/g1m_1gram.txt',
multi: bool = False) -> list:
def _check(word: str) -> bo... | spec/data/graph/walk_e2e_spec.py | from data import word_frequencies
from data.graph import bloom_node, ngram, regex, walk
from spec.mamba import *
comparison = perf.Perf('trie v regex', ['trie', 'regex'])
def get_words(
length_mask: int = None,
file: str = 'data/g1m_1gram.txt',
multi: bool = False) -> list:
def _check(word: str) -> bo... | 0.560974 | 0.565659 |
import csv
# Loading a specific file and output file
file_load = "election_data.csv"
file_output = "PyPoll.txt"
# Candidate votes and options
candidate_votes = {}
candidate_options = []
# Vote counter (total)
total_votes = 0
# Winning count and winning candidate
winning_count = 0
winning_candidate = ""
# Read th... | Resources/py_poll.py | import csv
# Loading a specific file and output file
file_load = "election_data.csv"
file_output = "PyPoll.txt"
# Candidate votes and options
candidate_votes = {}
candidate_options = []
# Vote counter (total)
total_votes = 0
# Winning count and winning candidate
winning_count = 0
winning_candidate = ""
# Read th... | 0.400515 | 0.227716 |
from .context import ztom as zt
import unittest
from unittest.mock import MagicMock
class RecoveryOrderManagerTestSuite(unittest.TestCase):
def test_owa_manager_create(self):
ex = zt.ccxtExchangeWrapper.load_from_id("binance")
order = zt.RecoveryOrder("ETH/BTC", "ETH", 1, "BTC", 0.1)
om =... | tests/test_order_manager_recovery.py | from .context import ztom as zt
import unittest
from unittest.mock import MagicMock
class RecoveryOrderManagerTestSuite(unittest.TestCase):
def test_owa_manager_create(self):
ex = zt.ccxtExchangeWrapper.load_from_id("binance")
order = zt.RecoveryOrder("ETH/BTC", "ETH", 1, "BTC", 0.1)
om =... | 0.679498 | 0.510496 |
from io import StringIO
import re
from unittest.mock import patch
from carebt.behaviorTreeRunner import BehaviorTreeRunner
from carebt.examples.simple_sequence import CreateRandomNumberAction
from carebt.examples.simple_sequence import PrintNumberAction
from carebt.examples.simple_sequence import SimpleSequence1
from... | tests/examples/test_simple_sequence.py |
from io import StringIO
import re
from unittest.mock import patch
from carebt.behaviorTreeRunner import BehaviorTreeRunner
from carebt.examples.simple_sequence import CreateRandomNumberAction
from carebt.examples.simple_sequence import PrintNumberAction
from carebt.examples.simple_sequence import SimpleSequence1
from... | 0.501953 | 0.44571 |
import logging
import os
import shutil
import time
import json
import random
import linecache
import gc
import numpy as np
import torch
from src.bayesian_summarization.bayesian import BayesianSummarizer
from src.common.loaders import load_model, create_loader
from src.bayesian_summarization.bleu import analyze_gener... | src/active_summarization/active_sum.py | import logging
import os
import shutil
import time
import json
import random
import linecache
import gc
import numpy as np
import torch
from src.bayesian_summarization.bayesian import BayesianSummarizer
from src.common.loaders import load_model, create_loader
from src.bayesian_summarization.bleu import analyze_gener... | 0.696991 | 0.198958 |
import shutil
from tokenizers.normalizers import NFKC
from autonmt.preprocessing import tokenizers
from autonmt.bundle import utils
from autonmt.bundle.utils import *
def normalize_file(input_file, output_file, normalizer, force_overwrite, limit=None):
if force_overwrite or not os.path.exists(output_file):
... | autonmt/preprocessing/processors.py | import shutil
from tokenizers.normalizers import NFKC
from autonmt.preprocessing import tokenizers
from autonmt.bundle import utils
from autonmt.bundle.utils import *
def normalize_file(input_file, output_file, normalizer, force_overwrite, limit=None):
if force_overwrite or not os.path.exists(output_file):
... | 0.42179 | 0.273071 |
from email.message import EmailMessage
import logging
from mailbox import MH
from operator import itemgetter
from pathlib import Path
from typing import List, Union
from mailbits import email2dict
import pytest
from outgoing import Sender, from_dict
from outgoing.senders.mailboxes import MHSender
@pytest.mark.paramet... | test/test_senders/test_mh.py | from email.message import EmailMessage
import logging
from mailbox import MH
from operator import itemgetter
from pathlib import Path
from typing import List, Union
from mailbits import email2dict
import pytest
from outgoing import Sender, from_dict
from outgoing.senders.mailboxes import MHSender
@pytest.mark.paramet... | 0.517327 | 0.307196 |
# Python modules
import logging
import inspect
import threading
import os
# NOC modules
from noc.config import config
from noc.core.log import PrefixLoggerAdapter
logger = logging.getLogger(__name__)
class BaseLoader(object):
name = None
base_cls = None # Base class to be loaded
base_path = None # Tu... | core/loader/base.py |
# Python modules
import logging
import inspect
import threading
import os
# NOC modules
from noc.config import config
from noc.core.log import PrefixLoggerAdapter
logger = logging.getLogger(__name__)
class BaseLoader(object):
name = None
base_cls = None # Base class to be loaded
base_path = None # Tu... | 0.511229 | 0.079139 |
STRM_DATA_BITS = 8
MEM_DATA_BITS = 64
RATIO = MEM_DATA_BITS / STRM_DATA_BITS
fp_cfg = open("cfg.dat", "w")
# all sizes in WORDS
lengths = [600, 101, 300, 407, 61, 222] # keep even number of frames
bursts = [16, 11, 1, 9, 4, 5]
DMA_WR_BASE = (0)
DMA_RD_BASE = (1 << 31)
START_ADDR = 0
LEN_ADDR... | wavetrace/verilog/lib/axi/sim/dma_2chan_wrap_tb_loop.py | STRM_DATA_BITS = 8
MEM_DATA_BITS = 64
RATIO = MEM_DATA_BITS / STRM_DATA_BITS
fp_cfg = open("cfg.dat", "w")
# all sizes in WORDS
lengths = [600, 101, 300, 407, 61, 222] # keep even number of frames
bursts = [16, 11, 1, 9, 4, 5]
DMA_WR_BASE = (0)
DMA_RD_BASE = (1 << 31)
START_ADDR = 0
LEN_ADDR... | 0.101012 | 0.142381 |
import argparse
import os.path
import pathlib
import json
import requests
from folioclient.FolioClient import FolioClient
class Backup:
def __init__(self, folioclient, path):
self.folioclient = folioclient
self.path = path
print('initializing Backup')
def load_schema(self, schema_loca... | erm_backup_and_restore.py | import argparse
import os.path
import pathlib
import json
import requests
from folioclient.FolioClient import FolioClient
class Backup:
def __init__(self, folioclient, path):
self.folioclient = folioclient
self.path = path
print('initializing Backup')
def load_schema(self, schema_loca... | 0.271348 | 0.115287 |
import asyncio
import datetime
import logging
import traceback
import discord
from discord.ext import commands
from donphan import create_pool, create_tables, create_views
import bot.config as config
import bot.timers as timers
from bot.config import config as BOT_CONFIG
try:
import uvloop
except ImportError:
... | bot/__main__.py | import asyncio
import datetime
import logging
import traceback
import discord
from discord.ext import commands
from donphan import create_pool, create_tables, create_views
import bot.config as config
import bot.timers as timers
from bot.config import config as BOT_CONFIG
try:
import uvloop
except ImportError:
... | 0.377655 | 0.149562 |
import sqlite3
con = sqlite3.connect('census.db')
cur = con.cursor()
cur.execute('DROP TABLE IF EXISTS Density')
cur.execute('CREATE TABLE Density(Name TEXT, Population INTEGER, Area REAL)')
data = [
('Newfoundland and Labrador', 512930, 370501.69),
('Prince Edward Island', 135294, 5684.39),
('Nova Scot... | chapter-17/exercise01.py | import sqlite3
con = sqlite3.connect('census.db')
cur = con.cursor()
cur.execute('DROP TABLE IF EXISTS Density')
cur.execute('CREATE TABLE Density(Name TEXT, Population INTEGER, Area REAL)')
data = [
('Newfoundland and Labrador', 512930, 370501.69),
('Prince Edward Island', 135294, 5684.39),
('Nova Scot... | 0.339499 | 0.255553 |
from django.core.management.base import BaseCommand
from mama_cas.services import get_backend_path
from mama_cas.services import get_callbacks
from mama_cas.services import get_logout_url
from mama_cas.services import logout_allowed
from mama_cas.services import proxy_allowed
from mama_cas.services import proxy_callba... | mama_cas/management/commands/checkservice.py | from django.core.management.base import BaseCommand
from mama_cas.services import get_backend_path
from mama_cas.services import get_callbacks
from mama_cas.services import get_logout_url
from mama_cas.services import logout_allowed
from mama_cas.services import proxy_allowed
from mama_cas.services import proxy_callba... | 0.461017 | 0.059949 |
from simulation.visualization import Visualizer
import game_events.game_events as events
class TextualVisualizer(Visualizer):
def __init__(self):
pass
def visualize(self, event, params):
if isinstance(event, events.AbilityCastStarted):
self.visualize_ability_cast_started(params)
... | game_visualizers/textual_visualizer.py | from simulation.visualization import Visualizer
import game_events.game_events as events
class TextualVisualizer(Visualizer):
def __init__(self):
pass
def visualize(self, event, params):
if isinstance(event, events.AbilityCastStarted):
self.visualize_ability_cast_started(params)
... | 0.587233 | 0.232408 |
import logging.config
logging.config.fileConfig('logging.conf')
logger = logging.getLogger('runner')
from db import ExperimentsOverview
import pdfkit
from lxml import etree
from StringIO import *
from db.Devices import Devices
import ConfigParser
# initialize configuration parser
config = ConfigParser.RawConfigParse... | helper/experiment_export_overview.py |
import logging.config
logging.config.fileConfig('logging.conf')
logger = logging.getLogger('runner')
from db import ExperimentsOverview
import pdfkit
from lxml import etree
from StringIO import *
from db.Devices import Devices
import ConfigParser
# initialize configuration parser
config = ConfigParser.RawConfigParse... | 0.202838 | 0.069384 |
from datetime import timedelta
from string import Template
from django.utils import timezone
from graphql_relay.node.node import to_global_id
from open_city_profile.consts import TOKEN_EXPIRED_ERROR
from open_city_profile.tests.asserts import assert_match_error_code
from .factories import ClaimTokenFactory, ProfileF... | profiles/tests/test_gql_claimable_profile_query.py | from datetime import timedelta
from string import Template
from django.utils import timezone
from graphql_relay.node.node import to_global_id
from open_city_profile.consts import TOKEN_EXPIRED_ERROR
from open_city_profile.tests.asserts import assert_match_error_code
from .factories import ClaimTokenFactory, ProfileF... | 0.688049 | 0.252283 |
from aiida.orm.data.structure import StructureData
from aiida.orm.data.parameter import ParameterData
from aiida.orm.data.base import Int, Float, Str, Bool
from aiida.orm.data.singlefile import SinglefileData
from aiida.orm.code import Code
from aiida.work.workchain import WorkChain, ToContext, Calc, while_
from aiida... | slab/slabwork.py | from aiida.orm.data.structure import StructureData
from aiida.orm.data.parameter import ParameterData
from aiida.orm.data.base import Int, Float, Str, Bool
from aiida.orm.data.singlefile import SinglefileData
from aiida.orm.code import Code
from aiida.work.workchain import WorkChain, ToContext, Calc, while_
from aiida... | 0.461259 | 0.220384 |
from django.core.urlresolvers import reverse
from django.core.urlresolvers import reverse_lazy
from django.utils.translation import ugettext_lazy as _
import horizon.exceptions
import horizon.tables
import horizon.tabs
from horizon.utils import memoized
import horizon.workflows
from tuskar_ui import api
from tuskar_u... | tuskar_ui/infrastructure/flavors/views.py |
from django.core.urlresolvers import reverse
from django.core.urlresolvers import reverse_lazy
from django.utils.translation import ugettext_lazy as _
import horizon.exceptions
import horizon.tables
import horizon.tabs
from horizon.utils import memoized
import horizon.workflows
from tuskar_ui import api
from tuskar_u... | 0.54359 | 0.117775 |
from os.path import join
from re import compile
POSVELRE = compile(r"position=<\s*([-\d]+),\s*([-\d]+)> velocity=<\s*([-\d]+),\s*([-\d]+)>")
def move2(workposv, velv):
numpos = len(workposv)
seconds = 0
minx = int(min([pos.real for pos in workposv]))
maxx = int(max([pos.real for pos in workposv]))... | 2018/day10/solution.py |
from os.path import join
from re import compile
POSVELRE = compile(r"position=<\s*([-\d]+),\s*([-\d]+)> velocity=<\s*([-\d]+),\s*([-\d]+)>")
def move2(workposv, velv):
numpos = len(workposv)
seconds = 0
minx = int(min([pos.real for pos in workposv]))
maxx = int(max([pos.real for pos in workposv]))... | 0.184988 | 0.385722 |
from django.conf import settings
from django.db import migrations, models
import django.db.models.deletion
import uuid
class Migration(migrations.Migration):
initial = True
dependencies = [
('core_ecommerce', '0001_initial'),
migrations.swappable_dependency(settings.AUTH_USER_MODEL),
]
... | vendors/migrations/0001_initial.py |
from django.conf import settings
from django.db import migrations, models
import django.db.models.deletion
import uuid
class Migration(migrations.Migration):
initial = True
dependencies = [
('core_ecommerce', '0001_initial'),
migrations.swappable_dependency(settings.AUTH_USER_MODEL),
]
... | 0.513181 | 0.171304 |
import io
import logging as log
import sys
import textwrap
import warnings
from typing import Optional, Set, TextIO
from .field import Field
from .ip_block import IpBlock
from .params import LocalParam
from .register import Register
from .multi_register import MultiRegister
from .signal import Signal
from .window imp... | util/reggen/gen_rust.py | import io
import logging as log
import sys
import textwrap
import warnings
from typing import Optional, Set, TextIO
from .field import Field
from .ip_block import IpBlock
from .params import LocalParam
from .register import Register
from .multi_register import MultiRegister
from .signal import Signal
from .window imp... | 0.530966 | 0.205575 |
from abc import ABC, abstractmethod
from itertools import chain, product
from collections import deque
import numpy as np
class SynapsesBuilder(object):
"""
Builder devoted to construct the ANN graph arch. from a config. dict.
"""
def __init__(self, topology):
self.topology = topology... | spike_swarm_sim/neural_networks/utils/builder.py | from abc import ABC, abstractmethod
from itertools import chain, product
from collections import deque
import numpy as np
class SynapsesBuilder(object):
"""
Builder devoted to construct the ANN graph arch. from a config. dict.
"""
def __init__(self, topology):
self.topology = topology... | 0.613815 | 0.108189 |
set_name(0x8007B4A4, "GetTpY__FUs", SN_NOWARN)
set_name(0x8007B4C0, "GetTpX__FUs", SN_NOWARN)
set_name(0x8007B4CC, "Remove96__Fv", SN_NOWARN)
set_name(0x8007B504, "AppMain", SN_NOWARN)
set_name(0x8007B5A4, "MAIN_RestartGameTask__Fv", SN_NOWARN)
set_name(0x8007B5D0, "GameTask__FP4TASK", SN_NOWARN)
set_name(0x8007B6B8, "... | psx/_dump_/23/_dump_ida_/make_psx.py | set_name(0x8007B4A4, "GetTpY__FUs", SN_NOWARN)
set_name(0x8007B4C0, "GetTpX__FUs", SN_NOWARN)
set_name(0x8007B4CC, "Remove96__Fv", SN_NOWARN)
set_name(0x8007B504, "AppMain", SN_NOWARN)
set_name(0x8007B5A4, "MAIN_RestartGameTask__Fv", SN_NOWARN)
set_name(0x8007B5D0, "GameTask__FP4TASK", SN_NOWARN)
set_name(0x8007B6B8, "... | 0.145479 | 0.062303 |
import time
import random
import pickle
import numpy as np
from sklearn.model_selection import RandomizedSearchCV, GridSearchCV
from sklearn.metrics import roc_auc_score
from sklearn.model_selection import StratifiedKFold, train_test_split
from xgboost import XGBClassifier
import xgboost as xgb
from sklearn.metrics imp... | Dinosaur Game/Modeling/xgboost_train.py | import time
import random
import pickle
import numpy as np
from sklearn.model_selection import RandomizedSearchCV, GridSearchCV
from sklearn.metrics import roc_auc_score
from sklearn.model_selection import StratifiedKFold, train_test_split
from xgboost import XGBClassifier
import xgboost as xgb
from sklearn.metrics imp... | 0.640074 | 0.444022 |
import logging
import os
import datakit.utils
from .utils import read_json, write_json
class CommandHelpers:
"""
Mixin class containing common helper methods for Datakit plugins.
Intended to be sub-classed alongside Cliff Command.
:Usage:
* Create a plugin command that subclasses both Command... | datakit/command_helpers.py | import logging
import os
import datakit.utils
from .utils import read_json, write_json
class CommandHelpers:
"""
Mixin class containing common helper methods for Datakit plugins.
Intended to be sub-classed alongside Cliff Command.
:Usage:
* Create a plugin command that subclasses both Command... | 0.591841 | 0.278336 |
import argparse
import socket
import time
import cv2
import numpy as np
def arg_parse():
parser = argparse.ArgumentParser(description='Client')
parser.add_argument('--save', default=False, help='Save video', action='store_true')
parser.add_argument("--ip", help="Client IP address", default="localhost")
... | server.py | import argparse
import socket
import time
import cv2
import numpy as np
def arg_parse():
parser = argparse.ArgumentParser(description='Client')
parser.add_argument('--save', default=False, help='Save video', action='store_true')
parser.add_argument("--ip", help="Client IP address", default="localhost")
... | 0.249539 | 0.096365 |
import logging
import os
import sys
from logging.handlers import RotatingFileHandler
from multiprocessing.pool import ThreadPool as Pool
DEFAULT_FOLDER = None
THEMES = None
TEMP_THEMES = None
FP_HASHES = None
LOG_FILE = None
LOG = logging.getLogger('bw_plex')
INI_FILE = None
DB_PATH = None
CONFIG = None
PMS = None
POO... | bw_plex/__init__.py | import logging
import os
import sys
from logging.handlers import RotatingFileHandler
from multiprocessing.pool import ThreadPool as Pool
DEFAULT_FOLDER = None
THEMES = None
TEMP_THEMES = None
FP_HASHES = None
LOG_FILE = None
LOG = logging.getLogger('bw_plex')
INI_FILE = None
DB_PATH = None
CONFIG = None
PMS = None
POO... | 0.391988 | 0.080683 |
import numpy as np
from pygem import CustomDeformation as OriginalCustomDeformation
from .cad_deformation import CADDeformation
class CustomDeformation(CADDeformation, OriginalCustomDeformation):
"""
Class to perform a custom deformation to the CAD geometries.
:param callable func: the function definying ... | pygem/cad/custom_deformation.py | import numpy as np
from pygem import CustomDeformation as OriginalCustomDeformation
from .cad_deformation import CADDeformation
class CustomDeformation(CADDeformation, OriginalCustomDeformation):
"""
Class to perform a custom deformation to the CAD geometries.
:param callable func: the function definying ... | 0.923691 | 0.78968 |
from germanium.static import *
from germanium.locators import StaticElementLocator
from behave import *
from features.steps.asserts import *
use_step_matcher("re")
@step(u'I search using S for (?P<locator>.*)')
def step_impl(context, locator):
print("Search for locator: %s" % locator)
S(locator).exists()
... | features/steps/germanium_S.py | from germanium.static import *
from germanium.locators import StaticElementLocator
from behave import *
from features.steps.asserts import *
use_step_matcher("re")
@step(u'I search using S for (?P<locator>.*)')
def step_impl(context, locator):
print("Search for locator: %s" % locator)
S(locator).exists()
... | 0.592077 | 0.345864 |
from jacdac.bus import Bus, SensorClient
from .constants import *
from typing import Optional
class WeightScaleClient(SensorClient):
"""
A weight measuring sensor.
Implements a client for the `Weight Scale <https://microsoft.github.io/jacdac-docs/services/weightscale>`_ service.
"""
def __init__... | jacdac/weight_scale/client.py | from jacdac.bus import Bus, SensorClient
from .constants import *
from typing import Optional
class WeightScaleClient(SensorClient):
"""
A weight measuring sensor.
Implements a client for the `Weight Scale <https://microsoft.github.io/jacdac-docs/services/weightscale>`_ service.
"""
def __init__... | 0.919086 | 0.3617 |
import os
import os.path
import time
import numpy as np
import PIL.Image
import scipy.misc
import caffe
import pandas as pd
from google.protobuf import text_format
from caffe.proto import caffe_pb2
def get_net(caffemodel, deploy_file, use_gpu=True):
"""
Returns an instance of caffe.Net
Arguments:
caf... | tools/pre_separation.py | import os
import os.path
import time
import numpy as np
import PIL.Image
import scipy.misc
import caffe
import pandas as pd
from google.protobuf import text_format
from caffe.proto import caffe_pb2
def get_net(caffemodel, deploy_file, use_gpu=True):
"""
Returns an instance of caffe.Net
Arguments:
caf... | 0.702326 | 0.409191 |
import datetime
from django.test import TestCase
from django.utils import timezone
from model_bakery import baker
from channels.models import Category, Channel, Video
class VideoManagerTestCase(TestCase):
def setUp(self):
self.channel = baker.make(Channel)
def test_last_24h_videos(self):
ju... | mediafeed/channels/tests/test_managers.py | import datetime
from django.test import TestCase
from django.utils import timezone
from model_bakery import baker
from channels.models import Category, Channel, Video
class VideoManagerTestCase(TestCase):
def setUp(self):
self.channel = baker.make(Channel)
def test_last_24h_videos(self):
ju... | 0.562657 | 0.339554 |
import matplotlib.pyplot as plt
import numpy as np
import pandas as pd
import sys, os
file_name_plant = '/home/renato/groimp_efficient/run_1/plant.txt'
file_name_field = '/home/renato/groimp_efficient/run_1/field.txt'
file_name_plant_jules = '/home/renato/groimp_efficient/run_1c/plant_{}.txt'
file_name_field_jules ... | run_1c/plot_beta_var.py | import matplotlib.pyplot as plt
import numpy as np
import pandas as pd
import sys, os
file_name_plant = '/home/renato/groimp_efficient/run_1/plant.txt'
file_name_field = '/home/renato/groimp_efficient/run_1/field.txt'
file_name_plant_jules = '/home/renato/groimp_efficient/run_1c/plant_{}.txt'
file_name_field_jules ... | 0.126704 | 0.239427 |
# If the ~/.m2 directory is not owned current user, the container
# assumption that it can be written won't be met. In that case, the
# directory is not used. That will slow the initial builds on the machine,
# because they will need to populate the .m2 cache instead of using the
# existing cache.
import optparse
i... | docker_run.py |
# If the ~/.m2 directory is not owned current user, the container
# assumption that it can be written won't be met. In that case, the
# directory is not used. That will slow the initial builds on the machine,
# because they will need to populate the .m2 cache instead of using the
# existing cache.
import optparse
i... | 0.303732 | 0.057045 |
import os
import shutil
import time
from config import config
from functions.utlis import printProgressBar, validate_path, Style, print_error, print_success, print_primary
# Initiates file sorting process
def init_f_o(current_dir):
create_folders(current_dir)
def create_folders(current_dir: str):
"""
Cr... | functions/os_functions.py | import os
import shutil
import time
from config import config
from functions.utlis import printProgressBar, validate_path, Style, print_error, print_success, print_primary
# Initiates file sorting process
def init_f_o(current_dir):
create_folders(current_dir)
def create_folders(current_dir: str):
"""
Cr... | 0.208743 | 0.096919 |
import datacube_ows.legend_generator
import pytest
from unittest.mock import patch, MagicMock
import numpy as np
@patch("datacube_ows.legend_generator.make_response")
def test_create_legends_from_styles(make_response):
def fake_img(bytesio):
from PIL import Image
Image.new('RGB', (256, 256)).sa... | tests/test_legend_generator.py | import datacube_ows.legend_generator
import pytest
from unittest.mock import patch, MagicMock
import numpy as np
@patch("datacube_ows.legend_generator.make_response")
def test_create_legends_from_styles(make_response):
def fake_img(bytesio):
from PIL import Image
Image.new('RGB', (256, 256)).sa... | 0.80213 | 0.351339 |
from __future__ import division, print_function
# Import Python Modules
import os
import sys
import argparse
# Import Broadband modules
import PlotMap
import plot_utils
import fault_utils
from install_cfg import InstallCfg
def parse_arguments():
"""
This function takes care of parsing the command-line argume... | bbp/utils/misc/plot_station_map.py | from __future__ import division, print_function
# Import Python Modules
import os
import sys
import argparse
# Import Broadband modules
import PlotMap
import plot_utils
import fault_utils
from install_cfg import InstallCfg
def parse_arguments():
"""
This function takes care of parsing the command-line argume... | 0.565419 | 0.244921 |
from itertools import combinations
from typing import (Callable,
Dict,
Iterable,
Iterator,
List,
Optional,
Tuple,
TypeVar)
from pathlib import Path
from collections import defaul... | lang/Python/anagrams-deranged-anagrams-2.py | from itertools import combinations
from typing import (Callable,
Dict,
Iterable,
Iterator,
List,
Optional,
Tuple,
TypeVar)
from pathlib import Path
from collections import defaul... | 0.774157 | 0.217774 |
import logging
import sys
from . import Session, Course
from . import utils as _utils
__all__ = ['Faculty']
class Faculty:
"""
A class used to represent a faculty of the University of Porto.
Args:
auth (:obj:`json_object`): A JSON object containing the `user` and the `password` authe... | scrapper/sigarra_data_scrapper/faculty.py | import logging
import sys
from . import Session, Course
from . import utils as _utils
__all__ = ['Faculty']
class Faculty:
"""
A class used to represent a faculty of the University of Porto.
Args:
auth (:obj:`json_object`): A JSON object containing the `user` and the `password` authe... | 0.614163 | 0.396769 |
import csv
import dataclasses
import datetime
import logging
import typing
import urllib.parse
from http import cookies
from .exceptions import UnknownHttpType
from .models import (
LoadBalancerErrorReason,
HttpType,
Host,
HttpRequest,
)
logger = logging.getLogger(__name__)
def to_http_type(value):... | aws_log_parser/parser.py | import csv
import dataclasses
import datetime
import logging
import typing
import urllib.parse
from http import cookies
from .exceptions import UnknownHttpType
from .models import (
LoadBalancerErrorReason,
HttpType,
Host,
HttpRequest,
)
logger = logging.getLogger(__name__)
def to_http_type(value):... | 0.520009 | 0.172311 |
import datetime
import logging
from typing import Tuple
from sqlalchemy import func
from sqlalchemy.orm import aliased
from flaskbb.extensions import db_hub
from flaskbb.user.models import User
from hub.features.karma.models import Karma
from hub.models import Player
from hub.utils import get_player_by_discord
logge... | modules/hub/hub/features/karma/karma.py | import datetime
import logging
from typing import Tuple
from sqlalchemy import func
from sqlalchemy.orm import aliased
from flaskbb.extensions import db_hub
from flaskbb.user.models import User
from hub.features.karma.models import Karma
from hub.models import Player
from hub.utils import get_player_by_discord
logge... | 0.610918 | 0.229665 |
import json
from rcvformats.conversions.base import GenericGuessAtTransferConverter
class OpavoteConverter(GenericGuessAtTransferConverter):
"""
Reads an opavote-formatted JSON file.
"""
@classmethod
def _get_eliminated_names(cls, rounds, candidate_names, round_i):
"""
Opavote fo... | rcvformats/conversions/opavote.py | import json
from rcvformats.conversions.base import GenericGuessAtTransferConverter
class OpavoteConverter(GenericGuessAtTransferConverter):
"""
Reads an opavote-formatted JSON file.
"""
@classmethod
def _get_eliminated_names(cls, rounds, candidate_names, round_i):
"""
Opavote fo... | 0.546254 | 0.366136 |
from base64 import b64decode, b64encode
import gevent
import gevent.event
import json
from PIL import Image, ImageDraw
import StringIO
import zlib
import logging
from ajenti.api import *
from ajenti.api.http import HttpPlugin, url, SocketPlugin
from ajenti.plugins.configurator.api import ClassConfigEditor
from ajenti.... | usr/share/pyshared/ajenti/plugins/terminal/main.py | from base64 import b64decode, b64encode
import gevent
import gevent.event
import json
from PIL import Image, ImageDraw
import StringIO
import zlib
import logging
from ajenti.api import *
from ajenti.api.http import HttpPlugin, url, SocketPlugin
from ajenti.plugins.configurator.api import ClassConfigEditor
from ajenti.... | 0.303938 | 0.071656 |
from pyparsing import (Forward, Word, alphas, alphanums, Literal,
Optional, ZeroOrMore, Group)
from node import Node
class NodeParser:
'''Class implementing tree structured data parser, data is of the form
(c1 ((c2) (c3 ((c4) (c5))) (c6)))'''
def __init__(self):
'''Cons... | Python/PyParsing/node_parser.py |
from pyparsing import (Forward, Word, alphas, alphanums, Literal,
Optional, ZeroOrMore, Group)
from node import Node
class NodeParser:
'''Class implementing tree structured data parser, data is of the form
(c1 ((c2) (c3 ((c4) (c5))) (c6)))'''
def __init__(self):
'''Cons... | 0.717705 | 0.32787 |
import os
import datetime
from PIL import Image as PILImage
import numpy as np
from traits.api import (
Array, Date, File, Float, HasTraits, Str, Tuple, observe
)
class Image(HasTraits):
""" An SEM image stored in a file. """
filename = File(exists=True)
sample_id = Str()
operator = Str("N/A")
... | venv/Lib/site-packages/traits/examples/introduction/3_observation.py | import os
import datetime
from PIL import Image as PILImage
import numpy as np
from traits.api import (
Array, Date, File, Float, HasTraits, Str, Tuple, observe
)
class Image(HasTraits):
""" An SEM image stored in a file. """
filename = File(exists=True)
sample_id = Str()
operator = Str("N/A")
... | 0.520496 | 0.199289 |
import math
import os
from time import time
from algorithms import get_cost
INF = float('inf')
COST_SCALE = 1
MAX_COST = (2**31 - 1) / 100
def read(filename):
with open(filename, 'r') as f:
return f.read()
def write(filename, string):
with open(filename, 'w') as f:
f.write(string)
def r... | fts/downward.py | import math
import os
from time import time
from algorithms import get_cost
INF = float('inf')
COST_SCALE = 1
MAX_COST = (2**31 - 1) / 100
def read(filename):
with open(filename, 'r') as f:
return f.read()
def write(filename, string):
with open(filename, 'w') as f:
f.write(string)
def r... | 0.308503 | 0.150559 |
from django.contrib import admin
from imagekit.admin import AdminThumbnail
from common.admin import AutoUserMixin
from shapes.models import SubmittedShape, \
MaterialShape, ShapeSubstance, ShapeSubstanceLabel, \
ShapeName, MaterialShapeNameLabel, MaterialShapeQuality
from normals.models import ShapeRectifiedN... | server/shapes/admin.py | from django.contrib import admin
from imagekit.admin import AdminThumbnail
from common.admin import AutoUserMixin
from shapes.models import SubmittedShape, \
MaterialShape, ShapeSubstance, ShapeSubstanceLabel, \
ShapeName, MaterialShapeNameLabel, MaterialShapeQuality
from normals.models import ShapeRectifiedN... | 0.536799 | 0.244961 |
import os
from PIL import Image
from PIL import Image, ImageDraw, ImageFont
from pathlib import Path
# Open guest file, get the amount of guests from it
guestFile = open(Path.cwd() / 'guests.txt')
guestList = guestFile.readlines()
guestNum = len(guestList)
# Set parameters and total height dependent on guest number
s... | Chapter-19/Custom Seating Cards.py | import os
from PIL import Image
from PIL import Image, ImageDraw, ImageFont
from pathlib import Path
# Open guest file, get the amount of guests from it
guestFile = open(Path.cwd() / 'guests.txt')
guestList = guestFile.readlines()
guestNum = len(guestList)
# Set parameters and total height dependent on guest number
s... | 0.355439 | 0.232365 |
from django.core.management.base import BaseCommand, CommandError
from apprest.services.experiment import CalipsoExperimentsServices
class Command(BaseCommand):
help = 'Add experiment'
experiments_services = CalipsoExperimentsServices()
def add_arguments(self, parser):
parser.add_argument('--pub... | apprest/management/commands/add_experiment.py | from django.core.management.base import BaseCommand, CommandError
from apprest.services.experiment import CalipsoExperimentsServices
class Command(BaseCommand):
help = 'Add experiment'
experiments_services = CalipsoExperimentsServices()
def add_arguments(self, parser):
parser.add_argument('--pub... | 0.533154 | 0.055875 |
from decimal import Decimal
from django.contrib.auth.models import User, Group
from django.test import TestCase
from product.models import Product, Price
from satchmo_ext.tieredpricing.models import *
from threaded_multihost.threadlocals import set_current_user, set_thread_variable, get_thread_variable
import keyedcach... | satchmo/apps/satchmo_ext/tieredpricing/tests.py | from decimal import Decimal
from django.contrib.auth.models import User, Group
from django.test import TestCase
from product.models import Product, Price
from satchmo_ext.tieredpricing.models import *
from threaded_multihost.threadlocals import set_current_user, set_thread_variable, get_thread_variable
import keyedcach... | 0.577734 | 0.184657 |
from django.test import TestCase
from django.contrib.auth.models import User
from .models import Neighborhood
# Create your tests here.
class NeighborhoodTestClass(TestCase):
def setUp(self):
self.user = User.objects.create_user(username='testuser', password='<PASSWORD>')
self.location = Location(i... | loop/tests.py | from django.test import TestCase
from django.contrib.auth.models import User
from .models import Neighborhood
# Create your tests here.
class NeighborhoodTestClass(TestCase):
def setUp(self):
self.user = User.objects.create_user(username='testuser', password='<PASSWORD>')
self.location = Location(i... | 0.444565 | 0.518059 |
import json
from pygal_maps_world.i18n import COUNTRIES
import pygal
from pygal.style import LightColorizedStyle as LCS, RotateStyle as RS
def get_country_code(country_name):
for code, name in sorted(COUNTRIES.items()):
if name == country_name:
return code
# 筛选出get_country_code不能帅选出的国别... | world_populaiton.py | import json
from pygal_maps_world.i18n import COUNTRIES
import pygal
from pygal.style import LightColorizedStyle as LCS, RotateStyle as RS
def get_country_code(country_name):
for code, name in sorted(COUNTRIES.items()):
if name == country_name:
return code
# 筛选出get_country_code不能帅选出的国别... | 0.271541 | 0.201185 |
import unittest
import numpy as np
from scipy.sparse import csr_matrix
from tick.robust import ModelModifiedHuber
from tick.base_model.tests.generalized_linear_model import TestGLM
from tick.linear_model import SimuLogReg
class Test(TestGLM):
def test_ModelModifiedHuber(self):
"""...Numerical consisten... | tick/robust/tests/modified_huber_test.py |
import unittest
import numpy as np
from scipy.sparse import csr_matrix
from tick.robust import ModelModifiedHuber
from tick.base_model.tests.generalized_linear_model import TestGLM
from tick.linear_model import SimuLogReg
class Test(TestGLM):
def test_ModelModifiedHuber(self):
"""...Numerical consisten... | 0.773986 | 0.613902 |
import discord
from discord.ext import commands
import os, sys, inspect
currentDir = os.path.dirname(os.path.abspath(inspect.getfile(inspect.currentframe())))
parentDir = os.path.dirname(currentDir)
sys.path.insert(0, parentDir)
from project import *
from projectList import ProjectList
from fileio import ... | src/cogs/scrumbotCog.py |
import discord
from discord.ext import commands
import os, sys, inspect
currentDir = os.path.dirname(os.path.abspath(inspect.getfile(inspect.currentframe())))
parentDir = os.path.dirname(currentDir)
sys.path.insert(0, parentDir)
from project import *
from projectList import ProjectList
from fileio import ... | 0.27474 | 0.079639 |
try:
from setuptools import setup, Extension, Command
except ImportError:
from distutils.core import setup, Extension, Command
import arbytmap
long_desc = ""
try:
long_desc = open("README.MD").read()
except Exception:
print("Couldn't read readme.")
setup(
name="arbytmap",
description='A textu... | setup.py | try:
from setuptools import setup, Extension, Command
except ImportError:
from distutils.core import setup, Extension, Command
import arbytmap
long_desc = ""
try:
long_desc = open("README.MD").read()
except Exception:
print("Couldn't read readme.")
setup(
name="arbytmap",
description='A textu... | 0.429429 | 0.199581 |
from argparse import ArgumentParser, RawTextHelpFormatter
from tabulate import tabulate
try:
from falconpy import APIHarness
except ImportError as no_falconpy:
raise SystemExit(
"The CrowdStrike SDK must be installed in order to use this utility.\n"
"Install this application with the command `py... | samples/sensor_download/download_sensor.py | from argparse import ArgumentParser, RawTextHelpFormatter
from tabulate import tabulate
try:
from falconpy import APIHarness
except ImportError as no_falconpy:
raise SystemExit(
"The CrowdStrike SDK must be installed in order to use this utility.\n"
"Install this application with the command `py... | 0.457864 | 0.084266 |
from __future__ import annotations
from unittest import TestCase
from typing import List, Dict
from datetime import date, datetime, timezone
from bson import ObjectId
from jsonclasses import jsonclass, types
from jsonclasses_pymongo import pymongo
from jsonclasses_pymongo.decoder import Decoder
class TestDecoder(Test... | tests/test_decoder.py | from __future__ import annotations
from unittest import TestCase
from typing import List, Dict
from datetime import date, datetime, timezone
from bson import ObjectId
from jsonclasses import jsonclass, types
from jsonclasses_pymongo import pymongo
from jsonclasses_pymongo.decoder import Decoder
class TestDecoder(Test... | 0.75037 | 0.42913 |
from typing import Tuple, List, Union
import numpy as np
from common.exceptionmanager import catch_error_exception
from common.functionutil import ImagesUtil
from dataloaders.batchdatagenerator import BatchDataGenerator
from models.pytorch.networks import UNet
from models.networkchecker import NetworkCheckerBase
cla... | src/models/pytorch/networkchecker.py | from typing import Tuple, List, Union
import numpy as np
from common.exceptionmanager import catch_error_exception
from common.functionutil import ImagesUtil
from dataloaders.batchdatagenerator import BatchDataGenerator
from models.pytorch.networks import UNet
from models.networkchecker import NetworkCheckerBase
cla... | 0.863291 | 0.307007 |