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 sys
import maya.OpenMaya as OpenMaya
import maya.OpenMayaMPx as OpenMayaMPx
import maya.cmds as cmds
__author__ = '<NAME>'
__copyright__ = 'Copyright (C) 2016 - Duiker Research Corp'
__license__ = ''
__maintainer__ = '<NAME>'
__email__ = '<EMAIL>'
__status__ = 'Production'
__major_version__ = '1'
__minor_versi... | plug-ins/pbrt/materials/hair.py | import sys
import maya.OpenMaya as OpenMaya
import maya.OpenMayaMPx as OpenMayaMPx
import maya.cmds as cmds
__author__ = '<NAME>'
__copyright__ = 'Copyright (C) 2016 - Duiker Research Corp'
__license__ = ''
__maintainer__ = '<NAME>'
__email__ = '<EMAIL>'
__status__ = 'Production'
__major_version__ = '1'
__minor_versi... | 0.153676 | 0.097476 |
from os import path as op
from uuid import uuid4
import numpy as np
import nibabel as nib
from matplotlib import pyplot as plt
from svgutils.transform import fromstring
from seaborn import color_palette
from nipype.interfaces.base import (
traits,
File,
isdefined,
)
from niworkflows.interfaces.report_b... | halfpipe/interface/report/imageplot.py |
from os import path as op
from uuid import uuid4
import numpy as np
import nibabel as nib
from matplotlib import pyplot as plt
from svgutils.transform import fromstring
from seaborn import color_palette
from nipype.interfaces.base import (
traits,
File,
isdefined,
)
from niworkflows.interfaces.report_b... | 0.579162 | 0.296508 |
import socket, threading, requests, time, os
from cryptography.fernet import Fernet
class ClientThread(threading.Thread):
def __init__(self, client_socket: socket.socket, client_address: tuple[str, int], server: "Server"):
threading.Thread.__init__(self)
self.client_socket = client_socket
self.client_add... | server.py | import socket, threading, requests, time, os
from cryptography.fernet import Fernet
class ClientThread(threading.Thread):
def __init__(self, client_socket: socket.socket, client_address: tuple[str, int], server: "Server"):
threading.Thread.__init__(self)
self.client_socket = client_socket
self.client_add... | 0.319546 | 0.055209 |
from six import iteritems
import anvil.node_types as nt
from anvil.sub_rig_templates import BipedFoot
from tests.base_test import TestBase, clean_up_scene, auto_save_result
import anvil.config as cfg
class TestBaseTemplateRigs(TestBase):
meta_data = {'name': 'eye', 'purpose': 'mvp'}
test_rig = None
TEMPLA... | tests/acceptance/test_biped_foot.py | from six import iteritems
import anvil.node_types as nt
from anvil.sub_rig_templates import BipedFoot
from tests.base_test import TestBase, clean_up_scene, auto_save_result
import anvil.config as cfg
class TestBaseTemplateRigs(TestBase):
meta_data = {'name': 'eye', 'purpose': 'mvp'}
test_rig = None
TEMPLA... | 0.727395 | 0.266268 |
import matplotlib
matplotlib.use('Agg')
import pandas as pd
import seaborn as sns
import sys
from matplotlib import pyplot as plt
import seaborn as sns
import pandas as pd
import numpy as np
from keyname import keyname as kn
from fileshash import fileshash as fsh
# open-type fonts
matplotlib.rcParams['pdf.fonttype'] =... | script/LowScoreDistributionPlot.py | import matplotlib
matplotlib.use('Agg')
import pandas as pd
import seaborn as sns
import sys
from matplotlib import pyplot as plt
import seaborn as sns
import pandas as pd
import numpy as np
from keyname import keyname as kn
from fileshash import fileshash as fsh
# open-type fonts
matplotlib.rcParams['pdf.fonttype'] =... | 0.355551 | 0.285574 |
import json
import uuid
from adjutant.common.tests import fake_clients
from rest_framework import status
from adjutant_moc.tests import base
class TestCreateProject(base.TestBase):
url = "/v1/moc/Projects"
demo_data = {
'project_name': 'demoproject1',
'description': 'demodescription',
... | adjutant_moc/tests/unit/test_apis/test_projects.py |
import json
import uuid
from adjutant.common.tests import fake_clients
from rest_framework import status
from adjutant_moc.tests import base
class TestCreateProject(base.TestBase):
url = "/v1/moc/Projects"
demo_data = {
'project_name': 'demoproject1',
'description': 'demodescription',
... | 0.462716 | 0.12363 |
import asyncio
import logging
import yaml
from core.exceptions import ParseTemplateError, LoginError
from core.template_parser.constants import POSSIBLE_CONSUMER_KWARGS
from core.template_parser.nodes import Root, Folder, Site
from core.template_parser.signal_handler import SignalHandler
logger = logging.getLogger(_... | core/template_parser/template.py | import asyncio
import logging
import yaml
from core.exceptions import ParseTemplateError, LoginError
from core.template_parser.constants import POSSIBLE_CONSUMER_KWARGS
from core.template_parser.nodes import Root, Folder, Site
from core.template_parser.signal_handler import SignalHandler
logger = logging.getLogger(_... | 0.380759 | 0.136954 |
from django.conf import settings
from django.db import migrations, models
import django.db.models.deletion
import django.utils.timezone
import uuid
class Migration(migrations.Migration):
initial = True
dependencies = [
migrations.swappable_dependency(settings.AUTH_USER_MODEL),
]
operations... | server/newconnectionwhodis/migrations/0001_initial.py |
from django.conf import settings
from django.db import migrations, models
import django.db.models.deletion
import django.utils.timezone
import uuid
class Migration(migrations.Migration):
initial = True
dependencies = [
migrations.swappable_dependency(settings.AUTH_USER_MODEL),
]
operations... | 0.526343 | 0.12424 |
import os, random
import numpy as np
from datetime import date
from psychopy import visual, event, core, monitors
from psychopy.hardware import joystick
from ResponseTrigger import *
from Solarized import * # Import solarized color palette
from BTS_Material import *
# Subject profile
today = date.today()
print('Today... | expRT/BTS_simulation.py | import os, random
import numpy as np
from datetime import date
from psychopy import visual, event, core, monitors
from psychopy.hardware import joystick
from ResponseTrigger import *
from Solarized import * # Import solarized color palette
from BTS_Material import *
# Subject profile
today = date.today()
print('Today... | 0.18429 | 0.129513 |
import argparse
import json
import os
import re
import sys
import urllib.parse
import adblock
from publicsuffixlist import PublicSuffixList
class AdblockSimulator:
def add_filter_list(self, filter_list, fmt='standard'):
for item in filter_list:
if os.path.isfile(item):
if not... | adblock_simulator.py |
import argparse
import json
import os
import re
import sys
import urllib.parse
import adblock
from publicsuffixlist import PublicSuffixList
class AdblockSimulator:
def add_filter_list(self, filter_list, fmt='standard'):
for item in filter_list:
if os.path.isfile(item):
if not... | 0.264168 | 0.059156 |
import re
flags = re.IGNORECASE | re.MULTILINE | re.VERBOSE
ref = r"[a-zA-Z0-9\-_]+"
section_finder = re.compile(
rf"""
(?:
\[(?P<comma_ref>{ref})\],\s*
)?
(?P<section>(?:section|sections|appendix|§)\s+)
(?P<num>[\d\.]*\d)\.?
(?:
\s+of\s+\[(?P<of_ref>{ref})\]
)?
""",
flags,
)
def linkify(text, spec_... | ietf_comments/linkify.py | import re
flags = re.IGNORECASE | re.MULTILINE | re.VERBOSE
ref = r"[a-zA-Z0-9\-_]+"
section_finder = re.compile(
rf"""
(?:
\[(?P<comma_ref>{ref})\],\s*
)?
(?P<section>(?:section|sections|appendix|§)\s+)
(?P<num>[\d\.]*\d)\.?
(?:
\s+of\s+\[(?P<of_ref>{ref})\]
)?
""",
flags,
)
def linkify(text, spec_... | 0.303525 | 0.368463 |
from __future__ import print_function
import sys
from lxml import etree
# noinspection PyProtectedMember
ElementTreeType = etree._ElementTree
# noinspection PyProtectedMember
ElementType = etree._Element
class CalsComparator(object):
def compare_files(self, src_path, exp_file):
src_tree = etree.parse(... | tests/converters/cals_comparator.py | from __future__ import print_function
import sys
from lxml import etree
# noinspection PyProtectedMember
ElementTreeType = etree._ElementTree
# noinspection PyProtectedMember
ElementType = etree._Element
class CalsComparator(object):
def compare_files(self, src_path, exp_file):
src_tree = etree.parse(... | 0.380989 | 0.39788 |
from dataclasses import dataclass
from typing import Iterable, Sequence, Tuple, Type
from gym_gridverse.action import Action
from gym_gridverse.geometry import Area, Orientation, Position, Shape
from gym_gridverse.grid_object import Color, GridObject, Hidden, NoneGridObject
from gym_gridverse.observation import Observ... | gym_gridverse/spaces.py | from dataclasses import dataclass
from typing import Iterable, Sequence, Tuple, Type
from gym_gridverse.action import Action
from gym_gridverse.geometry import Area, Orientation, Position, Shape
from gym_gridverse.grid_object import Color, GridObject, Hidden, NoneGridObject
from gym_gridverse.observation import Observ... | 0.862381 | 0.510558 |
from collections import namedtuple
from enum import IntEnum
from shared.const import CODING
ORDERTYPE = IntEnum('OrderType', 'Set Timer Event Create Destroy Condition '
'Move Setobj Watchdog')
Condition = namedtuple("Condition", "target event once")
class Order:
""" A change to b... | src/shared/orders.py | from collections import namedtuple
from enum import IntEnum
from shared.const import CODING
ORDERTYPE = IntEnum('OrderType', 'Set Timer Event Create Destroy Condition '
'Move Setobj Watchdog')
Condition = namedtuple("Condition", "target event once")
class Order:
""" A change to b... | 0.433142 | 0.265851 |
from tensorflow.keras import backend as K
from tensorflow.keras.models import Model
from tensorflow.keras.layers import Permute, Flatten
from tensorflow.keras.layers import MaxPooling2D, MaxPooling1D
from tensorflow.keras.layers import Reshape, Dense, Input, Dropout, Activation, LSTM, Conv2D,\
... | code/Septor.py | from tensorflow.keras import backend as K
from tensorflow.keras.models import Model
from tensorflow.keras.layers import Permute, Flatten
from tensorflow.keras.layers import MaxPooling2D, MaxPooling1D
from tensorflow.keras.layers import Reshape, Dense, Input, Dropout, Activation, LSTM, Conv2D,\
... | 0.901401 | 0.666219 |
import os
import sys
import time
import string
import locale
import numpy as np
import pandas as pd
import hdbscan
import _utils as utils
import ServerSideExtension_pb2 as SSE
# Add Generated folder to module path
PARENT_DIR = os.path.dirname(os.path.dirname(os.path.abspath(__file__)))
sys.path.append(os.path.join(PAR... | core/_clustering.py | import os
import sys
import time
import string
import locale
import numpy as np
import pandas as pd
import hdbscan
import _utils as utils
import ServerSideExtension_pb2 as SSE
# Add Generated folder to module path
PARENT_DIR = os.path.dirname(os.path.dirname(os.path.abspath(__file__)))
sys.path.append(os.path.join(PAR... | 0.539226 | 0.268779 |
import argparse
from collections import defaultdict
import logging
import json
import os.path
import shlex
from multiprocessing import Pool
from packaging.specifiers import (
Specifier,
InvalidSpecifier,
LegacySpecifier,
)
from packaging.utils import canonicalize_name
import pkg_resources
from pipsqueak.e... | pipsqueak/main.py | import argparse
from collections import defaultdict
import logging
import json
import os.path
import shlex
from multiprocessing import Pool
from packaging.specifiers import (
Specifier,
InvalidSpecifier,
LegacySpecifier,
)
from packaging.utils import canonicalize_name
import pkg_resources
from pipsqueak.e... | 0.435781 | 0.073497 |
from types import NoneType
__all__ = ('Const', 'C')
class Const(object):
creation_counter = 0
def __init__(self, id_or_attrs_dict=None, attrs_dict=None, **attrs_kwargs):
assert isinstance(id_or_attrs_dict, (int, dict, NoneType)), \
'First arg (if given) should be id integer or attributes... | const_choice/const.py | from types import NoneType
__all__ = ('Const', 'C')
class Const(object):
creation_counter = 0
def __init__(self, id_or_attrs_dict=None, attrs_dict=None, **attrs_kwargs):
assert isinstance(id_or_attrs_dict, (int, dict, NoneType)), \
'First arg (if given) should be id integer or attributes... | 0.602412 | 0.23053 |
# Python modules
import re
from collections import defaultdict
# NOC modules
from noc.lib.app.extdocapplication import ExtDocApplication, view
from noc.main.models.label import Label
from noc.core.translation import ugettext as _
class LabelApplication(ExtDocApplication):
"""
Label application
"""
... | services/web/apps/main/label/views.py |
# Python modules
import re
from collections import defaultdict
# NOC modules
from noc.lib.app.extdocapplication import ExtDocApplication, view
from noc.main.models.label import Label
from noc.core.translation import ugettext as _
class LabelApplication(ExtDocApplication):
"""
Label application
"""
... | 0.513425 | 0.245786 |
import numpy as np
import pandas as pd
import os
import matplotlib.pyplot as plt
from datetime import date,datetime
import logging
import torch
from torch import nn
from torch import optim
from torch.autograd import Variable
device = torch.device("cuda" if torch.cuda.is_available() else "cpu")
device
# ------------... | 2019_12_16/FunkSVD.py | import numpy as np
import pandas as pd
import os
import matplotlib.pyplot as plt
from datetime import date,datetime
import logging
import torch
from torch import nn
from torch import optim
from torch.autograd import Variable
device = torch.device("cuda" if torch.cuda.is_available() else "cpu")
device
# ------------... | 0.457137 | 0.479747 |
from collections import OrderedDict
import re
import numpy as np
from PyQt5 import QtCore, QtGui, QtWidgets
from .utils import *
PC_RE = re.compile('(.+) \(\d+\)')
class VarEditor(object):
def __init__(self, var=None):
if var is None:
self.variable = None
self.type = 0
el... | gui/layouts/var_editor.py | from collections import OrderedDict
import re
import numpy as np
from PyQt5 import QtCore, QtGui, QtWidgets
from .utils import *
PC_RE = re.compile('(.+) \(\d+\)')
class VarEditor(object):
def __init__(self, var=None):
if var is None:
self.variable = None
self.type = 0
el... | 0.458591 | 0.061143 |
from django.conf import settings
from django.db import migrations, models
import django.db.models.deletion
class Migration(migrations.Migration):
dependencies = [
('core', '0006_remove_work_user'),
]
operations = [
migrations.AddField(
model_name='work',
name='ab... | app/core/migrations/0007_auto_20190103_0513.py |
from django.conf import settings
from django.db import migrations, models
import django.db.models.deletion
class Migration(migrations.Migration):
dependencies = [
('core', '0006_remove_work_user'),
]
operations = [
migrations.AddField(
model_name='work',
name='ab... | 0.588298 | 0.136781 |
import context
import io
import json
import requests
import numpy as np
import pandas as pd
import xarray as xr
from glob import glob
from pathlib import Path
from netCDF4 import Dataset
import matplotlib.pyplot as plt
from wrf import ll_to_xy, xy_to_ll
from datetime import datetime, date, timedelta
from context impo... | utils/make_intercomp.py | import context
import io
import json
import requests
import numpy as np
import pandas as pd
import xarray as xr
from glob import glob
from pathlib import Path
from netCDF4 import Dataset
import matplotlib.pyplot as plt
from wrf import ll_to_xy, xy_to_ll
from datetime import datetime, date, timedelta
from context impo... | 0.129568 | 0.284446 |
import numpy as np
def func(x):
y = np.sum(x**2)
return y
class BasicPSO:
def __init__(self, num_params,
lbound,
ubound,
w = 0.5,
c1 = 1,
c2 = 2,
popsize = 15,
ada_w... | src/SwarmTools.py | import numpy as np
def func(x):
y = np.sum(x**2)
return y
class BasicPSO:
def __init__(self, num_params,
lbound,
ubound,
w = 0.5,
c1 = 1,
c2 = 2,
popsize = 15,
ada_w... | 0.328314 | 0.373105 |
import json
from alipay.aop.api.constant.ParamConstants import *
class MybankCreditLoanapplyQrcodeCreateModel(object):
def __init__(self):
self._bank_card_category = None
self._beneficiary_account = None
self._beneficiary_name = None
self._deposit_bank = None
self._deposi... | alipay/aop/api/domain/MybankCreditLoanapplyQrcodeCreateModel.py | import json
from alipay.aop.api.constant.ParamConstants import *
class MybankCreditLoanapplyQrcodeCreateModel(object):
def __init__(self):
self._bank_card_category = None
self._beneficiary_account = None
self._beneficiary_name = None
self._deposit_bank = None
self._deposi... | 0.512693 | 0.114146 |
import numpy as np
def assignment_to_index(assignment, card):
return np.ravel_multi_index(assignment, card)
def index_to_assignment(index, card):
return np.asarray(np.unravel_index(index, card), dtype=np.int64)
def get_cardinality(graph, *identifiers):
"""
Get the cardinality of all nodes in given... | apogee/factors/discrete/operations/utils.py | import numpy as np
def assignment_to_index(assignment, card):
return np.ravel_multi_index(assignment, card)
def index_to_assignment(index, card):
return np.asarray(np.unravel_index(index, card), dtype=np.int64)
def get_cardinality(graph, *identifiers):
"""
Get the cardinality of all nodes in given... | 0.799638 | 0.738315 |
import argparse
import math
import datetime
import sys
import ephem
import ephem.cities
def fatal(text):
print(sys.argv[0] + ": " + text)
sys.exit(1)
def query(city, **kwargs):
result = ""
try:
obs = ephem.cities.lookup(city)
except ValueError as ve:
return ve
except Excepti... | pysol.py | import argparse
import math
import datetime
import sys
import ephem
import ephem.cities
def fatal(text):
print(sys.argv[0] + ": " + text)
sys.exit(1)
def query(city, **kwargs):
result = ""
try:
obs = ephem.cities.lookup(city)
except ValueError as ve:
return ve
except Excepti... | 0.37319 | 0.18628 |
import logging
import os
import subprocess
import sys
from datetime import datetime
import time
import gphoto2 as gp
def send_scp(save_path, filename):
#This function can be used to send the images from the camera
#to a remote storage location via SCP
#Define your destination path here (on the remote mac... | timelapse.py | import logging
import os
import subprocess
import sys
from datetime import datetime
import time
import gphoto2 as gp
def send_scp(save_path, filename):
#This function can be used to send the images from the camera
#to a remote storage location via SCP
#Define your destination path here (on the remote mac... | 0.273574 | 0.164516 |
import contextlib
import csv
import json
import logging
import os
import re
from pathlib import Path
import click
import pandas as pd
from utils import make_mongodb, mongodb
log_format = logging.Formatter(
"[%(asctime)s][%(filename)s:%(lineno)4s - %(funcName)10s()] %(message)s"
)
handler = logging.StreamHandler()... | MongoDB/import.py | import contextlib
import csv
import json
import logging
import os
import re
from pathlib import Path
import click
import pandas as pd
from utils import make_mongodb, mongodb
log_format = logging.Formatter(
"[%(asctime)s][%(filename)s:%(lineno)4s - %(funcName)10s()] %(message)s"
)
handler = logging.StreamHandler()... | 0.192995 | 0.094845 |
version = '0.0.4'
author = """
Emanuele '<NAME>'
Email:<lele [at] quasinormale [dot] it>
Github/Twitter: eldios
"""
from pycodicefiscale import codicefiscale as cf
import datetime
from random import choice as randchoice
from random import randint
import argparse
# script description
parser = argparse.ArgumentParser... | rcfg.py |
version = '0.0.4'
author = """
Emanuele '<NAME>'
Email:<lele [at] quasinormale [dot] it>
Github/Twitter: eldios
"""
from pycodicefiscale import codicefiscale as cf
import datetime
from random import choice as randchoice
from random import randint
import argparse
# script description
parser = argparse.ArgumentParser... | 0.25488 | 0.114864 |
import pickle
import tensorflow as tf
from sklearn.model_selection import train_test_split
class MacOSFile():
"""Workaround for issue 24658 (https://bugs.python.org/issue24658).
Source: https://stackoverflow.com/questions/31468117/python-3-can-pickle- \
handle-byte-objects-larger-than-4gb.
"""
... | algo_archive/old_ml_algos/iteration-unus.py | import pickle
import tensorflow as tf
from sklearn.model_selection import train_test_split
class MacOSFile():
"""Workaround for issue 24658 (https://bugs.python.org/issue24658).
Source: https://stackoverflow.com/questions/31468117/python-3-can-pickle- \
handle-byte-objects-larger-than-4gb.
"""
... | 0.720762 | 0.351283 |
from datadog_api_client.v1.model_utils import (
ModelNormal,
cached_property,
)
def lazy_import():
from datadog_api_client.v1.model.service_summary_widget_definition_type import ServiceSummaryWidgetDefinitionType
from datadog_api_client.v1.model.widget_service_summary_display_format import WidgetSer... | code/venv/lib/python3.8/site-packages/datadog_api_client/v1/model/service_summary_widget_definition.py |
from datadog_api_client.v1.model_utils import (
ModelNormal,
cached_property,
)
def lazy_import():
from datadog_api_client.v1.model.service_summary_widget_definition_type import ServiceSummaryWidgetDefinitionType
from datadog_api_client.v1.model.widget_service_summary_display_format import WidgetSer... | 0.793626 | 0.225918 |
from cryptography.fernet import Fernet
import os
import base64
from cryptography.hazmat.backends import default_backend
from cryptography.hazmat.primitives import hashes
from cryptography.hazmat.primitives.kdf.pbkdf2 import PBKDF2HMAC
print('\nthe password that you will Enter below will generate a unique key to Encryp... | main.py | from cryptography.fernet import Fernet
import os
import base64
from cryptography.hazmat.backends import default_backend
from cryptography.hazmat.primitives import hashes
from cryptography.hazmat.primitives.kdf.pbkdf2 import PBKDF2HMAC
print('\nthe password that you will Enter below will generate a unique key to Encryp... | 0.202759 | 0.111459 |
from __future__ import annotations
import re
from dataclasses import dataclass
from typing import Any, Awaitable, Callable
from textwrap import dedent
from virtool_workflow.utils import coerce_to_coroutine_function
def get_display_name(function: Callable[..., Any]):
"""
Get the display name for a step funct... | virtool_workflow/_steps.py | from __future__ import annotations
import re
from dataclasses import dataclass
from typing import Any, Awaitable, Callable
from textwrap import dedent
from virtool_workflow.utils import coerce_to_coroutine_function
def get_display_name(function: Callable[..., Any]):
"""
Get the display name for a step funct... | 0.899661 | 0.324262 |
from __future__ import absolute_import, division, print_function
import pytest
from six import with_metaclass
from proxo.messages import RegisterProxies, MessageProxy, Map
@pytest.fixture
def d():
return {'a': 1,
'b': [{'j': 9},
{'g': 7, 'h': 8}],
'c': {'d': 4,
... | proxo/tests/test_messages.py | from __future__ import absolute_import, division, print_function
import pytest
from six import with_metaclass
from proxo.messages import RegisterProxies, MessageProxy, Map
@pytest.fixture
def d():
return {'a': 1,
'b': [{'j': 9},
{'g': 7, 'h': 8}],
'c': {'d': 4,
... | 0.802246 | 0.697274 |
import opcodetools.cpu.base_assembly
import opcodetools.cpu.base_disassembly
import opcodetools.cpu.opcode
'''
The CPU class is a list of individual opcodes. An opcode has several parts:
- DATA the byte format of the opcode in memory
- MNEMONIC the assembly language representation
- USE how the individua... | opcodetools/cpu/base_cpu.py | import opcodetools.cpu.base_assembly
import opcodetools.cpu.base_disassembly
import opcodetools.cpu.opcode
'''
The CPU class is a list of individual opcodes. An opcode has several parts:
- DATA the byte format of the opcode in memory
- MNEMONIC the assembly language representation
- USE how the individua... | 0.801004 | 0.57069 |
from collections import OrderedDict
import logging
from pyidf.helper import DataObject
logger = logging.getLogger("pyidf")
logger.addHandler(logging.NullHandler())
class ZoneInfiltrationDesignFlowRate(DataObject):
""" Corresponds to IDD object `ZoneInfiltration:DesignFlowRate`
Infiltration is specified... | pyidf/zone_airflow.py | from collections import OrderedDict
import logging
from pyidf.helper import DataObject
logger = logging.getLogger("pyidf")
logger.addHandler(logging.NullHandler())
class ZoneInfiltrationDesignFlowRate(DataObject):
""" Corresponds to IDD object `ZoneInfiltration:DesignFlowRate`
Infiltration is specified... | 0.802942 | 0.260828 |
from __future__ import print_function
import os
import sys
import six
import elex
import ujson as json
import time
import datetime
from elex import cache
from elex.exceptions import APAPIKeyException
from pymongo import MongoClient
class UnicodeMixin(object):
"""
Python 2 + 3 compatibility for __unicode__
... | elex/api/utils.py | from __future__ import print_function
import os
import sys
import six
import elex
import ujson as json
import time
import datetime
from elex import cache
from elex.exceptions import APAPIKeyException
from pymongo import MongoClient
class UnicodeMixin(object):
"""
Python 2 + 3 compatibility for __unicode__
... | 0.482429 | 0.084229 |
import time
import json
from brownie import *
from rich.console import Console
from assistant.rewards.rewards_utils import calculate_sett_balances
from assistant.subgraph.client import fetch_wallet_balances
from config.badger_config import badger_config
from rich.console import Console
from scripts.systems.badger_syste... | scripts/status/yearn_whitelist.py | import time
import json
from brownie import *
from rich.console import Console
from assistant.rewards.rewards_utils import calculate_sett_balances
from assistant.subgraph.client import fetch_wallet_balances
from config.badger_config import badger_config
from rich.console import Console
from scripts.systems.badger_syste... | 0.238994 | 0.143098 |
import logging
import sys
_scheduler_supported = True
try:
import win32com.client
from pythoncom import com_error
except ImportError:
_scheduler_supported = False
log = logging.getLogger("cfn.init")
def set_reboot_trigger():
if not _scheduler_supported:
log.debug("Not setting a reboot trigge... | cfnbootstrap/platform_utils.py |
import logging
import sys
_scheduler_supported = True
try:
import win32com.client
from pythoncom import com_error
except ImportError:
_scheduler_supported = False
log = logging.getLogger("cfn.init")
def set_reboot_trigger():
if not _scheduler_supported:
log.debug("Not setting a reboot trigge... | 0.332852 | 0.08061 |
from zuki.policies.feed_forward_policy import FeedForwardPolicy
from zuki.policy_gradient_methods.monte_carlo import MonteCarloPolicyGradient
from zuki.envs.simple_continuous_action_env import SimpleContinuousActionEnv
from typing import List
def test_continuous_action_env_positive():
"""
Test continuous acti... | test/test_simple.py | from zuki.policies.feed_forward_policy import FeedForwardPolicy
from zuki.policy_gradient_methods.monte_carlo import MonteCarloPolicyGradient
from zuki.envs.simple_continuous_action_env import SimpleContinuousActionEnv
from typing import List
def test_continuous_action_env_positive():
"""
Test continuous acti... | 0.908755 | 0.525795 |
__author__ = '<NAME>'
import ast
import json
import os
import re
import time
import unittest
import warnings
from unittest.util import safe_repr
from uuid import uuid4
from flask import url_for
from flask.wrappers import Response
from bootini_star import app, version
from bootini_star.email import unittest_address
f... | tests/base.py | __author__ = '<NAME>'
import ast
import json
import os
import re
import time
import unittest
import warnings
from unittest.util import safe_repr
from uuid import uuid4
from flask import url_for
from flask.wrappers import Response
from bootini_star import app, version
from bootini_star.email import unittest_address
f... | 0.393152 | 0.112332 |
import jsonlines
import pymongo
import os
from posts import MongoDatabase
"""
This takes a very long time to run - in the order of a few days
"""
DIR_PATH = os.path.dirname(os.path.realpath(__file__))
FILE_PATH = os.path.join(DIR_PATH, "data")
MONGO_CLIENT = 'localhost'
DB_NAME = 'reddit'
COLLECTION_NAME = 'subred... | geolocate/bin/subreddit_data.py | import jsonlines
import pymongo
import os
from posts import MongoDatabase
"""
This takes a very long time to run - in the order of a few days
"""
DIR_PATH = os.path.dirname(os.path.realpath(__file__))
FILE_PATH = os.path.join(DIR_PATH, "data")
MONGO_CLIENT = 'localhost'
DB_NAME = 'reddit'
COLLECTION_NAME = 'subred... | 0.170197 | 0.165526 |
from unittest.mock import patch
import unittest
import json
from stix_shifter_modules.sentinelone.entry_point import EntryPoint
from stix_shifter.stix_transmission import stix_transmission
from requests.exceptions import ConnectionError
class PingResponse:
""" class for capturing response"""
def __init__(self,... | stix_shifter_modules/sentinelone/tests/stix_transmission/test_sentinelone.py | from unittest.mock import patch
import unittest
import json
from stix_shifter_modules.sentinelone.entry_point import EntryPoint
from stix_shifter.stix_transmission import stix_transmission
from requests.exceptions import ConnectionError
class PingResponse:
""" class for capturing response"""
def __init__(self,... | 0.710327 | 0.21712 |
import httplib
import os
import shutil
import tempfile
import unittest
import iap_watcher
from jsobject import Object
class TestIapVerifier(unittest.TestCase):
class TestMetadataWatcher(Object):
"""Used to mock out metadata watcher."""
def GetMetadata(self, **args):
return self.result_value_
de... | iap_watcher/iap_watcher_test.py | import httplib
import os
import shutil
import tempfile
import unittest
import iap_watcher
from jsobject import Object
class TestIapVerifier(unittest.TestCase):
class TestMetadataWatcher(Object):
"""Used to mock out metadata watcher."""
def GetMetadata(self, **args):
return self.result_value_
de... | 0.532425 | 0.24897 |
import argparse
import datetime
import os
import sys
sys.path.append(os.path.join(os.getcwd(), '../common'))
from runner_helper2 import *
from logtable_def import *
MOCK = False
RERUN_TESTS = False
NUM_EPOCH = 3
TIMESTAMP = datetime.datetime.now().strftime("%Y-%m-%d_%H-%M-%S")
HERE = os.path.abspath(os.path.dirname(... | exp/table4/run.py | import argparse
import datetime
import os
import sys
sys.path.append(os.path.join(os.getcwd(), '../common'))
from runner_helper2 import *
from logtable_def import *
MOCK = False
RERUN_TESTS = False
NUM_EPOCH = 3
TIMESTAMP = datetime.datetime.now().strftime("%Y-%m-%d_%H-%M-%S")
HERE = os.path.abspath(os.path.dirname(... | 0.29209 | 0.141786 |
import torch
import qelos_core as q
import os
def load_data(p="../../datasets/wikitext2/",
batsize=100, eval_batsize=10, seqlen=35):
class Dictionary(object):
def __init__(self):
self.word2idx = {}
self.idx2word = []
def add_word(self, word):
if ... | qelos_core/scripts/lm.py | import torch
import qelos_core as q
import os
def load_data(p="../../datasets/wikitext2/",
batsize=100, eval_batsize=10, seqlen=35):
class Dictionary(object):
def __init__(self):
self.word2idx = {}
self.idx2word = []
def add_word(self, word):
if ... | 0.798069 | 0.394551 |
from udp_client import *
import sys
from ConfigParser import SafeConfigParser
if sys.version_info < (3, 0):
from Tkinter import *
from tkMessageBox import *
from tkColorChooser import askcolor
import ttk as ttk
else:
from tkinter import *
from tkinter.messagebox import *
from tkinter.colorc... | main.py | from udp_client import *
import sys
from ConfigParser import SafeConfigParser
if sys.version_info < (3, 0):
from Tkinter import *
from tkMessageBox import *
from tkColorChooser import askcolor
import ttk as ttk
else:
from tkinter import *
from tkinter.messagebox import *
from tkinter.colorc... | 0.184437 | 0.097993 |
from abc import ABC, abstractmethod
class CommonInterfaceNsd(ABC):
"""
NSD Management Interfaces
Base: {apiRoot}/nsd/v1
"""
def get_ns_descriptors(self):
""" NSD Management Interface - NS Descriptors
/ns_descriptors:
GET - Query information about multip... | wrappers/CommonInterface/nsd.py | from abc import ABC, abstractmethod
class CommonInterfaceNsd(ABC):
"""
NSD Management Interfaces
Base: {apiRoot}/nsd/v1
"""
def get_ns_descriptors(self):
""" NSD Management Interface - NS Descriptors
/ns_descriptors:
GET - Query information about multip... | 0.652352 | 0.178741 |
from pathlib import Path
from dataclasses import dataclass
from typing import Union
import toml
from semver import VersionInfo
from typeguard import typechecked
from wheel_inspect import inspect_wheel
from balsa import get_logger
from pyship import __application_name__ as pyship_application_name
from pyship import py... | pyship/app_info.py | from pathlib import Path
from dataclasses import dataclass
from typing import Union
import toml
from semver import VersionInfo
from typeguard import typechecked
from wheel_inspect import inspect_wheel
from balsa import get_logger
from pyship import __application_name__ as pyship_application_name
from pyship import py... | 0.507812 | 0.092565 |
import gc
import random
import torch
import torch.backends.cudnn
from torch.utils.data import DataLoader
from tqdm import tqdm
import numpy as np
import constants
from constants import DUMP_DIR, DEVICE, TEST_BATCH_SIZE, TOT_IMG_NUM, TEST_SUB_BATCH_SIZE, TEST_DATA_LOAD_WORKERS
from datasets.eval_dataset import EvalDat... | evaluator_graph.py | import gc
import random
import torch
import torch.backends.cudnn
from torch.utils.data import DataLoader
from tqdm import tqdm
import numpy as np
import constants
from constants import DUMP_DIR, DEVICE, TEST_BATCH_SIZE, TOT_IMG_NUM, TEST_SUB_BATCH_SIZE, TEST_DATA_LOAD_WORKERS
from datasets.eval_dataset import EvalDat... | 0.558688 | 0.175821 |
import copy
from hearthbreaker.effects.minion import Draw
import hearthbreaker.targeting
from hearthbreaker.constants import CHARACTER_CLASS, CARD_RARITY
from hearthbreaker.game_objects import Card, Minion, MinionCard, SecretCard
class AvengingWrath(Card):
def __init__(self):
super().__init__("Avenging Wr... | hearthbreaker/cards/spells/paladin.py | import copy
from hearthbreaker.effects.minion import Draw
import hearthbreaker.targeting
from hearthbreaker.constants import CHARACTER_CLASS, CARD_RARITY
from hearthbreaker.game_objects import Card, Minion, MinionCard, SecretCard
class AvengingWrath(Card):
def __init__(self):
super().__init__("Avenging Wr... | 0.489992 | 0.141548 |
import os
import subprocess
from argparse import ArgumentParser
from datetime import datetime
def build_parser():
parser = ArgumentParser()
parser.add_argument('--stanfordpath',
dest='pathtostanfordfolder',
default="../data/stanfordfiles/",
... | userstudy/src/createdogspeciesdata.py | import os
import subprocess
from argparse import ArgumentParser
from datetime import datetime
def build_parser():
parser = ArgumentParser()
parser.add_argument('--stanfordpath',
dest='pathtostanfordfolder',
default="../data/stanfordfiles/",
... | 0.220678 | 0.099821 |
import sys
import matplotlib.pyplot as plt
import numpy as np
MB = 1048576
data = {
"lens": [],
"cpu_times": [],
"sending_times": [],
"cpu_usages": [],
"lats": []
}
data_packets = {
"lens": [],
"bytes_trans": [],
"packets": [],
"avg_packet_size": []
}
oper_costs = {
"movistar":... | make_plots.py | import sys
import matplotlib.pyplot as plt
import numpy as np
MB = 1048576
data = {
"lens": [],
"cpu_times": [],
"sending_times": [],
"cpu_usages": [],
"lats": []
}
data_packets = {
"lens": [],
"bytes_trans": [],
"packets": [],
"avg_packet_size": []
}
oper_costs = {
"movistar":... | 0.243822 | 0.370083 |
import datetime
import json
import logging
import shutil
import subprocess
logger = logging.getLogger(__name__)
class ContCommandResult:
"""A representation engine command results."""
def __init__(self, exit_status=None, stdout=None, stderr=None, command=None):
self.exit_status = exit_status
... | src/rhel_containers/engine.py | import datetime
import json
import logging
import shutil
import subprocess
logger = logging.getLogger(__name__)
class ContCommandResult:
"""A representation engine command results."""
def __init__(self, exit_status=None, stdout=None, stderr=None, command=None):
self.exit_status = exit_status
... | 0.702632 | 0.083106 |
import requests
from rootinsurance.quote import GadgetQuote, TermQuote
class RootInsurance(object):
def __init__(self, sandbox=False, key=None):
self._url = "https://sandbox.root.co.za"
self._base = self._url + "/v1/insurance/"
self._key = key
def post(self, path, json=None, **kwargs... | roswell/rootinsurance/root.py | import requests
from rootinsurance.quote import GadgetQuote, TermQuote
class RootInsurance(object):
def __init__(self, sandbox=False, key=None):
self._url = "https://sandbox.root.co.za"
self._base = self._url + "/v1/insurance/"
self._key = key
def post(self, path, json=None, **kwargs... | 0.430866 | 0.063222 |
z test zaimportuj support
zaimportuj re
zaimportuj sys
zaimportuj types
zaimportuj unittest
def get_tb():
spróbuj:
podnieś OSError()
wyjąwszy:
zwróć sys.exc_info()[2]
klasa Context:
def __enter__(self):
zwróć self
def __exit__(self, exc_type, exc_value, exc_tb):
zwróć... | Lib/test/test_raise.py | z test zaimportuj support
zaimportuj re
zaimportuj sys
zaimportuj types
zaimportuj unittest
def get_tb():
spróbuj:
podnieś OSError()
wyjąwszy:
zwróć sys.exc_info()[2]
klasa Context:
def __enter__(self):
zwróć self
def __exit__(self, exc_type, exc_value, exc_tb):
zwróć... | 0.400984 | 0.547222 |
from flask import Flask, render_template, request
from static.plt.graph import build_graph
from urllib.request import urlopen
from datetime import date, timedelta
import csv
import json
app = Flask(__name__)
listaNomeBancos = []
listaTaxaBancos = []
@app.route('/')
def index():
return render_template('index.htm... | app.py | from flask import Flask, render_template, request
from static.plt.graph import build_graph
from urllib.request import urlopen
from datetime import date, timedelta
import csv
import json
app = Flask(__name__)
listaNomeBancos = []
listaTaxaBancos = []
@app.route('/')
def index():
return render_template('index.htm... | 0.298389 | 0.110615 |
#Compute AUC and Precision.
import random
import numpy as np
import pickle
import json
from argparse import ArgumentParser,ArgumentDefaultsHelpFormatter
def AUC(task,nonexist,authors,times,node_vector,missing_edges,confs=None):
"""
Compute sample AUC.
:param task: the task we need to compute,cp/re/conf
... | Task3/evaluation4task3.py | #Compute AUC and Precision.
import random
import numpy as np
import pickle
import json
from argparse import ArgumentParser,ArgumentDefaultsHelpFormatter
def AUC(task,nonexist,authors,times,node_vector,missing_edges,confs=None):
"""
Compute sample AUC.
:param task: the task we need to compute,cp/re/conf
... | 0.492432 | 0.458288 |
def velocity_from_acceleration(ax, ay, az, t):
"""
Estimate velocity from accelerometer readings.
Parameters
----------
ax : list or numpy array of floats
accelerometer x-axis data
ay : list or numpy array of floats
accelerometer y-axis data
az : list or numpy array of float... | SM_openSMILE/openSMILE_runSM/mhealthx/mhealthx/xtras/dead_reckon.py | def velocity_from_acceleration(ax, ay, az, t):
"""
Estimate velocity from accelerometer readings.
Parameters
----------
ax : list or numpy array of floats
accelerometer x-axis data
ay : list or numpy array of floats
accelerometer y-axis data
az : list or numpy array of float... | 0.879613 | 0.60996 |
from ..DyStockAccountManager import *
from ....Common.DyStockCommon import *
class DyStockGtjaAccountManager(DyStockAccountManager):
"""
国泰君安Web管理类
由于Web接口不同数据之间的异步性,推送券商原始数据时,一定要保证顺序。
委托->成交->资金->持仓
"""
broker = 'gtja'
brokerName = '国泰君安'
headerNameMap = {'capital': {... | Stock/Trade/AccountManager/Broker/DyStockGtjaAccountManager.py | from ..DyStockAccountManager import *
from ....Common.DyStockCommon import *
class DyStockGtjaAccountManager(DyStockAccountManager):
"""
国泰君安Web管理类
由于Web接口不同数据之间的异步性,推送券商原始数据时,一定要保证顺序。
委托->成交->资金->持仓
"""
broker = 'gtja'
brokerName = '国泰君安'
headerNameMap = {'capital': {... | 0.215186 | 0.135175 |
import Init
import Modeling
import System
import Time
class Subsystem:
"""This class represents the the agents that are assigned to the subsystems.
The agents can predict the behavior of their subsystems and store the
current costs, coupling variables and states.
Parameters
----------
sys_id ... | pyDMPC/ControlFramework/Subsystem.py | import Init
import Modeling
import System
import Time
class Subsystem:
"""This class represents the the agents that are assigned to the subsystems.
The agents can predict the behavior of their subsystems and store the
current costs, coupling variables and states.
Parameters
----------
sys_id ... | 0.68616 | 0.653818 |
from typing import Tuple
from reportlab.platypus import Flowable
from lyric import Lyric
from neume_chunk import NeumeChunk
from neume_dict import stand_alone
class Glyph(Flowable):
def __init__(self,
neume_chunk: NeumeChunk = None,
neume_chunk_pos: Tuple[float, float] = None,
... | glyphs.py | from typing import Tuple
from reportlab.platypus import Flowable
from lyric import Lyric
from neume_chunk import NeumeChunk
from neume_dict import stand_alone
class Glyph(Flowable):
def __init__(self,
neume_chunk: NeumeChunk = None,
neume_chunk_pos: Tuple[float, float] = None,
... | 0.723798 | 0.356055 |
from __future__ import unicode_literals
from django.db import migrations, models
import unach_photo_server.models
class Migration(migrations.Migration):
initial = True
dependencies = [
]
operations = [
migrations.CreateModel(
name='AppRegister',
fields=[
... | unach_photo_server/migrations/0001_initial.py | from __future__ import unicode_literals
from django.db import migrations, models
import unach_photo_server.models
class Migration(migrations.Migration):
initial = True
dependencies = [
]
operations = [
migrations.CreateModel(
name='AppRegister',
fields=[
... | 0.627495 | 0.179531 |
import pygame
from pygame.locals import *
pygame.init()
import random
import os
import math
class Mouse(pygame.sprite.Sprite):
def __init__(self):
'''
M.__init__()
Initializes Mouse
'''
pygame.sprite.Sprite.__init__(self)
self.x=0
self.y=0
... | classes.py | import pygame
from pygame.locals import *
pygame.init()
import random
import os
import math
class Mouse(pygame.sprite.Sprite):
def __init__(self):
'''
M.__init__()
Initializes Mouse
'''
pygame.sprite.Sprite.__init__(self)
self.x=0
self.y=0
... | 0.270288 | 0.141786 |
## How long does a patient stay in different status_dat
# Categories :
## 1. Followed
## 2. LTFU real
## 3. LTFU data
## 4. LTFU return
## 5. Other out
## Change to make : for patient who are Data Entry LTFU have the change of status happen right after the data is entered. Ie : 2 dates have to be added / 2 periods
d... | src/models/time_in_status.py |
## How long does a patient stay in different status_dat
# Categories :
## 1. Followed
## 2. LTFU real
## 3. LTFU data
## 4. LTFU return
## 5. Other out
## Change to make : for patient who are Data Entry LTFU have the change of status happen right after the data is entered. Ie : 2 dates have to be added / 2 periods
d... | 0.318591 | 0.634996 |
from PyQt5 import QtCore, QtGui, QtWidgets
from threading import Thread
from win32gui import GetWindowText, GetForegroundWindow
import tkinter as tk
import pymem, pymem.process, ctypes, requests, re, time, keyboard, pyautogui
# <...>
# < Переменные >
_translate = QtCore.QCoreApplication.translate
pm = ... | main.py | from PyQt5 import QtCore, QtGui, QtWidgets
from threading import Thread
from win32gui import GetWindowText, GetForegroundWindow
import tkinter as tk
import pymem, pymem.process, ctypes, requests, re, time, keyboard, pyautogui
# <...>
# < Переменные >
_translate = QtCore.QCoreApplication.translate
pm = ... | 0.151718 | 0.10581 |
from scipy.stats import mode
class KNN_Classifier:
xTrain = []
yTrain = []
yTest = []
k_smaller = []
k = 0
def __init__(self, k = 5):
self.k = k
def fit(self, xTrain, yTrain):
self.xTrain = xTrain
self.yTrain = yTrain
def predict(self, xTest):
... | KNN/KNN_IMP.py | from scipy.stats import mode
class KNN_Classifier:
xTrain = []
yTrain = []
yTest = []
k_smaller = []
k = 0
def __init__(self, k = 5):
self.k = k
def fit(self, xTrain, yTrain):
self.xTrain = xTrain
self.yTrain = yTrain
def predict(self, xTest):
... | 0.332852 | 0.489442 |
import pandas as pd
import os
import numpy as np
from qualifier.utils.cleaner import *
def read_housing_inventory_data():
# Reading Housing List prices from `Resources/RDC_Inventory_Core_Metrics_County_History.csv`
house_listing_df = pd.read_csv('Resources/RDC_Inventory_Core_Metrics_County_History.csv')
... | qualifier/utils/fileio.py | import pandas as pd
import os
import numpy as np
from qualifier.utils.cleaner import *
def read_housing_inventory_data():
# Reading Housing List prices from `Resources/RDC_Inventory_Core_Metrics_County_History.csv`
house_listing_df = pd.read_csv('Resources/RDC_Inventory_Core_Metrics_County_History.csv')
... | 0.401453 | 0.206034 |
from tests.util import pick_ray
from pyrosetta import Pose
from pyrosetta.rosetta.core.import_pose import pose_from_pdbstring
name = "C_G"
contents = """
HETNAM C__ A 1 C__
HETNAM G__ A 2 G__
HETATM 1 CV C__ A 1 9.822 1.552 -1.932 1.00 0.00 X
HETATM 2 CD C__ A 1 ... | tests/data/networks/C_G.py | from tests.util import pick_ray
from pyrosetta import Pose
from pyrosetta.rosetta.core.import_pose import pose_from_pdbstring
name = "C_G"
contents = """
HETNAM C__ A 1 C__
HETNAM G__ A 2 G__
HETATM 1 CV C__ A 1 9.822 1.552 -1.932 1.00 0.00 X
HETATM 2 CD C__ A 1 ... | 0.502686 | 0.232986 |
import os.path
import pickle
from pathlib import Path
from typing import List
from google.auth.transport.requests import Request
from google_auth_oauthlib.flow import InstalledAppFlow
from googleapiclient.discovery import build
from norma43utils.services.service import Service
class GoogleSpreadsheetService(Service... | norma43utils/services/google_spreadsheet_service.py | import os.path
import pickle
from pathlib import Path
from typing import List
from google.auth.transport.requests import Request
from google_auth_oauthlib.flow import InstalledAppFlow
from googleapiclient.discovery import build
from norma43utils.services.service import Service
class GoogleSpreadsheetService(Service... | 0.395835 | 0.161849 |
import numpy as np
import math
def ang_error(pred_normal, gt_normal, ROI = None):
'''
Inputs
pred_normal: A numpy array of HxWx3, float32
gt_normal: A numpy array of HxWx3, float32
ROI: A numpy array of HxW, uint8.
If None, the entire image is ROI
Return
The angular differences between pred and ... | eval/absolute_surface_normal/eval_abs_normal.py | import numpy as np
import math
def ang_error(pred_normal, gt_normal, ROI = None):
'''
Inputs
pred_normal: A numpy array of HxWx3, float32
gt_normal: A numpy array of HxWx3, float32
ROI: A numpy array of HxW, uint8.
If None, the entire image is ROI
Return
The angular differences between pred and ... | 0.718989 | 0.788176 |
"""Define model topology."""
from collections import namedtuple
import numpy as np
GroupInfo = namedtuple("GroupInfo", ["size", "rank", "world"])
class Topology(object):
def __init__(self,
device_rank,
world_size,
dp_degree=1,
pp_degree=1,
... | knover/utils/topo.py | """Define model topology."""
from collections import namedtuple
import numpy as np
GroupInfo = namedtuple("GroupInfo", ["size", "rank", "world"])
class Topology(object):
def __init__(self,
device_rank,
world_size,
dp_degree=1,
pp_degree=1,
... | 0.899152 | 0.357343 |
__author__ = '<NAME>'
__date__ = '08-14-2011'
__version__ = '1.0'
"""
Releasing Under the New BSD License same as where I got some of the code from.
Most of the S3 directory sync code came from the django-command-extensions project
on Google Code: http://code.google.com/p/django-command-extensions/wiki/sync_media_s3... | backups/sync2S3.py |
__author__ = '<NAME>'
__date__ = '08-14-2011'
__version__ = '1.0'
"""
Releasing Under the New BSD License same as where I got some of the code from.
Most of the S3 directory sync code came from the django-command-extensions project
on Google Code: http://code.google.com/p/django-command-extensions/wiki/sync_media_s3... | 0.256832 | 0.096025 |
from cognite.client.data_classes._base import *
class ServiceAccount(CogniteResource):
"""No description.
Args:
name (str): Unique name of the service account
groups (List[int]): List of group ids
id (int): No description.
is_deleted (bool): If this service account has been lo... | cognite/client/data_classes/iam.py | from cognite.client.data_classes._base import *
class ServiceAccount(CogniteResource):
"""No description.
Args:
name (str): Unique name of the service account
groups (List[int]): List of group ids
id (int): No description.
is_deleted (bool): If this service account has been lo... | 0.833426 | 0.148232 |
import os
from tests import RQTestCase, slow
from tests.fixtures import say_hello, div_by_zero, do_nothing, create_file, \
create_file_after_timeout
from tests.helpers import strip_milliseconds
from rq import Queue, Worker, get_failed_queue
from rq.job import Job
class TestWorker(RQTestCase):
def test_cre... | tests/test_worker.py | import os
from tests import RQTestCase, slow
from tests.fixtures import say_hello, div_by_zero, do_nothing, create_file, \
create_file_after_timeout
from tests.helpers import strip_milliseconds
from rq import Queue, Worker, get_failed_queue
from rq.job import Job
class TestWorker(RQTestCase):
def test_cre... | 0.553988 | 0.290877 |
import torch
import random
from torchvision import transforms
import numpy as np
from PIL import Image, ImageChops
def get_transform_ops(resize=256, image_mean=None, crop='center', crop_size=224, normalize=False):
ops = []
if resize:
ops.append(transforms.Resize(resize, Image.BICUBIC))
if image_mea... | utils/datasets/preprocess.py | import torch
import random
from torchvision import transforms
import numpy as np
from PIL import Image, ImageChops
def get_transform_ops(resize=256, image_mean=None, crop='center', crop_size=224, normalize=False):
ops = []
if resize:
ops.append(transforms.Resize(resize, Image.BICUBIC))
if image_mea... | 0.83612 | 0.390302 |
__author__ = 'lycheng'
__email__ = "<EMAIL>"
from public import ListNode
import unittest
class Solution(unittest.TestCase):
def getIntersectionNode(self, headA, headB):
''' https://oj.leetcode.com/problems/intersection-of-two-linked-lists/
'''
def get_len_and_tail(head):
r... | part12.py |
__author__ = 'lycheng'
__email__ = "<EMAIL>"
from public import ListNode
import unittest
class Solution(unittest.TestCase):
def getIntersectionNode(self, headA, headB):
''' https://oj.leetcode.com/problems/intersection-of-two-linked-lists/
'''
def get_len_and_tail(head):
r... | 0.755005 | 0.395659 |
import os
import pytest
import numpy as np
import pandas as pd
from piperoni.operators.pandas_operators import PandasMergeFiles
from piperoni.operators.pandas_operators import PandasConcatFiles
class TestPandasOperators:
"""Test the Pandas Operators"""
@pytest.fixture(scope="class")
def test_dataframe_1... | piperoni/operators/tests/test_pandas_operators.py | import os
import pytest
import numpy as np
import pandas as pd
from piperoni.operators.pandas_operators import PandasMergeFiles
from piperoni.operators.pandas_operators import PandasConcatFiles
class TestPandasOperators:
"""Test the Pandas Operators"""
@pytest.fixture(scope="class")
def test_dataframe_1... | 0.532911 | 0.644295 |
from test_map_base import TestMapBase
from unittest.mock import patch
from werkzeug.datastructures import OrderedMultiDict
import os
import pytest
class TestMapDownload(TestMapBase):
def setup(self):
TestMapBase.setup(self)
self.downloads_dir = self.app.config["MAP_DOWNLOADS_DIR"]
self.clean_map_downlo... | tests/test_map_download.py | from test_map_base import TestMapBase
from unittest.mock import patch
from werkzeug.datastructures import OrderedMultiDict
import os
import pytest
class TestMapDownload(TestMapBase):
def setup(self):
TestMapBase.setup(self)
self.downloads_dir = self.app.config["MAP_DOWNLOADS_DIR"]
self.clean_map_downlo... | 0.532182 | 0.357245 |
from __future__ import absolute_import
from __future__ import division
from __future__ import print_function
import numpy as np
from ..utils.data_utils import get_duplicate_smiles_in1d, get_dissimilarity_matrix, get_dissimilarity_matrix_from_file, feature_dist_func_dict
class NBSBase(object):
"""Abstract base Ne... | active_learning_dd/next_batch_selector/nbs_base.py | from __future__ import absolute_import
from __future__ import division
from __future__ import print_function
import numpy as np
from ..utils.data_utils import get_duplicate_smiles_in1d, get_dissimilarity_matrix, get_dissimilarity_matrix_from_file, feature_dist_func_dict
class NBSBase(object):
"""Abstract base Ne... | 0.72027 | 0.311492 |
import os
import numpy as np
import matplotlib.pyplot as plt
from matplotlib.animation import FuncAnimation, PillowWriter
class Animation:
def __init__(self, env, speedup=1.0, interval=1, mode='notebook'):
"""
Initialize an animation from the given environment.
speedup:
(fl... | code/animations.py | import os
import numpy as np
import matplotlib.pyplot as plt
from matplotlib.animation import FuncAnimation, PillowWriter
class Animation:
def __init__(self, env, speedup=1.0, interval=1, mode='notebook'):
"""
Initialize an animation from the given environment.
speedup:
(fl... | 0.743913 | 0.561936 |
import numpy as np
from math import pi
from os.path import join
import matplotlib.pyplot as plt
from matplotlib.colors import ListedColormap
from matplotlib.cm import ScalarMappable
from scipy.stats import linregress
from src import EngProc, Config
plt.style.use('elr')
plt.ion()
fc = 400
#fc = 1e3
source_depth="shal... | reports/jasa/bg_stats.py | import numpy as np
from math import pi
from os.path import join
import matplotlib.pyplot as plt
from matplotlib.colors import ListedColormap
from matplotlib.cm import ScalarMappable
from scipy.stats import linregress
from src import EngProc, Config
plt.style.use('elr')
plt.ion()
fc = 400
#fc = 1e3
source_depth="shal... | 0.561696 | 0.549459 |
import logging
from datetime import datetime
from .switch import Switch
LOG = logging.getLogger(__name__)
class Insight(Switch):
def __init__(self, *args, **kwargs):
Switch.__init__(self, *args, **kwargs)
self.insight_params = {}
def __repr__(self):
return '<WeMo Insight "{name}">'.f... | pywemo/ouimeaux_device/insight.py | import logging
from datetime import datetime
from .switch import Switch
LOG = logging.getLogger(__name__)
class Insight(Switch):
def __init__(self, *args, **kwargs):
Switch.__init__(self, *args, **kwargs)
self.insight_params = {}
def __repr__(self):
return '<WeMo Insight "{name}">'.f... | 0.649467 | 0.088072 |
import random
import numpy as np
from cnn import create_cnn, calculate_cnn_output, calculate_fitness
from nn_utilities import update_model_weights
from datasets import load_images_torcs_4
from visualization import plot_feature_vectors
from deap import algorithms, base, creator, tools
from operator import attrgetter
fro... | neuroevolution/train_cnn_ga.py | import random
import numpy as np
from cnn import create_cnn, calculate_cnn_output, calculate_fitness
from nn_utilities import update_model_weights
from datasets import load_images_torcs_4
from visualization import plot_feature_vectors
from deap import algorithms, base, creator, tools
from operator import attrgetter
fro... | 0.800497 | 0.477798 |
import torch
import itertools
__EPSILON = 1e-6
class Metric:
def add(self, y_pred, y_true):
raise NotImplementedError
def get(self):
raise NotImplementedError
def reset(self):
raise NotImplementedError
def write_to_tensorboard(self, writer, epoch):
raise NotImplemen... | brats_competition/model_training/common/metrics.py | import torch
import itertools
__EPSILON = 1e-6
class Metric:
def add(self, y_pred, y_true):
raise NotImplementedError
def get(self):
raise NotImplementedError
def reset(self):
raise NotImplementedError
def write_to_tensorboard(self, writer, epoch):
raise NotImplemen... | 0.715722 | 0.408631 |
from FutuAlgo.advanced.strategy_types import CandlestickStrategy
import datetime
import pandas as pd
class SMACrossover(CandlestickStrategy):
def __init__(self, short, long):
super().__init__(name='SMA Crossover ({}, {})'.format(short, long), bars_window=long + 1)
self.short = short
self.l... | FutuAlgo/examples/SMA_crossover.py | from FutuAlgo.advanced.strategy_types import CandlestickStrategy
import datetime
import pandas as pd
class SMACrossover(CandlestickStrategy):
def __init__(self, short, long):
super().__init__(name='SMA Crossover ({}, {})'.format(short, long), bars_window=long + 1)
self.short = short
self.l... | 0.344885 | 0.22007 |
import csv
from io import TextIOWrapper
from django.shortcuts import render, redirect, reverse, get_object_or_404
from django.views.decorators.http import require_POST
from django.contrib import messages
from core import forms as core_forms
from journal.models import Journal
from submission.models import Section
from... | views.py | import csv
from io import TextIOWrapper
from django.shortcuts import render, redirect, reverse, get_object_or_404
from django.views.decorators.http import require_POST
from django.contrib import messages
from core import forms as core_forms
from journal.models import Journal
from submission.models import Section
from... | 0.373076 | 0.070913 |
import pytest
import skbio
from onecodex.exceptions import OneCodexException
from onecodex.helpers import collate_classification_results
from onecodex.viz import plot_distance, plot_heatmap, plot_metadata, plot_pca
def test_result_collation(ocx, api_data):
analyses = [ocx.Classifications.get('45a573fb7833449a')]... | tests/test_viz.py | import pytest
import skbio
from onecodex.exceptions import OneCodexException
from onecodex.helpers import collate_classification_results
from onecodex.viz import plot_distance, plot_heatmap, plot_metadata, plot_pca
def test_result_collation(ocx, api_data):
analyses = [ocx.Classifications.get('45a573fb7833449a')]... | 0.713232 | 0.708933 |
import unittest
import numpy as np
import datetime
from openquake.hmtk.seismicity.catalogue import Catalogue
from openquake.hmtk.seismicity.selector import (_check_depth_limits,
_get_decimal_from_datetime,
CatalogueSelector)... | openquake/hmtk/tests/seismicity/test_selector.py | import unittest
import numpy as np
import datetime
from openquake.hmtk.seismicity.catalogue import Catalogue
from openquake.hmtk.seismicity.selector import (_check_depth_limits,
_get_decimal_from_datetime,
CatalogueSelector)... | 0.671147 | 0.626724 |
import numpy as np
def compute_gravitational_force(cphi, sphi, ctheta, stheta, mass, g):
""" Gravitational force expressed in body frame
"""
fx = -mass * g * stheta
fy = mass * g * ctheta * sphi
fz = mass * g * ctheta * cphi
return fx, fy, fz
def compute_gamma(attrs):
Jx = attrs.Jx
... | hummingbird/physics/generics.py | import numpy as np
def compute_gravitational_force(cphi, sphi, ctheta, stheta, mass, g):
""" Gravitational force expressed in body frame
"""
fx = -mass * g * stheta
fy = mass * g * ctheta * sphi
fz = mass * g * ctheta * cphi
return fx, fy, fz
def compute_gamma(attrs):
Jx = attrs.Jx
... | 0.767429 | 0.652304 |
# Basic imports
import sys
import os
from tqdm import tqdm
import numpy as np
import torch
import torch.nn as nn
import torch.nn.functional as F
from torch.distributions import Categorical
from torch.utils.tensorboard import SummaryWriter
# img2poem package
from .trainer import Trainer
from .earlystopping import Ear... | img2poem/trainers/adversarial.py |
# Basic imports
import sys
import os
from tqdm import tqdm
import numpy as np
import torch
import torch.nn as nn
import torch.nn.functional as F
from torch.distributions import Categorical
from torch.utils.tensorboard import SummaryWriter
# img2poem package
from .trainer import Trainer
from .earlystopping import Ear... | 0.836988 | 0.486027 |
import keras
from keras.layers import Dropout, GlobalAveragePooling1D, Dense
from layers.bojone_attention_keras import MultiHeadAttn, PositionEncoding
from models.basic_model import BasicModel
from utils.tools import UnitReduceDense
class MultiHeadAttnAvgDenseModel(BasicModel):
def __init__(self):
super(... | models/multiheadattn_avg_dense.py | import keras
from keras.layers import Dropout, GlobalAveragePooling1D, Dense
from layers.bojone_attention_keras import MultiHeadAttn, PositionEncoding
from models.basic_model import BasicModel
from utils.tools import UnitReduceDense
class MultiHeadAttnAvgDenseModel(BasicModel):
def __init__(self):
super(... | 0.845847 | 0.132908 |
from django.contrib.auth import get_user_model
from django.conf import settings
from django.core.urlresolvers import reverse
from django.http import HttpRequest, HttpResponse
from django.test import TestCase
from swingers.sauth.decorators import crossdomain
from swingers.sauth.models import ApplicationLink
from swinge... | swingers/utils/tests.py | from django.contrib.auth import get_user_model
from django.conf import settings
from django.core.urlresolvers import reverse
from django.http import HttpRequest, HttpResponse
from django.test import TestCase
from swingers.sauth.decorators import crossdomain
from swingers.sauth.models import ApplicationLink
from swinge... | 0.601711 | 0.304158 |
import re
import json
def rtvslo(page):
output = {}
output["Author"] = re.search("<div class=\"author-name\">(.*?)</div>", page)[1]
output["PublishedTime"] = re.search("<div class=\"publish-meta\">(\d+\. \w+ \d{4} ob \d{2}:\d{2}).*?</div>", page)[1]
output["Title"] = re.search("<header class=\"articl... | implementation/regex.py | import re
import json
def rtvslo(page):
output = {}
output["Author"] = re.search("<div class=\"author-name\">(.*?)</div>", page)[1]
output["PublishedTime"] = re.search("<div class=\"publish-meta\">(\d+\. \w+ \d{4} ob \d{2}:\d{2}).*?</div>", page)[1]
output["Title"] = re.search("<header class=\"articl... | 0.093896 | 0.077762 |
import bottle
from contextlib import contextmanager
from os import path, makedirs
from shutil import rmtree
from unittest.mock import Mock
from _sadm import cfg
import _sadm.devops.wapp.cfg
import _sadm.devops.wapp.tpl.tpl
import _sadm.devops.wapp.session.session
import _sadm.devops.wapp.wapp
from _sadmtest import... | tlib/_sadmtest/devops/wapp.py |
import bottle
from contextlib import contextmanager
from os import path, makedirs
from shutil import rmtree
from unittest.mock import Mock
from _sadm import cfg
import _sadm.devops.wapp.cfg
import _sadm.devops.wapp.tpl.tpl
import _sadm.devops.wapp.session.session
import _sadm.devops.wapp.wapp
from _sadmtest import... | 0.206414 | 0.074939 |
from ._models_py3 import App
from ._models_py3 import AppAvailabilityInfo
from ._models_py3 import AppListResult
from ._models_py3 import AppPatch
from ._models_py3 import AppSkuInfo
from ._models_py3 import AppTemplate
from ._models_py3 import AppTemplateLocations
from ._models_py3 import AppTemplatesResult
from ._mo... | sdk/iothub/azure-mgmt-iotcentral/azure/mgmt/iotcentral/models/__init__.py |
from ._models_py3 import App
from ._models_py3 import AppAvailabilityInfo
from ._models_py3 import AppListResult
from ._models_py3 import AppPatch
from ._models_py3 import AppSkuInfo
from ._models_py3 import AppTemplate
from ._models_py3 import AppTemplateLocations
from ._models_py3 import AppTemplatesResult
from ._mo... | 0.510496 | 0.051558 |
class Computer():
def __init__(self, brand, memory_size, storage_size, os_type):
self.brand = brand
self.memory_size = memory_size
self.storage_size = storage_size
self.os_type = os_type
#use name mangling to make it private
self.__warranty = 12
def power_up(sel... | computer.py | class Computer():
def __init__(self, brand, memory_size, storage_size, os_type):
self.brand = brand
self.memory_size = memory_size
self.storage_size = storage_size
self.os_type = os_type
#use name mangling to make it private
self.__warranty = 12
def power_up(sel... | 0.577972 | 0.205874 |
from typing import Dict, Optional
from dmvr import builders
from dmvr import processors
import tensorflow as tf
import tensorflow_probability as tfp
tfd = tfp.distributions
def sample_start_and_goal(
sequence: Dict[str, tf.Tensor],
history_length: int = 1,
img_feature_name: str = builders.IMAGE_FEATURE... | scenic/projects/func_dist/datasets/regression_utils.py | from typing import Dict, Optional
from dmvr import builders
from dmvr import processors
import tensorflow as tf
import tensorflow_probability as tfp
tfd = tfp.distributions
def sample_start_and_goal(
sequence: Dict[str, tf.Tensor],
history_length: int = 1,
img_feature_name: str = builders.IMAGE_FEATURE... | 0.917631 | 0.448487 |
import random
from copy import deepcopy
from env import EMPTY, NAMES, BOARD_FORMAT, DRAW
from lib import gameover, emptystate
def enumStates(state, idx, agent):
if idx > 8:
player = 1 if idx % 2 == 0 else 2
if player == agent.player:
agent.add(state)
else:
winner = gameove... | Agent.py | import random
from copy import deepcopy
from env import EMPTY, NAMES, BOARD_FORMAT, DRAW
from lib import gameover, emptystate
def enumStates(state, idx, agent):
if idx > 8:
player = 1 if idx % 2 == 0 else 2
if player == agent.player:
agent.add(state)
else:
winner = gameove... | 0.34632 | 0.31279 |