code stringlengths 22 1.05M | apis listlengths 1 3.31k | extract_api stringlengths 75 3.25M |
|---|---|---|
# Beispielprogramm für das Buch "Python Challenge"
#
# Copyright 2020 by <NAME>
import pytest
from ch09_search_and_sort.solutions.ex07_bucket_sort import bucket_sort
@pytest.mark.parametrize("values, max, expected",
[([10, 50, 22, 7, 42, 111, 50, 7], 150,
[7, 7, 1... | [
"pytest.mark.parametrize",
"ch09_search_and_sort.solutions.ex07_bucket_sort.bucket_sort"
] | [((171, 455), 'pytest.mark.parametrize', 'pytest.mark.parametrize', (['"""values, max, expected"""', '[([10, 50, 22, 7, 42, 111, 50, 7], 150, [7, 7, 10, 22, 42, 50, 50, 111]), (\n [10, 50, 22, 7, 42, 111, 50, 7], 120, [7, 7, 10, 22, 42, 50, 50, 111]),\n [[5, 2, 7, 9, 6, 3, 1, 4, 2, 3, 8], 10, [1, 2, 2, 3, 3, 4, 5... |
#!/usr/bin/env python3
# -*- coding: utf-8 -*-
# =============================================================================
# Created By : <NAME>
# Created Date: 3/1/2022
# =============================================================================
"""
The class 'LM' contains an ordinary linear model object (lm)... | [
"pandas.DataFrame",
"rpy2.rinterface_lib.callbacks.logger.setLevel",
"rpy2.robjects.pandas2ri.activate"
] | [((660, 695), 'rpy2.rinterface_lib.callbacks.logger.setLevel', 'rpy2_logger.setLevel', (['logging.ERROR'], {}), '(logging.ERROR)\n', (680, 695), True, 'from rpy2.rinterface_lib.callbacks import logger as rpy2_logger\n'), ((696, 716), 'rpy2.robjects.pandas2ri.activate', 'pandas2ri.activate', ([], {}), '()\n', (714, 716)... |
from typing import NoReturn
from .datasets import mnist
from .datasets.utils import shuffle_truncate_dataset
from .matrix2d import one_hot_encode, shape, transpose
from deriv8 import model
def main() -> NoReturn:
learning_rate = 1e-1
lamb = 1e-2
batch_size = 500
hidden_units = 32
epochs = 20
... | [
"deriv8.model.train",
"deriv8.model.init_parameters"
] | [((1591, 1647), 'deriv8.model.init_parameters', 'model.init_parameters', (['input_num_units', 'layers_num_units'], {}), '(input_num_units, layers_num_units)\n', (1612, 1647), False, 'from deriv8 import model\n'), ((1653, 1755), 'deriv8.model.train', 'model.train', (['X_train', 'Y_train', 'X_test', 'Y_test', 'parameters... |
# -*- coding: utf-8 -*-
"""Generating the training data.
This script generates the training data according to the config specifications.
Example
-------
To run this script, pass in the desired config file as argument::
$ generate baobab/configs/tdlmc_diagonal_config.py --n_data 1000
"""
import os, sys
import r... | [
"lenstronomy.LensModel.Solver.lens_equation_solver.LensEquationSolver",
"numpy.save",
"os.path.exists",
"baobab.sim_utils.get_PSF_model",
"argparse.ArgumentParser",
"lenstronomy.LensModel.lens_model.LensModel",
"numpy.random.seed",
"pandas.DataFrame",
"lenstronomy.SimulationAPI.data_api.DataAPI",
... | [((1177, 1202), 'argparse.ArgumentParser', 'argparse.ArgumentParser', ([], {}), '()\n', (1200, 1202), False, 'import argparse\n'), ((1695, 1730), 'baobab.configs.BaobabConfig.from_file', 'BaobabConfig.from_file', (['args.config'], {}), '(args.config)\n', (1717, 1730), False, 'from baobab.configs import BaobabConfig\n')... |
import os
import platform
import shutil
import subprocess
import sys
from setuptools import setup, Distribution
import setuptools.command.build_ext as _build_ext
from setuptools.command.install import install
class Install(install):
def run(self):
install.run(self)
python_executable = sys.executab... | [
"setuptools.command.install.install.run",
"setuptools.setup"
] | [((416, 582), 'setuptools.setup', 'setup', ([], {'name': '"""weldsklearn"""', 'version': '"""0.0.1"""', 'packages': "['weldsklearn']", 'cmdclass': "{'install': Install}", 'distclass': 'BinaryDistribution', 'install_requires': "['pyweld']"}), "(name='weldsklearn', version='0.0.1', packages=['weldsklearn'],\n cmdclass... |
import requests
from server import init_db
print("\n")
print("Add an attending with his phone number is not string")
# should be 400
new_attending = {"attending_username": "Everett",
"attending_email": "<EMAIL>",
"attending_phone": 9191111110}
r = requests.post("http://127.0.0.1:5000... | [
"requests.post",
"requests.get"
] | [((284, 360), 'requests.post', 'requests.post', (['"""http://127.0.0.1:5000/api/new_attending"""'], {'json': 'new_attending'}), "('http://127.0.0.1:5000/api/new_attending', json=new_attending)\n", (297, 360), False, 'import requests\n'), ((663, 739), 'requests.post', 'requests.post', (['"""http://127.0.0.1:5000/api/new... |
class Bot:
"""
A class to make a Twitch Bot.
register method is used to add a trigger response.
"""
def __init__(
self,
username: str,
token: str,
channel: str,
callback,
debug: bool = False,
):
"""
username: Twitch username of the... | [
"re.sub",
"threading.Thread",
"socket.socket",
"re.search"
] | [((858, 873), 'socket.socket', 'socket.socket', ([], {}), '()\n', (871, 873), False, 'import socket\n'), ((1237, 1279), 'threading.Thread', 'threading.Thread', ([], {'target': 'self.run', 'args': '()'}), '(target=self.run, args=())\n', (1253, 1279), False, 'import threading\n'), ((1829, 1862), 're.sub', 're.sub', (['""... |
#!/usr/bin/python
# -*- coding: utf-8 -*-
from collections import namedtuple
from copy import deepcopy
from datetime import datetime, timedelta
from itertools import compress
Item = namedtuple("Item", ['index', 'value', 'weight'])
def enough_space(cur_sel, items, capacity):
"""
Check current selection agai... | [
"collections.namedtuple",
"datetime.datetime.now",
"copy.deepcopy",
"datetime.timedelta",
"itertools.compress"
] | [((185, 233), 'collections.namedtuple', 'namedtuple', (['"""Item"""', "['index', 'value', 'weight']"], {}), "('Item', ['index', 'value', 'weight'])\n", (195, 233), False, 'from collections import namedtuple\n'), ((2653, 2673), 'datetime.timedelta', 'timedelta', ([], {'minutes': '(5)'}), '(minutes=5)\n', (2662, 2673), F... |
""" Unit tests for image operations
"""
import logging
import unittest
import numpy
from rascil.processing_components.griddata.operations import create_griddata_from_image, convert_griddata_to_image
from rascil.processing_components.simulation import create_test_image
log = logging.getLogger('logger')
log.setLeve... | [
"logging.getLogger",
"rascil.processing_components.simulation.create_test_image",
"rascil.processing_components.griddata.operations.convert_griddata_to_image",
"rascil.processing_components.griddata.operations.create_griddata_from_image",
"unittest.main",
"rascil.data_models.parameters.rascil_path"
] | [((280, 307), 'logging.getLogger', 'logging.getLogger', (['"""logger"""'], {}), "('logger')\n", (297, 307), False, 'import logging\n'), ((1264, 1279), 'unittest.main', 'unittest.main', ([], {}), '()\n', (1277, 1279), False, 'import unittest\n'), ((486, 513), 'rascil.data_models.parameters.rascil_path', 'rascil_path', (... |
"""The entrance tank of an AguaClara water treatment plant
#. removes large grit particles using plate settlers,
#. contains the :ref:`design-lfom`, which maintains a linear relation between flow and water level, and
#. introduces chemical dosing through the CDC <add link> using the water level set by the :ref:`design... | [
"numpy.ceil",
"aguaclara.design.pipeline.Pipe",
"aguaclara.core.physchem.viscosity_kinematic_water",
"aguaclara.core.physchem.diam_pipe"
] | [((3005, 3011), 'aguaclara.design.pipeline.Pipe', 'Pipe', ([], {}), '()\n', (3009, 3011), False, 'from aguaclara.design.pipeline import Pipe\n'), ((3383, 3422), 'aguaclara.core.physchem.viscosity_kinematic_water', 'pc.viscosity_kinematic_water', (['self.temp'], {}), '(self.temp)\n', (3411, 3422), True, 'import aguaclar... |
import argparse
from evaluator_package.evaluator_utilities import is_ogc
import evaluator_package.selection_expression_validator as expr_val
import shlex
def common_commands_parser():
"""The commands common to all parsers in all mode.
If an argument has a const value of 'MISSING_USER_DEFINED_VALUE', a value w... | [
"shlex.split",
"evaluator_package.selection_expression_validator.select_parser_validator",
"argparse.ArgumentParser"
] | [((482, 532), 'argparse.ArgumentParser', 'argparse.ArgumentParser', ([], {'fromfile_prefix_chars': '"""$"""'}), "(fromfile_prefix_chars='$')\n", (505, 532), False, 'import argparse\n'), ((12028, 12068), 'evaluator_package.selection_expression_validator.select_parser_validator', 'expr_val.select_parser_validator', (['va... |
"""
Adapted from https://github.com/pybind/cmake_example
"""
import os
import platform
import re
import shutil
import subprocess
import sys
import sysconfig
from distutils.command.build_ext import build_ext
from distutils.core import Distribution, Extension
from distutils.version import LooseVersion
from typing import ... | [
"os.path.exists",
"os.listdir",
"os.makedirs",
"subprocess.run",
"distutils.core.Distribution",
"os.environ.copy",
"os.chmod",
"sysconfig.get_path",
"os.getcwd",
"shutil.copyfile",
"platform.system",
"os.path.abspath",
"os.stat",
"os.path.relpath"
] | [((5304, 5367), 'distutils.core.Distribution', 'Distribution', (["{'name': 'pyfastjet', 'ext_modules': ext_modules}"], {}), "({'name': 'pyfastjet', 'ext_modules': ext_modules})\n", (5316, 5367), False, 'from distutils.core import Distribution, Extension\n'), ((740, 766), 'os.path.abspath', 'os.path.abspath', (['sourced... |
import os, sys
GOOS = ['windows', 'linux', 'darwin', 'freebsd']
GOARCH = ['amd64', '386']
packname = sys.argv[1:]
print('[Start Compile]')
if not os.path.exists('target'):
os.mkdir('target')
os.chdir('target')
path = os.getcwd()
for o in GOOS:
os.environ['GOOS'] = o
ARCHS = GOARCH.copy()
if o in ['li... | [
"os.path.exists",
"os.getcwd",
"os.chdir",
"os.mkdir",
"os.system"
] | [((197, 215), 'os.chdir', 'os.chdir', (['"""target"""'], {}), "('target')\n", (205, 215), False, 'import os, sys\n'), ((223, 234), 'os.getcwd', 'os.getcwd', ([], {}), '()\n', (232, 234), False, 'import os, sys\n'), ((147, 171), 'os.path.exists', 'os.path.exists', (['"""target"""'], {}), "('target')\n", (161, 171), Fals... |
import open3d as o3d
image_rgb = o3d.io.read_image("image.png")
image_depth = o3d.io.read_image("image_depth.png")
width = int(image_rgb.get_max_bound()[0])
height = int(image_rgb.get_max_bound()[1])
camera_intrinsic = o3d.camera.PinholeCameraIntrinsic(width=width, height=height, fx=500, fy=500,cx=width/2, cy=height/2... | [
"open3d.io.read_image",
"open3d.geometry.KDTreeSearchParamHybrid",
"open3d.camera.PinholeCameraIntrinsic",
"open3d.io.write_point_cloud",
"open3d.visualization.draw_geometries",
"open3d.geometry.PointCloud.create_from_rgbd_image",
"open3d.geometry.RGBDImage.create_from_color_and_depth"
] | [((34, 64), 'open3d.io.read_image', 'o3d.io.read_image', (['"""image.png"""'], {}), "('image.png')\n", (51, 64), True, 'import open3d as o3d\n'), ((79, 115), 'open3d.io.read_image', 'o3d.io.read_image', (['"""image_depth.png"""'], {}), "('image_depth.png')\n", (96, 115), True, 'import open3d as o3d\n'), ((220, 331), 'o... |
from django.urls import reverse
from service_catalog.models import Request, RequestMessage
from service_catalog.models.instance import InstanceState
from tests.test_service_catalog.base_test_request import BaseTestRequest
class TestCustomerInstanceRequestOperation(BaseTestRequest):
def setUp(self):
supe... | [
"service_catalog.models.Request.objects.all",
"service_catalog.models.RequestMessage.objects.all",
"service_catalog.models.Request.objects.latest",
"django.urls.reverse"
] | [((883, 953), 'django.urls.reverse', 'reverse', (['"""service_catalog:instance_request_new_operation"""'], {'kwargs': 'args'}), "('service_catalog:instance_request_new_operation', kwargs=args)\n", (890, 953), False, 'from django.urls import reverse\n'), ((1556, 1626), 'django.urls.reverse', 'reverse', (['"""service_cat... |
import os
import pytest
from importlib import reload
VALID_ENVKEY = "<KEY>"
INVALID_ENVKEYS = (
"Emzt4BE7C23QtsC7gb1z-3NvfNiG1Boy6XH2oinvalid-env-staging.envkey.com",
"Emzt4BE7C23QtsC7gb1zinvalid-3NvfNiG1Boy6XH2o-env-staging.envkey.com",
"Emzt4BE7C23QtsC7gb1zinvalid-3NvfNiG1Boy6XH2o-localhost:387946",
"invalid",
)... | [
"os.environ.clear",
"envkey.fetch_env",
"os.environ.get",
"pytest.raises",
"importlib.reload",
"envkey.load"
] | [((393, 411), 'os.environ.clear', 'os.environ.clear', ([], {}), '()\n', (409, 411), False, 'import os\n'), ((452, 466), 'importlib.reload', 'reload', (['envkey'], {}), '(envkey)\n', (458, 466), False, 'from importlib import reload\n'), ((575, 593), 'os.environ.clear', 'os.environ.clear', ([], {}), '()\n', (591, 593), F... |
# Copyright (c) 2018, Arm Limited and affiliates.
# SPDX-License-Identifier: Apache-2.0
#
# 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
#
# ... | [
"time.sleep",
"os.path.join",
"os.utime"
] | [((1389, 1409), 'os.utime', 'os.utime', (['path', 'None'], {}), '(path, None)\n', (1397, 1409), False, 'import os\n'), ((2619, 2661), 'os.path.join', 'os.path.join', (['destination_disk', 'capability'], {}), '(destination_disk, capability)\n', (2631, 2661), False, 'import os\n'), ((2968, 2981), 'time.sleep', 'time.slee... |
import MySQLdb
from Model.pessoa_model import PessoaModel
class PessoaDao:
# --- Inicialização da conecção com o servidor local
# --- Inicialização do cursor para manter conecção
def __init__(self):
self.connection = MySQLdb.connect(host='mysql.padawans.dev',database='padawans16',user='padawans16'... | [
"MySQLdb.connect",
"Model.pessoa_model.PessoaModel"
] | [((239, 349), 'MySQLdb.connect', 'MySQLdb.connect', ([], {'host': '"""mysql.padawans.dev"""', 'database': '"""padawans16"""', 'user': '"""padawans16"""', 'passwd': '"""<PASSWORD>"""'}), "(host='mysql.padawans.dev', database='padawans16', user=\n 'padawans16', passwd='<PASSWORD>')\n", (254, 349), False, 'import MySQL... |
#!/usr/bin/env /Users/alexrudy/.pyenv/versions/bitly-boto/bin/python
import subprocess
import click
import re
import tempfile
import shlex
import os
import typing as t
from pathlib import Path
from collections import OrderedDict
@click.command()
@click.option(
"--name", type=str, help="Name of the GCE instance t... | [
"subprocess.check_output",
"tempfile.TemporaryDirectory",
"collections.OrderedDict",
"pathlib.Path",
"click.option",
"shlex.split",
"re.match",
"click.echo",
"click.command",
"os.path.expanduser"
] | [((233, 248), 'click.command', 'click.command', ([], {}), '()\n', (246, 248), False, 'import click\n'), ((250, 349), 'click.option', 'click.option', (['"""--name"""'], {'type': 'str', 'help': '"""Name of the GCE instance to query for."""', 'required': '(True)'}), "('--name', type=str, help=\n 'Name of the GCE instan... |
from acceptance_tests import browser
from common.browser_utilities import wait_for_url_matches
from config import Config
def go_to_using_context(context, conversation_tab='open'):
tab = conversation_tab.replace(' ', '+')
target_url = f"{Config.RESPONSE_OPERATIONS_UI}/messages/{context.short_name}?conversation... | [
"acceptance_tests.browser.driver.find_element_by_id",
"acceptance_tests.browser.driver.find_element_by_class_name",
"acceptance_tests.browser.find_by_text",
"acceptance_tests.browser.driver.find_element_by_link_text",
"acceptance_tests.browser.find_by_name",
"common.browser_utilities.wait_for_url_matches"... | [((336, 361), 'acceptance_tests.browser.visit', 'browser.visit', (['target_url'], {}), '(target_url)\n', (349, 361), False, 'from acceptance_tests import browser\n'), ((366, 443), 'common.browser_utilities.wait_for_url_matches', 'wait_for_url_matches', (['target_url'], {'timeout': '(3)', 'retry': '(0.5)', 'post_change_... |
import unittest
from unittest.mock import MagicMock, call
from .api_backend import ApiBackend
class ApiBackendTest(unittest.TestCase):
def setUp(self):
self.api_response = {"status": "success", "data": {"id": 5}}
response = type('', (), {'ok': True, 'json': lambda: self.api_response, 'content': 's... | [
"unittest.mock.MagicMock"
] | [((1851, 1883), 'unittest.mock.MagicMock', 'MagicMock', ([], {'return_value': 'response'}), '(return_value=response)\n', (1860, 1883), False, 'from unittest.mock import MagicMock, call\n'), ((3022, 3054), 'unittest.mock.MagicMock', 'MagicMock', ([], {'return_value': 'response'}), '(return_value=response)\n', (3031, 305... |
#!/usr/bin/env python
# -*- coding: utf-8 -*-
#
# Create configuration from user provided configuration file.
#
import argparse
import typing
import json
def _read_arguments() -> typing.Dict[str, str]:
parser = argparse.ArgumentParser()
parser.add_argument("--input", required=True, help="Input file.")
pa... | [
"json.load",
"json.dump",
"argparse.ArgumentParser"
] | [((218, 243), 'argparse.ArgumentParser', 'argparse.ArgumentParser', ([], {}), '()\n', (241, 243), False, 'import argparse\n'), ((543, 560), 'json.load', 'json.load', (['stream'], {}), '(stream)\n', (552, 560), False, 'import json\n'), ((1082, 1107), 'json.dump', 'json.dump', (['result', 'stream'], {}), '(result, stream... |
"""
Contains application administration URLs.
"""
from django.conf.urls import url
from . import views
urlpatterns = [
url(r'^pages/revisions/(?P<page_id>\d+)/$', views.page_revisions, name='page_revisions'),
url(r'^pages/preview/(?P<revision_id>\d+)/$', views.preview_page_version, name='preview_page_version... | [
"django.conf.urls.url"
] | [((126, 219), 'django.conf.urls.url', 'url', (['"""^pages/revisions/(?P<page_id>\\\\d+)/$"""', 'views.page_revisions'], {'name': '"""page_revisions"""'}), "('^pages/revisions/(?P<page_id>\\\\d+)/$', views.page_revisions, name=\n 'page_revisions')\n", (129, 219), False, 'from django.conf.urls import url\n'), ((220, 3... |
"""
Source: https://github.com/rokups/paste2box
License: GNU General Public License v3.0
"""
from PySide.QtCore import Qt, Signal
from PySide.QtGui import QKeySequence
class GlobalHotkeyManagerBase(object):
keyPressed = Signal(int)
keyReleased = Signal(int)
def __init__(self):
self.shortcuts = {... | [
"PySide.QtCore.Qt.Key",
"PySide.QtCore.Signal",
"PySide.QtGui.QKeySequence"
] | [((227, 238), 'PySide.QtCore.Signal', 'Signal', (['int'], {}), '(int)\n', (233, 238), False, 'from PySide.QtCore import Qt, Signal\n'), ((257, 268), 'PySide.QtCore.Signal', 'Signal', (['int'], {}), '(int)\n', (263, 268), False, 'from PySide.QtCore import Qt, Signal\n'), ((1735, 1781), 'PySide.QtCore.Qt.Key', 'Qt.Key', ... |
import requests
from front import exceptions
class API(object):
base_url = 'https://api2.frontapp.com/'
def __init__(self):
self.jwt_key = None
def set_key(self, key):
self.jwt_key = key
@property
def _headers(self):
return {
'Authorization': 'Bearer {}'.for... | [
"front.exceptions.AuthenticationError",
"requests.request"
] | [((1121, 1171), 'requests.request', 'requests.request', ([], {'method': 'method', 'url': 'url'}), '(method=method, url=url, **kwargs)\n', (1137, 1171), False, 'import requests\n'), ((765, 862), 'front.exceptions.AuthenticationError', 'exceptions.AuthenticationError', (['"""`front.set_api_key` must be called before maki... |
from django.contrib.auth import get_user_model
from django.urls import reverse
from django.test import TestCase
from rest_framework import status
from rest_framework.test import APIClient
from core.models import Tag
from recipe.serializers import TagSerializer
TAGS_URL = reverse('recipe:tag-list')
class PublicT... | [
"django.contrib.auth.get_user_model",
"core.models.Tag.objects.create",
"rest_framework.test.APIClient",
"recipe.serializers.TagSerializer",
"django.urls.reverse",
"core.models.Tag.objects.all"
] | [((277, 303), 'django.urls.reverse', 'reverse', (['"""recipe:tag-list"""'], {}), "('recipe:tag-list')\n", (284, 303), False, 'from django.urls import reverse\n'), ((427, 438), 'rest_framework.test.APIClient', 'APIClient', ([], {}), '()\n', (436, 438), False, 'from rest_framework.test import APIClient\n'), ((924, 935), ... |
from pystorm.PyDriver import bddriver as bd
import time
"""TAT0[0] is configured to forward one input tag to another out
We then send some tags and record the outputs
"""
CORE = 0
tag_in_start = 0
tag_out = [int("01"*5 + "0", 2), int("10"*5 + "1", 2)] # tag returned by TAT
#count = [int("01"*4 + "0", 2), int("10"*4 +... | [
"pystorm.PyDriver.bddriver.GetField",
"pystorm.PyDriver.bddriver.PackWord",
"time.sleep",
"pystorm.PyDriver.bddriver.Driver"
] | [((444, 455), 'pystorm.PyDriver.bddriver.Driver', 'bd.Driver', ([], {}), '()\n', (453, 455), True, 'from pystorm.PyDriver import bddriver as bd\n'), ((1611, 1624), 'time.sleep', 'time.sleep', (['(2)'], {}), '(2)\n', (1621, 1624), False, 'import time\n'), ((2000, 2015), 'time.sleep', 'time.sleep', (['(0.5)'], {}), '(0.5... |
"""Player registry views."""
from .serializers import PlayerSerializer
from .models import Player
from rest_framework import viewsets
from rest_framework.decorators import action
from rest_framework.response import Response
from rest_framework.permissions import IsAuthenticated
from rest_framework_api_key.permissions ... | [
"rest_framework.response.Response",
"rest_framework.decorators.action"
] | [((555, 574), 'rest_framework.decorators.action', 'action', ([], {'detail': '(True)'}), '(detail=True)\n', (561, 574), False, 'from rest_framework.decorators import action\n'), ((739, 783), 'rest_framework.response.Response', 'Response', (["{'status': 'ok', 'data': sfx_data}"], {}), "({'status': 'ok', 'data': sfx_data}... |
import logging
import os
import docker
from background_task import background
from nifi_web.models import ImageMirrorJob
logger = logging.getLogger(__name__)
@background(schedule=0, remove_existing_tasks=True)
def perform_mirror_ops_bg():
perform_mirror_ops()
def perform_mirror_ops():
logger.info('perform... | [
"logging.getLogger",
"background_task.background",
"docker.from_env",
"nifi_web.models.ImageMirrorJob.objects.filter"
] | [((132, 159), 'logging.getLogger', 'logging.getLogger', (['__name__'], {}), '(__name__)\n', (149, 159), False, 'import logging\n'), ((163, 213), 'background_task.background', 'background', ([], {'schedule': '(0)', 'remove_existing_tasks': '(True)'}), '(schedule=0, remove_existing_tasks=True)\n', (173, 213), False, 'fro... |
#!/usr/bin/env python3
# -*- coding: utf-8 -*-
"""
Created on Sun Jul 1 21:33:40 2018
@author: ivan
"""
import os
import numpy as np
import scipy
import matplotlib.pyplot as plt
class time_series():
"""
Create a time series object.
"""
def __init__(self, file_path):
"""
data is requ... | [
"matplotlib.pyplot.figure",
"scipy.io.wavfile.read",
"os.path.basename",
"numpy.loadtxt",
"matplotlib.pyplot.show"
] | [((1005, 1017), 'matplotlib.pyplot.figure', 'plt.figure', ([], {}), '()\n', (1015, 1017), True, 'import matplotlib.pyplot as plt\n'), ((1082, 1092), 'matplotlib.pyplot.show', 'plt.show', ([], {}), '()\n', (1090, 1092), True, 'import matplotlib.pyplot as plt\n'), ((456, 483), 'os.path.basename', 'os.path.basename', (['f... |
from datetime import datetime, timedelta
import pandas as pd
import prefect
from legal_api.models import Filing
from prefect import task, Flow, unmapped
from prefect.executors import LocalDaskExecutor
from prefect.schedules import IntervalSchedule
from config import get_named_config
from common.firm_queries import ge... | [
"custom_filer.filer.process_filing",
"common.firm_filing_data_cleaning_utils.clean_naics_data",
"datetime.timedelta",
"common.firm_filing_json_factory.get_registration_sp_filing_json",
"tasks.task_utils.ColinInitTask",
"legal_api.models.Filing",
"config.get_named_config",
"prefect.task",
"prefect.co... | [((873, 905), 'tasks.task_utils.ColinInitTask', 'ColinInitTask', ([], {'name': '"""init_colin"""'}), "(name='init_colin')\n", (886, 905), False, 'from tasks.task_utils import ColinInitTask, LearInitTask\n'), ((923, 993), 'tasks.task_utils.LearInitTask', 'LearInitTask', ([], {'name': '"""init_lear"""', 'flask_app_name':... |
'''
This script is to get anchors and pos/neg weights
'''
import os
import h5py
import json
import math
import numpy as np
import h5py
import random
import time
import threading
from sklearn.cluster import KMeans
sample_ratio = 1.0
c3d_resolution = 16
stride = 4
sample_num = 1
n_anchors = 128
tiou_... | [
"sklearn.cluster.KMeans",
"threading.Thread.__init__",
"math.ceil",
"os.path.join",
"h5py.File",
"numpy.array",
"random.randint",
"json.dump"
] | [((445, 468), 'h5py.File', 'h5py.File', (['feature_path'], {}), '(feature_path)\n', (454, 468), False, 'import h5py\n'), ((6046, 6069), 'numpy.array', 'np.array', (['count_anchors'], {}), '(count_anchors)\n', (6054, 6069), True, 'import numpy as np\n'), ((6392, 6415), 'json.dump', 'json.dump', (['weights', 'fid'], {}),... |
import time
def read_input(file_name):
with open(file_name, 'r') as f:
stripped_lines = (line.rstrip() for line in f.readlines())
return [line for line in stripped_lines if line]
def timeit(func):
def wrapper(*args, **kwargs):
start_time = time.time()
func(*args, **kwargs)
... | [
"time.time"
] | [((277, 288), 'time.time', 'time.time', ([], {}), '()\n', (286, 288), False, 'import time\n'), ((338, 349), 'time.time', 'time.time', ([], {}), '()\n', (347, 349), False, 'import time\n')] |
"""lake/utils.py"""
import os
import math
import random
import datetime
import torch
import numpy as np
import matplotlib.pyplot as plt
def get_summary_dir():
now = datetime.datetime.now()
summary_dir = os.path.join('.', 'runs', now.strftime("%Y%m%d-%H%M%S"))
return summary_dir
def set_seed(seed):
random.... | [
"numpy.clip",
"math.sqrt",
"torch.sum",
"matplotlib.pyplot.switch_backend",
"numpy.reshape",
"numpy.where",
"numpy.random.seed",
"numpy.argmin",
"matplotlib.pyplot.savefig",
"numpy.argmax",
"numpy.square",
"matplotlib.pyplot.subplots_adjust",
"matplotlib.pyplot.show",
"torch.manual_seed",
... | [((171, 194), 'datetime.datetime.now', 'datetime.datetime.now', ([], {}), '()\n', (192, 194), False, 'import datetime\n'), ((313, 330), 'random.seed', 'random.seed', (['seed'], {}), '(seed)\n', (324, 330), False, 'import random\n'), ((333, 353), 'numpy.random.seed', 'np.random.seed', (['seed'], {}), '(seed)\n', (347, 3... |
from flask import render_template, flash, redirect, url_for, request
from app import app, db, scheduler
from app.forms import LoginForm, RegistrationForm, ResetPasswordRequestForm, ResetPasswordForm
from flask_login import current_user, login_user, logout_user, login_required
from app.models import User
from werkzeug.u... | [
"datetime.datetime.utcfromtimestamp",
"flask.render_template",
"app.forms.ResetPasswordRequestForm",
"flask.request.args.get",
"app.db.session.commit",
"app.scheduler.get_job",
"app.models.User",
"app.db.session.add",
"app.scheduler.delete_job",
"flask.flash",
"XIRR.xirr",
"flask.request.form.... | [((7303, 7317), 'app.app.route', 'app.route', (['"""/"""'], {}), "('/')\n", (7312, 7317), False, 'from app import app, db, scheduler\n'), ((7319, 7363), 'app.app.route', 'app.route', (['"""/index"""'], {'methods': "['GET', 'POST']"}), "('/index', methods=['GET', 'POST'])\n", (7328, 7363), False, 'from app import app, d... |
import numpy as np
import sqlalchemy
from sqlalchemy.ext.automap import automap_base
from sqlalchemy.orm import Session
from sqlalchemy import create_engine, func
import datetime as dt
from flask import Flask, jsonify
engine = create_engine("sqlite:///Homework/Instructions/Resources/hawaii.sqlite")
Base =... | [
"flask.Flask",
"sqlalchemy.ext.automap.automap_base",
"sqlalchemy.create_engine",
"sqlalchemy.orm.Session",
"flask.jsonify"
] | [((240, 312), 'sqlalchemy.create_engine', 'create_engine', (['"""sqlite:///Homework/Instructions/Resources/hawaii.sqlite"""'], {}), "('sqlite:///Homework/Instructions/Resources/hawaii.sqlite')\n", (253, 312), False, 'from sqlalchemy import create_engine, func\n'), ((321, 335), 'sqlalchemy.ext.automap.automap_base', 'au... |
"""
File: main.py
Description: Driver function to run the CFPL interpreter
Author: <NAME> (<EMAIL>)
Copyright 2020
"""
from constants.reserved_keywords import *
from cfpl.Token import Token
from cfpl.Tokenizer import Tokenizer
from cfpl.Parser import Parser
from cfpl.Interpreter import Interpret... | [
"cfpl.Interpreter.Interpreter",
"cfpl.Parser.Parser",
"cfpl.Tokenizer.Tokenizer"
] | [((473, 488), 'cfpl.Tokenizer.Tokenizer', 'Tokenizer', (['text'], {}), '(text)\n', (482, 488), False, 'from cfpl.Tokenizer import Tokenizer\n'), ((502, 519), 'cfpl.Parser.Parser', 'Parser', (['tokenizer'], {}), '(tokenizer)\n', (508, 519), False, 'from cfpl.Parser import Parser\n'), ((538, 557), 'cfpl.Interpreter.Inter... |
import json
import os
from collections import OrderedDict
from iowa_tools.formats import JsonDataset, convert_dataframe_to_json, \
convert_dataframe_to_csv, convert_json_to_dataframe, convert_csv_to_dataframe
from iowa_tools.constants import JSON_DATA_SUFFIX, JSON_HEADERS_SUFFIX, ST_VOTES, \
CSV_SUFFIX, DATA_D... | [
"iowa_tools.formats.convert_json_to_dataframe",
"iowa_tools.formats.convert_dataframe_to_csv",
"os.path.join",
"os.path.dirname",
"iowa_tools.formats.convert_csv_to_dataframe",
"iowa_tools.formats.JsonDataset",
"json.load",
"iowa_tools.formats.convert_dataframe_to_json"
] | [((475, 514), 'iowa_tools.formats.convert_json_to_dataframe', 'convert_json_to_dataframe', (['json_dataset'], {}), '(json_dataset)\n', (500, 514), False, 'from iowa_tools.formats import JsonDataset, convert_dataframe_to_json, convert_dataframe_to_csv, convert_json_to_dataframe, convert_csv_to_dataframe\n'), ((754, 829)... |
#! /usr/bin/python3
import freeling
import sys
# # ------------ output a parse tree ------------
FREELINGDIR = "/usr/local"
DATA = FREELINGDIR + "/share/freeling/"
LANG = "es"
freeling.util_init_locale("default")
# create language analyzer
la = freeling.lang_ident(DATA + "common/lang_ident/ident.dat")
# create op... | [
"freeling.Document",
"freeling.lang_ident",
"freeling.splitter",
"freeling.ukb",
"freeling.maco",
"freeling.senses",
"sys.stdin.readline",
"freeling.hmm_tagger",
"freeling.chart_parser",
"freeling.semgraph_extract",
"freeling.util_init_locale",
"freeling.tokenizer",
"freeling.maco_options"
] | [((180, 216), 'freeling.util_init_locale', 'freeling.util_init_locale', (['"""default"""'], {}), "('default')\n", (205, 216), False, 'import freeling\n'), ((250, 307), 'freeling.lang_ident', 'freeling.lang_ident', (["(DATA + 'common/lang_ident/ident.dat')"], {}), "(DATA + 'common/lang_ident/ident.dat')\n", (269, 307), ... |
import urllib.request, urllib.parse, urllib.error
from bs4 import BeautifulSoup
import ssl
# Ignore SSL certificate errors
ctx = ssl.create_default_context()
ctx.check_hostname = False
ctx.verify_mode = ssl.CERT_NONE
url = input('Enter - ')
html = urllib.request.urlopen(url, context=ctx).read()
soup = BeautifulSoup(htm... | [
"bs4.BeautifulSoup",
"ssl.create_default_context"
] | [((129, 157), 'ssl.create_default_context', 'ssl.create_default_context', ([], {}), '()\n', (155, 157), False, 'import ssl\n'), ((303, 337), 'bs4.BeautifulSoup', 'BeautifulSoup', (['html', '"""html.parser"""'], {}), "(html, 'html.parser')\n", (316, 337), False, 'from bs4 import BeautifulSoup\n')] |
import string
import nltk
from sklearn.feature_extraction.text import TfidfVectorizer
from sklearn.metrics.pairwise import cosine_similarity
nltk.download('punkt')
nltk.download('wordnet')
def LemmatizeTokenizer(text):
punctTranslateDict = dict((ord(punc), None) for punc in string.punctuation)
text = text.lower()... | [
"sklearn.metrics.pairwise.cosine_similarity",
"nltk.word_tokenize",
"nltk.download",
"nltk.stem.WordNetLemmatizer",
"sklearn.feature_extraction.text.TfidfVectorizer"
] | [((142, 164), 'nltk.download', 'nltk.download', (['"""punkt"""'], {}), "('punkt')\n", (155, 164), False, 'import nltk\n'), ((165, 189), 'nltk.download', 'nltk.download', (['"""wordnet"""'], {}), "('wordnet')\n", (178, 189), False, 'import nltk\n'), ((362, 386), 'nltk.word_tokenize', 'nltk.word_tokenize', (['text'], {})... |
""" Contains classes used for the player selection screen. """
import pygame as pg
import yaml
from settings import prepare, tools, status_machine, menu_functions
from entity import enemy_entity, player
from .constants import *
FONT = pg.font.Font(prepare.FONTS["Fixedsys500c"], 60) ###
SMALL_FONT = pg.font.Font(prep... | [
"pygame.time.get_ticks",
"settings.status_machine.State.startup",
"yaml.dump",
"pygame.Surface",
"settings.status_machine.StateMachine",
"yaml.load",
"entity.player.Player",
"settings.status_machine.State.__init__",
"pygame.Color",
"pygame.font.Font",
"settings.menu_functions.BasicMenu.__init__"... | [((237, 284), 'pygame.font.Font', 'pg.font.Font', (["prepare.FONTS['Fixedsys500c']", '(60)'], {}), "(prepare.FONTS['Fixedsys500c'], 60)\n", (249, 284), True, 'import pygame as pg\n'), ((303, 350), 'pygame.font.Font', 'pg.font.Font', (["prepare.FONTS['Fixedsys500c']", '(32)'], {}), "(prepare.FONTS['Fixedsys500c'], 32)\n... |
# -*- coding: utf-8 -*-
# Copyright 2020 Google LLC
#
# Licensed under the Apache License, Version 2.0 (the "License");
# you may not use this file except in compliance with the License.
# You may obtain a copy of the License at
#
# http://www.apache.org/licenses/LICENSE-2.0
#
# Unless required by applicable law o... | [
"mock.patch.dict",
"mock.Mock",
"grpc.experimental.aio.insecure_channel",
"mock.PropertyMock",
"google.cloud.talent_v4beta1.types.completion_service.CompleteQueryRequest",
"mock.patch",
"google.cloud.talent_v4beta1.services.completion.CompletionClient",
"google.cloud.talent_v4beta1.services.completion... | [((2836, 2922), 'pytest.mark.parametrize', 'pytest.mark.parametrize', (['"""client_class"""', '[CompletionClient, CompletionAsyncClient]'], {}), "('client_class', [CompletionClient,\n CompletionAsyncClient])\n", (2859, 2922), False, 'import pytest\n'), ((3812, 4046), 'pytest.mark.parametrize', 'pytest.mark.parametri... |
# -*- coding: utf-8 -*-
from __future__ import division
from __future__ import absolute_import
from __future__ import print_function
from __future__ import unicode_literals
import unittest
from asciimatics.parsers import AsciimaticsParser, AnsiTerminalParser, ControlCodeParser
import asciimatics.constants as constants
... | [
"asciimatics.parsers.AsciimaticsParser",
"asciimatics.parsers.ControlCodeParser",
"asciimatics.parsers.AnsiTerminalParser"
] | [((492, 511), 'asciimatics.parsers.ControlCodeParser', 'ControlCodeParser', ([], {}), '()\n', (509, 511), False, 'from asciimatics.parsers import AsciimaticsParser, AnsiTerminalParser, ControlCodeParser\n'), ((1126, 1145), 'asciimatics.parsers.AsciimaticsParser', 'AsciimaticsParser', ([], {}), '()\n', (1143, 1145), Fal... |
# Copyright Amazon.com, Inc. or its affiliates. All Rights Reserved.
# SPDX-License-Identifier: MIT-0
import os, sys, unittest
os.environ['EVIDENTLY_PROJECT_NAME'] = 'retaildemostore'
sys.argv += ['discover', os.path.dirname(sys.argv[0]), 'test_*.py']
unittest.main(module=None) | [
"unittest.main",
"os.path.dirname"
] | [((256, 282), 'unittest.main', 'unittest.main', ([], {'module': 'None'}), '(module=None)\n', (269, 282), False, 'import os, sys, unittest\n'), ((212, 240), 'os.path.dirname', 'os.path.dirname', (['sys.argv[0]'], {}), '(sys.argv[0])\n', (227, 240), False, 'import os, sys, unittest\n')] |
from functools import wraps
from flask import g
def plugin_available():
def wrapper(fn):
@wraps(fn)
def decorated_view(*args, **kwargs):
for func in getattr(g, 'call_before_{}'.format(fn.__name__), ()):
func()
response = fn(*args, **kwargs)
for f... | [
"functools.wraps"
] | [((104, 113), 'functools.wraps', 'wraps', (['fn'], {}), '(fn)\n', (109, 113), False, 'from functools import wraps\n')] |
## Imports
import handybeam
import handybeam.opencl_wrappers.abstract_wrapper
import handybeam.propagator_mixins
import handybeam.propagator_mixins.clist_propagator
import handybeam.propagator_mixins.rect_propagator
import handybeam.propagator_mixins.hex_propagator
import handybeam.propagator_mixins.lamb_propagator
im... | [
"handybeam.cl_system.OpenCLSystem"
] | [((1736, 1859), 'handybeam.cl_system.OpenCLSystem', 'handybeam.cl_system.OpenCLSystem', ([], {'parent': 'self.parent', 'use_device': 'self.parent.device', 'use_platform': 'self.parent.platform'}), '(parent=self.parent, use_device=self.parent\n .device, use_platform=self.parent.platform)\n', (1768, 1859), False, 'imp... |
# -*- coding: utf-8 -*-
# -----------------------------------------------------------------------------
# (C) British Crown Copyright 2017-2019 Met Office.
# All rights reserved.
#
# Redistribution and use in source and binary forms, with or without
# modification, are permitted provided that the following conditions a... | [
"improver.spotdata.neighbour_finding.NeighbourSelection",
"cartopy.crs.Mercator",
"numpy.sqrt",
"improver.utilities.cube_metadata.create_coordinate_hash",
"numpy.array",
"numpy.zeros",
"numpy.stack",
"numpy.linspace",
"iris.coord_systems.GeogCS",
"numpy.nonzero",
"unittest.main",
"numpy.full",... | [((11680, 11707), 'improver.utilities.warnings_handler.ManageWarnings', 'ManageWarnings', ([], {'record': '(True)'}), '(record=True)\n', (11694, 11707), False, 'from improver.utilities.warnings_handler import ManageWarnings\n'), ((13118, 13145), 'improver.utilities.warnings_handler.ManageWarnings', 'ManageWarnings', ([... |
# -*- coding: utf-8 -*-
"""Browse page related API operations.
"""
import fastapi
from omoide import domain, use_cases
from omoide.presentation import dependencies as dep, utils, infra
router = fastapi.APIRouter()
@router.get('/api/browse/{uuid}')
async def api_browse(
request: fastapi.Request,
uuid... | [
"fastapi.APIRouter",
"omoide.presentation.utils.to_simple_items",
"fastapi.Depends",
"omoide.presentation.infra.parse.cast_uuid"
] | [((196, 215), 'fastapi.APIRouter', 'fastapi.APIRouter', ([], {}), '()\n', (213, 215), False, 'import fastapi\n'), ((355, 392), 'fastapi.Depends', 'fastapi.Depends', (['dep.get_current_user'], {}), '(dep.get_current_user)\n', (370, 392), False, 'import fastapi\n'), ((441, 481), 'fastapi.Depends', 'fastapi.Depends', (['d... |
import time
import gym
import numpy as np
import quanser_robots
import torch
from torch.multiprocessing import Value, Process
from a3c.train_test import train, test
from a3c.util.util import get_model, get_shared_optimizer
class A3C(object):
def __init__(self, args) -> None:
"""
Constructor
... | [
"torch.multiprocessing.Process",
"torch.manual_seed",
"a3c.util.util.get_shared_optimizer",
"torch.optim.lr_scheduler.ExponentialLR",
"a3c.util.util.get_model",
"time.sleep",
"torch.multiprocessing.Value",
"gym.make"
] | [((437, 450), 'torch.multiprocessing.Value', 'Value', (['"""i"""', '(0)'], {}), "('i', 0)\n", (442, 450), False, 'from torch.multiprocessing import Value, Process\n'), ((480, 499), 'torch.multiprocessing.Value', 'Value', (['"""d"""', '(-np.inf)'], {}), "('d', -np.inf)\n", (485, 499), False, 'from torch.multiprocessing ... |
from distutils.core import setup
setup(
name='C3Linearize',
version='0.1.0',
description='Python implementation of the C3 linearization algorithm.',
url='http://github.com/mikeboers/C3Linearize',
py_modules=['c3linearize'],
author='<NAME>',
author_email='<EMAIL>',
license='BSD-3',... | [
"distutils.core.setup"
] | [((35, 1034), 'distutils.core.setup', 'setup', ([], {'name': '"""C3Linearize"""', 'version': '"""0.1.0"""', 'description': '"""Python implementation of the C3 linearization algorithm."""', 'url': '"""http://github.com/mikeboers/C3Linearize"""', 'py_modules': "['c3linearize']", 'author': '"""<NAME>"""', 'author_email': ... |
from rdkit import Chem
from rdkit.Chem import AllChem
import numpy as np
def reset_ids(mol):
for i, conf in enumerate(mol.GetConformers()):
conf.SetId(i)
class EnergyFilter:
def __init__(self, energy_diff):
self.energy_diff = energy_diff
def filter(self, mol, energies, min_energy=None... | [
"numpy.argmin",
"rdkit.Chem.RemoveHs",
"numpy.min"
] | [((379, 395), 'numpy.min', 'np.min', (['energies'], {}), '(energies)\n', (385, 395), True, 'import numpy as np\n'), ((751, 769), 'rdkit.Chem.RemoveHs', 'Chem.RemoveHs', (['mol'], {}), '(mol)\n', (764, 769), False, 'from rdkit import Chem\n'), ((3011, 3038), 'numpy.argmin', 'np.argmin', (['similar_energies'], {}), '(sim... |
#!/usr/bin/env python3
import os
import time
from itertools import combinations
from gdaxapi import Gdax
from geminiapi import Gemini
from krakenapi import Kraken
from wallet import Wallet
maxDiff = 0
maxDiffp = 0
minDiff = 0
minDiffp = 0
maxSymbol = ""
minSymbol = ""
maxExchange = ""
minExchange = ""
gdaxWallets = ... | [
"krakenapi.Kraken",
"time.sleep",
"itertools.combinations",
"wallet.Wallet",
"geminiapi.Gemini",
"os.system",
"gdaxapi.Gdax"
] | [((333, 339), 'gdaxapi.Gdax', 'Gdax', ([], {}), '()\n', (337, 339), False, 'from gdaxapi import Gdax\n'), ((363, 391), 'wallet.Wallet', 'Wallet', (['"""gdax"""', '"""LTC"""', '(2.835)'], {}), "('gdax', 'LTC', 2.835)\n", (369, 391), False, 'from wallet import Wallet\n'), ((415, 443), 'wallet.Wallet', 'Wallet', (['"""gda... |
#!/usr/bin/env python
# coding: utf-8
from websocket import create_connection
import json
import psutil
import os
import datetime
import time
import configparser
import sys
import requests
import secrets
import distro
from hashit import make_hash
#Provide full path, if you are using a systemd service
conf_file = 'mo... | [
"secrets.token_hex",
"json.loads",
"configparser.ConfigParser",
"psutil.swap_memory",
"json.dumps",
"time.sleep",
"psutil.virtual_memory",
"distro.info",
"datetime.datetime.now",
"psutil.boot_time",
"psutil.cpu_times_percent",
"sys.exit",
"websocket.create_connection",
"time.time"
] | [((899, 926), 'configparser.ConfigParser', 'configparser.ConfigParser', ([], {}), '()\n', (924, 926), False, 'import configparser\n'), ((1431, 1441), 'sys.exit', 'sys.exit', ([], {}), '()\n', (1439, 1441), False, 'import sys\n'), ((2115, 2125), 'sys.exit', 'sys.exit', ([], {}), '()\n', (2123, 2125), False, 'import sys\... |
#!/usr/bin/env python
import logging
import sys
from pathlib import Path
from typing import Dict, Iterator, Optional, Tuple, Union
import fire
from benchmarker.cli.l5.common.utils import save_t5_kleister_cache
from benchmarker.data.model.feature import Feature
from benchmarker.data.reader import Corpus, qa_strategies... | [
"logging.getLogger",
"benchmarker.utils.training.load_tokenizer",
"pathlib.Path",
"fire.Fire",
"benchmarker.cli.l5.common.utils.save_t5_kleister_cache",
"benchmarker.data.slicer.LongPageStrategy"
] | [((496, 523), 'logging.getLogger', 'logging.getLogger', (['__name__'], {}), '(__name__)\n', (513, 523), False, 'import logging\n'), ((5854, 5954), 'benchmarker.utils.training.load_tokenizer', 'load_tokenizer', (['model_path'], {'model_type': 'model_type', 'convert_to_fast_tokenizer': 'use_fast_tokenizer'}), '(model_pat... |
import numpy as np
from utils.bit_tools import parity, int_to_bin
class eigenstate:
"""Class for constructing the n-th +1-eigenstate of A
Attributes
----------
A : dict
Dictionary containg two items A = \{P_1:r_1, P_2:r_2\}}
n : int
The eigenstate index
num_qubits : int
... | [
"utils.bit_tools.int_to_bin",
"numpy.array",
"numpy.cos",
"utils.bit_tools.parity",
"numpy.sin",
"numpy.arctan"
] | [((1932, 1967), 'utils.bit_tools.int_to_bin', 'int_to_bin', (['self.n', 'self.num_qubits'], {}), '(self.n, self.num_qubits)\n', (1942, 1967), False, 'from utils.bit_tools import parity, int_to_bin\n'), ((3114, 3149), 'utils.bit_tools.int_to_bin', 'int_to_bin', (['self.n', 'self.num_qubits'], {}), '(self.n, self.num_qub... |
"""
Module Functors
AUTHORS:
- <NAME> (2017-10): Initial implementation of
:class:`QuotientModuleFunctor`
"""
#*****************************************************************************
# Copyright (C) 2017 <NAME> <<EMAIL>>
#
# This program is free software: you can redistribute it and/or modify
# it unde... | [
"sage.categories.modules.Modules"
] | [((2787, 2797), 'sage.categories.modules.Modules', 'Modules', (['R'], {}), '(R)\n', (2794, 2797), False, 'from sage.categories.modules import Modules\n'), ((2799, 2809), 'sage.categories.modules.Modules', 'Modules', (['R'], {}), '(R)\n', (2806, 2809), False, 'from sage.categories.modules import Modules\n')] |
import numpy as np
import torch
import torch.nn.functional as F
from tqdm import trange
from torch import nn
from ..metrics import Metric, MultipleMetrics
from ..wdtypes import *
use_cuda = torch.cuda.is_available()
class WarmUp(object):
r"""
'Warm up' methods to be applied to the individual models before t... | [
"torch.nn.functional.softmax",
"numpy.sqrt",
"torch.sigmoid",
"torch.optim.lr_scheduler.CyclicLR",
"torch.cuda.is_available",
"tqdm.trange",
"torch.optim.AdamW"
] | [((192, 217), 'torch.cuda.is_available', 'torch.cuda.is_available', ([], {}), '()\n', (215, 217), False, 'import torch\n'), ((3245, 3416), 'torch.optim.lr_scheduler.CyclicLR', 'torch.optim.lr_scheduler.CyclicLR', (['optimizer'], {'base_lr': '(max_lr / 10.0)', 'max_lr': 'max_lr', 'step_size_up': 'step_size_up', 'step_si... |
#from __future__ import unicode_literals
# Create your models here.
from django.contrib.auth.models import User
from django.core.validators import MinLengthValidator
from django.db import models
class Idea(models.Model):
idea_title = models.CharField(max_length=50, validators=[MinLengthValidator(3, message='Leng... | [
"django.db.models.TextField",
"django.db.models.ForeignKey",
"django.db.models.IntegerField",
"django.core.validators.MinLengthValidator",
"django.db.models.DateTimeField",
"django.db.models.CharField"
] | [((365, 408), 'django.db.models.TextField', 'models.TextField', ([], {'max_length': '(500)', 'null': '(True)'}), '(max_length=500, null=True)\n', (381, 408), False, 'from django.db import models\n'), ((424, 463), 'django.db.models.DateTimeField', 'models.DateTimeField', ([], {'auto_now_add': '(True)'}), '(auto_now_add=... |
import torch
class GE2E(torch.nn.Module):
def __init__(self, init_w=10.0, init_b=-5.0, loss_method='softmax'):
super(GE2E, self).__init__()
self.w = torch.nn.Parameter(torch.tensor(init_w))
self.b = torch.nn.Parameter(torch.tensor(init_b))
self.loss_method = loss_method
as... | [
"torch.mean",
"torch.stack",
"torch.sigmoid",
"torch.max",
"torch.tensor",
"torch.cat",
"torch.norm",
"torch.nn.functional.log_softmax",
"torch.clamp"
] | [((643, 696), 'torch.cat', 'torch.cat', (['(dvecs[spkr, :utt], dvecs[spkr, utt + 1:])'], {}), '((dvecs[spkr, :utt], dvecs[spkr, utt + 1:]))\n', (652, 696), False, 'import torch\n'), ((708, 727), 'torch.mean', 'torch.mean', (['excl', '(0)'], {}), '(excl, 0)\n', (718, 727), False, 'import torch\n'), ((953, 979), 'torch.s... |
"""students URL Configuration
The `urlpatterns` list routes URLs to views. For more information please see:
https://docs.djangoproject.com/en/2.2/topics/http/urls/
Examples:
Function views
1. Add an import: from my_app import views
2. Add a URL to urlpatterns: path('', views.home, name='home')
Cl... | [
"django.urls.path",
"django.conf.urls.url",
"django.urls.include"
] | [((914, 945), 'django.urls.path', 'path', (['"""admin/"""', 'admin.site.urls'], {}), "('admin/', admin.site.urls)\n", (918, 945), False, 'from django.urls import path\n'), ((952, 984), 'django.conf.urls.url', 'url', (['"""^listone/$"""', 'views.listone'], {}), "('^listone/$', views.listone)\n", (955, 984), False, 'from... |
import numpy as np
import scipy.integrate
import sys
import Functional
from scipy import signal
class MFA1d(Functional.Functional):
def __init__(self, fluid, system):
super(MFA1d, self).__init__(fluid, system)
# ============ init DCF ============ #
self.DCF = np.zeros((self.maxNum*2+1,... | [
"matplotlib.pyplot.savefig",
"matplotlib.pyplot.xlim",
"numpy.sqrt",
"matplotlib.pyplot.plot",
"numpy.array",
"matplotlib.pyplot.figure",
"numpy.zeros",
"numpy.linspace",
"matplotlib.pyplot.scatter",
"matplotlib.pyplot.ylim",
"numpy.loadtxt"
] | [((3477, 3492), 'numpy.array', 'np.array', (['[1.0]'], {}), '([1.0])\n', (3485, 3492), True, 'import numpy as np\n'), ((3516, 3531), 'numpy.array', 'np.array', (['[1.0]'], {}), '([1.0])\n', (3524, 3531), True, 'import numpy as np\n'), ((3556, 3571), 'numpy.array', 'np.array', (['[1.0]'], {}), '([1.0])\n', (3564, 3571),... |
import subprocess
import os
def get_git_root_dir():
res = subprocess.run(["git", "rev-parse", "--show-toplevel"],
stdout=subprocess.PIPE,
stderr=subprocess.PIPE
)
path = res.stdout.decode('utf-8').strip()
return path
def get_mariadb_password(mysql_config_filepath):
with open(mys... | [
"subprocess.run"
] | [((64, 172), 'subprocess.run', 'subprocess.run', (["['git', 'rev-parse', '--show-toplevel']"], {'stdout': 'subprocess.PIPE', 'stderr': 'subprocess.PIPE'}), "(['git', 'rev-parse', '--show-toplevel'], stdout=subprocess.\n PIPE, stderr=subprocess.PIPE)\n", (78, 172), False, 'import subprocess\n')] |
"""
Read in the SnowEx 2020 Decimated GPR data. Uploaded SWE, Two Way Travel, Depth, to
the database.
1. Data must be downloaded via sh ../download/download_nsidc.sh
2A. python run.py # To run all together all at once
2B. python add_gpr.py # To run individually
"""
import time
from os.path import abspath, expanduser... | [
"os.path.expanduser",
"snowexsql.db.get_db"
] | [((1185, 1234), 'snowexsql.db.get_db', 'get_db', (['db_name'], {'credentials': '"""./credentials.json"""'}), "(db_name, credentials='./credentials.json')\n", (1191, 1234), False, 'from snowexsql.db import get_db\n'), ((1057, 1073), 'os.path.expanduser', 'expanduser', (['file'], {}), '(file)\n', (1067, 1073), False, 'fr... |
# Generated by Django 2.2.3 on 2019-08-13 18:01
from django.db import migrations, models
class Migration(migrations.Migration):
dependencies = [
('models', '0052_auto_20190805_1405'),
]
operations = [
migrations.RenameField(
model_name='secretnote',
old_name='rea... | [
"django.db.migrations.RenameField",
"django.db.models.IntegerField"
] | [((234, 330), 'django.db.migrations.RenameField', 'migrations.RenameField', ([], {'model_name': '"""secretnote"""', 'old_name': '"""reads_left"""', 'new_name': '"""reads_max"""'}), "(model_name='secretnote', old_name='reads_left',\n new_name='reads_max')\n", (256, 330), False, 'from django.db import migrations, mode... |
import matplotlib
matplotlib.use("Agg")
import traceback
from flask import render_template, jsonify, request
from app import app
import app.optimusform as opform
import sys
sys.path.append("..")
from hardware_router import route
from stats import get_dwave_plot, get_networkx_plot_of_qubo
from optimus_parser... | [
"flask.render_template",
"traceback.format_exc",
"stats_rigetti.plot_this_rigetti",
"stats_ibm.plot_this",
"stats.get_networkx_plot_of_qubo",
"stats.get_dwave_plot",
"matplotlib.use",
"optimus_parser.refresh_globals",
"app.app.route",
"hardware_router.route",
"sys.path.append"
] | [((19, 40), 'matplotlib.use', 'matplotlib.use', (['"""Agg"""'], {}), "('Agg')\n", (33, 40), False, 'import matplotlib\n'), ((182, 203), 'sys.path.append', 'sys.path.append', (['""".."""'], {}), "('..')\n", (197, 203), False, 'import sys\n'), ((443, 457), 'app.app.route', 'app.route', (['"""/"""'], {}), "('/')\n", (452,... |
import numpy as np
import matplotlib.pyplot as plt
import pandas as pd
from scipy.constants import k,h,c
from scipy.optimize import curve_fit
from numba import njit,jit
import emcee
@njit
def Planck(lamb,T):
"""
Black-body radiation; Bnu.
Args:
lam: (float) wavelength [m]
T: (float) te... | [
"numpy.log10",
"numpy.average",
"numpy.asarray",
"numpy.exp",
"numpy.linspace"
] | [((2274, 2329), 'numpy.average', 'np.average', (['(mag_obs - mag_fit)'], {'weights': '(1 / mag_err ** 2)'}), '(mag_obs - mag_fit, weights=1 / mag_err ** 2)\n', (2284, 2329), True, 'import numpy as np\n'), ((4364, 4382), 'numpy.asarray', 'np.asarray', (['loglik'], {}), '(loglik)\n', (4374, 4382), True, 'import numpy as ... |
#!/usr/bin/env python3
# -*- coding: utf-8 -*-
"""
This script saves bid and ask data for specified ETFs to files for each day
during market open hours.
It assumes the computer is at US East Coast Time.
@author: mark
"""
import os
import pandas as pd
import numpy as np
from itertools import product
import streaml... | [
"pandas.read_pickle",
"bokeh.models.DatetimeTickFormatter",
"numpy.log10",
"pandas.read_csv",
"streamlit_metrics.metric_row",
"bokeh.models.VBar",
"itertools.product",
"streamlit.write",
"bokeh.models.Rect",
"pandas.to_datetime",
"pandas.Timedelta",
"bokeh.models.tools.HoverTool",
"bokeh.mod... | [((17120, 17175), 'streamlit.write', 'st.write', (['"""# Bid-Ask spreads. Does time of day matter?"""'], {}), "('# Bid-Ask spreads. Does time of day matter?')\n", (17128, 17175), True, 'import streamlit as st\n'), ((17176, 17202), 'streamlit.write', 'st.write', (['"""#### By <NAME>"""'], {}), "('#### By <NAME>')\n", (1... |
from pathlib import Path
ROOT_DIR = Path(__file__).parent.parent.parent
DEFAULT_EMBED_COLOUR = 0x00CD99
# Dependant on above constants.
from .loc import CodeCounter
from .ready import Ready
| [
"pathlib.Path"
] | [((37, 51), 'pathlib.Path', 'Path', (['__file__'], {}), '(__file__)\n', (41, 51), False, 'from pathlib import Path\n')] |
from distutils.core import setup
setup(
name = 'py-geohash-any',
packages = ['py_geohash_any', 'py_geohash_any.tests'],
version = '1.1',
description = 'Python geohash library designed to use any encoding',
author = '<NAME>',
author_email = '<EMAIL>',
url = 'https://github.com/kyleb... | [
"distutils.core.setup"
] | [((36, 485), 'distutils.core.setup', 'setup', ([], {'name': '"""py-geohash-any"""', 'packages': "['py_geohash_any', 'py_geohash_any.tests']", 'version': '"""1.1"""', 'description': '"""Python geohash library designed to use any encoding"""', 'author': '"""<NAME>"""', 'author_email': '"""<EMAIL>"""', 'url': '"""https://... |
from flask import Blueprint, render_template, redirect, url_for, g, request
from flask_login import login_required, current_user
from app.forms import DreamsForm
from app.models import Dream
dream_module = Blueprint('dreams', __name__, template_folder='templates')
@dream_module.route('/dreams', methods=['GET', 'POST'... | [
"flask.render_template",
"app.models.Dream",
"flask.url_for",
"flask.g.user.get_current_month",
"app.forms.DreamsForm",
"flask.Blueprint"
] | [((206, 264), 'flask.Blueprint', 'Blueprint', (['"""dreams"""', '__name__'], {'template_folder': '"""templates"""'}), "('dreams', __name__, template_folder='templates')\n", (215, 264), False, 'from flask import Blueprint, render_template, redirect, url_for, g, request\n'), ((371, 395), 'app.forms.DreamsForm', 'DreamsFo... |
from abc import ABC, abstractmethod
from functools import partial
from mininlp.predict import predict_binary, predict_dl, predict_multiclass
from sklearn.metrics import accuracy_score, f1_score
import torch
import torch.nn as nn
from torch.utils.data import DataLoader
from typing import Callable
def metric_lower_is_b... | [
"torch.no_grad",
"functools.partial",
"mininlp.predict.predict_dl"
] | [((1870, 1907), 'functools.partial', 'partial', (['f1_score'], {'average': '"""weighted"""'}), "(f1_score, average='weighted')\n", (1877, 1907), False, 'from functools import partial\n'), ((1373, 1388), 'torch.no_grad', 'torch.no_grad', ([], {}), '()\n', (1386, 1388), False, 'import torch\n'), ((1413, 1452), 'mininlp.p... |
from scipy.io import loadmat
import numpy as np
import pyfftw
from scipy.special import erf
np.set_string_function(lambda a: str(a.shape), repr=False)
def mat_to_npy(file_name):
return loadmat(file_name + '.mat')[file_name]
def mat_to_npy_vec(file_name):
a = mat_to_npy(file_name)
return a.reshape(a.sha... | [
"numpy.mean",
"numpy.prod",
"pyfftw.interfaces.numpy_fft.fftn",
"scipy.io.loadmat",
"numpy.floor",
"numpy.square",
"numpy.array",
"numpy.zeros",
"numpy.linspace",
"pyfftw.interfaces.numpy_fft.ifftn",
"scipy.special.erf",
"numpy.expand_dims",
"numpy.std",
"numpy.shape",
"numpy.transpose",... | [((502, 513), 'numpy.floor', 'np.floor', (['n'], {}), '(n)\n', (510, 513), True, 'import numpy as np\n'), ((1526, 1541), 'numpy.floor', 'np.floor', (['(n / 2)'], {}), '(n / 2)\n', (1534, 1541), True, 'import numpy as np\n'), ((1798, 1816), 'numpy.zeros', 'np.zeros', (['n_images'], {}), '(n_images)\n', (1806, 1816), Tru... |
import pandas as pd
import torch
import numpy as np
import torch.nn as nn
import Pre_processing
df = pd.read_csv(r'C:data/coords.csv')
df.drop(df.tail(10).index,inplace=True)
print(df.shape)
df_model = Pre_processing.Pre_process(df)
x = df_model.iloc[:,4:].to_numpy()
X = np.reshape(x,(-1,50,66)).astype(np.float)
... | [
"numpy.reshape",
"pandas.read_csv",
"Pre_processing.Pre_process",
"torch.nn.LSTM",
"torch.load",
"torch.nn.BatchNorm1d",
"torch.cuda.is_available",
"torch.nn.Linear",
"torch.device"
] | [((103, 135), 'pandas.read_csv', 'pd.read_csv', (['"""C:data/coords.csv"""'], {}), "('C:data/coords.csv')\n", (114, 135), True, 'import pandas as pd\n'), ((206, 236), 'Pre_processing.Pre_process', 'Pre_processing.Pre_process', (['df'], {}), '(df)\n', (232, 236), False, 'import Pre_processing\n'), ((964, 989), 'torch.cu... |
#!/usr/bin/python3
import sys
import os
import subprocess
PATH_TO_LOGS = "/tmp/logs"
LOG_NAME = "clang-tidy-output.txt"
l = sys.argv
l[0] = "/usr/bin/clang-tidy"
with open(os.path.join(PATH_TO_LOGS, "run-clang-tidy.sh"), "at") as script:
for i in l:
script.write(i + " ")
script.write("\n")
try:
... | [
"subprocess.check_output",
"os.path.join"
] | [((330, 382), 'subprocess.check_output', 'subprocess.check_output', (['l'], {'stderr': 'subprocess.STDOUT'}), '(l, stderr=subprocess.STDOUT)\n', (353, 382), False, 'import subprocess\n'), ((176, 223), 'os.path.join', 'os.path.join', (['PATH_TO_LOGS', '"""run-clang-tidy.sh"""'], {}), "(PATH_TO_LOGS, 'run-clang-tidy.sh')... |
from setuptools import setup, find_packages
def parse_requirements(requirement_file):
with open(requirement_file) as f:
return f.readlines()
setup(
name='graphish',
version='1.3.0',
packages=find_packages(exclude=['tests*']),
license='MIT',
description='A Python package to search & del... | [
"setuptools.find_packages"
] | [((217, 250), 'setuptools.find_packages', 'find_packages', ([], {'exclude': "['tests*']"}), "(exclude=['tests*'])\n", (230, 250), False, 'from setuptools import setup, find_packages\n')] |
#!/usr/bin/env python3
import intcode
def run_game():
grid = {}
computer = intcode.Computer(intcode.load_program("input"), intcode.BufferIOHandler())
computer.execute()
grid_data = computer.get_output()
for x, y, tile_id in (grid_data[i:i+3] for i in range(0, len(grid_data), 3)):
grid[(... | [
"intcode.BufferIOHandler",
"intcode.load_program"
] | [((104, 133), 'intcode.load_program', 'intcode.load_program', (['"""input"""'], {}), "('input')\n", (124, 133), False, 'import intcode\n'), ((135, 160), 'intcode.BufferIOHandler', 'intcode.BufferIOHandler', ([], {}), '()\n', (158, 160), False, 'import intcode\n')] |
from sklearn.metrics import mean_squared_error
import numpy as np
def mse(A, B):
return (np.square(A - B)).mean(axis=None)
from scipy.stats import spearmanr
def spearman_rank(A, B):
result = 0.0
for i in range(len(A)):
result += spearmanr(A[i], B[i], axis=None)[0]
return result / len(A) | [
"scipy.stats.spearmanr",
"numpy.square"
] | [((94, 110), 'numpy.square', 'np.square', (['(A - B)'], {}), '(A - B)\n', (103, 110), True, 'import numpy as np\n'), ((252, 284), 'scipy.stats.spearmanr', 'spearmanr', (['A[i]', 'B[i]'], {'axis': 'None'}), '(A[i], B[i], axis=None)\n', (261, 284), False, 'from scipy.stats import spearmanr\n')] |
#!/usr/bin/env python
# coding=utf-8
"""TrainingPreparator engine action.
Use this module to add the project main code.
"""
from .._compatibility import six
from .._logging import get_logger
from ..spark_serializer import SparkSerializer
from marvin_python_toolbox.engine_base import EngineBaseDataHandler
__all__ =... | [
"pyspark.ml.feature.VectorAssembler",
"pyspark.sql.types.DoubleType",
"pyspark.ml.feature.StringIndexer"
] | [((1506, 1625), 'pyspark.ml.feature.VectorAssembler', 'VectorAssembler', ([], {'inputCols': "['SepalLengthCm', 'SepalWidthCm', 'PetalLengthCm', 'PetalWidthCm']", 'outputCol': '"""features"""'}), "(inputCols=['SepalLengthCm', 'SepalWidthCm', 'PetalLengthCm',\n 'PetalWidthCm'], outputCol='features')\n", (1521, 1625), ... |
# -*- coding: UTF-8 -*-
import time
import datetime
import numpy as np
import sys
import os.path
import json
if sys.argv[1] == 'train':
root_loc = "trainProcessed/card_train_inverted_cleaned.txt"
feature_loc = "trainProcessed/CardProcessed.txt"
elif sys.argv[1] == 'test':
root_loc = "testProcessed... | [
"json.dumps",
"time.split"
] | [((3134, 3149), 'time.split', 'time.split', (['""" """'], {}), "(' ')\n", (3144, 3149), False, 'import time\n'), ((3171, 3186), 'time.split', 'time.split', (['""" """'], {}), "(' ')\n", (3181, 3186), False, 'import time\n'), ((6793, 6829), 'json.dumps', 'json.dumps', (['features'], {'sort_keys': '(True)'}), '(features,... |
def slt_workflow(slicetiming_txt="alt+z",SinkTag="func_preproc",wf_name="slicetiming_correction"):
"""
Modified version of porcupine generated slicetiming code:
`source: -`
Creates a slice time corrected functional image.
Workflow inputs:
:param func: The reoriented functional file.
... | [
"os.path.exists",
"os.makedirs",
"nipype.pipeline.Node",
"nipype.interfaces.afni.TShift",
"os.path.abspath",
"nipype.interfaces.utility.IdentityInterface",
"nipype.Workflow"
] | [((1048, 1098), 'os.path.abspath', 'os.path.abspath', (["(globals._SinkDir_ + '/' + SinkTag)"], {}), "(globals._SinkDir_ + '/' + SinkTag)\n", (1063, 1098), False, 'import os\n'), ((1683, 1729), 'nipype.pipeline.Node', 'pe.Node', ([], {'interface': 'info_get.TR', 'name': '"""TRvalue"""'}), "(interface=info_get.TR, name=... |
#!/usr/bin/env python3
# -*- coding: utf-8 -*-
"""
Created on Mon May 18 20:54:57 2020
@author: dkreitler
"""
import setuptools
with open("README.md", "r") as fh:
long_description = fh.read()
setuptools.setup(
name="mxscreen",
version="0.0.1dev",
author="<NAME>",
author_email="<EMAIL>",
des... | [
"setuptools.find_packages"
] | [((538, 564), 'setuptools.find_packages', 'setuptools.find_packages', ([], {}), '()\n', (562, 564), False, 'import setuptools\n')] |
#!/usr/bin/python3
from sys import exit as sys_exit
from subprocess import run
from subprocess import Popen
from pathlib import PurePath
from os import system
from signal import signal
from signal import SIGINT
from signal import SIGTERM
from time import sleep
# Local Imports
from python_logger import create_logger #... | [
"signal.signal",
"subprocess.Popen",
"subprocess.run",
"time.sleep",
"pathlib.PurePath",
"sys.exit",
"os.system"
] | [((775, 805), 'signal.signal', 'signal', (['SIGINT', 'stop_container'], {}), '(SIGINT, stop_container)\n', (781, 805), False, 'from signal import signal\n'), ((806, 837), 'signal.signal', 'signal', (['SIGTERM', 'stop_container'], {}), '(SIGTERM, stop_container)\n', (812, 837), False, 'from signal import signal\n'), ((7... |
# -*- coding: utf-8 -*-
"""
Created on Tue Dec 5 06:36:36 2017
@author: Salem
This script takes the resulting mesh and spring constants from the design process and tests it by applying forces and checking if the
desired mode comes out.
The energy used here does not assume linear displacements so we only expect agr... | [
"numpy.random.rand",
"numpy.average",
"numpy.sum",
"numpy.dot",
"LatticeMaking.get_complement_space",
"importlib.reload",
"numpy.linalg.eigh",
"Many_Triangles.wave_changer",
"LatticeMaking.get_rigid_transformations",
"LatticeMaking.makeDynamicalMat"
] | [((593, 613), 'importlib.reload', 'importlib.reload', (['LM'], {}), '(LM)\n', (609, 613), False, 'import importlib\n'), ((614, 634), 'importlib.reload', 'importlib.reload', (['MT'], {}), '(MT)\n', (630, 634), False, 'import importlib\n'), ((2833, 2901), 'numpy.sum', 'np.sum', (['((vertices[edges[:, 1]] - vertices[edges... |
import sys
cmd_folder = "../../../vis"
if cmd_folder not in sys.path:
sys.path.insert(0, cmd_folder)
from get_hdf5_data import ReadHDF5
import numpy as np
from scipy import fftpack
from scipy import signal
import pylab as plt
from matplotlib.image import NonUniformImage
from multiprocessing import Pool
#==... | [
"get_hdf5_data.ReadHDF5.get_files",
"sys.path.insert",
"numpy.sqrt",
"scipy.signal.welch",
"get_hdf5_data.ReadHDF5",
"numpy.argmax",
"pylab.close",
"pylab.figure",
"numpy.sum",
"numpy.zeros",
"pylab.colorbar",
"numpy.ravel"
] | [((617, 736), 'get_hdf5_data.ReadHDF5.get_files', 'ReadHDF5.get_files', (['"""."""'], {'include': '[plt_file]', 'exclude': "['temp', '.png', 'inputs']", 'times': '[]', 'tol': '(0.0001)', 'get_all': '(True)'}), "('.', include=[plt_file], exclude=['temp', '.png',\n 'inputs'], times=[], tol=0.0001, get_all=True)\n", (6... |
# -*- coding: utf-8 -*-
try:
import yaml
except ImportError:
pass
from layeredconfig import source
class YamlFile(source.Source):
"""Source for yaml files"""
def __init__(self, source, **kwargs):
try:
assert yaml
except NameError:
raise ImportError('You are m... | [
"yaml.load",
"yaml.dump"
] | [((555, 568), 'yaml.load', 'yaml.load', (['fh'], {}), '(fh)\n', (564, 568), False, 'import yaml\n'), ((654, 673), 'yaml.dump', 'yaml.dump', (['data', 'fh'], {}), '(data, fh)\n', (663, 673), False, 'import yaml\n')] |
from django.db import models
class Product(models.Model):
name = models.CharField(max_length=100)
brand = models.CharField(max_length=50)
price = models.DecimalField(max_digits=6, decimal_places=2)
quantity = models.IntegerField()
bar_code = models.IntegerField(unique=True)
def __str__(self):... | [
"django.db.models.DecimalField",
"django.db.models.CharField",
"django.db.models.IntegerField"
] | [((71, 103), 'django.db.models.CharField', 'models.CharField', ([], {'max_length': '(100)'}), '(max_length=100)\n', (87, 103), False, 'from django.db import models\n'), ((116, 147), 'django.db.models.CharField', 'models.CharField', ([], {'max_length': '(50)'}), '(max_length=50)\n', (132, 147), False, 'from django.db im... |
from event_manager import event_actions, event_subjects
from event_manager.event import Attribute, Event
CLUSTER_CREATED = '{}.{}'.format(event_subjects.CLUSTER, event_actions.CREATED)
CLUSTER_UPDATED = '{}.{}'.format(event_subjects.CLUSTER, event_actions.UPDATED)
CLUSTER_RESOURCES_UPDATED = '{}.resources_updated'.for... | [
"event_manager.event.Attribute"
] | [((778, 819), 'event_manager.event.Attribute', 'Attribute', (['"""created_at"""'], {'is_datetime': '(True)'}), "('created_at', is_datetime=True)\n", (787, 819), False, 'from event_manager.event import Attribute, Event\n'), ((829, 851), 'event_manager.event.Attribute', 'Attribute', (['"""namespace"""'], {}), "('namespac... |
# -*- coding: utf-8 -*-
from __future__ import absolute_import
import sys
#
# :::~ Copyright (C) 2005 by <NAME> <<EMAIL>>
#
# Created on: 09 Jan 2005
#
# Copyright: Distributed according to GNU/GPL Version 2
# (see http://www.gnu.org)
#
#
from builtins import map, object, range
from math import *
class S... | [
"sys.exit",
"builtins.map"
] | [((2318, 2341), 'builtins.map', 'map', (['eval', 'str_rest[1:]'], {}), '(eval, str_rest[1:])\n', (2321, 2341), False, 'from builtins import map, object, range\n'), ((5512, 5522), 'sys.exit', 'sys.exit', ([], {}), '()\n', (5520, 5522), False, 'import sys\n')] |
import pandas
import folium
folmap = folium.Map(location=[34.06112803699629, -118.24010772157081],zoom_start=3,tiles="Stamen Terrain")
fg = folium.FeatureGroup(name="COVID 19")
covid_url = "https://opendata.ecdc.europa.eu/covid19/casedistribution/csv"
data = pandas.read_csv(covid_url)
dateRep = list(data["dateRep"])... | [
"pandas.read_csv",
"folium.Icon",
"folium.LayerControl",
"folium.Map",
"folium.FeatureGroup"
] | [((37, 140), 'folium.Map', 'folium.Map', ([], {'location': '[34.06112803699629, -118.24010772157081]', 'zoom_start': '(3)', 'tiles': '"""Stamen Terrain"""'}), "(location=[34.06112803699629, -118.24010772157081], zoom_start=3,\n tiles='Stamen Terrain')\n", (47, 140), False, 'import folium\n'), ((140, 176), 'folium.Fe... |
import datetime
import os
from datetime import timedelta
import numpy
from esdl.cube_provider import NetCDFCubeSourceProvider
all_vars_descr = {'E': {
'evaporation': {
'source_name': 'E',
'data_type': numpy.float32,
'fill_value': numpy.nan,
'units': 'mm/day',
'long_name': ... | [
"datetime.datetime",
"os.listdir",
"os.path.join",
"numpy.rot90",
"datetime.timedelta",
"os.walk"
] | [((8232, 8254), 'os.walk', 'os.walk', (['self.dir_path'], {}), '(self.dir_path)\n', (8239, 8254), False, 'import os\n'), ((9837, 9865), 'numpy.rot90', 'numpy.rot90', (['source_image', '(3)'], {}), '(source_image, 3)\n', (9848, 9865), False, 'import numpy\n'), ((8473, 8509), 'os.path.join', 'os.path.join', (['self.dir_p... |
#!/usr/bin/env python
##########################################################################
# Copyright 2018 Kata.ai
#
# 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.ap... | [
"numpy.mean",
"argparse.ArgumentParser",
"math.floor",
"json.dumps",
"numpy.std",
"numpy.percentile"
] | [((1019, 1048), 'numpy.percentile', 'np.percentile', (['data', '(25, 75)'], {}), '(data, (25, 75))\n', (1032, 1048), True, 'import numpy as np\n'), ((2244, 2391), 'argparse.ArgumentParser', 'argparse.ArgumentParser', ([], {'description': '"""Preprocess outliers in a given JSONL file."""', 'formatter_class': 'argparse.A... |
# -*- coding: utf-8 -*-
##############################################################################
#
# OpenERP, Open Source Management Solution
# Copyright (C) 2004-2010 Tiny SPRL (<http://tiny.be>).
#
# This program is free software: you can redistribute it and/or modify
# it under the terms of the GNU... | [
"openerp.osv.fields.char",
"openerp.osv.fields.many2one",
"time.strftime",
"openerp.osv.fields.date",
"openerp.osv.fields.selection",
"openerp.tools.translate._"
] | [((1246, 1381), 'openerp.osv.fields.date', 'fields.date', (['"""Date"""'], {'help': '"""This date will be used as the invoice date for credit note and period will be chosen accordingly!"""'}), "('Date', help=\n 'This date will be used as the invoice date for credit note and period will be chosen accordingly!'\n )... |
import h5py
import random
import numpy as np
import pdb
import torch
class DataLoaderSimple(object):
"""
DataLoader class for abstracting the reading, batching and shuffling operations
Does not use expert rewards.
"""
def __init__(self, opts):
"""
Loads the dataset and saves settin... | [
"numpy.array",
"torch.load",
"random.shuffle",
"h5py.File"
] | [((605, 633), 'h5py.File', 'h5py.File', (['opts.h5_path', '"""r"""'], {}), "(opts.h5_path, 'r')\n", (614, 633), False, 'import h5py\n'), ((686, 717), 'numpy.array', 'np.array', (["self.h5_file['train']"], {}), "(self.h5_file['train'])\n", (694, 717), True, 'import numpy as np\n'), ((745, 774), 'numpy.array', 'np.array'... |
from glypy.structure.glycan_composition import FrozenMonosaccharideResidue
from glycan_profiling.database.glycan_composition_filter import GlycanCompositionFilter
_hexose = FrozenMonosaccharideResidue.from_iupac_lite("Hex")
_hexnac = FrozenMonosaccharideResidue.from_iupac_lite("HexNAc")
def composition_distance(c1,... | [
"glycan_profiling.database.glycan_composition_filter.GlycanCompositionFilter",
"glypy.structure.glycan_composition.FrozenMonosaccharideResidue.from_iupac_lite"
] | [((175, 225), 'glypy.structure.glycan_composition.FrozenMonosaccharideResidue.from_iupac_lite', 'FrozenMonosaccharideResidue.from_iupac_lite', (['"""Hex"""'], {}), "('Hex')\n", (218, 225), False, 'from glypy.structure.glycan_composition import FrozenMonosaccharideResidue\n'), ((236, 289), 'glypy.structure.glycan_compos... |
# Copyright (c) 2015 by California Institute of Technology
# All rights reserved.
#
# Redistribution and use in source and binary forms, with or without
# modification, are permitted provided that the following conditions
# are met:
#
# 1. Redistributions of source code must retain the above copyright
# notice, this... | [
"logging.getLogger",
"tulip.spec.translate",
"gr1py.solve.synthesize",
"tulip.interfaces.gr1c.load_aut_json",
"gr1py.solve.check_realizable",
"gr1py.output.dumps_json",
"tulip.interfaces.gr1c.select_options",
"gr1py.cli.loads"
] | [((1976, 2003), 'logging.getLogger', 'logging.getLogger', (['__name__'], {}), '(__name__)\n', (1993, 2003), False, 'import logging\n'), ((2255, 2275), 'tulip.interfaces.gr1c.select_options', 'select_options', (['spec'], {}), '(spec)\n', (2269, 2275), False, 'from tulip.interfaces.gr1c import select_options\n'), ((2328,... |
import numpy as np
import cv2
import os
import random
from skimage.transform import resize
from skimage.color import rgb2gray
import pickle
import tensorflow as tf
from keras.utils import np_utils
from PIL import Image
import threading
from concurrent.futures import ThreadPoolExecutor
#from flask import session
# imag... | [
"numpy.iinfo",
"numpy.array",
"numpy.linalg.norm",
"tensorflow.gfile.Exists",
"threading.Lock",
"numpy.asarray",
"numpy.max",
"numpy.concatenate",
"numpy.min",
"random.randint",
"numpy.arctan",
"numpy.random.normal",
"skimage.color.rgb2gray",
"cv2.warpAffine",
"random.shuffle",
"numpy.... | [((3485, 3520), 'tensorflow.gfile.Exists', 'tf.gfile.Exists', (['self.datalist_file'], {}), '(self.datalist_file)\n', (3500, 3520), True, 'import tensorflow as tf\n'), ((4351, 4367), 'threading.Lock', 'threading.Lock', ([], {}), '()\n', (4365, 4367), False, 'import threading\n'), ((6302, 6313), 'os.getcwd', 'os.getcwd'... |
# coding: utf-8
"""
metal-api
API to manage and control plane resources like machines, switches, operating system images, machine sizes, networks, IP addresses and more # noqa: E501
OpenAPI spec version: v0.15.7
Generated by: https://github.com/swagger-api/swagger-codegen.git
"""
import pprin... | [
"six.iteritems"
] | [((6916, 6949), 'six.iteritems', 'six.iteritems', (['self.swagger_types'], {}), '(self.swagger_types)\n', (6929, 6949), False, 'import six\n')] |
#!/usr/bin/env python3
from typing import Optional
import requests
def register_webhook_bot(charon_url: str, bot_api_key: Optional[str], auth_code: str) -> bool:
""""
Registers web hook bot in the charon. Returns True if the registration was success.
"""
payload = {
"bot_api_key": bot_api_key... | [
"requests.post"
] | [((400, 462), 'requests.post', 'requests.post', (['f"""{charon_url}/registration/hook"""'], {'json': 'payload'}), "(f'{charon_url}/registration/hook', json=payload)\n", (413, 462), False, 'import requests\n')] |
from pineapple_core.core.node import node, wrap
from pineapple_core.core.input_flags import Hidden
from pineapple_core.core.types import Any
from pineapple_core.core.node_output import NodeOutput
@node(module="Value", name="String", autotrigger=True)
def string_node(a: Hidden(str)) -> str:
return a
@node(module... | [
"pineapple_core.core.input_flags.Hidden",
"pineapple_core.core.node.node",
"pineapple_core.core.node.node.on.connect_input.add",
"pineapple_core.core.node.wrap",
"pineapple_core.core.types.Any",
"pineapple_core.core.node_output.NodeOutput"
] | [((199, 252), 'pineapple_core.core.node.node', 'node', ([], {'module': '"""Value"""', 'name': '"""String"""', 'autotrigger': '(True)'}), "(module='Value', name='String', autotrigger=True)\n", (203, 252), False, 'from pineapple_core.core.node import node, wrap\n'), ((309, 359), 'pineapple_core.core.node.node', 'node', (... |