code stringlengths 2k 1.04M | repo_path stringlengths 5 517 | parsed_code stringlengths 0 1.04M | quality_prob float64 0.02 0.95 | learning_prob float64 0.02 0.93 |
|---|---|---|---|---|
from __future__ import division, print_function
import sys
import os
import time
import enum
import numpy as np
from mpi4py import MPI
import h5py
from .finite_differences import SOR_step, apply_operator
from scipy.fftpack import fft2, ifft2
def format_float(x, sigfigs=4, units=''):
"""Returns a string of the flo... | parPDE/parPDE.py | from __future__ import division, print_function
import sys
import os
import time
import enum
import numpy as np
from mpi4py import MPI
import h5py
from .finite_differences import SOR_step, apply_operator
from scipy.fftpack import fft2, ifft2
def format_float(x, sigfigs=4, units=''):
"""Returns a string of the flo... | 0.704872 | 0.295135 |
import os
from textwrap import dedent
from nipype import Workflow, Node, Function
from traits.api import TraitError
import pytest
from .. import frontend
class TestFrontend(object):
@pytest.fixture
def lyman_dir(self, execdir):
lyman_dir = execdir.mkdir("lyman")
os.environ["LYMAN_DIR"] = str... | lyman/tests/test_frontend.py | import os
from textwrap import dedent
from nipype import Workflow, Node, Function
from traits.api import TraitError
import pytest
from .. import frontend
class TestFrontend(object):
@pytest.fixture
def lyman_dir(self, execdir):
lyman_dir = execdir.mkdir("lyman")
os.environ["LYMAN_DIR"] = str... | 0.449151 | 0.491273 |
import sys
import numpy as np
import pylab as pl
import scipy.io
import scipy.linalg
from UFL.common import DataInputOutput, DataNormalization, AuxFunctions, Visualization
from UFL.PCA import PCA
ICA_COST_FUNCTION_ICA = 0;
ICA_COST_FUNCTION_RICA = 1;
ICA_COST_FUNCTIONS = [ICA_COST_FUNCTION_ICA, ICA_COST_FUNCTION_RICA... | ICA/ICA.py | import sys
import numpy as np
import pylab as pl
import scipy.io
import scipy.linalg
from UFL.common import DataInputOutput, DataNormalization, AuxFunctions, Visualization
from UFL.PCA import PCA
ICA_COST_FUNCTION_ICA = 0;
ICA_COST_FUNCTION_RICA = 1;
ICA_COST_FUNCTIONS = [ICA_COST_FUNCTION_ICA, ICA_COST_FUNCTION_RICA... | 0.417509 | 0.558508 |
import os
import sys
import logging
import pytz
__author__ = "<NAME>"
class Settings:
"""Class to hold settings and paths
Attributes:
AppName: Application name
FooterLine: Frontend footer line
PyPath: computed path to the current script folder
ProjPath: project path, defaults to <PyPath>/..
... | common/settings.py |
import os
import sys
import logging
import pytz
__author__ = "<NAME>"
class Settings:
"""Class to hold settings and paths
Attributes:
AppName: Application name
FooterLine: Frontend footer line
PyPath: computed path to the current script folder
ProjPath: project path, defaults to <PyPath>/..
... | 0.464902 | 0.308203 |
from django.core.management.base import BaseCommand
from twisted.internet import reactor
from twisted.internet.defer import Deferred, inlineCallbacks
from twisted.logger import Logger
from autobahn.twisted.util import sleep
from autobahn.twisted.wamp import ApplicationSession, ApplicationRunner
from autobahn.wamp imp... | wampclient/management/commands/wamp_client.py | from django.core.management.base import BaseCommand
from twisted.internet import reactor
from twisted.internet.defer import Deferred, inlineCallbacks
from twisted.logger import Logger
from autobahn.twisted.util import sleep
from autobahn.twisted.wamp import ApplicationSession, ApplicationRunner
from autobahn.wamp imp... | 0.467089 | 0.073663 |
import json
import random
import time
from adafruit_magtag.magtag import MagTag
weekdays = ("Mon", "Tues", "Wed", "Thurs", "Fri", "Sat", "Sun")
months = ("Jan", "Feb", "Mar", "Apr", "May", "Jun", "Jul", "Aug", "Sep", "Oct", "Nov", "Dec")
def main():
magtag = MagTag()
# Date label
magtag.add_t... | quotes_calendar.py | import json
import random
import time
from adafruit_magtag.magtag import MagTag
weekdays = ("Mon", "Tues", "Wed", "Thurs", "Fri", "Sat", "Sun")
months = ("Jan", "Feb", "Mar", "Apr", "May", "Jun", "Jul", "Aug", "Sep", "Oct", "Nov", "Dec")
def main():
magtag = MagTag()
# Date label
magtag.add_t... | 0.292292 | 0.09611 |
import os
import sys
import psycopg2
from psycopg2.extras import LoggingConnection
import pytest
from .db import TemporaryTable
connection_params = {
'dbname': os.getenv('POSTGRES_DB', 'pgcopy_test'),
'port': int(os.getenv('POSTGRES_PORT', '5432')),
'host': os.getenv('POSTGRES_HOST'),
'user': os.getenv... | tests/conftest.py | import os
import sys
import psycopg2
from psycopg2.extras import LoggingConnection
import pytest
from .db import TemporaryTable
connection_params = {
'dbname': os.getenv('POSTGRES_DB', 'pgcopy_test'),
'port': int(os.getenv('POSTGRES_PORT', '5432')),
'host': os.getenv('POSTGRES_HOST'),
'user': os.getenv... | 0.209066 | 0.071461 |
import uvicorn
import requests
import uuid
from fastapi import FastAPI, Path
from typing import Optional
from pydantic import BaseModel
from config.config import config
class User(BaseModel):
name: str
username: str = uuid.uuid4()
email: Optional[str] = None
phone: Optional[str] = None
website: Op... | src/main.py | import uvicorn
import requests
import uuid
from fastapi import FastAPI, Path
from typing import Optional
from pydantic import BaseModel
from config.config import config
class User(BaseModel):
name: str
username: str = uuid.uuid4()
email: Optional[str] = None
phone: Optional[str] = None
website: Op... | 0.675444 | 0.178365 |
import warnings
from pathlib import Path
import numpy as np
import pandas as pd
from scipy import stats
from skimage import morphology
from matplotlib import pyplot as plt
from matplotlib import (patheffects, colors)
import aplpy
import pyspeckit
from pyspeckit.spectrum.models import ammonia
import radio_beam
from as... | cube_fitting.py | import warnings
from pathlib import Path
import numpy as np
import pandas as pd
from scipy import stats
from skimage import morphology
from matplotlib import pyplot as plt
from matplotlib import (patheffects, colors)
import aplpy
import pyspeckit
from pyspeckit.spectrum.models import ammonia
import radio_beam
from as... | 0.804713 | 0.411466 |
# Author: <NAME>
import logging
import os
import re
import shutil
import subprocess
from typing import Dict, List, Optional
import pendulum
from airflow.exceptions import AirflowException
from airflow.models.taskinstance import TaskInstance
from google.cloud.bigquery import SourceFormat
from oaebu_workflows.config i... | oaebu_workflows/workflows/onix_telescope.py |
# Author: <NAME>
import logging
import os
import re
import shutil
import subprocess
from typing import Dict, List, Optional
import pendulum
from airflow.exceptions import AirflowException
from airflow.models.taskinstance import TaskInstance
from google.cloud.bigquery import SourceFormat
from oaebu_workflows.config i... | 0.747155 | 0.179602 |
import json
import os
import unittest
import loadConfig
class ConfigDotJSONTest(unittest.TestCase):
def test_configuration(self):
cwd = os.path.dirname(os.path.abspath(__file__))
loadConfig.loadBuilderConfig({}, is_test_mode_enabled=True, master_prefix_path=cwd)
def test_builder_keys(self)... | Tools/BuildSlaveSupport/ews-build/loadConfig_unittest.py |
import json
import os
import unittest
import loadConfig
class ConfigDotJSONTest(unittest.TestCase):
def test_configuration(self):
cwd = os.path.dirname(os.path.abspath(__file__))
loadConfig.loadBuilderConfig({}, is_test_mode_enabled=True, master_prefix_path=cwd)
def test_builder_keys(self)... | 0.516839 | 0.196229 |
from __future__ import print_function
import os
import sys
from chromite.api.gen.chromiumos import common_pb2
from chromite.lib import chroot_lib
from chromite.lib import constants
from chromite.lib import cros_build_lib
from chromite.lib import cros_test_lib
from chromite.lib import osutils
from chromite.lib import ... | lib/sysroot_lib_unittest.py | from __future__ import print_function
import os
import sys
from chromite.api.gen.chromiumos import common_pb2
from chromite.lib import chroot_lib
from chromite.lib import constants
from chromite.lib import cros_build_lib
from chromite.lib import cros_test_lib
from chromite.lib import osutils
from chromite.lib import ... | 0.531453 | 0.266041 |
from __future__ import print_function, unicode_literals
from escher.plots import Builder
from escher.urls import get_url
from escher.version import __version__
from escher.urls import top_directory, root_directory
from os.path import join, dirname, realpath
from jinja2 import Environment, PackageLoader
import shutil
... | py/escher/static_site.py | from __future__ import print_function, unicode_literals
from escher.plots import Builder
from escher.urls import get_url
from escher.version import __version__
from escher.urls import top_directory, root_directory
from os.path import join, dirname, realpath
from jinja2 import Environment, PackageLoader
import shutil
... | 0.47171 | 0.063978 |
from aql import get_aql_info
info = get_aql_info()
SCRIPTS_PATH = 'scripts'
MODULES_PATH = 'modules'
AQL_MODULE_PATH = MODULES_PATH + '/' + info.module
UNIX_SCRIPT_PATH = SCRIPTS_PATH + '/aql'
WINDOWS_SCRIPT_PATH = SCRIPTS_PATH + '/aql.cmd'
MANIFEST = """include {unix_script}
include {win_script}
""".format(unix_sc... | make/setup_settings.py | from aql import get_aql_info
info = get_aql_info()
SCRIPTS_PATH = 'scripts'
MODULES_PATH = 'modules'
AQL_MODULE_PATH = MODULES_PATH + '/' + info.module
UNIX_SCRIPT_PATH = SCRIPTS_PATH + '/aql'
WINDOWS_SCRIPT_PATH = SCRIPTS_PATH + '/aql.cmd'
MANIFEST = """include {unix_script}
include {win_script}
""".format(unix_sc... | 0.203391 | 0.04679 |
import argparse
import cv2
import os
import numpy as np
import torch
import torch.nn as nn
import torch.nn.functional as F
import torch.optim as optim
from torch.utils.data import Dataset, DataLoader
from torch.autograd import Variable
# Network architecture of proposed autoencoder
class Color_Generator(nn.Module):... | representation.py |
import argparse
import cv2
import os
import numpy as np
import torch
import torch.nn as nn
import torch.nn.functional as F
import torch.optim as optim
from torch.utils.data import Dataset, DataLoader
from torch.autograd import Variable
# Network architecture of proposed autoencoder
class Color_Generator(nn.Module):... | 0.888215 | 0.373819 |
import os.path
import hashlib
import requests
import tornado.web
import tornado.ioloop
import tornado.gen
import tornado.escape
from io import BytesIO
from PIL import Image
from bs4 import BeautifulSoup as bs4
from datetime import datetime
from selenium import webdriver
from whoosh.query import Every
from whoosh.index ... | web.py | import os.path
import hashlib
import requests
import tornado.web
import tornado.ioloop
import tornado.gen
import tornado.escape
from io import BytesIO
from PIL import Image
from bs4 import BeautifulSoup as bs4
from datetime import datetime
from selenium import webdriver
from whoosh.query import Every
from whoosh.index ... | 0.18385 | 0.064713 |
# Created by <NAME>
# National Renewable Energy Laboratory
# Summer 2019
#########################################################################################################################################
#####################################################################################################... | post_process/AAOutputFile2_post.py |
# Created by <NAME>
# National Renewable Energy Laboratory
# Summer 2019
#########################################################################################################################################
#####################################################################################################... | 0.273477 | 0.138782 |
from __future__ import unicode_literals, print_function
import collections
import datetime
import sys
import xml.etree.ElementTree
import vi3o
from vi3o import mkv
from vi3o import cat
from vi3o import compat
if sys.version_info >= (3, 5, 0):
from typing import Any, List, Union, Dict
# Representation of data in ... | vi3o/recording.py | from __future__ import unicode_literals, print_function
import collections
import datetime
import sys
import xml.etree.ElementTree
import vi3o
from vi3o import mkv
from vi3o import cat
from vi3o import compat
if sys.version_info >= (3, 5, 0):
from typing import Any, List, Union, Dict
# Representation of data in ... | 0.52342 | 0.155816 |
from lxml import etree
import requests
from counter.config import Config
from counter import pasta_db
def clean(text):
return " ".join(text.split())
def get_entity_name(dataset, rid: str):
name = None
urls = dataset.findall("./physical/distribution/online/url")
for url in urls:
if rid == ur... | src/counter/package.py | from lxml import etree
import requests
from counter.config import Config
from counter import pasta_db
def clean(text):
return " ".join(text.split())
def get_entity_name(dataset, rid: str):
name = None
urls = dataset.findall("./physical/distribution/online/url")
for url in urls:
if rid == ur... | 0.532911 | 0.089177 |
import argparse
import sys
import sqlite3
from sqlite3 import Error
class sql_connect:
def __init__(self, db):
# create a database connection
self.conn = self.create_connection(db)
sql_create_metadata_table = """ CREATE TABLE IF NOT EXISTS metadata (
... | jaws/jaws_wdls/scripts/sqlite_functions.py | import argparse
import sys
import sqlite3
from sqlite3 import Error
class sql_connect:
def __init__(self, db):
# create a database connection
self.conn = self.create_connection(db)
sql_create_metadata_table = """ CREATE TABLE IF NOT EXISTS metadata (
... | 0.172834 | 0.134122 |
from django.urls import path
from . import views
app_name = "management"
urlpatterns = [
path('management/', views.login, name='login'),
path('management/login', views.login, name='login'),
path('management/overview', views.overview, name='overview'),
path('management/inventory', views.inventory, name... | coffeenijuan/management/urls.py | from django.urls import path
from . import views
app_name = "management"
urlpatterns = [
path('management/', views.login, name='login'),
path('management/login', views.login, name='login'),
path('management/overview', views.overview, name='overview'),
path('management/inventory', views.inventory, name... | 0.318591 | 0.055566 |
print('digite 1 para masculino e 0 para feminino.')
sexo = int(input('qual e o seu sexo? (numero)'))
if sexo == 1:
from datetime import date
nacimento = int(input('em que ano vc nasceu ?'))
if nacimento + 18 < date.today().year:
cnascimento = date.today().year - nacimento
calistamento = c... | download-deveres/para-execicios-curso-em-video/exe039b.py | print('digite 1 para masculino e 0 para feminino.')
sexo = int(input('qual e o seu sexo? (numero)'))
if sexo == 1:
from datetime import date
nacimento = int(input('em que ano vc nasceu ?'))
if nacimento + 18 < date.today().year:
cnascimento = date.today().year - nacimento
calistamento = c... | 0.18717 | 0.244622 |
import pysplishsplash as sph
from pysplishsplash.Extras import Scenes
import os
import sys
import json
import xml.etree.ElementTree as ET
if __name__ == "__main__":
assert(len(sys.argv) == 5), "sim_run.py should have 4 arguments."
upload_config_file_path = sys.argv[1]
upload_file_dir = sys.argv[2]
uplo... | sph_run.py | import pysplishsplash as sph
from pysplishsplash.Extras import Scenes
import os
import sys
import json
import xml.etree.ElementTree as ET
if __name__ == "__main__":
assert(len(sys.argv) == 5), "sim_run.py should have 4 arguments."
upload_config_file_path = sys.argv[1]
upload_file_dir = sys.argv[2]
uplo... | 0.13887 | 0.151184 |
import os
import sys
import json
__author__ = '<NAME>'
__email__ = '<EMAIL>'
__copyright__ = 'Copyright(c) 2015, Cisco Systems, Inc.'
__version__ = '0.1'
__status__ = 'alpha'
"""
Common testing constants, mappings, functions; global pytest settings
"""
#: enable ../sfc-py/common files usage in tests
test_path =... | test/conftest.py |
import os
import sys
import json
__author__ = '<NAME>'
__email__ = '<EMAIL>'
__copyright__ = 'Copyright(c) 2015, Cisco Systems, Inc.'
__version__ = '0.1'
__status__ = 'alpha'
"""
Common testing constants, mappings, functions; global pytest settings
"""
#: enable ../sfc-py/common files usage in tests
test_path =... | 0.467818 | 0.064124 |
import pandas as pd
import numpy as np
import matplotlib.pyplot as plt
#Path of the file is stored in the variable path
data = pd.read_csv(path)
#Code starts here
# Data Loading
data=data.rename(columns={'Total':'Total_Medals'})
print(data.head(10))
print('='*80)
# Summer or Winter
data['Better_Event']=np.where(da... | code.py | import pandas as pd
import numpy as np
import matplotlib.pyplot as plt
#Path of the file is stored in the variable path
data = pd.read_csv(path)
#Code starts here
# Data Loading
data=data.rename(columns={'Total':'Total_Medals'})
print(data.head(10))
print('='*80)
# Summer or Winter
data['Better_Event']=np.where(da... | 0.430626 | 0.283124 |
from CONFIG import (
CFFMPEG_STREAM, CFFMPEG_HOST, CFFMPEG_PORT, CFFMPEG_LEGLEVEL, CTMP_DIR
)
class FFMpeg(object):
"""docstring for FFMpeg."""
def __init__(self):
super(FFMpeg, self).__init__()
self.cmd = []
self.cmd.append('ffmpeg')
def log(self, hide_banner=True, stats=Fal... | classes/ffmpeg.py | from CONFIG import (
CFFMPEG_STREAM, CFFMPEG_HOST, CFFMPEG_PORT, CFFMPEG_LEGLEVEL, CTMP_DIR
)
class FFMpeg(object):
"""docstring for FFMpeg."""
def __init__(self):
super(FFMpeg, self).__init__()
self.cmd = []
self.cmd.append('ffmpeg')
def log(self, hide_banner=True, stats=Fal... | 0.489503 | 0.166777 |
import sklearn
from sklearn.linear_model import SGDRegressor, SGDClassifier
from sklearn.neural_network import MLPRegressor, MLPClassifier
from sklearn.naive_bayes import MultinomialNB, GaussianNB
from sklearn.neighbors import KNeighborsRegressor, KNeighborsClassifier
from sklearn.ensemble import GradientBoostingRegre... | python-mip-sklearn/sklearn_to_pfa/sklearn_to_pfa/sklearn_to_pfa.py |
import sklearn
from sklearn.linear_model import SGDRegressor, SGDClassifier
from sklearn.neural_network import MLPRegressor, MLPClassifier
from sklearn.naive_bayes import MultinomialNB, GaussianNB
from sklearn.neighbors import KNeighborsRegressor, KNeighborsClassifier
from sklearn.ensemble import GradientBoostingRegre... | 0.740737 | 0.396828 |
import sys
import os
import ast
if "--silent" in sys.argv:
os.environ["TF_CPP_MIN_LOG_LEVEL"] = "3"
if "--cpu" in sys.argv or "--cpu_only" in sys.argv:
os.environ["CUDA_VISIBLE_DEVICES"] = "-1"
from math import sqrt
from argparse import ArgumentParser, Namespace
from datetime import datetime, timedelta
from ... | windpower/batch/__main__.py | import sys
import os
import ast
if "--silent" in sys.argv:
os.environ["TF_CPP_MIN_LOG_LEVEL"] = "3"
if "--cpu" in sys.argv or "--cpu_only" in sys.argv:
os.environ["CUDA_VISIBLE_DEVICES"] = "-1"
from math import sqrt
from argparse import ArgumentParser, Namespace
from datetime import datetime, timedelta
from ... | 0.388154 | 0.237443 |
import os
import numpy as np
import struct
class MNISTChurner:
def __init__(self, data_path):
"""
initializes object with mnist data path
:param data_path:
"""
print("Loading dataset path")
self.train_data_path = os.path.join(data_path, "train-images.idx3-ubyte")
... | dataset_reader.py | import os
import numpy as np
import struct
class MNISTChurner:
def __init__(self, data_path):
"""
initializes object with mnist data path
:param data_path:
"""
print("Loading dataset path")
self.train_data_path = os.path.join(data_path, "train-images.idx3-ubyte")
... | 0.366136 | 0.346458 |
import sys
import os
usage = '''<file> <max position> <threshold>
The file should be the ncnc.score.tsv file that has the following columns:
posistion phage bacteria metric species genus family order class phylum
The max position is the maximum allowable position to include in the score
and we use this value or... | code/summarize_ncnc.py | import sys
import os
usage = '''<file> <max position> <threshold>
The file should be the ncnc.score.tsv file that has the following columns:
posistion phage bacteria metric species genus family order class phylum
The max position is the maximum allowable position to include in the score
and we use this value or... | 0.235988 | 0.586049 |
from __future__ import absolute_import
from __future__ import division
from __future__ import print_function
import numpy as np
from scipy.stats import norm
from . import Acquirer
__all__ = [
'ExpectedImprovementAcquirer',
]
def preprocess_data(data):
"""
Preprocess preference data for use in model.
... | src/prefopt/acquisition/expected_improvement.py | from __future__ import absolute_import
from __future__ import division
from __future__ import print_function
import numpy as np
from scipy.stats import norm
from . import Acquirer
__all__ = [
'ExpectedImprovementAcquirer',
]
def preprocess_data(data):
"""
Preprocess preference data for use in model.
... | 0.938752 | 0.553867 |
import logging
from django.utils.translation import gettext_lazy as _
from drf_yasg.utils import swagger_auto_schema
from rest_framework.generics import GenericAPIView, UpdateAPIView, ListAPIView
from rest_framework.response import Response
from rest_framework import status
from rest_framework.reverse import reverse_la... | web/chat/views.py | import logging
from django.utils.translation import gettext_lazy as _
from drf_yasg.utils import swagger_auto_schema
from rest_framework.generics import GenericAPIView, UpdateAPIView, ListAPIView
from rest_framework.response import Response
from rest_framework import status
from rest_framework.reverse import reverse_la... | 0.315841 | 0.051702 |
import json
import coc.utils
from Data.Variables.import_var import Linked_accounts
from Data.Constants.useful import Useful
from Script.Clients.clash_of_clans_client import Clash_of_clans
from Script.import_functions import create_embed
async def link_coc_account(ctx, player_tag, api_token):
player_tag = coc.u... | Script/Commands/Messages/link_coc_account.py |
import json
import coc.utils
from Data.Variables.import_var import Linked_accounts
from Data.Constants.useful import Useful
from Script.Clients.clash_of_clans_client import Clash_of_clans
from Script.import_functions import create_embed
async def link_coc_account(ctx, player_tag, api_token):
player_tag = coc.u... | 0.481698 | 0.197116 |
import numpy as np
from skmultiflow.trees.nodes import ActiveLearningNode
from skmultiflow.trees.attribute_observer import NominalAttributeRegressionObserver
from skmultiflow.trees.attribute_observer import NumericAttributeRegressionObserver
from skmultiflow.utils import check_random_state
class ActiveLearningNodePer... | src/skmultiflow/trees/nodes/active_learning_node_perceptron.py | import numpy as np
from skmultiflow.trees.nodes import ActiveLearningNode
from skmultiflow.trees.attribute_observer import NominalAttributeRegressionObserver
from skmultiflow.trees.attribute_observer import NumericAttributeRegressionObserver
from skmultiflow.utils import check_random_state
class ActiveLearningNodePer... | 0.916641 | 0.620219 |
import os
import subprocess
import numpy as np
from mako.template import Template
from mbgdml import utils
class CalcTemplate:
"""Contains all quantum chemistry templates for mako.
Parameters
----------
package : :obj:`str`
Computational chemistry package to perform calculations.
"""
... | mbgdml/qc.py |
import os
import subprocess
import numpy as np
from mako.template import Template
from mbgdml import utils
class CalcTemplate:
"""Contains all quantum chemistry templates for mako.
Parameters
----------
package : :obj:`str`
Computational chemistry package to perform calculations.
"""
... | 0.728362 | 0.144903 |
import json
import logging
import os
logger = logging.getLogger(__name__)
class ConfigError(ValueError):
"""Specific error for configuration issues."""
pass
class Config(object):
"""Configuration defaults."""
DEBUG = False
SECRET_KEY = 'youwillneverguessme'
SERVER_BASE = 'localhost'
S... | flask_forecaster/config.py |
import json
import logging
import os
logger = logging.getLogger(__name__)
class ConfigError(ValueError):
"""Specific error for configuration issues."""
pass
class Config(object):
"""Configuration defaults."""
DEBUG = False
SECRET_KEY = 'youwillneverguessme'
SERVER_BASE = 'localhost'
S... | 0.799011 | 0.196441 |
import unittest
import gym_buster.envs.buster_env as env
class EnvTest(unittest.TestCase):
def test_run_1_game_random_action(self):
"""
Run one game from the env from random sampled action
"""
buster_number = 3 # per team
ghost_number = 15
max_episodes = 1
... | gym_buster/envs/game_classes/test/env_tests.py | import unittest
import gym_buster.envs.buster_env as env
class EnvTest(unittest.TestCase):
def test_run_1_game_random_action(self):
"""
Run one game from the env from random sampled action
"""
buster_number = 3 # per team
ghost_number = 15
max_episodes = 1
... | 0.71423 | 0.687253 |
# Common utils and data for test files
from __future__ import absolute_import
from __future__ import print_function
try:
# Python 2
from cStringIO import StringIO
except ImportError:
from io import StringIO
import __main__
import sys
import os
import re
import datetime
import time
import unittest
import... | test/util.py |
# Common utils and data for test files
from __future__ import absolute_import
from __future__ import print_function
try:
# Python 2
from cStringIO import StringIO
except ImportError:
from io import StringIO
import __main__
import sys
import os
import re
import datetime
import time
import unittest
import... | 0.584627 | 0.216156 |
# COMMAND ----------
# MAGIC %run ./adb_1_functions
# COMMAND ----------
# MAGIC %run ./adb_3_ingest_to_df
# COMMAND ----------
# MAGIC %md
# MAGIC ### Partitions and repartitioning
# COMMAND ----------
num_partitions = 16
# COMMAND ----------
print(df_flights_full.rdd.getNumPartitions())
# COMMAND ---------... | flight-data/adb_5_write_to_parquet.py |
# COMMAND ----------
# MAGIC %run ./adb_1_functions
# COMMAND ----------
# MAGIC %run ./adb_3_ingest_to_df
# COMMAND ----------
# MAGIC %md
# MAGIC ### Partitions and repartitioning
# COMMAND ----------
num_partitions = 16
# COMMAND ----------
print(df_flights_full.rdd.getNumPartitions())
# COMMAND ---------... | 0.455683 | 0.3415 |
import json
import aiohttp
import discord
from discord.ext import commands
from modules.utils import checks
from modules.utils.weather import data_fetch, data_return, url_meteo
with open('./config/config.json', 'r') as cjson:
config = json.load(cjson)
OWNER = config["owner_id"]
class General(commands.Cog):
... | modules/general/general.py |
import json
import aiohttp
import discord
from discord.ext import commands
from modules.utils import checks
from modules.utils.weather import data_fetch, data_return, url_meteo
with open('./config/config.json', 'r') as cjson:
config = json.load(cjson)
OWNER = config["owner_id"]
class General(commands.Cog):
... | 0.33764 | 0.085862 |
import time
import numpy as np
from ledtrix.effects.coloreffects import effect_complemetary_colors
class EffectExponentialFade():
def __init__(self, lifetime, minimum_brightness = 0):
"""
half_life: float
Half life of decay in milliseconds
"""
self.lifetime = lifetime
... | ledtrix/effects/screeneffects.py | import time
import numpy as np
from ledtrix.effects.coloreffects import effect_complemetary_colors
class EffectExponentialFade():
def __init__(self, lifetime, minimum_brightness = 0):
"""
half_life: float
Half life of decay in milliseconds
"""
self.lifetime = lifetime
... | 0.669961 | 0.231158 |
from colorama import Fore
from utils.collector import Item
def canonize(source):
stop_symbols = '.,!?:;-\n\r()\''
stop_words = (u"the",)
return [x for x in [y.strip(stop_symbols) for y in source.lower().split()] if x and (x not in stop_words)]
def genshingle(source):
import binascii
shingle_l... | utils/teseract.py |
from colorama import Fore
from utils.collector import Item
def canonize(source):
stop_symbols = '.,!?:;-\n\r()\''
stop_words = (u"the",)
return [x for x in [y.strip(stop_symbols) for y in source.lower().split()] if x and (x not in stop_words)]
def genshingle(source):
import binascii
shingle_l... | 0.312055 | 0.289246 |
import re, pprint, os, sys
from urllib.request import urlopen
from bs4 import BeautifulSoup # sudo apt install python-bs4
from jinja2 import Environment, FileSystemLoader # pip install Jinja2
pp = pprint.PrettyPrinter(indent=2, width=120)
proj_dir = os.path.dirname(os.path.realpath(__file__)) + "/../"
html = urlopen(... | jipp-core/bin/genCupsTypes.py |
import re, pprint, os, sys
from urllib.request import urlopen
from bs4 import BeautifulSoup # sudo apt install python-bs4
from jinja2 import Environment, FileSystemLoader # pip install Jinja2
pp = pprint.PrettyPrinter(indent=2, width=120)
proj_dir = os.path.dirname(os.path.realpath(__file__)) + "/../"
html = urlopen(... | 0.240418 | 0.129706 |
import bpy
import uuid
from bpy.types import Menu, Panel, UIList,UILayout,Operator
def findLod(obj,lodLevel,set=None,replace=True):
lod=None
collection=None
if obj.data!=None and "_f3b_Lod" in obj.data:
lodGroup=obj.data["_f3b_Lod"]
lodName="LOD"+str(lodLevel)+"_"
if lodGroup in bpy... | blender_f3b/tools/F3bLod.py | import bpy
import uuid
from bpy.types import Menu, Panel, UIList,UILayout,Operator
def findLod(obj,lodLevel,set=None,replace=True):
lod=None
collection=None
if obj.data!=None and "_f3b_Lod" in obj.data:
lodGroup=obj.data["_f3b_Lod"]
lodName="LOD"+str(lodLevel)+"_"
if lodGroup in bpy... | 0.089482 | 0.095139 |
import pytest
from .context import gatherers # noqa
from gatherers import rdns
@pytest.mark.parametrize("data,expected", [
(
[
'{"value": "18f.gov"}',
'{"value": "123.112.18f.gov"}',
'{"value": "172.16.17.32"}',
'{"value": "u-123.112.23.23"}',
'... | tests/test_gatherers_rdns.py | import pytest
from .context import gatherers # noqa
from gatherers import rdns
@pytest.mark.parametrize("data,expected", [
(
[
'{"value": "18f.gov"}',
'{"value": "123.112.18f.gov"}',
'{"value": "172.16.17.32"}',
'{"value": "u-123.112.23.23"}',
'... | 0.13005 | 0.309721 |
import os
import sys
import json
import pickle
import cv2
import random
import argparse
from pathlib import Path
from collections import OrderedDict
def find_data_dir(root_dir_name=""):
"""
For finding the right data folder, since directories of data folder are different among users
root_dir_name: ... | scripts/utils/util.py | import os
import sys
import json
import pickle
import cv2
import random
import argparse
from pathlib import Path
from collections import OrderedDict
def find_data_dir(root_dir_name=""):
"""
For finding the right data folder, since directories of data folder are different among users
root_dir_name: ... | 0.232049 | 0.280278 |
import sys
import os
import logging
from collections import OrderedDict
from substance.monads import *
from substance.logs import *
from substance.shell import Shell
from substance.engine import Engine
from substance.link import Link
from substance.box import Box
from substance.db import DB
from substance.constants im... | substance/core.py | import sys
import os
import logging
from collections import OrderedDict
from substance.monads import *
from substance.logs import *
from substance.shell import Shell
from substance.engine import Engine
from substance.link import Link
from substance.box import Box
from substance.db import DB
from substance.constants im... | 0.350755 | 0.076408 |
import bson
import pytest
import xarray
from xarray_mongodb import DocumentNotFoundError, XarrayMongoDB
from . import assert_chunks_index
from .data import (
da,
ds,
expect_da_chunks,
expect_da_meta,
expect_ds_chunks,
expect_ds_meta,
expect_meta_minimal,
parametrize_roundtrip,
)
def ... | xarray_mongodb/tests/test_sync.py | import bson
import pytest
import xarray
from xarray_mongodb import DocumentNotFoundError, XarrayMongoDB
from . import assert_chunks_index
from .data import (
da,
ds,
expect_da_chunks,
expect_da_meta,
expect_ds_chunks,
expect_ds_meta,
expect_meta_minimal,
parametrize_roundtrip,
)
def ... | 0.64969 | 0.467575 |
import pygame as pg
from music import fallSound
class player(pg.sprite.Sprite):
def __init__(self):
pg.sprite.Sprite.__init__(self)
self.moving_right = False
self.moving_left = False
self.vertical_momentum = 0
self.air_timer = 0 # necessary because movement speed ro... | player_char.py | import pygame as pg
from music import fallSound
class player(pg.sprite.Sprite):
def __init__(self):
pg.sprite.Sprite.__init__(self)
self.moving_right = False
self.moving_left = False
self.vertical_momentum = 0
self.air_timer = 0 # necessary because movement speed ro... | 0.540924 | 0.199737 |
from moduleUsefulFunctions_20180215 import *
plt.close()
class dimerSixBaseObject:
def __init__(self):
self.readSeqDict={} #keys are tuples of the form ('Mutations in 1st half','Dimer junction','Mutations in 2nd half','Three Prime Base addition')
def returnStartPosition(alignInfoList):
for eachEl in a... | Fig_S14/junctions_20180430_ver2.py | from moduleUsefulFunctions_20180215 import *
plt.close()
class dimerSixBaseObject:
def __init__(self):
self.readSeqDict={} #keys are tuples of the form ('Mutations in 1st half','Dimer junction','Mutations in 2nd half','Three Prime Base addition')
def returnStartPosition(alignInfoList):
for eachEl in a... | 0.339499 | 0.376623 |
import numpy as np
import h5py
import os
import yaml
def make_stats_file(path, GridX, GridY, output):
files =[]
for r, d, f in os.walk(path):
for file in f:
if '.hdf5' in file:
files.append(os.path.join(r, file))
stats_dict = {'variable':{'mean':2, 'min':1, 'max':5, 'st... | make_statistics_file/make_statistics_file.py |
import numpy as np
import h5py
import os
import yaml
def make_stats_file(path, GridX, GridY, output):
files =[]
for r, d, f in os.walk(path):
for file in f:
if '.hdf5' in file:
files.append(os.path.join(r, file))
stats_dict = {'variable':{'mean':2, 'min':1, 'max':5, 'st... | 0.244634 | 0.174147 |
from .mobile_robot_env import *
MAX_STEPS = 1500
class MobileRobot2TargetGymEnv(MobileRobotGymEnv):
"""
Gym wrapper for Mobile Robot environment with 2 targets
WARNING: to be compatible with kuka scripts, additional keyword arguments are discarded
:param urdf_root: (str) Path to pybullet urdf files
... | environments/mobile_robot/mobile_robot_2target_env.py | from .mobile_robot_env import *
MAX_STEPS = 1500
class MobileRobot2TargetGymEnv(MobileRobotGymEnv):
"""
Gym wrapper for Mobile Robot environment with 2 targets
WARNING: to be compatible with kuka scripts, additional keyword arguments are discarded
:param urdf_root: (str) Path to pybullet urdf files
... | 0.877424 | 0.582372 |
import argparse
from dask import visualize
from distributed import LocalCluster, Client, progress
from .execute import get_dask_outputs
def parse_args(parse_this=None):
parser = argparse.ArgumentParser()
parser.add_argument("path", default='.')
package_specs = parser.add_mutually_exclusive_group()
p... | conda_gitlab_ci/cli.py | import argparse
from dask import visualize
from distributed import LocalCluster, Client, progress
from .execute import get_dask_outputs
def parse_args(parse_this=None):
parser = argparse.ArgumentParser()
parser.add_argument("path", default='.')
package_specs = parser.add_mutually_exclusive_group()
p... | 0.422505 | 0.103749 |
from __future__ import print_function
import sys
import ldap
from .objects import LDAPUser, LDAPGroup, LDAPObjectException
from ..base import print_error
class LDAPServer(object):
def __init__(self, **kwargs):
config = dict(kwargs.get('config'))
self.host = config.get('server')
self.base_... | src/lpconnector/ldap/server.py | from __future__ import print_function
import sys
import ldap
from .objects import LDAPUser, LDAPGroup, LDAPObjectException
from ..base import print_error
class LDAPServer(object):
def __init__(self, **kwargs):
config = dict(kwargs.get('config'))
self.host = config.get('server')
self.base_... | 0.273671 | 0.041385 |
import logging
import os
import random
from datetime import datetime
from pathlib import Path
import numpy as np
import pandas as pd
from emoji import emojize
from flask_app.player import LocalDummyPlayer, LocalFasttextPlayer # noqa: F401
from settings import CRITERIA, N_EXPLAIN_WORDS, N_GUESSING_WORDS, VOCAB_PATH
f... | run_game.py | import logging
import os
import random
from datetime import datetime
from pathlib import Path
import numpy as np
import pandas as pd
from emoji import emojize
from flask_app.player import LocalDummyPlayer, LocalFasttextPlayer # noqa: F401
from settings import CRITERIA, N_EXPLAIN_WORDS, N_GUESSING_WORDS, VOCAB_PATH
f... | 0.343342 | 0.108614 |
import numpy as np
import matplotlib.pyplot as plt
import time
from astropy.io import fits
from astropy.table import Table,vstack
from astropy.coordinates import SkyCoord # High-level coordinates
from astropy.coordinates import ICRS, Galactic, FK4, FK5 # Low-level frames
from astropy.coordinates import Angle, Latitud... | python/skymakercam/catalog.py | import numpy as np
import matplotlib.pyplot as plt
import time
from astropy.io import fits
from astropy.table import Table,vstack
from astropy.coordinates import SkyCoord # High-level coordinates
from astropy.coordinates import ICRS, Galactic, FK4, FK5 # Low-level frames
from astropy.coordinates import Angle, Latitud... | 0.381335 | 0.552962 |
import numpy as np
def forward(net, x):
for layer in net:
x = layer.forward(x)
# print('f', layer.name, x.shape)
return x
def backward(net, loss):
grad = loss.backward()
for layer in reversed(net):
grad = layer.backward(grad)
# print('b', layer.name, grad.shape)
def... | nnpy/utils.py | import numpy as np
def forward(net, x):
for layer in net:
x = layer.forward(x)
# print('f', layer.name, x.shape)
return x
def backward(net, loss):
grad = loss.backward()
for layer in reversed(net):
grad = layer.backward(grad)
# print('b', layer.name, grad.shape)
def... | 0.645679 | 0.698888 |
import pytest
import pyarrow as pa
import numpy as np
# XXX: pyarrow.schema.schema masks the module on imports
sch = pa._schema
def test_type_integers():
dtypes = ['int8', 'int16', 'int32', 'int64',
'uint8', 'uint16', 'uint32', 'uint64']
for name in dtypes:
factory = getattr(pa, nam... | python/pyarrow/tests/test_schema.py |
import pytest
import pyarrow as pa
import numpy as np
# XXX: pyarrow.schema.schema masks the module on imports
sch = pa._schema
def test_type_integers():
dtypes = ['int8', 'int16', 'int32', 'int64',
'uint8', 'uint16', 'uint32', 'uint64']
for name in dtypes:
factory = getattr(pa, nam... | 0.597138 | 0.533458 |
from __future__ import print_function
import os
import sys
from slipstream.command.CommandBase import CommandBase
from slipstream.HttpClient import HttpClient
import slipstream.util as util
import slipstream.SlipStreamHttpClient as SlipStreamHttpClient
etree = util.importETree()
class MainProgram(CommandBase):
... | client/src/main/python/ss-module-upload.py | from __future__ import print_function
import os
import sys
from slipstream.command.CommandBase import CommandBase
from slipstream.HttpClient import HttpClient
import slipstream.util as util
import slipstream.SlipStreamHttpClient as SlipStreamHttpClient
etree = util.importETree()
class MainProgram(CommandBase):
... | 0.275519 | 0.089494 |
import cv2 as cv
import math
import argparse
import numpy as np
import time
parser = argparse.ArgumentParser(description='Use this script to run text detection deep learning networks using OpenCV.')
# Input argument
parser.add_argument('--input', help='Path to input image or video file. Skip this argument to cap... | text_classify.py | import cv2 as cv
import math
import argparse
import numpy as np
import time
parser = argparse.ArgumentParser(description='Use this script to run text detection deep learning networks using OpenCV.')
# Input argument
parser.add_argument('--input', help='Path to input image or video file. Skip this argument to cap... | 0.553505 | 0.102529 |
import arrangement
import arturia_leds
import channels
import general
import midi
import patterns
import time
import transport
import ui
from arturia_display import ArturiaDisplay
from arturia_encoders import ArturiaInputControls
from arturia_leds import ArturiaLights
from arturia_metronome import VisualMetronome
from... | arturia.py | import arrangement
import arturia_leds
import channels
import general
import midi
import patterns
import time
import transport
import ui
from arturia_display import ArturiaDisplay
from arturia_encoders import ArturiaInputControls
from arturia_leds import ArturiaLights
from arturia_metronome import VisualMetronome
from... | 0.479747 | 0.099121 |
import sys
import os
from shutil import copyfile
GLOBAL_PATH='/Users/heitorsampaio/Google_Drive/Projetos/Protein_DeepLearning/DeepPM'
sys.path.insert(0, GLOBAL_PATH+'/lib')
from library import load_train_test_data_padding_with_interval,K_max_pooling1d,DLS2F_train_complex_win_filter_layer_opt
if len(sys.argv... | training/training_main.py | import sys
import os
from shutil import copyfile
GLOBAL_PATH='/Users/heitorsampaio/Google_Drive/Projetos/Protein_DeepLearning/DeepPM'
sys.path.insert(0, GLOBAL_PATH+'/lib')
from library import load_train_test_data_padding_with_interval,K_max_pooling1d,DLS2F_train_complex_win_filter_layer_opt
if len(sys.argv... | 0.080259 | 0.059839 |
import torch
import adpulses
from adpulses import io, optimizers, metrics, penalties
if __name__ == "__main__":
import sys
if len(sys.argv) <= 1: # mode DEBUG
import os
os.chdir(os.path.dirname(os.path.abspath(__file__)))
m2pName = ('m2p.mat' if len(sys.argv) <= 1 else sys.argv[1])
... | +adpulses/+opt/parctanAD.py |
import torch
import adpulses
from adpulses import io, optimizers, metrics, penalties
if __name__ == "__main__":
import sys
if len(sys.argv) <= 1: # mode DEBUG
import os
os.chdir(os.path.dirname(os.path.abspath(__file__)))
m2pName = ('m2p.mat' if len(sys.argv) <= 1 else sys.argv[1])
... | 0.413359 | 0.221224 |
import gdal
import numpy as np
from tqdm import tqdm
import argparse
import pandas as pd
import os
import subprocess
def main():
parser = argparse.ArgumentParser(
description='efficiently extract data from a vector file and multiple accompanying rasters')
parser.add_argument('crown_file', type=str)
... | extract_aop_data_from_mosaics.py | import gdal
import numpy as np
from tqdm import tqdm
import argparse
import pandas as pd
import os
import subprocess
def main():
parser = argparse.ArgumentParser(
description='efficiently extract data from a vector file and multiple accompanying rasters')
parser.add_argument('crown_file', type=str)
... | 0.253676 | 0.190913 |
from pynvml import *
import json
# 系列名称
brandNames = {
NVML_BRAND_UNKNOWN: "Unknown",
NVML_BRAND_QUADRO: "Quadro",
NVML_BRAND_TESLA: "Tesla",
NVML_BRAND_NVS: "NVS",
NVML_BRAND_GRID: "Grid",
NVML_BRAND_GEFORCE: "GeForce",
}
# 首先应该初始化nvmlInit()
# 返回错误类型
def handleError(err):
info = {'error_i... | LocalService/localapp/DockerApp/local_service.py | from pynvml import *
import json
# 系列名称
brandNames = {
NVML_BRAND_UNKNOWN: "Unknown",
NVML_BRAND_QUADRO: "Quadro",
NVML_BRAND_TESLA: "Tesla",
NVML_BRAND_NVS: "NVS",
NVML_BRAND_GRID: "Grid",
NVML_BRAND_GEFORCE: "GeForce",
}
# 首先应该初始化nvmlInit()
# 返回错误类型
def handleError(err):
info = {'error_i... | 0.1692 | 0.161519 |
from cProfile import label
from operator import index
from turtle import color
import numpy as np
import pandas as pd
import matplotlib.pyplot as plt
#Pandas ile verileri okuduk
AAPL = pd.read_csv("AAPL.csv")
#print(AAPL.head())
#30 Günlük hareketli ortalama
SMA30 = pd.DataFrame() #Yeni dataset oluşturduk... | grafik.py | from cProfile import label
from operator import index
from turtle import color
import numpy as np
import pandas as pd
import matplotlib.pyplot as plt
#Pandas ile verileri okuduk
AAPL = pd.read_csv("AAPL.csv")
#print(AAPL.head())
#30 Günlük hareketli ortalama
SMA30 = pd.DataFrame() #Yeni dataset oluşturduk... | 0.113653 | 0.231169 |
import yaml
from samplespace import pyyaml_support
from samplespace import distributions, algorithms, repeatablerandom
from tests.test_distributions import dist_lookup, dist_args
pyyaml_support.enable_yaml_support()
def test_tags():
"""Ensure that YAML tags are injected."""
assert repeatablerandom.Repeatabl... | tests/test_pyyaml_support.py | import yaml
from samplespace import pyyaml_support
from samplespace import distributions, algorithms, repeatablerandom
from tests.test_distributions import dist_lookup, dist_args
pyyaml_support.enable_yaml_support()
def test_tags():
"""Ensure that YAML tags are injected."""
assert repeatablerandom.Repeatabl... | 0.8288 | 0.632049 |
from pyflu.setuptools.base import CommandBase
from pyflu.modules import deep_import
from pyflu.command import run_script
import os
from os.path import join
import tarfile
import tempfile
import shutil
import re
class VersionCommandBase(CommandBase):
"""
Base class for commands that manipulate version.
"""... | pyflu/setuptools/versioning.py | from pyflu.setuptools.base import CommandBase
from pyflu.modules import deep_import
from pyflu.command import run_script
import os
from os.path import join
import tarfile
import tempfile
import shutil
import re
class VersionCommandBase(CommandBase):
"""
Base class for commands that manipulate version.
"""... | 0.466846 | 0.131396 |
import warnings
warnings.simplefilter('ignore',DeprecationWarning)
import os
import sys
from numpy import median, savez
from optparse import OptionParser # Command-line args
import qfed
#---------------------------------------------------------------------
if __name__ == "__main__":
igbp_dir = '/nob... | src/Components/qfed/qfed_l2b.py | import warnings
warnings.simplefilter('ignore',DeprecationWarning)
import os
import sys
from numpy import median, savez
from optparse import OptionParser # Command-line args
import qfed
#---------------------------------------------------------------------
if __name__ == "__main__":
igbp_dir = '/nob... | 0.134747 | 0.091992 |
from __future__ import absolute_import, print_function, unicode_literals
from builtins import range
import Live
from itertools import count
from ...base import EventObject, in_range, product, listens, listens_group
from ..component import Component
from ..control import ButtonControl
from .scene import SceneComponent
... | ableton/v2/control_surface/components/session.py | from __future__ import absolute_import, print_function, unicode_literals
from builtins import range
import Live
from itertools import count
from ...base import EventObject, in_range, product, listens, listens_group
from ..component import Component
from ..control import ButtonControl
from .scene import SceneComponent
... | 0.69181 | 0.167695 |
import argparse
import glob
from os.path import join
from loguru import logger
from tokenizers import CharBPETokenizer
"""
The original BPE tokenizer, as proposed in Sennrich, Haddow and Birch, Neural Machine Translation
of Rare Words with Subword Units. ACL 2016
https://arxiv.org/abs/1508.07909
https://github.com/rse... | scripts/train_char_level_bpe.py | import argparse
import glob
from os.path import join
from loguru import logger
from tokenizers import CharBPETokenizer
"""
The original BPE tokenizer, as proposed in Sennrich, Haddow and Birch, Neural Machine Translation
of Rare Words with Subword Units. ACL 2016
https://arxiv.org/abs/1508.07909
https://github.com/rse... | 0.722821 | 0.861596 |
import logging
import unittest
from datetime import datetime, timezone
from unittest.mock import Mock
import bottle
from external.routes.plugins.auth_plugin import AuthPlugin, EDIT_REPORT_PERMISSION
from shared.routes.plugins import InjectionPlugin
class AuthPluginTest(unittest.TestCase):
"""Unit tests for the... | components/server/tests/external/routes/plugins/test_route_auth_plugin.py |
import logging
import unittest
from datetime import datetime, timezone
from unittest.mock import Mock
import bottle
from external.routes.plugins.auth_plugin import AuthPlugin, EDIT_REPORT_PERMISSION
from shared.routes.plugins import InjectionPlugin
class AuthPluginTest(unittest.TestCase):
"""Unit tests for the... | 0.815453 | 0.266435 |
import matplotlib.pyplot as plt
import numpy as np
from scipy import stats
from statsmodels.tsa.stattools import adfuller, grangercausalitytests, kpss
def metrics(data):
print('\nKpss test: ')
# Stationary around a constant
print(kpss(data, regression='c'))
# Stationary around a trend
print(kpss(d... | forecaster/timeseries.py | import matplotlib.pyplot as plt
import numpy as np
from scipy import stats
from statsmodels.tsa.stattools import adfuller, grangercausalitytests, kpss
def metrics(data):
print('\nKpss test: ')
# Stationary around a constant
print(kpss(data, regression='c'))
# Stationary around a trend
print(kpss(d... | 0.608943 | 0.682687 |
from __future__ import absolute_import
from __future__ import division
from __future__ import print_function
# coding=utf-8
import stylize
import os
import base64
import json
import re
import time
import glob
import shutil
from io import BytesIO
from PIL import Image
# Flask utils
from flask import Flask, redirect,... | server/app_stylize.py | from __future__ import absolute_import
from __future__ import division
from __future__ import print_function
# coding=utf-8
import stylize
import os
import base64
import json
import re
import time
import glob
import shutil
from io import BytesIO
from PIL import Image
# Flask utils
from flask import Flask, redirect,... | 0.399812 | 0.05549 |
import random
import ast
import base64
max_prim_length = 1000000000000
def get_keys_from_file(
private_keys_path = "private_keys.txt",
public_keys_path = "public_keys.txt"
):
public_keys_file = open(public_keys_path, 'r')
e = int(public_keys_file.readline())
n = int(public_keys_file.readline())
... | rsa_implementation.py | import random
import ast
import base64
max_prim_length = 1000000000000
def get_keys_from_file(
private_keys_path = "private_keys.txt",
public_keys_path = "public_keys.txt"
):
public_keys_file = open(public_keys_path, 'r')
e = int(public_keys_file.readline())
n = int(public_keys_file.readline())
... | 0.307774 | 0.288422 |
import tensorflow as tf
import numpy as np
class Reverse(tf.keras.layers.Layer):
def __init__(self, axis, **kwargs):
super().__init__(**kwargs)
self.axis = axis
def call(self, inputs, **kwargs):
return tf.reverse(inputs, self.axis)
class ExpandDims(tf.keras.layers.Layer):
def __in... | ssu_tf_keras/layers.py | import tensorflow as tf
import numpy as np
class Reverse(tf.keras.layers.Layer):
def __init__(self, axis, **kwargs):
super().__init__(**kwargs)
self.axis = axis
def call(self, inputs, **kwargs):
return tf.reverse(inputs, self.axis)
class ExpandDims(tf.keras.layers.Layer):
def __in... | 0.510252 | 0.48749 |
from __future__ import annotations
from spark_auto_mapper_fhir.fhir_types.uri import FhirUri
from spark_auto_mapper_fhir.value_sets.generic_type import GenericTypeCode
from spark_auto_mapper.type_definitions.defined_types import AutoMapperTextInputType
# This file is auto-generated by generate_classes so do not edi... | spark_auto_mapper_fhir/value_sets/property_type.py | from __future__ import annotations
from spark_auto_mapper_fhir.fhir_types.uri import FhirUri
from spark_auto_mapper_fhir.value_sets.generic_type import GenericTypeCode
from spark_auto_mapper.type_definitions.defined_types import AutoMapperTextInputType
# This file is auto-generated by generate_classes so do not edi... | 0.847084 | 0.327184 |
from string import join
import email.Message
import smtplib
from email.MIMEMultipart import MIMEMultipart
from email.MIMEText import MIMEText
from klab.fs.fsio import read_file
class MailServer(object):
def __init__(self, host = None, port = None):
self.host = host
self.port = port
def sendm... | klab/comms/mail.py | from string import join
import email.Message
import smtplib
from email.MIMEMultipart import MIMEMultipart
from email.MIMEText import MIMEText
from klab.fs.fsio import read_file
class MailServer(object):
def __init__(self, host = None, port = None):
self.host = host
self.port = port
def sendm... | 0.14978 | 0.0559 |
import torch
import torch.nn as nn
import tridepth_renderer.cuda.rasterize as rasterize_cuda
from . import vertices_to_faces, rasterize_image
def flip(x, dim):
"""
Flip tensor in specified dimension.
"""
indices = [slice(None)] * x.dim()
indices[dim] = torch.arange(x.size(dim) - 1, -1, -1,
... | tridepth/renderer/renderer.py | import torch
import torch.nn as nn
import tridepth_renderer.cuda.rasterize as rasterize_cuda
from . import vertices_to_faces, rasterize_image
def flip(x, dim):
"""
Flip tensor in specified dimension.
"""
indices = [slice(None)] * x.dim()
indices[dim] = torch.arange(x.size(dim) - 1, -1, -1,
... | 0.942055 | 0.611411 |
import os
import logging
class Yalow:
"""Yet Another LOgging Wrapper
Wraps Python's logging module functionality for the
generic use case of generating and writing to a shared project
log file in the 'root_path/log' directory.
Parameters
----------
root_path : pathlib.Path
Root p... | yalow/__init__.py | import os
import logging
class Yalow:
"""Yet Another LOgging Wrapper
Wraps Python's logging module functionality for the
generic use case of generating and writing to a shared project
log file in the 'root_path/log' directory.
Parameters
----------
root_path : pathlib.Path
Root p... | 0.633637 | 0.227394 |
import torch
from torch import nn
import torch.nn.functional as F
from segment.api import Model
class DoubleBlock(nn.Module):
'''(conv => BN => ReLU) * 2'''
def __init__(self, in_ch, out_ch):
super(DoubleBlock, self).__init__()
self.conv = nn.Sequential(
nn.Conv2d(in_ch, out_ch, ... | segment/ml/models/two_dimensional/unet.py | import torch
from torch import nn
import torch.nn.functional as F
from segment.api import Model
class DoubleBlock(nn.Module):
'''(conv => BN => ReLU) * 2'''
def __init__(self, in_ch, out_ch):
super(DoubleBlock, self).__init__()
self.conv = nn.Sequential(
nn.Conv2d(in_ch, out_ch, ... | 0.954563 | 0.540075 |
from sqlalchemy import Column, Integer, String, Numeric, Text, Boolean, DateTime
from sqlalchemy.orm import relationship
from database import Base
import datetime
class Member(Base):
"""
# general
id :pk
nick_name: (str)short name
full_name: (str)complete name
cur_status: (str)
bio: (text)
join_date: (datetime... | models.py | from sqlalchemy import Column, Integer, String, Numeric, Text, Boolean, DateTime
from sqlalchemy.orm import relationship
from database import Base
import datetime
class Member(Base):
"""
# general
id :pk
nick_name: (str)short name
full_name: (str)complete name
cur_status: (str)
bio: (text)
join_date: (datetime... | 0.319652 | 0.097907 |
from datetime import timedelta
import logging
from pyflume import FlumeData, FlumeDeviceList
import voluptuous as vol
from homeassistant.components.sensor import PLATFORM_SCHEMA
from homeassistant.const import CONF_NAME, CONF_PASSWORD, CONF_USERNAME
import homeassistant.helpers.config_validation as cv
from homeassist... | homeassistant/components/flume/sensor.py | from datetime import timedelta
import logging
from pyflume import FlumeData, FlumeDeviceList
import voluptuous as vol
from homeassistant.components.sensor import PLATFORM_SCHEMA
from homeassistant.const import CONF_NAME, CONF_PASSWORD, CONF_USERNAME
import homeassistant.helpers.config_validation as cv
from homeassist... | 0.629661 | 0.080973 |
import argparse
import time as money
import wrappers.wrapper_CRF as crf_
import wrappers.wrapper_pretrained as pretrained_
import functions
import load_save
from seqeval.metrics import classification_report, f1_score
parser = argparse.ArgumentParser(prog="PROG")
parser.add_argument(
"--config-path",
require... | anelfop/pl_experiment.py | import argparse
import time as money
import wrappers.wrapper_CRF as crf_
import wrappers.wrapper_pretrained as pretrained_
import functions
import load_save
from seqeval.metrics import classification_report, f1_score
parser = argparse.ArgumentParser(prog="PROG")
parser.add_argument(
"--config-path",
require... | 0.39222 | 0.266119 |
import sys, socket, struct
try:
host = sys.argv[1]
port = int(sys.argv[2])
except IndexError:
print "Usage: %s <target> <port>" % sys.argv[0]
print "Example: %s 192.168.0.16 80" % sys.argv[0]
sys.exit(0)
print "[->] Attacking %s:%d get that handler up" % (host,port)
# msfvenom -p windows/shell_reverse_tcp LH... | Personal-Exploits/SyncBreeze Enterprise v10.1.16 - Unauthenticated RCE/sploit-PoC.py |
import sys, socket, struct
try:
host = sys.argv[1]
port = int(sys.argv[2])
except IndexError:
print "Usage: %s <target> <port>" % sys.argv[0]
print "Example: %s 192.168.0.16 80" % sys.argv[0]
sys.exit(0)
print "[->] Attacking %s:%d get that handler up" % (host,port)
# msfvenom -p windows/shell_reverse_tcp LH... | 0.074101 | 0.263801 |
from django.shortcuts import render,redirect,get_object_or_404
from django.contrib.auth.forms import UserCreationForm
from django.http import HttpResponseRedirect,HttpResponse, Http404
from django.contrib.auth import login, authenticate
from django.contrib.auth.decorators import login_required
from django.contrib.auth.... | projectapp/views.py | from django.shortcuts import render,redirect,get_object_or_404
from django.contrib.auth.forms import UserCreationForm
from django.http import HttpResponseRedirect,HttpResponse, Http404
from django.contrib.auth import login, authenticate
from django.contrib.auth.decorators import login_required
from django.contrib.auth.... | 0.394434 | 0.064359 |
import json
import os
import time
from pathlib import Path
import bin.ERRORS as error
data = {1:'name', 2:'session time', 3:'break time', 4:'bonus break time', 5:'long break time'}
version = 'v6.0.0 Alpha'
class Config():
def __init__(self, name='Joe', session_time=50, break_time=10, bonus_break=3, long_break=65):
... | bin/config.py | import json
import os
import time
from pathlib import Path
import bin.ERRORS as error
data = {1:'name', 2:'session time', 3:'break time', 4:'bonus break time', 5:'long break time'}
version = 'v6.0.0 Alpha'
class Config():
def __init__(self, name='Joe', session_time=50, break_time=10, bonus_break=3, long_break=65):
... | 0.068729 | 0.123207 |
import tkinter as tk
from tkinter import ttk
import pyglet
from PIL import Image, ImageTk, ImageFilter, ImageDraw, ImageFont
class Player(tk.Frame):
def __init__(self, root, track='', backup_track='', artist='', album=None,
art=None, playfunc=None, stopfunc=None, nextfunc=None,
... | musictk/player.py | import tkinter as tk
from tkinter import ttk
import pyglet
from PIL import Image, ImageTk, ImageFilter, ImageDraw, ImageFont
class Player(tk.Frame):
def __init__(self, root, track='', backup_track='', artist='', album=None,
art=None, playfunc=None, stopfunc=None, nextfunc=None,
... | 0.54577 | 0.099952 |
from typing import List, Dict, cast
import numpy as np
from ...math.matrix import Matrix
from ...common.config import Config
from ...collision.algorithm.gjk import PointPair
from ...collision.detector import Collsion
from ..body import Body
# FIXME:
def generate_relation(bodya: Body, bodyb: Body) -> int:
# Comb... | TaichiGAME/dynamics/constraint/contact.py | from typing import List, Dict, cast
import numpy as np
from ...math.matrix import Matrix
from ...common.config import Config
from ...collision.algorithm.gjk import PointPair
from ...collision.detector import Collsion
from ..body import Body
# FIXME:
def generate_relation(bodya: Body, bodyb: Body) -> int:
# Comb... | 0.605449 | 0.356055 |
import datetime, glob, os, re, sys
DATE_FORMAT="%Y-%m-%d"
def load_review():
if len(sys.argv) > 1:
fp = sys.argv[1]
current_date = '-'.join(fp.split("/")[-1].split("-")[:3])
current_date = datetime.datetime.strptime(current_date, DATE_FORMAT)
else:
current_date=datetime.date.tod... | budget_summary.py | import datetime, glob, os, re, sys
DATE_FORMAT="%Y-%m-%d"
def load_review():
if len(sys.argv) > 1:
fp = sys.argv[1]
current_date = '-'.join(fp.split("/")[-1].split("-")[:3])
current_date = datetime.datetime.strptime(current_date, DATE_FORMAT)
else:
current_date=datetime.date.tod... | 0.198142 | 0.157622 |
from text_game_map_maker import forms
from text_game_map_maker.qt_auto_form import QtAutoForm
from text_game_map_maker.utils import yesNoDialog, errorDialog
from text_game_maker.tile import tile
from PyQt5 import QtWidgets, QtCore, QtGui
class DoorEditor(QtWidgets.QDialog):
def __init__(self, parent, tileobj):
... | text_game_map_maker/door_editor.py | from text_game_map_maker import forms
from text_game_map_maker.qt_auto_form import QtAutoForm
from text_game_map_maker.utils import yesNoDialog, errorDialog
from text_game_maker.tile import tile
from PyQt5 import QtWidgets, QtCore, QtGui
class DoorEditor(QtWidgets.QDialog):
def __init__(self, parent, tileobj):
... | 0.543348 | 0.070113 |
import sys
import os
from docopt import docopt
from apiclient.http import MediaFileUpload
import core.schedule as schedule
import core.auth as conf_auth
import core.excel_db as excel_db
USAGE = """
Upload the Videos to YouTube
Usage:
upload_yt_videos.py <video_list.xlsx> <video_root_path> [--no-update]
"""
argu... | upload_yt_videos.py | import sys
import os
from docopt import docopt
from apiclient.http import MediaFileUpload
import core.schedule as schedule
import core.auth as conf_auth
import core.excel_db as excel_db
USAGE = """
Upload the Videos to YouTube
Usage:
upload_yt_videos.py <video_list.xlsx> <video_root_path> [--no-update]
"""
argu... | 0.135518 | 0.111193 |
import time
from selenium import webdriver
from selenium.webdriver.chrome.options import Options
from webdriver_manager.chrome import ChromeDriverManager
from data import *
class TestCreateAndDeleteArticle(object):
def setup(self):
browser_options = Options()
browser_options.headless = True
... | test/test_10_creating_article_and_saving_title_and_body.py | import time
from selenium import webdriver
from selenium.webdriver.chrome.options import Options
from webdriver_manager.chrome import ChromeDriverManager
from data import *
class TestCreateAndDeleteArticle(object):
def setup(self):
browser_options = Options()
browser_options.headless = True
... | 0.105239 | 0.059537 |
__author__ = '<NAME>'
"""
This program takes in a sudoku and solves it ,here 0 means not set so add numbers write them down
"""
'''trying the empty board '''
def moves(board, row, column):
"""
used set to i
:param board:
:param row:
:param column:
:return:list -> list of legal moves that the ... | sudoku_solver/Sudoku_test.py | __author__ = '<NAME>'
"""
This program takes in a sudoku and solves it ,here 0 means not set so add numbers write them down
"""
'''trying the empty board '''
def moves(board, row, column):
"""
used set to i
:param board:
:param row:
:param column:
:return:list -> list of legal moves that the ... | 0.374562 | 0.462352 |
import pprint
import re # noqa: F401
import six
class S3ObjectListItem(object):
"""NOTE: This class is auto generated by the swagger code generator program.
Do not edit the class manually.
"""
"""
Attributes:
swagger_types (dict): The key is attribute name
and... | syntropy_sdk/models/s3_object_list_item.py | import pprint
import re # noqa: F401
import six
class S3ObjectListItem(object):
"""NOTE: This class is auto generated by the swagger code generator program.
Do not edit the class manually.
"""
"""
Attributes:
swagger_types (dict): The key is attribute name
and... | 0.653569 | 0.188679 |
import uuid
from django.db import models
from django.conf import settings
# Create your models here.
class Board(models.Model):
name = models.CharField(max_length=50)
super_admin = models.ForeignKey(settings.AUTH_USER_MODEL, on_delete=models.DO_NOTHING, null=True)
user_list = models.ManyToManyField(setting... | Backend/board/models.py | import uuid
from django.db import models
from django.conf import settings
# Create your models here.
class Board(models.Model):
name = models.CharField(max_length=50)
super_admin = models.ForeignKey(settings.AUTH_USER_MODEL, on_delete=models.DO_NOTHING, null=True)
user_list = models.ManyToManyField(setting... | 0.466359 | 0.15925 |
from typing import Iterator
from dagger.dsl.node_output_reference import NodeOutputReference
from dagger.serializer import Serializer
class NodeOutputPartitionUsage:
"""
Represents the usage of a partition from a node output.
An instance of this class is returned whenever an output reference is iterated... | dagger/dsl/node_output_partition_usage.py | from typing import Iterator
from dagger.dsl.node_output_reference import NodeOutputReference
from dagger.serializer import Serializer
class NodeOutputPartitionUsage:
"""
Represents the usage of a partition from a node output.
An instance of this class is returned whenever an output reference is iterated... | 0.947648 | 0.763484 |
import discord
import asyncio
from discord.ext import commands
import aiohttp
class Default(object):
"""Стандартные команды."""
def __init__(self, bot):
self.bot = bot
async def _hastebin_post(self, text):
async with aiohttp.ClientSession() as session:
async with session.... | cogs/default.py |
import discord
import asyncio
from discord.ext import commands
import aiohttp
class Default(object):
"""Стандартные команды."""
def __init__(self, bot):
self.bot = bot
async def _hastebin_post(self, text):
async with aiohttp.ClientSession() as session:
async with session.... | 0.425605 | 0.122287 |
import os,sys
import numpy as np
import yaml
import scipy.integrate as integrate
import matplotlib.pyplot as plt
import math
"""
------------
Parameters
"""
with open('configure.yml','r') as conf_para:
conf_para = yaml.load(conf_para,Loader=yaml.FullLoader)
"""
------------
wavefront_initialize
>> input
pixelsi... | Tomo_sim/propogate.py | import os,sys
import numpy as np
import yaml
import scipy.integrate as integrate
import matplotlib.pyplot as plt
import math
"""
------------
Parameters
"""
with open('configure.yml','r') as conf_para:
conf_para = yaml.load(conf_para,Loader=yaml.FullLoader)
"""
------------
wavefront_initialize
>> input
pixelsi... | 0.575111 | 0.37222 |
from django.apps import AppConfig
import time, logging, os, sys
from watchdog.events import PatternMatchingEventHandler
from watchdog.observers import Observer
logger = logging.getLogger(__name__)
class WatchersConfig(AppConfig):
name = 'watchers'
verbose_name = "Directory Watchers"
if 'runserver' in sy... | watchers/apps.py | from django.apps import AppConfig
import time, logging, os, sys
from watchdog.events import PatternMatchingEventHandler
from watchdog.observers import Observer
logger = logging.getLogger(__name__)
class WatchersConfig(AppConfig):
name = 'watchers'
verbose_name = "Directory Watchers"
if 'runserver' in sy... | 0.221772 | 0.04489 |