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 datetime as dt
from typing import Any, Dict, List, Tuple
import dash
import google.protobuf.json_format as json_format
from dash.dependencies import ALL, Input, Output, State
from dash.exceptions import PreventUpdate
from graph_structures_pb2 import SLI
from .. import (
compute_status,
constants,
c... | ujt/callbacks/graph_callbacks.py | import datetime as dt
from typing import Any, Dict, List, Tuple
import dash
import google.protobuf.json_format as json_format
from dash.dependencies import ALL, Input, Output, State
from dash.exceptions import PreventUpdate
from graph_structures_pb2 import SLI
from .. import (
compute_status,
constants,
c... | 0.705379 | 0.317625 |
from noval import _,GetApp,NewId
import os
import noval.iface as iface
import noval.plugin as plugin
import noval.util.utils as utils
import noval.constants as constants
from noval.project.templatemanager import ProjectTemplateManager
import gittool.gitui as gitui
import noval.consts as consts
import noval.men... | plugins/GitTool/gittool/__init__.py | from noval import _,GetApp,NewId
import os
import noval.iface as iface
import noval.plugin as plugin
import noval.util.utils as utils
import noval.constants as constants
from noval.project.templatemanager import ProjectTemplateManager
import gittool.gitui as gitui
import noval.consts as consts
import noval.men... | 0.175679 | 0.043043 |
import os
import traceback
from selenium import webdriver
from selenium_stealth import stealth
from scraping_the_world.scrapers.webdriver_manager.webdriver_toolkit import WebDriverToolKit
from scraping_the_world.models.querys import add_log
from env import ENV
WEBDRIVERS_PATH = os.path.dirname(os.path.realpath(__fil... | scraping_the_world/scrapers/webdriver_manager/webdriver_manager.py | import os
import traceback
from selenium import webdriver
from selenium_stealth import stealth
from scraping_the_world.scrapers.webdriver_manager.webdriver_toolkit import WebDriverToolKit
from scraping_the_world.models.querys import add_log
from env import ENV
WEBDRIVERS_PATH = os.path.dirname(os.path.realpath(__fil... | 0.435661 | 0.048926 |
import os, sys
sys.path.append(os.path.dirname(__file__))
from Editor_TestClass import BaseClass
class Editor_DisplaySettingsBus_Work(BaseClass):
# Description:
# Tests the Python API from DisplaySettingsPythonFuncs.cpp while the Editor is running
@staticmethod
def test():
import azlmbr.b... | AutomatedTesting/Gem/PythonTests/EditorPythonBindings/tests/Editor_DisplaySettingsBus_Work.py | import os, sys
sys.path.append(os.path.dirname(__file__))
from Editor_TestClass import BaseClass
class Editor_DisplaySettingsBus_Work(BaseClass):
# Description:
# Tests the Python API from DisplaySettingsPythonFuncs.cpp while the Editor is running
@staticmethod
def test():
import azlmbr.b... | 0.327131 | 0.121217 |
import os
from glob import glob
from traits.api import *
import nibabel as nib
from nipype.utils.filemanip import split_filename
from nipype.interfaces.base import traits, isdefined, CommandLine, CommandLineInputSpec,\
TraitedSpec, File, InputMultiPath, OutputMultiPath, BaseInterface, BaseInterfaceInputSpec
fr... | pymialsrtk/interfaces/preprocess.py | import os
from glob import glob
from traits.api import *
import nibabel as nib
from nipype.utils.filemanip import split_filename
from nipype.interfaces.base import traits, isdefined, CommandLine, CommandLineInputSpec,\
TraitedSpec, File, InputMultiPath, OutputMultiPath, BaseInterface, BaseInterfaceInputSpec
fr... | 0.323915 | 0.160069 |
from __future__ import unicode_literals
from django.core.exceptions import ValidationError
from django.db.models import Q
from django.forms import widgets
from django.forms.fields import ChoiceField
from django.forms.models import ModelForm
from django.utils.html import format_html
from django.utils.encoding import fo... | cmsplugin_cascade/bootstrap4/container.py | from __future__ import unicode_literals
from django.core.exceptions import ValidationError
from django.db.models import Q
from django.forms import widgets
from django.forms.fields import ChoiceField
from django.forms.models import ModelForm
from django.utils.html import format_html
from django.utils.encoding import fo... | 0.618204 | 0.092442 |
# imports
import PySide.QtCore as __PySide_QtCore
import Shiboken as __Shiboken
class QIcon(__Shiboken.Object):
# no doc
def actualSize(self, *args, **kwargs): # real signature unknown
pass
def addFile(self, *args, **kwargs): # real signature unknown
pass
def addPixmap(self, *args, ... | resources/dot_PyCharm/system/python_stubs/-762174762/PySide/QtGui/QIcon.py |
# imports
import PySide.QtCore as __PySide_QtCore
import Shiboken as __Shiboken
class QIcon(__Shiboken.Object):
# no doc
def actualSize(self, *args, **kwargs): # real signature unknown
pass
def addFile(self, *args, **kwargs): # real signature unknown
pass
def addPixmap(self, *args, ... | 0.528777 | 0.084833 |
import io
import sys
import json
import shutil
PY2 = sys.version_info[0] == 2
if PY2:
text_type = unicode # NOQA
else:
text_type = str
class Envelope(object):
def __init__(self, headers=None, items=None):
if headers is not None:
headers = dict(headers)
self.headers = headers... | py/sentry_relay/envelope.py | import io
import sys
import json
import shutil
PY2 = sys.version_info[0] == 2
if PY2:
text_type = unicode # NOQA
else:
text_type = str
class Envelope(object):
def __init__(self, headers=None, items=None):
if headers is not None:
headers = dict(headers)
self.headers = headers... | 0.370795 | 0.085633 |
from __future__ import print_function
import telegram
from telegram.ext import MessageHandler, Filters
from textblob import TextBlob
from myTelegramBot.PluginSystem import BasePlugin
from myTelegramBot.libs.gcal import GoogleCalendar
import datetime
class HelloFilter(Filters):
def __init__(self):
super... | myTelegramBot/modules/rac_plugin.py | from __future__ import print_function
import telegram
from telegram.ext import MessageHandler, Filters
from textblob import TextBlob
from myTelegramBot.PluginSystem import BasePlugin
from myTelegramBot.libs.gcal import GoogleCalendar
import datetime
class HelloFilter(Filters):
def __init__(self):
super... | 0.501221 | 0.078819 |
from json import loads, dumps
from uuid import uuid4
from datetime import datetime, timedelta
from flask.sessions import SessionInterface, SessionMixin
from flask_login import _create_identifier
from dataactcore.interfaces.db import GlobalDB
from dataactcore.models.userModel import SessionMap
class LoginSession:
... | dataactbroker/handlers/aws/session.py | from json import loads, dumps
from uuid import uuid4
from datetime import datetime, timedelta
from flask.sessions import SessionInterface, SessionMixin
from flask_login import _create_identifier
from dataactcore.interfaces.db import GlobalDB
from dataactcore.models.userModel import SessionMap
class LoginSession:
... | 0.629433 | 0.231669 |
import requests, re
import csv
from datetime import timedelta, date
import datetime
import os.path
from collections import deque
from average import average
from typhoon import typhoon
from merge import merge
from transToJson import transToJson
import VG
dir = os.path.dirname(os.path.abspath(__file__... | vegetable-price/python/parser/parser.py | import requests, re
import csv
from datetime import timedelta, date
import datetime
import os.path
from collections import deque
from average import average
from typhoon import typhoon
from merge import merge
from transToJson import transToJson
import VG
dir = os.path.dirname(os.path.abspath(__file__... | 0.12412 | 0.065068 |
from .sbaas_base import sbaas_base
from .sbaas_base_query_insert import sbaas_base_query_insert
from .sbaas_base_query_update import sbaas_base_query_update
from .sbaas_base_query_delete import sbaas_base_query_delete
# resources
from io_utilities.base_importData import base_importData
class sbaas_base_i(sbaas_base
... | SBaaS_base/sbaas_base_i.py | from .sbaas_base import sbaas_base
from .sbaas_base_query_insert import sbaas_base_query_insert
from .sbaas_base_query_update import sbaas_base_query_update
from .sbaas_base_query_delete import sbaas_base_query_delete
# resources
from io_utilities.base_importData import base_importData
class sbaas_base_i(sbaas_base
... | 0.290981 | 0.041598 |
import argparse
parser = argparse.ArgumentParser(description="CoViAR")
# Data.
parser.add_argument('--data-name', type=str,
help='dataset name.') #choices=['ucf101', 'hmdb51']
parser.add_argument('--data-root', type=str,
help='root of data directory.')
parser.add_argument('--t... | train_options.py |
import argparse
parser = argparse.ArgumentParser(description="CoViAR")
# Data.
parser.add_argument('--data-name', type=str,
help='dataset name.') #choices=['ucf101', 'hmdb51']
parser.add_argument('--data-root', type=str,
help='root of data directory.')
parser.add_argument('--t... | 0.593609 | 0.072735 |
from schema import Schema, And, Or, Use
import yaml
from pathlib import Path
from io import StringIO
DEFAULT_CONFIG = """\
runtime:
cores_per_node: 1 # Number of cores per node (positive integer)
batch_size: 1 # Size of batches (positive integer)
raven:
annotations: false ... | opensoundscape/config.py | from schema import Schema, And, Or, Use
import yaml
from pathlib import Path
from io import StringIO
DEFAULT_CONFIG = """\
runtime:
cores_per_node: 1 # Number of cores per node (positive integer)
batch_size: 1 # Size of batches (positive integer)
raven:
annotations: false ... | 0.817064 | 0.335609 |
from aws_cdk import (
aws_stepfunctions as sfn,
aws_stepfunctions_tasks as sfn_tasks,
core,
)
class JobPollerStack(core.Stack):
def __init__(self, app: core.App, id: str, **kwargs) -> None:
super().__init__(app, id, **kwargs)
submit_job_activity = sfn.Activity(
self, "Subm... | python/stepfunctions/stepfunctions/stepfunctions_stack.py | from aws_cdk import (
aws_stepfunctions as sfn,
aws_stepfunctions_tasks as sfn_tasks,
core,
)
class JobPollerStack(core.Stack):
def __init__(self, app: core.App, id: str, **kwargs) -> None:
super().__init__(app, id, **kwargs)
submit_job_activity = sfn.Activity(
self, "Subm... | 0.66072 | 0.152568 |
# V1
# https://leetcode.com/problems/peeking-iterator/discuss/123811/Python-solution
class PeekingIterator(object):
def __init__(self, iterator):
"""
Initialize your data structure here.
:type iterator: Iterator
"""
self.next_val = None
self.iterator = iterator
... | leetcode_python/Design/peeking-iterator.py |
# V1
# https://leetcode.com/problems/peeking-iterator/discuss/123811/Python-solution
class PeekingIterator(object):
def __init__(self, iterator):
"""
Initialize your data structure here.
:type iterator: Iterator
"""
self.next_val = None
self.iterator = iterator
... | 0.88894 | 0.142769 |
import numpy as np
__all__ = [
'distance', 'is_close', 'is_same', 'normalize'
]
def distance(p1, p2):
"""
Return the euclidean distance between the two points
parameters
----------
p1 : numpy array
N-array describing the position of p1
p2 : numpy array
N-array describing ... | alloy/math/basic.py | import numpy as np
__all__ = [
'distance', 'is_close', 'is_same', 'normalize'
]
def distance(p1, p2):
"""
Return the euclidean distance between the two points
parameters
----------
p1 : numpy array
N-array describing the position of p1
p2 : numpy array
N-array describing ... | 0.872102 | 0.816113 |
print(" -- Script start -- ")
from brownie import accounts
from .pcat import PCat
# Account names are not important, but they must be unique.
me = accounts[0]
# MT
rudeus_greyart = accounts[1]
eris_whats_her_face = accounts[2]
# TSCOG
seol_jihu = accounts[3]
yeo_soohi = accounts[4]
# TBATE
arthur_lewyin = accounts[... | scripts/main.py | print(" -- Script start -- ")
from brownie import accounts
from .pcat import PCat
# Account names are not important, but they must be unique.
me = accounts[0]
# MT
rudeus_greyart = accounts[1]
eris_whats_her_face = accounts[2]
# TSCOG
seol_jihu = accounts[3]
yeo_soohi = accounts[4]
# TBATE
arthur_lewyin = accounts[... | 0.157914 | 0.124985 |
import arcas
import pandas
def test_setup():
api = arcas.Plos()
assert api.standard == 'http://api.plos.org/search?q='
def test_keys():
api = arcas.Plos()
assert api.keys() == ['url', 'key', 'unique_key', 'title', 'author', 'abstract',
'doi', 'date', 'journal', 'provenance', ... | tests/test_plos.py | import arcas
import pandas
def test_setup():
api = arcas.Plos()
assert api.standard == 'http://api.plos.org/search?q='
def test_keys():
api = arcas.Plos()
assert api.keys() == ['url', 'key', 'unique_key', 'title', 'author', 'abstract',
'doi', 'date', 'journal', 'provenance', ... | 0.595728 | 0.454351 |
import xml.etree.ElementTree as ET
import sys
from html.parser import HTMLParser
class MLStripper(HTMLParser):
def __init__(self):
self.reset()
self.strict = False
self.convert_charrefs = True
self.fed = []
def handle_data(self, d):
self.fed.append(d)
def get_data... | script/parsegoodreads.py | import xml.etree.ElementTree as ET
import sys
from html.parser import HTMLParser
class MLStripper(HTMLParser):
def __init__(self):
self.reset()
self.strict = False
self.convert_charrefs = True
self.fed = []
def handle_data(self, d):
self.fed.append(d)
def get_data... | 0.159054 | 0.134975 |
from __future__ import absolute_import
from __future__ import unicode_literals
from datetime import datetime
import mock
import pytest
from pymysqlreplication.event import GtidEvent
from pymysqlreplication.event import QueryEvent
from replication_handler.components.simple_binlog_stream_reader_wrapper import SimpleBi... | tests/components/simple_binlog_stream_reader_wrapper_test.py | from __future__ import absolute_import
from __future__ import unicode_literals
from datetime import datetime
import mock
import pytest
from pymysqlreplication.event import GtidEvent
from pymysqlreplication.event import QueryEvent
from replication_handler.components.simple_binlog_stream_reader_wrapper import SimpleBi... | 0.644001 | 0.236153 |
import numpy as np
import json
import os
import matplotlib.pyplot as plt
from matplotlib.lines import Line2D
import matplotlib.patches as mpatches
from matplotlib.patches import Patch
from matplotlib.lines import Line2D
pink = '#EC6779'
green = '#288737'
blue = '#4678a8'
yellow = '#CBBA4E'
cyan = '#6BC... | tools/plot_planner_compare.py | import numpy as np
import json
import os
import matplotlib.pyplot as plt
from matplotlib.lines import Line2D
import matplotlib.patches as mpatches
from matplotlib.patches import Patch
from matplotlib.lines import Line2D
pink = '#EC6779'
green = '#288737'
blue = '#4678a8'
yellow = '#CBBA4E'
cyan = '#6BC... | 0.400046 | 0.382776 |
from accelergy.utils import *
class SystemState():
def __init__(self):
self.cc_classes = {}
self.pc_classes = {}
self.arch_spec = None
self.hier_arch_spec = None
self.ccs = {}
self.pcs = {}
self.action_counts = None
self.plug_ins = []
self.ERT ... | accelergy/system_state.py | from accelergy.utils import *
class SystemState():
def __init__(self):
self.cc_classes = {}
self.pc_classes = {}
self.arch_spec = None
self.hier_arch_spec = None
self.ccs = {}
self.pcs = {}
self.action_counts = None
self.plug_ins = []
self.ERT ... | 0.531939 | 0.14624 |
import sys
from PyQt5.QtWidgets import (
QWidget,
QPushButton,
QHBoxLayout,
QVBoxLayout,
QApplication,
QMainWindow,
QAction,
QGridLayout,
QScrollArea,
QLabel,
QListWidget,
QListWidgetItem,
QAbstractItemView,
QLineEdit,
QDateEdit,
QCheckBox
)
from PyQt5.QtG... | main.py | import sys
from PyQt5.QtWidgets import (
QWidget,
QPushButton,
QHBoxLayout,
QVBoxLayout,
QApplication,
QMainWindow,
QAction,
QGridLayout,
QScrollArea,
QLabel,
QListWidget,
QListWidgetItem,
QAbstractItemView,
QLineEdit,
QDateEdit,
QCheckBox
)
from PyQt5.QtG... | 0.197251 | 0.064095 |
from zope import interface, schema
from zope.i18nmessageid import MessageFactory
from zojax.content.feeds.interfaces import IRSS2Feed
from zojax.content.type.interfaces import IItem, IContent
from zojax.content.space.interfaces import IWorkspace, IWorkspaceFactory
from zojax.content.notifications.interfaces import ICo... | src/zojax/blogger/interfaces.py | from zope import interface, schema
from zope.i18nmessageid import MessageFactory
from zojax.content.feeds.interfaces import IRSS2Feed
from zojax.content.type.interfaces import IItem, IContent
from zojax.content.space.interfaces import IWorkspace, IWorkspaceFactory
from zojax.content.notifications.interfaces import ICo... | 0.603114 | 0.148541 |
from datetime import datetime
import numpy as np
import matplotlib.pyplot as plt
import math
import random
from initialize import initcond, neighbors
def sim_parameters():
"""This function defines the initial parameters used in simulations"""
global rows, cols, h, per_cycle, num_cycles
rows = 100
cols... | fastdifgrow/fastdifgrow_main.py | from datetime import datetime
import numpy as np
import matplotlib.pyplot as plt
import math
import random
from initialize import initcond, neighbors
def sim_parameters():
"""This function defines the initial parameters used in simulations"""
global rows, cols, h, per_cycle, num_cycles
rows = 100
cols... | 0.581422 | 0.602442 |
import torch
import torch.nn as nn
import torch.nn.functional as F
import keras
from keras import backend as K
from keras.models import Input, Model
from keras.layers import Conv2D, MaxPooling2D
from keras.layers import Conv2DTranspose, concatenate
K.set_image_data_format('channels_first')
# From https://github.com/... | nn_transfer/test/architectures/unet.py | import torch
import torch.nn as nn
import torch.nn.functional as F
import keras
from keras import backend as K
from keras.models import Input, Model
from keras.layers import Conv2D, MaxPooling2D
from keras.layers import Conv2DTranspose, concatenate
K.set_image_data_format('channels_first')
# From https://github.com/... | 0.951605 | 0.713694 |
import random
import math
class NeuralNetwork:
learning_rate = 0.5
def __init__(self,input_num,hidden_num,output_num,input_hidden_weights=None,
input_hidden_bias=None,hidden_output_weights=None,hidden_output_bias=None):
self.input_num = input_num
# 构建掩藏层
... | bpnn/ref_code/nn.py | import random
import math
class NeuralNetwork:
learning_rate = 0.5
def __init__(self,input_num,hidden_num,output_num,input_hidden_weights=None,
input_hidden_bias=None,hidden_output_weights=None,hidden_output_bias=None):
self.input_num = input_num
# 构建掩藏层
... | 0.388966 | 0.290138 |
from charcoaltoken import CharcoalToken as CT
from unicodegrammars import UnicodeGrammars
def PassThrough(r):
return r
def GetFreeVariable(s, n=1):
r = ""
for _ in range(n):
r += next(filter(lambda c: c not in s + r, "ικλμνξπρςστυφχψωαβγδεζηθ"))
return r
def VerbosifyVariable(c):
return ... | astprocessor.py | from charcoaltoken import CharcoalToken as CT
from unicodegrammars import UnicodeGrammars
def PassThrough(r):
return r
def GetFreeVariable(s, n=1):
r = ""
for _ in range(n):
r += next(filter(lambda c: c not in s + r, "ικλμνξπρςστυφχψωαβγδεζηθ"))
return r
def VerbosifyVariable(c):
return ... | 0.451085 | 0.531331 |
from gtts import gTTS
import speech_recognition as sr
import os
import re
import webbrowser
import smtplib
import requests
from weather import Weather
def talkToMe(audio):
"""speaks audio passed as argument"""
print(audio)
for _ in audio.splitlines():
os.system("echo " + audio)
... | jarvis.py | from gtts import gTTS
import speech_recognition as sr
import os
import re
import webbrowser
import smtplib
import requests
from weather import Weather
def talkToMe(audio):
"""speaks audio passed as argument"""
print(audio)
for _ in audio.splitlines():
os.system("echo " + audio)
... | 0.234056 | 0.076408 |
import numpy as np
from numba import jit
from numba.extending import overload
def moving_average(x, w):
print("moving_av")
return np.convolve(x, np.ones(w), "valid") / w
@jit(nopython=True)
def calculate_age(array):
ret = np.zeros(array.shape)
for i in range(array.shape[0]):
count = 0
... | src/flowrect/simulations/util.py | import numpy as np
from numba import jit
from numba.extending import overload
def moving_average(x, w):
print("moving_av")
return np.convolve(x, np.ones(w), "valid") / w
@jit(nopython=True)
def calculate_age(array):
ret = np.zeros(array.shape)
for i in range(array.shape[0]):
count = 0
... | 0.270962 | 0.563918 |
import hashlib
import hmac
from secrets import token_bytes
from typing import Any, Union
from cryptography.hazmat.primitives import hashes
from cryptography.hazmat.primitives.asymmetric import ec
from cryptography.hazmat.primitives.asymmetric.ec import (
EllipticCurvePrivateKey,
EllipticCurvePublicKey,
)
from ... | pyseto/versions/v3.py | import hashlib
import hmac
from secrets import token_bytes
from typing import Any, Union
from cryptography.hazmat.primitives import hashes
from cryptography.hazmat.primitives.asymmetric import ec
from cryptography.hazmat.primitives.asymmetric.ec import (
EllipticCurvePrivateKey,
EllipticCurvePublicKey,
)
from ... | 0.76708 | 0.27036 |
import sys
import cv2 as cv
import numpy as np
def getGradient(image, sigma):
"""
Gradient magnitude calculation from lecture
Takes in image and sigma
Calculates gradient magnitudes and directions(angles) based on sigma
Returns magnitude and directions
"""
kernelSize = (int(4*sigma+1), int(... | orientation/orientation.py | import sys
import cv2 as cv
import numpy as np
def getGradient(image, sigma):
"""
Gradient magnitude calculation from lecture
Takes in image and sigma
Calculates gradient magnitudes and directions(angles) based on sigma
Returns magnitude and directions
"""
kernelSize = (int(4*sigma+1), int(... | 0.653238 | 0.735475 |
import sys
from fun import public
import pymysql
from settings import config
class DBConnection:
def __init__(self):
self.__conn_dict = config.wk_mysql_default_conn
self.conn = None
self.cursor = None
def connect(self, cursor=pymysql.cursors.DictCursor):
# 创建数据库连接
... | auto/wpt_interface_test/fun/wk_db_server.py |
import sys
from fun import public
import pymysql
from settings import config
class DBConnection:
def __init__(self):
self.__conn_dict = config.wk_mysql_default_conn
self.conn = None
self.cursor = None
def connect(self, cursor=pymysql.cursors.DictCursor):
# 创建数据库连接
... | 0.177775 | 0.137504 |
import pandas as pd
import psycopg2
import os
from dotenv import load_dotenv
load_dotenv()
USER = os.getenv('USER')
PASSWORD = os.getenv('PASSWORD')
df_titanic = pd.read_csv('titanic.csv')
# get columns names for PostGreSQL database
columns = ['Survived', 'Pclass', 'Name', 'Sex', 'Age', 'Siblings/Spouses Aboard',
... | module2-sql-for-analysis/assignment/insert_titanic.py | import pandas as pd
import psycopg2
import os
from dotenv import load_dotenv
load_dotenv()
USER = os.getenv('USER')
PASSWORD = os.getenv('PASSWORD')
df_titanic = pd.read_csv('titanic.csv')
# get columns names for PostGreSQL database
columns = ['Survived', 'Pclass', 'Name', 'Sex', 'Age', 'Siblings/Spouses Aboard',
... | 0.135146 | 0.132908 |
import argparse
import pickle
import numpy as np
import pandas as pd
from sklearn import svm
from sklearn.model_selection import cross_validate
from definitions import TISSUES
# python -u 05_01_svms_communities.py --tissue_num NUM | tee outputs/output_05_01_NUM.txt
def calculate_svm(tissue_name):
corr_mat = p... | 05_01_svms_communities.py | import argparse
import pickle
import numpy as np
import pandas as pd
from sklearn import svm
from sklearn.model_selection import cross_validate
from definitions import TISSUES
# python -u 05_01_svms_communities.py --tissue_num NUM | tee outputs/output_05_01_NUM.txt
def calculate_svm(tissue_name):
corr_mat = p... | 0.486332 | 0.280486 |
import mysql.connector
import csv
import sys
import boto3
from messytables import CSVTableSet, type_guess, \
types_processor, headers_guess, headers_processor, \
offset_processor, any_tableset
# A table set is a collection of tables:
def csvParse(csv_file_path):
fh = open(csv_file_path, 'rb')
# Load a file... | import.py | import mysql.connector
import csv
import sys
import boto3
from messytables import CSVTableSet, type_guess, \
types_processor, headers_guess, headers_processor, \
offset_processor, any_tableset
# A table set is a collection of tables:
def csvParse(csv_file_path):
fh = open(csv_file_path, 'rb')
# Load a file... | 0.257298 | 0.152001 |
import string
import adabas
from adabas.api import *
from adabas.datamap import *
from adabas.dump import *
DBID=8;FNR=11 # Employees file mf
#DBID=12;FNR=11 # Employees file pcmm2
STARTISN=0
RCOUNT=1100
MULTIFETCH=8 # number of records per call: MULTI FETCH if > 1
USEACBX=1
# define the mapping of data in record ... | Adabas/demo/Emptel/EmptelReadByDescriptorMF.py |
import string
import adabas
from adabas.api import *
from adabas.datamap import *
from adabas.dump import *
DBID=8;FNR=11 # Employees file mf
#DBID=12;FNR=11 # Employees file pcmm2
STARTISN=0
RCOUNT=1100
MULTIFETCH=8 # number of records per call: MULTI FETCH if > 1
USEACBX=1
# define the mapping of data in record ... | 0.199971 | 0.060474 |
import networkx as nx
import numpy as np
from molreps.methods.geo_npy import add_edges_reverse_indices
# Rdkit
try:
import rdkit
import rdkit.Chem.Descriptors
import rdkit.Chem.AllChem
MOLGRAPH_RDKIT_AVAILABLE = True
from molreps.methods.mol_rdkit import rdkit_atom_list, rdkit_bond_list, ... | molreps/graph.py | import networkx as nx
import numpy as np
from molreps.methods.geo_npy import add_edges_reverse_indices
# Rdkit
try:
import rdkit
import rdkit.Chem.Descriptors
import rdkit.Chem.AllChem
MOLGRAPH_RDKIT_AVAILABLE = True
from molreps.methods.mol_rdkit import rdkit_atom_list, rdkit_bond_list, ... | 0.575111 | 0.367157 |
import os
import yaml
from pocs.utils.database import PanMongo
from pocs.utils.logger import get_root_logger
from pocs.utils.messaging import PanMessaging
from pocs.utils.rs232 import SerialData
from . import load_config
class ArduinoSerialMonitor(object):
"""
Monitors the serial lines and tries to par... | peas/sensors.py | import os
import yaml
from pocs.utils.database import PanMongo
from pocs.utils.logger import get_root_logger
from pocs.utils.messaging import PanMessaging
from pocs.utils.rs232 import SerialData
from . import load_config
class ArduinoSerialMonitor(object):
"""
Monitors the serial lines and tries to par... | 0.573081 | 0.288851 |
import importlib
from inspect import getmembers
from pathlib import Path
import gym
def _get_envs(foldername=None, env_prefix=None, allow_list=None):
"""A helper function to get all environments in a folder.
Example usage:
_get_envs(foldername=None, env_prefix=None)
_get_envs(foldername='con... | ngym_shaping/envs/registration.py | import importlib
from inspect import getmembers
from pathlib import Path
import gym
def _get_envs(foldername=None, env_prefix=None, allow_list=None):
"""A helper function to get all environments in a folder.
Example usage:
_get_envs(foldername=None, env_prefix=None)
_get_envs(foldername='con... | 0.581065 | 0.209227 |
from unittest.mock import patch
from django.test import TestCase
from django.contrib.auth import get_user_model
from core import models
def sample_user(email='<EMAIL>', password='<PASSWORD>'):
"""Create a sample user"""
return get_user_model().objects.create_user(email, password)
class ModelTests(TestCase... | app/core/tests/test_models.py | from unittest.mock import patch
from django.test import TestCase
from django.contrib.auth import get_user_model
from core import models
def sample_user(email='<EMAIL>', password='<PASSWORD>'):
"""Create a sample user"""
return get_user_model().objects.create_user(email, password)
class ModelTests(TestCase... | 0.72027 | 0.38523 |
import unittest
from datetime import datetime
import numpy as np
from dateutil.tz import tzlocal
from nwbwidgets.utils.units import get_min_spike_time, align_by_trials, align_by_time_intervals
from pynwb import NWBFile
from pynwb.epoch import TimeIntervals
class ShowPSTHTestCase(unittest.TestCase):
def setUp(se... | nwbwidgets/test/test_utils_units.py | import unittest
from datetime import datetime
import numpy as np
from dateutil.tz import tzlocal
from nwbwidgets.utils.units import get_min_spike_time, align_by_trials, align_by_time_intervals
from pynwb import NWBFile
from pynwb.epoch import TimeIntervals
class ShowPSTHTestCase(unittest.TestCase):
def setUp(se... | 0.59514 | 0.436142 |
from openprocurement_client.exceptions import (
ResourceNotFound,
)
from openprocurement.caravan.observers.base_observer import (
BaseObserverObservable,
ObserverObservableWithClient,
)
from openprocurement.caravan.observers.constants import (
CONTRACT_STATUS_MAPPING,
LOT_CONTRACT_TERMINAL_STATUSES,... | openprocurement/caravan/observers/lot.py | from openprocurement_client.exceptions import (
ResourceNotFound,
)
from openprocurement.caravan.observers.base_observer import (
BaseObserverObservable,
ObserverObservableWithClient,
)
from openprocurement.caravan.observers.constants import (
CONTRACT_STATUS_MAPPING,
LOT_CONTRACT_TERMINAL_STATUSES,... | 0.446495 | 0.085939 |
import os
basedir = os.path.abspath(os.path.dirname(__file__))
VERSION = '0.1'
URL_PREFIX_VERSION = '/api'
GEO_FILE = 'logtoes/geocity/GeoLiteCity.dat'
HOST = 'localhost'
PORT = 5555
DEBUG = True
BRANCH = 'master'
TRAP_HTTP_EXCEPTIONS = True
TRAP_BAD_REQUEST_ERRORS = True
JSONIFY_PRETTYPRINT_REGULAR = True
ERROR_4... | logtoes/default_settings.py | import os
basedir = os.path.abspath(os.path.dirname(__file__))
VERSION = '0.1'
URL_PREFIX_VERSION = '/api'
GEO_FILE = 'logtoes/geocity/GeoLiteCity.dat'
HOST = 'localhost'
PORT = 5555
DEBUG = True
BRANCH = 'master'
TRAP_HTTP_EXCEPTIONS = True
TRAP_BAD_REQUEST_ERRORS = True
JSONIFY_PRETTYPRINT_REGULAR = True
ERROR_4... | 0.164416 | 0.149097 |
import os
import pytest
import six
from pytest import raises
from kipoi.specs import DataLoaderDescription, example_kwargs, RemoteFile
from related import from_yaml
# Class to test
CLS = DataLoaderDescription
# common header
inp_targ = """
"""
GOOD_EXAMPLES = ["""
type: Dataset
defined_as: dataloader.py::SeqDistData... | tests/specs/parsing/test_027_parsing_DataLoaderDescription.py | import os
import pytest
import six
from pytest import raises
from kipoi.specs import DataLoaderDescription, example_kwargs, RemoteFile
from related import from_yaml
# Class to test
CLS = DataLoaderDescription
# common header
inp_targ = """
"""
GOOD_EXAMPLES = ["""
type: Dataset
defined_as: dataloader.py::SeqDistData... | 0.729327 | 0.458106 |
import os
from anycurve import losscurve
class a2v_curve():
def __init__(self, cfg):
self.cfg = cfg
self.curve = self.setup()
def setup(self):
loss_curve_dir = os.path.join(self.cfg.LOG_DIR, 'loss_curve_db')
loss_curve = losscurve(db_path=loss_curve_dir, db_name='d... | activity2vec/ult/visualize.py | import os
from anycurve import losscurve
class a2v_curve():
def __init__(self, cfg):
self.cfg = cfg
self.curve = self.setup()
def setup(self):
loss_curve_dir = os.path.join(self.cfg.LOG_DIR, 'loss_curve_db')
loss_curve = losscurve(db_path=loss_curve_dir, db_name='d... | 0.818338 | 0.084531 |
import socket
import select
import queue as Queue
from request import Request
from response import Response, DefaultResponse
class Server:
inputs = []
outputs = []
messages = {}
routes = {}
donotkill = False
def __init__(self,port=2145):
self.sock = socket.socket(socket.AF_INET,s... | server.py | import socket
import select
import queue as Queue
from request import Request
from response import Response, DefaultResponse
class Server:
inputs = []
outputs = []
messages = {}
routes = {}
donotkill = False
def __init__(self,port=2145):
self.sock = socket.socket(socket.AF_INET,s... | 0.234582 | 0.059156 |
import json
import sys
import portalocker
from bot import utils
default_config = {
"general": {
"language": "en",
"cache_file_name": "TTMediaBotCache.dat",
"blocked_commands": [],
"send_channel_messages": True,
"delete_uploaded_files_after": 300,
"time_format": r"%... | bot/config.py | import json
import sys
import portalocker
from bot import utils
default_config = {
"general": {
"language": "en",
"cache_file_name": "TTMediaBotCache.dat",
"blocked_commands": [],
"send_channel_messages": True,
"delete_uploaded_files_after": 300,
"time_format": r"%... | 0.125159 | 0.23688 |
from kivy.factory import Factory
from kivy.properties import NumericProperty, BooleanProperty
from kivy.uix.boxlayout import BoxLayout
from kivy.uix.label import Label
from cobiv.modules.core.component import Component
class StatusLabel(Component, Label):
def __init__(self, **kwargs):
super(StatusLabel, ... | cobiv/modules/hud_components/sidebar/statusbar.py | from kivy.factory import Factory
from kivy.properties import NumericProperty, BooleanProperty
from kivy.uix.boxlayout import BoxLayout
from kivy.uix.label import Label
from cobiv.modules.core.component import Component
class StatusLabel(Component, Label):
def __init__(self, **kwargs):
super(StatusLabel, ... | 0.61659 | 0.081374 |
import tempfile
import numpy as np
from numpy import count_nonzero
import os
def computeBias(Xvar,Yvar,sampling_cnf, sampling_weights_y_1, sampling_weights_y_0, inputfile_name, SkolemKnown, args):
samples_biased_one = generatesample( args, 500, sampling_cnf + sampling_weights_y_1, inputfile_name, 1)
samples_biased_... | src/generateSamples.py | import tempfile
import numpy as np
from numpy import count_nonzero
import os
def computeBias(Xvar,Yvar,sampling_cnf, sampling_weights_y_1, sampling_weights_y_0, inputfile_name, SkolemKnown, args):
samples_biased_one = generatesample( args, 500, sampling_cnf + sampling_weights_y_1, inputfile_name, 1)
samples_biased_... | 0.185099 | 0.281603 |
from __future__ import annotations
from imports import k8s
from cdk8s import Chart
from kubeasy_sdk.container import Container
from kubeasy_sdk.utils.collections.containers import Containers
from kubeasy_sdk.utils.resource import Rendered
from kubeasy_sdk.volume import Volume
from kubeasy_sdk.utils.collections.volumes... | kubeasy_sdk/deployment.py | from __future__ import annotations
from imports import k8s
from cdk8s import Chart
from kubeasy_sdk.container import Container
from kubeasy_sdk.utils.collections.containers import Containers
from kubeasy_sdk.utils.resource import Rendered
from kubeasy_sdk.volume import Volume
from kubeasy_sdk.utils.collections.volumes... | 0.773388 | 0.257993 |
from ducktape.tests.test import Test
from kafkatest.services.zookeeper import ZookeeperService
from kafkatest.services.kafka import KafkaService
from kafkatest.services.kafka.version import LATEST_0_8_2, TRUNK
from kafkatest.services.verifiable_producer import VerifiableProducer
from kafkatest.services.console_consum... | tests/kafkatest/tests/compatibility_test.py |
from ducktape.tests.test import Test
from kafkatest.services.zookeeper import ZookeeperService
from kafkatest.services.kafka import KafkaService
from kafkatest.services.kafka.version import LATEST_0_8_2, TRUNK
from kafkatest.services.verifiable_producer import VerifiableProducer
from kafkatest.services.console_consum... | 0.677367 | 0.23268 |
import torch
from torch import nn
from .attention import CustomMultiHeadAttention
from .blocks import PositionwiseFeedForward, CustomLayerNorm
from .position_layers import PositionEncoding
class CustomEncoderLayer(nn.Module):
def __init__(self, dim, n_head, ffn_hidden=None, dropout=0.0):
"""
Encod... | modules/encoder.py | import torch
from torch import nn
from .attention import CustomMultiHeadAttention
from .blocks import PositionwiseFeedForward, CustomLayerNorm
from .position_layers import PositionEncoding
class CustomEncoderLayer(nn.Module):
def __init__(self, dim, n_head, ffn_hidden=None, dropout=0.0):
"""
Encod... | 0.957308 | 0.340293 |
import logging
from django.db import models
from jsonfield import JSONField
from ...bases.metadata.models import BaseListingItemRelation
logger = logging.getLogger(__name__)
class EmbeddedInfo(models.Model):
path = models.CharField(max_length=500)
query_key = models.CharField(max_length=50)
index = mo... | tridentstream/metadata/embedded/models.py | import logging
from django.db import models
from jsonfield import JSONField
from ...bases.metadata.models import BaseListingItemRelation
logger = logging.getLogger(__name__)
class EmbeddedInfo(models.Model):
path = models.CharField(max_length=500)
query_key = models.CharField(max_length=50)
index = mo... | 0.494629 | 0.20458 |
import sys
_b=sys.version_info[0]<3 and (lambda x:x) or (lambda x:x.encode('latin1'))
from google.protobuf import descriptor as _descriptor
from google.protobuf import message as _message
from google.protobuf import reflection as _reflection
from google.protobuf import symbol_database as _symbol_database
from google.p... | src/tt_protocol/tt_protocol/protocol/effects_pb2.py |
import sys
_b=sys.version_info[0]<3 and (lambda x:x) or (lambda x:x.encode('latin1'))
from google.protobuf import descriptor as _descriptor
from google.protobuf import message as _message
from google.protobuf import reflection as _reflection
from google.protobuf import symbol_database as _symbol_database
from google.p... | 0.204978 | 0.17749 |
__all__ = ['RetinaNetModule', 'save_final']
# Cell
import json, os, requests, sys, tarfile
import matplotlib.pyplot as plt
import matplotlib.colors as mcolors
import numpy as np
import pickle
import random
from collections import defaultdict
from functools import reduce
from IPython.utils import io
from pathlib impo... | mcbbox/subcoco_retnet_lightning.py |
__all__ = ['RetinaNetModule', 'save_final']
# Cell
import json, os, requests, sys, tarfile
import matplotlib.pyplot as plt
import matplotlib.colors as mcolors
import numpy as np
import pickle
import random
from collections import defaultdict
from functools import reduce
from IPython.utils import io
from pathlib impo... | 0.705075 | 0.181717 |
import numpy as np
import pandas as pd
from statsmodels.tsa.stattools import coint
import matplotlib.pyplot as plt
# Set a seed value to make the experience reproducible
np.random.seed(123)
import pandas as pd
pd.set_option('display.max_rows', 500)
pd.set_option('display.max_columns', 500)
pd.set_option('display.widt... | Chapter4/ch4_pairs_correlation_real_symbol.py | import numpy as np
import pandas as pd
from statsmodels.tsa.stattools import coint
import matplotlib.pyplot as plt
# Set a seed value to make the experience reproducible
np.random.seed(123)
import pandas as pd
pd.set_option('display.max_rows', 500)
pd.set_option('display.max_columns', 500)
pd.set_option('display.widt... | 0.190573 | 0.519582 |
import gym
import numpy as np
from typing import Callable
from skdecide.hub.domain.gym import DeterministicGymDomain, GymWidthDomain, GymDiscreteActionDomain
from skdecide.hub.solver.riw import RIW
from skdecide.utils import rollout
ENV_NAME = 'CartPole-v0'
HORIZON = 200
class D(DeterministicGymDomain, GymWidthDom... | examples/riw_gym_solver.py |
import gym
import numpy as np
from typing import Callable
from skdecide.hub.domain.gym import DeterministicGymDomain, GymWidthDomain, GymDiscreteActionDomain
from skdecide.hub.solver.riw import RIW
from skdecide.utils import rollout
ENV_NAME = 'CartPole-v0'
HORIZON = 200
class D(DeterministicGymDomain, GymWidthDom... | 0.932615 | 0.487063 |
import os
import pytest
import shutil
from flexmock import flexmock
from pathlib import Path
from container_workflow_tool.cli import ImageRebuilder
class TestDistgit(object):
def setup_method(self):
self.component = 's2i-base'
self.ir = ImageRebuilder('Testing')
self.ir.set_config('def... | tests/test_distgit.py |
import os
import pytest
import shutil
from flexmock import flexmock
from pathlib import Path
from container_workflow_tool.cli import ImageRebuilder
class TestDistgit(object):
def setup_method(self):
self.component = 's2i-base'
self.ir = ImageRebuilder('Testing')
self.ir.set_config('def... | 0.326057 | 0.246137 |
import database
import wst
from game.player import Player
from random import randint, choice
abc = 'ABCDEFGHJKLMNPQRSTUVWXYZ123456789'
class Round():
def __init__(self, game_type):
self.type = game_type # 1-random 0-code
self.players_list = []
self.state = 0 # 0-wait for players #1-pl... | server/game/round.py | import database
import wst
from game.player import Player
from random import randint, choice
abc = 'ABCDEFGHJKLMNPQRSTUVWXYZ123456789'
class Round():
def __init__(self, game_type):
self.type = game_type # 1-random 0-code
self.players_list = []
self.state = 0 # 0-wait for players #1-pl... | 0.310904 | 0.271122 |
import codecs
import json
import os
import re
import sys
#---------------------------
# [Required] Script Information
#---------------------------
ScriptName = "Spam Parameter"
Website = "https://www.twitch.tv/EncryptedThoughts"
Description = "Parameter ($spam) to be used in custom commands that will duplicate and s... | SpamParameter_StreamlabsSystem.py | import codecs
import json
import os
import re
import sys
#---------------------------
# [Required] Script Information
#---------------------------
ScriptName = "Spam Parameter"
Website = "https://www.twitch.tv/EncryptedThoughts"
Description = "Parameter ($spam) to be used in custom commands that will duplicate and s... | 0.238284 | 0.104523 |
import os.path as osp
import torch
import mmcv
import cv2
from mmcv.runner.hooks import HOOKS, Hook
from mmcv.runner import master_only
from mmdet.core.utils import tensor2imgs
from mmdet.utils.det3d import box_np_ops
import numpy as np
def imshow_3d_det_bboxes(img,
corners,
... | mmdet/core/utils/debug_utils.py | import os.path as osp
import torch
import mmcv
import cv2
from mmcv.runner.hooks import HOOKS, Hook
from mmcv.runner import master_only
from mmdet.core.utils import tensor2imgs
from mmdet.utils.det3d import box_np_ops
import numpy as np
def imshow_3d_det_bboxes(img,
corners,
... | 0.766206 | 0.506469 |
from tornado import web, gen
from docker.errors import NotFound
from jupyterhub.handlers.base import BaseHandler
from IPython.html.utils import url_path_join
from tornado.httputil import url_concat
from tornado.httpclient import HTTPRequest, AsyncHTTPClient
import json
import re
@gen.coroutine
def _fork_github_repo(... | everware/home_handler.py | from tornado import web, gen
from docker.errors import NotFound
from jupyterhub.handlers.base import BaseHandler
from IPython.html.utils import url_path_join
from tornado.httputil import url_concat
from tornado.httpclient import HTTPRequest, AsyncHTTPClient
import json
import re
@gen.coroutine
def _fork_github_repo(... | 0.355439 | 0.061876 |
from django.shortcuts import render, redirect
from django.views.generic import FormView, TemplateView
from django.urls import reverse, reverse_lazy
from django.db import transaction
from django.utils.translation import ugettext_lazy as _
from django.contrib.auth import get_user_model, login
from django.contrib.auth.tok... | registration/views.py | from django.shortcuts import render, redirect
from django.views.generic import FormView, TemplateView
from django.urls import reverse, reverse_lazy
from django.db import transaction
from django.utils.translation import ugettext_lazy as _
from django.contrib.auth import get_user_model, login
from django.contrib.auth.tok... | 0.419767 | 0.054904 |
from tests.infrastructure.test_utils import parse_local
from tests.parser.test_method_call_parsing import validate_method_call
from thinglang.lexer.values.identifier import Identifier
from thinglang.lexer.values.inline_text import InlineString
from thinglang.lexer.values.numeric import NumericValue
from thinglang.parse... | tests/parser/test_assignment_operation_parsing.py | from tests.infrastructure.test_utils import parse_local
from tests.parser.test_method_call_parsing import validate_method_call
from thinglang.lexer.values.identifier import Identifier
from thinglang.lexer.values.inline_text import InlineString
from thinglang.lexer.values.numeric import NumericValue
from thinglang.parse... | 0.73029 | 0.622201 |
import pandas as pd
import numpy as np
from sklearn import svm
from sklearn import model_selection
from sklearn.model_selection import learning_curve
from sklearn.ensemble import GradientBoostingRegressor
from sklearn.ensemble import RandomForestRegressor
from sklearn.model_selection import cross_val_score
from skle... | models/tunning.py | import pandas as pd
import numpy as np
from sklearn import svm
from sklearn import model_selection
from sklearn.model_selection import learning_curve
from sklearn.ensemble import GradientBoostingRegressor
from sklearn.ensemble import RandomForestRegressor
from sklearn.model_selection import cross_val_score
from skle... | 0.463201 | 0.479138 |
import collections
from typing import Callable, Optional, Tuple
import d4rl
import gym
import numpy as np
from rjax.datasets.d4rl.utils import (get_preprocessing_fn,
sequence_dataset_iter)
from rjax.datasets.dataset import Dataset
Batch = collections.namedtuple(
'Batch',
... | rjax/datasets/d4rl/sequence_dataset.py | import collections
from typing import Callable, Optional, Tuple
import d4rl
import gym
import numpy as np
from rjax.datasets.d4rl.utils import (get_preprocessing_fn,
sequence_dataset_iter)
from rjax.datasets.dataset import Dataset
Batch = collections.namedtuple(
'Batch',
... | 0.832679 | 0.50653 |
from csrv.model.actions import subroutines
from csrv.model.actions.access_card import AccessCard
from csrv.model.actions.action import Action
from csrv.model.actions.advance_card import AdvanceCard
from csrv.model.actions.ai_break_subroutine import AiBreakSubroutine
from csrv.model.actions.boost_breaker_strength impor... | csrv/model/actions/__init__.py | from csrv.model.actions import subroutines
from csrv.model.actions.access_card import AccessCard
from csrv.model.actions.action import Action
from csrv.model.actions.advance_card import AdvanceCard
from csrv.model.actions.ai_break_subroutine import AiBreakSubroutine
from csrv.model.actions.boost_breaker_strength impor... | 0.522689 | 0.038125 |
from collections import namedtuple
from karbor.common import constants
from karbor import exception
from karbor.services.protection import graph
from oslo_log import log as logging
LOG = logging.getLogger(__name__)
HOOKS = (
HOOK_PRE_BEGIN,
HOOK_PRE_FINISH,
HOOK_MAIN,
HOOK_COMPLETE
) = (
'on_pre... | karbor/services/protection/resource_flow.py | from collections import namedtuple
from karbor.common import constants
from karbor import exception
from karbor.services.protection import graph
from oslo_log import log as logging
LOG = logging.getLogger(__name__)
HOOKS = (
HOOK_PRE_BEGIN,
HOOK_PRE_FINISH,
HOOK_MAIN,
HOOK_COMPLETE
) = (
'on_pre... | 0.596903 | 0.159087 |
import os
import pytest
import sqlalchemy as sa
from webtest import TestApp as WebTestApp
from zope.interface import implementer
from zope.interface.verify import verifyObject
from ensign import BinaryFlag
from ensign._interfaces import IStorage
from ensign._storage import DefaultStorage
from ensign.api import mai... | tests/conftest.py |
import os
import pytest
import sqlalchemy as sa
from webtest import TestApp as WebTestApp
from zope.interface import implementer
from zope.interface.verify import verifyObject
from ensign import BinaryFlag
from ensign._interfaces import IStorage
from ensign._storage import DefaultStorage
from ensign.api import mai... | 0.641422 | 0.390185 |
from dataclasses import dataclass
import numpy as np
import matplotlib.pyplot as plt
import math
import seaborn as sns
from tarpan.shared.info_path import InfoPath, get_info_path
from tarpan.shared.summary import SummaryParams, sample_summary
from tarpan.shared.param_names import filter_param_names
@dataclass
class ... | tarpan/shared/histogram.py |
from dataclasses import dataclass
import numpy as np
import matplotlib.pyplot as plt
import math
import seaborn as sns
from tarpan.shared.info_path import InfoPath, get_info_path
from tarpan.shared.summary import SummaryParams, sample_summary
from tarpan.shared.param_names import filter_param_names
@dataclass
class ... | 0.873822 | 0.620162 |
import logging
import click
import runez
from runez.pyenv import PythonDepot, PythonSpec
from runez.render import PrettyTable
from portable_python import BuildSetup, PPG
from portable_python.inspector import LibAutoCorrect, PythonInspector
LOG = logging.getLogger(__name__)
@runez.click.group()
@runez.click.versio... | src/portable_python/cli.py | import logging
import click
import runez
from runez.pyenv import PythonDepot, PythonSpec
from runez.render import PrettyTable
from portable_python import BuildSetup, PPG
from portable_python.inspector import LibAutoCorrect, PythonInspector
LOG = logging.getLogger(__name__)
@runez.click.group()
@runez.click.versio... | 0.382603 | 0.089137 |
from scapy.all import *
from colorama import Fore, init
import argparse
import sys
init()
parse = argparse.ArgumentParser()
parse.add_argument("-r","--range",help="Range to scan or spoof")
parse.add_argument("-g","--gateway",help="Gatewat")
parse = parse.parse_args()
def get_mac(gateway):
arp_layer = ARP(pdst=g... | spoof.py |
from scapy.all import *
from colorama import Fore, init
import argparse
import sys
init()
parse = argparse.ArgumentParser()
parse.add_argument("-r","--range",help="Range to scan or spoof")
parse.add_argument("-g","--gateway",help="Gatewat")
parse = parse.parse_args()
def get_mac(gateway):
arp_layer = ARP(pdst=g... | 0.287068 | 0.129155 |
import copy
import uuid
from collections import OrderedDict
from unittest import mock
import unittest
from tethys_gizmos.gizmo_options import MVLayer
from tethysext.atcore.services.model_database import ModelDatabase
from tethysext.atcore.services.model_db_spatial_manager import ModelDBSpatialManager
from tethysext.atc... | tethysext/atcore/tests/unit_tests/services/map_manager.py | import copy
import uuid
from collections import OrderedDict
from unittest import mock
import unittest
from tethys_gizmos.gizmo_options import MVLayer
from tethysext.atcore.services.model_database import ModelDatabase
from tethysext.atcore.services.model_db_spatial_manager import ModelDBSpatialManager
from tethysext.atc... | 0.673084 | 0.281677 |
from __future__ import unicode_literals
import pytest
from libweasyl.test.common import datadir
from libweasyl import images, media
def test_fetch_or_create_disk_media_item(staticdir, db):
"""
``MediaItem.fetch_or_create`` by default creates a disk media item,
populates its attributes, and stores the fi... | libweasyl/libweasyl/test/test_media.py | from __future__ import unicode_literals
import pytest
from libweasyl.test.common import datadir
from libweasyl import images, media
def test_fetch_or_create_disk_media_item(staticdir, db):
"""
``MediaItem.fetch_or_create`` by default creates a disk media item,
populates its attributes, and stores the fi... | 0.64579 | 0.451871 |
from rest_framework import status
import json
from authors.apps.articles.helpers import get_time_to_read_article
from authors.apps.articles.tests.base_tests import BaseTest, API_Reverse
from authors.apps.articles.models import ArticlesModel
class ArticleTests(BaseTest):
def test_anyone_can_get_articles(self):
... | authors/apps/articles/tests/test_articles.py | from rest_framework import status
import json
from authors.apps.articles.helpers import get_time_to_read_article
from authors.apps.articles.tests.base_tests import BaseTest, API_Reverse
from authors.apps.articles.models import ArticlesModel
class ArticleTests(BaseTest):
def test_anyone_can_get_articles(self):
... | 0.55652 | 0.180594 |
from django.test import TestCase
from guardian.shortcuts import get_anonymous_user
from authentik.lib.generators import generate_key
from authentik.policies.password.models import PasswordPolicy
from authentik.policies.types import PolicyRequest, PolicyResult
class TestPasswordPolicy(TestCase):
"""Test Password ... | authentik/policies/password/tests/test_policy.py | from django.test import TestCase
from guardian.shortcuts import get_anonymous_user
from authentik.lib.generators import generate_key
from authentik.policies.password.models import PasswordPolicy
from authentik.policies.types import PolicyRequest, PolicyResult
class TestPasswordPolicy(TestCase):
"""Test Password ... | 0.500244 | 0.315532 |
from mpd import MPDClient
from MopidyConfig import MopidyConfig
import RPi.GPIO as gpio
import os.path
import time
import json
import logging
import threading
RED = [True, False, False]
GREEN = [False, True, False]
BLUE = [False, False, True]
YELLOW = [True, True, False]
WHITE = [True, True, True]
clas... | MopidyClient.py | from mpd import MPDClient
from MopidyConfig import MopidyConfig
import RPi.GPIO as gpio
import os.path
import time
import json
import logging
import threading
RED = [True, False, False]
GREEN = [False, True, False]
BLUE = [False, False, True]
YELLOW = [True, True, False]
WHITE = [True, True, True]
clas... | 0.121204 | 0.055132 |
from datetime import date, datetime
from unittest import mock
import pytz
from django.conf import settings
from django.core import mail
from django.core.exceptions import ValidationError
from django.test import TestCase, override_settings
from oscar.apps.customer.forms import (
EmailUserCreationForm, OrderSearchF... | tests/unit/customer/test_forms.py | from datetime import date, datetime
from unittest import mock
import pytz
from django.conf import settings
from django.core import mail
from django.core.exceptions import ValidationError
from django.test import TestCase, override_settings
from oscar.apps.customer.forms import (
EmailUserCreationForm, OrderSearchF... | 0.557845 | 0.262777 |
import wandb
from src.Data import Data
from src.configurations import Configuration, WandbLogs
from src.models.BestPreTrainedModelForAStation import BestPreTrainedModelForAStation
from src.models.PerStationModel import PerStationModel
from src.run_utils import LogKeys, train_predict_evaluate_log_for_model_and_data
d... | src/predict_using_trained_models.py | import wandb
from src.Data import Data
from src.configurations import Configuration, WandbLogs
from src.models.BestPreTrainedModelForAStation import BestPreTrainedModelForAStation
from src.models.PerStationModel import PerStationModel
from src.run_utils import LogKeys, train_predict_evaluate_log_for_model_and_data
d... | 0.641085 | 0.479382 |
import sys
import ConfigParser
from os.path import expanduser
# Set system path
home = expanduser("~")
cfgfile = open(home + "\\STVTools.ini", 'r')
config = ConfigParser.ConfigParser()
config.read(home + "\\STVTools.ini")
# Master Path
syspath1 = config.get('SysDir','MasterPackage')
sys.path.append(syspath1)
# Built Pa... | CustomExtension.extension/STVTools.tab/MEP Tools.panel/Tools.stack3/Slope.pulldown/irregular.pushbutton/script.py | import sys
import ConfigParser
from os.path import expanduser
# Set system path
home = expanduser("~")
cfgfile = open(home + "\\STVTools.ini", 'r')
config = ConfigParser.ConfigParser()
config.read(home + "\\STVTools.ini")
# Master Path
syspath1 = config.get('SysDir','MasterPackage')
sys.path.append(syspath1)
# Built Pa... | 0.217421 | 0.092074 |
from find_gene import find_gene
from batch_find_gene import batch_find_gene
from find_homologues import find_homologues
from find_ipg import find_ipg
from choose_gene import choose_gene
def test_find_gene():
"""
test_early_find_gene should return the matching DNA accession
number (M22259.1) of pro... | test_all.py | from find_gene import find_gene
from batch_find_gene import batch_find_gene
from find_homologues import find_homologues
from find_ipg import find_ipg
from choose_gene import choose_gene
def test_find_gene():
"""
test_early_find_gene should return the matching DNA accession
number (M22259.1) of pro... | 0.703957 | 0.541106 |
def_numtx = [1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 2, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 2, 1, 2, 2, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1]
def_scheduleTimes = [152, 277, 404, 537, 663, 789, 915, 1050, 1173, 1300, 1433, 1560, 1686, 1812, 1946, 2071, 2197, 2330, 2457,... | examples/task3/plotting/data/data10m.py | def_numtx = [1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 2, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 2, 1, 2, 2, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1]
def_scheduleTimes = [152, 277, 404, 537, 663, 789, 915, 1050, 1173, 1300, 1433, 1560, 1686, 1812, 1946, 2071, 2197, 2330, 2457,... | 0.156427 | 0.507507 |
from ...configuration.utilities import enable_yaml_load
from ...exceptions.executorexceptions import CommandExecutionFailure
from ...interfaces.executor import Executor
from ..attributedict import AttributeDict
import asyncio
import asyncssh
@enable_yaml_load("!SSHExecutor")
class SSHExecutor(Executor):
def __in... | tardis/utilities/executors/sshexecutor.py | from ...configuration.utilities import enable_yaml_load
from ...exceptions.executorexceptions import CommandExecutionFailure
from ...interfaces.executor import Executor
from ..attributedict import AttributeDict
import asyncio
import asyncssh
@enable_yaml_load("!SSHExecutor")
class SSHExecutor(Executor):
def __in... | 0.558327 | 0.098079 |
import csv
import pandas as pd
from src.filepaths import getFilePathOutput
def exportInputData(params: dict):
rows = []
for paramKey, paramData in params.items():
source = paramData['source'] if 'source' in paramData else ''
rows.extend(__printScenarioValue(paramData['desc'], paramData['uni... | src/data/params/export_params.py | import csv
import pandas as pd
from src.filepaths import getFilePathOutput
def exportInputData(params: dict):
rows = []
for paramKey, paramData in params.items():
source = paramData['source'] if 'source' in paramData else ''
rows.extend(__printScenarioValue(paramData['desc'], paramData['uni... | 0.326271 | 0.229827 |
import os
import time
from datetime import datetime
import requests
from flask import Blueprint, jsonify, json, current_app
from flask_login import current_user, login_user
from jaysblog import User, db
from jaysblog.utils.response_code import RET
oauth_bp = Blueprint('oauth_blueprint', __name__)
name = 'github',
c... | jaysblog/blueprints/oauth/oauth_blueprint.py | import os
import time
from datetime import datetime
import requests
from flask import Blueprint, jsonify, json, current_app
from flask_login import current_user, login_user
from jaysblog import User, db
from jaysblog.utils.response_code import RET
oauth_bp = Blueprint('oauth_blueprint', __name__)
name = 'github',
c... | 0.172137 | 0.053725 |
from environments import SerialTwoDOFGym
from visualservoing.state_extractory import StateExtractor
import numpy as np
import matplotlib.pyplot as plt
from mpl_toolkits.mplot3d import Axes3D
import torch
import glob
#HELPER FUNCTION
#+++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++... | src/viz_robot_traj.py | from environments import SerialTwoDOFGym
from visualservoing.state_extractory import StateExtractor
import numpy as np
import matplotlib.pyplot as plt
from mpl_toolkits.mplot3d import Axes3D
import torch
import glob
#HELPER FUNCTION
#+++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++... | 0.301465 | 0.520009 |
import lambda_toolkit.modules.logger as logger
from lambda_toolkit.modules.utils import Utils
import os
import json
import pkgutil
import boto3
from shutil import copytree
class Conf:
def __init__(self):
self.config_file = os.path.join(os.path.expanduser('~'), ".lambda-toolkit.json")
self.log = ... | lambda_toolkit/modules/conf.py |
import lambda_toolkit.modules.logger as logger
from lambda_toolkit.modules.utils import Utils
import os
import json
import pkgutil
import boto3
from shutil import copytree
class Conf:
def __init__(self):
self.config_file = os.path.join(os.path.expanduser('~'), ".lambda-toolkit.json")
self.log = ... | 0.196209 | 0.046335 |
from keras.models import load_model
from keras.models import model_from_json
# internal package
from src.infra import infra
# Initialize Global alias
_appendListElement = infra._appendListElement
_getSplitedStringByIndex = infra._getSplitedStringByIndex
_getElementByIndex = infra._get... | refactoring_project/src/config/config.py | from keras.models import load_model
from keras.models import model_from_json
# internal package
from src.infra import infra
# Initialize Global alias
_appendListElement = infra._appendListElement
_getSplitedStringByIndex = infra._getSplitedStringByIndex
_getElementByIndex = infra._get... | 0.665845 | 0.221298 |
from mock import patch
from django.test import TestCase
from ..serializer import CollaboratorSerializer
class CollaboratorSerializerTests(TestCase):
"""Test RepoSerializer methods"""
def setUp(self):
self.username = "delete_me_username"
self.repo_base = "delete_me_repo_base"
self.pa... | src/api/test/test_collaborator_serializer.py | from mock import patch
from django.test import TestCase
from ..serializer import CollaboratorSerializer
class CollaboratorSerializerTests(TestCase):
"""Test RepoSerializer methods"""
def setUp(self):
self.username = "delete_me_username"
self.repo_base = "delete_me_repo_base"
self.pa... | 0.584034 | 0.183502 |
import os.path
import time
import sys
import logging
import pickle
import urllib.request
from io import StringIO
from pathlib import Path
import yaml
import numpy as np
# Params
def load_params(path):
"""Return loaded parameters from a yaml file"""
with open(path, "r") as handle:
content = yaml.safe_... | asmk/io_helpers.py |
import os.path
import time
import sys
import logging
import pickle
import urllib.request
from io import StringIO
from pathlib import Path
import yaml
import numpy as np
# Params
def load_params(path):
"""Return loaded parameters from a yaml file"""
with open(path, "r") as handle:
content = yaml.safe_... | 0.478041 | 0.1585 |
import warnings
import pulumi
import pulumi.runtime
from typing import Any, Mapping, Optional, Sequence, Union, overload
from .. import _utilities
__all__ = ['KeyArgs', 'Key']
@pulumi.input_type
class KeyArgs:
def __init__(__self__, *,
domain: pulumi.Input[str]):
"""
The set of a... | sdk/python/pulumi_gandi/livedns/key.py |
import warnings
import pulumi
import pulumi.runtime
from typing import Any, Mapping, Optional, Sequence, Union, overload
from .. import _utilities
__all__ = ['KeyArgs', 'Key']
@pulumi.input_type
class KeyArgs:
def __init__(__self__, *,
domain: pulumi.Input[str]):
"""
The set of a... | 0.855066 | 0.077169 |
from collections import defaultdict
import sys, csv, bz2, re
import rdflib
import getopt
#Read command line options
options, operands = getopt.getopt(sys.argv[4:], "", ["one_type_per_line"])
config = dict(options)
config.setdefault("one_type_per_line", False)
csv.field_size_limit(1000000000)
IGNORED_PREFIXES = ["/b... | index/src/main/scripts/DBpediaResource/types_freebase.py | from collections import defaultdict
import sys, csv, bz2, re
import rdflib
import getopt
#Read command line options
options, operands = getopt.getopt(sys.argv[4:], "", ["one_type_per_line"])
config = dict(options)
config.setdefault("one_type_per_line", False)
csv.field_size_limit(1000000000)
IGNORED_PREFIXES = ["/b... | 0.319121 | 0.145085 |
from __future__ import annotations
from typing import Optional
class TreeNode:
def __init__(self, val: int, left: Optional[TreeNode] = None, right: Optional[TreeNode] = None) -> None:
self.val = val
self.left = left
self.right = right
def preorder(root: TreeNode) -> list[int]:
stack: l... | .archived/snakecode/other/btree_traversal.py | from __future__ import annotations
from typing import Optional
class TreeNode:
def __init__(self, val: int, left: Optional[TreeNode] = None, right: Optional[TreeNode] = None) -> None:
self.val = val
self.left = left
self.right = right
def preorder(root: TreeNode) -> list[int]:
stack: l... | 0.764012 | 0.426859 |
# Licensed under the Apache License, Version 2.0 (the "License");
# you may not use this file except in compliance with the License.
# You may obtain a copy of the License at
# http://www.apache.org/licenses/LICENSE-2.0
# Unless required by applicable law or agreed to in writing, software
# distributed under the L... | main.py |
# Licensed under the Apache License, Version 2.0 (the "License");
# you may not use this file except in compliance with the License.
# You may obtain a copy of the License at
# http://www.apache.org/licenses/LICENSE-2.0
# Unless required by applicable law or agreed to in writing, software
# distributed under the L... | 0.764056 | 0.092442 |
from typing import cast
import numpy
import scipy.stats # type: ignore
from optimizer import trust_region
from overloads import difference
from overloads.typedefs import ndarray
class Sample:
beta: ndarray
X: ndarray
Y: ndarray
lambda_: float
beta_decomp: ndarray
def symm_eig(self, A: ndar... | tests/test_lasso.py | from typing import cast
import numpy
import scipy.stats # type: ignore
from optimizer import trust_region
from overloads import difference
from overloads.typedefs import ndarray
class Sample:
beta: ndarray
X: ndarray
Y: ndarray
lambda_: float
beta_decomp: ndarray
def symm_eig(self, A: ndar... | 0.861115 | 0.678899 |
from __future__ import absolute_import, print_function
import os
import sys
import logging
import threading
import fibers
import six
from . import util
__all__ = ['get_logger']
# Add a new level: TRACE.
logging.TRACE = 5
assert logging.NOTSET < logging.TRACE < logging.DEBUG
logging.addLevelName('TRACE', logging.TR... | lib/gruvi/logging.py |
from __future__ import absolute_import, print_function
import os
import sys
import logging
import threading
import fibers
import six
from . import util
__all__ = ['get_logger']
# Add a new level: TRACE.
logging.TRACE = 5
assert logging.NOTSET < logging.TRACE < logging.DEBUG
logging.addLevelName('TRACE', logging.TR... | 0.645455 | 0.11808 |
import torch
import numpy as np
import pytest
from EduNLP.Pretrain import BertTokenizer, finetune_bert
from EduNLP.Vector import BertModel, T2V
from EduNLP.I2V import Bert, get_pretrained_i2v
@pytest.fixture(scope="module")
def stem_data_bert(data):
test_items = [
{'stem': '有公式$\\FormFigureID{wrong1?}$和公式... | tests/test_vec/test_bert.py | import torch
import numpy as np
import pytest
from EduNLP.Pretrain import BertTokenizer, finetune_bert
from EduNLP.Vector import BertModel, T2V
from EduNLP.I2V import Bert, get_pretrained_i2v
@pytest.fixture(scope="module")
def stem_data_bert(data):
test_items = [
{'stem': '有公式$\\FormFigureID{wrong1?}$和公式... | 0.495117 | 0.459622 |
import pandas as pd
import Poll
import re
class Answer ():
def __init__(self, questionText, answer):
self.questionText = questionText
self.answer = answer
def getNumbers(self, str):
array = re.findall(r'[0-9]+', str)
return array
def read_and_assign_answerkey(self... | Answer.py | import pandas as pd
import Poll
import re
class Answer ():
def __init__(self, questionText, answer):
self.questionText = questionText
self.answer = answer
def getNumbers(self, str):
array = re.findall(r'[0-9]+', str)
return array
def read_and_assign_answerkey(self... | 0.048597 | 0.11928 |