code stringlengths 22 1.05M | apis listlengths 1 3.31k | extract_api stringlengths 75 3.25M |
|---|---|---|
from __future__ import division
import random
import pprint
import sys
import time
import numpy as np
from optparse import OptionParser
import pickle
from keras import backend as K
from keras.optimizers import Adam, SGD, RMSprop
from keras.layers import Input
from keras.models import Model
from frcnn import config, dat... | [
"log.logger.exception",
"frcnn.resnet.base_net",
"frcnn.data_generators.get_anchor_gt",
"frcnn.roi_helpers.calc_iou",
"os.path.exists",
"numpy.mean",
"numpy.where",
"frcnn.resnet.rpn",
"keras.utils.plot_model",
"frcnn.losses.rpn_class_loss",
"frcnn.losses.rpn_regr_loss",
"keras.models.Model",
... | [((548, 562), 'optparse.OptionParser', 'OptionParser', ([], {}), '()\n', (560, 562), False, 'from optparse import OptionParser\n'), ((3065, 3080), 'frcnn.config.Config', 'config.Config', ([], {}), '()\n', (3078, 3080), False, 'from frcnn import config, data_generators\n'), ((4984, 5015), 'random.shuffle', 'random.shuff... |
# -*- coding: utf-8 -*-
import datetime
from typing import List
from peewee import *
import helpers
import util
from models import Bot
from models.basemodel import BaseModel
from models.category import Category
from models.country import Country
from models.user import User
class Favorite(BaseModel):
id = Prima... | [
"datetime.date.today",
"models.category.Category"
] | [((498, 554), 'models.category.Category', 'Category', ([], {'id': '(1000)', 'order': '(1000)', 'emojis': '"""👤"""', 'name': '"""Others"""'}), "(id=1000, order=1000, emojis='👤', name='Others')\n", (506, 554), False, 'from models.category import Category\n'), ((899, 920), 'datetime.date.today', 'datetime.date.today', (... |
"""
cobyladriver.py - Contains a driver that wraps the cobyla
optimizer as used in pyOpt:
Minimize a function using the Constrained Optimization BY Linear
Approximation (COBYLA) method.
COBYLA is gradient-free and can handle inequality constraints.
"""
from math import isnan
from numpy import zeros, array, hstack
... | [
"openmdao.main.datatypes.api.Float",
"numpy.hstack",
"openmdao.main.datatypes.api.Enum",
"openmdao.main.interfaces.implements",
"cobyla.cobyla.cobyla",
"openmdao.main.datatypes.api.Int",
"numpy.zeros",
"cobyla.cobyla.closeunit",
"openmdao.util.decorators.add_delegate",
"openmdao.main.datatypes.api... | [((837, 898), 'openmdao.util.decorators.add_delegate', 'add_delegate', (['HasParameters', 'HasIneqConstraints', 'HasObjective'], {}), '(HasParameters, HasIneqConstraints, HasObjective)\n', (849, 898), False, 'from openmdao.util.decorators import add_delegate\n'), ((1211, 1285), 'openmdao.main.interfaces.implements', 'i... |
import warnings
import numpy as np
import pandas as pd
import matplotlib.pyplot as plt
import statsmodels.api as sm
import statsmodels.formula.api as smf
from statsmodels.stats.weightstats import DescrStatsW
from scipy.stats import norm
from zepid.causal.utils import (propensity_score, plot_kde, plot_love,
... | [
"numpy.sqrt",
"zepid.causal.utils.plot_love",
"zepid.causal.utils.plot_kde",
"numpy.nanmean",
"statsmodels.api.families.family.Binomial",
"zepid.causal.utils.positivity",
"statsmodels.api.families.family.Gaussian",
"statsmodels.formula.api.glm",
"zepid.causal.utils.propensity_score",
"numpy.where"... | [((8650, 8748), 'zepid.causal.utils.propensity_score', 'propensity_score', (['self.df', 'self._exp_model'], {'weights': 'self._weight_', 'print_results': 'print_results'}), '(self.df, self._exp_model, weights=self._weight_,\n print_results=print_results)\n', (8666, 8748), False, 'from zepid.causal.utils import prope... |
import yaml
from collections import OrderedDict
from .dict import UnsortableOrderedDict
'''
class _CustomAnchor(yaml.Dumper):
anchor_tags = {}
def __init__(self,*args,**kwargs):
super().__init__(*args,**kwargs)
self.new_anchors = {}
self.anchor_next = None
def anchor_node(self, node):
if self.an... | [
"yaml.nodes.MappingNode",
"yaml.add_representer",
"yaml.dump"
] | [((1274, 1330), 'yaml.add_representer', 'yaml.add_representer', (['OrderedDict', 'represent_ordereddict'], {}), '(OrderedDict, represent_ordereddict)\n', (1294, 1330), False, 'import yaml\n'), ((1217, 1272), 'yaml.nodes.MappingNode', 'yaml.nodes.MappingNode', (['u"""tag:yaml.org,2002:map"""', 'value'], {}), "(u'tag:yam... |
# =======================================================================================================================================
# VNU-HCM, University of Science
# Department Computer Science, Faculty of Information Technology
# Authors: <NAME> (<NAME>)
# © 2020
import unittest
"""
Given 2 arrays of ints, a ... | [
"unittest.main"
] | [((1195, 1210), 'unittest.main', 'unittest.main', ([], {}), '()\n', (1208, 1210), False, 'import unittest\n')] |
import pandas as pd
from scipy import *
from scipy.sparse import *
import similaripy as sim
from sklearn.feature_extraction.text import CountVectorizer
import argparse
import re
import os
def remove_spaces(s, n=2):
s = re.sub(' +',' ',s).strip()
ngrams = zip(*[s[i:] for i in range(n)])
return [''.join(ngra... | [
"argparse.ArgumentParser",
"pandas.read_csv",
"sklearn.feature_extraction.text.CountVectorizer",
"os.makedirs",
"os.path.isdir",
"re.sub",
"similaripy.jaccard"
] | [((782, 807), 'argparse.ArgumentParser', 'argparse.ArgumentParser', ([], {}), '()\n', (805, 807), False, 'import argparse\n'), ((1298, 1364), 'pandas.read_csv', 'pd.read_csv', (['f"""../dataset/{args.split}/train.csv"""'], {'escapechar': '"""\\\\"""'}), "(f'../dataset/{args.split}/train.csv', escapechar='\\\\')\n", (13... |
# Copyright (c) 2019 Horizon Robotics. 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 applicab... | [
"tensorflow.exp",
"tensorflow.math.sigmoid",
"tensorflow.clip_by_value",
"tensorflow.maximum"
] | [((1043, 1098), 'tensorflow.clip_by_value', 'tf.clip_by_value', (['value', 'clip_value_min', 'clip_value_max'], {}), '(value, clip_value_min, clip_value_max)\n', (1059, 1098), True, 'import tensorflow as tf\n'), ((1110, 1123), 'tensorflow.exp', 'tf.exp', (['value'], {}), '(value)\n', (1116, 1123), True, 'import tensorf... |
import argparse
import time
import cv2
import numpy as np
from estimator import TfPoseEstimator
from loguru import logger
from alfred.utils.log import init_logger
init_logger()
fps_time = 0
if __name__ == '__main__':
parser = argparse.ArgumentParser(description='tf-pose-estimation Video')
parser.add_argum... | [
"argparse.ArgumentParser",
"loguru.logger.debug",
"loguru.logger.info",
"estimator.TfPoseEstimator.draw_humans",
"cv2.imshow",
"numpy.zeros",
"alfred.utils.log.init_logger",
"cv2.destroyAllWindows",
"cv2.VideoCapture",
"cv2.waitKey",
"time.time"
] | [((166, 179), 'alfred.utils.log.init_logger', 'init_logger', ([], {}), '()\n', (177, 179), False, 'from alfred.utils.log import init_logger\n'), ((1813, 1838), 'loguru.logger.debug', 'logger.debug', (['"""finished+"""'], {}), "('finished+')\n", (1825, 1838), False, 'from loguru import logger\n'), ((236, 299), 'argparse... |
from billy.scrape.votes import VoteScraper, Vote
from billy.scrape.utils import url_xpath
import datetime as dt
import urllib
import lxml
import re
RI_URL_BASE = "http://webserver.rilin.state.ri.us"
class RIVoteScraper(VoteScraper):
jurisdiction = 'ri'
def get_dates(self, page):
dates = url_xpath( ... | [
"datetime.datetime.strptime",
"lxml.html.fromstring",
"billy.scrape.utils.url_xpath",
"re.search"
] | [((553, 579), 'lxml.html.fromstring', 'lxml.html.fromstring', (['html'], {}), '(html)\n', (573, 579), False, 'import lxml\n'), ((1743, 1788), 'datetime.datetime.strptime', 'dt.datetime.strptime', (['time_string', 'fmt_string'], {}), '(time_string, fmt_string)\n', (1763, 1788), True, 'import datetime as dt\n'), ((3870, ... |
from django.db.models import Q
from django.contrib.auth import get_user_model
from ..models import Job
User = get_user_model()
# Removes all jobs that the user cannot view due to insufficient permissions
def filter_jobs_for_user(user: User, jobs):
if not user.is_superuser:
jobs = jobs.filter(Q(only_vis... | [
"django.contrib.auth.get_user_model",
"django.db.models.Q"
] | [((113, 129), 'django.contrib.auth.get_user_model', 'get_user_model', ([], {}), '()\n', (127, 129), False, 'from django.contrib.auth import get_user_model\n'), ((353, 384), 'django.db.models.Q', 'Q', ([], {'only_visible_to__isnull': '(True)'}), '(only_visible_to__isnull=True)\n', (354, 384), False, 'from django.db.mode... |
import numpy as np
import nanonet.tb as tb
from test.test_hamiltonian_module import expected_bulk_silicon_band_structure
def test_simple_atomic_chain():
""" """
site_energy = -1.0
coupling = -1.0
l_const = 1.0
a = tb.Orbitals('A')
a.add_orbital(title='s', energy=-1, )
xyz_file = """1
... | [
"nanonet.tb.HamiltonianSp",
"numpy.sqrt",
"nanonet.tb.get_k_coords",
"nanonet.tb.set_tb_params",
"nanonet.tb.Orbitals",
"numpy.testing.assert_allclose",
"numpy.array",
"numpy.linspace",
"numpy.zeros",
"test.test_hamiltonian_module.expected_bulk_silicon_band_structure",
"numpy.cos"
] | [((237, 253), 'nanonet.tb.Orbitals', 'tb.Orbitals', (['"""A"""'], {}), "('A')\n", (248, 253), True, 'import nanonet.tb as tb\n'), ((397, 444), 'nanonet.tb.set_tb_params', 'tb.set_tb_params', ([], {'PARAMS_A_A': "{'ss_sigma': -1.0}"}), "(PARAMS_A_A={'ss_sigma': -1.0})\n", (413, 444), True, 'import nanonet.tb as tb\n'), ... |
from flask_wtf import FlaskForm
from wtforms import StringField,TextAreaField,SubmitField,ValidationError
from wtforms import validators
from wtforms.fields.core import SelectField
from wtforms.validators import Required
from ..models import User
class ReviewForm(FlaskForm):
title = StringField('Give your title',... | [
"wtforms.validators.Required",
"wtforms.SubmitField"
] | [((426, 447), 'wtforms.SubmitField', 'SubmitField', (['"""Submit"""'], {}), "('Submit')\n", (437, 447), False, 'from wtforms import StringField, TextAreaField, SubmitField, ValidationError\n'), ((570, 591), 'wtforms.SubmitField', 'SubmitField', (['"""Submit"""'], {}), "('Submit')\n", (581, 591), False, 'from wtforms im... |
import sys
from easyprocess import EasyProcess
python = sys.executable
print("-- Run program, wait for it to complete, get stdout:")
s = EasyProcess([python, "-c", "print(3)"]).call().stdout
print(s)
print("-- Run program, wait for it to complete, get stderr:")
s = EasyProcess([python, "-c", "import sys;sys.stderr.... | [
"easyprocess.EasyProcess"
] | [((140, 179), 'easyprocess.EasyProcess', 'EasyProcess', (["[python, '-c', 'print(3)']"], {}), "([python, '-c', 'print(3)'])\n", (151, 179), False, 'from easyprocess import EasyProcess\n'), ((270, 336), 'easyprocess.EasyProcess', 'EasyProcess', (['[python, \'-c\', "import sys;sys.stderr.write(\'4\\\\n\')"]'], {}), '([py... |
import subprocess
def get_crab_files(crab_path):
"""Get a list of output files for a CRAB directory."""
# CRAB does the heavy lifting
cmd = ["crab", "out", "--dump","--xrootd", crab_path]
proc = subprocess.Popen(cmd, stdout=subprocess.PIPE)
stdout, _ = proc.communicate()
if proc.returncode != ... | [
"subprocess.Popen"
] | [((213, 258), 'subprocess.Popen', 'subprocess.Popen', (['cmd'], {'stdout': 'subprocess.PIPE'}), '(cmd, stdout=subprocess.PIPE)\n', (229, 258), False, 'import subprocess\n')] |
# Generated by Django 2.1.4 on 2019-01-25 08:32
from django.conf import settings
from django.db import migrations, models
import django.db.models.deletion
class Migration(migrations.Migration):
dependencies = [
migrations.swappable_dependency(settings.AUTH_USER_MODEL),
("articles", "0001_initial... | [
"django.db.migrations.swappable_dependency",
"django.db.migrations.RenameField",
"django.db.models.ForeignKey"
] | [((227, 284), 'django.db.migrations.swappable_dependency', 'migrations.swappable_dependency', (['settings.AUTH_USER_MODEL'], {}), '(settings.AUTH_USER_MODEL)\n', (258, 284), False, 'from django.db import migrations, models\n'), ((358, 433), 'django.db.migrations.RenameField', 'migrations.RenameField', ([], {'model_name... |
#!/usr/bin/env python3
# -*- coding: utf-8 -*-
# python3 d_speed_size.py : test speed/compression for folder 'corpus'
# python3 d_speed_size.py indir : test speed/compression for folder 'indir'
import os
import sys
import stat
import time
import shutil
import ntpath
import subprocess
import pandas as pd
def ... | [
"sys.exit",
"os.remove",
"pandas.read_pickle",
"os.path.exists",
"seaborn.set",
"os.listdir",
"os.path.isdir",
"subprocess.call",
"pandas.DataFrame",
"shutil.which",
"seaborn.lineplot",
"os.path.isfile",
"time.time",
"matplotlib.pyplot.show",
"ntpath.basename",
"os.path.join",
"os.pa... | [((798, 830), 'subprocess.call', 'subprocess.call', (['cmd'], {'shell': '(True)'}), '(cmd, shell=True)\n', (813, 830), False, 'import subprocess\n'), ((1913, 1933), 'ntpath.basename', 'ntpath.basename', (['exe'], {}), '(exe)\n', (1928, 1933), False, 'import ntpath\n'), ((3430, 3447), 'os.listdir', 'os.listdir', (['indi... |
import logging
import os
from typing import Tuple, List, Callable, Union
import torch
from torch import Tensor
from torch.utils.data import Dataset
from torchvision.transforms import ToTensor
from src.base import IO
from src.base.model import ImageWithText, Text
log = logging.getLogger('pytorch_lightning').getChild(... | [
"logging.getLogger",
"src.base.IO.get_image_paths",
"os.path.join",
"torch.tensor",
"src.base.IO.load_image",
"torchvision.transforms.ToTensor"
] | [((272, 310), 'logging.getLogger', 'logging.getLogger', (['"""pytorch_lightning"""'], {}), "('pytorch_lightning')\n", (289, 310), False, 'import logging\n'), ((700, 735), 'os.path.join', 'os.path.join', (['path', 'image_file_glob'], {}), '(path, image_file_glob)\n', (712, 735), False, 'import os\n'), ((898, 927), 'src.... |
# -*- coding: utf-8 -*-
# Generated by Django 1.11.13 on 2018-07-10 15:58
from __future__ import unicode_literals
import django.core.validators
import django.db.models.deletion
from django.conf import settings
from django.db import migrations, models
import debug # pyflakes:ignore
import... | [
"django.db.models.ForeignKey",
"django.db.models.BooleanField",
"django.db.models.AutoField",
"django.db.models.DateTimeField",
"django.db.migrations.swappable_dependency",
"django.db.models.CharField"
] | [((409, 466), 'django.db.migrations.swappable_dependency', 'migrations.swappable_dependency', (['settings.AUTH_USER_MODEL'], {}), '(settings.AUTH_USER_MODEL)\n', (440, 466), False, 'from django.db import migrations, models\n'), ((878, 940), 'django.db.models.BooleanField', 'models.BooleanField', ([], {'default': '(Fals... |
#!/usr/bin/env python
"""
2b. Create a Python module named 'my_funcs.py'. In this file create two functions:
function1 should read the YAML file you created in exercise 2a and return the corresponding data structure;
function2 should handle the output printing of the ARP entries
(in other words, create a separate f... | [
"pyeapi.client.Node",
"my_funcs.arp_output",
"my_funcs.read_yaml",
"pyeapi.client.connect"
] | [((695, 722), 'my_funcs.read_yaml', 'read_yaml', (['"""inventory.yaml"""'], {}), "('inventory.yaml')\n", (704, 722), False, 'from my_funcs import read_yaml, arp_output\n'), ((826, 856), 'pyeapi.client.Node', 'pyeapi.client.Node', (['connection'], {}), '(connection)\n', (844, 856), False, 'import pyeapi\n'), ((783, 815)... |
from __future__ import absolute_import
from __future__ import division
from __future__ import print_function
from __future__ import unicode_literals
import collections
import json
import os
import re
import mock
import requests_mock
from six.moves.urllib import parse as urlparse
import testtools
# Setup dummy enviro... | [
"json.loads",
"collections.namedtuple",
"hook._get_zone_id",
"re.compile",
"hook.create_txt_record",
"six.moves.urllib.parse.urlparse",
"requests_mock.Mocker",
"hook._get_txt_record_id",
"mock.patch.object"
] | [((868, 960), 'collections.namedtuple', 'collections.namedtuple', (['"""ExpectedRequestsData"""', "['method', 'path', 'query', 'json_body']"], {}), "('ExpectedRequestsData', ['method', 'path', 'query',\n 'json_body'])\n", (890, 960), False, 'import collections\n'), ((965, 987), 'requests_mock.Mocker', 'requests_mock... |
#!/usr/local/bin/python3
# -*- coding: utf-8 -*-
from random import randint, shuffle, sample, choice
from math import floor
from reportlab.lib.pagesizes import A4
from reportlab.lib.units import cm
from reportlab.pdfgen.canvas import Canvas
# WORDCOUNT, WORDLENGTH, WORDS_PER_LINE, DIM = 40, 5, 6, (14, 14)
# WORDCOUNT... | [
"random.randint",
"random.shuffle"
] | [((2223, 2241), 'random.shuffle', 'shuffle', (['rand_dirs'], {}), '(rand_dirs)\n', (2230, 2241), False, 'from random import randint, shuffle, sample, choice\n'), ((5297, 5311), 'random.shuffle', 'shuffle', (['words'], {}), '(words)\n', (5304, 5311), False, 'from random import randint, shuffle, sample, choice\n'), ((248... |
import json
import traceback
from datetime import datetime, timedelta, date
from django.test import TestCase
from django.core import management
from django.contrib.auth.models import User
from django.conf import settings
from django.db import IntegrityError
from django.utils.timezone import localtime, now
from . impo... | [
"django.utils.timezone.now",
"django.contrib.auth.models.User.objects.create",
"datetime.timedelta"
] | [((1151, 1236), 'django.contrib.auth.models.User.objects.create', 'User.objects.create', ([], {'username': '"""member_one"""', 'first_name': '"""Member"""', 'last_name': '"""One"""'}), "(username='member_one', first_name='Member', last_name='One'\n )\n", (1170, 1236), False, 'from django.contrib.auth.models import U... |
import time
import logging
import traceback
from datetime import datetime, timedelta, date
from django.conf import settings
from django.db.models import Count, Q
from django.core.exceptions import ObjectDoesNotExist
from django.utils import timezone
from django.contrib.auth.models import User
from nadine.models.core ... | [
"logging.getLogger",
"traceback.format_exc",
"nadine.models.payment.BillingLog.objects.create",
"django.db.models.Count",
"nadine.models.core.Membership.objects.filter",
"nadine.models.payment.Transaction",
"django.utils.timezone.now",
"datetime.datetime.date",
"nadine.models.payment.Bill",
"nadin... | [((457, 484), 'logging.getLogger', 'logging.getLogger', (['__name__'], {}), '(__name__)\n', (474, 484), False, 'import logging\n'), ((6596, 6620), 'datetime.datetime.date', 'datetime.date', (['bill_time'], {}), '(bill_time)\n', (6609, 6620), False, 'from datetime import datetime, timedelta, date\n'), ((7059, 7086), 'na... |
import gym
env = gym.make('Pendulum-v0')
act_limit = env.action_space.low[0]
print(act_limit) | [
"gym.make"
] | [((17, 40), 'gym.make', 'gym.make', (['"""Pendulum-v0"""'], {}), "('Pendulum-v0')\n", (25, 40), False, 'import gym\n')] |
from typing import Optional, List, Callable, Tuple, Iterable
from fedot.core.log import default_log, Log
ConditionType = Callable[[], bool]
ConditionEntryType = Tuple[ConditionType, Optional[str]]
class GroupedCondition:
"""Represents sequence of ordinary conditions with logging.
All composed conditions are... | [
"fedot.core.log.default_log"
] | [((812, 833), 'fedot.core.log.default_log', 'default_log', (['__name__'], {}), '(__name__)\n', (823, 833), False, 'from fedot.core.log import default_log, Log\n')] |
# SPDX-FileCopyrightText: 2021 <NAME> for Adafruit Industries
# SPDX-License-Identifier: Unlicense
"""
CircuitPython Essentials Storage CP Filesystem code.py file
"""
import time
import board
import microcontroller
import neopixel
pixel = neopixel.NeoPixel(board.NEOPIXEL, 1)
try:
with open("/temperature.txt", "a"... | [
"neopixel.NeoPixel",
"time.sleep"
] | [((240, 276), 'neopixel.NeoPixel', 'neopixel.NeoPixel', (['board.NEOPIXEL', '(1)'], {}), '(board.NEOPIXEL, 1)\n', (257, 276), False, 'import neopixel\n'), ((820, 833), 'time.sleep', 'time.sleep', (['(1)'], {}), '(1)\n', (830, 833), False, 'import time\n'), ((925, 938), 'time.sleep', 'time.sleep', (['(9)'], {}), '(9)\n'... |
# -*- coding:utf-8 -*-
# Copyright (c) 2020 Huawei Technologies Co.,Ltd.
#
# openGauss is licensed under Mulan PSL v2.
# You can use this software according to the terms
# and conditions of the Mulan PSL v2.
# You may obtain a copy of Mulan PSL v2 at:
#
# http://license.coscl.org.cn/MulanPSL2
#
# THIS SOFTWARE... | [
"datetime.datetime.strptime",
"gspylib.inspection.common.SharedFuncs.runShellCmd"
] | [((1428, 1483), 'gspylib.inspection.common.SharedFuncs.runShellCmd', 'SharedFuncs.runShellCmd', (['cmd', 'self.user', 'self.mpprcFile'], {}), '(cmd, self.user, self.mpprcFile)\n', (1451, 1483), False, 'from gspylib.inspection.common import SharedFuncs\n'), ((1797, 1847), 'datetime.datetime.strptime', 'datetime.strptime... |
from importlib import import_module
from os import environ
environment_name = environ.get('ENVIRONMENT_NAME', 'dev')
config = import_module('app.config.{}'.format(environment_name)).CONFIG
def get_config():
return config
| [
"os.environ.get"
] | [((79, 117), 'os.environ.get', 'environ.get', (['"""ENVIRONMENT_NAME"""', '"""dev"""'], {}), "('ENVIRONMENT_NAME', 'dev')\n", (90, 117), False, 'from os import environ\n')] |
# -*- coding: utf-8 -*-
import itertools
from collections import Iterable
import torch
class GeneralCollateFunction(object):
"""A Generic `Collate_fn`.
For finetuning-train.
"""
def __init__(self, trfms, times):
"""Initialize a `GeneralCollateFunction`.
Args:
trfms (lis... | [
"itertools.chain.from_iterable",
"torch.tensor",
"torch.stack",
"torch.cat"
] | [((1542, 1559), 'torch.cat', 'torch.cat', (['images'], {}), '(images)\n', (1551, 1559), False, 'import torch\n'), ((1583, 1623), 'torch.tensor', 'torch.tensor', (['targets'], {'dtype': 'torch.int64'}), '(targets, dtype=torch.int64)\n', (1595, 1623), False, 'import torch\n'), ((5606, 5625), 'torch.stack', 'torch.stack',... |
import asyncio
import hashlib
import logging
import sys
from pathlib import Path
import aiomisc
from aiomisc.service import MemoryTracer
from lsm import LSM
@aiomisc.threaded
def seq_reader(fname: Path):
hasher = hashlib.md5()
logging.info("Start reading %s", fname)
with LSM(fname, binary=True, readonly... | [
"hashlib.md5",
"pathlib.Path",
"aiomisc.service.MemoryTracer",
"lsm.LSM",
"logging.info"
] | [((220, 233), 'hashlib.md5', 'hashlib.md5', ([], {}), '()\n', (231, 233), False, 'import hashlib\n'), ((239, 278), 'logging.info', 'logging.info', (['"""Start reading %s"""', 'fname'], {}), "('Start reading %s', fname)\n", (251, 278), False, 'import logging\n'), ((492, 534), 'logging.info', 'logging.info', (['"""Readin... |
import tensorflow as tf
from tensorflow.keras import layers, initializers, optimizers
#gaussian0_1 = initializers.RandomNormal(mean=0.0, stddev=0.1, seed=None)
def build_model():
model = tf.keras.Sequential()
model.add(layers.Conv1D(100, 5, input_shape= (8000, 1), padding='same', activation='relu', name='conv... | [
"tensorflow.keras.Sequential",
"tensorflow.keras.layers.Flatten",
"tensorflow.keras.layers.Dropout",
"tensorflow.keras.layers.Dense",
"tensorflow.keras.layers.Conv1D",
"tensorflow.keras.layers.MaxPooling1D"
] | [((193, 214), 'tensorflow.keras.Sequential', 'tf.keras.Sequential', ([], {}), '()\n', (212, 214), True, 'import tensorflow as tf\n'), ((229, 327), 'tensorflow.keras.layers.Conv1D', 'layers.Conv1D', (['(100)', '(5)'], {'input_shape': '(8000, 1)', 'padding': '"""same"""', 'activation': '"""relu"""', 'name': '"""conv1"""'... |
import functools
import numpy as np
import torch as t
import torch.nn as nn
import torch.distributed as dist
from jukebox.transformer.ops import Conv1D, ACT_FNS, LayerNorm
from jukebox.transformer.factored_attention import FactoredAttention
from jukebox.utils.checkpoint import checkpoint
def _convert_mlp_traced(l):
... | [
"torch.nn.Dropout",
"torch.abs",
"jukebox.transformer.ops.Conv1D",
"jukebox.utils.dist_utils.setup_dist_from_mpi",
"torch.nn.ModuleList",
"jukebox.transformer.ops.LayerNorm",
"torch.chunk",
"functools.partial",
"torch.no_grad",
"torch.randn",
"torch.cat"
] | [((10329, 10360), 'jukebox.utils.dist_utils.setup_dist_from_mpi', 'setup_dist_from_mpi', ([], {'port': '(29600)'}), '(port=29600)\n', (10348, 10360), False, 'from jukebox.utils.dist_utils import setup_dist_from_mpi\n'), ((740, 784), 'jukebox.transformer.ops.Conv1D', 'Conv1D', (['n_in', 'n_state'], {'init_scale': 'init_... |
"""Test example file that can be used as orientation."""
import unittest
import unittest.mock as mock
class ExampleTestCase(unittest.TestCase):
"""An example for how to create a test case."""
def test_foo(self):
"""How create a test."""
def function_under_test(file_path):
"""Example function wi... | [
"unittest.mock.mock_open",
"unittest.mock.patch"
] | [((592, 632), 'unittest.mock.patch', 'mock.patch', (['"""builtins.open"""'], {'create': '(True)'}), "('builtins.open', create=True)\n", (602, 632), True, 'import unittest.mock as mock\n'), ((794, 834), 'unittest.mock.mock_open', 'mock.mock_open', ([], {'read_data': '"""FileContents"""'}), "(read_data='FileContents')\n"... |
"""The |pydwf.core.api.analog_out| module implements a single class: |AnalogOut|."""
# pylint: disable=too-many-lines
from typing import Tuple, List
import numpy as np
from pydwf.core.dwf_device_subapi import AbstractDwfDeviceSubApi
from pydwf.core.auxiliary.typespec_ctypes import typespec_ctypes
from pydwf.core.a... | [
"pydwf.core.auxiliary.typespec_ctypes.typespec_ctypes.DwfState",
"pydwf.core.auxiliary.enum_types.DwfAnalogOutMode",
"pydwf.core.auxiliary.typespec_ctypes.typespec_ctypes.c_int",
"pydwf.core.auxiliary.typespec_ctypes.typespec_ctypes.c_unsigned_int",
"pydwf.core.auxiliary.typespec_ctypes.typespec_ctypes.DwfT... | [((3280, 3306), 'pydwf.core.auxiliary.typespec_ctypes.typespec_ctypes.DwfState', 'typespec_ctypes.DwfState', ([], {}), '()\n', (3304, 3306), False, 'from pydwf.core.auxiliary.typespec_ctypes import typespec_ctypes\n'), ((3482, 3506), 'pydwf.core.auxiliary.enum_types.DwfState', 'DwfState', (['c_status.value'], {}), '(c_... |
# Copyright (C) 2018-2021 Intel Corporation
# SPDX-License-Identifier: Apache-2.0
import logging as log
import numpy as np
from openvino.tools.mo.front.common.partial_infer.utils import shape_array, dynamic_dimension_value
from openvino.tools.mo.front.tf.common import tf_data_type_decode
from openvino.tools.mo.utils... | [
"openvino.tools.mo.front.common.partial_infer.utils.shape_array",
"numpy.full",
"numpy.array",
"openvino.tools.mo.utils.utils.refer_to_faq_msg",
"numpy.frombuffer",
"logging.error"
] | [((437, 530), 'openvino.tools.mo.front.common.partial_infer.utils.shape_array', 'shape_array', (['[(dim.size if dim.size >= 0 else dynamic_dimension_value) for dim in pb.dim]'], {}), '([(dim.size if dim.size >= 0 else dynamic_dimension_value) for\n dim in pb.dim])\n', (448, 530), False, 'from openvino.tools.mo.front... |
#!/usr/bin/env python3
# BEGIN_LEGAL
# BSD License
#
# Copyright (c)2019 Intel Corporation. All rights reserved.
#
# Redistribution and use in source and binary forms, with or without
# modification, are permitted provided that the following conditions are
# met:
#
# Redistributions of source code must retain the abov... | [
"os.path.exists",
"msg.PrintAndExit",
"locale.setlocale",
"util.GetNumThreadsWP",
"util.GetWPDir",
"util.RoundupPow2",
"os.path.join",
"msg.PrintMsgPlus",
"locale.format",
"config.GlobalVar",
"util.AddCfgFile",
"util.RunCmd",
"struct.unpack",
"os.path.basename",
"msg.PrintMsg",
"util.O... | [((1724, 1759), 'locale.setlocale', 'locale.setlocale', (['locale.LC_ALL', '""""""'], {}), "(locale.LC_ALL, '')\n", (1740, 1759), False, 'import locale\n'), ((6122, 6140), 'config.GlobalVar', 'config.GlobalVar', ([], {}), '()\n', (6138, 6140), False, 'import config\n'), ((6344, 6373), 'util.GetNumThreadsWP', 'util.GetN... |
from django.shortcuts import render, redirect
from django.http import HttpResponse
from datetime import datetime
from django.http import Http404
from django.http import JsonResponse
import socket as sok
from random import randint
from . import Comunicacion
# Create your views here.
def loguin(request):
if request.... | [
"django.shortcuts.render",
"socket.socket",
"django.http.HttpResponse",
"datetime.datetime.now",
"django.shortcuts.redirect",
"random.randint",
"django.http.Http404"
] | [((1242, 1260), 'django.shortcuts.redirect', 'redirect', (['"""loguin"""'], {}), "('loguin')\n", (1250, 1260), False, 'from django.shortcuts import render, redirect\n'), ((1474, 1513), 'django.shortcuts.render', 'render', (['request', '"""index.html"""', 'contexto'], {}), "(request, 'index.html', contexto)\n", (1480, 1... |
import argparse
import sys
import pathlib
import random
from unittest import mock
import pytest
from _repobee import plugin
import repobee_plug as plug
from repobee_feedback import feedback
ASSIGNMENT_NAMES = ("task-1", "task-2")
STUDENT_TEAMS = tuple(
[
plug.StudentTeam(members=members)
for memb... | [
"random.choice",
"sys.getdefaultencoding",
"unittest.mock.MagicMock",
"unittest.mock.call",
"_repobee.plugin.register_plugins",
"repobee_plug.generate_repo_name",
"random.seed",
"repobee_feedback.feedback.callback",
"argparse.Namespace",
"pytest.raises",
"repobee_plug.Issue",
"unittest.mock.pa... | [((450, 518), 'repobee_plug.Issue', 'plug.Issue', ([], {'title': '"""Pass"""', 'body': '"""Well done!\nAbsolutely flawless!"""'}), '(title=\'Pass\', body="""Well done!\nAbsolutely flawless!""")\n', (460, 518), True, 'import repobee_plug as plug\n'), ((529, 605), 'repobee_plug.Issue', 'plug.Issue', ([], {'title': '"""Ko... |
import abc
from collections import namedtuple
import subprocess
from galaxy.tools.deps.commands import which
try:
from lxml import etree
except ImportError:
etree = None
XMLLINT_COMMAND = "xmllint --noout --schema {0} {1} 2>&1"
INSTALL_VALIDATOR_MESSAGE = ("This feature requires an external dependency "
... | [
"lxml.etree.XMLSchema",
"collections.namedtuple",
"subprocess.Popen",
"lxml.etree.parse",
"galaxy.tools.deps.commands.which"
] | [((943, 995), 'collections.namedtuple', 'namedtuple', (['"""ValidationResult"""', "['passed', 'output']"], {}), "('ValidationResult', ['passed', 'output'])\n", (953, 995), False, 'from collections import namedtuple\n'), ((1762, 1823), 'subprocess.Popen', 'subprocess.Popen', (['command'], {'stdout': 'subprocess.PIPE', '... |
from datetime import datetime, timedelta
import pytest
import astropy.units as u
from astropy.time import Time, TimeDelta
from astropy.utils.exceptions import ErfaWarning
import sunpy.time
from sunpy.time import is_time_equal
tbegin_str = '2012/1/1'
tfin_str = '2012/1/2'
dt = u.Quantity(24 * 60 * 60, 's')
start = ... | [
"datetime.datetime",
"astropy.time.TimeDelta",
"pytest.warns",
"sunpy.time.is_time_equal",
"pytest.mark.parametrize",
"astropy.time.Time",
"pytest.raises",
"datetime.timedelta",
"astropy.units.Quantity"
] | [((281, 310), 'astropy.units.Quantity', 'u.Quantity', (['(24 * 60 * 60)', '"""s"""'], {}), "(24 * 60 * 60, 's')\n", (291, 310), True, 'import astropy.units as u\n'), ((3657, 3761), 'pytest.mark.parametrize', 'pytest.mark.parametrize', (['"""ainput"""', '[(tbegin_str, tfin_str), (tfin_str, -dt), (tfin_str, tbegin_str)]'... |
import onnxruntime as rt
sess = rt.InferenceSession("pretrained/original_ckpt.onnx")
print("====INPUT====")
for i in sess.get_inputs():
print("Name: {}, Shape: {}, Dtype: {}".format(i.name, i.shape, i.type))
print("====OUTPUT====")
for i in sess.get_outputs():
print("Name: {}, Shape: {}, Dtype: {}".format(i.nam... | [
"onnxruntime.InferenceSession"
] | [((32, 84), 'onnxruntime.InferenceSession', 'rt.InferenceSession', (['"""pretrained/original_ckpt.onnx"""'], {}), "('pretrained/original_ckpt.onnx')\n", (51, 84), True, 'import onnxruntime as rt\n')] |
import os
from environ import Env
env = Env()
HOME_DIR = env.str(
"HOME_DIR",
default=os.path.realpath(os.path.join(os.path.dirname(__file__), ".."))
)
env.read_env(os.path.join(HOME_DIR, ".env"))
DEBUG = env.bool("DEBUG", False)
SECRET_KEY = env.bool("SECRET_KEY", "Sehr lecker Wurst" if DEBUG else Env.NOTSE... | [
"os.path.join",
"os.path.dirname",
"environ.Env"
] | [((42, 47), 'environ.Env', 'Env', ([], {}), '()\n', (45, 47), False, 'from environ import Env\n'), ((176, 206), 'os.path.join', 'os.path.join', (['HOME_DIR', '""".env"""'], {}), "(HOME_DIR, '.env')\n", (188, 206), False, 'import os\n'), ((533, 565), 'os.path.join', 'os.path.join', (['HOME_DIR', '"""static"""'], {}), "(... |
import argparse
import os
import pandas as pd
def run(images_dir, data_file):
s_old = set()
s_new = set()
# retrieve or create dataframe
df = pd.DataFrame([])
if os.path.exists(data_file):
df = pd.read_hdf(data_file, "images")
s_old.update(df.index)
# search image files
fo... | [
"os.path.exists",
"os.listdir",
"argparse.ArgumentParser",
"os.path.join",
"pandas.Index",
"pandas.DataFrame",
"pandas.read_hdf"
] | [((161, 177), 'pandas.DataFrame', 'pd.DataFrame', (['[]'], {}), '([])\n', (173, 177), True, 'import pandas as pd\n'), ((185, 210), 'os.path.exists', 'os.path.exists', (['data_file'], {}), '(data_file)\n', (199, 210), False, 'import os\n'), ((334, 356), 'os.listdir', 'os.listdir', (['images_dir'], {}), '(images_dir)\n',... |
from math import isqrt
import numpy as np
import matplotlib.pyplot as plt
PRIME_AMT =100000
R_MAX = 10000
primes = []
def is_prime(n):
if n < 0:
pass
for i in range (2, isqrt(n) + 1):
if n % i == 0:
return False
return True
def prime_bounds(b):
for i in range(2,... | [
"math.isqrt",
"matplotlib.pyplot.savefig",
"matplotlib.pyplot.subplots"
] | [((449, 497), 'matplotlib.pyplot.subplots', 'plt.subplots', ([], {'subplot_kw': "{'projection': 'polar'}"}), "(subplot_kw={'projection': 'polar'})\n", (461, 497), True, 'import matplotlib.pyplot as plt\n'), ((744, 774), 'matplotlib.pyplot.savefig', 'plt.savefig', (['"""polarspiral.png"""'], {}), "('polarspiral.png')\n"... |
from gql import gql
from navability.common.mutations import GQL_SOLVESESSION
from navability.entities.client import Client
from navability.entities.navabilityclient import MutationOptions, NavAbilityClient
async def solveSession(navAbilityClient: NavAbilityClient, client: Client):
result = await navAbilityClient... | [
"gql.gql"
] | [((353, 374), 'gql.gql', 'gql', (['GQL_SOLVESESSION'], {}), '(GQL_SOLVESESSION)\n', (356, 374), False, 'from gql import gql\n')] |
import os
import pandas as pd
import numpy as np
import datetime as dt
import sys
from datetime import datetime
import rasterio
import geopandas as gpd
pkg_dir = os.path.join(os.path.dirname(__file__),'..')
sys.path.insert(0, pkg_dir)
from ela.textproc import *
from ela.spatial import *
from ela.classification impor... | [
"rasterio.crs.CRS",
"sys.path.insert",
"numpy.reshape",
"ela.utils.flip",
"rasterio.transform.from_origin",
"ela.io.GeotiffExporter",
"os.path.join",
"os.path.dirname",
"numpy.zeros",
"numpy.array",
"numpy.isnan",
"numpy.empty",
"numpy.full",
"geopandas.GeoDataFrame",
"numpy.arange"
] | [((209, 236), 'sys.path.insert', 'sys.path.insert', (['(0)', 'pkg_dir'], {}), '(0, pkg_dir)\n', (224, 236), False, 'import sys\n'), ((176, 201), 'os.path.dirname', 'os.path.dirname', (['__file__'], {}), '(__file__)\n', (191, 201), False, 'import os\n'), ((1893, 1918), 'numpy.isnan', 'np.isnan', (['predicted[1, 1]'], {}... |
from django.contrib import admin
from .models import PhoneNumber, Employee, Organization
class PhoneNumberAdmin(admin.ModelAdmin):
list_display = ('phone_number', 'phone_type', 'employee',)
admin.site.register(PhoneNumber, PhoneNumberAdmin)
class EmployeeAdmin(admin.ModelAdmin):
list_display = ('full_name... | [
"django.contrib.admin.site.register"
] | [((198, 248), 'django.contrib.admin.site.register', 'admin.site.register', (['PhoneNumber', 'PhoneNumberAdmin'], {}), '(PhoneNumber, PhoneNumberAdmin)\n', (217, 248), False, 'from django.contrib import admin\n'), ((515, 559), 'django.contrib.admin.site.register', 'admin.site.register', (['Employee', 'EmployeeAdmin'], {... |
from dassl.utils import Registry, check_availability
EVALUATOR_REGISTRY = Registry("EVALUATOR")
def build_evaluator(cfg, **kwargs):
avai_evaluators = EVALUATOR_REGISTRY.registered_names()
check_availability(cfg.TEST.EVALUATOR, avai_evaluators)
if cfg.VERBOSE:
print("Loading evaluator: {}".format(... | [
"dassl.utils.Registry",
"dassl.utils.check_availability"
] | [((75, 96), 'dassl.utils.Registry', 'Registry', (['"""EVALUATOR"""'], {}), "('EVALUATOR')\n", (83, 96), False, 'from dassl.utils import Registry, check_availability\n'), ((199, 254), 'dassl.utils.check_availability', 'check_availability', (['cfg.TEST.EVALUATOR', 'avai_evaluators'], {}), '(cfg.TEST.EVALUATOR, avai_evalu... |
from hybrid_astar_planner.HybridAStar.hybrid_astar_wrapper \
import apply_hybrid_astar
import numpy as np
from pylot.planning.planner import Planner
class HybridAStarPlanner(Planner):
"""Wrapper around the Hybrid A* planner.
Note:
Details can be found at `Hybrid A* Planner`_.
Args:
... | [
"hybrid_astar_planner.HybridAStar.hybrid_astar_wrapper.apply_hybrid_astar",
"numpy.deg2rad"
] | [((2491, 2552), 'hybrid_astar_planner.HybridAStar.hybrid_astar_wrapper.apply_hybrid_astar', 'apply_hybrid_astar', (['initial_conditions', 'self._hyperparameters'], {}), '(initial_conditions, self._hyperparameters)\n', (2509, 2552), False, 'from hybrid_astar_planner.HybridAStar.hybrid_astar_wrapper import apply_hybrid_a... |
#!/usr/bin/env python
# coding: utf-8
import os
import sys
import json
import shutil
import time
import subprocess
from optparse import OptionParser
from django.template.base import Template, Context
from django.conf import settings
from settings_template import RPMTOOLS_CONF, RPMTOOLS_CONF_DIR
settings.configure()... | [
"os.path.exists",
"os.listdir",
"django.template.base.Context",
"django.template.base.Template",
"subprocess.Popen",
"os.path.join",
"optparse.OptionParser",
"sys.stdout.write",
"os.path.dirname",
"os.mkdir",
"shutil.rmtree",
"os.path.abspath",
"sys.stdout.flush",
"time.time",
"django.co... | [((300, 320), 'django.conf.settings.configure', 'settings.configure', ([], {}), '()\n', (318, 320), False, 'from django.conf import settings\n'), ((600, 631), 'os.listdir', 'os.listdir', (['target_template_dir'], {}), '(target_template_dir)\n', (610, 631), False, 'import os\n'), ((1245, 1270), 'os.path.dirname', 'os.pa... |
import torch
import torch.nn as nn
import torch.optim as optim
def build_optimizer(model, optim_cfg):
if optim_cfg['type'] == 'SGD':
optimizer = optim.SGD(
model.parameters(), lr=optim_cfg.lr, momentum=optim_cfg.momentum)
elif optim_cfg['type'] == 'Adam':
optimizer = optim.Adam(mod... | [
"torch.nn.BCEWithLogitsLoss",
"torch.nn.CrossEntropyLoss",
"torch.nn.TripletMarginLoss"
] | [((746, 849), 'torch.nn.BCEWithLogitsLoss', 'nn.BCEWithLogitsLoss', ([], {'weight': 'weight', 'size_average': 'size_average', 'reduce': 'reduce', 'reduction': 'reduction'}), '(weight=weight, size_average=size_average, reduce=\n reduce, reduction=reduction)\n', (766, 849), True, 'import torch.nn as nn\n'), ((943, 104... |
import sys, os
import time
import numpy as np
import torch
import torch.nn as nn
from torch.utils import data
from parsers import parse_a3m, read_templates
from RoseTTAFoldModel import RoseTTAFoldModule_e2e
import util
from collections import namedtuple
from ffindex import *
from kinematics import xyz_to_c6d, c6d_to_b... | [
"torch.from_numpy",
"numpy.array",
"torch.cuda.is_available",
"torch.sum",
"sys.exit",
"numpy.arange",
"torch.arange",
"os.path.exists",
"argparse.ArgumentParser",
"RoseTTAFoldModel.RoseTTAFoldModule_e2e",
"numpy.ix_",
"torch.cuda.amp.autocast",
"numpy.concatenate",
"parsers.parse_a3m",
... | [((1975, 2067), 'numpy.array', 'np.array', (['[[-0.676, -1.294, 0.0], [0.0, 0.0, 0.0], [1.5, -0.174, 0.0]]'], {'dtype': 'np.float32'}), '([[-0.676, -1.294, 0.0], [0.0, 0.0, 0.0], [1.5, -0.174, 0.0]],\n dtype=np.float32)\n', (1983, 2067), True, 'import numpy as np\n'), ((2214, 2230), 'numpy.deg2rad', 'np.deg2rad', ([... |
#!/usr/bin/env python
import json, requests, re, random, os, syslog
from bs4 import BeautifulSoup
class RevttRss:
def __init__(self):
self.path = os.path.expanduser('~') + '/.revtt-rss'
self.good = None
self.bad = None
self.history = None
syslog.openlog('revttrss... | [
"syslog.openlog",
"re.match",
"requests.get",
"bs4.BeautifulSoup",
"syslog.syslog",
"json.load",
"random.randint",
"os.path.expanduser"
] | [((296, 381), 'syslog.openlog', 'syslog.openlog', (['"""revttrss"""'], {'logoption': 'syslog.LOG_PID', 'facility': 'syslog.LOG_LOCAL0'}), "('revttrss', logoption=syslog.LOG_PID, facility=syslog.LOG_LOCAL0\n )\n", (310, 381), False, 'import json, requests, re, random, os, syslog\n'), ((1092, 1126), 'requests.get', 'r... |
import numpy as np
import pytest
import pandas as pd
from pandas import (
DatetimeIndex,
Index,
)
import pandas._testing as tm
dtlike_dtypes = [
np.dtype("timedelta64[ns]"),
np.dtype("datetime64[ns]"),
pd.DatetimeTZDtype("ns", "Asia/Tokyo"),
pd.PeriodDtype("ns"),
]
@pytest.... | [
"pandas.DatetimeIndex",
"pandas.Index",
"pytest.mark.parametrize",
"numpy.array",
"pandas._testing.assert_numpy_array_equal",
"pandas.PeriodDtype",
"numpy.dtype",
"pandas.DatetimeTZDtype",
"numpy.arange"
] | [((313, 361), 'pytest.mark.parametrize', 'pytest.mark.parametrize', (['"""ldtype"""', 'dtlike_dtypes'], {}), "('ldtype', dtlike_dtypes)\n", (336, 361), False, 'import pytest\n'), ((364, 412), 'pytest.mark.parametrize', 'pytest.mark.parametrize', (['"""rdtype"""', 'dtlike_dtypes'], {}), "('rdtype', dtlike_dtypes)\n", (3... |
# -*- coding: utf-8 -*-
"""
Decorators
----------
Sometimes you need selectively run tests. For that reason you can tag your tests:
.. code-block:: python
# test_acceptance.py
import unittest
from morelia import run
from morelia.decorators import tags
class CalculatorTestCase(unittest.TestCas... | [
"os.environ.get"
] | [((2589, 2623), 'os.environ.get', 'os.environ.get', (['"""MORELIA_TAGS"""', '""""""'], {}), "('MORELIA_TAGS', '')\n", (2603, 2623), False, 'import os\n')] |
from collections import deque
class FrontMiddleBackQueue:
def __init__(self):
self.front = deque([])
self.back = deque([])
def pushFront(self, val: int) -> None:
self.front.appendleft(val)
if len(self.front) > len(self.back) + 1:
self.back.appendleft(self.front... | [
"collections.deque"
] | [((107, 116), 'collections.deque', 'deque', (['[]'], {}), '([])\n', (112, 116), False, 'from collections import deque\n'), ((137, 146), 'collections.deque', 'deque', (['[]'], {}), '([])\n', (142, 146), False, 'from collections import deque\n')] |
import pathlib
from setuptools import setup
CWD = pathlib.Path(__file__).parent
README = (CWD / "README.rst").read_text()
setup(
name='django-referer',
version='0.1.0',
description='Keep HTTP referer information on query parameter and display referer information',
packages=["referer", "referer/middle... | [
"setuptools.setup",
"pathlib.Path"
] | [((125, 707), 'setuptools.setup', 'setup', ([], {'name': '"""django-referer"""', 'version': '"""0.1.0"""', 'description': '"""Keep HTTP referer information on query parameter and display referer information"""', 'packages': "['referer', 'referer/middleware']", 'include_package_data': '(True)', 'install_requires': "['Dj... |
import time
import math
def project_euler_97():
return (28433 * pow(2, 7830457) + 1) % 10**10
if __name__ == '__main__':
print('Project Euler #97')
print('Find the last ten digits of 28433×2^7830457 + 1.')
START_TIME = time.time()
print('Result: {}'.format(project_euler_97()))
print('Elapsed t... | [
"time.time"
] | [((237, 248), 'time.time', 'time.time', ([], {}), '()\n', (246, 248), False, 'import time\n'), ((344, 355), 'time.time', 'time.time', ([], {}), '()\n', (353, 355), False, 'import time\n')] |
from __future__ import unicode_literals
import sys
from pre_commit.xargs import xargs
ENVIRONMENT_DIR = None
GREP = 'ggrep' if sys.platform == 'darwin' else 'grep'
def install_environment(
repo_cmd_runner,
version='default',
additional_dependencies=(),
):
"""Installation for pcre type ... | [
"pre_commit.xargs.xargs"
] | [((684, 718), 'pre_commit.xargs.xargs', 'xargs', (['cmd', 'file_args'], {'negate': '(True)'}), '(cmd, file_args, negate=True)\n', (689, 718), False, 'from pre_commit.xargs import xargs\n')] |
# Author : <NAME>
# Date : 2019-03-28 22:30:00
# Python Ver : 3.6
# Description : Second gen of read email module, added more functions
import imaplib
import re
import email
import datetime
import pandas
def read_appts(): #function that returns a list of email messages on new appointments
M... | [
"imaplib.IMAP4_SSL",
"datetime.datetime.strptime",
"datetime.timedelta",
"email.message_from_bytes",
"re.search"
] | [((323, 358), 'imaplib.IMAP4_SSL', 'imaplib.IMAP4_SSL', (['"""imap.gmail.com"""'], {}), "('imap.gmail.com')\n", (340, 358), False, 'import imaplib\n'), ((1676, 1742), 'datetime.datetime.strptime', 'datetime.datetime.strptime', (["(date + ' ' + time)", '"""%B %d %Y %I:%M %p"""'], {}), "(date + ' ' + time, '%B %d %Y %I:%... |
import numpy as np
from src.dqn.replay.memory import Memory
from src.dqn.replay.sum_tree import SumTree
class PERMemory(Memory):
def __init__(self, size, state_size, alpha, beta, epsilon, beta_grow):
super().__init__(size, state_size)
self.alpha = alpha
self.beta = beta
self.epsil... | [
"numpy.abs",
"numpy.power",
"numpy.empty",
"numpy.random.uniform",
"src.dqn.replay.sum_tree.SumTree"
] | [((424, 442), 'src.dqn.replay.sum_tree.SumTree', 'SumTree', (['self.size'], {}), '(self.size)\n', (431, 442), False, 'from src.dqn.replay.sum_tree import SumTree\n'), ((840, 879), 'numpy.empty', 'np.empty', (['(batch_size, self.state_size)'], {}), '((batch_size, self.state_size))\n', (848, 879), True, 'import numpy as ... |
import os
import numpy as np
import matplotlib.pyplot as plt
import pyvips as Vips
NP_DTYPE_TO_VIPS_FORMAT = {
np.dtype('int8'): Vips.BandFormat.CHAR,
np.dtype('uint8'): Vips.BandFormat.UCHAR,
np.dtype('int16'): Vips.BandFormat.SHORT,
np.dtype('uint16'): Vips.BandFormat.USHORT,
... | [
"os.path.exists",
"matplotlib.pyplot.get_cmap",
"os.makedirs",
"numpy.max",
"os.path.basename",
"pyvips.Image.dzsave",
"numpy.dtype",
"matplotlib.pyplot.show"
] | [((121, 137), 'numpy.dtype', 'np.dtype', (['"""int8"""'], {}), "('int8')\n", (129, 137), True, 'import numpy as np\n'), ((169, 186), 'numpy.dtype', 'np.dtype', (['"""uint8"""'], {}), "('uint8')\n", (177, 186), True, 'import numpy as np\n'), ((219, 236), 'numpy.dtype', 'np.dtype', (['"""int16"""'], {}), "('int16')\n", (... |
# -*- coding: utf-8 -*-
###
# (C) Copyright [2020] Hewlett Packard Enterprise Development LP
#
# 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
#... | [
"config_loader.try_load_from_file",
"hpeOneView.oneview_client.OneViewClient",
"pprint.pprint"
] | [((1697, 1723), 'config_loader.try_load_from_file', 'try_load_from_file', (['config'], {}), '(config)\n', (1715, 1723), False, 'from config_loader import try_load_from_file\n'), ((1742, 1763), 'hpeOneView.oneview_client.OneViewClient', 'OneViewClient', (['config'], {}), '(config)\n', (1755, 1763), False, 'from hpeOneVi... |
from torch import nn
import torch.nn.functional as F
from ssd.modeling import registry
from ssd.modeling.anchors.prior_box import PriorBox
from ssd.modeling.box_head.box_predictor import make_box_predictor
from ssd.utils import box_utils
from .inference import PostProcessor
from .loss import MultiBoxLoss, FocalLoss
... | [
"ssd.modeling.registry.BOX_HEADS.register",
"ssd.utils.box_utils.convert_locations_to_boxes",
"ssd.modeling.box_head.box_predictor.make_box_predictor",
"ssd.utils.box_utils.center_form_to_corner_form",
"ssd.modeling.anchors.prior_box.PriorBox",
"torch.nn.functional.softmax"
] | [((321, 362), 'ssd.modeling.registry.BOX_HEADS.register', 'registry.BOX_HEADS.register', (['"""SSDBoxHead"""'], {}), "('SSDBoxHead')\n", (348, 362), False, 'from ssd.modeling import registry\n'), ((496, 519), 'ssd.modeling.box_head.box_predictor.make_box_predictor', 'make_box_predictor', (['cfg'], {}), '(cfg)\n', (514,... |
"""
Make a compund path -- in this case two simple polygons, a rectangle
and a triangle. Use CLOSEOPOLY and MOVETO for the different parts of
the compound path
"""
import numpy as np
from matplotlib.path import Path
from matplotlib.patches import PathPatch
import matplotlib.pyplot as plt
vertices = []
codes = []
co... | [
"matplotlib.path.Path",
"numpy.array",
"matplotlib.pyplot.figure",
"matplotlib.patches.PathPatch",
"matplotlib.pyplot.show"
] | [((541, 566), 'numpy.array', 'np.array', (['vertices', 'float'], {}), '(vertices, float)\n', (549, 566), True, 'import numpy as np\n'), ((574, 595), 'matplotlib.path.Path', 'Path', (['vertices', 'codes'], {}), '(vertices, codes)\n', (578, 595), False, 'from matplotlib.path import Path\n'), ((609, 661), 'matplotlib.patc... |
import time
import sys
import pathlib
import logging
import cv2
from tools.test_detect import MtcnnDetector
logger = logging.getLogger("app")
formatter = logging.Formatter('%(asctime)s %(levelname)-8s: %(message)s')
console_handler = logging.StreamHandler(sys.stdout)
logger.addHandler(console_handler)
logger.setLevel(... | [
"logging.getLogger",
"logging.StreamHandler",
"pathlib.Path",
"logging.Formatter",
"tools.test_detect.MtcnnDetector",
"cv2.cvtColor",
"time.time"
] | [((118, 142), 'logging.getLogger', 'logging.getLogger', (['"""app"""'], {}), "('app')\n", (135, 142), False, 'import logging\n'), ((155, 216), 'logging.Formatter', 'logging.Formatter', (['"""%(asctime)s %(levelname)-8s: %(message)s"""'], {}), "('%(asctime)s %(levelname)-8s: %(message)s')\n", (172, 216), False, 'import ... |
from django.db import models
class Population(models.Model):
total = models.PositiveIntegerField()
male = models.PositiveIntegerField()
female = models.PositiveIntegerField()
hindu = models.PositiveIntegerField()
buddhist = models.PositiveIntegerField()
muslim = models.PositiveIntegerField()
... | [
"django.db.models.PositiveIntegerField"
] | [((75, 104), 'django.db.models.PositiveIntegerField', 'models.PositiveIntegerField', ([], {}), '()\n', (102, 104), False, 'from django.db import models\n'), ((116, 145), 'django.db.models.PositiveIntegerField', 'models.PositiveIntegerField', ([], {}), '()\n', (143, 145), False, 'from django.db import models\n'), ((159,... |
#!/usr/bin/env python
# -*- encoding: utf-8 -*-
"""
__file__ = 'receive.py'
__author__ = 'king'
__time__ = '2022/04/02 10:36:52'
__version__ = '1.0'
"""
import time
from oslo_config import cfg
import oslo_messaging as messaging
transport_url = "rabbit://guest:guest@127.0.0.1:5672/"
class Endpoint(object... | [
"time.sleep",
"oslo_messaging.get_rpc_server",
"oslo_messaging.get_rpc_transport",
"oslo_messaging.Target"
] | [((760, 821), 'oslo_messaging.get_rpc_transport', 'messaging.get_rpc_transport', ([], {'conf': 'cfg.CONF', 'url': 'transport_url'}), '(conf=cfg.CONF, url=transport_url)\n', (787, 821), True, 'import oslo_messaging as messaging\n'), ((831, 880), 'oslo_messaging.Target', 'messaging.Target', ([], {'topic': '"""test"""', '... |
#!/usr/bin/env python
"""This script removes n percent of annotated paragraphs from the MediaWiki
dump and writes them to a test file. The training file remains valid XML.
$ bzcat nlwiki-latest-pages-articles.xml.bz2 | python split_train_test.py 0.05 nl_test.txt > nl_train.xml
Author: <NAME>
"""
from __future__ impo... | [
"random.randint",
"argparse.ArgumentParser",
"sys.stdout.write"
] | [((437, 524), 'argparse.ArgumentParser', 'argparse.ArgumentParser', ([], {'description': '__doc__', 'formatter_class': 'RawTextHelpFormatter'}), '(description=__doc__, formatter_class=\n RawTextHelpFormatter)\n', (460, 524), False, 'import argparse, sys\n'), ((1157, 1179), 'sys.stdout.write', 'sys.stdout.write', (['... |
from collections import deque
from functools import reduce
from itertools import islice
from os import makedirs, path
from pprint import PrettyPrinter
from random import sample
import quantumrandom
it_consumes = (
lambda it, n=None: deque(it, maxlen=0)
if n is None
else next(islice(it, n, n), None)
)
pp ... | [
"random.sample",
"itertools.islice",
"collections.deque",
"os.makedirs",
"os.path.join",
"os.path.normpath",
"os.path.dirname",
"os.path.isdir",
"pprint.PrettyPrinter",
"os.path.basename",
"quantumrandom.get_data"
] | [((322, 345), 'pprint.PrettyPrinter', 'PrettyPrinter', ([], {'indent': '(4)'}), '(indent=4)\n', (335, 345), False, 'from pprint import PrettyPrinter\n'), ((930, 946), 'random.sample', 'sample', (['whole', 'n'], {}), '(whole, n)\n', (936, 946), False, 'from random import sample\n'), ((1691, 1712), 'os.path.isdir', 'path... |
from nose.tools import assert_raises, assert_equal
from boids.flock import Flock
from boids.flight import Flight
import yaml
import os
def test_init():
_ROOT = os.path.abspath(os.path.dirname(__file__))
with open(os.path.join(_ROOT,'config_correct.yaml')) as config_file:
config = yaml.load(config_file... | [
"boids.flock.Flock",
"os.path.join",
"yaml.load",
"nose.tools.assert_raises",
"os.path.dirname",
"boids.flight.Flight"
] | [((1862, 1960), 'boids.flock.Flock', 'Flock', (['boid_number', 'x_position_limits', 'y_position_limits', 'x_velocity_limits', 'y_velocity_limits'], {}), '(boid_number, x_position_limits, y_position_limits, x_velocity_limits,\n y_velocity_limits)\n', (1867, 1960), False, 'from boids.flock import Flock\n'), ((2036, 21... |
from brown.core.accidental import Accidental
from brown.core.music_text import MusicText
from brown.core.object_group import ObjectGroup
from brown.core.staff_object import StaffObject
from brown.models.accidental_type import AccidentalType
from brown.models.clef_type import ClefType
from brown.models.key_signature_typ... | [
"brown.core.music_text.MusicText.__init__",
"brown.core.staff_object.StaffObject.__init__"
] | [((1368, 1401), 'brown.core.staff_object.StaffObject.__init__', 'StaffObject.__init__', (['self', 'staff'], {}), '(self, staff)\n', (1388, 1401), False, 'from brown.core.staff_object import StaffObject\n'), ((4093, 4213), 'brown.core.music_text.MusicText.__init__', 'MusicText.__init__', (['self', 'pos', 'Accidental._ca... |
# -*- coding: utf-8 -*-
#
# This file is part of REANA.
# Copyright (C) 2017, 2018, 2019, 2020, 2021, 2022 CERN.
#
# REANA is free software; you can redistribute it and/or modify it
# under the terms of the MIT License; see LICENSE file for more details.
"""REANA client configuration commands."""
import json
import lo... | [
"traceback.format_exc",
"click.group",
"click.option",
"json.dumps",
"reana_client.printer.display_message",
"reana_client.api.client.info",
"reana_client.api.client.ping",
"sys.exit",
"reana_client.utils.get_api_url"
] | [((580, 622), 'click.group', 'click.group', ([], {'help': '"""Configuration commands"""'}), "(help='Configuration commands')\n", (591, 622), False, 'import click\n'), ((2543, 2654), 'click.option', 'click.option', (['"""--json"""', '"""output_format"""'], {'flag_value': '"""json"""', 'default': 'None', 'help': '"""Get ... |
# -*- coding: utf-8 -*-
from netmiko import ConnectHandler
class NetmikoOperator():
def __init__(self):
self.net_connect = {}
self.device = ""
def open_session(self,ip,username,password,device,hostname):
# open session to target device
if hostname in self.net_connect:
... | [
"netmiko.ConnectHandler"
] | [((609, 634), 'netmiko.ConnectHandler', 'ConnectHandler', ([], {}), '(**handler)\n', (623, 634), False, 'from netmiko import ConnectHandler\n')] |
#! python3
# -*- coding: utf-8 -*-
#
# Flicket - copyright <NAME>: <EMAIL>
"""
Uploads
=======
Get Upload By ID
~~~~~~~~~~~~~~~~
.. http:get:: /flicket-api/upload/(int:upload_id)
**Request**
.. sourcecode:: http
GET /flicket-api/upload/1 HTTP/1.1
HOST: l... | [
"application.flicket.models.flicket_models.FlicketUploads.to_collection_dict",
"flask.request.args.get",
"application.flicket.models.flicket_models.FlicketUploads.query.get_or_404",
"flask.jsonify"
] | [((4532, 4617), 'application.flicket.models.flicket_models.FlicketUploads.to_collection_dict', 'FlicketUploads.to_collection_dict', (['uploads', 'page', 'per_page', '"""bp_api.get_uploads"""'], {}), "(uploads, page, per_page, 'bp_api.get_uploads'\n )\n", (4565, 4617), False, 'from application.flicket.models.flicket_... |
import random
votes = []
stimme = None
Rollennummer = 1 # Spieler ID
gesamt_spieler = [] # Ort zum Sammeln aller Spielernamen
spieler_nummer = {} # Ort zum Sammeln von Spieler ID und zugewiesener Spieler
for x in range(0, 4): # 4 Spieler eingeben
spielername = input("Was ist ihr Spielername? ") # Spielernam... | [
"random.randint"
] | [((1008, 1028), 'random.randint', 'random.randint', (['(1)', '(2)'], {}), '(1, 2)\n', (1022, 1028), False, 'import random\n')] |
import json
# Loads env file
# Don't use .env on Replit
import os
secrets = { }
if ("REPL_SLUG" in os.environ and "REPLIT_DB_URL" in os.environ and "REPL_ID" in os.environ and "REPL_IMAGE" in os.environ and "REPL_LANGUAGE" in os.environ and "REPL_OWNER" in os.environ and "REPL_PUBKEYS" in os.environ and "REPL_SLUG" in... | [
"scratchclient.ScratchSession",
"os.environ.get",
"time.sleep",
"getpass.getpass",
"datetime.datetime.now",
"dotenv.dotenv_values"
] | [((1482, 1554), 'scratchclient.ScratchSession', 'ScratchSession', (["secrets['SCRATCH_USERNAME']", "secrets['SCRATCH_PASSWORD']"], {}), "(secrets['SCRATCH_USERNAME'], secrets['SCRATCH_PASSWORD'])\n", (1496, 1554), False, 'from scratchclient import ScratchSession\n'), ((985, 1072), 'getpass.getpass', 'getpass', ([], {'p... |
import setuptools
import subprocess
import os
cfbs_version = subprocess.run(['git', 'describe', '--tags'], stdout=subprocess.PIPE).stdout.decode("utf-8").strip()
if "-" in cfbs_version:
# when not on tag, git describe outputs: "1.3.3-22-gdf81228"
# pip has gotten strict with version numbers
# so change it ... | [
"os.path.isfile",
"subprocess.run",
"setuptools.find_packages"
] | [((564, 597), 'os.path.isfile', 'os.path.isfile', (['"""cfbs/version.py"""'], {}), "('cfbs/version.py')\n", (578, 597), False, 'import os\n'), ((1119, 1145), 'setuptools.find_packages', 'setuptools.find_packages', ([], {}), '()\n', (1143, 1145), False, 'import setuptools\n'), ((62, 131), 'subprocess.run', 'subprocess.r... |
"""
Results generated
0: Number of hospitals
1: Mean time to thrombolysis
2: Max time to thrombolysis
3: Mean time to thrombectomy
4: Maximum time to thrombectomy
5: Minimum thrombolysis admissions to any one hospital
6: Maximum thrombolysis admissions to any one hospital
7: Minimum thrombectomy admissions to ... | [
"numpy.unique",
"pandas.DataFrame",
"numpy.max",
"classes.score.Score_population",
"numpy.sum",
"datetime.datetime.now",
"numpy.vstack",
"classes.pareto.Pareto",
"classes.data.Data",
"classes.score_with_diagnostic.Score_population_with_diagnostic",
"time.time",
"classes.population.Pop"
] | [((2174, 2180), 'classes.data.Data', 'Data', ([], {}), '()\n', (2178, 2180), False, 'from classes.data import Data\n'), ((2200, 2205), 'classes.population.Pop', 'Pop', ([], {}), '()\n', (2203, 2205), False, 'from classes.population import Pop\n'), ((8850, 8896), 'pandas.DataFrame', 'pd.DataFrame', (['self.score.results... |
"""This module contains utilities to merge data together."""
from __future__ import annotations
from contextlib import suppress
from typing import TYPE_CHECKING
from griffe.logger import get_logger
if TYPE_CHECKING:
from griffe.dataclasses import Attribute, Class, Function, Module, Object
logger = get_logger(... | [
"griffe.logger.get_logger",
"contextlib.suppress"
] | [((309, 329), 'griffe.logger.get_logger', 'get_logger', (['__name__'], {}), '(__name__)\n', (319, 329), False, 'from griffe.logger import get_logger\n'), ((877, 895), 'contextlib.suppress', 'suppress', (['KeyError'], {}), '(KeyError)\n', (885, 895), False, 'from contextlib import suppress\n'), ((1497, 1515), 'contextli... |
"""-----------------------------------------------------------------------------
sample.py (Last Updated: 01/26/2021)
The purpose of this script is to actually to run the sample project.
Specifically, it will initiate a call to file watcher that searches for incoming
dicom files, do some sort of analysis based on the... | [
"nibabel.nicom.dicomreaders.mosaic_to_nii",
"scipy.io.savemat",
"rtCommon.imageHandling.convertDicomImgToNifti",
"argparse.ArgumentParser",
"rtCommon.imageHandling.readRetryDicomFromDataInterface",
"rtCommon.dataInterface.DataInterface",
"os.path.join",
"warnings.catch_warnings",
"os.path.realpath",... | [((2594, 2619), 'sys.path.append', 'sys.path.append', (['rootPath'], {}), '(rootPath)\n', (2609, 2619), False, 'import sys\n'), ((3000, 3042), 'os.path.join', 'os.path.join', (['currPath', '"""conf/sample.toml"""'], {}), "(currPath, 'conf/sample.toml')\n", (3012, 3042), False, 'import os\n'), ((1972, 1997), 'warnings.c... |
#ABC051b
import sys
input = sys.stdin.readline
sys.setrecursionlimit(10**6)
k, s = map(int, input().split())
c = 0
for x in range(k + 1):
for y in range(k + 1):
if (0 <= s - x - y <= k):
c += 1
print(c) | [
"sys.setrecursionlimit"
] | [((47, 77), 'sys.setrecursionlimit', 'sys.setrecursionlimit', (['(10 ** 6)'], {}), '(10 ** 6)\n', (68, 77), False, 'import sys\n')] |
import numpy as np
from .base_classifier import BaseClassifier
from regex.handlers import CaptureHandler
from collections import defaultdict
class CaptureClassifier(BaseClassifier):
"""Class specialized in capturing information of interest. E.g Country of Birth
"""
def __init__(self, classifier_name="Capt... | [
"numpy.array",
"regex.handlers.CaptureHandler",
"collections.defaultdict"
] | [((413, 429), 'regex.handlers.CaptureHandler', 'CaptureHandler', ([], {}), '()\n', (427, 429), False, 'from regex.handlers import CaptureHandler\n'), ((5639, 5654), 'numpy.array', 'np.array', (['preds'], {}), '(preds)\n', (5647, 5654), True, 'import numpy as np\n'), ((4126, 4142), 'collections.defaultdict', 'defaultdic... |
from starlette.datastructures import CommaSeparatedStrings
import os
ALLOWED_HOSTS = CommaSeparatedStrings(os.getenv("ALLOWED_HOSTS", ""))
PROJECT_NAME = "TodayApp"
| [
"os.getenv"
] | [((108, 138), 'os.getenv', 'os.getenv', (['"""ALLOWED_HOSTS"""', '""""""'], {}), "('ALLOWED_HOSTS', '')\n", (117, 138), False, 'import os\n')] |
# Copyright (c) 2017 nexB Inc. and others. All rights reserved.
# http://nexb.com and https://github.com/nexB/vulnerablecode/
# The VulnerableCode software is licensed under the Apache License version 2.0.
# Data generated with VulnerableCode require an acknowledgment.
#
# You may not use this software except in compli... | [
"vulnerabilities.package_managers.RubyVersionAPI",
"collections.OrderedDict",
"pathlib.Path",
"vulnerabilities.data_source.Reference",
"os.path.join",
"vulnerabilities.importers.ruby.RubyDataSource",
"os.path.abspath",
"unittest.mock.patch"
] | [((1866, 1909), 'os.path.join', 'os.path.join', (['BASE_DIR', '"""test_data"""', '"""ruby"""'], {}), "(BASE_DIR, 'test_data', 'ruby')\n", (1878, 1909), False, 'import os\n'), ((1827, 1852), 'os.path.abspath', 'os.path.abspath', (['__file__'], {}), '(__file__)\n', (1842, 1852), False, 'import os\n'), ((2367, 2474), 'uni... |
# Copyright 2017 reinforce.io. 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 applicable law or... | [
"tensorflow.logical_not",
"tensorflow.range",
"tensorflow.where",
"tensorflow.gather",
"tensorflow.reshape",
"tensorflow.minimum"
] | [((1820, 1852), 'tensorflow.minimum', 'tf.minimum', ([], {'x': 'n', 'y': 'num_timesteps'}), '(x=n, y=num_timesteps)\n', (1830, 1852), True, 'import tensorflow as tf\n'), ((2015, 2070), 'tensorflow.gather', 'tf.gather', ([], {'params': 'self.terminal_memory', 'indices': 'indices'}), '(params=self.terminal_memory, indice... |
import numpy as np
from detection_utilities import detect
class YoloExecutor:
def __init__(self):
self.detections = []
def get_labels(self, input_frame: np.ndarray):
print(f'Length of detections: {len(self.detections)}')
self.detections = detect(input_frame=input_frame, operation='ad... | [
"detection_utilities.detect"
] | [((275, 323), 'detection_utilities.detect', 'detect', ([], {'input_frame': 'input_frame', 'operation': '"""add"""'}), "(input_frame=input_frame, operation='add')\n", (281, 323), False, 'from detection_utilities import detect\n')] |
from os import path
import os
from .utils.fastly_api_util import FastlyApiClient
from .utils import fs_util, cli_util
from . import instrumentator, logs_collector, logs_processor, reporter
from .constants import SYSLOG_INSTRUMENTATION_NAME
def upload_instrumented_version(fastly_client, proxy_remote_addr):
"""
... | [
"os.path.join",
"os.getcwd"
] | [((2840, 2867), 'os.path.join', 'path.join', (['"""/tmp"""', '"""syslog"""'], {}), "('/tmp', 'syslog')\n", (2849, 2867), False, 'from os import path\n'), ((3053, 3085), 'os.path.join', 'path.join', (['logs_path', '"""messages"""'], {}), "(logs_path, 'messages')\n", (3062, 3085), False, 'from os import path\n'), ((3680,... |
from serif.theory.serif_theory import SerifTheory
from serif.xmlio import _SimpleAttribute
class AlternatePOS(SerifTheory):
tag = _SimpleAttribute(is_required=True)
prob = _SimpleAttribute(float)
| [
"serif.xmlio._SimpleAttribute"
] | [((136, 170), 'serif.xmlio._SimpleAttribute', '_SimpleAttribute', ([], {'is_required': '(True)'}), '(is_required=True)\n', (152, 170), False, 'from serif.xmlio import _SimpleAttribute\n'), ((182, 205), 'serif.xmlio._SimpleAttribute', '_SimpleAttribute', (['float'], {}), '(float)\n', (198, 205), False, 'from serif.xmlio... |
import io
import json
import os
import time
import unittest
import requests
from localstack import config
from localstack.services.generic_proxy import ProxyListener, start_proxy_server
from localstack.utils.aws import aws_stack
from localstack.utils.bootstrap import is_api_enabled
from localstack.utils.common import... | [
"requests.post",
"localstack.utils.common.get_free_tcp_port",
"localstack.utils.common.to_str",
"io.BytesIO",
"localstack.services.generic_proxy.start_proxy_server",
"time.sleep",
"localstack.utils.bootstrap.is_api_enabled",
"os.environ.get",
"os.environ.pop",
"localstack.utils.common.short_uid",
... | [((612, 632), 'localstack.utils.bootstrap.is_api_enabled', 'is_api_enabled', (['"""s3"""'], {}), "('s3')\n", (626, 632), False, 'from localstack.utils.bootstrap import is_api_enabled\n'), ((754, 779), 'localstack.utils.bootstrap.is_api_enabled', 'is_api_enabled', (['"""kinesis"""'], {}), "('kinesis')\n", (768, 779), Fa... |
#!/usr/bin/env python3
__description__ = \
"""
Create a name file and sanitized fasta file from a uniprot fasta file.
A name file can be used in conjunction with editNames.py to convert the strings
within text files between human-readable and phyml readable formats. The
sanitized fasta file is ready to be edited wit... | [
"re.sub"
] | [((1241, 1267), 're.sub', 're.sub', (['""":"""', '"""-"""', 'out_line'], {}), "(':', '-', out_line)\n", (1247, 1267), False, 'import sys, re\n'), ((1281, 1307), 're.sub', 're.sub', (['""","""', '"""-"""', 'out_line'], {}), "(',', '-', out_line)\n", (1287, 1307), False, 'import sys, re\n'), ((1321, 1351), 're.sub', 're.... |
import logging
from brownie import web3
from scripts.utils.gas_strategy import GasFeeStrategy
from tests.fixtures.pytest_fixtures import setup_web3_gas_fee_fixtures
from tests.utils.logs import find_log_message
def test_percentile_calculate(caplog, setup_web3_gas_fee_fixtures):
caplog.set_level(logging.INFO)
... | [
"scripts.utils.gas_strategy.GasFeeStrategy",
"tests.utils.logs.find_log_message"
] | [((342, 362), 'scripts.utils.gas_strategy.GasFeeStrategy', 'GasFeeStrategy', (['web3'], {}), '(web3)\n', (356, 362), False, 'from scripts.utils.gas_strategy import GasFeeStrategy\n'), ((592, 642), 'tests.utils.logs.find_log_message', 'find_log_message', (['caplog', '"""Use cached gas history"""'], {}), "(caplog, 'Use c... |
import glob
import os
import sys
import sysconfig
from typing import Any, Optional, Tuple
from .common import code_object_replace
from .finder import ModuleFinder
from .module import Module
MINGW = sysconfig.get_platform() == "mingw"
WIN32 = sys.platform == "win32"
def initialize(finder: ModuleFinder) -> None:
... | [
"os.path.exists",
"os.getenv",
"os.path.join",
"sys.platform.startswith",
"os.path.dirname",
"os.path.isdir",
"sysconfig.get_platform",
"os.path.basename",
"sys.platform.split"
] | [((200, 224), 'sysconfig.get_platform', 'sysconfig.get_platform', ([], {}), '()\n', (222, 224), False, 'import sysconfig\n'), ((9400, 9428), 'os.path.dirname', 'os.path.dirname', (['module.file'], {}), '(module.file)\n', (9415, 9428), False, 'import os\n'), ((19544, 19588), 'os.path.join', 'os.path.join', (['"""lib"""'... |
from src.data_loader.data_set import Data_Set
from src.utils import read_json
from easydict import EasyDict as edict
from src.constants import TRAINING_CONFIG_PATH
from src.data_loader.utils import error_in_conversion, get_data
from tqdm import tqdm
def main():
train_param = edict(read_json(TRAINING_CONFIG_PATH))... | [
"src.utils.read_json",
"src.data_loader.utils.error_in_conversion",
"src.data_loader.utils.get_data"
] | [((332, 434), 'src.data_loader.utils.get_data', 'get_data', (['Data_Set', 'train_param'], {'sources': "['youtube']", 'experiment_type': '"""supervised"""', 'split': '"""train"""'}), "(Data_Set, train_param, sources=['youtube'], experiment_type=\n 'supervised', split='train')\n", (340, 434), False, 'from src.data_loa... |
from rllab.misc import logger
import matplotlib as mpl
mpl.use('Agg')
import matplotlib.pyplot as plt
import os.path as osp
import numpy as np
import math
import random
def line_intersect(pt1, pt2, ptA, ptB):
"""
Taken from https://www.cs.hmc.edu/ACM/lectures/intersections.html
this returns the intersect... | [
"numpy.ones",
"matplotlib.use",
"matplotlib.pyplot.plot",
"os.path.join",
"matplotlib.pyplot.close",
"numpy.array",
"math.cos",
"rllab.misc.logger.get_snapshot_dir",
"math.fabs",
"matplotlib.pyplot.scatter",
"math.sin",
"matplotlib.pyplot.subplots",
"numpy.arange"
] | [((55, 69), 'matplotlib.use', 'mpl.use', (['"""Agg"""'], {}), "('Agg')\n", (62, 69), True, 'import matplotlib as mpl\n'), ((15460, 15474), 'matplotlib.pyplot.subplots', 'plt.subplots', ([], {}), '()\n', (15472, 15474), True, 'import matplotlib.pyplot as plt\n'), ((16510, 16537), 'matplotlib.pyplot.scatter', 'plt.scatte... |
#!/usr/bin/env python3
import re
import os
VERSION_FILE = 'app/build.gradle'
VERSION_TAG = 'versionName \"([0-9]*).([0-9]*)\"'
SCRIPT_DIR = os.path.abspath(os.path.dirname(__file__))
ROOT_DIR = os.path.join(SCRIPT_DIR, '..')
def lookupVersion():
with open(f'{ROOT_DIR}/{VERSION_FILE}', 'r') as fl:
data = ... | [
"os.path.dirname",
"os.path.join",
"re.search"
] | [((195, 225), 'os.path.join', 'os.path.join', (['SCRIPT_DIR', '""".."""'], {}), "(SCRIPT_DIR, '..')\n", (207, 225), False, 'import os\n'), ((157, 182), 'os.path.dirname', 'os.path.dirname', (['__file__'], {}), '(__file__)\n', (172, 182), False, 'import os\n'), ((339, 367), 're.search', 're.search', (['VERSION_TAG', 'da... |
#
# Licensed to the Apache Software Foundation (ASF) under one
# or more contributor license agreements. See the NOTICE file
# distributed with this work for additional information
# regarding copyright ownership. The ASF licenses this file
# to you under the Apache License, Version 2.0 (the
# "License"); you may not... | [
"tests.test_utils.db.clear_rendered_ti_fields",
"airflow.utils.session.create_session",
"airflow.operators.bash.BashOperator",
"airflow.models.Variable.set",
"airflow.models.RenderedTaskInstanceFields",
"airflow.models.DAG",
"pytest.mark.usefixtures",
"tests.test_utils.db.clear_db_runs",
"pytest.fix... | [((1401, 1430), 'airflow.utils.timezone.datetime', 'timezone.datetime', (['(2020)', '(3)', '(1)'], {}), '(2020, 3, 1)\n', (1418, 1430), False, 'from airflow.utils import timezone\n'), ((1434, 1450), 'pytest.fixture', 'pytest.fixture', ([], {}), '()\n', (1448, 1450), False, 'import pytest\n'), ((1692, 1708), 'pytest.fix... |
from fastapi import FastAPI
app = FastAPI()
@app.get("/items/{item_id}")
async def read_item(item_id):
print(item_id)
return {"item_id": item_id}
| [
"fastapi.FastAPI"
] | [((35, 44), 'fastapi.FastAPI', 'FastAPI', ([], {}), '()\n', (42, 44), False, 'from fastapi import FastAPI\n')] |
'''An example to show how to set up an pommerman game programmatically'''
import pommerman
from pommerman import agents
import numpy as np
from tqdm import tqdm
def main():
'''Simple function to bootstrap a game.
Use this as an example to set up your training env.
'''
# Print all possible en... | [
"numpy.reshape",
"pommerman.make",
"pommerman.agents.DeepQAgent",
"pommerman.agents.SimpleAgent",
"numpy.ravel"
] | [((1211, 1230), 'pommerman.agents.DeepQAgent', 'agents.DeepQAgent', ([], {}), '()\n', (1228, 1230), False, 'from pommerman import agents\n'), ((1394, 1435), 'pommerman.make', 'pommerman.make', (['"""OneVsOne-v0"""', 'agent_list'], {}), "('OneVsOne-v0', agent_list)\n", (1408, 1435), False, 'import pommerman\n'), ((1171,... |