code stringlengths 20 1.04M | apis list | extract_api stringlengths 75 9.94M |
|---|---|---|
#coding=utf-8
#正则表达式练习
#导入re模块
import re
'''
匹配单个字符串
. 匹配任意1个字符(除了\n)
[] 匹配[]中列举的字符
\d 匹配数字,即0-9
\D 匹配非数字,即不是数字
\s 匹配空白,即 空格,tab键
\S 匹配非空白
\w 匹配单词字符,即a-z、A-Z、0-9、_
\W 匹配非单词字符
'''
####################################################
#.用法总结:仅代表单个字符
# ret = re.match('.','Mac')
# if ret:
# print(ret.group())
# else:
... | [
"re.match"
] | [((1579, 1610), 're.match', 're.match', (['"""[A-Z][a-z]*"""', '"""Mook"""'], {}), "('[A-Z][a-z]*', 'Mook')\n", (1587, 1610), False, 'import re\n')] |
import numpy as np # random seed
# Preprocessing
import torch
import torchvision.datasets as dset
import torchvision.transforms as transforms
from torch.utils.data import DataLoader, sampler, random_split, Dataset
from PIL import Image
class NewDataset(Dataset):
def __init__(self, data, targets, na... | [
"numpy.random.seed",
"torch.utils.data.DataLoader",
"torch.LongTensor",
"torchvision.transforms.RandomHorizontalFlip",
"torchvision.datasets.CIFAR10",
"numpy.array",
"numpy.arange",
"PIL.Image.fromarray",
"torchvision.transforms.RandomCrop",
"torchvision.transforms.Normalize",
"torchvision.datas... | [((1450, 1537), 'torchvision.datasets.MNIST', 'dset.MNIST', ([], {'root': '"""../dataset/MNIST"""', 'train': '(True)', 'transform': 'transform', 'download': '(True)'}), "(root='../dataset/MNIST', train=True, transform=transform,\n download=True)\n", (1460, 1537), True, 'import torchvision.datasets as dset\n'), ((163... |
# Licensed under a 3-clause BSD style license - see LICENSE.rst
"""
======================
sbpy data.Orbit Module
======================
Class for querying, manipulating, integrating, and fitting orbital elements.
created on June 04, 2017
"""
import os
from numpy import array, ndarray, double, arange
from astropy.tim... | [
"astropy.time.Time",
"astropy.time.Time.now",
"astropy.table.vstack",
"astroquery.jplhorizons.Horizons",
"pyoorb.pyoorb.oorb_init",
"os.getenv"
] | [((15945, 15977), 'pyoorb.pyoorb.oorb_init', 'pyoorb.pyoorb.oorb_init', (['ephfile'], {}), '(ephfile)\n', (15968, 15977), False, 'import pyoorb\n'), ((19174, 19206), 'pyoorb.pyoorb.oorb_init', 'pyoorb.pyoorb.oorb_init', (['ephfile'], {}), '(ephfile)\n', (19197, 19206), False, 'import pyoorb\n'), ((4113, 4183), 'astroqu... |
#!/usr/bin/env python3
import argparse
import subprocess
def main():
parser = argparse.ArgumentParser()
parser.add_argument('ldd')
parser.add_argument('bin')
args = parser.parse_args()
p, o, _ = subprocess.run([args.ldd, args.bin], stdout=subprocess.PIPE)
assert p == 0
o = o.decode()
... | [
"subprocess.run",
"argparse.ArgumentParser"
] | [((84, 109), 'argparse.ArgumentParser', 'argparse.ArgumentParser', ([], {}), '()\n', (107, 109), False, 'import argparse\n'), ((218, 278), 'subprocess.run', 'subprocess.run', (['[args.ldd, args.bin]'], {'stdout': 'subprocess.PIPE'}), '([args.ldd, args.bin], stdout=subprocess.PIPE)\n', (232, 278), False, 'import subproc... |
__all__ = ['shortest_simple_paths', 'bfs_search', 'find_sources',
'get_path_iter']
import sys
import logging
from collections import deque
from copy import deepcopy
import networkx as nx
import networkx.algorithms.simple_paths as simple_paths
from networkx.classes.reportviews import NodeView, OutEdgeView, \... | [
"copy.deepcopy",
"sys.getsizeof",
"logging.getLogger",
"networkx.NodeNotFound",
"networkx.algorithms.simple_paths.PathBuffer",
"networkx.all_simple_paths",
"collections.deque"
] | [((392, 419), 'logging.getLogger', 'logging.getLogger', (['__name__'], {}), '(__name__)\n', (409, 419), False, 'import logging\n'), ((3586, 3611), 'networkx.algorithms.simple_paths.PathBuffer', 'simple_paths.PathBuffer', ([], {}), '()\n', (3609, 3611), True, 'import networkx.algorithms.simple_paths as simple_paths\n'),... |
import torch
import torch.nn as nn
import torch.optim as optim
from torch.autograd import Variable
from baseline.pytorch.torchy import pytorch_prepare_optimizer
import numpy as np
from baseline.progress import create_progress_bar
from baseline.reporting import basic_reporting
from baseline.utils import listify, get_mod... | [
"baseline.progress.create_progress_bar",
"torch.nn.DataParallel",
"baseline.utils.get_model_file",
"time.time",
"baseline.pytorch.torchy.pytorch_prepare_optimizer",
"numpy.exp",
"baseline.train.create_trainer"
] | [((3556, 3600), 'baseline.utils.get_model_file', 'get_model_file', (['kwargs', '"""seq2seq"""', '"""pytorch"""'], {}), "(kwargs, 'seq2seq', 'pytorch')\n", (3570, 3600), False, 'from baseline.utils import listify, get_model_file\n'), ((4039, 4093), 'baseline.train.create_trainer', 'create_trainer', (['Seq2SeqTrainerPyTo... |
from haalpr import HAAlpr
alpr = HAAlpr()
with open("test.jpg", "rb") as fl_image:
image = fl_image.read()
result = alpr.recognize_byte(image)
print("%s" % result)
| [
"haalpr.HAAlpr"
] | [((34, 42), 'haalpr.HAAlpr', 'HAAlpr', ([], {}), '()\n', (40, 42), False, 'from haalpr import HAAlpr\n')] |
from math import trunc
def Enumero(argumento=""):
veredito = True
for c in range(0, len(argumento)):
if argumento[c] not in "0123456789":
veredito = False
break
return veredito
def Einteiro(numero=float()):
verifica = False
numero = float(numero)
compara = tru... | [
"math.trunc"
] | [((317, 330), 'math.trunc', 'trunc', (['numero'], {}), '(numero)\n', (322, 330), False, 'from math import trunc\n')] |
import torch.nn as nn
import pytorch_lightning as pl
import torch
from pytorch_lightning.metrics.functional import accuracy, auroc
class TextSentiment(pl.LightningModule):
def __init__(self, vocab_size, embed_dim, num_class):
super().__init__()
self.embedding = nn.EmbeddingBag(vocab_size, embed_di... | [
"torch.optim.lr_scheduler.StepLR",
"torch.nn.CrossEntropyLoss",
"torch.nn.EmbeddingBag",
"torch.nn.Linear"
] | [((284, 335), 'torch.nn.EmbeddingBag', 'nn.EmbeddingBag', (['vocab_size', 'embed_dim'], {'sparse': '(True)'}), '(vocab_size, embed_dim, sparse=True)\n', (299, 335), True, 'import torch.nn as nn\n'), ((354, 385), 'torch.nn.Linear', 'nn.Linear', (['embed_dim', 'num_class'], {}), '(embed_dim, num_class)\n', (363, 385), Tr... |
import torch
from torch.utils.data import DataLoader
import pandas as pd
import numpy as np
from horaizon.block import Block
from horaizon.decoder import Decoder
from horaizon.encoder import Encoder
from horaizon.embedder import Embedder
from horaizon.preprocessor import Preprocessor
from horaizon.data_generator import... | [
"horaizon.decoder.Decoder",
"horaizon.embedder.Embedder",
"horaizon.full_model.FullModel",
"torch.utils.data.DataLoader",
"numpy.column_stack",
"torch.cat",
"torch.randn",
"horaizon.data_generator.DataGenerator",
"numpy.random.randint",
"horaizon.block.Block",
"horaizon.loss_and_metric.maximum_l... | [((599, 637), 'torch.randn', 'torch.randn', ([], {'size': '(bs, horizon, x_dim)'}), '(size=(bs, horizon, x_dim))\n', (610, 637), False, 'import torch\n'), ((646, 684), 'torch.randn', 'torch.randn', ([], {'size': '(bs, horizon, c_dim)'}), '(size=(bs, horizon, c_dim))\n', (657, 684), False, 'import torch\n'), ((693, 736)... |
"""
smartdart.py: Provides the class for performing smart darting moves
during an NCMC simulation.
Authors: <NAME>
Contributors: <NAME>
"""
import mdtraj as md
import numpy as np
import simtk.unit as unit
from simtk.openmm import *
from simtk.openmm.app import *
from simtk.unit import *
from blues.ncmc import SimNCM... | [
"numpy.sum",
"numpy.asarray",
"numpy.zeros",
"numpy.cross",
"mdtraj.load",
"numpy.random.random",
"numpy.linalg.inv",
"numpy.array",
"numpy.dot"
] | [((877, 895), 'numpy.linalg.inv', 'np.linalg.inv', (['a.T'], {}), '(a.T)\n', (890, 895), True, 'import numpy as np\n'), ((962, 979), 'numpy.dot', 'np.dot', (['ainv', 'b.T'], {}), '(ainv, b.T)\n', (968, 979), True, 'import numpy as np\n'), ((1522, 1536), 'numpy.dot', 'np.dot', (['a', 'b.T'], {}), '(a, b.T)\n', (1528, 15... |
#!/usr/bin/env python3
import os
import urllib
import urllib.parse
import urllib.request
import sys
import hashlib
import json
#Filetree
def removePrefix(string, prefix):
if string.startswith(prefix):
return string[len(prefix):]
return string
def hashFile(filename):
file = open(filename, "rb")
content = file.r... | [
"json.dump",
"os.remove",
"json.load",
"os.makedirs",
"hashlib.sha1",
"os.path.isdir",
"os.path.dirname",
"os.walk",
"urllib.request.urlopen",
"urllib.parse.quote",
"os.path.isfile",
"os.rmdir",
"os.path.join",
"os.chdir"
] | [((334, 348), 'hashlib.sha1', 'hashlib.sha1', ([], {}), '()\n', (346, 348), False, 'import hashlib\n'), ((483, 500), 'os.walk', 'os.walk', (['treeroot'], {}), '(treeroot)\n', (490, 500), False, 'import os\n'), ((1089, 1104), 'json.load', 'json.load', (['file'], {}), '(file)\n', (1098, 1104), False, 'import json\n'), ((... |
"""
*nix style python functions
"""
from __future__ import with_statement
import contextlib
import errno
import filecmp
try:
import grp
except ImportError:
grp = None
import os
import platform
try:
import pwd as pwdb
except ImportError:
pwdb = None
import shutil
import sys
from ffs import exceptions
... | [
"pwd.getpwnam",
"os.path.join",
"ffs.exceptions.DoesNotExistError",
"os.path.isdir",
"os.access",
"os.path.exists",
"ffs.exceptions.ExistsError",
"ffs.exceptions.BadParentingError",
"ffs.Path",
"ffs.exceptions.NotSupportedError",
"os.link",
"shutil.move",
"platform.system",
"sys.exc_info",... | [((4141, 4163), 'os.path.exists', 'os.path.exists', (['target'], {}), '(target)\n', (4155, 4163), False, 'import os\n'), ((4257, 4280), 'os.path.isdir', 'os.path.isdir', (['resource'], {}), '(resource)\n', (4270, 4280), False, 'import os\n'), ((6120, 6147), 'os.symlink', 'os.symlink', (['*args'], {}), '(*args, **kwargs... |
import random
import tkinter as tk
import tkinter.ttk as ttk
from tkinter import PhotoImage
from tkinter import messagebox
from datetime import datetime
from logic import isSolvable, isSolved
from game_over_screen import GameWon
class Application(tk.Frame):
def __init__(self, master=None):
super().__in... | [
"tkinter.StringVar",
"tkinter.PhotoImage",
"tkinter.Label",
"logic.isSolvable",
"tkinter.Button",
"random.shuffle",
"game_over_screen.GameWon",
"datetime.datetime.now",
"tkinter.Frame",
"logic.isSolved",
"tkinter.LabelFrame",
"tkinter.Tk"
] | [((6694, 6701), 'tkinter.Tk', 'tk.Tk', ([], {}), '()\n', (6699, 6701), True, 'import tkinter as tk\n'), ((6783, 6820), 'tkinter.PhotoImage', 'PhotoImage', ([], {'file': '"""icons/white_bg.png"""'}), "(file='icons/white_bg.png')\n", (6793, 6820), False, 'from tkinter import PhotoImage\n'), ((6839, 6875), 'tkinter.PhotoI... |
# Copyright 2017-present Open Networking Foundation
#
# 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 agr... | [
"unittest.main",
"xosconfig.Config.init",
"mock.patch.object",
"os.path.abspath",
"os.path.realpath",
"os.path.exists",
"mock.MagicMock",
"tempfile.mkdtemp",
"dynamicbuild.DynamicBuilder",
"mock.Mock",
"shutil.rmtree",
"xosconfig.Config.clear",
"os.path.join"
] | [((18291, 18306), 'unittest.main', 'unittest.main', ([], {}), '()\n', (18304, 18306), False, 'import unittest\n'), ((1573, 1587), 'xosconfig.Config.clear', 'Config.clear', ([], {}), '()\n', (1585, 1587), False, 'from xosconfig import Config\n'), ((1644, 1663), 'xosconfig.Config.init', 'Config.init', (['config'], {}), '... |
"""Get data into JVM for prediction and out again as Spark Dataframe"""
import logging
logger = logging.getLogger('nlu')
import pyspark
from pyspark.sql.functions import monotonically_increasing_id
import numpy as np
import pandas as pd
from pyspark.sql.types import StringType, StructType, StructField
class DataConv... | [
"pandas.DataFrame",
"pyspark.sql.types.StringType",
"pyspark.sql.functions.monotonically_increasing_id",
"pandas.notnull",
"pandas.Series",
"logging.getLogger"
] | [((97, 121), 'logging.getLogger', 'logging.getLogger', (['"""nlu"""'], {}), "('nlu')\n", (114, 121), False, 'import logging\n'), ((4826, 4895), 'pandas.DataFrame', 'pd.DataFrame', (["{raw_text_column: data, 'origin_index': [0]}"], {'index': '[0]'}), "({raw_text_column: data, 'origin_index': [0]}, index=[0])\n", (4838, ... |
from fastapi import FastAPI
from .routes.endereco import router as EnderecoRouter
from .routes.pessoa import router as PessoaRouter
app = FastAPI()
# Adiciona rotas
app.include_router(EnderecoRouter, tags=["Endereco"], prefix="/endereco")
app.include_router(PessoaRouter, tags=["Pessoa"], prefix="/pessoa")
@app.get("... | [
"fastapi.FastAPI"
] | [((139, 148), 'fastapi.FastAPI', 'FastAPI', ([], {}), '()\n', (146, 148), False, 'from fastapi import FastAPI\n')] |
from keras.preprocessing.sequence import make_sampling_table , skipgrams , pad_sequences
from keras.preprocessing.text import Tokenizer , one_hot , text_to_word_sequence
from keras.layers import Flatten , Conv1D , MaxPool1D , Dense,Embedding
from keras.models import Sequential
import perpare_dataset
import pandas as pd... | [
"keras.preprocessing.sequence.pad_sequences",
"keras.preprocessing.text.Tokenizer",
"numpy.array",
"keras.preprocessing.sequence.skipgrams"
] | [((467, 478), 'keras.preprocessing.text.Tokenizer', 'Tokenizer', ([], {}), '()\n', (476, 478), False, 'from keras.preprocessing.text import Tokenizer, one_hot, text_to_word_sequence\n'), ((2198, 2261), 'keras.preprocessing.sequence.pad_sequences', 'pad_sequences', (['encoded_data'], {'maxlen': 'max_length', 'padding': ... |
import sys, os
import numpy as np
import nibabel as nib
from scipy import ndimage as ndi
from scipy.signal import convolve
from numpy.linalg import norm
import networkx as nx
import logging
import traceback
import timeit
import time
import math
from ast import literal_eval as make_tuple
from skimage.measur... | [
"skimage.measure.label",
"numpy.savez_compressed",
"numpy.arange",
"pyqtgraph.opengl.GLViewWidget",
"os.path.join",
"pyqtgraph.QtGui.QApplication",
"numpy.full",
"numpy.zeros_like",
"os.path.dirname",
"numpy.savetxt",
"os.path.exists",
"numpy.swapaxes",
"numpy.bincount",
"pyqtgraph.glColor... | [((876, 918), 'os.path.join', 'os.path.join', (['volumeFolderPath', 'volumeName'], {}), '(volumeFolderPath, volumeName)\n', (888, 918), False, 'import sys, os\n'), ((936, 960), 'nibabel.load', 'nib.load', (['volumeFilePath'], {}), '(volumeFilePath)\n', (944, 960), True, 'import nibabel as nib\n'), ((2627, 2678), 'skima... |
import os
from redpanda.ecs.core import Resources
from redpanda.ecs.core import Area
from redpanda.ecs.pygame_plugin import ResourceTypes
def generate_areas_from_world_template(resources: Resources):
template = resources['asset_registry'].world()
for _, area_template in template.areas.items():
yield A... | [
"os.path.join"
] | [((364, 462), 'os.path.join', 'os.path.join', (["resources[ResourceTypes.GAME_DIRECTORIES]['assets.maps']", 'area_template.filename'], {}), "(resources[ResourceTypes.GAME_DIRECTORIES]['assets.maps'],\n area_template.filename)\n", (376, 462), False, 'import os\n')] |
#!/usr/bin/env python
# Plot or dump proton density for HCN+
import h5py
import numpy as np
def grabGR(h5file,myi,myj):
# get gofr list with label "gofr_ion0_myi_myj"
r = []
GR = []
f = h5py.File(h5file)
for name,quantity in f.items():
if name.startswith('gofr'):
g,p,i,j =... | [
"pandas.DataFrame",
"h5py.File",
"matplotlib.pyplot.show",
"argparse.ArgumentParser",
"numpy.array"
] | [((209, 226), 'h5py.File', 'h5py.File', (['h5file'], {}), '(h5file)\n', (218, 226), False, 'import h5py\n'), ((1118, 1184), 'argparse.ArgumentParser', 'argparse.ArgumentParser', ([], {'description': '"""Plot time evolution of g(r)"""'}), "(description='Plot time evolution of g(r)')\n", (1141, 1184), False, 'import argp... |
import json;
from engine import Global;
from engine.Element import Element;
from engine.render.image import Image;
from gameplay.Ground import Ground;
from engine import Render;
from gameplay.Wall import Wall;
from gameplay.Background import Background;
from gameplay.Door import Door;
from gameplay.Teleport import Tele... | [
"engine.Global.setTimeout",
"json.load",
"gameplay.Door.Door",
"gameplay.Background.Background",
"gameplay.Character.Character",
"engine.Render.set",
"gameplay.Dialog.Dialog",
"engine.Render.delete",
"gameplay.behaviours.sceneBehaviour.getTransition",
"gameplay.Pickup.Pickup",
"gameplay.behaviou... | [((1526, 1534), 'gameplay.Ground.Ground', 'Ground', ([], {}), '()\n', (1532, 1534), False, 'from gameplay.Ground import Ground\n'), ((3219, 3262), 'engine.Global.setTimeout', 'Global.setTimeout', (['self.appendToRender', '(500)'], {}), '(self.appendToRender, 500)\n', (3236, 3262), False, 'from engine import Global\n'),... |
# coding=utf-8
import tensorrt as trt
TRT_LOGGER = trt.Logger(trt.Logger.WARNING)
trt_runtime = trt.Runtime(TRT_LOGGER)
def build_engine(onnx_path, shape=[1,3,512,512]):
"""
This is the function to create the TensorRT engine
Args:
onnx_path : Path to onnx_file.
shape : Shape of the input... | [
"tensorrt.Logger",
"tensorrt.OnnxParser",
"tensorrt.Builder",
"tensorrt.Runtime",
"onnx.ModelProto"
] | [((52, 82), 'tensorrt.Logger', 'trt.Logger', (['trt.Logger.WARNING'], {}), '(trt.Logger.WARNING)\n', (62, 82), True, 'import tensorrt as trt\n'), ((97, 120), 'tensorrt.Runtime', 'trt.Runtime', (['TRT_LOGGER'], {}), '(TRT_LOGGER)\n', (108, 120), True, 'import tensorrt as trt\n'), ((1198, 1210), 'onnx.ModelProto', 'Model... |
import config
config.load()
"""
The above line MUST be imported first
Global parameters should not mutate at any time
Export path if necessay
export PYTHONPATH=~/dissertation/code; export LD_LIBRARY_PATH=~/venv/lib
"""
import nltk
import config
from nltk.tree import Tree
from tqdm import tqdm
from numba.core import typ... | [
"nltk.tree.Tree.fromstring",
"parsing.contrained.constrained",
"config.load",
"multiprocessing.set_start_method",
"os.cpu_count",
"parsing.baseline.prune",
"multiprocessing.Pool",
"nltk.pos_tag",
"numba.typed.List"
] | [((14, 27), 'config.load', 'config.load', ([], {}), '()\n', (25, 27), False, 'import config\n'), ((3175, 3246), 'parsing.baseline.prune', 'prune', (['terminals', 'r3_p', 'r1_p', 'pi_p', 'r3_lookupC', 'r1_lookup', 'prune_cutoff'], {}), '(terminals, r3_p, r1_p, pi_p, r3_lookupC, r1_lookup, prune_cutoff)\n', (3180, 3246),... |
#!/usr/bin/env python
from twython import Twython
from twython.exceptions import TwythonError
from credentials import *
from encodings_list import ENCODINGS_LIST
from random import randint
import os
import sys
import random
import logging
TWEET_LENGTH = 140
def login():
# Get credentials from credentialy.py, fall b... | [
"random.randint",
"logging.basicConfig",
"random.choice",
"os.environ.get",
"logging.info",
"os.urandom",
"sys.exit"
] | [((637, 790), 'logging.info', 'logging.info', (['f"""Logged in as \'{info[\'name\']}\' (@{info[\'screen_name\']}). Tweets: {info[\'statuses_count\']}, Followers: {info[\'followers_count\']}"""'], {}), '(\n f"Logged in as \'{info[\'name\']}\' (@{info[\'screen_name\']}). Tweets: {info[\'statuses_count\']}, Followers: ... |
import collections
import numpy as np
import torch
from vel.api import BatchInfo
from vel.api.metrics import BaseMetric, AveragingMetric, ValueMetric
class FramesMetric(ValueMetric):
""" Count the frames """
def __init__(self, name="frames"):
super().__init__(name)
def _value_function(self, bat... | [
"numpy.mean",
"numpy.quantile",
"torch.var",
"collections.deque"
] | [((858, 887), 'collections.deque', 'collections.deque', ([], {'maxlen': '(100)'}), '(maxlen=100)\n', (875, 887), False, 'import collections\n'), ((1526, 1560), 'collections.deque', 'collections.deque', ([], {'maxlen': 'buf_size'}), '(maxlen=buf_size)\n', (1543, 1560), False, 'import collections\n'), ((2217, 2246), 'col... |
import os
import cv2
import numpy as np
from keras.applications.imagenet_utils import preprocess_input
import utils.utils as utils
from net.mobilenet import MobileNet
from net.mtcnn import mtcnn
class face_rec():
def __init__(self):
#-------------------------#
# 创建mtcnn的模型
... | [
"net.mobilenet.MobileNet",
"cv2.putText",
"cv2.cvtColor",
"cv2.waitKey",
"net.mtcnn.mtcnn",
"utils.utils.rect2square",
"numpy.clip",
"cv2.imshow",
"cv2.VideoCapture",
"numpy.shape",
"utils.utils.Alignment_1",
"numpy.array",
"numpy.reshape",
"cv2.rectangle",
"cv2.destroyAllWindows",
"os... | [((3533, 3552), 'cv2.VideoCapture', 'cv2.VideoCapture', (['(0)'], {}), '(0)\n', (3549, 3552), False, 'import cv2\n'), ((3787, 3810), 'cv2.destroyAllWindows', 'cv2.destroyAllWindows', ([], {}), '()\n', (3808, 3810), False, 'import cv2\n'), ((399, 406), 'net.mtcnn.mtcnn', 'mtcnn', ([], {}), '()\n', (404, 406), False, 'fr... |
"""
A single input VAE adapted from the keras documentation found at https://keras.io/examples/variational_autoencoder/
<NAME> 2020
"""
from __future__ import absolute_import
from __future__ import division
from __future__ import print_function
from keras.layers import Dense, Input
from keras.layers import Co... | [
"keras.backend.flatten",
"keras.backend.exp",
"keras.backend.sum",
"keras.layers.Flatten",
"keras.models.Model",
"keras.backend.random_normal",
"keras.layers.Conv2DTranspose",
"keras.backend.square",
"keras.utils.plot_model",
"keras.layers.Dense",
"keras.backend.mean",
"keras.layers.Lambda",
... | [((814, 860), 'keras.layers.Input', 'Input', ([], {'shape': 'input_shape', 'name': '"""encoder_input"""'}), "(shape=input_shape, name='encoder_input')\n", (819, 860), False, 'from keras.layers import Dense, Input\n'), ((1942, 1956), 'keras.backend.int_shape', 'K.int_shape', (['x'], {}), '(x)\n', (1953, 1956), True, 'fr... |
#
import os, sys
import pandas as pd
import numpy as np
import argparse
OUTPUT_DIR = "./"
EV2KT = 38.94
KT2KCAL = 0.593
method_list = ["AVG", "EXP", "nc-EXP", "cu-EXP"]
parser = argparse.ArgumentParser(description="Give something ...")
parser.add_argument("-OUTPUT_DIR", "--OUTPUT_DIR", type=str, required=True,
... | [
"os.listdir",
"pandas.DataFrame",
"argparse.ArgumentParser",
"numpy.log",
"pandas.read_csv",
"numpy.array",
"numpy.exp",
"numpy.var",
"pandas.concat",
"sys.exit"
] | [((181, 238), 'argparse.ArgumentParser', 'argparse.ArgumentParser', ([], {'description': '"""Give something ..."""'}), "(description='Give something ...')\n", (204, 238), False, 'import argparse\n'), ((563, 577), 'numpy.exp', 'np.exp', (['values'], {}), '(values)\n', (569, 577), True, 'import numpy as np\n'), ((780, 79... |
# Discord Packages
from discord.ext import commands
from random import randint
class Broder(commands.Cog):
def __init__(self, bot):
self.bot = bot
@commands.Cog.listener()
async def on_message(self, message):
if not message.author.bot:
await self._filter(message)
@comman... | [
"random.randint",
"discord.ext.commands.Cog.listener"
] | [((168, 191), 'discord.ext.commands.Cog.listener', 'commands.Cog.listener', ([], {}), '()\n', (189, 191), False, 'from discord.ext import commands\n'), ((314, 337), 'discord.ext.commands.Cog.listener', 'commands.Cog.listener', ([], {}), '()\n', (335, 337), False, 'from discord.ext import commands\n'), ((707, 722), 'ran... |
import pygame
# from genericfunctions import *
class SpriteSheet:
def __init__(self, filename, default_scale):
self.sheet = pygame.image.load(filename).convert_alpha()
if default_scale <= 1:
self.default_scale = None
else:
self.default_scale = default_scale
... | [
"pygame.image.load",
"pygame.Surface"
] | [((142, 169), 'pygame.image.load', 'pygame.image.load', (['filename'], {}), '(filename)\n', (159, 169), False, 'import pygame\n'), ((706, 749), 'pygame.Surface', 'pygame.Surface', (['dimensions', 'pygame.SRCALPHA'], {}), '(dimensions, pygame.SRCALPHA)\n', (720, 749), False, 'import pygame\n')] |
import mock
from unittest import TestCase
from dispatcher.device_manager.device_manager import (
get_device_manager, LinuxDeviceManager, WindowsDeviceManager
)
from dispatcher.device_manager.constants import (
SUCCESS_RESTART, SUCCESS_SHUTDOWN, SUCCESS_DECOMMISSION
)
class TestDeviceManager(TestCase):
d... | [
"dispatcher.device_manager.device_manager.WindowsDeviceManager",
"dispatcher.device_manager.device_manager.LinuxDeviceManager",
"dispatcher.device_manager.device_manager.get_device_manager",
"mock.patch"
] | [((442, 500), 'mock.patch', 'mock.patch', (['"""dispatcher.device_manager.device_manager.sys"""'], {}), "('dispatcher.device_manager.device_manager.sys')\n", (452, 500), False, 'import mock\n'), ((717, 775), 'mock.patch', 'mock.patch', (['"""dispatcher.device_manager.device_manager.sys"""'], {}), "('dispatcher.device_m... |
"""Module __main__. Entry point."""
__author__ = '<NAME> (japinol)'
__version__ = '1.0.1'
from argparse import ArgumentParser
import gc
import logging
import traceback
import pygame as pg
from life import constants as consts
from life.life_game import Game
from life.settings import SCREEN_MIN_WIDTH, SC... | [
"pygame.quit",
"life.life_game.Game",
"argparse.ArgumentParser",
"logging.basicConfig",
"traceback.print_tb",
"pygame.init",
"gc.collect",
"tests.test_life.TestLife",
"logging.getLogger"
] | [((505, 553), 'logging.basicConfig', 'logging.basicConfig', ([], {'format': 'consts.LOGGER_FORMAT'}), '(format=consts.LOGGER_FORMAT)\n', (524, 553), False, 'import logging\n'), ((564, 591), 'logging.getLogger', 'logging.getLogger', (['__name__'], {}), '(__name__)\n', (581, 591), False, 'import logging\n'), ((753, 1088)... |
# Generated by Django 2.0 on 2018-02-19 15:30
from django.db import migrations, models
import django.db.models.deletion
import django.utils.timezone
class Migration(migrations.Migration):
initial = True
dependencies = [
]
operations = [
migrations.CreateModel(
name='Article',
... | [
"django.db.models.TextField",
"django.db.models.ForeignKey",
"django.db.models.CharField",
"django.db.models.AutoField",
"django.db.models.IntegerField",
"django.db.models.DateTimeField"
] | [((1602, 1730), 'django.db.models.ForeignKey', 'models.ForeignKey', ([], {'null': '(True)', 'on_delete': 'django.db.models.deletion.SET_NULL', 'related_name': '"""articles"""', 'to': '"""common.ArticleType"""'}), "(null=True, on_delete=django.db.models.deletion.SET_NULL,\n related_name='articles', to='common.Article... |
from matplotlib import pyplot as plt
variance = [1, 2, 4, 8, 16, 32, 64, 128, 256]
bias_squared = [256, 128, 64, 32, 16, 8, 4, 2, 1]
total_error = [x + y for x, y in zip(variance, bias_squared)]
xs = [i for i, _ in enumerate(variance)]
# podemos fazer múltiplas chamadas para plt.plot
# para mostrar múltiplas séries no... | [
"matplotlib.pyplot.title",
"matplotlib.pyplot.show",
"matplotlib.pyplot.plot",
"matplotlib.pyplot.legend",
"matplotlib.pyplot.xlabel"
] | [((335, 381), 'matplotlib.pyplot.plot', 'plt.plot', (['xs', 'variance', '"""g-"""'], {'label': '"""variance"""'}), "(xs, variance, 'g-', label='variance')\n", (343, 381), True, 'from matplotlib import pyplot as plt\n'), ((403, 452), 'matplotlib.pyplot.plot', 'plt.plot', (['xs', 'bias_squared', '"""r-."""'], {'label': '... |
from itertools import chain
from blox.etc.errors import BlockCompositionError
from more_itertools import prepend
from blox.etc.utils import remove_trailing_digits
class BlockTransformsMixin:
""" Adds structural transformations to the Block class """
def __call__(self, *args, **kwargs):
"""
Th... | [
"blox.etc.errors.BlockCompositionError",
"blox.etc.utils.remove_trailing_digits"
] | [((2108, 2142), 'blox.etc.utils.remove_trailing_digits', 'remove_trailing_digits', (['child.name'], {}), '(child.name)\n', (2130, 2142), False, 'from blox.etc.utils import remove_trailing_digits\n'), ((1240, 1302), 'blox.etc.errors.BlockCompositionError', 'BlockCompositionError', (['"""Could not figure out the parent b... |
# Copyright 2019 <NAME>.
#
# 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, s... | [
"datetime.datetime.strptime",
"config.build_weatherunlocked_base_url",
"datetime.datetime.now"
] | [((898, 930), 'config.build_weatherunlocked_base_url', 'build_weatherunlocked_base_url', ([], {}), '()\n', (928, 930), False, 'from config import build_weatherunlocked_base_url\n'), ((1859, 1873), 'datetime.datetime.now', 'datetime.now', ([], {}), '()\n', (1871, 1873), False, 'from datetime import datetime\n'), ((1906,... |
"""
Modified based on: https://github.com/open-mmlab/mmskeleton
"""
import argparse
import pickle
from tqdm import tqdm
import numpy as np
import os
import math
import pandas
from pathlib import Path
training_subjects = [
1, 2, 4, 5, 8, 9, 13, 14, 15, 16, 17, 18, 19, 25, 27, 28, 31, 34, 35, 38
]
training_cameras... | [
"numpy.abs",
"argparse.ArgumentParser",
"numpy.clip",
"pathlib.Path",
"numpy.linalg.norm",
"os.path.join",
"numpy.transpose",
"os.path.exists",
"math.cos",
"tqdm.tqdm",
"numpy.ceil",
"numpy.cross",
"math.sin",
"numpy.dot",
"os.listdir",
"os.makedirs",
"numpy.zeros",
"numpy.array",
... | [((2288, 2344), 'numpy.zeros', 'np.zeros', (["(3, seq_info['numFrame'], num_joint, max_body)"], {}), "((3, seq_info['numFrame'], num_joint, max_body))\n", (2296, 2344), True, 'import numpy as np\n'), ((7668, 7689), 'os.listdir', 'os.listdir', (['data_path'], {}), '(data_path)\n', (7678, 7689), False, 'import os\n'), ((... |
#!/usr/bin/env python3
import sys
import shutil
import os.path
import subprocess
INSTALLATION_PATH = "/opt/sphotik/"
IBUS_COMPONENT_BANK = "/usr/share/ibus/component/"
MANIFEST_FILENAME = "MANIFEST.in"
ENGINE_FILENAME = "ibus_sphotik.py"
IBUS_COMPONENT_FILENAME = "sphotik.xml"
UNINSTALLER_FILENAME = "uninstaller.sh"
... | [
"enchant.Dict",
"sphotik.engine.render_component_template",
"shutil.copyfile",
"sys.exit",
"subprocess.check_call"
] | [((1328, 1339), 'sys.exit', 'sys.exit', (['(1)'], {}), '(1)\n', (1336, 1339), False, 'import sys\n'), ((1838, 1849), 'sys.exit', 'sys.exit', (['(2)'], {}), '(2)\n', (1846, 1849), False, 'import sys\n'), ((3402, 3453), 'subprocess.check_call', 'subprocess.check_call', (['[installed_uninstaller_path]'], {}), '([installed... |
# -*- coding: utf-8 -*-
from __future__ import unicode_literals
from django.db import migrations, models
import django.utils.timezone
from django.conf import settings
class Migration(migrations.Migration):
dependencies = [
('auth', '0006_require_contenttypes_0002'),
('leagues', '0001_initial'),
... | [
"django.db.models.TextField",
"django.db.models.OneToOneField",
"django.db.models.ManyToManyField",
"django.db.models.ForeignKey",
"django.db.models.CharField",
"django.db.models.PositiveIntegerField",
"django.db.models.BooleanField",
"django.db.models.AutoField",
"django.db.models.EmailField",
"d... | [((8066, 8137), 'django.db.models.ForeignKey', 'models.ForeignKey', ([], {'blank': '(True)', 'to': '"""user.PlayerRatingsReport"""', 'null': '(True)'}), "(blank=True, to='user.PlayerRatingsReport', null=True)\n", (8083, 8137), False, 'from django.db import migrations, models\n'), ((8270, 8362), 'django.db.models.Foreig... |
#!/usr/bin/env python
"""
Inherits the stuff from tests.csvk – i.e. csvkit.tests.utils
"""
from tests.csvk import *
from tests.csvk import CSVKitTestCase as BaseCsvkitTestCase
import unittest
from unittest.mock import patch
from unittest import skip as skiptest
from unittest import TestCase
import warnings
from io ... | [
"subprocess.check_output",
"subprocess.Popen",
"warnings.filterwarnings"
] | [((631, 693), 'warnings.filterwarnings', 'warnings.filterwarnings', (['"""ignore"""'], {'category': 'DeprecationWarning'}), "('ignore', category=DeprecationWarning)\n", (654, 693), False, 'import warnings\n'), ((799, 855), 'subprocess.check_output', 'sub_check_output', (['command'], {'shell': '(True)', 'stderr': 'sys.s... |
"""
This module implements the RingBuffer class
"""
from typing import Union
import numpy as np # type: ignore
class RingBuffer:
""" ring buffer """
def __init__(self, shape: list, dtype=np.float32) -> None:
self._dtype = dtype
self._shape = shape
self._shape[0] += 1
self._b... | [
"numpy.empty",
"numpy.concatenate"
] | [((328, 374), 'numpy.empty', 'np.empty', ([], {'shape': 'self._shape', 'dtype': 'self._dtype'}), '(shape=self._shape, dtype=self._dtype)\n', (336, 374), True, 'import numpy as np\n'), ((3129, 3152), 'numpy.concatenate', 'np.concatenate', (['current'], {}), '(current)\n', (3143, 3152), True, 'import numpy as np\n')] |
__authors__ = '<NAME>'
import random
import Player
import Message
class PBATPlayer(Player.Player):
# self variables
player_list = []
rock_cut = .3
paper_cut = .6
total = 10
name = None
# finds a player and his information
def find_player(self, person):
found_player = False
... | [
"Message.Message.get_round_end_message",
"random.random",
"Message.Message.get_match_start_message",
"Message.Message.get_round_start_message"
] | [((2382, 2397), 'random.random', 'random.random', ([], {}), '()\n', (2395, 2397), False, 'import random\n'), ((2816, 2831), 'random.random', 'random.random', ([], {}), '()\n', (2829, 2831), False, 'import random\n'), ((3167, 3215), 'Message.Message.get_match_start_message', 'Message.Message.get_match_start_message', ([... |
"""Config for springs system.
This is a system of random shapes that collide and bounce of the walls.
To demo this task, navigate to the main directory and run the following:
'''
$ python demo.py --config=spriteworld_physics.configs.collisions \
--hsv_colors=True
'''
"""
# pylint: disable=import-error
from __fu... | [
"spriteworld.factor_distributions.Continuous",
"os.path.basename",
"spriteworld.factor_distributions.Discrete",
"spriteworld.renderers.PILRenderer",
"spriteworld_physics.graph_generators.LowerTriangular",
"spriteworld_physics.forces.SymmetricShellCollision",
"numpy.random.randint"
] | [((1878, 1927), 'spriteworld_physics.forces.SymmetricShellCollision', 'forces.SymmetricShellCollision', ([], {'shell_radius': '(0.08)'}), '(shell_radius=0.08)\n', (1908, 1927), False, 'from spriteworld_physics import forces\n'), ((1950, 1995), 'spriteworld_physics.graph_generators.LowerTriangular', 'graph_generators.Lo... |
import numpy
from numpy import array, zeros
from interpolation.smolyak import SmolyakGrid as SmolyakGrid0
from interpolation.smolyak import SmolyakInterp, build_B
from dolo.numeric.grids import cat_grids, n_nodes, node
from dolo.numeric.grids import UnstructuredGrid, CartesianGrid, SmolyakGrid, EmptyGrid
from dolo.nume... | [
"interpolation.smolyak.SmolyakGrid",
"interpolation.splines.eval_cubic.vec_eval_cubic_splines",
"dolo.numeric.grids.cat_grids",
"interpolation.smolyak.build_B",
"scipy.linalg.lu_factor",
"scipy.linalg.lu_solve",
"numpy.zeros",
"numpy.array",
"interpolation.splines.filter_cubic.filter_mcoeffs",
"nu... | [((1302, 1314), 'numpy.array', 'array', (['ndims'], {}), '(ndims)\n', (1307, 1314), False, 'from numpy import array, zeros\n'), ((1442, 1489), 'interpolation.splines.filter_cubic.filter_mcoeffs', 'filter_mcoeffs', (['a', 'b', 'ndims', 'controls[i_m, ...]'], {}), '(a, b, ndims, controls[i_m, ...])\n', (1456, 1489), Fals... |
import os
import pip
import tempfile
import subprocess
BUCKET_NAME = 'deepchem.io'
if not any(d.project_name == 's3cmd'
for d in pip.get_installed_distributions()):
raise ImportError('The s3cmd package is required. try $ pip install s3cmd')
# The secret key is available as a secure environment variable
... | [
"tempfile.NamedTemporaryFile",
"pip.get_installed_distributions"
] | [((386, 418), 'tempfile.NamedTemporaryFile', 'tempfile.NamedTemporaryFile', (['"""w"""'], {}), "('w')\n", (413, 418), False, 'import tempfile\n'), ((142, 175), 'pip.get_installed_distributions', 'pip.get_installed_distributions', ([], {}), '()\n', (173, 175), False, 'import pip\n')] |
# Copyright 2020 The Kale Authors
#
# 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 ... | [
"kale.rpc.nb.get_pipeline_parameters",
"nbformat.v4.new_notebook",
"pytest.fixture",
"nbformat.write",
"kale.rpc.nb.get_pipeline_metrics",
"nbformat.v4.new_code_cell",
"os.path.join"
] | [((660, 690), 'pytest.fixture', 'pytest.fixture', ([], {'scope': '"""module"""'}), "(scope='module')\n", (674, 690), False, 'import pytest\n'), ((883, 909), 'nbformat.v4.new_notebook', 'nbformat.v4.new_notebook', ([], {}), '()\n', (907, 909), False, 'import nbformat\n'), ((1189, 1224), 'os.path.join', 'os.path.join', (... |
'''Example low-level socket usage'''
import time
import sys
import libzt
def print_usage():
'''print help'''
print(
"\nUsage: <server|client> <id_path> <nwid> <zt_service_port> <remote_ip> <remote_port>\n"
)
print("Ex: python3 demo.py server . 0123456789abcdef 9994 8080")
print("Ex: pytho... | [
"libzt.socket",
"libzt.start",
"libzt.errno",
"time.sleep",
"libzt.join",
"sys.exit"
] | [((511, 522), 'sys.exit', 'sys.exit', (['(0)'], {}), '(0)\n', (519, 522), False, 'import sys\n'), ((3132, 3191), 'libzt.start', 'libzt.start', (['key_file_path', 'event_callback', 'zt_service_port'], {}), '(key_file_path, event_callback, zt_service_port)\n', (3143, 3191), False, 'import libzt\n'), ((3338, 3360), 'libzt... |
# -*- coding: utf-8 -*-
# %%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%
#
# Copyright (c) 2019 Image Processing Research Group of University Federico II of Naples ('GRIP-UNINA').
# All rights reserved.
# This work should only be used for nonprofit purposes.
#
# By downloading and/or u... | [
"numpy.pad",
"numpy.subtract",
"numpy.isscalar",
"numpy.zeros",
"numpy.ones",
"numpy.squeeze",
"skimage.util.view_as_windows"
] | [((858, 877), 'numpy.isscalar', 'np.isscalar', (['pShape'], {}), '(pShape)\n', (869, 877), True, 'import numpy as np\n'), ((987, 1007), 'numpy.isscalar', 'np.isscalar', (['pStride'], {}), '(pStride)\n', (998, 1007), True, 'import numpy as np\n'), ((3066, 3086), 'numpy.isscalar', 'np.isscalar', (['pStride'], {}), '(pStr... |
def run_script():
import os
from org.apache.pig.scripting import Pig
# compile the pig code
P = Pig.compileFromFile("../pigscripts/#{script_name}.pig")
bound = P.bind()
bound.runSingle()
if __name__ == '__main__':
run_script()
| [
"org.apache.pig.scripting.Pig.compileFromFile"
] | [((113, 168), 'org.apache.pig.scripting.Pig.compileFromFile', 'Pig.compileFromFile', (['"""../pigscripts/#{script_name}.pig"""'], {}), "('../pigscripts/#{script_name}.pig')\n", (132, 168), False, 'from org.apache.pig.scripting import Pig\n')] |
#!/usr/bin/env python
from flask import Blueprint, render_template
from render_utils import make_context
games = Blueprint('games', __name__)
@games.route('/game.html')
def game():
"""
Render the game itself.
"""
# Set up standard page context.
context = make_context()
return render_templat... | [
"render_utils.make_context",
"flask.Blueprint",
"flask.render_template"
] | [((116, 144), 'flask.Blueprint', 'Blueprint', (['"""games"""', '__name__'], {}), "('games', __name__)\n", (125, 144), False, 'from flask import Blueprint, render_template\n'), ((279, 293), 'render_utils.make_context', 'make_context', ([], {}), '()\n', (291, 293), False, 'from render_utils import make_context\n'), ((306... |
import data_handling.helper_functions as f
import data_handling.nearest_neighbor_crunching as nn
import data_handling.data_frame_functions as dff
class ModelNNItem():
"""
Model class for the item metadata nearest neighbor model.
Methods
fit(df): Fit the model on training data
predict(df):... | [
"data_handling.nearest_neighbor_crunching.predict_nn",
"data_handling.helper_functions.print_time",
"data_handling.data_frame_functions.explode",
"data_handling.nearest_neighbor_crunching.calc_item_sims"
] | [((508, 542), 'data_handling.helper_functions.print_time', 'f.print_time', (['"""explode properties"""'], {}), "('explode properties')\n", (520, 542), True, 'import data_handling.helper_functions as f\n'), ((567, 596), 'data_handling.data_frame_functions.explode', 'dff.explode', (['df', '"""properties"""'], {}), "(df, ... |
import asyncio
from logging import exception, warning
from .httpclient import HttpClient
from typing import List # , Tuple
from aiohttp.client import ClientSession
# import json
from .const import (
CHECK_DOOR_STATE_INTERVAL,
DEFAULT_DOOR_STATE_CHANGE_TIMEOUT,
LOGGER,
RE_WEBTOKEN,
RE_DOORS,
S... | [
"logging.exception",
"asyncio.sleep"
] | [((3787, 3855), 'logging.exception', 'exception', (['"""Failed getting door status. Reason: %s"""', 'response.reason'], {}), "('Failed getting door status. Reason: %s', response.reason)\n", (3796, 3855), False, 'from logging import exception, warning\n'), ((5355, 5395), 'asyncio.sleep', 'asyncio.sleep', (['CHECK_DOOR_S... |
import os
from Cython.Build import cythonize
from Cython.Compiler.Options import get_directive_defaults
from setuptools import Extension, setup
# https://stackoverflow.com/a/28301932/463500
if "IS_TOX_BUILD" in os.environ:
directive_defaults = get_directive_defaults()
directive_defaults["linetrace"] = True
... | [
"setuptools.Extension",
"Cython.Build.cythonize",
"Cython.Compiler.Options.get_directive_defaults"
] | [((250, 274), 'Cython.Compiler.Options.get_directive_defaults', 'get_directive_defaults', ([], {}), '()\n', (272, 274), False, 'from Cython.Compiler.Options import get_directive_defaults\n'), ((454, 524), 'setuptools.Extension', 'Extension', (['"""acurl_ng"""', "['src/acurl.pyx']"], {'libraries': "['curl']"}), "('acurl... |
from src.GOL import GOL
from src.Axiom_Parser import Axiom_Parser
from src.Engine import Engine
# GOL = GOL(15, 15)
# AXIOMS = Axiom_Parser()
# with open('axioms.txt', 'r') as file_handle:
# AXIOMS.parse(file_handle.read())
# from src.Cells.Gol_Cell import Gol_Cell
# GOL.set_sequence([
# [None, Gol_Cell(), N... | [
"src.Engine.Engine"
] | [((516, 524), 'src.Engine.Engine', 'Engine', ([], {}), '()\n', (522, 524), False, 'from src.Engine import Engine\n')] |
# -*- coding: utf-8 -*-
"""
ktcal2: This file contains function for SSH brute forcer.
"""
import asyncio
import asyncssh
import itertools
from .data import FoundCredential
__license__ = '''Copyright (c) cr0hn - cr0hn<-at->cr<EMAIL> (@ggdaniel) All rights reserved.
Redistribution and use in source and binary forms... | [
"asyncio.get_event_loop",
"asyncio.sleep",
"asyncssh.create_connection",
"itertools.islice",
"asyncio.wait"
] | [((4395, 4419), 'asyncio.get_event_loop', 'asyncio.get_event_loop', ([], {}), '()\n', (4417, 4419), False, 'import asyncio\n'), ((3096, 3213), 'asyncssh.create_connection', 'asyncssh.create_connection', (['None'], {'host': 'target', 'port': 'port', 'username': 'user', 'password': 'password', 'server_host_keys': 'None'}... |
from __future__ import print_function
import os
import argparse
import time
import numpy as np
import pathlib
import torch
import torch.optim as optim
import torch.nn as nn
import torch.utils.data
import torchvision.datasets as dset
import torchvision.transforms as transforms
import torchvision.utils as vutils
from dnn... | [
"argparse.ArgumentParser",
"dnnlib.EasyDict",
"numpy.floor",
"torch.randn",
"pathlib.Path",
"torchvision.transforms.Normalize",
"torch.no_grad",
"os.path.join",
"mlflow.start_run",
"mlflow.log_param",
"torch.utils.data.DataLoader",
"torch.load",
"loss_criterions.base_loss_criterions.Logistic... | [((607, 672), 'argparse.ArgumentParser', 'argparse.ArgumentParser', ([], {'description': '"""Pytorch style-gan training"""'}), "(description='Pytorch style-gan training')\n", (630, 672), False, 'import argparse\n'), ((3051, 3061), 'dnnlib.EasyDict', 'EasyDict', ([], {}), '()\n', (3059, 3061), False, 'from dnnlib import... |
import os
import pathlib
from typing import Sequence, Union
import dataframe_image as dfi
import pandas as pd
import structlog
from sklearn.metrics import classification_report
logger = structlog.get_logger()
def classification_report_mlflow(
y_true: Sequence,
y_pred: Sequence,
path: Union[str, pathlib.... | [
"pandas.DataFrame",
"os.getcwd",
"sklearn.metrics.classification_report",
"dataframe_image.export",
"structlog.get_logger"
] | [((188, 210), 'structlog.get_logger', 'structlog.get_logger', ([], {}), '()\n', (208, 210), False, 'import structlog\n'), ((890, 945), 'sklearn.metrics.classification_report', 'classification_report', (['y_true', 'y_pred'], {'output_dict': '(True)'}), '(y_true, y_pred, output_dict=True)\n', (911, 945), False, 'from skl... |
"""
This is a setup.py script generated by py2applet
Usage:
python setup.py py2app
"""
from setuptools import setup, find_packages
from shutil import copyfile
import os
import sys
# 再帰回数に引っかかるのでとりあえず大きい数に.
sys.setrecursionlimit(10 ** 9)
VERSION = '0.1.0'
VERSION_PYTHON = '{0}.{1}'.format(sys.version_info.major... | [
"os.path.exists",
"shutil.copyfile",
"sys.setrecursionlimit",
"os.path.join",
"os.listdir"
] | [((213, 243), 'sys.setrecursionlimit', 'sys.setrecursionlimit', (['(10 ** 9)'], {}), '(10 ** 9)\n', (234, 243), False, 'import sys\n'), ((797, 844), 'os.path.join', 'os.path.join', (["os.environ['CONDA_PREFIX']", '"""lib"""'], {}), "(os.environ['CONDA_PREFIX'], 'lib')\n", (809, 844), False, 'import os\n'), ((1054, 1093... |
from collections import Counter
L = list(map(list, map(lambda x: x.strip(), open('input/3.txt').readlines())))
def A():
a = b = ""
for i in range(len(L[0])):
c = Counter([R[i] for R in L])
a += c.most_common()[0][0]
b += c.most_common()[-1][0]
return int(a, 2) * int(b, 2)
def B():
X = L
for i i... | [
"collections.Counter"
] | [((172, 198), 'collections.Counter', 'Counter', (['[R[i] for R in L]'], {}), '([R[i] for R in L])\n', (179, 198), False, 'from collections import Counter\n'), ((348, 374), 'collections.Counter', 'Counter', (['[R[i] for R in X]'], {}), '([R[i] for R in X])\n', (355, 374), False, 'from collections import Counter\n'), ((5... |
from insights.parsers.ls_dev import LsDev
from insights.tests import context_wrap
LS_DEV = """
/dev:
total 3
brw-rw----. 1 0 6 253, 0 Aug 4 16:56 dm-0
brw-rw----. 1 0 6 253, 1 Aug 4 16:56 dm-1
brw-rw----. 1 0 6 253, 10 Aug 4 16:56 dm-10
crw-rw-rw-. 1 0 5 5, 2 Aug 5 2016 ptmx
drwxr-xr-x. 2 0 0 ... | [
"insights.tests.context_wrap"
] | [((1141, 1161), 'insights.tests.context_wrap', 'context_wrap', (['LS_DEV'], {}), '(LS_DEV)\n', (1153, 1161), False, 'from insights.tests import context_wrap\n')] |
"""
Functionalities to process a lightcurve file for KN-Classify
"""
import argparse
import os
import sys
sys.path.append('knc')
import numpy as np
import pandas as pd
import feature_extraction
from utils import ArgumentError, load, save
def trim_lcs(lcs : dict, cut_requirement : int = 0) -> dict :
"""
Remo... | [
"sys.path.append",
"os.mkdir",
"utils.ArgumentError",
"pandas.DataFrame",
"argparse.ArgumentParser",
"os.getcwd",
"os.path.exists",
"utils.load",
"feature_extraction.extract_all",
"utils.save"
] | [((106, 128), 'sys.path.append', 'sys.path.append', (['"""knc"""'], {}), "('knc')\n", (121, 128), False, 'import sys\n'), ((3584, 3598), 'utils.load', 'load', (['lcs_file'], {}), '(lcs_file)\n', (3588, 3598), False, 'from utils import ArgumentError, load, save\n'), ((3637, 3689), 'feature_extraction.extract_all', 'feat... |
import glob
import os
import pytest
from pele_platform.constants import constants as cs
from pele_platform.Utilities.Helpers import helpers
from pele_platform import main
from .test_adaptive import check_file
test_path = os.path.join(cs.DIR, "Examples")
LOCAL_ADAPTIVE = [
'"type" : "inverselyProportional",',
... | [
"pele_platform.Utilities.Helpers.helpers.check_remove_folder",
"pele_platform.main.run_platform_from_yaml",
"os.path.dirname",
"os.path.exists",
"pytest.mark.parametrize",
"pytest.mark.skip",
"os.path.join"
] | [((223, 255), 'os.path.join', 'os.path.join', (['cs.DIR', '"""Examples"""'], {}), "(cs.DIR, 'Examples')\n", (235, 255), False, 'import os\n'), ((1265, 1372), 'pytest.mark.parametrize', 'pytest.mark.parametrize', (['"""yaml"""', "['site_finder/input_global.yaml', 'site_finder/input_global_xtc.yaml']"], {}), "('yaml', ['... |
from __future__ import division
import scitbx.rigid_body
import scitbx.graph.tardy_tree
import scitbx.math
from scitbx.array_family import flex
from libtbx.str_utils import show_string
from libtbx.utils import sequence_index_dict
from libtbx.utils import Sorry
import math
rotamer_info_master_phil_str = """\
tor_ids = ... | [
"math.radians",
"libtbx.str_utils.show_string",
"libtbx.utils.sequence_index_dict",
"scitbx.array_family.flex.double"
] | [((2062, 2105), 'libtbx.utils.sequence_index_dict', 'sequence_index_dict', ([], {'seq': 'mon_lib_atom_names'}), '(seq=mon_lib_atom_names)\n', (2081, 2105), False, 'from libtbx.utils import sequence_index_dict\n'), ((7479, 7522), 'libtbx.utils.sequence_index_dict', 'sequence_index_dict', ([], {'seq': 'mon_lib_atom_names... |
import datetime
import numpy as np
import pandas as pd
import pandas.testing as pdt
import pytest
from plateau.io.eager import (
read_dataset_as_dataframes,
read_table,
store_dataframes_as_dataset,
)
from plateau.io.testing.read import * # noqa
@pytest.fixture(
params=["dataframe", "table"],
id... | [
"pandas.DataFrame",
"pandas.testing.assert_frame_equal",
"plateau.io.eager.read_dataset_as_dataframes",
"pytest.fixture",
"datetime.date",
"plateau.io.eager.read_table",
"pytest.mark.parametrize",
"plateau.io.eager.store_dataframes_as_dataset"
] | [((263, 336), 'pytest.fixture', 'pytest.fixture', ([], {'params': "['dataframe', 'table']", 'ids': "['dataframe', 'table']"}), "(params=['dataframe', 'table'], ids=['dataframe', 'table'])\n", (277, 336), False, 'import pytest\n'), ((1087, 1103), 'pytest.fixture', 'pytest.fixture', ([], {}), '()\n', (1101, 1103), False,... |
#!/usr/bin/env pgzrun
from brick import Brick
from paddle import Paddle
from settings import WIDTH, HEIGHT, TITLE, ICON
from ball import Ball
# actors = []
ball = Ball()
paddle = Paddle()
# creating bricks
bricks = []
for i in range(10):
brick = Brick()
brick.left = brick.width * i
bricks.append(brick)
... | [
"brick.Brick",
"paddle.Paddle",
"ball.Ball"
] | [((165, 171), 'ball.Ball', 'Ball', ([], {}), '()\n', (169, 171), False, 'from ball import Ball\n'), ((181, 189), 'paddle.Paddle', 'Paddle', ([], {}), '()\n', (187, 189), False, 'from paddle import Paddle\n'), ((254, 261), 'brick.Brick', 'Brick', ([], {}), '()\n', (259, 261), False, 'from brick import Brick\n')] |
import requests
from bs4 import BeautifulSoup
# assign the target url
URL = "https://www.empireonline.com/movies/features/best-movies-2/"
# requesting the url
response = requests.get(URL)
# get the raw html
website_html = response.text
# crawling the html
soup = BeautifulSoup(website_html, "html.parser")
# printin... | [
"bs4.BeautifulSoup",
"requests.get"
] | [((172, 189), 'requests.get', 'requests.get', (['URL'], {}), '(URL)\n', (184, 189), False, 'import requests\n'), ((267, 309), 'bs4.BeautifulSoup', 'BeautifulSoup', (['website_html', '"""html.parser"""'], {}), "(website_html, 'html.parser')\n", (280, 309), False, 'from bs4 import BeautifulSoup\n')] |
import yaml
def max_or_int(some_str_value):
if some_str_value == 'max':
return 'max'
else:
return int(some_str_value)
DEFAULTS = {
'cache_time': (float, 10.0),
'service_name_header': (str, None),
'log_path': (str, 'stderr'),
'mysql_username': (str, None),
'mysql_password'... | [
"yaml.safe_load"
] | [((526, 543), 'yaml.safe_load', 'yaml.safe_load', (['f'], {}), '(f)\n', (540, 543), False, 'import yaml\n')] |
import os
import numpy as np
import pandas as pd
import sys
import argparse
import logging
import matplotlib.pyplot as plt
import yaml
from astropy.cosmology import FlatLambdaCDM
from scipy.stats import binned_statistic, moment
def setup_logging():
fmt = "[%(levelname)8s |%(funcName)21s:%(lineno)3d] %(message)... | [
"numpy.isin",
"argparse.ArgumentParser",
"pandas.read_csv",
"numpy.ones",
"numpy.histogram",
"yaml.safe_load",
"scipy.stats.moment",
"numpy.unique",
"logging.FileHandler",
"logging.warning",
"numpy.std",
"numpy.isfinite",
"numpy.linspace",
"matplotlib.pyplot.subplots",
"numpy.var",
"nu... | [((337, 370), 'logging.StreamHandler', 'logging.StreamHandler', (['sys.stdout'], {}), '(sys.stdout)\n', (358, 370), False, 'import logging\n'), ((686, 711), 'argparse.ArgumentParser', 'argparse.ArgumentParser', ([], {}), '()\n', (709, 711), False, 'import argparse\n'), ((1002, 1055), 'logging.info', 'logging.info', (['... |
import numpy as np
def get_point_quantile_expected_dist_by_time_fcns(quantile=0.2, select_inds=np.arange(9, 60, 10)):
# Base on ordering of overall *point* distance rather than
# *trajectory* distance at each selected time
# (point allows for switching best sample index at each timestep).
# q: quantil... | [
"numpy.einsum",
"numpy.expand_dims",
"numpy.argsort",
"numpy.arange",
"numpy.array",
"numpy.take_along_axis",
"numpy.concatenate"
] | [((97, 117), 'numpy.arange', 'np.arange', (['(9)', '(60)', '(10)'], {}), '(9, 60, 10)\n', (106, 117), True, 'import numpy as np\n'), ((1932, 1952), 'numpy.arange', 'np.arange', (['(9)', '(60)', '(10)'], {}), '(9, 60, 10)\n', (1941, 1952), True, 'import numpy as np\n'), ((2929, 2949), 'numpy.arange', 'np.arange', (['(9)... |
import sys
import logging
log_name = dict()
def setup_logger(name, log_level="INFO"):
if name in log_name:
return log_name[name]
formatter = logging.Formatter(
datefmt='%Y/%m/%d %H:%M:%S', fmt='%(asctime)s - %(levelname)s : %(message)s')
handler = logging.StreamHandler(stream=sys.stderr)... | [
"logging.Formatter",
"logging.StreamHandler",
"logging.getLogger"
] | [((160, 260), 'logging.Formatter', 'logging.Formatter', ([], {'datefmt': '"""%Y/%m/%d %H:%M:%S"""', 'fmt': '"""%(asctime)s - %(levelname)s : %(message)s"""'}), "(datefmt='%Y/%m/%d %H:%M:%S', fmt=\n '%(asctime)s - %(levelname)s : %(message)s')\n", (177, 260), False, 'import logging\n'), ((280, 320), 'logging.StreamHa... |
from math import *
import numpy as np
import tqdm
from get_csection import cross_section
import matplotlib.pyplot as plt
def get_Halo_cs_relation(M200_min=1e13,M200_max=1e15):
Mstar = 10**11.5
Re = 3
z1 = .3
z2 = 1.5
Halo_mass = np.logspace(np.log10(M200_min),np.log10(M200_max),200)
cs_area = ... | [
"matplotlib.pyplot.loglog",
"matplotlib.pyplot.figure",
"numpy.linspace",
"get_csection.cross_section",
"matplotlib.pyplot.ylabel",
"numpy.log10",
"matplotlib.pyplot.xlabel",
"matplotlib.pyplot.savefig"
] | [((559, 585), 'matplotlib.pyplot.figure', 'plt.figure', ([], {'figsize': '(7, 5)'}), '(figsize=(7, 5))\n', (569, 585), True, 'import matplotlib.pyplot as plt\n'), ((589, 619), 'matplotlib.pyplot.loglog', 'plt.loglog', (['Halo_mass', 'cs_area'], {}), '(Halo_mass, cs_area)\n', (599, 619), True, 'import matplotlib.pyplot ... |
# -*- coding: utf-8 -*-
"""
Created on Fri Jun 14 16:59:13 2019
@author: holys
"""
from sklearn import preprocessing
enc = preprocessing.OneHotEncoder() # 创建对象
enc.fit([[0,0,3],[1,1,0],[0,2,1],[1,0,2]]) # 拟合
array = enc.transform([[0,1,3]]).toarray() # 转化
print(array) | [
"sklearn.preprocessing.OneHotEncoder"
] | [((143, 172), 'sklearn.preprocessing.OneHotEncoder', 'preprocessing.OneHotEncoder', ([], {}), '()\n', (170, 172), False, 'from sklearn import preprocessing\n')] |
#!/usr/bin/env python
# Copyright (c) PLUMgrid, Inc.
# Licensed under the Apache License, Version 2.0 (the "License")
from bcc import BPF
from unittest import main, TestCase
class TestClang(TestCase):
def test_complex(self):
b = BPF(src_file="test_clang_complex.c", debug=0)
fn = b.load_func("handl... | [
"unittest.main",
"bcc.BPF"
] | [((7068, 7074), 'unittest.main', 'main', ([], {}), '()\n', (7072, 7074), False, 'from unittest import main, TestCase\n'), ((243, 288), 'bcc.BPF', 'BPF', ([], {'src_file': '"""test_clang_complex.c"""', 'debug': '(0)'}), "(src_file='test_clang_complex.c', debug=0)\n", (246, 288), False, 'from bcc import BPF\n'), ((687, 7... |
'''
Keeping the order of rows during transformations.
@author rambabu.posa
'''
from pyspark.sql import (SparkSession, functions as F)
from pyspark.sql.types import (StructType, StructField,
StringType, IntegerType, DoubleType)
def createDataframe(spark):
schema = StructType([
... | [
"pyspark.sql.types.DoubleType",
"pyspark.sql.types.StringType",
"pyspark.sql.functions.monotonically_increasing_id",
"pyspark.sql.types.IntegerType",
"pyspark.sql.SparkSession.builder.appName"
] | [((787, 818), 'pyspark.sql.functions.monotonically_increasing_id', 'F.monotonically_increasing_id', ([], {}), '()\n', (816, 818), True, 'from pyspark.sql import SparkSession, functions as F\n'), ((344, 357), 'pyspark.sql.types.IntegerType', 'IntegerType', ([], {}), '()\n', (355, 357), False, 'from pyspark.sql.types imp... |
import pytest
import numpy as np
from opaque.stats import inverse_prevalence_cdf, prevalence_cdf
@pytest.mark.parametrize(
"test_input",
[
(n, t, sens_a, sens_b, spec_a, spec_b)
for n in [100, 1000]
for t in [n // 3, 2 * n // 3]
for sens_a, sens_b in [(60, 40), (80, 20)]
... | [
"numpy.abs",
"opaque.stats.inverse_prevalence_cdf",
"numpy.linspace",
"pytest.mark.parametrize",
"opaque.stats.prevalence_cdf"
] | [((101, 325), 'pytest.mark.parametrize', 'pytest.mark.parametrize', (['"""test_input"""', '[(n, t, sens_a, sens_b, spec_a, spec_b) for n in [100, 1000] for t in [n //\n 3, 2 * n // 3] for sens_a, sens_b in [(60, 40), (80, 20)] for spec_a,\n spec_b in [(60, 40), (80, 20)]]'], {}), "('test_input', [(n, t, sens_a, s... |
#!/usr/bin/env python
# encoding: utf-8
"""
test_genotype_pytest.py
Attributes of genotypes to be tested:
- genotype STRING
- allele_1 STRING
- allele_2 STRING
- genotyped BOOL
- has_variant BOOL
- heterozygote BOOL
- homo_alt BOOL
- homo_ref BOOL
- has_variant BOOL
- filter ST... | [
"genmod.vcf_tools.Genotype"
] | [((855, 880), 'genmod.vcf_tools.Genotype', 'Genotype', ([], {}), "(**{'GT': './.'})\n", (863, 880), False, 'from genmod.vcf_tools import Genotype\n'), ((1297, 1320), 'genmod.vcf_tools.Genotype', 'Genotype', ([], {}), "(**{'GT': '1'})\n", (1305, 1320), False, 'from genmod.vcf_tools import Genotype\n'), ((1665, 1690), 'g... |
# Copyright 2018 ZTE Corporation.
#
# 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 ... | [
"rest_framework.serializers.CharField",
"rest_framework.serializers.ChoiceField"
] | [((1165, 1375), 'rest_framework.serializers.CharField', 'serializers.CharField', ([], {'help_text': '"""Identifier of the onboarded individual PNF descriptor resource. This identifier is allocated by the NFVO."""', 'required': '(True)', 'allow_null': '(False)', 'allow_blank': '(False)'}), "(help_text=\n 'Ide... |
import os
import numpy as np
import xarray as xr
from dask.distributed import Client
import matplotlib.pyplot as plt
from matplotlib.pyplot import cm
from matplotlib.pyplot import Figure, Axes
from typing import Union
from HSTB.kluster.fqpr_helpers import return_directory_from_data
from HSTB.kluster.fqpr_convenience i... | [
"numpy.ravel",
"numpy.ones",
"numpy.isnan",
"matplotlib.pyplot.figure",
"numpy.mean",
"matplotlib.pyplot.gca",
"numpy.round",
"os.path.join",
"numpy.unique",
"HSTB.kluster.fqpr_convenience.return_surface",
"matplotlib.pyplot.close",
"numpy.append",
"numpy.max",
"matplotlib.pyplot.subplots"... | [((20634, 20661), 'numpy.isnan', 'np.isnan', (['grid_depth_at_loc'], {}), '(grid_depth_at_loc)\n', (20642, 20661), True, 'import numpy as np\n'), ((20915, 20961), 'numpy.rad2deg', 'np.rad2deg', (['ang[sounding_idx][~empty_grid_idx]'], {}), '(ang[sounding_idx][~empty_grid_idx])\n', (20925, 20961), True, 'import numpy as... |
from flask import Flask, render_template, request
from selenium import webdriver
from selenium.webdriver import FirefoxOptions
from selenium.webdriver.common.keys import Keys
import time
app = Flask(__name__)
@app.route("/")
def form():
return render_template("form.html")
@app.route("/", methods=["POST"])
def my... | [
"selenium.webdriver.Firefox",
"flask.Flask",
"time.sleep",
"flask.render_template",
"selenium.webdriver.FirefoxOptions"
] | [((194, 209), 'flask.Flask', 'Flask', (['__name__'], {}), '(__name__)\n', (199, 209), False, 'from flask import Flask, render_template, request\n'), ((250, 278), 'flask.render_template', 'render_template', (['"""form.html"""'], {}), "('form.html')\n", (265, 278), False, 'from flask import Flask, render_template, reques... |
import os
import sys
sys.path.append(os.path.dirname(os.path.realpath(__file__)))
sys.path.append(os.getcwd())
sys.path.append(os.path.normpath(os.getcwd() + os.sep + os.pardir))
# Need to run this before calling models from application!
os.environ.setdefault('DJANGO_SETTINGS_MODULE', 'project.settings')
import django... | [
"os.getcwd",
"os.path.realpath",
"os.environ.setdefault",
"django.setup"
] | [((238, 305), 'os.environ.setdefault', 'os.environ.setdefault', (['"""DJANGO_SETTINGS_MODULE"""', '"""project.settings"""'], {}), "('DJANGO_SETTINGS_MODULE', 'project.settings')\n", (259, 305), False, 'import os\n'), ((375, 389), 'django.setup', 'django.setup', ([], {}), '()\n', (387, 389), False, 'import django\n'), (... |
import argparse
import json
import os
from tqdm import tqdm
import numpy as np
import torch
import torch.optim as optim
from torch.utils.data import DataLoader
from torch.utils.tensorboard import SummaryWriter
import torch.nn.functional as F
import torch.nn as nn
torch.backends.cudnn.benchmark = True
import sys
sys.... | [
"argparse.ArgumentParser",
"torch.cat",
"sklearn.metrics.f1_score",
"torch.no_grad",
"os.path.join",
"sys.path.append",
"torch.nn.BCELoss",
"torch.utils.data.DataLoader",
"torch.FloatTensor",
"torch.utils.tensorboard.SummaryWriter",
"model.generate_model",
"numpy.stack",
"json.dump",
"tqdm... | [((316, 387), 'sys.path.append', 'sys.path.append', (['"""/home/hankung/Desktop/Interaction_benchmark/datasets"""'], {}), "('/home/hankung/Desktop/Interaction_benchmark/datasets')\n", (331, 387), False, 'import sys\n'), ((388, 457), 'sys.path.append', 'sys.path.append', (['"""/home/hankung/Desktop/Interaction_benchmark... |
"""This script can be used to construct bar charts coloured
according to an impact factor (e.g. MNCS/PP(top10)
the colours will be categorical'"""
import plotly.express as px
import pandas as pd
#read in data
df = pd.read_excel('/Users/liahu895/Documents/testdata/test_bars.xlsx',
sheet_name='Sheet 1',
engine='o... | [
"pandas.read_excel",
"pandas.cut",
"plotly.express.bar"
] | [((214, 325), 'pandas.read_excel', 'pd.read_excel', (['"""/Users/liahu895/Documents/testdata/test_bars.xlsx"""'], {'sheet_name': '"""Sheet 1"""', 'engine': '"""openpyxl"""'}), "('/Users/liahu895/Documents/testdata/test_bars.xlsx',\n sheet_name='Sheet 1', engine='openpyxl')\n", (227, 325), True, 'import pandas as pd\... |
# -*- coding: utf-8 -*-
import scrapy
from ..items import MovieSpider
from ..common import Common
def parse_list(response):
rank_type = response.meta['rank_type']
detail_urls = list(map(lambda x: "https://www.rottentomatoes.com"+x, response.xpath("//tr/td[3]/a[@class='unstyled articleLink']/@href").extract()... | [
"scrapy.Request"
] | [((753, 831), 'scrapy.Request', 'scrapy.Request', ([], {'url': 'detail_urls[n]', 'callback': 'parse_detail', 'meta': "{'data': item}"}), "(url=detail_urls[n], callback=parse_detail, meta={'data': item})\n", (767, 831), False, 'import scrapy\n'), ((3614, 3706), 'scrapy.Request', 'scrapy.Request', ([], {'url': 'type_url_... |
#!/usr/bin/python
# -*- coding: utf-8 -*-
import glob
from kicadsearch import LibFileParser, DcmFileParser, LibDocCreator
from kicadsearch import ModFileParser, ModDocCreator
from kicadsearch import KicadModFileParser, KicadModDocCreator
# .lib, .dcm
def test_LibFileParser():
docs = []
for f in glob.glob(r'./... | [
"kicadsearch.KicadModFileParser",
"kicadsearch.LibFileParser",
"kicadsearch.ModDocCreator",
"kicadsearch.KicadModDocCreator",
"glob.glob",
"kicadsearch.LibDocCreator",
"kicadsearch.ModFileParser",
"kicadsearch.DcmFileParser"
] | [((306, 344), 'glob.glob', 'glob.glob', (['"""./test/data/library/*.lib"""'], {}), "('./test/data/library/*.lib')\n", (315, 344), False, 'import glob\n'), ((496, 534), 'glob.glob', 'glob.glob', (['"""./test/data/library/*.dcm"""'], {}), "('./test/data/library/*.dcm')\n", (505, 534), False, 'import glob\n'), ((686, 724)... |
#!/usr/bin/env python
import rospy
from std_msgs.msg import String
import threading
import serial
from sensor_msgs.msg import Imu
print("--------Ultrasonic and 9 Degree of Freedom Listener-----------")
US_9d0F_serial = serial.Serial('/dev/ttyUSB1', 115200, timeout=.1)
bus_codes = {
"L": "UFL", #ultrasonic le... | [
"serial.Serial",
"rospy.Time.now",
"rospy.Publisher",
"sensor_msgs.msg.Imu",
"rospy.is_shutdown",
"rospy.init_node"
] | [((220, 270), 'serial.Serial', 'serial.Serial', (['"""/dev/ttyUSB1"""', '(115200)'], {'timeout': '(0.1)'}), "('/dev/ttyUSB1', 115200, timeout=0.1)\n", (233, 270), False, 'import serial\n'), ((523, 565), 'rospy.Publisher', 'rospy.Publisher', (['"""imu"""', 'Imu'], {'queue_size': '(10)'}), "('imu', Imu, queue_size=10)\n"... |
# coding: utf-8
# -----------------------------------------------------------------------------------
# <copyright company="Aspose Pty Ltd" file="viewer_api.py">
# Copyright (c) 2003-2021 Aspose Pty Ltd
# </copyright>
# <summary>
# Permission is hereby granted, free of charge, to any person obtaining a copy
# of ... | [
"six.iteritems",
"groupdocs_viewer_cloud.configuration.Configuration",
"groupdocs_viewer_cloud.auth.Auth",
"groupdocs_viewer_cloud.api_client.ApiClient"
] | [((1933, 1957), 'groupdocs_viewer_cloud.api_client.ApiClient', 'ApiClient', (['configuration'], {}), '(configuration)\n', (1942, 1957), False, 'from groupdocs_viewer_cloud.api_client import ApiClient\n'), ((1979, 2010), 'groupdocs_viewer_cloud.auth.Auth', 'Auth', (['configuration', 'api_client'], {}), '(configuration, ... |
import cv2
import pyyolo
def main():
detector = pyyolo.YOLO("./models/yolov3-spp.cfg",
"./models/yolov3-spp.weights",
"./models/coco.data",
detection_threshold = 0.5,
hier_threshold = 0.5,
... | [
"cv2.waitKey",
"cv2.VideoCapture",
"pyyolo.YOLO",
"cv2.rectangle",
"cv2.imshow"
] | [((53, 217), 'pyyolo.YOLO', 'pyyolo.YOLO', (['"""./models/yolov3-spp.cfg"""', '"""./models/yolov3-spp.weights"""', '"""./models/coco.data"""'], {'detection_threshold': '(0.5)', 'hier_threshold': '(0.5)', 'nms_threshold': '(0.45)'}), "('./models/yolov3-spp.cfg', './models/yolov3-spp.weights',\n './models/coco.data', ... |
import jittor as jt
from jittor import nn
from jittor import Module
from jittor import init
from backbone import resnet50, resnet101
from deeplab import DeepLab
from voc import TrainDataset, ValDataset
import numpy as np
from utils import Evaluator
from tensorboardX import SummaryWriter
import os
jt.flags.use_cuda = 1
... | [
"os.path.join",
"numpy.argmax",
"voc.TrainDataset",
"voc.ValDataset",
"jittor.nn.cross_entropy_loss",
"deeplab.DeepLab",
"utils.Evaluator"
] | [((2275, 2316), 'deeplab.DeepLab', 'DeepLab', ([], {'output_stride': '(16)', 'num_classes': '(21)'}), '(output_stride=16, num_classes=21)\n', (2282, 2316), False, 'from deeplab import DeepLab\n'), ((2336, 2441), 'voc.TrainDataset', 'TrainDataset', ([], {'data_root': '"""/home/guomenghao/voc_aug/mydata/"""', 'split': '"... |
import datetime
import os
import os.path
import re
import traceback
import mailpile.plugins
from mailpile.commands import Command
from mailpile.mailutils import Email
from mailpile.search import MailIndex
from mailpile.util import *
from mailpile.plugins.search import Search, SearchResults
class EditableSearchResul... | [
"mailpile.mailutils.Email",
"mailpile.plugins.search.SearchResults._prune_msg_tree",
"os.path.exists",
"mailpile.mailutils.Email.Create"
] | [((426, 478), 'mailpile.plugins.search.SearchResults._prune_msg_tree', 'SearchResults._prune_msg_tree', (['self', '*args'], {}), '(self, *args, **kwargs)\n', (455, 478), False, 'from mailpile.plugins.search import Search, SearchResults\n'), ((3366, 3395), 'os.path.exists', 'os.path.exists', (['self.args[-1]'], {}), '(s... |
""" Main module. """
__version__ = "0.1"
__author__ = "<NAME>"
# folderly
from folderly.cli import cli
if __name__ == "__main__":
cli()
| [
"folderly.cli.cli"
] | [((137, 142), 'folderly.cli.cli', 'cli', ([], {}), '()\n', (140, 142), False, 'from folderly.cli import cli\n')] |
"""
This model shows how to train a model with Soft Nearest Neighbor Loss
regularization. The paper which presents this method can be found at
https://arxiv.org/abs/1902.01889
"""
# pylint: disable=missing-docstring
from __future__ import absolute_import
from __future__ import division
from __future__ import print_func... | [
"cleverhans.utils.AccuracyReport",
"cleverhans.compat.flags.DEFINE_integer",
"matplotlib.pyplot.figure",
"matplotlib.pyplot.gca",
"matplotlib.offsetbox.AnnotationBbox",
"cleverhans.compat.flags.DEFINE_float",
"cleverhans.loss.CrossEntropy",
"matplotlib.offsetbox.OffsetImage",
"cleverhans.utils.set_l... | [((2292, 2308), 'cleverhans.utils.AccuracyReport', 'AccuracyReport', ([], {}), '()\n', (2306, 2308), False, 'from cleverhans.utils import AccuracyReport, set_log_level\n'), ((2366, 2390), 'tensorflow.set_random_seed', 'tf.set_random_seed', (['(1234)'], {}), '(1234)\n', (2384, 2390), True, 'import tensorflow as tf\n'), ... |
from django.contrib import admin
from .models import Banner, Services, Video, Testimonial
admin.site.register(Banner)
admin.site.register(Services)
admin.site.register(Video)
admin.site.register(Testimonial)
| [
"django.contrib.admin.site.register"
] | [((91, 118), 'django.contrib.admin.site.register', 'admin.site.register', (['Banner'], {}), '(Banner)\n', (110, 118), False, 'from django.contrib import admin\n'), ((119, 148), 'django.contrib.admin.site.register', 'admin.site.register', (['Services'], {}), '(Services)\n', (138, 148), False, 'from django.contrib import... |
# Copyright (c) 2012 The Chromium Authors. All rights reserved.
# Use of this source code is governed by a BSD-style license that can be
# found in the LICENSE file.
'''The 'grit transl2tc' tool.
'''
from __future__ import print_function
from grit import grd_reader
from grit import util
from grit.tool import interfa... | [
"grit.tool.rc2grd.Rc2Grd",
"grit.grd_reader.Parse",
"grit.util.ReadFile"
] | [((2081, 2096), 'grit.tool.rc2grd.Rc2Grd', 'rc2grd.Rc2Grd', ([], {}), '()\n', (2094, 2096), False, 'from grit.tool import rc2grd\n'), ((2686, 2744), 'grit.grd_reader.Parse', 'grd_reader.Parse', (['self.o.input'], {'debug': 'self.o.extra_verbose'}), '(self.o.input, debug=self.o.extra_verbose)\n', (2702, 2744), False, 'f... |
import json
from pathlib import Path
import joblib
import numpy as np
import matplotlib.pyplot as plt
from ..analysis.searchstims import p_item_grid, acc_grid, err_grid
def heatmap(grid, ax=None, cmap='rainbow', vmin=0, vmax=1):
"""helper function that plots a heatmap,
using the matplotlib.pyplot.imshow fu... | [
"json.load",
"numpy.asarray",
"numpy.nonzero",
"pathlib.Path",
"joblib.load",
"matplotlib.pyplot.subplots",
"numpy.concatenate"
] | [((3012, 3038), 'joblib.load', 'joblib.load', (['data_gz_fname'], {}), '(data_gz_fname)\n', (3023, 3038), False, 'import joblib\n'), ((8039, 8065), 'joblib.load', 'joblib.load', (['data_gz_fname'], {}), '(data_gz_fname)\n', (8050, 8065), False, 'import joblib\n'), ((10471, 10500), 'joblib.load', 'joblib.load', (['resul... |
import numpy as np
import sys
import os
#Generate Dataset for Rotated / Fashion MNIST
base_dir= 'datasets/colored_mnist/'
if not os.path.exists(base_dir):
os.makedirs(base_dir)
if sys.argv[1] == 'resnet18':
# Generate 10 random subsets of size 2,000 each for Rotated MNIST
data_size=60000
subset_size... | [
"os.path.exists",
"os.makedirs",
"numpy.random.choice"
] | [((130, 154), 'os.path.exists', 'os.path.exists', (['base_dir'], {}), '(base_dir)\n', (144, 154), False, 'import os\n'), ((160, 181), 'os.makedirs', 'os.makedirs', (['base_dir'], {}), '(base_dir)\n', (171, 181), False, 'import os\n'), ((430, 454), 'os.path.exists', 'os.path.exists', (['data_dir'], {}), '(data_dir)\n', ... |
from datetime import datetime
atual = datetime.today().year
cont = 0
velho = [0]
novo = [0]
for c in range(1, 8):
ano = int(input('Em que ano a {}ª pessoa nasceu?'.format(cont + c)))
if atual - ano >= 18: # considerando a maioridade 18 anos
velho.insert(c, ano)
else:
novo.insert(c, ano)
maio... | [
"datetime.datetime.today"
] | [((38, 54), 'datetime.datetime.today', 'datetime.today', ([], {}), '()\n', (52, 54), False, 'from datetime import datetime\n')] |
import os
from xmltodict import parse
from pyQuARC.code.schema_validator import SchemaValidator
KEYS = [
"no_error_metadata", "bad_syntax_metadata", "test_cmr_metadata"
]
class TestSchemaValidator:
def setup_method(self):
self.data = self.read_data()
self.schema_validator = SchemaValidator(... | [
"os.getcwd",
"pyQuARC.code.schema_validator.SchemaValidator"
] | [((304, 321), 'pyQuARC.code.schema_validator.SchemaValidator', 'SchemaValidator', ([], {}), '()\n', (319, 321), False, 'from pyQuARC.code.schema_validator import SchemaValidator\n'), ((537, 548), 'os.getcwd', 'os.getcwd', ([], {}), '()\n', (546, 548), False, 'import os\n')] |
from robocorp_ls_core.lsp import (
HoverTypedDict,
MarkupKind,
SignatureHelp,
SignatureInformation,
MarkupContentTypedDict,
)
from typing import Optional
def hover(completion_context) -> Optional[HoverTypedDict]:
from robotframework_ls.impl.signature_help import signature_help_internal
si... | [
"robotframework_ls.impl.signature_help.signature_help_internal"
] | [((354, 397), 'robotframework_ls.impl.signature_help.signature_help_internal', 'signature_help_internal', (['completion_context'], {}), '(completion_context)\n', (377, 397), False, 'from robotframework_ls.impl.signature_help import signature_help_internal\n')] |
from functools import lru_cache
@lru_cache(maxsize=None)
def fib4(n: int) -> int:
if n < 2:
return n
return fib4(n - 1) + fib4(n - 2)
if __name__ == "__main__":
print(fib4(50))
| [
"functools.lru_cache"
] | [((35, 58), 'functools.lru_cache', 'lru_cache', ([], {'maxsize': 'None'}), '(maxsize=None)\n', (44, 58), False, 'from functools import lru_cache\n')] |
Subsets and Splits
No community queries yet
The top public SQL queries from the community will appear here once available.