code stringlengths 22 1.05M | apis listlengths 1 3.31k | extract_api stringlengths 75 3.25M |
|---|---|---|
#!/usr/bin/env python3
import json
file = '578.json'
data = json.load(open(file))
print(json.dumps(data, indent=4))
| [
"json.dumps"
] | [((96, 122), 'json.dumps', 'json.dumps', (['data'], {'indent': '(4)'}), '(data, indent=4)\n', (106, 122), False, 'import json\n')] |
import os
import time
import argparse
import torch
def get_options(args=None):
parser = argparse.ArgumentParser(description="Dual-Aspect Collaborative Transformer")
# Overall settings
parser.add_argument('--problem', default='tsp', choices = ['vrp', 'tsp'], help="the targeted problem to solve, defau... | [
"time.strftime",
"torch.cuda.is_available",
"argparse.ArgumentParser",
"torch.cuda.device_count"
] | [((99, 175), 'argparse.ArgumentParser', 'argparse.ArgumentParser', ([], {'description': '"""Dual-Aspect Collaborative Transformer"""'}), "(description='Dual-Aspect Collaborative Transformer')\n", (122, 175), False, 'import argparse\n'), ((5690, 5715), 'torch.cuda.device_count', 'torch.cuda.device_count', ([], {}), '()\... |
# Copyright (c) 2021 Graphcore Ltd. All rights reserved.
import popart
import pytest
import numpy as np
# `import test_util` requires adding to sys.path
import sys
from pathlib import Path
sys.path.append(str(Path(__file__).resolve().parent.parent))
import test_util as tu
@tu.requires_ipu_model
def test_2_restores_f... | [
"popart.ConstSGD",
"numpy.random.seed",
"numpy.allclose",
"popart.Builder",
"popart.AnchorReturnType",
"pytest.raises",
"test_util.create_test_device",
"pathlib.Path",
"popart.PyStepIO",
"numpy.random.rand",
"popart.SessionOptions"
] | [((887, 904), 'numpy.random.seed', 'np.random.seed', (['(2)'], {}), '(2)\n', (901, 904), True, 'import numpy as np\n'), ((2993, 3036), 'numpy.allclose', 'np.allclose', (['ref_weights', 'pipelined_weights'], {}), '(ref_weights, pipelined_weights)\n', (3004, 3036), True, 'import numpy as np\n'), ((3048, 3098), 'numpy.all... |
from frappe.model import table_fields
from graphql import GraphQLSchema, GraphQLResolveInfo, GraphQLObjectType
import frappe
def bind(schema: GraphQLSchema):
schema.mutation_type.fields["setValue"].resolve = set_value_resolver
# setting type resolver for Abstract type (interface)
SET_VALUE_TYPE: GraphQL... | [
"frappe.get_meta",
"frappe.parse_json",
"frappe.set_value",
"frappe.clear_document_cache",
"frappe.get_doc"
] | [((893, 979), 'frappe.set_value', 'frappe.set_value', ([], {'doctype': 'doctype', 'docname': 'name', 'fieldname': 'fieldname', 'value': 'value'}), '(doctype=doctype, docname=name, fieldname=fieldname, value=\n value)\n', (909, 979), False, 'import frappe\n'), ((1012, 1054), 'frappe.clear_document_cache', 'frappe.cle... |
import pytest
from dewar import dewar
@pytest.fixture(autouse=True, scope='function')
def site_cleanup():
yield
if hasattr(dewar, '_site_instances'):
del dewar._site_instances
| [
"pytest.fixture"
] | [((42, 88), 'pytest.fixture', 'pytest.fixture', ([], {'autouse': '(True)', 'scope': '"""function"""'}), "(autouse=True, scope='function')\n", (56, 88), False, 'import pytest\n')] |
from __future__ import absolute_import
from jinja2 import nodes
from jinja2.ext import Extension
from csp.utils import SCRIPT_ATTRS, build_script_tag
class NoncedScript(Extension):
# a set of names that trigger the extension.
tags = set(['script'])
def parse(self, parser):
# the first token is ... | [
"csp.utils.build_script_tag",
"jinja2.nodes.ContextReference"
] | [((1748, 1774), 'csp.utils.build_script_tag', 'build_script_tag', ([], {}), '(**kwargs)\n', (1764, 1774), False, 'from csp.utils import SCRIPT_ATTRS, build_script_tag\n'), ((705, 729), 'jinja2.nodes.ContextReference', 'nodes.ContextReference', ([], {}), '()\n', (727, 729), False, 'from jinja2 import nodes\n')] |
from functools import wraps
from silence.exceptions import HTTPError, DatabaseError
import re
regex_error_str = re.compile(r"""\(.*?, ['"](.*)['"]\)""")
# Wraps a DB query/update call to catch any possible DatabaseErrors
# and wrap them inside a HTTPError
def db_call(func):
@wraps(func)
def wrapper(*args, **... | [
"silence.exceptions.HTTPError",
"functools.wraps",
"re.compile"
] | [((114, 153), 're.compile', 're.compile', (['"""\\\\(.*?, [\'"](.*)[\'"]\\\\)"""'], {}), '(\'\\\\(.*?, [\\\'"](.*)[\\\'"]\\\\)\')\n', (124, 153), False, 'import re\n'), ((283, 294), 'functools.wraps', 'wraps', (['func'], {}), '(func)\n', (288, 294), False, 'from functools import wraps\n'), ((619, 639), 'silence.excepti... |
"""
Module for guiding Arc/Sky line tracing
.. _numpy.ndarray: https://docs.scipy.org/doc/numpy/reference/generated/numpy.ndarray.html
"""
import os
import copy
import inspect
import numpy as np
from astropy.io import fits
from pypeit import msgs
from pypeit import masterframe
from pypeit import ginga
from pypeit.... | [
"numpy.invert",
"astropy.io.fits.PrimaryHDU",
"pypeit.core.tracewave.fit2tilts",
"os.path.isfile",
"astropy.io.fits.Header",
"pypeit.msgs.warn",
"pypeit.core.pixels.tslits2mask",
"pypeit.core.arc.get_censpec",
"pypeit.msgs.info",
"astropy.io.fits.ImageHDU",
"pypeit.core.arc.resize_mask2arc",
"... | [((2420, 2556), 'pypeit.masterframe.MasterFrame.__init__', 'masterframe.MasterFrame.__init__', (['self', 'self.master_type'], {'master_dir': 'master_dir', 'master_key': 'master_key', 'reuse_masters': 'reuse_masters'}), '(self, self.master_type, master_dir=\n master_dir, master_key=master_key, reuse_masters=reuse_mas... |
from unittest import TestCase, mock
from unittest.mock import MagicMock, call
from datetime import datetime
from py_eve_chat_mon.chat_message import parse_msg, EveChatLogReader
MESSAGE_SINGLE_LINE = "[ 2015.03.05 21:04:03 ] Some Dude > MSG"
MESSAGE_MULTI_LINE = "[ 2015.03.05 21:04:03 ] Some Dude > MSG\nON NEXT LINE\nA... | [
"py_eve_chat_mon.chat_message.EveChatLogReader",
"py_eve_chat_mon.chat_message.EveChatLogReader.chat_line_delimiter.join",
"unittest.mock.MagicMock",
"py_eve_chat_mon.chat_message.parse_msg",
"unittest.mock.patch",
"datetime.datetime",
"unittest.mock.call"
] | [((463, 579), 'py_eve_chat_mon.chat_message.EveChatLogReader.chat_line_delimiter.join', 'EveChatLogReader.chat_line_delimiter.join', (["['[ 2015.03.05 21:04:03 ] Some Dude > MSG ', ' middle ', ' end msg']"], {}), "([\n '[ 2015.03.05 21:04:03 ] Some Dude > MSG ', ' middle ', ' end msg'])\n", (504, 579), False, 'from ... |
import glob, os, sys, math, time, pyperclip, fileinput, re
def clear():
if os.name == 'nt':
os.system('cls')
else:
os.system('clear')
#This was from somewhere on StackExchange...
def list_columns(obj, cols=4, columnwise=True, gap=4):
"""
Print the given list in evenly-spaced col... | [
"fileinput.input",
"os.path.dirname",
"fileinput.close",
"os.system",
"time.sleep",
"re.sub",
"pyperclip.copy",
"glob.glob",
"os.path.join",
"os.listdir",
"sys.exit"
] | [((1861, 1889), 'os.listdir', 'os.listdir', (['"""NeuralNetworks"""'], {}), "('NeuralNetworks')\n", (1871, 1889), False, 'import glob, os, sys, math, time, pyperclip, fileinput, re\n'), ((1906, 1934), 'os.listdir', 'os.listdir', (['"""NeuralNetworks"""'], {}), "('NeuralNetworks')\n", (1916, 1934), False, 'import glob, ... |
## @package libgsidem2el 地理院標高タイルから標高値を取得するライブラリ
# @brief 地理院標高タイルから標高値を取得するライブラリ
# 地図の種類はDEM5A,DEM5B,DEM10B,DEMGMの4種類が選択可能 https://maps.gsi.go.jp/help/pdf/demapi.pdf参照
# zoom levelは,DEM5A,B:15, DEM10B:0-14, DEMGM:0-8
# getELメソッドで取得,DEM5AB,10Bは[m],DEMGMは[cm]の標高値を返す.
# それぞれの地図の対象範囲外は'outside'を返す
# 水面等により欠測の場合は,'e'を返す(地... | [
"pandas.read_csv",
"numpy.sin"
] | [((1769, 1798), 'pandas.read_csv', 'pd.read_csv', (['url'], {'header': 'None'}), '(url, header=None)\n', (1780, 1798), True, 'import pandas as pd\n'), ((1251, 1276), 'numpy.sin', 'np.sin', (['(np.pi / 180.0 * L)'], {}), '(np.pi / 180.0 * L)\n', (1257, 1276), True, 'import numpy as np\n'), ((1213, 1240), 'numpy.sin', 'n... |
from typing import Callable, Generic, List, Optional, Sequence, TypeVar, cast
S = TypeVar("S")
T = TypeVar("T")
class Promise(Generic[T]):
"""
A light-weight single-thread implementation of Promise.
We specifically are careful to remove references as soon as possible to
enable garbage collection.
... | [
"typing.cast",
"typing.TypeVar"
] | [((83, 95), 'typing.TypeVar', 'TypeVar', (['"""S"""'], {}), "('S')\n", (90, 95), False, 'from typing import Callable, Generic, List, Optional, Sequence, TypeVar, cast\n'), ((100, 112), 'typing.TypeVar', 'TypeVar', (['"""T"""'], {}), "('T')\n", (107, 112), False, 'from typing import Callable, Generic, List, Optional, Se... |
#!/usr/bin/env python
"""
This is free and unencumbered software released into the public domain.
Anyone is free to copy, modify, publish, use, compile, sell, or
distribute this software, either in source code form or as a compiled
binary, for any purpose, commercial or non-commercial, and by any
means.
In jurisdict... | [
"os.mkdir",
"itertools.repeat",
"os.getcwd",
"os.path.exists",
"os.environ.get",
"os.path.splitext",
"multiprocessing.Pool",
"os.path.join",
"sys.exit",
"multiprocessing.cpu_count"
] | [((1619, 1651), 'os.environ.get', 'os.environ.get', (['"""MCELL_PATH"""', '""""""'], {}), "('MCELL_PATH', '')\n", (1633, 1651), False, 'import os\n'), ((2936, 2977), 'multiprocessing.Pool', 'multiprocessing.Pool', ([], {'processes': 'cpu_count'}), '(processes=cpu_count)\n', (2956, 2977), False, 'import multiprocessing\... |
"""
Main module
Script to pull down the aaindex1 file from ftp://ftp.genome.jp/pub/db/community/aaindex/
"""
import shutil
import urllib.request as request
from contextlib import closing
import time
class FtpGetFeatures:
def __init__(self, base_url):
self.base_url = base_url
with closing(request.... | [
"shutil.copyfileobj",
"urllib.request.urlopen",
"time.sleep"
] | [((530, 544), 'time.sleep', 'time.sleep', (['(10)'], {}), '(10)\n', (540, 544), False, 'import time\n'), ((312, 342), 'urllib.request.urlopen', 'request.urlopen', (['self.base_url'], {}), '(self.base_url)\n', (327, 342), True, 'import urllib.request as request\n'), ((412, 436), 'shutil.copyfileobj', 'shutil.copyfileobj... |
import pandas as pd
import numpy as np
import os
import keras
from sklearn.model_selection import train_test_split
from keras.models import load_model, Sequential
model = Sequential()
model_path = os.path.join(os.getcwd(),'convmodel.h5')
model = load_model(model_path)
test_data = pd.read_csv('test.csv').astype('float32... | [
"keras.models.load_model",
"pandas.DataFrame",
"numpy.argmax",
"os.getcwd",
"pandas.read_csv",
"keras.models.Sequential"
] | [((171, 183), 'keras.models.Sequential', 'Sequential', ([], {}), '()\n', (181, 183), False, 'from keras.models import load_model, Sequential\n'), ((246, 268), 'keras.models.load_model', 'load_model', (['model_path'], {}), '(model_path)\n', (256, 268), False, 'from keras.models import load_model, Sequential\n'), ((477, ... |
from celery import Celery
app = Celery("api")
app.config_from_object("django.conf:settings", namespace="CELERY")
app.autodiscover_tasks()
| [
"celery.Celery"
] | [((34, 47), 'celery.Celery', 'Celery', (['"""api"""'], {}), "('api')\n", (40, 47), False, 'from celery import Celery\n')] |
import sys
import cv2
import numpy as np
from .detect_reso_chart import detect_reso_chart
from .compute_mtf import compute_mtf
def reso_meas(images, verbose=False):
""" measure the resolution from multiple photos of resolution test chart
STEP1: Extract edge images from photos.
STEP2: Estimate MTF ... | [
"cv2.imread",
"numpy.mean",
"sys.exit"
] | [((1063, 1126), 'sys.exit', 'sys.exit', (['"""[ERROR]: no valid image for resolution measurement!"""'], {}), "('[ERROR]: no valid image for resolution measurement!')\n", (1071, 1126), False, 'import sys\n'), ((1218, 1263), 'numpy.mean', 'np.mean', (['[mtf[1] for mtf in mtf_list]'], {'axis': '(0)'}), '([mtf[1] for mtf i... |
import json
import os
from elasticsearch import Elasticsearch, helpers
BASE_DIR = os.path.dirname(os.path.dirname(os.path.abspath(__file__)))
es = Elasticsearch([{"host": "es-smartparking", "port": 9200, "timeout": 60}])
default_settings = {
"index": {
"number_of_shards": 1,
"number_of_replicas"... | [
"elasticsearch.Elasticsearch",
"os.path.abspath",
"json.load",
"elasticsearch.helpers.bulk",
"os.path.join"
] | [((150, 223), 'elasticsearch.Elasticsearch', 'Elasticsearch', (["[{'host': 'es-smartparking', 'port': 9200, 'timeout': 60}]"], {}), "([{'host': 'es-smartparking', 'port': 9200, 'timeout': 60}])\n", (163, 223), False, 'from elasticsearch import Elasticsearch, helpers\n'), ((116, 141), 'os.path.abspath', 'os.path.abspath... |
# -*- coding: utf-8 -*-
import re
import scrapy
from locations.items import GeojsonPointItem
from locations.hours import OpeningHours
class TwoMenAndATruckSpider(scrapy.Spider):
name = "two_men_and_truck"
item_attributes = {"brand": "Two Men and a Truck"}
allowed_domains = ["twomenandatruck.com", "twome... | [
"locations.items.GeojsonPointItem",
"scrapy.Request"
] | [((552, 596), 'scrapy.Request', 'scrapy.Request', ([], {'url': 'url', 'callback': 'self.parse'}), '(url=url, callback=self.parse)\n', (566, 596), False, 'import scrapy\n'), ((1333, 1363), 'locations.items.GeojsonPointItem', 'GeojsonPointItem', ([], {}), '(**properties)\n', (1349, 1363), False, 'from locations.items imp... |
import os
import sys
import fileinput
import subprocess
from multiprocessing import Pool
NCORES = int(os.environ['SLURM_CPUS_PER_TASK'])
cmd_tmpl = "lasindex -i {}"
def work(laz):
laz = laz.rstrip()
cmd = cmd_tmpl.format(laz)
p = subprocess.run(cmd, shell=True, capture_output=True)
if p.returncode != 0:... | [
"fileinput.input",
"subprocess.run",
"multiprocessing.Pool"
] | [((372, 384), 'multiprocessing.Pool', 'Pool', (['NCORES'], {}), '(NCORES)\n', (376, 384), False, 'from multiprocessing import Pool\n'), ((393, 410), 'fileinput.input', 'fileinput.input', ([], {}), '()\n', (408, 410), False, 'import fileinput\n'), ((243, 295), 'subprocess.run', 'subprocess.run', (['cmd'], {'shell': '(Tr... |
"""
Description
Turn the PowerSwith Tail II on and off and communicate it's status over
the websocet connection
"""
import time
import threading
import websocket
import RPi.GPIO as GPIO
try:
import simplejson as json
except ImportError:
import json
GPIO.setwarnings(False)
GPIO.setmode(GPIO.BCM)
OUT... | [
"websocket.WebSocketApp",
"threading.Thread",
"RPi.GPIO.setmode",
"RPi.GPIO.setup",
"json.dumps",
"time.sleep",
"RPi.GPIO.output",
"RPi.GPIO.setwarnings"
] | [((269, 292), 'RPi.GPIO.setwarnings', 'GPIO.setwarnings', (['(False)'], {}), '(False)\n', (285, 292), True, 'import RPi.GPIO as GPIO\n'), ((293, 315), 'RPi.GPIO.setmode', 'GPIO.setmode', (['GPIO.BCM'], {}), '(GPIO.BCM)\n', (305, 315), True, 'import RPi.GPIO as GPIO\n'), ((421, 446), 'RPi.GPIO.setup', 'GPIO.setup', (['k... |
# test_model.py
import numpy as np
import cv2
import time
import os
from grabscreen import grab_screen
from directkeys import PressKey, ReleaseKey, DirectionKey as dk
from alexnet import alexnet
from getkeys import key_check
cwd = os.getcwd()
for file_name in os.listdir(cwd):
if file_name.startswith('Osori-SelfD... | [
"alexnet.alexnet",
"numpy.argmax",
"os.getcwd",
"cv2.cvtColor",
"cv2.destroyAllWindows",
"cv2.waitKey",
"directkeys.ReleaseKey",
"time.sleep",
"directkeys.PressKey",
"time.time",
"grabscreen.grab_screen",
"getkeys.key_check",
"cv2.imshow",
"os.listdir",
"cv2.resize"
] | [((234, 245), 'os.getcwd', 'os.getcwd', ([], {}), '()\n', (243, 245), False, 'import os\n'), ((263, 278), 'os.listdir', 'os.listdir', (['cwd'], {}), '(cwd)\n', (273, 278), False, 'import os\n'), ((849, 886), 'alexnet.alexnet', 'alexnet', (['WIDTH', 'HEIGHT', 'LEARNING_RATE'], {}), '(WIDTH, HEIGHT, LEARNING_RATE)\n', (8... |
import cv2
import time
import imutils
import argparse
import numpy as np
import logging
from imutils.video import FPS
from imutils.video import VideoStream
logging.basicConfig(level=logging.INFO,
format='%(asctime)s :: %(levelname)s :: %(message)s')
#Constructing Argument Parse to inpu... | [
"imutils.video.VideoStream",
"imutils.video.FPS",
"cv2.putText",
"argparse.ArgumentParser",
"logging.basicConfig",
"cv2.waitKey",
"cv2.imshow",
"time.sleep",
"cv2.rectangle",
"numpy.arange",
"numpy.array",
"cv2.dnn.readNetFromCaffe",
"imutils.resize",
"cv2.destroyAllWindows",
"cv2.resize... | [((166, 264), 'logging.basicConfig', 'logging.basicConfig', ([], {'level': 'logging.INFO', 'format': '"""%(asctime)s :: %(levelname)s :: %(message)s"""'}), "(level=logging.INFO, format=\n '%(asctime)s :: %(levelname)s :: %(message)s')\n", (185, 264), False, 'import logging\n'), ((346, 371), 'argparse.ArgumentParser'... |
import unittest
import model_obj
from model_obj.dimensions import DimInch, DimMillimeter
oneInch = DimInch(1)
twoInches = DimInch(2)
oneMillimeter = DimMillimeter(1)
twoMillimeters = DimMillimeter(2)
class TestDivision(unittest.TestCase):
def test_division_scalar(self):
val = oneInch / 2
expect... | [
"unittest.main",
"model_obj.dimensions.DimMillimeter",
"model_obj.dimensions.DimInch"
] | [((101, 111), 'model_obj.dimensions.DimInch', 'DimInch', (['(1)'], {}), '(1)\n', (108, 111), False, 'from model_obj.dimensions import DimInch, DimMillimeter\n'), ((124, 134), 'model_obj.dimensions.DimInch', 'DimInch', (['(2)'], {}), '(2)\n', (131, 134), False, 'from model_obj.dimensions import DimInch, DimMillimeter\n'... |
import time
timestr = time.strftime("%Y%m%d-%H%M%S")
print(timestr)
if True:
dim = 299
else:
dim = 224
print(dim) | [
"time.strftime"
] | [((22, 52), 'time.strftime', 'time.strftime', (['"""%Y%m%d-%H%M%S"""'], {}), "('%Y%m%d-%H%M%S')\n", (35, 52), False, 'import time\n')] |
from lemoncheesecake.events import AsyncEventManager, SyncEventManager, Event
class MyEvent(Event):
def __init__(self, val):
super(MyEvent, self).__init__()
self.val = val
def test_async_fire():
i_got_called = []
def handler(event):
i_got_called.append(event.val)
eventmgr = A... | [
"lemoncheesecake.events.SyncEventManager",
"lemoncheesecake.events.AsyncEventManager"
] | [((319, 338), 'lemoncheesecake.events.AsyncEventManager', 'AsyncEventManager', ([], {}), '()\n', (336, 338), False, 'from lemoncheesecake.events import AsyncEventManager, SyncEventManager, Event\n'), ((644, 662), 'lemoncheesecake.events.SyncEventManager', 'SyncEventManager', ([], {}), '()\n', (660, 662), False, 'from l... |
# Copyright 2020 <NAME>
from kubism.util import greek
from kubism.util.psql import DB
DEBUG = False
class State:
t_idx = 0
def __init__(self):
self.remote = DB()
self.connect_to_remote()
def connect_to_remote(self):
if not self.remote_connected:
self.remot... | [
"kubism.util.psql.DB"
] | [((187, 191), 'kubism.util.psql.DB', 'DB', ([], {}), '()\n', (189, 191), False, 'from kubism.util.psql import DB\n')] |
# -*- coding: utf-8 -*-
# Copyright 2021 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
#
# https://www.apache.org/licenses/LICENSE-2.0
#
# Unless required by applicable law ... | [
"logging.warning",
"threading.Thread",
"google.cloud.aiplatform.training_utils.cloud_profiler.webserver.WebServer"
] | [((2260, 2363), 'threading.Thread', 'threading.Thread', ([], {'name': '"""profile_server"""', 'target': 'serving.run_simple', 'args': "('0.0.0.0', port, server)"}), "(name='profile_server', target=serving.run_simple, args=(\n '0.0.0.0', port, server))\n", (2276, 2363), False, 'import threading\n'), ((3187, 3221), 'g... |
import json
import ratelimiter
from lru import LRU
from src.integration.mapbox_client import mapbox_geocode
class Geocoder:
Country = 'Country'
Admin3 = 'Admin3'
Admin2 = 'Admin2'
Admin1 = 'Admin1'
Point = 'Point'
def __init__(self, api_token, admins_fetcher, rate_limit=600):
"""Needs... | [
"lru.LRU",
"src.integration.mapbox_client.mapbox_geocode",
"ratelimiter.RateLimiter"
] | [((370, 426), 'ratelimiter.RateLimiter', 'ratelimiter.RateLimiter', ([], {'max_calls': 'rate_limit', 'period': '(60)'}), '(max_calls=rate_limit, period=60)\n', (393, 426), False, 'import ratelimiter\n'), ((483, 491), 'lru.LRU', 'LRU', (['(500)'], {}), '(500)\n', (486, 491), False, 'from lru import LRU\n'), ((2850, 2979... |
import cv2
import glob
import h5py
import imageio
import numpy as np
import os
import matplotlib.pylab as plt
from keras.datasets import mnist
from keras.preprocessing.image import ImageDataGenerator
from keras.utils import np_utils
def normalization(X):
return X / 127.5 - 1
def inverse_normalization(X):
... | [
"keras.preprocessing.image.ImageDataGenerator",
"os.walk",
"numpy.random.randint",
"numpy.arange",
"numpy.random.normal",
"matplotlib.pylab.close",
"matplotlib.pylab.title",
"os.path.join",
"numpy.round",
"matplotlib.pylab.figure",
"matplotlib.pylab.legend",
"keras.utils.np_utils.to_categorica... | [((455, 472), 'keras.datasets.mnist.load_data', 'mnist.load_data', ([], {}), '()\n', (470, 472), False, 'from keras.datasets import mnist\n'), ((1006, 1050), 'keras.utils.np_utils.to_categorical', 'np_utils.to_categorical', (['y_train', 'nb_classes'], {}), '(y_train, nb_classes)\n', (1029, 1050), False, 'from keras.uti... |
from bisect import bisect_left, bisect_right
from operator import add
from lhc.interval import Interval
from functools import reduce
class TrackedIndex(object):
def __init__(self, n):
self.n = n
self.tracks = [Track(n)]
def add(self, item, offset):
cost_increases = [(track.get_cost_in... | [
"bisect.bisect_right",
"json.dump",
"json.load",
"bisect.bisect_left"
] | [((2577, 2746), 'json.dump', 'json.dump', (["{'n': index.n, 'tracks': [{'n': track.n, 'starts': track.starts, 'stops':\n track.stops, 'offsets': track.offsets} for track in index.tracks]}", 'fileobj'], {}), "({'n': index.n, 'tracks': [{'n': track.n, 'starts': track.starts,\n 'stops': track.stops, 'offsets': track... |
#!/usr/bin/python
# -*- coding: UTF-8 -*-
import logging
import platform
import subprocess
import configloader
import gnupg
from db_transfer import MySqlWrapper
db_instance = None
webapi = None
class AutoExec(object):
def __init__(self):
import threading
self.event = threading.Event()
... | [
"gnupg.GPG",
"logging.error",
"webapi_utils.WebApi",
"logging.info",
"db_transfer.MySqlWrapper",
"threading.Event",
"traceback.format_exc",
"platform.system",
"configloader.get_config"
] | [((293, 310), 'threading.Event', 'threading.Event', ([], {}), '()\n', (308, 310), False, 'import threading\n'), ((331, 356), 'gnupg.GPG', 'gnupg.GPG', (['"""/tmp/ssshell"""'], {}), "('/tmp/ssshell')\n", (340, 356), False, 'import gnupg\n'), ((1534, 1548), 'db_transfer.MySqlWrapper', 'MySqlWrapper', ([], {}), '()\n', (1... |
from typing import Callable, List, Optional
from pydantic.class_validators import root_validator
from pydantic.fields import Field
from hydrolib.core.basemodel import BaseModel, FileModel
from hydrolib.core.io.base import DummmyParser, DummySerializer
from hydrolib.core.io.net.models import Network
from hydrolib.core... | [
"pydantic.fields.Field",
"pydantic.class_validators.root_validator",
"hydrolib.core.io.rr.topology.parser.NetworkTopologyFileParser"
] | [((860, 877), 'pydantic.fields.Field', 'Field', ([], {'alias': '"""id"""'}), "(alias='id')\n", (865, 877), False, 'from pydantic.fields import Field\n'), ((904, 921), 'pydantic.fields.Field', 'Field', ([], {'alias': '"""nm"""'}), "(alias='nm')\n", (909, 921), False, 'from pydantic.fields import Field\n'), ((942, 959), ... |
__author__ = '<NAME>'
import pymc
import numpy as np
from simtk.unit import kilojoules_per_mole
import torsionfit.database.qmdatabase as TorsionScan
import torsionfit.parameters as par
import warnings
from torsionfit.utils import logger
class TorsionFitModel(object):
"""pymc model
This model only allows a p... | [
"torsionfit.parameters.set_phase_0",
"numpy.log",
"pymc.Uniform",
"torsionfit.utils.logger",
"torsionfit.parameters.add_missing",
"torsionfit.parameters.update_param_from_sample",
"numpy.append",
"numpy.exp",
"pymc.Normal",
"warnings.warn",
"torsionfit.database.qmdatabase.to_optimize",
"pymc.D... | [((8975, 9052), 'torsionfit.parameters.add_missing', 'par.add_missing', (['self.parameters_to_optimize', 'param'], {'sample_n5': 'self.sample_n5'}), '(self.parameters_to_optimize, param, sample_n5=self.sample_n5)\n', (8990, 9052), True, 'import torsionfit.parameters as par\n'), ((9850, 9863), 'numpy.ndarray', 'np.ndarr... |
"""This is a helper file to auto-generate the sample
READMEs page for the mybinder documentation. It expects
a couple of environment variables to be set corresponding
to your github username / password, or to an access token
you've created (see below for the proper variable names).
The script grabs some metadata and t... | [
"os.path.abspath",
"os.path.join",
"tqdm.tqdm",
"github.Github"
] | [((679, 704), 'os.path.abspath', 'os.path.abspath', (['__file__'], {}), '(__file__)\n', (694, 704), False, 'import os\n'), ((754, 822), 'github.Github', 'Github', (["os.environ['GITHUB_USERNAME']", "os.environ['GITHUB_PASSWORD']"], {}), "(os.environ['GITHUB_USERNAME'], os.environ['GITHUB_PASSWORD'])\n", (760, 822), Fal... |
"""Common imports for generated toolresults client library."""
# pylint:disable=wildcard-import
import pkgutil
from googlecloudsdk.third_party.apitools.base.py import *
from googlecloudsdk.third_party.apis.toolresults.v1beta3.toolresults_v1beta3_client import *
from googlecloudsdk.third_party.apis.toolresults.v1beta3... | [
"pkgutil.extend_path"
] | [((371, 410), 'pkgutil.extend_path', 'pkgutil.extend_path', (['__path__', '__name__'], {}), '(__path__, __name__)\n', (390, 410), False, 'import pkgutil\n')] |
from matplotlib import pyplot as plt
from autolens.data.array.plotters import plotter_util, grid_plotters, array_plotters
def plot_image_plane_image(
plane, mask=None, extract_array_from_mask=False, zoom_around_mask=False, positions=None, grid=None,
as_subplot=False,
units='arcsec', figsize=(... | [
"autolens.data.array.plotters.grid_plotters.plot_grid",
"matplotlib.pyplot.subplot",
"autolens.data.array.plotters.plotter_util.output_subplot_array",
"matplotlib.pyplot.close",
"autolens.data.array.plotters.array_plotters.plot_array",
"matplotlib.pyplot.figure",
"autolens.data.array.plotters.plotter_ut... | [((758, 1557), 'autolens.data.array.plotters.array_plotters.plot_array', 'array_plotters.plot_array', ([], {'array': 'plane.image_plane_image', 'mask': 'mask', 'extract_array_from_mask': 'extract_array_from_mask', 'zoom_around_mask': 'zoom_around_mask', 'positions': 'positions', 'grid': 'grid', 'as_subplot': 'as_subplo... |
from django.shortcuts import render
from django.views.generic import TemplateView,View, FormView
from django.shortcuts import redirect
from django.contrib.auth.mixins import LoginRequiredMixin
from django.contrib.auth.models import User
from .forms import SocialAuthForm
from django.urls import reverse_lazy, reverse
fro... | [
"myapp.email.SendEmail.send",
"django.http.HttpResponse",
"django.contrib.auth.models.User.objects.get",
"social_django.models.UserSocialAuth.objects.get",
"django.urls.reverse",
"rest_framework.response.Response",
"requests.post",
"social_django.models.UserSocialAuth.objects.filter"
] | [((1311, 1336), 'myapp.email.SendEmail.send', 'SendEmail.send', (['emailData'], {}), '(emailData)\n', (1325, 1336), False, 'from myapp.email import SendEmail\n'), ((1353, 1388), 'django.http.HttpResponse', 'HttpResponse', (['challenge'], {'status': '(200)'}), '(challenge, status=200)\n', (1365, 1388), False, 'from djan... |
import NameMarkupLanguage as NML
def main():
listNameMark = NML.load('C:\\Users\\DEV-C2-2\\XuCompa\\XRequest\\Request')
nml = listNameMark[0]
nml.setCategory("Hello")
nml.commit()
mng = nml.defManager()
new = NML.NameMark()
new.setPath("C:\\Users\\DEV-C2-2\\XuCompa\\XRequest\\Request\\tes... | [
"NameMarkupLanguage.NameMark",
"NameMarkupLanguage.load"
] | [((66, 125), 'NameMarkupLanguage.load', 'NML.load', (['"""C:\\\\Users\\\\DEV-C2-2\\\\XuCompa\\\\XRequest\\\\Request"""'], {}), "('C:\\\\Users\\\\DEV-C2-2\\\\XuCompa\\\\XRequest\\\\Request')\n", (74, 125), True, 'import NameMarkupLanguage as NML\n'), ((236, 250), 'NameMarkupLanguage.NameMark', 'NML.NameMark', ([], {}), ... |
#!/usr/bin/env python
import rospy
import std_srvs
from std_srvs import srv
from easy_handeye.handeye_client import HandeyeClient
# for reading single character without hitting RETURN (unless it's ipython!)
def getchar():
import sys, tty, termios
fd = sys.stdin.fileno()
old_settings = termios.tcgetattr(f... | [
"rospy.get_namespace",
"sys.stdin.read",
"termios.tcgetattr",
"termios.tcsetattr",
"rospy.is_shutdown",
"rospy.init_node",
"sys.stdin.fileno",
"easy_handeye.handeye_client.HandeyeClient",
"rospy.get_time"
] | [((263, 281), 'sys.stdin.fileno', 'sys.stdin.fileno', ([], {}), '()\n', (279, 281), False, 'import sys, tty, termios\n'), ((301, 322), 'termios.tcgetattr', 'termios.tcgetattr', (['fd'], {}), '(fd)\n', (318, 322), False, 'import sys, tty, termios\n'), ((2363, 2394), 'rospy.init_node', 'rospy.init_node', (['"""easy_hande... |
from numpy import random
from RandomGenerator.randomDecimal import random_decimal
def random_decimal_seeded(start, end, seed):
state = random.get_state()
random.seed(seed)
try:
rand_decimal_seeded = random_decimal(start, end)
return rand_decimal_seeded
finally:
random.set_state... | [
"numpy.random.get_state",
"RandomGenerator.randomDecimal.random_decimal",
"numpy.random.seed",
"numpy.random.set_state"
] | [((141, 159), 'numpy.random.get_state', 'random.get_state', ([], {}), '()\n', (157, 159), False, 'from numpy import random\n'), ((164, 181), 'numpy.random.seed', 'random.seed', (['seed'], {}), '(seed)\n', (175, 181), False, 'from numpy import random\n'), ((221, 247), 'RandomGenerator.randomDecimal.random_decimal', 'ran... |
"""
RGB Driver
"""
import logging
from .utils import set_bit, unset_bit
from . import STATUS_OK
RGB_COLOR_OFF = "Off"
RGB_COLOR_RED = "Red"
RGB_COLOR_BLUE = "Blue"
RGB_COLOR_GREEN = "Green"
RGB_COLOR_YELLOW = "Yellow"
RGB_COLOR_PURPLE = "Purple"
RGB_COLOR_CYAN = "Cyan"
RGB_COLOR_WHITE = "White"
COLOR_LIST = {
RGB_... | [
"logging.info"
] | [((2311, 2356), 'logging.info', 'logging.info', (['"""Initializing RGBDriver Module"""'], {}), "('Initializing RGBDriver Module')\n", (2323, 2356), False, 'import logging\n'), ((2736, 2776), 'logging.info', 'logging.info', (['"""Closing RGBDriver Module"""'], {}), "('Closing RGBDriver Module')\n", (2748, 2776), False, ... |
#!/usr/bin/env python3
# coding: utf8
"""
Keras model for training using a mask based appoach.
"""
from keras.layers import Dropout, Conv2D, MaxPooling2D, Flatten, Dense, LeakyReLU, Reshape, Input, ReLU, Activation, BatchNormalization, LSTM
from keras.models import Sequential, Model
from keras.activations import sig... | [
"keras.layers.LeakyReLU",
"unmix.source.configuration.Configuration.get",
"keras.layers.LSTM",
"keras.layers.Dense",
"keras.models.Sequential",
"keras.layers.Reshape"
] | [((562, 621), 'unmix.source.configuration.Configuration.get', 'Configuration.get', (['"""transformation.options"""'], {'optional': '(False)'}), "('transformation.options', optional=False)\n", (579, 621), False, 'from unmix.source.configuration import Configuration\n'), ((692, 704), 'keras.models.Sequential', 'Sequentia... |
from django.contrib.auth.decorators import login_required
from django.core.urlresolvers import reverse
from django.shortcuts import render, get_object_or_404, redirect
from edit import decorators
import edit.models
from tokens.forms import TokenForm
import tokens.models
@decorators.belongs_to_document
@login_required... | [
"django.contrib.auth.decorators.login_required",
"django.shortcuts.get_object_or_404",
"tokens.forms.TokenForm",
"django.core.urlresolvers.reverse"
] | [((306, 349), 'django.contrib.auth.decorators.login_required', 'login_required', ([], {'login_url': '"""dashboard:login"""'}), "(login_url='dashboard:login')\n", (320, 349), False, 'from django.contrib.auth.decorators import login_required\n'), ((769, 812), 'django.contrib.auth.decorators.login_required', 'login_requir... |
"""Adversarial Variational Bayes (AVB).
Adversarial Variational Bayes: Unifying Variational Autoencoders and Generative
Adversarial Networks
http://arxiv.org/abs/1701.04722
Ref)
https://github.com/gdikov/adversarial-variational-bayes
http://seiya-kumada.blogspot.com/2018/07/adversarial-variational-bayes.html
https://... | [
"torch.ones",
"torch.nn.ReLU",
"torch.nn.BCEWithLogitsLoss",
"torch.nn.ConvTranspose2d",
"torch.randn_like",
"torch.nn.Conv2d",
"torch.cat",
"torch.nn.Linear",
"torch.zeros",
"torch.nn.LeakyReLU",
"torch.nn.Sigmoid"
] | [((1646, 1673), 'torch.nn.Linear', 'nn.Linear', (['(z_dim * 2)', 'z_dim'], {}), '(z_dim * 2, z_dim)\n', (1655, 1673), False, 'from torch import Tensor, nn\n'), ((4043, 4063), 'torch.nn.Linear', 'nn.Linear', (['(1024)', '(256)'], {}), '(1024, 256)\n', (4052, 4063), False, 'from torch import Tensor, nn\n'), ((4316, 4333)... |
import fractions
from prover import *
# test distinct objects
assert distinct_object("a") == distinct_object("a")
assert distinct_object("a") != distinct_object("b")
assert not (distinct_object("a") != distinct_object("a"))
assert not (distinct_object("a") == distinct_object("b"))
###################################... | [
"fractions.Fraction"
] | [((8887, 8912), 'fractions.Fraction', 'fractions.Fraction', (['"""2/3"""'], {}), "('2/3')\n", (8905, 8912), False, 'import fractions\n'), ((8682, 8707), 'fractions.Fraction', 'fractions.Fraction', (['"""1/3"""'], {}), "('1/3')\n", (8700, 8707), False, 'import fractions\n'), ((8828, 8853), 'fractions.Fraction', 'fractio... |
from __future__ import print_function, absolute_import, division
import sys
import timeit
import os
sys.path.append("..")
print(sys.path)
from numpy import *
from pyKratos import *
from inflows import *
from channelIO import *
#this i a modified copy of the stokes testcase to test the first prototype of the navier... | [
"sys.path.append",
"pyKratos.newton_raphson_strategy.NewtonRaphsonStrategy",
"timeit.default_timer",
"bossak_scheme.BossakScheme",
"pyKratos.gid_io_navier_stokes.GidIONS"
] | [((102, 123), 'sys.path.append', 'sys.path.append', (['""".."""'], {}), "('..')\n", (117, 123), False, 'import sys\n'), ((372, 394), 'timeit.default_timer', 'timeit.default_timer', ([], {}), '()\n', (392, 394), False, 'import timeit\n'), ((1732, 1785), 'pyKratos.gid_io_navier_stokes.GidIONS', 'gid_io_navier_stokes.GidI... |
# All of these attributes are defined in _about.py, but it must be imported this way.
__project_name__ = None
__version__ = None
__author__ = None
__author_email__= None
__project_url__ = None
exec(open('pytpp/_about.py', 'r').read())
from setuptools import setup, find_packages
import os
PROD_REQUIREMENTS = [
'is... | [
"os.path.dirname",
"setuptools.find_packages"
] | [((1012, 1046), 'setuptools.find_packages', 'find_packages', ([], {'include': "('pytpp*',)"}), "(include=('pytpp*',))\n", (1025, 1046), False, 'from setuptools import setup, find_packages\n'), ((745, 770), 'os.path.dirname', 'os.path.dirname', (['__file__'], {}), '(__file__)\n', (760, 770), False, 'import os\n')] |
"""Copyright (c) Facebook, Inc. and its affiliates.
All rights reserved.
This source code is licensed under the license found in the
LICENSE file in the root directory of this source tree.
Portions of the source code are from the OLTR project which
notice below and in LICENSE in the root directory of
this source tree.... | [
"numpy.sum",
"numpy.power",
"torch.nn.functional.cross_entropy",
"numpy.array",
"torch.tensor"
] | [((1370, 1437), 'torch.nn.functional.cross_entropy', 'F.cross_entropy', (['output_logits', 'target'], {'weight': 'self.per_cls_weights'}), '(output_logits, target, weight=self.per_cls_weights)\n', (1385, 1437), True, 'import torch.nn.functional as F\n'), ((977, 1046), 'torch.tensor', 'torch.tensor', (['per_cls_weights'... |
# --------------
# Importing header files
import numpy as np
# Path of the file has been stored in variable called 'path'
data = np.genfromtxt(path, delimiter = ",", skip_header = 1)
#New record
new_record=[[50, 9, 4, 1, 0, 0, 40, 0]]
#Code starts here
census = np.concatenate((data, new_record))
print... | [
"numpy.std",
"numpy.genfromtxt",
"numpy.max",
"numpy.mean",
"numpy.min",
"numpy.concatenate"
] | [((134, 183), 'numpy.genfromtxt', 'np.genfromtxt', (['path'], {'delimiter': '""","""', 'skip_header': '(1)'}), "(path, delimiter=',', skip_header=1)\n", (147, 183), True, 'import numpy as np\n'), ((279, 313), 'numpy.concatenate', 'np.concatenate', (['(data, new_record)'], {}), '((data, new_record))\n', (293, 313), True... |
# Generated by the protocol buffer compiler. DO NOT EDIT!
# source: launcher.proto
import sys
_b = sys.version_info[0] < 3 and (lambda x: x) or (lambda x: x.encode('latin1'))
from google.protobuf import descriptor as _descriptor
from google.protobuf import message as _message
from google.protobuf import reflection as... | [
"google.protobuf.symbol_database.Default",
"google.protobuf.descriptor_pb2.FileOptions"
] | [((487, 513), 'google.protobuf.symbol_database.Default', '_symbol_database.Default', ([], {}), '()\n', (511, 513), True, 'from google.protobuf import symbol_database as _symbol_database\n'), ((2285, 2313), 'google.protobuf.descriptor_pb2.FileOptions', 'descriptor_pb2.FileOptions', ([], {}), '()\n', (2311, 2313), False,... |
from src.data_structures.nodes import Node
class LinkedList(object):
"""
Class representing a linked list.
"""
def __init__(self, key=None):
if key:
self.head = Node(key)
else:
self.head = None
def traverse(self):
"""
method to traverse a li... | [
"src.data_structures.nodes.Node"
] | [((621, 630), 'src.data_structures.nodes.Node', 'Node', (['key'], {}), '(key)\n', (625, 630), False, 'from src.data_structures.nodes import Node\n'), ((945, 954), 'src.data_structures.nodes.Node', 'Node', (['key'], {}), '(key)\n', (949, 954), False, 'from src.data_structures.nodes import Node\n'), ((1774, 1783), 'src.d... |
def reload():
from utils.Colors import Colors
Colors.reload()
| [
"utils.Colors.Colors.reload"
] | [((55, 70), 'utils.Colors.Colors.reload', 'Colors.reload', ([], {}), '()\n', (68, 70), False, 'from utils.Colors import Colors\n')] |
import yaml
import logging
import threading
import time
import math
from ucsmsdk.ucsexception import UcsException
from modules.UcsmServer import UcsmServer
logger = logging.getLogger("ConnectionManager")
class DataPoller(threading.Thread):
"""The DataPoller collects the data from one remote host"""
def __in... | [
"modules.Netbox.Netbox",
"threading.Thread.__init__",
"time.time",
"time.sleep",
"modules.UcsmServer.UcsmServer",
"yaml.safe_load",
"logging.getLogger"
] | [((167, 205), 'logging.getLogger', 'logging.getLogger', (['"""ConnectionManager"""'], {}), "('ConnectionManager')\n", (184, 205), False, 'import logging\n'), ((363, 394), 'threading.Thread.__init__', 'threading.Thread.__init__', (['self'], {}), '(self)\n', (388, 394), False, 'import threading\n'), ((3767, 3867), 'modul... |
"""
..
/------------------------------------------------------------------------------\
| -- FACADE TECHNOLOGIES INC. CONFIDENTIAL -- |
|------------------------------------------------------------------------------|
| ... | [
"data.properties.Properties.fromDict",
"data.properties.Properties.createPropertiesObject",
"data.entity.Entity.setName"
] | [((3280, 3353), 'data.properties.Properties.createPropertiesObject', 'Properties.createPropertiesObject', (['predefinedCategories', 'customCategories'], {}), '(predefinedCategories, customCategories)\n', (3313, 3353), False, 'from data.properties import Properties\n'), ((10334, 10360), 'data.entity.Entity.setName', 'En... |
import sys
try:
with open(sys.argv[1], 'r') as f:
nums = f.read()
except:
sys.exit('Could not read file')
nums = nums.strip()
nums = [int(i) for i in nums.split('\n')]
_sum = 0
sums = []
while True:
for n in nums:
_sum += n
if _sum in sums:
print(_sum)
sys.exit(0)
else:
sums.append(_sum)
print(... | [
"sys.exit"
] | [((79, 110), 'sys.exit', 'sys.exit', (['"""Could not read file"""'], {}), "('Could not read file')\n", (87, 110), False, 'import sys\n'), ((272, 283), 'sys.exit', 'sys.exit', (['(0)'], {}), '(0)\n', (280, 283), False, 'import sys\n')] |
# coding=utf-8
"""
create by pymu
on 2021/8/18
at 20:29
"""
from qtpy.QtCore import QSize
from sherry.view.activity.activity_about import AboutActivity
class AboutDecoration(AboutActivity):
def configure(self):
super(AboutDecoration, self).configure()
self.resize(500, 300)
se... | [
"qtpy.QtCore.QSize"
] | [((772, 785), 'qtpy.QtCore.QSize', 'QSize', (['(60)', '(60)'], {}), '(60, 60)\n', (777, 785), False, 'from qtpy.QtCore import QSize\n')] |
# -*- coding: utf-8 -*-
# pylint: disable=missing-docstring
from __future__ import absolute_import, unicode_literals
# 3rd party imports
import pytest
from mock import Mock
# local imports
from restible import ModelResource
class FakeRes(ModelResource):
name = 'fake_res'
read_only = ['value']
schema = {... | [
"pytest.mark.parametrize",
"mock.Mock"
] | [((892, 949), 'pytest.mark.parametrize', 'pytest.mark.parametrize', (['"""req_data"""', "[{'value': 'a'}, {}]"], {}), "('req_data', [{'value': 'a'}, {}])\n", (915, 949), False, 'import pytest\n'), ((1317, 1396), 'pytest.mark.parametrize', 'pytest.mark.parametrize', (['"""req_data"""', "[{'name': 'a', 'extra': 'a'}, {'n... |
from django.contrib import admin
from fornecedor.models import Fornecedor
admin.site.register(Fornecedor)
| [
"django.contrib.admin.site.register"
] | [((76, 107), 'django.contrib.admin.site.register', 'admin.site.register', (['Fornecedor'], {}), '(Fornecedor)\n', (95, 107), False, 'from django.contrib import admin\n')] |
"Haldis admin related views and models"
import flask_login as login
from flask import Flask
from flask_admin import Admin
from flask_admin.contrib.sqla import ModelView
from flask_sqlalchemy import SQLAlchemy
from models import Location, Order, OrderItem, Product, User
class ModelBaseView(ModelView):
"Base mode... | [
"flask_login.current_user.is_admin",
"flask_admin.Admin",
"flask_login.current_user.is_anonymous"
] | [((1287, 1354), 'flask_admin.Admin', 'Admin', (['app'], {'name': '"""Haldis"""', 'url': '"""/admin"""', 'template_mode': '"""bootstrap3"""'}), "(app, name='Haldis', url='/admin', template_mode='bootstrap3')\n", (1292, 1354), False, 'from flask_admin import Admin\n'), ((480, 513), 'flask_login.current_user.is_anonymous'... |
import asyncio
async def foreach(func, iterable):
for item in iterable:
func(item)
async def fetcher(name, queue):
while True:
url = await queue.get()
# stuff here
queue.task_done()
async def main():
queue = asyncio.Queue()
tasks = []
await queue.join()
awa... | [
"asyncio.gather",
"asyncio.Queue"
] | [((258, 273), 'asyncio.Queue', 'asyncio.Queue', ([], {}), '()\n', (271, 273), False, 'import asyncio\n'), ((369, 415), 'asyncio.gather', 'asyncio.gather', (['*tasks'], {'return_exceptions': '(True)'}), '(*tasks, return_exceptions=True)\n', (383, 415), False, 'import asyncio\n')] |
from pycparser.c_generator import CGenerator as CGeneratorBaseBuggy
from pycparserext.ext_c_parser import FuncDeclExt, TypeDeclExt
import pycparser.c_ast as c_ast
class CGeneratorBase(CGeneratorBaseBuggy):
# bug fix
def visit_UnaryOp(self, n):
operand = self._parenthesize_unless_simple(n.expr)
... | [
"warnings.warn"
] | [((5208, 5295), 'warnings.warn', 'warn', (['"""GNUCGenerator is now called GnuCGenerator"""', 'DeprecationWarning'], {'stacklevel': '(2)'}), "('GNUCGenerator is now called GnuCGenerator', DeprecationWarning,\n stacklevel=2)\n", (5212, 5295), False, 'from warnings import warn\n')] |
import ConfigParser
import sys
import collections
def is_float(value):
try:
float(value)
return True
except ValueError:
return False
def parse_config(config_section, config_path):
"""
Read a config file into a dictionary, while converting variables to appropriate types
"""... | [
"collections.OrderedDict",
"ConfigParser.SafeConfigParser"
] | [((341, 391), 'ConfigParser.SafeConfigParser', 'ConfigParser.SafeConfigParser', ([], {'allow_no_value': '(True)'}), '(allow_no_value=True)\n', (370, 391), False, 'import ConfigParser\n'), ((442, 467), 'collections.OrderedDict', 'collections.OrderedDict', ([], {}), '()\n', (465, 467), False, 'import collections\n')] |
import regex
import json
import re
from typing import TYPE_CHECKING
from ..config import JMCSyntaxError
from ..utils import BracketRegex
from .. import Logger
if TYPE_CHECKING:
from ..datapack import DataPack
logger = Logger(__name__)
bracket_regex = BracketRegex()
NEW_REGEX = r'^new\s*([\w\._]+)\s*'+ bracket_... | [
"regex.subn",
"json.loads"
] | [((1124, 1171), 'regex.subn', 'regex.subn', (['NEW_REGEX', 'new_found', 'line'], {'count': '(1)'}), '(NEW_REGEX, new_found, line, count=1)\n', (1134, 1171), False, 'import regex\n'), ((772, 804), 'json.loads', 'json.loads', (['f"""{{{new_content}}}"""'], {}), "(f'{{{new_content}}}')\n", (782, 804), False, 'import json\... |
import tensorflow as tf
import numpy as np
test_arr = [[np.zeros(shape=(2, 2), dtype="float32"), 0], [np.ones(shape=(2, 2), dtype="float32"), 1]]
def input_gen():
for i in range(len(test_arr)):
label = test_arr[i][1]
features = test_arr[i][0]
yield label, features
dataset = tf.data.Data... | [
"tensorflow.data.Dataset.from_generator",
"numpy.zeros",
"numpy.ones"
] | [((57, 96), 'numpy.zeros', 'np.zeros', ([], {'shape': '(2, 2)', 'dtype': '"""float32"""'}), "(shape=(2, 2), dtype='float32')\n", (65, 96), True, 'import numpy as np\n'), ((103, 141), 'numpy.ones', 'np.ones', ([], {'shape': '(2, 2)', 'dtype': '"""float32"""'}), "(shape=(2, 2), dtype='float32')\n", (110, 141), True, 'imp... |
#!/usr/bin/env python
# -*- coding: utf-8 -*-
import os
import sys
try:
from setuptools import setup
except ImportError:
from distutils.core import setup
if sys.argv[-1] == 'publish':
os.system("python setup.py sdist upload")
sys.exit()
deps = [
'Flask==0.8',
'Flask-Script==0.3.1',
'Ji... | [
"os.system",
"sys.exit",
"distutils.core.setup"
] | [((491, 1136), 'distutils.core.setup', 'setup', ([], {'name': '"""httpbin"""', 'version': '"""0.0.6"""', 'install_requires': 'deps', 'description': '"""HTTP Request and Response Service."""', 'long_description': '"""httpbin.org"""', 'author': '"""<NAME>"""', 'author_email': '"""<EMAIL>"""', 'url': '"""https://httpbin.o... |
# -*- coding: utf-8 -*-
import markdown
from django import template
from django.template.defaultfilters import stringfilter
from django.utils.encoding import force_text
from django.utils.safestring import mark_safe
register = template.Library()
@register.filter(is_safe=True)
@stringfilter
def custom_markdown(valu... | [
"django.template.Library",
"markdown.markdown"
] | [((230, 248), 'django.template.Library', 'template.Library', ([], {}), '()\n', (246, 248), False, 'from django import template\n'), ((464, 557), 'markdown.markdown', 'markdown.markdown', (['value'], {'extensions': 'extensions', 'safe_mode': '(False)', 'enable_attributes': '(False)'}), '(value, extensions=extensions, sa... |
"""Circles models."""
# Django
from django.db import models
# Utils
from bookshare.utils import BookShareModel
class Circle(BookShareModel):
"""
Circle models.
This model work as a private groups where books lends are
offer and take between the users. To join into the circle
must rec... | [
"django.db.models.TextField",
"django.db.models.ManyToManyField",
"django.db.models.CharField",
"django.db.models.PositiveIntegerField",
"django.db.models.BooleanField",
"django.db.models.SlugField",
"django.db.models.ImageField"
] | [((377, 424), 'django.db.models.CharField', 'models.CharField', (['"""circle name"""'], {'max_length': '(148)'}), "('circle name', max_length=148)\n", (393, 424), False, 'from django.db import models\n'), ((442, 507), 'django.db.models.SlugField', 'models.SlugField', (['"""circle slug name"""'], {'unique': '(True)', 'm... |
import hashlib
import os.path
import pickle
import tempfile
import sublime
class SublimeTextHelpers(object):
def __init__(self, edit):
self.edit = edit
self.window = sublime.active_window()
def get_base_dir(self):
return sublime.active_window().folders()[0]
def error_message(sel... | [
"sublime.message_dialog",
"tempfile.gettempdir",
"sublime.Region",
"sublime.active_window",
"sublime.error_message"
] | [((189, 212), 'sublime.active_window', 'sublime.active_window', ([], {}), '()\n', (210, 212), False, 'import sublime\n'), ((338, 365), 'sublime.error_message', 'sublime.error_message', (['text'], {}), '(text)\n', (359, 365), False, 'import sublime\n'), ((411, 439), 'sublime.message_dialog', 'sublime.message_dialog', ([... |
# VMware vRA Health test Python SDK Community Samples
#
# Copyright 2018 VMware, Inc. All rights reserved
# The MIT license (the “License”) set forth below applies to all parts of the VMware vRealize Health Service Code Samples project. You may not use this file except in compliance with the License.
# MIT Lic... | [
"testsuite_module.vrahealthtestsuite.vRAUpgradeTestSuite",
"json.dumps"
] | [((1585, 1606), 'testsuite_module.vrahealthtestsuite.vRAUpgradeTestSuite', 'vRAUpgradeTestSuite', ([], {}), '()\n', (1604, 1606), False, 'from testsuite_module.vrahealthtestsuite import vRAUpgradeTestSuite\n'), ((3519, 3535), 'json.dumps', 'json.dumps', (['args'], {}), '(args)\n', (3529, 3535), False, 'import json\n')] |
''' Implements manifest validation for Kako simulations. '''
from cerberus import Validator
from cerberus import schema_registry
# Define a generic schema for response entities.
SCHEMA_RESPONSE = {
'code': {'type': 'integer'},
'text': {'type': 'string'},
'body': {'type': 'string'},
'headers': {
... | [
"cerberus.Validator"
] | [((2436, 2453), 'cerberus.Validator', 'Validator', (['SCHEMA'], {}), '(SCHEMA)\n', (2445, 2453), False, 'from cerberus import Validator\n')] |
################################################
############ ################
############ DEPRECATED ################
############ ################
################################################
import logging
from sqlalchemy import create_engine
from sqlalchemy.orm i... | [
"sqlalchemy.create_engine",
"sqlalchemy.orm.sessionmaker",
"celery.Celery",
"logging.basicConfig"
] | [((411, 488), 'sqlalchemy.create_engine', 'create_engine', (['"""postgresql+psycopg2://quellen:quellen@localhost/manu_tironis"""'], {}), "('postgresql+psycopg2://quellen:quellen@localhost/manu_tironis')\n", (424, 488), False, 'from sqlalchemy import create_engine\n'), ((518, 543), 'sqlalchemy.orm.sessionmaker', 'sessio... |
"""
Tools for gapfilling missing data.
Gapfill functions that can be applied are called from the gapfunctions module.
"""
import pandas as pd
import numpy as np
from datetime import datetime
from sawyer import gapfunctions as gfuncs
import sawyer.plots as dpl
import sawyer.io as sio
import sawyer.dtools as tools
fro... | [
"pandas.DataFrame",
"matplotlib.pyplot.show",
"numpy.logical_and",
"sawyer.dtools.regex_colnames",
"matplotlib.pyplot.subplots",
"sawyer.io.get_datadir",
"sawyer.io.read_yaml_conf",
"numpy.logical_or",
"sawyer.plots.gf_var_tsplot",
"sawyer.io.get_latest_df",
"datetime.datetime.now"
] | [((7957, 8012), 'pandas.DataFrame', 'pd.DataFrame', (['(False)'], {'index': 'df.index', 'columns': 'df.columns'}), '(False, index=df.index, columns=df.columns)\n', (7969, 8012), True, 'import pandas as pd\n'), ((10443, 10494), 'sawyer.io.get_latest_df', 'sio.get_latest_df', (['lname', 'dlevel'], {'optmatch': '"""masked... |
"""Stock picker that conectors to the marketstack API to obtain EOD stock prices."""
import json
import pickle
import requests
class Stock:
"""Stock object across all stock exchanges."""
def __init__(self):
self.date = "2019-02-01T00:00:00+0000"
self.ticker = ""
self.exchange = ""
... | [
"json.loads",
"requests.get"
] | [((618, 683), 'requests.get', 'requests.get', (['"""http://api.marketstack.com/v1/eod"""'], {'params': 'payload'}), "('http://api.marketstack.com/v1/eod', params=payload)\n", (630, 683), False, 'import requests\n'), ((849, 918), 'requests.get', 'requests.get', (['"""http://api.marketstack.com/v1/tickers"""'], {'params'... |
# Generated by Django 3.0.6 on 2020-05-25 16:13
from django.conf import settings
from django.db import migrations, models
import django.db.models.deletion
class Migration(migrations.Migration):
initial = True
dependencies = [
migrations.swappable_dependency(settings.AUTH_USER_MODEL),
]
ope... | [
"django.db.models.URLField",
"django.db.migrations.swappable_dependency",
"django.db.models.ManyToManyField",
"django.db.models.ForeignKey",
"django.db.models.CharField",
"django.db.models.PositiveSmallIntegerField",
"django.db.models.AutoField",
"django.db.models.DateTimeField"
] | [((247, 304), 'django.db.migrations.swappable_dependency', 'migrations.swappable_dependency', (['settings.AUTH_USER_MODEL'], {}), '(settings.AUTH_USER_MODEL)\n', (278, 304), False, 'from django.db import migrations, models\n'), ((2271, 2501), 'django.db.models.ForeignKey', 'models.ForeignKey', ([], {'editable': '(False... |
import datetime
import unittest
import omniture
class UtilsTest(unittest.TestCase):
def setUp(self):
fakelist = [{"id":"123", "title":"abc"},{"id":"456","title":"abc"}]
self.alist = omniture.Value.list("segemnts",fakelist,{})
def tearDown(self):
del self.alist
def test_addre... | [
"omniture.utils.wrap",
"omniture.Value.list",
"omniture.utils.affix",
"datetime.date",
"datetime.datetime",
"omniture.utils.translate",
"omniture.utils.date"
] | [((208, 253), 'omniture.Value.list', 'omniture.Value.list', (['"""segemnts"""', 'fakelist', '{}'], {}), "('segemnts', fakelist, {})\n", (227, 253), False, 'import omniture\n'), ((1953, 1978), 'datetime.date', 'datetime.date', (['(2016)', '(9)', '(1)'], {}), '(2016, 9, 1)\n', (1966, 1978), False, 'import datetime\n'), (... |
import pytest
from jsonschema import validate
from jsonschema.exceptions import ValidationError
from pyhttptest.http_schemas.base_schema import base_schema
def test_schema_with_valid_data():
data = {
'name': 'Test',
'verb': 'GET',
'endpoint': 'users',
'host': 'http://test.com',
... | [
"jsonschema.validate",
"pytest.raises"
] | [((339, 382), 'jsonschema.validate', 'validate', ([], {'instance': 'data', 'schema': 'base_schema'}), '(instance=data, schema=base_schema)\n', (347, 382), False, 'from jsonschema import validate\n'), ((458, 488), 'pytest.raises', 'pytest.raises', (['ValidationError'], {}), '(ValidationError)\n', (471, 488), False, 'imp... |
# SPDX-License-Identifier: Apache-2.0
# Copyright (C) 2020 ifm electronic gmbh
#
# THE PROGRAM IS PROVIDED "AS IS" WITHOUT WARRANTY OF ANY KIND.
#
"""
This module provides the gui logging service for nexxT.
"""
import datetime
from queue import Queue
import traceback
import logging
import shiboken2
from PySide2.QtCore... | [
"nexxT.interface.Services.getService",
"PySide2.QtWidgets.QAction",
"PySide2.QtGui.QColor",
"traceback.format_exception",
"PySide2.QtCore.QTimer",
"PySide2.QtWidgets.QActionGroup",
"nexxT.core.Utils.assertMainThread",
"PySide2.QtCore.QModelIndex",
"shiboken2.isValid",
"datetime.datetime.fromtimest... | [((7457, 7464), 'queue.Queue', 'Queue', ([], {}), '()\n', (7462, 7464), False, 'from queue import Queue\n'), ((8240, 8248), 'PySide2.QtCore.QTimer', 'QTimer', ([], {}), '()\n', (8246, 8248), False, 'from PySide2.QtCore import Qt, QTimer, QAbstractItemModel, QModelIndex\n'), ((10892, 10910), 'nexxT.core.Utils.assertMain... |
# Copyright 2021 <NAME>
#
# Licensed under the Apache License, Version 2.0 (the "License");
# you may not use this file except in compliance with the License.
# You may obtain a copy of the License at
#
# http://www.apache.org/licenses/LICENSE-2.0
#
# Unless required by applicable law or agreed to in writing, ... | [
"asyncio.Lock",
"aioeapi.Device"
] | [((2997, 3048), 'aioeapi.Device', 'DeviceEAPI', ([], {'host': 'device.name', 'auth': 'g_eos.basic_auth'}), '(host=device.name, auth=g_eos.basic_auth)\n', (3007, 3048), True, 'from aioeapi import Device as DeviceEAPI\n'), ((3232, 3246), 'asyncio.Lock', 'asyncio.Lock', ([], {}), '()\n', (3244, 3246), False, 'import async... |
#!/usr/bin/env python
import os
from string import find
from MolKit import Read
from MolKit.pdbWriter import PdbqWriter
if __name__ == '__main__':
import sys
import getopt
def usage():
"Print helpful, accurate usage statement to stdout."
print("Usage: pdbqt_to_pdbq.py -s filename")
... | [
"MolKit.Read",
"getopt.getopt",
"sys.exit",
"MolKit.pdbWriter.PdbqWriter"
] | [((1705, 1725), 'MolKit.Read', 'Read', (['pdbqt_filename'], {}), '(pdbqt_filename)\n', (1709, 1725), False, 'from MolKit import Read\n'), ((1997, 2009), 'MolKit.pdbWriter.PdbqWriter', 'PdbqWriter', ([], {}), '()\n', (2007, 2009), False, 'from MolKit.pdbWriter import PdbqWriter\n'), ((647, 683), 'getopt.getopt', 'getopt... |
def are_overlapped(gstart,gend,tstart,tend):
return ( (( gstart <= tend ) and (gstart >= tstart)) or
((gend <= tend) and (gend >= tstart)) or
((tstart <= gend) and (tstart >= gstart))or
((tend <= gend) and (tend >= gstart))
)
# Runs through deid'ed (gs) file ... | [
"collections.defaultdict",
"re.findall"
] | [((1235, 1252), 'collections.defaultdict', 'defaultdict', (['list'], {}), '(list)\n', (1246, 1252), False, 'from collections import defaultdict\n'), ((1268, 1285), 'collections.defaultdict', 'defaultdict', (['list'], {}), '(list)\n', (1279, 1285), False, 'from collections import defaultdict\n'), ((5383, 5400), 'collect... |
from __future__ import absolute_import
import re
from celery import shared_task
from celery.utils.log import get_task_logger
try:
# Django 1.9
from django.apps import apps
get_model = apps.get_model
except ImportError:
# Django 1.7 and before
from django.db.models import get_model
logger = get_... | [
"celery.utils.log.get_task_logger",
"django.db.models.get_model",
"re.compile"
] | [((316, 341), 'celery.utils.log.get_task_logger', 'get_task_logger', (['__name__'], {}), '(__name__)\n', (331, 341), False, 'from celery.utils.log import get_task_logger\n'), ((433, 473), 're.compile', 're.compile', (['"""(.*)_recalculation_needed$"""'], {}), "('(.*)_recalculation_needed$')\n", (443, 473), False, 'impo... |
"""
gen_secret.py
Generates a secret using the Fuzzy Key Recovery scheme
"""
import json
import click
from fuzzyvault import gen_secret, FuzzyError
def work(params_path: str, words: str, secret_path: str) -> None:
"workhorse"
original_words = json.dumps([int(word) for word in words.split()], indent=2)
wi... | [
"click.option",
"fuzzyvault.gen_secret",
"click.command"
] | [((570, 585), 'click.command', 'click.command', ([], {}), '()\n', (583, 585), False, 'import click\n'), ((587, 749), 'click.option', 'click.option', (['"""--params-path"""'], {'type': 'str', 'default': '"""params.json"""', 'help': "('path to a JSON representation of an' +\n ' InputParams object (default= params.json... |
# file openpyxl/tests/test_named_range.py
# Copyright (c) 2010-2011 openpyxl
#
# Permission is hereby granted, free of charge, to any person obtaining a copy
# of this software and associated documentation files (the "Software"), to deal
# in the Software without restriction, including without limitation the rights
#... | [
"openpyxl.tests.helper.clean_tmpdir",
"openpyxl.namedrange.split_named_range",
"nose.tools.eq_",
"openpyxl.tests.helper.make_tmpdir",
"nose.tools.assert_raises",
"openpyxl.reader.excel.load_workbook",
"openpyxl.workbook.Workbook"
] | [((1980, 2051), 'nose.tools.assert_raises', 'assert_raises', (['NamedRangeException', 'split_named_range', '"""HYPOTHESES$B$3"""'], {}), "(NamedRangeException, split_named_range, 'HYPOTHESES$B$3')\n", (1993, 2051), False, 'from nose.tools import eq_, assert_raises, ok_\n'), ((4128, 4147), 'nose.tools.eq_', 'eq_', (['(1... |
#!/usr/bin/env python
import os
import sys
BLACK = '\033[0;30m'
RED = '\033[0;31m'
GREEN = '\033[0;32m'
ORANGE = '\033[0;33m'
BLUE = '\033[0;34m'
PURPLE = '\033[0;35m'
CYAN = '\033[0;36m'
LGRAY = '\033[0;37m'
DGREY = '\033[1;30m'
LRED = '\033[1;31m'
LGREEN = '\033[1;32m'
YELLOW = '\033[1;33m'
LBLUE = '\033[1;34m'
LPU... | [
"os.path.isdir",
"os.path.isfile"
] | [((3510, 3531), 'os.path.isdir', 'os.path.isdir', (['outdir'], {}), '(outdir)\n', (3523, 3531), False, 'import os\n'), ((3693, 3712), 'os.path.isfile', 'os.path.isfile', (['fnp'], {}), '(fnp)\n', (3707, 3712), False, 'import os\n'), ((3907, 3925), 'os.path.isfile', 'os.path.isfile', (['fn'], {}), '(fn)\n', (3921, 3925)... |
#!/usr/bin/env python3
# programming-with-guis
# Ex. 1.11
from guizero import App, ButtonGroup, CheckBox, Combo, ListBox, Picture, PushButton, Slider, Text, TextBox
import textwrap
char_class = {
1: {
"name": "Barbarian",
"desc": "A fierce warrior of primitive background who can enter a battle rag... | [
"guizero.Slider",
"guizero.App",
"guizero.ButtonGroup",
"textwrap.wrap",
"guizero.CheckBox",
"guizero.Picture",
"guizero.Combo",
"guizero.PushButton",
"guizero.ListBox",
"guizero.Text"
] | [((2222, 2309), 'guizero.App', 'App', ([], {'title': '"""Hero-o-matic v2.0"""', 'width': '(640)', 'height': '(680)', 'layout': '"""grid"""', 'bg': '"""#c0c0c0"""'}), "(title='Hero-o-matic v2.0', width=640, height=680, layout='grid', bg=\n '#c0c0c0')\n", (2225, 2309), False, 'from guizero import App, ButtonGroup, Che... |
from pathlib import Path
from .boxes import Boxes, empty, empty_like
from .ops import ARModify, concatenate, intersection, iou, ioa, \
non_max_suppression, resize, shift, \
set_aspect_ratio, sort_by_field, boxes_in_window
__version__ = None
def _read_version():
with open(Path(... | [
"pathlib.Path"
] | [((315, 329), 'pathlib.Path', 'Path', (['__file__'], {}), '(__file__)\n', (319, 329), False, 'from pathlib import Path\n')] |
import sys
from pyspark.sql import SparkSession
from pyspark import SparkContext
from pyspark.mllib.regression import LabeledPoint
from pyspark.mllib.classification import LogisticRegressionWithSGD
from pyspark.ml.classification import LogisticRegression
# def parsePoint(line):
# """
# Parse a line of text in... | [
"pyspark.sql.SparkSession.builder.master",
"pyspark.ml.classification.LogisticRegression"
] | [((1379, 1444), 'pyspark.ml.classification.LogisticRegression', 'LogisticRegression', ([], {'maxIter': '(10)', 'regParam': '(0.3)', 'elasticNetParam': '(0.8)'}), '(maxIter=10, regParam=0.3, elasticNetParam=0.8)\n', (1397, 1444), False, 'from pyspark.ml.classification import LogisticRegression\n'), ((1753, 1845), 'pyspa... |
from car_utils import get_rotation, get_car_can_path, get_points_rotated
from street_view import ImageWgsHandler
import sys
import time
import threading
from argparse import ArgumentParser
import numpy as np
import pandas as pd
import matplotlib.pyplot as plt
import os
import cv2
from car_utils import OFFSET_STEERING, ... | [
"numpy.load",
"argparse.ArgumentParser",
"pandas.read_csv",
"car_utils.get_points_rotated",
"os.path.isfile",
"sys.stdout.flush",
"cv2.imshow",
"os.path.join",
"matplotlib.pyplot.close",
"matplotlib.pyplot.draw",
"cv2.destroyAllWindows",
"matplotlib.pyplot.pause",
"matplotlib.pyplot.subplots... | [((5159, 5200), 'threading.Thread', 'threading.Thread', ([], {'target': 'looping', 'args': '()'}), '(target=looping, args=())\n', (5175, 5200), False, 'import threading\n'), ((5323, 5339), 'argparse.ArgumentParser', 'ArgumentParser', ([], {}), '()\n', (5337, 5339), False, 'from argparse import ArgumentParser\n'), ((535... |
#! /bin/env python
"""
Examples
--------
Create a grid of length 2 in the x direction, and 3 in the y direction.
>>> (x, y) = np.meshgrid ([1., 2., 4., 8.], [1., 2., 3.])
>>> g = Structured(y.flatten(), x.flatten(), [3, 4])
>>> g.get_point_count()
12
>>> g.get_cell_count()
6
>>> g.get_x()
array([ 1., 2., 4., 8., ... | [
"warnings.warn",
"pymt.grids.connectivity.get_connectivity",
"numpy.array",
"doctest.testmod"
] | [((5855, 5912), 'doctest.testmod', 'doctest.testmod', ([], {'optionflags': 'doctest.NORMALIZE_WHITESPACE'}), '(optionflags=doctest.NORMALIZE_WHITESPACE)\n', (5870, 5912), False, 'import doctest\n'), ((3872, 3898), 'numpy.array', 'np.array', (['shape'], {'dtype': 'int'}), '(shape, dtype=int)\n', (3880, 3898), True, 'imp... |
# -*- coding: utf-8 -*-
""" Thresholds Functions
This file helps to calculate useful statistics to further choose thresholds
Created on Fri May 15 12:47:14 2020
Authors: <NAME> (<EMAIL>)
<NAME> (<EMAIL>)
"""
import numpy as np
import pandas as pd
from trackintel.geogr.distances imp... | [
"pandas.DataFrame",
"numpy.quantile",
"numpy.median",
"help_functions.getDataPaths",
"help_functions.selectRange",
"numpy.transpose",
"trackintel.geogr.distances.haversine_dist",
"numpy.mean",
"numpy.array",
"help_functions.parseLocs"
] | [((2554, 2573), 'numpy.array', 'np.array', (['ddiff_max'], {}), '(ddiff_max)\n', (2562, 2573), True, 'import numpy as np\n'), ((2590, 2613), 'numpy.transpose', 'np.transpose', (['ddiff_max'], {}), '(ddiff_max)\n', (2602, 2613), True, 'import numpy as np\n'), ((2630, 2649), 'numpy.array', 'np.array', (['ddiff_min'], {})... |
# -*- coding: utf-8 -*-
# Copyright (c) 2015, zup.com http://zup.com/, all rights reserved.
# author: victor
from middleman.database import db
def to_persist(entity):
db.session.add(entity)
def save_all():
db.session.commit()
def to_remove(entity):
db.session.delete(entity) | [
"middleman.database.db.session.delete",
"middleman.database.db.session.add",
"middleman.database.db.session.commit"
] | [((173, 195), 'middleman.database.db.session.add', 'db.session.add', (['entity'], {}), '(entity)\n', (187, 195), False, 'from middleman.database import db\n'), ((218, 237), 'middleman.database.db.session.commit', 'db.session.commit', ([], {}), '()\n', (235, 237), False, 'from middleman.database import db\n'), ((266, 29... |
import hickle
import numpy as np
# Load file
print("Loading file!")
file = hickle.load('output.hkl')
# Create matrix
print("Creating matrix...")
matrix = np.empty(shape=(len(file), len(file[0][1])))
for i in range(0, len(file)):
matrix[i] = file[i][1]
print("Saving matrix...")
hickle.dump(matrix, 'matrix.hkl', mod... | [
"hickle.load",
"hickle.dump"
] | [((76, 101), 'hickle.load', 'hickle.load', (['"""output.hkl"""'], {}), "('output.hkl')\n", (87, 101), False, 'import hickle\n'), ((283, 346), 'hickle.dump', 'hickle.dump', (['matrix', '"""matrix.hkl"""'], {'mode': '"""w"""', 'compression': '"""gzip"""'}), "(matrix, 'matrix.hkl', mode='w', compression='gzip')\n", (294, ... |
# Copyright 2013 <NAME>
# Licensed under the Apache License, Version 2.0 (the "License");
# you may not use this file except in compliance with the License.
# You may obtain a copy of the License at
# http://www.apache.org/licenses/LICENSE-2.0
# Unless required by applicable law or agreed to in writing, software... | [
"SimpleGP.GP",
"numpy.ones",
"numpy.fabs",
"numpy.array",
"numpy.linspace"
] | [((672, 697), 'numpy.linspace', 'np.linspace', (['(-10)', '(10)', '(100)'], {}), '(-10, 10, 100)\n', (683, 697), True, 'import numpy as np\n'), ((712, 738), 'numpy.array', 'np.array', (['[0.2, -0.3, 0.2]'], {}), '([0.2, -0.3, 0.2])\n', (720, 738), True, 'import numpy as np\n'), ((1171, 1223), 'numpy.array', 'np.array',... |
#############################
# --- Day 12: Rain Risk --- #
#############################
import AOCUtils
moves = {"E": (1, 0),
"N": (0, 1),
"W": (-1, 0),
"S": (0, -1)}
#############################
navigation = AOCUtils.loadInput(12)
pos = (0, 0)
facing = 0
for inst in navigation:
... | [
"AOCUtils.printTimeTaken",
"AOCUtils.loadInput"
] | [((243, 265), 'AOCUtils.loadInput', 'AOCUtils.loadInput', (['(12)'], {}), '(12)\n', (261, 265), False, 'import AOCUtils\n'), ((1410, 1435), 'AOCUtils.printTimeTaken', 'AOCUtils.printTimeTaken', ([], {}), '()\n', (1433, 1435), False, 'import AOCUtils\n')] |
from bs4 import BeautifulSoup
import csv
import json
import math
from multiprocessing import Pool
from multiprocessing.dummy import Pool as ThreadPool
import os
import re
import requests
import time
import urllib.request
MAX_TIME_OUT = 60
url_root = "https://www.aria.developpement-durable.gouv.fr/"
url_search = url_r... | [
"os.mkdir",
"os.remove",
"csv.reader",
"os.path.join",
"json.loads",
"math.ceil",
"multiprocessing.dummy.Pool",
"os.path.getsize",
"os.path.exists",
"re.match",
"json.dumps",
"requests.get",
"bs4.BeautifulSoup",
"requests.post",
"re.sub",
"os.listdir"
] | [((2422, 2452), 'os.path.exists', 'os.path.exists', (['links_csv_file'], {}), '(links_csv_file)\n', (2436, 2452), False, 'import os\n'), ((5831, 5845), 'multiprocessing.dummy.Pool', 'ThreadPool', (['(20)'], {}), '(20)\n', (5841, 5845), True, 'from multiprocessing.dummy import Pool as ThreadPool\n'), ((464, 480), 'os.mk... |
import os
import sys
import asyncio
import signal
import re
from textwrap import dedent
import pytest
from kernel_driver import KernelDriver # type: ignore
TIMEOUT = 5
KERNELSPEC_PATH = (
os.environ["CONDA_PREFIX"] + "/share/jupyter/kernels/akernel/kernel.json"
)
ANSI_ESCAPE = re.compile(r"\x1B(?:[@-Z\\-_]|\[... | [
"textwrap.dedent",
"sys.platform.startswith",
"asyncio.sleep",
"kernel_driver.KernelDriver",
"os.kill",
"re.compile"
] | [((288, 343), 're.compile', 're.compile', (['"""\\\\x1B(?:[@-Z\\\\\\\\-_]|\\\\[[0-?]*[ -/]*[@-~])"""'], {}), "('\\\\x1B(?:[@-Z\\\\\\\\-_]|\\\\[[0-?]*[ -/]*[@-~])')\n", (298, 343), False, 'import re\n'), ((388, 418), 'sys.platform.startswith', 'sys.platform.startswith', (['"""win"""'], {}), "('win')\n", (411, 418), Fals... |
import motionTools
import numpy as np
import os
print("Loading Simulator Motion Files")
simMotion_1 = np.genfromtxt("data/MotionCondition_1.csv", delimiter = ",", skip_header = 1)
simMotion_2 = np.genfromtxt("data/MotionCondition_2.csv", delimiter = ",", skip_header = 1)
# Changing time to seconds instead of ... | [
"os.listdir",
"motionTools.headMotionSystem",
"numpy.genfromtxt"
] | [((108, 181), 'numpy.genfromtxt', 'np.genfromtxt', (['"""data/MotionCondition_1.csv"""'], {'delimiter': '""","""', 'skip_header': '(1)'}), "('data/MotionCondition_1.csv', delimiter=',', skip_header=1)\n", (121, 181), True, 'import numpy as np\n'), ((201, 274), 'numpy.genfromtxt', 'np.genfromtxt', (['"""data/MotionCondi... |
from LSP.plugin.core.typing import Any, Callable, Dict, Literal, Optional, Set
from LSP.plugin import uri_to_filename
from LSP.plugin import WorkspaceFolder
from lsp_utils import notification_handler
from lsp_utils import NpmClientHandler
from lsp_utils import request_handler
import os
import re
import sublime
import w... | [
"webbrowser.open",
"os.path.isabs",
"LSP.plugin.uri_to_filename",
"lsp_utils.request_handler",
"sublime.active_window",
"lsp_utils.notification_handler",
"os.path.normpath",
"os.path.join",
"re.sub"
] | [((592, 648), 'os.path.join', 'os.path.join', (['server_directory', '"""out"""', '"""eslintServer.js"""'], {}), "(server_directory, 'out', 'eslintServer.js')\n", (604, 648), False, 'import os\n'), ((810, 847), 'lsp_utils.notification_handler', 'notification_handler', (['"""eslint/status"""'], {}), "('eslint/status')\n"... |
import torch.nn as nn
class ResBlock(nn.Module):
def __init__(self, dim):
super(ResBlock, self).__init__()
self.res_block = nn.Sequential(
nn.ReLU(True),
nn.Conv1d(dim, dim, 5, padding=2), # nn.Linear(DIM, DIM),
nn.ReLU(True),
nn.Conv1d(dim, dim, 5,... | [
"torch.nn.ReLU",
"torch.nn.Conv1d",
"torch.nn.Softmax",
"torch.nn.Linear"
] | [((671, 700), 'torch.nn.Linear', 'nn.Linear', (['(128)', '(dim * seq_len)'], {}), '(128, dim * seq_len)\n', (680, 700), True, 'import torch.nn as nn\n'), ((903, 932), 'torch.nn.Conv1d', 'nn.Conv1d', (['dim', 'vocab_size', '(1)'], {}), '(dim, vocab_size, 1)\n', (912, 932), True, 'import torch.nn as nn\n'), ((956, 968), ... |