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 opera.constants import OperationHost, StandardInterfaceOperation, ConfigureInterfaceOperation
from opera.error import DataError
from opera.template.capability import Capability
from opera.template.interface import Interface
from opera.template.operation import Operation
class CollectorMixin:
def collect_type... | src/opera/parser/tosca/v_1_3/collector_mixin.py | from opera.constants import OperationHost, StandardInterfaceOperation, ConfigureInterfaceOperation
from opera.error import DataError
from opera.template.capability import Capability
from opera.template.interface import Interface
from opera.template.operation import Operation
class CollectorMixin:
def collect_type... | 0.499268 | 0.272375 |
import pygame
import os
import math
import numpy as np
from board import *
pygame.init()
os.environ['SDL_VIDEO_CENTERED'] = '1'
pygame.display.set_caption('Dots and Boxes AI')
screen = pygame.display.set_mode((WIDTH, HEIGHT))
# top, bottom, left, right
board = np.zeros((n - 1, m - 1, 5), dtype=object)
# -1 human, 1 a... | main.py | import pygame
import os
import math
import numpy as np
from board import *
pygame.init()
os.environ['SDL_VIDEO_CENTERED'] = '1'
pygame.display.set_caption('Dots and Boxes AI')
screen = pygame.display.set_mode((WIDTH, HEIGHT))
# top, bottom, left, right
board = np.zeros((n - 1, m - 1, 5), dtype=object)
# -1 human, 1 a... | 0.291586 | 0.257785 |
from __future__ import absolute_import
from __future__ import division
from __future__ import unicode_literals
from googlecloudsdk.api_lib.logging import util
from googlecloudsdk.calliope import arg_parsers
from googlecloudsdk.calliope import base
from googlecloudsdk.core import log
@base.ReleaseTracks(base.ReleaseT... | lib/surface/logging/metrics/update.py | from __future__ import absolute_import
from __future__ import division
from __future__ import unicode_literals
from googlecloudsdk.api_lib.logging import util
from googlecloudsdk.calliope import arg_parsers
from googlecloudsdk.calliope import base
from googlecloudsdk.core import log
@base.ReleaseTracks(base.ReleaseT... | 0.903249 | 0.210746 |
import torch
from ..net import zero_gather
class FusedExpertsNetwork(torch.nn.Module):
def __init__(self, hidden_size_per_expert, activation_fn=None, activation_fn_with_self=None, output_dim=None):
super().__init__()
self.skip_expert = (int(torch.os.environ.get('SKIP_EXPERT', '0')) != 0)
s... | tutel/experts/ffn.py |
import torch
from ..net import zero_gather
class FusedExpertsNetwork(torch.nn.Module):
def __init__(self, hidden_size_per_expert, activation_fn=None, activation_fn_with_self=None, output_dim=None):
super().__init__()
self.skip_expert = (int(torch.os.environ.get('SKIP_EXPERT', '0')) != 0)
s... | 0.890604 | 0.571826 |
from __future__ import print_function
import hashlib
import hmac
import os
import struct
import sys
import time
import ldap
from ldap.cidict import cidict as CIDict
from ldap.ldapobject import LDAPObject
if len(sys.argv) > 1 and sys.argv[1] == "--check":
raise SystemExit(0)
def get_digits(h, digits):
offs... | tests/scripts/test081-totp.py |
from __future__ import print_function
import hashlib
import hmac
import os
import struct
import sys
import time
import ldap
from ldap.cidict import cidict as CIDict
from ldap.ldapobject import LDAPObject
if len(sys.argv) > 1 and sys.argv[1] == "--check":
raise SystemExit(0)
def get_digits(h, digits):
offs... | 0.38318 | 0.172625 |
from __future__ import absolute_import, print_function
import io
import os
import re
from glob import glob
from os.path import basename
from os.path import dirname
from os.path import join
from os.path import relpath
from os.path import splitext
from setuptools import find_packages
from setuptools import setup
from s... | setup.py | from __future__ import absolute_import, print_function
import io
import os
import re
from glob import glob
from os.path import basename
from os.path import dirname
from os.path import join
from os.path import relpath
from os.path import splitext
from setuptools import find_packages
from setuptools import setup
from s... | 0.460289 | 0.072933 |
import __future__
import ast
import dis
import sys
import unittest
from compiler.consts import (
CO_ASYNC_GENERATOR,
CO_COROUTINE,
CO_GENERATOR,
CO_NESTED,
CO_NEWLOCALS,
CO_NOFREE,
CO_OPTIMIZED,
)
from dis import opmap, opname
from unittest import TestCase
from .common import CompilerTest
... | Lib/test/test_compiler/test_flags.py | import __future__
import ast
import dis
import sys
import unittest
from compiler.consts import (
CO_ASYNC_GENERATOR,
CO_COROUTINE,
CO_GENERATOR,
CO_NESTED,
CO_NEWLOCALS,
CO_NOFREE,
CO_OPTIMIZED,
)
from dis import opmap, opname
from unittest import TestCase
from .common import CompilerTest
... | 0.414188 | 0.16807 |
from __future__ import absolute_import
from __future__ import division
from __future__ import print_function
import torch
import torch.nn as nn
class JointsMSELoss(nn.Module):
def __init__(self, use_target_weight):
super(JointsMSELoss, self).__init__()
self.criterion = nn.MSELoss(reduction='mean... | core/loss.py |
from __future__ import absolute_import
from __future__ import division
from __future__ import print_function
import torch
import torch.nn as nn
class JointsMSELoss(nn.Module):
def __init__(self, use_target_weight):
super(JointsMSELoss, self).__init__()
self.criterion = nn.MSELoss(reduction='mean... | 0.866853 | 0.319373 |
import simplejson as json
from alipay.aop.api.constant.ParamConstants import *
class AlipayPcreditHuabeiAuthPageSignModel(object):
def __init__(self):
self._auth_scene = None
self._external_logon_id = None
self._freeze_amount = None
self._order_title = None
self._out_requ... | alipay/aop/api/domain/AlipayPcreditHuabeiAuthPageSignModel.py | import simplejson as json
from alipay.aop.api.constant.ParamConstants import *
class AlipayPcreditHuabeiAuthPageSignModel(object):
def __init__(self):
self._auth_scene = None
self._external_logon_id = None
self._freeze_amount = None
self._order_title = None
self._out_requ... | 0.477067 | 0.093347 |
"""Segmentation input and model functions for serving/inference."""
from __future__ import absolute_import
from __future__ import division
from __future__ import print_function
from six.moves import range
import tensorflow.compat.v1 as tf
from dataloader import mode_keys
from modeling import factory
from serving imp... | models/official/detection/serving/segmentation.py | """Segmentation input and model functions for serving/inference."""
from __future__ import absolute_import
from __future__ import division
from __future__ import print_function
from six.moves import range
import tensorflow.compat.v1 as tf
from dataloader import mode_keys
from modeling import factory
from serving imp... | 0.951964 | 0.50531 |
import sys
import unittest
from kanaconv.converter import KanaConv
from kanaconv.constants import MACRON_STYLE, CIRCUMFLEX_STYLE
from .assets import (
tests_apostrophe, tests_preprocessing, tests_rare_exc, tests_word_border,
tests_long_vowels, tests_xvowels, tests_xtsu_chi, tests_freq1000,
tests_circumfle... | kanaconv/tests/test_kanaconv.py |
import sys
import unittest
from kanaconv.converter import KanaConv
from kanaconv.constants import MACRON_STYLE, CIRCUMFLEX_STYLE
from .assets import (
tests_apostrophe, tests_preprocessing, tests_rare_exc, tests_word_border,
tests_long_vowels, tests_xvowels, tests_xtsu_chi, tests_freq1000,
tests_circumfle... | 0.453262 | 0.535463 |
import unittest
import tests.test_utils as test_utils
from VisualBERT.mmf.utils.build import build_model
from VisualBERT.mmf.utils.configuration import Configuration
from VisualBERT.mmf.utils.env import setup_imports
BERT_VOCAB_SIZE = 30255
ROBERTA_VOCAB_SIZE = 50265
XLM_ROBERTA_VOCAB_SIZE = 250002
class TestMMFT... | VisualBERT/tests/models/test_mmf_transformer.py |
import unittest
import tests.test_utils as test_utils
from VisualBERT.mmf.utils.build import build_model
from VisualBERT.mmf.utils.configuration import Configuration
from VisualBERT.mmf.utils.env import setup_imports
BERT_VOCAB_SIZE = 30255
ROBERTA_VOCAB_SIZE = 50265
XLM_ROBERTA_VOCAB_SIZE = 250002
class TestMMFT... | 0.558929 | 0.36441 |
from apitools.base.protorpclite import messages as _messages
package = 'clouduseraccounts'
class AuthorizedKeysView(_messages.Message):
"""A list of authorized public keys for a user account.
Fields:
keys: [Output Only] The list of authorized public keys in SSH format.
sudoer: [Output Only] Whether th... | google-cloud-sdk/.install/.backup/lib/googlecloudsdk/third_party/apis/clouduseraccounts/beta/clouduseraccounts_beta_messages.py |
from apitools.base.protorpclite import messages as _messages
package = 'clouduseraccounts'
class AuthorizedKeysView(_messages.Message):
"""A list of authorized public keys for a user account.
Fields:
keys: [Output Only] The list of authorized public keys in SSH format.
sudoer: [Output Only] Whether th... | 0.867598 | 0.308613 |
from __future__ import absolute_import
from __future__ import division
from __future__ import print_function
import numpy as np
from sklearn import metrics
import pandas
import tensorflow as tf
from tensorflow.contrib import skflow
### Training data
# Download dbpedia_csv.tar.gz from
# https://drive.google.com/fold... | tensorflow/examples/skflow/text_classification_cnn.py | from __future__ import absolute_import
from __future__ import division
from __future__ import print_function
import numpy as np
from sklearn import metrics
import pandas
import tensorflow as tf
from tensorflow.contrib import skflow
### Training data
# Download dbpedia_csv.tar.gz from
# https://drive.google.com/fold... | 0.851737 | 0.283564 |
from django.shortcuts import render, redirect, HttpResponse
from django.views.generic import ListView, CreateView,UpdateView,DeleteView, TemplateView, View
from apps.movimientos.models import *
from apps.movimientos.forms import *
from django.contrib.auth import authenticate, login
from django.contrib import messages
... | cintas01/apps/movimientos/views.py | from django.shortcuts import render, redirect, HttpResponse
from django.views.generic import ListView, CreateView,UpdateView,DeleteView, TemplateView, View
from apps.movimientos.models import *
from apps.movimientos.forms import *
from django.contrib.auth import authenticate, login
from django.contrib import messages
... | 0.148016 | 0.056185 |
import warnings
from cms.api import add_plugin, create_page
from cms.test_utils.testcases import CMSTestCase
from .test_app.cms_plugins import TestPluginPlugin
# we're testing the plugin generation from a sample django CMS addon in
# tests/test_app
class TestPluginTestCase(CMSTestCase):
def setUp(self):
... | tests/test_plugins.py | import warnings
from cms.api import add_plugin, create_page
from cms.test_utils.testcases import CMSTestCase
from .test_app.cms_plugins import TestPluginPlugin
# we're testing the plugin generation from a sample django CMS addon in
# tests/test_app
class TestPluginTestCase(CMSTestCase):
def setUp(self):
... | 0.724091 | 0.27125 |
import tensorflow as tf
from tensorflow.contrib import slim
from builders import frontend_builder
import numpy as np
import os, sys
# define a initializer
initializer = slim.variance_scaling_initializer(factor=2.0, mode='FAN_IN', uniform=False)
# Use bilinear interpolation to adjust images to a fixed size.
def Upsamp... | models/DepthwiseAAFF2.py |
import tensorflow as tf
from tensorflow.contrib import slim
from builders import frontend_builder
import numpy as np
import os, sys
# define a initializer
initializer = slim.variance_scaling_initializer(factor=2.0, mode='FAN_IN', uniform=False)
# Use bilinear interpolation to adjust images to a fixed size.
def Upsamp... | 0.813868 | 0.554229 |
from __future__ import absolute_import
from webtest import TestApp as Client
import bowerstatic
import json
import mock
import os
import pytest
def test_injector_specific_path():
bower = bowerstatic.Bower()
components = bower.components('components', os.path.join(
os.path.dirname(__file__), 'bower_co... | bowerstatic/tests/test_injector.py | from __future__ import absolute_import
from webtest import TestApp as Client
import bowerstatic
import json
import mock
import os
import pytest
def test_injector_specific_path():
bower = bowerstatic.Bower()
components = bower.components('components', os.path.join(
os.path.dirname(__file__), 'bower_co... | 0.395251 | 0.156073 |
from __future__ import print_function
import sys, logging, six
import datetime as dt
from collections import OrderedDict
from objbrowser import browse
from objbrowser.utils import logging_basic_config
from objbrowser.attribute_model import ALL_ATTR_MODELS
logger = logging.getLogger(__name__)
MY_CONSTANT = 55
YOUR_CO... | examples/test.py | from __future__ import print_function
import sys, logging, six
import datetime as dt
from collections import OrderedDict
from objbrowser import browse
from objbrowser.utils import logging_basic_config
from objbrowser.attribute_model import ALL_ATTR_MODELS
logger = logging.getLogger(__name__)
MY_CONSTANT = 55
YOUR_CO... | 0.390708 | 0.138055 |
import os
import sys
import tempfile
import unittest
import subprocess
from flower.command import FlowerCommand
from tornado.options import options
from tests.unit import AsyncHTTPTestCase
class TestFlowerCommand(AsyncHTTPTestCase):
def test_port(self):
with self.mock_option('port', 5555):
co... | tests/unit/test_command.py | import os
import sys
import tempfile
import unittest
import subprocess
from flower.command import FlowerCommand
from tornado.options import options
from tests.unit import AsyncHTTPTestCase
class TestFlowerCommand(AsyncHTTPTestCase):
def test_port(self):
with self.mock_option('port', 5555):
co... | 0.337749 | 0.164987 |
import wx
import common, config
from edit_windows import ManagedBase, EditStylesMixin
from gui_mixins import BitmapMixin
from tree import Node
import new_properties as np
class EditToggleButton(ManagedBase, EditStylesMixin, BitmapMixin):
"Class to handle wxToggleButton objects"
_PROPERTIES = ["Widget", "lab... | Libraries/Python/wxGlade/v0.9,5/wxGlade-0.9.5-py3.6.egg/wxglade/widgets/toggle_button/toggle_button.py | import wx
import common, config
from edit_windows import ManagedBase, EditStylesMixin
from gui_mixins import BitmapMixin
from tree import Node
import new_properties as np
class EditToggleButton(ManagedBase, EditStylesMixin, BitmapMixin):
"Class to handle wxToggleButton objects"
_PROPERTIES = ["Widget", "lab... | 0.474388 | 0.092852 |
from specutils import SpectrumList
from specutils.io.registers import data_loader
from .dc_common import FITS_FILE_EXTS, SINGLE_SPLIT_LABEL
from ..parsing_utils import read_fileobj_or_hdulist
GALAH_5EXT_CONFIG = {
"hdus": {
"0": {
"purpose": "science",
"units": {"flux_unit": "count... | specutils/io/default_loaders/galah.py | from specutils import SpectrumList
from specutils.io.registers import data_loader
from .dc_common import FITS_FILE_EXTS, SINGLE_SPLIT_LABEL
from ..parsing_utils import read_fileobj_or_hdulist
GALAH_5EXT_CONFIG = {
"hdus": {
"0": {
"purpose": "science",
"units": {"flux_unit": "count... | 0.695648 | 0.364127 |
import sys
reload(sys)
sys.setdefaultencoding('utf8')
import json
from link_crawler import link_crawler
from datetime import datetime, timedelta
import os
import shutil
import zlib
from hashlib import md5
import base64
a2b_hex = base64.binascii.a2b_hex
hexlify = base64.binascii.hexlify
md5_str = lambda x: md5(x).hexd... | disk_cache.py | import sys
reload(sys)
sys.setdefaultencoding('utf8')
import json
from link_crawler import link_crawler
from datetime import datetime, timedelta
import os
import shutil
import zlib
from hashlib import md5
import base64
a2b_hex = base64.binascii.a2b_hex
hexlify = base64.binascii.hexlify
md5_str = lambda x: md5(x).hexd... | 0.197367 | 0.089733 |
from django.conf.urls import url
from django.urls import path
from .views import AdventCalendarView, AdventDoorView, QuizListView, QuizView, QuizResultView
from .views.quiz import quiz_reply, QuizScoreboardView, QuizResultDeleteView
from .views.user_test import test_result, TestView
from .views.advent import participat... | nablapps/interactive/urls.py | from django.conf.urls import url
from django.urls import path
from .views import AdventCalendarView, AdventDoorView, QuizListView, QuizView, QuizResultView
from .views.quiz import quiz_reply, QuizScoreboardView, QuizResultDeleteView
from .views.user_test import test_result, TestView
from .views.advent import participat... | 0.271059 | 0.137938 |
import operator
import unittest
from nose.plugins.skip import SkipTest
from mongoengine import connect
from mongoengine.connection import get_db, disconnect_all
from mongoengine.mongodb_support import get_mongodb_version, MONGODB_26, MONGODB_3, MONGODB_32, MONGODB_34
from mongoengine.pymongo_support import IS_PYMONGO... | tests/utils.py | import operator
import unittest
from nose.plugins.skip import SkipTest
from mongoengine import connect
from mongoengine.connection import get_db, disconnect_all
from mongoengine.mongodb_support import get_mongodb_version, MONGODB_26, MONGODB_3, MONGODB_32, MONGODB_34
from mongoengine.pymongo_support import IS_PYMONGO... | 0.628977 | 0.287943 |
from fastapi import APIRouter, Depends, status, Response
from typing import Optional
from pydantic import BaseModel
from core.config import (
ALLOWED_HOSTS,
PROJECT_NAME,
PROJECT_VERSION,
API_PORT,
DATABASE_NAME,
NER_LABEL_COLLECTION,
Feedback_Template_Collection,
Feedback_Suggestion_... | api/api_v1/endpoints/suggestion_predict.py | from fastapi import APIRouter, Depends, status, Response
from typing import Optional
from pydantic import BaseModel
from core.config import (
ALLOWED_HOSTS,
PROJECT_NAME,
PROJECT_VERSION,
API_PORT,
DATABASE_NAME,
NER_LABEL_COLLECTION,
Feedback_Template_Collection,
Feedback_Suggestion_... | 0.683525 | 0.097691 |
from abc import abstractmethod
from pants.backend.native.config.environment import CppToolchain, CToolchain
from pants.backend.native.subsystems.native_build_settings import NativeBuildSettings
from pants.backend.native.subsystems.native_build_step import NativeBuildStep
from pants.backend.native.subsystems.native_to... | src/python/pants/backend/native/tasks/native_task.py |
from abc import abstractmethod
from pants.backend.native.config.environment import CppToolchain, CToolchain
from pants.backend.native.subsystems.native_build_settings import NativeBuildSettings
from pants.backend.native.subsystems.native_build_step import NativeBuildStep
from pants.backend.native.subsystems.native_to... | 0.82308 | 0.182426 |
import time
from datetime import datetime
import testify as T
from osxcollector import osxcollector
def _convert_to_utc(func):
'''Local time to UTC conversion
source: http://feihonghsu.blogspot.com/2008/02/converting-from-local-time-to-utc.html
'''
def wrapper(dt):
dt_utc = datetime.utcfromt... | osxc/tests/osxcollector_value_normalization_test.py | import time
from datetime import datetime
import testify as T
from osxcollector import osxcollector
def _convert_to_utc(func):
'''Local time to UTC conversion
source: http://feihonghsu.blogspot.com/2008/02/converting-from-local-time-to-utc.html
'''
def wrapper(dt):
dt_utc = datetime.utcfromt... | 0.629091 | 0.544196 |
import json
from rocketchat_API.APIExceptions.RocketExceptions import RocketMissingParamException
from rocketchat_API.APISections.base import RocketChatBase
class RocketChatChannels(RocketChatBase):
def channels_list(self, **kwargs):
"""Retrieves all of the channels from the server."""
return sel... | rocketchat_API/APISections/channels.py | import json
from rocketchat_API.APIExceptions.RocketExceptions import RocketMissingParamException
from rocketchat_API.APISections.base import RocketChatBase
class RocketChatChannels(RocketChatBase):
def channels_list(self, **kwargs):
"""Retrieves all of the channels from the server."""
return sel... | 0.775945 | 0.064329 |
import json
import os
import time
from periphery import I2C
import notecard
import sys
import cv2
from edge_impulse_linux.image import ImageImpulseRunner
productUID = "<com.blues.your_name:your_project>"
dir_path = os.path.dirname(os.path.realpath(__file__))
modelfile = os.path.join(dir_path, '../model/model.eim')
pr... | src/main.py | import json
import os
import time
from periphery import I2C
import notecard
import sys
import cv2
from edge_impulse_linux.image import ImageImpulseRunner
productUID = "<com.blues.your_name:your_project>"
dir_path = os.path.dirname(os.path.realpath(__file__))
modelfile = os.path.join(dir_path, '../model/model.eim')
pr... | 0.207616 | 0.088347 |
import pandas as pd
import tensorflow as tf
from sklearn.model_selection import train_test_split
from sklearn.preprocessing import MinMaxScaler
number_of_inputs = 63
number_of_outputs = 1
learning_rate=0.001
training_epochs=100
display_step=5
layer_1_nodes=50
layer_2_nodes=100
layer_3_nodes=50
def readData():
... | HouseTensor.py | import pandas as pd
import tensorflow as tf
from sklearn.model_selection import train_test_split
from sklearn.preprocessing import MinMaxScaler
number_of_inputs = 63
number_of_outputs = 1
learning_rate=0.001
training_epochs=100
display_step=5
layer_1_nodes=50
layer_2_nodes=100
layer_3_nodes=50
def readData():
... | 0.41834 | 0.515498 |
import os
import pytest
import shutil
import tarfile
import tempfile
import unittest
from datetime import datetime
from elyra.util import create_temp_archive
class ArchiveTestCase(unittest.TestCase):
temp_dir = tempfile.gettempdir()
test_timestamp = datetime.now().strftime("%m%d%H%M%S")
test_dir_name = ... | elyra/util/tests/test_archive.py | import os
import pytest
import shutil
import tarfile
import tempfile
import unittest
from datetime import datetime
from elyra.util import create_temp_archive
class ArchiveTestCase(unittest.TestCase):
temp_dir = tempfile.gettempdir()
test_timestamp = datetime.now().strftime("%m%d%H%M%S")
test_dir_name = ... | 0.263031 | 0.511351 |
import os.path
import torchvision.transforms as transforms
from .dataset import DatasetBase
from PIL import Image
import random
import numpy as np
import pickle
import pandas as pd
from PATH import PATH
PRESET_VARS = PATH()
import pickle
class Test_dataset(object):
def __init__(self, opt, video_data, train_mode = ... | Multitask-CNN/data/test_video_dataset.py | import os.path
import torchvision.transforms as transforms
from .dataset import DatasetBase
from PIL import Image
import random
import numpy as np
import pickle
import pandas as pd
from PATH import PATH
PRESET_VARS = PATH()
import pickle
class Test_dataset(object):
def __init__(self, opt, video_data, train_mode = ... | 0.655667 | 0.235581 |
import pygame
import math
import numpy as np
from pygame.locals import *
class Wheel():
def __init__(self, window, colour, pos, size):
self.window = window
self.colour = colour
self.size = size
self.pos = np.array(pos)
self.ang = 0.0
self.mat = np.array([[math.cos(... | turning_o.py | import pygame
import math
import numpy as np
from pygame.locals import *
class Wheel():
def __init__(self, window, colour, pos, size):
self.window = window
self.colour = colour
self.size = size
self.pos = np.array(pos)
self.ang = 0.0
self.mat = np.array([[math.cos(... | 0.418816 | 0.432483 |
import pprint
import re # noqa: F401
import six
from yapily.configuration import Configuration
class OverdraftOverdraftFeeChargeDetail(object):
"""NOTE: This class is auto generated by OpenAPI Generator.
Ref: https://openapi-generator.tech
Do not edit the class manually.
"""
"""
Attribute... | sdk/yapily/models/overdraft_overdraft_fee_charge_detail.py | import pprint
import re # noqa: F401
import six
from yapily.configuration import Configuration
class OverdraftOverdraftFeeChargeDetail(object):
"""NOTE: This class is auto generated by OpenAPI Generator.
Ref: https://openapi-generator.tech
Do not edit the class manually.
"""
"""
Attribute... | 0.728555 | 0.14978 |
import numpy as np
import matplotlib
from matplotlib import pyplot as pl, cm, colors
# Function to extract a colourmap from cmap object, from https://gist.github.com/denis-bz/8052855
def get_cmap( cmap, name=None, n=256 ):
""" in: a name "Blues" "BuGn_r" ... of a builtin cmap (case-sensitive)
or a filena... | ChrisFuncs/FromGitHub/denis_bz.py | import numpy as np
import matplotlib
from matplotlib import pyplot as pl, cm, colors
# Function to extract a colourmap from cmap object, from https://gist.github.com/denis-bz/8052855
def get_cmap( cmap, name=None, n=256 ):
""" in: a name "Blues" "BuGn_r" ... of a builtin cmap (case-sensitive)
or a filena... | 0.571049 | 0.495667 |
import unittest
from graphtheory.structures.edges import Edge
from graphtheory.structures.graphs import Graph
from graphtheory.traversing.dfs import DFSWithStack
from graphtheory.traversing.dfs import DFSWithRecursion
from graphtheory.traversing.dfs import SimpleDFS
# 0---1 2---3
# | | / | / |
# 4 5---6---7
cl... | graphtheory/traversing/tests/test_dfs.py |
import unittest
from graphtheory.structures.edges import Edge
from graphtheory.structures.graphs import Graph
from graphtheory.traversing.dfs import DFSWithStack
from graphtheory.traversing.dfs import DFSWithRecursion
from graphtheory.traversing.dfs import SimpleDFS
# 0---1 2---3
# | | / | / |
# 4 5---6---7
cl... | 0.455683 | 0.743354 |
# This python script uses `pub get --offline` to fill in
# .dart_tool/package_config.json files for Dart packages in the tree whose
# dependencies should be entirely resolved without requesting data from pub.dev.
# This allows us to be certain that the Dart code we are pulling for these
# packages is explicitly fetche... | tools/pub_get_offline.py |
# This python script uses `pub get --offline` to fill in
# .dart_tool/package_config.json files for Dart packages in the tree whose
# dependencies should be entirely resolved without requesting data from pub.dev.
# This allows us to be certain that the Dart code we are pulling for these
# packages is explicitly fetche... | 0.590897 | 0.310531 |
import getpass
import logging
import os
import random
import string
import ee
import pytest
from builtins import input
from gee_asset_manager.batch_remover import delete
from gee_asset_manager.batch_uploader import upload
logging.basicConfig(level=logging.INFO)
class memoize:
def __init__(self, function):
se... | tests/test_upload.py | import getpass
import logging
import os
import random
import string
import ee
import pytest
from builtins import input
from gee_asset_manager.batch_remover import delete
from gee_asset_manager.batch_uploader import upload
logging.basicConfig(level=logging.INFO)
class memoize:
def __init__(self, function):
se... | 0.283285 | 0.101545 |
import ast
import os
import sys
from logging import getLogger
from thonny.plugins.cpython_backend import MainCPythonBackend, get_backend
logger = getLogger(__name__)
def augment_ast(root):
mode = os.environ.get("PGZERO_MODE", "False")
assert mode != "False"
warning_prelude = "WARNING: Pygame Zero mode ... | thonny/plugins/backend/pgzero_backend.py | import ast
import os
import sys
from logging import getLogger
from thonny.plugins.cpython_backend import MainCPythonBackend, get_backend
logger = getLogger(__name__)
def augment_ast(root):
mode = os.environ.get("PGZERO_MODE", "False")
assert mode != "False"
warning_prelude = "WARNING: Pygame Zero mode ... | 0.252753 | 0.161916 |
import pandas as pd
from abc import ABC, abstractmethod
class RegionalLoadModel(ABC):
"""
An interface for different kinds of load models (per region)
"""
ALL_REQUEST_TYPES_WILDCARD = '*'
_Registry = {}
@classmethod
def register(cls, name : str):
def decorator(regional_load_mode... | autoscalingsim/load/regional_load_model/regional_load_model.py | import pandas as pd
from abc import ABC, abstractmethod
class RegionalLoadModel(ABC):
"""
An interface for different kinds of load models (per region)
"""
ALL_REQUEST_TYPES_WILDCARD = '*'
_Registry = {}
@classmethod
def register(cls, name : str):
def decorator(regional_load_mode... | 0.696371 | 0.320688 |
import requests
from bs4 import BeautifulSoup as soup
class Product:
def __init__(self, name, price, location, img, link):
self.name = name
self.price = price
self.location = location
self.img = img
self.link = link
def __str__(self):
return "name : " + self.name... | webscrape/check_olx.py | import requests
from bs4 import BeautifulSoup as soup
class Product:
def __init__(self, name, price, location, img, link):
self.name = name
self.price = price
self.location = location
self.img = img
self.link = link
def __str__(self):
return "name : " + self.name... | 0.119845 | 0.084153 |
import operator
import os
import numpy as np
import tensorflow as tf
import test_parameters as param
import util as u
graph = tf.get_default_graph()
def predict_best_tail(test_triple, full_triple_list, full_entity_list, entity_embeddings_txt,
entity_embeddings_img,
... | ikrl/test.py | import operator
import os
import numpy as np
import tensorflow as tf
import test_parameters as param
import util as u
graph = tf.get_default_graph()
def predict_best_tail(test_triple, full_triple_list, full_entity_list, entity_embeddings_txt,
entity_embeddings_img,
... | 0.316686 | 0.125092 |
"""Determines support level for different steps for masters."""
from services.deps import GetOSPlatformName
from model.wf_config import FinditConfig
# Explicitly list unsupported masters. Additional work might be needed in order
# to support them.
_UNSUPPORTED_MASTERS = [
'chromium.lkgr', # Disable as results ar... | appengine/findit/waterfall/waterfall_config.py | """Determines support level for different steps for masters."""
from services.deps import GetOSPlatformName
from model.wf_config import FinditConfig
# Explicitly list unsupported masters. Additional work might be needed in order
# to support them.
_UNSUPPORTED_MASTERS = [
'chromium.lkgr', # Disable as results ar... | 0.907985 | 0.599485 |
import numpy as np
from qutip.qip.gates import globalphase
class CircuitProcessor(object):
"""
Base class for representation of the physical implementation of a quantum
program/algorithm on a specified qubit system.
"""
def __init__(self, N, correct_global_phase):
"""
Parameters
... | qutip/qip/models/circuitprocessor.py | import numpy as np
from qutip.qip.gates import globalphase
class CircuitProcessor(object):
"""
Base class for representation of the physical implementation of a quantum
program/algorithm on a specified qubit system.
"""
def __init__(self, N, correct_global_phase):
"""
Parameters
... | 0.956912 | 0.764716 |
import argparse
parser = argparse.ArgumentParser(description=
"""
This script train PACIFIC using fasta reads.
The model, training and validation
plots will be generated.
... | scripts/transfer_learning_pacific.py | import argparse
parser = argparse.ArgumentParser(description=
"""
This script train PACIFIC using fasta reads.
The model, training and validation
plots will be generated.
... | 0.625324 | 0.26421 |
import unittest
import re
from typing import Pattern, Dict, List
import sqlalchemy
import sqlalchemy.orm
from qaqa_bot import model, game
from .util import CONFIG, create_sample_users
class FullGameTests(unittest.TestCase):
def setUp(self) -> None:
# Setup database schema
engine = sqlalchemy.cr... | test/test_game_fullgames.py |
import unittest
import re
from typing import Pattern, Dict, List
import sqlalchemy
import sqlalchemy.orm
from qaqa_bot import model, game
from .util import CONFIG, create_sample_users
class FullGameTests(unittest.TestCase):
def setUp(self) -> None:
# Setup database schema
engine = sqlalchemy.cr... | 0.557845 | 0.342957 |
field_metadata = {}
"""
Dictionary that contains the meta data of each field.
Required meta data entries are:
- **name**: human readable description
- **shortname**: description used in visualization etc
- **unit**: SI unit of the field
- **filename**: filename for output files
The naming convention for field keys i... | thetis/field_defs.py | field_metadata = {}
"""
Dictionary that contains the meta data of each field.
Required meta data entries are:
- **name**: human readable description
- **shortname**: description used in visualization etc
- **unit**: SI unit of the field
- **filename**: filename for output files
The naming convention for field keys i... | 0.779993 | 0.594316 |
import os
import argparse
import numpy as np
import pandas as pd
ROOT_DIR = os.path.dirname(os.path.dirname(os.path.realpath(__file__)))
def processLine(line):
# Identify if the line of log contains important information
if 'Sweep Count' in line:
return 'swp_count'
if 'Config' in line:
... | utils/log_to_csv.py | import os
import argparse
import numpy as np
import pandas as pd
ROOT_DIR = os.path.dirname(os.path.dirname(os.path.realpath(__file__)))
def processLine(line):
# Identify if the line of log contains important information
if 'Sweep Count' in line:
return 'swp_count'
if 'Config' in line:
... | 0.327561 | 0.196094 |
from enum import IntFlag
from typing import cast, List, Tuple, Iterable, TextIO
from itertools import takewhile
from qcodes import VisaInstrument, InstrumentChannel, ChannelList
from qcodes.utils.validators import Enum, Numbers
from qcodes.instrument.group_parameter import GroupParameter, Group
def read_curve_file(c... | qcodes/instrument_drivers/Lakeshore/Model_325.py | from enum import IntFlag
from typing import cast, List, Tuple, Iterable, TextIO
from itertools import takewhile
from qcodes import VisaInstrument, InstrumentChannel, ChannelList
from qcodes.utils.validators import Enum, Numbers
from qcodes.instrument.group_parameter import GroupParameter, Group
def read_curve_file(c... | 0.912302 | 0.53279 |
"""Step functions for optimization methods."""
from absl import logging
import jax
from jax import numpy as jnp
from jax.flatten_util import ravel_pytree
def gradient_descent_step(data, loss_f, model_param, options):
"""Gradient Descent optimization step.
Args:
data: A tuple of inputs and labels passed to ... | robust_optim/optim.py |
"""Step functions for optimization methods."""
from absl import logging
import jax
from jax import numpy as jnp
from jax.flatten_util import ravel_pytree
def gradient_descent_step(data, loss_f, model_param, options):
"""Gradient Descent optimization step.
Args:
data: A tuple of inputs and labels passed to ... | 0.933749 | 0.730843 |
from __future__ import division
import tensorflow as tf
from ACNET4_test import ACNet
import numpy as np
import json
import os
import time
import pickle
import tensorflow.contrib.layers as layers
import matplotlib.pyplot as plt
import threading
from datetime import datetime
import copy
import scipy.signal as signal
im... | flatland_testing.py | from __future__ import division
import tensorflow as tf
from ACNET4_test import ACNet
import numpy as np
import json
import os
import time
import pickle
import tensorflow.contrib.layers as layers
import matplotlib.pyplot as plt
import threading
from datetime import datetime
import copy
import scipy.signal as signal
im... | 0.421314 | 0.369059 |
from nssrc.com.citrix.netscaler.nitro.resource.base.base_resource import base_resource
from nssrc.com.citrix.netscaler.nitro.resource.base.base_resource import base_response
from nssrc.com.citrix.netscaler.nitro.service.options import options
from nssrc.com.citrix.netscaler.nitro.exception.nitro_exception import nitro... | nssrc/com/citrix/netscaler/nitro/resource/config/dns/dnszone_binding.py |
from nssrc.com.citrix.netscaler.nitro.resource.base.base_resource import base_resource
from nssrc.com.citrix.netscaler.nitro.resource.base.base_resource import base_response
from nssrc.com.citrix.netscaler.nitro.service.options import options
from nssrc.com.citrix.netscaler.nitro.exception.nitro_exception import nitro... | 0.54819 | 0.168378 |
from tina.advans import *
@ti.func
def inside(p, a, b, c):
u = (a - p).cross(b - p)
v = (b - p).cross(c - p)
w = (c - p).cross(a - p)
ccw = u >= 0 and v >= 0 and w >= 0
cw = u <= 0 and v <= 0 and w <= 0
return ccw or cw
@ti.data_oriented
class MeshVoxelizer:
def __init__(self, res):
... | melt/voxelizer.py | from tina.advans import *
@ti.func
def inside(p, a, b, c):
u = (a - p).cross(b - p)
v = (b - p).cross(c - p)
w = (c - p).cross(a - p)
ccw = u >= 0 and v >= 0 and w >= 0
cw = u <= 0 and v <= 0 and w <= 0
return ccw or cw
@ti.data_oriented
class MeshVoxelizer:
def __init__(self, res):
... | 0.501709 | 0.554953 |
import base64
import warnings
from optigatrust.util.types import *
from optigatrust.util import io
__all__ = [
'read_existing',
'write_new',
]
def _break_apart(f, sep, step):
return sep.join(f[n:n + step] for n in range(0, len(f), step))
def read_existing(certid=ObjectId.IFX_CERT, to_pem=False)... | lib/optigatrust/x509/cert.py | import base64
import warnings
from optigatrust.util.types import *
from optigatrust.util import io
__all__ = [
'read_existing',
'write_new',
]
def _break_apart(f, sep, step):
return sep.join(f[n:n + step] for n in range(0, len(f), step))
def read_existing(certid=ObjectId.IFX_CERT, to_pem=False)... | 0.34798 | 0.209369 |
from math import sin, cos, radians
class Pumpkin:
"""
Store and calculate data relating to a pumpkin projectile.
"""
# Class property
# ==============
time_interval = 0.1
# "Constructor" method
# ====================
def __init__(self, angle, velocity, initial_height=0):
... | examples/lecture16b.py | from math import sin, cos, radians
class Pumpkin:
"""
Store and calculate data relating to a pumpkin projectile.
"""
# Class property
# ==============
time_interval = 0.1
# "Constructor" method
# ====================
def __init__(self, angle, velocity, initial_height=0):
... | 0.876211 | 0.513059 |
from ..remote import RemoteModel
from infoblox_netmri.utils.utils import check_api_availability
class SpmInterfacesHubLocatorGridRemote(RemoteModel):
"""
This table lists all SPM interfaces on which multiple end hosts were connected within the user specified period of time.
| ``id:`` The internal N... | infoblox_netmri/api/remote/models/spm_interfaces_hub_locator_grid_remote.py | from ..remote import RemoteModel
from infoblox_netmri.utils.utils import check_api_availability
class SpmInterfacesHubLocatorGridRemote(RemoteModel):
"""
This table lists all SPM interfaces on which multiple end hosts were connected within the user specified period of time.
| ``id:`` The internal N... | 0.72487 | 0.529142 |
from ipaddress import ip_network
import logging
import unittest
from unittest.mock import patch
import openpeerpower.components.http as http
from openpeerpower.setup import async_setup_component
from openpeerpower.util.ssl import server_context_intermediate, server_context_modern
class TestView(http.OpenPeerPowerVie... | tests/components/http/test_init.py | from ipaddress import ip_network
import logging
import unittest
from unittest.mock import patch
import openpeerpower.components.http as http
from openpeerpower.setup import async_setup_component
from openpeerpower.util.ssl import server_context_intermediate, server_context_modern
class TestView(http.OpenPeerPowerVie... | 0.852122 | 0.370567 |
from bandwidth.api_helper import APIHelper
from bandwidth.voice.models.transcription import Transcription
class RecordingMetadataResponse(object):
"""Implementation of the 'RecordingMetadataResponse' model.
TODO: type model description here.
Attributes:
application_id (string): TODO:... | build/lib/bandwidth/voice/models/recording_metadata_response.py | from bandwidth.api_helper import APIHelper
from bandwidth.voice.models.transcription import Transcription
class RecordingMetadataResponse(object):
"""Implementation of the 'RecordingMetadataResponse' model.
TODO: type model description here.
Attributes:
application_id (string): TODO:... | 0.482917 | 0.133613 |
from flask import Blueprint, jsonify
from brainzutils import cache
from critiquebrainz.db.review import supported_languages, ENTITY_TYPES
import critiquebrainz.db.review as db_review
from critiquebrainz.db import (
vote as db_vote,
exceptions as db_exceptions,
spam_report as db_spam_report,
revision as ... | critiquebrainz/ws/review/views.py | from flask import Blueprint, jsonify
from brainzutils import cache
from critiquebrainz.db.review import supported_languages, ENTITY_TYPES
import critiquebrainz.db.review as db_review
from critiquebrainz.db import (
vote as db_vote,
exceptions as db_exceptions,
spam_report as db_spam_report,
revision as ... | 0.628977 | 0.165931 |
from __future__ import unicode_literals
import pytest
from django.core.urlresolvers import reverse
from machina.apps.forum.signals import forum_viewed
from machina.core.db.models import get_model
from machina.core.loading import get_class
from machina.test.context_managers import mock_signal_receiver
from machina.te... | tests/functional/forum/test_views.py |
from __future__ import unicode_literals
import pytest
from django.core.urlresolvers import reverse
from machina.apps.forum.signals import forum_viewed
from machina.core.db.models import get_model
from machina.core.loading import get_class
from machina.test.context_managers import mock_signal_receiver
from machina.te... | 0.500488 | 0.166777 |
def load(h):
return ({'abbr': 0, 'code': 0, 'title': 'Unknown'},
{'abbr': 'fsob',
'code': 1022,
'title': 'Forecast sensitivity to observations'},
{'abbr': 'fsow',
'code': 1023,
'title': 'Forecast sensitivity to observations wave'},
... | pyeccodes/defs/mars/stream_table.py | def load(h):
return ({'abbr': 0, 'code': 0, 'title': 'Unknown'},
{'abbr': 'fsob',
'code': 1022,
'title': 'Forecast sensitivity to observations'},
{'abbr': 'fsow',
'code': 1023,
'title': 'Forecast sensitivity to observations wave'},
... | 0.798933 | 0.547222 |
import os
if __name__ == '__main__':
amplxe_cl_path = '/opt/intel/vtune_amplifier/bin64/amplxe-cl'
# dataset and parameters
dataset_dir_path = '/home/yche/GitRepos/ScanOptimizing/dataset/'
dataset_path_lst = map(lambda file_name: dataset_dir_path + file_name,
['snap_orkut', '... | paper/deprecated/set-intersection/report_set_intersection_statistics.py | import os
if __name__ == '__main__':
amplxe_cl_path = '/opt/intel/vtune_amplifier/bin64/amplxe-cl'
# dataset and parameters
dataset_dir_path = '/home/yche/GitRepos/ScanOptimizing/dataset/'
dataset_path_lst = map(lambda file_name: dataset_dir_path + file_name,
['snap_orkut', '... | 0.176069 | 0.074433 |
# -*- coding: utf-8 -*-
import os, sys, traceback
# Config
from Components.config import *
from Components.Sources.StaticText import StaticText
# Screen
from Components.ActionMap import ActionMap
from Components.ScrollLabel import ScrollLabel
from enigma import eSize, ePoint, getDesktop
from Screens.Screen import Sc... | autotimer/src/ShowLogScreen.py | # -*- coding: utf-8 -*-
import os, sys, traceback
# Config
from Components.config import *
from Components.Sources.StaticText import StaticText
# Screen
from Components.ActionMap import ActionMap
from Components.ScrollLabel import ScrollLabel
from enigma import eSize, ePoint, getDesktop
from Screens.Screen import Sc... | 0.071701 | 0.057098 |
__author__ = '<NAME>'
__date__ = '19/03/2018'
__copyright__ = 'Copyright 2018, The QGIS Project'
# This will get replaced with a git SHA1 when you do a git archive
__revision__ = '<PASSWORD>'
import qgis # NOQA
from qgis.PyQt.QtXml import QDomDocument
from qgis.core import (QgsProjectMetadata,
... | tests/src/python/test_qgsprojectmetadata.py | __author__ = '<NAME>'
__date__ = '19/03/2018'
__copyright__ = 'Copyright 2018, The QGIS Project'
# This will get replaced with a git SHA1 when you do a git archive
__revision__ = '<PASSWORD>'
import qgis # NOQA
from qgis.PyQt.QtXml import QDomDocument
from qgis.core import (QgsProjectMetadata,
... | 0.642881 | 0.233051 |
from sqlalchemy import Column, DateTime, ForeignKey, Integer, String
from sqlalchemy.orm import backref, relationship
from sqlalchemy.schema import UniqueConstraint
from c3po.db.base import Base
class UserLikes(Base):
__tablename__ = "user_likes"
# Columns
id = Column(Integer, primary_key=True)
user... | c3po/db/models/user.py | from sqlalchemy import Column, DateTime, ForeignKey, Integer, String
from sqlalchemy.orm import backref, relationship
from sqlalchemy.schema import UniqueConstraint
from c3po.db.base import Base
class UserLikes(Base):
__tablename__ = "user_likes"
# Columns
id = Column(Integer, primary_key=True)
user... | 0.628179 | 0.196498 |
import argparse
import pdb
import traceback
from dataclasses import dataclass
from typing import List, Tuple
Layer = List[List[int]]
@dataclass
class Bitmap:
width: int
height: int
layer: Layer
@classmethod
def from_image(cls, image):
bitmap = Bitmap(image.width, image.height, [])
... | 2019/08-space_image/solve.py |
import argparse
import pdb
import traceback
from dataclasses import dataclass
from typing import List, Tuple
Layer = List[List[int]]
@dataclass
class Bitmap:
width: int
height: int
layer: Layer
@classmethod
def from_image(cls, image):
bitmap = Bitmap(image.width, image.height, [])
... | 0.697609 | 0.389024 |
import struct
import time
from rethinkdb import ql2_pb2
from rethinkdb.errors import ReqlAuthError, ReqlDriverError, ReqlTimeoutError, RqlCursorEmpty
from rethinkdb.net import Connection as ConnectionBase, Cursor, Query, Response, maybe_profile
from twisted.internet import defer, reactor
from twisted.internet.defer i... | rethinkdb/twisted_net/net_twisted.py |
import struct
import time
from rethinkdb import ql2_pb2
from rethinkdb.errors import ReqlAuthError, ReqlDriverError, ReqlTimeoutError, RqlCursorEmpty
from rethinkdb.net import Connection as ConnectionBase, Cursor, Query, Response, maybe_profile
from twisted.internet import defer, reactor
from twisted.internet.defer i... | 0.443359 | 0.111024 |
import arcade
from pyglet.math import Vec2
SPRITE_SCALING = 0.5
SCREEN_WIDTH = 1000
SCREEN_HEIGHT = 600
SCREEN_TITLE = "Sprite with Moving Platforms Example"
SPRITE_PIXEL_SIZE = 128
GRID_PIXEL_SIZE = (SPRITE_PIXEL_SIZE * SPRITE_SCALING)
# How many pixels to keep as a minimum margin between the character
# and the ed... | arcade/examples/sprite_moving_platforms.py | import arcade
from pyglet.math import Vec2
SPRITE_SCALING = 0.5
SCREEN_WIDTH = 1000
SCREEN_HEIGHT = 600
SCREEN_TITLE = "Sprite with Moving Platforms Example"
SPRITE_PIXEL_SIZE = 128
GRID_PIXEL_SIZE = (SPRITE_PIXEL_SIZE * SPRITE_SCALING)
# How many pixels to keep as a minimum margin between the character
# and the ed... | 0.734215 | 0.307904 |
from __future__ import annotations
from datetime import datetime
from os import getenv
from typing import Generic, Type, TypeVar
from .environment import running_in_pytest
T = TypeVar("T", bound="Singleton")
class Singleton(Generic[T], type):
_instances: dict[Type[T], T] = {}
def __call__(cls, *args, **kw... | src/spellbot/settings.py | from __future__ import annotations
from datetime import datetime
from os import getenv
from typing import Generic, Type, TypeVar
from .environment import running_in_pytest
T = TypeVar("T", bound="Singleton")
class Singleton(Generic[T], type):
_instances: dict[Type[T], T] = {}
def __call__(cls, *args, **kw... | 0.644673 | 0.100481 |
import json
from twisted.python import usage, log
from twisted.application import internet
from twisted.internet import reactor, endpoints
from twisted.web import resource, static, server
import subprocess
# curl --data-binary '{"password_hex": "<PASSWORD>", "msg1_hex": "<PASSWORD>"}' http://localhost:8705/A
# curl --... | server/src/spake2_interop_server/server.py | import json
from twisted.python import usage, log
from twisted.application import internet
from twisted.internet import reactor, endpoints
from twisted.web import resource, static, server
import subprocess
# curl --data-binary '{"password_hex": "<PASSWORD>", "msg1_hex": "<PASSWORD>"}' http://localhost:8705/A
# curl --... | 0.420005 | 0.081082 |
import os
import shutil
import tarfile
import tempfile
from resource_management.core.logger import Logger
from resource_management.core.exceptions import Fail
BACKUP_TEMP_DIR = "falcon-upgrade-backup"
BACKUP_DATA_ARCHIVE = "falcon-local-backup.tar"
BACKUP_CONF_ARCHIVE = "falcon-conf-backup.tar"
def post_stop_backup(... | ambari-server/src/main/resources/common-services/FALCON/0.5.0.2.1/package/scripts/falcon_server_upgrade.py | import os
import shutil
import tarfile
import tempfile
from resource_management.core.logger import Logger
from resource_management.core.exceptions import Fail
BACKUP_TEMP_DIR = "falcon-upgrade-backup"
BACKUP_DATA_ARCHIVE = "falcon-local-backup.tar"
BACKUP_CONF_ARCHIVE = "falcon-conf-backup.tar"
def post_stop_backup(... | 0.254046 | 0.067547 |
from . import entropy
from .shifterator import Shift
class WeightedAvgShift(Shift):
"""
Shift object for calculating weighted scores of two systems of types,
and the shift between them
Parameters
----------
type2freq_1, type2freq_2: dict
Keys are types of a system and values are frequ... | shifterator/shifts.py | from . import entropy
from .shifterator import Shift
class WeightedAvgShift(Shift):
"""
Shift object for calculating weighted scores of two systems of types,
and the shift between them
Parameters
----------
type2freq_1, type2freq_2: dict
Keys are types of a system and values are frequ... | 0.952794 | 0.600803 |
import StringIO
import unittest
import mock
from telemetry import story
from telemetry.internal.results import page_test_results
from telemetry import page as page_module
_GROUPING_KEY_DEFAULT = {'1': '2'}
def _MakeStorySet():
story_set = story.StorySet()
story_set.AddStory(
page_module.Page('http://ww... | telemetry/telemetry/internal/results/gtest_progress_reporter_unittest.py |
import StringIO
import unittest
import mock
from telemetry import story
from telemetry.internal.results import page_test_results
from telemetry import page as page_module
_GROUPING_KEY_DEFAULT = {'1': '2'}
def _MakeStorySet():
story_set = story.StorySet()
story_set.AddStory(
page_module.Page('http://ww... | 0.510496 | 0.236318 |
import advection_fv4.interface_f as interface_f
import mesh.array_indexer as ai
def fluxes(my_data, rp, dt):
"""Construct the fluxes through the interfaces for the linear advection
equation:
.. math::
a_t + u a_x + v a_y = 0
We use a fourth-order Godunov method to construct the interface
... | advection_fv4/fluxes.py | import advection_fv4.interface_f as interface_f
import mesh.array_indexer as ai
def fluxes(my_data, rp, dt):
"""Construct the fluxes through the interfaces for the linear advection
equation:
.. math::
a_t + u a_x + v a_y = 0
We use a fourth-order Godunov method to construct the interface
... | 0.815894 | 0.763175 |
import torch
from torchdet3d.evaluation import compute_metrics_per_cls
from torchdet3d.losses import WingLoss, ADD_loss, DiagLoss
from torchdet3d.builders import (build_loss, build_optimizer, build_scheduler,
build_model, AVAILABLE_LOSS, AVAILABLE_OPTIMS, AVAILABLE_SCHEDS)
from tor... | tests/test_pipeline.py | import torch
from torchdet3d.evaluation import compute_metrics_per_cls
from torchdet3d.losses import WingLoss, ADD_loss, DiagLoss
from torchdet3d.builders import (build_loss, build_optimizer, build_scheduler,
build_model, AVAILABLE_LOSS, AVAILABLE_OPTIMS, AVAILABLE_SCHEDS)
from tor... | 0.772101 | 0.449091 |
import time
import numpy as np
import theano
floatX = theano.config.floatX
class AgentMemory(object):
def __init__(self, rng, stateShape, phiLength=4, memorySize=10000, discountRate = 1.0, numTasks = 1):
"""
Arguments:
stateShape - tuple containing the dimensions of the experiences b... | Agents/AgentMemory.py | import time
import numpy as np
import theano
floatX = theano.config.floatX
class AgentMemory(object):
def __init__(self, rng, stateShape, phiLength=4, memorySize=10000, discountRate = 1.0, numTasks = 1):
"""
Arguments:
stateShape - tuple containing the dimensions of the experiences b... | 0.52975 | 0.512266 |
from conduit.article.models import Article
from conduit.auth.models import User
from conduit.auth.tests.test_auth_views import USER_ONE_JWT
from conduit.auth.tests.test_auth_views import USER_TWO_JWT
from sqlalchemy.orm.session import Session
from webtest import TestApp
def test_feed(testapp: TestApp, democontent: N... | src/conduit/article/tests/test_article_views.py |
from conduit.article.models import Article
from conduit.auth.models import User
from conduit.auth.tests.test_auth_views import USER_ONE_JWT
from conduit.auth.tests.test_auth_views import USER_TWO_JWT
from sqlalchemy.orm.session import Session
from webtest import TestApp
def test_feed(testapp: TestApp, democontent: N... | 0.75401 | 0.50531 |
from __future__ import absolute_import
from __future__ import division
from __future__ import print_function
import collections
import numpy as np
import tensorflow as tf
from cv2 import resize
import logging
from utils.misc_utils import get_center
Rectangle = collections.namedtuple('Rectangle', ['x', 'y', 'width',... | utils/infer_utils.py | from __future__ import absolute_import
from __future__ import division
from __future__ import print_function
import collections
import numpy as np
import tensorflow as tf
from cv2 import resize
import logging
from utils.misc_utils import get_center
Rectangle = collections.namedtuple('Rectangle', ['x', 'y', 'width',... | 0.863765 | 0.381392 |
import sys
import traceback
from collections import deque
from threading import Condition, Thread
from time import time
""" Sits between incoming messages from a subscription, and the outgoing
publish method. Provides throttling / buffering capabilities.
When the parameters change, the handler may transition to a d... | rosbridge_library/src/rosbridge_library/internal/subscription_modifiers.py |
import sys
import traceback
from collections import deque
from threading import Condition, Thread
from time import time
""" Sits between incoming messages from a subscription, and the outgoing
publish method. Provides throttling / buffering capabilities.
When the parameters change, the handler may transition to a d... | 0.439868 | 0.111338 |
import torch
import torch.nn as nn
import torch.nn.functional as F
from torch import Tensor
from .builder import OPERATORS
def coords_grid(flow: Tensor) -> Tensor:
"""Generate shifted coordinate grid based based input flow.
Args:
flow (Tensor): Estimated optical flow.
Returns:
Tensor: T... | mmflow/ops/warp.py | import torch
import torch.nn as nn
import torch.nn.functional as F
from torch import Tensor
from .builder import OPERATORS
def coords_grid(flow: Tensor) -> Tensor:
"""Generate shifted coordinate grid based based input flow.
Args:
flow (Tensor): Estimated optical flow.
Returns:
Tensor: T... | 0.958596 | 0.762579 |
import os
import sys
import argparse
import json
import uuid
import re
from pprint import pprint
from html.parser import HTMLParser
from html.entities import name2codepoint
# NOTE: This script is standalone does not include any libraries
DLG_JSON_HUMAN_EXTENSION = ".dlg_human.json"
ROOT_NODE_INDEX = -1
class Colo... | Tools/DlgTwineToJsonHumanText.py |
import os
import sys
import argparse
import json
import uuid
import re
from pprint import pprint
from html.parser import HTMLParser
from html.entities import name2codepoint
# NOTE: This script is standalone does not include any libraries
DLG_JSON_HUMAN_EXTENSION = ".dlg_human.json"
ROOT_NODE_INDEX = -1
class Colo... | 0.290075 | 0.087564 |
"HTML Renderer for FPDF.py"
__author__ = "<NAME> <<EMAIL>>"
__copyright__ = "Copyright (C) 2010 <NAME>"
__license__ = "LGPL 3.0"
# Inspired by tuto5.py and several examples from fpdf.org, html2fpdf, etc.
from fpdf import FPDF
from HTMLParser import HTMLParser
DEBUG = False
def px2mm(px):
return int(px)*25.4/7... | gluon/contrib/pyfpdf/html.py |
"HTML Renderer for FPDF.py"
__author__ = "<NAME> <<EMAIL>>"
__copyright__ = "Copyright (C) 2010 <NAME>"
__license__ = "LGPL 3.0"
# Inspired by tuto5.py and several examples from fpdf.org, html2fpdf, etc.
from fpdf import FPDF
from HTMLParser import HTMLParser
DEBUG = False
def px2mm(px):
return int(px)*25.4/7... | 0.25618 | 0.128744 |
from __future__ import annotations
import abc
from typing import Any, Generic, List, Mapping, Sequence, TypeVar
from .userr import Err, Res
_Value = TypeVar("_Value")
_Item = TypeVar("_Item")
class Collector(abc.ABC, Generic[_Value]):
"""
Collects argument instances and computes the final value
"""
... | src/configpile/collector.py | from __future__ import annotations
import abc
from typing import Any, Generic, List, Mapping, Sequence, TypeVar
from .userr import Err, Res
_Value = TypeVar("_Value")
_Item = TypeVar("_Item")
class Collector(abc.ABC, Generic[_Value]):
"""
Collects argument instances and computes the final value
"""
... | 0.895125 | 0.322473 |
from spack import *
class BigdftLibabinit(AutotoolsPackage):
"""BigDFT-libABINIT: this is a subsection of files coming from ABINIT software package,
to which BigDFT has been coupled since the early days. It handles different parts
like symmetries, ewald corrections, PAW routines, density and potent... | var/spack/repos/builtin/packages/bigdft-libabinit/package.py |
from spack import *
class BigdftLibabinit(AutotoolsPackage):
"""BigDFT-libABINIT: this is a subsection of files coming from ABINIT software package,
to which BigDFT has been coupled since the early days. It handles different parts
like symmetries, ewald corrections, PAW routines, density and potent... | 0.748168 | 0.309428 |
import requests
import logging
import pandas as pd
from datetime import datetime, timedelta
import time
from sqlalchemy import create_engine
creds = {'usr': 'ONEBIT',
'pwd': '<PASSWORD>',
'hst': '127.0.0.1',
'prt': 3306,
'dbn': 'crypto_data'}
conn = create_engine('mysql+pymysql://{... | binance/binance_spot_kline_rest.py | import requests
import logging
import pandas as pd
from datetime import datetime, timedelta
import time
from sqlalchemy import create_engine
creds = {'usr': 'ONEBIT',
'pwd': '<PASSWORD>',
'hst': '127.0.0.1',
'prt': 3306,
'dbn': 'crypto_data'}
conn = create_engine('mysql+pymysql://{... | 0.232484 | 0.143938 |
import datetime
import unittest
from conflowgen.domain_models.data_types.mode_of_transport import ModeOfTransport
from conflowgen.domain_models.distribution_models.mode_of_transport_distribution import ModeOfTransportDistribution
from conflowgen.domain_models.distribution_repositories.mode_of_transport_distribution_re... | conflowgen/tests/previews/test_container_flow_by_vehicle_type_preview.py | import datetime
import unittest
from conflowgen.domain_models.data_types.mode_of_transport import ModeOfTransport
from conflowgen.domain_models.distribution_models.mode_of_transport_distribution import ModeOfTransportDistribution
from conflowgen.domain_models.distribution_repositories.mode_of_transport_distribution_re... | 0.567697 | 0.292873 |
from django.db import models
from django.core.cache import cache
from common import keys
def to_dict(self, *exclude):
'''
将 model 对象转换成一个属性字典
exclude: 需要排出的字段名
'''
attr_dict = {}
for field in self._meta.fields:
field_name = field.attname
if field_name not in exclude:
... | libs/orm.py | from django.db import models
from django.core.cache import cache
from common import keys
def to_dict(self, *exclude):
'''
将 model 对象转换成一个属性字典
exclude: 需要排出的字段名
'''
attr_dict = {}
for field in self._meta.fields:
field_name = field.attname
if field_name not in exclude:
... | 0.366703 | 0.094845 |
import py
import sys
from _pytest.monkeypatch import monkeypatch
from _pytest.assertion import util
def pytest_addoption(parser):
group = parser.getgroup("debugconfig")
group.addoption('--assert',
action="store",
dest="assertmode",
choices... | venv/lib/python3.6/site-packages/_pytest/assertion/__init__.py | import py
import sys
from _pytest.monkeypatch import monkeypatch
from _pytest.assertion import util
def pytest_addoption(parser):
group = parser.getgroup("debugconfig")
group.addoption('--assert',
action="store",
dest="assertmode",
choices... | 0.300438 | 0.325949 |
import unit_tests.utils as ut_utils
import zaza.model as model
import zaza.openstack.utilities.ceph as ceph_utils
import zaza.openstack.utilities.openstack as openstack_utils
class TestCephUtils(ut_utils.BaseTestCase):
def setUp(self):
super(TestCephUtils, self).setUp()
def _test_expected_pools(self... | unit_tests/utilities/test_zaza_utilities_ceph.py | import unit_tests.utils as ut_utils
import zaza.model as model
import zaza.openstack.utilities.ceph as ceph_utils
import zaza.openstack.utilities.openstack as openstack_utils
class TestCephUtils(ut_utils.BaseTestCase):
def setUp(self):
super(TestCephUtils, self).setUp()
def _test_expected_pools(self... | 0.594316 | 0.408336 |
import os
import os.path
import sys
import torch
import torch.utils.data as data
import torchvision.transforms as transforms
from PIL import Image, ImageDraw, ImageFont
import cv2
import numpy as np
import math
from utils import get_boxes, generate_gt
class MLTDetection(data.Dataset):
def __init__(self, root, s... | data/mlt.py |
import os
import os.path
import sys
import torch
import torch.utils.data as data
import torchvision.transforms as transforms
from PIL import Image, ImageDraw, ImageFont
import cv2
import numpy as np
import math
from utils import get_boxes, generate_gt
class MLTDetection(data.Dataset):
def __init__(self, root, s... | 0.333612 | 0.348119 |
import os
import pytest
from buildstream.exceptions import ErrorDomain, LoadErrorReason
from buildstream.testing import cli # pylint: disable=unused-import
from tests.testutils import filetypegenerator
DATA_DIR = os.path.join(os.path.dirname(os.path.realpath(__file__)), "patch",)
@pytest.mark.datafiles(os.path.jo... | tests/sources/patch.py |
import os
import pytest
from buildstream.exceptions import ErrorDomain, LoadErrorReason
from buildstream.testing import cli # pylint: disable=unused-import
from tests.testutils import filetypegenerator
DATA_DIR = os.path.join(os.path.dirname(os.path.realpath(__file__)), "patch",)
@pytest.mark.datafiles(os.path.jo... | 0.409221 | 0.313144 |
"""Tests for minimization utils."""
from __future__ import absolute_import
from __future__ import division
from __future__ import print_function
# Dependency imports
import numpy as np
import tensorflow.compat.v1 as tf1
import tensorflow.compat.v2 as tf
import tensorflow_probability as tfp
from tensorflow_probabili... | tensorflow_probability/python/math/minimize_test.py | """Tests for minimization utils."""
from __future__ import absolute_import
from __future__ import division
from __future__ import print_function
# Dependency imports
import numpy as np
import tensorflow.compat.v1 as tf1
import tensorflow.compat.v2 as tf
import tensorflow_probability as tfp
from tensorflow_probabili... | 0.912095 | 0.585931 |
from enum import IntEnum, unique
import qtawesome as qta
from PyQt5.Qt import QIcon
from hbutils.model import int_enum_loads
@int_enum_loads(enable_int=False, name_preprocess=str.upper, )
@unique
class ProcessingStatus(IntEnum):
PENDING = 0
WAITING = 1
PROCESSING = 2
COMPLETED = 3
ERROR = 4
... | app/widget/models.py | from enum import IntEnum, unique
import qtawesome as qta
from PyQt5.Qt import QIcon
from hbutils.model import int_enum_loads
@int_enum_loads(enable_int=False, name_preprocess=str.upper, )
@unique
class ProcessingStatus(IntEnum):
PENDING = 0
WAITING = 1
PROCESSING = 2
COMPLETED = 3
ERROR = 4
... | 0.572006 | 0.162015 |
import asyncio
import voluptuous as vol
from homeassistant.components.knx import DATA_KNX, ATTR_DISCOVER_DEVICES
from homeassistant.components.notify import PLATFORM_SCHEMA, \
BaseNotificationService
from homeassistant.const import CONF_NAME
from homeassistant.core import callback
import homeassistant.helpers.conf... | homeassistant/components/notify/knx.py | import asyncio
import voluptuous as vol
from homeassistant.components.knx import DATA_KNX, ATTR_DISCOVER_DEVICES
from homeassistant.components.notify import PLATFORM_SCHEMA, \
BaseNotificationService
from homeassistant.const import CONF_NAME
from homeassistant.core import callback
import homeassistant.helpers.conf... | 0.640074 | 0.114567 |
import string
import email.message
from time import strftime
import sys
from random import *
from optparse import OptionParser
from email.mime.multipart import MIMEMultipart
from email.mime.text import MIMEText
import smtplib,os,random,time
from colorama import *
from datetime import datetime
from multiprocessing impor... | mass.py | import string
import email.message
from time import strftime
import sys
from random import *
from optparse import OptionParser
from email.mime.multipart import MIMEMultipart
from email.mime.text import MIMEText
import smtplib,os,random,time
from colorama import *
from datetime import datetime
from multiprocessing impor... | 0.075138 | 0.079782 |
from cvxpy.atoms.atom import Atom
from cvxpy.atoms.affine.binary_operators import multiply
import numpy as np
import scipy.sparse as sp
def diff_pos(x, y):
r"""The difference :math:`x - y` with domain `\{x, y : x > y > 0\}`.
This atom is log-log concave.
Parameters:
----------
x : :class:`~cvxpy... | cvxpy/atoms/one_minus_pos.py | from cvxpy.atoms.atom import Atom
from cvxpy.atoms.affine.binary_operators import multiply
import numpy as np
import scipy.sparse as sp
def diff_pos(x, y):
r"""The difference :math:`x - y` with domain `\{x, y : x > y > 0\}`.
This atom is log-log concave.
Parameters:
----------
x : :class:`~cvxpy... | 0.922944 | 0.779637 |
from __future__ import absolute_import
from datetime import date, datetime # noqa: F401
from typing import List, Dict # noqa: F401
from .base_model_ import Model
from .. import util
class DocumentInfoPageEntry(Model):
"""NOTE: This class is auto generated by the swagger code generator program.
Do not ed... | backend/swagger_server/models/document_info_page_entry.py |
from __future__ import absolute_import
from datetime import date, datetime # noqa: F401
from typing import List, Dict # noqa: F401
from .base_model_ import Model
from .. import util
class DocumentInfoPageEntry(Model):
"""NOTE: This class is auto generated by the swagger code generator program.
Do not ed... | 0.937929 | 0.197097 |
import csv
import time
import json
import emoji
import re
import pickle
from emoji import unicode_codes
filename = "/data/06333/aroraish/ut_venmo_2018.json"
brokenlines = "/data/06333/aroraish/broken4.txt"
emojicols = [u"\U0001f3fb", u"\U0001f3fc", u"\U0001f3fd", u"\U0001f3fe", u"\U0001f3ff"]
pattern = u'(' + u'|'.... | gonnawork2.py | import csv
import time
import json
import emoji
import re
import pickle
from emoji import unicode_codes
filename = "/data/06333/aroraish/ut_venmo_2018.json"
brokenlines = "/data/06333/aroraish/broken4.txt"
emojicols = [u"\U0001f3fb", u"\U0001f3fc", u"\U0001f3fd", u"\U0001f3fe", u"\U0001f3ff"]
pattern = u'(' + u'|'.... | 0.094109 | 0.056809 |
from behave import *
from selenium.webdriver.common.keys import Keys
from selenium.webdriver.common.action_chains import ActionChains
import urllib.parse as urlparse
import re
def getToken(browser):
parsed = urlparse.urlparse(browser.current_url)
return urlparse.parse_qs(parsed.query)['token'][0]
category = None
c... | ITS/Project-2/features/steps/edit.py | from behave import *
from selenium.webdriver.common.keys import Keys
from selenium.webdriver.common.action_chains import ActionChains
import urllib.parse as urlparse
import re
def getToken(browser):
parsed = urlparse.urlparse(browser.current_url)
return urlparse.parse_qs(parsed.query)['token'][0]
category = None
c... | 0.494873 | 0.074231 |