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 |
|---|---|---|---|---|
from __future__ import absolute_import, print_function, unicode_literals
import unittest
import ipaddress
import unipath
from pybsd import AttachNonMasterError, InvalidUIDError, Jail, Master, System
from ..utils import extract_message
class JailTestCase(unittest.TestCase):
master_params = {
'name': 'm... | tests/systems/test_jails.py | from __future__ import absolute_import, print_function, unicode_literals
import unittest
import ipaddress
import unipath
from pybsd import AttachNonMasterError, InvalidUIDError, Jail, Master, System
from ..utils import extract_message
class JailTestCase(unittest.TestCase):
master_params = {
'name': 'm... | 0.531209 | 0.294063 |
import argparse
from git import Repo
from pathlib import Path
import sys
from blessings import Terminal
import os
import yaml
import pprint
import sewer
import traceback
from datetime import datetime, timedelta
from OpenSSL import crypto
import nginx
from shutil import which
def create_dir(directory_path):
p = Pa... | src/update-config.py | import argparse
from git import Repo
from pathlib import Path
import sys
from blessings import Terminal
import os
import yaml
import pprint
import sewer
import traceback
from datetime import datetime, timedelta
from OpenSSL import crypto
import nginx
from shutil import which
def create_dir(directory_path):
p = Pa... | 0.226099 | 0.063135 |
import quandl
import pandas as pd
import numpy as np
class Macro:
def __init__(self, token):
self.token = token
self.macro = None
def quarter_lag(self, df: pd.DataFrame, freq: str, steps: int = 4):
if freq == 'Q':
multiplier = 1
elif freq == 'M':
multip... | data/macro.py | import quandl
import pandas as pd
import numpy as np
class Macro:
def __init__(self, token):
self.token = token
self.macro = None
def quarter_lag(self, df: pd.DataFrame, freq: str, steps: int = 4):
if freq == 'Q':
multiplier = 1
elif freq == 'M':
multip... | 0.360264 | 0.2742 |
import datetime
import os
import bleach
import werkzeug.exceptions
from flask import jsonify, Blueprint, current_app, redirect
from app import video_service, limiter, redis_app
from app.services import StatsService
bp = Blueprint('api', __name__, url_prefix='/api')
def str_to_bool(value: str) -> bool:
"""Deduc... | app/api.py | import datetime
import os
import bleach
import werkzeug.exceptions
from flask import jsonify, Blueprint, current_app, redirect
from app import video_service, limiter, redis_app
from app.services import StatsService
bp = Blueprint('api', __name__, url_prefix='/api')
def str_to_bool(value: str) -> bool:
"""Deduc... | 0.385953 | 0.110567 |
from ...ucscentralmo import ManagedObject
from ...ucscentralcoremeta import UcsCentralVersion, MoPropertyMeta, MoMeta
from ...ucscentralmeta import VersionMeta
class ConfigManagedEpImpactResponseConsts():
REBOOT_REQUIRED_FALSE = "false"
REBOOT_REQUIRED_NO = "no"
REBOOT_REQUIRED_TRUE = "true"
REBOOT_R... | ucscentralsdk/mometa/config/ConfigManagedEpImpactResponse.py |
from ...ucscentralmo import ManagedObject
from ...ucscentralcoremeta import UcsCentralVersion, MoPropertyMeta, MoMeta
from ...ucscentralmeta import VersionMeta
class ConfigManagedEpImpactResponseConsts():
REBOOT_REQUIRED_FALSE = "false"
REBOOT_REQUIRED_NO = "no"
REBOOT_REQUIRED_TRUE = "true"
REBOOT_R... | 0.36693 | 0.123418 |
import sys
import argparse
import re
import random
import json
def from_rule(rule, parameters):
"""
Generates a string that matches the specified rules.
"""
if not rule or not parameters:
return None
# Find all parameters that are wrapped in curly braces (e.g. {foo})
... | words.py |
import sys
import argparse
import re
import random
import json
def from_rule(rule, parameters):
"""
Generates a string that matches the specified rules.
"""
if not rule or not parameters:
return None
# Find all parameters that are wrapped in curly braces (e.g. {foo})
... | 0.409693 | 0.200421 |
from typing import Union
import cvxpy as cp
import numpy as np
from pfopt.base import _IOptimizer
from simpleutils.asserts import require
class QOptimizer(_IOptimizer):
def __init__(self,
cost: np.ndarray,
variance: np.ndarray,
penalty: float = 1.0,
... | pfopt/quadratic.py | from typing import Union
import cvxpy as cp
import numpy as np
from pfopt.base import _IOptimizer
from simpleutils.asserts import require
class QOptimizer(_IOptimizer):
def __init__(self,
cost: np.ndarray,
variance: np.ndarray,
penalty: float = 1.0,
... | 0.902559 | 0.575528 |
from loop_index import LoopIndex
from os import system
def backward_iter_console_test(num_list, jump, start=None):
test_announcement = "Backward iteration by " + str(jump)
if start == None:
start = len(num_list)-1
else:
test_announcement += " from " + str(start)
print(test_annou... | index_test.py |
from loop_index import LoopIndex
from os import system
def backward_iter_console_test(num_list, jump, start=None):
test_announcement = "Backward iteration by " + str(jump)
if start == None:
start = len(num_list)-1
else:
test_announcement += " from " + str(start)
print(test_annou... | 0.472927 | 0.528777 |
import torch
import torch.nn as nn
import torch.nn.functional as func
def _compute_indices(data, indices, counts, max_count):
offset = max_count - counts
offset = offset.roll(1, 0)
offset[0] = 0
offset = torch.repeat_interleave(offset.cumsum(dim=0), counts, dim=0)
offset = offset.to(data.device)
index = o... | torchsupport/structured/scatter.py | import torch
import torch.nn as nn
import torch.nn.functional as func
def _compute_indices(data, indices, counts, max_count):
offset = max_count - counts
offset = offset.roll(1, 0)
offset[0] = 0
offset = torch.repeat_interleave(offset.cumsum(dim=0), counts, dim=0)
offset = offset.to(data.device)
index = o... | 0.634543 | 0.4881 |
import subprocess
import time
import os
import sys
from subprocess import PIPE
import pymail
blacklist = [
"brock800_1.clq",
"brock800_2.clq",
"brock800_3.clq",
"brock800_4.clq",
"keller6.clq",
"DSJC1000_5.clq",
"p_hat700-1.clq",
"p_hat700-2.clq",
"p_hat700-3.clq",
"p_hat1000-1.clq",
"p_hat1000-2.clq",
"p_hat1000-3... | python/main.py |
import subprocess
import time
import os
import sys
from subprocess import PIPE
import pymail
blacklist = [
"brock800_1.clq",
"brock800_2.clq",
"brock800_3.clq",
"brock800_4.clq",
"keller6.clq",
"DSJC1000_5.clq",
"p_hat700-1.clq",
"p_hat700-2.clq",
"p_hat700-3.clq",
"p_hat1000-1.clq",
"p_hat1000-2.clq",
"p_hat1000-3... | 0.130743 | 0.144119 |
import core.mixins
from django.db import migrations, models
import django.db.models.deletion
class Migration(migrations.Migration):
dependencies = [
('sema', '0044_sema_pies_relevance'),
]
operations = [
migrations.CreateModel(
name='SemaEngine',
fields=[
... | ecommercejockey/sema/migrations/0045_semaengine.py |
import core.mixins
from django.db import migrations, models
import django.db.models.deletion
class Migration(migrations.Migration):
dependencies = [
('sema', '0044_sema_pies_relevance'),
]
operations = [
migrations.CreateModel(
name='SemaEngine',
fields=[
... | 0.501953 | 0.141756 |
import pytest
from pytj.algorithm_diff import Diffable, DiffableString
class TestData(object):
"""
"""
def __init__(self, name, a, b, a_b, b_a):
self.name = name
self.a = self.b = None
if isinstance(a, list):
self.a = Diffable(a)
elif isinstance(a, str):
... | tests/test_algorithm_diff.py |
import pytest
from pytj.algorithm_diff import Diffable, DiffableString
class TestData(object):
"""
"""
def __init__(self, name, a, b, a_b, b_a):
self.name = name
self.a = self.b = None
if isinstance(a, list):
self.a = Diffable(a)
elif isinstance(a, str):
... | 0.70477 | 0.71638 |
import alog
import pytest
from mock import PropertyMock, MagicMock, mock
from bitmex_websocket import Instrument
from bitmex_websocket._instrument import SubscribeToAtLeastOneChannelException, \
SubscribeToSecureChannelException
from bitmex_websocket.constants import Channels, SecureChannels, \
SecureInstrumen... | tests/test_instrument.py | import alog
import pytest
from mock import PropertyMock, MagicMock, mock
from bitmex_websocket import Instrument
from bitmex_websocket._instrument import SubscribeToAtLeastOneChannelException, \
SubscribeToSecureChannelException
from bitmex_websocket.constants import Channels, SecureChannels, \
SecureInstrumen... | 0.684475 | 0.386648 |
import QUANTAXIS as QA
"""
在这里 我们演示两种方法
1. 直接通过QA_Thread 创建一个事件线程做任务
2. 通过QA_Engine 来创建一个QA_Thread 来分派事件
"""
thread = QA.QA_Thread() # 创建一个QA_Thread
engine = QA.QA_Engine() # 创建一个QA_Engine
engine.start() # engine 开启
engine.create_kernel('backtest') # engine创建一个叫 backtest的线程
engine.start_kernel... | Documents/about_event.py |
import QUANTAXIS as QA
"""
在这里 我们演示两种方法
1. 直接通过QA_Thread 创建一个事件线程做任务
2. 通过QA_Engine 来创建一个QA_Thread 来分派事件
"""
thread = QA.QA_Thread() # 创建一个QA_Thread
engine = QA.QA_Engine() # 创建一个QA_Engine
engine.start() # engine 开启
engine.create_kernel('backtest') # engine创建一个叫 backtest的线程
engine.start_kernel... | 0.261331 | 0.801625 |
import os
import pickle
import numpy as np
from categorical.models import sample_joint
def intervention_distances(k, n, concentration, intervention, dense_init=True):
"""Sample n mechanisms of order k and for each of them sample an intervention on the desired
mechanism. Return the distance between the origi... | categorical/experiment_distance.py | import os
import pickle
import numpy as np
from categorical.models import sample_joint
def intervention_distances(k, n, concentration, intervention, dense_init=True):
"""Sample n mechanisms of order k and for each of them sample an intervention on the desired
mechanism. Return the distance between the origi... | 0.723114 | 0.630059 |
import sys
from django.apps import AppConfig
preload_models = {}
genre_rmap = {}
def load_model(model, task):
import numpy as np
import torch
import tensorflow as tf
import torch.nn.functional as F
import os
sys.path.append("..")
sys.path.extend([os.path.join(root, name) for root, dirs, _ ... | myweb/myapp/apps.py | import sys
from django.apps import AppConfig
preload_models = {}
genre_rmap = {}
def load_model(model, task):
import numpy as np
import torch
import tensorflow as tf
import torch.nn.functional as F
import os
sys.path.append("..")
sys.path.extend([os.path.join(root, name) for root, dirs, _ ... | 0.277473 | 0.082697 |
# pylint: disable=unused-variable
import logging
import requests
from tornado.options import options
def send_game_start_webhook():
send_webhook({"action": "game_start"})
def send_game_stop_webhook():
send_webhook({"action": "game_stop"})
def send_capture_webhook(user, flag, reward):
send_webhook(
... | libs/WebhookHelpers.py | # pylint: disable=unused-variable
import logging
import requests
from tornado.options import options
def send_game_start_webhook():
send_webhook({"action": "game_start"})
def send_game_stop_webhook():
send_webhook({"action": "game_stop"})
def send_capture_webhook(user, flag, reward):
send_webhook(
... | 0.339171 | 0.165357 |
from d2lib.classes import CLASS_NAMES
from d2lib.errors import ItemParseError
from d2lib.items_storage import ItemsDataStorage
from d2lib.skills import SKILL_NAMES, SKILLS_TREE_NAMES, SKILLS_TREE_OFFSETS
from d2lib.utils import (
ReverseBitReader,
calc_bits_to_align,
obj_to_dict,
to_dict_list,
)
class... | d2lib/item.py | from d2lib.classes import CLASS_NAMES
from d2lib.errors import ItemParseError
from d2lib.items_storage import ItemsDataStorage
from d2lib.skills import SKILL_NAMES, SKILLS_TREE_NAMES, SKILLS_TREE_OFFSETS
from d2lib.utils import (
ReverseBitReader,
calc_bits_to_align,
obj_to_dict,
to_dict_list,
)
class... | 0.71413 | 0.264495 |
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_database.Default()
from google.protobuf im... | lib/third_party/google/cloud/appengine_v1beta/proto/operation_pb2.py |
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_database.Default()
from google.protobuf im... | 0.305386 | 0.07627 |
from ....constant.colors import GOLD, GREEN, WHITE, RARITY_COLORS
from ....function.util import checkpoint
from ....object.items import get_item
__all__ = ['grandma_wolf']
@checkpoint
def grandma_wolf(player, /):
for index, pet in enumerate(player.pets):
if pet.name == 'grandma_wolf_pet':
bre... | skyblock/map/npc/function/grandma_wolf.py | from ....constant.colors import GOLD, GREEN, WHITE, RARITY_COLORS
from ....function.util import checkpoint
from ....object.items import get_item
__all__ = ['grandma_wolf']
@checkpoint
def grandma_wolf(player, /):
for index, pet in enumerate(player.pets):
if pet.name == 'grandma_wolf_pet':
bre... | 0.324235 | 0.266954 |
import os
import re
from setuptools import find_packages, setup
from subprocess import check_output
MAJOR = 0
MINOR = 1
MICRO = 3
IS_RELEASED = False
VERSION = '%d.%d.%d' % (MAJOR, MINOR, MICRO)
VERSION_FILE_TEMPLATE = """\
# This file is generated from setup.py
version = '{version}'
full_version = '{full_version}'
gi... | setup.py | import os
import re
from setuptools import find_packages, setup
from subprocess import check_output
MAJOR = 0
MINOR = 1
MICRO = 3
IS_RELEASED = False
VERSION = '%d.%d.%d' % (MAJOR, MINOR, MICRO)
VERSION_FILE_TEMPLATE = """\
# This file is generated from setup.py
version = '{version}'
full_version = '{full_version}'
gi... | 0.356111 | 0.071041 |
Python 3.7.3 (v3.7.3:ef4ec6ed12, Mar 25 2019, 21:26:53) [MSC v.1916 32 bit (Intel)] on win32
Type "help", "copyright", "credits" or "license()" for more information.
>>> print('hello')
hello
>>> for i in range(1, 100)
SyntaxError: invalid syntax
>>> for i in range(1, 100):
print("hello World!")
hello World!
hello Wor... | File Opening.py | Python 3.7.3 (v3.7.3:ef4ec6ed12, Mar 25 2019, 21:26:53) [MSC v.1916 32 bit (Intel)] on win32
Type "help", "copyright", "credits" or "license()" for more information.
>>> print('hello')
hello
>>> for i in range(1, 100)
SyntaxError: invalid syntax
>>> for i in range(1, 100):
print("hello World!")
hello World!
hello Wor... | 0.168378 | 0.214928 |
import os
import time
from collections import OrderedDict
import cv2
import numpy as np
from ace2p.processor import get_direction, get_3rd_point, get_affine_transform
__all__ = ['reader']
def _box2cs(box, aspect_ratio):
x, y, w, h = box[:4]
return _xywh2cs(x, y, w, h, aspect_ratio)
def _xywh2cs(x, y, w, ... | modules/image/semantic_segmentation/ace2p/data_feed.py | import os
import time
from collections import OrderedDict
import cv2
import numpy as np
from ace2p.processor import get_direction, get_3rd_point, get_affine_transform
__all__ = ['reader']
def _box2cs(box, aspect_ratio):
x, y, w, h = box[:4]
return _xywh2cs(x, y, w, h, aspect_ratio)
def _xywh2cs(x, y, w, ... | 0.725357 | 0.323433 |
import traceback
import subprocess
import os
import socket
import time
import sys
if len(sys.argv) != 2:
print("Usage: python3.6 coordinator.py (ID)")
sys.exit(1)
coordinator_id = sys.argv[1]
if not coordinator_id.isalnum():
print("Expected an alphanumeric string.")
sys.exit(1)
subprocess_current = None
def subp... | coordinator.py | import traceback
import subprocess
import os
import socket
import time
import sys
if len(sys.argv) != 2:
print("Usage: python3.6 coordinator.py (ID)")
sys.exit(1)
coordinator_id = sys.argv[1]
if not coordinator_id.isalnum():
print("Expected an alphanumeric string.")
sys.exit(1)
subprocess_current = None
def subp... | 0.071575 | 0.069763 |
import logging
from collections import defaultdict
import celery
from .abstract_message_center import AbstractMessageCenter
from .const import Messagio, TASK_PRIORITY
logger = logging.getLogger("odb_ecs")
class MessageCenter(AbstractMessageCenter):
def __init__(self):
self._task_settings = defaultdict(... | src/messagio/message_center.py | import logging
from collections import defaultdict
import celery
from .abstract_message_center import AbstractMessageCenter
from .const import Messagio, TASK_PRIORITY
logger = logging.getLogger("odb_ecs")
class MessageCenter(AbstractMessageCenter):
def __init__(self):
self._task_settings = defaultdict(... | 0.470007 | 0.067886 |
import numpy
StrippedDown = {
'galaxyID' : (0, int),
'x': (1, float),
'y' : (2, float),
'z' : (3, float),
'mag_bc' : (4, float),
'mag_bB' : (5, float),
}
MSdata = {
'galaxyID' : (0, int),
'lastProg' : (1, int),
'descedantID' : (2, int),
'haloID' : (3, int),
'subHaloID' : (4... | sandbox/src1/FECommon.py | import numpy
StrippedDown = {
'galaxyID' : (0, int),
'x': (1, float),
'y' : (2, float),
'z' : (3, float),
'mag_bc' : (4, float),
'mag_bB' : (5, float),
}
MSdata = {
'galaxyID' : (0, int),
'lastProg' : (1, int),
'descedantID' : (2, int),
'haloID' : (3, int),
'subHaloID' : (4... | 0.448426 | 0.427217 |
import uuid
import auth
from app import app, sio, state
from models import PlayerRoom
@sio.on("Room.Info.InviteCode.Refresh", namespace="/planarally")
@auth.login_required(app, sio)
async def refresh_invite_code(sid):
sid_data = state.sid_map[sid]
user = sid_data["user"]
room = sid_data["room"]
if ro... | server/api/socket/room.py | import uuid
import auth
from app import app, sio, state
from models import PlayerRoom
@sio.on("Room.Info.InviteCode.Refresh", namespace="/planarally")
@auth.login_required(app, sio)
async def refresh_invite_code(sid):
sid_data = state.sid_map[sid]
user = sid_data["user"]
room = sid_data["room"]
if ro... | 0.272993 | 0.102036 |
import array
import asyncio
import base64
import logging
import os
import pathlib
from datetime import datetime, timezone
import chardet
import yaml
from aiohttp import web
from bson import ObjectId
import plugins.adversary.app.config as config
from plugins.adversary.app.attack import refresh_attack
from plugins.adve... | app/service/api_logic.py | import array
import asyncio
import base64
import logging
import os
import pathlib
from datetime import datetime, timezone
import chardet
import yaml
from aiohttp import web
from bson import ObjectId
import plugins.adversary.app.config as config
from plugins.adversary.app.attack import refresh_attack
from plugins.adve... | 0.279533 | 0.08266 |
from abc import ABC, abstractmethod
from dataclasses import dataclass, field
from typing import (
Any,
AsyncIterator,
Awaitable,
Callable,
Coroutine,
List,
Optional,
Sequence,
Tuple,
)
from typing_extensions import Protocol
from ..util.error import LabgraphError
from .topic import... | labgraph/graphs/method.py |
from abc import ABC, abstractmethod
from dataclasses import dataclass, field
from typing import (
Any,
AsyncIterator,
Awaitable,
Callable,
Coroutine,
List,
Optional,
Sequence,
Tuple,
)
from typing_extensions import Protocol
from ..util.error import LabgraphError
from .topic import... | 0.871953 | 0.632418 |
from PDFGradients import PDFGradients as FPDF
pdf = FPDF()
#first page
pdf.add_page()
pdf.set_font('Helvetica','',14)
pdf.cell(0,5,'Page 1',0,1,'C')
pdf.ln()
#set colors for gradients (r,g,b) or (grey 0-255)
red=[255,0,0]
blue=[0,0,200]
yellow=[255,255,0]
green=[0,255,0]
white=[255]
black=[0]
#set the coordinates... | gradiens/demo.py |
from PDFGradients import PDFGradients as FPDF
pdf = FPDF()
#first page
pdf.add_page()
pdf.set_font('Helvetica','',14)
pdf.cell(0,5,'Page 1',0,1,'C')
pdf.ln()
#set colors for gradients (r,g,b) or (grey 0-255)
red=[255,0,0]
blue=[0,0,200]
yellow=[255,255,0]
green=[0,255,0]
white=[255]
black=[0]
#set the coordinates... | 0.452052 | 0.324342 |
def read_single_keypress():
import termios, fcntl, sys, os
fd = sys.stdin.fileno()
flags_save = fcntl.fcntl(fd, fcntl.F_GETFL) # save old state
attrs_save = termios.tcgetattr(fd)
attrs = list(
attrs_save) # make raw - the way to do this comes from the termios(3) man page. # copy the store... | apm_new_pigpio.py | def read_single_keypress():
import termios, fcntl, sys, os
fd = sys.stdin.fileno()
flags_save = fcntl.fcntl(fd, fcntl.F_GETFL) # save old state
attrs_save = termios.tcgetattr(fd)
attrs = list(
attrs_save) # make raw - the way to do this comes from the termios(3) man page. # copy the store... | 0.381796 | 0.146301 |
import os
import json
import functools
import subprocess
from unittest import SkipTest
def skip_if_data_missing(repo_path):
"""
Decorator for unittest.TestCase test functions. Raises SkipTest if the
pygeoprocessing data repository has not been cloned.
Arguments:
repo_path (string): The path ... | src/natcap/invest/pygeoprocessing_0_3_3/testing/scm.py | import os
import json
import functools
import subprocess
from unittest import SkipTest
def skip_if_data_missing(repo_path):
"""
Decorator for unittest.TestCase test functions. Raises SkipTest if the
pygeoprocessing data repository has not been cloned.
Arguments:
repo_path (string): The path ... | 0.647687 | 0.352049 |
import os
import numpy as np
from gputools import OCLArray, OCLProgram, get_device
from gputools import convolve, fft_convolve, fft, fft_plan
from gputools import OCLElementwiseKernel
from typing import Optional, Callable
import warnings
import gputools
_multiply_inplace = OCLElementwiseKernel("float *a, floa... | lls_dd/deconv_gputools.py | import os
import numpy as np
from gputools import OCLArray, OCLProgram, get_device
from gputools import convolve, fft_convolve, fft, fft_plan
from gputools import OCLElementwiseKernel
from typing import Optional, Callable
import warnings
import gputools
_multiply_inplace = OCLElementwiseKernel("float *a, floa... | 0.537284 | 0.212477 |
import json
import re
from collections import OrderedDict
from inspect import getfullargspec
import numpy as np
from .linalg import iscomplexobj
from .pulse import Pulse, _PulseConfigAttribs
from .units import UnitConvert, UnitFloat
class _NumpyAwareJSONEncoder(json.JSONEncoder):
"""JSON Encoder than can handle... | src/qdyn/analytical_pulse.py | import json
import re
from collections import OrderedDict
from inspect import getfullargspec
import numpy as np
from .linalg import iscomplexobj
from .pulse import Pulse, _PulseConfigAttribs
from .units import UnitConvert, UnitFloat
class _NumpyAwareJSONEncoder(json.JSONEncoder):
"""JSON Encoder than can handle... | 0.825343 | 0.37359 |
import bpy
from bpy.types import (
Curve,
)
from mathutils import (geometry, Vector)
import numpy
from . import grid
from . import bezier
import importlib
grid = importlib.reload(grid)
bezier = importlib.reload(bezier)
def is_valid_curve(curve):
if curve.dimensions != '2D' or len(curve.splines) != 1:
... | border.py | import bpy
from bpy.types import (
Curve,
)
from mathutils import (geometry, Vector)
import numpy
from . import grid
from . import bezier
import importlib
grid = importlib.reload(grid)
bezier = importlib.reload(bezier)
def is_valid_curve(curve):
if curve.dimensions != '2D' or len(curve.splines) != 1:
... | 0.826572 | 0.354852 |
import os
import sys
from xml.dom.minidom import parse
import pygame
from pygame.locals import *
from pyso.map import Map
def _safe_get(path:str):
if path.startswith('std:'):
p=os.path.join(os.path._getfullpathname('.'), path.replace('std:',''))
p=sys.executable.replace('python.exe','')+'Lib\\pys... | __init__.py | import os
import sys
from xml.dom.minidom import parse
import pygame
from pygame.locals import *
from pyso.map import Map
def _safe_get(path:str):
if path.startswith('std:'):
p=os.path.join(os.path._getfullpathname('.'), path.replace('std:',''))
p=sys.executable.replace('python.exe','')+'Lib\\pys... | 0.156041 | 0.060724 |
from tkinter import *
import csv
import datetime
def display(mysql):
'''
display()
:return: None
Displays the Spreadsheets UI
'''
def generate_spreadsheet():
'''
generate_spreadsheet()
:return: None
Generates a spreadsheet for given data
'''
scr... | spreadsheets.py | from tkinter import *
import csv
import datetime
def display(mysql):
'''
display()
:return: None
Displays the Spreadsheets UI
'''
def generate_spreadsheet():
'''
generate_spreadsheet()
:return: None
Generates a spreadsheet for given data
'''
scr... | 0.416085 | 0.287768 |
import cv2
import os
import os.path as op
import argparse
import json
from scene_graph_benchmark.scene_parser import SceneParser
from scene_graph_benchmark.AttrRCNN import AttrRCNN
from maskrcnn_benchmark.data.transforms import build_transforms
from maskrcnn_benchmark.utils.checkpoint import DetectronCheckpointer
fro... | tools/demo/demo_dir.py |
import cv2
import os
import os.path as op
import argparse
import json
from scene_graph_benchmark.scene_parser import SceneParser
from scene_graph_benchmark.AttrRCNN import AttrRCNN
from maskrcnn_benchmark.data.transforms import build_transforms
from maskrcnn_benchmark.utils.checkpoint import DetectronCheckpointer
fro... | 0.382949 | 0.177454 |
from test.test_utilities import parse_node_combo_template_yaml_file
fileName = "npm-test-lint-validation-xunit.yml"
contents = parse_node_combo_template_yaml_file(fileName)
steps = contents["steps"]
parameters = contents["parameters"]
npmInstallParameters = parameters["npmInstall"]
npmTestScriptParameters = parameters... | test/yml/node/combo/npm_test_lint_validation_xunit_test.py | from test.test_utilities import parse_node_combo_template_yaml_file
fileName = "npm-test-lint-validation-xunit.yml"
contents = parse_node_combo_template_yaml_file(fileName)
steps = contents["steps"]
parameters = contents["parameters"]
npmInstallParameters = parameters["npmInstall"]
npmTestScriptParameters = parameters... | 0.440951 | 0.574037 |
from users.views import user_info
from django.contrib.auth.models import AnonymousUser
from django.test.client import RequestFactory
from django.urls import reverse
from users.forms import CustomUserChangeForm, CustomUserCreationForm
from django.test import TestCase, override_settings
from .models import CustomUser
# C... | app/users/tests.py | from users.views import user_info
from django.contrib.auth.models import AnonymousUser
from django.test.client import RequestFactory
from django.urls import reverse
from users.forms import CustomUserChangeForm, CustomUserCreationForm
from django.test import TestCase, override_settings
from .models import CustomUser
# C... | 0.520009 | 0.198608 |
import folium
from geopy.geocoders import Nominatim
from geopy.exc import GeocoderUnavailable
import math
import random
import re
def processing_locations(locations: list) -> list:
"""
Calculates the cordinates for locations, appends them to locations list
and returns the list.
"""
fo... | main.py | import folium
from geopy.geocoders import Nominatim
from geopy.exc import GeocoderUnavailable
import math
import random
import re
def processing_locations(locations: list) -> list:
"""
Calculates the cordinates for locations, appends them to locations list
and returns the list.
"""
fo... | 0.435661 | 0.445168 |
from flask import Flask, request, abort, jsonify
from flask_cors import CORS
import random
from models import setup_db, Question, Category
QUESTIONS_PER_PAGE = 10
BAD_REQUEST = "Bad Request"
NOT_FOUND = "Not Found"
UNPROCESSABLE_ENTITY = "Unprocessable Entity"
INTERNAL_SERVER_ERROR = "Internal Server Error"
def cre... | backend/flaskr/__init__.py | from flask import Flask, request, abort, jsonify
from flask_cors import CORS
import random
from models import setup_db, Question, Category
QUESTIONS_PER_PAGE = 10
BAD_REQUEST = "Bad Request"
NOT_FOUND = "Not Found"
UNPROCESSABLE_ENTITY = "Unprocessable Entity"
INTERNAL_SERVER_ERROR = "Internal Server Error"
def cre... | 0.386879 | 0.14442 |
import torch
from torch.distributions import Dirichlet, Beta
from einops import rearrange, repeat
from opt_einsum import contract
class PRIMEAugModule(torch.nn.Module):
def __init__(self, augmentations):
super().__init__()
self.augmentations = augmentations
self.num_transforms = len(augme... | utils/prime.py | import torch
from torch.distributions import Dirichlet, Beta
from einops import rearrange, repeat
from opt_einsum import contract
class PRIMEAugModule(torch.nn.Module):
def __init__(self, augmentations):
super().__init__()
self.augmentations = augmentations
self.num_transforms = len(augme... | 0.916363 | 0.455078 |
from __future__ import absolute_import
from __future__ import division
from __future__ import print_function
from __future__ import unicode_literals
from six.moves import range
from tensorflow.contrib.rnn.python.ops import core_rnn_cell
from tensorflow.python.ops import array_ops
from tensorflow.python.ops import init... | open_seq2seq/parts/rnns/glstm.py | from __future__ import absolute_import
from __future__ import division
from __future__ import print_function
from __future__ import unicode_literals
from six.moves import range
from tensorflow.contrib.rnn.python.ops import core_rnn_cell
from tensorflow.python.ops import array_ops
from tensorflow.python.ops import init... | 0.640523 | 0.343424 |
__all__ = ['GetDeltas','plot_by_param','plot_function','ChoosingDelta','preprocess_temporal_communities','plot_temporal_communities','plot_with_lambdas']
__author__ = """\n""".join(['<NAME> (<EMAIL>)',
'<NAME> <<EMAIL>>',
'<NAME> <<EMAIL>>'])
# Copyright (C) 201... | Estrangement/plots.py | __all__ = ['GetDeltas','plot_by_param','plot_function','ChoosingDelta','preprocess_temporal_communities','plot_temporal_communities','plot_with_lambdas']
__author__ = """\n""".join(['<NAME> (<EMAIL>)',
'<NAME> <<EMAIL>>',
'<NAME> <<EMAIL>>'])
# Copyright (C) 201... | 0.711531 | 0.377397 |
import sys, os, time, datetime, json, urllib.request
from optparse import OptionParser
def registerPlayready(drmType, auth, kid, enckey):
url=""
if (drmType==DRM_TYPE.TEST): url = "https://pr-gen.test.expressplay.com/hms/pr/token"
elif (drmType==DRM_TYPE.PROD): url = "https://pr-gen.service.expressplay.com... | tools/test/RegisterDRM_ExpressPlay.py |
import sys, os, time, datetime, json, urllib.request
from optparse import OptionParser
def registerPlayready(drmType, auth, kid, enckey):
url=""
if (drmType==DRM_TYPE.TEST): url = "https://pr-gen.test.expressplay.com/hms/pr/token"
elif (drmType==DRM_TYPE.PROD): url = "https://pr-gen.service.expressplay.com... | 0.167627 | 0.07024 |
from generate import main as single_model_main
import os, sys, subprocess
import time, sys
import re
from fairseq import options
def obtain_sys_argv():
def if_illegal_args(str_check):
illegal_args_names = ['--ckpt', '--initial', '--generate', '--decokenizer', '--sacre-test', '--store-testfiles', '--decode... | seq_translate.py | from generate import main as single_model_main
import os, sys, subprocess
import time, sys
import re
from fairseq import options
def obtain_sys_argv():
def if_illegal_args(str_check):
illegal_args_names = ['--ckpt', '--initial', '--generate', '--decokenizer', '--sacre-test', '--store-testfiles', '--decode... | 0.176956 | 0.120931 |
class Node:
# Constructor to initialize data
# If data is not given by user,its taken as None
def __init__(self, data=None, next=None, prev=None):
self.data = data
self.next = next
self.prev = prev
# method for setting the data field of the node
def set_data(self, data):... | doubly_linkedlists.py | class Node:
# Constructor to initialize data
# If data is not given by user,its taken as None
def __init__(self, data=None, next=None, prev=None):
self.data = data
self.next = next
self.prev = prev
# method for setting the data field of the node
def set_data(self, data):... | 0.607197 | 0.419172 |
__all__ = ['Averager']
import time
import itertools
import numpy as np
from .filter import Filter
from auspex.log import logger
from auspex.parameter import Parameter, FloatParameter
from auspex.stream import InputConnector, OutputConnector, DataStreamDescriptor, DataAxis
def view_fields(a, names):
"""
`a` ... | src/auspex/filters/average.py |
__all__ = ['Averager']
import time
import itertools
import numpy as np
from .filter import Filter
from auspex.log import logger
from auspex.parameter import Parameter, FloatParameter
from auspex.stream import InputConnector, OutputConnector, DataStreamDescriptor, DataAxis
def view_fields(a, names):
"""
`a` ... | 0.802556 | 0.409664 |
import numpy as np
import pandas as pd
import os
import sqlalchemy
from time import sleep
import pickle
from numbers import Number
def serialize(x):
if not isinstance(x, (str, Number)):
return pickle.dumps(x)
else:
return x
def unserialize(x):
if not isinstance(x, (str, Number)):
... | parameterscan/sqlite.py | import numpy as np
import pandas as pd
import os
import sqlalchemy
from time import sleep
import pickle
from numbers import Number
def serialize(x):
if not isinstance(x, (str, Number)):
return pickle.dumps(x)
else:
return x
def unserialize(x):
if not isinstance(x, (str, Number)):
... | 0.528533 | 0.163045 |
from common.response import json_response
import logging
import re
logger = logging.getLogger("newt." + __name__)
def get_machines(request):
"""Returns the available machines that jobs can run on
Keyword arguments:
request - Django HttpRequest
"""
pass
def view_queue(request, machine_name):
... | job/adapters/template_adapter.py | from common.response import json_response
import logging
import re
logger = logging.getLogger("newt." + __name__)
def get_machines(request):
"""Returns the available machines that jobs can run on
Keyword arguments:
request - Django HttpRequest
"""
pass
def view_queue(request, machine_name):
... | 0.802788 | 0.301002 |
from __future__ import division, generators, print_function
import random
import torch
import torch.nn as nn
import torch.nn.functional as F
from torch.autograd import Variable as Var
import sys
import macarico.util
macarico.util.reseed()
from macarico.annealing import ExponentialAnnealing, stochastic
from macarico.l... | tests/test_reslope.py | from __future__ import division, generators, print_function
import random
import torch
import torch.nn as nn
import torch.nn.functional as F
from torch.autograd import Variable as Var
import sys
import macarico.util
macarico.util.reseed()
from macarico.annealing import ExponentialAnnealing, stochastic
from macarico.l... | 0.477311 | 0.282086 |
import hashlib
import io
import os
import uuid
from functools import lru_cache
from pathlib import Path
import xmltodict
from fastapi import Depends
from pydantic import BaseModel
from .config import Settings
class CheckInfoBasesResponse(BaseModel):
InfoBasesChanged: bool = False
URL: str
location: str
... | app/dependencies.py | import hashlib
import io
import os
import uuid
from functools import lru_cache
from pathlib import Path
import xmltodict
from fastapi import Depends
from pydantic import BaseModel
from .config import Settings
class CheckInfoBasesResponse(BaseModel):
InfoBasesChanged: bool = False
URL: str
location: str
... | 0.256832 | 0.069132 |
from django.shortcuts import render, get_object_or_404, redirect
from django.views.generic import DetailView
from django.utils.translation import gettext as _
from froide.account.preferences import get_preferences_for_user
from froide.helper.utils import render_403
from ..models import FoiRequest, FoiEvent, FoiAttach... | froide/foirequest/views/request.py | from django.shortcuts import render, get_object_or_404, redirect
from django.views.generic import DetailView
from django.utils.translation import gettext as _
from froide.account.preferences import get_preferences_for_user
from froide.helper.utils import render_403
from ..models import FoiRequest, FoiEvent, FoiAttach... | 0.404155 | 0.149687 |
import nltk
import discord
from discord.ext import commands
from nltk.sentiment import SentimentIntensityAnalyzer
import database as db
import variables as var
from functions import get_prefix
from ext.permissions import has_command_permission
nltk.download('vader_lexicon')
sia = SentimentIntensityAnalyzer()
class ... | axiol/plugins/karma.py | import nltk
import discord
from discord.ext import commands
from nltk.sentiment import SentimentIntensityAnalyzer
import database as db
import variables as var
from functions import get_prefix
from ext.permissions import has_command_permission
nltk.download('vader_lexicon')
sia = SentimentIntensityAnalyzer()
class ... | 0.432423 | 0.122523 |
import os
import re
import sys
import urllib.request
from time import strptime
# Regular Expressions
CVE_RE = re.compile('CVE-[0-9]{4}-[0-9]{4,}')
HTML_RE = re.compile('<[^<]+?>')
BOUNTY_RE = re.compile('\[\$([0-9\.]|TBD|N/A)+\]')
BUG_RE = re.compile('\[[0-9]+\]')
DESCRIPTION_RE = re.compile('[:-]{0,1} [^\.]*(\.|\s)'... | scripts/get_cves_from_url.py |
import os
import re
import sys
import urllib.request
from time import strptime
# Regular Expressions
CVE_RE = re.compile('CVE-[0-9]{4}-[0-9]{4,}')
HTML_RE = re.compile('<[^<]+?>')
BOUNTY_RE = re.compile('\[\$([0-9\.]|TBD|N/A)+\]')
BUG_RE = re.compile('\[[0-9]+\]')
DESCRIPTION_RE = re.compile('[:-]{0,1} [^\.]*(\.|\s)'... | 0.277571 | 0.166201 |
import json
import dml
import prov.model
import datetime
import uuid
import pandas as pd
class topCertifiedCompanies(dml.Algorithm):
contributor = 'ashwini_gdukuray_justini_utdesai'
reads = ['ashwini_gdukuray_justini_utdesai.topCompanies', 'ashwini_gdukuray_justini_utdesai.masterList']
writes = ['ashwini_... | topCertifiedCompanies.py | import json
import dml
import prov.model
import datetime
import uuid
import pandas as pd
class topCertifiedCompanies(dml.Algorithm):
contributor = 'ashwini_gdukuray_justini_utdesai'
reads = ['ashwini_gdukuray_justini_utdesai.topCompanies', 'ashwini_gdukuray_justini_utdesai.masterList']
writes = ['ashwini_... | 0.278747 | 0.179531 |
import numpy as np
from scipy.interpolate.interpolate import interp1d
import matplotlib.pyplot as plt
import os
path_104 = os.path.abspath('../../../Downloads/realTime-master-AlAl-data_trial5/AlAl/data_trial5/104S/')
files_104_unsorted = os.listdir(path_104)
order = [int(str.split(ff, "_")[1]) for ff in files... | examples/shpb-flyer-Al5083_pooled_prep.py | import numpy as np
from scipy.interpolate.interpolate import interp1d
import matplotlib.pyplot as plt
import os
path_104 = os.path.abspath('../../../Downloads/realTime-master-AlAl-data_trial5/AlAl/data_trial5/104S/')
files_104_unsorted = os.listdir(path_104)
order = [int(str.split(ff, "_")[1]) for ff in files... | 0.135546 | 0.210158 |
from typing_extensions import Literal
from pydantic import BaseModel, Field, conint
from enum import Enum
class EdgeType(str, Enum):
"""
An enumeration for the types of edges.
"""
Surface = "Surface"
Space = "Space"
Flight = "Flight"
class Edge(BaseModel):
"""
Base class for all edg... | spacenet/schemas/edge.py | from typing_extensions import Literal
from pydantic import BaseModel, Field, conint
from enum import Enum
class EdgeType(str, Enum):
"""
An enumeration for the types of edges.
"""
Surface = "Surface"
Space = "Space"
Flight = "Flight"
class Edge(BaseModel):
"""
Base class for all edg... | 0.896013 | 0.51562 |
from numpy.testing import assert_allclose
import pytest
from fluids.numerics import assert_close, assert_close1d
from chemicals.thermal_conductivity import *
from chemicals.identifiers import check_CAS
from chemicals.thermal_conductivity import k_data_Perrys_8E_2_314, k_data_Perrys_8E_2_315, k_data_VDI_PPDS_10, k_data_... | tests/test_thermal_conductivity.py | from numpy.testing import assert_allclose
import pytest
from fluids.numerics import assert_close, assert_close1d
from chemicals.thermal_conductivity import *
from chemicals.identifiers import check_CAS
from chemicals.thermal_conductivity import k_data_Perrys_8E_2_314, k_data_Perrys_8E_2_315, k_data_VDI_PPDS_10, k_data_... | 0.472927 | 0.481027 |
import pytest
from cirq.ops.qubit_order import default_sorting_key
from cirq.ops import QubitOrder, NamedQubit
def test_default_sorting_key():
assert default_sorting_key('') == ''
assert default_sorting_key('a') == 'a'
assert default_sorting_key('a0') == 'a00000000:1'
assert default_sorting_key('a00... | cirq/ops/qubit_order_test.py |
import pytest
from cirq.ops.qubit_order import default_sorting_key
from cirq.ops import QubitOrder, NamedQubit
def test_default_sorting_key():
assert default_sorting_key('') == ''
assert default_sorting_key('a') == 'a'
assert default_sorting_key('a0') == 'a00000000:1'
assert default_sorting_key('a00... | 0.764716 | 0.75647 |
class Point:
"""A point object in pixels, with X and Y coordinates.
X and Y are counted from 0. The point at (x=0, y=0) is the
top-left corner of your window. X represents the horizontal axis
and Y is the vertical axis. Therefore, Point(x=50 y=0) is to
the right of Point(x=0 y=0), while Point(x... | bui/geometry.py | class Point:
"""A point object in pixels, with X and Y coordinates.
X and Y are counted from 0. The point at (x=0, y=0) is the
top-left corner of your window. X represents the horizontal axis
and Y is the vertical axis. Therefore, Point(x=50 y=0) is to
the right of Point(x=0 y=0), while Point(x... | 0.9471 | 0.763087 |
import dash_html_components as html
from dash.dependencies import Output, Input
import pages.rocket_builder.rocket_builder_page as rb
from app import app
from conversions import metric_convert
inputs = {
'number of fins': {'unit': '', 'default_value': 4, 'input_prefix': '-', 'si_prefix': '-'},
'root chord': {... | pages/rocket_builder/fins_page.py | import dash_html_components as html
from dash.dependencies import Output, Input
import pages.rocket_builder.rocket_builder_page as rb
from app import app
from conversions import metric_convert
inputs = {
'number of fins': {'unit': '', 'default_value': 4, 'input_prefix': '-', 'si_prefix': '-'},
'root chord': {... | 0.61231 | 0.110904 |
import pytest
import popart
import popart._internal.ir as _ir
def check_graph_inputs(graph, graph_inputs):
""" Helper function, graph inputs are what we expect. """
assert graph.getInputIds() == graph_inputs, \
f"Expected Graph {graph.getGraphString()} to have inputs {graph_inputs}, got {graph.getInp... | tests/unittests/python/popart._internal.ir/bindings/test_graph.py | import pytest
import popart
import popart._internal.ir as _ir
def check_graph_inputs(graph, graph_inputs):
""" Helper function, graph inputs are what we expect. """
assert graph.getInputIds() == graph_inputs, \
f"Expected Graph {graph.getGraphString()} to have inputs {graph_inputs}, got {graph.getInp... | 0.696062 | 0.638215 |
import abc
import typing
from datetime import datetime
from typing import (
Any,
Awaitable,
Callable,
ItemsView,
Iterable,
Iterator,
KeysView,
Mapping,
MutableMapping,
Optional,
Set,
Tuple,
TypeVar,
Union,
ValuesView,
)
from mode import Seconds, ServiceT
from... | consumers/venv/lib/python3.7/site-packages/faust/types/tables.py | import abc
import typing
from datetime import datetime
from typing import (
Any,
Awaitable,
Callable,
ItemsView,
Iterable,
Iterator,
KeysView,
Mapping,
MutableMapping,
Optional,
Set,
Tuple,
TypeVar,
Union,
ValuesView,
)
from mode import Seconds, ServiceT
from... | 0.770896 | 0.143098 |
from itertools import chain
from typing import Dict, FrozenSet, Generator, List, Optional
from .doc_region_restriction import get_doc_region_restriction
from .document import DocRegion, Document, EZDocRegion
from .extraction import Field
from .scoring import ScoredExtraction
from .spatial_formula import DNF, Formula, ... | blueprint/py/bp/doc_region_prefilter.py | from itertools import chain
from typing import Dict, FrozenSet, Generator, List, Optional
from .doc_region_restriction import get_doc_region_restriction
from .document import DocRegion, Document, EZDocRegion
from .extraction import Field
from .scoring import ScoredExtraction
from .spatial_formula import DNF, Formula, ... | 0.730866 | 0.264189 |
import abc
from collections import OrderedDict
from .._common import get_file_encoding, json
from .._constant import SourceType
from .._constant import TableNameTemplate as tnt
from .._logger import FileSourceLogger, TextSourceLogger
from .._validator import FileValidator, NullValidator, TextValidator
from ..error imp... | pytablereader/json/core.py | import abc
from collections import OrderedDict
from .._common import get_file_encoding, json
from .._constant import SourceType
from .._constant import TableNameTemplate as tnt
from .._logger import FileSourceLogger, TextSourceLogger
from .._validator import FileValidator, NullValidator, TextValidator
from ..error imp... | 0.693784 | 0.369088 |
from Problema.Nodo import Nodo
from Problema.Frontera import Frontera
from Problema.Estado import Estado
import Cnfg
class Busqueda:
def __init__(self, dict_manual):
self.diccionario = dict_manual
self.inicio = tuple(Cnfg.inicial)
self.objetivo = tuple(Cnfg.objetivo)
self.estrateg... | Problema/Busqueda.py | from Problema.Nodo import Nodo
from Problema.Frontera import Frontera
from Problema.Estado import Estado
import Cnfg
class Busqueda:
def __init__(self, dict_manual):
self.diccionario = dict_manual
self.inicio = tuple(Cnfg.inicial)
self.objetivo = tuple(Cnfg.objetivo)
self.estrateg... | 0.255158 | 0.176849 |
import os
import os.path
import platform
from knack.arguments import CLIArgumentType
from ._completers import get_kubernetes_version_completion_list
from ._completers import get_vm_size_completion_list
from ._completers import get_workflow_clusters_completion_list
def load_arguments(self, _):
"""Loads command a... | src/capi/azext_capi/_params.py | import os
import os.path
import platform
from knack.arguments import CLIArgumentType
from ._completers import get_kubernetes_version_completion_list
from ._completers import get_vm_size_completion_list
from ._completers import get_workflow_clusters_completion_list
def load_arguments(self, _):
"""Loads command a... | 0.322313 | 0.052741 |
from __future__ import division
import numpy as np
np.seterr(all='raise')
import random
import logging
from VisionEgg.Gratings import SinGrating2D
from VisionEgg.Textures import Mask2D
from VisionEgg.MoreStimuli import Target2D
from LightUtil import TimeFormat
from Core import Stimulus
from SweepController import S... | StimControl/LightStim/Grating.py |
from __future__ import division
import numpy as np
np.seterr(all='raise')
import random
import logging
from VisionEgg.Gratings import SinGrating2D
from VisionEgg.Textures import Mask2D
from VisionEgg.MoreStimuli import Target2D
from LightUtil import TimeFormat
from Core import Stimulus
from SweepController import S... | 0.64646 | 0.143278 |
import numpy as np
import matplotlib.pyplot as plt
from matplotlib import cm
from matplotlib.ticker import MultipleLocator
from util import low_shelving_2nd_cascade, shelving_filter_parameters, \
shelving_slope_parameters, sosfreqs, db, set_rcparams, \
set_outdir
set_rcparams()
outdir = set_outdir()
Biquad_pe... | python/mkfig-gain-error.py | import numpy as np
import matplotlib.pyplot as plt
from matplotlib import cm
from matplotlib.ticker import MultipleLocator
from util import low_shelving_2nd_cascade, shelving_filter_parameters, \
shelving_slope_parameters, sosfreqs, db, set_rcparams, \
set_outdir
set_rcparams()
outdir = set_outdir()
Biquad_pe... | 0.468304 | 0.676633 |
# @file download.py
# @brief download
# @author libowei,<EMAIL>
# @version 0.2.00
# @date 2016-9-3
# 下载插件
import requests
import re
from bs4 import BeautifulSoup
import os
def download(url, fileName, className, session):
dir = os.getcwd() + "/" + className
file = os.getcwd() + "/" + className + "/" + fileNam... | download.py |
# @file download.py
# @brief download
# @author libowei,<EMAIL>
# @version 0.2.00
# @date 2016-9-3
# 下载插件
import requests
import re
from bs4 import BeautifulSoup
import os
def download(url, fileName, className, session):
dir = os.getcwd() + "/" + className
file = os.getcwd() + "/" + className + "/" + fileNam... | 0.07544 | 0.081813 |
import six
class TextDatasetMixin(object):
"""
Use multiple inheritance with this class and any other dataset
class in order to provide useful functionality for natural
language processing purposes.
The derived class is expected to have a `_vocabulary`, which
is a dictionary from words (strin... | pylearn2/sandbox/nlp/datasets/text.py | import six
class TextDatasetMixin(object):
"""
Use multiple inheritance with this class and any other dataset
class in order to provide useful functionality for natural
language processing purposes.
The derived class is expected to have a `_vocabulary`, which
is a dictionary from words (strin... | 0.900669 | 0.599983 |
import glob
import json
import os
import re
from pathlib import Path
from frontend.models import Course, GlobalConfig
from moodle.fieldnames import JsonFieldNames as Jn
from persistence.models import AssignmentFolder, SubmissionFolder, GradeFolder
from util import zipwrangler
class WorkTree:
DATA_FOLDER = '.mdt... | persistence/worktree.py | import glob
import json
import os
import re
from pathlib import Path
from frontend.models import Course, GlobalConfig
from moodle.fieldnames import JsonFieldNames as Jn
from persistence.models import AssignmentFolder, SubmissionFolder, GradeFolder
from util import zipwrangler
class WorkTree:
DATA_FOLDER = '.mdt... | 0.382026 | 0.071624 |
from decimal import Decimal
import django
from django.db import migrations, models
def assign_price_to_order(apps, schema_editor):
Order = apps.get_model("payments", "Order")
BerthProduct = apps.get_model("payments", "BerthProduct")
# Filter orders with BerthProducts without price
for order in Order... | payments/migrations/0018_add_price_tiers.py | from decimal import Decimal
import django
from django.db import migrations, models
def assign_price_to_order(apps, schema_editor):
Order = apps.get_model("payments", "Order")
BerthProduct = apps.get_model("payments", "BerthProduct")
# Filter orders with BerthProducts without price
for order in Order... | 0.619586 | 0.182899 |
import os
import sys
import subprocess
from pkg_resources import resource_filename
from options import parser
from utils import target, project
def addOptions(parser):
pass
def execCommand(args, following_args):
current_target = target.get_current_target()
if current_target:
project_name = pro... | kubos/flash.py |
import os
import sys
import subprocess
from pkg_resources import resource_filename
from options import parser
from utils import target, project
def addOptions(parser):
pass
def execCommand(args, following_args):
current_target = target.get_current_target()
if current_target:
project_name = pro... | 0.100054 | 0.048383 |
from asyncio import sleep
from telethon.tl.types import ChatBannedRights
from telethon.tl.functions.channels import EditBannedRequest
from telethon.tl.types import ChannelParticipantsKicked
from AyiinXd import CMD_HELP
from AyiinXd import CMD_HANDLER as cmd
from AyiinXd.ayiin import ayiin_cmd, eod, eor
from Stringyi... | AyiinXd/modules/yinsban.py |
from asyncio import sleep
from telethon.tl.types import ChatBannedRights
from telethon.tl.functions.channels import EditBannedRequest
from telethon.tl.types import ChannelParticipantsKicked
from AyiinXd import CMD_HELP
from AyiinXd import CMD_HANDLER as cmd
from AyiinXd.ayiin import ayiin_cmd, eod, eor
from Stringyi... | 0.295433 | 0.070272 |
import numpy as np
import pickle
import operator
# read in the Cornell Movie Dialogues data
f = open('movie_lines.txt', 'r')
lines = f.read().split('\n')
dic = {}
for line in lines:
if len(line.split('+++$+++')) > 4:
dic[int(line.split()[0][1:])] = line.split('+++$+++')[4:]
# sort the dialog... | get_train_data.py | import numpy as np
import pickle
import operator
# read in the Cornell Movie Dialogues data
f = open('movie_lines.txt', 'r')
lines = f.read().split('\n')
dic = {}
for line in lines:
if len(line.split('+++$+++')) > 4:
dic[int(line.split()[0][1:])] = line.split('+++$+++')[4:]
# sort the dialog... | 0.123683 | 0.318896 |
# Official Libraries
# My Modules
from stobu.infos.common import get_record_as_splitter, get_record_as_data_title
from stobu.syss import messages as msg
from stobu.types.action import ActType
from stobu.types.info import InfoRecord, InfosData, InfoType
from stobu.types.info import PersonInfo, PersonInfoType
from sto... | stobu/infos/personinfos.py |
# Official Libraries
# My Modules
from stobu.infos.common import get_record_as_splitter, get_record_as_data_title
from stobu.syss import messages as msg
from stobu.types.action import ActType
from stobu.types.info import InfoRecord, InfosData, InfoType
from stobu.types.info import PersonInfo, PersonInfoType
from sto... | 0.398641 | 0.291633 |
from __future__ import print_function
import os
import sys
import glob
from tqdm import tqdm
from pyiem.dep import read_slp
def main(argv):
"""Go Main Go"""
SCENARIO = int(argv[1])
SLOPE_THRESHOLD = float(argv[2])
# make needed mods
# use old one with mods if slope less than threshold
# repla... | scripts/switchgrass/modify_for_switchgrass.py | from __future__ import print_function
import os
import sys
import glob
from tqdm import tqdm
from pyiem.dep import read_slp
def main(argv):
"""Go Main Go"""
SCENARIO = int(argv[1])
SLOPE_THRESHOLD = float(argv[2])
# make needed mods
# use old one with mods if slope less than threshold
# repla... | 0.373304 | 0.092483 |
from .enaml_test_case import EnamlTestCase, required_method
class SelectionTestHelper(object):
""" Helper mixin for selection model test cases.
"""
@property
def widget(self):
""" Get the current toolkit "widget", as it may change.
"""
return self.component.abstract_obj.selec... | enaml/tests/old/components/selection_models.py | from .enaml_test_case import EnamlTestCase, required_method
class SelectionTestHelper(object):
""" Helper mixin for selection model test cases.
"""
@property
def widget(self):
""" Get the current toolkit "widget", as it may change.
"""
return self.component.abstract_obj.selec... | 0.847621 | 0.622459 |
from imapclient import IMAPClient
from dotenv import load_dotenv
import dropbox
import email
import logging
logger = logging.getLogger(__name__)
load_dotenv()
class EmailConnect:
def __init__(self, host, username, password):
self.host = host
self.username = username
self.password = passwo... | services.py | from imapclient import IMAPClient
from dotenv import load_dotenv
import dropbox
import email
import logging
logger = logging.getLogger(__name__)
load_dotenv()
class EmailConnect:
def __init__(self, host, username, password):
self.host = host
self.username = username
self.password = passwo... | 0.374562 | 0.051296 |
from statistics import mean
import numpy as np
import matplotlib.pyplot as plt
import seaborn as sns
plt.style.use("ggplot") # グラフのデザインを指定する
sns.set_palette('Set2') # グラフの色を指定する
import warnings
warnings.filterwarnings('ignore') # 警告メッセージを出ないようにしている
hakohige_labels=[]
hakohige_lawdata=[]
hakohige_data=[]
class ... | output/python_checkkeyplace.py | from statistics import mean
import numpy as np
import matplotlib.pyplot as plt
import seaborn as sns
plt.style.use("ggplot") # グラフのデザインを指定する
sns.set_palette('Set2') # グラフの色を指定する
import warnings
warnings.filterwarnings('ignore') # 警告メッセージを出ないようにしている
hakohige_labels=[]
hakohige_lawdata=[]
hakohige_data=[]
class ... | 0.289773 | 0.252894 |
import sublime
import sublime_plugin
import os.path
import json
def get_settings():
return sublime.load_settings('TodoPlease.sublime-settings')
class TodoPlease(sublime_plugin.WindowCommand):
def get_project_manager_projects(self):
with open(os.path.join(sublime.packages_path(), 'User', 'Projects', ... | TodoPlease.py |
import sublime
import sublime_plugin
import os.path
import json
def get_settings():
return sublime.load_settings('TodoPlease.sublime-settings')
class TodoPlease(sublime_plugin.WindowCommand):
def get_project_manager_projects(self):
with open(os.path.join(sublime.packages_path(), 'User', 'Projects', ... | 0.154695 | 0.093058 |
from __future__ import annotations
import asyncio
import os
import re
from glob import glob
from typing import Any, Callable, Union
from astropy.time import Time
from clu import Command
from cherno import config
from cherno.exceptions import ExposerError
from cherno.maskbits import GuiderStatus
from . import Che... | cherno/actor/exposer.py |
from __future__ import annotations
import asyncio
import os
import re
from glob import glob
from typing import Any, Callable, Union
from astropy.time import Time
from clu import Command
from cherno import config
from cherno.exceptions import ExposerError
from cherno.maskbits import GuiderStatus
from . import Che... | 0.905724 | 0.308203 |
import os
import sys
import logging
from datetime import datetime
import covid19_spider as covid19
import spider_customize as customize
import spider_hot as hot
import weibo_spider as weibo
import zhihu_spider as zhihu
from apscheduler.schedulers.background import BackgroundScheduler
from apscheduler.schedulers.block... | crawlers/beta/process_util.py | import os
import sys
import logging
from datetime import datetime
import covid19_spider as covid19
import spider_customize as customize
import spider_hot as hot
import weibo_spider as weibo
import zhihu_spider as zhihu
from apscheduler.schedulers.background import BackgroundScheduler
from apscheduler.schedulers.block... | 0.17989 | 0.075995 |
articles_data = [
{
'id': 4,
'day': 28,
'month': 2,
'year': 2017,
'image_name': 'mattcorallo.png',
'file_name': 'bitcoin-trustlessness',
'title': "Bitcoin's Diversity of Use-Cases and Security Models",
'author': '<NAME>',
'source': 'https://blu... | readingbitcoin/articles.py | articles_data = [
{
'id': 4,
'day': 28,
'month': 2,
'year': 2017,
'image_name': 'mattcorallo.png',
'file_name': 'bitcoin-trustlessness',
'title': "Bitcoin's Diversity of Use-Cases and Security Models",
'author': '<NAME>',
'source': 'https://blu... | 0.52829 | 0.407157 |
import pytest
from dynaconf.base import LazySettings
TOML = """
[default]
dynaconf_include = ["plugin1.toml", "plugin2.toml", "plugin2.toml"]
DEBUG = false
SERVER = "base.example.com"
PORT = 6666
[development]
DEBUG = false
SERVER = "dev.example.com"
[production]
DEBUG = false
SERVER = "prod.example.com"
"""
MIXED... | tests/test_nested_loading.py | import pytest
from dynaconf.base import LazySettings
TOML = """
[default]
dynaconf_include = ["plugin1.toml", "plugin2.toml", "plugin2.toml"]
DEBUG = false
SERVER = "base.example.com"
PORT = 6666
[development]
DEBUG = false
SERVER = "dev.example.com"
[production]
DEBUG = false
SERVER = "prod.example.com"
"""
MIXED... | 0.423339 | 0.166032 |
from __future__ import absolute_import
import parmed
from .leapify import Leapify
from .utils import tempfolder, which, easy_call
class AmberBuilder(Leapify):
''' Require many programs in AmberTools (pytraj, tleap, nab, ...)
Inheritance: AmberPDBFixer --> Leapify --> AmberBuilder
'''
def build_prote... | moledit/amber_builder.py | from __future__ import absolute_import
import parmed
from .leapify import Leapify
from .utils import tempfolder, which, easy_call
class AmberBuilder(Leapify):
''' Require many programs in AmberTools (pytraj, tleap, nab, ...)
Inheritance: AmberPDBFixer --> Leapify --> AmberBuilder
'''
def build_prote... | 0.451568 | 0.15662 |
import os
import sys
from select import select
import Pyro5.api
from sensor import Sensor
from tools import NameServer, Settings, debug, init, log_exception
DEFAULT_SETTINGS = {'max_loop_duration': 5}
MODULE_NAME = 'monitor'
class Monitor(Sensor):
def __init__(self):
self._states = {}
@Pyro5.api.e... | src/monitor.py |
import os
import sys
from select import select
import Pyro5.api
from sensor import Sensor
from tools import NameServer, Settings, debug, init, log_exception
DEFAULT_SETTINGS = {'max_loop_duration': 5}
MODULE_NAME = 'monitor'
class Monitor(Sensor):
def __init__(self):
self._states = {}
@Pyro5.api.e... | 0.416203 | 0.121738 |
import argparse
import datetime
from io import open
import logging
import os
import sys
import unicodecsv as csv
import peewee
import jinja2
"""
MIT License
Copyright (c) 2018 <NAME>, <NAME>
Please share comments and questions at:
https://github.com/PythonForensics/Learning-Python-for-Forensics
or email <EMAIL>
P... | Chapter05/file_lister_peewee.py | import argparse
import datetime
from io import open
import logging
import os
import sys
import unicodecsv as csv
import peewee
import jinja2
"""
MIT License
Copyright (c) 2018 <NAME>, <NAME>
Please share comments and questions at:
https://github.com/PythonForensics/Learning-Python-for-Forensics
or email <EMAIL>
P... | 0.412175 | 0.119562 |
from collections import defaultdict
import numpy as np
__all__ = ["get_traj_info"]
def get_traj_info(traj, lipid=None, lipid_atoms=None, resi_offset=0, nprot=1, protein_ref=None, lipid_ref=None):
"""Get trajectory information regarding atom/residue index and topologies.
Parameters
----------
traj :... | pylipid/util/trajectory.py | from collections import defaultdict
import numpy as np
__all__ = ["get_traj_info"]
def get_traj_info(traj, lipid=None, lipid_atoms=None, resi_offset=0, nprot=1, protein_ref=None, lipid_ref=None):
"""Get trajectory information regarding atom/residue index and topologies.
Parameters
----------
traj :... | 0.83957 | 0.478224 |
import pytest
import vcr
from requests.exceptions import HTTPError
from tests.conftest import FIXTURES_DIR
from phylm.clients.tmdb import TmdbClient
VCR_FIXTURES_DIR = f"{FIXTURES_DIR}/clients/tmdb"
class TestSearchMovies:
"""Tests for the `search_movies` method."""
@vcr.use_cassette(
f"{VCR_FIXTUR... | tests/unit/clients/test_tmdb.py | import pytest
import vcr
from requests.exceptions import HTTPError
from tests.conftest import FIXTURES_DIR
from phylm.clients.tmdb import TmdbClient
VCR_FIXTURES_DIR = f"{FIXTURES_DIR}/clients/tmdb"
class TestSearchMovies:
"""Tests for the `search_movies` method."""
@vcr.use_cassette(
f"{VCR_FIXTUR... | 0.687105 | 0.423696 |
import logging
import os
import click
import psycopg2
import psycopg2.extras
from mschematool import core
log = core.log
class PostgresLoggingDictCursor(psycopg2.extras.DictCursor):
"""Postgres cursor subclass: log all SQL executed in the database.
"""
def __init__(self, *args, **kwargs):
psy... | mschematool/executors/postgres.py | import logging
import os
import click
import psycopg2
import psycopg2.extras
from mschematool import core
log = core.log
class PostgresLoggingDictCursor(psycopg2.extras.DictCursor):
"""Postgres cursor subclass: log all SQL executed in the database.
"""
def __init__(self, *args, **kwargs):
psy... | 0.345547 | 0.126947 |
from __future__ import unicode_literals
import frappe
from frappe import _
from frappe.utils import flt, cstr
from frappe.desk.reportview import get_match_cond, get_filters_cond
from frappe.utils import nowdate
from collections import defaultdict
from frappe.model.naming import make_autoname
# test_records = frappe.ge... | ptmac/ptmac/custom_ptmac.py | from __future__ import unicode_literals
import frappe
from frappe import _
from frappe.utils import flt, cstr
from frappe.desk.reportview import get_match_cond, get_filters_cond
from frappe.utils import nowdate
from collections import defaultdict
from frappe.model.naming import make_autoname
# test_records = frappe.ge... | 0.199152 | 0.116789 |
import logging
import azure.functions as func
import os
import json
import pickle
import sklearn
from timeit import default_timer as timer
def main(req: func.HttpRequest, context: func.Context) -> func.HttpResponse:
logging.info('Python HTTP trigger function processed a request.')
localdir = context.function_... | Predict/__init__.py | import logging
import azure.functions as func
import os
import json
import pickle
import sklearn
from timeit import default_timer as timer
def main(req: func.HttpRequest, context: func.Context) -> func.HttpResponse:
logging.info('Python HTTP trigger function processed a request.')
localdir = context.function_... | 0.332961 | 0.081996 |
__author__ = '<NAME>'
import unittest
import threading
import time
import pg_simple
TEST_DB_DSN = 'dbname=pg_simple user=masroor'
class AbstractPgSimpleTestCase(unittest.TestCase):
def __init__(self, *args, **kwargs):
super(AbstractPgSimpleTestCase, self).__init__(*args, **kwargs)
# Kludge a... | tests/main.py |
__author__ = '<NAME>'
import unittest
import threading
import time
import pg_simple
TEST_DB_DSN = 'dbname=pg_simple user=masroor'
class AbstractPgSimpleTestCase(unittest.TestCase):
def __init__(self, *args, **kwargs):
super(AbstractPgSimpleTestCase, self).__init__(*args, **kwargs)
# Kludge a... | 0.475605 | 0.124399 |
def main():
ine = raw_input().split()
W = int(ine[0])
H = int(ine[1])
map = [[None]*W for i in xrange(H)]
for i in xrange (H):
s = str(raw_input())
for j in xrange (W):
if s[j] == '.':
map[i][j] = 0
elif s[j] == '/':
map[i][j]... | nypc/laserlamp.py | def main():
ine = raw_input().split()
W = int(ine[0])
H = int(ine[1])
map = [[None]*W for i in xrange(H)]
for i in xrange (H):
s = str(raw_input())
for j in xrange (W):
if s[j] == '.':
map[i][j] = 0
elif s[j] == '/':
map[i][j]... | 0.0967 | 0.477006 |
from brownie import *
from .contract_addresses import *
import time
# Custom parameters
TENPOW18 = 10 ** 18
# Number of tokens you wish to auction, you must be able to transfer these
AUCTION_TOKENS = 1000 * TENPOW18
AUCTION_DAYS = 20
# Dutch auctions start at a high price per token
AUCTION_START_PRICE = 100 * TENPOW1... | scripts/deploy_DutchSwapAuction.py | from brownie import *
from .contract_addresses import *
import time
# Custom parameters
TENPOW18 = 10 ** 18
# Number of tokens you wish to auction, you must be able to transfer these
AUCTION_TOKENS = 1000 * TENPOW18
AUCTION_DAYS = 20
# Dutch auctions start at a high price per token
AUCTION_START_PRICE = 100 * TENPOW1... | 0.557845 | 0.232506 |
# Octowire Framework
# Copyright (c) ImmunIT - <NAME> / <NAME>
# License: Apache 2.0
# <NAME> / Eresse <<EMAIL>>
# <NAME> / Ghecko <<EMAIL>>
import struct
from octowire.octowire import Octowire
class Logic(Octowire):
"""
Logic analyzer class.
"""
OPCODE = b"\x08"
OPERATION_SNIF... | octowire/logic.py |
# Octowire Framework
# Copyright (c) ImmunIT - <NAME> / <NAME>
# License: Apache 2.0
# <NAME> / Eresse <<EMAIL>>
# <NAME> / Ghecko <<EMAIL>>
import struct
from octowire.octowire import Octowire
class Logic(Octowire):
"""
Logic analyzer class.
"""
OPCODE = b"\x08"
OPERATION_SNIF... | 0.596786 | 0.097347 |