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 src.praxxis.util.roots import _output_root
from src.praxxis.util.roots import _user_info_db
from src.praxxis.util.roots import _library_root
from src.praxxis.util.roots import _library_db
from src.praxxis.util.roots import _scene_root
from src.praxxis.util.roots import _history_db
from src.praxxis.util.roots impor... | src/praxxis/entrypoints/entry_notebook.py | from src.praxxis.util.roots import _output_root
from src.praxxis.util.roots import _user_info_db
from src.praxxis.util.roots import _library_root
from src.praxxis.util.roots import _library_db
from src.praxxis.util.roots import _scene_root
from src.praxxis.util.roots import _history_db
from src.praxxis.util.roots impor... | 0.395835 | 0.131173 |
from collections import defaultdict
class Solution:
def removeStones(self, stones) -> int:
def dfs(stone_pos):
nonlocal count
visited[(stone_pos[0], stone_pos[1])] = True
for c in col_stones[stone_pos[0]]:
if not visited[c[0], c[1]]:
... | 947.py | from collections import defaultdict
class Solution:
def removeStones(self, stones) -> int:
def dfs(stone_pos):
nonlocal count
visited[(stone_pos[0], stone_pos[1])] = True
for c in col_stones[stone_pos[0]]:
if not visited[c[0], c[1]]:
... | 0.538741 | 0.373219 |
"""Tests for CRF."""
from __future__ import absolute_import
from __future__ import division
from __future__ import print_function
import itertools
import numpy as np
import tensorflow as tf
class CrfTest(tf.test.TestCase):
def testCrfSequenceScore(self):
inputs = np.array(
[[4, 5, -3], [3, -1, 3], [... | tensorflow/contrib/crf/python/kernel_tests/crf_test.py | """Tests for CRF."""
from __future__ import absolute_import
from __future__ import division
from __future__ import print_function
import itertools
import numpy as np
import tensorflow as tf
class CrfTest(tf.test.TestCase):
def testCrfSequenceScore(self):
inputs = np.array(
[[4, 5, -3], [3, -1, 3], [... | 0.888081 | 0.515925 |
import argparse
import os
import chainer
import numpy as np
from PIL import Image
import chainer.functions as F
import chainer.links as L
from chainer import initializers
from chainer import training
from chainer import Variable
from chainer import cuda
from chainer.dataset import iterator as iterator_module
from chain... | CIFAR-10/main.py | import argparse
import os
import chainer
import numpy as np
from PIL import Image
import chainer.functions as F
import chainer.links as L
from chainer import initializers
from chainer import training
from chainer import Variable
from chainer import cuda
from chainer.dataset import iterator as iterator_module
from chain... | 0.475118 | 0.144692 |
import sublime_plugin, sublime
import re
from time import time
wheel = [
(255,0,0),
(255,51,0),
(255,102,0),
(255,128,0),
(255,153,0),
(255,178,0),
(255,204,0),
(255,229,0),
(255,255,0),
(204,255,0),
(153,255,0),
(51,255,0),
(0,204,0),
(0,178,102),
(0,153,153... | colortip.py | import sublime_plugin, sublime
import re
from time import time
wheel = [
(255,0,0),
(255,51,0),
(255,102,0),
(255,128,0),
(255,153,0),
(255,178,0),
(255,204,0),
(255,229,0),
(255,255,0),
(204,255,0),
(153,255,0),
(51,255,0),
(0,204,0),
(0,178,102),
(0,153,153... | 0.338186 | 0.155784 |
import asyncio
import itertools
import os
import pprint
from collections import namedtuple
from cryptology import ClientWriterStub, Keys, run_client, exceptions
from datetime import datetime
from decimal import Decimal
from typing import Iterable
SERVER = os.getenv('SERVER', 'ws://127.0.0.1:8080')
Order = namedtuple(... | examples/client.py | import asyncio
import itertools
import os
import pprint
from collections import namedtuple
from cryptology import ClientWriterStub, Keys, run_client, exceptions
from datetime import datetime
from decimal import Decimal
from typing import Iterable
SERVER = os.getenv('SERVER', 'ws://127.0.0.1:8080')
Order = namedtuple(... | 0.402275 | 0.101456 |
import argparse
import matplotlib.pyplot as plt
import numpy as np
import scipy.stats as stats
import sys
sys.path.append('../')
from PDE_solver import SIR_PDEroutine
from Likelihood import log_likelihood_models
"""
Usage:
python Pde_inference.py \
--infectious_time_distribution exponential
--contact_interva... | Examples/pde_example.py | import argparse
import matplotlib.pyplot as plt
import numpy as np
import scipy.stats as stats
import sys
sys.path.append('../')
from PDE_solver import SIR_PDEroutine
from Likelihood import log_likelihood_models
"""
Usage:
python Pde_inference.py \
--infectious_time_distribution exponential
--contact_interva... | 0.388386 | 0.238406 |
from __future__ import absolute_import, division, print_function, unicode_literals
import logging
import numpy as np
from art.config import ART_NUMPY_DTYPE
from art.defences.preprocessor.preprocessor import Preprocessor
logger = logging.getLogger(__name__)
class PixelDefend(Preprocessor):
"""
Implement th... | art/defences/preprocessor/pixel_defend.py | from __future__ import absolute_import, division, print_function, unicode_literals
import logging
import numpy as np
from art.config import ART_NUMPY_DTYPE
from art.defences.preprocessor.preprocessor import Preprocessor
logger = logging.getLogger(__name__)
class PixelDefend(Preprocessor):
"""
Implement th... | 0.932561 | 0.675537 |
from enum import Enum
import logging
import asyncio
from azure.iot.device.aio import IoTHubModuleClient
from azure.iot.device import MethodResponse
# TODO: Module 2 Module Comms & Upstream Telemetry/Messages
class Sample_Twin_Properties():
"""
Class encapsulating the Twin Properties for this module.
"""
... | EdgeSolution/modules/SampleModule/sample_module.py | from enum import Enum
import logging
import asyncio
from azure.iot.device.aio import IoTHubModuleClient
from azure.iot.device import MethodResponse
# TODO: Module 2 Module Comms & Upstream Telemetry/Messages
class Sample_Twin_Properties():
"""
Class encapsulating the Twin Properties for this module.
"""
... | 0.427038 | 0.107017 |
from model.contact import Contact
import string
import random
import os.path
import jsonpickle
import getopt
import sys
from fixture.orm import ORMFixture
try:
opts, args = getopt.getopt(sys.argv[1:], "n:f:", ["number of contacts", "file"])
except getopt.GetoptError as err:
getopt.usage()
sys.exit(2)
n = 2
... | generator/contacts.py | from model.contact import Contact
import string
import random
import os.path
import jsonpickle
import getopt
import sys
from fixture.orm import ORMFixture
try:
opts, args = getopt.getopt(sys.argv[1:], "n:f:", ["number of contacts", "file"])
except getopt.GetoptError as err:
getopt.usage()
sys.exit(2)
n = 2
... | 0.145874 | 0.148386 |
import os
if "GDAL_DATA" in list(os.environ.keys()):
del os.environ["GDAL_DATA"]
if "PROJ_LIB" in list(os.environ.keys()):
del os.environ["PROJ_LIB"]
from distutils.version import LooseVersion
import rasterio as rio
from rasterio.crs import CRS as RioCRS
from pyproj.crs import CRS
from pyproj.enums import Wk... | component/scripts/compute_areas.py | import os
if "GDAL_DATA" in list(os.environ.keys()):
del os.environ["GDAL_DATA"]
if "PROJ_LIB" in list(os.environ.keys()):
del os.environ["PROJ_LIB"]
from distutils.version import LooseVersion
import rasterio as rio
from rasterio.crs import CRS as RioCRS
from pyproj.crs import CRS
from pyproj.enums import Wk... | 0.525125 | 0.253006 |
import glob
import os
import shutil
import subprocess
import pytest
from unit.applications.proto import TestApplicationProto
from unit.option import option
class TestApplicationJava(TestApplicationProto):
application_type = "java"
def prepare_env(self, script):
app_path = option.temp_dir + '/java'
... | test/unit/applications/lang/java.py | import glob
import os
import shutil
import subprocess
import pytest
from unit.applications.proto import TestApplicationProto
from unit.option import option
class TestApplicationJava(TestApplicationProto):
application_type = "java"
def prepare_env(self, script):
app_path = option.temp_dir + '/java'
... | 0.160792 | 0.092196 |
import xml.dom.minidom
#===============================================================================
#===============================================================================
def getNodeContent(node):
if node.childNodes is not None and len(node.childNodes) == 1:
return node.childNodes[0].nodeVal... | scripts/moduledb.py |
import xml.dom.minidom
#===============================================================================
#===============================================================================
def getNodeContent(node):
if node.childNodes is not None and len(node.childNodes) == 1:
return node.childNodes[0].nodeVal... | 0.461745 | 0.178812 |
from typing import Dict, List, cast
import psycopg2
import psycopg2.extras
class MetricsExporter:
__connection = None
__bufferSize = 10000
__bufferMetrics: List[List[float]] = []
__metricsAcc: List[Dict[str, float]] = []
__metricsNames: List[str] = []
__insertSqlNames: str
__bufferLen = 0
... | metrics_exporter/MetricsExporter.py | from typing import Dict, List, cast
import psycopg2
import psycopg2.extras
class MetricsExporter:
__connection = None
__bufferSize = 10000
__bufferMetrics: List[List[float]] = []
__metricsAcc: List[Dict[str, float]] = []
__metricsNames: List[str] = []
__insertSqlNames: str
__bufferLen = 0
... | 0.706596 | 0.188492 |
from bs4 import BeautifulSoup
import numpy as np
import requests
import itertools
import sys
from wordcloud import WordCloud
def find_between(in_str, start='>', end='<'):
""" Find string between two search patterns.
"""
return in_str.split(start)[1].split(end)[0]
def unquote_str(in_str):
""" Decode ... | stackoverflow_users_taginfo.py | from bs4 import BeautifulSoup
import numpy as np
import requests
import itertools
import sys
from wordcloud import WordCloud
def find_between(in_str, start='>', end='<'):
""" Find string between two search patterns.
"""
return in_str.split(start)[1].split(end)[0]
def unquote_str(in_str):
""" Decode ... | 0.52902 | 0.38523 |
import json, os, shutil, re
from datetime import datetime
# python3 -m pip install python-frontmatter
import frontmatter
sitetree = {}
site_root = '.'
index_name = 'index'
content_root = '{}/-/content'.format(site_root)
sitetree_file_path = '{}/-/meta/sitetree.json'.format(site_root)
template_path = '{}/-/template'.... | -/utils/sitetree.py | import json, os, shutil, re
from datetime import datetime
# python3 -m pip install python-frontmatter
import frontmatter
sitetree = {}
site_root = '.'
index_name = 'index'
content_root = '{}/-/content'.format(site_root)
sitetree_file_path = '{}/-/meta/sitetree.json'.format(site_root)
template_path = '{}/-/template'.... | 0.098047 | 0.069922 |
from mako.template import Template
from mako.lookup import TemplateLookup
from core.weexceptions import DevException
from core.loggers import log
from core import modules
import utils
from core import messages
import re
import os
import _thread
class Os:
"""Represent the operating system vector compatibility.
... | packages/weevely/core/vectors.py | from mako.template import Template
from mako.lookup import TemplateLookup
from core.weexceptions import DevException
from core.loggers import log
from core import modules
import utils
from core import messages
import re
import os
import _thread
class Os:
"""Represent the operating system vector compatibility.
... | 0.881079 | 0.374791 |
import GPy
import GPyOpt
import numpy as np
from sys import path
import pickle
import time
path.append("..")
path.append("../..")
path.append("../../..")
from solver import SimulatedAnnealingSolver, RandomSolver
import map_converter as m
def bayesian_optimization_min_dist_simulated_annealing(x):
fs = open("../../... | master/scripts/planner/solvers/hyperparameter_optimization/bayesian_optimization_min_dist_simulated_annealing.py | import GPy
import GPyOpt
import numpy as np
from sys import path
import pickle
import time
path.append("..")
path.append("../..")
path.append("../../..")
from solver import SimulatedAnnealingSolver, RandomSolver
import map_converter as m
def bayesian_optimization_min_dist_simulated_annealing(x):
fs = open("../../... | 0.271638 | 0.234396 |
import warnings
import pulumi
import pulumi.runtime
from typing import Any, Mapping, Optional, Sequence, Union, overload
from .. import _utilities
__all__ = ['InstanceArgs', 'Instance']
@pulumi.input_type
class InstanceArgs:
def __init__(__self__, *,
database_name: pulumi.Input[str],
... | sdk/python/pulumi_gandi/simplehosting/instance.py |
import warnings
import pulumi
import pulumi.runtime
from typing import Any, Mapping, Optional, Sequence, Union, overload
from .. import _utilities
__all__ = ['InstanceArgs', 'Instance']
@pulumi.input_type
class InstanceArgs:
def __init__(__self__, *,
database_name: pulumi.Input[str],
... | 0.834272 | 0.069858 |
import argparse
import math
import os
import time
import numpy as np
from easydict import EasyDict as edict
import moxing
import mindspore.common.dtype as mstype
from mindspore import context, Tensor, load_checkpoint, export
from mindspore.nn.wrap.loss_scale import DynamicLossScaleUpdateCell
from mindspore.nn import A... | research/nlp/gpt2/modelarts/start_train_language_model.py | import argparse
import math
import os
import time
import numpy as np
from easydict import EasyDict as edict
import moxing
import mindspore.common.dtype as mstype
from mindspore import context, Tensor, load_checkpoint, export
from mindspore.nn.wrap.loss_scale import DynamicLossScaleUpdateCell
from mindspore.nn import A... | 0.612426 | 0.188455 |
# Author: <NAME> (<EMAIL>)
# Copyright (C) 2004-2019 by
# <NAME> <<EMAIL>>
# <NAME> <<EMAIL>>
# <NAME> <<EMAIL>>
# All rights reserved.
# BSD license.
import random
try:
import pygraphviz
from networkx.drawing.nx_agraph import graphviz_layout
except ImportError:
try:
import pydo... | rasa_test/share/doc/networkx-2.3/examples/drawing/plot_atlas.py | # Author: <NAME> (<EMAIL>)
# Copyright (C) 2004-2019 by
# <NAME> <<EMAIL>>
# <NAME> <<EMAIL>>
# <NAME> <<EMAIL>>
# All rights reserved.
# BSD license.
import random
try:
import pygraphviz
from networkx.drawing.nx_agraph import graphviz_layout
except ImportError:
try:
import pydo... | 0.581303 | 0.383699 |
import cv2
import datetime
import numpy as np
import tensorflow as tf
from tensorflow.keras.preprocessing import image
from tensorflow.keras.applications.resnet50 import preprocess_input
from tensorflow.python.compiler.tensorrt import trt_convert as trt
from tensorflow.python.saved_model import tag_constants
import jso... | Inference/inference-trt.py | import cv2
import datetime
import numpy as np
import tensorflow as tf
from tensorflow.keras.preprocessing import image
from tensorflow.keras.applications.resnet50 import preprocess_input
from tensorflow.python.compiler.tensorrt import trt_convert as trt
from tensorflow.python.saved_model import tag_constants
import jso... | 0.741206 | 0.422981 |
from typing import Optional, Union
import numpy as np
import pandas as pd
from sklearn.base import BaseEstimator, TransformerMixin
class SigmaClipper(TransformerMixin, BaseEstimator):
"""Clip values exceeding specified sigma levels from median
:param sigma: both low_sigma and high_sigma
:param low_sigma... | mlutil/transform/_scaler.py | from typing import Optional, Union
import numpy as np
import pandas as pd
from sklearn.base import BaseEstimator, TransformerMixin
class SigmaClipper(TransformerMixin, BaseEstimator):
"""Clip values exceeding specified sigma levels from median
:param sigma: both low_sigma and high_sigma
:param low_sigma... | 0.954932 | 0.750118 |
import collections
import functools
from ggrc.utils import helpers
class ImmutableDict(collections.Mapping):
"""An immutable wrapper for defaultdict with False by default."""
__slots__ = ("_dict", "_hash")
DEFAULT_VALUE = False
def __init__(self, **kwargs):
super(ImmutableDict, self).__init__()
sel... | src/ggrc/utils/rules.py | import collections
import functools
from ggrc.utils import helpers
class ImmutableDict(collections.Mapping):
"""An immutable wrapper for defaultdict with False by default."""
__slots__ = ("_dict", "_hash")
DEFAULT_VALUE = False
def __init__(self, **kwargs):
super(ImmutableDict, self).__init__()
sel... | 0.800458 | 0.194999 |
from django.test import TestCase
from django.contrib.sites.models import Site
from zinnia.models.entry import Entry
from zinnia.models.category import Category
from zinnia.managers import PUBLISHED
class CategoryTestCase(TestCase):
def setUp(self):
self.site = Site.objects.get_current()
self.cat... | zinnia/tests/category.py | from django.test import TestCase
from django.contrib.sites.models import Site
from zinnia.models.entry import Entry
from zinnia.models.category import Category
from zinnia.managers import PUBLISHED
class CategoryTestCase(TestCase):
def setUp(self):
self.site = Site.objects.get_current()
self.cat... | 0.492432 | 0.348728 |
from unittest import TestCase
from mock import Mock, patch
from pyramid import testing
from pyramid.request import Request
from webtest import TestApp
from requests.models import Response
from unicore.distribute.api.proxy import ProxyView, Proxy
from unicore.distribute.api import main
class TestProxy(TestCase):
... | unicore/distribute/tests/test_proxy.py | from unittest import TestCase
from mock import Mock, patch
from pyramid import testing
from pyramid.request import Request
from webtest import TestApp
from requests.models import Response
from unicore.distribute.api.proxy import ProxyView, Proxy
from unicore.distribute.api import main
class TestProxy(TestCase):
... | 0.595493 | 0.351339 |
import typing as t
import os
from typing import Dict, Tuple, Sequence,List
from jinja2 import Environment, PackageLoader, select_autoescape,Template
import re
from plugins.ISpecialID import IStag,IDtag,IBtag,ITag,ICodePreproc
class MyPDefine(ICodePreproc):
kobj=None
def getName(self) -> str:
return 'My... | jupyter_MyNodejs_kernel/plugins/Pdefine.py | import typing as t
import os
from typing import Dict, Tuple, Sequence,List
from jinja2 import Environment, PackageLoader, select_autoescape,Template
import re
from plugins.ISpecialID import IStag,IDtag,IBtag,ITag,ICodePreproc
class MyPDefine(ICodePreproc):
kobj=None
def getName(self) -> str:
return 'My... | 0.360714 | 0.111362 |
"""Runs a batch job for performing Tensorflow Model Analysis."""
# pytype: skip-file
from __future__ import absolute_import, division, print_function
import argparse
import tensorflow as tf
import tensorflow_model_analysis as tfma
from tensorflow_model_analysis.evaluators import evaluator
import apache_beam as bea... | sdks/python/apache_beam/testing/benchmarks/chicago_taxi/process_tfma.py | """Runs a batch job for performing Tensorflow Model Analysis."""
# pytype: skip-file
from __future__ import absolute_import, division, print_function
import argparse
import tensorflow as tf
import tensorflow_model_analysis as tfma
from tensorflow_model_analysis.evaluators import evaluator
import apache_beam as bea... | 0.907185 | 0.42668 |
from __future__ import (absolute_import, division, print_function)
from tamoc import ambient, blowout
from tamoc import dbm_utilities
from tamoc import particle_size_models as psm
import test_sbm
from datetime import datetime
from netCDF4 import date2num
import os
import numpy as np
from numpy.testing import asser... | test/test_psm.py |
from __future__ import (absolute_import, division, print_function)
from tamoc import ambient, blowout
from tamoc import dbm_utilities
from tamoc import particle_size_models as psm
import test_sbm
from datetime import datetime
from netCDF4 import date2num
import os
import numpy as np
from numpy.testing import asser... | 0.856197 | 0.525917 |
import ctypes
import gc
import logging
import time
import pytest
from pyvisa import constants, errors
from pyvisa.constants import EventType, ResourceAttribute
from pyvisa.resources import Resource
from .resource_utils import (
EventAwareResourceTestCaseMixin,
LockableResourceTestCaseMixin,
ResourceTestC... | pyvisa/testsuite/keysight_assisted_tests/messagebased_resource_utils.py | import ctypes
import gc
import logging
import time
import pytest
from pyvisa import constants, errors
from pyvisa.constants import EventType, ResourceAttribute
from pyvisa.resources import Resource
from .resource_utils import (
EventAwareResourceTestCaseMixin,
LockableResourceTestCaseMixin,
ResourceTestC... | 0.651577 | 0.337558 |
from unittest import mock
from unittest.mock import call
from airflow_breeze.utils.docker_command_utils import check_docker_compose_version, check_docker_version
@mock.patch('airflow_breeze.utils.docker_command_utils.run_command')
@mock.patch('airflow_breeze.utils.docker_command_utils.console')
def test_check_docke... | dev/breeze/tests/test_docker_command_utils.py |
from unittest import mock
from unittest.mock import call
from airflow_breeze.utils.docker_command_utils import check_docker_compose_version, check_docker_version
@mock.patch('airflow_breeze.utils.docker_command_utils.run_command')
@mock.patch('airflow_breeze.utils.docker_command_utils.console')
def test_check_docke... | 0.61682 | 0.41478 |
# Import libraries necessary for this project
import numpy as np
import pandas as pd
from sklearn.model_selection import ShuffleSplit
# Import supplementary visualizations code visuals.py
import visuals as vs
# Pretty display for notebooks
# %matplotlib inline
# Load the Boston housing dataset
data = pd.read_csv('Ho... | Boston Housing Prices/booston_housing.py | # Import libraries necessary for this project
import numpy as np
import pandas as pd
from sklearn.model_selection import ShuffleSplit
# Import supplementary visualizations code visuals.py
import visuals as vs
# Pretty display for notebooks
# %matplotlib inline
# Load the Boston housing dataset
data = pd.read_csv('Ho... | 0.625438 | 0.755141 |
from __future__ import print_function
import BaseHTTPServer
import sys
from typing import cast
from typing import Optional, Tuple # NOQA, pylint: disable=unused-import
import pynullweb.content
import pynullweb.header
import pynullweb.server # NOQA, pylint: disable=unused-import
ACCEPT_HEADERS = pynullweb.content... | pynullweb/handler.py | from __future__ import print_function
import BaseHTTPServer
import sys
from typing import cast
from typing import Optional, Tuple # NOQA, pylint: disable=unused-import
import pynullweb.content
import pynullweb.header
import pynullweb.server # NOQA, pylint: disable=unused-import
ACCEPT_HEADERS = pynullweb.content... | 0.636353 | 0.077448 |
import sys
import time
import json
import getpass
import codecs
from PTTLibrary import PTT
PTTBot = None
ResPath = './OldBug/'
def End():
PTTBot.logout()
sys.exit()
def FastPushError():
Board = 'Test'
ErrCode, NewestIndex = PTTBot.getNewestIndex(Board=Board)
if ErrCode != PTT.ErrorCode.Success... | OldBug.py | import sys
import time
import json
import getpass
import codecs
from PTTLibrary import PTT
PTTBot = None
ResPath = './OldBug/'
def End():
PTTBot.logout()
sys.exit()
def FastPushError():
Board = 'Test'
ErrCode, NewestIndex = PTTBot.getNewestIndex(Board=Board)
if ErrCode != PTT.ErrorCode.Success... | 0.113187 | 0.061819 |
import fix_paths
from models.author import Author
from models.commit import Commit
from models.file import File
from models.file_diff import FileDiff
from models.patch import Patch
import common
from collections import defaultdict
from datetime import datetime
from flask import Flask, render_template
import json
from... | visualization/main.py | import fix_paths
from models.author import Author
from models.commit import Commit
from models.file import File
from models.file_diff import FileDiff
from models.patch import Patch
import common
from collections import defaultdict
from datetime import datetime
from flask import Flask, render_template
import json
from... | 0.340156 | 0.266313 |
import Header
from Header import *
import TreeUtilFunc
from TreeUtilFunc import *
#-------------------------------------------------
""" this is a function to recombine two parent trees
this operation is termed as prune delete graph recombination """
def Prune_Del_Graph_Recomb(parent_tree1, parent_tree2):
if (DEBUG... | Server/PythonCrawl/SOURCE_CODE/Tree_Recombination.py | import Header
from Header import *
import TreeUtilFunc
from TreeUtilFunc import *
#-------------------------------------------------
""" this is a function to recombine two parent trees
this operation is termed as prune delete graph recombination """
def Prune_Del_Graph_Recomb(parent_tree1, parent_tree2):
if (DEBUG... | 0.241758 | 0.526221 |
from sanic import Blueprint, response
from urllib.parse import unquote
from bs4 import BeautifulSoup
from pprint import pprint
from owllook.fetcher.function import get_time, get_netloc
from owllook.fetcher.extract_novels import extract_chapters
from owllook.fetcher.decorators import authenticator, auth_params
from owl... | owllook/views/api_blueprint.py | from sanic import Blueprint, response
from urllib.parse import unquote
from bs4 import BeautifulSoup
from pprint import pprint
from owllook.fetcher.function import get_time, get_netloc
from owllook.fetcher.extract_novels import extract_chapters
from owllook.fetcher.decorators import authenticator, auth_params
from owl... | 0.187728 | 0.087175 |
from msrest.serialization import Model
class FrontdoorUpdateParameters(Model):
"""The properties needed to update a Frontdoor.
:param friendly_name: A friendly name for the frontdoor
:type friendly_name: str
:param routing_rules: Routing rules associated with this Frontdoor.
:type routing_rules:... | src/front-door/azext_front_door/vendored_sdks/models/frontdoor_update_parameters.py |
from msrest.serialization import Model
class FrontdoorUpdateParameters(Model):
"""The properties needed to update a Frontdoor.
:param friendly_name: A friendly name for the frontdoor
:type friendly_name: str
:param routing_rules: Routing rules associated with this Frontdoor.
:type routing_rules:... | 0.907968 | 0.179064 |
import sys
import pandas as pd
import numpy as np
# determine if we are loading from a jupyter notebook (to make pretty progress bars)
if 'ipykernel' in sys.modules:
from tqdm.notebook import tqdm
else:
from tqdm import tqdm
from pyscisci.utils import zip2dict, check4columns, groupby_count, groupby_range
fro... | pyscisci/metrics/author.py | import sys
import pandas as pd
import numpy as np
# determine if we are loading from a jupyter notebook (to make pretty progress bars)
if 'ipykernel' in sys.modules:
from tqdm.notebook import tqdm
else:
from tqdm import tqdm
from pyscisci.utils import zip2dict, check4columns, groupby_count, groupby_range
fro... | 0.639736 | 0.543772 |
from PIL import Image
import imghdr
import math
import ast
import random
# the structure of the for loops for the encoding functions was inspired by:
# https://hackernoon.com/simple-image-steganography-in-python-18c7b534854f
# particularly how an iterator is used to iterate through the bits of the secret mes... | stegoImgTxt.py |
from PIL import Image
import imghdr
import math
import ast
import random
# the structure of the for loops for the encoding functions was inspired by:
# https://hackernoon.com/simple-image-steganography-in-python-18c7b534854f
# particularly how an iterator is used to iterate through the bits of the secret mes... | 0.227555 | 0.120026 |
import sys
import selectors
import struct
from virgo.core.transport import set_selector_events_mask, read_socket, write_socket, \
json_encode, json_decode, close_socket
class ClientMessage:
def __init__(self, selector, sock, addr, request):
self.selector = selector
self.sock = sock
sel... | gui_client/message.py | import sys
import selectors
import struct
from virgo.core.transport import set_selector_events_mask, read_socket, write_socket, \
json_encode, json_decode, close_socket
class ClientMessage:
def __init__(self, selector, sock, addr, request):
self.selector = selector
self.sock = sock
sel... | 0.199542 | 0.067026 |
from webcamlib.Config import Config, ConfigTemperature
import logging
from pathlib import PosixPath
from abc import ABC, abstractproperty
from webcamlib.Exceptions import DeviceError, ConfigError
class AbstractLightSensor(ABC):
""" Base class for the light sensor """
def __init__(self, lightsensor_config):
... | webcamlib/LightSensor.py | from webcamlib.Config import Config, ConfigTemperature
import logging
from pathlib import PosixPath
from abc import ABC, abstractproperty
from webcamlib.Exceptions import DeviceError, ConfigError
class AbstractLightSensor(ABC):
""" Base class for the light sensor """
def __init__(self, lightsensor_config):
... | 0.735831 | 0.131257 |
import warnings
import pulumi
import pulumi.runtime
from typing import Any, Mapping, Optional, Sequence, Union, overload
from .. import _utilities
__all__ = ['DatabaseArgs', 'Database']
@pulumi.input_type
class DatabaseArgs:
def __init__(__self__, *,
instance_id: pulumi.Input[str],
... | sdk/python/pulumi_alicloud/rds/database.py |
import warnings
import pulumi
import pulumi.runtime
from typing import Any, Mapping, Optional, Sequence, Union, overload
from .. import _utilities
__all__ = ['DatabaseArgs', 'Database']
@pulumi.input_type
class DatabaseArgs:
def __init__(__self__, *,
instance_id: pulumi.Input[str],
... | 0.812012 | 0.092976 |
import tensorflow.compat.v1 as tf
import numpy as np
from .utils import lazy_property
class Encoder(object):
def __init__(self, input, latent_space_size, num_filters, kernel_size, strides, batch_norm, is_training=False):
self._input = input
self._latent_space_size = latent_space_size
sel... | auto_pose/ae/encoder.py |
import tensorflow.compat.v1 as tf
import numpy as np
from .utils import lazy_property
class Encoder(object):
def __init__(self, input, latent_space_size, num_filters, kernel_size, strides, batch_norm, is_training=False):
self._input = input
self._latent_space_size = latent_space_size
sel... | 0.922905 | 0.373076 |
from ._models_py3 import AssociatedWorkspace
from ._models_py3 import AvailableServiceTier
from ._models_py3 import AzureEntityResource
from ._models_py3 import AzureResourceProperties
from ._models_py3 import CapacityReservationProperties
from ._models_py3 import Cluster
from ._models_py3 import ClusterListResult
fro... | sdk/loganalytics/azure-mgmt-loganalytics/azure/mgmt/loganalytics/models/__init__.py |
from ._models_py3 import AssociatedWorkspace
from ._models_py3 import AvailableServiceTier
from ._models_py3 import AzureEntityResource
from ._models_py3 import AzureResourceProperties
from ._models_py3 import CapacityReservationProperties
from ._models_py3 import Cluster
from ._models_py3 import ClusterListResult
fro... | 0.564699 | 0.106365 |
from configurable_automation import ConfigurableAutomation
from lib.actions import Action
from lib.presence_helper import HOME_PERSON_STATUSES, PERSON_STATUS_ARRIVING, \
PERSON_STATUS_AWAY, PRESENCE_MODE_SOMEONE_IS_ARRIVING_HOME, \
PRESENCE_MODE_SOMEONE_IS_HOME, PRESENCE_MODE_NO_ONE_IS_HOME, \
PRESENCE_MODE... | appdaemon/apps/presence_mode_updater.py | from configurable_automation import ConfigurableAutomation
from lib.actions import Action
from lib.presence_helper import HOME_PERSON_STATUSES, PERSON_STATUS_ARRIVING, \
PERSON_STATUS_AWAY, PRESENCE_MODE_SOMEONE_IS_ARRIVING_HOME, \
PRESENCE_MODE_SOMEONE_IS_HOME, PRESENCE_MODE_NO_ONE_IS_HOME, \
PRESENCE_MODE... | 0.435061 | 0.094594 |
import numpy as np
import torch
import math
import torch.nn as nn
import torch.nn.functional as F
class WideBasic(nn.Module):
def __init__(
self, wrapped_conv, input_size, in_c, out_c, stride, dropout_rate, mod=True, batchnorm_momentum=0.01,
):
super().__init__()
self.mod = mod
... | net/wide_resnet.py |
import numpy as np
import torch
import math
import torch.nn as nn
import torch.nn.functional as F
class WideBasic(nn.Module):
def __init__(
self, wrapped_conv, input_size, in_c, out_c, stride, dropout_rate, mod=True, batchnorm_momentum=0.01,
):
super().__init__()
self.mod = mod
... | 0.929592 | 0.355649 |
# Do not use urllib's HTTP GET and POST mechanisms.
# Write your own HTTP GET and POST
# The point is to understand what you have to send and get experience with it
import sys
import socket
import re
# you may use urllib to encode data appropriately
import urllib.parse
def help():
print("httpclient.py [GET/POST]... | httpclient.py |
# Do not use urllib's HTTP GET and POST mechanisms.
# Write your own HTTP GET and POST
# The point is to understand what you have to send and get experience with it
import sys
import socket
import re
# you may use urllib to encode data appropriately
import urllib.parse
def help():
print("httpclient.py [GET/POST]... | 0.467332 | 0.199172 |
import argparse
from PIL import Image, ImageFont, ImageDraw
from font_hanken_grotesk import HankenGroteskBold, HankenGroteskMedium
from font_intuitive import Intuitive
print("""Inky pHAT/wHAT: Hello... my name is:
Use Inky pHAT/wHAT as a personalised name badge!
""")
# Command line arguments to set display type a... | examples/name-badge.py |
import argparse
from PIL import Image, ImageFont, ImageDraw
from font_hanken_grotesk import HankenGroteskBold, HankenGroteskMedium
from font_intuitive import Intuitive
print("""Inky pHAT/wHAT: Hello... my name is:
Use Inky pHAT/wHAT as a personalised name badge!
""")
# Command line arguments to set display type a... | 0.545044 | 0.214362 |
print(__doc__)
import numpy as np
from movement_primitives.promp import ProMP
import matplotlib.pyplot as plt
n_weights_per_dim = 100
promp = ProMP(n_dims=1, n_weights_per_dim=n_weights_per_dim)
random_state = np.random.RandomState(10)
n_demos = 10
n_steps = 101
T = np.empty((n_demos, n_steps))
T[:, :] = np.linsp... | examples/plot_promp_velocities.py | print(__doc__)
import numpy as np
from movement_primitives.promp import ProMP
import matplotlib.pyplot as plt
n_weights_per_dim = 100
promp = ProMP(n_dims=1, n_weights_per_dim=n_weights_per_dim)
random_state = np.random.RandomState(10)
n_demos = 10
n_steps = 101
T = np.empty((n_demos, n_steps))
T[:, :] = np.linsp... | 0.531453 | 0.562657 |
from utils import walkTable, showErrors, getLine
def verifyReturn():
content = walkTable()
varTypes = []
paramTypes = []
retorno = []
for item in content:
if 'info' in item and item['info'][0]['categoria'] == 'variavel':
varTypes.append(item['info'][0]['lexema']+'-'+item['tipo'... | src/walkSymbolTable.py | from utils import walkTable, showErrors, getLine
def verifyReturn():
content = walkTable()
varTypes = []
paramTypes = []
retorno = []
for item in content:
if 'info' in item and item['info'][0]['categoria'] == 'variavel':
varTypes.append(item['info'][0]['lexema']+'-'+item['tipo'... | 0.108183 | 0.133218 |
import gevent
import json
import logging
import subprocess
from jadi import component
import aj
from aj.api.http import url, HttpPlugin
from aj.plugins import PluginManager, DirectoryPluginProvider
from aj.api.endpoint import endpoint
@component(HttpPlugin)
class Handler(HttpPlugin):
def __init__(self, context)... | plugins/core/views/main.py | import gevent
import json
import logging
import subprocess
from jadi import component
import aj
from aj.api.http import url, HttpPlugin
from aj.plugins import PluginManager, DirectoryPluginProvider
from aj.api.endpoint import endpoint
@component(HttpPlugin)
class Handler(HttpPlugin):
def __init__(self, context)... | 0.216177 | 0.036254 |
import torch
from tango.common.registrable import Registrable
class Optimizer(torch.optim.Optimizer, Registrable):
"""
A :class:`~tango.common.Registrable` version of a PyTorch
:class:`torch.optim.Optimizer`.
All `built-in PyTorch optimizers
<https://pytorch.org/docs/stable/optim.html#algorithms... | tango/integrations/torch/optim.py | import torch
from tango.common.registrable import Registrable
class Optimizer(torch.optim.Optimizer, Registrable):
"""
A :class:`~tango.common.Registrable` version of a PyTorch
:class:`torch.optim.Optimizer`.
All `built-in PyTorch optimizers
<https://pytorch.org/docs/stable/optim.html#algorithms... | 0.8874 | 0.474692 |
import time
from datetime import datetime, timedelta
import unittest
from opcua import Client
from opcua import Server
from opcua import ua
from opcua.server.history_sql import HistorySQLite
from opcua.server.history import HistoryDict
from tests_common import CommonTests, add_server_methods
from opcua.common.event... | tests/python-opcua/tests/tests_history.py | import time
from datetime import datetime, timedelta
import unittest
from opcua import Client
from opcua import Server
from opcua import ua
from opcua.server.history_sql import HistorySQLite
from opcua.server.history import HistoryDict
from tests_common import CommonTests, add_server_methods
from opcua.common.event... | 0.382372 | 0.256884 |
import graphene
from graphql.validation.rules import NoUnusedFragments, specified_rules
from wagtail.core import hooks
from .registry import registry
from .settings import grapple_settings
# HACK: Remove NoUnusedFragments validator
# Due to the way previews work on the frontend, we need to pass all
# fragments into t... | grapple/schema.py | import graphene
from graphql.validation.rules import NoUnusedFragments, specified_rules
from wagtail.core import hooks
from .registry import registry
from .settings import grapple_settings
# HACK: Remove NoUnusedFragments validator
# Due to the way previews work on the frontend, we need to pass all
# fragments into t... | 0.592667 | 0.213234 |
from __future__ import absolute_import
from __future__ import division
from __future__ import print_function
# pylint: disable=g-direct-tensorflow-import
from tensorflow.compiler.xla.python import xla_client
from tensorflow.compiler.xla.python import xla_extension as _xla
# pylint: enable=g-direct-tensorflow-import
... | tensorflow/compiler/xla/python/xrt.py | from __future__ import absolute_import
from __future__ import division
from __future__ import print_function
# pylint: disable=g-direct-tensorflow-import
from tensorflow.compiler.xla.python import xla_client
from tensorflow.compiler.xla.python import xla_extension as _xla
# pylint: enable=g-direct-tensorflow-import
... | 0.763043 | 0.218461 |
import json
from django.shortcuts import render
from django.contrib import messages
from django.http import HttpResponse, HttpResponseBadRequest
from django.views.generic.base import View
from django.utils.translation import ugettext_lazy as _
from django.template.loader import render_to_string
from django.template im... | oscar_shipping/views.py | import json
from django.shortcuts import render
from django.contrib import messages
from django.http import HttpResponse, HttpResponseBadRequest
from django.views.generic.base import View
from django.utils.translation import ugettext_lazy as _
from django.template.loader import render_to_string
from django.template im... | 0.420243 | 0.076201 |
import unittest
import json
import os
from dateutil.parser import isoparse
from craft_ai import format_property, format_decision_rules, errors
class TestFormatter(unittest.TestCase):
def test_format_property_time_of_day(self):
formatter = format_property("time_of_day")
self.assertEqual(formatt... | tests/test_formatters.py | import unittest
import json
import os
from dateutil.parser import isoparse
from craft_ai import format_property, format_decision_rules, errors
class TestFormatter(unittest.TestCase):
def test_format_property_time_of_day(self):
formatter = format_property("time_of_day")
self.assertEqual(formatt... | 0.633637 | 0.475788 |
from __future__ import absolute_import
import unittest
from time import sleep
import yaml
import semaphore_client
from semaphore_client.models.task import Task # noqa: E501
from semaphore_client.rest import ApiException
from semaphore_client.semaphore_helper import SemaphoreHelper
import names
yaml.Dumper.ignore_a... | semaphore-python-client-generated/test/test_task.py | from __future__ import absolute_import
import unittest
from time import sleep
import yaml
import semaphore_client
from semaphore_client.models.task import Task # noqa: E501
from semaphore_client.rest import ApiException
from semaphore_client.semaphore_helper import SemaphoreHelper
import names
yaml.Dumper.ignore_a... | 0.173813 | 0.075075 |
import sys
import os
import time
import codecs
import subprocess
import requests
import json
# watson 音声認識、翻訳機能、音声合成
import watson_developer_cloud as watson
import speech_api_watson_key as watson_key
class SpeechAPI:
def __init__(self, ):
self.timeOut = 10
self.stt = None
sel... | speech_api_watson.py |
import sys
import os
import time
import codecs
import subprocess
import requests
import json
# watson 音声認識、翻訳機能、音声合成
import watson_developer_cloud as watson
import speech_api_watson_key as watson_key
class SpeechAPI:
def __init__(self, ):
self.timeOut = 10
self.stt = None
sel... | 0.070436 | 0.07703 |
import pyrealsense2 as rs
import numpy as np
import cv2
import tensorflow as tf
from PIL import Image
image_size=200
images = []
# Create a pipeline
pipeline = rs.pipeline()
#Create a config and configure the pipeline to stream
config = rs.config()
config.enable_stream(rs.stream.depth, 640, 360, rs.format.z16, 30)
c... | predict.py | import pyrealsense2 as rs
import numpy as np
import cv2
import tensorflow as tf
from PIL import Image
image_size=200
images = []
# Create a pipeline
pipeline = rs.pipeline()
#Create a config and configure the pipeline to stream
config = rs.config()
config.enable_stream(rs.stream.depth, 640, 360, rs.format.z16, 30)
c... | 0.518059 | 0.220227 |
from unittest import mock
from airflow.providers.google.cloud.transfers.calendar_to_gcs import GoogleCalendarToGCSOperator
API_VERSION = "v3"
CALENDAR_ID = "1234567890"
EVENT = {
'summary': 'Calendar Test Event',
'description': 'A chance to test creating an event from airflow.',
'start': {
'dateT... | tests/providers/google/cloud/transfers/test_calendar_to_gcs.py |
from unittest import mock
from airflow.providers.google.cloud.transfers.calendar_to_gcs import GoogleCalendarToGCSOperator
API_VERSION = "v3"
CALENDAR_ID = "1234567890"
EVENT = {
'summary': 'Calendar Test Event',
'description': 'A chance to test creating an event from airflow.',
'start': {
'dateT... | 0.725162 | 0.438124 |
from datetime import datetime
from dateutil.relativedelta import relativedelta
from psycopg2 import IntegrityError
from odoo import fields
from odoo.exceptions import AccessError, ValidationError, UserError
from odoo.tools import mute_logger, test_reports
from odoo.addons.hr_holidays.tests.common import TestHrHolid... | odoo-13.0/addons/hr_holidays/tests/test_holidays_flow.py |
from datetime import datetime
from dateutil.relativedelta import relativedelta
from psycopg2 import IntegrityError
from odoo import fields
from odoo.exceptions import AccessError, ValidationError, UserError
from odoo.tools import mute_logger, test_reports
from odoo.addons.hr_holidays.tests.common import TestHrHolid... | 0.555676 | 0.167763 |
import logging
import os
import threading
import time
import picamera
"""
Lance la fonction passée en paramètre dans un nouveau thread
"""
def runAsync(fn):
def run(*k, **kw):
t = threading.Thread(target=fn, args=k, kwargs=kw)
t.start()
return t
return run
"""
Mesure le temps éc... | Server/TimeLapse.py |
import logging
import os
import threading
import time
import picamera
"""
Lance la fonction passée en paramètre dans un nouveau thread
"""
def runAsync(fn):
def run(*k, **kw):
t = threading.Thread(target=fn, args=k, kwargs=kw)
t.start()
return t
return run
"""
Mesure le temps éc... | 0.342132 | 0.154249 |
import threading
from Sharing.Sharing import sharing1Dealer, sharing2Dealer
from Reconstruction.Reconstruction import reconstructionDealer1, reconstructionDealer2
from Utils.Utils_function import logMsg
from groups import parametres
par = parametres()
PATH_DATA_USERS = par.PATH_DATA_USERS
FILE_NAME_COMM = par.FILE_NA... | Scripts/Dealer/CustomThreads/ManageClientConnection.py | import threading
from Sharing.Sharing import sharing1Dealer, sharing2Dealer
from Reconstruction.Reconstruction import reconstructionDealer1, reconstructionDealer2
from Utils.Utils_function import logMsg
from groups import parametres
par = parametres()
PATH_DATA_USERS = par.PATH_DATA_USERS
FILE_NAME_COMM = par.FILE_NA... | 0.201106 | 0.200323 |
import numpy as np
import scipy as sp
from scipy.stats import poisson
def invert(x):
return np.linalg.inv(np.array(x, dtype=np.float32))
class Poisson:
def __init__(self, means, covariances):
self.means = np.array(means)
mean_shape = self.means.shape
if len(mean_shape) == 1:
... | python_scripts/multivariate_normal.py | import numpy as np
import scipy as sp
from scipy.stats import poisson
def invert(x):
return np.linalg.inv(np.array(x, dtype=np.float32))
class Poisson:
def __init__(self, means, covariances):
self.means = np.array(means)
mean_shape = self.means.shape
if len(mean_shape) == 1:
... | 0.647352 | 0.573141 |
from collections import OrderedDict
from dataprofiler.data_readers.filepath_or_buffer import FileOrBufferHandler
import json
import warnings
from six import StringIO
import numpy as np
import pandas as pd
from . import data_utils
from .base_data import BaseData
from .structured_mixins import SpreadSheetDataMixin
from ... | dataprofiler/data_readers/json_data.py | from collections import OrderedDict
from dataprofiler.data_readers.filepath_or_buffer import FileOrBufferHandler
import json
import warnings
from six import StringIO
import numpy as np
import pandas as pd
from . import data_utils
from .base_data import BaseData
from .structured_mixins import SpreadSheetDataMixin
from ... | 0.74008 | 0.274187 |
from datetime import timedelta
import numpy as np
import pytest
from pandas.core.dtypes.generic import ABCDateOffset
import pandas as pd
from pandas import Series, TimedeltaIndex, timedelta_range
from pandas.tests.test_base import Ops
import pandas.util.testing as tm
from pandas.tseries.offsets import Day, Hour
c... | pandas/tests/indexes/timedeltas/test_ops.py | from datetime import timedelta
import numpy as np
import pytest
from pandas.core.dtypes.generic import ABCDateOffset
import pandas as pd
from pandas import Series, TimedeltaIndex, timedelta_range
from pandas.tests.test_base import Ops
import pandas.util.testing as tm
from pandas.tseries.offsets import Day, Hour
c... | 0.594434 | 0.604545 |
"""Unit tests for pandas functionality in tiingo"""
import vcr
from unittest import TestCase
from tiingo import TiingoClient
from tiingo.api import APIColumnNameError, InstallPandasException
try:
import pandas as pd
pandas_is_installed = True
except ImportError:
pandas_is_installed = False
class TestTiin... | tests/test_tiingo_pandas.py | """Unit tests for pandas functionality in tiingo"""
import vcr
from unittest import TestCase
from tiingo import TiingoClient
from tiingo.api import APIColumnNameError, InstallPandasException
try:
import pandas as pd
pandas_is_installed = True
except ImportError:
pandas_is_installed = False
class TestTiin... | 0.760828 | 0.682686 |
import math
from submission import Submission
class SilvestreSubmission(Submission):
def run(self, s):
initial_configs, final_configs = self.read_input(s)
current_config = (('.','#','.'),('.','.','#'),('#','#','#'))
n = 0 # iterations number
while n < 18:
# Split
... | day-21/part-2/silvestre.py | import math
from submission import Submission
class SilvestreSubmission(Submission):
def run(self, s):
initial_configs, final_configs = self.read_input(s)
current_config = (('.','#','.'),('.','.','#'),('#','#','#'))
n = 0 # iterations number
while n < 18:
# Split
... | 0.207455 | 0.332798 |
from __future__ import absolute_import, division, print_function
from __future__ import unicode_literals
from sklearn.base import BaseEstimator, TransformerMixin
from sklearn.utils.metaestimators import _BaseComposition
from sklearn.utils.validation import check_is_fitted
import numpy as np
from ..utils.utils import M... | src/direpack/preprocessing/robcent.py | from __future__ import absolute_import, division, print_function
from __future__ import unicode_literals
from sklearn.base import BaseEstimator, TransformerMixin
from sklearn.utils.metaestimators import _BaseComposition
from sklearn.utils.validation import check_is_fitted
import numpy as np
from ..utils.utils import M... | 0.759225 | 0.1526 |
from hashlib import md5
from hashlib import sha1
from urllib.parse import urljoin
from xml.etree import ElementTree as ET
import requests
from defusedxml import ElementTree as DefusedET
class MerchantAPI:
url_root = "https://api.privatbank.ua/p24api/"
def __init__(self, merchant_id: str, merchant_password: ... | myfunds/modules/api/privat24.py | from hashlib import md5
from hashlib import sha1
from urllib.parse import urljoin
from xml.etree import ElementTree as ET
import requests
from defusedxml import ElementTree as DefusedET
class MerchantAPI:
url_root = "https://api.privatbank.ua/p24api/"
def __init__(self, merchant_id: str, merchant_password: ... | 0.555676 | 0.128361 |
import base64
import PySimpleGUI as sg
from sys import platform
import backend
icon = base64.b64encode(open("framework.png", "rb").read())
sg.set_options(font=("Courier New", 12))
backend = backend.Backend()
def LedControl(name):
return [
sg.Input(key="Input " + name, visible=False, enable_events=True,... | main.py | import base64
import PySimpleGUI as sg
from sys import platform
import backend
icon = base64.b64encode(open("framework.png", "rb").read())
sg.set_options(font=("Courier New", 12))
backend = backend.Backend()
def LedControl(name):
return [
sg.Input(key="Input " + name, visible=False, enable_events=True,... | 0.297164 | 0.164248 |
from PIL import Image
from pyautonifty.constants import DRAWING_SIZE
from pyautonifty.helper_fns import rotate
from pyautonifty.pos import Pos
from pyautonifty.drawing import Drawing
from pyautonifty.renderer import Renderer
# Draw an image from file using square pixels
def square_image(drawing, image_name, brush_ra... | examples/square_image.py | from PIL import Image
from pyautonifty.constants import DRAWING_SIZE
from pyautonifty.helper_fns import rotate
from pyautonifty.pos import Pos
from pyautonifty.drawing import Drawing
from pyautonifty.renderer import Renderer
# Draw an image from file using square pixels
def square_image(drawing, image_name, brush_ra... | 0.710427 | 0.30806 |
import os
Test.Summary = '''
Test that Trafficserver rejects requests for host 0
'''
Test.ContinueOnFail = True
HOST1='redirect.test'
redirect_serv = Test.MakeOriginServer("redirect_serv", ip='0.0.0.0')
dns = Test.MakeDNServer("dns")
dns.addRecords(records={HOST1: ['127.0.0.1']})
ts = Test.MakeATSProcess("ts")
ts... | tests/gold_tests/basic/deny0.test.py |
import os
Test.Summary = '''
Test that Trafficserver rejects requests for host 0
'''
Test.ContinueOnFail = True
HOST1='redirect.test'
redirect_serv = Test.MakeOriginServer("redirect_serv", ip='0.0.0.0')
dns = Test.MakeDNServer("dns")
dns.addRecords(records={HOST1: ['127.0.0.1']})
ts = Test.MakeATSProcess("ts")
ts... | 0.366703 | 0.169819 |
"""
Train images augmentation.
Load images and binary masks from train folder, and apply various methods
for transformation. Finally save them in the train folder.
"""
import random, time, csv, os
import numpy as np
import elasticdeform
from scipy import ndimage
import tensorflow as tf
def rotation(image, mask):
... | src/augment.py | """
Train images augmentation.
Load images and binary masks from train folder, and apply various methods
for transformation. Finally save them in the train folder.
"""
import random, time, csv, os
import numpy as np
import elasticdeform
from scipy import ndimage
import tensorflow as tf
def rotation(image, mask):
... | 0.93065 | 0.862062 |
import shutil
import tempfile
import unittest
import asyncio
import logging
import hashlib
from lbry.testcase import AsyncioTestCase
from lbry.conf import Config
from lbry.extras.daemon.storage import SQLiteStorage
from lbry.blob.blob_info import BlobInfo
from lbry.blob.blob_manager import BlobManager
from lbry.stream.... | tests/unit/database/test_SQLiteStorage.py | import shutil
import tempfile
import unittest
import asyncio
import logging
import hashlib
from lbry.testcase import AsyncioTestCase
from lbry.conf import Config
from lbry.extras.daemon.storage import SQLiteStorage
from lbry.blob.blob_info import BlobInfo
from lbry.blob.blob_manager import BlobManager
from lbry.stream.... | 0.415729 | 0.280795 |
import matplotlib.pyplot as plt
import numpy as np
import json
from collections import OrderedDict
from itertools import islice
def parse_data(option):
bytes_dict = dict()
lang_count_dict = dict()
with open("lang_data.jsonl") as lang_data:
count = 0
for item in lang_data:
curren... | generate_bar_chart.py | import matplotlib.pyplot as plt
import numpy as np
import json
from collections import OrderedDict
from itertools import islice
def parse_data(option):
bytes_dict = dict()
lang_count_dict = dict()
with open("lang_data.jsonl") as lang_data:
count = 0
for item in lang_data:
curren... | 0.268078 | 0.273773 |
from flask import Blueprint, Response, request, send_file
from datetime import datetime, timedelta
from dateutil.relativedelta import relativedelta
import pandas as pd
import numpy as np
from io import BytesIO
from .db import engine
from .auth import checkAuth
bp = Blueprint('expenses', __name__, url_prefix... | flaskr/expenses.py | from flask import Blueprint, Response, request, send_file
from datetime import datetime, timedelta
from dateutil.relativedelta import relativedelta
import pandas as pd
import numpy as np
from io import BytesIO
from .db import engine
from .auth import checkAuth
bp = Blueprint('expenses', __name__, url_prefix... | 0.226014 | 0.070816 |
from rest_framework import serializers
from . import models
class ProfileSerializer(serializers.ModelSerializer):
accounts = serializers.StringRelatedField(many=True, read_only=True)
class Meta:
model = models.Profile
fields = [
'id',
'first_name',
'last_... | web/app/core/serializers.py | from rest_framework import serializers
from . import models
class ProfileSerializer(serializers.ModelSerializer):
accounts = serializers.StringRelatedField(many=True, read_only=True)
class Meta:
model = models.Profile
fields = [
'id',
'first_name',
'last_... | 0.559531 | 0.177597 |
from socket import timeout
from urllib.error import HTTPError, URLError
from prometheus_client.metrics_core import GaugeMetricFamily
from flask import current_app
import json
import urllib.request
import urllib.parse
class ViewPowerCollector(object):
def __init__(self, config):
self._config = config
... | prometheus_viewpower/collector.py | from socket import timeout
from urllib.error import HTTPError, URLError
from prometheus_client.metrics_core import GaugeMetricFamily
from flask import current_app
import json
import urllib.request
import urllib.parse
class ViewPowerCollector(object):
def __init__(self, config):
self._config = config
... | 0.52975 | 0.088426 |
import re
import sys
import os
import time
import subprocess
def convert_registry_db(mysql_dump_file, pgsql_dump_file):
mysql_dump = open(mysql_dump_file)
pgsql_dump = open(pgsql_dump_file, "w")
insert_lines = []
for i, line in enumerate(mysql_dump):
line = line.decode("utf8").strip(... | tools/migration/db/util/mysql_pgsql_data_converter.py |
import re
import sys
import os
import time
import subprocess
def convert_registry_db(mysql_dump_file, pgsql_dump_file):
mysql_dump = open(mysql_dump_file)
pgsql_dump = open(pgsql_dump_file, "w")
insert_lines = []
for i, line in enumerate(mysql_dump):
line = line.decode("utf8").strip(... | 0.166777 | 0.059866 |
from PyQt5.QtWidgets import QMainWindow, QWidget, QLabel, QVBoxLayout, QPushButton
from PyQt5.QtCore import Qt, QRect, QCoreApplication, QMetaObject
from PyQt5.QtGui import QIcon, QFont, QPixmap
class Ui_AboutWindow(QMainWindow):
def __init__(self):
super().__init__()
self.setWindowFlags(Qt.Window... | pydebloatx/gui_about.py | from PyQt5.QtWidgets import QMainWindow, QWidget, QLabel, QVBoxLayout, QPushButton
from PyQt5.QtCore import Qt, QRect, QCoreApplication, QMetaObject
from PyQt5.QtGui import QIcon, QFont, QPixmap
class Ui_AboutWindow(QMainWindow):
def __init__(self):
super().__init__()
self.setWindowFlags(Qt.Window... | 0.473414 | 0.087019 |
import mock
import webob.exc
from nova.api.openstack import compute
from nova.api.openstack.compute import extension_info
from nova.api.openstack import extensions
from nova import exception
from nova import test
class fake_bad_extension(object):
name = "fake_bad_extension"
alias = "fake-bad"
class Extens... | nova/tests/unit/api/openstack/compute/test_extensions.py |
import mock
import webob.exc
from nova.api.openstack import compute
from nova.api.openstack.compute import extension_info
from nova.api.openstack import extensions
from nova import exception
from nova import test
class fake_bad_extension(object):
name = "fake_bad_extension"
alias = "fake-bad"
class Extens... | 0.599837 | 0.196229 |
# Django
from django.contrib.auth import authenticate, password_validation
from django.core.validators import RegexValidator
# Django REST Framework
from rest_framework import serializers
from rest_framework.validators import UniqueValidator
# Django REST Framework Simple JWT
from rest_framework_simplejwt.tokens imp... | app/users/serializers/users.py |
# Django
from django.contrib.auth import authenticate, password_validation
from django.core.validators import RegexValidator
# Django REST Framework
from rest_framework import serializers
from rest_framework.validators import UniqueValidator
# Django REST Framework Simple JWT
from rest_framework_simplejwt.tokens imp... | 0.668339 | 0.129458 |
"""Offline training binary."""
from __future__ import absolute_import
from __future__ import division
from __future__ import print_function
import os
from absl import app
from absl import flags
from absl import logging
import gin
import tensorflow as tf0
import tensorflow.compat.v1 as tf
from behavior_regularized... | brac/scripts/train_brac.py |
"""Offline training binary."""
from __future__ import absolute_import
from __future__ import division
from __future__ import print_function
import os
from absl import app
from absl import flags
from absl import logging
import gin
import tensorflow as tf0
import tensorflow.compat.v1 as tf
from behavior_regularized... | 0.67104 | 0.121295 |
from __future__ import unicode_literals
from django.template.response import TemplateResponse
from django.db.models import Q
from django.utils import timezone
from django.utils.translation import get_language_from_request
from django.conf import settings
from django.views.decorators.cache import cache_page
from cms.... | js_sitemap/views.py |
from __future__ import unicode_literals
from django.template.response import TemplateResponse
from django.db.models import Q
from django.utils import timezone
from django.utils.translation import get_language_from_request
from django.conf import settings
from django.views.decorators.cache import cache_page
from cms.... | 0.498535 | 0.063832 |
from discord.ext import commands
import discord
from rtlib import DatabaseManager
class DataManager(DatabaseManager):
DB = "OriginalCommand"
def __init__(self, db):
self.db = db
async def init_table(self, cursor) -> None:
await cursor.create_table(
self.DB, {
... | cogs/original_command.py |
from discord.ext import commands
import discord
from rtlib import DatabaseManager
class DataManager(DatabaseManager):
DB = "OriginalCommand"
def __init__(self, db):
self.db = db
async def init_table(self, cursor) -> None:
await cursor.create_table(
self.DB, {
... | 0.505859 | 0.15925 |
from .. import models as m
def delivery_description(delivery, subgroups, **kwargs):
"""Generate a description of the purchases performed by users in `subgroups`
for `delivery`. The resulting dictionary is used to render HTML as well as
PDF and MS-Excel views. It's used both to display the complete order ... | floreal/views/delivery_description.py |
from .. import models as m
def delivery_description(delivery, subgroups, **kwargs):
"""Generate a description of the purchases performed by users in `subgroups`
for `delivery`. The resulting dictionary is used to render HTML as well as
PDF and MS-Excel views. It's used both to display the complete order ... | 0.62498 | 0.521227 |
import logging
from typing import Optional
from sqlalchemy import Column, Float, ForeignKey, Integer, String
from sqlalchemy.ext.declarative import DeclarativeMeta, declarative_base
from sqlalchemy.orm import backref, relationship
import pybel.dsl
from pybel import BELGraph
from .constants import MODULE
logger = log... | src/bio2bel_hippie/models.py | import logging
from typing import Optional
from sqlalchemy import Column, Float, ForeignKey, Integer, String
from sqlalchemy.ext.declarative import DeclarativeMeta, declarative_base
from sqlalchemy.orm import backref, relationship
import pybel.dsl
from pybel import BELGraph
from .constants import MODULE
logger = log... | 0.818047 | 0.17815 |
import numpy as np
import pytest
import pandas as pd
from pandas import (
DataFrame,
MultiIndex,
)
import pandas._testing as tm
def test_to_numpy(idx):
result = idx.to_numpy()
exp = idx.values
tm.assert_numpy_array_equal(result, exp)
def test_to_frame():
tuples = [(1, "one"), (1, "two"), (2... | crabageprediction/venv/Lib/site-packages/pandas/tests/indexes/multi/test_conversion.py | import numpy as np
import pytest
import pandas as pd
from pandas import (
DataFrame,
MultiIndex,
)
import pandas._testing as tm
def test_to_numpy(idx):
result = idx.to_numpy()
exp = idx.values
tm.assert_numpy_array_equal(result, exp)
def test_to_frame():
tuples = [(1, "one"), (1, "two"), (2... | 0.710729 | 0.76973 |
from __future__ import (absolute_import, division, print_function)
__metaclass__ = type
from os import path, walk
import re
from ansible.errors import AnsibleError
from ansible.module_utils.six import string_types
from ansible.module_utils._text import to_native, to_text
from ansible.plugins.action import ActionBase... | ansible-devel/lib/ansible/plugins/action/include_vars.py |
from __future__ import (absolute_import, division, print_function)
__metaclass__ = type
from os import path, walk
import re
from ansible.errors import AnsibleError
from ansible.module_utils.six import string_types
from ansible.module_utils._text import to_native, to_text
from ansible.plugins.action import ActionBase... | 0.549641 | 0.07579 |
from tqdm import tqdm, trange
from PIL import Image
import numpy as np
from openpyxl import load_workbook
import os
from pprint import PrettyPrinter
import argparse
import sys
from glob import glob
import logging
import random
import warnings
pp = PrettyPrinter()
class Faces10K:
def __init__(self, root_path, tra... | dataset.py | from tqdm import tqdm, trange
from PIL import Image
import numpy as np
from openpyxl import load_workbook
import os
from pprint import PrettyPrinter
import argparse
import sys
from glob import glob
import logging
import random
import warnings
pp = PrettyPrinter()
class Faces10K:
def __init__(self, root_path, tra... | 0.351645 | 0.2551 |
import os
from os import listdir
from os.path import isdir, isfile, join
from typing import List
from wtfml.utils import config
import numpy as np
import random
def basename(path: str) -> str:
"""
get '17asdfasdf2d_0_0.jpg' from 'train_folder/train/o/17asdfasdf2d_0_0.jpg
Args:
path (str): [descri... | wtfml/utils/utils.py | import os
from os import listdir
from os.path import isdir, isfile, join
from typing import List
from wtfml.utils import config
import numpy as np
import random
def basename(path: str) -> str:
"""
get '17asdfasdf2d_0_0.jpg' from 'train_folder/train/o/17asdfasdf2d_0_0.jpg
Args:
path (str): [descri... | 0.692538 | 0.256041 |
test = {
'name': 'Problem 12',
'points': 1,
'suites': [
{
'cases': [
{
'code': r"""
>>> # Testing TankAnt parameters
>>> TankAnt.food_cost
50ae32be3e31df6c59633df7fdfb3a72
# locked
>>> TankAnt.damage
d89cf7c79d5a479b0f63673414... | ants/tests/12.py | test = {
'name': 'Problem 12',
'points': 1,
'suites': [
{
'cases': [
{
'code': r"""
>>> # Testing TankAnt parameters
>>> TankAnt.food_cost
50ae32be3e31df6c59633df7fdfb3a72
# locked
>>> TankAnt.damage
d89cf7c79d5a479b0f63673414... | 0.510741 | 0.35301 |
import os
pjoin = os.path.join
from setuptools import setup, find_packages
here = os.path.abspath(os.path.dirname(__file__))
exec(open(pjoin(here,'cdsdashboards/version.py')).read()) # Load __version__
install_requires = [
'tornado>=6.0.4', # Mainly for jhsingle-native-proxy but best to keep consistent
'tra... | setup.py | import os
pjoin = os.path.join
from setuptools import setup, find_packages
here = os.path.abspath(os.path.dirname(__file__))
exec(open(pjoin(here,'cdsdashboards/version.py')).read()) # Load __version__
install_requires = [
'tornado>=6.0.4', # Mainly for jhsingle-native-proxy but best to keep consistent
'tra... | 0.30715 | 0.121191 |
from bitarray import bitarray
import mmh3, datetime
class BloomFilter:
def __init__(self, size, hash_count):
'''
Initializing the bloom filter
INPUT
size : size of bitarray
hash_count : Number of times to run the function
'''
self.size = size
se... | main.py | from bitarray import bitarray
import mmh3, datetime
class BloomFilter:
def __init__(self, size, hash_count):
'''
Initializing the bloom filter
INPUT
size : size of bitarray
hash_count : Number of times to run the function
'''
self.size = size
se... | 0.434221 | 0.420064 |
import os.path
import json
from delairstack.core.config import ConnectionConfig
from tests.delairstacktest import DelairStackTestBase
from unittest import mock
from delairstack.core.utils.filehelper import read_file
DEFAULT_MOCK_CONTENT = {
'password': '<PASSWORD>',
'user': 'default us... | tests/core/test_config.py | import os.path
import json
from delairstack.core.config import ConnectionConfig
from tests.delairstacktest import DelairStackTestBase
from unittest import mock
from delairstack.core.utils.filehelper import read_file
DEFAULT_MOCK_CONTENT = {
'password': '<PASSWORD>',
'user': 'default us... | 0.542863 | 0.172067 |
import os
import sys
import colorama
import subprocess
import jaconv
import datetime
import config
import re
class Utils:
def __init__(self):
# 実行時刻
self.time = datetime.datetime.now()
def get_macro(self, environ):#環境変数を取得
# 値が存在しなかった場合の初期値
macro_default = '--'
... | AmatsukazeNotifier/utils.py | import os
import sys
import colorama
import subprocess
import jaconv
import datetime
import config
import re
class Utils:
def __init__(self):
# 実行時刻
self.time = datetime.datetime.now()
def get_macro(self, environ):#環境変数を取得
# 値が存在しなかった場合の初期値
macro_default = '--'
... | 0.159905 | 0.195613 |
import warnings
import numpy as np
import pandas as pd
from xgboost import XGBClassifier
from sklearn.base import clone, BaseEstimator, ClassifierMixin
from sklearn.utils.validation import check_is_fitted
from autoimpute.utils import check_nan_columns, check_predictors_fit
# pylint:disable=attribute-defined-outside-in... | autoimpute/imputations/mis_classifier.py | import warnings
import numpy as np
import pandas as pd
from xgboost import XGBClassifier
from sklearn.base import clone, BaseEstimator, ClassifierMixin
from sklearn.utils.validation import check_is_fitted
from autoimpute.utils import check_nan_columns, check_predictors_fit
# pylint:disable=attribute-defined-outside-in... | 0.884377 | 0.565299 |