code stringlengths 22 1.05M | apis listlengths 1 3.31k | extract_api stringlengths 75 3.25M |
|---|---|---|
import logging
import archinstall
__version__ = 0.1
class Plugin:
VARIANTS_DICT_KEY = "variants"
VARIANT_KEY = "variant"
def __init__(self):
if self.has_variants() and self.variants_is_dict():
variant_key = self.get_selected_variant_key()
variant = archinstall.arguments[... | [
"archinstall.arguments.__str__",
"archinstall.log",
"archinstall.generic_select"
] | [((444, 545), 'archinstall.log', 'archinstall.log', (['f"""The \'{variant_key}\' variant was applied to the arguments."""'], {'level': 'logging.INFO'}), '(f"The \'{variant_key}\' variant was applied to the arguments.",\n level=logging.INFO)\n', (459, 545), False, 'import archinstall\n'), ((1791, 1906), 'archinstall.... |
# Standard Library
import pickle
from typing import *
from pathlib import Path
# Third-party Party
import numpy as np
import PIL.Image as Image
from colorama import Fore, init
# Torch Library
import torch
import torch.utils.data as data
import torchvision.transforms as T
# My Library
from helper import visualize_np... | [
"helper.ProjectPath.config.joinpath",
"numpy.array",
"helper.DatasetPath.Cifar10.test.open",
"colorama.init",
"numpy.load",
"numpy.savez",
"numpy.where",
"helper.DatasetPath.Cifar100.test.open",
"helper.ClassLabelLookuper",
"numpy.asarray",
"helper.DatasetPath.PascalVOC2012.train_idx.items",
"... | [((434, 454), 'colorama.init', 'init', ([], {'autoreset': '(True)'}), '(autoreset=True)\n', (438, 454), False, 'from colorama import Fore, init\n'), ((6474, 6513), 'helper.ClassLabelLookuper', 'ClassLabelLookuper', ([], {'datasets': 'md.dataset'}), '(datasets=md.dataset)\n', (6492, 6513), False, 'from helper import Cla... |
# Copyright 2022 Huawei Technologies Co., Ltd
#
# Licensed under the Apache License, Version 2.0 (the "License");
# you may not use this file except in compliance with the License.
# You may obtain a copy of the License at
#
# http://www.apache.org/licenses/LICENSE-2.0
#
# Unless required by applicable law or agreed to... | [
"mindspore.common.initializer.XavierUniform",
"mindspore.common.initializer.HeUniform",
"mindspore.ops.ZerosLike",
"mindspore.ops.clip_by_value",
"os.path.join",
"math.sqrt",
"mindspore.ops.OnesLike",
"numpy.zeros",
"mindspore.common.initializer.Normal",
"mindspore.common.initializer.initializer",... | [((2894, 2908), 'mindspore.ops.OnesLike', 'ops.OnesLike', ([], {}), '()\n', (2906, 2908), True, 'import mindspore.ops as ops\n'), ((2934, 2949), 'mindspore.ops.ZerosLike', 'ops.ZerosLike', ([], {}), '()\n', (2947, 2949), True, 'import mindspore.ops as ops\n'), ((2972, 2984), 'mindspore.ops.Assign', 'ops.Assign', ([], {... |
import itertools
stevke = ['1', '3', '7', '9']
def je_prastevilo(n):
if n < 2 or n % 2 == 0:
return n == 2
i = 3
while i * i <= n:
if n % i == 0 or n % 2 == 0:
return False
i += 2
return True
def zasukej(nabor):
stevilo = list(nabor)
seznam = []
while l... | [
"itertools.product"
] | [((525, 570), 'itertools.product', 'itertools.product', (['stevke'], {'repeat': 'ponavljanje'}), '(stevke, repeat=ponavljanje)\n', (542, 570), False, 'import itertools\n')] |
"""
~/utils/update_ontario_stocking.py
Created: 23 Jan 2019 15:29:22
DESCRIPTION:
This script updates the ontario data in the lake wide cwt database.
Updates include tag type, and sequence number for sequential cwts, cwt
manufacturer (where it should have been Micro Mark (MM))
Updates are preformed on both stocking... | [
"fsdviz.common.models.CWT.objects.get_or_create",
"collections.namedtuple",
"fsdviz.stocking.models.StockingEvent.objects.filter",
"fsdviz.common.models.CWT.objects.filter",
"fsdviz.stocking.models.StockingEvent.objects.get",
"fsdviz.common.models.CWTsequence.objects.filter",
"fsdviz.common.models.CWTse... | [((1036, 1124), 'fsdviz.stocking.models.StockingEvent.objects.filter', 'StockingEvent.objects.filter', ([], {'agency__abbrev': '"""OMNR"""', 'jurisdiction__lake__abbrev': '"""HU"""'}), "(agency__abbrev='OMNR',\n jurisdiction__lake__abbrev='HU')\n", (1064, 1124), False, 'from fsdviz.stocking.models import StockingEve... |
import os
from math import radians, sin, cos, asin, degrees, pi, sqrt, pow, fabs, atan2
from django import forms
from django.db import models
from django.conf import settings
from modelcluster.fields import ParentalKey
from wagtail.wagtailcore.models import Page, Orderable
from wagtail.wagtailadmin.edit_handlers impo... | [
"wagtail.wagtailimages.edit_handlers.ImageChooserPanel",
"django.db.models.ForeignKey",
"math.pow",
"wagtail.wagtailsearch.index.SearchField",
"wagtail.wagtailadmin.edit_handlers.FieldPanel",
"os.path.join",
"math.degrees",
"math.asin",
"django.db.models.BooleanField",
"wagtail.wagtailadmin.edit_h... | [((622, 677), 'django.db.models.CharField', 'models.CharField', ([], {'max_length': '(250)', 'null': '(True)', 'blank': '(True)'}), '(max_length=250, null=True, blank=True)\n', (638, 677), False, 'from django.db import models\n'), ((707, 820), 'django.db.models.ForeignKey', 'models.ForeignKey', (['"""wagtailimages.Imag... |
#!/usr/bin/env python
import os
os.environ['POMAGMA_LOG_LEVEL'] = '3'
from pomagma.compiler.util import temp_memoize # isort:skip
from pomagma.reducer import bohm # isort:skip
print('Example 1.')
with temp_memoize():
bohm.sexpr_simplify('(ABS (ABS (1 0 (1 0))) (ABS (ABS (1 (0 0)))))')
print('Example 2.')
w... | [
"pomagma.reducer.bohm.sexpr_simplify",
"pomagma.compiler.util.temp_memoize"
] | [((208, 222), 'pomagma.compiler.util.temp_memoize', 'temp_memoize', ([], {}), '()\n', (220, 222), False, 'from pomagma.compiler.util import temp_memoize\n'), ((228, 296), 'pomagma.reducer.bohm.sexpr_simplify', 'bohm.sexpr_simplify', (['"""(ABS (ABS (1 0 (1 0))) (ABS (ABS (1 (0 0)))))"""'], {}), "('(ABS (ABS (1 0 (1 0))... |
"""Utilities for debugging memory usage, blocking calls, etc."""
import os
import sys
import traceback
from contextlib import contextmanager
from functools import partial
from pprint import pprint
from celery.platforms import signals
from celery.utils.text import WhateverIO
try:
from psutil import Process
except ... | [
"inspect.getframeinfo",
"traceback.print_stack",
"threading.enumerate",
"celery.utils.text.WhateverIO",
"celery.platforms.signals.arm_alarm",
"functools.partial",
"gc.collect",
"os.getpid",
"celery.platforms.signals.reset_alarm",
"sys._current_frames",
"pprint.pprint"
] | [((1715, 1727), 'gc.collect', 'gc.collect', ([], {}), '()\n', (1725, 1727), False, 'import gc\n'), ((2056, 2081), 'functools.partial', 'partial', (['print'], {'file': 'file'}), '(print, file=file)\n', (2063, 2081), False, 'from functools import partial\n'), ((4087, 4111), 'functools.partial', 'partial', (['print'], {'f... |
#! /usr/bin/python3
import sys
sys.path.append('../../')
import numpy as np
import numpy.fft as npfft
import matplotlib.pyplot as plt
from matplotlib import animation
import time
from netCDF4 import MFDataset
from nephelae_simulation.mesonh_interface import MesoNHVariable
from nephelae_base.types import Position
fr... | [
"numpy.sqrt",
"netCDF4.MFDataset",
"numpy.array",
"numpy.sin",
"sys.path.append",
"sklearn.gaussian_process.GaussianProcessRegressor",
"nephelae_base.types.Position",
"numpy.exp",
"numpy.linspace",
"numpy.meshgrid",
"sys.stdout.flush",
"numpy.cos",
"numpy.random.randn",
"time.time",
"mat... | [((32, 57), 'sys.path.append', 'sys.path.append', (['"""../../"""'], {}), "('../../')\n", (47, 57), False, 'import sys\n'), ((2711, 2737), 'numpy.linspace', 'np.linspace', (['(0)', '(300.0)', '(300)'], {}), '(0, 300.0, 300)\n', (2722, 2737), True, 'import numpy as np\n'), ((3050, 3087), 'nephelae_base.types.Position', ... |
# coding: utf-8
# Originally from
# https://github.com/PPartisan/THE_LONG_DARK
# Simply adapted to LINUX by <NAME>
import threading
import time
import psutil
from pylab import rcParams
from pynput.keyboard import Key, Controller
import mapping
rcParams['figure.figsize'] = 12, 9.5
def is_tld_running():
retur... | [
"pynput.keyboard.Controller",
"psutil.pids",
"mapping.delete_screenshots",
"psutil.Process",
"mapping.write_coords_to_file",
"time.sleep",
"mapping.read_coords_from_screenshots",
"threading.Thread"
] | [((351, 364), 'psutil.pids', 'psutil.pids', ([], {}), '()\n', (362, 364), False, 'import psutil\n'), ((513, 553), 'threading.Thread', 'threading.Thread', ([], {'target': 'func', 'args': 'args'}), '(target=func, args=args)\n', (529, 553), False, 'import threading\n'), ((668, 680), 'pynput.keyboard.Controller', 'Controll... |
# import random
#
# deck = list()
# for suit in ["♦", "♥", "♠", "♣"]:
# for value in ["A", "K", "Q", "J", "10", "9", "8", "7", "6", "5", "4", "3", "2"]:
# deck.append((value, suit))
# r_sample = random.sample(deck, 7)
# print(r_sample)
from enum import Enum, auto, unique
class Suit(Enum):
... | [
"enum.auto"
] | [((435, 441), 'enum.auto', 'auto', ([], {}), '()\n', (439, 441), False, 'from enum import Enum, auto, unique\n'), ((455, 461), 'enum.auto', 'auto', ([], {}), '()\n', (459, 461), False, 'from enum import Enum, auto, unique\n'), ((475, 481), 'enum.auto', 'auto', ([], {}), '()\n', (479, 481), False, 'from enum import Enum... |
import datetime
import unittest
class KalmanFilterTest(unittest.TestCase):
def test_kalman_filter_with_prior_predict(self):
t0 = datetime.datetime(2014, 2, 12, 16, 18, 25, 204000)
print(t0)
self.assertEqual(1., 1.)
def test_kalman_filter_without_prior_predict(self... | [
"unittest.main",
"datetime.datetime"
] | [((519, 534), 'unittest.main', 'unittest.main', ([], {}), '()\n', (532, 534), False, 'import unittest\n'), ((147, 197), 'datetime.datetime', 'datetime.datetime', (['(2014)', '(2)', '(12)', '(16)', '(18)', '(25)', '(204000)'], {}), '(2014, 2, 12, 16, 18, 25, 204000)\n', (164, 197), False, 'import datetime\n')] |
#!/usr/bin/env python3
import numpy as np
import numpy.random as npr
import pytest
A1 = npr.rand( 1, 1)
B1 = npr.rand( 1, 1)
C1 = npr.rand( 1, 1)
A3 = npr.rand( 3, 3)
B3 = npr.rand( 3, 3)
C3 = npr.rand( 3, 3)
A10 = npr.rand( 10, 10)
B10 = npr.rand( 10, 10)
C10... | [
"numpy.random.rand",
"pytest.main"
] | [((93, 107), 'numpy.random.rand', 'npr.rand', (['(1)', '(1)'], {}), '(1, 1)\n', (101, 107), True, 'import numpy.random as npr\n'), ((122, 136), 'numpy.random.rand', 'npr.rand', (['(1)', '(1)'], {}), '(1, 1)\n', (130, 136), True, 'import numpy.random as npr\n'), ((151, 165), 'numpy.random.rand', 'npr.rand', (['(1)', '(1... |
# Copyright 2015 Mirantis Inc
#
# Licensed under the Apache License, Version 2.0 (the "License"); you may
# not use this file except in compliance with the License. You may obtain
# a copy of the License at
#
# http://www.apache.org/licenses/LICENSE-2.0
#
# Unless required by applicable law or agreed to in writing... | [
"oslo_utils.timeutils.utcnow_ts"
] | [((3106, 3127), 'oslo_utils.timeutils.utcnow_ts', 'timeutils.utcnow_ts', ([], {}), '()\n', (3125, 3127), False, 'from oslo_utils import timeutils\n'), ((1681, 1702), 'oslo_utils.timeutils.utcnow_ts', 'timeutils.utcnow_ts', ([], {}), '()\n', (1700, 1702), False, 'from oslo_utils import timeutils\n'), ((2488, 2509), 'osl... |
import numpy as np
from bs4 import BeautifulSoup
from tqdm import tqdm
import json
def read_file(filename):
with open(filename, 'r', encoding='utf-8') as f:
contents = f.read()
soup = BeautifulSoup(contents, "html.parser")
return soup
if __name__ == '__main__':
with open('name2idx.js... | [
"bs4.BeautifulSoup",
"json.load"
] | [((206, 244), 'bs4.BeautifulSoup', 'BeautifulSoup', (['contents', '"""html.parser"""'], {}), "(contents, 'html.parser')\n", (219, 244), False, 'from bs4 import BeautifulSoup\n'), ((356, 369), 'json.load', 'json.load', (['fp'], {}), '(fp)\n', (365, 369), False, 'import json\n'), ((470, 508), 'bs4.BeautifulSoup', 'Beauti... |
from firedrake import *
import numpy as np
from firedrake.petsc import PETSc
from firedrake import COMM_WORLD
try:
import matplotlib.pyplot as plt
plt.rcParams["contour.corner_mask"] = False
plt.close("all")
except:
warning("Matplotlib not imported")
nx, ny = 4, 4
Lx, Ly = 1.0, 1.0
quadrilateral = Fa... | [
"matplotlib.pyplot.close",
"matplotlib.pyplot.axis",
"firedrake.petsc.PETSc.Sys.Print",
"matplotlib.pyplot.show"
] | [((402, 417), 'matplotlib.pyplot.axis', 'plt.axis', (['"""off"""'], {}), "('off')\n", (410, 417), True, 'import matplotlib.pyplot as plt\n'), ((4237, 4349), 'firedrake.petsc.PETSc.Sys.Print', 'PETSc.Sys.Print', (['"""*******************************************\nSolving using static condensation.\n"""'], {}), '(\n ""... |
from kafka import KafkaConsumer
consumer = KafkaConsumer('test-topic', bootstrap_servers='localhost:9092')
print("listening")
for msg in consumer:
print(msg)
| [
"kafka.KafkaConsumer"
] | [((44, 107), 'kafka.KafkaConsumer', 'KafkaConsumer', (['"""test-topic"""'], {'bootstrap_servers': '"""localhost:9092"""'}), "('test-topic', bootstrap_servers='localhost:9092')\n", (57, 107), False, 'from kafka import KafkaConsumer\n')] |
import random
import numpy as np
import tensorflow as tf
from recognition.utils import train_utils, googlenet_load
try:
from tensorflow.models.rnn import rnn_cell
except ImportError:
rnn_cell = tf.nn.rnn_cell
from tensorflow.python.framework import ops
from tensorflow.python.ops import array_ops
random.seed... | [
"tensorflow.python.framework.ops.RegisterGradient",
"tensorflow.models.rnn.rnn_cell.MultiRNNCell",
"tensorflow.get_variable",
"tensorflow.transpose",
"tensorflow.get_variable_scope",
"tensorflow.nn.dropout",
"tensorflow.nn.conv2d_transpose",
"tensorflow.nn.softmax",
"recognition.utils.train_utils.in... | [((309, 323), 'random.seed', 'random.seed', (['(0)'], {}), '(0)\n', (320, 323), False, 'import random\n'), ((324, 341), 'numpy.random.seed', 'np.random.seed', (['(0)'], {}), '(0)\n', (338, 341), True, 'import numpy as np\n'), ((345, 378), 'tensorflow.python.framework.ops.RegisterGradient', 'ops.RegisterGradient', (['""... |
# AUTOGENERATED! DO NOT EDIT! File to edit: linear.ipynb (unless otherwise specified).
__all__ = ['vv', 'denoising_MRF']
# Cell
import numpy as np
import gtsam
from gtsam import noiseModel
from .display import show
from typing import Dict
# Cell
def vv(keys_vectors: Dict[int, np.ndarray]):
"""Create a VectorVal... | [
"numpy.eye",
"gtsam.noiseModel.Isotropic.Sigmas",
"numpy.random.default_rng",
"gtsam.symbol",
"numpy.array",
"numpy.zeros",
"gtsam.VectorValues",
"gtsam.GaussianFactorGraph"
] | [((352, 372), 'gtsam.VectorValues', 'gtsam.VectorValues', ([], {}), '()\n', (370, 372), False, 'import gtsam\n'), ((800, 825), 'numpy.random.default_rng', 'np.random.default_rng', (['(42)'], {}), '(42)\n', (821, 825), True, 'import numpy as np\n'), ((901, 937), 'gtsam.noiseModel.Isotropic.Sigmas', 'noiseModel.Isotropic... |
import os
from shutil import copyfile
from sphinxcontrib.collections.drivers import Driver
class CopyFileDriver(Driver):
def run(self):
self.info('Copy file...')
if not os.path.exists(self.config['source']):
self.error('Source {} does not exist'.format(self.config['source']))
... | [
"os.path.exists",
"shutil.copyfile",
"os.remove"
] | [((195, 232), 'os.path.exists', 'os.path.exists', (["self.config['source']"], {}), "(self.config['source'])\n", (209, 232), False, 'import os\n'), ((360, 414), 'shutil.copyfile', 'copyfile', (["self.config['source']", "self.config['target']"], {}), "(self.config['source'], self.config['target'])\n", (368, 414), False, ... |
# -*- coding: utf-8 -*-
# Copyright 2020 Red Hat
# GNU General Public License v3.0+
# (see COPYING or https://www.gnu.org/licenses/gpl-3.0.txt)
from __future__ import absolute_import, division, print_function
__metaclass__ = type
import ast
import re
from ansible.plugins.action import ActionBase
from ansible.module... | [
"jinja2.Template",
"ast.literal_eval",
"ansible.module_utils._text.to_native",
"re.sub",
"ansible_collections.ansible.utils.plugins.module_utils.common.argspec_validate.AnsibleArgSpecValidator",
"ansible.errors.AnsibleActionFail"
] | [((1094, 1190), 'ansible_collections.ansible.utils.plugins.module_utils.common.argspec_validate.AnsibleArgSpecValidator', 'AnsibleArgSpecValidator', ([], {'data': 'self._task.args', 'schema': 'DOCUMENTATION', 'name': 'self._task.action'}), '(data=self._task.args, schema=DOCUMENTATION, name=\n self._task.action)\n', ... |
import os
import zipfile
import zlib
def make_rel_archive(a_parent, a_name):
archive = zipfile.ZipFile("release/" + a_name + ".zip", "w", zipfile.ZIP_DEFLATED)
def do_write(a_relative):
archive.write(a_parent + a_relative, a_relative)
do_write("F4SE/Plugins/" + a_name + ".dll")
do_write("F4SE/Plugins/" + a_name... | [
"os.path.realpath",
"os.mkdir",
"zipfile.ZipFile",
"os.getcwd"
] | [((89, 161), 'zipfile.ZipFile', 'zipfile.ZipFile', (["('release/' + a_name + '.zip')", '"""w"""', 'zipfile.ZIP_DEFLATED'], {}), "('release/' + a_name + '.zip', 'w', zipfile.ZIP_DEFLATED)\n", (104, 161), False, 'import zipfile\n'), ((437, 523), 'zipfile.ZipFile', 'zipfile.ZipFile', (["('release/' + a_name + '_pdb' + '.z... |
"""Evaluating Prophet model on M4 timeseries
"""
from darts.models import Prophet
from darts.utils.statistics import check_seasonality
from darts.utils import _build_tqdm_iterator
import numpy as np
import pandas as pd
import pickle as pkl
from M4_metrics import owa_m4, mase_m4, smape_m4
if __name__ == "__main__"... | [
"M4_metrics.mase_m4",
"pandas.read_csv",
"M4_metrics.smape_m4",
"numpy.argmax",
"numpy.stack",
"darts.models.Prophet"
] | [((429, 478), 'pandas.read_csv', 'pd.read_csv', (['"""dataset/M4-info.csv"""'], {'delimiter': '""","""'}), "('dataset/M4-info.csv', delimiter=',')\n", (440, 478), True, 'import pandas as pd\n'), ((2152, 2175), 'darts.models.Prophet', 'Prophet', ([], {}), '(**prophet_args)\n', (2159, 2175), False, 'from darts.models imp... |
from __future__ import absolute_import
from __future__ import division
from __future__ import print_function
import tensorflow as tf
import os
from datasets import convert_data
FLAGS = tf.app.flags.FLAGS
tf.app.flags.DEFINE_string('data_type', None,
'The type of the dataset to convert, ne... | [
"os.path.exists",
"tensorflow.app.flags.DEFINE_integer",
"os.makedirs",
"tensorflow.app.flags.DEFINE_string",
"datasets.convert_data.run",
"tensorflow.app.run"
] | [((208, 333), 'tensorflow.app.flags.DEFINE_string', 'tf.app.flags.DEFINE_string', (['"""data_type"""', 'None', '"""The type of the dataset to convert, need to be either "train" or "test"."""'], {}), '(\'data_type\', None,\n \'The type of the dataset to convert, need to be either "train" or "test".\')\n', (234, 333),... |
# -*- coding: utf-8 -*-
# Copyright (c) 2015, Vispy Development Team.
# Distributed under the (new) BSD License. See LICENSE.txt for more info.
import numpy as np
from numpy.testing import assert_array_equal, assert_allclose
from vispy.testing import run_tests_if_main
from vispy.geometry import (create_box, create_cub... | [
"numpy.ones_like",
"numpy.unique",
"vispy.geometry.create_cylinder",
"vispy.testing.run_tests_if_main",
"vispy.geometry.create_plane",
"vispy.geometry.create_sphere",
"vispy.geometry.create_cube",
"vispy.geometry.create_box"
] | [((1913, 1932), 'vispy.testing.run_tests_if_main', 'run_tests_if_main', ([], {}), '()\n', (1930, 1932), False, 'from vispy.testing import run_tests_if_main\n'), ((475, 487), 'vispy.geometry.create_box', 'create_box', ([], {}), '()\n', (485, 487), False, 'from vispy.geometry import create_box, create_cube, create_cylind... |
import logging
import numpy as np
from bico.geometry.point import Point
from bico.nearest_neighbor.base import NearestNeighbor
from bico.utils.ClusteringFeature import ClusteringFeature
from datetime import datetime
from typing import Callable, TextIO, List
logger = logging.getLogger(__name__)
class BICONode:
de... | [
"logging.getLogger",
"datetime.datetime.now",
"numpy.zeros"
] | [((268, 295), 'logging.getLogger', 'logging.getLogger', (['__name__'], {}), '(__name__)\n', (285, 295), False, 'import logging\n'), ((796, 809), 'numpy.zeros', 'np.zeros', (['dim'], {}), '(dim)\n', (804, 809), True, 'import numpy as np\n'), ((818, 831), 'numpy.zeros', 'np.zeros', (['dim'], {}), '(dim)\n', (826, 831), T... |
# import required module
import ctypes
# create node class
class Node:
def __init__(self, value):
self.value = value
self.npx = 0
# create linked list class
class XorLinkedList:
# constructor
def __init__(self):
self.head = None
self.tail = None
self.__nodes = []
# method to insert no... | [
"ctypes.cast"
] | [((4364, 4397), 'ctypes.cast', 'ctypes.cast', (['id', 'ctypes.py_object'], {}), '(id, ctypes.py_object)\n', (4375, 4397), False, 'import ctypes\n')] |
"""
class to read files in specific ways
"""
import glob
import random
class Filer:
"""
read files
"""
def __init__(self, file_path):
self.path = file_path
def get_random_iter(self):
"""
get file contents in random
"""
nb_files = sum(1 for _ in glob.iglob(self.path))
file_iter = glob.glob(self.path... | [
"glob.iglob",
"glob.glob"
] | [((301, 321), 'glob.glob', 'glob.glob', (['self.path'], {}), '(self.path)\n', (310, 321), False, 'import glob\n'), ((264, 285), 'glob.iglob', 'glob.iglob', (['self.path'], {}), '(self.path)\n', (274, 285), False, 'import glob\n')] |
import numpy as np
from scipy.stats import linregress as li
from math import exp
def calc_factor(field,stepsize=0.01):
"""
Function for calculation of the summed binning.
The returned result is an integral over the binning of the velocities.
It is done for the negative and positive half separately.
... | [
"numpy.copy",
"numpy.where",
"numpy.log",
"numpy.max",
"numpy.count_nonzero",
"numpy.array",
"numpy.exp",
"numpy.sum",
"numpy.isnan",
"numpy.min",
"math.exp"
] | [((785, 799), 'numpy.copy', 'np.copy', (['field'], {}), '(field)\n', (792, 799), True, 'import numpy as np\n'), ((1213, 1227), 'numpy.copy', 'np.copy', (['field'], {}), '(field)\n', (1220, 1227), True, 'import numpy as np\n'), ((1496, 1516), 'numpy.array', 'np.array', (['result_pos'], {}), '(result_pos)\n', (1504, 1516... |
from machine import Pin, UART
from grip import Grip
import time
class Floppy:
AXIS_POS_LIMIT = (0, 5, 5)
AXIS_NEG_LIMIT = (-7.5, 0, -5)
def __init__(self):
# region Attributes
self._speed = 20
self._buffer = 0
self._pos_tracker = [0.0, 0.0, 0.0]
# endregion
... | [
"time.sleep",
"machine.Pin",
"grip.Grip",
"time.sleep_ms",
"machine.UART",
"time.sleep_us"
] | [((342, 358), 'machine.Pin', 'Pin', (['(21)', 'Pin.OUT'], {}), '(21, Pin.OUT)\n', (345, 358), False, 'from machine import Pin, UART\n'), ((383, 399), 'machine.Pin', 'Pin', (['(13)', 'Pin.OUT'], {}), '(13, Pin.OUT)\n', (386, 399), False, 'from machine import Pin, UART\n'), ((591, 606), 'machine.UART', 'UART', (['(1)', '... |
import urllib3
import pandas as pd
import numpy as np
import zipfile
import copy
import pickle
import os
from esig import tosig
from tqdm import tqdm
from multiprocessing import Pool
from functools import partial
from os import listdir
from os.path import isfile, join
from sklearn.ensemble import RandomForestClassifier... | [
"os.listdir",
"copy.deepcopy",
"numpy.unique",
"zipfile.ZipFile",
"pandas.read_csv",
"numpy.where",
"os.path.join",
"sklearn.ensemble.RandomForestClassifier",
"numpy.max",
"numpy.array",
"urllib3.PoolManager",
"functools.partial",
"numpy.concatenate",
"numpy.min",
"multiprocessing.Pool",... | [((500, 521), 'urllib3.PoolManager', 'urllib3.PoolManager', ([], {}), '()\n', (519, 521), False, 'import urllib3\n'), ((784, 822), 'zipfile.ZipFile', 'zipfile.ZipFile', (['"""data/input.zip"""', '"""r"""'], {}), "('data/input.zip', 'r')\n", (799, 822), False, 'import zipfile\n'), ((1275, 1291), 'pandas.read_csv', 'pd.r... |
#-------------------------------------------------------------------------------
# Filename: create_pics.py
# Description: creates square pictures out of a picture which is mostly empty
# for training a neural network later.
# The parameters to fool around with include:
# factor: scaled down image for faster imag... | [
"os.path.exists",
"os.listdir",
"PIL.Image.open",
"numpy.reshape",
"os.makedirs",
"os.path.splitext",
"numpy.argsort",
"numpy.sum",
"numpy.zeros"
] | [((1785, 1803), 'os.listdir', 'listdir', (['from_path'], {}), '(from_path)\n', (1792, 1803), False, 'from os import listdir, path, makedirs\n'), ((1343, 1365), 'os.path.exists', 'path.exists', (['from_path'], {}), '(from_path)\n', (1354, 1365), False, 'from os import listdir, path, makedirs\n'), ((1883, 1911), 'os.path... |
"""
Helper functions for the tests
"""
import os
import numpy as np
from msl.io import read
def read_sample(filename, **kwargs):
"""Read a file in the 'samples' directory.
Parameters
----------
filename : str
The name of the file in the samples/ directory
Returns
-------
A root... | [
"os.path.dirname",
"numpy.array_equal"
] | [((955, 987), 'numpy.array_equal', 'np.array_equal', (['d1.data', 'd2.data'], {}), '(d1.data, d2.data)\n', (969, 987), True, 'import numpy as np\n'), ((365, 390), 'os.path.dirname', 'os.path.dirname', (['__file__'], {}), '(__file__)\n', (380, 390), False, 'import os\n'), ((661, 683), 'numpy.array_equal', 'np.array_equa... |
# -*- coding: utf-8 -*-
"""
Created on Wed Oct 19 17:35:09 2016
@author: yxl
"""
from imagepy.core.engine import Tool
import numpy as np
from imagepy.core.manager import ColorManager
from imagepy.core.draw.fill import floodfill
class Plugin(Tool):
title = 'Flood Fill'
para = {'tor':10, 'con':'8-connect'}
... | [
"imagepy.core.manager.ColorManager.get_front",
"numpy.mean",
"imagepy.core.draw.fill.floodfill"
] | [((549, 624), 'imagepy.core.draw.fill.floodfill', 'floodfill', (['ips.img', 'x', 'y', "self.para['tor']", "(self.para['con'] == '8-connect')"], {}), "(ips.img, x, y, self.para['tor'], self.para['con'] == '8-connect')\n", (558, 624), False, 'from imagepy.core.draw.fill import floodfill\n'), ((684, 708), 'imagepy.core.ma... |
"""Signal dispatchers and handlers for the articles module"""
from django.db.models.signals import post_save
from django.dispatch import receiver, Signal
from authors.apps.articles.models import Article
# our custom signal that will be sent when a new article is published
# we could have stuck to using the post_save ... | [
"django.dispatch.receiver",
"django.dispatch.Signal"
] | [((509, 543), 'django.dispatch.Signal', 'Signal', ([], {'providing_args': "['article']"}), "(providing_args=['article'])\n", (515, 543), False, 'from django.dispatch import receiver, Signal\n'), ((586, 621), 'django.dispatch.receiver', 'receiver', (['post_save'], {'sender': 'Article'}), '(post_save, sender=Article)\n',... |
"""TFTBechmark scripts"""
import shutil
import tempfile
import time
import tensorflow as tf
import tqdm
from datasets import load_dataset
from transformers import RobertaTokenizerFast
from tf_transformers.models import Classification_Model
from tf_transformers.models import RobertaModel as Model
_ALLOWED_DECODER_TYP... | [
"tensorflow.saved_model.load",
"tensorflow.data.Dataset.from_tensor_slices",
"time.time",
"tqdm.tqdm",
"shutil.rmtree",
"tf_transformers.models.Classification_Model",
"tf_transformers.models.RobertaModel.from_pretrained",
"tempfile.mkdtemp",
"datasets.load_dataset",
"gc.collect",
"tensorflow.one... | [((742, 795), 'transformers.RobertaTokenizerFast.from_pretrained', 'RobertaTokenizerFast.from_pretrained', (['self.model_name'], {}), '(self.model_name)\n', (778, 795), False, 'from transformers import RobertaTokenizerFast\n'), ((820, 838), 'tempfile.mkdtemp', 'tempfile.mkdtemp', ([], {}), '()\n', (836, 838), False, 'i... |
#
# Copyright(c) 2020-2021 Intel Corporation
# SPDX-License-Identifier: BSD-3-Clause-Clear
#
import os
import pytest
from api.cas import casadm
from api.cas.cache_config import CacheMode
from core.test_run import TestRun
from storage_devices.disk import DiskTypeSet, DiskType, DiskTypeLowerThan
from test_tools.dd impo... | [
"pytest.mark.parametrizex",
"storage_devices.disk.DiskTypeSet",
"test_utils.size.Size",
"core.test_run.TestRun.LOGGER.info",
"os.path.join",
"api.cas.casadm.start_cache",
"test_utils.os_utils.drop_caches",
"api.cas.casadm.load_cache",
"core.test_run.TestRun.plugin_manager.get_plugin",
"core.test_r... | [((695, 744), 'pytest.mark.parametrizex', 'pytest.mark.parametrizex', (['"""cache_mode"""', 'CacheMode'], {}), "('cache_mode', CacheMode)\n", (719, 744), False, 'import pytest\n'), ((746, 796), 'pytest.mark.parametrizex', 'pytest.mark.parametrizex', (['"""filesystem"""', 'Filesystem'], {}), "('filesystem', Filesystem)\... |
# type: ignore
# This is a small script to parse the header files from wasmtime and generate
# appropriate function definitions in Python for each exported function. This
# also reflects types into Python with `ctypes`. While there's at least one
# other generate that does this already it seemed to not quite fit our p... | [
"pycparser.parse_file"
] | [((6278, 6657), 'pycparser.parse_file', 'parse_file', (['"""./wasmtime/include/wasmtime.h"""'], {'use_cpp': '(True)', 'cpp_path': '"""gcc"""', 'cpp_args': "['-E', '-I./wasmtime/include', '-D__attribute__(x)=', '-D__asm__(x)=',\n '-D__asm(x)=', '-D__volatile__(x)=', '-D_Static_assert(x, y)=',\n '-Dstatic_assert(x,... |
from utils import project_list
from learning import IncrementalLearningModel
def get_testing_dataset_size(prj):
l = IncrementalLearningModel(prj['name'], 'RF', 30, 1)
y_proba, y_test = l.get_predicted_data()
return len(y_test)
def main():
for idx, prj in enumerate(project_list):
print(prj['... | [
"learning.IncrementalLearningModel"
] | [((122, 172), 'learning.IncrementalLearningModel', 'IncrementalLearningModel', (["prj['name']", '"""RF"""', '(30)', '(1)'], {}), "(prj['name'], 'RF', 30, 1)\n", (146, 172), False, 'from learning import IncrementalLearningModel\n')] |
# ================================================================
# MIT License
# Copyright (c) 2022 edwardyehuang (https://github.com/edwardyehuang)
# ================================================================
import tensorflow as tf
from iseg.layers.normalizations import normalization
from iseg.utils.attent... | [
"tensorflow.shape",
"tensorflow.reduce_sum",
"tensorflow.math.divide_no_nan",
"tensorflow.cast",
"car_core.utils.get_intra_class_absolute_loss",
"tensorflow.nn.avg_pool2d",
"iseg.vis.vismanager.get_visualization_manager",
"tensorflow.keras.layers.Conv2D",
"iseg.layers.model_builder.get_training_valu... | [((1435, 1462), 'iseg.vis.vismanager.get_visualization_manager', 'get_visualization_manager', ([], {}), '()\n', (1460, 1462), False, 'from iseg.vis.vismanager import get_visualization_manager\n'), ((3980, 4008), 'iseg.layers.model_builder.get_training_value', 'get_training_value', (['training'], {}), '(training)\n', (3... |
from serendipity.linear_structures.singly_linked_list import LinkedList
class Set:
def __init__(self):
self._list = LinkedList()
def get_size(self):
return self._list.get_size()
def is_empty(self):
return self._list.is_empty()
def contains(self, e):
return self._list... | [
"serendipity.linear_structures.singly_linked_list.LinkedList"
] | [((130, 142), 'serendipity.linear_structures.singly_linked_list.LinkedList', 'LinkedList', ([], {}), '()\n', (140, 142), False, 'from serendipity.linear_structures.singly_linked_list import LinkedList\n')] |
#!/usr/bin/env python
# coding: utf-8
import argparse
import elitech
import datetime
from elitech.msg import (
StopButton,
ToneSet,
AlarmSetting,
TemperatureUnit,
)
from elitech.msg import _bin
import six
import os
def main():
args = parse_args()
if (args.command == 'simple-set'):
com... | [
"elitech.msg._bin",
"datetime.time",
"argparse.ArgumentParser",
"datetime.datetime.strptime",
"six.print_",
"elitech.Device"
] | [((844, 892), 'datetime.time', 'datetime.time', ([], {'hour': 'hour', 'minute': 'min', 'second': 'sec'}), '(hour=hour, minute=min, second=sec)\n', (857, 892), False, 'import datetime\n'), ((936, 1005), 'elitech.Device', 'elitech.Device', (['args.serial_port', 'args.ser_baudrate', 'args.ser_timeout'], {}), '(args.serial... |
#!/usr/bin/env python
import sys
import string
import re
for line in sys.stdin:
if '"' in line:
entry = re.split(''',(?=(?:[^'"]|'[^']*'|"[^"]*")*$)''', line)
else:
entry = line.split(",")
licence_type = entry[2]
amount_due = entry[-6]
print("%s\t%s" % (licence_type, amount_due))
| [
"re.split"
] | [((110, 164), 're.split', 're.split', (['""",(?=(?:[^\'"]|\'[^\']*\'|"[^"]*")*$)"""', 'line'], {}), '(\',(?=(?:[^\\\'"]|\\\'[^\\\']*\\\'|"[^"]*")*$)\', line)\n', (118, 164), False, 'import re\n')] |
from flask_restplus import fields, Model
def add_models_to_namespace(namespace):
namespace.models[route_request_model.name] = route_request_model
route_request_model = Model("Represents a Route Request", {
"id": fields.Integer(description="Unique identifier for the ride"),
"start_point_lat": fields.Floa... | [
"flask_restplus.fields.Float",
"flask_restplus.fields.Integer"
] | [((224, 284), 'flask_restplus.fields.Integer', 'fields.Integer', ([], {'description': '"""Unique identifier for the ride"""'}), "(description='Unique identifier for the ride')\n", (238, 284), False, 'from flask_restplus import fields, Model\n'), ((309, 382), 'flask_restplus.fields.Float', 'fields.Float', ([], {'descrip... |
from collections import OrderedDict
import torch
import torch.nn as nn
import torch.nn.functional as F
from torch.nn import Module
'''
# ===================================
# Advanced nn.Sequential
# reform nn.Sequentials and nn.Modules
# to a single nn.Sequential
# ===================================
'''
def sequen... | [
"torch.nn.Sigmoid",
"torch.nn.ReLU",
"torch.nn.BatchNorm2d",
"torch.nn.LeakyReLU",
"torch.nn.PixelShuffle",
"torch.nn.Sequential",
"torch.eye",
"torch.Tensor",
"torch.nn.Conv2d",
"torch.nn.InstanceNorm2d",
"torch.nn.MaxPool2d",
"torch.nn.Upsample",
"torch.nn.AdaptiveAvgPool2d",
"torch.nn.A... | [((807, 830), 'torch.nn.Sequential', 'nn.Sequential', (['*modules'], {}), '(*modules)\n', (820, 830), True, 'import torch.nn as nn\n'), ((3235, 3256), 'torch.Tensor', 'torch.Tensor', (['rgb_std'], {}), '(rgb_std)\n', (3247, 3256), False, 'import torch\n'), ((5496, 5519), 'torch.nn.AdaptiveAvgPool2d', 'nn.AdaptiveAvgPoo... |
# -*- encoding: utf-8 -*-
"""
Created by <NAME> at 01/09/2021 at 19:51:44
Project: py_dss_tools [set, 2021]
"""
import attr
import pandas as pd
from py_dss_tools.model.other import VSource
from py_dss_tools.utils import Utils
@attr.s
class Circuit(VSource):
_name = attr.ib(validator=attr.validators.instance_of... | [
"pandas.DataFrame.from_records",
"py_dss_tools.utils.Utils.check_instance",
"py_dss_tools.utils.Utils.remove_blank_spaces",
"py_dss_tools.utils.Utils.generate_random_string",
"attr.validators.instance_of"
] | [((1296, 1338), 'pandas.DataFrame.from_records', 'pd.DataFrame.from_records', (['[self.__dict__]'], {}), '([self.__dict__])\n', (1321, 1338), True, 'import pandas as pd\n'), ((1601, 1645), 'py_dss_tools.utils.Utils.check_instance', 'Utils.check_instance', (['value', '"""name"""', "['str']"], {}), "(value, 'name', ['str... |
from django.conf import settings
from django.db import models
class Tasks(models.Model):
"Generated Model"
task_name = models.TextField()
| [
"django.db.models.TextField"
] | [((129, 147), 'django.db.models.TextField', 'models.TextField', ([], {}), '()\n', (145, 147), False, 'from django.db import models\n')] |
import os
import json
from vector2d import Vector2D
from interpolator import Interpolator
from utils import map_range
# Each game controller axis returns a value in the closed interval [-1, 1]. We
# limit the number of decimal places we use with the PRECISION constant. This is
# done for a few reasons: 1) it makes th... | [
"json.dumps",
"os.path.join",
"os.path.isfile",
"pwm_controller.PWMController",
"interpolator.Interpolator",
"json.load",
"utils.map_range",
"vector2d.Vector2D"
] | [((3896, 3906), 'vector2d.Vector2D', 'Vector2D', ([], {}), '()\n', (3904, 3906), False, 'from vector2d import Vector2D\n'), ((3925, 3935), 'vector2d.Vector2D', 'Vector2D', ([], {}), '()\n', (3933, 3935), False, 'from vector2d import Vector2D\n'), ((3999, 4013), 'interpolator.Interpolator', 'Interpolator', ([], {}), '()... |
import operator
import unittest
from asq.queryables import Queryable
__author__ = "<NAME>"
class TestPreScan(unittest.TestCase):
def test_pre_scan_empty_default(self):
a = []
b = Queryable(a).pre_scan().to_list()
c = []
self.assertEqual(b, c)
def test_pre_scan_s... | [
"asq.queryables.Queryable"
] | [((1446, 1459), 'asq.queryables.Queryable', 'Queryable', (['[]'], {}), '([])\n', (1455, 1459), False, 'from asq.queryables import Queryable\n'), ((212, 224), 'asq.queryables.Queryable', 'Queryable', (['a'], {}), '(a)\n', (221, 224), False, 'from asq.queryables import Queryable\n'), ((372, 384), 'asq.queryables.Queryabl... |
from django.core.exceptions import SuspiciousOperation
from django.core.signing import Signer, BadSignature
from django.forms import HiddenInput
signer = Signer()
class SignedHiddenInput(HiddenInput):
def __init__(self, include_field_name=True, attrs=None):
self.include_field_name = include_field_name
... | [
"django.core.signing.Signer",
"django.core.exceptions.SuspiciousOperation"
] | [((155, 163), 'django.core.signing.Signer', 'Signer', ([], {}), '()\n', (161, 163), False, 'from django.core.signing import Signer, BadSignature\n'), ((621, 642), 'django.core.exceptions.SuspiciousOperation', 'SuspiciousOperation', ([], {}), '()\n', (640, 642), False, 'from django.core.exceptions import SuspiciousOpera... |
from fastapi import APIRouter
from starlette.requests import Request
router = APIRouter()
@router.get('/')
async def read_root(request: Request):
return "ML serving with fastapi"
@router.get('api/predict')
async def predict_number(request: Request):
model = request.app.ml_model
return model.predict('bla... | [
"fastapi.APIRouter"
] | [((79, 90), 'fastapi.APIRouter', 'APIRouter', ([], {}), '()\n', (88, 90), False, 'from fastapi import APIRouter\n')] |
# Copyright 2020 The TensorFlow Probability Authors.
#
# Licensed under the Apache License, Version 2.0 (the "License");
# you may not use this file except in compliance with the License.
# You may obtain a copy of the License at
#
# http://www.apache.org/licenses/LICENSE-2.0
#
# Unless required by applicable law o... | [
"tensorflow.compat.v2.test.main",
"inference_gym.targets.eight_schools.EightSchools"
] | [((1887, 1901), 'tensorflow.compat.v2.test.main', 'tf.test.main', ([], {}), '()\n', (1899, 1901), True, 'import tensorflow.compat.v2 as tf\n'), ((1109, 1137), 'inference_gym.targets.eight_schools.EightSchools', 'eight_schools.EightSchools', ([], {}), '()\n', (1135, 1137), False, 'from inference_gym.targets import eight... |
import os
from django.http import HttpResponse
from django.contrib.auth.decorators import login_required
def isAccess(path):
try:
os.listdir(path)
return True
except PermissionError:
return False
@login_required
def isExist(request):
return HttpResponse(os.path.exists(os.path.abspat... | [
"os.path.abspath",
"os.listdir"
] | [((143, 159), 'os.listdir', 'os.listdir', (['path'], {}), '(path)\n', (153, 159), False, 'import os\n'), ((306, 343), 'os.path.abspath', 'os.path.abspath', (["request.POST['path']"], {}), "(request.POST['path'])\n", (321, 343), False, 'import os\n')] |
from typing import Union
from scipy.spatial.qhull import Delaunay
from shapely.geometry import LineString
from subsurface.structs.base_structures import StructuredData
import numpy as np
try:
import segyio
segyio_imported = True
except ImportError:
segyio_imported = False
def read_in_segy(filepath: str, ... | [
"numpy.copy",
"subsurface.structs.base_structures.StructuredData.from_numpy",
"numpy.array",
"numpy.zeros",
"scipy.spatial.qhull.Delaunay",
"segyio.open"
] | [((793, 836), 'segyio.open', 'segyio.open', (['filepath'], {'ignore_geometry': '(True)'}), '(filepath, ignore_geometry=True)\n', (804, 836), False, 'import segyio\n'), ((913, 944), 'subsurface.structs.base_structures.StructuredData.from_numpy', 'StructuredData.from_numpy', (['data'], {}), '(data)\n', (938, 944), False,... |
#!/bin/python
# should be started from project base directory
# helper script to regenerate helm chart file: partial of charts/external-dns-management/templates/deployment.yaml
import re
import os
helpFilename = "/tmp/dns-controller-manager-help.txt"
rc = os.system("make build-local && ./dns-controller-manager --he... | [
"re.split",
"re.compile",
"re.match",
"os.remove"
] | [((433, 456), 'os.remove', 'os.remove', (['helpFilename'], {}), '(helpFilename)\n', (442, 456), False, 'import os\n'), ((1070, 1096), 're.compile', 're.compile', (['""".*cache-dir$"""'], {}), "('.*cache-dir$')\n", (1080, 1096), False, 'import re\n'), ((1098, 1127), 're.compile', 're.compile', (['""".*blocked-zone$"""']... |
from MDP import MDP
import unittest
class MDPTestCase(unittest.TestCase):
def test_small1(self):
lst = [['a', 'a', 'b', 'b', 'c', 'c', 'd', 'd']]
self.__printInput(lst)
mdp = MDP(lst)
mdp.run()
# Get the result Transition Probabilities (dictionary)
tp = mdp.getTrans... | [
"unittest.main",
"MDP.MDP"
] | [((1337, 1352), 'unittest.main', 'unittest.main', ([], {}), '()\n', (1350, 1352), False, 'import unittest\n'), ((205, 213), 'MDP.MDP', 'MDP', (['lst'], {}), '(lst)\n', (208, 213), False, 'from MDP import MDP\n'), ((704, 712), 'MDP.MDP', 'MDP', (['lst'], {}), '(lst)\n', (707, 712), False, 'from MDP import MDP\n')] |
# Generated by Django 2.2.10 on 2020-05-02 05:53
from django.db import migrations
class Migration(migrations.Migration):
dependencies = [
('purchases', '0008_auto_20200430_1617'),
]
operations = [
migrations.RenameField(
model_name='itempurchase',
old_name='suppl... | [
"django.db.migrations.RenameField"
] | [((230, 328), 'django.db.migrations.RenameField', 'migrations.RenameField', ([], {'model_name': '"""itempurchase"""', 'old_name': '"""supplier_price"""', 'new_name': '"""price"""'}), "(model_name='itempurchase', old_name='supplier_price',\n new_name='price')\n", (252, 328), False, 'from django.db import migrations\n... |
import dash
from dash import Output, Input, dcc
from dash import html
from tabs import tab1, tab2
# from tab2_callbacks import tab2_out, upload_prediction, render_graph2
import flask
server = flask.Flask(__name__) # define flask app.server
external_stylesheets = [
{
"href": "https://fonts.googleapis.com... | [
"flask.Flask",
"dash.Input",
"dash.html.H1",
"dash.Output",
"dash.html.P",
"dash.dcc.Tab",
"dash.Dash"
] | [((195, 216), 'flask.Flask', 'flask.Flask', (['__name__'], {}), '(__name__)\n', (206, 216), False, 'import flask\n'), ((537, 614), 'dash.Dash', 'dash.Dash', (['__name__'], {'server': 'server', 'external_stylesheets': 'external_stylesheets'}), '(__name__, server=server, external_stylesheets=external_stylesheets)\n', (54... |
from unittest import TestCase
from evaluate import Calculator
calc = Calculator()
class TestCalculator(TestCase):
def test_evaluate_01(self):
self.assertEqual(calc.evaluate(string='127'), 127)
def test_evaluate_02(self):
self.assertEqual(calc.evaluate(string='2 + 3'), 5)
d... | [
"evaluate.Calculator"
] | [((71, 83), 'evaluate.Calculator', 'Calculator', ([], {}), '()\n', (81, 83), False, 'from evaluate import Calculator\n')] |
import os
import lxml.etree as et
import pandas as pd
import numpy as np
import regex as re
def get_element_text(element):
"""
Extract text while
-skipping footnote numbers
-Adding a space before and after emphasized text
"""
head = element.text if element.tag != 'SU' else ''
child = ' '.... | [
"regex.search",
"regex.finditer",
"lxml.etree.parse",
"regex.match",
"regex.sub",
"pandas.DataFrame"
] | [((5550, 5583), 'regex.sub', 're.sub', (['"""(\\\\S)\\\\("""', '"""\\\\g<1> ("""', 's'], {}), "('(\\\\S)\\\\(', '\\\\g<1> (', s)\n", (5556, 5583), True, 'import regex as re\n'), ((5629, 5688), 'regex.sub', 're.sub', (['"""(\\\\S)([\\\\u2014-])(\\\\S)"""', '"""\\\\g<1> \\\\g<2> \\\\g<3>"""', 's'], {}), "('(\\\\S)([\\\\u... |
"""
Script to generate a custom list of stopwords that extend upon existing lists.
"""
import json
import spacy
from urllib.request import urlopen
from itertools import chain
def combine(*lists):
"Combine an arbitrary number of lists into a single list"
return list(chain(*lists))
def get_spacy_lemmas():
... | [
"itertools.chain",
"json.loads",
"spacy.blank",
"urllib.request.urlopen"
] | [((547, 565), 'json.loads', 'json.loads', (['lemmas'], {}), '(lemmas)\n', (557, 565), False, 'import json\n'), ((1120, 1137), 'spacy.blank', 'spacy.blank', (['"""en"""'], {}), "('en')\n", (1131, 1137), False, 'import spacy\n'), ((276, 289), 'itertools.chain', 'chain', (['*lists'], {}), '(*lists)\n', (281, 289), False, ... |
# -*- coding: utf-8 -*-
# @Time : 18/12/10 上午10:27
# @Author : L_zejie
# @Site :
# @File : setup.py.py
# @Software: PyCharm Community Edition
from setuptools import setup, find_packages
setup(
name="DynamicPool",
packages=find_packages(),
version='0.14',
description="动态任务阻塞线程/进程池",
autho... | [
"setuptools.find_packages"
] | [((242, 257), 'setuptools.find_packages', 'find_packages', ([], {}), '()\n', (255, 257), False, 'from setuptools import setup, find_packages\n')] |
#!/usr/bin/env py.test
"""
Test SinglyLinkedList class.
"""
import copy
import unittest
from py_alg_dat import singly_linked_list
class TestSinglyLinkedList(unittest.TestCase):
"""
Test SinglyLinkedList class.
"""
def setUp(self):
self.list1 = singly_linked_list.SinglyLinkedList()
... | [
"copy.copy",
"py_alg_dat.singly_linked_list.SinglyLinkedList",
"py_alg_dat.singly_linked_list.SinglyLinkedListElement"
] | [((275, 312), 'py_alg_dat.singly_linked_list.SinglyLinkedList', 'singly_linked_list.SinglyLinkedList', ([], {}), '()\n', (310, 312), False, 'from py_alg_dat import singly_linked_list\n'), ((610, 647), 'py_alg_dat.singly_linked_list.SinglyLinkedList', 'singly_linked_list.SinglyLinkedList', ([], {}), '()\n', (645, 647), ... |
import urllib.parse
import time
import hashlib
import hmac
from bravado.requests_client import Authenticator
class APIKeyAuthenticator(Authenticator):
"""?api_key authenticator.
This authenticator adds BitMEX API key support via header.
:param host: Host to authenticate for.
:param api_key: API key.
... | [
"time.time"
] | [((846, 857), 'time.time', 'time.time', ([], {}), '()\n', (855, 857), False, 'import time\n')] |
from .models import db, User
from m import Router
from m.utils import jsonify
router = Router(prefix='')
@router.route('/', methods=['POST'])
def home(ctx, request):
name = request.json().get('name')
user = User(name=name)
db.session.add(user)
try:
db.session.commit()
except Exception as ... | [
"m.Router"
] | [((88, 105), 'm.Router', 'Router', ([], {'prefix': '""""""'}), "(prefix='')\n", (94, 105), False, 'from m import Router\n')] |
# -*- coding: utf-8 -*-
import os
import sys
from pyzabbix import ZabbixMetric, ZabbixSender
from lumbermill.BaseThreadedModule import BaseThreadedModule
from lumbermill.utils.Buffers import Buffer
from lumbermill.utils.Decorators import ModuleDocstringParser
from lumbermill.utils.DynamicValues import mapDynamicValue
... | [
"pyzabbix.ZabbixMetric",
"lumbermill.utils.DynamicValues.mapDynamicValue",
"os.path.isfile",
"pyzabbix.ZabbixSender",
"lumbermill.BaseThreadedModule.BaseThreadedModule.configure",
"lumbermill.BaseThreadedModule.BaseThreadedModule.initAfterFork"
] | [((2237, 2286), 'lumbermill.BaseThreadedModule.BaseThreadedModule.configure', 'BaseThreadedModule.configure', (['self', 'configuration'], {}), '(self, configuration)\n', (2265, 2286), False, 'from lumbermill.BaseThreadedModule import BaseThreadedModule\n'), ((4084, 4122), 'lumbermill.BaseThreadedModule.BaseThreadedModu... |
#!/usr/bin/python
#author: zhaofeng-shu33
import numpy as np
from ace_cream import ace_cream
def pearson_correlation(X,Y):
return (np.mean(X*Y, axis=0) -np.mean(X, axis = 0)* np.mean(Y, axis = 0)) / ( np.std(X, axis = 0) * np.std(Y, axis = 0))
if __name__ == '__main__':
N_SIZE = 1000
ERROR_PROBABILITY = ... | [
"numpy.mean",
"numpy.unique",
"numpy.random.choice",
"ace_cream.ace_cream",
"numpy.std",
"numpy.random.uniform"
] | [((332, 369), 'numpy.random.choice', 'np.random.choice', (['[0, 1]'], {'size': 'N_SIZE'}), '([0, 1], size=N_SIZE)\n', (348, 369), True, 'import numpy as np\n'), ((376, 406), 'numpy.random.uniform', 'np.random.uniform', ([], {'size': 'N_SIZE'}), '(size=N_SIZE)\n', (393, 406), True, 'import numpy as np\n'), ((770, 798), ... |
# Generated by Django 3.1.7 on 2021-03-19 15:51
from django.db import migrations
class Migration(migrations.Migration):
dependencies = [
("track", "0021_auto_20200915_1528"),
]
operations = [
migrations.RemoveField(
model_name="track",
name="parser",
),
... | [
"django.db.migrations.DeleteModel",
"django.db.migrations.RemoveField"
] | [((225, 282), 'django.db.migrations.RemoveField', 'migrations.RemoveField', ([], {'model_name': '"""track"""', 'name': '"""parser"""'}), "(model_name='track', name='parser')\n", (247, 282), False, 'from django.db import migrations\n'), ((327, 363), 'django.db.migrations.DeleteModel', 'migrations.DeleteModel', ([], {'na... |
'''
Name: color_segmentation.py
Version: 1.0
Summary: Extract plant traits (leaf area, width, height, ) by paralell processing
Author: <NAME>
Author-email: <EMAIL>
Created: 2018-09-29
USAGE:
python3 color_kmeans_vis.py -p /home/suxingliu/plant-image-analysis/sample_test/ -i 01.jpg -m 01_seg.jpg -c 5
'''
... | [
"os.path.exists",
"cv2.imwrite",
"utils.centroid_histogram",
"argparse.ArgumentParser",
"cv2.threshold",
"utils.plot_centroid_histogram",
"sklearn.cluster.MiniBatchKMeans",
"os.makedirs",
"cv2.bitwise_and",
"utils.plot_colors",
"cv2.cvtColor",
"cv2.imread",
"utils.plot_color_bar"
] | [((792, 812), 'os.path.exists', 'os.path.exists', (['path'], {}), '(path)\n', (806, 812), False, 'import os\n'), ((1261, 1299), 'cv2.cvtColor', 'cv2.cvtColor', (['image', 'cv2.COLOR_BGR2RGB'], {}), '(image, cv2.COLOR_BGR2RGB)\n', (1273, 1299), False, 'import cv2\n'), ((1377, 1417), 'cv2.bitwise_and', 'cv2.bitwise_and',... |
import pandas as pd
import matplotlib.pyplot as plt
import pickle
df = pd.read_json('result.json',lines=True)
print(df) | [
"pandas.read_json"
] | [((72, 111), 'pandas.read_json', 'pd.read_json', (['"""result.json"""'], {'lines': '(True)'}), "('result.json', lines=True)\n", (84, 111), True, 'import pandas as pd\n')] |
import logging
from django.core.exceptions import ImproperlyConfigured
from rest_framework.exceptions import APIException
from rest_framework.views import APIView
from rest_framework.response import Response
from .checks import (
internal_services,
external_services,
)
logger = logging.getLogger('hhs_server.%s... | [
"logging.getLogger",
"rest_framework.response.Response",
"django.core.exceptions.ImproperlyConfigured"
] | [((288, 333), 'logging.getLogger', 'logging.getLogger', (["('hhs_server.%s' % __name__)"], {}), "('hhs_server.%s' % __name__)\n", (305, 333), False, 'import logging\n'), ((1233, 1268), 'rest_framework.response.Response', 'Response', (['{\'message\': "all\'s well"}'], {}), '({\'message\': "all\'s well"})\n', (1241, 1268... |
from machine import Pin
import time
from led import LED
tube_btn = Pin(21, Pin.IN, Pin.PULL_UP)
sys_led = Pin(25, Pin.OUT)
print('Blinking LED to power check (no LED? Check LED batteries and/or script).')
LED.led_blink(5)
print('Blink code finish - Listening for presses.')
while True:
first = tube_btn.value()
... | [
"led.LED.led_blink",
"led.LED.led_display",
"time.sleep",
"machine.Pin"
] | [((68, 96), 'machine.Pin', 'Pin', (['(21)', 'Pin.IN', 'Pin.PULL_UP'], {}), '(21, Pin.IN, Pin.PULL_UP)\n', (71, 96), False, 'from machine import Pin\n'), ((108, 124), 'machine.Pin', 'Pin', (['(25)', 'Pin.OUT'], {}), '(25, Pin.OUT)\n', (111, 124), False, 'from machine import Pin\n'), ((208, 224), 'led.LED.led_blink', 'LE... |
from nipype.interfaces import utility as util
from nipype.pipeline import engine as pe
from .interfaces import dsi_studio as dsi
import nipype.interfaces.diffusion_toolkit as dtk
from nipype.algorithms.misc import Gunzip
import os.path
def create_pipeline(name="dsi_track", opt="", ensemble=""):
parameters = {'nos... | [
"nipype.interfaces.diffusion_toolkit.TrackMerge",
"nipype.pipeline.engine.Workflow",
"nipype.interfaces.utility.IdentityInterface",
"nipype.algorithms.misc.Gunzip"
] | [((1522, 1544), 'nipype.pipeline.engine.Workflow', 'pe.Workflow', ([], {'name': 'name'}), '(name=name)\n', (1533, 1544), True, 'from nipype.pipeline import engine as pe\n'), ((468, 554), 'nipype.interfaces.utility.IdentityInterface', 'util.IdentityInterface', ([], {'fields': "['odf', 'seed', 'angle', 'algorithm', 'min_... |
import pandas as pd
from phc.easy.ocr.suggestion import (expand_array_column,
expand_medication_administrations,
frame_for_type)
sample = expand_array_column(
pd.DataFrame(
[
{
"suggestions": [
... | [
"pandas.DataFrame",
"phc.easy.ocr.suggestion.frame_for_type"
] | [((238, 1501), 'pandas.DataFrame', 'pd.DataFrame', (["[{'suggestions': [{'id': '728e79cd-6cd2-421f-9e38-3181200c301', 'condition':\n {'conditionCode': [], 'onsetDate': [], 'abatementDate': [], 'bodySite':\n []}, 'observation': {}, 'medicationAdministration': {'medicationCode':\n [{'value': {'system': 'http://w... |
from django.contrib import admin
from .models import Auction, Lot, Bid
class BidAdmin(admin.ModelAdmin):
readonly_fields = (
'user',
'auction',
'bid_amount',
'bid_time',
)
admin.site.register(Auction)
admin.site.register(Lot)
admin.site.register(Bid, BidAdmin)
| [
"django.contrib.admin.site.register"
] | [((223, 251), 'django.contrib.admin.site.register', 'admin.site.register', (['Auction'], {}), '(Auction)\n', (242, 251), False, 'from django.contrib import admin\n'), ((252, 276), 'django.contrib.admin.site.register', 'admin.site.register', (['Lot'], {}), '(Lot)\n', (271, 276), False, 'from django.contrib import admin\... |
import os
from aim.web.api.utils import APIRouter # wrapper for fastapi.APIRouter
from fastapi.responses import FileResponse
from aim.web.api.projects.project import Project
general_router = APIRouter()
@general_router.get('/static-files/{path:path}/')
async def serve_static_files(path):
from aim import web
... | [
"os.path.exists",
"aim.web.api.projects.project.Project",
"fastapi.responses.FileResponse",
"aim.web.api.utils.APIRouter",
"os.path.join",
"os.path.dirname"
] | [((195, 206), 'aim.web.api.utils.APIRouter', 'APIRouter', ([], {}), '()\n', (204, 206), False, 'from aim.web.api.utils import APIRouter\n'), ((474, 510), 'os.path.exists', 'os.path.exists', (['compressed_file_name'], {}), '(compressed_file_name)\n', (488, 510), False, 'import os\n'), ((611, 641), 'fastapi.responses.Fil... |
import threading
import enum
import os
import sys
import copy
import json
import asyncio
import attr
import uuid
import functools
import datetime
import multiprocessing
from time import monotonic
import time
import copy
from collections import deque
from concurrent.futures import ThreadPoolExecutor
from async_timeout i... | [
"merceedge.providers.ServiceProviderFactory.get_provider",
"asyncio.iscoroutinefunction",
"merceedge.api_server.models.ComponentDBModel.query.all",
"merceedge.util.id.generte_unique_id",
"merceedge.util.repr_helper",
"sys.exit",
"merceedge.util.async_util.Context",
"merceedge.util.yaml.load_yaml",
"... | [((593, 619), 'os.path.realpath', 'os.path.realpath', (['__file__'], {}), '(__file__)\n', (609, 619), False, 'import os\n'), ((18680, 18707), 'merceedge.util.id.generte_unique_id', 'id_util.generte_unique_id', ([], {}), '()\n', (18705, 18707), True, 'import merceedge.util.id as id_util\n'), ((1907, 1931), 'asyncio.get_... |
#!/usr/bin/env python
from django.core.management import execute_manager
try:
import settings # Assumed to be in the same directory.
except ImportError:
import sys
sys.stderr.write("Error: Can't find the file 'settings.py' in the directory"
" containing %r. It appears you've customized things.\n"
"You'll have to... | [
"django.core.management.execute_manager",
"sys.stderr.write",
"sys.exit"
] | [((524, 549), 'django.core.management.execute_manager', 'execute_manager', (['settings'], {}), '(settings)\n', (539, 549), False, 'from django.core.management import execute_manager\n'), ((167, 472), 'sys.stderr.write', 'sys.stderr.write', (['("""Error: Can\'t find the file \'settings.py\' in the directory containing %... |
import os
import sys
import shutil
import asyncio
import aioboto3
from glob import glob
from PIL import Image
from fnmatch import fnmatch
from src.secrets import (
SPACES_REGION,
SPACES_BUCKET,
SPACES_PREFIX,
SPACES_ENDPOINT_URL,
SPACES_ACCESS_KEY,
SPACES_SECRET_KEY
)
from src.format import (... | [
"os.path.exists",
"PIL.Image.open",
"asyncio.gather",
"os.makedirs",
"src.format.get_filename",
"os.walk",
"os.path.join",
"src.format.get_image_id",
"shutil.rmtree",
"src.logger.logger.error",
"fnmatch.fnmatch",
"src.logger.logger.info",
"aioboto3.resource",
"glob.glob"
] | [((1537, 1574), 'fnmatch.fnmatch', 'fnmatch', (['file', 'f"""{image.height}*.jpg"""'], {}), "(file, f'{image.height}*.jpg')\n", (1544, 1574), False, 'from fnmatch import fnmatch\n'), ((2872, 2928), 'glob.glob', 'glob', (["(LOCAL_IMAGES_PATH + f'/{SPACES_PREFIX}/*/720*.jpg')"], {}), "(LOCAL_IMAGES_PATH + f'/{SPACES_PREF... |
import re
import operator
from collections import namedtuple
SCHEMA_TYPES = {'str', 'int', 'bool'}
ROWID_KEY = '_rowid'
class Literal(namedtuple('Literal', 'value')):
@classmethod
def eval_value(cls, value):
if not isinstance(value, str):
raise ValueError(f"Parameter {value} must be a str... | [
"collections.namedtuple",
"re.compile"
] | [((137, 167), 'collections.namedtuple', 'namedtuple', (['"""Literal"""', '"""value"""'], {}), "('Literal', 'value')\n", (147, 167), False, 'from collections import namedtuple\n'), ((789, 817), 'collections.namedtuple', 'namedtuple', (['"""Column"""', '"""name"""'], {}), "('Column', 'name')\n", (799, 817), False, 'from ... |
"""
A module for calculating the relationship (or distance) between 2 strings.
Namely:
- edit_distance()
- needleman_wunsch()
- align()
- coverage()
"""
from typing import Callable, Tuple, List
from enum import IntEnum
from operator import itemgetter
from functools import lru_cache
import unittest
cl... | [
"unittest.main",
"functools.lru_cache",
"doctest.testmod",
"operator.itemgetter"
] | [((1194, 1217), 'functools.lru_cache', 'lru_cache', ([], {'maxsize': 'None'}), '(maxsize=None)\n', (1203, 1217), False, 'from functools import lru_cache\n'), ((2137, 2160), 'functools.lru_cache', 'lru_cache', ([], {'maxsize': 'None'}), '(maxsize=None)\n', (2146, 2160), False, 'from functools import lru_cache\n'), ((481... |
# -*- coding: utf-8 -*-
import pandas as pd
import numpy as np
import math
import datetime
import time
import matplotlib.pyplot as plt
import warnings
warnings.filterwarnings("ignore")
class Indicators():
def __init__(self, dataframe, params = []):
self.dataframe = dataframe
self.params = params
... | [
"datetime.datetime",
"matplotlib.pyplot.subplots_adjust",
"time.strptime",
"math.pow",
"matplotlib.pyplot.subplot",
"matplotlib.pyplot.figure",
"numpy.std",
"pandas.DataFrame",
"pandas.concat",
"warnings.filterwarnings",
"pandas.to_datetime",
"matplotlib.pyplot.show"
] | [((151, 184), 'warnings.filterwarnings', 'warnings.filterwarnings', (['"""ignore"""'], {}), "('ignore')\n", (174, 184), False, 'import warnings\n'), ((1033, 1071), 'pandas.to_datetime', 'pd.to_datetime', (["dataframe['tradeDate']"], {}), "(dataframe['tradeDate'])\n", (1047, 1071), True, 'import pandas as pd\n'), ((1704... |
# Copyright 2021 The OpenBytes Team. 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 appl... | [
"concurrent.futures.ThreadPoolExecutor",
"tqdm.tqdm",
"requests.get",
"concurrent.futures.as_completed",
"os.path.dirname"
] | [((1887, 1904), 'tqdm.tqdm', 'tqdm', ([], {'total': 'total'}), '(total=total)\n', (1891, 1904), False, 'from tqdm import tqdm\n'), ((2389, 2423), 'requests.get', 'requests.get', (['obj.url'], {'stream': '(True)'}), '(obj.url, stream=True)\n', (2401, 2423), False, 'import requests\n'), ((1931, 1968), 'concurrent.futures... |
"""
Name : c14_11_rainbow_callMaxOn2_viaSimulation.py
Book : Python for Finance (2nd ed.)
Publisher: Packt Publishing Ltd.
Author : <NAME>
Date : 6/6/2017
email : <EMAIL>
<EMAIL>
"""
import scipy as sp
from scipy import zeros, sqrt, shape
#
sp.random.seed(123) # fix our ra... | [
"scipy.sqrt",
"scipy.exp",
"scipy.zeros",
"scipy.random.normal",
"scipy.mean",
"scipy.random.seed"
] | [((287, 306), 'scipy.random.seed', 'sp.random.seed', (['(123)'], {}), '(123)\n', (301, 306), True, 'import scipy as sp\n'), ((815, 851), 'scipy.zeros', 'sp.zeros', (['[nSimulation]'], {'dtype': 'float'}), '([nSimulation], dtype=float)\n', (823, 851), True, 'import scipy as sp\n'), ((953, 987), 'scipy.random.normal', 's... |
import os
from os.path import join
INVESTIGATE = False # Records coverages and saves them. Generates a plot in the end. Do not use with automate.
TEST_OUTSIDE_FUZZER = False # Runs FATE as standalone (1+1) EA
BLACKBOX = True and TEST_OUTSIDE_FUZZER # Disables white-box information such as thresholds and feat imp.
F... | [
"os.path.join",
"os.getcwd"
] | [((13058, 13081), 'os.path.join', 'join', (['MODEL_DIR', '"""json"""'], {}), "(MODEL_DIR, 'json')\n", (13062, 13081), False, 'from os.path import join\n'), ((13121, 13145), 'os.path.join', 'join', (['DATA_DIR', '"""libsvm"""'], {}), "(DATA_DIR, 'libsvm')\n", (13125, 13145), False, 'from os.path import join\n'), ((13160... |
# -*- coding: utf-8 -*-
# pylint: disable=missing-docstring,unused-import,reimported
import io
import json
import pytest # type: ignore
import xmllint_map_html.cli as cli
import xmllint_map_html.xmllint_map_html as xmh
def test_main_ok_minimal(capsys):
job = ['']
report_expected = ''
assert cli.main(arg... | [
"xmllint_map_html.cli.main"
] | [((308, 326), 'xmllint_map_html.cli.main', 'cli.main', ([], {'argv': 'job'}), '(argv=job)\n', (316, 326), True, 'import xmllint_map_html.cli as cli\n')] |
"""Test is_boundary_not_x_monotone method in WeightedPointBoundary."""
# Standard
from typing import List, Any
from random import randint
# Models
from voronoi_diagrams.models import (
WeightedSite,
WeightedPointBisector,
WeightedPointBoundary,
)
# Math
from decimal import Decimal
class TestWeightedPoin... | [
"voronoi_diagrams.models.WeightedPointBisector",
"voronoi_diagrams.models.WeightedPointBoundary",
"decimal.Decimal"
] | [((661, 696), 'voronoi_diagrams.models.WeightedPointBisector', 'WeightedPointBisector', ([], {'sites': '(p, q)'}), '(sites=(p, q))\n', (682, 696), False, 'from voronoi_diagrams.models import WeightedSite, WeightedPointBisector, WeightedPointBoundary\n'), ((721, 772), 'voronoi_diagrams.models.WeightedPointBoundary', 'We... |
from europython import hello
hello("Alisa")
| [
"europython.hello"
] | [((29, 43), 'europython.hello', 'hello', (['"""Alisa"""'], {}), "('Alisa')\n", (34, 43), False, 'from europython import hello\n')] |
#!/usr/bin/env python3
import sys
import csv
import datetime
import math
from tabulate import tabulate
import scipy.stats as st
from tqdm import tqdm
import numpy as np
np.seterr(all='ignore')
def isfloat(val):
try:
val = float(val)
if math.isnan(val):
return False
return ... | [
"datetime.datetime",
"csv.DictReader",
"datetime.datetime.fromtimestamp",
"scipy.stats.kstest",
"math.sqrt",
"numpy.seterr",
"math.isnan"
] | [((175, 198), 'numpy.seterr', 'np.seterr', ([], {'all': '"""ignore"""'}), "(all='ignore')\n", (184, 198), True, 'import numpy as np\n'), ((263, 278), 'math.isnan', 'math.isnan', (['val'], {}), '(val)\n', (273, 278), False, 'import math\n'), ((7153, 7187), 'datetime.datetime.fromtimestamp', 'datetime.datetime.fromtimest... |
import os
import shutil
from modulefinder import ModuleFinder
def main():
temp_dir = "package_temp"
if os.path.exists(temp_dir):
shutil.rmtree(temp_dir)
os.makedirs(temp_dir)
for py in ["index.py", "notifier.py"]:
src, dst = py, os.path.join(temp_dir, py)
print("copy '%s' to '... | [
"os.path.exists",
"modulefinder.ModuleFinder",
"shutil.make_archive",
"os.makedirs",
"shutil.ignore_patterns",
"os.path.join",
"os.path.dirname",
"os.path.basename",
"shutil.copy",
"shutil.rmtree",
"os.remove"
] | [((113, 137), 'os.path.exists', 'os.path.exists', (['temp_dir'], {}), '(temp_dir)\n', (127, 137), False, 'import os\n'), ((175, 196), 'os.makedirs', 'os.makedirs', (['temp_dir'], {}), '(temp_dir)\n', (186, 196), False, 'import os\n'), ((418, 432), 'modulefinder.ModuleFinder', 'ModuleFinder', ([], {}), '()\n', (430, 432... |
import numpy as np
def flip_axis(x_in, axis):
x_out = np.zeros(x_in.shape, dtype=x_in.dtype)
for i, x in enumerate(x_in):
x = np.asarray(x).swapaxes(axis, 0)
x = x[::-1, ...]
x_out[i] = x.swapaxes(0, axis)
return x_out
def flip_axis_fra(x, flipping_axis):
pattern = [flipping_... | [
"numpy.random.random",
"numpy.zeros",
"numpy.array_equal",
"numpy.asarray"
] | [((60, 98), 'numpy.zeros', 'np.zeros', (['x_in.shape'], {'dtype': 'x_in.dtype'}), '(x_in.shape, dtype=x_in.dtype)\n', (68, 98), True, 'import numpy as np\n'), ((614, 645), 'numpy.random.random', 'np.random.random', (['(10, 2, 3, 4)'], {}), '((10, 2, 3, 4))\n', (630, 645), True, 'import numpy as np\n'), ((845, 867), 'nu... |
# -*- coding: utf-8 -*-
#
# 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
... | [
"apiclient.discovery.build"
] | [((1410, 1453), 'apiclient.discovery.build', 'build', (['"""pubsub"""', '"""v1"""'], {'http': 'http_authorized'}), "('pubsub', 'v1', http=http_authorized)\n", (1415, 1453), False, 'from apiclient.discovery import build\n')] |
""" Defines the Note repository """
import random
import string
import time
import bcrypt
from sqlalchemy.orm import load_only
from werkzeug.exceptions import Forbidden, UnprocessableEntity
from models import Note
class NoteRepository:
@staticmethod
def create(user, notebook_id, title, content):
""... | [
"models.Note",
"models.Note.query.filter_by",
"time.time",
"werkzeug.exceptions.UnprocessableEntity"
] | [((505, 635), 'models.Note', 'Note', ([], {'notebook_id': 'notebook_id', 'title': 'title', 'content': 'content', 'user_id': 'user.id', 'created_at': 'current_time', 'updated_at': 'current_time'}), '(notebook_id=notebook_id, title=title, content=content, user_id=user.id,\n created_at=current_time, updated_at=current_... |
'''tzinfo timezone information for Africa/Ndjamena.'''
from pytz.tzinfo import DstTzInfo
from pytz.tzinfo import memorized_datetime as d
from pytz.tzinfo import memorized_ttinfo as i
class Ndjamena(DstTzInfo):
'''Africa/Ndjamena timezone definition. See datetime.tzinfo for details'''
zone = 'Africa/Ndjamena'
... | [
"pytz.tzinfo.memorized_ttinfo",
"pytz.tzinfo.memorized_datetime"
] | [((351, 370), 'pytz.tzinfo.memorized_datetime', 'd', (['(1)', '(1)', '(1)', '(0)', '(0)', '(0)'], {}), '(1, 1, 1, 0, 0, 0)\n', (352, 370), True, 'from pytz.tzinfo import memorized_datetime as d\n'), ((367, 394), 'pytz.tzinfo.memorized_datetime', 'd', (['(1911)', '(12)', '(31)', '(22)', '(59)', '(48)'], {}), '(1911, 12,... |
import logging
import os
import shutil
import tempfile
from git import Repo
from .ast_analysis import _get_all_names, _get_all_func_names, _generate_trees
from .ntlk_analysis import _get_verbs_from_function_name, _get_nouns_from_function_name
from .utils import _get_count_most_common, _get_converted_names, _convert_t... | [
"logging.basicConfig",
"git.Repo.clone_from",
"os.path.join",
"tempfile.mkdtemp",
"shutil.rmtree",
"logging.info",
"os.walk"
] | [((332, 492), 'logging.basicConfig', 'logging.basicConfig', ([], {'filename': '"""code_analyzer.log"""', 'format': '"""%(asctime)s - %(levelname)s - %(message)s"""', 'datefmt': '"""%d-%b-%y %H:%M:%S"""', 'level': 'logging.INFO'}), "(filename='code_analyzer.log', format=\n '%(asctime)s - %(levelname)s - %(message)s',... |
from flask_app.config.mysqlconnection import connectToMySQL
from flask import flash
from base64 import b64encode
class Pet:
db = 'pawfosterfamily'
def __init__(self,data):
self.id = data['id']
self.img = data['img']
self.name = data['name']
self.age = data['age']
self.f... | [
"flask_app.config.mysqlconnection.connectToMySQL",
"flask.flash"
] | [((2917, 2949), 'flask.flash', 'flash', (['"""Name is required"""', '"""pet"""'], {}), "('Name is required', 'pet')\n", (2922, 2949), False, 'from flask import flash\n'), ((3037, 3083), 'flask.flash', 'flash', (['"""Foster time needed is required"""', '"""pet"""'], {}), "('Foster time needed is required', 'pet')\n", (3... |
import wallycore as wally
from . import exceptions
from gaservices.utils import h2b
wordlist_ = wally.bip39_get_wordlist('en')
wordlist = [wally.bip39_get_word(wordlist_, i) for i in range(2048)]
def seed_from_mnemonic(mnemonic_or_hex_seed):
"""Return seed, mnemonic given an input string
mnemonic_or_hex_se... | [
"wallycore.bip39_mnemonic_validate",
"wallycore.bip39_mnemonic_from_bytes",
"wallycore.bip32_key_from_seed",
"wallycore.sha256d",
"wallycore.bip39_get_wordlist",
"wallycore.bip39_mnemonic_to_seed512",
"wallycore.bip39_mnemonic_to_bytes",
"wallycore.bip39_get_word",
"gaservices.utils.h2b",
"wallyco... | [((98, 128), 'wallycore.bip39_get_wordlist', 'wally.bip39_get_wordlist', (['"""en"""'], {}), "('en')\n", (122, 128), True, 'import wallycore as wally\n'), ((141, 175), 'wallycore.bip39_get_word', 'wally.bip39_get_word', (['wordlist_', 'i'], {}), '(wordlist_, i)\n', (161, 175), True, 'import wallycore as wally\n'), ((11... |
def elastic_rate(
hv,
hs,
v,
s,
rho,
mu,
nx,
dx,
order,
t,
y,
r0,
r1,
tau0_1,
tau0_2,
tauN_1,
tauN_2,
type_0,
forcing,
):
# we compute rates that will be used for Runge-Kutta time-stepping
#
import first_derivative_sbp_operators
... | [
"boundarycondition.bcm",
"numpy.sqrt",
"first_derivative_sbp_operators.dx",
"boundarycondition.bcp",
"numpy.exp",
"numpy.zeros",
"numpy.cos",
"numpy.sin"
] | [((378, 395), 'numpy.zeros', 'np.zeros', (['(nx, 1)'], {}), '((nx, 1))\n', (386, 395), True, 'import numpy as np\n'), ((404, 421), 'numpy.zeros', 'np.zeros', (['(nx, 1)'], {}), '((nx, 1))\n', (412, 421), True, 'import numpy as np\n'), ((431, 448), 'numpy.zeros', 'np.zeros', (['(nx, 1)'], {}), '((nx, 1))\n', (439, 448),... |
import datetime
import json
import os
from unittest import mock
from django.conf import settings
from django.core.files.storage import default_storage as storage
from freezegun import freeze_time
from waffle.testutils import override_switch
from olympia.amo.tests import addon_factory, TestCase, user_factory
from oly... | [
"datetime.datetime",
"olympia.blocklist.cron.upload_mlbf_to_kinto",
"os.path.exists",
"os.path.getsize",
"olympia.zadmin.models.set_config",
"olympia.amo.tests.user_factory",
"os.path.join",
"waffle.testutils.override_switch",
"olympia.amo.tests.addon_factory",
"olympia.zadmin.models.get_config",
... | [((881, 915), 'freezegun.freeze_time', 'freeze_time', (['"""2020-01-01 12:34:56"""'], {}), "('2020-01-01 12:34:56')\n", (892, 915), False, 'from freezegun import freeze_time\n'), ((921, 974), 'waffle.testutils.override_switch', 'override_switch', (['"""blocklist_mlbf_submit"""'], {'active': '(True)'}), "('blocklist_mlb... |
import numpy as np
import pandas as pd
import pytest
from etna.datasets import TSDataset
from etna.datasets import generate_ar_df
from etna.datasets import generate_const_df
from etna.datasets import generate_periodic_df
from etna.metrics import R2
from etna.models import LinearPerSegmentModel
from etna.transforms imp... | [
"etna.transforms.encoders.categorical.LabelEncoderTransform",
"etna.datasets.TSDataset.to_dataset",
"etna.datasets.generate_periodic_df",
"numpy.random.default_rng",
"etna.metrics.R2",
"etna.datasets.TSDataset",
"etna.models.LinearPerSegmentModel",
"etna.transforms.FilterFeaturesTransform",
"etna.da... | [((8503, 8595), 'pytest.mark.parametrize', 'pytest.mark.parametrize', (['"""in_column, prefix"""', "[('2', ''), ('regressor_1', 'regressor_')]"], {}), "('in_column, prefix', [('2', ''), ('regressor_1',\n 'regressor_')])\n", (8526, 8595), False, 'import pytest\n'), ((9071, 9163), 'pytest.mark.parametrize', 'pytest.ma... |