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 logging
import threading
import functools
import coloredlogs
from qtpy.QtCore import QtInfoMsg, QtWarningMsg, QtCriticalMsg
def qt_message_handler(mode, context, message):
logger = logging.getLogger("QT Logger")
"""Qt errors handler"""
if mode == QtInfoMsg:
mode = 20
elif mode == QtWarn... | lista3/utils.py | import logging
import threading
import functools
import coloredlogs
from qtpy.QtCore import QtInfoMsg, QtWarningMsg, QtCriticalMsg
def qt_message_handler(mode, context, message):
logger = logging.getLogger("QT Logger")
"""Qt errors handler"""
if mode == QtInfoMsg:
mode = 20
elif mode == QtWarn... | 0.274935 | 0.058212 |
from __future__ import print_function
__all__ = ["getKeyword"]
import re
ptn = re.compile(r'\s*(?P<key>[a-zA-Z_][a-zA-Z0-9_]*)(?:\s*$|(?:\s*(?P<next>[=;])))')
def getKeyword(astr, begInd=0):
"""
Returns the next keyword from an APO format message. Keywords must start
with a letter or underscore and may... | python/opscore/RO/ParseMsg/GetKeyword.py | from __future__ import print_function
__all__ = ["getKeyword"]
import re
ptn = re.compile(r'\s*(?P<key>[a-zA-Z_][a-zA-Z0-9_]*)(?:\s*$|(?:\s*(?P<next>[=;])))')
def getKeyword(astr, begInd=0):
"""
Returns the next keyword from an APO format message. Keywords must start
with a letter or underscore and may... | 0.603932 | 0.303487 |
import unittest
import numpy as np
from numpy.random import random
from numpy.testing import assert_array_almost_equal, assert_array_equal
from structured import hmm
class TestHMM(unittest.TestCase):
def test_hmm_0(self):
# random markov model, deterministic output
nstates = 5
T = 1... | structured/tests/test_hmm.py | import unittest
import numpy as np
from numpy.random import random
from numpy.testing import assert_array_almost_equal, assert_array_equal
from structured import hmm
class TestHMM(unittest.TestCase):
def test_hmm_0(self):
# random markov model, deterministic output
nstates = 5
T = 1... | 0.67662 | 0.748214 |
from zope.interface import implements
from axiom.item import Item
from axiom.attributes import reference
from imaginary.iimaginary import ISittable, IContainer, IMovementRestriction
from imaginary.eimaginary import ActionFailure
from imaginary.events import ThatDoesntWork
from imaginary.language import Noun
from imag... | ExampleGame/examplegame/furniture.py | from zope.interface import implements
from axiom.item import Item
from axiom.attributes import reference
from imaginary.iimaginary import ISittable, IContainer, IMovementRestriction
from imaginary.eimaginary import ActionFailure
from imaginary.events import ThatDoesntWork
from imaginary.language import Noun
from imag... | 0.600305 | 0.210138 |
from typing import Dict, Tuple
import numpy as np
from ax.core.types import TParameterization
from ax.exceptions.core import OptimizationShouldStop
from ax.global_stopping.strategies.base import BaseGlobalStoppingStrategy
from ax.service.ax_client import AxClient
from ax.utils.common.testutils import TestCase
from ax... | ax/service/tests/test_global_stopping.py |
from typing import Dict, Tuple
import numpy as np
from ax.core.types import TParameterization
from ax.exceptions.core import OptimizationShouldStop
from ax.global_stopping.strategies.base import BaseGlobalStoppingStrategy
from ax.service.ax_client import AxClient
from ax.utils.common.testutils import TestCase
from ax... | 0.927986 | 0.284731 |
from __future__ import absolute_import, print_function
import imp
import sys
from collections import namedtuple
import pytest
from flask import Flask
from flask import current_app as flask_current_app
from flask import g
from flask_limiter import Limiter
from mock import patch
from pkg_resources import Distribution
... | tests/conftest.py | from __future__ import absolute_import, print_function
import imp
import sys
from collections import namedtuple
import pytest
from flask import Flask
from flask import current_app as flask_current_app
from flask import g
from flask_limiter import Limiter
from mock import patch
from pkg_resources import Distribution
... | 0.457137 | 0.072243 |
import datetime
import os
from test.splitgraph.conftest import INGESTION_RESOURCES
from unittest.mock import MagicMock
from click.testing import CliRunner
from splitgraph.commandline.ingestion import csv_import
from splitgraph.core.repository import Repository
from splitgraph.core.types import Credentials, Params
fro... | test/splitgraph/ingestion/test_dbt_data_source.py | import datetime
import os
from test.splitgraph.conftest import INGESTION_RESOURCES
from unittest.mock import MagicMock
from click.testing import CliRunner
from splitgraph.commandline.ingestion import csv_import
from splitgraph.core.repository import Repository
from splitgraph.core.types import Credentials, Params
fro... | 0.63409 | 0.334739 |
import random
import argparse
import sys
import os
import json
import torch
import torch.nn as nn
import torch.nn.functional as F
import torch.optim as optim
sys.path.append(os.path.abspath(os.path.join(os.path.dirname(__file__), '..', '..', '..')))
from common.pytorch.ner.model import Tagger
def lines(path):
w... | src/training/pytorch/ner/train.py | import random
import argparse
import sys
import os
import json
import torch
import torch.nn as nn
import torch.nn.functional as F
import torch.optim as optim
sys.path.append(os.path.abspath(os.path.join(os.path.dirname(__file__), '..', '..', '..')))
from common.pytorch.ner.model import Tagger
def lines(path):
w... | 0.445771 | 0.313906 |
import sys
import MySQLdb
import argparse
import progressbar
import pandas as pd
from collections import OrderedDict
OUTPUT_FILE = 'db_conflicts.csv'
def main(user, passwd, database):
# Open database connection
db = MySQLdb.connect("localhost", user, passwd, database)
# Prepare a cursor object using cur... | codes/scripts/get_db_conflicts.py | import sys
import MySQLdb
import argparse
import progressbar
import pandas as pd
from collections import OrderedDict
OUTPUT_FILE = 'db_conflicts.csv'
def main(user, passwd, database):
# Open database connection
db = MySQLdb.connect("localhost", user, passwd, database)
# Prepare a cursor object using cur... | 0.265785 | 0.099996 |
import hashlib
import time
DISTRIBUTION_NAME = 'sawtooth-payment'
DEFAULT_URL = 'http://127.0.0.1:8009'
TP_FAMILYNAME = 'payment'
TP_VERSION = '1.0'
PAYMENT_ENTITY_CODE = '01'
PATIENT_ENTITY_CODE = '02'
CONTRACT_ENTITY_CODE = '03'
CONTRACT_PAYMENT__RELATION_CODE = "51"
PAYMENT_CONTRACT__RELATION_CODE = "52"
PATIE... | payment_common/helper.py | import hashlib
import time
DISTRIBUTION_NAME = 'sawtooth-payment'
DEFAULT_URL = 'http://127.0.0.1:8009'
TP_FAMILYNAME = 'payment'
TP_VERSION = '1.0'
PAYMENT_ENTITY_CODE = '01'
PATIENT_ENTITY_CODE = '02'
CONTRACT_ENTITY_CODE = '03'
CONTRACT_PAYMENT__RELATION_CODE = "51"
PAYMENT_CONTRACT__RELATION_CODE = "52"
PATIE... | 0.427875 | 0.04798 |
import argparse
import os
import json
if __name__ == '__main__':
parser = argparse.ArgumentParser()
parser.add_argument('--wiki', type=str, help="The file containing the annotated wiki samples.", default='wiki-anno-samples.jsonl')
parser.add_argument('--bbc', type=str, help="The file containing the annotated bb... | annotations/simplify_annotations.py |
import argparse
import os
import json
if __name__ == '__main__':
parser = argparse.ArgumentParser()
parser.add_argument('--wiki', type=str, help="The file containing the annotated wiki samples.", default='wiki-anno-samples.jsonl')
parser.add_argument('--bbc', type=str, help="The file containing the annotated bb... | 0.319971 | 0.174235 |
import sys
class Node(object):
""" Abstract base class for AST nodes.
"""
def children(self):
""" A sequence of all children that are Nodes
"""
pass
def __str__(self):
return self.show()
def __repr__(self):
return str(self.to_tuples())
def to_tuples... | setlx2py/setlx_ast.py |
import sys
class Node(object):
""" Abstract base class for AST nodes.
"""
def children(self):
""" A sequence of all children that are Nodes
"""
pass
def __str__(self):
return self.show()
def __repr__(self):
return str(self.to_tuples())
def to_tuples... | 0.54698 | 0.231614 |
import networkx as nx
assert int(nx.__version__.split('.')[0]) >= 2
# This class is responsible for deadlock detecting using a "wait-for" dependency graph.
# In real-life case we might find a more-efficient solution, using properties of that
# graph (for example: out degree = 1).
class DeadlockDetector:
def __ini... | hw2-romv-scheduler/deadlock_detector.py | import networkx as nx
assert int(nx.__version__.split('.')[0]) >= 2
# This class is responsible for deadlock detecting using a "wait-for" dependency graph.
# In real-life case we might find a more-efficient solution, using properties of that
# graph (for example: out degree = 1).
class DeadlockDetector:
def __ini... | 0.797241 | 0.458046 |
import json
from common.logger import get_logger
from constants.entity import EventConsumerEntity, EthereumEventConsumerEntities, CardanoEventConsumer, \
ConverterBridgeEntities
from constants.error_details import ErrorCode, ErrorDetails
from constants.general import BlockchainName
from utils.exceptions import Int... | application/factory/consumer_factory.py | import json
from common.logger import get_logger
from constants.entity import EventConsumerEntity, EthereumEventConsumerEntities, CardanoEventConsumer, \
ConverterBridgeEntities
from constants.error_details import ErrorCode, ErrorDetails
from constants.general import BlockchainName
from utils.exceptions import Int... | 0.383757 | 0.083516 |
import numpy as np
from numpy import pi
def spec_var(model, ph):
"""Compute variance of ``p`` from Fourier coefficients ``ph``.
Parameters
----------
model : pyqg.Model instance
The model object from which `ph` originates
ph : complex array
The field on which to compute the varian... | pyqg/diagnostic_tools.py |
import numpy as np
from numpy import pi
def spec_var(model, ph):
"""Compute variance of ``p`` from Fourier coefficients ``ph``.
Parameters
----------
model : pyqg.Model instance
The model object from which `ph` originates
ph : complex array
The field on which to compute the varian... | 0.940644 | 0.713057 |
import os
import re
import sys
def getExecutionPath(argv):
if "--workingDir" in argv:
index = argv.index("--workingDir")
if index < len(argv) - 1:
value = argv[len(argv) - 1]
print("Using workingDir value of " + value + ".")
return value
else:
print("No value provided for paramete... | phrag.py | import os
import re
import sys
def getExecutionPath(argv):
if "--workingDir" in argv:
index = argv.index("--workingDir")
if index < len(argv) - 1:
value = argv[len(argv) - 1]
print("Using workingDir value of " + value + ".")
return value
else:
print("No value provided for paramete... | 0.055797 | 0.050075 |
import json
import warnings
import pulumi
import pulumi.runtime
from typing import Union
from .. import utilities, tables
class SecurityScanConfig(pulumi.CustomResource):
authentication: pulumi.Output[dict]
blacklist_patterns: pulumi.Output[list]
display_name: pulumi.Output[str]
export_to_security_com... | sdk/python/pulumi_gcp/compute/security_scan_config.py |
import json
import warnings
import pulumi
import pulumi.runtime
from typing import Union
from .. import utilities, tables
class SecurityScanConfig(pulumi.CustomResource):
authentication: pulumi.Output[dict]
blacklist_patterns: pulumi.Output[list]
display_name: pulumi.Output[str]
export_to_security_com... | 0.740925 | 0.069069 |
from avgn.utils.paths import DATA_DIR
import avgn
from avgn.utils.json import NoIndent, NoIndentEncoder
import json
import numpy as np
import librosa
import xml.etree.ElementTree
from avgn.utils.audio import get_samplerate
import pandas as pd
from tqdm.autonotebook import tqdm
DATASET_ID = "koumura_bengalese_finch"
... | avgn/custom_parsing/koumura_bengalese_finch.py | from avgn.utils.paths import DATA_DIR
import avgn
from avgn.utils.json import NoIndent, NoIndentEncoder
import json
import numpy as np
import librosa
import xml.etree.ElementTree
from avgn.utils.audio import get_samplerate
import pandas as pd
from tqdm.autonotebook import tqdm
DATASET_ID = "koumura_bengalese_finch"
... | 0.380644 | 0.218909 |
import scipy as N
def fastnorm(x):
""" Fast Euclidean Norm (L2)
This version should be faster than numpy.linalg.norm if
the dot function uses blas.
Inputs:
x -- numpy array
Output:
L2 norm from 1d representation of x
"""
xv = x.ravel()
return N.dot(xv, xv)**(1/2... | v1s_math.py | import scipy as N
def fastnorm(x):
""" Fast Euclidean Norm (L2)
This version should be faster than numpy.linalg.norm if
the dot function uses blas.
Inputs:
x -- numpy array
Output:
L2 norm from 1d representation of x
"""
xv = x.ravel()
return N.dot(xv, xv)**(1/2... | 0.621656 | 0.537163 |
from collections import defaultdict
from copy import copy
from sqlglot import expressions as exp
from sqlglot.errors import OptimizeError
from sqlglot.optimizer.helper import SelectParts
# Sentinel value that means an outer query selecting ALL columns
SELECT_ALL = object()
def projection_pushdown(expression):
"... | sqlglot/optimizer/projection_pushdown.py | from collections import defaultdict
from copy import copy
from sqlglot import expressions as exp
from sqlglot.errors import OptimizeError
from sqlglot.optimizer.helper import SelectParts
# Sentinel value that means an outer query selecting ALL columns
SELECT_ALL = object()
def projection_pushdown(expression):
"... | 0.913489 | 0.595992 |
import json
from os.path import join
from functools import wraps
from twisted.internet.threads import deferToThread
from twisted.internet.task import deferLater
from twisted.internet.defer import inlineCallbacks
from twisted.internet import reactor
from slyd.projects import ProjectsManager
from slyd.projecttemplates ... | slyd/slyd/gitstorage/projects.py | import json
from os.path import join
from functools import wraps
from twisted.internet.threads import deferToThread
from twisted.internet.task import deferLater
from twisted.internet.defer import inlineCallbacks
from twisted.internet import reactor
from slyd.projects import ProjectsManager
from slyd.projecttemplates ... | 0.534127 | 0.069573 |
from collections import defaultdict, namedtuple
import os
import cv2
import numpy as np
import pandas as pd
import utils
class DataPreprocessing:
"""Preprocessing base class. Since resizing is necessary for both train and test set, it is defined here"""
def __init__(self, dataset_parameters, base_csv, datas... | data_preprocessing.py | from collections import defaultdict, namedtuple
import os
import cv2
import numpy as np
import pandas as pd
import utils
class DataPreprocessing:
"""Preprocessing base class. Since resizing is necessary for both train and test set, it is defined here"""
def __init__(self, dataset_parameters, base_csv, datas... | 0.723114 | 0.279116 |
# Import Modules
import numpy as np
import scipy.special
from scipy.optimize import root
import logging
from ep_clustering._utils import fix_docs, logsumexp
from ep_clustering.likelihoods._likelihoods import Likelihood
from ep_clustering.likelihoods._slice_sampler import SliceSampler
from ep_clustering.exp_family._von_... | ep_clustering/likelihoods/_von_mises_fisher_likelihood.py | # Import Modules
import numpy as np
import scipy.special
from scipy.optimize import root
import logging
from ep_clustering._utils import fix_docs, logsumexp
from ep_clustering.likelihoods._likelihoods import Likelihood
from ep_clustering.likelihoods._slice_sampler import SliceSampler
from ep_clustering.exp_family._von_... | 0.770422 | 0.465327 |
from .coloring import EffectSupporter
from .convolution import GaussianBlur
from ...base import SecondPassRenderer, BaseRenderer
from ...uniformed import UniformedRenderer
from ...util import sample_vertex_shader, gen_screen_mesh
from ....gl.shader import ShaderProgram
from ....gl.framebuffer import FrameBuffer, FB_NON... | engine/renderer/presets/fancy/bloom.py | from .coloring import EffectSupporter
from .convolution import GaussianBlur
from ...base import SecondPassRenderer, BaseRenderer
from ...uniformed import UniformedRenderer
from ...util import sample_vertex_shader, gen_screen_mesh
from ....gl.shader import ShaderProgram
from ....gl.framebuffer import FrameBuffer, FB_NON... | 0.59302 | 0.138958 |
from util.quadtree import Point
from projections.projection import GeospatialProjection
from scipy.cluster.hierarchy import linkage, leaves_list
from scipy.spatial.distance import euclidean
import numpy as np
class HierarchicalClusteringProjection(GeospatialProjection):
def add_data(self, data, method='single', ... | preprocessing/projections/hierarchicalclustering.py | from util.quadtree import Point
from projections.projection import GeospatialProjection
from scipy.cluster.hierarchy import linkage, leaves_list
from scipy.spatial.distance import euclidean
import numpy as np
class HierarchicalClusteringProjection(GeospatialProjection):
def add_data(self, data, method='single', ... | 0.47098 | 0.600305 |
import ROOT
import rootUtils as ut
import shipunit as u
fn = 'ship.Pythia8-TGeant4.root'
# fn = 'ship.Genie-TGeant4.root'
f = ROOT.TFile(fn)
sTree = f.FindObjectAny('cbmsim')
nEvents = sTree.GetEntries()
sFol = f.FindObjectAny('cbmroot')
MCTracks = ROOT.TClonesArray("FairMCTrack")
TrackingHits = ROOT.TClonesA... | python/shipEvent_ex.py | import ROOT
import rootUtils as ut
import shipunit as u
fn = 'ship.Pythia8-TGeant4.root'
# fn = 'ship.Genie-TGeant4.root'
f = ROOT.TFile(fn)
sTree = f.FindObjectAny('cbmsim')
nEvents = sTree.GetEntries()
sFol = f.FindObjectAny('cbmroot')
MCTracks = ROOT.TClonesArray("FairMCTrack")
TrackingHits = ROOT.TClonesA... | 0.106226 | 0.186576 |
from configparser import ConfigParser
import re
from psycopg2 import connect
from datetime import datetime
__author__ = 'litleleprikon'
SPLIT_RE = re.compile(r" |(?<! |[',\\.:!()@/<>])(?=[',\\.:!()@/<>])|(?<=[',\\.:!()@/<>])(?![',\\.:!()@/<>])",
re.IGNORECASE)
REMOVE_TAGS_RE = re.compile(r'<[A-Z... | parser/tf_idf.py | from configparser import ConfigParser
import re
from psycopg2 import connect
from datetime import datetime
__author__ = 'litleleprikon'
SPLIT_RE = re.compile(r" |(?<! |[',\\.:!()@/<>])(?=[',\\.:!()@/<>])|(?<=[',\\.:!()@/<>])(?![',\\.:!()@/<>])",
re.IGNORECASE)
REMOVE_TAGS_RE = re.compile(r'<[A-Z... | 0.277277 | 0.083143 |
class CoupledPair(object):
"""
Custom Pair class. CoupledPair has special methods that allow checking for
clashing with another pair, similarity to another pair, retrieving a value
in the pair with its counterpart value and modifying it, giving it more
utility and versatility. These methods... | coupledpairs/coupledpairs.py |
class CoupledPair(object):
"""
Custom Pair class. CoupledPair has special methods that allow checking for
clashing with another pair, similarity to another pair, retrieving a value
in the pair with its counterpart value and modifying it, giving it more
utility and versatility. These methods... | 0.871612 | 0.394026 |
from pycatia.knowledge_interfaces.enum_param import EnumParam
class BoolParam(EnumParam):
"""
.. note::
:class: toggle
CAA V5 Visual Basic Help (2020-06-11 12:40:47.360445)
| System.IUnknown
| System.IDispatch
| System.C... | pycatia/knowledge_interfaces/bool_param.py | from pycatia.knowledge_interfaces.enum_param import EnumParam
class BoolParam(EnumParam):
"""
.. note::
:class: toggle
CAA V5 Visual Basic Help (2020-06-11 12:40:47.360445)
| System.IUnknown
| System.IDispatch
| System.C... | 0.883205 | 0.373105 |
from __future__ import print_function
from __future__ import division
import os, sys
sys.path.insert(0, r'../')
import time
import argparse
from optimise import TRAIN, TUNE, hyperoptTUNE, skoptTUNE
parser = argparse.ArgumentParser()
# Pick a data set and a LSTM model
parser.add_argument('--data', type=str, default='... | src/run.py | from __future__ import print_function
from __future__ import division
import os, sys
sys.path.insert(0, r'../')
import time
import argparse
from optimise import TRAIN, TUNE, hyperoptTUNE, skoptTUNE
parser = argparse.ArgumentParser()
# Pick a data set and a LSTM model
parser.add_argument('--data', type=str, default='... | 0.444565 | 0.056914 |
import subprocess
import datetime
from ruffus import *
import pandas as pd
import re
import urllib.request
@originate("data/BLUETH_20150819.BT")
def bt19(output_file):
# Download file from AARNet Cloudstor OwnCloud Service
url = "https://cloudstor.aarnet.edu.au/plus/index.php/s/SlTMKzq9OKOaWQr/download?path=%2... | pipeline/data_bt.py | import subprocess
import datetime
from ruffus import *
import pandas as pd
import re
import urllib.request
@originate("data/BLUETH_20150819.BT")
def bt19(output_file):
# Download file from AARNet Cloudstor OwnCloud Service
url = "https://cloudstor.aarnet.edu.au/plus/index.php/s/SlTMKzq9OKOaWQr/download?path=%2... | 0.432303 | 0.241445 |
# Part 1 - Data Preprocessing
# Importing the libraries
import numpy as np
import matplotlib.pyplot as plt
import pandas as pd
# Importing the training set
dataset_train = pd.read_csv('Google_Stock_Price_Train.csv')
training_set = dataset_train.iloc[:,1:2].values
# Feature Scaling
from sklearn.preproce... | rnn1.py |
# Part 1 - Data Preprocessing
# Importing the libraries
import numpy as np
import matplotlib.pyplot as plt
import pandas as pd
# Importing the training set
dataset_train = pd.read_csv('Google_Stock_Price_Train.csv')
training_set = dataset_train.iloc[:,1:2].values
# Feature Scaling
from sklearn.preproce... | 0.818519 | 0.614249 |
from datetime import datetime
from flask_helpers.ErrorHandler import ErrorHandler
from google.cloud import datastore
from Persistence.AbstractPersister import AbstractPersister
class Persister(AbstractPersister):
def __init__(self):
super(Persister, self).__init__()
self.handler.module="GCPDatast... | PersistenceExtensions/GCPDatastore.py | from datetime import datetime
from flask_helpers.ErrorHandler import ErrorHandler
from google.cloud import datastore
from Persistence.AbstractPersister import AbstractPersister
class Persister(AbstractPersister):
def __init__(self):
super(Persister, self).__init__()
self.handler.module="GCPDatast... | 0.440469 | 0.152442 |
from ukfm import SO2, UKF, EKF
from ukfm import LOCALIZATION as MODEL
import ukfm
import numpy as np
import matplotlib
ukfm.utils.set_matplotlib_config()
################################################################################
# We compare the filters on a large number of Monte-Carlo runs.
# Monte-C... | docsource/source/auto_benchmark/localization.py | from ukfm import SO2, UKF, EKF
from ukfm import LOCALIZATION as MODEL
import ukfm
import numpy as np
import matplotlib
ukfm.utils.set_matplotlib_config()
################################################################################
# We compare the filters on a large number of Monte-Carlo runs.
# Monte-C... | 0.773772 | 0.482063 |
import numpy as np
import pandas as pd
"""# **Looking at the raw dataset**"""
data=pd.read_csv("healthcare-dataset-stroke-data.csv")
data.head()
data.shape
data.describe()
data.dtypes
data.columns
data.size
data.info()
"""# **Explorartory Data Analysis & Feature Engineering**"""
!pip install dataprep
!pip i... | advanced_bioinformatics_project.py | import numpy as np
import pandas as pd
"""# **Looking at the raw dataset**"""
data=pd.read_csv("healthcare-dataset-stroke-data.csv")
data.head()
data.shape
data.describe()
data.dtypes
data.columns
data.size
data.info()
"""# **Explorartory Data Analysis & Feature Engineering**"""
!pip install dataprep
!pip i... | 0.585338 | 0.362236 |
import itertools
from pathlib import Path
import pytest
from fpdf import FPDF
from fpdf.errors import FPDFException
from fpdf.fonts import fpdf_charwidths
from test.conftest import assert_pdf_equal
HERE = Path(__file__).resolve().parent
def test_no_set_font():
pdf = FPDF()
pdf.add_page()
with pytest.ra... | SMSProject/venv/Lib/site-packages/test/fonts/test_set_font.py | import itertools
from pathlib import Path
import pytest
from fpdf import FPDF
from fpdf.errors import FPDFException
from fpdf.fonts import fpdf_charwidths
from test.conftest import assert_pdf_equal
HERE = Path(__file__).resolve().parent
def test_no_set_font():
pdf = FPDF()
pdf.add_page()
with pytest.ra... | 0.605566 | 0.390011 |
import os
import smpl.util as util
import smpl.log_module as logger
from smpl.package import LibraryPackage
from smpl.config_file import ConfigObject, PackageParms
import smpl.exec as exec
supported_versions = {
"6.2": {
"url": "https://ftp.gnu.org/pub/gnu/ncurses/ncurses-6.2.tar.gz",
"ta... | smpl/ncurses.py | import os
import smpl.util as util
import smpl.log_module as logger
from smpl.package import LibraryPackage
from smpl.config_file import ConfigObject, PackageParms
import smpl.exec as exec
supported_versions = {
"6.2": {
"url": "https://ftp.gnu.org/pub/gnu/ncurses/ncurses-6.2.tar.gz",
"ta... | 0.22414 | 0.120129 |
from keras import layers, models
from keras.utils.generic_utils import register_keras_serializable
from keras.utils.tf_utils import shape_type_conversion
from .aim import AIM
from .sim import SIM
from ...backbone import Backbone
from ...common import ConvBnRelu, ClassificationHead, resize_by_sample
@register_keras_se... | segme/model/minet/model.py | from keras import layers, models
from keras.utils.generic_utils import register_keras_serializable
from keras.utils.tf_utils import shape_type_conversion
from .aim import AIM
from .sim import SIM
from ...backbone import Backbone
from ...common import ConvBnRelu, ClassificationHead, resize_by_sample
@register_keras_se... | 0.92801 | 0.276324 |
import requests
from bs4 import BeautifulSoup
import re
import time
import json
from mysql_handle.mysql_conn import MySqlConn
class AreaCodeParse(object):
html_file_path = '/Users/xxxs/Documents/dev-code/html_area_zip_code.txt'
html_file_parsed_path = '/Users/xxxs/Documents/dev-code/html_area_zip_code_pars... | pachong/xingzheng_area_code/area_zip_code.py |
import requests
from bs4 import BeautifulSoup
import re
import time
import json
from mysql_handle.mysql_conn import MySqlConn
class AreaCodeParse(object):
html_file_path = '/Users/xxxs/Documents/dev-code/html_area_zip_code.txt'
html_file_parsed_path = '/Users/xxxs/Documents/dev-code/html_area_zip_code_pars... | 0.204739 | 0.090856 |
from pygments.style import Style
from pygments.token import Token, Comment, Name, Keyword, Generic, Number
from pygments.token import Operator, String, Text, Error
white = '#ffffff'
bright_orange = '#f26512'
yolk_yellow = '#f8d734'
lemon_yellow = '#BBF34E'
bright_green = '#62d04e'
dark_green... | qtc_color_themes/blackboard.py | from pygments.style import Style
from pygments.token import Token, Comment, Name, Keyword, Generic, Number
from pygments.token import Operator, String, Text, Error
white = '#ffffff'
bright_orange = '#f26512'
yolk_yellow = '#f8d734'
lemon_yellow = '#BBF34E'
bright_green = '#62d04e'
dark_green... | 0.477067 | 0.083441 |
from kProcessor.kDataFrame import kDataFrame
class colored_kDataFrame(kDataFrame):
"""colored_kDataFrame class
.. note:: the colored_kDataFrame Inherits all the functions from :class:`kProcessor.kDataFrame` plus other new functions.
*Introduction*:
- The colored_kDataFrame class holds the Kmers c... | kProcessor/colored_kDataFrame.py | from kProcessor.kDataFrame import kDataFrame
class colored_kDataFrame(kDataFrame):
"""colored_kDataFrame class
.. note:: the colored_kDataFrame Inherits all the functions from :class:`kProcessor.kDataFrame` plus other new functions.
*Introduction*:
- The colored_kDataFrame class holds the Kmers c... | 0.913032 | 0.807081 |
from layout import datatypes
from . import root
class AlignLM(root.LayoutManager):
"""
A layout manager that takes one element and aligns it according to
the given parameters, optionally within a box of at least a given
size. Several of the other layout managers do some alignment as
part of their n... | layout/managers/align.py | from layout import datatypes
from . import root
class AlignLM(root.LayoutManager):
"""
A layout manager that takes one element and aligns it according to
the given parameters, optionally within a box of at least a given
size. Several of the other layout managers do some alignment as
part of their n... | 0.926458 | 0.560974 |
import argparse
import subprocess
import sys
import os
import shutil
import sysconfig
def vcpkg_root_dir():
return os.path.abspath(os.path.join(os.path.dirname(__file__)))
def run_vcpkg(triplet, vcpkg_args):
if not shutil.which("vcpkg"):
raise RuntimeError("vcpkg executable not found in the PATH env... | clean.py | import argparse
import subprocess
import sys
import os
import shutil
import sysconfig
def vcpkg_root_dir():
return os.path.abspath(os.path.join(os.path.dirname(__file__)))
def run_vcpkg(triplet, vcpkg_args):
if not shutil.which("vcpkg"):
raise RuntimeError("vcpkg executable not found in the PATH env... | 0.309128 | 0.104981 |
import json
class apiCallsWrapper(object):
def __init__(self, access_hostname, account_switch_key):
self.access_hostname = access_hostname
if account_switch_key != None:
self.account_switch_key = '&accountSwitchKey=' + account_switch_key
else:
self.account_switch_key... | bin/wrapper_api.py | import json
class apiCallsWrapper(object):
def __init__(self, access_hostname, account_switch_key):
self.access_hostname = access_hostname
if account_switch_key != None:
self.account_switch_key = '&accountSwitchKey=' + account_switch_key
else:
self.account_switch_key... | 0.205615 | 0.063106 |
import numpy as np
from scipy import signal
from scipy.fftpack import fft, ifft
def band_pass_filter(x, Fs, Fp1, Fp2):
"""Bandpass filter for the signal x.
An acausal fft algorithm is applied (i.e. no phase shift). The filter
functions is constructed from a Hamming window (window used in "firwin2"
fu... | mne/filter.py | import numpy as np
from scipy import signal
from scipy.fftpack import fft, ifft
def band_pass_filter(x, Fs, Fp1, Fp2):
"""Bandpass filter for the signal x.
An acausal fft algorithm is applied (i.e. no phase shift). The filter
functions is constructed from a Hamming window (window used in "firwin2"
fu... | 0.921079 | 0.816918 |
from pygame import MOUSEBUTTONDOWN, MOUSEBUTTONUP
from pygame.sprite import Sprite, Group
from pygame.image import load
from pygame.color import Color
from pygame.rect import Rect
from pygame.surface import Surface
from Utils.Panel import Element
def _collide(ra, rb):
c1 = ra.top <= rb.top <= ra.bottom
... | Frame/Utils/ButtonElement.py | from pygame import MOUSEBUTTONDOWN, MOUSEBUTTONUP
from pygame.sprite import Sprite, Group
from pygame.image import load
from pygame.color import Color
from pygame.rect import Rect
from pygame.surface import Surface
from Utils.Panel import Element
def _collide(ra, rb):
c1 = ra.top <= rb.top <= ra.bottom
... | 0.463687 | 0.122549 |
import tweepy, sys, os
from datetime import datetime
from time import tzname
from math import *
from random import randint, choice, seed
from PIL import Image, ImageDraw, ImageFont
# The PolyFriends Bot
# Find the bot at https://twitter.com/PolyFriendsBot!
# Created by <NAME> 2020
# Files
KEYS_PATH = "keys.txt... | polyfriends_bot.py | import tweepy, sys, os
from datetime import datetime
from time import tzname
from math import *
from random import randint, choice, seed
from PIL import Image, ImageDraw, ImageFont
# The PolyFriends Bot
# Find the bot at https://twitter.com/PolyFriendsBot!
# Created by <NAME> 2020
# Files
KEYS_PATH = "keys.txt... | 0.193033 | 0.142202 |
import json
from pathlib import Path
from typing import Any, Tuple
import click
from openff.toolkit.typing.engines.smirnoff import ForceField
from openff.units import unit
from rich import get_console, pretty
from rich.console import NewLine
from rich.padding import Padding
from interchange_regression_utilities.pertu... | value-propagation/enumerate-perturbations.py | import json
from pathlib import Path
from typing import Any, Tuple
import click
from openff.toolkit.typing.engines.smirnoff import ForceField
from openff.units import unit
from rich import get_console, pretty
from rich.console import NewLine
from rich.padding import Padding
from interchange_regression_utilities.pertu... | 0.59843 | 0.254113 |
from urllib import parse
import requests
import logging
import json
import time
from requests.adapters import HTTPAdapter
from requests.packages.urllib3.util.retry import Retry
from veracode_api_signing.exceptions import VeracodeAPISigningException
from veracode_api_signing.plugin_requests import RequestsAuthPluginVe... | veracode_api_py/apihelper.py |
from urllib import parse
import requests
import logging
import json
import time
from requests.adapters import HTTPAdapter
from requests.packages.urllib3.util.retry import Retry
from veracode_api_signing.exceptions import VeracodeAPISigningException
from veracode_api_signing.plugin_requests import RequestsAuthPluginVe... | 0.370795 | 0.050894 |
import requests
from source.util.settings import Settings
from source.util.timekeeper import Timestamps
from urllib.request import Request, urlopen
import webbrowser
from selenium import webdriver
from selenium.webdriver.chrome.options import Options
import chromedriver_autoinstaller
from selenium.webdriver.common.by i... | source/network/update_nodes.py | import requests
from source.util.settings import Settings
from source.util.timekeeper import Timestamps
from urllib.request import Request, urlopen
import webbrowser
from selenium import webdriver
from selenium.webdriver.chrome.options import Options
import chromedriver_autoinstaller
from selenium.webdriver.common.by i... | 0.202917 | 0.046486 |
from typing import Dict,Sequence,List
from dmt.entity import Entity
from dmt.blueprint import Blueprint
from .blueprints.gdfcylinder import GDFCylinderBlueprint
from typing import Dict
from sima.sima.moao import MOAO
from sima.sima.scriptablevalue import ScriptableValue
class GDFCylinder(MOAO):
"""
Keyword arg... | src/sima/hydro/gdfcylinder.py | from typing import Dict,Sequence,List
from dmt.entity import Entity
from dmt.blueprint import Blueprint
from .blueprints.gdfcylinder import GDFCylinderBlueprint
from typing import Dict
from sima.sima.moao import MOAO
from sima.sima.scriptablevalue import ScriptableValue
class GDFCylinder(MOAO):
"""
Keyword arg... | 0.88816 | 0.369315 |
__doc__ = """
Test arg parser
---------------
Test suite for arg_parser.
"""
import io
import argparse
import inspect
from unittest import TestCase, mock
from contextlib import redirect_stdout
from dataf import ArgParser
class CommandTest:
def run(self):
"""
Test command.
"""
... | dataf/tests/test_arg_parser.py |
__doc__ = """
Test arg parser
---------------
Test suite for arg_parser.
"""
import io
import argparse
import inspect
from unittest import TestCase, mock
from contextlib import redirect_stdout
from dataf import ArgParser
class CommandTest:
def run(self):
"""
Test command.
"""
... | 0.693265 | 0.394609 |
import sys,getopt
from CommonDefs import CommonDefs
def fileToTuples(file, delimiter):
f1 = open(file,"r")
data1 = [] #list of tuples from f1
for line in f1.readlines():
line = line.strip()
tokens = line.split(delimiter)
tuple = []
for token in tokens:
tuple.append(toke... | compareoutput.py | import sys,getopt
from CommonDefs import CommonDefs
def fileToTuples(file, delimiter):
f1 = open(file,"r")
data1 = [] #list of tuples from f1
for line in f1.readlines():
line = line.strip()
tokens = line.split(delimiter)
tuple = []
for token in tokens:
tuple.append(toke... | 0.126124 | 0.293613 |
import csv
# RICS .CSV
ricsFileName = 'Oboz'
ricsFile = open(ricsFileName + '.csv')
ricsReader = csv.reader(ricsFile)
ricsData = list(ricsReader)
# AMAZON .CSV
amzFileName = 'Amazon'
amzFile = open(amzFileName + '.csv')
amzReader = csv.reader(amzFile)
amzData = list(amzReader)
# Number of possible rows... | stockcheck.py | import csv
# RICS .CSV
ricsFileName = 'Oboz'
ricsFile = open(ricsFileName + '.csv')
ricsReader = csv.reader(ricsFile)
ricsData = list(ricsReader)
# AMAZON .CSV
amzFileName = 'Amazon'
amzFile = open(amzFileName + '.csv')
amzReader = csv.reader(amzFile)
amzData = list(amzReader)
# Number of possible rows... | 0.195364 | 0.197174 |
import os
import re
import shutil
import sys
import time
from optparse import OptionParser
sys.path.insert(1, re.sub(r'/\w*$', '', os.getcwd()))
import dirq # noqa E402
from dirq import queue # noqa E402
from dirq.QueueSimple import QueueSimple # noqa E402
opts = None
TEST = ''
ProgramName = sys.argv[0]
def in... | test/dqst.py | import os
import re
import shutil
import sys
import time
from optparse import OptionParser
sys.path.insert(1, re.sub(r'/\w*$', '', os.getcwd()))
import dirq # noqa E402
from dirq import queue # noqa E402
from dirq.QueueSimple import QueueSimple # noqa E402
opts = None
TEST = ''
ProgramName = sys.argv[0]
def in... | 0.322633 | 0.120077 |
import os
import json
import argparse
import random
import numpy as np
from scoring import inception
def get_args():
parser = argparse.ArgumentParser()
# Oft-changed parameters
parser.add_argument('-d', '--data_set', type=str, default='cifar', help='Can be either cifar|imagenet')
parser.add_argument('... | get_inception_score_with_dataloader.py | import os
import json
import argparse
import random
import numpy as np
from scoring import inception
def get_args():
parser = argparse.ArgumentParser()
# Oft-changed parameters
parser.add_argument('-d', '--data_set', type=str, default='cifar', help='Can be either cifar|imagenet')
parser.add_argument('... | 0.341912 | 0.108236 |
import pickle
import numpy as np
import numpy.linalg as la
from numpy.random import default_rng
# Create the random number generator
rng = default_rng()
class Organization(object):
"""Defines a class Organization which contains an organization network
structure (a.k.a. an organizational form) populated with ... | Organization.py | import pickle
import numpy as np
import numpy.linalg as la
from numpy.random import default_rng
# Create the random number generator
rng = default_rng()
class Organization(object):
"""Defines a class Organization which contains an organization network
structure (a.k.a. an organizational form) populated with ... | 0.833392 | 0.492127 |
import random
import warnings
from extra.trees.bst import BSTNode, BST
class TreapNode(BSTNode):
"""
A treap node is the basic unit for building Treap instances. A treap node
must contain a number. Each treap node has either zero, one or two children
treap nodes. The node that has no children is calle... | extra/trees/treap.py | import random
import warnings
from extra.trees.bst import BSTNode, BST
class TreapNode(BSTNode):
"""
A treap node is the basic unit for building Treap instances. A treap node
must contain a number. Each treap node has either zero, one or two children
treap nodes. The node that has no children is calle... | 0.926275 | 0.687361 |
from splinter import Browser
from bs4 import BeautifulSoup as bs
import time
import pandas as pd
import requests
import os
# https://splinter.readthedocs.io/en/latest/drivers/chrome.html
# get_ipython().system('which chromedriver')
def init_browser():
executable_path = {'executable_path': 'chromedriver.exe'}
... | scrape_mars.py | from splinter import Browser
from bs4 import BeautifulSoup as bs
import time
import pandas as pd
import requests
import os
# https://splinter.readthedocs.io/en/latest/drivers/chrome.html
# get_ipython().system('which chromedriver')
def init_browser():
executable_path = {'executable_path': 'chromedriver.exe'}
... | 0.322099 | 0.109064 |
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/py/proto/v3/Trash_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.273089 | 0.112844 |
import tensorflow as tf
import numpy as np
import functools
def lazy_property(function):
"""
Decorator to help structure graphs.
Taken from https://danijar.com/structuring-your-tensorflow-models/
"""
attribute = '_cache_' + function.__name__
@property
@functools.wraps(function)
def... | image_transfer_learning/network.py |
import tensorflow as tf
import numpy as np
import functools
def lazy_property(function):
"""
Decorator to help structure graphs.
Taken from https://danijar.com/structuring-your-tensorflow-models/
"""
attribute = '_cache_' + function.__name__
@property
@functools.wraps(function)
def... | 0.898921 | 0.497986 |
import numpy as np
import pandas as pd
import json
from pprint import pprint
import parser
def c_j(H, b, j, maximiser=1) :
"""indice de concordance partiel selon le critère j, max=1 si le critère est à maximiser,0 si non"""
print(" ------B----- ", b)
print("MAXIMISER ", type(maximiser), " H "... | FlaskApp/algo3.py | import numpy as np
import pandas as pd
import json
from pprint import pprint
import parser
def c_j(H, b, j, maximiser=1) :
"""indice de concordance partiel selon le critère j, max=1 si le critère est à maximiser,0 si non"""
print(" ------B----- ", b)
print("MAXIMISER ", type(maximiser), " H "... | 0.210279 | 0.387806 |
from typing import Optional
import pyexlatex as pl
import pyexlatex.table as lt
import pyexlatex.presentation as lp
import pyexlatex.graphics as lg
import pyexlatex.layouts as ll
import more_itertools
class _LabBlock(lp.Block):
def __init__(self, content, color: str = 'violet', **kwargs):
super().__init... | fin_model_course/pltemplates/blocks.py | from typing import Optional
import pyexlatex as pl
import pyexlatex.table as lt
import pyexlatex.presentation as lp
import pyexlatex.graphics as lg
import pyexlatex.layouts as ll
import more_itertools
class _LabBlock(lp.Block):
def __init__(self, content, color: str = 'violet', **kwargs):
super().__init... | 0.709724 | 0.154887 |
import pandas as pd
def two_values_melt(df, first_value_vars, second_value_vars, var_name,
value_name):
"""
First, build two DataFrames from the original one: one to compute a melt
for the value, another one to compute a melt for the evolution. Second,
merge these two DataFrames. T... | toucan_data_sdk/utils/generic/two_values_melt.py | import pandas as pd
def two_values_melt(df, first_value_vars, second_value_vars, var_name,
value_name):
"""
First, build two DataFrames from the original one: one to compute a melt
for the value, another one to compute a melt for the evolution. Second,
merge these two DataFrames. T... | 0.813942 | 0.672143 |
# Imports
import re
import os
import datetime
# Functions
'''
Primary handle function
Get request header, check method and path, and create response accordingly
'''
def http_handle(request_string):
assert not isinstance(request_string, bytes)
req_header = http_get_header(request_string)
path = req_header.... | functions.py |
# Imports
import re
import os
import datetime
# Functions
'''
Primary handle function
Get request header, check method and path, and create response accordingly
'''
def http_handle(request_string):
assert not isinstance(request_string, bytes)
req_header = http_get_header(request_string)
path = req_header.... | 0.385143 | 0.110952 |
from distutils.version import LooseVersion
import keras
from keras.models import Sequential
from keras.layers import Dense, Activation, Flatten, Dropout
if LooseVersion(keras.__version__) >= LooseVersion('2.0.0'):
from keras.layers import Conv2D
else:
from keras.layers import Convolution2D
import math
... | cleverhans_tutorials/mymodel.py | from distutils.version import LooseVersion
import keras
from keras.models import Sequential
from keras.layers import Dense, Activation, Flatten, Dropout
if LooseVersion(keras.__version__) >= LooseVersion('2.0.0'):
from keras.layers import Conv2D
else:
from keras.layers import Convolution2D
import math
... | 0.945876 | 0.558989 |
from layers import *
class DarkNet_Block(nn.Module):
"""
__version__ = 1.0
__date__ = Mar 7, 2022
paper : https://arxiv.org/abs/1804.02767
The structure is decribed in <Table 1.> of the paper.
"""
def __init__(self,
in_channels: int,
out_channels: int,
... | backbone/block/dark.py | from layers import *
class DarkNet_Block(nn.Module):
"""
__version__ = 1.0
__date__ = Mar 7, 2022
paper : https://arxiv.org/abs/1804.02767
The structure is decribed in <Table 1.> of the paper.
"""
def __init__(self,
in_channels: int,
out_channels: int,
... | 0.944389 | 0.477798 |
from unittest import mock
import pytest
from .cherry_picker import get_base_branch, get_current_branch, \
get_full_sha_from_short, is_cpython_repo, CherryPicker, \
normalize_commit_message
def test_get_base_branch():
cherry_pick_branch = 'backport-afc23f4-2.7'
result = get_base_branch(cherry_pick_br... | cherry_picker/cherry_picker/test.py | from unittest import mock
import pytest
from .cherry_picker import get_base_branch, get_current_branch, \
get_full_sha_from_short, is_cpython_repo, CherryPicker, \
normalize_commit_message
def test_get_base_branch():
cherry_pick_branch = 'backport-afc23f4-2.7'
result = get_base_branch(cherry_pick_br... | 0.628293 | 0.287818 |
import numpy as np
import csv
import matplotlib.pyplot as plt
n = 16 # number of input features.
m = 60 # number of training examples.
grad = np.zeros(shape = (n, 1))
theta = np.ones(shape=(n, 1), dtype = float)
hx = np.ones(shape=(m, 1), dtype = float)
file_handle = open("datasets/air-pollution/data.csv", "r")
reade... | master/multivariate-linear-regression.py | import numpy as np
import csv
import matplotlib.pyplot as plt
n = 16 # number of input features.
m = 60 # number of training examples.
grad = np.zeros(shape = (n, 1))
theta = np.ones(shape=(n, 1), dtype = float)
hx = np.ones(shape=(m, 1), dtype = float)
file_handle = open("datasets/air-pollution/data.csv", "r")
reade... | 0.360489 | 0.653956 |
import ethereum.tester
from ethereum.tester import TransactionFailed
import attr
import binascii
import unittest
import collections
from types import MethodType
from typing import List
__author__ = '<NAME>'
__email__ = '<EMAIL>'
__version__ = '3.2.0'
__license__ = 'MIT'
__all__ = [
'ContractTest',
'default_acc... | serpent_tests/__init__.py | import ethereum.tester
from ethereum.tester import TransactionFailed
import attr
import binascii
import unittest
import collections
from types import MethodType
from typing import List
__author__ = '<NAME>'
__email__ = '<EMAIL>'
__version__ = '3.2.0'
__license__ = 'MIT'
__all__ = [
'ContractTest',
'default_acc... | 0.665954 | 0.176672 |
import logging
import os
import platform
import pwd
import threading
import ipaddress
import requests
import yaml
from containercluster import ca, utils
__all__ = [
"Config",
"SSHKeyPair"
]
class Config(object):
dir_lock = threading.RLock()
log = logging.getLogger(__name__)
def __init__(sel... | containercluster/config.py | import logging
import os
import platform
import pwd
import threading
import ipaddress
import requests
import yaml
from containercluster import ca, utils
__all__ = [
"Config",
"SSHKeyPair"
]
class Config(object):
dir_lock = threading.RLock()
log = logging.getLogger(__name__)
def __init__(sel... | 0.400984 | 0.113064 |
import copy
class MetaPrototype(type):
""" A metaclass for Prototypes """
def __init__(cls, *args):
type.__init__(cls, *args)
cls.clone = lambda self: copy.deepcopy(self)
class MetaSingletonPrototype(type):
""" A metaclass for Singleton & Prototype patterns """
def __init__(cls, *arg... | Section 3/prototype.py | import copy
class MetaPrototype(type):
""" A metaclass for Prototypes """
def __init__(cls, *args):
type.__init__(cls, *args)
cls.clone = lambda self: copy.deepcopy(self)
class MetaSingletonPrototype(type):
""" A metaclass for Singleton & Prototype patterns """
def __init__(cls, *arg... | 0.682045 | 0.086555 |
del_items(0x801384E4)
SetType(0x801384E4, "void GameOnlyTestRoutine__Fv()")
del_items(0x801384EC)
SetType(0x801384EC, "int vecleny__Fii(int a, int b)")
del_items(0x80138510)
SetType(0x80138510, "int veclenx__Fii(int a, int b)")
del_items(0x8013853C)
SetType(0x8013853C, "void GetDamageAmt__FiPiT1(int i, int *mind, int *... | psx/_dump_/44/_dump_ida_/overlay_c/set_funcs.py | del_items(0x801384E4)
SetType(0x801384E4, "void GameOnlyTestRoutine__Fv()")
del_items(0x801384EC)
SetType(0x801384EC, "int vecleny__Fii(int a, int b)")
del_items(0x80138510)
SetType(0x80138510, "int veclenx__Fii(int a, int b)")
del_items(0x8013853C)
SetType(0x8013853C, "void GetDamageAmt__FiPiT1(int i, int *mind, int *... | 0.216177 | 0.152127 |
from pathlib import Path
import pickle
from typing import Optional
from matplotlib import cm
import matplotlib.pyplot as plt
import numpy as np
import matplotlib as mpl
def jitter(x):
return x + np.random.normal(scale=0.13, size=(len(x),))
def feature_scale(arr):
mini, maxi = arr.min(), arr.max()
return... | alr/training/diagnostics/__init__.py | from pathlib import Path
import pickle
from typing import Optional
from matplotlib import cm
import matplotlib.pyplot as plt
import numpy as np
import matplotlib as mpl
def jitter(x):
return x + np.random.normal(scale=0.13, size=(len(x),))
def feature_scale(arr):
mini, maxi = arr.min(), arr.max()
return... | 0.702836 | 0.504272 |
from itertools import accumulate
from bisect import bisect_right
import random
def basic_selection(population):
"""
:param population: Population Object
:return: Individual Obejct
"""
return random.choice(population.individuals)
def fitnetss_proporitional(population):
"""
... | EAlib/operators/selection.py |
from itertools import accumulate
from bisect import bisect_right
import random
def basic_selection(population):
"""
:param population: Population Object
:return: Individual Obejct
"""
return random.choice(population.individuals)
def fitnetss_proporitional(population):
"""
... | 0.752195 | 0.533154 |
# Python 2/3 compatibility
from __future__ import print_function
import os, numpy as np
import cv2 as cv
from tests_common import NewOpenCVTests
class aruco_test(NewOpenCVTests):
def test_idsAccessibility(self):
ids = np.arange(17)
rev_ids = ids[::-1]
aruco_dict = cv.aruco.Dictionar... | modules/aruco/misc/python/test/test_aruco.py |
# Python 2/3 compatibility
from __future__ import print_function
import os, numpy as np
import cv2 as cv
from tests_common import NewOpenCVTests
class aruco_test(NewOpenCVTests):
def test_idsAccessibility(self):
ids = np.arange(17)
rev_ids = ids[::-1]
aruco_dict = cv.aruco.Dictionar... | 0.682362 | 0.535281 |
import os
import copy
import logging
import argparse
from typing import *
logger = logging.getLogger(__name__)
def add_env_args_to_parser(parser):
# type: (argparse.ArgumentParser) -> None
parser.add_argument('--pd-work', required=False, default=None, help="Path to working directory")
parser.add_argume... | code/python/lib/mg_general/__init__.py |
import os
import copy
import logging
import argparse
from typing import *
logger = logging.getLogger(__name__)
def add_env_args_to_parser(parser):
# type: (argparse.ArgumentParser) -> None
parser.add_argument('--pd-work', required=False, default=None, help="Path to working directory")
parser.add_argume... | 0.598077 | 0.110759 |
import asyncio
import importlib
import json
import logging
import os
import pprint
import re
import sys
import time
import docker
import netaddr
import netifaces
import sh
import tornado.httpclient
from wotemu.enums import Labels
_CGROUP_PATH = "/proc/self/cgroup"
_STACK_NAMESPACE = "com.docker.stack.namespace"
_CID... | wotemu/utils.py | import asyncio
import importlib
import json
import logging
import os
import pprint
import re
import sys
import time
import docker
import netaddr
import netifaces
import sh
import tornado.httpclient
from wotemu.enums import Labels
_CGROUP_PATH = "/proc/self/cgroup"
_STACK_NAMESPACE = "com.docker.stack.namespace"
_CID... | 0.235284 | 0.081082 |
import os
import pytest
import caproto as ca
from caproto._headers import MessageHeader
def test_broadcast_auto_address_list():
pytest.importorskip('netifaces')
env = os.environ.copy()
try:
os.environ['EPICS_CA_ADDR_LIST'] = ''
os.environ['EPICS_CA_AUTO_ADDR_LIST'] = 'YES'
expect... | caproto/tests/test_utils.py | import os
import pytest
import caproto as ca
from caproto._headers import MessageHeader
def test_broadcast_auto_address_list():
pytest.importorskip('netifaces')
env = os.environ.copy()
try:
os.environ['EPICS_CA_ADDR_LIST'] = ''
os.environ['EPICS_CA_AUTO_ADDR_LIST'] = 'YES'
expect... | 0.484624 | 0.378344 |
from tornado.testing import AsyncHTTPTestCase
import tornado.web
import tornado.httputil
import tornado.escape
from unittest.mock import Mock
from error import DoesNotExist
from format import JsonAttributeGroup
from group import UnixGroup
from .group import (
HttpRequestGroup,
Parameter,
)
from storage import ... | src/unix_accounts/http_request/group_test.py | from tornado.testing import AsyncHTTPTestCase
import tornado.web
import tornado.httputil
import tornado.escape
from unittest.mock import Mock
from error import DoesNotExist
from format import JsonAttributeGroup
from group import UnixGroup
from .group import (
HttpRequestGroup,
Parameter,
)
from storage import ... | 0.753829 | 0.174903 |
# # S_FacRepNormTest [<img src="https://www.arpm.co/lab/icons/icon_permalink.png" width=30 height=30 style="display: inline;">](https://www.arpm.co/lab/redirect.php?code=S_FacRepNormTest&codeLang=Python)
# For details, see [here](https://www.arpm.co/lab/redirect.php?permalink=eb-fac-rep-port-norm).
# ## Prepare the e... | scripts/sources/S_FacRepNormTest.py |
# # S_FacRepNormTest [<img src="https://www.arpm.co/lab/icons/icon_permalink.png" width=30 height=30 style="display: inline;">](https://www.arpm.co/lab/redirect.php?code=S_FacRepNormTest&codeLang=Python)
# For details, see [here](https://www.arpm.co/lab/redirect.php?permalink=eb-fac-rep-port-norm).
# ## Prepare the e... | 0.686475 | 0.675186 |
import click
from flask import Flask,request
import os
import random
from DBInsertion import DBInsertion
from datetime import datetime,timedelta
current_directory= os.path.dirname(__file__)
database_file_path = os.path.join(current_directory, "../DBScript/CMD2WEB.sqlite")
database_object = DBInsertion(database_file_pat... | DBOperations/DBCommandLineTool.py | import click
from flask import Flask,request
import os
import random
from DBInsertion import DBInsertion
from datetime import datetime,timedelta
current_directory= os.path.dirname(__file__)
database_file_path = os.path.join(current_directory, "../DBScript/CMD2WEB.sqlite")
database_object = DBInsertion(database_file_pat... | 0.419648 | 0.055669 |
from datetime import datetime
from app.models.model import *
from flask_login import UserMixin,AnonymousUserMixin
from flask import current_app
from werkzeug.security import generate_password_hash, check_password_hash
from app.includes import file
from itsdangerous import TimedJSONWebSignatureSerializer as Serializer
... | app/models/user.py | from datetime import datetime
from app.models.model import *
from flask_login import UserMixin,AnonymousUserMixin
from flask import current_app
from werkzeug.security import generate_password_hash, check_password_hash
from app.includes import file
from itsdangerous import TimedJSONWebSignatureSerializer as Serializer
... | 0.453746 | 0.06256 |
import re
DEPS = [
'depot_tools/bot_update',
'depot_tools/gclient',
'recipe_engine/json',
'recipe_engine/path',
'recipe_engine/properties',
'recipe_engine/python',
'recipe_engine/raw_io',
'recipe_engine/step',
]
TESTS = [
{
'name': 'Test auto-bisect on tester',
'properties': {
'workdi... | scripts/slave/recipes/v8/infra_end_to_end.py |
import re
DEPS = [
'depot_tools/bot_update',
'depot_tools/gclient',
'recipe_engine/json',
'recipe_engine/path',
'recipe_engine/properties',
'recipe_engine/python',
'recipe_engine/raw_io',
'recipe_engine/step',
]
TESTS = [
{
'name': 'Test auto-bisect on tester',
'properties': {
'workdi... | 0.363195 | 0.135775 |
from .grammars import Language
java15 = Language("Java 1.5","""
goal ::= compilation_unit
literal ::= "INTEGER_LITERAL"
| "FLOATING_POINT_LITERAL"
| "BOOLEAN_LITERAL"
| "CHARACTER_LITERAL"
| "STRING_LITERAL"
| "NULL_LITERAL"
type ::= primitive_type
| reference_... | lib/eco/grammars/java15.py |
from .grammars import Language
java15 = Language("Java 1.5","""
goal ::= compilation_unit
literal ::= "INTEGER_LITERAL"
| "FLOATING_POINT_LITERAL"
| "BOOLEAN_LITERAL"
| "CHARACTER_LITERAL"
| "STRING_LITERAL"
| "NULL_LITERAL"
type ::= primitive_type
| reference_... | 0.507812 | 0.051966 |
import torch
import torch.nn as nn
from abc import ABC
class BaseNet(nn.Module, ABC):
def __init__(self, num_state, seed):
super(BaseNet, self).__init__()
# set seed
torch.manual_seed(seed)
self.num_hidden = 256
self.base = nn.Sequential(
nn.Linear(in_featur... | source/offline_ds_evaluation/networks.py | import torch
import torch.nn as nn
from abc import ABC
class BaseNet(nn.Module, ABC):
def __init__(self, num_state, seed):
super(BaseNet, self).__init__()
# set seed
torch.manual_seed(seed)
self.num_hidden = 256
self.base = nn.Sequential(
nn.Linear(in_featur... | 0.938322 | 0.423518 |
import torch
from torch.nn.utils.rnn import pad_sequence
from transformer import (
Transformer,
add_eos,
add_sos,
decoder_padding_mask,
encoder_padding_mask,
generate_square_subsequent_mask,
)
def test_encoder_padding_mask():
supervisions = {
"sequence_idx": torch.tensor([0, 1, 2... | egs/librispeech/ASR/conformer_ctc/test_transformer.py |
import torch
from torch.nn.utils.rnn import pad_sequence
from transformer import (
Transformer,
add_eos,
add_sos,
decoder_padding_mask,
encoder_padding_mask,
generate_square_subsequent_mask,
)
def test_encoder_padding_mask():
supervisions = {
"sequence_idx": torch.tensor([0, 1, 2... | 0.703549 | 0.669421 |
import argparse
import json
import pprint
import requests
import sys
import urllib
import random
import os
API_KEY = os.environ["DINECISION_API_KEY"]
from urllib.error import HTTPError
from urllib.parse import quote
from urllib.parse import urlencode
# API constants, you shouldn't have to change these.
API_HOST = ... | app/DineCision.py | import argparse
import json
import pprint
import requests
import sys
import urllib
import random
import os
API_KEY = os.environ["DINECISION_API_KEY"]
from urllib.error import HTTPError
from urllib.parse import quote
from urllib.parse import urlencode
# API constants, you shouldn't have to change these.
API_HOST = ... | 0.134776 | 0.066995 |
from __future__ import annotations
from typing import Optional, TYPE_CHECKING, Union
# noinspection PyPackageRequirements
from pyspark.sql.types import StructType, DataType
from spark_auto_mapper_fhir.fhir_types.boolean import FhirBoolean
from spark_auto_mapper_fhir.fhir_types.date import FhirDate
from spark_auto_mapp... | spark_auto_mapper_fhir/resources/related_person.py | from __future__ import annotations
from typing import Optional, TYPE_CHECKING, Union
# noinspection PyPackageRequirements
from pyspark.sql.types import StructType, DataType
from spark_auto_mapper_fhir.fhir_types.boolean import FhirBoolean
from spark_auto_mapper_fhir.fhir_types.date import FhirDate
from spark_auto_mapp... | 0.90185 | 0.277173 |
from weld.grizzly.core.indexes.base import Index
class ColumnIndex(Index):
"""
An index used for columns in a Grizzly DataFrame.
Each index value is a Python object. For operations between two DataFrames
with the same ColumnIndex, the result will also have the same index. For
operations between tw... | weld-python/weld/grizzly/core/indexes/column.py | from weld.grizzly.core.indexes.base import Index
class ColumnIndex(Index):
"""
An index used for columns in a Grizzly DataFrame.
Each index value is a Python object. For operations between two DataFrames
with the same ColumnIndex, the result will also have the same index. For
operations between tw... | 0.901271 | 0.865963 |
def merge_sorted_arrays(arrays):
if not len(arrays):
return arrays
# O(K) Time & Space
def create_min_heap_from_first_element(arrays):
min_heap = ModifiedMinHeap()
for i in range(len(arrays)):
# node_config = [initial_element, sub_array_idx,
# ... | algorithms/merge/array_merge_algorithms.py |
def merge_sorted_arrays(arrays):
if not len(arrays):
return arrays
# O(K) Time & Space
def create_min_heap_from_first_element(arrays):
min_heap = ModifiedMinHeap()
for i in range(len(arrays)):
# node_config = [initial_element, sub_array_idx,
# ... | 0.509032 | 0.292317 |
import os
import sys
import logging
logging.basicConfig(level=logging.INFO)
logger = logging.getLogger("tetrautils")
logger.setLevel(logging.INFO)
TEST_RESULTS_DIR = os.path.join(
os.path.dirname(os.path.abspath(__file__)), "test_results"
)
MENDER_QA_TEST_SUITES = [
{
"id": 1,
"name": "tes... | scripts/common.py |
import os
import sys
import logging
logging.basicConfig(level=logging.INFO)
logger = logging.getLogger("tetrautils")
logger.setLevel(logging.INFO)
TEST_RESULTS_DIR = os.path.join(
os.path.dirname(os.path.abspath(__file__)), "test_results"
)
MENDER_QA_TEST_SUITES = [
{
"id": 1,
"name": "tes... | 0.204263 | 0.196942 |
from typing import TYPE_CHECKING, Dict, Tuple
if TYPE_CHECKING:
from core.cell import Cell
class Distances:
"""Gives distances for all cells linked to a starting cell, called root.
This datastructure starts at a `root` cell and gives the distance
from all cells linked to the root to the root. So, ro... | core/distances.py | from typing import TYPE_CHECKING, Dict, Tuple
if TYPE_CHECKING:
from core.cell import Cell
class Distances:
"""Gives distances for all cells linked to a starting cell, called root.
This datastructure starts at a `root` cell and gives the distance
from all cells linked to the root to the root. So, ro... | 0.820793 | 0.69633 |
from pyfiler.setup_worker import SetupWorker
from watchdog.events import FileSystemEventHandler
from watchdog.observers import Observer
import os
import json
import argparse
import time
class MyHandler(FileSystemEventHandler):
"""subclass of FileSystemEventHandler, implements on_modified()."""
def __init__(se... | pyfiler/__main__.py | from pyfiler.setup_worker import SetupWorker
from watchdog.events import FileSystemEventHandler
from watchdog.observers import Observer
import os
import json
import argparse
import time
class MyHandler(FileSystemEventHandler):
"""subclass of FileSystemEventHandler, implements on_modified()."""
def __init__(se... | 0.399577 | 0.076857 |
from __future__ import print_function
import os
import subprocess
import sys
import yaml
from bcbiovm.docker import manage, mounts
DEFAULT_IMAGE = "quay.io/bcbio/bcbio-vc"
def full(args, dockerconf):
"""Full installaction of docker image and data.
"""
updates = []
args = add_install_defaults(args)
... | bcbiovm/docker/install.py | from __future__ import print_function
import os
import subprocess
import sys
import yaml
from bcbiovm.docker import manage, mounts
DEFAULT_IMAGE = "quay.io/bcbio/bcbio-vc"
def full(args, dockerconf):
"""Full installaction of docker image and data.
"""
updates = []
args = add_install_defaults(args)
... | 0.312475 | 0.12544 |
import numpy as np
import pandas as pd
import matplotlib.pyplot as plt
import seaborn as sns
import re
from nltk.corpus import stopwords
from sklearn.model_selection import train_test_split
from sklearn.feature_extraction.text import CountVectorizer, TfidfVectorizer
from sklearn.naive_bayes import MultinomialNB
from s... | NLP:-Classify-the-News-Articles/code.py | import numpy as np
import pandas as pd
import matplotlib.pyplot as plt
import seaborn as sns
import re
from nltk.corpus import stopwords
from sklearn.model_selection import train_test_split
from sklearn.feature_extraction.text import CountVectorizer, TfidfVectorizer
from sklearn.naive_bayes import MultinomialNB
from s... | 0.475849 | 0.433981 |
import sys, os, pdb
curr_path = os.getcwd();
sys.path.append(curr_path+'/..');
# Importing stuff from all folders in python path
import numpy as np
from focusfun import *
from refocus import *
from KSpaceFunctions import *
# TESTING CODE FOR FOCUS_DATA Below
import scipy.io as sio
from scipy.signal import hilbert, ga... | Python/kSpaceSimulations/KSpaceWalkingApertureFocusedTransmits.py | import sys, os, pdb
curr_path = os.getcwd();
sys.path.append(curr_path+'/..');
# Importing stuff from all folders in python path
import numpy as np
from focusfun import *
from refocus import *
from KSpaceFunctions import *
# TESTING CODE FOR FOCUS_DATA Below
import scipy.io as sio
from scipy.signal import hilbert, ga... | 0.447702 | 0.262599 |
import matplotlib.pyplot as plt
import seaborn as sns
import pandas as pd
import numpy as np
import math
from scipy.stats import mode
from typing import List
from VASA.vasa import VASA
from VASA.BasePlot import BasePlot
class Scatter(BasePlot):
def __init__(self, v: VASA, desc=None, figsize=(0, 0), titles: str ... | VASA/scatter.py | import matplotlib.pyplot as plt
import seaborn as sns
import pandas as pd
import numpy as np
import math
from scipy.stats import mode
from typing import List
from VASA.vasa import VASA
from VASA.BasePlot import BasePlot
class Scatter(BasePlot):
def __init__(self, v: VASA, desc=None, figsize=(0, 0), titles: str ... | 0.878184 | 0.552902 |
#Copyright 2015 RAPP
#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
#distr... | rapp_face_detection/tests/face_detection/functional_tests.py |
#Copyright 2015 RAPP
#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
#distr... | 0.617167 | 0.305982 |
""" generated source for module ConfigurableConfigPanel """
# package: org.ggp.base.player.gamer.statemachine.configurable
import java.awt.GridBagConstraints
import java.awt.GridBagLayout
import java.awt.Insets
import java.awt.event.ActionEvent
import java.awt.event.ActionListener
import java.io.BufferedReader
im... | ggpy/cruft/autocode/ConfigurableConfigPanel.py | """ generated source for module ConfigurableConfigPanel """
# package: org.ggp.base.player.gamer.statemachine.configurable
import java.awt.GridBagConstraints
import java.awt.GridBagLayout
import java.awt.Insets
import java.awt.event.ActionEvent
import java.awt.event.ActionListener
import java.io.BufferedReader
im... | 0.543348 | 0.074299 |