code stringlengths 22 1.05M | apis listlengths 1 3.31k | extract_api stringlengths 75 3.25M |
|---|---|---|
from django.contrib import admin
from .models import Dish
# Register your models here.
admin.site.register(Dish) | [
"django.contrib.admin.site.register"
] | [((87, 112), 'django.contrib.admin.site.register', 'admin.site.register', (['Dish'], {}), '(Dish)\n', (106, 112), False, 'from django.contrib import admin\n')] |
#!/usr/bin/python3
'''
############################################################################
->Autores:
-<NAME>
-<NAME>
->Fecha de creación: 01/11/2020
->Descripción: Análisis y resolución del problema 'Los alumnos y el asesor'
############################################################################... | [
"threading.Thread",
"random.random",
"threading.Semaphore",
"random.randint"
] | [((1942, 1973), 'threading.Semaphore', 'threading.Semaphore', (['num_sillas'], {}), '(num_sillas)\n', (1961, 1973), False, 'import threading\n'), ((1990, 2012), 'threading.Semaphore', 'threading.Semaphore', (['(0)'], {}), '(0)\n', (2009, 2012), False, 'import threading\n'), ((2035, 2057), 'threading.Semaphore', 'thread... |
"""Defines hooks that can run during training."""
from __future__ import absolute_import
from __future__ import division
from __future__ import print_function
import lasagne
import numpy as np
from sklearn import metrics
class LoggingHook(object):
"""This hook writes information to a log file."""
def __ini... | [
"lasagne.layers.get_all_param_values",
"numpy.argmax",
"numpy.asarray",
"numpy.zeros",
"numpy.max",
"numpy.arange"
] | [((1068, 1096), 'numpy.asarray', 'np.asarray', (["kwargs['losses']"], {}), "(kwargs['losses'])\n", (1078, 1096), True, 'import numpy as np\n'), ((1983, 2033), 'lasagne.layers.get_all_param_values', 'lasagne.layers.get_all_param_values', (['self._network'], {}), '(self._network)\n', (2018, 2033), False, 'import lasagne\... |
# Implementations done in Python since it natively supports unbounded integer
# arithmetic and fractional math
#Compiled with Python 2.7.3 (default, Apr 10 2012, 23:31:26) [MSC v.1500 32 bit (Intel)] on win32
#in IDLE version 2.7.3
#For profiling (written in C to avoid overhead)
import cProfile
# to deal with fract... | [
"fractions.Fraction",
"cProfile.run"
] | [((8040, 8068), 'cProfile.run', 'cProfile.run', (['"""fibonacci(n)"""'], {}), "('fibonacci(n)')\n", (8052, 8068), False, 'import cProfile\n'), ((8185, 8211), 'cProfile.run', 'cProfile.run', (['"""fibLoop(n)"""'], {}), "('fibLoop(n)')\n", (8197, 8211), False, 'import cProfile\n'), ((8340, 8368), 'cProfile.run', 'cProfil... |
#Get dependencies
from flask import Flask, render_template, redirect
import pymongo
import mission_to_mars
import jinja2
from jinja2 import TemplateNotFound
#Create Flask App
app = Flask(__name__)
#Connect to MongoDB
conn = "mongodb://localhost:27017"
client = pymongo.MongoClient(conn)
db = client.mars_DB... | [
"pymongo.MongoClient",
"mission_to_mars.scrape",
"flask.redirect",
"flask.Flask",
"flask.render_template"
] | [((189, 204), 'flask.Flask', 'Flask', (['__name__'], {}), '(__name__)\n', (194, 204), False, 'from flask import Flask, render_template, redirect\n'), ((274, 299), 'pymongo.MongoClient', 'pymongo.MongoClient', (['conn'], {}), '(conn)\n', (293, 299), False, 'import pymongo\n'), ((402, 442), 'flask.render_template', 'rend... |
# -*- coding: utf-8 -*-
"""
xobox.cli.logger
~~~~~~~~~~~~~~~~
:copyright: Copyright 2017 by the Stormrose Project team, see AUTHORS.
:license: MIT License, see LICENSE for details.
"""
import sys
from datetime import datetime
from ..conf import get_conf
from ..utils.singleton import Singleton
from ..u... | [
"datetime.datetime.now"
] | [((4827, 4841), 'datetime.datetime.now', 'datetime.now', ([], {}), '()\n', (4839, 4841), False, 'from datetime import datetime\n'), ((5249, 5263), 'datetime.datetime.now', 'datetime.now', ([], {}), '()\n', (5261, 5263), False, 'from datetime import datetime\n')] |
# -*- coding: utf-8 -*-
###############################################################################
# Copyright (c), Forschungszentrum Jülich GmbH, IAS-1/PGI-1, Germany. #
# All rights reserved. #
# This file is part of the Masci-tools package. ... | [
"masci_tools.io.parsers.hdf5.reader.AttribTransformation",
"h5py.File",
"masci_tools.io.parsers.hdf5.HDF5Reader",
"masci_tools.io.parsers.hdf5.reader.Transformation",
"numpy.array2string",
"numpy.zeros",
"numpy.array",
"collections.namedtuple",
"numpy.linalg.norm"
] | [((1342, 1462), 'collections.namedtuple', 'namedtuple', (['"""GreensfElement"""', "['l', 'lp', 'atomType', 'atomTypep', 'sphavg', 'onsite', 'contour', 'nLO',\n 'atomDiff']"], {}), "('GreensfElement', ['l', 'lp', 'atomType', 'atomTypep', 'sphavg',\n 'onsite', 'contour', 'nLO', 'atomDiff'])\n", (1352, 1462), False,... |
# logging times and names to a file for event parsing
import os
import time
from pathlib import Path
import csv
logPath = os.path.join(os.getcwd(), "face-log.txt")
FIELD_AMT = 2
class Logger(object):
# initialization function that creates the log file
def __init__(self):
path = Path(logPath)
if... | [
"os.getcwd",
"pathlib.Path",
"csv.reader",
"time.time"
] | [((135, 146), 'os.getcwd', 'os.getcwd', ([], {}), '()\n', (144, 146), False, 'import os\n'), ((296, 309), 'pathlib.Path', 'Path', (['logPath'], {}), '(logPath)\n', (300, 309), False, 'from pathlib import Path\n'), ((2289, 2324), 'csv.reader', 'csv.reader', (['logFile'], {'delimiter': '"""\t"""'}), "(logFile, delimiter=... |
#**********************************************************************************************
# Traffic Emulator for Network Services
# Copyright 2020 VMware, Inc
# The BSD-2 license (the "License") set forth below applies to all parts of
# the Traffic Emulator for Network Services project. You may not use this file
... | [
"collections.defaultdict"
] | [((2909, 2926), 'collections.defaultdict', 'defaultdict', (['list'], {}), '(list)\n', (2920, 2926), False, 'from collections import defaultdict\n')] |
# Copyright 2020 The TensorFlow 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 required by applica... | [
"tensorboard.plugins.projector.visualize_embeddings",
"tensorflow_datasets.load",
"tensorflow.train.Checkpoint",
"tensorflow.keras.layers.Dense",
"tensorflow.keras.losses.BinaryCrossentropy",
"tensorboard.plugins.projector.ProjectorConfig",
"tensorflow.keras.layers.GlobalAveragePooling1D",
"tensorflow... | [((1344, 1464), 'tensorflow_datasets.load', 'tfds.load', (['"""imdb_reviews/subwords8k"""'], {'split': '(tfds.Split.TRAIN, tfds.Split.TEST)', 'with_info': '(True)', 'as_supervised': '(True)'}), "('imdb_reviews/subwords8k', split=(tfds.Split.TRAIN, tfds.Split.\n TEST), with_info=True, as_supervised=True)\n", (1353, 1... |
# -*- coding: utf-8 -*-
#
# Copyright © 2021–2022 <NAME> <<EMAIL>>
# Released under the MIT Licence
#
import pytest
from pytcnz.gender import Gender, InvalidGenderError
@pytest.fixture(
params=[
"M",
"W",
"Man",
"Men",
"Women",
"Woman",
"male",
"fe... | [
"pytest.raises",
"pytcnz.gender.Gender.to_sex",
"pytcnz.gender.Gender.from_string",
"pytest.fixture"
] | [((174, 295), 'pytest.fixture', 'pytest.fixture', ([], {'params': "['M', 'W', 'Man', 'Men', 'Women', 'Woman', 'male', 'female', None, 'NONE',\n 'N', 'w', 'm', 'f']"}), "(params=['M', 'W', 'Man', 'Men', 'Women', 'Woman', 'male',\n 'female', None, 'NONE', 'N', 'w', 'm', 'f'])\n", (188, 295), False, 'import pytest\n... |
import scrappers
import re
import scrappers.mixins
class CBSNews(scrappers.mixins.RSSScrapper, scrappers.Scrapper):
"""The CBS News RSS feeds scrapper.
"""
def __init__(self, *args, **kwargs):
super().__init__(*args, **kwargs)
def should_translate(self):
return False
def encodin... | [
"re.compile"
] | [((536, 593), 're.compile', 're.compile', (['"""^Photos\\\\s+of\\\\s+the\\\\s+week"""', 're.IGNORECASE'], {}), "('^Photos\\\\s+of\\\\s+the\\\\s+week', re.IGNORECASE)\n", (546, 593), False, 'import re\n')] |
#!/usr/bin/python3
import time
import dh.data
import dh.image
import dh.network
import dh.utils
###
#%% main
###
def main():
C = dh.network.ImageProcessingClient2("localhost")
# input
I = dh.data.lena()
params = {"gamma": 0.5}
print("Input:")
dh.image.pinfo(I)
# result
t0 = time.... | [
"time.time"
] | [((315, 326), 'time.time', 'time.time', ([], {}), '()\n', (324, 326), False, 'import time\n'), ((373, 384), 'time.time', 'time.time', ([], {}), '()\n', (382, 384), False, 'import time\n')] |
#!/usr/bin/env python
# coding=utf-8
"""
Copyright 2013 Load Impact
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 la... | [
"loadimpact.ApiTokenClient",
"sys.exit",
"traceback.format_exc",
"optparse.OptionParser"
] | [((1033, 1058), 'loadimpact.ApiTokenClient', 'ApiTokenClient', (['api_token'], {}), '(api_token)\n', (1047, 1058), False, 'from loadimpact import ApiTokenClient, ApiError, DataStore, LoadZone, TestConfig, UserScenario, __version__ as li_sdk_version\n'), ((1841, 1900), 'optparse.OptionParser', 'optparse.OptionParser', (... |
import glob
import json
import os
from wsgiref.util import FileWrapper
import shutil
import pandas as pd
from django.conf import settings
from django.contrib.auth.decorators import login_required
from django.http.response import HttpResponse
from django.shortcuts import render
from interface.models import DbQuery
fro... | [
"django.contrib.auth.decorators.login_required",
"pandas.DataFrame",
"json.load",
"os.path.basename",
"os.path.getsize",
"interface.models.StarsFilter.objects.filter",
"os.environ.get",
"pandas.to_datetime",
"glob.glob",
"django.shortcuts.render",
"interface.models.DbQuery.objects.filter",
"os... | [((361, 395), 'django.contrib.auth.decorators.login_required', 'login_required', ([], {'login_url': '"""login/"""'}), "(login_url='login/')\n", (375, 395), False, 'from django.contrib.auth.decorators import login_required\n'), ((1854, 1888), 'django.contrib.auth.decorators.login_required', 'login_required', ([], {'logi... |
from models.abstract_handler import BaseValidator
from configs.configs import dataset_type_asr, dataset_type_asr_unlabeled, dataset_type_tts, asr_minimum_words_per_min
import logging
from logging.config import dictConfig
log = logging.getLogger('file')
import audio_metadata
from word2number import w2n
from datetime imp... | [
"os.path.getsize",
"os.path.exists",
"audio_metadata.load",
"os.path.isfile",
"logging.config.dictConfig",
"word2number.w2n.word_to_num",
"logging.getLogger"
] | [((227, 252), 'logging.getLogger', 'logging.getLogger', (['"""file"""'], {}), "('file')\n", (244, 252), False, 'import logging\n'), ((5196, 5784), 'logging.config.dictConfig', 'dictConfig', (["{'version': 1, 'formatters': {'default': {'format':\n '[%(asctime)s] {%(filename)s:%(lineno)d} %(threadName)s %(levelname)s ... |
import os
import sys
import click
from flask import Flask
from flask_sqlalchemy import SQLAlchemy
from flask import redirect, url_for, abort, render_template, flash
from flask_wtf import FlaskForm
from wtforms import SubmitField, TextAreaField
from wtforms.validators import DataRequired
# SQLite URI compatible
WIN = ... | [
"sys.platform.startswith",
"flask.Flask",
"os.path.join",
"flask_sqlalchemy.SQLAlchemy"
] | [((320, 350), 'sys.platform.startswith', 'sys.platform.startswith', (['"""win"""'], {}), "('win')\n", (343, 350), False, 'import sys\n'), ((425, 440), 'flask.Flask', 'Flask', (['__name__'], {}), '(__name__)\n', (430, 440), False, 'from flask import Flask\n'), ((616, 631), 'flask_sqlalchemy.SQLAlchemy', 'SQLAlchemy', ([... |
import pandas as pd
import logging
import os
import snakemake as snakemake_api
import tempfile
import yaml
from .constants import *
from .i_o import get_logger, get_df_drop_message
# Helper functions
def convert_with_map(row, index, convert_map):
try:
return convert_map[row[index]]
except KeyError:
retu... | [
"tempfile.NamedTemporaryFile",
"snakemake.snakemake",
"os.unlink",
"yaml.dump",
"pandas.Categorical"
] | [((2036, 2100), 'pandas.Categorical', 'pd.Categorical', (['df[COLNAME.CHR.value]', 'CHROMOSOMES'], {'ordered': '(True)'}), '(df[COLNAME.CHR.value], CHROMOSOMES, ordered=True)\n', (2050, 2100), True, 'import pandas as pd\n'), ((2557, 2608), 'tempfile.NamedTemporaryFile', 'tempfile.NamedTemporaryFile', ([], {'mode': '"""... |
#!/bin/python3
# -*- coding: utf-8 -*-
import pandas
data = pandas.read_csv('./annser.csv',
header=0,
na_values=[''],
usecols=[0, 1, 3, 4])
abbrevs = ""
for index, rows in data.iterrows():
abbrev = "".join(
[s[:1] for s in (str(rows[1])).... | [
"pandas.read_csv"
] | [((61, 140), 'pandas.read_csv', 'pandas.read_csv', (['"""./annser.csv"""'], {'header': '(0)', 'na_values': "['']", 'usecols': '[0, 1, 3, 4]'}), "('./annser.csv', header=0, na_values=[''], usecols=[0, 1, 3, 4])\n", (76, 140), False, 'import pandas\n')] |
# -*- coding: utf-8 -*-
"""
2D sweep of drive power and frequency in Lockin mode.
"""
from typing import List
import h5py
import numpy as np
from presto.hardware import AdcFSample, AdcMode, DacFSample, DacMode
from presto import lockin
from presto.utils import ProgressBar
from _base import Base
DAC_CURRENT = 32_000... | [
"h5py.File",
"numpy.zeros_like",
"numpy.atleast_1d",
"presto.utils.ProgressBar",
"numpy.abs",
"numpy.full_like",
"numpy.angle",
"numpy.zeros",
"presto.lockin.Lockin",
"numpy.percentile",
"matplotlib.pyplot.figure",
"numpy.mean",
"numpy.arange",
"matplotlib.widgets.SpanSelector",
"numpy.l... | [((6151, 6181), 'numpy.percentile', 'np.percentile', (['resp_dB', 'cutoff'], {}), '(resp_dB, cutoff)\n', (6164, 6181), True, 'import numpy as np\n'), ((6200, 6238), 'numpy.percentile', 'np.percentile', (['resp_dB', '(100.0 - cutoff)'], {}), '(resp_dB, 100.0 - cutoff)\n', (6213, 6238), True, 'import numpy as np\n'), ((1... |
# Lint as: python3
# Copyright 2020 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
#
# https://www.apache.org/licenses/LICENSE-2.0
#
# Unless required ... | [
"pandas.read_csv",
"numpy.random.permutation",
"tensorflow.io.gfile.exists",
"tensorflow.io.gfile.GFile"
] | [((1632, 1660), 'tensorflow.io.gfile.exists', 'tf.io.gfile.exists', (['datafile'], {}), '(datafile)\n', (1650, 1660), True, 'import tensorflow as tf\n'), ((1736, 1763), 'tensorflow.io.gfile.GFile', 'tf.io.gfile.GFile', (['datafile'], {}), '(datafile)\n', (1753, 1763), True, 'import tensorflow as tf\n'), ((1792, 1842), ... |
from datetime import date, datetime
dados = dict()
dados['nome'] = str(input('Nome: '))
nasc = int(input('ANO DE NASCIMENTO: '))
dados['idade'] = datetime.now().year - nasc
dados['ctps'] = int(input('carteira de trabalho (0 não tem): '))
if dados['ctps'] != 0:
dados['contratação'] = int(input('ano de contratação: '... | [
"datetime.datetime.now"
] | [((146, 160), 'datetime.datetime.now', 'datetime.now', ([], {}), '()\n', (158, 160), False, 'from datetime import date, datetime\n'), ((435, 449), 'datetime.datetime.now', 'datetime.now', ([], {}), '()\n', (447, 449), False, 'from datetime import date, datetime\n')] |
import torch
from torch.utils.data import Dataset
import numpy as np
from scipy.io import loadmat
class NatPatchDataset(Dataset):
def __init__(self, N:int, width:int, height:int, border:int=4, fpath:str='../../data/IMAGES.mat', test=False):
super(NatPatchDataset, self).__init__()
self.N = N
... | [
"torch.zeros",
"numpy.random.randint",
"torch.tensor",
"scipy.io.loadmat"
] | [((746, 765), 'scipy.io.loadmat', 'loadmat', (['self.fpath'], {}), '(self.fpath)\n', (753, 765), False, 'from scipy.io import loadmat\n'), ((869, 923), 'torch.zeros', 'torch.zeros', (['(self.N * n_img, self.width, self.height)'], {}), '((self.N * n_img, self.width, self.height))\n', (880, 923), False, 'import torch\n')... |
import ihm.model
import logging
dockinglog = logging.getLogger("log")
class DockingModel(ihm.model.Model):
"""Subclass to save memory."""
# ======================================================================
# IMPORTANT #
# To add the atoms, the class module needs a list containing the following:... | [
"logging.getLogger"
] | [((46, 70), 'logging.getLogger', 'logging.getLogger', (['"""log"""'], {}), "('log')\n", (63, 70), False, 'import logging\n')] |
from django.core.management.base import BaseCommand
from mainapp.functions.mail import send_mail
from mainapp.models import UserProfile
class Command(BaseCommand):
help = "Sends a test e-mail to check if the mail-system is configured correctly"
def add_arguments(self, parser):
parser.add_argument("t... | [
"mainapp.models.UserProfile.objects.filter",
"mainapp.functions.mail.send_mail"
] | [((618, 679), 'mainapp.functions.mail.send_mail', 'send_mail', (['to_email', '"""Hello 🌏"""', 'body_text', 'body_html', 'profile'], {}), "(to_email, 'Hello 🌏', body_text, body_html, profile)\n", (627, 679), False, 'from mainapp.functions.mail import send_mail\n'), ((552, 600), 'mainapp.models.UserProfile.objects.filt... |
# Copyright 2020 <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
#
# https://www.apache.org/licenses/LICENSE-2.0
#
# Unless required by applicable law or agreed to in writing, soft... | [
"packaging.version.parse"
] | [((843, 864), 'packaging.version.parse', 'parse', (['tf.__version__'], {}), '(tf.__version__)\n', (848, 864), False, 'from packaging.version import parse\n'), ((867, 881), 'packaging.version.parse', 'parse', (['"""2.0.0"""'], {}), "('2.0.0')\n", (872, 881), False, 'from packaging.version import parse\n')] |
import string
from nltk.tokenize.casual import TweetTokenizer
def tokenize(text):
tweet_tokenizer = TweetTokenizer()
# 1. Tokenize
text = tweet_tokenizer.tokenize(text)
# 2. Cleaning
# Punctuation
text = [t for t in text if t not in string.punctuation]
# Normalisieren
text = [t.lower() ... | [
"nltk.tokenize.casual.TweetTokenizer"
] | [((105, 121), 'nltk.tokenize.casual.TweetTokenizer', 'TweetTokenizer', ([], {}), '()\n', (119, 121), False, 'from nltk.tokenize.casual import TweetTokenizer\n')] |
import subprocess
proc = subprocess.Popen(["cargo", "clippy"], stderr=subprocess.PIPE)
output = proc.stderr.read().decode("utf-8")
groups = [group for group in output.split("\n\n") if "parser.rs" not in group]
print("\n-----------------\n".join(groups[:20]))
| [
"subprocess.Popen"
] | [((26, 87), 'subprocess.Popen', 'subprocess.Popen', (["['cargo', 'clippy']"], {'stderr': 'subprocess.PIPE'}), "(['cargo', 'clippy'], stderr=subprocess.PIPE)\n", (42, 87), False, 'import subprocess\n')] |
import logging
from datetime import timedelta
from os import path
import dateutil.parser
import requests
import yaml
from beancount.core import amount, data
from beancount.core.number import D
from beancount.ingest import importer
class Importer(importer.ImporterProtocol):
"""An importer for Truelayer API (e.g. ... | [
"os.path.basename",
"logging.warning",
"beancount.core.amount.Amount",
"yaml.safe_load",
"datetime.timedelta",
"requests.get",
"requests.post",
"beancount.core.data.new_metadata"
] | [((1413, 1618), 'requests.post', 'requests.post', (['f"""https://auth.{self.domain}/connect/token"""'], {'data': "{'grant_type': 'refresh_token', 'client_id': self.clientId, 'client_secret':\n self.clientSecret, 'refresh_token': self.refreshToken}"}), "(f'https://auth.{self.domain}/connect/token', data={\n 'grant... |
import logging
import sys
from enum import Enum
from racelogger.util.utils import gate
CAR_SLOW_SPEED = 25
""" a car is considered to be slow if its speed is below this value"""
CarsManifest = ['state','carIdx','carNum','userName','teamName','car','carClass','pos','pic','lap','lc','gap','interval','trackPos','speed'... | [
"logging.getLogger",
"racelogger.util.utils.gate"
] | [((3347, 3389), 'logging.getLogger', 'logging.getLogger', (['self.__class__.__name__'], {}), '(self.__class__.__name__)\n', (3364, 3389), False, 'import logging\n'), ((4729, 4770), 'racelogger.util.utils.gate', 'gate', (["ir['CarIdxLapDistPct'][self.carIdx]"], {}), "(ir['CarIdxLapDistPct'][self.carIdx])\n", (4733, 4770... |
from base64 import b64encode as _e, b64decode as _d
def encode(text: str, timestamp: float) -> str:
"""Encode comment into base64 string.
:param text: The text of the comment.
:param timestamp: The timestamp of the comment.
:return: The base64-encoded comment.
"""
return '%s:%s' % (_encode(text), _encode(time... | [
"base64.b64decode"
] | [((1251, 1258), 'base64.b64decode', '_d', (['src'], {}), '(src)\n', (1253, 1258), True, 'from base64 import b64encode as _e, b64decode as _d\n')] |
#!/usr/bin/env python
# -*- coding: utf-8 -*-
from setuptools import setup, find_packages
import pypandoc
import os
os.chdir(os.path.normpath(os.path.join(os.path.abspath(__file__), os.pardir)))
with open('requirements.txt') as requirements:
install_requires = requirements.read().splitlines()
try:
long_descri... | [
"os.path.abspath",
"pypandoc.convert",
"setuptools.find_packages",
"io.open"
] | [((328, 364), 'pypandoc.convert', 'pypandoc.convert', (['"""README.md"""', '"""rst"""'], {}), "('README.md', 'rst')\n", (344, 364), False, 'import pypandoc\n'), ((683, 698), 'setuptools.find_packages', 'find_packages', ([], {}), '()\n', (696, 698), False, 'from setuptools import setup, find_packages\n'), ((156, 181), '... |
# -*- coding: utf-8 -*-
import argparse, datetime, glob, json, logging, os, pprint, random, time
from functools import partial
from operator import itemgetter
from typing import Iterator, List, Optional
import asks, trio
logging.basicConfig(
# filename=settings.LOG_PATH,
level=logging.DEBUG,
format='[%(... | [
"functools.partial",
"trio.open_nursery",
"trio.Semaphore",
"argparse.ArgumentParser",
"logging.basicConfig",
"random.randint",
"json.loads",
"pprint.pformat",
"datetime.datetime.fromtimestamp",
"json.dumps",
"datetime.datetime.strptime",
"asks.post",
"os.path.getmtime",
"glob.glob",
"op... | [((225, 394), 'logging.basicConfig', 'logging.basicConfig', ([], {'level': 'logging.DEBUG', 'format': '"""[%(asctime)s] %(levelname)s [%(module)s-%(funcName)s()::%(lineno)d] %(message)s"""', 'datefmt': '"""%d/%b/%Y %H:%M:%S"""'}), "(level=logging.DEBUG, format=\n '[%(asctime)s] %(levelname)s [%(module)s-%(funcName)s... |
from cookiecutter.main import cookiecutter
def main():
cookiecutter('source-files')#, no_input=True)
if __name__ == '__main__':
main()
| [
"cookiecutter.main.cookiecutter"
] | [((60, 88), 'cookiecutter.main.cookiecutter', 'cookiecutter', (['"""source-files"""'], {}), "('source-files')\n", (72, 88), False, 'from cookiecutter.main import cookiecutter\n')] |
from typing import Union
from fastapi import HTTPException
from fastapi.exceptions import RequestValidationError
from fastapi.openapi.constants import REF_PREFIX
from fastapi.openapi.utils import validation_error_response_definition
from pydantic import ValidationError
from starlette.requests import Request
fr... | [
"starlette.responses.JSONResponse"
] | [((518, 585), 'starlette.responses.JSONResponse', 'JSONResponse', (["{'errors': [exc.detail]}"], {'status_code': 'exc.status_code'}), "({'errors': [exc.detail]}, status_code=exc.status_code)\n", (530, 585), False, 'from starlette.responses import JSONResponse\n')] |
from nonebot import adapters
from typing import Optional
from pydantic import Field, BaseModel
class Config(BaseModel):
"""
telegram配置类
:配置项:
- ``webhook_host`` / ``telegram_webhook_host``: webhook的host
- ``bot_token`` / ``telegram_bot_token``: bot_token
- ``telegram_command_only`` / ... | [
"pydantic.Field"
] | [((506, 556), 'pydantic.Field', 'Field', ([], {'default': 'None', 'alias': '"""telegram_webhook_host"""'}), "(default=None, alias='telegram_webhook_host')\n", (511, 556), False, 'from pydantic import Field, BaseModel\n'), ((588, 635), 'pydantic.Field', 'Field', ([], {'default': 'None', 'alias': '"""telegram_bot_token""... |
import json
from core.utils.cleanOrder import cleanString
yesWords = ["oui", "d'accord", "d accord", "ok", "ça marche", "pourquoi pas", "bien sur"]
noWords = ["non", "pas du tout", "hors de question", "pas question", "impossible", "je refuse"]
def sendAnswer(answer, client):
msg = { "type": "answer", "msg": answe... | [
"json.loads",
"json.dumps",
"core.utils.cleanOrder.cleanString"
] | [((338, 353), 'json.dumps', 'json.dumps', (['msg'], {}), '(msg)\n', (348, 353), False, 'import json\n'), ((482, 497), 'json.dumps', 'json.dumps', (['msg'], {}), '(msg)\n', (492, 497), False, 'import json\n'), ((710, 725), 'json.dumps', 'json.dumps', (['msg'], {}), '(msg)\n', (720, 725), False, 'import json\n'), ((1096,... |
"""
Feedback database model
"""
from uuid import UUID
# pylint incorrectly complains about unused import for UniqueConstraint... not sure why
from sqlalchemy.schema import ( # pylint:disable=unused-import
ForeignKey,
UniqueConstraint,
)
from pydantic import Field
from woolgatherer.db_models.base import DBBas... | [
"sqlalchemy.schema.UniqueConstraint",
"pydantic.Field",
"sqlalchemy.schema.ForeignKey"
] | [((549, 559), 'pydantic.Field', 'Field', (['...'], {}), '(...)\n', (554, 559), False, 'from pydantic import Field\n'), ((585, 607), 'pydantic.Field', 'Field', (['...'], {'index': '(True)'}), '(..., index=True)\n', (590, 607), False, 'from pydantic import Field\n'), ((424, 465), 'sqlalchemy.schema.UniqueConstraint', 'Un... |
from RouteManager import RouteManager
from Route import Route
import numpy as np
class GeneticAlgorithmSolver:
def __init__(self, cities, population_size=50, mutation_rate=0.05, tournament_size=5, elitism=True):
self.cities = cities
self.population_size = population_size
self.mutation_rat... | [
"numpy.random.rand",
"Route.Route",
"RouteManager.RouteManager",
"numpy.random.choice"
] | [((866, 913), 'RouteManager.RouteManager', 'RouteManager', (['self.cities', 'self.population_size'], {}), '(self.cities, self.population_size)\n', (878, 913), False, 'from RouteManager import RouteManager\n'), ((1350, 1397), 'RouteManager.RouteManager', 'RouteManager', (['self.cities', 'self.population_size'], {}), '(s... |
import json
import pytest
from flask import Response
from flask.testing import FlaskClient
class APIResponse(Response):
def json(self):
return json.loads(self.data)
@pytest.fixture()
def test_client(core_app):
core_app.test_client_class = FlaskClient
core_app.response_class = APIResponse
re... | [
"pytest.fixture",
"json.loads"
] | [((183, 199), 'pytest.fixture', 'pytest.fixture', ([], {}), '()\n', (197, 199), False, 'import pytest\n'), ((158, 179), 'json.loads', 'json.loads', (['self.data'], {}), '(self.data)\n', (168, 179), False, 'import json\n')] |
"""
--- okta-user-id --
This is a simple module for turning (apparently) base62-encoded Okta user IDs
into UUIDs. It also allows for reversing the UUID to an Okta user ID.
"""
__title__ = 'okta-uuid'
__author__ = '<NAME>'
__email__ = '<EMAIL>'
__version__ = '0.1.0'
import uuid
import base62
class OktaUserId(obje... | [
"base62.encode",
"base62.decode",
"uuid.UUID"
] | [((391, 409), 'base62.decode', 'base62.decode', (['uid'], {}), '(uid)\n', (404, 409), False, 'import base62\n'), ((483, 504), 'uuid.UUID', 'uuid.UUID', ([], {'bytes_le': 'b'}), '(bytes_le=b)\n', (492, 504), False, 'import uuid\n'), ((1072, 1088), 'base62.encode', 'base62.encode', (['b'], {}), '(b)\n', (1085, 1088), Fal... |
import dearpygui.dearpygui as dpg
from .window import Window
from . import ConnectionListWindow
class SchemaWindow(Window):
def __init__(self, app, **kwargs):
# fmt: off
super().__init__(
app, 'Текущее подключение', 'main_window', (800, 500),
tag_schema_selector='schema se... | [
"dearpygui.dearpygui.add_input_text",
"dearpygui.dearpygui.add_text",
"dearpygui.dearpygui.add_button",
"dearpygui.dearpygui.group",
"dearpygui.dearpygui.get_value",
"dearpygui.dearpygui.delete_item",
"dearpygui.dearpygui.add_combo",
"dearpygui.dearpygui.add_spacer",
"dearpygui.dearpygui.tab",
"de... | [((2008, 2039), 'dearpygui.dearpygui.delete_item', 'dpg.delete_item', (['self.window_id'], {}), '(self.window_id)\n', (2023, 2039), True, 'import dearpygui.dearpygui as dpg\n'), ((2194, 2247), 'dearpygui.dearpygui.delete_item', 'dpg.delete_item', (['self.tag_content'], {'children_only': '(True)'}), '(self.tag_content, ... |
#!/usr/bin/env python3
####################################################################################
# Script is not in use, since this is no longer in the main corpus
# Cleaning up parliament speech files
# Output is an UTF-8 file with one article per line
######################################################... | [
"pandas.read_csv",
"re.findall",
"argparse.ArgumentParser"
] | [((549, 611), 'pandas.read_csv', 'pd.read_csv', (['args.input_file'], {'encoding': '"""utf-8"""', 'dtype': '"""string"""'}), "(args.input_file, encoding='utf-8', dtype='string')\n", (560, 611), True, 'import pandas as pd\n'), ((1382, 1492), 'argparse.ArgumentParser', 'argparse.ArgumentParser', ([], {'description': '"""... |
# Generated by Django 3.2.7 on 2021-09-20 13:31
from django.db import migrations
class Migration(migrations.Migration):
dependencies = [
('my_ip', '0004_alter_rating_table'),
]
operations = [
migrations.RenameField(
model_name='project',
old_name='image',
... | [
"django.db.migrations.RenameField"
] | [((225, 318), 'django.db.migrations.RenameField', 'migrations.RenameField', ([], {'model_name': '"""project"""', 'old_name': '"""image"""', 'new_name': '"""project_image"""'}), "(model_name='project', old_name='image', new_name=\n 'project_image')\n", (247, 318), False, 'from django.db import migrations\n')] |
from aoc2019.helpers.day04 import countValidPasswordsInRange, consecutiveDigitsRegex, exactlyTwoConsecutiveDigitsRegex
from aoc2019.shared.solution import Solution
class Day4(Solution):
def part1(self):
return countValidPasswordsInRange(
152085, 670283, consecutiveDigitsRegex)
def part2(s... | [
"aoc2019.helpers.day04.countValidPasswordsInRange"
] | [((224, 290), 'aoc2019.helpers.day04.countValidPasswordsInRange', 'countValidPasswordsInRange', (['(152085)', '(670283)', 'consecutiveDigitsRegex'], {}), '(152085, 670283, consecutiveDigitsRegex)\n', (250, 290), False, 'from aoc2019.helpers.day04 import countValidPasswordsInRange, consecutiveDigitsRegex, exactlyTwoCons... |
# Load libraries
import matplotlib.pyplot as plt
import pandas as pd
import pickle
import numpy as np
import os
from keras.applications.resnet50 import ResNet50
from keras.optimizers import Adam
from keras.layers import Dense, Flatten,Input, Convolution2D, Dropout, LSTM, TimeDistributed, Embedding, Bidirectiona... | [
"numpy.load",
"pickle.dump",
"numpy.argmax",
"pandas.read_csv",
"keras.preprocessing.sequence.pad_sequences",
"keras.models.Model",
"IPython.core.display.HTML",
"keras.preprocessing.image.img_to_array",
"pickle.load",
"keras.preprocessing.image.load_img",
"numpy.save",
"IPython.core.display.di... | [((564, 605), 'os.listdir', 'os.listdir', (['"""D:\\\\FBAi\\\\data\\\\Flickr_Data"""'], {}), "('D:\\\\FBAi\\\\data\\\\Flickr_Data')\n", (574, 605), False, 'import os\n'), ((1624, 1661), 'IPython.display.Image', 'Image', ([], {'filename': '(images_path + temp[0])'}), '(filename=images_path + temp[0])\n', (1629, 1661), F... |
'''
File: message_dispatcher.py
Description: Message dispatch handler
Date: 29/09/2017
Author: <NAME> <<EMAIL>>
'''
from structures import Message, MessagePacket, MessageQueue
class MessageDispatcher(object):
"""Handle the dispatch of the message from the bolt server
Registers new messages for the dispatch ha... | [
"structures.MessageQueue",
"structures.MessagePacket",
"structures.Message"
] | [((854, 863), 'structures.Message', 'Message', ([], {}), '()\n', (861, 863), False, 'from structures import Message, MessagePacket, MessageQueue\n'), ((932, 946), 'structures.MessageQueue', 'MessageQueue', ([], {}), '()\n', (944, 946), False, 'from structures import Message, MessagePacket, MessageQueue\n'), ((3397, 342... |
#!/usr/bin/env python
# coding: utf-8
# # Buscador
#
# Esse notebook implementa um buscador simples.
# A representação pra cada texto é criada a partir da TF-IDF.
# A representação da query (consulta, ou termos buscados)
# é construída a partir do vocabulário dos textos.
# O ranqueamento dos resultados é feito de acor... | [
"sklearn.feature_extraction.text.CountVectorizer",
"sklearn.metrics.pairwise.cosine_similarity",
"pandas.read_json",
"numpy.argsort",
"scripts.nlp.remove_portuguese_stopwords",
"sklearn.feature_extraction.text.TfidfTransformer"
] | [((1247, 1272), 'pandas.read_json', 'pd.read_json', (['"""leis.json"""'], {}), "('leis.json')\n", (1259, 1272), True, 'import pandas as pd\n'), ((2097, 2114), 'sklearn.feature_extraction.text.CountVectorizer', 'CountVectorizer', ([], {}), '()\n', (2112, 2114), False, 'from sklearn.feature_extraction.text import CountVe... |
# -*- coding: utf-8 -*-
import os
import numpy as np
import subprocess as subp
from sklearn.datasets import load_iris
from sklearn.datasets import load_breast_cancer
from sklearn.datasets import load_digits
from sklearn.utils import shuffle
from tests.utils.Timer import Timer
from tests.estimator.classifier.Separate... | [
"sklearn.datasets.load_iris",
"sklearn.datasets.load_digits",
"numpy.random.seed",
"sklearn.datasets.load_breast_cancer",
"os.environ.get",
"subprocess.call",
"sklearn.utils.shuffle"
] | [((484, 501), 'numpy.random.seed', 'np.random.seed', (['(5)'], {}), '(5)\n', (498, 501), True, 'import numpy as np\n'), ((1007, 1027), 'sklearn.datasets.load_breast_cancer', 'load_breast_cancer', ([], {}), '()\n', (1025, 1027), False, 'from sklearn.datasets import load_breast_cancer\n'), ((1275, 1286), 'sklearn.dataset... |
import cv2 as cv
capture = cv.VideoCapture('opencv_practicas/VID_20200312_162550.mp4')
while True:
isTrue, frame = capture.read()
cv.imshow('video', frame)
if cv.waitKey(20) &0xFF==ord('d'):
break
capture.release()
cv.destroyAllWindows() | [
"cv2.VideoCapture",
"cv2.destroyAllWindows",
"cv2.imshow",
"cv2.waitKey"
] | [((28, 87), 'cv2.VideoCapture', 'cv.VideoCapture', (['"""opencv_practicas/VID_20200312_162550.mp4"""'], {}), "('opencv_practicas/VID_20200312_162550.mp4')\n", (43, 87), True, 'import cv2 as cv\n'), ((241, 263), 'cv2.destroyAllWindows', 'cv.destroyAllWindows', ([], {}), '()\n', (261, 263), True, 'import cv2 as cv\n'), (... |
import preprocess_directory
import unittest
FIXTURES_DIRECTORY_PATH = "Fixtures"
class TestGetImages(unittest.TestCase):
"""
Class for test function below for the get_all_images function from the preprocess_directory.py file
"""
def test_check_file(self):
"""
Test for the get_all_images... | [
"unittest.main",
"preprocess_directory.get_all_images"
] | [((617, 632), 'unittest.main', 'unittest.main', ([], {}), '()\n', (630, 632), False, 'import unittest\n'), ((432, 492), 'preprocess_directory.get_all_images', 'preprocess_directory.get_all_images', (['FIXTURES_DIRECTORY_PATH'], {}), '(FIXTURES_DIRECTORY_PATH)\n', (467, 492), False, 'import preprocess_directory\n')] |
import logging
import requests
import json
import azure.functions as func
def main(req: func.HttpRequest, config: str) -> func.HttpResponse:
configuration = json.loads(config)
response = requests.get(configuration["websiteUrl"])
logging.info("%s -> %s" % (response.url, response.reason))
return... | [
"azure.functions.HttpResponse",
"logging.info",
"json.loads",
"requests.get"
] | [((168, 186), 'json.loads', 'json.loads', (['config'], {}), '(config)\n', (178, 186), False, 'import json\n'), ((203, 244), 'requests.get', 'requests.get', (["configuration['websiteUrl']"], {}), "(configuration['websiteUrl'])\n", (215, 244), False, 'import requests\n'), ((250, 308), 'logging.info', 'logging.info', (["(... |
"""Urls for the Zinnia comments"""
from django.conf.urls import url
from zinnia.urls import _
from zinnia.views.comments import CommentSuccess
urlpatterns = [
url(_(r'^success/$'),
CommentSuccess.as_view(),
name='comment_success'),
]
| [
"zinnia.urls._",
"zinnia.views.comments.CommentSuccess.as_view"
] | [((170, 185), 'zinnia.urls._', '_', (['"""^success/$"""'], {}), "('^success/$')\n", (171, 185), False, 'from zinnia.urls import _\n'), ((196, 220), 'zinnia.views.comments.CommentSuccess.as_view', 'CommentSuccess.as_view', ([], {}), '()\n', (218, 220), False, 'from zinnia.views.comments import CommentSuccess\n')] |
'''
Defines database models.
'''
from flask_login import UserMixin
from flask_sqlalchemy import SQLAlchemy
from sqlalchemy.sql import func
from hashids import Hashids
import bcrypt
from blog.helpers import is_username, is_email, is_password, in_database
from blog import app
db = SQLAlchemy(app)
class User(db.Model... | [
"blog.helpers.in_database",
"sqlalchemy.sql.func.now",
"bcrypt.gensalt",
"blog.helpers.is_email",
"hashids.Hashids",
"flask_sqlalchemy.SQLAlchemy",
"blog.helpers.is_username",
"blog.helpers.is_password"
] | [((283, 298), 'flask_sqlalchemy.SQLAlchemy', 'SQLAlchemy', (['app'], {}), '(app)\n', (293, 298), False, 'from flask_sqlalchemy import SQLAlchemy\n'), ((3467, 3519), 'hashids.Hashids', 'Hashids', ([], {'min_length': '(5)', 'salt': "app.config['SECRET_KEY']"}), "(min_length=5, salt=app.config['SECRET_KEY'])\n", (3474, 35... |
import datetime
from .stwno_constants import CSV_MEAL_TYPE_MAP,\
CSV_NUTRITION_TYPE_MAP,\
NutritionType,\
CSV_DATE_FORMAT,\
MealType,\
NutritionType,\
STWNO_INGREDIENTS,\
STWNO_ALLERGENS
class NoValidDateStringException(Exception):
pass
class UnknownMealTypeException(Exception):
... | [
"datetime.datetime.strptime"
] | [((1419, 1471), 'datetime.datetime.strptime', 'datetime.datetime.strptime', (['dateStr', 'CSV_DATE_FORMAT'], {}), '(dateStr, CSV_DATE_FORMAT)\n', (1445, 1471), False, 'import datetime\n')] |
#!/usr/bin/env python3
"""Tool for plotting the Voronoi tessellation described by the provided data
Note that the seeds of the tessellation are based on the provided towers file,
not computed from the cells. The tool also prints to the console the number
of towers and number of cells. Towers without an associated cel... | [
"descartes.PolygonPatch",
"data_interface.load_voronoi_cells",
"matplotlib.pyplot.show",
"matplotlib.pyplot.ioff",
"data_interface.load_towers",
"matplotlib.pyplot.figure"
] | [((890, 966), 'descartes.PolygonPatch', 'PolygonPatch', (['polygon'], {'facecolor': '[0, 0, 0.5]', 'edgecolor': '[0, 0, 0]', 'alpha': '(0.5)'}), '(polygon, facecolor=[0, 0, 0.5], edgecolor=[0, 0, 0], alpha=0.5)\n', (902, 966), False, 'from descartes import PolygonPatch\n'), ((1101, 1133), 'data_interface.load_voronoi_c... |
from setuptools import setup
setup(name = 'infupy',
version = '2022.1.11',
description = 'Syringe pump infusion',
url = 'https://github.com/jaj42/infupy',
author = '<NAME>',
author_email = '<EMAIL>',
license = 'ISC',
packages = ['infupy', ... | [
"setuptools.setup"
] | [((30, 354), 'setuptools.setup', 'setup', ([], {'name': '"""infupy"""', 'version': '"""2022.1.11"""', 'description': '"""Syringe pump infusion"""', 'url': '"""https://github.com/jaj42/infupy"""', 'author': '"""<NAME>"""', 'author_email': '"""<EMAIL>"""', 'license': '"""ISC"""', 'packages': "['infupy', 'infupy.backends'... |
#!/usr/bin/env python
# -*- coding: utf-8 -*-
from __future__ import unicode_literals, division, print_function, absolute_import
import sys
import platform
import argparse
import os
from pyt import tester, __version__, main
from pyt.compat import *
def console():
# ripped from unittest.__main__.py
if sys.arg... | [
"pyt.main",
"os.path.basename"
] | [((553, 570), 'pyt.main', 'main', ([], {'module': 'None'}), '(module=None)\n', (557, 570), False, 'from pyt import tester, __version__, main\n'), ((371, 403), 'os.path.basename', 'os.path.basename', (['sys.executable'], {}), '(sys.executable)\n', (387, 403), False, 'import os\n')] |
"""
Capacity estimation method.
Written by <NAME>
December 12th 2019
This method can be used for any spatially aggregated unit, such as
postcode sectors or local authority districts. First, a points in
polygon analysis needs to provide the total number of 4G or 5G sites
in an area, in order to then get the density o... | [
"csv.DictReader",
"os.path.dirname",
"itertools.tee",
"configparser.ConfigParser",
"os.path.join"
] | [((523, 550), 'configparser.ConfigParser', 'configparser.ConfigParser', ([], {}), '()\n', (548, 550), False, 'import configparser\n'), ((687, 717), 'os.path.join', 'os.path.join', (['BASE_PATH', '"""raw"""'], {}), "(BASE_PATH, 'raw')\n", (699, 717), False, 'import os\n'), ((738, 777), 'os.path.join', 'os.path.join', ([... |
import serial
import struct
rf_channel_list = [b"\x01", b"\x02", b"\x03", b"\x04"]
def send_rf_command(config_class, channel, is_study = False):
ser = serial.Serial(
port = config_class.tty,
baudrate = 9600,
parity = serial.PARITY_NONE,
stopbits = serial.STOPBITS_ONE,
bytes... | [
"serial.Serial"
] | [((157, 297), 'serial.Serial', 'serial.Serial', ([], {'port': 'config_class.tty', 'baudrate': '(9600)', 'parity': 'serial.PARITY_NONE', 'stopbits': 'serial.STOPBITS_ONE', 'bytesize': 'serial.EIGHTBITS'}), '(port=config_class.tty, baudrate=9600, parity=serial.\n PARITY_NONE, stopbits=serial.STOPBITS_ONE, bytesize=ser... |
# Generated by the gRPC Python protocol compiler plugin. DO NOT EDIT!
"""Client and server classes corresponding to protobuf-defined services."""
import grpc
from google.protobuf import empty_pb2 as google_dot_protobuf_dot_empty__pb2
import test_evocraft_py.minecraft_pb2 as minecraft__pb2
class MinecraftServiceStub(... | [
"grpc.method_handlers_generic_handler",
"grpc.unary_unary_rpc_method_handler",
"grpc.experimental.unary_unary"
] | [((3232, 3329), 'grpc.method_handlers_generic_handler', 'grpc.method_handlers_generic_handler', (['"""dk.itu.real.ooe.MinecraftService"""', 'rpc_method_handlers'], {}), "('dk.itu.real.ooe.MinecraftService',\n rpc_method_handlers)\n", (3268, 3329), False, 'import grpc\n'), ((2367, 2572), 'grpc.unary_unary_rpc_method_... |
# SORTEANDO UMA ORDEM NA LISTA
# O mesmo professor do ex 19 quer sortear a ordem de apresentação de trabalhos dos alunos. Faça um programa que leia o nome dos quatro alunos e mostre a ordem sorteada.
from random import sample, choice
a1 = input('Digite o nome do primeiro aluno: ')
a2 = input('Digite o nome do segund... | [
"random.sample"
] | [((504, 522), 'random.sample', 'sample', (['lista'], {'k': '(4)'}), '(lista, k=4)\n', (510, 522), False, 'from random import sample, choice\n')] |
from tests.cli import commands
from click.testing import CliRunner
def test_get_not_found():
"""
Executes the kv get <key> command. The key does not exist yet so it
returns the Key Doesn't exist message and status_code. It validates
the output.
"""
runner = CliRunner()
result = runner.invo... | [
"click.testing.CliRunner"
] | [((284, 295), 'click.testing.CliRunner', 'CliRunner', ([], {}), '()\n', (293, 295), False, 'from click.testing import CliRunner\n'), ((734, 745), 'click.testing.CliRunner', 'CliRunner', ([], {}), '()\n', (743, 745), False, 'from click.testing import CliRunner\n'), ((1114, 1125), 'click.testing.CliRunner', 'CliRunner', ... |
import os
import hashlib
import secrets
from django.db import models
from django.core.cache import cache
from django.db.models.signals import pre_save, pre_delete, post_migrate
from django.conf import settings
from django.contrib.auth.models import User
from django.contrib.postgres.fields import JSONField, ArrayField
... | [
"django.db.models.signals.pre_save.connect",
"django.db.models.signals.post_migrate.connect",
"hashlib.md5",
"django.db.models.CharField",
"django.db.models.ForeignKey",
"secrets.token_hex",
"django.db.models.BooleanField",
"django.db.models.signals.pre_delete.connect",
"django.contrib.postgres.fiel... | [((4827, 4876), 'django.db.models.signals.pre_save.connect', 'pre_save.connect', (['clear_txn_caches'], {'sender': 'Ledger'}), '(clear_txn_caches, sender=Ledger)\n', (4843, 4876), False, 'from django.db.models.signals import pre_save, pre_delete, post_migrate\n'), ((4877, 4931), 'django.db.models.signals.pre_save.conne... |
"""Unit test for keytabs
"""
from __future__ import absolute_import
from __future__ import division
from __future__ import print_function
from __future__ import unicode_literals
import io
import os
import shutil
import tempfile
import unittest
import mock
from treadmill import keytabs
class KeytabsTest(unittest.T... | [
"unittest.main",
"treadmill.keytabs.add_keytabs_to_file",
"mock.patch",
"tempfile.mkdtemp",
"shutil.rmtree",
"os.path.join"
] | [((616, 658), 'mock.patch', 'mock.patch', (['"""treadmill.subproc.check_call"""'], {}), "('treadmill.subproc.check_call')\n", (626, 658), False, 'import mock\n'), ((1735, 1750), 'unittest.main', 'unittest.main', ([], {}), '()\n', (1748, 1750), False, 'import unittest\n'), ((414, 432), 'tempfile.mkdtemp', 'tempfile.mkdt... |
"""
The MIT License (MIT)
Copyright (c) 2015 <NAME>
Permission is hereby granted, free of charge, to any person obtaining a copy
of this software and associated documentation files (the "Software"), to deal
in the Software without restriction, including without limitation the rights
to use, copy, modify, merge, publi... | [
"os.getcwd",
"subprocess.call",
"os.chdir",
"urllib.request.urlopen"
] | [((2342, 2403), 'subprocess.call', 'subprocess.call', (["['git', 'clone', repo.clone_url, repo.title]"], {}), "(['git', 'clone', repo.clone_url, repo.title])\n", (2357, 2403), False, 'import subprocess\n'), ((2445, 2456), 'os.getcwd', 'os.getcwd', ([], {}), '()\n', (2454, 2456), False, 'import os\n'), ((2466, 2485), 'o... |
from django.contrib import admin
# Register your models here.
from .models import Payment, ContractFile, Company, Contractor
@admin.register(Company)
class Company(admin.ModelAdmin):
list_display = (
'name',
)
@admin.register(Contractor)
class Contractor(admin.ModelAdmin):
list_display = (
... | [
"django.contrib.admin.register"
] | [((130, 153), 'django.contrib.admin.register', 'admin.register', (['Company'], {}), '(Company)\n', (144, 153), False, 'from django.contrib import admin\n'), ((233, 259), 'django.contrib.admin.register', 'admin.register', (['Contractor'], {}), '(Contractor)\n', (247, 259), False, 'from django.contrib import admin\n')] |
import asyncio
import inspect
import logging
from abc import ABC, abstractclassmethod
from collections import defaultdict
from typing import Callable, Set, Type, Dict, List, Union
from json import JSONEncoder
class Exploit(ABC):
@abstractclassmethod
def generate_payload(command: str) -> Union[str, List[str]]:... | [
"collections.defaultdict",
"asyncio.set_event_loop",
"inspect.isabstract",
"asyncio.new_event_loop"
] | [((1573, 1590), 'collections.defaultdict', 'defaultdict', (['list'], {}), '(list)\n', (1584, 1590), False, 'from collections import defaultdict\n'), ((948, 972), 'asyncio.new_event_loop', 'asyncio.new_event_loop', ([], {}), '()\n', (970, 972), False, 'import asyncio\n'), ((981, 1014), 'asyncio.set_event_loop', 'asyncio... |
import os
from google_search import GoogleCustomSearch
#set variables
os.environ["SEARCH_ENGINE_ID"] = "000839040200690289140:u2lurwk5tko"
os.environ["GOOGLE_CLOUD_API_KEY"] = "<KEY>"
SEARCH_ENGINE_ID = os.environ['SEARCH_ENGINE_ID']
API_KEY = os.environ['GOOGLE_CLOUD_API_KEY']
api = Googl... | [
"google_search.GoogleCustomSearch"
] | [((315, 360), 'google_search.GoogleCustomSearch', 'GoogleCustomSearch', (['SEARCH_ENGINE_ID', 'API_KEY'], {}), '(SEARCH_ENGINE_ID, API_KEY)\n', (333, 360), False, 'from google_search import GoogleCustomSearch\n')] |
# Import needed libraries
import discord
import os
import pymongo
import pendulum
import requests
import re
if os.path.exists("env.py"):
import env
# Define Environment Variables
MONGO_DBNAME = os.environ.get("MONGO_DBNAME")
MONGO_URI = os.environ.get("MONGO_URI")
MONGO_CONN = pymongo.MongoClient(MONGO_URI)
MON... | [
"pymongo.MongoClient",
"discord.Embed",
"os.path.exists",
"os.environ.get",
"pendulum.today",
"requests.get",
"re.compile"
] | [((112, 136), 'os.path.exists', 'os.path.exists', (['"""env.py"""'], {}), "('env.py')\n", (126, 136), False, 'import os\n'), ((202, 232), 'os.environ.get', 'os.environ.get', (['"""MONGO_DBNAME"""'], {}), "('MONGO_DBNAME')\n", (216, 232), False, 'import os\n'), ((245, 272), 'os.environ.get', 'os.environ.get', (['"""MONG... |
import os, shutil
from setuptools import setup, find_packages
#
CUR_PATH = os.path.dirname(os.path.abspath(__file__))
path = os.path.join(CUR_PATH, 'build')
if os.path.isdir(path):
print('INFO del dir ', path)
shutil.rmtree(path)
setup(
name = 'pipeline',
# Author details
author='JiejunHuo',
... | [
"os.path.abspath",
"os.path.isdir",
"shutil.rmtree",
"os.path.join",
"setuptools.find_packages"
] | [((126, 157), 'os.path.join', 'os.path.join', (['CUR_PATH', '"""build"""'], {}), "(CUR_PATH, 'build')\n", (138, 157), False, 'import os, shutil\n'), ((161, 180), 'os.path.isdir', 'os.path.isdir', (['path'], {}), '(path)\n', (174, 180), False, 'import os, shutil\n'), ((92, 117), 'os.path.abspath', 'os.path.abspath', (['... |
import matplotlib.pyplot as plt
import pandas as pd
from scipy.interpolate import make_interp_spline, BSpline
import numpy as np
def plot_results(title, csv_name):
df = pd.read_csv('../' + csv_name + '.csv')
ax = plt.gca()
df.columns = ['V', 'E', 'Time']
df = df[['V', 'Time']]
df = pd.DataFrame(df.groupby('V').m... | [
"pandas.read_csv",
"matplotlib.pyplot.savefig",
"matplotlib.pyplot.plot",
"matplotlib.pyplot.gca"
] | [((171, 209), 'pandas.read_csv', 'pd.read_csv', (["('../' + csv_name + '.csv')"], {}), "('../' + csv_name + '.csv')\n", (182, 209), True, 'import pandas as pd\n'), ((216, 225), 'matplotlib.pyplot.gca', 'plt.gca', ([], {}), '()\n', (223, 225), True, 'import matplotlib.pyplot as plt\n'), ((782, 815), 'matplotlib.pyplot.p... |
import argparse
import os
import shutil
import json
import numpy as np
import torch
import torch.nn as nn
import matplotlib.pyplot as plt
from dense_estimation.resnet import resnet50
from dense_estimation.output import GaussianScaleMixtureOutput, PowerExponentialOutput
from dense_estimation.losses import (BerHuLoss, ... | [
"argparse.ArgumentParser",
"torch.var",
"torch.cat",
"matplotlib.pyplot.figure",
"dense_estimation.losses.Log10Loss",
"dense_estimation.output.PowerExponentialOutput",
"torch.load",
"dense_estimation.output.GaussianScaleMixtureOutput",
"dense_estimation.data.get_testing_loader",
"dense_estimation.... | [((841, 894), 'argparse.ArgumentParser', 'argparse.ArgumentParser', ([], {'description': '"""testing script"""'}), "(description='testing script')\n", (864, 894), False, 'import argparse\n'), ((1965, 2053), 'dense_estimation.data.get_testing_loader', 'get_testing_loader', (['NYU_Depth_V2', 'raw_root', '(1)', 'transf_si... |
import sys, os
sys.path.append("..")
import helper as h
from constants import SINC
import numpy as np
import matplotlib.pyplot as plt
eigengrid = h.r_window_to_matrix_eig(SINC) # h.window_pad_to_box_rfft(SINC,pad_factor=10.0)
eigengrid_hann = h.r_window_to_matrix_eig(SINC * np.hanning(len(SINC)))
eigengrid_hamm = h.r_... | [
"sys.path.append",
"matplotlib.pyplot.subplot",
"matplotlib.pyplot.title",
"matplotlib.pyplot.tight_layout",
"matplotlib.pyplot.show",
"matplotlib.pyplot.suptitle",
"matplotlib.pyplot.legend",
"helper.r_window_to_matrix_eig",
"matplotlib.pyplot.ylabel",
"matplotlib.pyplot.xlabel",
"matplotlib.py... | [((15, 36), 'sys.path.append', 'sys.path.append', (['""".."""'], {}), "('..')\n", (30, 36), False, 'import sys, os\n'), ((147, 177), 'helper.r_window_to_matrix_eig', 'h.r_window_to_matrix_eig', (['SINC'], {}), '(SINC)\n', (171, 177), True, 'import helper as h\n'), ((413, 433), 'matplotlib.pyplot.show', 'plt.show', ([],... |
import networkx as nx
import os
from diagram import Diagram
from spf import spf
class tilfa:
"""This class provides draft-ietf-rtgwg-segment-routing-ti-lfa TI-LFA calculations"""
def __init__(self, debug=0, ep_space=True, trombone=False):
"""
Init the TI-LFA class.
:param int debug:... | [
"os.path.join",
"diagram.Diagram",
"spf.spf"
] | [((643, 659), 'diagram.Diagram', 'Diagram', ([], {'debug': '(2)'}), '(debug=2)\n', (650, 659), False, 'from diagram import Diagram\n'), ((769, 790), 'spf.spf', 'spf', ([], {'debug': 'self.debug'}), '(debug=self.debug)\n', (772, 790), False, 'from spf import spf\n'), ((5838, 5874), 'os.path.join', 'os.path.join', (['out... |
from __future__ import print_function
import logging
import traceback
import sys
logger = logging.getLogger(__name__)
class NoSuchModule(object):
def __init__(self, name):
self.__name = name
self.__traceback_str = traceback.format_tb(sys.exc_info()[2])
errtype, value = sys.exc_info()[:2]... | [
"logging.getLogger",
"sys.exc_info"
] | [((92, 119), 'logging.getLogger', 'logging.getLogger', (['__name__'], {}), '(__name__)\n', (109, 119), False, 'import logging\n'), ((302, 316), 'sys.exc_info', 'sys.exc_info', ([], {}), '()\n', (314, 316), False, 'import sys\n'), ((258, 272), 'sys.exc_info', 'sys.exc_info', ([], {}), '()\n', (270, 272), False, 'import ... |
import numpy as np
from PIL import Image
from paillier import *
import sys
from matplotlib import pyplot as plt
class bcolors:
HEADER = '\033[95m'
OKBLUE = '\033[94m'
OKCYAN = '\033[96m'
OKGREEN = '\033[92m'
WARNING = '\033[93m'
FAIL = '\033[91m'
ENDC = '\033[0m'
BOLD = '\033[1m'
UNDERLINE = '\033[4m'
cl... | [
"matplotlib.pyplot.title",
"matplotlib.pyplot.show",
"matplotlib.pyplot.imshow",
"matplotlib.pyplot.axis",
"matplotlib.pyplot.figure"
] | [((2081, 2108), 'matplotlib.pyplot.figure', 'plt.figure', ([], {'figsize': '(10, 7)'}), '(figsize=(10, 7))\n', (2091, 2108), True, 'from matplotlib import pyplot as plt\n'), ((2256, 2271), 'matplotlib.pyplot.axis', 'plt.axis', (['"""off"""'], {}), "('off')\n", (2264, 2271), True, 'from matplotlib import pyplot as plt\n... |
import os
import matplotlib.image as mpimg
import matplotlib.pyplot as plt
import tensorflow as tf
from tensorflow.python import keras
from tensorflow.python.keras.preprocessing.image import ImageDataGenerator
from tensorflow.python.keras.preprocessing.text import Tokenizer
from keras.utils import to_categorical
from t... | [
"matplotlib.pyplot.subplot",
"tensorflow.python.keras.preprocessing.image.ImageDataGenerator",
"matplotlib.image.imread",
"tensorflow.keras.layers.Conv2D",
"tensorflow.keras.layers.MaxPooling2D",
"tensorflow.keras.layers.Dense",
"matplotlib.pyplot.gcf",
"os.path.join",
"os.listdir",
"tensorflow.ke... | [((694, 725), 'os.path.join', 'os.path.join', (['base_dir', '"""train"""'], {}), "(base_dir, 'train')\n", (706, 725), False, 'import os\n'), ((743, 779), 'os.path.join', 'os.path.join', (['base_dir', '"""validation"""'], {}), "(base_dir, 'validation')\n", (755, 779), False, 'import os\n'), ((845, 876), 'os.path.join', ... |
import tkinter as tk
def int_validate(entry_widget, from_=None, to=None):
"""
Validates an entry_widget so that only integers within a specified range may be entered
:param entry_widget: The tkinter.Entry widget to validate
:param from_: The start limit of the integer
:param to: The end limit of ... | [
"tkinter.Tk",
"tkinter.ttk.Spinbox"
] | [((4447, 4454), 'tkinter.Tk', 'tk.Tk', ([], {}), '()\n', (4452, 4454), True, 'import tkinter as tk\n'), ((4468, 4522), 'tkinter.ttk.Spinbox', 'ttk.Spinbox', (['root'], {'justify': 'tk.CENTER', 'from_': '(-5)', 'to_': '(10)'}), '(root, justify=tk.CENTER, from_=-5, to_=10)\n', (4479, 4522), False, 'from tkinter import tt... |
# Modules
import subprocess
from os import name
from ..utils.bases import BaseCommand
# Command class
class Clear(BaseCommand):
def __init__(self, core):
self.core = core
def clear(self, arguments):
# Locate our command
command = "clear"
if name == "nt":
command =... | [
"subprocess.run"
] | [((354, 391), 'subprocess.run', 'subprocess.run', (['[command]'], {'shell': '(True)'}), '([command], shell=True)\n', (368, 391), False, 'import subprocess\n')] |
# -*- coding: utf-8 -*-
# standard library
from unittest.mock import Mock
__author__ = "Ssu-Tsen"
__license__ = "Apache 2.0"
# standard library
# scip plugin
from ribbon.client.config.client_config import ClientConfig
from spring_cloud.ribbon.spring_client_factory import DynamicServerListLoadBalancer, SpringClientFa... | [
"unittest.mock.Mock",
"spring_cloud.ribbon.spring_client_factory.SpringClientFactory"
] | [((379, 385), 'unittest.mock.Mock', 'Mock', ([], {}), '()\n', (383, 385), False, 'from unittest.mock import Mock\n'), ((441, 462), 'unittest.mock.Mock', 'Mock', ([], {'return_value': '[]'}), '(return_value=[])\n', (445, 462), False, 'from unittest.mock import Mock\n'), ((491, 525), 'spring_cloud.ribbon.spring_client_fa... |
#!/usr/bin/env python
from rich.progress import track
from rich import print
from rich.progress import Progress
from rich.table import Column
from rich.progress import Progress, BarColumn, TextColumn,TimeRemainingColumn,SpinnerColumn,TimeElapsedColumn
from rich.console import Console
filename="big.fa"
seqCount=0
num_... | [
"rich.progress.TextColumn",
"rich.print",
"rich.progress.BarColumn",
"rich.progress.SpinnerColumn",
"rich.console.Console",
"rich.progress.TimeRemainingColumn",
"rich.progress.TimeElapsedColumn"
] | [((366, 396), 'rich.print', 'print', (['"""num_lines:"""', 'num_lines'], {}), "('num_lines:', num_lines)\n", (371, 396), False, 'from rich import print\n'), ((407, 427), 'rich.console.Console', 'Console', ([], {'record': '(True)'}), '(record=True)\n', (414, 427), False, 'from rich.console import Console\n'), ((448, 463... |
import dataclasses
import pathlib
import subprocess
from typing import DefaultDict, List, Sequence
import dacite
from pysen.command import CommandBase
from pysen.component import ComponentBase, RunOptions
from pysen.path import change_dir
from pysen.plugin import PluginBase
from pysen.pyproject_model import Config, P... | [
"dacite.Config",
"pysen.path.change_dir",
"subprocess.run"
] | [((790, 816), 'pysen.path.change_dir', 'change_dir', (['self._base_dir'], {}), '(self._base_dir)\n', (800, 816), False, 'from pysen.path import change_dir\n'), ((2434, 2460), 'dacite.Config', 'dacite.Config', ([], {'strict': '(True)'}), '(strict=True)\n', (2447, 2460), False, 'import dacite\n'), ((857, 882), 'subproces... |
from __future__ import absolute_import
from nightson.managers.base_entity_manager import BaseEntityManager
from tornado import gen
class EventUsersManager(BaseEntityManager):
def __init__(self):
pass
def __init__(self, request):
super(EventUsersManager, self).__init__(request)
@gen.cor... | [
"tornado.gen.Return"
] | [((863, 881), 'tornado.gen.Return', 'gen.Return', (['result'], {}), '(result)\n', (873, 881), False, 'from tornado import gen\n')] |
"""
###########################################################################
# @file optimization_utils.py
# @brief Functions for optimizing transformations and parameters.
#
# @author <NAME>
#
# @Link: https://www.cbica.upenn.edu/sbia/software/
#
# @Contact: <EMAIL>
#################################################... | [
"numpy.random.uniform",
"Mstep_trans.solve_delta",
"numpy.random.seed",
"numpy.log",
"numpy.eye",
"Mstep_trans.solve_T",
"numpy.sum",
"Mstep_trans.solve_sigsq",
"numpy.power",
"numpy.zeros",
"numpy.ones",
"numpy.transpose",
"numpy.finfo",
"numpy.linalg.norm",
"numpy.exp",
"Mstep_trans.... | [((435, 451), 'numpy.random.seed', 'np.random.seed', ([], {}), '()\n', (449, 451), True, 'import numpy as np\n'), ((832, 862), 'numpy.random.uniform', 'np.random.uniform', ([], {'size': '(D, K)'}), '(size=(D, K))\n', (849, 862), True, 'import numpy as np\n'), ((1040, 1056), 'numpy.zeros', 'np.zeros', (['(D, M)'], {}), ... |
from pwn import *
from LibcSearcher import LibcSearcher
############################
#********修改文件名**********
############################
file_name = 'babyrop2'
port = 27150
io = -1
###########修改宏###########
DEBUG = 1
LOG_PRINT = 1
TMUX = 0
def LOG_ADDR_SUCCESS(name:str, addr:int):
'''
打印地址
name: 变量名,str... | [
"LibcSearcher.LibcSearcher"
] | [((2041, 2096), 'LibcSearcher.LibcSearcher', 'LibcSearcher', (['"""__libc_start_main"""', 'libc_start_main_addr'], {}), "('__libc_start_main', libc_start_main_addr)\n", (2053, 2096), False, 'from LibcSearcher import LibcSearcher\n')] |
import io
import json
import math
import random
import time
import traceback
from datetime import datetime
import aiofiles
import discord
import sanic
import sanic.response
from PIL import Image
from discord.ext import commands
from modules import leaks
async def handler(req):
return sanic.response.json(json.lo... | [
"io.BytesIO",
"aiofiles.open",
"modules.leaks.GenerateCard",
"PIL.Image.open",
"json.dumps",
"time.time",
"datetime.datetime.utcnow"
] | [((586, 597), 'time.time', 'time.time', ([], {}), '()\n', (595, 597), False, 'import time\n'), ((1787, 1799), 'io.BytesIO', 'io.BytesIO', ([], {}), '()\n', (1797, 1799), False, 'import io\n'), ((1689, 1700), 'time.time', 'time.time', ([], {}), '()\n', (1698, 1700), False, 'import time\n'), ((546, 572), 'json.dumps', 'j... |
#!/usr/bin/env python
from __future__ import (
absolute_import,
division,
print_function,
unicode_literals,
)
import unittest
import dlint
class TestBadSysUse(dlint.test.base.BaseTest):
def test_bad_sys_usage(self):
python_string = self.get_ast_node(
"""
import ... | [
"unittest.main",
"dlint.linters.base.Flake8Result",
"dlint.linters.BadSysUseLinter"
] | [((1242, 1257), 'unittest.main', 'unittest.main', ([], {}), '()\n', (1255, 1257), False, 'import unittest\n'), ((490, 521), 'dlint.linters.BadSysUseLinter', 'dlint.linters.BadSysUseLinter', ([], {}), '()\n', (519, 521), False, 'import dlint\n'), ((630, 741), 'dlint.linters.base.Flake8Result', 'dlint.linters.base.Flake8... |
#!/usr/bin/env python
"""Wrapper script with bsub functionality."""
from __future__ import print_function
import sys
import os
import shlex
import argparse
from submitjob import submitjob
from utility import color
def esub(args, bsubargs, jobscript):
"""Wrapper script with bsub functionality."""
data = {"c... | [
"sys.stdin.read",
"argparse.ArgumentParser",
"utility.color",
"submitjob.submitjob",
"sys.exit"
] | [((1340, 1396), 'argparse.ArgumentParser', 'argparse.ArgumentParser', ([], {'description': '"""Wrapper for bsub."""'}), "(description='Wrapper for bsub.')\n", (1363, 1396), False, 'import argparse\n'), ((1591, 1607), 'sys.stdin.read', 'sys.stdin.read', ([], {}), '()\n', (1605, 1607), False, 'import sys\n'), ((1154, 116... |
import argparse
import numpy as np
import models
from utils import set_arch_name
model_names = sorted(name for name in models.__dict__
if name.islower() and not name.startswith("__")
and callable(models.__dict__[name]))
def config():
r"""configuration settings
"""
parser = argparse.ArgumentParser... | [
"utils.set_arch_name",
"argparse.ArgumentParser"
] | [((297, 358), 'argparse.ArgumentParser', 'argparse.ArgumentParser', ([], {'description': '"""Check model parameters"""'}), "(description='Check model parameters')\n", (320, 358), False, 'import argparse\n'), ((1605, 1623), 'utils.set_arch_name', 'set_arch_name', (['opt'], {}), '(opt)\n', (1618, 1623), False, 'from util... |
from django.shortcuts import render
from .models import InfoPage
# Create your views here.
def view_page(request, slug):
# Look up the slug.
page = InfoPage.objects.get(slug=slug)
page_data = {
"page": page
}
return render(request, 'infopages/view_page.html', page_data)
| [
"django.shortcuts.render"
] | [((244, 298), 'django.shortcuts.render', 'render', (['request', '"""infopages/view_page.html"""', 'page_data'], {}), "(request, 'infopages/view_page.html', page_data)\n", (250, 298), False, 'from django.shortcuts import render\n')] |
"""
This component launches a Batch Prediction job on Vertex AI.
Know more about Vertex AI Batch Predictions jobs, go here:
https://cloud.google.com/vertex-ai/docs/predictions/batch-predictions.
"""
from google.cloud import storage
from tfx.dsl.component.experimental.annotations import Parameter, InputArtifact
from t... | [
"absl.logging.info",
"google.cloud.aiplatform.init",
"google.cloud.storage.Client",
"google.cloud.aiplatform.Model.list"
] | [((1235, 1251), 'google.cloud.storage.Client', 'storage.Client', ([], {}), '()\n', (1249, 1251), False, 'from google.cloud import storage\n'), ((1524, 1565), 'absl.logging.info', 'logging.info', (['f"""bucketname: {bucketname}"""'], {}), "(f'bucketname: {bucketname}')\n", (1536, 1565), False, 'from absl import logging\... |
# ----------------------------------------------------------------
# Copyright 2016 Cisco Systems
#
# 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/LICENS... | [
"logging.getLogger"
] | [((997, 1036), 'logging.getLogger', 'logging.getLogger', (['"""ydk.tests.unittest"""'], {}), "('ydk.tests.unittest')\n", (1014, 1036), False, 'import logging\n')] |
#!/usr/bin/env python3
import numpy as np
import matplotlib.pyplot as plt
m = 1e-3
i_load = np.logspace(-5,-3)
i_load = np.linspace(1e-5,1e-3,200)
i_s = 1e-12
i_ph = 1e-3
V_T = 1.38e-23*300/1.6e-19
V_D = V_T*np.log((i_ph - i_load)/(i_s) + 1)
P_load = V_D*i_load
plt.subplot(2,1,1)
plt.plot(i_load/m,V_D)
plt.yl... | [
"matplotlib.pyplot.subplot",
"matplotlib.pyplot.show",
"numpy.log",
"matplotlib.pyplot.plot",
"numpy.logspace",
"numpy.linspace",
"matplotlib.pyplot.ylabel",
"matplotlib.pyplot.xlabel",
"matplotlib.pyplot.grid",
"matplotlib.pyplot.savefig"
] | [((94, 113), 'numpy.logspace', 'np.logspace', (['(-5)', '(-3)'], {}), '(-5, -3)\n', (105, 113), True, 'import numpy as np\n'), ((122, 152), 'numpy.linspace', 'np.linspace', (['(1e-05)', '(0.001)', '(200)'], {}), '(1e-05, 0.001, 200)\n', (133, 152), True, 'import numpy as np\n'), ((271, 291), 'matplotlib.pyplot.subplot'... |
import argparse
from pathlib import Path
from novel_tools.toolkit import analyze, docgen
from novel_tools.utils import get_config
def do_analyze(args):
config_filename = args.toolkit + '_config.json'
input_path = Path(args.input)
output_path = Path(args.output) if args.output is not None else None
if ... | [
"argparse.ArgumentParser",
"novel_tools.toolkit.docgen",
"novel_tools.utils.get_config",
"novel_tools.toolkit.analyze",
"pathlib.Path"
] | [((223, 239), 'pathlib.Path', 'Path', (['args.input'], {}), '(args.input)\n', (227, 239), False, 'from pathlib import Path\n'), ((655, 729), 'argparse.ArgumentParser', 'argparse.ArgumentParser', ([], {'description': '"""Novel Tools command line interface."""'}), "(description='Novel Tools command line interface.')\n", ... |
from itertools import combinations
def get_data(filepath):
return [int(line) for line in open(filepath).readlines()]
def solve1(filepath, preamble):
inputs = get_data(filepath)
for i, line in enumerate(inputs):
if i <= preamble:
continue
sums = set(sum(comb) for comb in combina... | [
"itertools.combinations"
] | [((313, 352), 'itertools.combinations', 'combinations', (['inputs[i - preamble:i]', '(2)'], {}), '(inputs[i - preamble:i], 2)\n', (325, 352), False, 'from itertools import combinations\n')] |
import warnings
import signal
import sys, os, time
from rcpy._rcpy import initialize, cleanup, get_state
from rcpy._rcpy import set_state as _set_state
from rcpy._rcpy import cleanup as _cleanup
#from hanging_threads import start_monitoring
#monitoring_thread = start_monitoring()
# constants
IDLE = 0
RUNNING = 1
PAU... | [
"atexit.register",
"os.pipe",
"os.close",
"rcpy._rcpy.set_state",
"warnings.warn",
"signal.signal",
"rcpy._rcpy.cleanup",
"atexit.unregister",
"rcpy._rcpy.initialize"
] | [((2471, 2483), 'rcpy._rcpy.initialize', 'initialize', ([], {}), '()\n', (2481, 2483), False, 'from rcpy._rcpy import initialize, cleanup, get_state\n'), ((2523, 2567), 'warnings.warn', 'warnings.warn', (['"""> Robotics cape initialized"""'], {}), "('> Robotics cape initialized')\n", (2536, 2567), False, 'import warnin... |
#------------------------------------------ EXTRACT DATA FROM METADATA.CSV -------------------------------------------------
#
# our table has the same structrure as the csv file downloaded
#
#
#---------------------------------------------------------------------------------------... | [
"pandas.read_csv"
] | [((877, 922), 'pandas.read_csv', 'pd.read_csv', (['"""metadata.csv"""'], {'low_memory': '(False)'}), "('metadata.csv', low_memory=False)\n", (888, 922), True, 'import pandas as pd\n')] |
from __future__ import annotations
import dataclasses
import os
from pathlib import Path
from typing import Dict, List, Optional
from porcupine import tabs, utils
@dataclasses.dataclass
class Command:
command_format: str
cwd_format: str
external_terminal: bool
substitutions: Dict[str, str]
def ... | [
"porcupine.utils.quote",
"porcupine.utils.find_project_root"
] | [((987, 1020), 'porcupine.utils.find_project_root', 'utils.find_project_root', (['tab.path'], {}), '(tab.path)\n', (1010, 1020), False, 'from porcupine import tabs, utils\n'), ((514, 532), 'porcupine.utils.quote', 'utils.quote', (['value'], {}), '(value)\n', (525, 532), False, 'from porcupine import tabs, utils\n')] |
# Modified based on the HRNet repo.
from __future__ import absolute_import, division, print_function
import logging
import os
import time
from pathlib import Path
import numpy as np
import torch
import torch.nn as nn
import torch.optim as optim
class FullModel(nn.Module):
"""
Distribute the loss on multi-g... | [
"torch.distributed.is_initialized",
"numpy.argmax",
"torch.distributed.get_rank",
"os.path.basename",
"logging.StreamHandler",
"numpy.zeros",
"time.strftime",
"pathlib.Path",
"torch.arange",
"torch.distributed.get_world_size",
"numpy.bincount",
"os.path.join",
"logging.getLogger"
] | [((1003, 1037), 'torch.distributed.get_world_size', 'torch.distributed.get_world_size', ([], {}), '()\n', (1035, 1037), False, 'import torch\n'), ((1131, 1159), 'torch.distributed.get_rank', 'torch.distributed.get_rank', ([], {}), '()\n', (1157, 1159), False, 'import torch\n'), ((2058, 2078), 'pathlib.Path', 'Path', ([... |