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
def start_train(param_dict,
mxnet_module,
context,
train_dataiter,
train_metric,
train_metric_update_frequency,
num_train_loops,
val_dataiter,
val_metric,
num_... | ChasingTrainFramework_GeneralOneClassDetection/train_GOCD.py | import logging
def start_train(param_dict,
mxnet_module,
context,
train_dataiter,
train_metric,
train_metric_update_frequency,
num_train_loops,
val_dataiter,
val_metric,
num_... | 0.428233 | 0.065098 |
import os
import json
import configparser
from tempest.lib.cli import base
from tempest.lib.common.utils import data_utils
from tempest.lib.exceptions import CommandFailed
class ESIBaseTestClass(base.ClientTestBase):
# TODO: refactor this to follow tempest style guide (no setUpClass)
@classmethod
def setU... | esileapclient/tests/functional/base.py | import os
import json
import configparser
from tempest.lib.cli import base
from tempest.lib.common.utils import data_utils
from tempest.lib.exceptions import CommandFailed
class ESIBaseTestClass(base.ClientTestBase):
# TODO: refactor this to follow tempest style guide (no setUpClass)
@classmethod
def setU... | 0.172625 | 0.076442 |
import pandas as pd
from pathlib import Path
from imlib.pandas.misc import regex_remove_df_columns
def load_and_clean_dlc(dlc_files, regex_remove_columns=None):
"""
Load N dlc files, and clean up the column names
:param dlc_files: A list of dlc files, in order
:param regex_remove_columns: A list of r... | movement/io/dlc.py | import pandas as pd
from pathlib import Path
from imlib.pandas.misc import regex_remove_df_columns
def load_and_clean_dlc(dlc_files, regex_remove_columns=None):
"""
Load N dlc files, and clean up the column names
:param dlc_files: A list of dlc files, in order
:param regex_remove_columns: A list of r... | 0.53777 | 0.431045 |
from __future__ import annotations
import argparse
import json
import typing
import attr
import requests
import tabulate
from bs4 import BeautifulSoup
from pathlib import Path
import tqdm
from imdb import ImdbMovieSet, ImdbMovieInfo, normalize_movie_name
FIREFOX_USER_AGENT = \
'Mozilla/5.0 (Macintosh; Intel Mac... | catalog_fetcher.py | from __future__ import annotations
import argparse
import json
import typing
import attr
import requests
import tabulate
from bs4 import BeautifulSoup
from pathlib import Path
import tqdm
from imdb import ImdbMovieSet, ImdbMovieInfo, normalize_movie_name
FIREFOX_USER_AGENT = \
'Mozilla/5.0 (Macintosh; Intel Mac... | 0.608827 | 0.164148 |
import sys
import os
import numpy as np
import random
import time
import pickle
import fitness
from display_room import display_room
import fitness
from utils import print_iter_msg
from utils import stopwatch
# ----------------------------------------------------------------
# Generate the room, from the specified pa... | generate_room.py | import sys
import os
import numpy as np
import random
import time
import pickle
import fitness
from display_room import display_room
import fitness
from utils import print_iter_msg
from utils import stopwatch
# ----------------------------------------------------------------
# Generate the room, from the specified pa... | 0.291082 | 0.301741 |
from datetime import datetime
import logging
import time
from google.appengine.ext import db, deferred
from dateutil.relativedelta import relativedelta
from rogerthat.bizz.communities.communities import get_community
from rogerthat.bizz.job import run_job
from rogerthat.consts import FAST_QUEUE
from rogerthat.dal imp... | src/solutions/common/migrations/deactive_loyalty.py | from datetime import datetime
import logging
import time
from google.appengine.ext import db, deferred
from dateutil.relativedelta import relativedelta
from rogerthat.bizz.communities.communities import get_community
from rogerthat.bizz.job import run_job
from rogerthat.consts import FAST_QUEUE
from rogerthat.dal imp... | 0.398406 | 0.116563 |
from imutils.video import VideoStream
import numpy as np
import argparse
import imutils
import time
import cv2
ap = argparse.ArgumentParser()
ap.add_argument("-p", "--prototxt", required = True, help = "path to Caffe 'deploy' prototxt file")
ap.add_argument("-m", "--model", required = True, help = "path to Caffe pre-t... | Face_Detect_Caffe_resnet/detect_faces_video.py | from imutils.video import VideoStream
import numpy as np
import argparse
import imutils
import time
import cv2
ap = argparse.ArgumentParser()
ap.add_argument("-p", "--prototxt", required = True, help = "path to Caffe 'deploy' prototxt file")
ap.add_argument("-m", "--model", required = True, help = "path to Caffe pre-t... | 0.356783 | 0.181735 |
from flask import (
Blueprint, flash, g, redirect, render_template, request, url_for, session
)
from produsys.auth import login_required
from produsys.db import repo
from datetime import timedelta
bp = Blueprint('projects', __name__, url_prefix='/projects')
@bp.route('/')
@login_required
def index():
project... | produsys/projects.py | from flask import (
Blueprint, flash, g, redirect, render_template, request, url_for, session
)
from produsys.auth import login_required
from produsys.db import repo
from datetime import timedelta
bp = Blueprint('projects', __name__, url_prefix='/projects')
@bp.route('/')
@login_required
def index():
project... | 0.38885 | 0.053108 |
import pickle
import os.path
from pathlib import Path
from types import SimpleNamespace as Namespace
from typing import Callable, List, Optional
from tqdm.auto import tqdm
from googleapiclient.http import MediaFileUpload
from googleapiclient.discovery import build
from google_auth_oauthlib.flow import InstalledAppFlow
... | gdrive.py | import pickle
import os.path
from pathlib import Path
from types import SimpleNamespace as Namespace
from typing import Callable, List, Optional
from tqdm.auto import tqdm
from googleapiclient.http import MediaFileUpload
from googleapiclient.discovery import build
from google_auth_oauthlib.flow import InstalledAppFlow
... | 0.624866 | 0.119768 |
from django.db import models
from datetime import datetime
import re
class UserManager(models.Manager):
def register_validator(self, post_data):
errors = {}
EMAIL_REGEX = re.compile(r'^[a-zA-Z0-9.+_-]+@[a-zA-Z0-9._-]+\.[a-zA-Z]+$')
if len(post_data['first_name']) < 1:
errors['fi... | django/rpg/main/models.py | from django.db import models
from datetime import datetime
import re
class UserManager(models.Manager):
def register_validator(self, post_data):
errors = {}
EMAIL_REGEX = re.compile(r'^[a-zA-Z0-9.+_-]+@[a-zA-Z0-9._-]+\.[a-zA-Z]+$')
if len(post_data['first_name']) < 1:
errors['fi... | 0.433022 | 0.133698 |
import os
import numpy as np
import argparse
from UCTB.model import ARIMA
from UCTB.dataset import NodeTrafficLoader
from UCTB.evaluation import metric
from UCTB.utils import multiple_process
parser = argparse.ArgumentParser(description="Argument Parser")
# data source
parser.add_argument('--Dataset', default='Bike'... | Experiments/ARIMA/ARIMA_Parallel.py | import os
import numpy as np
import argparse
from UCTB.model import ARIMA
from UCTB.dataset import NodeTrafficLoader
from UCTB.evaluation import metric
from UCTB.utils import multiple_process
parser = argparse.ArgumentParser(description="Argument Parser")
# data source
parser.add_argument('--Dataset', default='Bike'... | 0.409575 | 0.202719 |
from future.standard_library import install_aliases
install_aliases()
from urllib.parse import urlparse, urlencode
from urllib.request import urlopen, Request
from urllib.error import HTTPError
from bs4 import BeautifulSoup
from bs4.element import Comment
import argparse
import html
import re
'''
Text Extractor is... | Text-Transformation/text_extract.py |
from future.standard_library import install_aliases
install_aliases()
from urllib.parse import urlparse, urlencode
from urllib.request import urlopen, Request
from urllib.error import HTTPError
from bs4 import BeautifulSoup
from bs4.element import Comment
import argparse
import html
import re
'''
Text Extractor is... | 0.500488 | 0.092524 |
import upsert
import itertools
class MergeFunction(upsert.MergeFunction):
@classmethod
def call_template(cls, controller, name, selector_keys, setter_keys):
return controller.fill_ident_placeholders('SELECT %s', (name,)) + '(' + ','.join(['?']*(len(selector_keys) + len(setter_keys))) + ')'
def exe... | upsert/postgresql.py | import upsert
import itertools
class MergeFunction(upsert.MergeFunction):
@classmethod
def call_template(cls, controller, name, selector_keys, setter_keys):
return controller.fill_ident_placeholders('SELECT %s', (name,)) + '(' + ','.join(['?']*(len(selector_keys) + len(setter_keys))) + ')'
def exe... | 0.349311 | 0.146942 |
from logutils import *
import re
from subprocess import getstatusoutput
import os
__author__ = 'jinzhao'
def version():
return '1.0.0'
def symbolicate_crash(crash_log, finder_func, output_path=None, verbose_mode=False):
"""
符号化crash日志
:param crash_log:crash日志文件路径
:param finder_func:查询app符号文件的处理函数... | symbolicate/symbolicate.py | from logutils import *
import re
from subprocess import getstatusoutput
import os
__author__ = 'jinzhao'
def version():
return '1.0.0'
def symbolicate_crash(crash_log, finder_func, output_path=None, verbose_mode=False):
"""
符号化crash日志
:param crash_log:crash日志文件路径
:param finder_func:查询app符号文件的处理函数... | 0.315103 | 0.145085 |
import jwt
from rest_framework import status
from django.urls import reverse
from django.test import TestCase
from django.conf import settings
from rest_framework.test import APIClient
from ..models import User
class LikeDislike(TestCase):
""" Test LikeDislike class"""
def setUp(self):
self.client = ... | authors/apps/articles/tests/test_like_article.py | import jwt
from rest_framework import status
from django.urls import reverse
from django.test import TestCase
from django.conf import settings
from rest_framework.test import APIClient
from ..models import User
class LikeDislike(TestCase):
""" Test LikeDislike class"""
def setUp(self):
self.client = ... | 0.447219 | 0.162048 |
from django.shortcuts import redirect
from django.views.generic import TemplateView
from django.contrib.auth.decorators import login_required
from django.utils.decorators import method_decorator
from django.contrib import messages
from django.template import RequestContext
from bucketlist.models import Bucketlistitem,... | bucketlist/views/bucketlistitem_view.py | from django.shortcuts import redirect
from django.views.generic import TemplateView
from django.contrib.auth.decorators import login_required
from django.utils.decorators import method_decorator
from django.contrib import messages
from django.template import RequestContext
from bucketlist.models import Bucketlistitem,... | 0.627609 | 0.039639 |
import configparser
import unittest
import datetime
from pathlib import Path
from metaindex import CacheEntry
from metaindex import humanize, register_humanizer
from metaindex.configuration import Configuration, CONF_DEFAULTS
from metaindex.cache import Cache, MemoryCache, CacheBase
@register_humanizer('*.round')
de... | tests/test_humanizer.py | import configparser
import unittest
import datetime
from pathlib import Path
from metaindex import CacheEntry
from metaindex import humanize, register_humanizer
from metaindex.configuration import Configuration, CONF_DEFAULTS
from metaindex.cache import Cache, MemoryCache, CacheBase
@register_humanizer('*.round')
de... | 0.564219 | 0.218878 |
from telisar.languages import draconic
from telisar.npc.base import BaseNPC, a_or_an
from telisar.npc import traits
import textwrap
import random
class NPC(BaseNPC):
ancestry = 'Dragon'
language = draconic.Dragon()
def __init__(self, *args, **kwargs):
super().__init__(*args, **kwargs)
s... | telisar/npc/dragon.py | from telisar.languages import draconic
from telisar.npc.base import BaseNPC, a_or_an
from telisar.npc import traits
import textwrap
import random
class NPC(BaseNPC):
ancestry = 'Dragon'
language = draconic.Dragon()
def __init__(self, *args, **kwargs):
super().__init__(*args, **kwargs)
s... | 0.717012 | 0.09187 |
import api.net as net
import torch
import time
from torch.autograd import Variable
from PIL import Image
from torchvision import transforms
import numpy as np
import PIL
import os
import glob
from os.path import join, dirname, realpath
import cv2
import random
makeup_path = './makeup_images'
FOLDER = join(dirname(real... | api/demo.py | import api.net as net
import torch
import time
from torch.autograd import Variable
from PIL import Image
from torchvision import transforms
import numpy as np
import PIL
import os
import glob
from os.path import join, dirname, realpath
import cv2
import random
makeup_path = './makeup_images'
FOLDER = join(dirname(real... | 0.350533 | 0.358662 |
__author__ = "ChenJun"
import numpy as np
import tensorflow as tf
from tensorflow.contrib import crf
class BatchNormLayer(object):
"""
batch normalization.
"""
def __init__(self, n_in, inputs):
self.gamma = tf.Variable(initial_value=np.ones(n_in,), dtype=tf.float32, name="gamma")
self... | tensorflow_models/layers.py | __author__ = "ChenJun"
import numpy as np
import tensorflow as tf
from tensorflow.contrib import crf
class BatchNormLayer(object):
"""
batch normalization.
"""
def __init__(self, n_in, inputs):
self.gamma = tf.Variable(initial_value=np.ones(n_in,), dtype=tf.float32, name="gamma")
self... | 0.845353 | 0.426023 |
import sys, os, platform, getpass
from datetime import date
def actualsignup(u,p):
f = open('udata.txt','a')
encred = encrypt(u,p)
f.write("%s " % encred[0])
f.write("%s\n" % encred[1])
os.mkdir('%s' % encred[0])
print("-"*67)
print("> USER CREDENTIALS SUCCESSFULLY WRITTEN")
print("-"*67)
prin... | pyjournal.py | import sys, os, platform, getpass
from datetime import date
def actualsignup(u,p):
f = open('udata.txt','a')
encred = encrypt(u,p)
f.write("%s " % encred[0])
f.write("%s\n" % encred[1])
os.mkdir('%s' % encred[0])
print("-"*67)
print("> USER CREDENTIALS SUCCESSFULLY WRITTEN")
print("-"*67)
prin... | 0.029944 | 0.061199 |
import time
from urllib import parse as URLParse
from pymongo import MongoClient
from pymongo.helpers import OperationFailure
class MongoDBManager():
def __init__(self):
self._client = None
self._config = None
def connect(self, scheme, host, username, password, port = 27017, database = "admin... | app/managers/mongodbmanager.py | import time
from urllib import parse as URLParse
from pymongo import MongoClient
from pymongo.helpers import OperationFailure
class MongoDBManager():
def __init__(self):
self._client = None
self._config = None
def connect(self, scheme, host, username, password, port = 27017, database = "admin... | 0.384103 | 0.083703 |
"""Tests for tensorflow.python.framework.composite_tensor."""
from __future__ import absolute_import
from __future__ import division
from __future__ import print_function
from tensorflow.python.framework import composite_tensor
from tensorflow.python.framework import sparse_tensor
from tensorflow.python.framework imp... | tensorflow/python/framework/composite_tensor_test.py | """Tests for tensorflow.python.framework.composite_tensor."""
from __future__ import absolute_import
from __future__ import division
from __future__ import print_function
from tensorflow.python.framework import composite_tensor
from tensorflow.python.framework import sparse_tensor
from tensorflow.python.framework imp... | 0.899159 | 0.669238 |
from wbml.parser import Parser, Whitespace, Literal, Float, SkipUntil
import wbml.plot
import matplotlib.pyplot as plt
from wbml.experiment import WorkingDirectory
wd = WorkingDirectory("_experiments", "temperature_parse")
def parse(path):
parser = Parser(path)
parser.find_line("RMSE")
rmse = parser.par... | experiments/temperature_parse.py | from wbml.parser import Parser, Whitespace, Literal, Float, SkipUntil
import wbml.plot
import matplotlib.pyplot as plt
from wbml.experiment import WorkingDirectory
wd = WorkingDirectory("_experiments", "temperature_parse")
def parse(path):
parser = Parser(path)
parser.find_line("RMSE")
rmse = parser.par... | 0.647241 | 0.572364 |
import numpy as np
from sklearn.preprocessing import OneHotEncoder
class SoftmaxRegression(object):
def __init__(self, reg_str=0.0):
self.W = None
self.error = None
self.lam = reg_str # regularization strength
def _linear_hypothesis(self, W, X):
"""
wX+b
"""
... | smla/linear_model/softmax_regression.py |
import numpy as np
from sklearn.preprocessing import OneHotEncoder
class SoftmaxRegression(object):
def __init__(self, reg_str=0.0):
self.W = None
self.error = None
self.lam = reg_str # regularization strength
def _linear_hypothesis(self, W, X):
"""
wX+b
"""
... | 0.892832 | 0.587677 |
from discord.ext import commands
from discord import Member, VoiceChannel
from datetime import timedelta
class Comandi(commands.Cog):
def __init__(self, bot):
self.bot = bot
@commands.Cog.listener()
async def on_ready(self):
print("Comandi caricati!")
@commands.command(n... | cogs/Comandi.py | from discord.ext import commands
from discord import Member, VoiceChannel
from datetime import timedelta
class Comandi(commands.Cog):
def __init__(self, bot):
self.bot = bot
@commands.Cog.listener()
async def on_ready(self):
print("Comandi caricati!")
@commands.command(n... | 0.298083 | 0.150029 |
import optparse , concurrent.futures , readline
from assets import CommandsParser , ScriptsRunner , CommandsPaths , Parser
from os import path
def Shell(Options):
Path = CommandsPaths.Main()
Commands = CommandsParser.Main(Path)
while (1):
Input = input("/> ")
try:
... | easy.py | import optparse , concurrent.futures , readline
from assets import CommandsParser , ScriptsRunner , CommandsPaths , Parser
from os import path
def Shell(Options):
Path = CommandsPaths.Main()
Commands = CommandsParser.Main(Path)
while (1):
Input = input("/> ")
try:
... | 0.170923 | 0.053899 |
import pytest
import torch
from nemo.collections.asr import modules
class TestASRModulesBasicTests:
@pytest.mark.unit
def test_AudioToMelSpectrogramPreprocessor1(self):
# Test 1 that should test the pure stft implementation as much as possible
instance1 = modules.AudioToMelSpectrogramPreproc... | tests/collections/asr/test_asr_modules.py |
import pytest
import torch
from nemo.collections.asr import modules
class TestASRModulesBasicTests:
@pytest.mark.unit
def test_AudioToMelSpectrogramPreprocessor1(self):
# Test 1 that should test the pure stft implementation as much as possible
instance1 = modules.AudioToMelSpectrogramPreproc... | 0.848847 | 0.72964 |
from PyQt5.QtWidgets import QWidget,QRubberBand
from PyQt5.QtWidgets import QLabel,QLineEdit
from PyQt5.QtWidgets import QGroupBox,QHBoxLayout,QVBoxLayout,QGridLayout,QPushButton
from PyQt5.QtWidgets import QPushButton
from PyQt5.QtCore import QPoint,QRect,QSize,QPointF
from PyQt5.QtCore import QThread
from PyQt5.QtGu... | colorTable/colorTable.py |
from PyQt5.QtWidgets import QWidget,QRubberBand
from PyQt5.QtWidgets import QLabel,QLineEdit
from PyQt5.QtWidgets import QGroupBox,QHBoxLayout,QVBoxLayout,QGridLayout,QPushButton
from PyQt5.QtWidgets import QPushButton
from PyQt5.QtCore import QPoint,QRect,QSize,QPointF
from PyQt5.QtCore import QThread
from PyQt5.QtGu... | 0.549036 | 0.118972 |
from pathlib import PosixPath
from typing import Dict, List, Optional, Union
import matplotlib.pylab as plt
import numpy as np
from numpy import ndarray
from modes import _analyse as anal
from modes import _mode_solver_lib as ms
from modes._mode_solver import _ModeSolver
class ModeSolverSemiVectorial(_ModeSolver):
... | modes/_mode_solver_semi_vectorial.py | from pathlib import PosixPath
from typing import Dict, List, Optional, Union
import matplotlib.pylab as plt
import numpy as np
from numpy import ndarray
from modes import _analyse as anal
from modes import _mode_solver_lib as ms
from modes._mode_solver import _ModeSolver
class ModeSolverSemiVectorial(_ModeSolver):
... | 0.948941 | 0.485173 |
from Usb import Usb
from Utils import int_to_byte, bytes_to_reg, bytes_reg_to_int_reg
import logging
class SintDigFrec:
usb = Usb()
reg1 = [0x04, 0x05, 0x06, 0x07, 0x08, 0x09]
reg2 = [0x0A, 0x0B, 0x0C, 0x0D, 0x0E, 0x0F]
dds_cmd = 0x70
dds_mode = 0x71
dds_rst = 0x72
dds_test = 0x73
dds_... | SintDigFrec.py | from Usb import Usb
from Utils import int_to_byte, bytes_to_reg, bytes_reg_to_int_reg
import logging
class SintDigFrec:
usb = Usb()
reg1 = [0x04, 0x05, 0x06, 0x07, 0x08, 0x09]
reg2 = [0x0A, 0x0B, 0x0C, 0x0D, 0x0E, 0x0F]
dds_cmd = 0x70
dds_mode = 0x71
dds_rst = 0x72
dds_test = 0x73
dds_... | 0.4206 | 0.425486 |
import logging.config
import warnings
from pathlib import Path
from typing import Any, Type
from omegaconf import DictConfig, OmegaConf, _utils
from hydra.conf import PluginConf
from hydra.core.hydra_config import HydraConfig
log = logging.getLogger(__name__)
def get_method(path: str) -> type:
return get_class... | hydra/utils.py | import logging.config
import warnings
from pathlib import Path
from typing import Any, Type
from omegaconf import DictConfig, OmegaConf, _utils
from hydra.conf import PluginConf
from hydra.core.hydra_config import HydraConfig
log = logging.getLogger(__name__)
def get_method(path: str) -> type:
return get_class... | 0.653238 | 0.171165 |
import numpy as np
import scipy.sparse as sp
from sklearn.utils.fixes import _astype_copy_false
class WeightsComputer:
'''
Weight methods:
idf : log( (1 + n) / (1 + df(t)) ) + 1
dfs : Distinguishing feature selector
chi2 : Term Weighting Based on Chi-Square Statistic
ig : Term... | models/computer.py | import numpy as np
import scipy.sparse as sp
from sklearn.utils.fixes import _astype_copy_false
class WeightsComputer:
'''
Weight methods:
idf : log( (1 + n) / (1 + df(t)) ) + 1
dfs : Distinguishing feature selector
chi2 : Term Weighting Based on Chi-Square Statistic
ig : Term... | 0.625552 | 0.494629 |
import logging # Used for logging
from typing import Union # Used for type hints with multiple types
# External Dependencies
import requests # Used to make http requests for redirect tracing
def trace(url: str, ignored_domains: Union[list, bool], print_result: bool = True) -> ... | sws/redirects.py | import logging # Used for logging
from typing import Union # Used for type hints with multiple types
# External Dependencies
import requests # Used to make http requests for redirect tracing
def trace(url: str, ignored_domains: Union[list, bool], print_result: bool = True) -> ... | 0.837188 | 0.454291 |
import pandas as pd
from bsbetl.alltable_calcs import at_columns
from bsbetl.alltable_calcs.at_virtual_cols import Virtual_Column
class at_virtual_MovingAverage(Virtual_Column):
""" represents and can creates a column in an all-table dataframe containing moving average price """
def __init__(self):
... | bsbetl/alltable_calcs/at_Virtual_MovingAverage.py |
import pandas as pd
from bsbetl.alltable_calcs import at_columns
from bsbetl.alltable_calcs.at_virtual_cols import Virtual_Column
class at_virtual_MovingAverage(Virtual_Column):
""" represents and can creates a column in an all-table dataframe containing moving average price """
def __init__(self):
... | 0.586404 | 0.457258 |
import numpy as np
import pandas as pd
from scipy.stats import mode
# code starts here
bank = pd.read_csv(path)
categorical_var = bank.select_dtypes(include='object')
print(categorical_var)
numerical_var = bank.select_dtypes(include='number')
print(numerical_var)
# code ends here
# --------------
# code ... | Bank-Loan-Project/code.py | import numpy as np
import pandas as pd
from scipy.stats import mode
# code starts here
bank = pd.read_csv(path)
categorical_var = bank.select_dtypes(include='object')
print(categorical_var)
numerical_var = bank.select_dtypes(include='number')
print(numerical_var)
# code ends here
# --------------
# code ... | 0.09033 | 0.141281 |
import requests
import simplejson
from service.ticket.ticket_base_service import TicketBaseService
headers = {}
class WeekPaper(object):
def __init__(self, url='http://10.254.50.230:31001/v1/', project=1):
self.url = url
self.project = project
self.username = 'xulei'
self.password ... | media/workflow_script/xxzx_week_page.py | import requests
import simplejson
from service.ticket.ticket_base_service import TicketBaseService
headers = {}
class WeekPaper(object):
def __init__(self, url='http://10.254.50.230:31001/v1/', project=1):
self.url = url
self.project = project
self.username = 'xulei'
self.password ... | 0.191101 | 0.341981 |
import tensorflow as tf
from tensorflow import keras
from tensorflow.keras import layers
import numpy as np
from datetime import datetime
import h5py
import os
from os.path import exists
'''inputs = keras.Input(shape=(784,), name="digits")
x = layers.Dense(64, activation="relu", name="dense_1")(inputs)
x ... | UNet.py |
import tensorflow as tf
from tensorflow import keras
from tensorflow.keras import layers
import numpy as np
from datetime import datetime
import h5py
import os
from os.path import exists
'''inputs = keras.Input(shape=(784,), name="digits")
x = layers.Dense(64, activation="relu", name="dense_1")(inputs)
x ... | 0.574275 | 0.246375 |
import sys
class JouvenceDocument:
"""Represents a Fountain screenplay in a structured way.
A screenplay contains:
* A title page (optional) with a key/value dictionary of settings.
* A list of scenes.
* Each scene contains a list of paragraphs of various types.
"""
def __init__(self):
... | jouvence/document.py | import sys
class JouvenceDocument:
"""Represents a Fountain screenplay in a structured way.
A screenplay contains:
* A title page (optional) with a key/value dictionary of settings.
* A list of scenes.
* Each scene contains a list of paragraphs of various types.
"""
def __init__(self):
... | 0.61855 | 0.348978 |
from node.telemetry.subscriber import Subscriber
import proto.report_pb2 as proto_report
from proto.negotiation_pb2 import Negotiation
import node.constants as const
import zmq
import node.memory
class NetworkSubscriber(Subscriber):
"""
Accepts subscriber updates and packages into Protobuf messages.
The m... | node/net/pack.py | from node.telemetry.subscriber import Subscriber
import proto.report_pb2 as proto_report
from proto.negotiation_pb2 import Negotiation
import node.constants as const
import zmq
import node.memory
class NetworkSubscriber(Subscriber):
"""
Accepts subscriber updates and packages into Protobuf messages.
The m... | 0.304972 | 0.112454 |
import django.test
from statusapp.views.helpers import is_ip_in_subnet, is_ipaddress, \
is_port
class IpInSubnetTest(django.test.TestCase):
"""
Test the is_ip_in_subnet function.
"""
def test_range(self):
"""
Test that the subnet bit, when provided, is handled correctly.
... | status/statusapp/tests.py | import django.test
from statusapp.views.helpers import is_ip_in_subnet, is_ipaddress, \
is_port
class IpInSubnetTest(django.test.TestCase):
"""
Test the is_ip_in_subnet function.
"""
def test_range(self):
"""
Test that the subnet bit, when provided, is handled correctly.
... | 0.661267 | 0.312304 |
# <NAME>
# Department of Political Science
# University of California, Davis
"""
judges.LoadData v2.0
This script takes the Federal Judicial Center's Biographical Directory of
Article III Federal Judges and generates a json file formatted for easy
import/use in other federal courts-related research applications.
New... | judges/LoadData.py |
# <NAME>
# Department of Political Science
# University of California, Davis
"""
judges.LoadData v2.0
This script takes the Federal Judicial Center's Biographical Directory of
Article III Federal Judges and generates a json file formatted for easy
import/use in other federal courts-related research applications.
New... | 0.308086 | 0.264623 |
from __future__ import print_function
import unittest
import ruffus
from ruffus import transform, regex, pipeline_run, Pipeline, originate, mkdir
import sys
"""
test_transform_with_no_re_matches.py
test messages with no regular expression matches
"""
# 8888888888888888888888888888888888888888888888888... | ruffus/test/test_transform_with_no_re_matches.py | from __future__ import print_function
import unittest
import ruffus
from ruffus import transform, regex, pipeline_run, Pipeline, originate, mkdir
import sys
"""
test_transform_with_no_re_matches.py
test messages with no regular expression matches
"""
# 8888888888888888888888888888888888888888888888888... | 0.331228 | 0.05375 |
#
#
# Part (c)
#
#
print("\n")
print("Part (c)")
print(" ")
print("\n")
print("Part (c1)")
print(" ")
from collections import namedtuple
Dish = namedtuple('Dish', 'name price calories')
d1 = Dish("Kung Pao Chicken", 9.50, 550)
d2 = Dish("Paht Woon Sen", 9.50, 330)
d3 = Dish("Big Mac", 5.75, 550)
... | Assignment 5/lab5.py |
#
#
# Part (c)
#
#
print("\n")
print("Part (c)")
print(" ")
print("\n")
print("Part (c1)")
print(" ")
from collections import namedtuple
Dish = namedtuple('Dish', 'name price calories')
d1 = Dish("Kung Pao Chicken", 9.50, 550)
d2 = Dish("Paht Woon Sen", 9.50, 330)
d3 = Dish("Big Mac", 5.75, 550)
... | 0.258513 | 0.329837 |
from __future__ import division
__author__ = "<NAME> and <NAME>"
__copyright__ = "Copyright 2013, The miMAP project"
__credits__ = "<NAME>", "<NAME>"
__license__ = "GPL"
__version__ = "0.0.0-dev"
__maintainer__ = "<NAME>"
__email__ = "<EMAIL>"
from shutil import rmtree
from os.path import join, split, splitext, exist... | biom_to_core_diversity_analyses.py | from __future__ import division
__author__ = "<NAME> and <NAME>"
__copyright__ = "Copyright 2013, The miMAP project"
__credits__ = "<NAME>", "<NAME>"
__license__ = "GPL"
__version__ = "0.0.0-dev"
__maintainer__ = "<NAME>"
__email__ = "<EMAIL>"
from shutil import rmtree
from os.path import join, split, splitext, exist... | 0.542136 | 0.22891 |
from importlib import import_module
import click
from config import CONFIG, read_config
def setup(config):
read_config(config)
hosts = str(CONFIG.get('general', 'HOSTS')).split(',')
indicator_module = import_module('indicators')
indicator_classes = str(CONFIG.get('general', 'indicators')).split('... | monitor.py |
from importlib import import_module
import click
from config import CONFIG, read_config
def setup(config):
read_config(config)
hosts = str(CONFIG.get('general', 'HOSTS')).split(',')
indicator_module = import_module('indicators')
indicator_classes = str(CONFIG.get('general', 'indicators')).split('... | 0.318803 | 0.121607 |
from sand.sensor_module import HardwareSensorModule
import subprocess
class NetworkDevices(HardwareSensorModule):
def __init__(self):
HardwareSensorModule.__init__(self)
self._process = None
def run_command(self):
self._process = subprocess.Popen(["ip", "address"], stdout=subprocess.P... | src/sand/modules/network/sensor.py | from sand.sensor_module import HardwareSensorModule
import subprocess
class NetworkDevices(HardwareSensorModule):
def __init__(self):
HardwareSensorModule.__init__(self)
self._process = None
def run_command(self):
self._process = subprocess.Popen(["ip", "address"], stdout=subprocess.P... | 0.425963 | 0.119305 |
import torch
from torch import Tensor
from torch.nn.functional import softmax
from src.helper_functions import predict
from typing import Dict, List
from collections import defaultdict
import numpy as np
def calculate_suff(attrs):
pass
def calculate_comp(
attr: Tensor,
k: float,
replacement_emb: Ten... | src/ablation_evaluation.py | import torch
from torch import Tensor
from torch.nn.functional import softmax
from src.helper_functions import predict
from typing import Dict, List
from collections import defaultdict
import numpy as np
def calculate_suff(attrs):
pass
def calculate_comp(
attr: Tensor,
k: float,
replacement_emb: Ten... | 0.954467 | 0.77768 |
import pytest
@pytest.mark.parametrize(
"json_credential_obj", [pytest.lazy_fixture("json_credential"), pytest.lazy_fixture("json_data_credential")]
)
def test_metadata(json_credential_obj) -> None:
assert json_credential_obj.provider_code == "json"
assert json_credential_obj.separator == "/"
@pytest.ma... | tests/unit/contrib/json/test_credential.py | import pytest
@pytest.mark.parametrize(
"json_credential_obj", [pytest.lazy_fixture("json_credential"), pytest.lazy_fixture("json_data_credential")]
)
def test_metadata(json_credential_obj) -> None:
assert json_credential_obj.provider_code == "json"
assert json_credential_obj.separator == "/"
@pytest.ma... | 0.542379 | 0.36815 |
class Arithmetic:
def __init__(self, name):
self._value = str(name)
def __str__(self):
return self._value
def __neg__(self):
return Neg(self)
def __add__(self, other):
return Add(self, other)
def __radd__(self, other):
return Add(other, self)
def __s... | logicycl/entity.py | class Arithmetic:
def __init__(self, name):
self._value = str(name)
def __str__(self):
return self._value
def __neg__(self):
return Neg(self)
def __add__(self, other):
return Add(self, other)
def __radd__(self, other):
return Add(other, self)
def __s... | 0.831588 | 0.269098 |
import logging
import sys
import getopt
import random
import numpy as np
from spectral_toolbox import *
class TurbulentICs:
"""
This class encapsulates the necessary methods to create initially-balanced turbulent
initial conditions, following Polvani et al 1994.
**Parameters**
- `co... | fdc_een_swm/initial_conditions/polvani_conditions.py | import logging
import sys
import getopt
import random
import numpy as np
from spectral_toolbox import *
class TurbulentICs:
"""
This class encapsulates the necessary methods to create initially-balanced turbulent
initial conditions, following Polvani et al 1994.
**Parameters**
- `co... | 0.763043 | 0.589953 |
from p5 import *
import sympy as sym
import mpmath as mp
import numpy as np
from tkinter import Tk
from scipy.spatial import distance
import PIL
from PIL import Image
import argparse
import os
import csv
import mimetypes
DEBUG = False
parser = argparse.ArgumentParser(
description='Custom frame annotator implement... | annotator.py | from p5 import *
import sympy as sym
import mpmath as mp
import numpy as np
from tkinter import Tk
from scipy.spatial import distance
import PIL
from PIL import Image
import argparse
import os
import csv
import mimetypes
DEBUG = False
parser = argparse.ArgumentParser(
description='Custom frame annotator implement... | 0.362743 | 0.175414 |
DESC = "dc-2018-04-10"
INFO = {
"CreateDirectConnectTunnel": {
"params": [
{
"name": "DirectConnectId",
"desc": "专线 ID,例如:dc-kd7d06of"
},
{
"name": "DirectConnectTunnelName",
"desc": "专用通道名称"
},
{
"name": "DirectConnectOwnerAccount",
"d... | tccli/services/dc/v20180410/help.py | DESC = "dc-2018-04-10"
INFO = {
"CreateDirectConnectTunnel": {
"params": [
{
"name": "DirectConnectId",
"desc": "专线 ID,例如:dc-kd7d06of"
},
{
"name": "DirectConnectTunnelName",
"desc": "专用通道名称"
},
{
"name": "DirectConnectOwnerAccount",
"d... | 0.257112 | 0.230108 |
class WorksharingDisplayGraphicSettings(object, IDisposable):
"""
Represents the graphical settings that can be assigned to elements in the worksharing
display modes.
WorksharingDisplayGraphicSettings(shouldApply: bool,lineColor: Color)
"""
def Dispose(self):
""" Dispose(self: W... | release/stubs.min/Autodesk/Revit/DB/__init___parts/WorksharingDisplayGraphicSettings.py | class WorksharingDisplayGraphicSettings(object, IDisposable):
"""
Represents the graphical settings that can be assigned to elements in the worksharing
display modes.
WorksharingDisplayGraphicSettings(shouldApply: bool,lineColor: Color)
"""
def Dispose(self):
""" Dispose(self: W... | 0.765506 | 0.285204 |
opaque_type_mapping = {
'Image': {
'ns': 0,
'id': 15,
'name': 'ByteString'
},
'Number': {
'ns': 0,
'id': 24,
'name': 'BaseDataType'
},
'UInteger': {
'ns': 0,
'id': 24,
'name': 'BaseDataType'
},
'ImageBMP': {
'ns'... | lib/src/tools/nodeset_compiler/opaque_type_mapping.py | opaque_type_mapping = {
'Image': {
'ns': 0,
'id': 15,
'name': 'ByteString'
},
'Number': {
'ns': 0,
'id': 24,
'name': 'BaseDataType'
},
'UInteger': {
'ns': 0,
'id': 24,
'name': 'BaseDataType'
},
'ImageBMP': {
'ns'... | 0.495117 | 0.264778 |
from django.shortcuts import render, get_object_or_404
from django.core.paginator import Paginator
from django.conf import settings
from django.views.generic import DetailView, View
from .models import Blog,BlogType
from read_statistics.utils import add_once_read
def base_data(request, blogs):
try:
page =... | blog/views.py | from django.shortcuts import render, get_object_or_404
from django.core.paginator import Paginator
from django.conf import settings
from django.views.generic import DetailView, View
from .models import Blog,BlogType
from read_statistics.utils import add_once_read
def base_data(request, blogs):
try:
page =... | 0.219254 | 0.128279 |
import requests
import json
from sys import stdout
from math import ceil
from datetime import datetime
import os
_ERROR_LOG_FILE = 'portal_error_log.txt'
_MB_PER_CHUNK = 64
_B_PER_MB = 1048576
_CHUNK_SIZE = _MB_PER_CHUNK * _B_PER_MB # Download 128 MB at a time
## Utility function to write to the error log file
de... | Python/DatasetUtilsPackage/DatasetUtils/GirderAPI.py | import requests
import json
from sys import stdout
from math import ceil
from datetime import datetime
import os
_ERROR_LOG_FILE = 'portal_error_log.txt'
_MB_PER_CHUNK = 64
_B_PER_MB = 1048576
_CHUNK_SIZE = _MB_PER_CHUNK * _B_PER_MB # Download 128 MB at a time
## Utility function to write to the error log file
de... | 0.31059 | 0.076857 |
import random
import unittest
import copy
from norm_behaviour_old import *
from aamas_experiments import sum_entry,average_entries
from priorityqueue import PriorityQueue
from norm_identification2 import *
from __builtin__ import str
class TestNormBehaviour(unittest.TestCase):
def setUp(self):
self.go... | test_norm_behaviour_old.py | import random
import unittest
import copy
from norm_behaviour_old import *
from aamas_experiments import sum_entry,average_entries
from priorityqueue import PriorityQueue
from norm_identification2 import *
from __builtin__ import str
class TestNormBehaviour(unittest.TestCase):
def setUp(self):
self.go... | 0.160595 | 0.339992 |
import torch
from tsl.nn.layers.graph_convs.dense_spatial_conv import SpatialConvOrderK
from tsl.nn.blocks.encoders.gcrnn import _GraphGRUCell, _GraphRNN
class DenseDCRNNCell(_GraphGRUCell):
r"""
Diffusion Convolutional Recurrent Cell.
Args:
input_size: Size of the input.
output_size: ... | tsl/nn/blocks/encoders/dense_dcrnn.py | import torch
from tsl.nn.layers.graph_convs.dense_spatial_conv import SpatialConvOrderK
from tsl.nn.blocks.encoders.gcrnn import _GraphGRUCell, _GraphRNN
class DenseDCRNNCell(_GraphGRUCell):
r"""
Diffusion Convolutional Recurrent Cell.
Args:
input_size: Size of the input.
output_size: ... | 0.942639 | 0.45944 |
"""Generated protocol buffer code."""
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
# @@protoc_insertion_point(imports)
_sym_db = _symbol_databas... | src/hedera_proto/consensus_submit_message_pb2.py | """Generated protocol buffer code."""
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
# @@protoc_insertion_point(imports)
_sym_db = _symbol_databas... | 0.307046 | 0.080033 |
import sys
if __name__ == '__main__':
sys.path.append('../..')
import copy
import logging
import inspect
from mongolog.handlers import MongoHandler
from base_state import BaseState
from state_tool import after_get_parameter, get_need_verify_types, \
get_next_verify_action, generate_log_data... | dianhua/worker/state/multi_verify_state.py | import sys
if __name__ == '__main__':
sys.path.append('../..')
import copy
import logging
import inspect
from mongolog.handlers import MongoHandler
from base_state import BaseState
from state_tool import after_get_parameter, get_need_verify_types, \
get_next_verify_action, generate_log_data... | 0.259544 | 0.064329 |
from highton import fields
from highton.models import HightonModel
from highton.highton_constants import HightonConstants
class Contact(
HightonModel,
):
"""
:ivar id: fields.IntegerField(name=HightonConstants.ID)
:ivar author_id: fields.IntegerField(name=HightonConstants.AUTHOR_ID)
:ivar backgro... | highton/models/contact.py | from highton import fields
from highton.models import HightonModel
from highton.highton_constants import HightonConstants
class Contact(
HightonModel,
):
"""
:ivar id: fields.IntegerField(name=HightonConstants.ID)
:ivar author_id: fields.IntegerField(name=HightonConstants.AUTHOR_ID)
:ivar backgro... | 0.673836 | 0.080719 |
import sys
import os
import math
import SudokuBoard
import Constraint
import ConstraintNetwork
import BTSolver
import Trail
import time
"""
Main driver file, which is responsible for interfacing with the
command line and properly starting the backtrack solver.
"""
def main ( ):
args = sys.argv
# Imp... | src/Main.py |
import sys
import os
import math
import SudokuBoard
import Constraint
import ConstraintNetwork
import BTSolver
import Trail
import time
"""
Main driver file, which is responsible for interfacing with the
command line and properly starting the backtrack solver.
"""
def main ( ):
args = sys.argv
# Imp... | 0.258794 | 0.13969 |
from unittest.mock import Mock
from tests.mock import AsyncContextManagerMock
def configure_mock_session(mock_session_class, coroutine):
"""Return a mock session object out of the `mock_session_class`
mock class, with proper asynchronous context management behavior,
specified by `coroutine`.
"""
... | tests/auth.py | from unittest.mock import Mock
from tests.mock import AsyncContextManagerMock
def configure_mock_session(mock_session_class, coroutine):
"""Return a mock session object out of the `mock_session_class`
mock class, with proper asynchronous context management behavior,
specified by `coroutine`.
"""
... | 0.898977 | 0.32354 |
import os
import json
import numpy as np
from ..default import API_SCHEMA_FILE
from .. import ErsiliaBase
class ApiSchema(ErsiliaBase):
def __init__(self, model_id, config_json):
ErsiliaBase.__init__(self, config_json=config_json)
self.model_id = model_id
self.schema_file = os.path.join(
... | ersilia/serve/schema.py | import os
import json
import numpy as np
from ..default import API_SCHEMA_FILE
from .. import ErsiliaBase
class ApiSchema(ErsiliaBase):
def __init__(self, model_id, config_json):
ErsiliaBase.__init__(self, config_json=config_json)
self.model_id = model_id
self.schema_file = os.path.join(
... | 0.207616 | 0.153962 |
import codecs
from flask import render_template, Markup
import flask
from charlotte import app
from charlotte import articles
from charlotte import settings
@app.context_processor
def inject():
return {
"blog_name": settings.get_blog_name()
}
@app.route("/")
@app.route("/<page>")
def index(page="1")... | charlotte/routes/view.py | import codecs
from flask import render_template, Markup
import flask
from charlotte import app
from charlotte import articles
from charlotte import settings
@app.context_processor
def inject():
return {
"blog_name": settings.get_blog_name()
}
@app.route("/")
@app.route("/<page>")
def index(page="1")... | 0.219087 | 0.06489 |
import random
import numpy as np
from gym_splendor_code.envs.mechanics.action import Action
from gym_splendor_code.envs.mechanics.state import State
from gym_splendor_code.envs.mechanics.state_as_dict import StateAsDict
from gym_splendor_code.envs.mechanics.action_space_generator import generate_all_legal_reservations... | monte_carlo_tree_search/rollout_policies/greedy_rollout.py | import random
import numpy as np
from gym_splendor_code.envs.mechanics.action import Action
from gym_splendor_code.envs.mechanics.state import State
from gym_splendor_code.envs.mechanics.state_as_dict import StateAsDict
from gym_splendor_code.envs.mechanics.action_space_generator import generate_all_legal_reservations... | 0.558929 | 0.314156 |
from launch import LaunchDescription
from launch.actions import DeclareLaunchArgument
from launch.actions import GroupAction
from launch.actions import OpaqueFunction
from launch.substitutions import LaunchConfiguration
from launch_ros.actions import Node
from launch_ros.actions import PushRosNamespace
import mbzirc... | mbzirc_custom/mbzirc_point_lidar/launch/bridge.launch.py |
from launch import LaunchDescription
from launch.actions import DeclareLaunchArgument
from launch.actions import GroupAction
from launch.actions import OpaqueFunction
from launch.substitutions import LaunchConfiguration
from launch_ros.actions import Node
from launch_ros.actions import PushRosNamespace
import mbzirc... | 0.740174 | 0.291441 |
from ctypes import c_uint8, c_int16, c_int32, c_double, c_ulong, c_float, c_bool, c_char, c_char_p, create_string_buffer, byref, POINTER
import numpy as np
try:
from .helper import log
except:
from helper import log
# WFS status bits
WFS_STATUS = {
"CON" : 0x00000001, # USB connection lost, set by drive... | src/pywfs/sdk.py | from ctypes import c_uint8, c_int16, c_int32, c_double, c_ulong, c_float, c_bool, c_char, c_char_p, create_string_buffer, byref, POINTER
import numpy as np
try:
from .helper import log
except:
from helper import log
# WFS status bits
WFS_STATUS = {
"CON" : 0x00000001, # USB connection lost, set by drive... | 0.57093 | 0.353819 |
import pytest
from os import environ
import trainingsetai
try:
api_key = environ['TRAININGSET_API_KEY']
client = trainingsetai.TrainingsetClient(api_key)
except KeyError:
raise Exception(
"TRAININGSET_API_KEY environment variable is not set")
@pytest.fixture
def task_template():
return {
... | tests/sdk_test.py | import pytest
from os import environ
import trainingsetai
try:
api_key = environ['TRAININGSET_API_KEY']
client = trainingsetai.TrainingsetClient(api_key)
except KeyError:
raise Exception(
"TRAININGSET_API_KEY environment variable is not set")
@pytest.fixture
def task_template():
return {
... | 0.29747 | 0.241277 |
from codecs import open as copen
from re import match
from xml.dom.minidom import parse
from os import listdir
from utility import createPath, loadStruct, dumpStruct
def createProjection(f_align_p, f_stats, f_clean, f_proj, f_unknown_p):
""" Creates the projection based on rules.
"""
fcount = 0
de_co... | Scripts/process.py | from codecs import open as copen
from re import match
from xml.dom.minidom import parse
from os import listdir
from utility import createPath, loadStruct, dumpStruct
def createProjection(f_align_p, f_stats, f_clean, f_proj, f_unknown_p):
""" Creates the projection based on rules.
"""
fcount = 0
de_co... | 0.191365 | 0.175697 |
from torch.nn.parallel import DistributedDataParallel
from torch.nn.parallel.distributed import _find_tensors
import torch.optim
import torch.utils.data
import torch
from packaging import version
class DDP(DistributedDataParallel):
"""
Override the forward call in lightning so it goes to training and validatio... | utils/commons/ddp_utils.py | from torch.nn.parallel import DistributedDataParallel
from torch.nn.parallel.distributed import _find_tensors
import torch.optim
import torch.utils.data
import torch
from packaging import version
class DDP(DistributedDataParallel):
"""
Override the forward call in lightning so it goes to training and validatio... | 0.694717 | 0.320037 |
from __future__ import absolute_import
import logging
from django.contrib import messages
from django.core.urlresolvers import reverse
from sentry.models import OrganizationMemberType
from sentry.permissions import can_create_teams, Permissions
from sentry.web.forms.add_project import AddProjectForm
from sentry.web.... | src/sentry/web/frontend/create_team.py | from __future__ import absolute_import
import logging
from django.contrib import messages
from django.core.urlresolvers import reverse
from sentry.models import OrganizationMemberType
from sentry.permissions import can_create_teams, Permissions
from sentry.web.forms.add_project import AddProjectForm
from sentry.web.... | 0.47098 | 0.157558 |
import tensorflow as tf
from opt_utils import CGOptimizer, BFGSOptimizer, ACGOptimizer
class Mnist:
"""
load mnist, provide mini-batch method.
"""
def __str__(self):
return 'Mnist'
def __init__(self, dir_path, one_hot):
"""
:param dir_path: path of cifar-10 data sets
... | demo.py | import tensorflow as tf
from opt_utils import CGOptimizer, BFGSOptimizer, ACGOptimizer
class Mnist:
"""
load mnist, provide mini-batch method.
"""
def __str__(self):
return 'Mnist'
def __init__(self, dir_path, one_hot):
"""
:param dir_path: path of cifar-10 data sets
... | 0.782164 | 0.502991 |
def setPixel(block, x, y, z):
if inBounds(x) == False:
raise RuntimeError('x=%s is out of bounds' % x)
if inBounds(y) == False:
raise RuntimeError('y=%s is out of bounds' % y)
if inBounds(z) == False:
raise RuntimeError('z=%s is out of bounds' % z)
if block[16 * x + 4 * y + z] != 0:
raise Runtim... | solve4x4Cube.py | def setPixel(block, x, y, z):
if inBounds(x) == False:
raise RuntimeError('x=%s is out of bounds' % x)
if inBounds(y) == False:
raise RuntimeError('y=%s is out of bounds' % y)
if inBounds(z) == False:
raise RuntimeError('z=%s is out of bounds' % z)
if block[16 * x + 4 * y + z] != 0:
raise Runtim... | 0.486575 | 0.436022 |
from pathlib import Path
import numpy as np
import pandas as pd
import pytest
from py_muvr import FeatureSelector
from py_muvr.data_structures import (
FeatureEvaluationResults,
FeatureRanks,
InputDataset,
OuterLoopResults,
)
ASSETS_DIR = Path(__file__).parent / "assets"
@pytest.fixture(scope="sess... | tests/conftest.py | from pathlib import Path
import numpy as np
import pandas as pd
import pytest
from py_muvr import FeatureSelector
from py_muvr.data_structures import (
FeatureEvaluationResults,
FeatureRanks,
InputDataset,
OuterLoopResults,
)
ASSETS_DIR = Path(__file__).parent / "assets"
@pytest.fixture(scope="sess... | 0.651133 | 0.492493 |
from .utils import api_call, parse_api_call
from datetime import datetime
class ScoreBoard:
""" The ScoreBoard class contains all resources needed to use the
score board API calls. `stats.nba.com <https://stats.nba.com>`_
has the following score board API endpoints:
- **scoreboard**: Live scores a... | py_ball/scoreboard.py | from .utils import api_call, parse_api_call
from datetime import datetime
class ScoreBoard:
""" The ScoreBoard class contains all resources needed to use the
score board API calls. `stats.nba.com <https://stats.nba.com>`_
has the following score board API endpoints:
- **scoreboard**: Live scores a... | 0.826747 | 0.578776 |
import datetime
from functools import wraps
from flask import g
from flask_restful import Resource, abort, reqparse, fields, marshal_with
from flask_jwt import jwt_required, current_identity
from .models import db, Subscription, Publication
publication_serializer = {
'id': fields.Integer,
'title': fields.St... | subscriptions/app/resources.py | import datetime
from functools import wraps
from flask import g
from flask_restful import Resource, abort, reqparse, fields, marshal_with
from flask_jwt import jwt_required, current_identity
from .models import db, Subscription, Publication
publication_serializer = {
'id': fields.Integer,
'title': fields.St... | 0.619126 | 0.085862 |
import os
BASE_DIR = os.path.dirname(os.path.dirname(os.path.abspath(__file__)))
INSTALLED_APPS = [
'django.contrib.admin',
'django.contrib.auth',
'django.contrib.contenttypes',
'django.contrib.sessions',
'django.contrib.messages',
'django.contrib.staticfiles',
# 3rd party
'django_exte... | core/core/settings/base.py | import os
BASE_DIR = os.path.dirname(os.path.dirname(os.path.abspath(__file__)))
INSTALLED_APPS = [
'django.contrib.admin',
'django.contrib.auth',
'django.contrib.contenttypes',
'django.contrib.sessions',
'django.contrib.messages',
'django.contrib.staticfiles',
# 3rd party
'django_exte... | 0.220091 | 0.067179 |
from cloud.crypto import *
import cloud.shortuuid as shortuuid
from cloud.auth.get_login_method import do as get_login_method
from cloud.permission import Permission, NeedPermission
from cloud.message import error
from secrets import token_urlsafe
# Define the input output format of the function.
# This information is... | aws_interface/cloud/auth/guest.py | from cloud.crypto import *
import cloud.shortuuid as shortuuid
from cloud.auth.get_login_method import do as get_login_method
from cloud.permission import Permission, NeedPermission
from cloud.message import error
from secrets import token_urlsafe
# Define the input output format of the function.
# This information is... | 0.361841 | 0.106993 |
import unittest
from sqlalchemy import Column, ForeignKey
from sqlalchemy.orm import relationship
from coaster.views import load_model, load_models
from coaster.sqlalchemy import BaseMixin, BaseNameMixin, BaseScopedIdMixin
from coaster.db import db
from test_models import (app1, app2, Container, NamedDocument,
S... | tests/test_loadmodels.py |
import unittest
from sqlalchemy import Column, ForeignKey
from sqlalchemy.orm import relationship
from coaster.views import load_model, load_models
from coaster.sqlalchemy import BaseMixin, BaseNameMixin, BaseScopedIdMixin
from coaster.db import db
from test_models import (app1, app2, Container, NamedDocument,
S... | 0.604983 | 0.124505 |
import math
import torch
import random
import numpy as np
from pathlib import Path
from typing import Tuple
from torch.optim.optimizer import Optimizer
from torch.optim.rmsprop import RMSprop
from torch.utils.tensorboard.writer import SummaryWriter
from datetime import datetime, timezone
from copy import deepcopy
fro... | models/DQN_paper/self_play_training.py | import math
import torch
import random
import numpy as np
from pathlib import Path
from typing import Tuple
from torch.optim.optimizer import Optimizer
from torch.optim.rmsprop import RMSprop
from torch.utils.tensorboard.writer import SummaryWriter
from datetime import datetime, timezone
from copy import deepcopy
fro... | 0.817064 | 0.242486 |
from aliyunsdkcore.client import AcsClient
from aliyunsdkcore.request import CommonRequest
from webAPi.utils.com import get_config_from_env
from webAPi.utils.snowflake import snow_flake
class SendSms(object):
def __init__(self, phone: str = None, category: str = None, template_param=None):
"""
发送短... | webAPi/utils/phone_msg.py | from aliyunsdkcore.client import AcsClient
from aliyunsdkcore.request import CommonRequest
from webAPi.utils.com import get_config_from_env
from webAPi.utils.snowflake import snow_flake
class SendSms(object):
def __init__(self, phone: str = None, category: str = None, template_param=None):
"""
发送短... | 0.358016 | 0.083068 |
import os
import pickle
import numpy as np
from maro.rl import AbsAgent, ColumnBasedStore
class DQNAgent(AbsAgent):
"""Implementation of AbsAgent for the DQN algorithm.
Args:
name (str): Agent's name.
algorithm (AbsAlgorithm): A concrete algorithm instance that inherits from AbstractAlgori... | examples/cim/dqn/components/agent.py |
import os
import pickle
import numpy as np
from maro.rl import AbsAgent, ColumnBasedStore
class DQNAgent(AbsAgent):
"""Implementation of AbsAgent for the DQN algorithm.
Args:
name (str): Agent's name.
algorithm (AbsAlgorithm): A concrete algorithm instance that inherits from AbstractAlgori... | 0.823896 | 0.334114 |
import os
import collections
import torch
class Model(object):
def name(self):
pass
def load(self):
pass
class FileModel(Model):
def __init__(self, path):
self._model = None
self._path = path
def _get_scale_index(self, state_dict):
# this is more or less guess... | model.py | import os
import collections
import torch
class Model(object):
def name(self):
pass
def load(self):
pass
class FileModel(Model):
def __init__(self, path):
self._model = None
self._path = path
def _get_scale_index(self, state_dict):
# this is more or less guess... | 0.475605 | 0.253324 |
from datetime import datetime
import math
def mag(x):
return np.linalg.norm(np.array(x))
def sec_to_jd(seconds):
"""seconds since J2000 to jd"""
return 2451545.0 + seconds / 86400.0
def jd_to_sec(jd):
"""jd to seconds since J2000"""
return (jd - 2451545.0) * 86400.0
def datetime_to_jd(t):
ye... | numeph/julian.py | from datetime import datetime
import math
def mag(x):
return np.linalg.norm(np.array(x))
def sec_to_jd(seconds):
"""seconds since J2000 to jd"""
return 2451545.0 + seconds / 86400.0
def jd_to_sec(jd):
"""jd to seconds since J2000"""
return (jd - 2451545.0) * 86400.0
def datetime_to_jd(t):
ye... | 0.483405 | 0.474692 |
from math import ceil
from PyQt5.QtCore import Qt
from PyQt5.QtGui import (
QPainter,
QPen,
QBrush,
QPixmap,
QImage,
QPaintEvent,
QColor,
QWheelEvent,
QMouseEvent,
)
from PyQt5.QtWidgets import (
QWidget,
QVBoxLayout,
QScrollBar,
QHBoxLayout,
)
from app import App
... | qt_classes/bits_widget.py | from math import ceil
from PyQt5.QtCore import Qt
from PyQt5.QtGui import (
QPainter,
QPen,
QBrush,
QPixmap,
QImage,
QPaintEvent,
QColor,
QWheelEvent,
QMouseEvent,
)
from PyQt5.QtWidgets import (
QWidget,
QVBoxLayout,
QScrollBar,
QHBoxLayout,
)
from app import App
... | 0.790247 | 0.124585 |
import pytest
import os
from unittest import mock
from tfx.components.base.base_component import BaseComponent
from fluent_tfx import PipelineDef, \
ExampleInputs, SchemaInputs, HyperParameterInputs
from fluent_tfx.pipeline_def import build_step
from tfx.components.base import executor_spec
from tfx.extensions.g... | tests/pipeline_def/tune_test.py | import pytest
import os
from unittest import mock
from tfx.components.base.base_component import BaseComponent
from fluent_tfx import PipelineDef, \
ExampleInputs, SchemaInputs, HyperParameterInputs
from fluent_tfx.pipeline_def import build_step
from tfx.components.base import executor_spec
from tfx.extensions.g... | 0.641535 | 0.483405 |
import os
import sys
import ssl
import re
import logging
from string import punctuation
from urllib.request import Request, urlopen, quote
from bs4 import BeautifulSoup
import requests
import socket
import json
from genius.song import Song
from genius.artist import Artist
logger = logging.getLogger(__name__)
DIR_P... | genius/api.py |
import os
import sys
import ssl
import re
import logging
from string import punctuation
from urllib.request import Request, urlopen, quote
from bs4 import BeautifulSoup
import requests
import socket
import json
from genius.song import Song
from genius.artist import Artist
logger = logging.getLogger(__name__)
DIR_P... | 0.371137 | 0.101679 |
from .version import __author__, __author_email__, __url__, __version__
# pylint: disable=wildcard-import
from .constants import *
# pylint: enable=wildcard-import
from .agent import SSHAgentClient, SSHAgentKeyPair, connect_agent
from .auth_keys import SSHAuthorizedKeys
from .auth_keys import import_authorized_key... | sandbox/lib/pythonbin/asyncssh/__init__.py | from .version import __author__, __author_email__, __url__, __version__
# pylint: disable=wildcard-import
from .constants import *
# pylint: enable=wildcard-import
from .agent import SSHAgentClient, SSHAgentKeyPair, connect_agent
from .auth_keys import SSHAuthorizedKeys
from .auth_keys import import_authorized_key... | 0.289773 | 0.030015 |
from django.conf import settings
from django.http import Http404
from django.shortcuts import redirect
from django.views.generic import View
from common.djangoapps.edxmako.shortcuts import render_to_response
from common.djangoapps.student.models import CourseEnrollment
from openedx.core.djangoapps.site_configuration i... | Part-03-Understanding-Software-Crafting-Your-Own-Tools/models/edx-platform/lms/djangoapps/support/views/contact_us.py | from django.conf import settings
from django.http import Http404
from django.shortcuts import redirect
from django.views.generic import View
from common.djangoapps.edxmako.shortcuts import render_to_response
from common.djangoapps.student.models import CourseEnrollment
from openedx.core.djangoapps.site_configuration i... | 0.419291 | 0.076098 |
from rest_framework import serializers
from django.contrib.auth.models import User
from models import Video, Frame, Region, DVAPQL, QueryResult, TEvent, IndexEntries, Tube, Segment, TrainedModel, \
Retriever, SystemState, QueryRegion, Worker, TrainingSet, RegionRelation, TubeRegionRelation, TubeRelation, \
Expo... | server/dvaapp/serializers.py | from rest_framework import serializers
from django.contrib.auth.models import User
from models import Video, Frame, Region, DVAPQL, QueryResult, TEvent, IndexEntries, Tube, Segment, TrainedModel, \
Retriever, SystemState, QueryRegion, Worker, TrainingSet, RegionRelation, TubeRegionRelation, TubeRelation, \
Expo... | 0.712332 | 0.087798 |
"""Mssql."""
from __future__ import annotations
from abc import ABC
from contextlib import contextmanager
from json import dumps
from logging import getLogger
from typing import TYPE_CHECKING, Any, Dict, Generator
from .persistor import Persistor as BasePersistor
from .service import Service, Task
from .utils import... | src/dsdk/mssql.py | """Mssql."""
from __future__ import annotations
from abc import ABC
from contextlib import contextmanager
from json import dumps
from logging import getLogger
from typing import TYPE_CHECKING, Any, Dict, Generator
from .persistor import Persistor as BasePersistor
from .service import Service, Task
from .utils import... | 0.820649 | 0.186521 |
import torch
from torch.autograd import Function
from torch.autograd.function import once_differentiable
from torch.nn.modules.module import Module
from . import psroi_pool_cuda
class PSRoIPoolingFunction(Function):
@staticmethod
def forward(ctx, features, rois, pooled_height, pooled_width,
spat... | mmdet/ops/psroi_pool/psroi_pool.py | import torch
from torch.autograd import Function
from torch.autograd.function import once_differentiable
from torch.nn.modules.module import Module
from . import psroi_pool_cuda
class PSRoIPoolingFunction(Function):
@staticmethod
def forward(ctx, features, rois, pooled_height, pooled_width,
spat... | 0.930395 | 0.547646 |
from keras.optimizers import SGD
from keras.layers import Input, Dense, Conv2D, MaxPooling2D, AveragePooling2D
from keras.layers import ZeroPadding2D, Flatten, add, Activation
from keras.layers.normalization import BatchNormalization
from keras.models import Model, load_model
from keras import backend as K
import load_... | photo-based/resnet.py | from keras.optimizers import SGD
from keras.layers import Input, Dense, Conv2D, MaxPooling2D, AveragePooling2D
from keras.layers import ZeroPadding2D, Flatten, add, Activation
from keras.layers.normalization import BatchNormalization
from keras.models import Model, load_model
from keras import backend as K
import load_... | 0.916194 | 0.468426 |
from kernel.type import TyInst
from kernel import term
from kernel.term import Term, Var, Bound, Inst
from kernel.thm import Thm, InvalidDerivationException
from kernel import theory
from kernel.proofterm import ProofTerm, refl
from logic import matcher
from util import typecheck
class ConvException(Exception):
... | logic/conv.py |
from kernel.type import TyInst
from kernel import term
from kernel.term import Term, Var, Bound, Inst
from kernel.thm import Thm, InvalidDerivationException
from kernel import theory
from kernel.proofterm import ProofTerm, refl
from logic import matcher
from util import typecheck
class ConvException(Exception):
... | 0.846165 | 0.349783 |
import time
class StepTimer:
def __init__(self, total_steps=None):
self.Lauched = False
self.LastStep = None
self.BeginStep = None
self.TotalSteps = total_steps
self.CurrentStep = 0
self.TimeFormatter = TimeFormatter()
self.CachedData = {}
def begin(se... | utils/timer.py | import time
class StepTimer:
def __init__(self, total_steps=None):
self.Lauched = False
self.LastStep = None
self.BeginStep = None
self.TotalSteps = total_steps
self.CurrentStep = 0
self.TimeFormatter = TimeFormatter()
self.CachedData = {}
def begin(se... | 0.404037 | 0.256012 |
import numpy as np
import matplotlib.pyplot as plt
def plot_data(xs, ys, c, lw, label, linestyle, **kwargs):
if ys is not None:
plt.plot(xs, ys, c=c, lw=lw, linestyle=linestyle, label=label, **kwargs)
else:
plt.plot(xs, c=c, lw=lw, linestyle=linestyle, label=label, **kwargs)
def plot_measure... | filters/utils.py | import numpy as np
import matplotlib.pyplot as plt
def plot_data(xs, ys, c, lw, label, linestyle, **kwargs):
if ys is not None:
plt.plot(xs, ys, c=c, lw=lw, linestyle=linestyle, label=label, **kwargs)
else:
plt.plot(xs, c=c, lw=lw, linestyle=linestyle, label=label, **kwargs)
def plot_measure... | 0.761716 | 0.439326 |
import codecs
import copy
import pickle
import requests
from app import app, qiskit_importer
from qiskit.circuit import Qubit
from qiskit.converters import circuit_to_dag, dag_to_circuit
def replace_oracle_in_circuit(dag_circuit, dag_oracle, oracle_Id):
dag_circuit_back = copy.deepcopy(dag_circuit)
# inser... | 2020-ucc/services/oracle-service/app/oracle_replacer.py | import codecs
import copy
import pickle
import requests
from app import app, qiskit_importer
from qiskit.circuit import Qubit
from qiskit.converters import circuit_to_dag, dag_to_circuit
def replace_oracle_in_circuit(dag_circuit, dag_oracle, oracle_Id):
dag_circuit_back = copy.deepcopy(dag_circuit)
# inser... | 0.5769 | 0.459561 |
import time
import shutil
import logging
from pathlib import Path
from tempfile import TemporaryDirectory
try:
import gdal
except:
try:
from osgeo import gdal
except Exception as e:
raise e
import rasterio
import numpy as np
from ost.helpers import helpers as h, raster as ras, vector as ve... | ost/generic/ts_ls_mask.py | import time
import shutil
import logging
from pathlib import Path
from tempfile import TemporaryDirectory
try:
import gdal
except:
try:
from osgeo import gdal
except Exception as e:
raise e
import rasterio
import numpy as np
from ost.helpers import helpers as h, raster as ras, vector as ve... | 0.355775 | 0.125788 |