code stringlengths 20 1.04M | apis list | extract_api stringlengths 75 9.94M |
|---|---|---|
# --- Receptor APP Developed By: <NAME> @ 2017 --- #
# KNOWN ISSUE: (occasonal crash due to the following)
# Traceback (most recent call last):
# File "opencv-qrcode.py", line 116, in <module>
# alpha_l * output[y1:y2, x1:x2, c])
# ValueError: operands could not be broadcast together with shapes (149,324) (149,0)
... | [
"cv2.resize",
"zbar.ImageScanner",
"cv2.cvtColor",
"zbar.Image",
"cv2.waitKey",
"cv2.imshow",
"cv2.VideoCapture",
"cv2.imread",
"cv2.CascadeClassifier",
"PIL.Image.fromarray",
"cv2.destroyAllWindows",
"cv2.namedWindow"
] | [((479, 510), 'cv2.CascadeClassifier', 'cv2.CascadeClassifier', (['cascPath'], {}), '(cascPath)\n', (500, 510), False, 'import cv2\n'), ((690, 729), 'cv2.namedWindow', 'cv2.namedWindow', (['"""#init17 Receptor App"""'], {}), "('#init17 Receptor App')\n", (705, 729), False, 'import cv2\n'), ((736, 755), 'cv2.VideoCaptur... |
#!/usr/bin/env python
"""
A Dumb full-screen editor.
This example program makes use of many context manager methods:
:meth:`~.Terminal.hidden_cursor`, :meth:`~.Terminal.raw`,
:meth:`~.Terminal.location`, :meth:`~.Terminal.fullscreen`, and
:meth:`~.Terminal.keypad`.
Early curses work focused namely around writing scre... | [
"functools.partial",
"blessed.Terminal",
"sys.stdout.flush",
"collections.namedtuple"
] | [((1817, 1869), 'collections.namedtuple', 'collections.namedtuple', (['"""Cursor"""', "('y', 'x', 'term')"], {}), "('Cursor', ('y', 'x', 'term'))\n", (1839, 1869), False, 'import collections\n'), ((808, 852), 'functools.partial', 'functools.partial', (['print'], {'end': '""""""', 'flush': '(True)'}), "(print, end='', f... |
import os,sys
import utils
import cv2
import numpy as np
from common_flags import FLAGS
import random
import math
import tensorflow_probability as tfp
tfd = tfp.distributions
from keras import backend as K
TEST_PHASE=0
def central_image_crop(img, crop_height,crop_width):
"""
Crops the input PILLOW image cente... | [
"numpy.exp",
"cv2.imshow",
"os.path.join",
"cv2.cvtColor",
"numpy.std",
"numpy.max",
"numpy.loadtxt",
"numpy.reshape",
"numpy.linspace",
"cv2.resize",
"cv2.circle",
"math.sqrt",
"cv2.waitKey",
"numpy.asarray",
"common_flags.FLAGS",
"cv2.resizeWindow",
"os.listdir",
"math.fabs",
"... | [((947, 982), 'numpy.max', 'np.max', (['x'], {'axis': 'axis', 'keepdims': '(True)'}), '(x, axis=axis, keepdims=True)\n', (953, 982), True, 'import numpy as np\n'), ((1378, 1393), 'common_flags.FLAGS', 'FLAGS', (['sys.argv'], {}), '(sys.argv)\n', (1383, 1393), False, 'from common_flags import FLAGS\n'), ((1814, 1846), '... |
import chess.engine
import random
from reconchess import *
import os
STOCKFISH_ENV_VAR = 'STOCKFISH_EXECUTABLE'
class TroutBot(Player):
"""
TroutBot uses the Stockfish chess engine to choose moves. In order to run TroutBot you'll need to download
Stockfish from https://stockfishchess.org/download/ and cr... | [
"os.path.exists",
"random.choice"
] | [((2551, 2579), 'random.choice', 'random.choice', (['sense_actions'], {}), '(sense_actions)\n', (2564, 2579), False, 'import random\n'), ((976, 1006), 'os.path.exists', 'os.path.exists', (['stockfish_path'], {}), '(stockfish_path)\n', (990, 1006), False, 'import os\n')] |
#!/usr/bin/python3
"""
See the README.md for instructions on how to run this file, and problem-03.md
for instructions on the problem this code solves :D
"""
from itertools import permutations
import sys
import argparse
parser = argparse.ArgumentParser(
description='Runs the problem 3 solver against some input fi... | [
"argparse.ArgumentParser",
"argparse.FileType"
] | [((231, 324), 'argparse.ArgumentParser', 'argparse.ArgumentParser', ([], {'description': '"""Runs the problem 3 solver against some input file"""'}), "(description=\n 'Runs the problem 3 solver against some input file')\n", (254, 324), False, 'import argparse\n'), ((395, 417), 'argparse.FileType', 'argparse.FileType... |
"""
This module contains the encodings related widgets (combox, menus,...)
"""
import locale
import logging
from pyqode.core.api import ENCODINGS_MAP, convert_to_codec_key
from pyqode.qt import QtCore, QtWidgets
from pyqode.core.cache import Cache
def _logger():
return logging.getLogger(__name__)
class Encoding... | [
"pyqode.qt.QtWidgets.QActionGroup",
"pyqode.core.dialogs.DlgPreferredEncodingsEditor.edit_encoding",
"pyqode.core.api.convert_to_codec_key",
"pyqode.qt.QtWidgets.QAction",
"pyqode.core.cache.Cache",
"pyqode.qt.QtCore.QTimer",
"pyqode.qt.QtCore.Signal",
"locale.getpreferredencoding",
"logging.getLogg... | [((276, 303), 'logging.getLogger', 'logging.getLogger', (['__name__'], {}), '(__name__)\n', (293, 303), False, 'import logging\n'), ((3078, 3096), 'pyqode.qt.QtCore.Signal', 'QtCore.Signal', (['str'], {}), '(str)\n', (3091, 3096), False, 'from pyqode.qt import QtCore, QtWidgets\n'), ((983, 1010), 'pyqode.core.api.conve... |
#!/usr/bin/env python
# -*- coding: utf-8 -*-
#
# Generated from FHIR 1.0.2.7202 on 2016-06-23.
# 2016, SMART Health IT.
import io
import json
import os
import unittest
from . import relatedperson
from .fhirdate import FHIRDate
class RelatedPersonTests(unittest.TestCase):
def instantiate_from(self, filename)... | [
"os.environ.get",
"json.load",
"os.path.join"
] | [((340, 379), 'os.environ.get', 'os.environ.get', (['"""FHIR_UNITTEST_DATADIR"""'], {}), "('FHIR_UNITTEST_DATADIR')\n", (354, 379), False, 'import os\n'), ((491, 508), 'json.load', 'json.load', (['handle'], {}), '(handle)\n', (500, 508), False, 'import json\n'), ((407, 438), 'os.path.join', 'os.path.join', (['datadir',... |
from __future__ import print_function
import logging
import os
import pkg_resources
import subprocess
import sys
import traceback
from distutils.version import StrictVersion
from pkg_resources import DistributionNotFound
from vext import logger
ignore_reload_errors = "VEXT_RELOAD_HACK" in os.environ
MIN_SETUPTOOLS... | [
"textwrap.dedent",
"distutils.version.StrictVersion",
"traceback.print_tb",
"pkg_resources.require",
"subprocess.check_output",
"os.path.dirname",
"setuptools.command.install_lib.install_lib.run",
"vext.logger.isEnabledFor",
"vext.logger.debug",
"importlib.reload",
"subprocess.call",
"os.path.... | [((1053, 1077), 'distutils.version.StrictVersion', 'StrictVersion', (['r.version'], {}), '(r.version)\n', (1066, 1077), False, 'from distutils.version import StrictVersion\n'), ((1081, 1110), 'distutils.version.StrictVersion', 'StrictVersion', (['MIN_SETUPTOOLS'], {}), '(MIN_SETUPTOOLS)\n', (1094, 1110), False, 'from d... |
import numpy as np
import gym
from gym import spaces
from gym.utils import seeding
class VarianceWorld(gym.Env):
def __init__(self):
self.pos = None
# 0 is left by N(0.05, 0.01), 1 is right by N(0.05, 0.01)
self.actions = lambda a: np.random.normal(np.power(-1, 1 - a) * 5) / 100
se... | [
"numpy.random.uniform",
"numpy.power",
"gym.spaces.Discrete",
"gym.spaces.Box",
"numpy.random.choice"
] | [((370, 417), 'gym.spaces.Box', 'spaces.Box', ([], {'low': 'np.inf', 'high': 'np.inf', 'shape': '(1,)'}), '(low=np.inf, high=np.inf, shape=(1,))\n', (380, 417), False, 'from gym import spaces\n'), ((446, 464), 'gym.spaces.Discrete', 'spaces.Discrete', (['(2)'], {}), '(2)\n', (461, 464), False, 'from gym import spaces\n... |
from os import urandom
from tempfile import NamedTemporaryFile
from PIL import Image
IMG_SUFFIX = {
'jpeg': '.jpg',
'png': '.png',
}
def image(width, height):
return Image.frombytes('RGB', (width, height), urandom(width * height * 3))
def temp_imagefile(width, height, format):
i = image(width, height)
f = N... | [
"tempfile.NamedTemporaryFile",
"os.urandom"
] | [((319, 364), 'tempfile.NamedTemporaryFile', 'NamedTemporaryFile', ([], {'suffix': 'IMG_SUFFIX[format]'}), '(suffix=IMG_SUFFIX[format])\n', (337, 364), False, 'from tempfile import NamedTemporaryFile\n'), ((214, 241), 'os.urandom', 'urandom', (['(width * height * 3)'], {}), '(width * height * 3)\n', (221, 241), False, ... |
# Copyright 2018 The Chromium Authors. All rights reserved.
# Use of this source code is governed by a BSD-style license that can be
# found in the LICENSE file.
import base64
import datetime
import hashlib
import re
from google.protobuf import json_format as jsonpb
from recipe_engine import recipe_api
from PB.recip... | [
"base64.urlsafe_b64encode",
"recipe_engine.recipe_api.defer_results",
"PB.recipe_engine.recipes_cfg.RepoSpec",
"datetime.datetime.strptime",
"datetime.timedelta",
"re.search"
] | [((2233, 2260), 'datetime.timedelta', 'datetime.timedelta', ([], {'hours': '(2)'}), '(hours=2)\n', (2251, 2260), False, 'import datetime\n'), ((2366, 2403), 'base64.urlsafe_b64encode', 'base64.urlsafe_b64encode', (['project_url'], {}), '(project_url)\n', (2390, 2403), False, 'import base64\n'), ((914, 983), 'datetime.d... |
import django_filters
from django.db.models import Q
from utilities.filters import BaseFilterSet
from ipam.models import Prefix
from netbox_aws.models import VPC
from netbox_aws.choices import VPCRegionChoices
class VPCFilterSet(BaseFilterSet):
q = django_filters.CharFilter(
method='search',
lab... | [
"ipam.models.Prefix.objects.all",
"django_filters.MultipleChoiceFilter",
"django_filters.CharFilter",
"django.db.models.Q"
] | [((257, 315), 'django_filters.CharFilter', 'django_filters.CharFilter', ([], {'method': '"""search"""', 'label': '"""Search"""'}), "(method='search', label='Search')\n", (282, 315), False, 'import django_filters\n'), ((352, 430), 'django_filters.MultipleChoiceFilter', 'django_filters.MultipleChoiceFilter', ([], {'choic... |
"""
A example of a constant-current beam for verifying the field output
"""
from __future__ import division
import numpy as np
import shutil
from shutil import os
from sys import exit
from warp_init_tools import * # Not really used but brings in ParticleDiagnostic.
from warp.data_dumping.openpmd_diag import field... | [
"shutil.os.remove",
"shutil.os.listdir",
"rswarp.utilities.beam_distributions.createKV",
"shutil.os.path.isdir",
"numpy.reshape",
"numpy.random.normal",
"numpy.column_stack",
"shutil.rmtree",
"rswarp.diagnostics.FieldDiagnostic.ElectrostaticFields",
"shutil.os.path.exists",
"rswarp.diagnostics.F... | [((1390, 1422), 'numpy.sqrt', 'np.sqrt', (['(1 - 1 / beam_gamma ** 2)'], {}), '(1 - 1 / beam_gamma ** 2)\n', (1397, 1422), True, 'import numpy as np\n'), ((677, 708), 'shutil.os.path.exists', 'os.path.exists', (['outputDirectory'], {}), '(outputDirectory)\n', (691, 708), False, 'from shutil import os\n'), ((3294, 3381)... |
import argparse, traceback
from errors_exceptions import OpenTAMPException
from pma import pr_graph
"""
Entry-level script. Calls pr_graph.p_mod_abs() to plan, then runs the plans in
simulation using the chosen viewer.
"""
cache = {}
def parse_file_to_dict(f_name):
d = {}
if f_name in cache:
return c... | [
"pma.pr_graph.p_mod_abs",
"traceback.print_exc",
"argparse.ArgumentParser"
] | [((1246, 1298), 'argparse.ArgumentParser', 'argparse.ArgumentParser', ([], {'description': '"""Run OpenTAMP."""'}), "(description='Run OpenTAMP.')\n", (1269, 1298), False, 'import argparse, traceback\n'), ((874, 939), 'pma.pr_graph.p_mod_abs', 'pr_graph.p_mod_abs', (['domain_config', 'problem_config', 'solvers_config']... |
# -*- coding: utf-8 -*-
#
# Copyright (C) 2021 Northwestern University.
# Copyright (C) 2022 University of Münster.
#
# invenio-subjects-ddc-german is free software; you can redistribute it and/or
# modify it under the terms of the MIT License; see LICENSE file for more
# details.
"""Command line tool."""
import clic... | [
"click.command"
] | [((458, 473), 'click.command', 'click.command', ([], {}), '()\n', (471, 473), False, 'import click\n')] |
import tempfile
import pytest
import trio
@pytest.fixture
def touch_path():
with tempfile.TemporaryDirectory() as base_dir:
yield trio.Path(base_dir) / "touch.txt"
| [
"trio.Path",
"tempfile.TemporaryDirectory"
] | [((88, 117), 'tempfile.TemporaryDirectory', 'tempfile.TemporaryDirectory', ([], {}), '()\n', (115, 117), False, 'import tempfile\n'), ((145, 164), 'trio.Path', 'trio.Path', (['base_dir'], {}), '(base_dir)\n', (154, 164), False, 'import trio\n')] |
# Copyright 2021 Ringgaard Research ApS
#
# 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... | [
"sling.flags.define"
] | [((666, 761), 'sling.flags.define', 'flags.define', (['"""--newssites"""'], {'default': '"""data/crawl/newssites.txt"""', 'help': '"""list of news sites"""'}), "('--newssites', default='data/crawl/newssites.txt', help=\n 'list of news sites')\n", (678, 761), True, 'import sling.flags as flags\n')] |
import math
import dash_html_components as html
import dash_bootstrap_components as dbc
from navbar import Navbar
from footer import Footer
from risk_calculator.utils import predict_risk, langs
from risk_calculator.visuals import get_labs_indicator, get_model_desc, get_feature_importance, get_inputed_vals
from risk_... | [
"risk_calculator.visuals.get_page_desc",
"risk_calculator.visuals.get_lang",
"footer.Footer",
"risk_calculator.visuals.get_feature_importance",
"risk_calculator.visuals.get_submit_button",
"dash_html_components.Div",
"risk_calculator.visuals.get_personal_visual",
"risk_calculator.utils.predict_risk",
... | [((518, 526), 'navbar.Navbar', 'Navbar', ([], {}), '()\n', (524, 526), False, 'from navbar import Navbar\n'), ((540, 548), 'footer.Footer', 'Footer', ([], {}), '()\n', (546, 548), False, 'from footer import Footer\n'), ((1365, 1412), 'dash_html_components.Div', 'html.Div', (['[nav, body, footer]'], {'className': '"""si... |
"""GLOBIO InVEST Model."""
import os
import logging
import collections
import tempfile
import pandas
from osgeo import gdal
from osgeo import ogr
from osgeo import osr
import numpy
import pygeoprocessing
import taskgraph
from . import utils
from . import validation
LOGGER = logging.getLogger(__name__)
# this value... | [
"taskgraph.TaskGraph",
"os.remove",
"numpy.sum",
"pandas.read_csv",
"numpy.empty",
"os.walk",
"logging.getLogger",
"osgeo.ogr.FieldDefn",
"collections.defaultdict",
"os.path.isfile",
"numpy.isclose",
"os.close",
"numpy.exp",
"osgeo.gdal.GetDriverByName",
"os.path.join",
"numpy.round",
... | [((279, 306), 'logging.getLogger', 'logging.getLogger', (['__name__'], {}), '(__name__)\n', (296, 306), False, 'import logging\n'), ((8795, 8830), 'os.path.join', 'os.path.join', (["args['workspace_dir']"], {}), "(args['workspace_dir'])\n", (8807, 8830), False, 'import os\n'), ((8915, 8974), 'os.path.join', 'os.path.jo... |
import json
import hydra
from deepspeech_pytorch.checkpoint import GCSCheckpointHandler, FileCheckpointHandler
from deepspeech_pytorch.configs.train_config import DeepSpeechConfig, GCSCheckpointConfig
from deepspeech_pytorch.loader.data_module import DeepSpeechDataModule
from deepspeech_pytorch.model import DeepSpeech... | [
"json.load",
"pytorch_lightning.seed_everything",
"hydra.utils.to_absolute_path",
"deepspeech_pytorch.checkpoint.FileCheckpointHandler",
"deepspeech_pytorch.loader.data_module.DeepSpeechDataModule",
"hydra.utils.instantiate",
"omegaconf.OmegaConf.get_type",
"deepspeech_pytorch.model.DeepSpeech",
"de... | [((480, 505), 'pytorch_lightning.seed_everything', 'seed_everything', (['cfg.seed'], {}), '(cfg.seed)\n', (495, 505), False, 'from pytorch_lightning import seed_everything\n'), ((1262, 1373), 'deepspeech_pytorch.loader.data_module.DeepSpeechDataModule', 'DeepSpeechDataModule', ([], {'labels': 'labels', 'data_cfg': 'cfg... |
# -*- coding: utf-8 -*-
# Generated by Django 1.11.5 on 2017-09-27 21:16
from __future__ import unicode_literals
import django.contrib.postgres.fields
import django.db.models.deletion
import touchtechnology.common.db.models
from django.db import migrations, models
class Migration(migrations.Migration):
dependen... | [
"django.db.models.URLField"
] | [((567, 584), 'django.db.models.URLField', 'models.URLField', ([], {}), '()\n', (582, 584), False, 'from django.db import migrations, models\n')] |
#!/usr/bin/env python
# -*- coding: utf-8 -*-
import os
import numpy as np
import xarray as xr
AUX_DATADIR = str(os.environ['AUX_DATADIR'])
DATADIR = str(os.environ['DATADIR'])
FN = 'runoff_1981_2020_regrid.nc'
# Open runoff file, get mean annual runoff [m3 s-1]
x = xr.open_dataset(os.path.join(AUX_DATADIR, FN))
#... | [
"os.path.join"
] | [((288, 317), 'os.path.join', 'os.path.join', (['AUX_DATADIR', 'FN'], {}), '(AUX_DATADIR, FN)\n', (300, 317), False, 'import os\n'), ((384, 424), 'os.path.join', 'os.path.join', (['AUX_DATADIR', '"""gridarea.nc"""'], {}), "(AUX_DATADIR, 'gridarea.nc')\n", (396, 424), False, 'import os\n'), ((576, 632), 'os.path.join', ... |
import osmnx as ox
from src.tilemani.retrieve.retriever import get_road_graph_and_bbox
from src.tilemani.rasterize.rasterizer import plot_figure_ground
def test_get_road_graph_and_bbox(tileXYZ):
G_r, bbox = get_road_graph_and_bbox(tileXYZ)
print("Manual bbox: ", bbox)
f1, ax1 = ox.plot_graph(G_r)
f1.sh... | [
"src.tilemani.retrieve.retriever.get_road_graph_and_bbox",
"osmnx.plot_figure_ground",
"osmnx.plot_graph",
"src.tilemani.rasterize.rasterizer.plot_figure_ground"
] | [((212, 244), 'src.tilemani.retrieve.retriever.get_road_graph_and_bbox', 'get_road_graph_and_bbox', (['tileXYZ'], {}), '(tileXYZ)\n', (235, 244), False, 'from src.tilemani.retrieve.retriever import get_road_graph_and_bbox\n'), ((292, 310), 'osmnx.plot_graph', 'ox.plot_graph', (['G_r'], {}), '(G_r)\n', (305, 310), True,... |
# Copyright 2014 OpenStack Foundation
# 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 requ... | [
"nuage_tempest_plugin.services.nuage_client.NuageRestClient",
"tempest.test.decorators.attr",
"nuage_tempest_plugin.lib.topology.Topology.get_conf",
"tempest.lib.common.utils.data_utils.rand_name",
"tempest.common.utils.is_extension_enabled",
"nuage_tempest_plugin.lib.topology.Topology.within_ext_id_relea... | [((1154, 1173), 'nuage_tempest_plugin.lib.topology.Topology.get_conf', 'Topology.get_conf', ([], {}), '()\n', (1171, 1173), False, 'from nuage_tempest_plugin.lib.topology import Topology\n'), ((7735, 7764), 'tempest.test.decorators.attr', 'decorators.attr', ([], {'type': '"""smoke"""'}), "(type='smoke')\n", (7750, 7764... |
import uuid
from django.db import models, transaction
from django.utils.translation import gettext_lazy as _
from .member import Member
class Invite(models.Model):
# id: int,
# sender: Member,
# receiver: User,
# invite_date: datetime
id = models.UUIDField(primary_key=True, default=uuid.uuid4, ed... | [
"django.db.transaction.atomic",
"django.utils.translation.gettext_lazy"
] | [((1368, 1380), 'django.utils.translation.gettext_lazy', '_', (['"""convite"""'], {}), "('convite')\n", (1369, 1380), True, 'from django.utils.translation import gettext_lazy as _\n'), ((1411, 1424), 'django.utils.translation.gettext_lazy', '_', (['"""convites"""'], {}), "('convites')\n", (1412, 1424), True, 'from djan... |
# coding: utf-8
from tornado import web,ioloop
import tornado.options
import tornado.httpserver
import routers
import os
import ui_module
import motor
import datetime
from tornado.options import define, options
define("port", default=80, help="run on the given port", type=int)
client = motor.MotorClient("mongodb://w... | [
"motor.MotorClient",
"tornado.options.define",
"os.path.dirname",
"datetime.datetime"
] | [((213, 279), 'tornado.options.define', 'define', (['"""port"""'], {'default': '(80)', 'help': '"""run on the given port"""', 'type': 'int'}), "('port', default=80, help='run on the given port', type=int)\n", (219, 279), False, 'from tornado.options import define, options\n'), ((290, 336), 'motor.MotorClient', 'motor.M... |
"""Performs zap spider scan of host web interface"""
# Generic imports to utilize
from time import sleep
from json import loads
from datetime import datetime
from subprocess import Popen, DEVNULL
from zapv2 import ZAPv2
from core.host import Host
from core.result import Results
from core.scan import Scan
from core.uti... | [
"core.utils.zap_setup_context",
"log.low",
"core.result.Results",
"core.utils.start_zap",
"zapv2.ZAPv2",
"time.sleep",
"datetime.datetime.now"
] | [((1350, 1361), 'core.utils.start_zap', 'start_zap', ([], {}), '()\n', (1359, 1361), False, 'from core.utils import xml2json, start_zap, wait_for_zap, zap_setup_context\n'), ((1376, 1383), 'zapv2.ZAPv2', 'ZAPv2', ([], {}), '()\n', (1381, 1383), False, 'from zapv2 import ZAPv2\n'), ((1811, 1819), 'time.sleep', 'sleep', ... |
from app.application import application
from app.application import api_url
import requests_mock
import pytest
from tests.helpers import get_mock
@pytest.fixture(autouse=True)
def get():
def _get(url):
client = application.test_client()
response = client.get(url)
return response.data.deco... | [
"requests_mock.mock",
"app.application.application.test_client",
"pytest.fixture",
"tests.helpers.get_mock"
] | [((150, 178), 'pytest.fixture', 'pytest.fixture', ([], {'autouse': '(True)'}), '(autouse=True)\n', (164, 178), False, 'import pytest\n'), ((226, 251), 'app.application.application.test_client', 'application.test_client', ([], {}), '()\n', (249, 251), False, 'from app.application import application\n'), ((382, 402), 're... |
# coding: utf8
"""Test IO Module"""
from pathlib import Path
import pytest
from urduhack.utils.io import remove_file, download_from_url, pickle_load, pickle_dump
from urduhack.config import MODELS_URL
SENTIMENT_WEIGHTS_URL = MODELS_URL["SENTIMENT_V1_WEIGHTS"]
SENTIMENT_FILE_NAME = SENTIMENT_WEIGHTS_URL.split("/")[-1]... | [
"urduhack.utils.io.pickle_load",
"urduhack.utils.io.remove_file",
"urduhack.utils.io.download_from_url",
"pytest.raises",
"pathlib.Path",
"urduhack.utils.io.pickle_dump"
] | [((537, 564), 'urduhack.utils.io.pickle_dump', 'pickle_dump', (['tmp_file', 'data'], {}), '(tmp_file, data)\n', (548, 564), False, 'from urduhack.utils.io import remove_file, download_from_url, pickle_load, pickle_dump\n'), ((578, 599), 'urduhack.utils.io.pickle_load', 'pickle_load', (['tmp_file'], {}), '(tmp_file)\n',... |
# NURBS curve minimal working example
def run():
# Import packages
import numpy as np
import matplotlib.pyplot as plt
from .nurbs_curve import NurbsCurve
# Define the array of control points
P = np.zeros((2,5))
P[:, 0] = [0.20, 0.50]
P[:, 1] = [0.40, 0.70]
P[:, 2] = [0.80, 0.60]
... | [
"numpy.zeros",
"matplotlib.pyplot.show"
] | [((221, 237), 'numpy.zeros', 'np.zeros', (['(2, 5)'], {}), '((2, 5))\n', (229, 237), True, 'import numpy as np\n'), ((486, 496), 'matplotlib.pyplot.show', 'plt.show', ([], {}), '()\n', (494, 496), True, 'import matplotlib.pyplot as plt\n')] |
from dotenv import load_dotenv
from sqlalchemy import create_engine
import os
def connect_to_db():
"""
This method creates the engine that allows a connection to the
database using the credentials stored in the .env file located
in the Database_Connection_Files folder.
Returns
----------
... | [
"dotenv.load_dotenv",
"sqlalchemy.create_engine",
"os.getenv"
] | [((907, 933), 'dotenv.load_dotenv', 'load_dotenv', ([], {'override': '(True)'}), '(override=True)\n', (918, 933), False, 'from dotenv import load_dotenv\n'), ((990, 1010), 'os.getenv', 'os.getenv', (['"""DB_HOST"""'], {}), "('DB_HOST')\n", (999, 1010), False, 'import os\n'), ((1038, 1062), 'os.getenv', 'os.getenv', (['... |
#! /usr/bin/env python3
# -*- coding: utf-8 -*-
from scrapenhl2.scrape.schedules import (
_get_current_season,
schedule_setup,
get_season_schedule_filename,
get_season_schedule,
get_team_schedule,
write_season_schedule,
get_game_data_from_schedule,
_CURRENT_SEASON,
_SCHEDULES,
)
fro... | [
"scrapenhl2.scrape.schedules.get_game_data_from_schedule",
"scrapenhl2.scrape.schedules.get_season_schedule_filename",
"unittest.mock.MagicMock",
"scrapenhl2.scrape.schedules.schedule_setup",
"pytest_mock.mocker.patch",
"unittest.mock.call",
"scrapenhl2.scrape.schedules.write_season_schedule",
"scrape... | [((444, 469), 'pytest_mock.mocker.patch', 'mocker.patch', (['"""arrow.now"""'], {}), "('arrow.now')\n", (456, 469), False, 'from pytest_mock import mocker\n'), ((806, 862), 'pytest_mock.mocker.patch', 'mocker.patch', (['"""scrapenhl2.scrape.schedules.organization"""'], {}), "('scrapenhl2.scrape.schedules.organization')... |
from django.shortcuts import render
from management.models import Unit
from django.http import HttpResponseRedirect
# class UnitForm(ModelForm):
# class Meta:
# model = Unit
# fields = ['name']
def management(request):
unit = Unit.objects.all()
return render(request, 'management/mana... | [
"django.shortcuts.render",
"management.models.Unit.objects.all"
] | [((248, 266), 'management.models.Unit.objects.all', 'Unit.objects.all', ([], {}), '()\n', (264, 266), False, 'from management.models import Unit\n'), ((288, 350), 'django.shortcuts.render', 'render', (['request', '"""management/management.html"""', "{'units': unit}"], {}), "(request, 'management/management.html', {'uni... |
from core.himesis import Himesis, HimesisPreConditionPatternLHS
import uuid
class HUnitR05_CompleteLHS(HimesisPreConditionPatternLHS):
def __init__(self):
"""
Creates the himesis graph representing the AToM3 model HUnitR05_CompleteLHS
"""
# Flag this instance as compiled now
self.is_compiled = True
super... | [
"uuid.uuid3"
] | [((631, 685), 'uuid.uuid3', 'uuid.uuid3', (['uuid.NAMESPACE_DNS', '"""HUnitR05_CompleteLHS"""'], {}), "(uuid.NAMESPACE_DNS, 'HUnitR05_CompleteLHS')\n", (641, 685), False, 'import uuid\n'), ((965, 1015), 'uuid.uuid3', 'uuid.uuid3', (['uuid.NAMESPACE_DNS', '"""5.0.m.0Partition"""'], {}), "(uuid.NAMESPACE_DNS, '5.0.m.0Par... |
# Copyright 2020 Tensorforce 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 applicable la... | [
"tensorforce.TensorforceError.unexpected",
"tensorforce.TensorforceError.value",
"numpy.minimum",
"numpy.maximum",
"numpy.asarray",
"tensorforce.core.utils.tf_util.dtype",
"tensorflow.TensorShape",
"tensorforce.util.product",
"tensorforce.util.is_iterable",
"numpy.isnan",
"numpy.isinf",
"tenso... | [((3176, 3203), 'tensorforce.util.product', 'util.product', ([], {'xs': 'self.shape'}), '(xs=self.shape)\n', (3188, 3203), False, 'from tensorforce import TensorforceError, util\n'), ((3439, 3469), 'tensorforce.util.np_dtype', 'util.np_dtype', ([], {'dtype': 'self.type'}), '(dtype=self.type)\n', (3452, 3469), False, 'f... |
"""
PCDS plugins and Overrides for AreaDetector Plugins.
"""
import logging
import ophyd
import numpy as np
from ophyd import EpicsSignal, Component as C
from ophyd.device import GenerateDatumInterface
from ophyd.utils import set_and_wait
from ophyd.areadetector.base import ADBase
logger = logging.getLogger(__name__... | [
"ophyd.utils.set_and_wait",
"ophyd.areadetector.base.ADBase.describe_configuration",
"ophyd.areadetector.base.ADBase.read_configuration",
"ophyd.Component",
"numpy.array",
"ophyd.areadetector.base.ADBase.stage",
"logging.getLogger"
] | [((294, 321), 'logging.getLogger', 'logging.getLogger', (['__name__'], {}), '(__name__)\n', (311, 321), False, 'import logging\n'), ((496, 584), 'ophyd.Component', 'C', (['EpicsSignal', '"""EnableCallbacks_RBV.RVAL"""'], {'write_pv': '"""EnableCallbacks"""', 'string': '(False)'}), "(EpicsSignal, 'EnableCallbacks_RBV.RV... |
# -*- coding: utf-8 -*-
"""
Classes to read all datasets from their corresponding source files.
@author: daniel, <NAME>
"""
import pandas as pd
from datetime import datetime
from dateutil import relativedelta
# ---------------------------------------- #
# ----- General data reading classes ----- #
# ---------------... | [
"pandas.read_csv",
"dateutil.relativedelta.relativedelta",
"datetime.datetime",
"datetime.datetime.strptime",
"pandas.read_stata"
] | [((11498, 11532), 'datetime.datetime', 'datetime', (['date.year', 'date.month', '(1)'], {}), '(date.year, date.month, 1)\n', (11506, 11532), False, 'from datetime import datetime\n'), ((11350, 11379), 'datetime.datetime.strptime', 'datetime.strptime', (['x', '"""%b-%y"""'], {}), "(x, '%b-%y')\n", (11367, 11379), False,... |
from __future__ import print_function
import os
import requests # http://docs.python-requests.org
if __name__ == '__main__':
import sys
CURRENT_DIR = os.path.dirname(os.path.dirname(__file__))
sys.path.append(os.path.join(CURRENT_DIR, '../'))
os.environ.setdefault("DJANGO_SETTINGS_MODULE", "geocon... | [
"gc_apps.geo_utils.message_helper_json.MessageHelperJSON.get_json_msg_from_dict",
"os.environ.setdefault",
"os.path.dirname",
"shared_dataverse_information.shared_form_util.format_form_errors.format_errors_as_text",
"shared_dataverse_information.shapefile_import.forms.ShapefileImportDataForm",
"requests.p... | [((747, 810), 'logging.getLogger', 'logging.getLogger', (['"""gc_apps.worldmap_connect.worldmap_importer"""'], {}), "('gc_apps.worldmap_connect.worldmap_importer')\n", (764, 810), False, 'import logging\n'), ((265, 335), 'os.environ.setdefault', 'os.environ.setdefault', (['"""DJANGO_SETTINGS_MODULE"""', '"""geoconnect.... |
# -*- coding: utf-8 -*-
from flexmock import flexmock, flexmock_teardown
from orator.connections import Connection
from orator.schema.grammars import SQLiteSchemaGrammar
from orator.schema.blueprint import Blueprint
from ... import OratorTestCase
class SqliteSchemaGrammarTestCase(OratorTestCase):
def tearDown(s... | [
"flexmock.flexmock_teardown",
"orator.connections.Connection",
"orator.schema.blueprint.Blueprint"
] | [((334, 353), 'flexmock.flexmock_teardown', 'flexmock_teardown', ([], {}), '()\n', (351, 353), False, 'from flexmock import flexmock, flexmock_teardown\n'), ((408, 426), 'orator.schema.blueprint.Blueprint', 'Blueprint', (['"""users"""'], {}), "('users')\n", (417, 426), False, 'from orator.schema.blueprint import Bluepr... |
#!/usr/bin/env python3
# -*- coding: utf-8 -*-
"""
Created on Mon Nov 8 22:26:09 2021
@author: michele
"""
import requests
import lxml
import shutil
import urllib.request
import urllib.error as uer
import time
import nltk
import datetime
import csv
import os
import math
from tqdm import tqdm
from bs4 import Beautiful... | [
"pandas.DataFrame",
"nltk.stem.PorterStemmer",
"math.sqrt",
"csv.writer",
"time.sleep",
"os.path.isfile",
"pathlib.Path",
"nltk.corpus.stopwords.words",
"requests.get",
"bs4.BeautifulSoup"
] | [((1199, 1216), 'requests.get', 'requests.get', (['url'], {}), '(url)\n', (1211, 1216), False, 'import requests\n'), ((1228, 1272), 'bs4.BeautifulSoup', 'BeautifulSoup', (['page.content'], {'features': '"""lxml"""'}), "(page.content, features='lxml')\n", (1241, 1272), False, 'from bs4 import BeautifulSoup\n'), ((4781, ... |
import torch
import time
def prep_images(images):
"""
preprocess images
Args:
images: pytorch tensor
"""
images = images.div(255.0)
images = torch.sub(images,0.5)
images = torch.mul(images,2.0)
return images
def calc_pairwise_distance(X, Y):
"""
computes pairw... | [
"torch.sqrt",
"torch.FloatTensor",
"torch.mul",
"torch.sub",
"torch.cos",
"torch.sin"
] | [((179, 201), 'torch.sub', 'torch.sub', (['images', '(0.5)'], {}), '(images, 0.5)\n', (188, 201), False, 'import torch\n'), ((214, 236), 'torch.mul', 'torch.mul', (['images', '(2.0)'], {}), '(images, 2.0)\n', (223, 236), False, 'import torch\n'), ((606, 622), 'torch.sqrt', 'torch.sqrt', (['dist'], {}), '(dist)\n', (616... |
from ..baseops import *
from ..exprs import *
from ..db import Database
from ..schema import *
from ..tuples import *
from ..util import cache, OBTuple
from ..udfs import *
from itertools import chain
from ..columns import ListColumns
from pyarrow import compute, Table
import pandas as pd
############################... | [
"pandas.DataFrame",
"itertools.chain"
] | [((2087, 2141), 'itertools.chain', 'chain', (['*[e.referenced_attrs for e in self.group_exprs]'], {}), '(*[e.referenced_attrs for e in self.group_exprs])\n', (2092, 2141), False, 'from itertools import chain\n'), ((2462, 2518), 'itertools.chain', 'chain', (['*[e.referenced_attrs for e in self.project_exprs]'], {}), '(*... |
import torch
import numba
import matplotlib.pyplot as plt
import seaborn as sns
mu_arms = torch.tensor([0.1, 0.2, 0.3, 0.4, 0.5])
n_arms = len(mu_arms)
def method_fully_random_selection(n_epochs=1000, disp_flag=False):
n_arms = len(mu_arms)
Q = torch.zeros(n_arms)
N = torch.zeros(n_arms)
reward_list =... | [
"torch.mean",
"torch.randint",
"matplotlib.pyplot.show",
"matplotlib.pyplot.plot",
"torch.argmax",
"matplotlib.pyplot.legend",
"torch.cumsum",
"torch.bernoulli",
"torch.zeros",
"matplotlib.pyplot.ylabel",
"matplotlib.pyplot.xlabel",
"torch.sum",
"torch.tensor"
] | [((91, 130), 'torch.tensor', 'torch.tensor', (['[0.1, 0.2, 0.3, 0.4, 0.5]'], {}), '([0.1, 0.2, 0.3, 0.4, 0.5])\n', (103, 130), False, 'import torch\n'), ((255, 274), 'torch.zeros', 'torch.zeros', (['n_arms'], {}), '(n_arms)\n', (266, 274), False, 'import torch\n'), ((283, 302), 'torch.zeros', 'torch.zeros', (['n_arms']... |
#!/usr/bin/env python
"""Downloading chess puzzles for lichess.org"""
# import sys to handle command line arguments
import sys
import logging
import requests
# tournaments
tournament_ids = sys.argv[1:]
with open('games.pgn','w') as file:
for id_number in tournament_ids: # using id_number instead of id as a n... | [
"logging.debug",
"requests.get"
] | [((803, 851), 'logging.debug', 'logging.debug', (['"""Finished... Pgn is in games.pgn"""'], {}), "('Finished... Pgn is in games.pgn')\n", (816, 851), False, 'import logging\n'), ((528, 545), 'requests.get', 'requests.get', (['url'], {}), '(url)\n', (540, 545), False, 'import requests\n')] |
# -*- coding: utf-8 -*-
from __future__ import absolute_import
from __future__ import division
from __future__ import print_function
import csv
import numpy as np
import os
import sys
from observations.util import maybe_download_and_extract
def crime4(path):
"""crime4
Data loads lazily. Type data(crime4) into ... | [
"observations.util.maybe_download_and_extract",
"os.path.expanduser",
"os.path.join"
] | [((2730, 2754), 'os.path.expanduser', 'os.path.expanduser', (['path'], {}), '(path)\n', (2748, 2754), False, 'import os\n'), ((2903, 2988), 'observations.util.maybe_download_and_extract', 'maybe_download_and_extract', (['path', 'url'], {'save_file_name': '"""crime4.csv"""', 'resume': '(False)'}), "(path, url, save_file... |
import matplotlib.pyplot as plt
from flow import FlowProject, aggregator
class Project(FlowProject):
pass
def get_pressure(crystal_name, density):
"""Pretend function returning a fake pressure value."""
if crystal_name == "fcc":
pressure = 1000 * density ** 2
else:
pressure = 5000 * ... | [
"matplotlib.pyplot.title",
"matplotlib.pyplot.plot",
"flow.aggregator",
"flow.aggregator.groupby",
"matplotlib.pyplot.close",
"matplotlib.pyplot.legend",
"matplotlib.pyplot.subplots",
"matplotlib.pyplot.savefig"
] | [((356, 404), 'flow.aggregator.groupby', 'aggregator.groupby', (['"""crystal"""'], {'sort_by': '"""density"""'}), "('crystal', sort_by='density')\n", (374, 404), False, 'from flow import FlowProject, aggregator\n'), ((1221, 1250), 'flow.aggregator', 'aggregator', ([], {'sort_by': '"""density"""'}), "(sort_by='density')... |
import torch
import torch.nn.functional as F
from torch import nn
from .base_models import BaseEncoderMaskerDecoder
from asteroid_filterbanks import make_enc_dec
from asteroid_filterbanks.transforms import mag, magreim, apply_mag_mask
from ..masknn import norms, activations
from einops import rearrange
from tqdm import... | [
"torch.nn.Dropout",
"tqdm.tqdm",
"asteroid_filterbanks.make_enc_dec",
"torch.nn.Sequential",
"torch.sqrt",
"asteroid_filterbanks.transforms.mag",
"asteroid_filterbanks.transforms.apply_mag_mask",
"torch.nn.functional.unfold",
"torch.nn.Sigmoid",
"einops.rearrange",
"torch.nn.Linear",
"torch.ze... | [((899, 1010), 'asteroid_filterbanks.make_enc_dec', 'make_enc_dec', (['"""stft"""'], {'n_filters': 'n_filters', 'kernel_size': 'kernel_size', 'stride': 'stride', 'sample_rate': 'sample_rate'}), "('stft', n_filters=n_filters, kernel_size=kernel_size, stride=\n stride, sample_rate=sample_rate)\n", (911, 1010), False, ... |
import requests
import json
def getlyrics(artist,song):
url="https://api.lyrics.ovh/v1/"+artist+'/'+song
response = requests.get(url)
print(response.text)
json_data = json.loads(response.text)
data=dict(json_data)
return data["lyrics"] | [
"json.loads",
"requests.get"
] | [((119, 136), 'requests.get', 'requests.get', (['url'], {}), '(url)\n', (131, 136), False, 'import requests\n'), ((172, 197), 'json.loads', 'json.loads', (['response.text'], {}), '(response.text)\n', (182, 197), False, 'import json\n')] |
"""ERM Baseline Model."""
from typing import Dict, List, Literal, Tuple
import ethicml as em
import pandas as pd
import pytorch_lightning as pl
import torch
import torchmetrics
from kit import implements
from torch import Tensor, nn, optim
from torch.optim.lr_scheduler import _LRScheduler
from fair_bolts.datasets.eth... | [
"ethicml.RenyiCorrelation",
"ethicml.TPR",
"torch.nn.BCEWithLogitsLoss",
"torch.nn.Sequential",
"torch.cat",
"kit.implements",
"torchmetrics.Accuracy",
"ethicml.Accuracy",
"ethicml.ProbPos",
"torch.rand_like",
"torch.optim.lr_scheduler.ExponentialLR",
"ethicml.Yanovich"
] | [((3577, 3607), 'kit.implements', 'implements', (['pl.LightningModule'], {}), '(pl.LightningModule)\n', (3587, 3607), False, 'from kit import implements\n'), ((3932, 3962), 'kit.implements', 'implements', (['pl.LightningModule'], {}), '(pl.LightningModule)\n', (3942, 3962), False, 'from kit import implements\n'), ((417... |
# coding: utf-8
"""
Qc API
Qc API # noqa: E501
The version of the OpenAPI document: 3.0.0
Contact: <EMAIL>
Generated by: https://openapi-generator.tech
"""
import pprint
import re # noqa: F401
import six
from telestream_cloud_qc.configuration import Configuration
class CaptionsTest(object... | [
"six.iteritems",
"telestream_cloud_qc.configuration.Configuration"
] | [((16476, 16509), 'six.iteritems', 'six.iteritems', (['self.openapi_types'], {}), '(self.openapi_types)\n', (16489, 16509), False, 'import six\n'), ((3117, 3132), 'telestream_cloud_qc.configuration.Configuration', 'Configuration', ([], {}), '()\n', (3130, 3132), False, 'from telestream_cloud_qc.configuration import Con... |
"""Let S be a finite set with N elements; i.e. |S|=N. There are N^N
endofunctions defined on this set.
For a given endofunction f, its image will have n=|f(S)| elements for 1 <= n <=
N. Similarly its second iterate will have |f(f(S))|=m<=n elements. Once
|f^(k)(S)|=|f^(k+1)(S)| then |f^(j)(S)|=|f^(k)(S)| for all j>k. ... | [
"numpy.meshgrid",
"funcstructs.combinat.nCk",
"numpy.zeros",
"funcstructs.combinat.compositions",
"numpy.arange",
"math.factorial",
"numpy.array",
"funcstructs.combinat.binary_compositions"
] | [((1539, 1573), 'numpy.zeros', 'np.zeros', (['(n, n - 1)'], {'dtype': 'object'}), '((n, n - 1), dtype=object)\n', (1547, 1573), True, 'import numpy as np\n'), ((2263, 2297), 'numpy.zeros', 'np.zeros', (['(n, n - 1)'], {'dtype': 'object'}), '((n, n - 1), dtype=object)\n', (2271, 2297), True, 'import numpy as np\n'), ((2... |
import csv
from db.db_context import DbContext
from config.config import DB_FILE_PATH, CSV_DATASET_FILE_PATH, CSV_MOVIE_COLUMNS
from repository.movie_repository import MovieRepository
from repository.genre_repository import GenreRepository
from repository.movie_genre_repository import MovieGenreRepository
context = Db... | [
"repository.movie_repository.MovieRepository",
"csv.DictReader",
"repository.movie_genre_repository.MovieGenreRepository",
"repository.genre_repository.GenreRepository",
"db.db_context.DbContext"
] | [((318, 341), 'db.db_context.DbContext', 'DbContext', (['DB_FILE_PATH'], {}), '(DB_FILE_PATH)\n', (327, 341), False, 'from db.db_context import DbContext\n'), ((390, 414), 'repository.movie_repository.MovieRepository', 'MovieRepository', (['context'], {}), '(context)\n', (405, 414), False, 'from repository.movie_reposi... |
import numpy as np
import pytest
import torch
from probflow.modules import DenseNetwork
from probflow.parameters import Parameter
from probflow.utils.settings import Sampling
def is_close(a, b, tol=1e-3):
return np.abs(a - b) < tol
def test_DenseNetwork():
"""Tests probflow.modules.DenseNetwork"""
# S... | [
"probflow.modules.DenseNetwork",
"probflow.utils.settings.Sampling",
"numpy.abs",
"torch.randn",
"pytest.raises"
] | [((521, 547), 'probflow.modules.DenseNetwork', 'DenseNetwork', (['[5, 4, 3, 2]'], {}), '([5, 4, 3, 2])\n', (533, 547), False, 'from probflow.modules import DenseNetwork\n'), ((589, 608), 'torch.randn', 'torch.randn', (['[7, 5]'], {}), '([7, 5])\n', (600, 608), False, 'import torch\n'), ((2687, 2734), 'probflow.modules.... |
## www.pubnub.com - PubNub Real-time push service in the cloud.
# coding=utf8
## PubNub Real-time Push APIs and Notifications Framework
## Copyright (c) 2010 <NAME>
## http://www.pubnub.com/
## -----------------------------------
## PubNub 3.1 Real-time Push Cloud API
## -----------------------------------
import sy... | [
"time.time",
"datetime.datetime.now",
"datetime.timedelta",
"pubnub.PubnubTwisted"
] | [((1848, 1963), 'pubnub.PubnubTwisted', 'Pubnub', (['publish_key', 'subscribe_key'], {'secret_key': 'secret_key', 'cipher_key': 'cipher_key', 'ssl_on': 'ssl_on', 'origin': 'origin'}), '(publish_key, subscribe_key, secret_key=secret_key, cipher_key=\n cipher_key, ssl_on=ssl_on, origin=origin)\n', (1854, 1963), True, ... |
# coding:utf-8
import logging
# 日志格式
format_dict = {
1: logging.Formatter('%(asctime)s - %(name)s - \
%(levelname)s - %(message)s'),
2: logging.Formatter('%(asctime)s - %(name)s - \
%(levelname)s - %(message)s'),
3: logging.Formatter('%(asctime)s - %(name)s - \
%(levelname)s - %(message)s'),
4: l... | [
"logging.Formatter",
"logging.StreamHandler",
"logging.FileHandler",
"logging.getLogger"
] | [((61, 137), 'logging.Formatter', 'logging.Formatter', (['"""%(asctime)s - %(name)s - %(levelname)s - %(message)s"""'], {}), "('%(asctime)s - %(name)s - %(levelname)s - %(message)s')\n", (78, 137), False, 'import logging\n'), ((147, 223), 'logging.Formatter', 'logging.Formatter', (['"""%(asctime)s - %(name)s - ... |
import boto3
import yaml
from functools import partial
from cement import Controller, ex
from ..core.environments.stack_deployer import StackDeployer
from ..core.environments.stack_collection import StackCollection
from ..core.utils import environment_names, template_names
class Environments(Controller):
class ... | [
"functools.partial",
"boto3.session.Session",
"yaml.dump"
] | [((3933, 3981), 'boto3.session.Session', 'boto3.session.Session', ([], {'profile_name': 'profile_name'}), '(profile_name=profile_name)\n', (3954, 3981), False, 'import boto3\n'), ((4168, 4205), 'functools.partial', 'partial', (['StackCollection.has_env', 'env'], {}), '(StackCollection.has_env, env)\n', (4175, 4205), Fa... |
import pytest
from pygelf import GelfTcpHandler, GelfUdpHandler, GelfHttpHandler, GelfTlsHandler, GelfHttpsHandler
from tests.helper import logger, get_unique_message, log_warning
@pytest.fixture(params=[
GelfTcpHandler(host='127.0.0.1', port=12201, debug=True),
GelfUdpHandler(host='127.0.0.1', port=12202, de... | [
"tests.helper.get_unique_message",
"pygelf.GelfUdpHandler",
"pygelf.GelfTlsHandler",
"pygelf.GelfTcpHandler",
"pygelf.GelfHttpHandler",
"tests.helper.log_warning",
"pygelf.GelfHttpsHandler"
] | [((932, 952), 'tests.helper.get_unique_message', 'get_unique_message', ([], {}), '()\n', (950, 952), False, 'from tests.helper import logger, get_unique_message, log_warning\n'), ((976, 1004), 'tests.helper.log_warning', 'log_warning', (['logger', 'message'], {}), '(logger, message)\n', (987, 1004), False, 'from tests.... |
import requests
import json
import hmac
import hashlib
AprErrorMappingDict = {
0 : 'No error',
1 : 'Invalid JSON payload',
2 : 'Missing X-BTK-APIKEY',
3 : 'Invalid API key',
4 : 'API pending for activation',
5 : 'IP not allowed',
6 : 'Missing / invalid signature',
7 : 'Missing timestamp... | [
"json.encode",
"json.dumps"
] | [((1575, 1630), 'json.dumps', 'json.dumps', (['data'], {'separators': "(',', ':')", 'sort_keys': '(True)'}), "(data, separators=(',', ':'), sort_keys=True)\n", (1585, 1630), False, 'import json\n'), ((1724, 1737), 'json.encode', 'json.encode', ([], {}), '()\n', (1735, 1737), False, 'import json\n')] |
"""
User Profiles module.
This file is subject to the terms and conditions defined in file 'LICENSE',
which is part of this source code package.
"""
# pylint: disable=line-too-long
from flask import Blueprint
from lib.auth import auth_basic, permission_super_admin, \
check_password_expiration
from modules.app_ke... | [
"lib.auth.check_password_expiration",
"lib.auth.permission_super_admin.require",
"flask.Blueprint"
] | [((862, 904), 'flask.Blueprint', 'Blueprint', (['"""admin_user_profiles"""', '__name__'], {}), "('admin_user_profiles', __name__)\n", (871, 904), False, 'from flask import Blueprint\n'), ((1491, 1541), 'lib.auth.permission_super_admin.require', 'permission_super_admin.require', ([], {'http_exception': '(403)'}), '(http... |
# SPDX-License-Identifier: Apache-2.0
#
# The OpenSearch Contributors require contributions made to
# this file be licensed under the Apache-2.0 license or a
# compatible open source license.
import argparse
import logging
class AssembleArgs:
manifest: str
keep: bool
def __init__(self):
parser =... | [
"argparse.ArgumentParser",
"argparse.FileType"
] | [((321, 395), 'argparse.ArgumentParser', 'argparse.ArgumentParser', ([], {'description': '"""Assemble an OpenSearch Distribution"""'}), "(description='Assemble an OpenSearch Distribution')\n", (344, 395), False, 'import argparse\n'), ((441, 463), 'argparse.FileType', 'argparse.FileType', (['"""r"""'], {}), "('r')\n", (... |
#!/usr/bin/env python
#-*- coding: utf-8 *-*
import progressbar
class ProgressFile(file):
def __init__(self, *args, **kw):
file.__init__(self, *args, **kw)
if 'widgets' in kw:
widgets = kw['widgets']
else:
widgets = [
'Upload: ',
pr... | [
"progressbar.ETA",
"progressbar.Percentage",
"progressbar.RotatingMarker",
"progressbar.FileTransferSpeed",
"progressbar.ProgressBar"
] | [((626, 683), 'progressbar.ProgressBar', 'progressbar.ProgressBar', ([], {'widgets': 'widgets', 'maxval': 'self.len'}), '(widgets=widgets, maxval=self.len)\n', (649, 683), False, 'import progressbar\n'), ((318, 342), 'progressbar.Percentage', 'progressbar.Percentage', ([], {}), '()\n', (340, 342), False, 'import progre... |
from django.db import models
from django.utils.timezone import now
class RecipientStatusQuerySet(models.QuerySet):
def get_status(self, code, label=None):
status, created = self.get_or_create(code=code)
if created:
status.label = label or code
status.save()
return s... | [
"django.utils.timezone.now"
] | [((631, 636), 'django.utils.timezone.now', 'now', ([], {}), '()\n', (634, 636), False, 'from django.utils.timezone import now\n'), ((963, 968), 'django.utils.timezone.now', 'now', ([], {}), '()\n', (966, 968), False, 'from django.utils.timezone import now\n')] |
from flask import Blueprint, request, flash, redirect, url_for, render_template
from watchmelog.forms import GameForm
bp = Blueprint("game", __name__)
@bp.route("/log", methods=["GET", "POST"])
def log_game():
form = GameForm()
if request.method == "POST" and form.validate():
flash("Game logged!")
... | [
"flask.flash",
"flask.Blueprint",
"watchmelog.forms.GameForm",
"flask.url_for",
"flask.render_template"
] | [((125, 152), 'flask.Blueprint', 'Blueprint', (['"""game"""', '__name__'], {}), "('game', __name__)\n", (134, 152), False, 'from flask import Blueprint, request, flash, redirect, url_for, render_template\n'), ((225, 235), 'watchmelog.forms.GameForm', 'GameForm', ([], {}), '()\n', (233, 235), False, 'from watchmelog.for... |
'''
Test returned values from post/patch/put/delete.
Get is in separate tests/test_get.py
'''
from example import family
from .helpers.blargh_config import modify_expected_data
import pytest
params = [
('post', 201, ('child', {'name': 'c4'}), {'id': 4, 'url': 'child/4', 'name': 'c4'}),
('post', 201, ('child',... | [
"pytest.mark.parametrize"
] | [((1416, 1495), 'pytest.mark.parametrize', 'pytest.mark.parametrize', (['"""method, expected_status, args, expected_data"""', 'params'], {}), "('method, expected_status, args, expected_data', params)\n", (1439, 1495), False, 'import pytest\n')] |
# Copyright 2022 Pants project contributors (see CONTRIBUTORS.md).
# Licensed under the Apache License, Version 2.0 (see LICENSE).
from __future__ import annotations
import logging
from typing import Iterable
from pants.backend.helm.resolve import artifacts
from pants.backend.helm.resolve.artifacts import ThirdParty... | [
"pants.engine.unions.UnionRule",
"pants.engine.rules.collect_rules",
"pants.engine.target.DependenciesRequest",
"pants.engine.internals.selectors.Get",
"pants.backend.helm.resolve.artifacts.rules",
"pants.util.strutil.bullet_list",
"pants.engine.target.InferredDependencies",
"pants.util.ordered_set.Or... | [((1215, 1242), 'logging.getLogger', 'logging.getLogger', (['__name__'], {}), '(__name__)\n', (1232, 1242), False, 'import logging\n'), ((2999, 3067), 'pants.engine.rules.rule', 'rule', ([], {'desc': '"""Inferring Helm chart dependencies"""', 'level': 'LogLevel.DEBUG'}), "(desc='Inferring Helm chart dependencies', leve... |
"""convert_umn_wages_to_csv.py
Usage:
convert_umn_wages_to_csv.py <input_file> <output_file>
"""
from docopt import docopt
from openpyxl import load_workbook
import pandas as pd
def _convert_ws_to_df(ws):
data = ws.values
cols = next(data)
return pd.DataFrame(data, columns=cols)
def _split_name_col... | [
"pandas.DataFrame",
"openpyxl.load_workbook",
"docopt.docopt"
] | [((266, 298), 'pandas.DataFrame', 'pd.DataFrame', (['data'], {'columns': 'cols'}), '(data, columns=cols)\n', (278, 298), True, 'import pandas as pd\n'), ((343, 357), 'pandas.DataFrame', 'pd.DataFrame', ([], {}), '()\n', (355, 357), True, 'import pandas as pd\n'), ((659, 693), 'openpyxl.load_workbook', 'load_workbook', ... |
import re
import numpy as np
from collections import defaultdict
from scipy.sparse import spdiags, csr_matrix
from sklearn.preprocessing import normalize
from sklearn.base import BaseEstimator, TransformerMixin
from sklearn.feature_extraction.text import ENGLISH_STOP_WORDS
__all__ = [
'CountVectorizer',
'Tfid... | [
"numpy.log",
"numpy.asarray",
"scipy.sparse.spdiags",
"collections.defaultdict",
"scipy.sparse.csr_matrix",
"sklearn.preprocessing.normalize",
"numpy.bincount",
"re.compile"
] | [((5800, 5834), 'numpy.asarray', 'np.asarray', (['indices'], {'dtype': 'np.intc'}), '(indices, dtype=np.intc)\n', (5810, 5834), True, 'import numpy as np\n'), ((5854, 5887), 'numpy.asarray', 'np.asarray', (['values'], {'dtype': 'np.intc'}), '(values, dtype=np.intc)\n', (5864, 5887), True, 'import numpy as np\n'), ((590... |
"""
Tags are entities that are attached to objects in the same way as
Attributes. But contrary to Attributes, which are unique to an
individual object, a single Tag can be attached to any number of
objects at the same time.
Tags are used for tagging, obviously, but the data structure is also
used for storing Aliases a... | [
"django.db.models.CharField",
"django.db.models.TextField",
"evennia.utils.utils.make_iter",
"evennia.utils.utils.to_str"
] | [((1873, 1971), 'django.db.models.CharField', 'models.CharField', (['"""key"""'], {'max_length': '(255)', 'null': '(True)', 'help_text': '"""tag identifier"""', 'db_index': '(True)'}), "('key', max_length=255, null=True, help_text=\n 'tag identifier', db_index=True)\n", (1889, 1971), False, 'from django.db import mo... |
"""Functions to test the difference of DEMs tools."""
import warnings
import geoutils as gu
import numpy as np
with warnings.catch_warnings():
warnings.simplefilter("ignore")
import xdem
class TestdDEM:
dem_2009 = xdem.DEM(xdem.examples.get_path("longyearbyen_ref_dem"))
dem_1990 = xdem.DEM(xdem.exam... | [
"numpy.zeros_like",
"numpy.count_nonzero",
"warnings.simplefilter",
"numpy.datetime64",
"numpy.isnan",
"numpy.mean",
"warnings.catch_warnings",
"numpy.random.choice",
"xdem.examples.get_path",
"numpy.all",
"numpy.nanmean"
] | [((118, 143), 'warnings.catch_warnings', 'warnings.catch_warnings', ([], {}), '()\n', (141, 143), False, 'import warnings\n'), ((149, 180), 'warnings.simplefilter', 'warnings.simplefilter', (['"""ignore"""'], {}), "('ignore')\n", (170, 180), False, 'import warnings\n'), ((239, 285), 'xdem.examples.get_path', 'xdem.exam... |
"""
Script to convert CoNLL format data into the (b,t,d,s) format specified in
the paper https://www.aclweb.org/anthology/P17-1002/ .
The third column of the CoNLL data has elements of form " [BIO_tag]-[C|P]:[n]:[relation_type] ", where
n is the first token position of the claim/premise the current claim/premise rela... | [
"argparse.ArgumentParser"
] | [((3076, 3101), 'argparse.ArgumentParser', 'argparse.ArgumentParser', ([], {}), '()\n', (3099, 3101), False, 'import argparse\n')] |
from bokeh.models import HoverTool
from bokeh.io import curdoc
from bokeh.layouts import column,row
import pandas as pd
from statement_parser import parse_ofx_statements
import holoviews as hv
from bokeh.models.formatters import DatetimeTickFormatter
pd.options.plotting.backend = 'holoviews'
merged_df = parse_ofx_stat... | [
"pandas.DataFrame",
"pandas.read_csv",
"pandas.DatetimeIndex",
"bokeh.io.curdoc",
"bokeh.models.formatters.DatetimeTickFormatter",
"bokeh.models.HoverTool",
"statement_parser.parse_ofx_statements",
"pandas.to_datetime",
"holoviews.render",
"pandas.Grouper",
"bokeh.layouts.column",
"pandas.conc... | [((306, 328), 'statement_parser.parse_ofx_statements', 'parse_ofx_statements', ([], {}), '()\n', (326, 328), False, 'from statement_parser import parse_ofx_statements\n'), ((546, 631), 'bokeh.models.HoverTool', 'HoverTool', ([], {'tooltips': "[('amount', '$@amount{0,0.00}'), ('date', '@date_formatted')]"}), "(tooltips=... |
#!/usr/bin/env python
# Copyright 2019 <NAME>
# License: Apache 2.0 (http://www.apache.org/licenses/LICENSE-2.0)
"""
Feature transform for ASR
Notations:
N: batch size
C: number of channels
T: number of frames
F: number of FFT bins
S: number of samples in utts
"""
import math
import torch as th
im... | [
"torch.eye",
"torch.var",
"torch.sqrt",
"kaldi_python_io.functional.read_kaldi_mat",
"aps.transform.utils.speed_perturb_filter",
"torch.cat",
"aps.transform.augment.perturb_speed",
"torch.arange",
"torch.isnan",
"torch.load",
"aps.transform.utils.mel_filter",
"aps.transform.augment.tf_mask",
... | [((21810, 21848), 'aps.libs.ApsRegisters.transform.register', 'ApsRegisters.transform.register', (['"""asr"""'], {}), "('asr')\n", (21841, 21848), False, 'from aps.libs import ApsRegisters\n'), ((936, 953), 'torch.isnan', 'th.isnan', (['feature'], {}), '(feature)\n', (944, 953), True, 'import torch as th\n'), ((1908, 1... |
import importlib
from dj_tables import *
def drop_all():
"""
Removes all manual tables
"""
ExpParams().drop_quick()
# ExpParams().drop_quick()
# ComputedParams().drop_quick()
# CaimanResults().drop_quick()
# ManualReview().drop_quick()
def pop_exxpp():
par = ExppParams()
par.... | [
"importlib.reload"
] | [((1728, 1755), 'importlib.reload', 'importlib.reload', (['dj_tables'], {}), '(dj_tables)\n', (1744, 1755), False, 'import importlib\n')] |
'''
Description:
Get data of COVID-19 in realtime with Python.
Author: AlejandroV
Version: 1.0
Video: https://youtu.be/tYJHAYA7wVI
'''
from bs4 import BeautifulSoup
import requests as req
import pandas as pd
import matplotlib.pyplot as plt
import json
num = 0 # counter
analize = "infected" # what ... | [
"pandas.DataFrame",
"json.load",
"matplotlib.pyplot.show",
"requests.get",
"bs4.BeautifulSoup",
"matplotlib.pyplot.subplots",
"matplotlib.pyplot.savefig"
] | [((1699, 1713), 'matplotlib.pyplot.subplots', 'plt.subplots', ([], {}), '()\n', (1711, 1713), True, 'import matplotlib.pyplot as plt\n'), ((1719, 1832), 'pandas.DataFrame', 'pd.DataFrame', (["{'A': country[0][analize], 'B': country[1][analize], 'C': country[2][analize]}"], {'index': '[analize]'}), "({'A': country[0][an... |
# -*- coding=utf-8 -*-
from __future__ import absolute_import, print_function, unicode_literals
import unittest
import warnings
import chemfiles
from chemfiles import Trajectory, ChemfilesError
class RemoveChemfilesWarnings(object):
def __enter__(self):
chemfiles.set_warnings_callback(lambda u: None)
... | [
"unittest.main",
"chemfiles.misc._set_default_warning_callback",
"warnings.simplefilter",
"chemfiles.set_warnings_callback",
"chemfiles.misc._last_error",
"chemfiles.clib._get_c_library",
"chemfiles.misc._clear_errors",
"chemfiles.guess_format",
"warnings.catch_warnings",
"chemfiles.Trajectory",
... | [((3232, 3247), 'unittest.main', 'unittest.main', ([], {}), '()\n', (3245, 3247), False, 'import unittest\n'), ((269, 316), 'chemfiles.set_warnings_callback', 'chemfiles.set_warnings_callback', (['(lambda u: None)'], {}), '(lambda u: None)\n', (300, 316), False, 'import chemfiles\n'), ((357, 403), 'chemfiles.misc._set_... |
'''
Hover glyphs
Now let's practice using and customizing the hover tool.
In this exercise, you're going to plot the blood glucose levels for an unknown patient. The blood glucose levels were recorded every 5 minutes on October 7th starting at 3 minutes past midnight.
The date and time of each measurement are provid... | [
"bokeh.models.HoverTool"
] | [((1495, 1533), 'bokeh.models.HoverTool', 'HoverTool', ([], {'tooltips': 'None', 'mode': '"""vline"""'}), "(tooltips=None, mode='vline')\n", (1504, 1533), False, 'from bokeh.models import HoverTool\n')] |
# coding=utf-8
# Copyright 2019 Google LLC.
#
# Licensed under the Apache License, Version 2.0 (the "License");
# you may not use this file except in compliance with the License.
# You may obtain a copy of the License at
#
# http://www.apache.org/licenses/LICENSE-2.0
#
# Unless required by applicable law or agreed ... | [
"functools.partial",
"tensorflow.compat.v1.cast",
"task_adaptation.registry.Registry.lookup",
"tensorflow.compat.v1.image.resize"
] | [((2133, 2169), 'tensorflow.compat.v1.image.resize', 'tf.image.resize', (['image', '[size, size]'], {}), '(image, [size, size])\n', (2148, 2169), True, 'import tensorflow.compat.v1 as tf\n'), ((1734, 1773), 'task_adaptation.registry.Registry.lookup', 'Registry.lookup', (["data_params['dataset']"], {}), "(data_params['d... |
import discord.ext.commands as commands
class Skip(commands.Cog):
def __init__(self, client) -> None:
super().__init__()
self.client = client
self.audio = client.Audio
@commands.command(aliases=['s'])
async def skip(self, ctx):
if not ctx.author.voice:
... | [
"discord.ext.commands.command"
] | [((216, 247), 'discord.ext.commands.command', 'commands.command', ([], {'aliases': "['s']"}), "(aliases=['s'])\n", (232, 247), True, 'import discord.ext.commands as commands\n')] |
import json
import os
import unittest
from odml.tools import dict_parser
from odml.tools.parser_utils import ParserException, InvalidVersionException
class TestJSONParser(unittest.TestCase):
def setUp(self):
dir_path = os.path.dirname(os.path.realpath(__file__))
self.basepath = os.path.join(dir_... | [
"os.path.realpath",
"odml.tools.dict_parser.DictReader",
"os.path.join",
"json.load"
] | [((303, 338), 'os.path.join', 'os.path.join', (['dir_path', '"""resources"""'], {}), "(dir_path, 'resources')\n", (315, 338), False, 'import os\n'), ((367, 391), 'odml.tools.dict_parser.DictReader', 'dict_parser.DictReader', ([], {}), '()\n', (389, 391), False, 'from odml.tools import dict_parser\n'), ((251, 277), 'os.... |
"""
Author: JV
Date: 2021-04-26
Function for the assertion message between initiator and validator.
Currently only supports integer, single and double array parameters.
"""
from copy import copy
"""
Pack the message for sending it over the waku network
Input: contract_address - Which contract should be used
... | [
"copy.copy"
] | [((1006, 1019), 'copy.copy', 'copy', (['message'], {}), '(message)\n', (1010, 1019), False, 'from copy import copy\n')] |
'''
This laboratory checks the functionality of the free.dm utils type checker module
@author: <NAME>
'''
# Imports
import unittest
import logging
import sys
# Test imports
import __init__
# free.dm Imports
from freedm.utils.types import TypeChecker as checker
# Setup logger
logger = logging.getLogger()
logger.set... | [
"logging.StreamHandler",
"logging.getLogger",
"freedm.utils.types.TypeChecker.isAlpha"
] | [((290, 309), 'logging.getLogger', 'logging.getLogger', ([], {}), '()\n', (307, 309), False, 'import logging\n'), ((392, 425), 'logging.StreamHandler', 'logging.StreamHandler', (['sys.stdout'], {}), '(sys.stdout)\n', (413, 425), False, 'import logging\n'), ((1311, 1332), 'freedm.utils.types.TypeChecker.isAlpha', 'check... |
from Procedure import pre_process, feedback, gather_info
from Handling import controls
from Strategy import strategy
from Util import U
from rlbot.utils.structures.quick_chats import QuickChats
def Process(s, game, version=3):
pre_process(s, game)
gather_info(s)
strategy(s)
controls(s)
feedback(s... | [
"Handling.controls",
"Procedure.feedback",
"Procedure.gather_info",
"Procedure.pre_process",
"Strategy.strategy"
] | [((234, 254), 'Procedure.pre_process', 'pre_process', (['s', 'game'], {}), '(s, game)\n', (245, 254), False, 'from Procedure import pre_process, feedback, gather_info\n'), ((259, 273), 'Procedure.gather_info', 'gather_info', (['s'], {}), '(s)\n', (270, 273), False, 'from Procedure import pre_process, feedback, gather_i... |
from math import floor
money_needed = float(input())
fantasy_count = int(input())
horror_count = int(input())
romantic_count = int(input())
fantasy_price = 14.90
horror_price = 9.80
romantic_price = 4.30
sell_sum = (fantasy_count * fantasy_price) + (horror_count * horror_price) + (romantic_count * romantic_price)
dds... | [
"math.floor"
] | [((476, 519), 'math.floor', 'floor', (['((sum_after_dds - money_needed) * 0.1)'], {}), '((sum_after_dds - money_needed) * 0.1)\n', (481, 519), False, 'from math import floor\n')] |
from model import Attribute
from config import extra_attributes as default_extra_attributes
from config import helptext as default_helptext
extra_attributes = {
'engineering': [
Attribute('expected_effect', 'Expected effect', True,
['logins', 'registrations', 'conversion', 'plays', 'uploa... | [
"config.helptext.items",
"model.Attribute"
] | [((560, 754), 'model.Attribute', 'Attribute', (['"""expected_effect"""', '"""Expected effect"""', '(True)', "['registrations', 'conversion', 'conversion mix', 'retention',\n 'winback/returning', 'offsite engage', 'site traffic', 'none']", '(True)'], {}), "('expected_effect', 'Expected effect', True, ['registrations'... |
import pickle
import pandas as pd
import numpy as np
import tensorflow_datasets as tfds
import tensorflow as tf
from tensorflow.keras.preprocessing.sequence import pad_sequences
from tensorflow.keras.callbacks import ModelCheckpoint
from tensorflow.keras.utils import Sequence
from sklearn.metrics import roc_curve, auc
... | [
"matplotlib.pyplot.title",
"tensorflow_datasets.features.text.TokenTextEncoder",
"tensorflow.keras.layers.Dense",
"tensorflow.keras.callbacks.ModelCheckpoint",
"matplotlib.pyplot.figure",
"pickle.load",
"tensorflow.keras.optimizers.Adam",
"tensorflow.keras.layers.Embedding",
"tensorflow.keras.layers... | [((1154, 1205), 'tensorflow_datasets.features.text.TokenTextEncoder', 'tfds.features.text.TokenTextEncoder', (['vocabulary_set'], {}), '(vocabulary_set)\n', (1189, 1205), True, 'import tensorflow_datasets as tfds\n'), ((2607, 2743), 'tensorflow.keras.callbacks.ModelCheckpoint', 'ModelCheckpoint', (['"""data/models/mode... |
from __future__ import absolute_import
from django.conf.urls import url
from balanssi import views
urlpatterns = [
url(r'^$', views.index, name='index'),
url(r'^transactions.csv$', views.TransactionsView.as_view()),
url(r'^vis$', views.vis),
]
| [
"django.conf.urls.url",
"balanssi.views.TransactionsView.as_view"
] | [((127, 163), 'django.conf.urls.url', 'url', (['"""^$"""', 'views.index'], {'name': '"""index"""'}), "('^$', views.index, name='index')\n", (130, 163), False, 'from django.conf.urls import url\n'), ((238, 261), 'django.conf.urls.url', 'url', (['"""^vis$"""', 'views.vis'], {}), "('^vis$', views.vis)\n", (241, 261), Fals... |
# Copyright Contributors to the Pyro project.
# SPDX-License-Identifier: Apache-2.0
"""
Example: Predator-Prey Model
============================
This example replicates the great case study [1], which leverages the Lotka-Volterra
equation [2] to describe the dynamics of Canada lynx (predator) and snowshoe hare
(prey... | [
"matplotlib.pyplot.title",
"numpyro.set_platform",
"numpyro.examples.datasets.load_dataset",
"argparse.ArgumentParser",
"matplotlib.pyplot.figure",
"jax.random.PRNGKey",
"matplotlib.pyplot.gca",
"matplotlib.pyplot.fill_between",
"numpyro.set_host_device_count",
"matplotlib.pyplot.legend",
"matpl... | [((1225, 1246), 'matplotlib.use', 'matplotlib.use', (['"""Agg"""'], {}), "('Agg')\n", (1239, 1246), False, 'import matplotlib\n'), ((1679, 1704), 'jax.numpy.stack', 'jnp.stack', (['[du_dt, dv_dt]'], {}), '([du_dt, dv_dt])\n', (1688, 1704), True, 'import jax.numpy as jnp\n'), ((2352, 2421), 'jax.experimental.ode.odeint'... |
# Copyright (c) 2019 PaddlePaddle Authors. All Rights Reserved.
#
# Licensed under the Apache License, Version 2.0 (the "License");
# you may not use this file except in compliance with the License.
# You may obtain a copy of the License at
#
# http://www.apache.org/licenses/LICENSE-2.0
#
# Unless required by appli... | [
"paddle.fluid.is_compiled_with_cuda",
"six.moves.range",
"paddle.enable_static",
"logging.getLogger",
"paddle.fluid.is_compiled_with_xpu",
"sys.exit"
] | [((851, 878), 'logging.getLogger', 'logging.getLogger', (['__name__'], {}), '(__name__)\n', (868, 878), False, 'import logging\n'), ((2797, 2820), 'six.moves.range', 'six.moves.range', (['length'], {}), '(length)\n', (2812, 2820), False, 'import six\n'), ((5053, 5075), 'paddle.enable_static', 'paddle.enable_static', ([... |
from django.shortcuts import render
from .models import *
from django.http import HttpResponseNotFound
from config import __version__
def index(request):
if request.method == 'GET':
releases = Release.objects.filter(is_active=True).order_by('-released_at').values()[0:15]
# for release in releas... | [
"django.shortcuts.render",
"django.http.HttpResponseNotFound"
] | [((1798, 1853), 'django.shortcuts.render', 'render', (['request', '"""about.html"""', "{'version': __version__}"], {}), "(request, 'about.html', {'version': __version__})\n", (1804, 1853), False, 'from django.shortcuts import render\n'), ((3270, 3327), 'django.shortcuts.render', 'render', (['request', '"""contact.html"... |
from typing import Optional
from fastapi import Depends, HTTPException
import jwt
from starlette import status
from passlib.context import CryptContext
from fastapi.security import OAuth2PasswordBearer
from apps.user.models import user
from apps.user.schema import User
from utils.config import settings
from utils.data... | [
"apps.user.models.user.select",
"fastapi.security.OAuth2PasswordBearer",
"fastapi.HTTPException",
"jwt.encode",
"fastapi.Depends",
"apps.user.schema.User",
"passlib.context.CryptContext",
"jwt.decode"
] | [((404, 455), 'passlib.context.CryptContext', 'CryptContext', ([], {'schemes': "['bcrypt']", 'deprecated': '"""auto"""'}), "(schemes=['bcrypt'], deprecated='auto')\n", (416, 455), False, 'from passlib.context import CryptContext\n'), ((472, 510), 'fastapi.security.OAuth2PasswordBearer', 'OAuth2PasswordBearer', ([], {'t... |
from django.contrib.auth import get_user_model
from rest_framework import serializers
from backend.api.v2.users.serializers import UserSerializer
from backend.groups.models import ChatGroup, GroupMembership, GroupMessage
User = get_user_model()
class MemberSerializer(serializers.ModelSerializer):
person = UserS... | [
"rest_framework.serializers.IntegerField",
"django.contrib.auth.get_user_model",
"backend.api.v2.users.serializers.UserSerializer"
] | [((230, 246), 'django.contrib.auth.get_user_model', 'get_user_model', ([], {}), '()\n', (244, 246), False, 'from django.contrib.auth import get_user_model\n'), ((315, 345), 'backend.api.v2.users.serializers.UserSerializer', 'UserSerializer', ([], {'read_only': '(True)'}), '(read_only=True)\n', (329, 345), False, 'from ... |
from __future__ import absolute_import
'''Resnet for cifar dataset.
Ported form
https://github.com/facebook/fb.resnet.torch
and
https://github.com/pytorch/vision/blob/master/torchvision/models/resnet.py
(c) <NAME>
'''
import torch.nn as nn
import math
import torch
import numpy as np
__all__ = ['resnet','resnet50']
d... | [
"torch.nn.AdaptiveAvgPool2d",
"torch.nn.ReLU",
"torch.nn.init.kaiming_normal_",
"math.sqrt",
"torch.nn.Sequential",
"numpy.empty",
"torch.nn.functional.avg_pool2d",
"torch.nn.Conv2d",
"torch.empty",
"torch.nn.BatchNorm2d",
"torch.nn.init.constant_",
"numpy.arange",
"torch.randperm",
"torch... | [((411, 500), 'torch.nn.Conv2d', 'nn.Conv2d', (['in_planes', 'out_planes'], {'kernel_size': '(3)', 'stride': 'stride', 'padding': '(1)', 'bias': '(False)'}), '(in_planes, out_planes, kernel_size=3, stride=stride, padding=1,\n bias=False)\n', (420, 500), True, 'import torch.nn as nn\n'), ((754, 776), 'torch.nn.BatchN... |
import numpy as np
import matplotlib.pyplot as plt
import glob
import astropy.io.fits as fits
import os
from astropy.table import Table
from astropy.io import ascii
import astropy.units as u
import astropy.constants as const
"""
Quick script for coadding LRS2 data and saving each band as ecsv files. Asumes that all of... | [
"matplotlib.pyplot.savefig",
"astropy.table.Table",
"numpy.average",
"matplotlib.pyplot.show",
"numpy.sum",
"matplotlib.pyplot.plot",
"matplotlib.pyplot.close",
"astropy.io.fits.getdata",
"astropy.io.fits.getheader",
"matplotlib.pyplot.figure",
"astropy.io.ascii.write",
"numpy.array",
"glob.... | [((1039, 1083), 'numpy.average', 'np.average', (['f_array'], {'axis': '(0)', 'weights': 'weights'}), '(f_array, axis=0, weights=weights)\n', (1049, 1083), True, 'import numpy as np\n'), ((1391, 1523), 'astropy.table.Table', 'Table', (['[w * u.AA, f * u.erg / u.s / u.cm ** 2 / u.AA, e * u.erg / u.s / u.cm ** 2 /\n u.... |
from Config import MONGO_URI, DB, OWNER
from pymongo import MongoClient
import asyncio
client = MongoClient(MONGO_URI)
Database = client[DB]
Admins = Database['Admins']
Posts = Database['Posts']
def setupMongo():
if not Admins.find_one({'_id':'admins'}):
Admins.insert_one({
'_id': 'admins',
... | [
"pymongo.MongoClient"
] | [((97, 119), 'pymongo.MongoClient', 'MongoClient', (['MONGO_URI'], {}), '(MONGO_URI)\n', (108, 119), False, 'from pymongo import MongoClient\n')] |
"""
Test cases for functions in general_utils.py
-- <EMAIL>
"""
# pylint: disable=import-error
# pylint: disable=no-member
# pylint: disable=invalid-name
# pylint: disable=relative-import
import numpy as np
from utils import general_utils
from utils.base_test_class import BaseTestClass, execute_tests
class Gene... | [
"numpy.abs",
"utils.general_utils.block_augment_array",
"utils.general_utils.dist_squared",
"utils.general_utils.project_symmetric_to_psd_cone",
"numpy.linalg.norm",
"numpy.random.normal",
"utils.general_utils.draw_gaussian_samples",
"utils.general_utils.map_to_cube",
"utils.general_utils.get_exp_pr... | [((5122, 5137), 'utils.base_test_class.execute_tests', 'execute_tests', ([], {}), '()\n', (5135, 5137), False, 'from utils.base_test_class import BaseTestClass, execute_tests\n'), ((594, 639), 'numpy.array', 'np.array', (['[[1, 2, 3], [1, 2, 4], [2, 3, 4.5]]'], {}), '([[1, 2, 3], [1, 2, 4], [2, 3, 4.5]])\n', (602, 639)... |
from __future__ import annotations
from typing import List, Optional
from pydantic import BaseModel, Field, validator
from pydantic.types import constr
from uuid import UUID, uuid4
from . import FieldModel, VersionModel
class SchemaModel(BaseModel):
uuid: UUID = Field(default_factory=uuid4, description="Automati... | [
"pydantic.Field",
"pydantic.validator",
"pydantic.types.constr"
] | [((270, 374), 'pydantic.Field', 'Field', ([], {'default_factory': 'uuid4', 'description': '"""Automatically generated unique identity for the schema."""'}), "(default_factory=uuid4, description=\n 'Automatically generated unique identity for the schema.')\n", (275, 374), False, 'from pydantic import BaseModel, Field... |
"""
Event action.
"""
from muddery.server.events.base_event_action import BaseEventAction
from muddery.server.database.worlddata.worlddata import WorldData
from muddery.server.utils.localized_strings_handler import _
class ActionCloseEvent(BaseEventAction):
"""
Close events.
"""
key = "ACTION_CLOSE_E... | [
"muddery.server.database.worlddata.worlddata.WorldData.get_table_data",
"muddery.server.utils.localized_strings_handler._"
] | [((337, 382), 'muddery.server.utils.localized_strings_handler._', '_', (['"""Close an Event"""'], {'category': '"""event_actions"""'}), "('Close an Event', category='event_actions')\n", (338, 382), False, 'from muddery.server.utils.localized_strings_handler import _\n'), ((740, 802), 'muddery.server.database.worlddata.... |
#!/usr/bin/env python3
#
# Copyright (c) 2017-2020 The Bitcoin ABC developers
# Distributed under the MIT software license, see the accompanying
# file COPYING or http://www.opensource.org/licenses/mit-license.php.
from test.abcbot_fixture import ABCBotFixture, TEST_USER
import unittest
class EndpointGetCurrentUserT... | [
"unittest.main",
"test.abcbot_fixture.TEST_USER.encode"
] | [((530, 545), 'unittest.main', 'unittest.main', ([], {}), '()\n', (543, 545), False, 'import unittest\n'), ((477, 495), 'test.abcbot_fixture.TEST_USER.encode', 'TEST_USER.encode', ([], {}), '()\n', (493, 495), False, 'from test.abcbot_fixture import ABCBotFixture, TEST_USER\n')] |
#☆𝒐𝒎𝒂𝒋𝒊𝒏𝒂𝒊☆#
import sys
import math
from math import ceil, floor
import itertools
from functools import lru_cache
from collections import deque
inf=10**20
sys.setrecursionlimit(10000000)
input=lambda : sys.stdin.readline().rstrip()
'''''✂'''''''''''''''''''''''''''''''''''''''''''''''''''''''''
s=list(set(inpu... | [
"sys.setrecursionlimit",
"sys.stdin.readline"
] | [((155, 186), 'sys.setrecursionlimit', 'sys.setrecursionlimit', (['(10000000)'], {}), '(10000000)\n', (176, 186), False, 'import sys\n'), ((202, 222), 'sys.stdin.readline', 'sys.stdin.readline', ([], {}), '()\n', (220, 222), False, 'import sys\n')] |
from multiprocessing import Pool
from contextlib import closing
import pandas as pd
import numpy as np
import argparse
import glob
import time
import os
try:
import __builtin__
except ImportError:
# Python 3
import builtins as __builtin__
# For debugging purposes only:
def print(*args, **kwargs):
__bu... | [
"numpy.sum",
"argparse.ArgumentParser",
"pandas.read_csv",
"os.path.exists",
"time.time",
"glob.glob",
"builtins.print"
] | [((316, 378), 'builtins.print', '__builtin__.print', (['"""\t molecular_file_count_updated: """'], {'end': '""""""'}), "('\\t molecular_file_count_updated: ', end='')\n", (333, 378), True, 'import builtins as __builtin__\n'), ((390, 424), 'builtins.print', '__builtin__.print', (['*args'], {}), '(*args, **kwargs)\n', (4... |
Subsets and Splits
No community queries yet
The top public SQL queries from the community will appear here once available.