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 torch
import numpy as np
import h5py
from .logging import logger
from .rotations import quat_to_rotMat, rotMat_to_quat
from .quaternion import quat_fix
def add_normalized_positions(filepaths, new_group_name):
"""Add position data normalized relative to the pelvis to h5 files.
Args:
filepaths ... | src/common/preprocessing.py |
import torch
import numpy as np
import h5py
from .logging import logger
from .rotations import quat_to_rotMat, rotMat_to_quat
from .quaternion import quat_fix
def add_normalized_positions(filepaths, new_group_name):
"""Add position data normalized relative to the pelvis to h5 files.
Args:
filepaths ... | 0.642993 | 0.585694 |
from typing import Optional, List
from pydantic import PrivateAttr
from pydantic.main import BaseModel
from inoft_vocal_framework.skill_settings.skill_settings import INFRASTRUCTURE_TO_BASE_URL
from inoft_vocal_framework.platforms_handlers.alexa.audioplayer.audioplayer_directives import AudioPlayerWrapper
from inoft_... | platforms_handlers/alexa/handler_input.py | from typing import Optional, List
from pydantic import PrivateAttr
from pydantic.main import BaseModel
from inoft_vocal_framework.skill_settings.skill_settings import INFRASTRUCTURE_TO_BASE_URL
from inoft_vocal_framework.platforms_handlers.alexa.audioplayer.audioplayer_directives import AudioPlayerWrapper
from inoft_... | 0.69451 | 0.13887 |
import socket
from .base import Test, passive
class Redis(Test):
def setUp(self):
super().setUp()
import zorro.redis
self.r = zorro.redis.Redis(db=13)
class SingleThread(Redis):
@passive
def test_execute(self):
self.assertEquals(self.r.execute('SET', 'test:key1', 'valu... | tests/test_redis.py | import socket
from .base import Test, passive
class Redis(Test):
def setUp(self):
super().setUp()
import zorro.redis
self.r = zorro.redis.Redis(db=13)
class SingleThread(Redis):
@passive
def test_execute(self):
self.assertEquals(self.r.execute('SET', 'test:key1', 'valu... | 0.423816 | 0.326137 |
# -*- coding: utf-8 -*-
from CmdBase import CmdBase
from Msg_Src import Msg_Src
from Msg_Dest import Msg_Dest
from ErrorCommandFormat import ErrorCommandFormat
class CmdSend(CmdBase):
"""
send command.
Command Format :
send <v1>
send <v1><[-|,]><v2>
"""
_... | CmdSend.py | # -*- coding: utf-8 -*-
from CmdBase import CmdBase
from Msg_Src import Msg_Src
from Msg_Dest import Msg_Dest
from ErrorCommandFormat import ErrorCommandFormat
class CmdSend(CmdBase):
"""
send command.
Command Format :
send <v1>
send <v1><[-|,]><v2>
"""
_... | 0.067824 | 0.051035 |
# 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 ... | nemo_nowcast/config.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 ... | 0.841435 | 0.196229 |
from __future__ import absolute_import, unicode_literals, division
from puls.models import Supplier, SupplierForm
from puls.compat import unquote_plus
from puls import app, paginate
import flask
@app.route("/admin/suppliers/", methods=["GET", "POST"],
endpoint="manage_suppliers")
@app.route("/admin/suppli... | puls/views/admin/suppliers.py | from __future__ import absolute_import, unicode_literals, division
from puls.models import Supplier, SupplierForm
from puls.compat import unquote_plus
from puls import app, paginate
import flask
@app.route("/admin/suppliers/", methods=["GET", "POST"],
endpoint="manage_suppliers")
@app.route("/admin/suppli... | 0.450118 | 0.163112 |
from field.fq import Fq
from field.fq2 import Fq2
from field.fq6 import Fq6
from field.fq12 import Fq12
from bn128.g1 import G1
from bn128.g2 import G2
from bn128.ate import *
class BN128:
def __init__(self):
# Parameters for base field (Fq)
Fq.field_modulus = 2188824287183927522224640574525727508... | bn128/bn128.py | from field.fq import Fq
from field.fq2 import Fq2
from field.fq6 import Fq6
from field.fq12 import Fq12
from bn128.g1 import G1
from bn128.g2 import G2
from bn128.ate import *
class BN128:
def __init__(self):
# Parameters for base field (Fq)
Fq.field_modulus = 2188824287183927522224640574525727508... | 0.599837 | 0.176494 |
from .vertex import Vertex
from .object_manager import Manager
class Polygon:
def __init__(self):
self.id = -1
# store the actual vertices, vertices are ordered in sequence!
self.vertices = []
self.vertex_ids = set()
self.edge_ids = set()
self.obstacle_ids = set()
... | rmf_building_map_tools/building_crowdsim/navmesh/polygon.py | from .vertex import Vertex
from .object_manager import Manager
class Polygon:
def __init__(self):
self.id = -1
# store the actual vertices, vertices are ordered in sequence!
self.vertices = []
self.vertex_ids = set()
self.edge_ids = set()
self.obstacle_ids = set()
... | 0.752195 | 0.45181 |
import numpy as np
import torch
import torch.nn.functional as F
from copy import deepcopy
import model_zoo
from model_zoo.utils.training import save_best
from model_zoo import utils
class MaxLikelihoodClassifier(torch.nn.Module):
def __init__(self, input_dim, num_classes, model_class, model_kwargs):
sup... | model_zoo/classifier/mle_classifier.py | import numpy as np
import torch
import torch.nn.functional as F
from copy import deepcopy
import model_zoo
from model_zoo.utils.training import save_best
from model_zoo import utils
class MaxLikelihoodClassifier(torch.nn.Module):
def __init__(self, input_dim, num_classes, model_class, model_kwargs):
sup... | 0.945562 | 0.435361 |
import os
import pytest
import json
from typing import (
Sequence,
)
from staking_deposit.utils.constants import (
MNEMONIC_LANG_OPTIONS,
)
from staking_deposit.key_handling.key_derivation.mnemonic import (
_index_to_word,
_get_word_list,
abbreviate_words,
get_seed,
get_mnemonic,
recons... | tests/test_key_handling/test_key_derivation/test_mnemonic.py | import os
import pytest
import json
from typing import (
Sequence,
)
from staking_deposit.utils.constants import (
MNEMONIC_LANG_OPTIONS,
)
from staking_deposit.key_handling.key_derivation.mnemonic import (
_index_to_word,
_get_word_list,
abbreviate_words,
get_seed,
get_mnemonic,
recons... | 0.637934 | 0.423518 |
from mxnet import ndarray as nd
from mxnet import autograd
from mxnet import gluon
import matplotlib as mpl
mpl.rcParams['figure.dpi'] = 120
import matplotlib.pyplot as plt
num_train = 1000
num_test = 100
true_w = [1.2, -3.4, 5.6]
true_b = 5.0
x = nd.random.normal(shape=(num_train + num_test, 1))
X = nd.concat(x, nd... | MXnet/supervised-learning/over_fit_under_fit.py | from mxnet import ndarray as nd
from mxnet import autograd
from mxnet import gluon
import matplotlib as mpl
mpl.rcParams['figure.dpi'] = 120
import matplotlib.pyplot as plt
num_train = 1000
num_test = 100
true_w = [1.2, -3.4, 5.6]
true_b = 5.0
x = nd.random.normal(shape=(num_train + num_test, 1))
X = nd.concat(x, nd... | 0.663233 | 0.614192 |
import os
import sys
import string
import re
import optparse
import CGAT.Experiment as E
def main(argv=None):
"""script main.
parses command line options in sys.argv, unless *argv* is given.
"""
if argv is None:
argv = sys.argv
parser = E.OptionParser(
version="%prog version: $I... | scripts/cgat_log2wiki.py | import os
import sys
import string
import re
import optparse
import CGAT.Experiment as E
def main(argv=None):
"""script main.
parses command line options in sys.argv, unless *argv* is given.
"""
if argv is None:
argv = sys.argv
parser = E.OptionParser(
version="%prog version: $I... | 0.065852 | 0.100437 |
from __future__ import absolute_import, unicode_literals
from adminsortable2.admin import CustomInlineFormSet as SortableInlineFormSet
from django import forms
from django.forms.models import BaseInlineFormSet
from django.utils.module_loading import import_string
from parler.forms import TranslatableModelForm
from sh... | shopit/forms/product.py | from __future__ import absolute_import, unicode_literals
from adminsortable2.admin import CustomInlineFormSet as SortableInlineFormSet
from django import forms
from django.forms.models import BaseInlineFormSet
from django.utils.module_loading import import_string
from parler.forms import TranslatableModelForm
from sh... | 0.516108 | 0.172694 |
class LinkedList_Example:
## initialization
def init(this):
LinkedList = MeowMeow()
assert LinkedList.getFront() == None
assert LinkedList.getBack() == None
## Adding to empty LinkedList
def AddToEmptyList(this, obj):
#1
LinkedList = MeowMeow()
item = 12
LinkedList.appendBack(item)
assert LinkedLis... | resource-1/examples/LinkedList_Example.py | class LinkedList_Example:
## initialization
def init(this):
LinkedList = MeowMeow()
assert LinkedList.getFront() == None
assert LinkedList.getBack() == None
## Adding to empty LinkedList
def AddToEmptyList(this, obj):
#1
LinkedList = MeowMeow()
item = 12
LinkedList.appendBack(item)
assert LinkedLis... | 0.66888 | 0.442576 |
from pybreaker.manager import CircuitBreakerManager, CircuitBreakerError
from time import sleep
from threading import Thread
import os
import logging
from argparse import ArgumentParser
import sys
from ConfigParser import SafeConfigParser
log = logging.getLogger(__file__)
class InvalidIdentifier(Exception):
def _... | src/pybreaker/manager/pipe.py | from pybreaker.manager import CircuitBreakerManager, CircuitBreakerError
from time import sleep
from threading import Thread
import os
import logging
from argparse import ArgumentParser
import sys
from ConfigParser import SafeConfigParser
log = logging.getLogger(__file__)
class InvalidIdentifier(Exception):
def _... | 0.64232 | 0.191668 |
import ray
import numpy as np
import tensorflow as tf
def get_batch(data, batch_index, batch_size):
# This method currently drops data when num_data is not divisible by
# batch_size.
num_data = data.shape[0]
num_batches = num_data / batch_size
batch_index %= num_batches
return data[(batch_index * batch_siz... | examples/hyperopt/hyperopt.py | import ray
import numpy as np
import tensorflow as tf
def get_batch(data, batch_index, batch_size):
# This method currently drops data when num_data is not divisible by
# batch_size.
num_data = data.shape[0]
num_batches = num_data / batch_size
batch_index %= num_batches
return data[(batch_index * batch_siz... | 0.854004 | 0.490297 |
from ._ffi import *
from ctypes import *
from wasmtime import Store, Extern, Func, Global, Table, Memory, Instance
from wasmtime import Module, Trap, WasiInstance
dll.wasmtime_linker_new.restype = P_wasmtime_linker_t
dll.wasmtime_linker_define.restype = c_bool
dll.wasmtime_linker_define_instance.restype = c_bool
dll.w... | wasmtime/_linker.py | from ._ffi import *
from ctypes import *
from wasmtime import Store, Extern, Func, Global, Table, Memory, Instance
from wasmtime import Module, Trap, WasiInstance
dll.wasmtime_linker_new.restype = P_wasmtime_linker_t
dll.wasmtime_linker_define.restype = c_bool
dll.wasmtime_linker_define_instance.restype = c_bool
dll.w... | 0.538012 | 0.079961 |
import json
import unittest
from tests.base_test import BaseTest
from tests.model_test_data import (
TEST_MEMBER_1,
TEST_ROLE_1,
TEST_ROLE_2,
TEST_ROLE_400,
)
# noinspection PyArgumentList
class TestRoleResource(BaseTest):
"""Test all endpoints for the role resource"""
PASSWO... | tests/resources/test_role.py | import json
import unittest
from tests.base_test import BaseTest
from tests.model_test_data import (
TEST_MEMBER_1,
TEST_ROLE_1,
TEST_ROLE_2,
TEST_ROLE_400,
)
# noinspection PyArgumentList
class TestRoleResource(BaseTest):
"""Test all endpoints for the role resource"""
PASSWO... | 0.307566 | 0.13589 |
import sympy
import catamount
from catamount.graph import Graph
from catamount.tensors.tensor_shape import Dimension
from catamount.tests.utils.helpers import *
# [_] TODO (Joel): Move these to the Catamount API
def linear(name, weights_shape, out_shape, input):
output_weights = variable('{}_weights'.format(nam... | catamount/tests/api/lstm_cell.py | import sympy
import catamount
from catamount.graph import Graph
from catamount.tensors.tensor_shape import Dimension
from catamount.tests.utils.helpers import *
# [_] TODO (Joel): Move these to the Catamount API
def linear(name, weights_shape, out_shape, input):
output_weights = variable('{}_weights'.format(nam... | 0.371707 | 0.583085 |
import asyncio
import enum
import queue
import threading
from typing import AsyncIterator, Any
# Queue status
class Status(enum.Enum):
"""Status codes for `FinishableQueue`"""
INIT = 0
READY = 103
ERROR = 500
FINISHED = 200
class FinishableQueue():
"""Thread-safe class that takes a built-in `... | ibpy_native/utils/finishable_queue.py | import asyncio
import enum
import queue
import threading
from typing import AsyncIterator, Any
# Queue status
class Status(enum.Enum):
"""Status codes for `FinishableQueue`"""
INIT = 0
READY = 103
ERROR = 500
FINISHED = 200
class FinishableQueue():
"""Thread-safe class that takes a built-in `... | 0.848345 | 0.217379 |
from __future__ import print_function
import cv2
import glob
import os
import argparse
if __name__ == '__main__':
parser = argparse.ArgumentParser(description='This is the simple VSLAM pipeline')
parser.add_argument('-f', '--folder', help='folder where all the images are',
default=os.pa... | trim_whitespaces_in_folder.py | from __future__ import print_function
import cv2
import glob
import os
import argparse
if __name__ == '__main__':
parser = argparse.ArgumentParser(description='This is the simple VSLAM pipeline')
parser.add_argument('-f', '--folder', help='folder where all the images are',
default=os.pa... | 0.449393 | 0.265012 |
import scrapy
from futhead.items import FutheadItem
class FutheadSpider(scrapy.Spider):
name = "futhead"
allowed_domains = ["futhead.com"]
max_pages = 50
def start_requests(self):
for i in range(self.max_pages):
yield scrapy.Request('htt... | Scrapy/futhead/futhead/spiders/futhead_spider.py | import scrapy
from futhead.items import FutheadItem
class FutheadSpider(scrapy.Spider):
name = "futhead"
allowed_domains = ["futhead.com"]
max_pages = 50
def start_requests(self):
for i in range(self.max_pages):
yield scrapy.Request('htt... | 0.240507 | 0.062617 |
import os
import shutil
from tqdm import tqdm
from luigi.parameter import Parameter
from luigi import Task, ExternalTask, Event
import pandas as pd
import dask.dataframe as dd
from oandapyV20 import API
import oandapyV20.endpoints.transactions as transactions
from helperfiles.task import TargetOutput, Requirement, Requ... | tools/tradinghistory.py | import os
import shutil
from tqdm import tqdm
from luigi.parameter import Parameter
from luigi import Task, ExternalTask, Event
import pandas as pd
import dask.dataframe as dd
from oandapyV20 import API
import oandapyV20.endpoints.transactions as transactions
from helperfiles.task import TargetOutput, Requirement, Requ... | 0.595845 | 0.226923 |
import json
import zlib
import sys
import os
try:
from server_common.channel_access import ChannelAccess as ca
except ImportError:
sys.path.append(os.path.join(os.path.dirname(sys.path[0]))) # to allow server common from dir below
from server_common.channel_access import ChannelAccess as ca
def compress... | scripts/set_instrument_list.py |
import json
import zlib
import sys
import os
try:
from server_common.channel_access import ChannelAccess as ca
except ImportError:
sys.path.append(os.path.join(os.path.dirname(sys.path[0]))) # to allow server common from dir below
from server_common.channel_access import ChannelAccess as ca
def compress... | 0.437583 | 0.164449 |
from django.db import models
class Organisation(models.Model):
"""
Table: Organisation
Comment: The place to store all the Organization
"""
org_id = models.BigIntegerField(null=False, unique=True)
name = models.CharField(max_length=200, null=False, unique=True)
created_at = models.DateFiel... | zendesk/models.py | from django.db import models
class Organisation(models.Model):
"""
Table: Organisation
Comment: The place to store all the Organization
"""
org_id = models.BigIntegerField(null=False, unique=True)
name = models.CharField(max_length=200, null=False, unique=True)
created_at = models.DateFiel... | 0.727879 | 0.221793 |
from matplotlib import cm
import matplotlib.pyplot as plt
import numpy as np
import random
import itertools
import torch
from torchvision.utils import make_grid
from tensorboardX import SummaryWriter
from data.utils import get_coord
from tools.utils import create_colormap, color_transfer, color_spread
... | tools/logger.py | from matplotlib import cm
import matplotlib.pyplot as plt
import numpy as np
import random
import itertools
import torch
from torchvision.utils import make_grid
from tensorboardX import SummaryWriter
from data.utils import get_coord
from tools.utils import create_colormap, color_transfer, color_spread
... | 0.755817 | 0.288438 |
from math import *
class Success:
success = None
feilmelding = None
def createStringReference(string):
stringReference = StringReference()
stringReference.string = string
return stringReference
def lagGyldigReversTabell(nummerliste):
maxnummer = 0.0
i = 0.0
while i < len(nummerliste):
maxnummer = ... | Python/kommunenummer.py | from math import *
class Success:
success = None
feilmelding = None
def createStringReference(string):
stringReference = StringReference()
stringReference.string = string
return stringReference
def lagGyldigReversTabell(nummerliste):
maxnummer = 0.0
i = 0.0
while i < len(nummerliste):
maxnummer = ... | 0.323166 | 0.138229 |
import base64
from collections import namedtuple
from http.client import HTTPResponse
import random
from datetime import datetime
from django.conf import settings
from django.contrib.auth.decorators import login_required
from django.urls import reverse
from django.db.models import Count, Q
from django.http import HttpR... | guests/views.py | import base64
from collections import namedtuple
from http.client import HTTPResponse
import random
from datetime import datetime
from django.conf import settings
from django.contrib.auth.decorators import login_required
from django.urls import reverse
from django.db.models import Count, Q
from django.http import HttpR... | 0.264074 | 0.067362 |
import discord
import asyncio
import aiohttp
import traceback
import datetime
import random
import asyncpg
import json
import datetime
import inspect
import re
import json
from io import BytesIO
import util
from emoji import clean_emoji
from event import Event
from options import Options
from configs import Configs
fro... | watch.py | help - This message
invite - Display bot invite
setup - Setup the bot for the server (Mod only)
settings - View your server settings (Mod only)
reason - Set the reason for a case (Mod only)
(Run "help reason" for further information)
recall - Recall a previously posted case
reset - Reset all settings/cases (O... | 0.404743 | 0.111024 |
import argparse
import sqlite3
import sys
import time
import ttystatus
from common import *
# If similar placements are closer in time than this number of seconds, consider
# them to be duplicates. /r/place always gave at least a 5 minute cooldown,
# so we'll use that as our window.
DUPLICATE_WINDOW = 300
parser ... | merge.py |
import argparse
import sqlite3
import sys
import time
import ttystatus
from common import *
# If similar placements are closer in time than this number of seconds, consider
# them to be duplicates. /r/place always gave at least a 5 minute cooldown,
# so we'll use that as our window.
DUPLICATE_WINDOW = 300
parser ... | 0.345436 | 0.282141 |
import numpy as np
from keras.engine.sequential import Sequential
from keras.layers.core import Dense, Dropout
from keras.layers.embeddings import Embedding
from keras.layers.recurrent import LSTM
from keras.preprocessing.text import Tokenizer
from keras.utils.np_utils import to_categorical
from pymystem3 import Mystem... | lstm/main.py | import numpy as np
from keras.engine.sequential import Sequential
from keras.layers.core import Dense, Dropout
from keras.layers.embeddings import Embedding
from keras.layers.recurrent import LSTM
from keras.preprocessing.text import Tokenizer
from keras.utils.np_utils import to_categorical
from pymystem3 import Mystem... | 0.82559 | 0.162314 |
import re
import argparse
from pathlib import Path
number_mappings = {
"0" : "null",
"1" : "ein",
"2" : "zwei",
"3" : "drei",
"4" : "vier",
"5" : "fünf",
"6" : "sechs",
"7" : "sieben",
"8" : "acht",
"9" : "neun",
"10" : "zehn",
"11" : "elf",
"12" : "zwölf",
"13" ... | huiAudioCorpus/calculator/TextNormalizer.py | import re
import argparse
from pathlib import Path
number_mappings = {
"0" : "null",
"1" : "ein",
"2" : "zwei",
"3" : "drei",
"4" : "vier",
"5" : "fünf",
"6" : "sechs",
"7" : "sieben",
"8" : "acht",
"9" : "neun",
"10" : "zehn",
"11" : "elf",
"12" : "zwölf",
"13" ... | 0.193223 | 0.420778 |
import os
import re
import sys
from os.path import expanduser
import ipfshttpclient
from broker import cfg
from broker._utils._log import log
from broker._utils.tools import get_ip, is_byte_str_zero, print_tb
from broker._utils.web3_tools import get_tx_status
from broker._utils.yaml import Yaml
from broker.config im... | broker/eblocbroker_scripts/register_provider.py |
import os
import re
import sys
from os.path import expanduser
import ipfshttpclient
from broker import cfg
from broker._utils._log import log
from broker._utils.tools import get_ip, is_byte_str_zero, print_tb
from broker._utils.web3_tools import get_tx_status
from broker._utils.yaml import Yaml
from broker.config im... | 0.333286 | 0.104935 |
__author__ = 'Charlie'
import numpy as np
import os, sys, inspect
import tensorflow as tf
utils_path = os.path.realpath(
os.path.abspath(os.path.join(os.path.split(inspect.getfile(inspect.currentframe()))[0], "..")))
if utils_path not in sys.path:
sys.path.insert(0, utils_path)
import TensorflowUtils as utils
... | notMNIST/notMNISTFullyConvultional.py | __author__ = 'Charlie'
import numpy as np
import os, sys, inspect
import tensorflow as tf
utils_path = os.path.realpath(
os.path.abspath(os.path.join(os.path.split(inspect.getfile(inspect.currentframe()))[0], "..")))
if utils_path not in sys.path:
sys.path.insert(0, utils_path)
import TensorflowUtils as utils
... | 0.538498 | 0.401101 |
import os
from pathlib import Path
import pytest
from nozomi import api
from nozomi.data import Post
@pytest.mark.integration
@pytest.mark.parametrize('url', [
'https://nozomi.la/post/26905532.html#veigar',
"https://nozomi.la/post/26932594.html#cho'gath",
'https://nozomi.la/post/25802243.html#nautilus'... | tests/integration/test_api.py |
import os
from pathlib import Path
import pytest
from nozomi import api
from nozomi.data import Post
@pytest.mark.integration
@pytest.mark.parametrize('url', [
'https://nozomi.la/post/26905532.html#veigar',
"https://nozomi.la/post/26932594.html#cho'gath",
'https://nozomi.la/post/25802243.html#nautilus'... | 0.407098 | 0.415847 |
from unittest import mock
import pytest
from werkzeug.exceptions import HTTPException
from secure_scaffold.contrib.appengine import users
@pytest.fixture
def request():
with mock.patch("flask.request") as mock_request:
mock_request.headers = {
users.USER_EMAIL_HEADER: "<EMAIL>",
... | secure_scaffold/contrib/appengine/tests/test_users.py | from unittest import mock
import pytest
from werkzeug.exceptions import HTTPException
from secure_scaffold.contrib.appengine import users
@pytest.fixture
def request():
with mock.patch("flask.request") as mock_request:
mock_request.headers = {
users.USER_EMAIL_HEADER: "<EMAIL>",
... | 0.557845 | 0.436682 |
from .base_node import BaseNode
from .data_holder_node import DataHolderNode
from ..utils import view_full
from ..utils import view_summary
import warnings
import copy
class DataNode(BaseNode):
def __init__(self, graph_uid, graph_alias, node_uid, value="__specialPFV__NoneData", persist=False, verbose=False,... | src/pyflow/node/data_node.py | from .base_node import BaseNode
from .data_holder_node import DataHolderNode
from ..utils import view_full
from ..utils import view_summary
import warnings
import copy
class DataNode(BaseNode):
def __init__(self, graph_uid, graph_alias, node_uid, value="__specialPFV__NoneData", persist=False, verbose=False,... | 0.437583 | 0.18866 |
from django.conf import settings
from django.utils.translation import ugettext_lazy as _
from rest_framework import decorators, exceptions, response, status, serializers as rf_serializers
from waldur_core.core import validators as core_validators, exceptions as core_exceptions
from waldur_core.structure import (views ... | src/waldur_openstack/openstack/views.py | from django.conf import settings
from django.utils.translation import ugettext_lazy as _
from rest_framework import decorators, exceptions, response, status, serializers as rf_serializers
from waldur_core.core import validators as core_validators, exceptions as core_exceptions
from waldur_core.structure import (views ... | 0.749821 | 0.14777 |
import sys
__version__ = '0.99'
header = '''\
__ _ __ ___ _ _ __ __ ___ _ _ _ ______
|_)|_|(_ (_ |_|| ||_)| \(_ |_||_||_/|_ |_)
| | |__)__)||||_|| \|_/__)| || || \|__| \_v{}
'''.format(__version__)
charsets = {
'alphanum': '0..9A..Za..z',
'extended': '0..9A..Za..z!@#$%',
'ascii': '!..~',
}
def expand(s)... | passwordshaker.py |
import sys
__version__ = '0.99'
header = '''\
__ _ __ ___ _ _ __ __ ___ _ _ _ ______
|_)|_|(_ (_ |_|| ||_)| \(_ |_||_||_/|_ |_)
| | |__)__)||||_|| \|_/__)| || || \|__| \_v{}
'''.format(__version__)
charsets = {
'alphanum': '0..9A..Za..z',
'extended': '0..9A..Za..z!@#$%',
'ascii': '!..~',
}
def expand(s)... | 0.486575 | 0.245627 |
import sys
import os.path
import re
from collections import defaultdict
from typing import List, DefaultDict, Iterator
initial_state_re = re.compile(r"initial state: ([.#]+)")
rule_re = re.compile(r"([.#]+) => ([.#])")
State = DefaultDict[int, str]
"""Represent a configuration of plants by mapping index to "#" if the... | day12/part1.py | import sys
import os.path
import re
from collections import defaultdict
from typing import List, DefaultDict, Iterator
initial_state_re = re.compile(r"initial state: ([.#]+)")
rule_re = re.compile(r"([.#]+) => ([.#])")
State = DefaultDict[int, str]
"""Represent a configuration of plants by mapping index to "#" if the... | 0.511229 | 0.410874 |
import torch
import torch.nn as nn
import torch.optim as optim
import torch.nn.functional as F
import torch.backends.cudnn as cudnn
import torchvision
import torchvision.transforms as transforms
import os
import argparse
from models import *
from utils import progress_bar
import ipdb
import pickle
import numpy as n... | main_sup.py | import torch
import torch.nn as nn
import torch.optim as optim
import torch.nn.functional as F
import torch.backends.cudnn as cudnn
import torchvision
import torchvision.transforms as transforms
import os
import argparse
from models import *
from utils import progress_bar
import ipdb
import pickle
import numpy as n... | 0.388734 | 0.298389 |
import tempfile
import mmap
import re
from boot_linux_console import LinuxKernelTest
class PluginKernelBase(LinuxKernelTest):
"""
Boots a Linux kernel with a TCG plugin enabled.
"""
timeout = 120
KERNEL_COMMON_COMMAND_LINE = 'printk.time=1 panic=-1 '
def run_vm(self, kernel_path, kernel_co... | qemu/tests/acceptance/tcg_plugins.py |
import tempfile
import mmap
import re
from boot_linux_console import LinuxKernelTest
class PluginKernelBase(LinuxKernelTest):
"""
Boots a Linux kernel with a TCG plugin enabled.
"""
timeout = 120
KERNEL_COMMON_COMMAND_LINE = 'printk.time=1 panic=-1 '
def run_vm(self, kernel_path, kernel_co... | 0.207295 | 0.09426 |
from typing import Callable
MAX_STR_LENGTH = 255
class Validator:
@staticmethod
def validate(t, arg):
return not arg or isinstance(arg, t)
class IntValidator(Validator):
@staticmethod
def validate( arg: int):
"""
Validate if arg is instance of integer
:param arg:
... | papaya_server/validator.py | from typing import Callable
MAX_STR_LENGTH = 255
class Validator:
@staticmethod
def validate(t, arg):
return not arg or isinstance(arg, t)
class IntValidator(Validator):
@staticmethod
def validate( arg: int):
"""
Validate if arg is instance of integer
:param arg:
... | 0.807688 | 0.416797 |
import bl2sdk
import datetime
class DPS(bl2sdk.BL2MOD):
Name = "DPS/TTK Calculator"
Description = "Upon damaging an enemy a counter will start in the background. On kill it will then calculate the " \
"DPS in that amount of time, from dealing damage to the kill. The longer you need to kill an enemy " \
... | DPS and TTK/__init__.py | import bl2sdk
import datetime
class DPS(bl2sdk.BL2MOD):
Name = "DPS/TTK Calculator"
Description = "Upon damaging an enemy a counter will start in the background. On kill it will then calculate the " \
"DPS in that amount of time, from dealing damage to the kill. The longer you need to kill an enemy " \
... | 0.264358 | 0.239372 |
from io import BytesIO
import tarfile
from zipfile import ZipFile
from click import progressbar
from logbook import Logger
import pandas as pd
import requests
from six.moves.urllib.parse import urlencode
from six import iteritems
from trading_calendars import register_calendar_alias
from zipline.utils.deprecate impor... | alpha_factory/data/bundles/hdf_bundle.py | from io import BytesIO
import tarfile
from zipfile import ZipFile
from click import progressbar
from logbook import Logger
import pandas as pd
import requests
from six.moves.urllib.parse import urlencode
from six import iteritems
from trading_calendars import register_calendar_alias
from zipline.utils.deprecate impor... | 0.342572 | 0.234242 |
from __future__ import absolute_import
from __future__ import division
from __future__ import print_function
from queue import Queue
from .graph import TernaryTree as SuperTernaryTree
def _clone(x):
if isinstance(x, tuple):
return tuple(_.clone() for _ in x)
else:
return x.clone()
class Te... | graph_utils/TernaryTree.py | from __future__ import absolute_import
from __future__ import division
from __future__ import print_function
from queue import Queue
from .graph import TernaryTree as SuperTernaryTree
def _clone(x):
if isinstance(x, tuple):
return tuple(_.clone() for _ in x)
else:
return x.clone()
class Te... | 0.735167 | 0.128498 |
from reporter.connections import RedcapInstance
from reporter.application_abstract_reports.redcap.percentage_complete import (
RedcapPercentageCompleteReport,
)
from reporter.application_abstract_reports.redcap.withdrawn_or_excluded_with_data import (
RedcapWithdrawnOrExcludedWithDataReport,
)
from reporter.em... | reporter/uhl_reports/briccs/data_quality/redcap.py |
from reporter.connections import RedcapInstance
from reporter.application_abstract_reports.redcap.percentage_complete import (
RedcapPercentageCompleteReport,
)
from reporter.application_abstract_reports.redcap.withdrawn_or_excluded_with_data import (
RedcapWithdrawnOrExcludedWithDataReport,
)
from reporter.em... | 0.513668 | 0.069321 |
import os
import logging
import sqlalchemy
from findd.services import Findd
from findd.utils.path import parents
__LOG__ = logging.getLogger(__name__)
DEBUG_MORE = 5
class ContextException(Exception):
pass
class Context(object):
def __init__(self, base_dir, findd_dir, db_url):
assert base_dir i... | findd/cli/context.py | import os
import logging
import sqlalchemy
from findd.services import Findd
from findd.utils.path import parents
__LOG__ = logging.getLogger(__name__)
DEBUG_MORE = 5
class ContextException(Exception):
pass
class Context(object):
def __init__(self, base_dir, findd_dir, db_url):
assert base_dir i... | 0.373076 | 0.084493 |
FILE = 'dictionary.txt'
word_list = []
found_word_list = []
def main():
"""
Input: 4 rows of 4 letters
Output: all the words found within the given 4 x 4 letter matrix under the rule of the game 'Boggle'
"""
global word_list
global found_word_list
word_list = read_dictionary()
letter_list = []
for i in rang... | stanCode_projects/boggle_game_solver/boggle.py | FILE = 'dictionary.txt'
word_list = []
found_word_list = []
def main():
"""
Input: 4 rows of 4 letters
Output: all the words found within the given 4 x 4 letter matrix under the rule of the game 'Boggle'
"""
global word_list
global found_word_list
word_list = read_dictionary()
letter_list = []
for i in rang... | 0.332852 | 0.307488 |
# This notebook was prepared by [<NAME>](https://github.com/donnemartin). Source and license info is on [GitHub](https://github.com/donnemartin/interactive-coding-challenges).
# # Solution Notebook
# ## Problem: Implement Fizz Buzz.
#
# * [Constraints](#Constraints)
# * [Test Cases](#Test-Cases)
# * [Algorithm](#Al... | arrays_strings/fizz_buzz/fizz_buzz_solution.py |
# This notebook was prepared by [<NAME>](https://github.com/donnemartin). Source and license info is on [GitHub](https://github.com/donnemartin/interactive-coding-challenges).
# # Solution Notebook
# ## Problem: Implement Fizz Buzz.
#
# * [Constraints](#Constraints)
# * [Test Cases](#Test-Cases)
# * [Algorithm](#Al... | 0.780453 | 0.586049 |
import json
import logging
import time
from . import utils
from . import listener
logger = logging.getLogger(__name__)
class RequestListener(listener.CommandListener):
def __init__(self,core,config):
self.core = core
self.config = config
def command(self):
return 'request'
... | mopidy_slack/request.py | import json
import logging
import time
from . import utils
from . import listener
logger = logging.getLogger(__name__)
class RequestListener(listener.CommandListener):
def __init__(self,core,config):
self.core = core
self.config = config
def command(self):
return 'request'
... | 0.20001 | 0.075961 |
from pudzu.charts import *
import seaborn as sns
from pudzu.dates import *
import dateparser
CONFEDERATE = ["South Carolina", "Mississippi", "Florida", "Alabama", "Georgia", "Louisiana", "Texas"] + ["Arkansas", "North Carolina", "Tennessee", "Virginia"]
UNION = ["California", "Connecticut", "Illinois", "Indiana"... | dataviz/politics_usnorthsouth.py | from pudzu.charts import *
import seaborn as sns
from pudzu.dates import *
import dateparser
CONFEDERATE = ["South Carolina", "Mississippi", "Florida", "Alabama", "Georgia", "Louisiana", "Texas"] + ["Arkansas", "North Carolina", "Tennessee", "Virginia"]
UNION = ["California", "Connecticut", "Illinois", "Indiana"... | 0.341253 | 0.235185 |
ANSIBLE_METADATA = {
'metadata_version': '1.1',
'status': ['preview'],
'supported_by': 'community'
}
DOCUMENTATION = '''
---
module: arubaoss_aaa_authentication
short_description: implements rest api for AAA Authentication configuration
version_added: "2.4"
description:
- "This implements rest apis... | aruba_module_installer/library/modules/network/arubaoss/arubaoss_aaa_authentication.py |
ANSIBLE_METADATA = {
'metadata_version': '1.1',
'status': ['preview'],
'supported_by': 'community'
}
DOCUMENTATION = '''
---
module: arubaoss_aaa_authentication
short_description: implements rest api for AAA Authentication configuration
version_added: "2.4"
description:
- "This implements rest apis... | 0.641759 | 0.2918 |
import argparse
import hashlib
import logging
import os
import subprocess
import sys
import urllib.request
from functools import partial
from typing import Union
log_level = logging.INFO
log_format = "%(message)s"
logging.basicConfig(level=log_level, format=log_format)
logger = logging.getLogger(__name__)
tools_dir... | tools/update_schema.py |
import argparse
import hashlib
import logging
import os
import subprocess
import sys
import urllib.request
from functools import partial
from typing import Union
log_level = logging.INFO
log_format = "%(message)s"
logging.basicConfig(level=log_level, format=log_format)
logger = logging.getLogger(__name__)
tools_dir... | 0.427397 | 0.071494 |
from pyminion.expansions.base import smithy, throne_room, village
from pyminion.game import Game
from pyminion.players import Human
def test_throne_room_no_action(human: Human, game: Game):
human.hand.add(throne_room)
human.hand.cards[0].play(human, game)
assert len(human.hand) == 0
assert len(human.... | tests/test_cards/test_actions/test_throne_room.py | from pyminion.expansions.base import smithy, throne_room, village
from pyminion.game import Game
from pyminion.players import Human
def test_throne_room_no_action(human: Human, game: Game):
human.hand.add(throne_room)
human.hand.cards[0].play(human, game)
assert len(human.hand) == 0
assert len(human.... | 0.639961 | 0.804866 |
import matplotlib.pyplot as plt # Plotting library
from scipy.integrate import odeint # SciPy ODE integration
from scipy.interpolate import interp1d # SciPy 1D interpolant
from numpy import linspace, pi, sqrt, exp # numpy functions and constants
def sheathFunc(f, x, vs):
# f is an array of all evolving variables
... | CompuTech/mly509_a2.py | import matplotlib.pyplot as plt # Plotting library
from scipy.integrate import odeint # SciPy ODE integration
from scipy.interpolate import interp1d # SciPy 1D interpolant
from numpy import linspace, pi, sqrt, exp # numpy functions and constants
def sheathFunc(f, x, vs):
# f is an array of all evolving variables
... | 0.851675 | 0.843251 |
import pandas as pd
import numpy as np
import time
from datetime import datetime, timedelta
import math
import os
import matplotlib.pyplot as plt
from matplotlib.dates import bytespdate2num, num2date
from matplotlib.ticker import FuncFormatter
import multiprocessing
from multiprocessing import Pool, cpu_count
from func... | data-science-not/weeks/m09_multiproc/p02/task2_multiproc.py | import pandas as pd
import numpy as np
import time
from datetime import datetime, timedelta
import math
import os
import matplotlib.pyplot as plt
from matplotlib.dates import bytespdate2num, num2date
from matplotlib.ticker import FuncFormatter
import multiprocessing
from multiprocessing import Pool, cpu_count
from func... | 0.187914 | 0.12408 |
import tensorflow.compat.v1 as tf
tf.disable_v2_behavior()
from libs import model_common
def placeholder(Batch_Size, P, Q, N, F_in, F_out):
labels = tf.compat.v1.placeholder(shape = (Batch_Size, Q, N, F_out), dtype = tf.float32,name="lables")
samples = tf.compat.v1.placeholder(shape = (Batch_Size, P, N, F_in),... | models/MSGC_Seq2seq.py | import tensorflow.compat.v1 as tf
tf.disable_v2_behavior()
from libs import model_common
def placeholder(Batch_Size, P, Q, N, F_in, F_out):
labels = tf.compat.v1.placeholder(shape = (Batch_Size, Q, N, F_out), dtype = tf.float32,name="lables")
samples = tf.compat.v1.placeholder(shape = (Batch_Size, P, N, F_in),... | 0.606964 | 0.439026 |
from sebs.cache import Cache
from sebs.faas.config import Credentials, Resources, Config
from sebs.utils import LoggingHandlers
from sebs.storage.config import MinioConfig
from typing import cast, Optional
class OpenWhiskCredentials(Credentials):
@staticmethod
def deserialize(config: dict, cache: Cache, hand... | sebs/openwhisk/config.py | from sebs.cache import Cache
from sebs.faas.config import Credentials, Resources, Config
from sebs.utils import LoggingHandlers
from sebs.storage.config import MinioConfig
from typing import cast, Optional
class OpenWhiskCredentials(Credentials):
@staticmethod
def deserialize(config: dict, cache: Cache, hand... | 0.853272 | 0.141015 |
from tests.utils import assert_bindings
def test_ipo6_ipo_1(mode, save_output, output_format):
"""
International Purchase Order 6
"""
assert_bindings(
schema="boeingData/ipo6/ipo.xsd",
instance="boeingData/ipo6/ipo_1.xml",
class_name="PurchaseOrder",
version="1.1",
... | tests/test_boeing_meta_12.py | from tests.utils import assert_bindings
def test_ipo6_ipo_1(mode, save_output, output_format):
"""
International Purchase Order 6
"""
assert_bindings(
schema="boeingData/ipo6/ipo.xsd",
instance="boeingData/ipo6/ipo_1.xml",
class_name="PurchaseOrder",
version="1.1",
... | 0.669853 | 0.298932 |
from maskgen import tool_set
import unittest
import numpy as np
from maskgen import image_wrap
from test_support import TestSupport
import sys
class TestToolSet(TestSupport):
def test_diff(self):
args = {'smoothing': 3, 'mode':'bgr', 'aggregate':'max','filling':'morphology'}
a = np.random.randi... | tests/test_tool_set.py | from maskgen import tool_set
import unittest
import numpy as np
from maskgen import image_wrap
from test_support import TestSupport
import sys
class TestToolSet(TestSupport):
def test_diff(self):
args = {'smoothing': 3, 'mode':'bgr', 'aggregate':'max','filling':'morphology'}
a = np.random.randi... | 0.336985 | 0.390883 |
from pyecharts import Bar, Kline, Map, Pie, WordCloud
class ChartFactory:
def __init__(self):
self._func = {}
self._charts = {}
def collect(self, name):
def _inject(func):
self._func[name] = func
return func
return _inject
def create(self, name)... | example/demo/demo_data.py |
from pyecharts import Bar, Kline, Map, Pie, WordCloud
class ChartFactory:
def __init__(self):
self._func = {}
self._charts = {}
def collect(self, name):
def _inject(func):
self._func[name] = func
return func
return _inject
def create(self, name)... | 0.488771 | 0.389024 |
from django.views.generic import RedirectView, FormView
from django.contrib.auth import authenticate, login
from django.shortcuts import Http404, redirect
from django.core.urlresolvers import reverse
from django.core.exceptions import ImproperlyConfigured, PermissionDenied
from django.contrib.auth.models import User
f... | account/views.py | from django.views.generic import RedirectView, FormView
from django.contrib.auth import authenticate, login
from django.shortcuts import Http404, redirect
from django.core.urlresolvers import reverse
from django.core.exceptions import ImproperlyConfigured, PermissionDenied
from django.contrib.auth.models import User
f... | 0.307878 | 0.054199 |
import unittest
import numpy as np
from phdTester.functions import DataFrameFunctionsDict
class MyTestCase(unittest.TestCase):
def test_01(self):
df = DataFrameFunctionsDict()
df.update_function_point("f1", 4, 2)
df.update_function_point("f1", 3, 5)
self.assertEqual(list(df.get... | PhdTester/phdTester/tests/test_dataframe_function_dict.py | import unittest
import numpy as np
from phdTester.functions import DataFrameFunctionsDict
class MyTestCase(unittest.TestCase):
def test_01(self):
df = DataFrameFunctionsDict()
df.update_function_point("f1", 4, 2)
df.update_function_point("f1", 3, 5)
self.assertEqual(list(df.get... | 0.605566 | 0.601857 |
import datetime
import argparse
import logging
from os import listdir
from os.path import join
from sys import exit
import xml.etree.ElementTree as ET
import wptools
from model import Mention, Entry, LinkedMention
from ner import detect as apply_ner
# create logger
logger = logging.getLogger(__name__)
logger.setLevel(... | main.py | import datetime
import argparse
import logging
from os import listdir
from os.path import join
from sys import exit
import xml.etree.ElementTree as ET
import wptools
from model import Mention, Entry, LinkedMention
from ner import detect as apply_ner
# create logger
logger = logging.getLogger(__name__)
logger.setLevel(... | 0.266071 | 0.108756 |
import os
import rclpy
from rclpy.node import Node
from thymio2_interfaces.msg import Thymio2Controller
from thymio2_interfaces.srv import Thymio2ControllerSrv
from thymio2_interfaces.srv import Thymio2MotorSrv
import dbus
import dbus.mainloop.glib
from gi.repository import GObject as gobject
from gi.repository impor... | ros2_ws/src/thymio2_ros2_bridge_py_pkg/thymio2_ros2_bridge_py_pkg/thymio2_controler_node.py | import os
import rclpy
from rclpy.node import Node
from thymio2_interfaces.msg import Thymio2Controller
from thymio2_interfaces.srv import Thymio2ControllerSrv
from thymio2_interfaces.srv import Thymio2MotorSrv
import dbus
import dbus.mainloop.glib
from gi.repository import GObject as gobject
from gi.repository impor... | 0.305386 | 0.126434 |
import os
import re
import json
import time
import subprocess
import threading
from datetime import datetime
import psutil
import requests
TEST_SERVER_HOSTS = ['192.168.40.215', '192.168.40.91']
TEST_SERVER_PORT = 8999
TEST_REQ_TMPL = 'http://%(host)s:%(port)d/test'
APP_SERVER_IP = '192.168.3.235'
APP_SERVER_PATH_T... | gateway/gateway-perfmance-tests/TestAll.py |
import os
import re
import json
import time
import subprocess
import threading
from datetime import datetime
import psutil
import requests
TEST_SERVER_HOSTS = ['192.168.40.215', '192.168.40.91']
TEST_SERVER_PORT = 8999
TEST_REQ_TMPL = 'http://%(host)s:%(port)d/test'
APP_SERVER_IP = '192.168.3.235'
APP_SERVER_PATH_T... | 0.175009 | 0.123049 |
import warnings
import nibabel as nb
import numpy as np
from nilearn.image import resample_img
PATH_SCHAEFER = (
"data/parcellations/Schaefer2018_1000Parcels_7Networks_order_FSLMNI152_2mm.nii.gz"
)
PATH_TIAN = "data/parcellations/Tian_Subcortex_S4_3T_2009cAsym.nii.gz"
def combine_atlas(img1, img2):
"""Combi... | bin/nifti_atlas.py | import warnings
import nibabel as nb
import numpy as np
from nilearn.image import resample_img
PATH_SCHAEFER = (
"data/parcellations/Schaefer2018_1000Parcels_7Networks_order_FSLMNI152_2mm.nii.gz"
)
PATH_TIAN = "data/parcellations/Tian_Subcortex_S4_3T_2009cAsym.nii.gz"
def combine_atlas(img1, img2):
"""Combi... | 0.632843 | 0.32314 |
import six
if six.PY3:
import unittest
else:
import unittest2 as unittest
import collections
from depsolver.compat \
import \
OrderedDict, sorted_with_cmp
from depsolver.package \
import \
PackageInfo
from depsolver.pool \
import \
Pool
from depsolver.repository \
impo... | depsolver/solver/tests/test_policy.py | import six
if six.PY3:
import unittest
else:
import unittest2 as unittest
import collections
from depsolver.compat \
import \
OrderedDict, sorted_with_cmp
from depsolver.package \
import \
PackageInfo
from depsolver.pool \
import \
Pool
from depsolver.repository \
impo... | 0.672332 | 0.254214 |
import unicodedata
import argparse
import re
from typing import Any, Callable, List, Union, TypeVar
from re import Pattern
CATEGORIES = {
"Cc": "Other, control",
"Cf": "Other, format",
"Cn": "Other, not assigned",
"Co": "Other, private use",
"Cs": "Other, surrogate",
"Ll": "Letter, lowercase",
... | charinfo/core.py | import unicodedata
import argparse
import re
from typing import Any, Callable, List, Union, TypeVar
from re import Pattern
CATEGORIES = {
"Cc": "Other, control",
"Cf": "Other, format",
"Cn": "Other, not assigned",
"Co": "Other, private use",
"Cs": "Other, surrogate",
"Ll": "Letter, lowercase",
... | 0.67662 | 0.380644 |
import sys
import pandas as pd
import nltk
nltk.download(['punkt', 'wordnet'])
from sqlalchemy import create_engine
from nltk.tokenize import word_tokenize
from nltk.stem import WordNetLemmatizer
from sklearn.multioutput import MultiOutputClassifier
from sklearn.pipeline import Pipeline, FeatureUnion
from sklearn.featu... | models/train_classifier.py | import sys
import pandas as pd
import nltk
nltk.download(['punkt', 'wordnet'])
from sqlalchemy import create_engine
from nltk.tokenize import word_tokenize
from nltk.stem import WordNetLemmatizer
from sklearn.multioutput import MultiOutputClassifier
from sklearn.pipeline import Pipeline, FeatureUnion
from sklearn.featu... | 0.432303 | 0.354852 |
import shutil
import subprocess
from collections import namedtuple
from subprocess import CompletedProcess
from textwrap import dedent
import pytest
from Pegasus.client._client import Client, PegasusClientError, Result, from_env
def test_PegasusClientError():
return_value = namedtuple("return_value", ["stdout",... | packages/pegasus-common/test/client/test_client.py | import shutil
import subprocess
from collections import namedtuple
from subprocess import CompletedProcess
from textwrap import dedent
import pytest
from Pegasus.client._client import Client, PegasusClientError, Result, from_env
def test_PegasusClientError():
return_value = namedtuple("return_value", ["stdout",... | 0.42179 | 0.272965 |
import itertools
import numpy as np
import pandas as pd
import urllib.request
import matplotlib.pyplot as plt
def download_data(url, filename):
"""
Download the dataset from the url
:param url: url of file to be downloaded
:param filename: filname to be saved
:return:
"""
urllib.request.ur... | 2_Neural_Network/2_AutoEncoder/utils.py | import itertools
import numpy as np
import pandas as pd
import urllib.request
import matplotlib.pyplot as plt
def download_data(url, filename):
"""
Download the dataset from the url
:param url: url of file to be downloaded
:param filename: filname to be saved
:return:
"""
urllib.request.ur... | 0.719679 | 0.574693 |
from __future__ import print_function, division
import argparse
import torch
import torch.nn as nn
import torch.optim as optim
import math
import pickle
import matplotlib.pyplot as plt
from teacher_student import *
from teacher_dataset import *
def get_Q(path_to_mask_list, path_to_teacher, input_dim):
unpruned_MLP... | evaluate.py | from __future__ import print_function, division
import argparse
import torch
import torch.nn as nn
import torch.optim as optim
import math
import pickle
import matplotlib.pyplot as plt
from teacher_student import *
from teacher_dataset import *
def get_Q(path_to_mask_list, path_to_teacher, input_dim):
unpruned_MLP... | 0.459561 | 0.45175 |
import json
import os
import re
import time
from aqt import mw
from aqt.utils import showInfo, chooseList
from aqt.qt import *
from anki.storage import Collection
def add_pitch_dialog():
# environment
collection_path = mw.col.path
plugin_dir_name = __name__
user_dir_path = os.path.split(collection_pat... | __init__.py | import json
import os
import re
import time
from aqt import mw
from aqt.utils import showInfo, chooseList
from aqt.qt import *
from anki.storage import Collection
def add_pitch_dialog():
# environment
collection_path = mw.col.path
plugin_dir_name = __name__
user_dir_path = os.path.split(collection_pat... | 0.343342 | 0.093512 |
import logging
import math
import os
import json
from urllib.parse import urlparse
from flask import g as flask_g, abort
from flask import (request, current_app, Response,
stream_with_context)
from flask_babel import gettext
from flask_restful import Resource
from py4j.protocol import Py4JJavaError
from sqlalchemy... | limonero/model_api.py | import logging
import math
import os
import json
from urllib.parse import urlparse
from flask import g as flask_g, abort
from flask import (request, current_app, Response,
stream_with_context)
from flask_babel import gettext
from flask_restful import Resource
from py4j.protocol import Py4JJavaError
from sqlalchemy... | 0.373533 | 0.086864 |
import argparse
import hashlib
import os
import sys
from functools import partial
from pathlib import Path
from .utils import ApplicationError
def dhash(string):
m = hashlib.sha1()
m.update(string.encode())
return int(m.hexdigest(), base=16)
def autoport(path):
lower = 2000
upper = 65535 + 1
... | src/refresher/cli.py | import argparse
import hashlib
import os
import sys
from functools import partial
from pathlib import Path
from .utils import ApplicationError
def dhash(string):
m = hashlib.sha1()
m.update(string.encode())
return int(m.hexdigest(), base=16)
def autoport(path):
lower = 2000
upper = 65535 + 1
... | 0.380644 | 0.101233 |
from . import domainresource
class TestScript(domainresource.DomainResource):
""" Describes a set of tests.
A structured set of tests against a FHIR server or client implementation to
determine compliance against the FHIR specification.
"""
resource_type = "TestScript"
def __in... | fhirclient/r4models/testscript.py |
from . import domainresource
class TestScript(domainresource.DomainResource):
""" Describes a set of tests.
A structured set of tests against a FHIR server or client implementation to
determine compliance against the FHIR specification.
"""
resource_type = "TestScript"
def __in... | 0.845863 | 0.462412 |
from __future__ import annotations
import unittest
from causets.embeddedcauset import EmbeddedCauset
from causets.sprinkledcauset import SprinkledCauset
from causets.spacetimes import BlackHoleSpacetime
from causets.shapes import CoordinateShape
from matplotlib import pyplot as plt
import causets.causetplotting ... | test_causetplotting.py | from __future__ import annotations
import unittest
from causets.embeddedcauset import EmbeddedCauset
from causets.sprinkledcauset import SprinkledCauset
from causets.spacetimes import BlackHoleSpacetime
from causets.shapes import CoordinateShape
from matplotlib import pyplot as plt
import causets.causetplotting ... | 0.575349 | 0.378172 |
import os
import tempfile
from pathlib import Path
from xeda import Design
from xeda.flow_runner import DefaultRunner
from xeda.flows import VivadoSynth
from xeda.flows.flow import FPGA
TESTS_DIR = Path(__file__).parent.absolute()
RESOURCES_DIR = TESTS_DIR / "resources"
EXAMPLES_DIR = TESTS_DIR.parent / "examples"
... | tests/test_vivado.py | import os
import tempfile
from pathlib import Path
from xeda import Design
from xeda.flow_runner import DefaultRunner
from xeda.flows import VivadoSynth
from xeda.flows.flow import FPGA
TESTS_DIR = Path(__file__).parent.absolute()
RESOURCES_DIR = TESTS_DIR / "resources"
EXAMPLES_DIR = TESTS_DIR.parent / "examples"
... | 0.422386 | 0.269341 |
import app.main.config as config
import Adyen
from random import randint
from flask import json
'''
Send Payment Request to Adyen
'''
def adyen_payments(frontend_request):
adyen = Adyen.Adyen()
adyen.client.platform = 'test'
adyen.client.xapikey = config.checkout_apikey
payment_info = frontend_request.get_json(... | app/main/payments.py | import app.main.config as config
import Adyen
from random import randint
from flask import json
'''
Send Payment Request to Adyen
'''
def adyen_payments(frontend_request):
adyen = Adyen.Adyen()
adyen.client.platform = 'test'
adyen.client.xapikey = config.checkout_apikey
payment_info = frontend_request.get_json(... | 0.273866 | 0.119717 |
import os
import sys
import time
import datetime
from tkinter import Tk
from tkinter.filedialog import askdirectory
from PIL import Image
from pathlib import Path
def resource_path(relative_path):
try:
base_path = sys._MEIPASS
except Exception:
base_path = os.path.abspath(".")
return os.pa... | main.py | import os
import sys
import time
import datetime
from tkinter import Tk
from tkinter.filedialog import askdirectory
from PIL import Image
from pathlib import Path
def resource_path(relative_path):
try:
base_path = sys._MEIPASS
except Exception:
base_path = os.path.abspath(".")
return os.pa... | 0.115063 | 0.158826 |
from win32com.client import gencache, constants
DEBUG = False
class MSOutlook(object):
def __init__(self):
try:
self.oOutlookApp = gencache.EnsureDispatch("Outlook.Application")
self.outlookFound = True
except:
print "MSOutlook: unable to load Outlook"
... | lang/py/cookbook/v2/source/cb2_10_16_sol_1.py | from win32com.client import gencache, constants
DEBUG = False
class MSOutlook(object):
def __init__(self):
try:
self.oOutlookApp = gencache.EnsureDispatch("Outlook.Application")
self.outlookFound = True
except:
print "MSOutlook: unable to load Outlook"
... | 0.222278 | 0.050401 |
import scrapy
from scrapy.item import Field
class BooksItem(scrapy.Item):
"""A scrapy item with 4 fields for books.toscrape.com - Title, Price, Image URL and Details URL"""
title = Field()
price = Field()
image_url = Field()
details_url = Field()
class BooksSpider(scrapy.Spider):
... | books.py | import scrapy
from scrapy.item import Field
class BooksItem(scrapy.Item):
"""A scrapy item with 4 fields for books.toscrape.com - Title, Price, Image URL and Details URL"""
title = Field()
price = Field()
image_url = Field()
details_url = Field()
class BooksSpider(scrapy.Spider):
... | 0.523908 | 0.262245 |
from PIL import Image, ImageDraw, ImageColor
import random
import colorsys
from . import color
class Generator:
'''
Generator for a random background image.
Args:
width: The image width.
height: The image height.
columns: The number of shapes to fit along the x-axis.
rows... | rngback/generator.py | from PIL import Image, ImageDraw, ImageColor
import random
import colorsys
from . import color
class Generator:
'''
Generator for a random background image.
Args:
width: The image width.
height: The image height.
columns: The number of shapes to fit along the x-axis.
rows... | 0.9292 | 0.656961 |
import re
from collections import defaultdict
from math import ceil
path = []
max_workers = 5
min_cost = 60
diff = ord('A')-1
infinite = 99999
def parseLine(line):
# Pulls the two single capital letters into a tuple
return re.search("\s([A-Z])\s.*\s([A-Z])\s", line).groups()
def requirementsM... | day7/sol.py |
import re
from collections import defaultdict
from math import ceil
path = []
max_workers = 5
min_cost = 60
diff = ord('A')-1
infinite = 99999
def parseLine(line):
# Pulls the two single capital letters into a tuple
return re.search("\s([A-Z])\s.*\s([A-Z])\s", line).groups()
def requirementsM... | 0.317638 | 0.241579 |
import json
import vogen
from typing import List
import argparse
Parser=argparse.ArgumentParser
def main():
#显示默认帮助
def pyvogen_default(args):
print("PyVogen命令行工具\n\npm 包管理器\nversion 显示版本信息\n\n可在此找到更多帮助:https://gitee.com/oxygendioxide/vogen")
parser = Parser(prog='pyvogen')
#print(parser)
parser.s... | vogen/__main__.py |
import json
import vogen
from typing import List
import argparse
Parser=argparse.ArgumentParser
def main():
#显示默认帮助
def pyvogen_default(args):
print("PyVogen命令行工具\n\npm 包管理器\nversion 显示版本信息\n\n可在此找到更多帮助:https://gitee.com/oxygendioxide/vogen")
parser = Parser(prog='pyvogen')
#print(parser)
parser.s... | 0.07832 | 0.050518 |
from oslo_utils import importutils
import testtools
from oslo_messaging.tests import utils as test_utils
# NOTE(jamespage) matchmaker tied directly to eventlet
# which is not yet py3 compatible - skip if import fails
matchmaker_ring = (
importutils.try_import('oslo_messaging._drivers.matchmaker_ring'))
@testto... | tools/dockerize/webportal/usr/lib/python2.7/site-packages/oslo_messaging/tests/drivers/test_matchmaker_ring.py |
from oslo_utils import importutils
import testtools
from oslo_messaging.tests import utils as test_utils
# NOTE(jamespage) matchmaker tied directly to eventlet
# which is not yet py3 compatible - skip if import fails
matchmaker_ring = (
importutils.try_import('oslo_messaging._drivers.matchmaker_ring'))
@testto... | 0.451327 | 0.300598 |
import matplotlib.pyplot as plt
import numpy as np
import os
import torch
from data_process import label_to_init_vector
from plotting import image_fancy
from settings import BETA, GAUSSIAN_STDEV, DIR_OUTPUT
import matplotlib as mpl
mpl.rcParams["mathtext.default"]
mpl.rcParams["text.usetex"] = False
mpl.rcParams["te... | RBM/custom_rbm.py | import matplotlib.pyplot as plt
import numpy as np
import os
import torch
from data_process import label_to_init_vector
from plotting import image_fancy
from settings import BETA, GAUSSIAN_STDEV, DIR_OUTPUT
import matplotlib as mpl
mpl.rcParams["mathtext.default"]
mpl.rcParams["text.usetex"] = False
mpl.rcParams["te... | 0.67854 | 0.409516 |
import datetime
import hashlib
from termcolor import colored
#Create a 'Block' class
class Block :
#Initialize values relating to the blockchain
index = 0
data = None
hash = None
timestamp = datetime.datetime.now()
previousHash = 0x0
next = None
#Number only sored once, or as I like to call it, 'incre... | main.py | import datetime
import hashlib
from termcolor import colored
#Create a 'Block' class
class Block :
#Initialize values relating to the blockchain
index = 0
data = None
hash = None
timestamp = datetime.datetime.now()
previousHash = 0x0
next = None
#Number only sored once, or as I like to call it, 'incre... | 0.561215 | 0.379666 |
import math
import torch
import torch.nn as nn
import torch.nn.functional as F
import numpy as np
def focal_loss(input_values, gamma):
"""Computes the focal loss"""
p = torch.exp(-input_values)
loss = (1 - p) ** gamma * input_values
return loss.mean()
class FocalLoss(nn.Module):
def __init__(self,... | ldam.py | import math
import torch
import torch.nn as nn
import torch.nn.functional as F
import numpy as np
def focal_loss(input_values, gamma):
"""Computes the focal loss"""
p = torch.exp(-input_values)
loss = (1 - p) ** gamma * input_values
return loss.mean()
class FocalLoss(nn.Module):
def __init__(self,... | 0.946855 | 0.67688 |
from construct.core import *
from construct.lib import *
""" TLS 1.3 related strcutres """
## RFC8446 section 4.2
ExtensionType = Enum( BytesInteger(2),
server_name = 0,
max_fragment_length = 1,
status_request = 5,
supported_group... | pylurk/extensions/tls13_tls13_struct.py | from construct.core import *
from construct.lib import *
""" TLS 1.3 related strcutres """
## RFC8446 section 4.2
ExtensionType = Enum( BytesInteger(2),
server_name = 0,
max_fragment_length = 1,
status_request = 5,
supported_group... | 0.591251 | 0.179064 |
from pygame import *
from random import randint
mixer.init()
music=mixer.Sound('space.ogg')
music.play()
font.init()
font2 = font.SysFont('Arial',36)
font1= font.SysFont('Arial',80)
lose=font1.render("You Lose",True,(255,69,0))
win1=font1.render("You win!",True,(0,200,0))
score = 0
lost= 0
max_lost=3
goal=10
max_... | shooter_game.py | from pygame import *
from random import randint
mixer.init()
music=mixer.Sound('space.ogg')
music.play()
font.init()
font2 = font.SysFont('Arial',36)
font1= font.SysFont('Arial',80)
lose=font1.render("You Lose",True,(255,69,0))
win1=font1.render("You win!",True,(0,200,0))
score = 0
lost= 0
max_lost=3
goal=10
max_... | 0.119113 | 0.165998 |
from user import User
from credential import Info
def create_account(F_name,L_name,S_name,E_mail):
new_user = User(F_name,L_name,S_name,E_mail)
return new_user
def create_credential(instagram,E_mail):
new_cred = Info(instagram,E_mail)
return new_cred
def save_account(user):
user.save_... | run.py | from user import User
from credential import Info
def create_account(F_name,L_name,S_name,E_mail):
new_user = User(F_name,L_name,S_name,E_mail)
return new_user
def create_credential(instagram,E_mail):
new_cred = Info(instagram,E_mail)
return new_cred
def save_account(user):
user.save_... | 0.135518 | 0.046834 |
import gtk
import gtk.glade
import subprocess
import shlex
from service import environment
from model.setting import Setting
from service.settings import Settings
from service.config import Config
from gui.entrydlg import EntryDlg
class TMUXCSSHGUI:
# Constant: Name of main window
__NAME_MAIN_WINDOW_GLADE_... | gui/main.py |
import gtk
import gtk.glade
import subprocess
import shlex
from service import environment
from model.setting import Setting
from service.settings import Settings
from service.config import Config
from gui.entrydlg import EntryDlg
class TMUXCSSHGUI:
# Constant: Name of main window
__NAME_MAIN_WINDOW_GLADE_... | 0.408631 | 0.043063 |
import os
import h5py
import shutil
import numpy as np
from copy import deepcopy
from contextlib import contextmanager
from gonzales.simulator.space import Space
import gonzales.simulator.simulation as sim
# ---------------------------------------------------------
# Utility functions
# -----------------------------... | test/test_simulation.py | import os
import h5py
import shutil
import numpy as np
from copy import deepcopy
from contextlib import contextmanager
from gonzales.simulator.space import Space
import gonzales.simulator.simulation as sim
# ---------------------------------------------------------
# Utility functions
# -----------------------------... | 0.482917 | 0.522385 |
import logging
import signal
from contextlib import contextmanager
from threading import Thread
from time import sleep
from typing import Union, Callable, Generator, List
from wsgiref.simple_server import make_server, WSGIServer
LOGGER = logging.getLogger(__name__)
class DevelopmentServer:
def __init__(self, wsg... | restit/development_server.py | import logging
import signal
from contextlib import contextmanager
from threading import Thread
from time import sleep
from typing import Union, Callable, Generator, List
from wsgiref.simple_server import make_server, WSGIServer
LOGGER = logging.getLogger(__name__)
class DevelopmentServer:
def __init__(self, wsg... | 0.58948 | 0.119691 |
__author__ = 'sandra'
# Python packages
import sys, os
import numpy as np
sys.path.append('/afs/cern.ch/user/s/saumon/FCCee/packages/python/madx_parameter/')
sys.path.append('/afs/cern.ch/user/s/saumon/FCCee/packages/python/metaclass/')
sys.path.append('/afs/cern.ch/user/s/saumon/FCCee/packages/python/classtwisstable... | correction_methods/getstuff/get_stuff.py |
__author__ = 'sandra'
# Python packages
import sys, os
import numpy as np
sys.path.append('/afs/cern.ch/user/s/saumon/FCCee/packages/python/madx_parameter/')
sys.path.append('/afs/cern.ch/user/s/saumon/FCCee/packages/python/metaclass/')
sys.path.append('/afs/cern.ch/user/s/saumon/FCCee/packages/python/classtwisstable... | 0.209308 | 0.054374 |
import copy
from operator import itemgetter
from unittest import mock
from neutron.db import segments_db
from neutron.plugins.ml2 import driver_context
from neutron.plugins.ml2 import models as ml2_models
from neutron.tests.unit.plugins.ml2 import test_plugin
from neutron_lib import context
from neutron_lib import ex... | networking_ccloud/tests/unit/ml2/test_mech_driver.py |
import copy
from operator import itemgetter
from unittest import mock
from neutron.db import segments_db
from neutron.plugins.ml2 import driver_context
from neutron.plugins.ml2 import models as ml2_models
from neutron.tests.unit.plugins.ml2 import test_plugin
from neutron_lib import context
from neutron_lib import ex... | 0.504883 | 0.098947 |
from flask import jsonify, current_app, request
from flask.views import MethodView
from flask_template.app import db
from models import User
from util.decorators import admin_required
class UserAPI(MethodView):
decorators = [admin_required]
def get(self):
arg_id = request.args.get('id')
arg_... | admin/views.py | from flask import jsonify, current_app, request
from flask.views import MethodView
from flask_template.app import db
from models import User
from util.decorators import admin_required
class UserAPI(MethodView):
decorators = [admin_required]
def get(self):
arg_id = request.args.get('id')
arg_... | 0.27048 | 0.055285 |