code stringlengths 2k 1.04M | repo_path stringlengths 5 517 | parsed_code stringlengths 0 1.04M | quality_prob float64 0.02 0.95 | learning_prob float64 0.02 0.93 |
|---|---|---|---|---|
import csv
import requests
class Mapper:
def __init__(self,agent):
self.AI_agent = agent
self.csv2mr_map = {}
@staticmethod
def rn_step1(AI_agent):
return raw_input('[%s]: What is the name of the CSV file you want to import? \n[YOU]: '%AI_agent)
def rn_step2(self,AI_a... | Mapper.py | import csv
import requests
class Mapper:
def __init__(self,agent):
self.AI_agent = agent
self.csv2mr_map = {}
@staticmethod
def rn_step1(AI_agent):
return raw_input('[%s]: What is the name of the CSV file you want to import? \n[YOU]: '%AI_agent)
def rn_step2(self,AI_a... | 0.248443 | 0.226131 |
from layers import ProcessingLayer
from lexical_shortcuts.shortcuts_attention_modules import \
MultiHeadAttentionShortcuts, \
MultiHeadAttentionShortcutsFeatureFusion, \
MultiHeadAttentionShortcutsFeatureFusionNonLexical
class ShortcutsAttentionBlock(object):
""" Defines a single attention block (ref... | codebase/lexical_shortcuts/lexical_shortcuts_blocks.py | from layers import ProcessingLayer
from lexical_shortcuts.shortcuts_attention_modules import \
MultiHeadAttentionShortcuts, \
MultiHeadAttentionShortcutsFeatureFusion, \
MultiHeadAttentionShortcutsFeatureFusionNonLexical
class ShortcutsAttentionBlock(object):
""" Defines a single attention block (ref... | 0.889745 | 0.367951 |
import json
import warnings
import pulumi
import pulumi.runtime
from typing import Union
from . import utilities, tables
class Record(pulumi.CustomResource):
created_on: pulumi.Output[str]
"""
The RFC3339 timestamp of when the record was created
"""
data: pulumi.Output[dict]
"""
Map of att... | sdk/python/pulumi_cloudflare/record.py |
import json
import warnings
import pulumi
import pulumi.runtime
from typing import Union
from . import utilities, tables
class Record(pulumi.CustomResource):
created_on: pulumi.Output[str]
"""
The RFC3339 timestamp of when the record was created
"""
data: pulumi.Output[dict]
"""
Map of att... | 0.822581 | 0.347067 |
from __future__ import division
import sys
import pickle
import numpy as np
from scipy.stats import johnsonsu
import pandas as pd
import ete3
def name_internal_nodes(T):
# Name internal nodes of a tree
i = 1
for node in T.traverse():
if not node.is_leaf():
node.name = str(i) + "_"
... | scripts/subclones/annotate_nodes_FayAndWusH.py | from __future__ import division
import sys
import pickle
import numpy as np
from scipy.stats import johnsonsu
import pandas as pd
import ete3
def name_internal_nodes(T):
# Name internal nodes of a tree
i = 1
for node in T.traverse():
if not node.is_leaf():
node.name = str(i) + "_"
... | 0.455683 | 0.421492 |
# Import Local Modules
from marvin.cloudstackTestCase import cloudstackTestCase, unittest
from marvin.cloudstackAPI import (updateStoragePool,
resizeVolume,
listCapacity,
addCluster)
from marvin.sshClient import SshCl... | test/integration/component/maint/test_bugs.py |
# Import Local Modules
from marvin.cloudstackTestCase import cloudstackTestCase, unittest
from marvin.cloudstackAPI import (updateStoragePool,
resizeVolume,
listCapacity,
addCluster)
from marvin.sshClient import SshCl... | 0.403332 | 0.116211 |
import os, time, json
import urllib.parse
import nabto
PARENT_DIRECTORY = os.path.dirname(os.path.abspath(__file__))
NABTO_HOME_DIRECTORY = os.path.join(PARENT_DIRECTORY, 'share', 'nabto')
NABTO_QUERIES = os.path.join(PARENT_DIRECTORY, 'unabto_queries.xml')
class NabtoDevice:
deviceID: str
session: nabto.Sess... | example/ex2.py | import os, time, json
import urllib.parse
import nabto
PARENT_DIRECTORY = os.path.dirname(os.path.abspath(__file__))
NABTO_HOME_DIRECTORY = os.path.join(PARENT_DIRECTORY, 'share', 'nabto')
NABTO_QUERIES = os.path.join(PARENT_DIRECTORY, 'unabto_queries.xml')
class NabtoDevice:
deviceID: str
session: nabto.Sess... | 0.304042 | 0.111895 |
import os
import urllib.request
import numpy as np
import pandas as pd
from astropy.io.votable import parse_single_table
from species.analysis import photometry
from species.util import data_util, query_util
def add_spex(input_path, database):
"""
Function for adding the SpeX Prism Spectral Library to the ... | species/data/spex.py | import os
import urllib.request
import numpy as np
import pandas as pd
from astropy.io.votable import parse_single_table
from species.analysis import photometry
from species.util import data_util, query_util
def add_spex(input_path, database):
"""
Function for adding the SpeX Prism Spectral Library to the ... | 0.650689 | 0.236489 |
import os
import glob
import sys
import argparse
import re
from collections import defaultdict
from celescope.__init__ import __CONDA__
from celescope.tools.utils import merge_report
from celescope.tools.utils import parse_map_col4, link_data
from celescope.tools.__init__ import __PATTERN_DICT__
class Multi():
de... | celescope/tools/Multi.py | import os
import glob
import sys
import argparse
import re
from collections import defaultdict
from celescope.__init__ import __CONDA__
from celescope.tools.utils import merge_report
from celescope.tools.utils import parse_map_col4, link_data
from celescope.tools.__init__ import __PATTERN_DICT__
class Multi():
de... | 0.332202 | 0.057229 |
__author__ = "<NAME> <<EMAIL>>"
# External Includes
from copy import deepcopy
import numpy as np
import os
import torch
from unittest import TestCase
# Internal Includes
from rfml.data import Dataset, DatasetBuilder, Encoder
class TestDataset(TestCase):
# 5 mods x 5 snrs x 1k examples = 25k entries in the datas... | test/data/test_dataset.py | __author__ = "<NAME> <<EMAIL>>"
# External Includes
from copy import deepcopy
import numpy as np
import os
import torch
from unittest import TestCase
# Internal Includes
from rfml.data import Dataset, DatasetBuilder, Encoder
class TestDataset(TestCase):
# 5 mods x 5 snrs x 1k examples = 25k entries in the datas... | 0.798187 | 0.470311 |
import smart_imports
smart_imports.all()
from the_tale.statistics.metrics import registrations
from the_tale.statistics.metrics import lifetime
from the_tale.statistics.metrics import monetization
from the_tale.statistics.metrics import actual
from the_tale.statistics.metrics import forum
from the_tale.statistics.met... | src/the_tale/the_tale/statistics/management/commands/statistics_complete.py | import smart_imports
smart_imports.all()
from the_tale.statistics.metrics import registrations
from the_tale.statistics.metrics import lifetime
from the_tale.statistics.metrics import monetization
from the_tale.statistics.metrics import actual
from the_tale.statistics.metrics import forum
from the_tale.statistics.met... | 0.313525 | 0.499451 |
mode: python; py-indent-offset: 4; tab-width: 4; coding: utf-8
Class that define a parallel coordinates chart display as post post processing
"""
import plotly.graph_objects as go
from sos_trades_core.tools.post_processing.post_processing_tools import escape_str_with_comma
from sos_trades_core.tools.post_processing.pos... | sos_trades_core/tools/post_processing/parallel_coordinates_charts/instantiated_parallel_coordinates_chart.py | mode: python; py-indent-offset: 4; tab-width: 4; coding: utf-8
Class that define a parallel coordinates chart display as post post processing
"""
import plotly.graph_objects as go
from sos_trades_core.tools.post_processing.post_processing_tools import escape_str_with_comma
from sos_trades_core.tools.post_processing.pos... | 0.798737 | 0.307774 |
from rest_framework import generics, status
from rest_framework.response import Response
from . import serializers
from .authentication import AUTH_HEADER_TYPES
from .exceptions import InvalidToken, TokenError
class TokenViewBase(generics.GenericAPIView):
permission_classes = ()
authentication_classes = ()
... | rest_framework_simplejwt/views.py | from rest_framework import generics, status
from rest_framework.response import Response
from . import serializers
from .authentication import AUTH_HEADER_TYPES
from .exceptions import InvalidToken, TokenError
class TokenViewBase(generics.GenericAPIView):
permission_classes = ()
authentication_classes = ()
... | 0.727975 | 0.174375 |
import random
from geomstats.geometry.full_rank_correlation_matrices import (
CorrelationMatricesBundle,
FullRankCorrelationMatrices,
)
from geomstats.geometry.symmetric_matrices import SymmetricMatrices
from tests.data_generation import TestData, _LevelSetTestData
class RankFullRankCorrelationMatricesTestDa... | tests/data/full_rank_correlation_matrices_data.py | import random
from geomstats.geometry.full_rank_correlation_matrices import (
CorrelationMatricesBundle,
FullRankCorrelationMatrices,
)
from geomstats.geometry.symmetric_matrices import SymmetricMatrices
from tests.data_generation import TestData, _LevelSetTestData
class RankFullRankCorrelationMatricesTestDa... | 0.549399 | 0.434221 |
from __future__ import annotations
import argparse
import logging
import os
import tempfile
from enum import Enum
import attr
from .fanout_test_driver import (
Binaries,
run_scenario_saved_state_init,
run_scenario_incremental_no_old_decls,
run_scenario_incremental_with_old_decls,
)
from .fanout_test_... | hphp/hack/test/fanout/tools/fanout.py | from __future__ import annotations
import argparse
import logging
import os
import tempfile
from enum import Enum
import attr
from .fanout_test_driver import (
Binaries,
run_scenario_saved_state_init,
run_scenario_incremental_no_old_decls,
run_scenario_incremental_with_old_decls,
)
from .fanout_test_... | 0.551574 | 0.069384 |
import os
from airflow.exceptions import AirflowException, AirflowSkipException
from airflow.models import BaseOperator
from airflow.utils.decorators import apply_defaults
from ..hooks.hdfs_hook import HDFSHook
from ..hooks.pyhive_hook import PyHiveHook
from ..utils import (create_concat_filename, concat_avro_files,... | o3/operators/ingest_avro_into_hive_operator.py | import os
from airflow.exceptions import AirflowException, AirflowSkipException
from airflow.models import BaseOperator
from airflow.utils.decorators import apply_defaults
from ..hooks.hdfs_hook import HDFSHook
from ..hooks.pyhive_hook import PyHiveHook
from ..utils import (create_concat_filename, concat_avro_files,... | 0.542742 | 0.222975 |
import os
import re
import logging
import benchexec.tools.template
class Tool(benchexec.tools.template.BaseTool2):
"""
Tool info for DC-SSAT: A Divide-and-Conquer Approach to Solving Stochastic Satisfiability Problems Efficiently
URL: https://www.aaai.org/Papers/AAAI/2005/AAAI05-066.pdf
"""
def... | reproduction-artifact/tool-info/dcssat.py |
import os
import re
import logging
import benchexec.tools.template
class Tool(benchexec.tools.template.BaseTool2):
"""
Tool info for DC-SSAT: A Divide-and-Conquer Approach to Solving Stochastic Satisfiability Problems Efficiently
URL: https://www.aaai.org/Papers/AAAI/2005/AAAI05-066.pdf
"""
def... | 0.456894 | 0.242396 |
def assertIn(v, c):
if not v in c:
raise AssertionError('{} not in {}'.format(v, c))
def assertNin(v, c):
if v in c:
raise AssertionError('{} in {}'.format(v, c))
def assertEq(l, r):
if l != r:
raise AssertionError('{} != {}'.format(l, r))
def assertNeq(l, r):
if l == r:
raise AssertionError(... | __init__.py | def assertIn(v, c):
if not v in c:
raise AssertionError('{} not in {}'.format(v, c))
def assertNin(v, c):
if v in c:
raise AssertionError('{} in {}'.format(v, c))
def assertEq(l, r):
if l != r:
raise AssertionError('{} != {}'.format(l, r))
def assertNeq(l, r):
if l == r:
raise AssertionError(... | 0.460289 | 0.423339 |
# COMMAND ----------
# MAGIC %run ../Includes/Classroom-Setup
# COMMAND ----------
# Read in the dataset for the lab, along with all functions
from pyspark.sql.functions import *
df = spark.read.format("delta").load(sales_path)
display(df)
# COMMAND ----------
# MAGIC %md ### 1. Extract item details from purcha... | Apache-Spark-Programming-with-Databricks/Solutions/ASP 3 - Functions/ASP 3.3L - Users.py |
# COMMAND ----------
# MAGIC %run ../Includes/Classroom-Setup
# COMMAND ----------
# Read in the dataset for the lab, along with all functions
from pyspark.sql.functions import *
df = spark.read.format("delta").load(sales_path)
display(df)
# COMMAND ----------
# MAGIC %md ### 1. Extract item details from purcha... | 0.72952 | 0.685354 |
# Unidirectional Sequence LSTM Test:
# 1 Time Step, Layer Normalization, No Cifg, Peephole, Projection, and No Clipping.
import copy
import dynamic_tensor
model = Model()
max_time = 1
n_batch = 2
n_input = 5
# n_cell and n_output have the same size when there is no projection.
n_cell = 4
n_output = 3
input_shape = ... | tests/nnapi/specs/V1_2/unidirectional_sequence_lstm_dynamic_nnfw.mod.py |
# Unidirectional Sequence LSTM Test:
# 1 Time Step, Layer Normalization, No Cifg, Peephole, Projection, and No Clipping.
import copy
import dynamic_tensor
model = Model()
max_time = 1
n_batch = 2
n_input = 5
# n_cell and n_output have the same size when there is no projection.
n_cell = 4
n_output = 3
input_shape = ... | 0.7641 | 0.442516 |
import logging
logger = logging.getLogger(__name__)
from .pyfda_lib import qstr
from .compat import QFrame, QMessageBox, Qt
#------------------------------------------------------------------------------
def qget_cmb_box(cmb_box, data=True):
"""
Get current itemData or Text of comboBox and convert it to stri... | pyfda/pyfda_qt_lib.py | import logging
logger = logging.getLogger(__name__)
from .pyfda_lib import qstr
from .compat import QFrame, QMessageBox, Qt
#------------------------------------------------------------------------------
def qget_cmb_box(cmb_box, data=True):
"""
Get current itemData or Text of comboBox and convert it to stri... | 0.735357 | 0.459864 |
from . import static as static
from . import gquery as gquery
from . import pagination as pageUtils
from . import swagger as swagger
from .prov import grlcPROV
from .fileLoaders import GithubLoader, LocalLoader, URLLoader
from .queryTypes import qType
from . import __version__ as grlc_version
import re
import requests... | src/utils.py | from . import static as static
from . import gquery as gquery
from . import pagination as pageUtils
from . import swagger as swagger
from .prov import grlcPROV
from .fileLoaders import GithubLoader, LocalLoader, URLLoader
from .queryTypes import qType
from . import __version__ as grlc_version
import re
import requests... | 0.427516 | 0.097305 |
from __future__ import annotations
import json
import tempfile
from os import environ, fsync, makedirs, path, rename
from pathlib import Path
from typing import Dict, List
from ghaudit import auth, config, schema
from ghaudit.config import Config
from ghaudit.query.branch_protection_push_allowances import (
Bran... | src/ghaudit/cache.py |
from __future__ import annotations
import json
import tempfile
from os import environ, fsync, makedirs, path, rename
from pathlib import Path
from typing import Dict, List
from ghaudit import auth, config, schema
from ghaudit.config import Config
from ghaudit.query.branch_protection_push_allowances import (
Bran... | 0.614625 | 0.179207 |
import os
from unittest import TestCase
from unittest.mock import patch, MagicMock, call
with patch("boto3.resource") as boto_resource_mock:
with patch("boto3.client") as boto_client_mock:
from functions.usergamedata.DeleteAll import index
BUNDLES_TABLE_NAME = 'test_bundles_table'
ITEMS_TABLE_NAME = 'tes... | AwsGameKit/Resources/cloudResources/functionsTests/test_usergamedata/test_DeleteAll/test_index.py |
import os
from unittest import TestCase
from unittest.mock import patch, MagicMock, call
with patch("boto3.resource") as boto_resource_mock:
with patch("boto3.client") as boto_client_mock:
from functions.usergamedata.DeleteAll import index
BUNDLES_TABLE_NAME = 'test_bundles_table'
ITEMS_TABLE_NAME = 'tes... | 0.47317 | 0.275671 |
import re
import dns.exception
NONE = 0
A = 1
NS = 2
MD = 3
MF = 4
CNAME = 5
SOA = 6
MB = 7
MG = 8
MR = 9
NULL = 10
WKS = 11
PTR = 12
HINFO = 13
MINFO = 14
MX = 15
TXT = 16
RP = 17
AFSDB = 18
X25 = 19
ISDN = 20
RT = 21
NSAP = 22
NSAP_PTR = 23
SIG = 24
KEY = 25
PX = 26
GPOS = 27
AAAA = ... | oscar/lib/python2.7/site-packages/dns/rdatatype.py | import re
import dns.exception
NONE = 0
A = 1
NS = 2
MD = 3
MF = 4
CNAME = 5
SOA = 6
MB = 7
MG = 8
MR = 9
NULL = 10
WKS = 11
PTR = 12
HINFO = 13
MINFO = 14
MX = 15
TXT = 16
RP = 17
AFSDB = 18
X25 = 19
ISDN = 20
RT = 21
NSAP = 22
NSAP_PTR = 23
SIG = 24
KEY = 25
PX = 26
GPOS = 27
AAAA = ... | 0.388386 | 0.078325 |
from functools import lru_cache
REQUIRED_FEATURES = [
"is_question",
"action_verb_full",
"language_question",
"question_mark_full",
"norm_text_len",
]
def find_absent_features(data):
missing = []
for feat in REQUIRED_FEATURES:
if feat not in data.keys():
missing.append... | ml_editor/inference.py | from functools import lru_cache
REQUIRED_FEATURES = [
"is_question",
"action_verb_full",
"language_question",
"question_mark_full",
"norm_text_len",
]
def find_absent_features(data):
missing = []
for feat in REQUIRED_FEATURES:
if feat not in data.keys():
missing.append... | 0.612426 | 0.472379 |
from os import path
import json
import pandas as pd
import numpy as np
import multiprocessing as mp
from sklearn import preprocessing
from sklearn.preprocessing import MinMaxScaler
from sklearn.metrics.pairwise import cosine_similarity
from percy.clusters import process, per_similarity, per_timeline
TOP_K = 100
de... | percy/similarity.py | from os import path
import json
import pandas as pd
import numpy as np
import multiprocessing as mp
from sklearn import preprocessing
from sklearn.preprocessing import MinMaxScaler
from sklearn.metrics.pairwise import cosine_similarity
from percy.clusters import process, per_similarity, per_timeline
TOP_K = 100
de... | 0.461502 | 0.176707 |
import argparse
from ...helper import add_arg_group, _SHOW_ALL_ARGS, KVAppendAction
from .... import __default_host__
from .... import helper
from ....enums import OnErrorStrategy, SocketType
def mixin_zed_runtime_parser(parser):
"""Mixing in arguments required by :class:`ZEDRuntime` into the given parser.
:... | jina/parsers/peapods/runtimes/zed.py | import argparse
from ...helper import add_arg_group, _SHOW_ALL_ARGS, KVAppendAction
from .... import __default_host__
from .... import helper
from ....enums import OnErrorStrategy, SocketType
def mixin_zed_runtime_parser(parser):
"""Mixing in arguments required by :class:`ZEDRuntime` into the given parser.
:... | 0.747708 | 0.252511 |
# Enthought library imports.
from traits.api import Interface
class IExtensionRegistry(Interface):
""" The interface for extension registries. """
def add_extension_point_listener(self, listener, extension_point_id=None):
""" Add a listener for extensions being added or removed.
A listener i... | envisage/i_extension_registry.py | # Enthought library imports.
from traits.api import Interface
class IExtensionRegistry(Interface):
""" The interface for extension registries. """
def add_extension_point_listener(self, listener, extension_point_id=None):
""" Add a listener for extensions being added or removed.
A listener i... | 0.793346 | 0.312816 |
from gridded_noise_nofg import core_eor, core_instr, likelihood, model_name
from py21cmmc.mcmc.mcmc import build_computation_chain
import pickle
import numpy as np
import matplotlib.pyplot as plt
import multiprocessing
nrealisations = 400
nthreads = 4
def _produce_mock(i):
"""Produces a mock power spectrum for pu... | devel/test_series/test_thermal_noise.py | from gridded_noise_nofg import core_eor, core_instr, likelihood, model_name
from py21cmmc.mcmc.mcmc import build_computation_chain
import pickle
import numpy as np
import matplotlib.pyplot as plt
import multiprocessing
nrealisations = 400
nthreads = 4
def _produce_mock(i):
"""Produces a mock power spectrum for pu... | 0.835986 | 0.73369 |
import csv
from elasticsearch_dsl import connections
from elasticsearch_dsl import Search
connections.create_connection(hosts=["localhost"], timeout=20)
s = Search(index="fluentd-*")
# only return the selected fields
s = s.source(
[
"str_time",
"timestamp",
"handler",
"ellapsed_m... | demo/EFK-stack/search.py | import csv
from elasticsearch_dsl import connections
from elasticsearch_dsl import Search
connections.create_connection(hosts=["localhost"], timeout=20)
s = Search(index="fluentd-*")
# only return the selected fields
s = s.source(
[
"str_time",
"timestamp",
"handler",
"ellapsed_m... | 0.213295 | 0.200206 |
from micropython import mem_info
from microbit import *
from utime import sleep,sleep_ms
def CW01AT(t,raw=False,wait=None,useUART=1):
if useUART == 1 or useUART == 2:
uart.init(baudrate=115200, bits=8, parity=None, stop=1, tx=pin1, rx=pin0)
sleep_ms(10)
if raw:
uart.write(bytearray(t))
... | microbit-azure.py | from micropython import mem_info
from microbit import *
from utime import sleep,sleep_ms
def CW01AT(t,raw=False,wait=None,useUART=1):
if useUART == 1 or useUART == 2:
uart.init(baudrate=115200, bits=8, parity=None, stop=1, tx=pin1, rx=pin0)
sleep_ms(10)
if raw:
uart.write(bytearray(t))
... | 0.10939 | 0.153676 |
import datetime
from urllib.parse import urljoin # Python 3
from flask import Blueprint, request, render_template, flash, g, session, redirect, url_for, jsonify
from werkzeug import secure_filename
from app import app, db, utils
from app.models import Uploads, User, Comment, Media, Country, Genre, MediaType, StoryTyp... | app/mod_media/controllers.py | import datetime
from urllib.parse import urljoin # Python 3
from flask import Blueprint, request, render_template, flash, g, session, redirect, url_for, jsonify
from werkzeug import secure_filename
from app import app, db, utils
from app.models import Uploads, User, Comment, Media, Country, Genre, MediaType, StoryTyp... | 0.220426 | 0.055362 |
import numpy as np
from glue.config import data_translator
from glue.core import Data, Subset
from astropy.wcs import WCS
from astropy import units as u
from astropy.wcs import WCSSUB_SPECTRAL
from astropy.nddata import StdDevUncertainty, InverseVariance, VarianceUncertainty
from glue_astronomy.spectral_coordinates ... | glue_astronomy/translators/spectrum1d.py | import numpy as np
from glue.config import data_translator
from glue.core import Data, Subset
from astropy.wcs import WCS
from astropy import units as u
from astropy.wcs import WCSSUB_SPECTRAL
from astropy.nddata import StdDevUncertainty, InverseVariance, VarianceUncertainty
from glue_astronomy.spectral_coordinates ... | 0.865665 | 0.438605 |
from openstack import resource
from openstack import utils
class Trunk(resource.Resource, resource.TagMixin):
resource_key = 'trunk'
resources_key = 'trunks'
base_path = '/trunks'
# capabilities
allow_create = True
allow_fetch = True
allow_commit = True
allow_delete = True
allow_... | openstack/network/v2/trunk.py |
from openstack import resource
from openstack import utils
class Trunk(resource.Resource, resource.TagMixin):
resource_key = 'trunk'
resources_key = 'trunks'
base_path = '/trunks'
# capabilities
allow_create = True
allow_fetch = True
allow_commit = True
allow_delete = True
allow_... | 0.51879 | 0.108637 |
from pycontract import *
import unittest
import test.utest
from datetime import datetime
"""
Test example for SAC-SVT 2022.
"""
class M4(Monitor):
def transition(self, event):
match event:
case {'name': 'command', 'cmd': c, 'nr': n, 'kind': "FSW"}:
return self.Dispatch(c, n)
... | test/test12-vpt-2022/test12.py | from pycontract import *
import unittest
import test.utest
from datetime import datetime
"""
Test example for SAC-SVT 2022.
"""
class M4(Monitor):
def transition(self, event):
match event:
case {'name': 'command', 'cmd': c, 'nr': n, 'kind': "FSW"}:
return self.Dispatch(c, n)
... | 0.5 | 0.255209 |
import numpy as np
class Preprocessor:
def __init__(
self,
users_dataframe=None,
items_dataframe=None,
interactions_dataframe=None,
item_id_column=None,
items_feature_columns=None,
user_id_column=None,
user_features_co... | lightfm_dataset_helper/Preprocessor.py | import numpy as np
class Preprocessor:
def __init__(
self,
users_dataframe=None,
items_dataframe=None,
interactions_dataframe=None,
item_id_column=None,
items_feature_columns=None,
user_id_column=None,
user_features_co... | 0.662578 | 0.393385 |
def _github_wiki_impl(ctx):
clonedir = ctx.outputs.clonedir
output = []
for f in ctx.files.srcs:
file = ctx.actions.declare_file(ctx.attr.dest + f.path.replace("/", "-").replace(".log", ".md"))
ctx.actions.run_shell(
inputs = [f],
outputs = [file],
prog... | github_wiki.bzl |
def _github_wiki_impl(ctx):
clonedir = ctx.outputs.clonedir
output = []
for f in ctx.files.srcs:
file = ctx.actions.declare_file(ctx.attr.dest + f.path.replace("/", "-").replace(".log", ".md"))
ctx.actions.run_shell(
inputs = [f],
outputs = [file],
prog... | 0.385837 | 0.296973 |
import os
from nanome.util import Logs, config
from nanome.util.enums import StreamDirection, PluginListButtonType
from nanome._internal import _PluginInstance
from nanome._internal._process import _Bonding, _Dssp
from nanome._internal._network._commands._callbacks import _Messages
from nanome.api.integration import I... | nanome/api/plugin_instance.py | import os
from nanome.util import Logs, config
from nanome.util.enums import StreamDirection, PluginListButtonType
from nanome._internal import _PluginInstance
from nanome._internal._process import _Bonding, _Dssp
from nanome._internal._network._commands._callbacks import _Messages
from nanome.api.integration import I... | 0.680985 | 0.250134 |
from ...tl.tlobject import TLObject
from typing import Optional, List, Union, TYPE_CHECKING
import os
import struct
if TYPE_CHECKING:
from ...tl.types import TypeBool, TypeChannelBannedRights, TypeInputUser, TypeInputChannel, TypeChannelAdminRights, TypeInputChatPhoto, TypeChannelParticipantsFilter, TypeChannelAdmi... | Lib/site-packages/telethon/tl/functions/channels.py | from ...tl.tlobject import TLObject
from typing import Optional, List, Union, TYPE_CHECKING
import os
import struct
if TYPE_CHECKING:
from ...tl.types import TypeBool, TypeChannelBannedRights, TypeInputUser, TypeInputChannel, TypeChannelAdminRights, TypeInputChatPhoto, TypeChannelParticipantsFilter, TypeChannelAdmi... | 0.748995 | 0.112893 |
from __future__ import print_function
import os
import sys
import traceback
from bloom.logging import debug
from bloom.logging import error
from bloom.logging import fmt
from bloom.logging import info
from bloom.generators.debian.generator import generate_substitutions_from_package
from bloom.generators.debian.gene... | bloom/generators/debian/generate_cmd.py |
from __future__ import print_function
import os
import sys
import traceback
from bloom.logging import debug
from bloom.logging import error
from bloom.logging import fmt
from bloom.logging import info
from bloom.generators.debian.generator import generate_substitutions_from_package
from bloom.generators.debian.gene... | 0.333829 | 0.073497 |
import math
from collections import Counter
import numpy as np
__all__ = ["LambdaLR", "MultiplicativeLR", "StepLR", "MultiStepLR", "ExponentialLR",
"CosineAnnealingLR", "CyclicLR", "CosineAnnealingWarmRestarts", "OneCycleLR"]
class _WarmUp():
def __init__(self, warmup_init_lr):
self.warmup_init... | model_zoo/official/cv/densenet121/src/lr_scheduler/lr_scheduler.py | import math
from collections import Counter
import numpy as np
__all__ = ["LambdaLR", "MultiplicativeLR", "StepLR", "MultiStepLR", "ExponentialLR",
"CosineAnnealingLR", "CyclicLR", "CosineAnnealingWarmRestarts", "OneCycleLR"]
class _WarmUp():
def __init__(self, warmup_init_lr):
self.warmup_init... | 0.878887 | 0.288118 |
import logging
import seamm
import seamm_widgets as sw
import packmol_step
import Pmw
import tkinter as tk
import tkinter.ttk as ttk
logger = logging.getLogger(__name__)
class TkPackmol(seamm.TkNode):
"""Graphical interface for using Packmol for fluid boxes"""
def __init__(
self, tk_flowchart=None, ... | packmol_step/tk_packmol.py | import logging
import seamm
import seamm_widgets as sw
import packmol_step
import Pmw
import tkinter as tk
import tkinter.ttk as ttk
logger = logging.getLogger(__name__)
class TkPackmol(seamm.TkNode):
"""Graphical interface for using Packmol for fluid boxes"""
def __init__(
self, tk_flowchart=None, ... | 0.601242 | 0.149252 |
import pytest
from stp_core.loop.eventually import eventually
from plenum.test.pool_transactions.conftest import looper
from plenum.test.helper import checkViewNoForNodes, sdk_send_random_and_check
from plenum.test.test_node import get_master_primary_node
def test_view_not_changed_when_short_disconnection(txnPoolNod... | plenum/test/view_change/test_view_not_changed_when_short_disconnection.py | import pytest
from stp_core.loop.eventually import eventually
from plenum.test.pool_transactions.conftest import looper
from plenum.test.helper import checkViewNoForNodes, sdk_send_random_and_check
from plenum.test.test_node import get_master_primary_node
def test_view_not_changed_when_short_disconnection(txnPoolNod... | 0.460532 | 0.298702 |
import json
import os
from logging import debug
from .cmdline.interpreter import SpaceCmdInterpreter
from . import model
class SpaceEngine(model.ModelQueryMixin):
def __init__(self, save_file, opts=None):
self.save_file = save_file
self.opts = opts
self.user = None
self.galaxy = ... | lib/engine.py |
import json
import os
from logging import debug
from .cmdline.interpreter import SpaceCmdInterpreter
from . import model
class SpaceEngine(model.ModelQueryMixin):
def __init__(self, save_file, opts=None):
self.save_file = save_file
self.opts = opts
self.user = None
self.galaxy = ... | 0.500732 | 0.080069 |
from enum import Enum
class Type:
""" Dummy base class to implement strong typed references
"""
def __init__(self):
pass
@classmethod
def dictToObject(cls, dict):
if dict is None:
return None
obj = cls()
return obj
class IntegerType (Type):
""" ... | yacg/model/model.py |
from enum import Enum
class Type:
""" Dummy base class to implement strong typed references
"""
def __init__(self):
pass
@classmethod
def dictToObject(cls, dict):
if dict is None:
return None
obj = cls()
return obj
class IntegerType (Type):
""" ... | 0.858807 | 0.361418 |
import sys
import argparse
from mdt.database import (
load_rxnorm,
load_meps,
load_fda,
check_table,
)
from mdt.yamlmanager import (
create_mdt_settings,
create_module_settings,
get_settings,
)
from mdt.utils import (
get_rxcui_ingredient_df,
get_rxcui_product_df,
get_rxcui_ndc_d... | src/mdt/cli.py | import sys
import argparse
from mdt.database import (
load_rxnorm,
load_meps,
load_fda,
check_table,
)
from mdt.yamlmanager import (
create_mdt_settings,
create_module_settings,
get_settings,
)
from mdt.utils import (
get_rxcui_ingredient_df,
get_rxcui_product_df,
get_rxcui_ndc_d... | 0.26971 | 0.110375 |
import pyperclip
from password import User
import random
import string
class Credential:
'''
Class to create account credentials, generate new passwords and save user information
'''
list_of_credentials =[]
user_credentials_list = []
def __init__(self,username,credential_account,account_name,password... | credential.py | import pyperclip
from password import User
import random
import string
class Credential:
'''
Class to create account credentials, generate new passwords and save user information
'''
list_of_credentials =[]
user_credentials_list = []
def __init__(self,username,credential_account,account_name,password... | 0.241847 | 0.127245 |
from django.contrib import messages
from django.http import HttpResponse
from django.shortcuts import redirect, render
from django.utils.timezone import now
from django.views.decorators.http import require_http_methods
from api.utils import api_login_required, handle_api_errors
from core.admin_menus import AdminMenuIt... | membership/views/membership_admin_members_view.py | from django.contrib import messages
from django.http import HttpResponse
from django.shortcuts import redirect, render
from django.utils.timezone import now
from django.views.decorators.http import require_http_methods
from api.utils import api_login_required, handle_api_errors
from core.admin_menus import AdminMenuIt... | 0.322739 | 0.096535 |
from pathlib import Path
from os.path import exists, dirname
from os import remove, mkdir
import logging
import shutil
from policy_sentry.shared.constants import (
HOME,
CONFIG_DIRECTORY,
DATABASE_FILE_NAME,
HTML_DIRECTORY_PATH,
HTML_DATA_DIRECTORY_SUBFOLDER,
)
from policy_sentry.util.file import cr... | policy_sentry/configuration/config_directory.py | from pathlib import Path
from os.path import exists, dirname
from os import remove, mkdir
import logging
import shutil
from policy_sentry.shared.constants import (
HOME,
CONFIG_DIRECTORY,
DATABASE_FILE_NAME,
HTML_DIRECTORY_PATH,
HTML_DATA_DIRECTORY_SUBFOLDER,
)
from policy_sentry.util.file import cr... | 0.290276 | 0.099908 |
import numpy as np
import pandas
import warnings
from modin.core.storage_formats.pandas.parsers import (
_split_result_for_readers,
PandasCSVGlobParser,
PandasPickleExperimentalParser,
CustomTextExperimentalParser,
)
from modin.core.storage_formats.pandas.query_compiler import PandasQueryCompiler
from ... | modin/experimental/core/execution/ray/implementations/pandas_on_ray/io/io.py | import numpy as np
import pandas
import warnings
from modin.core.storage_formats.pandas.parsers import (
_split_result_for_readers,
PandasCSVGlobParser,
PandasPickleExperimentalParser,
CustomTextExperimentalParser,
)
from modin.core.storage_formats.pandas.query_compiler import PandasQueryCompiler
from ... | 0.797517 | 0.392133 |
import subprocess
from ..files import LocationDoesNotExist, NotADirectory
from ..resources import console, default_transient_progress
def make(dir_path, args, app_name=""):
"""Invoke make in the given directory.
Args:
dir_path (Path): the directory in which invoke make.
args (list): the argu... | commands/utils/make/make.py | import subprocess
from ..files import LocationDoesNotExist, NotADirectory
from ..resources import console, default_transient_progress
def make(dir_path, args, app_name=""):
"""Invoke make in the given directory.
Args:
dir_path (Path): the directory in which invoke make.
args (list): the argu... | 0.644673 | 0.250337 |
from os import path
from time import sleep
import sys
class FFEA_springs:
def __init__(self, fname = ""):
self.reset()
if fname == "":
return
try:
self.load(fname)
except:
raise
def load(self, fname):
sys.stdout.write("Loading FFEA springs file...")
# File format?
base, ext = path.sp... | ffeatools/modules/FFEA_springs.py |
from os import path
from time import sleep
import sys
class FFEA_springs:
def __init__(self, fname = ""):
self.reset()
if fname == "":
return
try:
self.load(fname)
except:
raise
def load(self, fname):
sys.stdout.write("Loading FFEA springs file...")
# File format?
base, ext = path.sp... | 0.134236 | 0.184988 |
from pathlib import Path, PurePath
from typing import Tuple, Collection, Mapping
from subprocess import check_output
from .fs.pathtree import PathTree, PathNode
class GitRepository:
"""Represents a Git repository on the file system."""
def __init__(self, path: str, init=False):
"""Create an abstract... | pre_commit_hooks/util/git.py | from pathlib import Path, PurePath
from typing import Tuple, Collection, Mapping
from subprocess import check_output
from .fs.pathtree import PathTree, PathNode
class GitRepository:
"""Represents a Git repository on the file system."""
def __init__(self, path: str, init=False):
"""Create an abstract... | 0.93263 | 0.463748 |
import requests
import unittest
class TestStringMethods(unittest.TestCase):
'''def test_000_operacoes_ola1(self):
r = requests.get('http://localhost:5000/ola/marcio')
self.assertEqual(r.text,'ola marcio')
r = requests.get('http://localhost:5000/ola/mario')
self.assertEqual(r.... | Aula_04_04/runtests.py | import requests
import unittest
class TestStringMethods(unittest.TestCase):
'''def test_000_operacoes_ola1(self):
r = requests.get('http://localhost:5000/ola/marcio')
self.assertEqual(r.text,'ola marcio')
r = requests.get('http://localhost:5000/ola/mario')
self.assertEqual(r.... | 0.148047 | 0.204203 |
from decimal import Decimal
from analytics.models import Rating
from collector.models import Log
from recs.base_recommender import base_recommender
from django.db.models import Count
from django.db.models import Q
from django.db.models import Avg
class PopularityBasedRecs(base_recommender):
def predict_score(sel... | recs/popularity_recommender.py | from decimal import Decimal
from analytics.models import Rating
from collector.models import Log
from recs.base_recommender import base_recommender
from django.db.models import Count
from django.db.models import Q
from django.db.models import Avg
class PopularityBasedRecs(base_recommender):
def predict_score(sel... | 0.58261 | 0.202739 |
import os
import sys
import pandas as pd
import yaml
# sys.path.append("/home/weber/PycharmProjects/EXOTIC/src")
sys.path.append("/home/weber/PycharmProjects/EXOTIC/clean/src")
pd.options.mode.chained_assignment = None # default='warn'
tqdm.pandas()
# YAML FILES CONFIG
yaml = yaml.load(open(
"/home/weber/Pyc... | src/prepare_refseq.py |
import os
import sys
import pandas as pd
import yaml
# sys.path.append("/home/weber/PycharmProjects/EXOTIC/src")
sys.path.append("/home/weber/PycharmProjects/EXOTIC/clean/src")
pd.options.mode.chained_assignment = None # default='warn'
tqdm.pandas()
# YAML FILES CONFIG
yaml = yaml.load(open(
"/home/weber/Pyc... | 0.396652 | 0.195249 |
import numpy as np
import matplotlib.pyplot as plt
import pandas as pd
import seaborn as sns
from sklearn import datasets
from sklearn.model_selection import train_test_split
import random
from qiskit import *
from qiskit import QuantumCircuit, ClassicalRegister, QuantumRegister
from qiskit import BasicAer, execut... | utils/Utils_pad.py |
import numpy as np
import matplotlib.pyplot as plt
import pandas as pd
import seaborn as sns
from sklearn import datasets
from sklearn.model_selection import train_test_split
import random
from qiskit import *
from qiskit import QuantumCircuit, ClassicalRegister, QuantumRegister
from qiskit import BasicAer, execut... | 0.659734 | 0.868938 |
from __future__ import absolute_import, division, print_function
import csv
import logging
import os
import sys
from collections import OrderedDict
from io import open
import numpy as np
from nltk import word_tokenize
logger = logging.getLogger(__name__)
class ExplaGraphInputExample(object):
def __init__(self,... | structured_model/utils_joint_model.py | from __future__ import absolute_import, division, print_function
import csv
import logging
import os
import sys
from collections import OrderedDict
from io import open
import numpy as np
from nltk import word_tokenize
logger = logging.getLogger(__name__)
class ExplaGraphInputExample(object):
def __init__(self,... | 0.365004 | 0.247214 |
import os
from tempfile import tempdir
from pulsar.manager_factory import build_managers
from pulsar.cache import Cache
from pulsar.tools import ToolBox
from pulsar.tools.authorization import get_authorizer
from pulsar import messaging
from galaxy.objectstore import build_object_store_from_config
from galaxy.tools.dep... | pulsar/core.py | import os
from tempfile import tempdir
from pulsar.manager_factory import build_managers
from pulsar.cache import Cache
from pulsar.tools import ToolBox
from pulsar.tools.authorization import get_authorizer
from pulsar import messaging
from galaxy.objectstore import build_object_store_from_config
from galaxy.tools.dep... | 0.585457 | 0.095729 |
import collections
from typing import Dict, Text
import prometheus_client
import six
from grr_response_core.lib import utils
from grr_response_core.lib.rdfvalues import stats as rdf_stats
from grr_response_core.lib.util import compatibility
from grr_response_core.lib.util import precondition
from grr_response_core.st... | grr/server/grr_response_server/prometheus_stats_collector.py | import collections
from typing import Dict, Text
import prometheus_client
import six
from grr_response_core.lib import utils
from grr_response_core.lib.rdfvalues import stats as rdf_stats
from grr_response_core.lib.util import compatibility
from grr_response_core.lib.util import precondition
from grr_response_core.st... | 0.897622 | 0.287502 |
from __future__ import absolute_import
import re # noqa: F401
# python 2 and python 3 compatibility library
import six
from mailmojo_sdk.api_client import ApiClient
class ListApi(object):
"""NOTE: This class is auto generated by the swagger code generator program.
Do not edit the class manually.
Ref:... | mailmojo_sdk/api/list_api.py | from __future__ import absolute_import
import re # noqa: F401
# python 2 and python 3 compatibility library
import six
from mailmojo_sdk.api_client import ApiClient
class ListApi(object):
"""NOTE: This class is auto generated by the swagger code generator program.
Do not edit the class manually.
Ref:... | 0.665193 | 0.051487 |
import json
import logging
import os
try:
import queue
except ImportError:
import Queue as queue
try:
import socketserver
except ImportError:
import SocketServer as socketserver
from apscheduler.schedulers.background import BackgroundScheduler
from datetime import datetime, timedelta
from flask impor... | jarvis/app.py |
import json
import logging
import os
try:
import queue
except ImportError:
import Queue as queue
try:
import socketserver
except ImportError:
import SocketServer as socketserver
from apscheduler.schedulers.background import BackgroundScheduler
from datetime import datetime, timedelta
from flask impor... | 0.412412 | 0.06134 |
import asyncio
import json
from metarepo2json.metarepo2json.interfaces import KitsInterface
def __init__(hub):
global HUB
global repo_web
global kitinfo_subpath
global kitsha1_subpath
global version_subpath
global fetcher
global get_raw_file_uri
global throw_on_corrupted_metarepo
... | metarepo2json/metarepo2json/kits/kits_web.py |
import asyncio
import json
from metarepo2json.metarepo2json.interfaces import KitsInterface
def __init__(hub):
global HUB
global repo_web
global kitinfo_subpath
global kitsha1_subpath
global version_subpath
global fetcher
global get_raw_file_uri
global throw_on_corrupted_metarepo
... | 0.429549 | 0.110904 |
import datetime
import factory
from accounts.models import Profile
from accounts.models.choices import Title, Role
from django.db.models.signals import post_save
from django.conf import settings
from django.utils import timezone
from random import randint
TEST_PASSWORD = "<PASSWORD>"
TITLES = [title.name for title in... | accounts/tests/factories.py | import datetime
import factory
from accounts.models import Profile
from accounts.models.choices import Title, Role
from django.db.models.signals import post_save
from django.conf import settings
from django.utils import timezone
from random import randint
TEST_PASSWORD = "<PASSWORD>"
TITLES = [title.name for title in... | 0.456894 | 0.114146 |
import inkex
import simplestyle, sys
from math import *
# The simplestyle module provides functions for style parsing.
from simplestyle import *
class Knob_Scale(inkex.Effect):
def __init__(self):
inkex.Effect.__init__(self)
# General settings
self.OptionParser.add_option("--x",
... | knob-scale-generator-master/render_knob_scale.py | import inkex
import simplestyle, sys
from math import *
# The simplestyle module provides functions for style parsing.
from simplestyle import *
class Knob_Scale(inkex.Effect):
def __init__(self):
inkex.Effect.__init__(self)
# General settings
self.OptionParser.add_option("--x",
... | 0.231354 | 0.143008 |
import copy
import os
import shutil
import tempfile
from pathlib import Path
import numpy as np
from fccpy import read_pdb
from fccpy.contacts import get_intermolecular_contacts
from pdbtools import pdb_segxchain
from haddock import log
from haddock.libs.libontology import Format, ModuleIO
from haddock.modules import... | src/haddock/modules/analysis/caprieval/__init__.py | import copy
import os
import shutil
import tempfile
from pathlib import Path
import numpy as np
from fccpy import read_pdb
from fccpy.contacts import get_intermolecular_contacts
from pdbtools import pdb_segxchain
from haddock import log
from haddock.libs.libontology import Format, ModuleIO
from haddock.modules import... | 0.52074 | 0.249865 |
import logging
import time
from ryu.base import app_manager
from ryu.controller import ofp_event
from ryu.controller.handler import MAIN_DISPATCHER, CONFIG_DISPATCHER
from ryu.controller.handler import set_ev_cls
from ryu.ofproto import ofproto_v1_3
from ryu.lib.packet import packet
from ryu.lib.packet import etherne... | ryu/topology/hosts_discovery.py |
import logging
import time
from ryu.base import app_manager
from ryu.controller import ofp_event
from ryu.controller.handler import MAIN_DISPATCHER, CONFIG_DISPATCHER
from ryu.controller.handler import set_ev_cls
from ryu.ofproto import ofproto_v1_3
from ryu.lib.packet import packet
from ryu.lib.packet import etherne... | 0.203154 | 0.067424 |
import cv2
import depthai as dai
import contextlib
# This can be customized to pass multiple parameters
def getPipeline(device_type):
# Start defining a pipeline
pipeline = dai.Pipeline()
# Define a source - color camera
cam_rgb = pipeline.createColorCamera()
# For the demo, just set a larger RGB... | src/multi.py |
import cv2
import depthai as dai
import contextlib
# This can be customized to pass multiple parameters
def getPipeline(device_type):
# Start defining a pipeline
pipeline = dai.Pipeline()
# Define a source - color camera
cam_rgb = pipeline.createColorCamera()
# For the demo, just set a larger RGB... | 0.587588 | 0.181553 |
import torch
from tqdm import tqdm, trange
import torch.nn.functional as F
from torch.autograd import Variable
from denseGCNConv import DenseGCNConv
from torch.nn import Linear, BatchNorm1d
from layers import SecondaryCapsuleLayer, firstCapsuleLayer, ReconstructionNet
class CapsGNN(torch.nn.Module):
def __init__(s... | capsgnn.py | import torch
from tqdm import tqdm, trange
import torch.nn.functional as F
from torch.autograd import Variable
from denseGCNConv import DenseGCNConv
from torch.nn import Linear, BatchNorm1d
from layers import SecondaryCapsuleLayer, firstCapsuleLayer, ReconstructionNet
class CapsGNN(torch.nn.Module):
def __init__(s... | 0.903741 | 0.415729 |
import argparse
import atexit
import pkg_resources # part of setuptools
from winnaker.models import *
from winnaker.notify import *
from winnaker.settings import *
def main():
print("""
____ __ ____ __ .__ __. .__ __. ___ __ ___ _______ .______
\ \ / \ / / | | | \ | | | \ | ... | winnaker/main.py | import argparse
import atexit
import pkg_resources # part of setuptools
from winnaker.models import *
from winnaker.notify import *
from winnaker.settings import *
def main():
print("""
____ __ ____ __ .__ __. .__ __. ___ __ ___ _______ .______
\ \ / \ / / | | | \ | | | \ | ... | 0.31279 | 0.091463 |
import os
import argparse
# Creates a new metricset with all the necessary file
# In case the module does not exist, also the module is created
def generate_metricset(base_path, metricbeat_path, module, metricset):
generate_module(base_path, metricbeat_path, module, metricset)
metricset_path = base_path + "... | vendor/github.com/elastic/beats/metricbeat/scripts/create_metricset.py | import os
import argparse
# Creates a new metricset with all the necessary file
# In case the module does not exist, also the module is created
def generate_metricset(base_path, metricbeat_path, module, metricset):
generate_module(base_path, metricbeat_path, module, metricset)
metricset_path = base_path + "... | 0.547222 | 0.104889 |
import numpy, theano, unittest
from theano.compile.pfunc import pfunc
from theano.compile.sharedvalue import shared
from theano import tensor
from theano.tensor.nnet import sigmoid
class NNet(object):
def __init__(self,
input=tensor.dvector('input'),
target=tensor.dvector('target'),
... | theano/compile/tests/test_misc.py | import numpy, theano, unittest
from theano.compile.pfunc import pfunc
from theano.compile.sharedvalue import shared
from theano import tensor
from theano.tensor.nnet import sigmoid
class NNet(object):
def __init__(self,
input=tensor.dvector('input'),
target=tensor.dvector('target'),
... | 0.497803 | 0.34679 |
from __future__ import division
import numpy as np
import chainer
import chainer.functions as F
from chainer import initializers
import chainer.links as L
from chainercv.links import Conv2DBNActiv
from chainercv.links.model.resnet import ResBlock
from chainercv.links import PickableSequentialChain
from chainercv imp... | chainercv/links/model/senet/se_resnext.py | from __future__ import division
import numpy as np
import chainer
import chainer.functions as F
from chainer import initializers
import chainer.links as L
from chainercv.links import Conv2DBNActiv
from chainercv.links.model.resnet import ResBlock
from chainercv.links import PickableSequentialChain
from chainercv imp... | 0.886746 | 0.425546 |
import unittest
from allergies import Allergies
# Python 2/3 compatibility
if not hasattr(unittest.TestCase, 'assertCountEqual'):
unittest.TestCase.assertCountEqual = unittest.TestCase.assertItemsEqual
# Tests adapted from `problem-specifications//canonical-data.json` @ v1.1.0
class AllergiesTest(unittest.Test... | exercises/allergies/allergies_test.py | import unittest
from allergies import Allergies
# Python 2/3 compatibility
if not hasattr(unittest.TestCase, 'assertCountEqual'):
unittest.TestCase.assertCountEqual = unittest.TestCase.assertItemsEqual
# Tests adapted from `problem-specifications//canonical-data.json` @ v1.1.0
class AllergiesTest(unittest.Test... | 0.633297 | 0.66503 |
import json
import typing
import os
def parseJson(filepath: str, output_folder: str) -> typing.List[dict]:
"""
Read and preprocess document input json, e.g., removal of certain characters.
@param filepath: path to json file
@param output_folder: The folder in which the result is stored
@return: Re... | parser/jsonparser.py | import json
import typing
import os
def parseJson(filepath: str, output_folder: str) -> typing.List[dict]:
"""
Read and preprocess document input json, e.g., removal of certain characters.
@param filepath: path to json file
@param output_folder: The folder in which the result is stored
@return: Re... | 0.461745 | 0.34621 |
"""Utilities for synchronizing and communication across multiple hosts."""
import functools
from typing import Optional
import zlib
import jax
import numpy as np
PyTreeDef = type(jax.tree_structure(None))
# NB: This needs to be top-level for the jax compilation cache.
@functools.partial(jax.pmap, axis_name='hosts'... | t5x/multihost_utils.py |
"""Utilities for synchronizing and communication across multiple hosts."""
import functools
from typing import Optional
import zlib
import jax
import numpy as np
PyTreeDef = type(jax.tree_structure(None))
# NB: This needs to be top-level for the jax compilation cache.
@functools.partial(jax.pmap, axis_name='hosts'... | 0.957715 | 0.464962 |
import numpy as np
import matplotlib.cm
import tensorflow as tf
from audiocodec.mdctransformer import MDCTransformer
from audiocodec.psychoacoustic import PsychoacousticModel
class AudioRepresentation:
def __init__(self, sample_rate, freq_n, compute_dtype):
# [batches_n, blocks_n, freqs_n, channels_n]
# s... | model/audiorepresentation.py | import numpy as np
import matplotlib.cm
import tensorflow as tf
from audiocodec.mdctransformer import MDCTransformer
from audiocodec.psychoacoustic import PsychoacousticModel
class AudioRepresentation:
def __init__(self, sample_rate, freq_n, compute_dtype):
# [batches_n, blocks_n, freqs_n, channels_n]
# s... | 0.90016 | 0.402627 |
import os
import sys
base_path = os.path.dirname(os.path.dirname(os.path.abspath(__file__)))
sys.path.append(base_path)
import multiprocessing as mp
import time
import argparse
import megengine as mge
import megengine.distributed as dist
from megengine.jit import trace
from megengine.data import RandomSampler, Sequenti... | tools/train.py | import os
import sys
base_path = os.path.dirname(os.path.dirname(os.path.abspath(__file__)))
sys.path.append(base_path)
import multiprocessing as mp
import time
import argparse
import megengine as mge
import megengine.distributed as dist
from megengine.jit import trace
from megengine.data import RandomSampler, Sequenti... | 0.261237 | 0.125012 |
from __future__ import annotations
from typing import Union, Optional
import importlib
import os
import pathlib
from enum import Enum
from route import quick_invalid, write, Cause
from route import error as e
class Method(Enum):
GET = "GET"
HEAD = "HEAD"
TRACE = "TRACE"
OPTIONS = "OPTIONS"
CONNEC... | src/endpoint.py | from __future__ import annotations
from typing import Union, Optional
import importlib
import os
import pathlib
from enum import Enum
from route import quick_invalid, write, Cause
from route import error as e
class Method(Enum):
GET = "GET"
HEAD = "HEAD"
TRACE = "TRACE"
OPTIONS = "OPTIONS"
CONNEC... | 0.834744 | 0.149159 |
import pprint
import re # noqa: F401
import six
from ncloud_server.model.common_code import CommonCode # noqa: F401,E501
from ncloud_server.model.port_forwarding_rule import PortForwardingRule # noqa: F401,E501
from ncloud_server.model.zone import Zone # noqa: F401,E501
class DeletePortForwardingRulesResponse(o... | lib/services/server/ncloud_server/model/delete_port_forwarding_rules_response.py | import pprint
import re # noqa: F401
import six
from ncloud_server.model.common_code import CommonCode # noqa: F401,E501
from ncloud_server.model.port_forwarding_rule import PortForwardingRule # noqa: F401,E501
from ncloud_server.model.zone import Zone # noqa: F401,E501
class DeletePortForwardingRulesResponse(o... | 0.673299 | 0.061255 |
__author__ = 'healplease'
import os
import json
import time
import requests
FT_APP_ICON = 0
FT_APP_VIDEO_AND_POSTER = 1
FT_APP_SCREENSHOT = 2
FT_RECOMMENDATION_VIDEO = 3
FT_RECOMMENDATION_IMAGE = 4
FT_APK_OR_RPK = 5
FT_PROXY_CERTIFICATE_OR_COPYRIGHT_IMAGE = 6
FT_CERTIFICATE_PDF = 7
FT_CULTURE_OPERA... | appgallery/utils.py |
__author__ = 'healplease'
import os
import json
import time
import requests
FT_APP_ICON = 0
FT_APP_VIDEO_AND_POSTER = 1
FT_APP_SCREENSHOT = 2
FT_RECOMMENDATION_VIDEO = 3
FT_RECOMMENDATION_IMAGE = 4
FT_APK_OR_RPK = 5
FT_PROXY_CERTIFICATE_OR_COPYRIGHT_IMAGE = 6
FT_CERTIFICATE_PDF = 7
FT_CULTURE_OPERA... | 0.243193 | 0.056993 |
import unittest
import numpy as np
import torch
from parameterized import parameterized
from monai.networks.layers import SavitzkyGolayFilter
from tests.utils import skip_if_no_cuda
# Zero-padding trivial tests
TEST_CASE_SINGLE_VALUE = [
{"window_length": 3, "order": 1},
torch.Tensor([1.0]).unsqueeze(0).un... | tests/test_savitzky_golay_filter.py |
import unittest
import numpy as np
import torch
from parameterized import parameterized
from monai.networks.layers import SavitzkyGolayFilter
from tests.utils import skip_if_no_cuda
# Zero-padding trivial tests
TEST_CASE_SINGLE_VALUE = [
{"window_length": 3, "order": 1},
torch.Tensor([1.0]).unsqueeze(0).un... | 0.781372 | 0.728 |
import argparse
import guitarpro
TOMS = set([38, 40, 37, 41, 43, 45, 47, 48, 50])
CYMBALS = set([49, 57, 52, 55, 51, 53, 54, 56, 59, 42, 44, 46])
HAND_NOTES = TOMS.union(CYMBALS)
def parse_args():
"""Parse input arguments."""
parser = argparse.ArgumentParser()
parser.add_argument(
'--input_file... | standardize_percussion_tracks.py | import argparse
import guitarpro
TOMS = set([38, 40, 37, 41, 43, 45, 47, 48, 50])
CYMBALS = set([49, 57, 52, 55, 51, 53, 54, 56, 59, 42, 44, 46])
HAND_NOTES = TOMS.union(CYMBALS)
def parse_args():
"""Parse input arguments."""
parser = argparse.ArgumentParser()
parser.add_argument(
'--input_file... | 0.586168 | 0.495789 |
from __future__ import print_function, unicode_literals
import io
import subprocess
from argparse import ArgumentParser
try:
prompt = raw_input
except NameError:
prompt = input
parser = ArgumentParser()
parser.add_argument(
'-r', '--requirements', type=str, default='requirements.txt',
... | venv/lib/python3.8/site-packages/upgrade_requirements.py | from __future__ import print_function, unicode_literals
import io
import subprocess
from argparse import ArgumentParser
try:
prompt = raw_input
except NameError:
prompt = input
parser = ArgumentParser()
parser.add_argument(
'-r', '--requirements', type=str, default='requirements.txt',
... | 0.237222 | 0.04982 |
import os
import sys
import logging
# This is the main prefix used for logging
LOGGER_BASENAME = '''_CI._initialize_template'''
LOGGER = logging.getLogger(LOGGER_BASENAME)
LOGGER.addHandler(logging.NullHandler())
def add_ci_directory_to_path():
current_file_path = os.path.dirname(os.path.abspath(__file__))
... | _CI/scripts/_initialize_template.py | import os
import sys
import logging
# This is the main prefix used for logging
LOGGER_BASENAME = '''_CI._initialize_template'''
LOGGER = logging.getLogger(LOGGER_BASENAME)
LOGGER.addHandler(logging.NullHandler())
def add_ci_directory_to_path():
current_file_path = os.path.dirname(os.path.abspath(__file__))
... | 0.155367 | 0.093347 |
import discord
from necrobot.race.racerstatus import RacerStatus
from necrobot.user import userlib
from necrobot.user.necrouser import NecroUser
from necrobot.util import racetime
from necrobot.util.necrodancer import level
FIELD_UNKNOWN = int(-1)
class Racer(object):
def __init__(self, member: discord.Member):... | necrobot/race/racer.py | import discord
from necrobot.race.racerstatus import RacerStatus
from necrobot.user import userlib
from necrobot.user.necrouser import NecroUser
from necrobot.util import racetime
from necrobot.util.necrodancer import level
FIELD_UNKNOWN = int(-1)
class Racer(object):
def __init__(self, member: discord.Member):... | 0.507324 | 0.250065 |
import time
import sys
import signal
import threading
from picam_lib import PicamImpl
#### Setup
print("Starting camera, connecting robot")
camera = PicamImpl(PicamImpl.RAW_BAYER)
subdir = "swc_" % int(time.time())
camera.set_save_directory(subdir)
print("Startup complete")
#### Functions
exit_all_loops = False
e... | picamera/scripts/switch_capture.py |
import time
import sys
import signal
import threading
from picam_lib import PicamImpl
#### Setup
print("Starting camera, connecting robot")
camera = PicamImpl(PicamImpl.RAW_BAYER)
subdir = "swc_" % int(time.time())
camera.set_save_directory(subdir)
print("Startup complete")
#### Functions
exit_all_loops = False
e... | 0.167832 | 0.094052 |
from __future__ import annotations
from .ExpireMessage import ExpireMessage, highest_message_number, message_number_range, valid_message_number_range
from .interfaces import IExpireReceiveListener, IExpireReceiveService
from ..receive import IReceiveListener, IReceiveService
from ..util.Atomic import Atomic
from ..util... | src/rcpicar/expire/ExpireReceiveService.py | from __future__ import annotations
from .ExpireMessage import ExpireMessage, highest_message_number, message_number_range, valid_message_number_range
from .interfaces import IExpireReceiveListener, IExpireReceiveService
from ..receive import IReceiveListener, IReceiveService
from ..util.Atomic import Atomic
from ..util... | 0.588889 | 0.059074 |
from django.forms import widgets
from django import forms
from django.utils.text import slugify
__all__ = [
'CheckboxSelectInlineLabelMultiple',
'CheckboxWithInlineLabel',
'ChoiceWidget',
'PrettyIDsMixin',
'RadioSelect',
'SelectMultipleAutocomplete',
'TextInputWithSubmitButton',
]
class ... | great_components/forms/widgets.py | from django.forms import widgets
from django import forms
from django.utils.text import slugify
__all__ = [
'CheckboxSelectInlineLabelMultiple',
'CheckboxWithInlineLabel',
'ChoiceWidget',
'PrettyIDsMixin',
'RadioSelect',
'SelectMultipleAutocomplete',
'TextInputWithSubmitButton',
]
class ... | 0.532668 | 0.056757 |
from abc import ABC
import logging
import tensorflow as tf
import numpy as np
from submarine.ml.model.abstract_model import AbstractModel
from submarine.ml.registries import input_fn_registry
from submarine.ml.parameters import default_parameters
from submarine.utils.env import get_from_registry, get_from_dicts, get_f... | submarine-sdk/pysubmarine/submarine/ml/model/base_tf_model.py |
from abc import ABC
import logging
import tensorflow as tf
import numpy as np
from submarine.ml.model.abstract_model import AbstractModel
from submarine.ml.registries import input_fn_registry
from submarine.ml.parameters import default_parameters
from submarine.utils.env import get_from_registry, get_from_dicts, get_f... | 0.884233 | 0.219735 |
from .util import number_to_string
from .ellipticcurve import INFINITY
from .keys import SigningKey, VerifyingKey
__all__ = [
"ECDH",
"NoKeyError",
"NoCurveError",
"InvalidCurveError",
"InvalidSharedSecretError",
]
class NoKeyError(Exception):
"""ECDH. Key not found but it is needed for oper... | src/ecdsa/ecdh.py | from .util import number_to_string
from .ellipticcurve import INFINITY
from .keys import SigningKey, VerifyingKey
__all__ = [
"ECDH",
"NoKeyError",
"NoCurveError",
"InvalidCurveError",
"InvalidSharedSecretError",
]
class NoKeyError(Exception):
"""ECDH. Key not found but it is needed for oper... | 0.940223 | 0.292027 |
import copy
import os.path as osp
from loguru import logger
import torch
import torch.multiprocessing as mp
from videoanalyst.evaluation.got_benchmark.experiments import ExperimentGOT10k
from ..tester_base import TRACK_TESTERS, TesterBase
from .utils.got_benchmark_helper import PipelineTracker
@TRACK_TESTERS.regi... | videoanalyst/engine/tester/tester_impl/got10k.py | import copy
import os.path as osp
from loguru import logger
import torch
import torch.multiprocessing as mp
from videoanalyst.evaluation.got_benchmark.experiments import ExperimentGOT10k
from ..tester_base import TRACK_TESTERS, TesterBase
from .utils.got_benchmark_helper import PipelineTracker
@TRACK_TESTERS.regi... | 0.466603 | 0.148109 |
import numpy as np
import os,sys
from plugins.core.logger import logger
from plugins.core.base_plugin_opt import BasePluginOptimizer
"""
Define user customized plugin optimizer for hyper parameter tuning
The class name "PluginOptimizer" should not be changed
user need to implement the search method at minimal
"""
cla... | HPO-demonstration/random/optimizer.py | import numpy as np
import os,sys
from plugins.core.logger import logger
from plugins.core.base_plugin_opt import BasePluginOptimizer
"""
Define user customized plugin optimizer for hyper parameter tuning
The class name "PluginOptimizer" should not be changed
user need to implement the search method at minimal
"""
cla... | 0.413714 | 0.149656 |
from datetime import datetime
from django.utils.translation.trans_real import translation
from .base import MessageBase
from ..errors import NoRouterError
from ..conf import settings
class OutgoingMessage(MessageBase):
"""
"""
def __init__(self, connection=None, template=None, **kwargs):
self._... | lib/rapidsms/messages/outgoing.py |
from datetime import datetime
from django.utils.translation.trans_real import translation
from .base import MessageBase
from ..errors import NoRouterError
from ..conf import settings
class OutgoingMessage(MessageBase):
"""
"""
def __init__(self, connection=None, template=None, **kwargs):
self._... | 0.608012 | 0.085289 |
from preprocess.application import application
from preprocess.bureau_and_balance import bureau_and_balance
from preprocess.previous_application import previous_application
from preprocess.pos_cash import pos_cash
from preprocess.installments_payments import installments_payments
from preprocess.credit_card_balance imp... | credit_risk/task_features_trainer.py | from preprocess.application import application
from preprocess.bureau_and_balance import bureau_and_balance
from preprocess.previous_application import previous_application
from preprocess.pos_cash import pos_cash
from preprocess.installments_payments import installments_payments
from preprocess.credit_card_balance imp... | 0.409693 | 0.290402 |
import warnings
import pulumi
import pulumi.runtime
from typing import Any, Mapping, Optional, Sequence, Union
from ... import _utilities, _tables
from . import outputs
from ._enums import *
from ._inputs import *
__all__ = ['UserRule']
class UserRule(pulumi.CustomResource):
def __init__(__self__,
... | sdk/python/pulumi_azure_native/network/v20210201preview/user_rule.py |
import warnings
import pulumi
import pulumi.runtime
from typing import Any, Mapping, Optional, Sequence, Union
from ... import _utilities, _tables
from . import outputs
from ._enums import *
from ._inputs import *
__all__ = ['UserRule']
class UserRule(pulumi.CustomResource):
def __init__(__self__,
... | 0.825871 | 0.073132 |
import numpy as np
TWO_PI = 2 * np.pi
WORD_CHAR = list(r"Ff+-|[]#!@{}><&()")
def _force_0_to_2pi(x: float) -> float:
# make sure angle_min in (0, 2 pi)
k = np.floor((TWO_PI - x) / TWO_PI)
return x + k * TWO_PI
def _iter_expand(axiom, idict, depth=1, maxdepth=4):
olist = []
for c in axiom:
... | LSystem.py | import numpy as np
TWO_PI = 2 * np.pi
WORD_CHAR = list(r"Ff+-|[]#!@{}><&()")
def _force_0_to_2pi(x: float) -> float:
# make sure angle_min in (0, 2 pi)
k = np.floor((TWO_PI - x) / TWO_PI)
return x + k * TWO_PI
def _iter_expand(axiom, idict, depth=1, maxdepth=4):
olist = []
for c in axiom:
... | 0.576184 | 0.660344 |
import torch
import torch.nn as nn
from torch.nn import functional as F
from collections import OrderedDict
from ..builder import BACKBONES
class PyramidFeatures(nn.Module):
'''
FPN pyramid layer
'''
def __init__(self, C3_size, C4_size, C5_size, feature_size=256):
super(PyramidFeatures, self)... | mmdet3d/models/backbones/fpn18.py | import torch
import torch.nn as nn
from torch.nn import functional as F
from collections import OrderedDict
from ..builder import BACKBONES
class PyramidFeatures(nn.Module):
'''
FPN pyramid layer
'''
def __init__(self, C3_size, C4_size, C5_size, feature_size=256):
super(PyramidFeatures, self)... | 0.93759 | 0.457985 |
import proto # type: ignore
from google.cloud.osconfig_v1beta.types import patch_jobs
from google.protobuf import duration_pb2 # type: ignore
from google.protobuf import timestamp_pb2 # type: ignore
from google.type import datetime_pb2 # type: ignore
from google.type import dayofweek_pb2 # type: ignore
from googl... | google/cloud/osconfig/v1beta/osconfig-v1beta-py/google/cloud/osconfig_v1beta/types/patch_deployments.py | import proto # type: ignore
from google.cloud.osconfig_v1beta.types import patch_jobs
from google.protobuf import duration_pb2 # type: ignore
from google.protobuf import timestamp_pb2 # type: ignore
from google.type import datetime_pb2 # type: ignore
from google.type import dayofweek_pb2 # type: ignore
from googl... | 0.642993 | 0.145146 |
from django.test import TestCase
from django.contrib.sites.models import Site
from .factories import GalleryFactory, PhotoFactory
class SitesTest(TestCase):
urls = 'photologue.tests.test_urls'
def setUp(self):
"""
Create two example sites that we can use to test what gets displayed
... | photologue/tests/test_sites.py | from django.test import TestCase
from django.contrib.sites.models import Site
from .factories import GalleryFactory, PhotoFactory
class SitesTest(TestCase):
urls = 'photologue.tests.test_urls'
def setUp(self):
"""
Create two example sites that we can use to test what gets displayed
... | 0.606615 | 0.464476 |