code stringlengths 22 1.05M | apis listlengths 1 3.31k | extract_api stringlengths 75 3.25M |
|---|---|---|
import numpy as np
import pyastar
# The start and goal coordinates are in matrix coordinates (i, j).
start = (0, 0)
goal = (4, 4)
# The minimum cost must be 1 for the heuristic to be valid.
weights = np.array([[1, 3, 3, 3, 3],
[2, 1, 3, 3, 3],
[2, 2, 1, 3, 3],
... | [
"pyastar.astar_path",
"numpy.array"
] | [((203, 321), 'numpy.array', 'np.array', (['[[1, 3, 3, 3, 3], [2, 1, 3, 3, 3], [2, 2, 1, 3, 3], [2, 2, 2, 1, 3], [2, 2,\n 2, 2, 1]]'], {'dtype': 'np.float32'}), '([[1, 3, 3, 3, 3], [2, 1, 3, 3, 3], [2, 2, 1, 3, 3], [2, 2, 2, 1, 3\n ], [2, 2, 2, 2, 1]], dtype=np.float32)\n', (211, 321), True, 'import numpy as np\n... |
"""
A micro:bit MicroPython implementation of a random string sender for testing's sake.
"""
from microbit import *
import random
import radio
radio.on()
radio.config()
primes = [2, 3, 5, 7, 11, 13, 17, 19]
e = random.choice(primes)
while True:
p = random.choice(primes)
if p % e != -1:
break
... | [
"radio.send",
"radio.config",
"random.choice",
"radio.on"
] | [((145, 155), 'radio.on', 'radio.on', ([], {}), '()\n', (153, 155), False, 'import radio\n'), ((157, 171), 'radio.config', 'radio.config', ([], {}), '()\n', (169, 171), False, 'import radio\n'), ((217, 238), 'random.choice', 'random.choice', (['primes'], {}), '(primes)\n', (230, 238), False, 'import random\n'), ((259, ... |
from pathlib import Path
module_dir = Path.home() / "module_results/basin_rivers"
module_dir.mkdir(exist_ok=True)
| [
"pathlib.Path.home"
] | [((39, 50), 'pathlib.Path.home', 'Path.home', ([], {}), '()\n', (48, 50), False, 'from pathlib import Path\n')] |
"""
Some basic admin tests.
Rather than testing the frontend UI -- that's be a job for something like
Selenium -- this does a bunch of mocking and just tests the various admin
callbacks.
"""
import mock
from django.contrib import admin
from django.contrib.auth import get_user_model
from django.test import TestCase
fro... | [
"fack.admin.QuestionAdmin",
"django.contrib.auth.get_user_model",
"mock.Mock"
] | [((543, 559), 'django.contrib.auth.get_user_model', 'get_user_model', ([], {}), '()\n', (557, 559), False, 'from django.contrib.auth import get_user_model\n'), ((576, 596), 'mock.Mock', 'mock.Mock', ([], {'spec': 'user'}), '(spec=user)\n', (585, 596), False, 'import mock\n'), ((613, 633), 'mock.Mock', 'mock.Mock', ([],... |
# engine/cursor.py
# Copyright (C) 2005-2020 the SQLAlchemy authors and contributors
# <see AUTHORS file>
#
# This module is part of SQLAlchemy and is released under
# the MIT License: http://www.opensource.org/licenses/mit-license.php
"""Define cursor-specific result set constructs including
:class:`.BaseCursorResult... | [
"functools.partial",
"collections.deque"
] | [((35366, 35393), 'collections.deque', 'collections.deque', (['new_rows'], {}), '(new_rows)\n', (35383, 35393), False, 'import collections\n'), ((36952, 36981), 'collections.deque', 'collections.deque', (['buf[size:]'], {}), '(buf[size:])\n', (36969, 36981), False, 'import collections\n'), ((38951, 38980), 'collections... |
from __future__ import absolute_import
# usage example:
#
# ARVADOS_API_TOKEN=abc ARVADOS_API_HOST=arvados.local python -m unittest discover
import unittest
import arvados
import apiclient
from . import run_test_server
class PipelineTemplateTest(run_test_server.TestCaseWithServers):
MAIN_SERVER = {}
KEEP_SERV... | [
"arvados.api"
] | [((971, 988), 'arvados.api', 'arvados.api', (['"""v1"""'], {}), "('v1')\n", (982, 988), False, 'import arvados\n'), ((1665, 1682), 'arvados.api', 'arvados.api', (['"""v1"""'], {}), "('v1')\n", (1676, 1682), False, 'import arvados\n'), ((1991, 2008), 'arvados.api', 'arvados.api', (['"""v1"""'], {}), "('v1')\n", (2002, 2... |
#
# File: vrfcode.py
# Copyright: Grimm Project, Ren Pin NGO, all rights reserved.
# License: MIT
# -------------------------------------------------------------------------
# Authors: <NAME>(<EMAIL>)
#
# Description: generate transaction ID and verification code,
# keeping them unique.
#
# To-Dos:
# 1. make other s... | [
"itsdangerous.URLSafeTimedSerializer",
"random.choices",
"server.sys_logger.error",
"time.time",
"uuid.uuid1",
"server.utils.misctools.is_ipv4_addr",
"server.utils.misctools.get_host_ip"
] | [((2180, 2230), 'itsdangerous.URLSafeTimedSerializer', 'URLSafeTimedSerializer', (["grimm.config['SECRET_KEY']"], {}), "(grimm.config['SECRET_KEY'])\n", (2202, 2230), False, 'from itsdangerous import URLSafeTimedSerializer\n'), ((2651, 2701), 'itsdangerous.URLSafeTimedSerializer', 'URLSafeTimedSerializer', (["grimm.con... |
import os
import pyomo
import pyomo.environ as pe
from pyomo.opt import SolverStatus, TerminationCondition
from blocks.economic_dispatch import EconomicDispatch
from manage_data.import_data import import_data
def run_market_clearing(
edp: EconomicDispatch
):
################################... | [
"os.path.join",
"pyomo.environ.Suffix",
"pyomo.environ.Constraint",
"pyomo.environ.Var",
"os.path.dirname",
"pyomo.environ.Objective",
"pyomo.environ.ConcreteModel",
"pyomo.opt.SolverFactory",
"manage_data.import_data.import_data"
] | [((492, 510), 'pyomo.environ.ConcreteModel', 'pe.ConcreteModel', ([], {}), '()\n', (508, 510), True, 'import pyomo.environ as pe\n'), ((553, 590), 'pyomo.environ.Suffix', 'pe.Suffix', ([], {'direction': 'pe.Suffix.IMPORT'}), '(direction=pe.Suffix.IMPORT)\n', (562, 590), True, 'import pyomo.environ as pe\n'), ((959, 100... |
import math
import random
from os.path import basename
from urllib.request import urlopen
from urllib.parse import unquote
from gi.repository import Gtk, GObject, Pango
from pychess.compat import create_task
from pychess.Players.Human import Human
from pychess.Players.engineNest import discoverer
from pychess.System ... | [
"urllib.parse.unquote",
"pychess.perspectives.games.get_open_dialog",
"pychess.System.uistuff.createCombo",
"pychess.Players.engineNest.discoverer.connect_after",
"gi.repository.Gtk.ListStore",
"pychess.Utils.TimeModel.TimeModel",
"pychess.Players.engineNest.discoverer.getName",
"pychess.System.conf.g... | [((6396, 6433), 'pychess.System.uistuff.GladeWidgets', 'uistuff.GladeWidgets', (['"""taskers.glade"""'], {}), "('taskers.glade')\n", (6416, 6433), False, 'from pychess.System import uistuff, conf\n'), ((10499, 10566), 'pychess.Utils.IconLoader.load_icon', 'load_icon', (['(48)', '"""stock_init"""', '"""gnome-globe"""', ... |
# Unsupervised learning: Iris clustering¶
import seaborn as sns
from sklearn.model_selection import train_test_split
from sklearn.datasets import load_digits
digits = load_digits()
digits.data.shape
digits.data[:10, :10]
digits.images.shape
import matplotlib.pyplot as plt
fig, axes = plt.subplots(10, 10, figsize=(8,... | [
"sklearn.datasets.load_digits",
"sklearn.naive_bayes.GaussianNB",
"matplotlib.pyplot.show",
"seaborn.heatmap",
"sklearn.model_selection.train_test_split",
"sklearn.metrics.accuracy_score",
"matplotlib.pyplot.ylabel",
"sklearn.manifold.Isomap",
"matplotlib.pyplot.clim",
"sklearn.metrics.confusion_m... | [((168, 181), 'sklearn.datasets.load_digits', 'load_digits', ([], {}), '()\n', (179, 181), False, 'from sklearn.datasets import load_digits\n'), ((967, 989), 'sklearn.manifold.Isomap', 'Isomap', ([], {'n_components': '(2)'}), '(n_components=2)\n', (973, 989), False, 'from sklearn.manifold import Isomap\n'), ((1313, 133... |
# Copyright (c) 2015, Frappe Technologies Pvt. Ltd. and Contributors
from __future__ import unicode_literals
import frappe
def execute():
frappe.db.set_value("DocType", "Maintenance Schedule", "module", "Maintenance")
frappe.db.set_value("DocType", "Maintenance Schedule Detail", "module", "Maintenance")
frappe.db.... | [
"frappe.db.set_value"
] | [((141, 220), 'frappe.db.set_value', 'frappe.db.set_value', (['"""DocType"""', '"""Maintenance Schedule"""', '"""module"""', '"""Maintenance"""'], {}), "('DocType', 'Maintenance Schedule', 'module', 'Maintenance')\n", (160, 220), False, 'import frappe\n'), ((222, 312), 'frappe.db.set_value', 'frappe.db.set_value', (['"... |
#!/usr/bin/env python
# Set True to force compile native C-coded extension providing direct access
# to inotify's syscalls. If set to False this extension will only be compiled
# if no inotify interface from ctypes is found.
compile_ext_mod = False
# import statements
import os
import sys
import distutils.extension
f... | [
"ctypes.util.find_library",
"distutils.core.setup",
"distutils.util.get_platform",
"sys.stderr.write",
"ctypes.CDLL",
"sys.exit"
] | [((558, 572), 'distutils.util.get_platform', 'get_platform', ([], {}), '()\n', (570, 572), False, 'from distutils.util import get_platform\n'), ((2373, 2826), 'distutils.core.setup', 'setup', ([], {'name': '"""pyinotify-smarkets"""', 'version': '"""1.0.0"""', 'description': '"""Linux filesystem events monitoring"""', '... |
import logging
import re
import sys
from datetime import datetime
from pathlib import Path
from flexget import plugin
from flexget.config_schema import one_or_more
from flexget.entry import Entry
from flexget.event import event
log = logging.getLogger('filesystem')
class Filesystem:
"""
Uses local path cont... | [
"flexget.entry.Entry",
"flexget.event.event",
"sys.getfilesystemencoding",
"pathlib.Path",
"flexget.plugin.register",
"flexget.config_schema.one_or_more",
"datetime.datetime.fromtimestamp",
"fnmatch.translate",
"logging.getLogger",
"re.compile"
] | [((236, 267), 'logging.getLogger', 'logging.getLogger', (['"""filesystem"""'], {}), "('filesystem')\n", (253, 267), False, 'import logging\n'), ((7650, 7674), 'flexget.event.event', 'event', (['"""plugin.register"""'], {}), "('plugin.register')\n", (7655, 7674), False, 'from flexget.event import event\n'), ((1500, 1568... |
# -*- coding: utf-8 -*-
# Copyright © 2017 Apple Inc. All rights reserved.
#
# Use of this source code is governed by a BSD-3-clause license that can
# be found in the LICENSE.txt file or at https://opensource.org/licenses/BSD-3-Clause
import random as _random
import tarfile as _tarfile
import turicreate as _tc
from t... | [
"turicreate.extensions.one_shot_object_detector",
"random.randint",
"turicreate.toolkits.one_shot_object_detector.util._error_handling.check_one_shot_input",
"turicreate.SArray",
"turicreate.toolkits._data_zoo.OneShotObjectDetectorBackgroundData",
"tarfile.open",
"turicreate.toolkits._internal_utils._ha... | [((1726, 1773), 'turicreate.toolkits.one_shot_object_detector.util._error_handling.check_one_shot_input', 'check_one_shot_input', (['data', 'target', 'backgrounds'], {}), '(data, target, backgrounds)\n', (1746, 1773), False, 'from turicreate.toolkits.one_shot_object_detector.util._error_handling import check_one_shot_i... |
from shutil import rmtree
from argparse import Namespace
from _pytest.tmpdir import TempPathFactory
from _pytest.capture import CaptureFixture
from pytest_mock import MockerFixture
from grizzly_cli.init import tree, init
from .helpers import onerror
def test_tree(tmp_path_factory: TempPathFactory) -> None:
tes... | [
"argparse.Namespace",
"shutil.rmtree",
"grizzly_cli.init.init",
"grizzly_cli.init.tree"
] | [((1018, 1055), 'shutil.rmtree', 'rmtree', (['test_context'], {'onerror': 'onerror'}), '(test_context, onerror=onerror)\n', (1024, 1055), False, 'from shutil import rmtree\n'), ((1398, 1462), 'argparse.Namespace', 'Namespace', ([], {'project': '"""foobar"""', 'with_mq': '(False)', 'grizzly_version': 'None'}), "(project... |
from kivy.uix.tabbedpanel import TabbedPanel, TabbedPanelItem,\
TabbedPanelHeader, TabbedPanelContent
from kivy.properties import ObjectProperty, StringProperty,\
BooleanProperty, NumericProperty
from kivy.uix.boxlayout import BoxLayout
from kivy.uix.gridlayout import GridLayout
from kivy.uix.widget import Widg... | [
"kivy.uix.gridlayout.GridLayout",
"kivy.lang.Builder.load_string",
"kivy.uix.button.Button.add_widget",
"kivy.properties.BooleanProperty",
"kivy.clock.Clock.schedule_once",
"kivy.animation.Animation",
"kivy.metrics.dp",
"kivy.properties.ObjectProperty",
"kivy.uix.scrollview.ScrollView",
"kivy.prop... | [((1927, 1949), 'kivy.properties.BooleanProperty', 'BooleanProperty', (['(False)'], {}), '(False)\n', (1942, 1949), False, 'from kivy.properties import ObjectProperty, StringProperty, BooleanProperty, NumericProperty\n'), ((2359, 2379), 'kivy.properties.ObjectProperty', 'ObjectProperty', (['None'], {}), '(None)\n', (23... |
import asyncio
import inspect
import sys
import time
from contextvars import ContextVar, Token
from types import TracebackType
from typing import Any, Callable, Coroutine, Dict, List, Optional, Type, Union
def current_task(loop: Optional[asyncio.AbstractEventLoop] = None) -> "Optional[asyncio.Task[Any]]":
"""retu... | [
"asyncio.get_event_loop",
"asyncio.TimeoutError",
"asyncio.Task.current_task",
"asyncio.current_task",
"asyncio.get_running_loop",
"time.time",
"inspect.getmodule",
"asyncio.iscoroutine",
"contextvars.ContextVar",
"asyncio.wait_for",
"asyncio.wait",
"asyncio.Future"
] | [((4069, 4113), 'contextvars.ContextVar', 'ContextVar', (['"""deadline_context"""'], {'default': 'None'}), "('deadline_context', default=None)\n", (4079, 4113), False, 'from contextvars import ContextVar, Token\n'), ((688, 712), 'asyncio.get_event_loop', 'asyncio.get_event_loop', ([], {}), '()\n', (710, 712), False, 'i... |
import logging
import re
import shutil
from bs4 import BeautifulSoup
from chibi.file import Chibi_path
from chibi.atlas import Chibi_atlas
from chibi_dl.site.base.site import Site
from chibi_requests import Chibi_url
from .regex import re_image
logger = logging.getLogger( "chibi_dl.sites.ehentai.episode" )
class ... | [
"chibi.atlas.Chibi_atlas",
"logging.getLogger"
] | [((258, 309), 'logging.getLogger', 'logging.getLogger', (['"""chibi_dl.sites.ehentai.episode"""'], {}), "('chibi_dl.sites.ehentai.episode')\n", (275, 309), False, 'import logging\n'), ((609, 633), 'chibi.atlas.Chibi_atlas', 'Chibi_atlas', ([], {'image': 'image'}), '(image=image)\n', (620, 633), False, 'from chibi.atlas... |
import RNA
sequence = "GGGGAAAACCCC"
# Set global switch for unique ML decomposition
RNA.cvar.uniq_ML = 1
subopt_data = { 'counter' : 1, 'sequence' : sequence }
# Print a subopt result as FASTA record
def print_subopt_result(structure, energy, data):
if not structure == None:
print(">subopt {:d}".format... | [
"RNA.fold_compound"
] | [((549, 576), 'RNA.fold_compound', 'RNA.fold_compound', (['sequence'], {}), '(sequence)\n', (566, 576), False, 'import RNA\n')] |
from base64 import urlsafe_b64decode
from django import forms
from phraseless.certificates import deserialize_certificate_chain
class CertificateAuth(forms.Form):
certificate_chain = forms.CharField()
challenge_signature = forms.CharField()
def clean_certificate_chain(self):
return deserialize_... | [
"django.forms.CharField"
] | [((191, 208), 'django.forms.CharField', 'forms.CharField', ([], {}), '()\n', (206, 208), False, 'from django import forms\n'), ((235, 252), 'django.forms.CharField', 'forms.CharField', ([], {}), '()\n', (250, 252), False, 'from django import forms\n')] |
# coding=utf-8
# *** WARNING: this file was generated by pulumigen. ***
# *** Do not edit by hand unless you're certain you know what you are doing! ***
import warnings
import pulumi
import pulumi.runtime
from typing import Any, Mapping, Optional, Sequence, Union
from ... import _utilities, _tables
from . import outpu... | [
"pulumi.get",
"pulumi.getter",
"pulumi.set"
] | [((2084, 2116), 'pulumi.getter', 'pulumi.getter', ([], {'name': '"""apiVersion"""'}), "(name='apiVersion')\n", (2097, 2116), False, 'import pulumi\n'), ((8717, 8751), 'pulumi.getter', 'pulumi.getter', ([], {'name': '"""clientConfig"""'}), "(name='clientConfig')\n", (8730, 8751), False, 'import pulumi\n'), ((11791, 1182... |
#simulate the movement of the rogue AP and recieved RSSI values at the stationary
#APs based on the lognormal shadowing model
#Results will be written in a file to be read by the server to calculate the distance to the rogue AP
#Prx(d) = Prx(d0)-10*n*log(d/d0) + x(0, σ)
#rogue AP moves at a constant speed = 1m/sec
from... | [
"math.sqrt",
"Crypto.Random.random.randrange",
"Crypto.Random.random.choice",
"math.log10",
"numpy.random.normal"
] | [((1323, 1350), 'Crypto.Random.random.choice', 'random.choice', (['[0, 1, 2, 3]'], {}), '([0, 1, 2, 3])\n', (1336, 1350), False, 'from Crypto.Random import random\n'), ((628, 678), 'math.sqrt', 'math.sqrt', (['((b[0] - a[0]) ** 2 + (b[1] - a[1]) ** 2)'], {}), '((b[0] - a[0]) ** 2 + (b[1] - a[1]) ** 2)\n', (637, 678), F... |
import networkx as nx
import pandas as pd
# file = open('/Users/aida/Dropbox/PhD/Internship/RegLab/COVID-Outbreak/node2vec/emb/karate_1.txt')
# i = 0
# for line in file:
# line = line.strip()
# line = line.split(' ')
# line = [float(i) for i in line]
# print(i , line)
# i += 1
df = pd.read_csv('/Users/aid... | [
"pandas.read_csv",
"networkx.get_edge_attributes",
"networkx.Graph",
"networkx.from_pandas_edgelist",
"networkx.write_edgelist"
] | [((297, 407), 'pandas.read_csv', 'pd.read_csv', (['"""/Users/aida/Dropbox/PhD/Internship/RegLab/COVID-Outbreak/node2vec/graph/node_pair.csv"""'], {}), "(\n '/Users/aida/Dropbox/PhD/Internship/RegLab/COVID-Outbreak/node2vec/graph/node_pair.csv'\n )\n", (308, 407), True, 'import pandas as pd\n'), ((515, 525), 'netw... |
# Import modules
import re
from json import loads
from urllib.request import urlopen
from subprocess import check_output, DEVNULL, STDOUT
# MAC address regex
macRegex = re.compile('[0-9a-f]{2}([-:]?)[0-9a-f]{2}(\\1[0-9a-f]{2}){4}$')
# Get router ip address
cmd = 'chcp 65001 && ipconfig | findstr /i \"Default Gat... | [
"subprocess.check_output",
"urllib.request.urlopen",
"json.loads",
"re.compile"
] | [((173, 236), 're.compile', 're.compile', (['"""[0-9a-f]{2}([-:]?)[0-9a-f]{2}(\\\\1[0-9a-f]{2}){4}$"""'], {}), "('[0-9a-f]{2}([-:]?)[0-9a-f]{2}(\\\\1[0-9a-f]{2}){4}$')\n", (183, 236), False, 'import re\n'), ((328, 388), 'subprocess.check_output', 'check_output', (['cmd'], {'shell': '(True)', 'stderr': 'DEVNULL', 'stdin... |
# -*- coding: utf-8 -*-
# *****************************************************************************
# NICOS, the Networked Instrument Control System of the MLZ
# Copyright (c) 2009-2020 by the NICOS contributors (see AUTHORS)
#
# This program is free software; you can redistribute it and/or modify it under
# the t... | [
"nicos.guisupport.qt.pyqtSignal",
"nicos.guisupport.typedvalue.create",
"nicos.guisupport.qt.QWidget",
"nicos.guisupport.utils.DoubleValidator",
"nicos.guisupport.qt.QLineEdit",
"nicos.guisupport.qt.QCheckBox",
"nicos.guisupport.qt.QHBoxLayout",
"nicos.guisupport.qt.QSpinBox",
"nicos.guisupport.qt.Q... | [((1565, 1583), 'nicos.guisupport.qt.pyqtSignal', 'pyqtSignal', (['object'], {}), '(object)\n', (1575, 1583), False, 'from nicos.guisupport.qt import QCheckBox, QComboBox, QHBoxLayout, QLineEdit, QObject, QSpinBox, QWidget, pyqtSignal\n'), ((1713, 1735), 'nicos.guisupport.qt.QObject.__init__', 'QObject.__init__', (['se... |
#!/usr/bin/python
# encoding: utf-8
import random
import os
import torch
from PIL import Image
import numpy as np
from utils import *
import cv2
def scale_image_channel(im, c, v):
cs = list(im.split())
cs[c] = cs[c].point(lambda i: i * v)
out = Image.merge(im.mode, tuple(cs))
return out
def distort_... | [
"random.randint",
"random.uniform",
"os.path.getsize",
"numpy.zeros",
"PIL.Image.open",
"numpy.reshape",
"numpy.loadtxt",
"torch.zeros",
"os.path.join",
"os.listdir",
"torch.from_numpy"
] | [((807, 827), 'random.uniform', 'random.uniform', (['(1)', 's'], {}), '(1, s)\n', (821, 827), False, 'import random\n'), ((1240, 1263), 'random.randint', 'random.randint', (['(-dw)', 'dw'], {}), '(-dw, dw)\n', (1254, 1263), False, 'import random\n'), ((1277, 1300), 'random.randint', 'random.randint', (['(-dw)', 'dw'], ... |
import os
import labelbox2pascal as lb2pa
class TestFromJSON():
def results_output(self):
TEST_OUTPUT_DIR = 'test-results'
if not os.path.isdir(TEST_OUTPUT_DIR):
os.makedirs(TEST_OUTPUT_DIR)
return TEST_OUTPUT_DIR
def test_wkt_1(self):
lb2pa.from_json('test-fixture... | [
"os.path.isdir",
"os.makedirs"
] | [((152, 182), 'os.path.isdir', 'os.path.isdir', (['TEST_OUTPUT_DIR'], {}), '(TEST_OUTPUT_DIR)\n', (165, 182), False, 'import os\n'), ((196, 224), 'os.makedirs', 'os.makedirs', (['TEST_OUTPUT_DIR'], {}), '(TEST_OUTPUT_DIR)\n', (207, 224), False, 'import os\n')] |
import logging
import os
import numpy as np
import torch
from tensorboardX import SummaryWriter
from torch.optim.lr_scheduler import ReduceLROnPlateau
from . import utils
from tqdm import tqdm
from unet3d.utils import unpad_eval
class UNet3DTrainer:
"""3D UNet trainer.
Args:
model (Unet3D): UNet 3D ... | [
"tqdm.tqdm",
"torch.no_grad",
"unet3d.utils.unpad_eval",
"numpy.ptp",
"numpy.min",
"torch.device",
"torch.zeros",
"os.path.split",
"os.path.join",
"torch.from_numpy"
] | [((4275, 4305), 'os.path.split', 'os.path.split', (['checkpoint_path'], {}), '(checkpoint_path)\n', (4288, 4305), False, 'import os\n'), ((4430, 4459), 'torch.device', 'torch.device', (["state['device']"], {}), "(state['device'])\n", (4442, 4459), False, 'import torch\n'), ((5759, 5785), 'os.path.split', 'os.path.split... |
from utilities import listFields, getShp, getOID, statusMessage, parseProp, makeInter
from arcpy import SpatialReference, SearchCursor
from parseGeometry import getParseFunc
from json import dump
#really the only global
wgs84="GEOGCS['GCS_WGS_1984',DATUM['D_WGS_1984',SPHEROID['WGS_1984',6378137.0,298.257223563]],PRI... | [
"utilities.listFields",
"json.dump",
"parseGeometry.getParseFunc",
"utilities.parseProp",
"arcpy.SearchCursor",
"utilities.getShp",
"utilities.getOID",
"utilities.statusMessage",
"arcpy.SpatialReference"
] | [((724, 744), 'utilities.getShp', 'getShp', (['featureClass'], {}), '(featureClass)\n', (730, 744), False, 'from utilities import listFields, getShp, getOID, statusMessage, parseProp, makeInter\n'), ((765, 789), 'utilities.listFields', 'listFields', (['featureClass'], {}), '(featureClass)\n', (775, 789), False, 'from u... |
import logging
import pytest
import kopf
# We assume that the handler filtering is tested in details elsewhere (for all handlers).
# Here, we only test if it is applied or not applied.
async def test_daemon_filtration_satisfied(
registry, settings, resource, dummy,
caplog, assert_logs, k8s_mocked, ... | [
"pytest.mark.parametrize",
"kopf.daemon"
] | [((1092, 1534), 'pytest.mark.parametrize', 'pytest.mark.parametrize', (['"""labels, annotations"""', "[({'a': 'value', 'b': '...'}, {'x': 'mismatching-value', 'b': '...'}), ({\n 'a': 'value', 'b': '...'}, {'x': 'value', 'y': '...', 'z': '...'}), ({\n 'a': 'value', 'b': '...'}, {'x': 'value'}), ({'a': 'mismatching... |
# -*- coding: utf-8 -*-
import h5py
import yaml
from collections import UserDict
from datetime import datetime
from numpy import string_
from contextlib import contextmanager
TYPEID = '_type_'
@contextmanager
def hdf_file(hdf, lazy=True, *args, **kwargs):
"""Context manager yields h5 file if hdf is str,
oth... | [
"yaml.safe_dump",
"h5py.File",
"numpy.string_",
"datetime.datetime.fromtimestamp"
] | [((419, 450), 'h5py.File', 'h5py.File', (['hdf', '*args'], {}), '(hdf, *args, **kwargs)\n', (428, 450), False, 'import h5py\n'), ((517, 548), 'h5py.File', 'h5py.File', (['hdf', '*args'], {}), '(hdf, *args, **kwargs)\n', (526, 548), False, 'import h5py\n'), ((1105, 1134), 'datetime.datetime.fromtimestamp', 'datetime.fro... |
import sys
import os
from PIL import Image, ImageFilter, EpsImagePlugin
#grab first and second argument
try:
in_folder = sys.argv[1]
out_folder = sys.argv[2]
os.makedirs(out_folder, exist_ok=True)
#loop through input folder
for filename in os.listdir(in_folder):
if filename.endswith('.jpg')... | [
"os.listdir",
"os.path.splitext",
"os.path.join",
"os.makedirs"
] | [((175, 213), 'os.makedirs', 'os.makedirs', (['out_folder'], {'exist_ok': '(True)'}), '(out_folder, exist_ok=True)\n', (186, 213), False, 'import os\n'), ((262, 283), 'os.listdir', 'os.listdir', (['in_folder'], {}), '(in_folder)\n', (272, 283), False, 'import os\n'), ((349, 382), 'os.path.join', 'os.path.join', (['in_f... |
"""Unit tests for reviewboard.diffviewer.parser.DiffXParser."""
from djblets.testing.decorators import add_fixtures
from reviewboard.diffviewer.errors import DiffParserError
from reviewboard.diffviewer.parser import DiffXParser
from reviewboard.scmtools.core import HEAD, PRE_CREATION, UNKNOWN
from reviewboard.testing... | [
"djblets.testing.decorators.add_fixtures",
"reviewboard.diffviewer.parser.DiffXParser"
] | [((65489, 65520), 'djblets.testing.decorators.add_fixtures', 'add_fixtures', (["['test_scmtools']"], {}), "(['test_scmtools'])\n", (65501, 65520), False, 'from djblets.testing.decorators import add_fixtures\n'), ((69688, 69719), 'djblets.testing.decorators.add_fixtures', 'add_fixtures', (["['test_scmtools']"], {}), "([... |
# coding: utf-8
from __future__ import absolute_import
"""
Copyright 2020 Jackpine Technologies Corporation
Licensed under the Apache License, Version 2.0 (the "License");
you may not use this file except in compliance with the License.
You may obtain a copy of the License at
http://www.apache.org... | [
"cons3rt.api_client.ApiClient",
"cons3rt.exceptions.ApiValueError",
"six.iteritems",
"cons3rt.exceptions.ApiTypeError"
] | [((4473, 4514), 'six.iteritems', 'six.iteritems', (["local_var_params['kwargs']"], {}), "(local_var_params['kwargs'])\n", (4486, 4514), False, 'import six\n'), ((9567, 9608), 'six.iteritems', 'six.iteritems', (["local_var_params['kwargs']"], {}), "(local_var_params['kwargs'])\n", (9580, 9608), False, 'import six\n'), (... |
def pooled_cohen_kappa(samples_a, samples_b, weight_type=None, questions=None):
"""
Compute the pooled Cohen's Kappa for the given samples.
From:
<NAME>., <NAME>., <NAME>., & <NAME>. (2008).
Using pooled kappa to summarize interrater agreement across many items.
Field methods, 20(3)... | [
"numpy.sum",
"numpy.zeros",
"numpy.mean",
"numpy.array",
"numpy.concatenate"
] | [((2022, 2041), 'numpy.array', 'np.array', (['samples_a'], {}), '(samples_a)\n', (2030, 2041), True, 'import numpy as np\n'), ((2058, 2077), 'numpy.array', 'np.array', (['samples_b'], {}), '(samples_b)\n', (2066, 2077), True, 'import numpy as np\n'), ((4942, 4957), 'numpy.zeros', 'np.zeros', (['ncols'], {}), '(ncols)\n... |
# Unit tests related to 'Pickups' (https://www.easypost.com/docs/api#pickups).
import time
import datetime
import easypost
import pytest
import pytz
ONE_DAY = datetime.timedelta(days=1)
@pytest.fixture
def noon_on_next_monday():
today = datetime.date.today()
next_monday = today + datetime.timedelta(days=(7 ... | [
"pytest.mark.vcr",
"easypost.Shipment.create",
"easypost.Batch.create_and_buy",
"datetime.date.today",
"easypost.Address.create",
"time.sleep",
"datetime.timedelta",
"pytz.timezone",
"datetime.datetime.combine"
] | [((161, 187), 'datetime.timedelta', 'datetime.timedelta', ([], {'days': '(1)'}), '(days=1)\n', (179, 187), False, 'import datetime\n'), ((481, 498), 'pytest.mark.vcr', 'pytest.mark.vcr', ([], {}), '()\n', (496, 498), False, 'import pytest\n'), ((3067, 3084), 'pytest.mark.vcr', 'pytest.mark.vcr', ([], {}), '()\n', (3082... |
import torch
import torch.nn as nn
import torch.nn.functional as F
import numpy as np
from .occ_targets_template import OccTargetsTemplate
from ....utils import coords_utils, point_box_utils
class OccTargets3D(OccTargetsTemplate):
def __init__(
self,
model_cfg,
voxel_size,
point_cl... | [
"torch.ones_like",
"torch.unique",
"torch.zeros_like",
"numpy.asarray",
"torch.cat",
"torch.zeros"
] | [((8412, 8490), 'torch.zeros', 'torch.zeros', (['[bs, self.nz, self.ny, self.nx]'], {'dtype': 'torch.uint8', 'device': '"""cuda"""'}), "([bs, self.nz, self.ny, self.nx], dtype=torch.uint8, device='cuda')\n", (8423, 8490), False, 'import torch\n'), ((11282, 11350), 'torch.zeros', 'torch.zeros', (['[bs, 3, nz, ny, nx]'],... |
import dash
from dash.testing import wait
from dash_table import DataTable
from dash_html_components import Div
from selenium.webdriver.common.keys import Keys
import pandas as pd
url = "https://github.com/plotly/datasets/raw/master/" "26k-consumer-complaints.csv"
rawDf = pd.read_csv(url, nrows=100)
df = rawDf.to_d... | [
"pandas.read_csv",
"dash.Dash",
"dash_table.DataTable"
] | [((277, 304), 'pandas.read_csv', 'pd.read_csv', (['url'], {'nrows': '(100)'}), '(url, nrows=100)\n', (288, 304), True, 'import pandas as pd\n'), ((374, 393), 'dash.Dash', 'dash.Dash', (['__name__'], {}), '(__name__)\n', (383, 393), False, 'import dash\n'), ((821, 843), 'dash_table.DataTable', 'DataTable', ([], {}), '(*... |
# -*- coding: utf-8 -*-
# Copyright (c) 2018, Frappe Technologies Pvt. Ltd. and Contributors
# See license.txt
from __future__ import unicode_literals
import frappe
import unittest
from frappe.utils import nowdate, add_days
test_dependencies = ["Shift Type"]
class TestShiftAssignment(unittest.TestCase):
def setUp(... | [
"frappe.db.sql",
"frappe.utils.nowdate"
] | [((329, 379), 'frappe.db.sql', 'frappe.db.sql', (['"""delete from `tabShift Assignment`"""'], {}), "('delete from `tabShift Assignment`')\n", (342, 379), False, 'import frappe\n'), ((1350, 1359), 'frappe.utils.nowdate', 'nowdate', ([], {}), '()\n', (1357, 1359), False, 'from frappe.utils import nowdate, add_days\n'), (... |
# critiquebrainz - Repository for Creative Commons licensed reviews
#
# Copyright (C) 2018 <NAME>.
#
# This program is free software; you can redistribute it and/or modify
# it under the terms of the GNU General Public License as published by
# the Free Software Foundation; either version 2 of the License, or
# (at you... | [
"flask.url_for",
"unittest.mock.MagicMock",
"critiquebrainz.db.users.get_or_create"
] | [((3122, 3148), 'unittest.mock.MagicMock', 'MagicMock', ([], {'return_value': '[]'}), '(return_value=[])\n', (3131, 3148), False, 'from unittest.mock import MagicMock\n'), ((3200, 3257), 'unittest.mock.MagicMock', 'MagicMock', ([], {'side_effect': 'mb_exceptions.NoDataFoundException'}), '(side_effect=mb_exceptions.NoDa... |
# -*- coding: utf-8 -*-
# Time : 2021/7/25 13:59
# Author : QIN2DIM
# Github : https://github.com/QIN2DIM
# Description:
import json
import os
from datetime import datetime
from bs4 import BeautifulSoup
from selenium.common.exceptions import (
StaleElementReferenceException,
WebDriverException,
... | [
"os.mkdir",
"os.path.exists",
"datetime.datetime.now",
"bs4.BeautifulSoup",
"src.BusinessCentralLayer.setting.logger.error",
"os.path.join"
] | [((1175, 1221), 'os.path.join', 'os.path.join', (['database_dir', 'self.cache_db_name'], {}), '(database_dir, self.cache_db_name)\n', (1187, 1221), False, 'import os\n'), ((1383, 1422), 'os.path.join', 'os.path.join', (['self.cache_db_path', 'signs'], {}), '(self.cache_db_path, signs)\n', (1395, 1422), False, 'import o... |
import csv
from collections import defaultdict
import numpy as np
from PySAM.ResourceTools import SAM_CSV_to_solar_data
from hybrid.keys import get_developer_nrel_gov_key
from hybrid.log import hybrid_logger as logger
from hybrid.resource.resource import *
class SolarResource(Resource):
"""
Class to mana... | [
"numpy.pad",
"hybrid.keys.get_developer_nrel_gov_key",
"numpy.array",
"PySAM.ResourceTools.SAM_CSV_to_solar_data",
"numpy.delete"
] | [((3314, 3346), 'PySAM.ResourceTools.SAM_CSV_to_solar_data', 'SAM_CSV_to_solar_data', (['data_dict'], {}), '(data_dict)\n', (3335, 3346), False, 'from PySAM.ResourceTools import SAM_CSV_to_solar_data\n'), ((2219, 2247), 'hybrid.keys.get_developer_nrel_gov_key', 'get_developer_nrel_gov_key', ([], {}), '()\n', (2245, 224... |
# Copyright 2013-2022 Lawrence Livermore National Security, LLC and other
# Spack Project Developers. See the top-level COPYRIGHT file for details.
#
# SPDX-License-Identifier: (Apache-2.0 OR MIT)
import os
from spack import *
from spack.version import ver
def get_best_target(microarch, compiler_name, compiler_vers... | [
"os.path.exists",
"spack.version.ver",
"os.path.splitext",
"os.path.getmtime",
"os.path.getatime",
"os.path.join"
] | [((6242, 6299), 'os.path.join', 'os.path.join', (['"""doc"""', '"""_build"""', '"""html"""', '"""en"""', '"""index.html"""'], {}), "('doc', '_build', 'html', 'en', 'index.html')\n", (6254, 6299), False, 'import os\n'), ((6311, 6328), 'os.path.exists', 'os.path.exists', (['f'], {}), '(f)\n', (6325, 6328), False, 'import... |
"""
@author: lxy
@email: <EMAIL>
@date: 2021/12/9
@description: 这里维护各种模型的复现结果。用户进行实验后,可以拉取实验结果,一键生成对应的 latex 表格,就不用手动抄写到论文中了
https://pandas.pydata.org/docs/reference/api/pandas.io.formats.style.Styler.to_latex.html
"""
import os
from pathlib import Path
from typing import List, Union, Dict
import pandas as pd
from to... | [
"os.getcwd",
"os.path.join",
"pandas.DataFrame.from_dict"
] | [((411, 422), 'os.getcwd', 'os.getcwd', ([], {}), '()\n', (420, 422), False, 'import os\n'), ((5605, 5616), 'os.getcwd', 'os.getcwd', ([], {}), '()\n', (5614, 5616), False, 'import os\n'), ((7827, 7891), 'pandas.DataFrame.from_dict', 'pd.DataFrame.from_dict', (['new_dict'], {'orient': '"""index"""', 'columns': 'header'... |
#Copyright (c) 2018-2020 Analog Devices, Inc. All Rights Reserved.
#This software is proprietary to Analog Devices, Inc. and its licensors.
#
#Author: <NAME>
#requires pythonnet to be installed (pip install pythonnet)
import clr
from time import sleep
import os
#get path to resources folder and dll
topDir = os.path.... | [
"os.getcwd",
"clr.AddReference",
"time.sleep"
] | [((377, 436), 'clr.AddReference', 'clr.AddReference', (["(topDir + '\\\\resources\\\\FX3ApiWrapper.dll')"], {}), "(topDir + '\\\\resources\\\\FX3ApiWrapper.dll')\n", (393, 436), False, 'import clr\n'), ((325, 336), 'os.getcwd', 'os.getcwd', ([], {}), '()\n', (334, 336), False, 'import os\n'), ((1063, 1073), 'time.sleep... |
import time
from torba.server.block_processor import BlockProcessor
from lbry.schema.claim import Claim
from lbry.wallet.server.db.writer import SQLDB
class Timer:
def __init__(self, name):
self.name = name
self.total = 0
self.count = 0
self.sub_timers = {}
self._last_st... | [
"lbry.schema.claim.Claim.from_bytes",
"time.time"
] | [((890, 901), 'time.time', 'time.time', ([], {}), '()\n', (899, 901), False, 'import time\n'), ((966, 977), 'time.time', 'time.time', ([], {}), '()\n', (975, 977), False, 'import time\n'), ((3431, 3454), 'lbry.schema.claim.Claim.from_bytes', 'Claim.from_bytes', (['value'], {}), '(value)\n', (3447, 3454), False, 'from l... |
from django.urls import path
from .views import emailView, successView
urlpatterns = [
path('contact/', emailView, name='contact'),
path('success/', successView, name='success'),
] | [
"django.urls.path"
] | [((93, 136), 'django.urls.path', 'path', (['"""contact/"""', 'emailView'], {'name': '"""contact"""'}), "('contact/', emailView, name='contact')\n", (97, 136), False, 'from django.urls import path\n'), ((142, 187), 'django.urls.path', 'path', (['"""success/"""', 'successView'], {'name': '"""success"""'}), "('success/', ... |
## Process profiling traces
# exctracted with: python -m cProfile -o profile $(which py.test)
# python -m cProfile -o profile c:\Python27\Scripts\py.test-2.7-script.py
import pstats
p = pstats.Stats('profile')
p.sort_stats("tottime")
p.print_stats() | [
"pstats.Stats"
] | [((188, 211), 'pstats.Stats', 'pstats.Stats', (['"""profile"""'], {}), "('profile')\n", (200, 211), False, 'import pstats\n')] |
# Copyright 2020 University of New South Wales, University of Sydney, Ingham Institute
# 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
# Unle... | [
"os.listdir",
"platipy.backend.DataObject",
"os.makedirs",
"pydicom.read_file",
"loguru.logger.error",
"os.path.basename",
"tarfile.is_tarfile",
"os.path.exists",
"json.dumps",
"platipy.backend.app.register",
"loguru.logger.info",
"tempfile.mkdtemp",
"pymedphys.experimental.pinnacle.Pinnacle... | [((989, 1077), 'platipy.backend.app.register', 'app.register', (['"""Pinnacle Export"""'], {'default_settings': 'PINNACLE_EXPORT_SETTINGS_DEFAULTS'}), "('Pinnacle Export', default_settings=\n PINNACLE_EXPORT_SETTINGS_DEFAULTS)\n", (1001, 1077), False, 'from platipy.backend import app, DataObject, celery\n'), ((1238,... |
import datetime
from datetime import datetime as dt
from datetime import timedelta
import pandas as pd
import plotly.express as px
import psycopg2.extras
import streamlit as st
import yfinance as yf
from database import connection, cursor
@st.cache
def query(sql):
cursor.execute(sql)
results = cursor.fetcha... | [
"pandas.DataFrame",
"streamlit.sidebar.number_input",
"streamlit.columns",
"database.connection.rollback",
"streamlit.plotly_chart",
"streamlit.table",
"yfinance.download",
"datetime.date",
"streamlit.title",
"datetime.datetime",
"streamlit.container",
"streamlit.sidebar.markdown",
"datetime... | [((273, 292), 'database.cursor.execute', 'cursor.execute', (['sql'], {}), '(sql)\n', (287, 292), False, 'from database import connection, cursor\n'), ((307, 324), 'database.cursor.fetchall', 'cursor.fetchall', ([], {}), '()\n', (322, 324), False, 'from database import connection, cursor\n'), ((372, 419), 'streamlit.tit... |
import sys
import os
import time
import datetime
import shutil
def main(path=sys.path[0], days=2,size=4096):
paths = [path+"\\"+"Archive",path+"\\"+"Small",path+"\\"]
if os.path.isdir(path):
flagA=False
flagS=False
if not os.path.isdir(paths[0]):
flagA=True
if not os... | [
"os.mkdir",
"datetime.datetime.today",
"os.path.isdir",
"os.path.getsize",
"os.path.isfile",
"datetime.timedelta",
"os.path.getmtime",
"os.listdir",
"shutil.copy"
] | [((179, 198), 'os.path.isdir', 'os.path.isdir', (['path'], {}), '(path)\n', (192, 198), False, 'import os\n'), ((382, 398), 'os.listdir', 'os.listdir', (['path'], {}), '(path)\n', (392, 398), False, 'import os\n'), ((414, 439), 'datetime.datetime.today', 'datetime.datetime.today', ([], {}), '()\n', (437, 439), False, '... |
# Generated by Django 2.0.1 on 2018-06-23 11:39
from django.db import migrations
class Migration(migrations.Migration):
dependencies = [
('unlabel_backend', '0014_auto_20180623_1137'),
]
operations = [
migrations.RenameModel(
old_name='News',
new_name='Article',
... | [
"django.db.migrations.AlterModelOptions",
"django.db.migrations.RenameModel"
] | [((235, 294), 'django.db.migrations.RenameModel', 'migrations.RenameModel', ([], {'old_name': '"""News"""', 'new_name': '"""Article"""'}), "(old_name='News', new_name='Article')\n", (257, 294), False, 'from django.db import migrations\n'), ((339, 459), 'django.db.migrations.AlterModelOptions', 'migrations.AlterModelOpt... |
import os
import sys
import csv
def chart():
print("\t Reading CSV File and Generating Graph... \n")
#Create lists
labels=[]
values=[]
#Check csv file
if not os.path.isfile('WifiTest.csv'):
print("\n The MCP has derezzed the file!\n")
with open('WifiTest.csv') as csvFile:
... | [
"os.path.isfile",
"csv.reader"
] | [((184, 214), 'os.path.isfile', 'os.path.isfile', (['"""WifiTest.csv"""'], {}), "('WifiTest.csv')\n", (198, 214), False, 'import os\n'), ((331, 365), 'csv.reader', 'csv.reader', (['csvFile'], {'delimiter': '""","""'}), "(csvFile, delimiter=',')\n", (341, 365), False, 'import csv\n')] |
import os
from os import path
import numpy as np
import pytest
from astropy import cosmology as cosmo
import autofit as af
import autolens as al
from autolens.fit.fit import InterferometerFit
from test_autolens.mock import mock_pipeline
pytestmark = pytest.mark.filterwarnings(
"ignore:Using a non-tuple sequence ... | [
"autolens.masked.interferometer",
"autolens.PhaseInterferometer",
"os.path.realpath",
"pytest.fixture",
"numpy.ones",
"autolens.visibilities.full",
"autolens.GalaxyModel",
"autolens.fit",
"autolens.hyper_data.HyperBackgroundNoise",
"autolens.fit.fit.InterferometerFit",
"pytest.mark.filterwarning... | [((253, 558), 'pytest.mark.filterwarnings', 'pytest.mark.filterwarnings', (['"""ignore:Using a non-tuple sequence for multidimensional indexing is deprecated; use `arr[tuple(seq)]` instead of `arr[seq]`. In the future this will be interpreted as an arrays index, `arr[np.arrays(seq)]`, which will result either in an err... |
"""
Customize the behavior of a fixture by allowing special code to be
executed before or after each test, and before or after each suite.
"""
from __future__ import absolute_import
import os
import sys
import bson
import pymongo
from . import fixtures
from . import testcases
from .. import errors
from .. import lo... | [
"bson.CodecOptions",
"os.getenv",
"sys.exc_info"
] | [((16763, 16813), 'bson.CodecOptions', 'bson.CodecOptions', ([], {'document_class': 'TypeSensitiveSON'}), '(document_class=TypeSensitiveSON)\n', (16780, 16813), False, 'import bson\n'), ((2930, 2959), 'os.getenv', 'os.getenv', (['"""ASAN_OPTIONS"""', '""""""'], {}), "('ASAN_OPTIONS', '')\n", (2939, 2959), False, 'impor... |
import logging
from utils import find_resource
from diana.apis import Orthanc, DcmDir
from diana.dixel import DixelView, ShamDixel
from diana.utils.dicom import DicomLevel
def test_orthanc_ep(setup_orthanc0):
logging.debug("Test Orthanc EP")
O = Orthanc()
print(O)
O.check()
def test_orthanc_upload... | [
"logging.debug",
"logging.basicConfig",
"conftest.mk_orthanc",
"diana.apis.Orthanc",
"diana.dixel.ShamDixel.from_dixel",
"utils.find_resource",
"diana.apis.DcmDir"
] | [((216, 248), 'logging.debug', 'logging.debug', (['"""Test Orthanc EP"""'], {}), "('Test Orthanc EP')\n", (229, 248), False, 'import logging\n'), ((258, 267), 'diana.apis.Orthanc', 'Orthanc', ([], {}), '()\n', (265, 267), False, 'from diana.apis import Orthanc, DcmDir\n'), ((343, 379), 'logging.debug', 'logging.debug',... |
from copy import copy
import image_loader
import torch
import os
import binary_classifier.model
import binary_classifier.binary_network_pytorch
import transfer_classifier.model
import transfer_classifier.transfer_network_pytorch
from utils import fill_labels
EPOCHS = 50
LEARNING_RATE = 0.001
BATCH_SIZE = 128
BINARY_... | [
"torch.load",
"copy.copy",
"os.path.exists",
"image_loader.get_nih_dataset",
"utils.fill_labels",
"image_loader.get_covid_dataset"
] | [((882, 912), 'image_loader.get_nih_dataset', 'image_loader.get_nih_dataset', ([], {}), '()\n', (910, 912), False, 'import image_loader\n'), ((946, 978), 'image_loader.get_covid_dataset', 'image_loader.get_covid_dataset', ([], {}), '()\n', (976, 978), False, 'import image_loader\n'), ((1005, 1048), 'image_loader.get_co... |
#!/usr/bin/env python3
# -*- encoding: utf-8
# SPDX-License-Identifier: MIT
# Copyright (c) 2021 - 2021, <EMAIL>
__banner__ = r""" (
_ ______ ____ _____ _______ _ _
| | | ____| / __ \ | __ \ |__ __| | | | |
__| | ___ ___ ... | [
"bs4.BeautifulSoup",
"copy.copy"
] | [((4784, 4808), 'copy.copy', 'copy.copy', (['self.in_order'], {}), '(self.in_order)\n', (4793, 4808), False, 'import hashlib, copy\n'), ((2543, 2577), 'bs4.BeautifulSoup', 'BeautifulSoup', (['html', '"""html.parser"""'], {}), "(html, 'html.parser')\n", (2556, 2577), False, 'from bs4 import BeautifulSoup\n')] |
from django.db import models
from django_extensions.db.fields.json import JSONField
from olympia.amo.fields import PositiveAutoField
from olympia.amo.models import SearchMixin
def update_inc(initial, key, count):
"""Update or create a dict of `int` counters, for JSONField."""
initial = initial or {}
init... | [
"django.db.models.ForeignKey",
"django.db.models.CharField",
"django.db.models.PositiveIntegerField",
"django_extensions.db.fields.json.JSONField",
"django.db.models.FloatField",
"django.db.models.IntegerField",
"django.db.models.DateField",
"django.db.models.Avg",
"olympia.amo.fields.PositiveAutoFi... | [((509, 544), 'olympia.amo.fields.PositiveAutoField', 'PositiveAutoField', ([], {'primary_key': '(True)'}), '(primary_key=True)\n', (526, 544), False, 'from olympia.amo.fields import PositiveAutoField\n'), ((605, 638), 'django.db.models.ForeignKey', 'models.ForeignKey', (['"""addons.Addon"""'], {}), "('addons.Addon')\n... |
#!/usr/bin/python
#
# Copyright 2018-2021 Polyaxon, Inc.
#
# Licensed under the Apache License, Version 2.0 (the "License");
# you may not use this file except in compliance with the License.
# You may obtain a copy of the License at
#
# http://www.apache.org/licenses/LICENSE-2.0
#
# Unless required by applicable ... | [
"polyaxon.utils.formatting.Printer.print_warning",
"click.option",
"polyaxon.cli.project_versions.open_project_version_dashboard",
"click.Choice",
"polyaxon.cli.project_versions.get_project_version",
"polyaxon.cli.project_versions.list_project_versions",
"polyaxon.cli.project_versions.delete_project_ver... | [((1164, 1177), 'click.group', 'click.group', ([], {}), '()\n', (1175, 1177), False, 'import click\n'), ((1179, 1246), 'click.option', 'click.option', (["*OPTIONS_PROJECT['args']"], {}), "(*OPTIONS_PROJECT['args'], **OPTIONS_PROJECT['kwargs'])\n", (1191, 1246), False, 'import click\n'), ((1248, 1327), 'click.option', '... |
# Copyright (c) Microsoft Corporation and Fairlearn contributors.
# Licensed under the MIT License.
import functools
import numpy as np
from sklearn.metrics import recall_score
from fairlearn.metrics._annotated_metric_function import AnnotatedMetricFunction
def test_constructor_unnamed():
fc = AnnotatedMetricF... | [
"numpy.array_equal",
"functools.partial",
"fairlearn.metrics._annotated_metric_function.AnnotatedMetricFunction"
] | [((304, 357), 'fairlearn.metrics._annotated_metric_function.AnnotatedMetricFunction', 'AnnotatedMetricFunction', ([], {'func': 'recall_score', 'name': 'None'}), '(func=recall_score, name=None)\n', (327, 357), False, 'from fairlearn.metrics._annotated_metric_function import AnnotatedMetricFunction\n'), ((413, 478), 'num... |
import discord
import datetime, time
from discord.ext import commands
restart_data = {
'str': str(datetime.datetime.now().strftime("%d/%m/%Y %H:%M:%S")),
'obj': time.time()
}
#this is very important for creating a cog
class UPTIME(commands.Cog):
def __init__(self, bot):
self.bot = bot
@comma... | [
"discord.ext.commands.command",
"discord.Embed",
"discord.Color.red",
"discord.Color.green",
"discord.Color.blue",
"discord.ext.commands.Cog.listener",
"time.time",
"discord.ext.commands.guild_only",
"datetime.datetime.now"
] | [((172, 183), 'time.time', 'time.time', ([], {}), '()\n', (181, 183), False, 'import datetime, time\n'), ((315, 338), 'discord.ext.commands.Cog.listener', 'commands.Cog.listener', ([], {}), '()\n', (336, 338), False, 'from discord.ext import commands\n'), ((508, 539), 'discord.ext.commands.command', 'commands.command',... |
import urllib.request
from pymongo import MongoClient
import pandas as pd
import os
import json
class Wunderground:
"""Class that fetches weather from Wunderground and copies to MongoDB"""
def __init__(self, dbc, sid, api):
"""
Initializes class
"""
self.dbc = dbc
self... | [
"pymongo.MongoClient",
"pandas.to_datetime",
"json.loads"
] | [((1362, 1377), 'json.loads', 'json.loads', (['msg'], {}), '(msg)\n', (1372, 1377), False, 'import json\n'), ((3872, 3893), 'pymongo.MongoClient', 'MongoClient', (['self.dbc'], {}), '(self.dbc)\n', (3883, 3893), False, 'from pymongo import MongoClient\n'), ((1568, 1600), 'pandas.to_datetime', 'pd.to_datetime', (["ob['o... |
# coding: utf-8
""" demo on forward 2D """
# Copyright (c) <NAME>. All Rights Reserved.
# Distributed under the (new) BSD License. See LICENSE.txt for more info.
from __future__ import absolute_import, division, print_function
import matplotlib.pyplot as plt
import numpy as np
import pyeit.eit.protocol as protocol
imp... | [
"pyeit.mesh.wrapper.PyEITAnomaly_Circle",
"matplotlib.pyplot.show",
"pyeit.eit.protocol.create",
"pyeit.mesh.set_perm",
"pyeit.eit.fem.Forward",
"matplotlib.pyplot.figure",
"numpy.real",
"pyeit.mesh.create"
] | [((938, 995), 'pyeit.mesh.wrapper.PyEITAnomaly_Circle', 'PyEITAnomaly_Circle', ([], {'center': '[0.4, 0.5]', 'r': '(0.2)', 'perm': '(100.0)'}), '(center=[0.4, 0.5], r=0.2, perm=100.0)\n', (957, 995), False, 'from pyeit.mesh.wrapper import PyEITAnomaly_Circle\n'), ((1007, 1063), 'pyeit.mesh.set_perm', 'mesh.set_perm', (... |
from .. components import OutputPitchWidget
from .. import Defaults
import json
from kivy.properties import NumericProperty
from kivy.properties import ListProperty
from kivy.properties import ObjectProperty
from kivy.properties import BooleanProperty
from kivy.properties import StringProperty
from kivy.core.window imp... | [
"kivy.properties.ListProperty",
"json.load",
"kivy.properties.BooleanProperty",
"kivy.uix.button.Button",
"kivy.uix.label.Label",
"kivy.logger.Logger.info",
"kivy.properties.NumericProperty"
] | [((735, 755), 'kivy.properties.NumericProperty', 'NumericProperty', (['(0.0)'], {}), '(0.0)\n', (750, 755), False, 'from kivy.properties import NumericProperty\n'), ((774, 791), 'kivy.properties.NumericProperty', 'NumericProperty', ([], {}), '()\n', (789, 791), False, 'from kivy.properties import NumericProperty\n'), (... |
# coding: utf-8
# Raytheon BBN Technologies 2016
# Contributiors: <NAME>
#
# This file contains the windows, view, and scene descriptions
from qtpy.QtGui import *
from qtpy.QtCore import *
from qtpy.QtSvg import *
from qtpy.QtWidgets import *
import glob
import time
import os
import os.path
import numpy as np
from .... | [
"os.path.dirname",
"ipdb.set_trace"
] | [((15543, 15559), 'ipdb.set_trace', 'ipdb.set_trace', ([], {}), '()\n', (15557, 15559), False, 'import ipdb\n'), ((14534, 14559), 'os.path.dirname', 'os.path.dirname', (['__file__'], {}), '(__file__)\n', (14549, 14559), False, 'import os\n')] |
import pytest
from dlms_cosem import enumerations
from dlms_cosem.protocol.acse import ReleaseRequest
class TestDecodeRLRQ:
def test_simple(self):
data = bytes.fromhex("6203800100") # Normal no user-information
rlrq = ReleaseRequest.from_bytes(data)
assert rlrq.reason == enumerations.Rel... | [
"dlms_cosem.protocol.acse.ReleaseRequest.from_bytes"
] | [((242, 273), 'dlms_cosem.protocol.acse.ReleaseRequest.from_bytes', 'ReleaseRequest.from_bytes', (['data'], {}), '(data)\n', (267, 273), False, 'from dlms_cosem.protocol.acse import ReleaseRequest\n'), ((715, 746), 'dlms_cosem.protocol.acse.ReleaseRequest.from_bytes', 'ReleaseRequest.from_bytes', (['data'], {}), '(data... |
import os
import time
from dagster_graphql.client.query import LAUNCH_PIPELINE_EXECUTION_MUTATION
from dagster_graphql.test.utils import execute_dagster_graphql, infer_pipeline_selector
from dagster import execute_pipeline
from dagster.utils import safe_tempfile_path
from .graphql_context_test_suite import GraphQLCo... | [
"dagster_graphql.test.utils.infer_pipeline_selector",
"os.path.exists",
"dagster.execute_pipeline",
"time.sleep",
"dagster_graphql.test.utils.execute_dagster_graphql",
"dagster.utils.safe_tempfile_path"
] | [((1034, 1100), 'dagster_graphql.test.utils.infer_pipeline_selector', 'infer_pipeline_selector', (['graphql_context', '"""infinite_loop_pipeline"""'], {}), "(graphql_context, 'infinite_loop_pipeline')\n", (1057, 1100), False, 'from dagster_graphql.test.utils import execute_dagster_graphql, infer_pipeline_selector\n'), ... |
import torch
from .ClauseEnhancer import ClauseEnhancer
class KnowledgeEnhancer(torch.nn.Module):
def __init__(self, predicates: [str], clauses: [str], initial_clause_weight=0.5, save_training_data=False, device=0):
"""Initialize the knowledge base.
:param predicates: a list of predicates names
... | [
"torch.stack"
] | [((2565, 2597), 'torch.stack', 'torch.stack', (['scatter_deltas_list'], {}), '(scatter_deltas_list)\n', (2576, 2597), False, 'import torch\n')] |
# Licensed to Elasticsearch B.V. under one or more contributor
# license agreements. See the NOTICE file distributed with
# this work for additional information regarding copyright
# ownership. Elasticsearch B.V. licenses this file to you under
# the Apache License, Version 2.0 (the "License"); you may
# not use ... | [
"elasticsearch.Elasticsearch"
] | [((2746, 2766), 'elasticsearch.Elasticsearch', 'Elasticsearch', (['hosts'], {}), '(hosts)\n', (2759, 2766), False, 'from elasticsearch import Elasticsearch\n'), ((2595, 2624), 'elasticsearch.Elasticsearch', 'Elasticsearch', (["['es.org:123']"], {}), "(['es.org:123'])\n", (2608, 2624), False, 'from elasticsearch import ... |
from collections import defaultdict
import pickle
from tqdm import tqdm
class ReverseIndex:
def __init__(self,docs, preprocessing):
self.lookup = defaultdict(set)
self.preprocess = preprocessing
if docs is not None:
for title,words in tqdm(docs):
self.add(titl... | [
"collections.defaultdict",
"tqdm.tqdm",
"pickle.load",
"pickle.dump"
] | [((161, 177), 'collections.defaultdict', 'defaultdict', (['set'], {}), '(set)\n', (172, 177), False, 'from collections import defaultdict\n'), ((279, 289), 'tqdm.tqdm', 'tqdm', (['docs'], {}), '(docs)\n', (283, 289), False, 'from tqdm import tqdm\n'), ((671, 698), 'pickle.dump', 'pickle.dump', (['self.lookup', 'f'], {}... |
import numpy as np
from scipy.spatial.distance import cdist
# reference vector generation
def das_dennis(n_part, n_obj):
if n_part == 0:
return np.full((1, n_obj), 1 / n_obj)
else:
ref_dirs = []
ref_dir = np.full(n_obj, np.nan)
das_dennis_recursion(ref_dirs, ref_dir, n_part, n_p... | [
"numpy.full",
"numpy.sum",
"numpy.copy",
"numpy.clip",
"numpy.sort",
"numpy.dot",
"numpy.concatenate"
] | [((869, 897), 'numpy.dot', 'np.dot', (['ref_dirs', 'ref_dirs.T'], {}), '(ref_dirs, ref_dirs.T)\n', (875, 897), True, 'import numpy as np\n'), ((157, 187), 'numpy.full', 'np.full', (['(1, n_obj)', '(1 / n_obj)'], {}), '((1, n_obj), 1 / n_obj)\n', (164, 187), True, 'import numpy as np\n'), ((238, 260), 'numpy.full', 'np.... |
# Copyright (c) 2019 <NAME>.
# Cura is released under the terms of the LGPLv3 or higher.
## Find_moveo ##
from copy import deepcopy
from typing import cast, Dict, List, Optional
from UM.Application import Application
from UM.Math.AxisAlignedBox import AxisAlignedBox
from UM.Math.Polygon import Polygon # For typing.
... | [
"threading.Thread",
"copy.deepcopy",
"UM.Math.AxisAlignedBox.AxisAlignedBox",
"cura.Settings.SettingOverrideDecorator.SettingOverrideDecorator",
"UM.Application.Application.getInstance",
"threading.Lock",
"queue.Queue"
] | [((1178, 1194), 'threading.Lock', 'threading.Lock', ([], {}), '()\n', (1192, 1194), False, 'import threading\n'), ((1244, 1257), 'queue.Queue', 'queue.Queue', ([], {}), '()\n', (1255, 1257), False, 'import queue\n'), ((6877, 6927), 'UM.Math.AxisAlignedBox.AxisAlignedBox', 'AxisAlignedBox', ([], {'minimum': 'position', ... |
import re
import os
from .newsBase import NewsBaseSrc
from .newsResult import NewsResult
class CnnIndo(NewsBaseSrc):
def parse_url(self, url, date, page):
return url + "?p=" + str(page) + "&date=" + date.strftime("%Y/%m/%d")
def get_default_url(self):
return "https://www.cnnindonesia.com/nas... | [
"re.sub",
"re.search"
] | [((1869, 1910), 're.sub', 're.sub', (['"""\\\\(([^)]+)\\\\)$"""', '""""""', 'result_text'], {}), "('\\\\(([^)]+)\\\\)$', '', result_text)\n", (1875, 1910), False, 'import re\n'), ((1596, 1622), 're.search', 're.search', (['"""Gambas:"""', 'text'], {}), "('Gambas:', text)\n", (1605, 1622), False, 'import re\n'), ((1714,... |
from discord.ext import commands
from cogs.utils import game
from cogs.utils.game import GamePlay
from cogs.utils import views_solomode as views
class Solomode(commands.Cog):
def __init__(self, bot):
self.bot = bot
@commands.command()
async def solo(self, ctx):
result = {}
i = 0... | [
"discord.ext.commands.command",
"cogs.utils.game.generate_num",
"cogs.utils.views_solomode.embed_gameclear",
"cogs.utils.views_solomode.embed_start",
"cogs.utils.views_solomode.embed_gameplay",
"cogs.utils.game.GamePlay",
"cogs.utils.views_solomode.embed_gameover"
] | [((236, 254), 'discord.ext.commands.command', 'commands.command', ([], {}), '()\n', (252, 254), False, 'from discord.ext import commands\n'), ((393, 412), 'cogs.utils.game.generate_num', 'game.generate_num', ([], {}), '()\n', (410, 412), False, 'from cogs.utils import game\n'), ((782, 826), 'cogs.utils.game.GamePlay', ... |
from django.db import models
from django.utils.timezone import now
# Create your models here.
SEDAN = "SEDAN"
SUV = "SUV"
WAGON = "WAGON"
# (...)
CAR_MODELS_CHOICES = (
(SEDAN, "Sedan"),
(SUV, "SUV"),
(WAGON, "WAGON"),
)
# <HINT> Create a Car Make model `class CarMake(models.Model)`:
class CarMake(model... | [
"django.db.models.CharField",
"django.db.models.IntegerField",
"django.db.models.ManyToManyField",
"django.db.models.DateField"
] | [((341, 372), 'django.db.models.CharField', 'models.CharField', ([], {'max_length': '(30)'}), '(max_length=30)\n', (357, 372), False, 'from django.db import models\n'), ((391, 422), 'django.db.models.CharField', 'models.CharField', ([], {'max_length': '(30)'}), '(max_length=30)\n', (407, 422), False, 'from django.db im... |
import torch
import torch.nn as nn
from typing import Optional
from scipy import special
import math
from .utils import kld_gaussian, rand_epanechnikov_trig
class GaussianDropout(nn.Module):
def __init__(self, p=0.0, truncate=None):
super().__init__()
self.alpha = p / (1.0 - p)
self.trunca... | [
"torch.numel",
"scipy.special.loggamma",
"torch.sqrt",
"torch.fmod",
"torch.abs",
"torch.exp",
"torch.Tensor",
"torch.zeros",
"math.log",
"torch.sum",
"torch.tensor"
] | [((3146, 3171), 'torch.exp', 'torch.exp', (['self.log_sigma'], {}), '(self.log_sigma)\n', (3155, 3171), False, 'import torch\n'), ((4266, 4291), 'torch.exp', 'torch.exp', (['self.log_sigma'], {}), '(self.log_sigma)\n', (4275, 4291), False, 'import torch\n'), ((958, 981), 'torch.zeros', 'torch.zeros', (['input_size'], {... |
import PyPDF2 as p
from translate import translator
import os
filename = 'sample.pdf'
filename2 = 'output.pdf'
try:
file = open(filename, mode = "rb")
except:
print("File not Found, Please Enter Filename along with Directory [ex-Dowload/1.pdf]")
def translate():
cur_lang = 'en'
dest_lang = 'ko'
try:
dat... | [
"PyPDF2.PdfFileReader",
"PyPDF2.PdfFileWriter.write",
"translate.translator"
] | [((940, 984), 'PyPDF2.PdfFileWriter.write', 'p.PdfFileWriter.write', (['finle', 'translated_pdf'], {}), '(finle, translated_pdf)\n', (961, 984), True, 'import PyPDF2 as p\n'), ((324, 345), 'PyPDF2.PdfFileReader', 'p.PdfFileReader', (['file'], {}), '(file)\n', (339, 345), True, 'import PyPDF2 as p\n'), ((662, 698), 'tra... |
from anvil.interfaces.maya.dependencies import DEFAULT_API
import anvil.interfaces.api_proxy as api_proxy
import anvil.config as cfg
default_properties = {
"layer": api_proxy.STR_TYPE,
"name": api_proxy.STR_TYPE,
"remove": api_proxy.BOOL_TYPE,
"targetList": api_proxy.BOOL_TYPE,
"weight": api_proxy.... | [
"anvil.interfaces.api_proxy.merge_dicts"
] | [((529, 592), 'anvil.interfaces.api_proxy.merge_dicts', 'api_proxy.merge_dicts', (['api_proxy.BOOL_TYPE', '{cfg.DEFAULT: True}'], {}), '(api_proxy.BOOL_TYPE, {cfg.DEFAULT: True})\n', (550, 592), True, 'import anvil.interfaces.api_proxy as api_proxy\n'), ((930, 1045), 'anvil.interfaces.api_proxy.merge_dicts', 'api_proxy... |
"""
Django settings for angular_site project.
Generated by 'django-admin startproject' using Django 2.2.
For more information on this file, see
https://docs.djangoproject.com/en/2.2/topics/settings/
For the full list of settings and their values, see
https://docs.djangoproject.com/en/2.2/ref/settings/
"""
import da... | [
"os.path.abspath",
"environ.Env.read_env",
"datetime.timedelta",
"os.path.join",
"environ.Env"
] | [((519, 567), 'environ.Env', 'environ.Env', ([], {'ALLOWED_HOSTS': "(list, ['127.0.0.1'])"}), "(ALLOWED_HOSTS=(list, ['127.0.0.1']))\n", (530, 567), False, 'import datetime, environ, os, ldap\n'), ((579, 607), 'environ.Env.read_env', 'environ.Env.read_env', (['""".env"""'], {}), "('.env')\n", (599, 607), False, 'import... |
import re
from django.http import HttpResponse, Http404
from mauveinternet.markdown import get_models, get_model
# This needs to be added to the URL configuration as /admin/markdown/links
# so that the Javascript can find it.
def links(request):
"""Returns a list of the models and instances of that model
that... | [
"mauveinternet.markdown.get_model",
"mauveinternet.markdown.get_models",
"django.http.Http404"
] | [((747, 778), 'mauveinternet.markdown.get_model', 'get_model', (["request.GET['model']"], {}), "(request.GET['model'])\n", (756, 778), False, 'from mauveinternet.markdown import get_models, get_model\n'), ((824, 833), 'django.http.Http404', 'Http404', ([], {}), '()\n', (831, 833), False, 'from django.http import HttpRe... |
"""
Quinitc Polynomials Planner
author: <NAME> (@Atsushi_twi)
Ref:
- [Local Path Planning And Motion Control For Agv In Positioning](http://ieeexplore.ieee.org/document/637936/)
"""
import numpy as np
import matplotlib.pyplot as plt
import math
# parameter
MAX_T = 100.0 # maximum time to the goal [s]
MIN_T = 5.... | [
"matplotlib.pyplot.show",
"matplotlib.pyplot.plot",
"math.atan2",
"math.radians",
"matplotlib.pyplot.axis",
"math.sin",
"numpy.hypot",
"numpy.arange",
"math.cos",
"numpy.array",
"matplotlib.pyplot.cla",
"matplotlib.pyplot.pause",
"numpy.linalg.solve",
"matplotlib.pyplot.grid"
] | [((2750, 2780), 'numpy.arange', 'np.arange', (['MIN_T', 'MAX_T', 'MIN_T'], {}), '(MIN_T, MAX_T, MIN_T)\n', (2759, 2780), True, 'import numpy as np\n'), ((5052, 5070), 'math.radians', 'math.radians', (['(10.0)'], {}), '(10.0)\n', (5064, 5070), False, 'import math\n'), ((5251, 5269), 'math.radians', 'math.radians', (['(2... |
import turtle
turtle.mode("logo")
turtle.shape("turtle")
turtle.bgcolor("black")
turtle.pensize(7)
turtle.colormode(255)
turtle.pencolor(157, 208, 228)
for i in range(4):
turtle.pu()
turtle.setpos(30*i, 0)
turtle.pd()
turtle.forward(80)
turtle.done()
| [
"turtle.shape",
"turtle.pensize",
"turtle.mode",
"turtle.done",
"turtle.colormode",
"turtle.pd",
"turtle.forward",
"turtle.pu",
"turtle.setpos",
"turtle.bgcolor",
"turtle.pencolor"
] | [((15, 34), 'turtle.mode', 'turtle.mode', (['"""logo"""'], {}), "('logo')\n", (26, 34), False, 'import turtle\n'), ((35, 57), 'turtle.shape', 'turtle.shape', (['"""turtle"""'], {}), "('turtle')\n", (47, 57), False, 'import turtle\n'), ((58, 81), 'turtle.bgcolor', 'turtle.bgcolor', (['"""black"""'], {}), "('black')\n", ... |
# -*- coding: utf-8 -*-
# Generated by Django 1.9.7 on 2016-11-27 17:09
from __future__ import unicode_literals
from django.conf import settings
from django.db import migrations, models
import django.db.models.deletion
class Migration(migrations.Migration):
initial = True
dependencies = [
migration... | [
"django.db.migrations.swappable_dependency",
"django.db.models.ForeignKey",
"django.db.models.CharField",
"django.db.models.FloatField",
"django.db.models.AutoField",
"django.db.models.ImageField",
"django.db.models.IntegerField",
"django.db.models.DateTimeField"
] | [((311, 368), 'django.db.migrations.swappable_dependency', 'migrations.swappable_dependency', (['settings.AUTH_USER_MODEL'], {}), '(settings.AUTH_USER_MODEL)\n', (342, 368), False, 'from django.db import migrations, models\n'), ((3031, 3120), 'django.db.models.ForeignKey', 'models.ForeignKey', ([], {'on_delete': 'djang... |
from __future__ import absolute_import
from __future__ import division
from __future__ import print_function
from __future__ import unicode_literals
import unittest
from hypothesis import assume, given
import hypothesis.strategies as st
import numpy as np
from caffe2.proto import caffe2_pb2
from caffe2.python import ... | [
"unittest.main",
"unittest.skipIf",
"caffe2.python.hypothesis_test_util.tensor",
"numpy.ones",
"hypothesis.strategies.booleans",
"caffe2.python.core.CreateOperator",
"hypothesis.strategies.floats"
] | [((430, 495), 'unittest.skipIf', 'unittest.skipIf', (['(not workspace.C.use_mkldnn)', '"""No MKLDNN support."""'], {}), "(not workspace.C.use_mkldnn, 'No MKLDNN support.')\n", (445, 495), False, 'import unittest\n'), ((1467, 1524), 'unittest.skipIf', 'unittest.skipIf', (['(True)', '"""Skip duo to different rand seed.""... |
#!/usr/bin/env python
"""Tests the Netstat client action."""
from absl import app
from grr_response_client.client_actions import network
from grr_response_core.lib.rdfvalues import client_action as rdf_client_action
from grr.test_lib import client_test_lib
from grr.test_lib import test_lib
class NetstatActionTest(c... | [
"grr_response_core.lib.rdfvalues.client_action.ListNetworkConnectionsArgs",
"absl.app.run",
"grr.test_lib.test_lib.main"
] | [((1017, 1036), 'grr.test_lib.test_lib.main', 'test_lib.main', (['argv'], {}), '(argv)\n', (1030, 1036), False, 'from grr.test_lib import test_lib\n'), ((1068, 1081), 'absl.app.run', 'app.run', (['main'], {}), '(main)\n', (1075, 1081), False, 'from absl import app\n'), ((516, 562), 'grr_response_core.lib.rdfvalues.clie... |
# Copyright (c) Facebook, Inc. and its affiliates.
#
# This source code is licensed under the MIT license found in the
# LICENSE file in the root directory of this source tree.
import re
import textwrap
import tokenize
from collections import deque
from dataclasses import dataclass
from enum import Enum
from io import... | [
"io.BytesIO",
"fixit.common.line_mapping.LineMappingInfo.compute",
"textwrap.wrap",
"re.sub",
"dataclasses.dataclass"
] | [((689, 723), 'dataclasses.dataclass', 'dataclass', ([], {'frozen': '(True)', 'order': '(True)'}), '(frozen=True, order=True)\n', (698, 723), False, 'from dataclasses import dataclass\n'), ((3449, 3471), 'dataclasses.dataclass', 'dataclass', ([], {'frozen': '(True)'}), '(frozen=True)\n', (3458, 3471), False, 'from data... |
# -*- coding: utf-8 -*-
__author__ = '<NAME>'
__email__ = '<EMAIL>'
__version__ = '0.6.4'
from . import layers
from . import preprocessing
from . import utils
from . import data
from . import initializers
from . import losses
from . import metrics
from . import eval_metrics
from . import regularizers
from . import hy... | [
"logging.Formatter",
"logging.StreamHandler",
"keras.utils.generic_utils.get_custom_objects",
"logging.getLogger"
] | [((883, 951), 'logging.Formatter', 'logging.Formatter', (['"""%(levelname)s:%(asctime)s:%(name)s] %(message)s"""'], {}), "('%(levelname)s:%(asctime)s:%(name)s] %(message)s')\n", (900, 951), False, 'import logging\n'), ((962, 990), 'logging.getLogger', 'logging.getLogger', (['"""concise"""'], {}), "('concise')\n", (979,... |
# TODO: remove this once WPILib is public, and use the real thing
import sys
import pytest
from unittest.mock import MagicMock
def pytest_runtest_setup():
pass
def pytest_runtest_teardown():
pass
@pytest.fixture(scope="function")
def wpimock(monkeypatch):
mock = MagicMock(name="wpimock")
monkeyp... | [
"pytest.fixture",
"unittest.mock.MagicMock"
] | [((213, 245), 'pytest.fixture', 'pytest.fixture', ([], {'scope': '"""function"""'}), "(scope='function')\n", (227, 245), False, 'import pytest\n'), ((381, 413), 'pytest.fixture', 'pytest.fixture', ([], {'scope': '"""function"""'}), "(scope='function')\n", (395, 413), False, 'import pytest\n'), ((731, 763), 'pytest.fixt... |
from threading import Thread, current_thread, RLock
from typing import NamedTuple, Callable, List, Optional
from utils.libs.chatbridge.common.logger import ChatBridgeLogger
from .cryptor import AESCryptor
class Address(NamedTuple):
hostname: str
port: int
def __str__(self):
return '{}:{}'.format(self.hostname,... | [
"threading.Thread",
"threading.RLock",
"threading.current_thread"
] | [((677, 684), 'threading.RLock', 'RLock', ([], {}), '()\n', (682, 684), False, 'from threading import Thread, current_thread, RLock\n'), ((994, 1048), 'threading.Thread', 'Thread', ([], {'target': 'target', 'args': '()', 'name': 'name', 'daemon': '(True)'}), '(target=target, args=(), name=name, daemon=True)\n', (1000, ... |
import torch
import torch.nn as nn
from torchvision import models
import os
class MRnet(nn.Module):
"""MRnet uses pretrained resnet50 as a backbone to extract features, this is multilabel classifying model
"""
def __init__(self): # add conf file
super(MRnet,self).__init__()
# init th... | [
"torch.nn.AdaptiveAvgPool2d",
"torchvision.models.alexnet",
"torch.cat",
"torch.squeeze",
"torch.max",
"torch.nn.Linear"
] | [((567, 590), 'torch.nn.AdaptiveAvgPool2d', 'nn.AdaptiveAvgPool2d', (['(1)'], {}), '(1)\n', (587, 590), True, 'import torch.nn as nn\n'), ((619, 642), 'torch.nn.AdaptiveAvgPool2d', 'nn.AdaptiveAvgPool2d', (['(1)'], {}), '(1)\n', (639, 642), True, 'import torch.nn as nn\n'), ((672, 695), 'torch.nn.AdaptiveAvgPool2d', 'n... |
from unittest.mock import MagicMock, patch
from scheduleServer import app
import unittest
from helperFunctions.helperFunctions import stdRet, AuthenticatedUser
class TestStaff_importStaff(unittest.TestCase):
def setUp(self):
# Set up a number of items that will be used for these tests.
# -- Mock... | [
"unittest.mock.MagicMock",
"scheduleServer.app.test_client",
"unittest.mock.patch.dict",
"helperFunctions.helperFunctions.AuthenticatedUser",
"unittest.mock.patch",
"scheduleServer.app.login_manager.init_app"
] | [((1352, 1399), 'unittest.mock.patch.dict', 'patch.dict', (['"""os.environ"""', 'self.helper_osEnviron'], {}), "('os.environ', self.helper_osEnviron)\n", (1362, 1399), False, 'from unittest.mock import MagicMock, patch\n'), ((1909, 1940), 'scheduleServer.app.login_manager.init_app', 'app.login_manager.init_app', (['app... |
# Python imports
import unittest
import numpy as np
import os
import shutil
import xarray as xr
import pytest
import oggm
from scipy import optimize as optimization
salem = pytest.importorskip('salem')
gpd = pytest.importorskip('geopandas')
# Locals
import oggm.cfg as cfg
from oggm import tasks, utils, workflow
from ... | [
"oggm.tasks.init_present_time_glacier",
"oggm.core.centerlines.compute_centerlines",
"oggm.core.centerlines.catchment_width_correction",
"numpy.sum",
"oggm.cfg.initialize",
"numpy.polyfit",
"numpy.abs",
"oggm.core.centerlines.compute_downstream_bedshape",
"xarray.zeros_like",
"oggm.core.centerline... | [((174, 202), 'pytest.importorskip', 'pytest.importorskip', (['"""salem"""'], {}), "('salem')\n", (193, 202), False, 'import pytest\n'), ((209, 241), 'pytest.importorskip', 'pytest.importorskip', (['"""geopandas"""'], {}), "('geopandas')\n", (228, 241), False, 'import pytest\n'), ((547, 580), 'pytest.mark.test_env', 'p... |
#!/usr/bin/env python3
# Copyright © 2018 Broadcom. All Rights Reserved. The term “Broadcom” refers to
# Broadcom Inc. and/or its subsidiaries.
#
# Licensed under the Apache License, Version 2.0 (the "License");
# you may not use this file except in compliance with the License.
# You may also obtain a copy of the Lice... | [
"pyfos.pyfos_auth.login",
"pyfos.pyfos_util.response_print",
"pyfos.pyfos_util.is_failed_resp",
"pyfos.utils.brcd_util.generic_input",
"pyfos.utils.brcd_util.exit_register",
"pyfos.pyfos_brocade_operation_license.license",
"pyfos.pyfos_auth.is_failed_login",
"pyfos.utils.brcd_util.full_usage",
"pyfo... | [((1980, 2031), 'pyfos.utils.brcd_util.generic_input', 'brcd_util.generic_input', (['argv', 'usage', 'valid_options'], {}), '(argv, usage, valid_options)\n', (2003, 2031), False, 'from pyfos.utils import brcd_util\n'), ((2047, 2168), 'pyfos.pyfos_auth.login', 'pyfos_auth.login', (["inputs['login']", "inputs['password']... |
# coding=utf-8
# Copyright 2021 The Google Research Authors.
#
# Licensed under the Apache License, Version 2.0 (the "License");
# you may not use this file except in compliance with the License.
# You may obtain a copy of the License at
#
# http://www.apache.org/licenses/LICENSE-2.0
#
# Unless required by applicab... | [
"autoregressive_diffusion.utils.util_fns.sum_except_batch",
"absl.logging.info",
"jax.lax.axis_index",
"autoregressive_diffusion.model.autoregressive_diffusion.ardm_utils.get_batch_permutations",
"autoregressive_diffusion.model.autoregressive_diffusion.ardm_utils.get_selections_for_sigma_and_range",
"jax.... | [((1649, 1689), 'flax.training.common_utils.onehot', 'common_utils.onehot', (['targets', 'vocab_size'], {}), '(targets, vocab_size)\n', (1668, 1689), False, 'from flax.training import common_utils\n'), ((1766, 1792), 'numpy.prod', 'np.prod', (['targets.shape[1:]'], {}), '(targets.shape[1:])\n', (1773, 1792), True, 'imp... |
# Copyright 2018 SAP SE
#
# Licensed under the Apache License, Version 2.0 (the "License"); you may
# not use this file except in compliance with the License. You may obtain
# a copy of the License at
#
# http://www.apache.org/licenses/LICENSE-2.0
#
# Unless required by applicable law or agreed to in writing, software
... | [
"oslo_log.log.getLogger",
"six.iteritems",
"octavia_f5.restclient.as3exceptions.RequiredKeyMissingException"
] | [((723, 750), 'oslo_log.log.getLogger', 'logging.getLogger', (['__name__'], {}), '(__name__)\n', (740, 750), True, 'from oslo_log import log as logging\n'), ((1769, 1788), 'six.iteritems', 'six.iteritems', (['data'], {}), '(data)\n', (1782, 1788), False, 'import six\n'), ((1636, 1682), 'octavia_f5.restclient.as3excepti... |
"""
Copyright (c) 2021, Electric Power Research Institute
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 above copyright notice,
this li... | [
"pandas.DataFrame",
"numpy.multiply",
"cvxpy.Parameter",
"cvxpy.multiply",
"cvxpy.Zero",
"storagevet.Library.drop_extra_data",
"storagevet.ValueStreams.ValueStream.ValueStream.__init__",
"cvxpy.promote",
"cvxpy.NonPos",
"cvxpy.sum",
"storagevet.Library.fill_extra_data",
"pandas.Period",
"cvx... | [((2376, 2416), 'storagevet.ValueStreams.ValueStream.ValueStream.__init__', 'ValueStream.__init__', (['self', 'name', 'params'], {}), '(self, name, params)\n', (2396, 2416), False, 'from storagevet.ValueStreams.ValueStream import ValueStream\n'), ((2974, 3015), 'pandas.DataFrame', 'pd.DataFrame', ([], {'columns': 'self... |
import numpy as np
import tensorflow as tf
# the activation function
def g_1(x):
assert len(x.shape) == 1
rand = tf.random_uniform([x.shape.as_list()[0]], dtype=tf.float32)
t = tf.nn.sigmoid(x) - rand
return 0.5*(1 + t / (tf.abs(t) + 1e-8))
def g_2(x):
return tf.nn.sigmoid(x)
def g(x):
ret... | [
"numpy.uint8",
"tensorflow.abs",
"tensorflow.global_variables_initializer",
"numpy.zeros",
"tensorflow.Session",
"tensorflow.matmul",
"tensorflow.placeholder",
"numpy.random.randint",
"numpy.array",
"tensorflow.global_variables",
"numpy.random.rand",
"tensorflow.train.GradientDescentOptimizer"... | [((284, 300), 'tensorflow.nn.sigmoid', 'tf.nn.sigmoid', (['x'], {}), '(x)\n', (297, 300), True, 'import tensorflow as tf\n'), ((324, 343), 'tensorflow.nn.leaky_relu', 'tf.nn.leaky_relu', (['x'], {}), '(x)\n', (340, 343), True, 'import tensorflow as tf\n'), ((3318, 3329), 'numpy.uint8', 'np.uint8', (['x'], {}), '(x)\n',... |
# -*- coding: utf-8 -*-
import os
import sys
from setuptools import find_packages, setup
# temporarily redirect config directory to prevent matplotlib importing
# testing that for writeable directory which results in sandbox error in
# certain easy_install versions
os.environ["MPLCONFIGDIR"] = "."
pkg_name = "tsget... | [
"setuptools.find_packages",
"os.system",
"sys.exit"
] | [((410, 432), 'os.system', 'os.system', (['"""cleanpy ."""'], {}), "('cleanpy .')\n", (419, 432), False, 'import os\n'), ((437, 471), 'os.system', 'os.system', (['"""python setup.py sdist"""'], {}), "('python setup.py sdist')\n", (446, 471), False, 'import os\n'), ((558, 568), 'sys.exit', 'sys.exit', ([], {}), '()\n', ... |
import os
from django.apps import AppConfig
from ctf.settings import *
class SystemConfig(AppConfig):
name = 'system'
verbose_name = open(os.path.join(BASE_DIR, 'ctf', 'eventname'), 'r').read().strip()
| [
"os.path.join"
] | [((146, 188), 'os.path.join', 'os.path.join', (['BASE_DIR', '"""ctf"""', '"""eventname"""'], {}), "(BASE_DIR, 'ctf', 'eventname')\n", (158, 188), False, 'import os\n')] |