code stringlengths 20 1.04M | apis list | extract_api stringlengths 75 9.94M |
|---|---|---|
import collections
import contextlib
import dataclasses
import difflib
import gettext
import json
import locale
import logging
import pathlib
import textwrap
gettext.bindtextdomain("taggerbot", "locale")
gettext.textdomain("taggerbot")
from typing import Any, Callable, Dict, List, Optional, Tuple
_ = gettext.gettext... | [
"gettext.bindtextdomain",
"gettext.translation",
"gettext.textdomain",
"collections.defaultdict",
"pathlib.Path",
"collections.namedtuple",
"logging.getLogger"
] | [((159, 204), 'gettext.bindtextdomain', 'gettext.bindtextdomain', (['"""taggerbot"""', '"""locale"""'], {}), "('taggerbot', 'locale')\n", (181, 204), False, 'import gettext\n'), ((205, 236), 'gettext.textdomain', 'gettext.textdomain', (['"""taggerbot"""'], {}), "('taggerbot')\n", (223, 236), False, 'import gettext\n'),... |
import pytest
from eth_utils import (
decode_hex,
to_int,
)
from eth.db.atomic import AtomicDB
from eth.vm.forks.constantinople import ConstantinopleVM
from eth.vm.forks.homestead import HomesteadVM
from eth.chains.mainnet import (
MainnetChain,
MAINNET_GENESIS_HEADER,
)
from eth.chains.ropsten import... | [
"eth_utils.decode_hex",
"eth_utils.to_int",
"trinity.config.ChainConfig.from_eip1085_genesis_config",
"trinity.utils.eip1085.validate_raw_eip1085_genesis_config",
"trinity.config.ChainConfig.from_preconfigured_network",
"pytest.mark.parametrize",
"trinity.utils.db.MemoryDB"
] | [((1124, 1203), 'pytest.mark.parametrize', 'pytest.mark.parametrize', (['"""network_id"""', '(MAINNET_NETWORK_ID, ROPSTEN_NETWORK_ID)'], {}), "('network_id', (MAINNET_NETWORK_ID, ROPSTEN_NETWORK_ID))\n", (1147, 1203), False, 'import pytest\n'), ((1296, 1346), 'trinity.config.ChainConfig.from_preconfigured_network', 'Ch... |
# -*- coding: utf-8 -*-
def predict_rating(gender=None,
occupation=None,
zipcode=None,
title=None,
genres=None,
timestamp=None):
""" Predictor for rating from model/5ba500639252736dee002427
Created using BigMLer
... | [
"re.findall",
"re.match",
"re.escape",
"re.compile"
] | [((2289, 2324), 're.compile', 're.compile', (['expression'], {'flags': 'flags'}), '(expression, flags=flags)\n', (2299, 2324), False, 'import re\n'), ((2343, 2368), 're.findall', 're.findall', (['pattern', 'text'], {}), '(pattern, text)\n', (2353, 2368), False, 'import re\n'), ((3275, 3309), 're.compile', 're.compile',... |
import logging
def init_logging():
logging.root.setLevel(logging.INFO)
logging.basicConfig(
format="%(asctime)s - %(filename)s:%(lineno)d - %(message)s",
datefmt="%Y-%m-%d %H:%M:%S",
)
logging.captureWarnings(capture=True)
| [
"logging.captureWarnings",
"logging.basicConfig",
"logging.root.setLevel"
] | [((41, 76), 'logging.root.setLevel', 'logging.root.setLevel', (['logging.INFO'], {}), '(logging.INFO)\n', (62, 76), False, 'import logging\n'), ((81, 201), 'logging.basicConfig', 'logging.basicConfig', ([], {'format': '"""%(asctime)s - %(filename)s:%(lineno)d - %(message)s"""', 'datefmt': '"""%Y-%m-%d %H:%M:%S"""'}), "... |
## Task 1: Introduction
"""What is BERT
BERT is a large-scale transformer-based Language Model that can be finetuned for a variety of tasks.
For more information, the original paper can be found [here](https://arxiv.org/abs/1810.04805).
[HuggingFace documentation](https://huggingface.co/transformers/model_doc/bert.ht... | [
"numpy.random.seed",
"torch.utils.data.RandomSampler",
"numpy.argmax",
"pandas.read_csv",
"sklearn.model_selection.train_test_split",
"tqdm.notebook.tqdm",
"sklearn.metrics.f1_score",
"torch.utils.data.TensorDataset",
"torch.device",
"torch.no_grad",
"numpy.unique",
"random.seed",
"torch.uti... | [((735, 822), 'pandas.read_csv', 'pd.read_csv', (['"""./Data/smile-annotations-final.csv"""'], {'names': "['id', 'text', 'category']"}), "('./Data/smile-annotations-final.csv', names=['id', 'text',\n 'category'])\n", (746, 822), True, 'import pandas as pd\n'), ((1233, 1346), 'sklearn.model_selection.train_test_split... |
############################################################################
# Copyright 2016 <NAME> #
# #
# Licensed under the Apache License, Version 2.0 (the "License"); #
# you may not use this... | [
"stats.order_mean_shiftexp",
"functools.lru_cache",
"scipy.special.comb"
] | [((10231, 10263), 'functools.lru_cache', 'functools.lru_cache', ([], {'maxsize': '(128)'}), '(maxsize=128)\n', (10250, 10263), False, 'import functools\n'), ((10753, 10783), 'functools.lru_cache', 'functools.lru_cache', ([], {'maxsize': '(8)'}), '(maxsize=8)\n', (10772, 10783), False, 'import functools\n'), ((12114, 12... |
import copy
import datetime
import math
from collections import OrderedDict
from typing import List, Mapping, Tuple, Any, Union, Iterator
import torch.utils.data
from ignite.handlers.checkpoint import BaseSaveHandler
from torch.jit import RecursiveScriptModule
from torch.optim import Adam
import numpy as np
from torch... | [
"copy.deepcopy",
"torch_geometric.data.DataLoader",
"collections.OrderedDict",
"datetime.datetime.now",
"ignite.handlers.global_step_from_engine"
] | [((1855, 1874), 'copy.deepcopy', 'copy.deepcopy', (['root'], {}), '(root)\n', (1868, 1874), False, 'import copy\n'), ((848, 871), 'datetime.datetime.now', 'datetime.datetime.now', ([], {}), '()\n', (869, 871), False, 'import datetime\n'), ((1893, 1914), 'copy.deepcopy', 'copy.deepcopy', (['target'], {}), '(target)\n', ... |
# That last plot looked like nonsense, so let's make it a stacked bar chart
# instead
import os
import matplotlib.pyplot as plt
import seaborn as sns
import numpy as np
ignoreFiles = set([".DS_Store","LICENSE","README.md"])
sherlockTitles = []
for root, dirs, files in os.walk("corpus"):
for fn in files:
if... | [
"matplotlib.pyplot.title",
"matplotlib.pyplot.tight_layout",
"matplotlib.pyplot.show",
"matplotlib.pyplot.legend",
"os.walk",
"numpy.asarray",
"matplotlib.pyplot.bar",
"matplotlib.pyplot.ylabel",
"matplotlib.pyplot.xticks",
"seaborn.set",
"matplotlib.pyplot.xlabel"
] | [((270, 287), 'os.walk', 'os.walk', (['"""corpus"""'], {}), "('corpus')\n", (277, 287), False, 'import os\n'), ((2239, 2248), 'seaborn.set', 'sns.set', ([], {}), '()\n', (2246, 2248), True, 'import seaborn as sns\n'), ((2385, 2428), 'matplotlib.pyplot.xticks', 'plt.xticks', (['index', 'shortTitles'], {'rotation': '(45)... |
import datetime
print(datetime.timezone.utc)
print(datetime.datetime.now())
print(datetime.datetime(1, 2, 3))
print(datetime.datetime(1, 2, 3, tzinfo=datetime.timezone.utc))
print(datetime.datetime(1, 2, 3, tzinfo=datetime.timezone(datetime.timedelta(hours=9))))
| [
"datetime.datetime.now",
"datetime.timedelta",
"datetime.datetime"
] | [((51, 74), 'datetime.datetime.now', 'datetime.datetime.now', ([], {}), '()\n', (72, 74), False, 'import datetime\n'), ((82, 108), 'datetime.datetime', 'datetime.datetime', (['(1)', '(2)', '(3)'], {}), '(1, 2, 3)\n', (99, 108), False, 'import datetime\n'), ((116, 172), 'datetime.datetime', 'datetime.datetime', (['(1)',... |
"""
Copyright (c) 2015 Red Hat, Inc
All rights reserved.
This software may be modified and distributed under the terms
of the BSD license. See the LICENSE file for details.
"""
from __future__ import unicode_literals
import pytest
from atomic_reactor.inner import DockerBuildWorkflow
from atomic_reactor.plugin import... | [
"atomic_reactor.util.ImageName",
"atomic_reactor.plugin.PreBuildPluginsRunner",
"atomic_reactor.inner.DockerBuildWorkflow",
"atomic_reactor.plugin.PluginFailedException",
"pytest.raises"
] | [((731, 763), 'atomic_reactor.util.ImageName', 'ImageName', ([], {'repo': '"""qwe"""', 'tag': '"""asd"""'}), "(repo='qwe', tag='asd')\n", (740, 763), False, 'from atomic_reactor.util import ImageName, df_parser\n'), ((1303, 1349), 'atomic_reactor.inner.DockerBuildWorkflow', 'DockerBuildWorkflow', (['MOCK_SOURCE', '"""t... |
# Copyright 2015, 2016 IBM Corp.
#
# All Rights Reserved.
#
# Licensed under the Apache License, Version 2.0 (the "License"); you may
# not use this file except in compliance with the License. You may obtain
# a copy of the License at
#
# http://www.apache.org/licenses/LICENSE-2.0
#
# Unless require... | [
"src.utility.HMCClientLogger.HMCClientLogger",
"src.common.ListModule.ListModule"
] | [((713, 754), 'src.utility.HMCClientLogger.HMCClientLogger', 'HMCClientLogger.HMCClientLogger', (['__name__'], {}), '(__name__)\n', (744, 754), False, 'from src.utility import HMCClientLogger\n'), ((1659, 1682), 'src.common.ListModule.ListModule', 'ListModule.ListModule', ([], {}), '()\n', (1680, 1682), False, 'from sr... |
from biterm.btm import oBTM
import numpy as np
from time import time
from biterm.cbtm import oBTM as c_oBTM
class TestBTM:
def __init__(self, K, V, theta_z, beta):
self.K = K
self.V = len(V)
self.theta_z = theta_z
self.phi_wz = np.random.dirichlet([beta] * self.V, K)
def sample... | [
"numpy.random.dirichlet",
"biterm.btm.oBTM",
"time.time",
"numpy.array",
"numpy.random.choice",
"biterm.cbtm.oBTM"
] | [((602, 625), 'biterm.btm.oBTM', 'oBTM', (['K', 'V', 'alpha', 'beta'], {}), '(K, V, alpha, beta)\n', (606, 625), False, 'from biterm.btm import oBTM\n'), ((641, 647), 'time.time', 'time', ([], {}), '()\n', (645, 647), False, 'from time import time\n'), ((907, 937), 'biterm.btm.oBTM', 'oBTM', (['K', 'V', 'alpha', 'beta'... |
import inspect
import os
import re
import warnings
from typing import (
TYPE_CHECKING,
Any,
Callable,
ClassVar,
Collection,
Dict,
List,
Optional,
Pattern,
Set,
Text,
Tuple,
Union,
cast,
)
import numpy as np
from aesara.configdefaults import config
from aesara.gr... | [
"aesara.graph.fg.FunctionGraph",
"os.path.isabs",
"typing.cast",
"os.path.dirname",
"numpy.dtype",
"inspect.getfile",
"aesara.link.c.cmodule.GCC_compiler.try_compile_tmp",
"warnings.warn",
"os.path.join",
"re.compile"
] | [((845, 875), 'typing.cast', 'cast', (['CThunkWrapperType', 'thunk'], {}), '(CThunkWrapperType, thunk)\n', (849, 875), False, 'from typing import TYPE_CHECKING, Any, Callable, ClassVar, Collection, Dict, List, Optional, Pattern, Set, Text, Tuple, Union, cast\n'), ((8925, 8979), 're.compile', 're.compile', (['"""^#secti... |
import unittest
from auditai.utils.functions import get_unique_name, two_tailed_ztest, dirichln
class TestUtils(unittest.TestCase):
def test_get_unique_name(self):
new_name = 'matched'
name_list = ['feat1', 'feat2', 'matched']
output = get_unique_name(new_name, name_list)
self.as... | [
"auditai.utils.functions.get_unique_name",
"auditai.utils.functions.dirichln",
"auditai.utils.functions.two_tailed_ztest"
] | [((268, 304), 'auditai.utils.functions.get_unique_name', 'get_unique_name', (['new_name', 'name_list'], {}), '(new_name, name_list)\n', (283, 304), False, 'from auditai.utils.functions import get_unique_name, two_tailed_ztest, dirichln\n'), ((404, 440), 'auditai.utils.functions.get_unique_name', 'get_unique_name', (['n... |
import re
import numpy as np
from typing import Optional, List, Literal
from unidecode import unidecode
import pandas as pd
from .tables import Table
from .variables import Variable
def underscore(name: Optional[str], validate: bool = True) -> Optional[str]:
"""Convert arbitrary string to under_score. This was f... | [
"unidecode.unidecode",
"re.match",
"numpy.where",
"re.sub",
"pandas.concat"
] | [((1884, 1909), 're.sub', 're.sub', (['"""__+"""', '"""__"""', 'name'], {}), "('__+', '__', name)\n", (1890, 1909), False, 'import re\n'), ((2132, 2156), 're.match', 're.match', (['"""^[0-9]"""', 'name'], {}), "('^[0-9]', name)\n", (2140, 2156), False, 'import re\n'), ((4525, 4553), 'pandas.concat', 'pd.concat', (['var... |
# -*- coding: utf-8 -*-
###############################################################################
# Copyright (c), Forschungszentrum Jülich GmbH, IAS-1/PGI-1, Germany. #
# All rights reserved. #
# This file is part of the AiiDA-FLEUR package. ... | [
"aiida.orm.Dict",
"json.load",
"masci_tools.util.xml.xml_getters.get_relaxation_information",
"aiida.orm.BandsData",
"masci_tools.io.parsers.fleur.outxml_parser",
"re.findall",
"lxml.etree.parse",
"masci_tools.io.parsers.fleur.fleur_schema.InputSchemaDict.fromVersion"
] | [((16192, 16203), 'aiida.orm.BandsData', 'BandsData', ([], {}), '()\n', (16201, 16203), False, 'from aiida.orm import Dict, BandsData\n'), ((16720, 16743), 'lxml.etree.parse', 'etree.parse', (['relax_file'], {}), '(relax_file)\n', (16731, 16743), False, 'from lxml import etree\n'), ((16760, 16805), 'masci_tools.util.xm... |
#
# run_mpo_adiab.py
# Toric_Code-Python
# execute mpo_adiab_evol.py
#
# created on Apr 24, 2019 by <NAME>
#
import os, sys, time, datetime, json
import para_dict as p
import numpy as np
from copy import copy
from itertools import product
# create result directory
benchmark = False
nowtime = datetime.datetim... | [
"os.system",
"os.makedirs",
"datetime.datetime.now",
"itertools.product"
] | [((491, 529), 'os.makedirs', 'os.makedirs', (['result_dir'], {'exist_ok': '(True)'}), '(result_dir, exist_ok=True)\n', (502, 529), False, 'import os, sys, time, datetime, json\n'), ((564, 599), 'os.makedirs', 'os.makedirs', (['out_dir'], {'exist_ok': '(True)'}), '(out_dir, exist_ok=True)\n', (575, 599), False, 'import ... |
#!/usr/bin/env python3
import requests
import websocket
import json
import ssl
import gen_valid as gv
import gen_print as gp
class event_notification():
r"""
Main class to subscribe and receive event notifications.
"""
def __init__(self, host, username, password):
r"""
Initialize ins... | [
"requests.session",
"gen_print.qprint_var",
"json.loads",
"json.dumps",
"gen_print.no_header",
"gen_print.strip_brackets",
"gen_valid.valid_value",
"websocket.enableTrace"
] | [((945, 963), 'requests.session', 'requests.session', ([], {}), '()\n', (961, 963), False, 'import requests\n'), ((1231, 1287), 'gen_valid.valid_value', 'gv.valid_value', (['response.status_code'], {'valid_values': '[200]'}), '(response.status_code, valid_values=[200])\n', (1245, 1287), True, 'import gen_valid as gv\n'... |
"""
Copyright 2020 Division of Medical Image Computing, German Cancer Research Center (DKFZ), Heidelberg, Germany
Licensed under the Apache License, Version 2.0 (the "License");
you may not use this file except in compliance with the License.
You may obtain a copy of the License at
http://www.apache.org/licenses/L... | [
"nndet.utils.to_dtype",
"torch.nn.Sequential",
"torch.nn.Upsample",
"nndet.arch.conv.conv_kwargs_helper",
"typing.TypeVar"
] | [((23513, 23551), 'typing.TypeVar', 'TypeVar', (['"""DecoderType"""'], {'bound': 'BaseUFPN'}), "('DecoderType', bound=BaseUFPN)\n", (23520, 23551), False, 'from typing import Sequence, List, Tuple, Union, Callable, Optional, TypeVar\n'), ((8731, 8838), 'nndet.arch.conv.conv_kwargs_helper', 'conv_kwargs_helper', ([], {'... |
from django.db import models
from django.utils import timezone
from datetime import datetime
from .settings import REVIEW_STAGE
# Create your models here.
class Card(models.Model):
# row_id = models.AutoField(primary_key=True)
front = models.TextField()
back = models.TextField(blank=True, null=True)
h... | [
"django.db.models.TextField",
"django.db.models.OneToOneField",
"django.db.models.ForeignKey",
"django.db.models.CharField",
"django.utils.timezone.now",
"django.db.models.BooleanField",
"django.db.models.IntegerField",
"ast.literal_eval",
"django.db.models.DateTimeField",
"datetime.datetime.now"
... | [((245, 263), 'django.db.models.TextField', 'models.TextField', ([], {}), '()\n', (261, 263), False, 'from django.db import models\n'), ((275, 314), 'django.db.models.TextField', 'models.TextField', ([], {'blank': '(True)', 'null': '(True)'}), '(blank=True, null=True)\n', (291, 314), False, 'from django.db import model... |
__author__ = 'sibirrer'
#this file contains a class to make a sersic profile
import numpy as np
from astrofunc.LensingProfiles.sersic_utils import SersicUtil
class Sersic(SersicUtil):
"""
this class contains functions to evaluate an spherical Sersic function
"""
def function(self, x, y, I0_sersic, ... | [
"numpy.zeros_like",
"numpy.empty_like",
"numpy.sin",
"numpy.exp",
"numpy.cos",
"numpy.sqrt"
] | [((614, 660), 'numpy.sqrt', 'np.sqrt', (['(x_shift * x_shift + y_shift * y_shift)'], {}), '(x_shift * x_shift + y_shift * y_shift)\n', (621, 660), True, 'import numpy as np\n'), ((1905, 1918), 'numpy.cos', 'np.cos', (['phi_G'], {}), '(phi_G)\n', (1911, 1918), True, 'import numpy as np\n'), ((1937, 1950), 'numpy.sin', '... |
#A python program to run the ABC-SMC for the RPE1 cell type, hypothesis 1.
#"Approximate Bayesian computation scheme for parameter inference and model selection in dynamical systems" - reference.
#Look the necessary modules.
import numpy as np
from scipy import integrate
#Read in the experimental data.
IL6_da... | [
"numpy.random.uniform",
"numpy.random.choice",
"numpy.sum",
"numpy.empty",
"numpy.asarray",
"numpy.savetxt",
"scipy.integrate.odeint",
"numpy.hstack",
"numpy.prod",
"numpy.max",
"numpy.min",
"numpy.array",
"numpy.loadtxt",
"numpy.linspace",
"numpy.random.normal",
"numpy.log10",
"nump... | [((329, 369), 'numpy.loadtxt', 'np.loadtxt', (['"""IL6_data_pS1_mean_RPE1.txt"""'], {}), "('IL6_data_pS1_mean_RPE1.txt')\n", (339, 369), True, 'import numpy as np\n'), ((386, 426), 'numpy.loadtxt', 'np.loadtxt', (['"""IL6_data_pS3_mean_RPE1.txt"""'], {}), "('IL6_data_pS3_mean_RPE1.txt')\n", (396, 426), True, 'import nu... |
# -*- coding: utf8 -*-fr
"""
ItopapiService is a abstraction of Service representation on iTop
"""
from itopapi.model.prototype import ItopapiPrototype
__version__ = '1.0'
__authors__ = ['<NAME> <<EMAIL>>']
class ItopapiService(ItopapiPrototype):
# Configuration specific to itop
itop = {
# Name of... | [
"itopapi.model.prototype.ItopapiPrototype.get_itop_class",
"itopapi.model.prototype.ItopapiPrototype.find_all",
"itopapi.model.prototype.ItopapiPrototype.find_by_name",
"itopapi.model.prototype.ItopapiPrototype.find"
] | [((927, 969), 'itopapi.model.prototype.ItopapiPrototype.find', 'ItopapiPrototype.find', (['ItopapiService', 'key'], {}), '(ItopapiService, key)\n', (948, 969), False, 'from itopapi.model.prototype import ItopapiPrototype\n'), ((1032, 1083), 'itopapi.model.prototype.ItopapiPrototype.find_by_name', 'ItopapiPrototype.find... |
# -*- coding: utf8 -*-
from copy import deepcopy
from jinja2 import Environment, FileSystemLoader
from math import sqrt
from os import listdir, makedirs, rename
from os.path import basename, dirname, exists, expanduser, isdir, isfile, join, split, splitext
from re import findall, finditer, search, sub, DOTALL, MULTILIN... | [
"copy.deepcopy",
"os.path.join",
"os.makedirs",
"os.path.basename",
"core.conf.logconfig.logger.warning",
"re.finditer",
"os.path.dirname",
"math.sqrt",
"os.path.exists",
"jinja2.FileSystemLoader",
"re.findall",
"os.path.splitext",
"re.search",
"core.conf.logconfig.logger.critical",
"os.... | [((6221, 6241), 'os.path.expanduser', 'expanduser', (['exp_file'], {}), '(exp_file)\n', (6231, 6241), False, 'from os.path import basename, dirname, exists, expanduser, isdir, isfile, join, split, splitext\n'), ((12582, 12595), 'os.listdir', 'listdir', (['path'], {}), '(path)\n', (12589, 12595), False, 'from os import ... |
from uio import fix_ctypes_struct, cached_getter
import ctypes
from ctypes import c_uint8 as ubyte, c_uint16 as ushort, c_uint32 as uint
from .eirq import EIrq
ctr_t = uint # counter value
class Pwm( ctypes.Structure ):
# pwm mode:
# output high while 0 <= counter < compare
# output low while compare ... | [
"ctypes.sizeof"
] | [((3341, 3360), 'ctypes.sizeof', 'ctypes.sizeof', (['ECap'], {}), '(ECap)\n', (3354, 3360), False, 'import ctypes\n')] |
from PIL import Image
import torch
import timm
import requests
import torchvision.transforms as transforms
from timm.data.constants import IMAGENET_DEFAULT_MEAN, IMAGENET_DEFAULT_STD
print(torch.__version__)
# should be 1.8.0
model = torch.hub.load('facebookresearch/deit:main', 'deit_base_patch16_224', pretrained=Tr... | [
"torch.argmax",
"torchvision.transforms.Normalize",
"requests.get",
"torchvision.transforms.CenterCrop",
"torch.hub.load",
"torchvision.transforms.Resize",
"torchvision.transforms.ToTensor"
] | [((237, 327), 'torch.hub.load', 'torch.hub.load', (['"""facebookresearch/deit:main"""', '"""deit_base_patch16_224"""'], {'pretrained': '(True)'}), "('facebookresearch/deit:main', 'deit_base_patch16_224',\n pretrained=True)\n", (251, 327), False, 'import torch\n'), ((760, 777), 'torch.argmax', 'torch.argmax', (['out'... |
# numpy_array.py
import numpy as np
x = [1, 2, 3]
y = np.array([1, 2, 3])
print(x) # [1, 2, 3]
print(y) # [1 2 3]
print(x[0]) # 1
print(y[0]) # 1
print(x + x) # [1, 2, 3, 1, 2, 3]
print(y + y) # [2 4 6]
w = np.zeros(3)
z = np.ones((2, 2))
print(w) # [0. 0. 0.]
print(z)
# [[1. 1.]
# [1. 1.]] | [
"numpy.zeros",
"numpy.array",
"numpy.ones"
] | [((55, 74), 'numpy.array', 'np.array', (['[1, 2, 3]'], {}), '([1, 2, 3])\n', (63, 74), True, 'import numpy as np\n'), ((221, 232), 'numpy.zeros', 'np.zeros', (['(3)'], {}), '(3)\n', (229, 232), True, 'import numpy as np\n'), ((237, 252), 'numpy.ones', 'np.ones', (['(2, 2)'], {}), '((2, 2))\n', (244, 252), True, 'import... |
# Copyright (c) Facebook, Inc. and its affiliates.
#
# Licensed under the Apache License, Version 2.0 (the "License");
# you may not use this file except in compliance with the License.
# You may obtain a copy of the License at
#
# http://www.apache.org/licenses/LICENSE-2.0
#
# Unless required by applicable law or ... | [
"numpy.linspace"
] | [((766, 793), 'numpy.linspace', 'np.linspace', (['(0.05)', '(0.95)', '(19)'], {}), '(0.05, 0.95, 19)\n', (777, 793), True, 'import numpy as np\n'), ((807, 834), 'numpy.linspace', 'np.linspace', (['(0.05)', '(0.95)', '(19)'], {}), '(0.05, 0.95, 19)\n', (818, 834), True, 'import numpy as np\n'), ((848, 875), 'numpy.linsp... |
# Copyright (c) Facebook, Inc. and its affiliates. All rights reserved.
#
# This source code is licensed under the BSD license found in the
# LICENSE file in the root directory of this source tree.
import pytest
import torch
from fairscale.nn import Top2Gate
from fairscale.nn.moe.top2gate import top2gating
skip_if_n... | [
"torch.manual_seed",
"torch.argmax",
"fairscale.nn.Top2Gate",
"torch.randn",
"fairscale.nn.moe.top2gate.top2gating",
"torch.cuda.is_available",
"pytest.approx",
"torch.sum",
"torch.all"
] | [((435, 449), 'fairscale.nn.Top2Gate', 'Top2Gate', (['(4)', '(8)'], {}), '(4, 8)\n', (443, 449), False, 'from fairscale.nn import Top2Gate\n'), ((561, 581), 'torch.manual_seed', 'torch.manual_seed', (['(3)'], {}), '(3)\n', (578, 581), False, 'import torch\n'), ((1037, 1070), 'torch.all', 'torch.all', (['(combine_weight... |
"""
定义Spectral Normal的计算函数
构建一个SN类 返回多种不同的SN计算
"""
import tensorflow as tf
class SpectralNormalization():
def __init__(self):
"""
反卷积层不需要SN 因为反卷积不出现在判别器中
但是为了开发的完整性 增加反卷积的真谱范数计算的选择
卷积的卷积核的维度意义如下
2D
[filter_height, filter_width, in_channels, out_channels]
3D
... | [
"tensorflow.linalg.matmul",
"tensorflow.random.normal",
"tensorflow.reshape",
"tensorflow.nn.conv3d_transpose",
"tensorflow.transpose",
"tensorflow.nn.conv3d",
"tensorflow.linalg.norm"
] | [((2618, 2659), 'tensorflow.reshape', 'tf.reshape', (['weight', '[weight.shape[0], -1]'], {}), '(weight, [weight.shape[0], -1])\n', (2628, 2659), True, 'import tensorflow as tf\n'), ((2704, 2743), 'tensorflow.random.normal', 'tf.random.normal', ([], {'shape': '[w.shape[0], 1]'}), '(shape=[w.shape[0], 1])\n', (2720, 274... |
"""
orders.py
"""
import logging
import requests
logger = logging.getLogger(__name__)
class Orders():
def __init__(self, parent):
"""Initialize Orders object.
Parameters
----------
parent : obj
The Cart3d object
Returns
-------
None
"... | [
"requests.get",
"requests.put",
"requests.post",
"logging.getLogger"
] | [((59, 86), 'logging.getLogger', 'logging.getLogger', (['__name__'], {}), '(__name__)\n', (76, 86), False, 'import logging\n'), ((1860, 1909), 'requests.get', 'requests.get', (['url'], {'headers': 'headers', 'params': 'params'}), '(url, headers=headers, params=params)\n', (1872, 1909), False, 'import requests\n'), ((22... |
import numpy as np
import matplotlib.pyplot as plt
import pandas as pd
df = pd.read_csv("data_1d.csv", header=None)
x = df[0].values
y = df[1].values
x_mean = x.mean()
x2_mean = (x*x).mean()
x_mean2 = x_mean*x_mean
y_mean = y.mean()
xy_mean = (x*y).mean()
a = (xy_mean-x_mean*y_mean)/(x2_mean-x_mean2)... | [
"pandas.read_csv",
"matplotlib.pyplot.scatter",
"matplotlib.pyplot.show",
"matplotlib.pyplot.plot"
] | [((81, 120), 'pandas.read_csv', 'pd.read_csv', (['"""data_1d.csv"""'], {'header': 'None'}), "('data_1d.csv', header=None)\n", (92, 120), True, 'import pandas as pd\n'), ((396, 413), 'matplotlib.pyplot.scatter', 'plt.scatter', (['x', 'y'], {}), '(x, y)\n', (407, 413), True, 'import matplotlib.pyplot as plt\n'), ((415, 4... |
"""This module handles all operations involving fetching reports.
The process of fetching reports is made up of these steps:
1. Each vendor is queried for its supported reports using the SUSHI API
2. The vendor is then queried for each supported report, also using the SUSHI API
3. The raw JSON response is converted t... | [
"PyQt5.QtCore.pyqtSignal",
"PyQt5.QtWidgets.QListView",
"PyQt5.QtWidgets.QPushButton",
"ui.ReportResultWidget.Ui_ReportResultWidget",
"ManageDB.UpdateDatabaseWorker",
"PyQt5.QtWidgets.QVBoxLayout",
"ctypes.windll.kernel32.SetFileAttributesW",
"PyQt5.QtCore.QDate.fromString",
"GeneralUtils.get_specia... | [((78893, 78908), 'PyQt5.QtCore.pyqtSignal', 'pyqtSignal', (['str'], {}), '(str)\n', (78903, 78908), False, 'from PyQt5.QtCore import QObject, QThread, pyqtSignal, QDate, Qt\n'), ((88610, 88625), 'PyQt5.QtCore.pyqtSignal', 'pyqtSignal', (['str'], {}), '(str)\n', (88620, 88625), False, 'from PyQt5.QtCore import QObject,... |
# coding=utf-8
'''
the file shows two ways of thread pool use.
from concurrent.futures import ThreadPoolExecutor
and
from multiprocessing.pool import ThreadPool
'''
import os
import sys
import unittest
import timeit
import time
import random
g_task_count = 16
def _futures_threadpool_framework(func, iterable):
'... | [
"unittest.main",
"multiprocessing.pool.ThreadPool",
"random.randint",
"timeit.default_timer",
"time.sleep",
"sys.stdout.flush",
"concurrent.futures.ThreadPoolExecutor",
"concurrent.futures.as_completed"
] | [((668, 702), 'multiprocessing.pool.ThreadPool', 'ThreadPool', ([], {'processes': 'g_task_count'}), '(processes=g_task_count)\n', (678, 702), False, 'from multiprocessing.pool import ThreadPool\n'), ((1167, 1192), 'time.sleep', 'time.sleep', (["arg[u'value']"], {}), "(arg[u'value'])\n", (1177, 1192), False, 'import tim... |
# Copyright 2019 TerraPower, LLC
#
# Licensed under the Apache License, Version 2.0 (the "License");
# you may not use this file except in compliance with the License.
# You may obtain a copy of the License at
#
# http://www.apache.org/licenses/LICENSE-2.0
#
# Unless required by applicable law or agreed to in writi... | [
"unittest.main",
"os.remove",
"os.getcwd",
"os.path.dirname",
"armi.nuclearDataIO.labels.readBinary",
"armi.nuclearDataIO.labels.writeAscii",
"os.path.join",
"os.chdir"
] | [((737, 762), 'os.path.dirname', 'os.path.dirname', (['__file__'], {}), '(__file__)\n', (752, 762), False, 'import os\n'), ((2620, 2635), 'unittest.main', 'unittest.main', ([], {}), '()\n', (2633, 2635), False, 'import unittest\n'), ((871, 882), 'os.getcwd', 'os.getcwd', ([], {}), '()\n', (880, 882), False, 'import os\... |
# Copyright 2021 Google LLC
#
# Licensed under the Apache License, Version 2.0 (the "License");
# you may not use this file except in compliance with the License.
# You may obtain a copy of the License at
#
# http://www.apache.org/licenses/LICENSE-2.0
#
# Unless required by applicable law or agreed to in writing, ... | [
"unittest.mock.patch",
"re.match",
"gcpdiag.queries.logs.execute_queries",
"gcpdiag.queries.logs.query"
] | [((837, 907), 'unittest.mock.patch', 'mock.patch', (['"""gcpdiag.queries.apis.get_api"""'], {'new': 'apis_stub.get_api_stub'}), "('gcpdiag.queries.apis.get_api', new=apis_stub.get_api_stub)\n", (847, 907), False, 'from unittest import mock\n'), ((1000, 1116), 'gcpdiag.queries.logs.query', 'logs.query', ([], {'project_i... |
import cmath
from fractions import Fraction
def calc(should_print=False):
print("""
Name: float to fraction converter
Operation : conversion of float to fraction of the given input
Inputs : a->float
Outputs: c= fraction of input
Author : UnnatiBhalekar
\n
""")
a = float(input("Ente... | [
"fractions.Fraction"
] | [((362, 377), 'fractions.Fraction', 'Fraction', (['value'], {}), '(value)\n', (370, 377), False, 'from fractions import Fraction\n')] |
import os
import sys
from enum import Enum
class Key(Enum):
""" keyboard keys """
ENTER = [10]
ESC = [27]
ARROW_UP = [27, 91, 65]
ARROW_DOWN = [27, 91, 66]
ARROW_LEFT = [27, 91, 68]
ARROW_RIGHT = [27, 91, 67]
PAGE_UP = [27, 91, 53, 126]
PAGE_DOWN = [27, 91, 54, 126]
HOME = [27,... | [
"sys.stdin.read",
"termios.tcgetattr",
"msvcrt.getch",
"signal.setitimer",
"termios.tcsetattr",
"sys.stdin.fileno",
"signal.alarm",
"signal.signal"
] | [((1314, 1332), 'sys.stdin.fileno', 'sys.stdin.fileno', ([], {}), '()\n', (1330, 1332), False, 'import sys\n'), ((1520, 1534), 'msvcrt.getch', 'msvcrt.getch', ([], {}), '()\n', (1532, 1534), False, 'import msvcrt\n'), ((2324, 2375), 'signal.signal', 'signal.signal', (['signal.SIGALRM', '_Getch.alarm_handler'], {}), '(s... |
import os
from django.db import models
def get_image_path(self, file):
return os.path.join("research", "static", "images", type(self).__name__, file)
class Projects(models.Model):
title = models.CharField(max_length=200)
principal_investigator = models.TextField(max_length=200)
sponsoring_agency = ... | [
"django.db.models.CharField",
"django.db.models.TextField",
"django.db.models.IntegerField",
"django.db.models.ImageField"
] | [((201, 233), 'django.db.models.CharField', 'models.CharField', ([], {'max_length': '(200)'}), '(max_length=200)\n', (217, 233), False, 'from django.db import models\n'), ((263, 295), 'django.db.models.TextField', 'models.TextField', ([], {'max_length': '(200)'}), '(max_length=200)\n', (279, 295), False, 'from django.d... |
import scrapy, re
from w3lib.html import remove_tags, remove_tags_with_content
from noticias.items import NoticiasItem
class TerraSpider(scrapy.Spider):
name = 'Terra'
allowed_domains = [ 'terra.com.br']
start_urls = ['https://www.terra.com.br/noticias/coronavirus/']
custom_settings = {
'ITEM_PIPELINES': {
... | [
"noticias.items.NoticiasItem",
"w3lib.html.remove_tags_with_content",
"w3lib.html.remove_tags"
] | [((1116, 1159), 'w3lib.html.remove_tags_with_content', 'remove_tags_with_content', (['text', "('script',)"], {}), "(text, ('script',))\n", (1140, 1159), False, 'from w3lib.html import remove_tags, remove_tags_with_content\n'), ((1185, 1223), 'w3lib.html.remove_tags', 'remove_tags', (['text_without_content_tags'], {}), ... |
from matrixclass import Matrix
#########################################
def MatrixProduct(matrixA, matrixB):
if matrixA.numberOfColumns == matrixB.numberOfRows:
resultantMatrix = Matrix(matrixA.numberOfRows, matrixB.numberOfColumns)
matrixBT = matrixB.getTrasnposedMatrix()
resultantPointer = [1, 1]
... | [
"matrixclass.Matrix"
] | [((842, 854), 'matrixclass.Matrix', 'Matrix', (['(2)', '(3)'], {}), '(2, 3)\n', (848, 854), False, 'from matrixclass import Matrix\n'), ((939, 951), 'matrixclass.Matrix', 'Matrix', (['(3)', '(3)'], {}), '(3, 3)\n', (945, 951), False, 'from matrixclass import Matrix\n'), ((191, 244), 'matrixclass.Matrix', 'Matrix', (['m... |
import sys
from PySide2.QtCore import Qt, QTimer
from PySide2.QtGui import QCursor, QIcon
from PySide2.QtWidgets import QApplication, QMainWindow
import memorymuppets.resources # noqa
from memorymuppets import ui
from random import randint
class MainWindow(QMainWindow):
def __init__(self, name):
super(M... | [
"random.randint",
"PySide2.QtWidgets.QApplication",
"PySide2.QtGui.QCursor",
"PySide2.QtCore.QTimer",
"PySide2.QtGui.QIcon",
"memorymuppets.ui.build"
] | [((3596, 3612), 'PySide2.QtWidgets.QApplication', 'QApplication', (['[]'], {}), '([])\n', (3608, 3612), False, 'from PySide2.QtWidgets import QApplication, QMainWindow\n'), ((416, 430), 'memorymuppets.ui.build', 'ui.build', (['self'], {}), '(self)\n', (424, 430), False, 'from memorymuppets import ui\n'), ((652, 660), '... |
#!/usr/bin/python
import socket
import cv2
import numpy
TCP_IP = '192.168.1.100'
TCP_PORT = 5001
sock = socket.socket()
sock.connect((TCP_IP, TCP_PORT))
capture = cv2.VideoCapture(0)
ret, frame = capture.read()
encode_param=[int(cv2.IMWRITE_JPEG_QUALITY),90]
result, imgencode = cv2.imencode('.jpg', frame, encode_pa... | [
"socket.socket",
"cv2.imdecode",
"cv2.VideoCapture",
"numpy.array",
"cv2.imencode"
] | [((106, 121), 'socket.socket', 'socket.socket', ([], {}), '()\n', (119, 121), False, 'import socket\n'), ((166, 185), 'cv2.VideoCapture', 'cv2.VideoCapture', (['(0)'], {}), '(0)\n', (182, 185), False, 'import cv2\n'), ((283, 324), 'cv2.imencode', 'cv2.imencode', (['""".jpg"""', 'frame', 'encode_param'], {}), "('.jpg', ... |
'''
File name: filter.py
Author: ZeroPass - <NAME>
License: MIT lincense
Python Version: 3.6
'''
from asn1crypto import crl, x509
import re
from settings import *
from database.storage.x509Storage import readFromDB_DSC_issuer_serialNumber, \
readFromDB_CSCA_issu... | [
"database.storage.x509Storage.readFromDB_CSCA_authorityKey",
"database.storage.x509Storage.readFromDB_CSCA_issuer_serialNumber",
"database.storage.x509Storage.deleteFromDB_DSC",
"database.storage.x509Storage.deleteFromDB_CSCA",
"database.storage.x509Storage.readFromDB_DSC_authorityKey",
"database.storage.... | [((2016, 2073), 'database.storage.x509Storage.readFromDB_CSCA_authorityKey', 'readFromDB_CSCA_authorityKey', (['CSCA.subjectKey', 'connection'], {}), '(CSCA.subjectKey, connection)\n', (2044, 2073), False, 'from database.storage.x509Storage import readFromDB_DSC_issuer_serialNumber, readFromDB_CSCA_issuer_serialNumber,... |
#!/usr/bin/python3
"""
This is a script to test Redis Stream Server for load testing.
"""
import json
import time
import sys
from locust import User, events, TaskSet, task
import redis
import gevent.monkey
gevent.monkey.patch_all()
from mysql.connector import connect, Error
import json
import datetime
def load_config... | [
"redis.Redis",
"locust.events.request_success.fire",
"locust.events.request_failure.fire",
"mysql.connector.connect",
"json.dumps",
"time.time",
"locust.task",
"sys.getsizeof"
] | [((535, 598), 'redis.Redis', 'redis.Redis', ([], {'host': 'settings.redis_host', 'port': 'settings.redis_port'}), '(host=settings.redis_host, port=settings.redis_port)\n', (546, 598), False, 'import redis\n'), ((3265, 3272), 'locust.task', 'task', (['(1)'], {}), '(1)\n', (3269, 3272), False, 'from locust import User, e... |
#!/usr/bin/env python3
"""test_expansion.py
Unit test for the 'expansion' common module.
"""
__author__ = '<NAME>'
import unittest
import common.expansion as expan
class TestExpansion(unittest.TestCase):
def test_sqrt_decimal_expansion(self) -> None:
self.assertEqual(expan.sqrt_decimal_expansion(1, 0... | [
"unittest.main",
"common.expansion.sqrt_fraction_expansion",
"common.expansion.sqrt_decimal_expansion"
] | [((2193, 2208), 'unittest.main', 'unittest.main', ([], {}), '()\n', (2206, 2208), False, 'import unittest\n'), ((287, 321), 'common.expansion.sqrt_decimal_expansion', 'expan.sqrt_decimal_expansion', (['(1)', '(0)'], {}), '(1, 0)\n', (315, 321), True, 'import common.expansion as expan\n'), ((354, 388), 'common.expansion... |
import numpy as np
import struct
from dataset.base import IDataset
from util.file import clean_dir, file_exists
from util.download import download_files, concatenate_urls
MNIST_IMAGE_MAGIC = 2051
MNIST_LABEL_MAGIC = 2049
COMMON_URL = "http://yann.lecun.com/exdb/mnist/"
FILE_NAMES = [
"train-images-idx3-ubyte",... | [
"gzip.open",
"util.download.concatenate_urls",
"util.file.clean_dir",
"util.download.download_files",
"util.file.file_exists",
"os.path.join"
] | [((669, 718), 'util.download.concatenate_urls', 'concatenate_urls', (['download_path', 'FILE_NAMES', '"""gz"""'], {}), "(download_path, FILE_NAMES, 'gz')\n", (685, 718), False, 'from util.download import download_files, concatenate_urls\n'), ((861, 907), 'util.download.concatenate_urls', 'concatenate_urls', (['save_pat... |
# Generated by Django 3.1.6 on 2021-02-07 20:29
from django.conf import settings
from django.db import migrations, models
import django.db.models.deletion
class Migration(migrations.Migration):
dependencies = [
migrations.swappable_dependency(settings.AUTH_USER_MODEL),
('hoodApp', '0001_initial'... | [
"django.db.models.OneToOneField",
"django.db.migrations.swappable_dependency",
"django.db.models.CharField",
"django.db.models.ForeignKey",
"django.db.models.EmailField",
"django.db.models.ImageField",
"django.db.models.AutoField"
] | [((227, 284), 'django.db.migrations.swappable_dependency', 'migrations.swappable_dependency', (['settings.AUTH_USER_MODEL'], {}), '(settings.AUTH_USER_MODEL)\n', (258, 284), False, 'from django.db import migrations, models\n'), ((453, 546), 'django.db.models.AutoField', 'models.AutoField', ([], {'auto_created': '(True)... |
"""
"""
from datetime import datetime
def prompt_time(default_time, text):
"""
Prompt the user to input a time.
:param default_time: String, The default time to offer
:param text: String, The text to prompt the user with
:return: A datetime, the current day and the user input time
"""
... | [
"datetime.datetime.strptime",
"datetime.datetime.now",
"datetime.datetime"
] | [((538, 570), 'datetime.datetime.strptime', 'datetime.strptime', (['time', '"""%H:%M"""'], {}), "(time, '%H:%M')\n", (555, 570), False, 'from datetime import datetime\n'), ((644, 658), 'datetime.datetime.now', 'datetime.now', ([], {}), '()\n', (656, 658), False, 'from datetime import datetime\n'), ((678, 746), 'datetim... |
# -*- coding: utf-8 -*-
"""
Created on Tue Jul 27 10:23:59 2021
@author: alber
"""
import re
import os
import pandas as pd
import numpy as np
import spacy
import pickle
import lightgbm as lgb
import imblearn
from sklearn import preprocessing
from sklearn.semi_supervised import (
LabelPropagation,
LabelSpread... | [
"pandas.DataFrame",
"sklearn.dummy.DummyClassifier",
"nltk.stem.snowball.SnowballStemmer",
"lightgbm.LGBMClassifier",
"sklearn.preprocessing.StandardScaler",
"sklearn.metrics.roc_curve",
"pandas.read_csv",
"statsmodels.stats.inter_rater.cohens_kappa",
"sklearn.metrics.classification_report",
"spac... | [((927, 956), 'spacy.load', 'spacy.load', (['"""es_core_news_md"""'], {}), "('es_core_news_md')\n", (937, 956), False, 'import spacy\n'), ((967, 993), 'nltk.stem.snowball.SnowballStemmer', 'SnowballStemmer', (['"""spanish"""'], {}), "('spanish')\n", (982, 993), False, 'from nltk.stem.snowball import SnowballStemmer\n')... |
import os
import unittest
import matplotlib
matplotlib.use('Agg')
import matplotlib.pyplot as plt
plt.style.use('ggplot')
from dymos.utils.doc_utils import save_for_docs
class TestBrachistochroneForDocs(unittest.TestCase):
def tearDown(self):
for filename in ['total_coloring.pkl', 'SLSQP.out', 'SNOPT_p... | [
"os.remove",
"dymos.run_problem",
"matplotlib.pyplot.style.use",
"openmdao.api.Group",
"dymos.Radau",
"openmdao.api.ScipyOptimizeDriver",
"unittest.main",
"openmdao.api.IndepVarComp",
"os.path.exists",
"openmdao.utils.assert_utils.assert_check_partials",
"dymos.examples.plotting.plot_results",
... | [((45, 66), 'matplotlib.use', 'matplotlib.use', (['"""Agg"""'], {}), "('Agg')\n", (59, 66), False, 'import matplotlib\n'), ((99, 122), 'matplotlib.pyplot.style.use', 'plt.style.use', (['"""ggplot"""'], {}), "('ggplot')\n", (112, 122), True, 'import matplotlib.pyplot as plt\n'), ((24831, 24846), 'unittest.main', 'unitte... |
# Copyright (c) 2015, Frappe Technologies Pvt. Ltd. and Contributors
# MIT License. See license.txt
from __future__ import unicode_literals
import frappe
import frappe.translate
import frappe.modules.patch_handler
import frappe.model.sync
from frappe.utils.fixtures import sync_fixtures
from frappe.sessions import cle... | [
"frappe.translate.clear_cache",
"frappe.desk.notifications.clear_notifications",
"frappe.website.render.clear_cache",
"frappe.utils.fixtures.sync_fixtures",
"frappe.modules.patch_handler.run_all",
"frappe.model.sync.sync_all",
"frappe.website.router.sync_global_search",
"frappe.core.doctype.language.l... | [((929, 949), 'frappe.sessions.clear_global_cache', 'clear_global_cache', ([], {}), '()\n', (947, 949), False, 'from frappe.sessions import clear_global_cache\n'), ((973, 1011), 'frappe.modules.patch_handler.run_all', 'frappe.modules.patch_handler.run_all', ([], {}), '()\n', (1009, 1011), False, 'import frappe\n'), ((1... |
# -*- coding: utf-8 -*-
from discord.ext.commands import Cog, Context, command
from discord import Forbidden
from random import randint
from asyncio import sleep
class Roulette(Cog):
"""A fun game for the amusement of everyone on the server."""
def __init__(self, bot):
self.bot = bot
@command()... | [
"discord.ext.commands.command",
"random.randint",
"asyncio.sleep"
] | [((311, 320), 'discord.ext.commands.command', 'command', ([], {}), '()\n', (318, 320), False, 'from discord.ext.commands import Cog, Context, command\n'), ((452, 465), 'random.randint', 'randint', (['(1)', '(6)'], {}), '(1, 6)\n', (459, 465), False, 'from random import randint\n'), ((637, 645), 'asyncio.sleep', 'sleep'... |
import discord
import os
import discord.ext
import asyncio
import requests
from discord.ext import commands
from discord.ext.commands import CommandNotFound
import keep_alive
client = discord.Client()
client = commands.Bot(help_command = None, command_prefix="u!")
@client.event
async def on_ready():
keep_alive.keep_... | [
"keep_alive.keep_alive",
"discord.Game",
"discord.ext.commands.Bot",
"os.getenv",
"os.listdir",
"discord.Client"
] | [((185, 201), 'discord.Client', 'discord.Client', ([], {}), '()\n', (199, 201), False, 'import discord\n'), ((211, 263), 'discord.ext.commands.Bot', 'commands.Bot', ([], {'help_command': 'None', 'command_prefix': '"""u!"""'}), "(help_command=None, command_prefix='u!')\n", (223, 263), False, 'from discord.ext import com... |
import difflib
import os
#function to calculate difference of code output with expected output
filenames = []
TAFilesPath = './dataset/gt'
ourOutputPath = './outputs'
for file in os.listdir(TAFilesPath):
filename = os.fsdecode(file)
filenames.append(filename)
f = open(os.path.join(TAFilesPath, filename), ... | [
"os.fsdecode",
"difflib.ndiff",
"os.path.join",
"os.listdir"
] | [((181, 204), 'os.listdir', 'os.listdir', (['TAFilesPath'], {}), '(TAFilesPath)\n', (191, 204), False, 'import os\n'), ((221, 238), 'os.fsdecode', 'os.fsdecode', (['file'], {}), '(file)\n', (232, 238), False, 'import os\n'), ((479, 546), 'difflib.ndiff', 'difflib.ndiff', (['expected', 'result'], {'charjunk': 'difflib.I... |
import torch
import torch.nn.functional as F
import torch.nn as nn
from scipy.spatial.distance import pdist,squareform
from DNN import CNN
import numpy as np
# ZPI * Spatial GC Layer || ZPI * Temporal GC Layer
class TLSGCNCNN(nn.Module):
def __init__(self, dim_in, dim_out, window_len, link_len, embed_di... | [
"torch.eye",
"torch.stack",
"torch.FloatTensor",
"torch.cat",
"torch.mm",
"torch.einsum",
"torch.matmul"
] | [((1455, 1486), 'torch.stack', 'torch.stack', (['support_set'], {'dim': '(0)'}), '(support_set, dim=0)\n', (1466, 1486), False, 'import torch\n'), ((1548, 1613), 'torch.einsum', 'torch.einsum', (['"""nd,dkio->nkio"""', 'node_embeddings', 'self.weights_pool'], {}), "('nd,dkio->nkio', node_embeddings, self.weights_pool)\... |
# coding: utf-8
#
# Copyright © 2017 weirdgiraffe <<EMAIL>>
#
# Distributed under terms of the MIT license.
#
import seasonvar.parser as parser
import re
from seasonvar.requester import Requester, HTTPError, NetworkError
def day_items(datestr):
r = Requester()
page = r.main_page()
return parser.main_pag... | [
"seasonvar.parser.player_params",
"seasonvar.parser.search_items",
"seasonvar.parser.seasons",
"seasonvar.parser.episodes",
"seasonvar.parser.playlists",
"seasonvar.requester.Requester",
"seasonvar.parser.main_page_items",
"re.compile"
] | [((257, 268), 'seasonvar.requester.Requester', 'Requester', ([], {}), '()\n', (266, 268), False, 'from seasonvar.requester import Requester, HTTPError, NetworkError\n'), ((305, 342), 'seasonvar.parser.main_page_items', 'parser.main_page_items', (['page', 'datestr'], {}), '(page, datestr)\n', (327, 342), True, 'import s... |
"""
Adapted from: https://github.com/muqiaoy/dl_signal/blob/master/music/parse_file.py
This file creates .npy dataset parts from resampled musicnet
Instructions:
First run the resample.py file. Then:
python3 -u parse_file.py
"""
import argparse
import numpy as np
from numpy.lib.format import open_memmap
from s... | [
"numpy.stack",
"argparse.ArgumentParser",
"numpy.empty",
"numpy.zeros",
"numpy.array",
"scipy.fft.rfft"
] | [((4540, 4565), 'argparse.ArgumentParser', 'argparse.ArgumentParser', ([], {}), '()\n', (4563, 4565), False, 'import argparse\n'), ((2864, 2932), 'numpy.empty', 'np.empty', (['[window_counts[recording_nr], n_features]'], {'dtype': 'data_type'}), '([window_counts[recording_nr], n_features], dtype=data_type)\n', (2872, 2... |
import logging
from tensorflow.keras.applications.resnet50 import ResNet50, decode_predictions
from numpy import expand_dims
class ResNet50Predictor:
def __init__(self):
"""
holds the pretrained model
"""
self.model = ResNet50(weights='imagenet')
logging.info('ResNet50 read... | [
"logging.info",
"tensorflow.keras.applications.resnet50.decode_predictions",
"numpy.expand_dims",
"tensorflow.keras.applications.resnet50.ResNet50"
] | [((256, 284), 'tensorflow.keras.applications.resnet50.ResNet50', 'ResNet50', ([], {'weights': '"""imagenet"""'}), "(weights='imagenet')\n", (264, 284), False, 'from tensorflow.keras.applications.resnet50 import ResNet50, decode_predictions\n'), ((293, 354), 'logging.info', 'logging.info', (['"""ResNet50 ready to predic... |
from vanilla import TextBox
from AppKit import NSFontAttributeName, NSFont, NSForegroundColorAttributeName, NSColor, NSMutableAttributedString
class AttributionText(TextBox):
def __init__(self, dimensions, font):
font_name = font.info.familyName or ""
attribution = "{} by {}".format(font_name, f... | [
"AppKit.NSMutableAttributedString.alloc",
"AppKit.NSFont.systemFontSize",
"AppKit.NSColor.whiteColor"
] | [((514, 534), 'AppKit.NSColor.whiteColor', 'NSColor.whiteColor', ([], {}), '()\n', (532, 534), False, 'from AppKit import NSFontAttributeName, NSFont, NSForegroundColorAttributeName, NSColor, NSMutableAttributedString\n'), ((444, 467), 'AppKit.NSFont.systemFontSize', 'NSFont.systemFontSize', ([], {}), '()\n', (465, 467... |
#!/usr/bin/env python3
# -*- coding: utf-8 -*-
"""
A script to re-enable colour in .html files produced from IPython notebooks.
Based on a script in a GitHub gist with this copyright notice:
#----------------------------------------------------------------------------
# Copyright (c) 2013 - <NAME>
#
# Distributed un... | [
"io.open"
] | [((742, 760), 'io.open', 'io.open', (['path', '"""r"""'], {}), "(path, 'r')\n", (749, 760), False, 'import io\n'), ((944, 962), 'io.open', 'io.open', (['path', '"""w"""'], {}), "(path, 'w')\n", (951, 962), False, 'import io\n')] |
#---------------------------------------------------------------------------
# Copyright 2013 The Open Source Electronic Health Record Agent
#
# Licensed under the Apache License, Version 2.0 (the "License");
# you may not use this file except in compliance with the License.
# You may obtain a copy of the License at
#
... | [
"VistATestClient.VistATestClientFactory.createVistATestClientWithArgs",
"VistATestClient.createTestClientArgParser",
"argparse.ArgumentParser",
"unittest.TextTestRunner",
"os.path.dirname",
"unittest.TestLoader",
"re.search"
] | [((4206, 4233), 'VistATestClient.createTestClientArgParser', 'createTestClientArgParser', ([], {}), '()\n', (4231, 4233), False, 'from VistATestClient import VistATestClientFactory, createTestClientArgParser\n'), ((4247, 4338), 'argparse.ArgumentParser', 'argparse.ArgumentParser', ([], {'description': '"""ZTMGRSET Unit... |
import json
from pathlib import Path
from arabic_reshaper import reshape
from hazm import Normalizer, word_tokenize
from loguru import logger
from src.data import DATA_DIR
from wordcloud import WordCloud
class ChatStatistics:
"""Telegram Chat Statistics class
"""
# Class attribute normalizer
normal... | [
"loguru.logger.info",
"json.load",
"arabic_reshaper.reshape",
"hazm.Normalizer"
] | [((327, 339), 'hazm.Normalizer', 'Normalizer', ([], {}), '()\n', (337, 339), False, 'from hazm import Normalizer, word_tokenize\n'), ((384, 454), 'loguru.logger.info', 'logger.info', (['"""Loading stop-words from src/data/persian_stop_words.txt"""'], {}), "('Loading stop-words from src/data/persian_stop_words.txt')\n",... |
import os
import glob
import sys
import heapq
# Merge sort
def sort(arr):
if len(arr) > 1:
left_array = arr[: len(arr) // 2]
right_array = arr[len(arr) // 2 :]
sort(left_array)
sort(right_array)
l_index = 0 # left array index
r_index = 0 # right array index
... | [
"os.remove",
"heapq.heapify",
"os.path.dirname",
"heapq.heappop",
"glob.glob"
] | [((1367, 1400), 'glob.glob', 'glob.glob', (['"""input/unsorted_*.txt"""'], {}), "('input/unsorted_*.txt')\n", (1376, 1400), False, 'import glob\n'), ((2829, 2853), 'heapq.heapify', 'heapq.heapify', (['init_list'], {}), '(init_list)\n', (2842, 2853), False, 'import heapq\n'), ((4073, 4105), 'glob.glob', 'glob.glob', (['... |
from lavadora import Lavadora
from refrigerador import refrigerador
from television import refrigerador
lavadoras = []
refris= []
teles = []
def listar_lavadoras():
lavadora1 = Lavadora('Whirlpool', '2095I', 'Gris', 30, 60, 40)
lavadoras.append(lavadora1)
lavadora1 = Lavadora('Mabe', 'LMD1800B2', 'Gris', ... | [
"lavadora.Lavadora"
] | [((183, 233), 'lavadora.Lavadora', 'Lavadora', (['"""Whirlpool"""', '"""2095I"""', '"""Gris"""', '(30)', '(60)', '(40)'], {}), "('Whirlpool', '2095I', 'Gris', 30, 60, 40)\n", (191, 233), False, 'from lavadora import Lavadora\n'), ((282, 331), 'lavadora.Lavadora', 'Lavadora', (['"""Mabe"""', '"""LMD1800B2"""', '"""Gris"... |
from dagster import RepositoryDefinition
from .hello_world import hello_world_pipeline
from .hello_dag import hello_dag_pipeline
from .actual_dag import actual_dag_pipeline
from .config import hello_with_config_pipeline
from .execution_context import execution_context_pipeline
from .resources_full import resources_pip... | [
"dagster.RepositoryDefinition"
] | [((481, 753), 'dagster.RepositoryDefinition', 'RepositoryDefinition', ([], {'name': '"""tutorial_repository"""', 'pipeline_defs': '[configuration_schema_pipeline, hello_world_pipeline, hello_dag_pipeline,\n actual_dag_pipeline, hello_with_config_pipeline,\n execution_context_pipeline, resources_pipeline, reusing_... |
from django.contrib.auth import authenticate, login
from rest_framework.authtoken.models import Token
from rest_framework.authtoken.views import ObtainAuthToken
from rest_framework.response import Response
from rest_framework.views import APIView
class CustomAuthToken(ObtainAuthToken):
"""Create custom auth token... | [
"rest_framework.authtoken.models.Token.objects.get_or_create",
"rest_framework.response.Response",
"django.contrib.auth.login",
"django.contrib.auth.authenticate"
] | [((604, 642), 'rest_framework.authtoken.models.Token.objects.get_or_create', 'Token.objects.get_or_create', ([], {'user': 'user'}), '(user=user)\n', (631, 642), False, 'from rest_framework.authtoken.models import Token\n'), ((658, 745), 'rest_framework.response.Response', 'Response', (["{'user_id': user.pk, 'email': us... |
from __future__ import print_function
from random import choice
from time import sleep
# import matplotlib.pyplot as plt
# import matplotlib.image as mpimg
import cv2
import numpy as np
import math
import os
from os import listdir
from os.path import isfile, join
import math
import random
from vizdoom import *
impo... | [
"numpy.random.seed",
"math.atan2",
"gym.spaces.Discrete",
"os.path.isfile",
"numpy.random.randint",
"os.path.join",
"math.radians",
"os.path.dirname",
"random.seed",
"math.cos",
"numpy.uint8",
"numpy.asarray",
"math.sin",
"time.sleep",
"gym.spaces.Dict",
"numpy.float32",
"numpy.zeros... | [((3935, 3960), 'os.path.isfile', 'os.path.isfile', (['game_path'], {}), '(game_path)\n', (3949, 3960), False, 'import os\n'), ((9147, 9170), 'gym.spaces.Dict', 'spaces.Dict', (['_obs_space'], {}), '(_obs_space)\n', (9158, 9170), False, 'from gym import spaces\n'), ((9199, 9225), 'gym.spaces.Discrete', 'spaces.Discrete... |
"""
/**
* Copyright (c) 2020-present, Nimbella, Inc.
*
* Licensed under the Apache License, Version 2.0 (the "License");
* you may not use this file except in compliance with the License.
* You may obtain a copy of the License at
*
* http://www.apache.org/licenses/LICENSE-2.0
*
* Unless required by applica... | [
"nimbella.esql",
"os.system"
] | [((862, 999), 'os.system', 'os.system', (['"""docker run -d --name redisqlite --rm -p 6379:6379 sciabarracom/redisqlite:v1.0.4 --requirepass password >/dev/null"""'], {}), "(\n 'docker run -d --name redisqlite --rm -p 6379:6379 sciabarracom/redisqlite:v1.0.4 --requirepass password >/dev/null'\n )\n", (871, 999), ... |
# coding:utf-8
# vim: tabstop=8 expandtab shiftwidth=4 softtabstop=4
import sys, json, datetime
import csvfile_common
import redis
logtype = ('panic', 'fatal', 'error', 'duration', 'slow', 'plan', 'vacuum', 'checkpoint', 'connect', 'parser_stat', 'planner_stat', 'executor_stat', 'statement_stat', 'misc')
def dump_pg... | [
"redis.Redis",
"csvfile_common.makedict",
"datetime.datetime.strptime",
"datetime.timedelta",
"sys.stderr.write",
"sys.stderr.flush",
"csvfile_common.tail_f"
] | [((7307, 7345), 'csvfile_common.tail_f', 'csvfile_common.tail_f', (['pathname', 'where'], {}), '(pathname, where)\n', (7328, 7345), False, 'import csvfile_common\n'), ((6603, 6678), 'datetime.datetime.strptime', 'datetime.datetime.strptime', (["csv_data['log_time']", '"""%Y-%m-%d %H:%M:%S.%f %Z"""'], {}), "(csv_data['l... |
import unittest
import crypto_backend.transformers as trfmer
# from crypto_backend.data import get_data
import pandas as pd
import numpy as np
class TransformerTester(unittest.TestCase):
@classmethod
def setUpClass(cls):
cls.data = pd.DataFrame({'test':[1, 10, 11, 112, 123],
... | [
"pandas.DataFrame",
"crypto_backend.transformers.LogTransformer",
"numpy.exp"
] | [((250, 327), 'pandas.DataFrame', 'pd.DataFrame', (["{'test': [1, 10, 11, 112, 123], 'test2': [1, 10, 11, 112, 123]}"], {}), "({'test': [1, 10, 11, 112, 123], 'test2': [1, 10, 11, 112, 123]})\n", (262, 327), True, 'import pandas as pd\n'), ((718, 728), 'numpy.exp', 'np.exp', (['(11)'], {}), '(11)\n', (724, 728), True, ... |
# Copyright (c) 2013, Web Notes Technologies Pvt. Ltd. and Contributors
# License: GNU General Public License v3. See license.txt
from __future__ import unicode_literals
import vmraid
def execute():
for report in vmraid.db.sql_list(""" select name from `tabReport` where report_type = 'Report Builder'
and is_standa... | [
"vmraid.db.sql_list",
"vmraid.get_doc"
] | [((216, 384), 'vmraid.db.sql_list', 'vmraid.db.sql_list', (['""" select name from `tabReport` where report_type = \'Report Builder\'\n\t\tand is_standard = \'No\' and `json` != \'\' and `json` is not null """'], {}), '(\n """ select name from `tabReport` where report_type = \'Report Builder\'\n\t\tand is_standard = ... |
"""Software to receive sensor readings from data sources and post
them to a HTTP URL. Readings are cached if an Internet connection
is not available, or the the post fails for any reason.
TO DO:
* Test separate threads writing to post_time_file simultaneously
* Perhaps abandon post if it isn't successful aft... | [
"threading.Thread.__init__",
"logging.exception",
"logging.debug",
"json.dumps",
"time.sleep",
"time.time",
"sqlite_queue.SqliteReliableQueue",
"requests.post"
] | [((1797, 1846), 'sqlite_queue.SqliteReliableQueue', 'sqlite_queue.SqliteReliableQueue', (['post_q_filename'], {}), '(post_q_filename)\n', (1829, 1846), False, 'import sqlite_queue\n'), ((3269, 3300), 'threading.Thread.__init__', 'threading.Thread.__init__', (['self'], {}), '(self)\n', (3294, 3300), False, 'import threa... |
import random
def f(n, l):
i = n
if i == 1:
return l
else:
for k in range(i-1):
if l[k] > l[k+1]:
l[k], l[k+1] = l[k+1], l[k]
return f(i-1, l)
A = []
for i in range(10):
A.append(random.randint(0, 100))
print(A)
print(f(len(A), A))
| [
"random.randint"
] | [((251, 273), 'random.randint', 'random.randint', (['(0)', '(100)'], {}), '(0, 100)\n', (265, 273), False, 'import random\n')] |
#crie um programa que vai gerar cinco números aleatórios e colocar em uma tupla. depois disso mostre a listagem de números
#gerados também indique o menor e o maior valor que estão na lista.
from random import randint
print('-' * 40)
print(f'{"MAIOR E MENOR EM TUPLAS":^40}') #titulo
print('-' * 40)
num = (randint(1, 10... | [
"random.randint"
] | [((307, 321), 'random.randint', 'randint', (['(1)', '(10)'], {}), '(1, 10)\n', (314, 321), False, 'from random import randint\n'), ((323, 337), 'random.randint', 'randint', (['(1)', '(10)'], {}), '(1, 10)\n', (330, 337), False, 'from random import randint\n'), ((339, 353), 'random.randint', 'randint', (['(1)', '(10)'],... |
import json
username = input("The username is: ").strip()
password = input("The password is: ").strip()
file_name = 'users.json'
def get_json():
with open(file_name, 'r') as f:
text = f.read()
return json.loads(text)
def write_json(a_dict):
with open(file_name, 'w') as f:
f.write(json.d... | [
"json.loads",
"json.dumps"
] | [((219, 235), 'json.loads', 'json.loads', (['text'], {}), '(text)\n', (229, 235), False, 'import json\n'), ((314, 358), 'json.dumps', 'json.dumps', (['a_dict'], {'sort_keys': '(True)', 'indent': '(4)'}), '(a_dict, sort_keys=True, indent=4)\n', (324, 358), False, 'import json\n')] |
from django.shortcuts import render
from rest_framework import viewsets
from .models import ShoppingCart
from .serializer import ShoppingCartSerializers,ShoppingCartDetailSerializers
from rest_framework.authentication import BasicAuthentication,SessionAuthentication
from rest_framework.permissions import IsAuthenticat... | [
"rest_framework.validators.ValidationError",
"goods.models.Goods.objects.filter"
] | [((2010, 2044), 'rest_framework.validators.ValidationError', 'validators.ValidationError', (['"""商品不足"""'], {}), "('商品不足')\n", (2036, 2044), False, 'from rest_framework import validators\n'), ((2960, 2994), 'rest_framework.validators.ValidationError', 'validators.ValidationError', (['"""商品不足"""'], {}), "('商品不足')\n", (2... |
#!/usr/bin/env python
# -*- coding: UTF-8 -*-
'''
Jesaja Keyword Service - Example
Written by <NAME> <<EMAIL>>
'''
from __future__ import print_function
from future import standard_library
standard_library.install_aliases()
from builtins import map
from builtins import str
from sys import path
from os.path import joi... | [
"json.loads",
"weblyzard_api.client.jesaja_ng.JesajaNg",
"weblyzard_api.model.xml_content.XMLContent",
"future.standard_library.install_aliases",
"os.path.dirname",
"gzip.GzipFile",
"glob.glob",
"builtins.str",
"weblyzard_api.client.jeremia.Jeremia",
"re.compile"
] | [((191, 225), 'future.standard_library.install_aliases', 'standard_library.install_aliases', ([], {}), '()\n', (223, 225), False, 'from future import standard_library\n'), ((688, 703), 're.compile', 'compile', (['"""\\\\s+"""'], {}), "('\\\\s+')\n", (695, 703), False, 'from re import compile\n'), ((719, 736), 're.compi... |
import os
from os.path import expanduser
BASE_DIR = os.path.join(expanduser("~"), ".rdf")
DATA_FILES_PATH = os.path.join(BASE_DIR, "files")
os.makedirs(BASE_DIR, exist_ok=True)
os.makedirs(DATA_FILES_PATH, exist_ok=True)
RDF_REDIS_HOST = os.environ.get("RDF_REDIS_HOST", "localhost")
RDF_REDIS_PORT = os.environ.get(... | [
"os.environ.get",
"os.path.join",
"os.makedirs",
"os.path.expanduser"
] | [((110, 141), 'os.path.join', 'os.path.join', (['BASE_DIR', '"""files"""'], {}), "(BASE_DIR, 'files')\n", (122, 141), False, 'import os\n'), ((143, 179), 'os.makedirs', 'os.makedirs', (['BASE_DIR'], {'exist_ok': '(True)'}), '(BASE_DIR, exist_ok=True)\n', (154, 179), False, 'import os\n'), ((180, 223), 'os.makedirs', 'o... |
"""
seasia_r12_example_plot.py
Make simple SEAsia 1/12 deg SSS plot.
"""
#%%
import coast
import matplotlib.pyplot as plt
#################################################
#%% Loading data
#################################################
dir_nam = "/projectsa/COAsT/NEMO_example_data/SEAsia_R12/"
fil_nam = "SEA... | [
"matplotlib.pyplot.title",
"matplotlib.pyplot.show",
"matplotlib.pyplot.colorbar",
"matplotlib.pyplot.figure",
"coast.Gridded",
"matplotlib.pyplot.ylabel",
"matplotlib.pyplot.xlabel"
] | [((474, 542), 'coast.Gridded', 'coast.Gridded', (['(dir_nam + fil_nam)', '(dir_nam + dom_nam)'], {'config': 'config_t'}), '(dir_nam + fil_nam, dir_nam + dom_nam, config=config_t)\n', (487, 542), False, 'import coast\n'), ((559, 571), 'matplotlib.pyplot.figure', 'plt.figure', ([], {}), '()\n', (569, 571), True, 'import ... |
#!/usr/bin/env python3
import argparse
import io
import os
import wave
import zipfile
from wave import Wave_write
start_encode = 'SND '.encode()
wav_params = (1, 2, 44100, 0, 'NONE', 'NONE')
def parse_args(args=None): # : list[str]
# initialize parser
parser = argparse.ArgumentParser()
parser.add_argu... | [
"wave.open",
"io.BytesIO",
"zipfile.ZipFile",
"argparse.ArgumentParser",
"os.makedirs",
"os.path.dirname",
"os.path.exists",
"os.path.splitext",
"os.path.normpath",
"os.path.split",
"os.path.join"
] | [((275, 300), 'argparse.ArgumentParser', 'argparse.ArgumentParser', ([], {}), '()\n', (298, 300), False, 'import argparse\n'), ((921, 952), 'os.path.normpath', 'os.path.normpath', (['args.src_path'], {}), '(args.src_path)\n', (937, 952), False, 'import os\n'), ((1423, 1449), 'os.path.normpath', 'os.path.normpath', (['d... |
from unittest.mock import Mock, patch, mock_open
# Intercept pexpect calls
patch('stack.switch.x1052.pexpect').start()
# We also don't need to sleep
patch('stack.switch.x1052.time').start()
# Throw an exception when we try to write the switch mac address file
mock_open = patch('stack.switch.x1052.open').start()
mock... | [
"unittest.mock.patch",
"unittest.mock.Mock"
] | [((341, 368), 'unittest.mock.Mock', 'Mock', ([], {'side_effect': 'Exception'}), '(side_effect=Exception)\n', (345, 368), False, 'from unittest.mock import Mock, patch, mock_open\n'), ((76, 111), 'unittest.mock.patch', 'patch', (['"""stack.switch.x1052.pexpect"""'], {}), "('stack.switch.x1052.pexpect')\n", (81, 111), Fa... |
"""
Copyright 2018 Skyscanner Ltd
Licensed under the Apache License, Version 2.0 (the "License"); you may not use
this file except in compliance with the License.
You may obtain a copy of the License at
http://www.apache.org/licenses/LICENSE-2.0
Unless required by applicable law or agreed to in writing, software dis... | [
"unittest.mock.Mock",
"cfripper.model.managed_policy_transformer.ManagedPolicyTransformer",
"pycfmodel.parse"
] | [((1578, 1602), 'pycfmodel.parse', 'pycfmodel.parse', (['test_cf'], {}), '(test_cf)\n', (1593, 1602), False, 'import pycfmodel\n'), ((1621, 1655), 'cfripper.model.managed_policy_transformer.ManagedPolicyTransformer', 'ManagedPolicyTransformer', (['cf_model'], {}), '(cf_model)\n', (1645, 1655), False, 'from cfripper.mod... |
# Your imports go here
import logging
import json
logger = logging.getLogger(__name__)
'''
Given a directory with receipt file and OCR output, this function should extract the amount
Parameters:
dirpath (str): directory path containing receipt and ocr output
Returns:
float: returns the extracted ... | [
"json.load",
"logging.getLogger"
] | [((59, 86), 'logging.getLogger', 'logging.getLogger', (['__name__'], {}), '(__name__)\n', (76, 86), False, 'import logging\n'), ((445, 460), 'json.load', 'json.load', (['file'], {}), '(file)\n', (454, 460), False, 'import json\n')] |
from django.contrib import admin
from .models import Profile
class ProfileAdmin(admin.ModelAdmin):
list_display =(
'pk',
'user',
'snils',
'medpolis',
'mobile'
)
list_filter = (
'user',
'snils',
'medpolis',
'mobile',
)
empty... | [
"django.contrib.admin.site.register"
] | [((349, 391), 'django.contrib.admin.site.register', 'admin.site.register', (['Profile', 'ProfileAdmin'], {}), '(Profile, ProfileAdmin)\n', (368, 391), False, 'from django.contrib import admin\n')] |
# -*- coding: utf-8 -*-
"""
Created on Fri Oct 22 2021
@author: <NAME>
Multiple classes for controlling Sky130TempSensor I/Os through FT232H
"""
from pyftdi.gpio import GpioMpsseController
import time
import numpy as np
'''
GPIO Board USB addresses
'''
gpio_in_addr = "ftdi://ftdi:232h:00:fd/1" # {SEL_INST[1:0], SEL... | [
"numpy.std",
"pyftdi.gpio.GpioMpsseController",
"time.sleep"
] | [((1809, 1830), 'pyftdi.gpio.GpioMpsseController', 'GpioMpsseController', ([], {}), '()\n', (1828, 1830), False, 'from pyftdi.gpio import GpioMpsseController\n'), ((2216, 2237), 'pyftdi.gpio.GpioMpsseController', 'GpioMpsseController', ([], {}), '()\n', (2235, 2237), False, 'from pyftdi.gpio import GpioMpsseController\... |
from django.conf import settings
from django.contrib.auth import get_user_model
from django.core.management.base import BaseCommand
from django.db.models import Q
class Command(BaseCommand):
help = "Elevate SSO user permissions for local development purposes"
def add_arguments(self, parser):
parser.a... | [
"django.contrib.auth.get_user_model",
"django.db.models.Q"
] | [((590, 606), 'django.contrib.auth.get_user_model', 'get_user_model', ([], {}), '()\n', (604, 606), False, 'from django.contrib.auth import get_user_model\n'), ((844, 873), 'django.db.models.Q', 'Q', ([], {'email__contains': '"""test.com"""'}), "(email__contains='test.com')\n", (845, 873), False, 'from django.db.models... |
# Copyright (c) 2016-present, Facebook, Inc.
#
# Licensed under the Apache License, Version 2.0 (the "License");
# you may not use this file except in compliance with the License.
# You may obtain a copy of the License at
#
# http://www.apache.org/licenses/LICENSE-2.0
#
# Unless required by applicable law or agreed... | [
"numpy.random.rand",
"numpy.linalg.norm",
"caffe2.python.core.CreateOperator",
"hypothesis.strategies.floats"
] | [((1378, 1453), 'caffe2.python.core.CreateOperator', 'core.CreateOperator', (['"""Lars"""', "['X', 'dX']", "['rescale_factor']"], {'offset': 'offset'}), "('Lars', ['X', 'dX'], ['rescale_factor'], offset=offset)\n", (1397, 1453), False, 'from caffe2.python import core\n'), ((1042, 1079), 'hypothesis.strategies.floats', ... |
#!/usr/bin/env python
import rospy
from ros_tcp_endpoint import TcpServer, RosPublisher, RosSubscriber, RosService
from geometry_msgs.msg import PoseStamped
from geometry_msgs.msg import TwistStamped
from sensor_msgs.msg import Image
from sensor_msgs.msg import CameraInfo
from sensor_msgs.msg import BatteryState
fr... | [
"rospy.spin",
"ros_tcp_endpoint.TcpServer",
"rospy.get_param",
"ros_tcp_endpoint.RosPublisher",
"rospy.init_node",
"rospy.get_name"
] | [((693, 714), 'ros_tcp_endpoint.TcpServer', 'TcpServer', (['servername'], {}), '(servername)\n', (702, 714), False, 'from ros_tcp_endpoint import TcpServer, RosPublisher, RosSubscriber, RosService\n'), ((2070, 2115), 'rospy.get_param', 'rospy.get_param', (['"""TCP_NODE_NAME"""', '"""TCPServer"""'], {}), "('TCP_NODE_NAM... |
from sklearn import svm
import numpy as np
import websocket
import json
from termcolor import cprint, colored
import chat
from config import Config
import sockets
from globalvars import GlobalVars
def main():
config = Config("config.json")
GlobalVars.config = config
cprint("Connecting to SE chat...", "bl... | [
"json.load",
"config.Config",
"json.loads",
"json.dumps",
"sockets.handle_frame",
"termcolor.colored",
"numpy.array",
"chat.connect",
"sklearn.svm.SVC",
"websocket.create_connection",
"termcolor.cprint"
] | [((224, 245), 'config.Config', 'Config', (['"""config.json"""'], {}), "('config.json')\n", (230, 245), False, 'from config import Config\n'), ((282, 324), 'termcolor.cprint', 'cprint', (['"""Connecting to SE chat..."""', '"""blue"""'], {}), "('Connecting to SE chat...', 'blue')\n", (288, 324), False, 'from termcolor im... |
# Generated by the protocol buffer compiler. DO NOT EDIT!
# source: _app_engine_key.proto
import sys
_b = sys.version_info[0] < 3 and (lambda x: x) or (lambda x: x.encode("latin1"))
from google.protobuf import descriptor as _descriptor
from google.protobuf import message as _message
from google.protobuf import refle... | [
"google.protobuf.symbol_database.Default",
"google.protobuf.descriptor.FieldDescriptor"
] | [((496, 522), 'google.protobuf.symbol_database.Default', '_symbol_database.Default', ([], {}), '()\n', (520, 522), True, 'from google.protobuf import symbol_database as _symbol_database\n'), ((2297, 2588), 'google.protobuf.descriptor.FieldDescriptor', '_descriptor.FieldDescriptor', ([], {'name': '"""path"""', 'full_nam... |
import torch
import torch.backends.cudnn as cudnn
import argparse
import numpy as np
import pandas as pd
import pyvista as pv
from pyro.infer import SVI, Trace_ELBO
from pyro.optim import StepLR
from torch.optim import Adam
from torch_geometric.utils import to_trimesh
from torch_geometric.datasets import FAUST
from tor... | [
"torch.ones",
"torch_geometric.datasets.FAUST",
"numpy.random.seed",
"coma.models.init_coma",
"argparse.ArgumentParser",
"torch.manual_seed",
"coma.utils.writer.MeshWriter",
"torch_geometric.utils.to_trimesh",
"pyro.optim.StepLR",
"coma.models.elbo.CustomELBO",
"torch.cuda.is_available",
"pyro... | [((709, 764), 'argparse.ArgumentParser', 'argparse.ArgumentParser', ([], {'description': '"""mesh autoencoder"""'}), "(description='mesh autoencoder')\n", (732, 764), False, 'import argparse\n'), ((2660, 2680), 'numpy.random.seed', 'np.random.seed', (['seed'], {}), '(seed)\n', (2674, 2680), True, 'import numpy as np\n'... |
# -*- coding: utf-8 -*-
# MegEngine is Licensed under the Apache License, Version 2.0 (the "License")
#
# Copyright (c) 2014-2021 Megvii Inc. All rights reserved.
#
# Unless required by applicable law or agreed to in writing,
# software distributed under the License is distributed on an
# "AS IS" BASIS, WITHOUT ARRANTI... | [
"numpy.random.rand",
"numpy.random.randint"
] | [((816, 855), 'numpy.random.randint', 'np.random.randint', (['(10)'], {'size': 'label_shape'}), '(10, size=label_shape)\n', (833, 855), True, 'import numpy as np\n'), ((751, 778), 'numpy.random.rand', 'np.random.rand', (['*data_shape'], {}), '(*data_shape)\n', (765, 778), True, 'import numpy as np\n')] |
# Copyright 2017 SAS Project Authors. All Rights Reserved.
#
# Licensed under the Apache License, Version 2.0 (the "License");
# you may not use this file except in compliance with the License.
# You may obtain a copy of the License at
#
# http://www.apache.org/licenses/LICENSE-2.0
#
# Unless requ... | [
"logging.error",
"util.configurable_testcase",
"logging.debug",
"reference_models.antenna.antenna.GetStandardAntennaGains",
"math.floor",
"reference_models.propagation.wf_hybrid.CalcHybridPropagationLoss",
"util.loadConfig",
"logging.info",
"reference_models.geo.utils.GridPolygon",
"reference_mode... | [((7389, 7444), 'util.configurable_testcase', 'configurable_testcase', (['generate_FT_S_PAT_default_config'], {}), '(generate_FT_S_PAT_default_config)\n', (7410, 7444), False, 'from util import winnforum_testcase, configurable_testcase, writeConfig, loadConfig\n'), ((2721, 2989), 'reference_models.propagation.wf_itm.Ca... |
""" Example: Shows how to create, train and use an FAQ matcher. """
import urllib3
import csv
import feersum_nlu
from feersum_nlu.rest import ApiException
from examples import feersumnlu_host, feersum_nlu_auth_token
# Configure API key authorization: APIKeyHeader
configuration = feersum_nlu.Configuration()... | [
"csv.reader",
"feersum_nlu.Configuration",
"feersum_nlu.LabelledTextSample",
"feersum_nlu.TextInput",
"feersum_nlu.ApiClient"
] | [((293, 320), 'feersum_nlu.Configuration', 'feersum_nlu.Configuration', ([], {}), '()\n', (318, 320), False, 'import feersum_nlu\n'), ((568, 604), 'feersum_nlu.ApiClient', 'feersum_nlu.ApiClient', (['configuration'], {}), '(configuration)\n', (589, 604), False, 'import feersum_nlu\n'), ((976, 1052), 'csv.reader', 'csv.... |
# chat/routing.py
from django.urls import re_path
from . import consumers
websocket_urlpatterns = [
re_path(r'ws/room/(?P<loc_name>\w+)/$', consumers.DataConsumer),
re_path(r'ws/control/(?P<thing>\w+)/$', consumers.CommandConsumer),
] | [
"django.urls.re_path"
] | [((105, 168), 'django.urls.re_path', 're_path', (['"""ws/room/(?P<loc_name>\\\\w+)/$"""', 'consumers.DataConsumer'], {}), "('ws/room/(?P<loc_name>\\\\w+)/$', consumers.DataConsumer)\n", (112, 168), False, 'from django.urls import re_path\n'), ((174, 240), 'django.urls.re_path', 're_path', (['"""ws/control/(?P<thing>\\\... |
import time
import logging
import config
import sys
import os
import re
from collections import namedtuple
import csv
from ast import literal_eval
def sleep(seconds):
# Slepper for snapshots
# Can be changed to minutes, kept to sec for precision
logging.debug("Sleep for {} seconds".format(seconds))
ti... | [
"re.split",
"logging.FileHandler",
"csv.reader",
"logging.debug",
"logging.StreamHandler",
"time.sleep",
"logging.Formatter",
"os.path.isfile",
"ast.literal_eval",
"logging.getLogger"
] | [((318, 337), 'time.sleep', 'time.sleep', (['seconds'], {}), '(seconds)\n', (328, 337), False, 'import time\n'), ((388, 538), 'logging.Formatter', 'logging.Formatter', (['"""%(asctime)s.%(msecs)03d000 [%(processName)s-%(threadName)-12.12s] [%(levelname)-5.5s] %(message)s"""', '"""%Y-%m-%d %H:%M:%S"""'], {}), "(\n '... |
import itertools
def add(*matrices):
heighte = len(matrices[0])
length = len(matrices[0][0])
for x in matrices:
if len(x) != heighte:
raise ValueError("Given matrices are not the same size.")
for y in x:
if len(y) != length:
raise ValueError("Given ma... | [
"itertools.chain"
] | [((419, 438), 'itertools.chain', 'itertools.chain', (['*m'], {}), '(*m)\n', (434, 438), False, 'import itertools\n')] |
### Image and steering angle extraction
import csv
import cv2
import numpy as np
from scipy import ndimage
lines = []
with open('./data_store_2/driving_log.csv') as csvfile:
my_read = csv.reader(csvfile)
for line in my_read:
lines.append(line)
### Initializers for the paramters to be used
images=[]... | [
"csv.reader",
"keras.layers.Cropping2D",
"cv2.cvtColor",
"keras.layers.Dropout",
"keras.layers.Flatten",
"numpy.shape",
"cv2.imread",
"numpy.fliplr",
"keras.layers.Dense",
"numpy.array",
"keras.layers.Lambda",
"keras.layers.Conv2D",
"keras.models.Sequential"
] | [((1920, 1936), 'numpy.array', 'np.array', (['images'], {}), '(images)\n', (1928, 1936), True, 'import numpy as np\n'), ((1947, 1972), 'numpy.array', 'np.array', (['steering_angles'], {}), '(steering_angles)\n', (1955, 1972), True, 'import numpy as np\n'), ((2212, 2224), 'keras.models.Sequential', 'Sequential', ([], {}... |
# Licensed to the Apache Software Foundation (ASF) under one
# or more contributor license agreements. See the NOTICE file
# distributed with this work for additional information
# regarding copyright ownership. The ASF licenses this file
# to you under the Apache License, Version 2.0 (the
# "License"); you may not u... | [
"logging.warning",
"tvm._ffi.get_global_func"
] | [((909, 955), 'tvm._ffi.get_global_func', 'get_global_func', (['func_name'], {'allow_missing': '(True)'}), '(func_name, allow_missing=True)\n', (924, 955), False, 'from tvm._ffi import get_global_func\n'), ((997, 1064), 'logging.warning', 'logging.warning', (['"""TVM is built with thrust but thrust is not used."""'], {... |
Subsets and Splits
No community queries yet
The top public SQL queries from the community will appear here once available.