code stringlengths 2k 1.04M | repo_path stringlengths 5 517 | parsed_code stringlengths 0 1.04M | quality_prob float64 0.02 0.95 | learning_prob float64 0.02 0.93 |
|---|---|---|---|---|
import os
import re
import shutil
import socket
import sqlite3
import tempfile
import time
import unicodedata
from subprocess import check_call, CalledProcessError
import psutil
from common.exceptions import ConfigValueError
from library import Library
from library.MyTrakt.user import *
from pytvdbapi import api
from ... | dadvision/library/syncrmt.py | import os
import re
import shutil
import socket
import sqlite3
import tempfile
import time
import unicodedata
from subprocess import check_call, CalledProcessError
import psutil
from common.exceptions import ConfigValueError
from library import Library
from library.MyTrakt.user import *
from pytvdbapi import api
from ... | 0.425725 | 0.061819 |
from typing import Dict
from pyspark.sql import SparkSession, Column, DataFrame, Row
# noinspection PyUnresolvedReferences
from pyspark.sql.functions import lit
from spark_auto_mapper.automappers.automapper import AutoMapper
from spark_auto_mapper.data_types.literal import AutoMapperDataTypeLiteral
def test_auto_m... | tests/literal/test_literal.py | from typing import Dict
from pyspark.sql import SparkSession, Column, DataFrame, Row
# noinspection PyUnresolvedReferences
from pyspark.sql.functions import lit
from spark_auto_mapper.automappers.automapper import AutoMapper
from spark_auto_mapper.data_types.literal import AutoMapperDataTypeLiteral
def test_auto_m... | 0.825976 | 0.605916 |
import os
import re
import sklearn
import pandas as pd
import numpy as np
from nltk.tokenize import word_tokenize
from nltk.corpus import stopwords
import matplotlib.pyplot as plt
from deBERTa import deberta
import copy
import torch
import os
import json
from .ops import *
from .bert import *
from .config import Mo... | Scripts/train_model.py | import os
import re
import sklearn
import pandas as pd
import numpy as np
from nltk.tokenize import word_tokenize
from nltk.corpus import stopwords
import matplotlib.pyplot as plt
from deBERTa import deberta
import copy
import torch
import os
import json
from .ops import *
from .bert import *
from .config import Mo... | 0.577495 | 0.192103 |
import heapq
# Licensed under the Creative Commons attribution-noncommercial-sharealike License by <NAME>
# Original version can be found at
# http://www.gghh.name/dibtp/2014/02/25/how-does-mercurial-select-the-greatest-common-ancestor.html
def depthf(a, b, pfunc):
print(str(a) + ' ' + str(b))
a, b = sorted... | snapmerge/home/ancestors.py | import heapq
# Licensed under the Creative Commons attribution-noncommercial-sharealike License by <NAME>
# Original version can be found at
# http://www.gghh.name/dibtp/2014/02/25/how-does-mercurial-select-the-greatest-common-ancestor.html
def depthf(a, b, pfunc):
print(str(a) + ' ' + str(b))
a, b = sorted... | 0.653901 | 0.341116 |
import re
class DataTableParserSupportFunctions:
def __init__(self): # pragma: no coverage
pass
@staticmethod
def convert_to_integer(value, defaultValue=None):
if value is None:
return None
if not str(value).isnumeric():
return defaultValue
... | reqlog/support/datatablessupport/datatablessupport.py | import re
class DataTableParserSupportFunctions:
def __init__(self): # pragma: no coverage
pass
@staticmethod
def convert_to_integer(value, defaultValue=None):
if value is None:
return None
if not str(value).isnumeric():
return defaultValue
... | 0.417271 | 0.114393 |
import argparse
import logging
import sys
import numpy as np
logging.basicConfig(
format='%(levelname)s(%(filename)s:%(lineno)d): %(message)s')
def levenshtein(u, v):
prev = None
curr = [0] + list(range(1, len(v) + 1))
# Operations: (SUB, DEL, INS)
prev_ops = None
curr_ops = [(0, 0, i) for i ... | utils/xer.py |
import argparse
import logging
import sys
import numpy as np
logging.basicConfig(
format='%(levelname)s(%(filename)s:%(lineno)d): %(message)s')
def levenshtein(u, v):
prev = None
curr = [0] + list(range(1, len(v) + 1))
# Operations: (SUB, DEL, INS)
prev_ops = None
curr_ops = [(0, 0, i) for i ... | 0.052062 | 0.258373 |
"""Simulation of the compton effect."""
import random, pygame,math,os
import tkinter as tk
from tkinter import ttk
from tkinter import *
SCREEN_WIDTH = 800
SCREEN_HEIGHT = 600
State = -1
Phi = math.pi/4
Psi = -math.pi/4
def load_png(name: str):
"""Charge une image et retourne un objet image"""
fullname = nam... | compton.py | """Simulation of the compton effect."""
import random, pygame,math,os
import tkinter as tk
from tkinter import ttk
from tkinter import *
SCREEN_WIDTH = 800
SCREEN_HEIGHT = 600
State = -1
Phi = math.pi/4
Psi = -math.pi/4
def load_png(name: str):
"""Charge une image et retourne un objet image"""
fullname = nam... | 0.504883 | 0.317929 |
import pytest
from app import face_app
import io
import cv2
import json
# Run the command below to run the tests for face_app.py api
# py.test -p no:warnings
@pytest.fixture
def client():
face_app.app.config['TESTING'] = True
with face_app.app.test_client() as client:
yield client
def read_img(pat... | app/test/test_face_app.py | import pytest
from app import face_app
import io
import cv2
import json
# Run the command below to run the tests for face_app.py api
# py.test -p no:warnings
@pytest.fixture
def client():
face_app.app.config['TESTING'] = True
with face_app.app.test_client() as client:
yield client
def read_img(pat... | 0.352871 | 0.340814 |
from __future__ import division, print_function
import os
import numpy as np
class FoilData(object):
"""
Object that represents a foil characteristic database.
"""
def __init__(self):
self.alpha = []
self.cl = []
self.cd = []
self.cm = []
self.comments = ["// Re... | foampy/foil.py | from __future__ import division, print_function
import os
import numpy as np
class FoilData(object):
"""
Object that represents a foil characteristic database.
"""
def __init__(self):
self.alpha = []
self.cl = []
self.cd = []
self.cm = []
self.comments = ["// Re... | 0.538983 | 0.141637 |
import os, sys, struct, codecs, inspect, binascii, optparse, construct
def write_dict(fdWriter, dictObj):
fdWriter.write("{")
keys = dictObj.keys()
for x in xrange(len(keys)):
item = '"{}":"{}"'.format(keys[x], dictObj[keys[x]].strip("\0"))
fdWriter.write(item)
if x != len(keys) - ... | binary_parser.py |
import os, sys, struct, codecs, inspect, binascii, optparse, construct
def write_dict(fdWriter, dictObj):
fdWriter.write("{")
keys = dictObj.keys()
for x in xrange(len(keys)):
item = '"{}":"{}"'.format(keys[x], dictObj[keys[x]].strip("\0"))
fdWriter.write(item)
if x != len(keys) - ... | 0.306008 | 0.169612 |
import getpass
import os
# Configurations
IS_SERVER = False
DUMPING = True
# File directories
FILE_CONTENTS_FOLDER = "filecontents/"
RESULTS_FOLDER = "analysis_results/"
WORKSPACE_DIR = "workspace/"
TMP_FOLDER = os.path.expanduser(
"~\\AppData\\Local\\Temp") if os.name == "nt" else "/tmp/"
UPLOAD_FOLDER = os.pa... | lexos/helpers/constants.py | import getpass
import os
# Configurations
IS_SERVER = False
DUMPING = True
# File directories
FILE_CONTENTS_FOLDER = "filecontents/"
RESULTS_FOLDER = "analysis_results/"
WORKSPACE_DIR = "workspace/"
TMP_FOLDER = os.path.expanduser(
"~\\AppData\\Local\\Temp") if os.name == "nt" else "/tmp/"
UPLOAD_FOLDER = os.pa... | 0.162979 | 0.056107 |
import glob
import numpy as np
import cv2
from matplotlib import pyplot as plt
### grab images from a directory
### returns np array of images
def read_image_dir(path):
Images = np.array([plt.imread(file) for file in glob.glob(path + '*')])
return Images
### apply color thresholds to image
### returns binariz... | functions.py | import glob
import numpy as np
import cv2
from matplotlib import pyplot as plt
### grab images from a directory
### returns np array of images
def read_image_dir(path):
Images = np.array([plt.imread(file) for file in glob.glob(path + '*')])
return Images
### apply color thresholds to image
### returns binariz... | 0.722918 | 0.613208 |
from mttools.utils.exceptions import DimensionError, NoInverseWarning
class Matrix:
"""
Models matrix objects
Rows by Columns
Attributes:
:array: (Array Like)
The matrix
:num_rows: (int)
Number of rows
:num_columns: (int)
Number of Column... | mttools/linear_algebra_tools/matrix.py | from mttools.utils.exceptions import DimensionError, NoInverseWarning
class Matrix:
"""
Models matrix objects
Rows by Columns
Attributes:
:array: (Array Like)
The matrix
:num_rows: (int)
Number of rows
:num_columns: (int)
Number of Column... | 0.92832 | 0.671891 |
import sqlite3
class User(object):
def __init__(self, id, username, password, highschool, dreamschool):
self.id = id
self.username = username
self.password = password
self.highschool = highschool
self.dreamschool = dreamschool
@classmethod
def store_to_db(self, ... | python-backend/model/user.py | import sqlite3
class User(object):
def __init__(self, id, username, password, highschool, dreamschool):
self.id = id
self.username = username
self.password = password
self.highschool = highschool
self.dreamschool = dreamschool
@classmethod
def store_to_db(self, ... | 0.385837 | 0.183502 |
import pandas as pd
import numpy as np
import plotly.express as px
def get_timerange_(df,resample):
"""get first and last timepoint from the dataframe,
and return a resampled datetimeindex.
Parameters
----------
df : Pandas Dataframe
Dataframe containing the data
ressample : str
... | niimpy/exploration/eda/punchcard.py | import pandas as pd
import numpy as np
import plotly.express as px
def get_timerange_(df,resample):
"""get first and last timepoint from the dataframe,
and return a resampled datetimeindex.
Parameters
----------
df : Pandas Dataframe
Dataframe containing the data
ressample : str
... | 0.810854 | 0.665302 |
import unittest
import mock
import os
from redisapi.storage import Instance
class InstanceTest(unittest.TestCase):
def test_instance(self):
host = "host"
id = "id"
name = "name"
port = "port"
plan = "plan"
endpoints = [{"port": port, "host": host, "container_id":... | tests/test_storage.py |
import unittest
import mock
import os
from redisapi.storage import Instance
class InstanceTest(unittest.TestCase):
def test_instance(self):
host = "host"
id = "id"
name = "name"
port = "port"
plan = "plan"
endpoints = [{"port": port, "host": host, "container_id":... | 0.524151 | 0.315802 |
from screws.freeze.base import FrozenOnly
class _3dCSCG_ExactSolution_Allocator(FrozenOnly):
""""""
@classmethod
def ___exact_solution_name___(cls):
return {'icpsNS:TGV1' : 'TGV1',
'icpsNS:sincosRC': 'SinCosRebholz_Conservation',
'icpsNS:sincos_CCBF' : 'SinCos_... | objects/CSCG/_3d/exact_solutions/status/allocator.py | from screws.freeze.base import FrozenOnly
class _3dCSCG_ExactSolution_Allocator(FrozenOnly):
""""""
@classmethod
def ___exact_solution_name___(cls):
return {'icpsNS:TGV1' : 'TGV1',
'icpsNS:sincosRC': 'SinCosRebholz_Conservation',
'icpsNS:sincos_CCBF' : 'SinCos_... | 0.493409 | 0.192388 |
from typing import List, Optional
from dataclasses import dataclass
from botbuilder.schema import ActivityTypes, Activity
from botbuilder.core import MessageFactory
from botbuilder.dialogs import (
WaterfallDialog,
WaterfallStepContext,
DialogTurnResult,
PromptOptions,
Choice,
ChoicePrompt,
)
fr... | dialogs/azure_dialog.py | from typing import List, Optional
from dataclasses import dataclass
from botbuilder.schema import ActivityTypes, Activity
from botbuilder.core import MessageFactory
from botbuilder.dialogs import (
WaterfallDialog,
WaterfallStepContext,
DialogTurnResult,
PromptOptions,
Choice,
ChoicePrompt,
)
fr... | 0.820146 | 0.091544 |
import numpy as np
import cvxpy as cp
from sklearn.base import BaseEstimator, clone
from sklearn.utils import check_random_state
from sklearn.ensemble._base import _set_random_states
from .utils import my_fit
# https://proceedings.neurips.cc/paper/1996/file/f47330643ae134ca204bf6b2481fec47-Paper.pdf
ENSEMBLE_MODE_BALA... | early_stopping_estimators.py | import numpy as np
import cvxpy as cp
from sklearn.base import BaseEstimator, clone
from sklearn.utils import check_random_state
from sklearn.ensemble._base import _set_random_states
from .utils import my_fit
# https://proceedings.neurips.cc/paper/1996/file/f47330643ae134ca204bf6b2481fec47-Paper.pdf
ENSEMBLE_MODE_BALA... | 0.624294 | 0.235592 |
import sys
sys.path.append('/usr/li-wen')
import csv
import copy
import codecs
import configparser
from logging import log
import time
from libs.conf import global_config
from libs.cloud.HWCloud.ecs_servers import ecs_server
from main.core.auto_extend import AutoExtendWorker
from main.monitor.workerstatus import QueryO... | main/wsdm.py | import sys
sys.path.append('/usr/li-wen')
import csv
import copy
import codecs
import configparser
from logging import log
import time
from libs.conf import global_config
from libs.cloud.HWCloud.ecs_servers import ecs_server
from main.core.auto_extend import AutoExtendWorker
from main.monitor.workerstatus import QueryO... | 0.34798 | 0.115961 |
from quilt3.data_transfer import S3Api, S3ClientProvider, get_bytes, list_url
from quilt3.util import PhysicalKey
from .base import PackageRegistryV1, PackageRegistryV2
def s3_list_objects(**kwargs):
s3_client = S3ClientProvider().find_correct_client(S3Api.LIST_OBJECTS_V2, kwargs['Bucket'], kwargs)
return s3... | api/python/quilt3/backends/s3.py | from quilt3.data_transfer import S3Api, S3ClientProvider, get_bytes, list_url
from quilt3.util import PhysicalKey
from .base import PackageRegistryV1, PackageRegistryV2
def s3_list_objects(**kwargs):
s3_client = S3ClientProvider().find_correct_client(S3Api.LIST_OBJECTS_V2, kwargs['Bucket'], kwargs)
return s3... | 0.409457 | 0.06767 |
import os
import copy
import lmdb
import numpy as np
import simplejson as json
from manet.utils import write_list, read_list
class LmdbDb(object):
def __init__(self, path, db_name):
"""Load an LMDB database, containing a dataset.
The dataset should be structured as image_id: binary representing t... | manet/lmdb/dataset.py | import os
import copy
import lmdb
import numpy as np
import simplejson as json
from manet.utils import write_list, read_list
class LmdbDb(object):
def __init__(self, path, db_name):
"""Load an LMDB database, containing a dataset.
The dataset should be structured as image_id: binary representing t... | 0.592902 | 0.11689 |
import numpy as np
from Parse_POSCAR import parse_POSCAR
from atoms_dist import atoms_dist
import math
def find_neighbors(ctrAtom, cutoff, POSCAR="POSCAR"):
""" Return the coordinates of neighboring atoms.
Use VASP 5 format POSCAR or CONTCAR files. Periodic boundary
conditions are taken into accont of.
... | Find_neighbors.py | import numpy as np
from Parse_POSCAR import parse_POSCAR
from atoms_dist import atoms_dist
import math
def find_neighbors(ctrAtom, cutoff, POSCAR="POSCAR"):
""" Return the coordinates of neighboring atoms.
Use VASP 5 format POSCAR or CONTCAR files. Periodic boundary
conditions are taken into accont of.
... | 0.789153 | 0.62621 |
from utils.core import *
import random
import unittest
import random
from typing import List, Tuple, Callable, Dict
from abc import ABC
from utils.buffer import ReplayBuffer
class SimulationBuffer:
def __init__(self):
self.frames: List[Dict[AgentKey, AgentReplayFrameBuilder]] = []
def push(self,
... | envs/base_env.py | from utils.core import *
import random
import unittest
import random
from typing import List, Tuple, Callable, Dict
from abc import ABC
from utils.buffer import ReplayBuffer
class SimulationBuffer:
def __init__(self):
self.frames: List[Dict[AgentKey, AgentReplayFrameBuilder]] = []
def push(self,
... | 0.716715 | 0.308359 |
import tempfile
import os
from couchbase.exceptions import (AuthError, ArgumentError,
BucketNotFoundError, ConnectError,
NotFoundError)
from couchbase.libcouchbase import Connection
from tests.base import CouchbaseTestCase
class ConnectionTest(Cou... | tests/test_connection.py |
import tempfile
import os
from couchbase.exceptions import (AuthError, ArgumentError,
BucketNotFoundError, ConnectError,
NotFoundError)
from couchbase.libcouchbase import Connection
from tests.base import CouchbaseTestCase
class ConnectionTest(Cou... | 0.315314 | 0.215268 |
import contextlib
import os
import re
import subprocess
import sys
class Module:
def __init__(self, name, arguments, signature):
self.name = name
self.arguments = arguments
self.signature = signature
def text(self, indent=""):
arguments = ""
if indent == "" and self.ar... | doc/utop/extract.py | import contextlib
import os
import re
import subprocess
import sys
class Module:
def __init__(self, name, arguments, signature):
self.name = name
self.arguments = arguments
self.signature = signature
def text(self, indent=""):
arguments = ""
if indent == "" and self.ar... | 0.348091 | 0.191252 |
from sqlalchemy.orm import sessionmaker
from sqlalchemy.orm import scoped_session
from .models import Base
from .utils.enum import AutoNumber
from .utils.conflictresolver import ConflictResolver
class Subsystem(AutoNumber):
"""Enumerator for available cryptoassets library subsystems.
Depending on your appl... | cryptoassets/core/app.py | from sqlalchemy.orm import sessionmaker
from sqlalchemy.orm import scoped_session
from .models import Base
from .utils.enum import AutoNumber
from .utils.conflictresolver import ConflictResolver
class Subsystem(AutoNumber):
"""Enumerator for available cryptoassets library subsystems.
Depending on your appl... | 0.747063 | 0.236087 |
from pymongo import MongoClient
def get_db():
client = MongoClient('localhost', 27017)
return client.archive
def create_tag(tag, description):
"""
Attempts to create a new tag
Parameters
----------
tag : string
The tag string
description : string
The description for ... | derpi_tags.py | from pymongo import MongoClient
def get_db():
client = MongoClient('localhost', 27017)
return client.archive
def create_tag(tag, description):
"""
Attempts to create a new tag
Parameters
----------
tag : string
The tag string
description : string
The description for ... | 0.835249 | 0.277412 |
import datetime
from south.db import db
from south.v2 import SchemaMigration
from django.db import models
class Migration(SchemaMigration):
def forwards(self, orm):
# Deleting field 'PostalCode.latitude'
db.delete_column('postalcodes_postalcode', 'latitude')
# Deleting field 'PostalCode.... | postalcodes/south_migrations/0002_auto__del_field_postalcode_latitude__del_field_postalcode_longitude__a.py | import datetime
from south.db import db
from south.v2 import SchemaMigration
from django.db import models
class Migration(SchemaMigration):
def forwards(self, orm):
# Deleting field 'PostalCode.latitude'
db.delete_column('postalcodes_postalcode', 'latitude')
# Deleting field 'PostalCode.... | 0.405802 | 0.126569 |
import time
import tornado.ioloop
from yadacoin.core.config import get_config
class HealthItem:
last_activity = time.time()
timeout = 600
status = True
ignore = False
def __init__(self):
self.config = get_config()
def report_bad_health(self, message):
self.config.app_log.error... | yadacoin/core/health.py | import time
import tornado.ioloop
from yadacoin.core.config import get_config
class HealthItem:
last_activity = time.time()
timeout = 600
status = True
ignore = False
def __init__(self):
self.config = get_config()
def report_bad_health(self, message):
self.config.app_log.error... | 0.379263 | 0.116036 |
import os
import unittest
import tempfile
import simplejson as json
import numpy as np
import xarray as xr
import netCDF4 as nc4
from ioos_qc import utils
class AuxillaryCheckTest(unittest.TestCase):
# Range of times every 15 minutes from 2013-01-01 to 2013-01-02.
times = np.arange('2013-01-01 00:00:00', '... | tests/test_utils.py | import os
import unittest
import tempfile
import simplejson as json
import numpy as np
import xarray as xr
import netCDF4 as nc4
from ioos_qc import utils
class AuxillaryCheckTest(unittest.TestCase):
# Range of times every 15 minutes from 2013-01-01 to 2013-01-02.
times = np.arange('2013-01-01 00:00:00', '... | 0.626238 | 0.554229 |
from PyQt4.QtGui import QCursor, QIcon
import os
from tempfile import NamedTemporaryFile
from revkit import *
from core.BaseItem import *
from core.SpinBoxDelegate import *
from ui.PatternInput import *
from ui.DesignerWidget import *
class PatternInput( DesignerWidget ):
deleteColumn = -1
def __init__( ... | rkqc/tools/gui/items/PatternInputItem.py | from PyQt4.QtGui import QCursor, QIcon
import os
from tempfile import NamedTemporaryFile
from revkit import *
from core.BaseItem import *
from core.SpinBoxDelegate import *
from ui.PatternInput import *
from ui.DesignerWidget import *
class PatternInput( DesignerWidget ):
deleteColumn = -1
def __init__( ... | 0.315841 | 0.114196 |
from __future__ import print_function, division, absolute_import
import os
from fontTools.misc.py23 import *
from ufo2ft.preProcessor import (
OTFPreProcessor, TTFPreProcessor, TTFInterpolatablePreProcessor)
from ufo2ft.featureCompiler import FeatureCompiler
from ufo2ft.outlineCompiler import OutlineOTFCompiler,... | Lib/ufo2ft/__init__.py | from __future__ import print_function, division, absolute_import
import os
from fontTools.misc.py23 import *
from ufo2ft.preProcessor import (
OTFPreProcessor, TTFPreProcessor, TTFInterpolatablePreProcessor)
from ufo2ft.featureCompiler import FeatureCompiler
from ufo2ft.outlineCompiler import OutlineOTFCompiler,... | 0.690559 | 0.131173 |
from collections import defaultdict
from typing import DefaultDict, Dict, List, AnyStr, Set
from yzrpc._types import ServiceType
class Protobuf:
def __init__(self):
self.modules: Set[str] = set()
self.messages: Dict[AnyStr, Dict] = dict()
self.services: List[ServiceType] = list()
@cl... | yzrpc/proto.py | from collections import defaultdict
from typing import DefaultDict, Dict, List, AnyStr, Set
from yzrpc._types import ServiceType
class Protobuf:
def __init__(self):
self.modules: Set[str] = set()
self.messages: Dict[AnyStr, Dict] = dict()
self.services: List[ServiceType] = list()
@cl... | 0.435541 | 0.111048 |
from django.db import models
from django.contrib.auth.models import PermissionsMixin
from django.contrib.auth.base_user import AbstractBaseUser
from django.contrib.auth.models import User
from django.contrib.auth.backends import ModelBackend, UserModel
from django.core.exceptions import MultipleObjectsReturned
from dja... | search/models.py | from django.db import models
from django.contrib.auth.models import PermissionsMixin
from django.contrib.auth.base_user import AbstractBaseUser
from django.contrib.auth.models import User
from django.contrib.auth.backends import ModelBackend, UserModel
from django.core.exceptions import MultipleObjectsReturned
from dja... | 0.553626 | 0.097648 |
import re
import sys
import glob
import json
import getpass
from string import Template
reload(sys)
sys.setdefaultencoding('utf-8')
import tlib.log as log
import tlib.conf as conf
import tlib.auto as auto
import tlib.xconf as xconf
import tlib.local as local
from tlib.path import Path
from tlib.path import curr_path... | flask_demo/__init__.py |
import re
import sys
import glob
import json
import getpass
from string import Template
reload(sys)
sys.setdefaultencoding('utf-8')
import tlib.log as log
import tlib.conf as conf
import tlib.auto as auto
import tlib.xconf as xconf
import tlib.local as local
from tlib.path import Path
from tlib.path import curr_path... | 0.122996 | 0.051487 |
from __future__ import absolute_import
import math
import numpy as np
from scipy import ndimage as ndi
from skimage.measure._regionprops import _RegionProperties
import cc3d
import tqdm
_supported_metrics = [
'area',
'bbox_area',
'convex_area',
'filled_area']
def _labeling(object_label, connectivity... | refine_label/remove_island.py | from __future__ import absolute_import
import math
import numpy as np
from scipy import ndimage as ndi
from skimage.measure._regionprops import _RegionProperties
import cc3d
import tqdm
_supported_metrics = [
'area',
'bbox_area',
'convex_area',
'filled_area']
def _labeling(object_label, connectivity... | 0.721841 | 0.226431 |
import numpy as np
from keras.layers import Flatten, Dense, ZeroPadding2D, Conv2D, Activation, MaxPooling2D, Dropout
from keras.preprocessing.image import ImageDataGenerator
from keras.layers import Flatten, Dense, Conv2D, Activation, MaxPooling2D, Dropout
from keras.models import Sequential, load_model
from keras.call... | src/CNN_augmented.py | import numpy as np
from keras.layers import Flatten, Dense, ZeroPadding2D, Conv2D, Activation, MaxPooling2D, Dropout
from keras.preprocessing.image import ImageDataGenerator
from keras.layers import Flatten, Dense, Conv2D, Activation, MaxPooling2D, Dropout
from keras.models import Sequential, load_model
from keras.call... | 0.859561 | 0.396448 |
import argparse
from functools import wraps
import logging
import os
import subprocess
import sys
from clams import arg, Command
import utilities
from . import current_project
logger = logging.getLogger(__name__)
dj = Command(
name='dj',
title='Django commands and tasks.',
description='Django commands and t... | unb_cli/unb/django_commands.py | import argparse
from functools import wraps
import logging
import os
import subprocess
import sys
from clams import arg, Command
import utilities
from . import current_project
logger = logging.getLogger(__name__)
dj = Command(
name='dj',
title='Django commands and tasks.',
description='Django commands and t... | 0.253214 | 0.053775 |
"""Application Definition"""
from os import fsdecode
from accelpy._common import yaml_read, yaml_write
from accelpy.exceptions import ConfigurationException
# Application definition format
FORMAT = {
'application': {
'_node': dict,
'name': dict(
required=True,
desc='Applica... | accelpy/_application.py | """Application Definition"""
from os import fsdecode
from accelpy._common import yaml_read, yaml_write
from accelpy.exceptions import ConfigurationException
# Application definition format
FORMAT = {
'application': {
'_node': dict,
'name': dict(
required=True,
desc='Applica... | 0.748444 | 0.227641 |
import types
import requests
from ._insert import getInsertRequestBody, processResponse, convertResponse
from ._config import Configuration
from ._config import InsertOptions, ConnectionConfig
from ._connection import createRequest
from ._detokenize import sendDetokenizeRequests, createDetokenizeResponseBody
from ._get... | skyflow/vault/_client.py | import types
import requests
from ._insert import getInsertRequestBody, processResponse, convertResponse
from ._config import Configuration
from ._config import InsertOptions, ConnectionConfig
from ._connection import createRequest
from ._detokenize import sendDetokenizeRequests, createDetokenizeResponseBody
from ._get... | 0.526099 | 0.076822 |
from telegram.ext import (Updater,CommandHandler,MessageHandler,Filters)
from models.msg_handler import (message_handler)
from models.database import (get_all_by_col,put_in_table, rem_from_table, get_cols_by_col)
import urllib
DB = "backlog.db"
TABLE_NAME = "backlog"
# logs command
def logs(update,ctx):
chat... | src/main.py | from telegram.ext import (Updater,CommandHandler,MessageHandler,Filters)
from models.msg_handler import (message_handler)
from models.database import (get_all_by_col,put_in_table, rem_from_table, get_cols_by_col)
import urllib
DB = "backlog.db"
TABLE_NAME = "backlog"
# logs command
def logs(update,ctx):
chat... | 0.121061 | 0.062847 |
from django import forms
from django.utils.translation import gettext_lazy as _
from .models import SoknaRequest
from crispy_forms.helper import FormHelper
from crispy_forms.layout import Submit
class SoknaRequestForm(forms.ModelForm):
# born_d = forms.IntegerField(widget=forms.NumberInput(attrs={'placeholder':'dd... | sokna/forms.py | from django import forms
from django.utils.translation import gettext_lazy as _
from .models import SoknaRequest
from crispy_forms.helper import FormHelper
from crispy_forms.layout import Submit
class SoknaRequestForm(forms.ModelForm):
# born_d = forms.IntegerField(widget=forms.NumberInput(attrs={'placeholder':'dd... | 0.388154 | 0.099645 |
import logging
import sys
from os import path
from keras.preprocessing import sequence
from keras.utils import np_utils
from nltk import TreebankWordTokenizer
from sklearn.calibration import CalibratedClassifierCV
from cntk.train.distributed import Communicator
from sklearn.feature_extraction.text import TfidfTransfor... | src/Sentiment.py | import logging
import sys
from os import path
from keras.preprocessing import sequence
from keras.utils import np_utils
from nltk import TreebankWordTokenizer
from sklearn.calibration import CalibratedClassifierCV
from cntk.train.distributed import Communicator
from sklearn.feature_extraction.text import TfidfTransfor... | 0.569134 | 0.319572 |
from __future__ import print_function
import argparse
import logging
import os
import shutil
import sys
import tempfile
from distutils.dir_util import copy_tree
from mercurial import hg, ui
from whoosh.filedb.filestore import FileStorage
sys.path.insert(1, os.path.abspath(os.path.join(os.path.dirname(__file__), os.p... | scripts/tool_shed/build_ts_whoosh_index.py | from __future__ import print_function
import argparse
import logging
import os
import shutil
import sys
import tempfile
from distutils.dir_util import copy_tree
from mercurial import hg, ui
from whoosh.filedb.filestore import FileStorage
sys.path.insert(1, os.path.abspath(os.path.join(os.path.dirname(__file__), os.p... | 0.244904 | 0.055081 |
# 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 Lic... | driven/vizualization/escher_viewer.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 Lic... | 0.894026 | 0.29745 |
import os
import unittest
import numpy as np
import pandas as pd
from .context import Leitor
from .context import calcular_matriz_cr, calcular_ari, obter_numeros_particoes
def verifica_se_eh_simetrica(a, tol=1e-8):
return np.allclose(a, a.T, atol=tol)
class TestMatrizCRIris(unittest.TestCase):
def setUp(... | test/test_util.py |
import os
import unittest
import numpy as np
import pandas as pd
from .context import Leitor
from .context import calcular_matriz_cr, calcular_ari, obter_numeros_particoes
def verifica_se_eh_simetrica(a, tol=1e-8):
return np.allclose(a, a.T, atol=tol)
class TestMatrizCRIris(unittest.TestCase):
def setUp(... | 0.479504 | 0.503662 |
import json
import csv
import os
import multiprocessing
from multiprocessing import Pool, cpu_count
csv_path = 'E:\\conceptnet\\assertions.csv'
def job_split(**kw):
'''
>>> concepnet.parse.job_split(path=csv_path)
[{'start': 0L, 'end': 1071224347L},
{'start': 1071224348L, '... | src/v2/conceptnet/parse.py | import json
import csv
import os
import multiprocessing
from multiprocessing import Pool, cpu_count
csv_path = 'E:\\conceptnet\\assertions.csv'
def job_split(**kw):
'''
>>> concepnet.parse.job_split(path=csv_path)
[{'start': 0L, 'end': 1071224347L},
{'start': 1071224348L, '... | 0.245537 | 0.10434 |
import json
from dataclasses import dataclass
from datetime import datetime
import abc
import requests
from flask_restful import Resource, reqparse
@dataclass(init=True)
class CallbackRequest:
status: bool
description: str
reference_id: str
mfs_transaction_id: str
amount: str
def unmarshall_cal... | src/tigopesasdk/__init__.py |
import json
from dataclasses import dataclass
from datetime import datetime
import abc
import requests
from flask_restful import Resource, reqparse
@dataclass(init=True)
class CallbackRequest:
status: bool
description: str
reference_id: str
mfs_transaction_id: str
amount: str
def unmarshall_cal... | 0.550487 | 0.116061 |
import os
import signal
import shutil
import json
from config import Config
from MIND_corpus import MIND_Corpus
from MIND_dataset import MIND_Train_Dataset
from util import compute_scores
from tqdm import tqdm
import torch
import torch.nn as nn
import torch.optim as optim
from torch.utils.data import DataLoader
import ... | trainer.py | import os
import signal
import shutil
import json
from config import Config
from MIND_corpus import MIND_Corpus
from MIND_dataset import MIND_Train_Dataset
from util import compute_scores
from tqdm import tqdm
import torch
import torch.nn as nn
import torch.optim as optim
from torch.utils.data import DataLoader
import ... | 0.713232 | 0.149159 |
import os
import argparse
import random
import numpy as np
import tensorflow as tf
from collections import namedtuple
from pathlib import Path
from model.model_manager import ModelManager
os.environ['TF_CPP_MIN_LOG_LEVEL'] = '3'
WordEmbedding = namedtuple(
'WordEmbedding',
['name', 'train_file', 'validatio... | random_hyperparameter_search.py | import os
import argparse
import random
import numpy as np
import tensorflow as tf
from collections import namedtuple
from pathlib import Path
from model.model_manager import ModelManager
os.environ['TF_CPP_MIN_LOG_LEVEL'] = '3'
WordEmbedding = namedtuple(
'WordEmbedding',
['name', 'train_file', 'validatio... | 0.456894 | 0.164516 |
from Union import *
import glob
from PIL import Image
import sys
import random
import os
import shutil
import tensorflow as tf
#コマンドライン引数
flags = tf.app.flags
flags.DEFINE_string('recipe_file','./GetPoint.csv','GetPoint.pyで作成した、ターゲットの配置場所がかかれているCSVファイル')
flags.DEFINE_string('annotation_file','./annotation.csv','アノテーシ... | DatasetFactory.py | from Union import *
import glob
from PIL import Image
import sys
import random
import os
import shutil
import tensorflow as tf
#コマンドライン引数
flags = tf.app.flags
flags.DEFINE_string('recipe_file','./GetPoint.csv','GetPoint.pyで作成した、ターゲットの配置場所がかかれているCSVファイル')
flags.DEFINE_string('annotation_file','./annotation.csv','アノテーシ... | 0.053589 | 0.091666 |
import sys
import unittest
from six.moves import cStringIO
import numpy as np
from openmdao.api import Problem, Group, Component, NLGaussSeidel, ScipyGMRES
class ErrorComp(Component):
""" This component generates numpy errors."""
def __init__(self, mode):
super(ErrorComp, self).__init__()
... | openmdao/solvers/test/test_solver_np_error.py |
import sys
import unittest
from six.moves import cStringIO
import numpy as np
from openmdao.api import Problem, Group, Component, NLGaussSeidel, ScipyGMRES
class ErrorComp(Component):
""" This component generates numpy errors."""
def __init__(self, mode):
super(ErrorComp, self).__init__()
... | 0.503174 | 0.360742 |
def init_actions_(service, args):
"""
this needs to returns an array of actions representing the depencies between actions.
Looks at ACTION_DEPS in this module for an example of what is expected
"""
return {
'test': ['install']
}
def test(job):
import sys
try:
log = j.l... | tests/test_services/test_limit_iops/actions.py | def init_actions_(service, args):
"""
this needs to returns an array of actions representing the depencies between actions.
Looks at ACTION_DEPS in this module for an example of what is expected
"""
return {
'test': ['install']
}
def test(job):
import sys
try:
log = j.l... | 0.392104 | 0.243657 |
import dash
import dash_core_components as dcc
import dash_html_components as html
import pandas as pd
import plotly.graph_objs as go
import dash
from dash.dependencies import Input, Output
import dash_core_components as dcc
import dash_html_components as html
import pandas as pd
import flask
import plotly.plotly as py... | Analitic Module/charts/main3d.py | import dash
import dash_core_components as dcc
import dash_html_components as html
import pandas as pd
import plotly.graph_objs as go
import dash
from dash.dependencies import Input, Output
import dash_core_components as dcc
import dash_html_components as html
import pandas as pd
import flask
import plotly.plotly as py... | 0.463687 | 0.093969 |
import numpy as np
import torch
import torch.nn as nn
from tqdm import tqdm
from pyramid_nested_ner.training.trainer import PyramidNerTrainer
from pyramid_nested_ner.utils.metrics import multi_label_span_classification_report
class MultiLabelTrainer(PyramidNerTrainer):
def test_model(self, test_data, out_dict=F... | pyramid_nested_ner/training/multi_label_trainer.py | import numpy as np
import torch
import torch.nn as nn
from tqdm import tqdm
from pyramid_nested_ner.training.trainer import PyramidNerTrainer
from pyramid_nested_ner.utils.metrics import multi_label_span_classification_report
class MultiLabelTrainer(PyramidNerTrainer):
def test_model(self, test_data, out_dict=F... | 0.810779 | 0.338583 |
from functools import partial
import numpy as np
import pandas as pd
import chainer
from chainer import functions
from chainer import functions as F
from chainer import links as L
from chainer.dataset import to_device
from lib.graph import Graph
def zero_plus(x):
return F.softplus(x) - 0.6931472
class Element... | source/02_triplet_update/lib/model.py | from functools import partial
import numpy as np
import pandas as pd
import chainer
from chainer import functions
from chainer import functions as F
from chainer import links as L
from chainer.dataset import to_device
from lib.graph import Graph
def zero_plus(x):
return F.softplus(x) - 0.6931472
class Element... | 0.765418 | 0.526099 |
from flask import Flask, redirect, url_for, render_template, request, flash
import flask
import os
from os.path import join, dirname
from dotenv import load_dotenv
import braintree
import json
app = Flask(__name__)
dotenv_path = join(dirname(__file__), '.env')
load_dotenv(dotenv_path)
app.secret_key = os.environ.get(... | app.py | from flask import Flask, redirect, url_for, render_template, request, flash
import flask
import os
from os.path import join, dirname
from dotenv import load_dotenv
import braintree
import json
app = Flask(__name__)
dotenv_path = join(dirname(__file__), '.env')
load_dotenv(dotenv_path)
app.secret_key = os.environ.get(... | 0.483405 | 0.058426 |
import os
import numpy as np
import pandas as pd
from argparse import ArgumentParser
if __name__ == "__main__":
# Parse arguments
parser = ArgumentParser(description='Get council info and voting adjacency matrix.')
parser.add_argument('-p',
action='store',
... | data/swiss-national-council/prepare_snc_data.py | import os
import numpy as np
import pandas as pd
from argparse import ArgumentParser
if __name__ == "__main__":
# Parse arguments
parser = ArgumentParser(description='Get council info and voting adjacency matrix.')
parser.add_argument('-p',
action='store',
... | 0.515864 | 0.203075 |
import os
from pathlib import Path
from pytest import mark, raises, warns
from staticjinja import Site, Reloader
import staticjinja
def test_template_names(site):
site.staticpaths = ["static_css", "static_js", "favicon.ico"]
expected_templates = set(
["template1.html", "template2.html", "sub/templat... | tests/test_staticjinja.py | import os
from pathlib import Path
from pytest import mark, raises, warns
from staticjinja import Site, Reloader
import staticjinja
def test_template_names(site):
site.staticpaths = ["static_css", "static_js", "favicon.ico"]
expected_templates = set(
["template1.html", "template2.html", "sub/templat... | 0.455199 | 0.566558 |
__author__ = '<NAME> <<EMAIL>>'
from .features.grendel import GenderNumberExtractor
from .features.speakerExtractor import SpeakerExtractor
from .graph.kafx import KafAndTreeGraphBuilder
from .multisieve.core import CoreferenceProcessor
from .output.progressbar import Fraction, ProgressBar
import logging
class Te... | core/corefgraph/text_processor.py |
__author__ = '<NAME> <<EMAIL>>'
from .features.grendel import GenderNumberExtractor
from .features.speakerExtractor import SpeakerExtractor
from .graph.kafx import KafAndTreeGraphBuilder
from .multisieve.core import CoreferenceProcessor
from .output.progressbar import Fraction, ProgressBar
import logging
class Te... | 0.592667 | 0.122392 |
import os
import os.path as osp
import tempfile
from datetime import timedelta
from enum import Enum
import django_rq
from django.utils import timezone
import pandas as pd
from openpyxl.workbook.child import INVALID_TITLE_REGEX
import re
import cvat.apps.dataset_manager.task as task
from cvat.apps.engine.log import ... | cvat/apps/dataset_manager/views.py |
import os
import os.path as osp
import tempfile
from datetime import timedelta
from enum import Enum
import django_rq
from django.utils import timezone
import pandas as pd
from openpyxl.workbook.child import INVALID_TITLE_REGEX
import re
import cvat.apps.dataset_manager.task as task
from cvat.apps.engine.log import ... | 0.306735 | 0.10885 |
import matplotlib.pyplot as plt
import numpy as np
from src.tpsd import Tpsd
class TpsdComparison:
"""
Implements the TPSD as described in De Haas et al.
"""
# pylint: disable=line-too-long
# pylint: disable=consider-using-enumerate
def __init__(self, chord_sequence_a: list[str], chord_seque... | src/tpsd_comparison.py | import matplotlib.pyplot as plt
import numpy as np
from src.tpsd import Tpsd
class TpsdComparison:
"""
Implements the TPSD as described in De Haas et al.
"""
# pylint: disable=line-too-long
# pylint: disable=consider-using-enumerate
def __init__(self, chord_sequence_a: list[str], chord_seque... | 0.703244 | 0.785185 |
# file: generate_mazes_in_csv_file.py
# author: tkornuta
# brief: generate a csv file containing m mazes of size w by h with random digits (from 1 to 9, with a single 0 and 9).
# date: Feb 2, 2016
import csv
import sys
import getopt
import numpy
def main(argv):
# Check arguments
try: ... | scripts/generate_mazes_in_csv_file.py |
# file: generate_mazes_in_csv_file.py
# author: tkornuta
# brief: generate a csv file containing m mazes of size w by h with random digits (from 1 to 9, with a single 0 and 9).
# date: Feb 2, 2016
import csv
import sys
import getopt
import numpy
def main(argv):
# Check arguments
try: ... | 0.283781 | 0.383006 |
from project import db, bcrypt
from sqlalchemy.ext.hybrid import hybrid_method, hybrid_property
class Recipe(db.Model):
__tablename__ = "recipes"
id = db.Column(db.Integer, primary_key=True)
recipe_title = db.Column(db.String, nullable=False)
recipe_description = db.Column(db.String, nullable=False)... | project/models.py | from project import db, bcrypt
from sqlalchemy.ext.hybrid import hybrid_method, hybrid_property
class Recipe(db.Model):
__tablename__ = "recipes"
id = db.Column(db.Integer, primary_key=True)
recipe_title = db.Column(db.String, nullable=False)
recipe_description = db.Column(db.String, nullable=False)... | 0.7324 | 0.079854 |
from __future__ import print_function
import keras
from keras.models import Model
from keras.layers import concatenate, Dense, Dropout, Flatten, Add, SpatialDropout2D, Conv3D
from keras.layers import Conv2D, MaxPooling2D, Input, Activation,AveragePooling2D,BatchNormalization
from keras.layers import MaxPooling3D, ... | network_openset.py | from __future__ import print_function
import keras
from keras.models import Model
from keras.layers import concatenate, Dense, Dropout, Flatten, Add, SpatialDropout2D, Conv3D
from keras.layers import Conv2D, MaxPooling2D, Input, Activation,AveragePooling2D,BatchNormalization
from keras.layers import MaxPooling3D, ... | 0.853913 | 0.376594 |
from .debug import Debug
from .utility import HtmlUtils
class BookmarkList(object):
"""This class keeps track of bookmarks in the document being processed by AVScript.
Bookmarks are automatically created for each new shot added in a document.
If the ///Shotlist/// keyword is later used, then the bookmar... | smd/core/bookmark.py |
from .debug import Debug
from .utility import HtmlUtils
class BookmarkList(object):
"""This class keeps track of bookmarks in the document being processed by AVScript.
Bookmarks are automatically created for each new shot added in a document.
If the ///Shotlist/// keyword is later used, then the bookmar... | 0.64232 | 0.331498 |
from math import *
import unittest
import time
from Spheral2d import *
from generateMesh import *
from SpheralTestUtilities import fuzzyEqual, testParallelConsistency
from SpheralGnuPlotUtilities import *
#===============================================================================
# Load mpi, and figure out how ... | tests/unit/Mesh/testPolygonalMesh.py |
from math import *
import unittest
import time
from Spheral2d import *
from generateMesh import *
from SpheralTestUtilities import fuzzyEqual, testParallelConsistency
from SpheralGnuPlotUtilities import *
#===============================================================================
# Load mpi, and figure out how ... | 0.740925 | 0.442697 |
import pygame
import sys
import math
import timeit
from copy import copy
from connect4 import Connect4
from agent_zero import Connect4Zero
class Gui:
def __init__(self, player1='Human', player2='AI'):
self.board_colour = (0, 0, 255)
self.bg_colour = (0, 0, 0)
self.p1_piece_col... | gui.py | import pygame
import sys
import math
import timeit
from copy import copy
from connect4 import Connect4
from agent_zero import Connect4Zero
class Gui:
def __init__(self, player1='Human', player2='AI'):
self.board_colour = (0, 0, 255)
self.bg_colour = (0, 0, 0)
self.p1_piece_col... | 0.248352 | 0.15219 |
# ======================================================================
# t r a c k . p y
# ======================================================================
"Tracks for the Mine Card Madness problem day 13 of Advent of Code 2018"
# ----------------------------------------------... | 2018/13_MineCartMadness/track.py |
# ======================================================================
# t r a c k . p y
# ======================================================================
"Tracks for the Mine Card Madness problem day 13 of Advent of Code 2018"
# ----------------------------------------------... | 0.601594 | 0.436802 |
from os.path import dirname, abspath, join, exists
from os import walk, remove, rmdir, chdir, chmod
def almost_equal(value1, value2, precision):
return abs(value1 - value2) < precision
def get_lines(file_name):
with open(file_name, 'r') as f:
result = f.readlines()
f.close()
return resu... | code-preprocessing/archive-update/test_archives.py |
from os.path import dirname, abspath, join, exists
from os import walk, remove, rmdir, chdir, chmod
def almost_equal(value1, value2, precision):
return abs(value1 - value2) < precision
def get_lines(file_name):
with open(file_name, 'r') as f:
result = f.readlines()
f.close()
return resu... | 0.599954 | 0.389082 |
import os
import ldap
import ldap.modlist as modlist
from pprint import pprint
server_uri = 'ldaps://massive'
connection = ldap.initialize(server_uri)
connection.simple_bind_s(ADMIN_DN,PASSWORD)
netgroup_search_base = NETGROUP_DN
user_search_base = USER_DN
group_search_base = GROUP_DN
user_criteria = "(objectClass=pe... | init.py | import os
import ldap
import ldap.modlist as modlist
from pprint import pprint
server_uri = 'ldaps://massive'
connection = ldap.initialize(server_uri)
connection.simple_bind_s(ADMIN_DN,PASSWORD)
netgroup_search_base = NETGROUP_DN
user_search_base = USER_DN
group_search_base = GROUP_DN
user_criteria = "(objectClass=pe... | 0.091114 | 0.085251 |
from sqlalchemy.ext.declarative import declarative_base
from sqlalchemy.orm import backref, relationship
from sqlalchemy.sql.schema import Column, ForeignKey, Table
from sqlalchemy.sql.sqltypes import Boolean, Integer, String
Base = declarative_base()
class CharacterSkillModel(Base):
__tablename__ = "character_sk... | discord_bot/model.py | from sqlalchemy.ext.declarative import declarative_base
from sqlalchemy.orm import backref, relationship
from sqlalchemy.sql.schema import Column, ForeignKey, Table
from sqlalchemy.sql.sqltypes import Boolean, Integer, String
Base = declarative_base()
class CharacterSkillModel(Base):
__tablename__ = "character_sk... | 0.687735 | 0.104249 |
import os
import sys
import requests
import json
from synchronizers.new_base.syncstep import SyncStep
from synchronizers.new_base.modelaccessor import *
from xos.logger import Logger, logging
from requests.auth import HTTPBasicAuth
logger = Logger(level=logging.INFO)
parentdir = os.path.join(os.path.dirname(__file_... | xos/synchronizer/steps/sync_vnaaseline.py |
import os
import sys
import requests
import json
from synchronizers.new_base.syncstep import SyncStep
from synchronizers.new_base.modelaccessor import *
from xos.logger import Logger, logging
from requests.auth import HTTPBasicAuth
logger = Logger(level=logging.INFO)
parentdir = os.path.join(os.path.dirname(__file_... | 0.244003 | 0.066478 |
import os
import subprocess
from functools import partial
def graalvm_build_system_executor(make_env):
result = build_system_executor(make_env, cc_version='--version', as_version='--version')
with subprocess.Popen([os.path.expandvars('${GRAALVM_DIR}/bin/lli'), '--version'], stdout=subprocess.PIPE) as p:
... | configs/sulong.py | import os
import subprocess
from functools import partial
def graalvm_build_system_executor(make_env):
result = build_system_executor(make_env, cc_version='--version', as_version='--version')
with subprocess.Popen([os.path.expandvars('${GRAALVM_DIR}/bin/lli'), '--version'], stdout=subprocess.PIPE) as p:
... | 0.361277 | 0.120775 |
import json
import ntpath
from modeci_mdf.functions.standard import mdf_functions, create_python_expression
from typing import List, Tuple, Dict, Optional, Set, Any, Union
from modeci_mdf.utils import load_mdf, print_summary
from modeci_mdf.mdf import *
from modeci_mdf.full_translator import *
from modeci_mdf.executio... | examples/PyTorch/run_translated_mlp_pure_mdf.py | import json
import ntpath
from modeci_mdf.functions.standard import mdf_functions, create_python_expression
from typing import List, Tuple, Dict, Optional, Set, Any, Union
from modeci_mdf.utils import load_mdf, print_summary
from modeci_mdf.mdf import *
from modeci_mdf.full_translator import *
from modeci_mdf.executio... | 0.321247 | 0.224353 |
import os
import input
import model
import tensorflow as tf
slim = tf.contrib.slim
flags = tf.app.flags
FLAGS = flags.FLAGS
flags.DEFINE_integer('batch_size', 100, 'Batch size.')
flags.DEFINE_string('harrison_dir', '/home/ardiya/HARRISON',
'Directory containing Benchmark Dataset(img_placeholder, data_list, and t... | evaluate.py | import os
import input
import model
import tensorflow as tf
slim = tf.contrib.slim
flags = tf.app.flags
FLAGS = flags.FLAGS
flags.DEFINE_integer('batch_size', 100, 'Batch size.')
flags.DEFINE_string('harrison_dir', '/home/ardiya/HARRISON',
'Directory containing Benchmark Dataset(img_placeholder, data_list, and t... | 0.404978 | 0.264257 |
import time
import numpy as np
from numpy import mean
from numpy import std
from numpy import max
from numpy import min
from numpy import empty
from numpy import cov
from numpy import argmax
from numpy import argmin
import numpy.linalg as LA
import h5py
import math
from math import sqrt
import numba
from numba import j... | cca.py | import time
import numpy as np
from numpy import mean
from numpy import std
from numpy import max
from numpy import min
from numpy import empty
from numpy import cov
from numpy import argmax
from numpy import argmin
import numpy.linalg as LA
import h5py
import math
from math import sqrt
import numba
from numba import j... | 0.343122 | 0.432842 |
import csv
import logging
from testrail_client import TestRailClient
class CsvManager(TestRailClient):
"""
This class is an example where csv upload function is implemented by APIs.
The primordial upload function is not so easy use, the cases
"""
def __init__(self, base_url, user_name,
... | examples/update_case.py |
import csv
import logging
from testrail_client import TestRailClient
class CsvManager(TestRailClient):
"""
This class is an example where csv upload function is implemented by APIs.
The primordial upload function is not so easy use, the cases
"""
def __init__(self, base_url, user_name,
... | 0.492432 | 0.195038 |
Case Type : 锁定表
Case Name : 对表进行REINDEX时是否产生AccessExclusiveLock锁
Description :
1.创建测试表并插入数据后创建索引
2.统计锁信息
3.开启事务,对测试表进行REINDEX,不做提交,统计锁信息
4.进行校验
5.清理环境
Expect :
1.创建测试表及索引并插入数据成功
2.查看视图PG_LOCKS,统计锁信息成功
3.开启事务,执行语句
4.统计锁信息成功,事务产生AccessExclusiveLock锁
5.清理环境成功
"""
import un... | openGaussBase/testcase/SQL/DML/lock/Opengauss_Function_DML_Lock_Case0114.py | Case Type : 锁定表
Case Name : 对表进行REINDEX时是否产生AccessExclusiveLock锁
Description :
1.创建测试表并插入数据后创建索引
2.统计锁信息
3.开启事务,对测试表进行REINDEX,不做提交,统计锁信息
4.进行校验
5.清理环境
Expect :
1.创建测试表及索引并插入数据成功
2.查看视图PG_LOCKS,统计锁信息成功
3.开启事务,执行语句
4.统计锁信息成功,事务产生AccessExclusiveLock锁
5.清理环境成功
"""
import un... | 0.241758 | 0.395134 |
from PyQt5.QtCore import QObject, pyqtSignal, pyqtSlot, Qt, QSize
from PyQt5.QtGui import QImage, QPixmap, QPainter
from PyQt5.QtWidgets import QWidget, QApplication, QLabel, QToolButton, QHBoxLayout, QVBoxLayout, QGroupBox, \
QPushButton, QSizePolicy, QComboBox, QGridLayout, QFileDialog, QLineEdit, QCheckBox, QSli... | LACV/widgets.py | from PyQt5.QtCore import QObject, pyqtSignal, pyqtSlot, Qt, QSize
from PyQt5.QtGui import QImage, QPixmap, QPainter
from PyQt5.QtWidgets import QWidget, QApplication, QLabel, QToolButton, QHBoxLayout, QVBoxLayout, QGroupBox, \
QPushButton, QSizePolicy, QComboBox, QGridLayout, QFileDialog, QLineEdit, QCheckBox, QSli... | 0.427994 | 0.154823 |
import wx
from .todo_list import TodoList
from .todo_form_dialog import TodoFormDialog
from .todo_group_form_dialog import TodoGroupFormDialog
from models import Todo
from views import GenericMessageDialog
from pubsub import pub
from .popup_menu_mixin import PopupMenuMixin
class TodoPanel(wx.Panel, PopupMenuMixin):
... | views/todo_panel.py | import wx
from .todo_list import TodoList
from .todo_form_dialog import TodoFormDialog
from .todo_group_form_dialog import TodoGroupFormDialog
from models import Todo
from views import GenericMessageDialog
from pubsub import pub
from .popup_menu_mixin import PopupMenuMixin
class TodoPanel(wx.Panel, PopupMenuMixin):
... | 0.323594 | 0.066176 |
from coub_api.modules.base import TmpBaseConnector, connector_return_type
from coub_api.schemas.search import (
CoubSearchResponse,
ChannelSearchResponse,
GeneralSearchResponse,
)
__all__ = ("Search",)
class Search(TmpBaseConnector):
__slots__ = ()
def _get_all_response(
self, q: str, *,... | coub_api/modules/search.py | from coub_api.modules.base import TmpBaseConnector, connector_return_type
from coub_api.schemas.search import (
CoubSearchResponse,
ChannelSearchResponse,
GeneralSearchResponse,
)
__all__ = ("Search",)
class Search(TmpBaseConnector):
__slots__ = ()
def _get_all_response(
self, q: str, *,... | 0.622115 | 0.101634 |
import base64
import hashlib
import json
import logging
import requests
from django.contrib.auth import get_user_model
from django.contrib.auth.backends import ModelBackend
from django.core.exceptions import SuspiciousOperation, ImproperlyConfigured
try:
from django.urls import reverse
except ImportError:
# Dj... | desktop/core/ext-py/mozilla-django-oidc-1.0.0/mozilla_django_oidc/auth.py | import base64
import hashlib
import json
import logging
import requests
from django.contrib.auth import get_user_model
from django.contrib.auth.backends import ModelBackend
from django.core.exceptions import SuspiciousOperation, ImproperlyConfigured
try:
from django.urls import reverse
except ImportError:
# Dj... | 0.652463 | 0.074804 |
import torch
import time
def threshold_confidence(x, threshold):
x_exp = torch.exp(x)
mx, _ = torch.max(x_exp, dim=1)
return torch.gt(mx, threshold), mx
class CacheControl():
def __init__(self, conf, input_shape, threshold, cache_exits, training=False, logger = None):
device = conf.test_device ... | backbone/CacheControl.py | import torch
import time
def threshold_confidence(x, threshold):
x_exp = torch.exp(x)
mx, _ = torch.max(x_exp, dim=1)
return torch.gt(mx, threshold), mx
class CacheControl():
def __init__(self, conf, input_shape, threshold, cache_exits, training=False, logger = None):
device = conf.test_device ... | 0.478041 | 0.330525 |
r""" Evaluation helpers """
import torch
class Evaluator:
r""" Computes intersection and union between prediction and ground-truth """
@classmethod
def classify_prediction(cls, pred_mask, batch, ignore_index=255):
gt_mask = batch.get('query_mask')
# Apply ignore_index in PASCAL-5i masks (... | fs-s/common/evaluation.py | r""" Evaluation helpers """
import torch
class Evaluator:
r""" Computes intersection and union between prediction and ground-truth """
@classmethod
def classify_prediction(cls, pred_mask, batch, ignore_index=255):
gt_mask = batch.get('query_mask')
# Apply ignore_index in PASCAL-5i masks (... | 0.887668 | 0.696604 |
import getpass
import gzip
import io
import json
import sys
import time
import traceback
import urllib.error
import urllib.parse
import urllib.request
__version__ = "1.0.1"
baseurl = "https://www.irccloud.com/chat/"
email, password, stat_user = None, None, None
def rpc(method, path, session=None, token=None, keepali... | ircclive.py | import getpass
import gzip
import io
import json
import sys
import time
import traceback
import urllib.error
import urllib.parse
import urllib.request
__version__ = "1.0.1"
baseurl = "https://www.irccloud.com/chat/"
email, password, stat_user = None, None, None
def rpc(method, path, session=None, token=None, keepali... | 0.093561 | 0.088387 |
import unittest
import ifm_contrib as ifm
from ifm import Enum
import numpy as np
class TestPlot(unittest.TestCase):
def test_fringes(self):
ifm.forceLicense("Viewer")
doc = ifm.loadDocument(r".\models\example_2D.dac")
doc.loadTimeStep(doc.getNumberOfTimeSteps() - 1)
gdf = doc.c.pl... | unittests/test_plot_geopandas.py | import unittest
import ifm_contrib as ifm
from ifm import Enum
import numpy as np
class TestPlot(unittest.TestCase):
def test_fringes(self):
ifm.forceLicense("Viewer")
doc = ifm.loadDocument(r".\models\example_2D.dac")
doc.loadTimeStep(doc.getNumberOfTimeSteps() - 1)
gdf = doc.c.pl... | 0.29696 | 0.595493 |
from collections import defaultdict
import multiprocessing as mp
import random
import pyhash
import Levenshtein
from jsonleveldb import JsonLevelDB
from .unionfind import UnionFind
class Signature(object):
"""Signature Base class."""
def __init__(self, dim):
self.dim = dim
self.hashes = self.... | lsh/lsh.py | from collections import defaultdict
import multiprocessing as mp
import random
import pyhash
import Levenshtein
from jsonleveldb import JsonLevelDB
from .unionfind import UnionFind
class Signature(object):
"""Signature Base class."""
def __init__(self, dim):
self.dim = dim
self.hashes = self.... | 0.79534 | 0.281079 |
from sys import path
from math import pow
path.append(".")
from xUserInterface import xUserInterface as xui
class Decimal2Binary(xui):
base = 2 #Base Number
#System Variables
isFloat = False
def __init__(self):
"""
This code is just to reverse engineer
the dec... | Binary & Decimal/Decimal to Binary.py |
from sys import path
from math import pow
path.append(".")
from xUserInterface import xUserInterface as xui
class Decimal2Binary(xui):
base = 2 #Base Number
#System Variables
isFloat = False
def __init__(self):
"""
This code is just to reverse engineer
the dec... | 0.370567 | 0.247561 |
from __future__ import absolute_import
from __future__ import division
from __future__ import print_function
import os
import logging
import motmetrics as mm
from tracking_utils.log import logger
from tracking_utils.evaluation import Evaluator
from opts import opts
def main(data_root, seqs):
logger.setLevel(lo... | trackers/fair/src/evaluate.py | from __future__ import absolute_import
from __future__ import division
from __future__ import print_function
import os
import logging
import motmetrics as mm
from tracking_utils.log import logger
from tracking_utils.evaluation import Evaluator
from opts import opts
def main(data_root, seqs):
logger.setLevel(lo... | 0.362631 | 0.086131 |
import umap
import hdbscan
import pandas as pd
class Experiment:
def __init__(self, sentence_model, umap_parameters, clustering_parameters):
self.sentence_model = sentence_model
self.n_neighbors = umap_parameters.n_neighbors
self.n_components = umap_parameters.n_components
self.uma... | model/Experiment.py | import umap
import hdbscan
import pandas as pd
class Experiment:
def __init__(self, sentence_model, umap_parameters, clustering_parameters):
self.sentence_model = sentence_model
self.n_neighbors = umap_parameters.n_neighbors
self.n_components = umap_parameters.n_components
self.uma... | 0.473657 | 0.213316 |
import pytest
from sacred.config import ConfigScope, ConfigDict, chain_evaluate_config_scopes
def test_chained_config_scopes_contain_combined_keys():
@ConfigScope
def cfg1():
a = 10
@ConfigScope
def cfg2():
b = 20
final_cfg, summary = chain_evaluate_config_scopes([cfg1, cfg2])
... | tests/test_config/test_config_scope_chain.py |
import pytest
from sacred.config import ConfigScope, ConfigDict, chain_evaluate_config_scopes
def test_chained_config_scopes_contain_combined_keys():
@ConfigScope
def cfg1():
a = 10
@ConfigScope
def cfg2():
b = 20
final_cfg, summary = chain_evaluate_config_scopes([cfg1, cfg2])
... | 0.521227 | 0.511717 |
from datetime import datetime
from logging import Logger
import os
from typing import Any, Dict, List
from qiskit.circuit.quantumcircuit import QuantumCircuit
from qiskit.ignis.verification.randomized_benchmarking.fitters import RBFitter
from resource_mapping.backend_chooser import Backend_Data
from quantum_execution_j... | randomized_benchmarking.py | from datetime import datetime
from logging import Logger
import os
from typing import Any, Dict, List
from qiskit.circuit.quantumcircuit import QuantumCircuit
from qiskit.ignis.verification.randomized_benchmarking.fitters import RBFitter
from resource_mapping.backend_chooser import Backend_Data
from quantum_execution_j... | 0.617397 | 0.208179 |
import torch
from rationalizers.modules.sentence_encoders import (
LSTMEncoder,
)
from rationalizers.utils import load_glove_embeddings
def build_sentence_encoder(
layer: str,
in_features: int,
hidden_size: int,
bidirectional: bool = True,
):
if layer == "lstm":
return LSTMEncoder(in_... | rationalizers/builders.py | import torch
from rationalizers.modules.sentence_encoders import (
LSTMEncoder,
)
from rationalizers.utils import load_glove_embeddings
def build_sentence_encoder(
layer: str,
in_features: int,
hidden_size: int,
bidirectional: bool = True,
):
if layer == "lstm":
return LSTMEncoder(in_... | 0.839471 | 0.255421 |
from __future__ import annotations
from enum import Enum, auto
from re import compile as compile_regex
from re import Pattern
from typing import Optional, Tuple
from dataclasses import dataclass
REDUCED_OBIS_PATTERN = r"((?P<AR>\d{0,3}){1}-)?((?P<BR>\d{0,3}){1}:)?((?P<CR>\d{0,3})\.)(?P<DR>\d{0,3})?(\.(?P<ER>\d{0,3})... | han/obis.py | from __future__ import annotations
from enum import Enum, auto
from re import compile as compile_regex
from re import Pattern
from typing import Optional, Tuple
from dataclasses import dataclass
REDUCED_OBIS_PATTERN = r"((?P<AR>\d{0,3}){1}-)?((?P<BR>\d{0,3}){1}:)?((?P<CR>\d{0,3})\.)(?P<DR>\d{0,3})?(\.(?P<ER>\d{0,3})... | 0.899944 | 0.425396 |
class CombineSignals(type):
'''A meta class to automatically combine signals from base classes'''
def __new__(metaclass, name, parents, class_dict, *kargs, **kwargs):
class_dict['signals'] = set(s for p in parents for s in getattr(p, 'signals', ())) | \
set(class_dict.get('signals', ())... | connectable/base.py | class CombineSignals(type):
'''A meta class to automatically combine signals from base classes'''
def __new__(metaclass, name, parents, class_dict, *kargs, **kwargs):
class_dict['signals'] = set(s for p in parents for s in getattr(p, 'signals', ())) | \
set(class_dict.get('signals', ())... | 0.765155 | 0.461017 |
from random import randint
from collection.collections_rest_client import CollectionsRest
from couchbase_helper.documentgenerator import SDKDataLoader
from membase.api.exception import CBQError
from .tuq import QueryTests
class QueryCollectionsUseKeys(QueryTests):
def setUp(self):
super(QueryCollections... | pytests/tuqquery/n1ql_collections_use_keys.py | from random import randint
from collection.collections_rest_client import CollectionsRest
from couchbase_helper.documentgenerator import SDKDataLoader
from membase.api.exception import CBQError
from .tuq import QueryTests
class QueryCollectionsUseKeys(QueryTests):
def setUp(self):
super(QueryCollections... | 0.405566 | 0.110615 |
from unittest import mock
from rest_framework.reverse import reverse
from know_me.journal import models
def test_create(entry_factory, user_factory):
"""
Test creating a new comment on a journal entry.
"""
models.EntryComment.objects.create(
entry=entry_factory(), text="My comment text.", us... | km_api/know_me/journal/tests/models/test_entry_comment_model.py | from unittest import mock
from rest_framework.reverse import reverse
from know_me.journal import models
def test_create(entry_factory, user_factory):
"""
Test creating a new comment on a journal entry.
"""
models.EntryComment.objects.create(
entry=entry_factory(), text="My comment text.", us... | 0.841761 | 0.408454 |
import torch
from d2l import torch as d2l
from torch import nn
def _get_batch_loss_bert(net, loss, vocab_size, tokens_X, segments_X,
valid_lens_x, pred_positions_X, mlm_weights_X, mlm_Y,
nsp_y):
# 前向传播
_, mlm_Y_hat, nsp_Y_hat = net(tokens_X, segments_X,
... | examples/d2l.ai_examples/bert.py | import torch
from d2l import torch as d2l
from torch import nn
def _get_batch_loss_bert(net, loss, vocab_size, tokens_X, segments_X,
valid_lens_x, pred_positions_X, mlm_weights_X, mlm_Y,
nsp_y):
# 前向传播
_, mlm_Y_hat, nsp_Y_hat = net(tokens_X, segments_X,
... | 0.645679 | 0.429549 |