code stringlengths 22 1.05M | apis listlengths 1 3.31k | extract_api stringlengths 75 3.25M |
|---|---|---|
import os
import unittest
from swamp.utils import create_tempfile
from swamp.parsers.phaserparser import PhaserParser
class PhaserParserTestCase(unittest.TestCase):
def test_1(self):
file_contents = """REMARK TITLE [no title set]
REMARK ENSEMBLE PDB_1 EULER 49.90 83.52 180.06 FRAC -0.288 -0.526 -0.158
... | [
"unittest.main",
"swamp.utils.create_tempfile",
"swamp.parsers.phaserparser.PhaserParser"
] | [((20188, 20203), 'unittest.main', 'unittest.main', ([], {}), '()\n', (20201, 20203), False, 'import unittest\n'), ((1625, 1663), 'swamp.utils.create_tempfile', 'create_tempfile', ([], {'content': 'file_contents'}), '(content=file_contents)\n', (1640, 1663), False, 'from swamp.utils import create_tempfile\n'), ((1723, ... |
#!/usr/bin/env python3
import re
import unittest
import requests
import responses
import haiker
from . import samples
URL_INITIATE = 'https://www.hatena.com/oauth/initiate'
URL_VERIFY = 'https://www.hatena.com/oauth/token'
BODY_INITIATE = 'oauth_token=OAuthToken&oauth_token_secret=OAuthTokenSecret'
BODY_VERIFY = 'oa... | [
"re.compile",
"responses.add",
"haiker.BasicAuth",
"haiker.Haiker",
"haiker.OAuth"
] | [((502, 559), 're.compile', 're.compile', (['"""http://h\\\\.hatena\\\\.ne\\\\.jp/api/statuses/.+"""'], {}), "('http://h\\\\.hatena\\\\.ne\\\\.jp/api/statuses/.+')\n", (512, 559), False, 'import re\n'), ((564, 618), 'responses.add', 'responses.add', (['responses.GET', 'url'], {'json': 'samples.STATUS'}), '(responses.GE... |
import types
import numpy as np
import jax
from jax import numpy as jnp
from flax import struct
import utils
DTYPE = jnp.int16
SIZE = 10
one_hot_10 = jax.partial(utils.one_hot, k=SIZE)
ACTION_MAP = jnp.stack([
jnp.array((1, 0), dtype=DTYPE), # visually DOWN
jnp.array((0, 1), dtype=DTYPE), # visually R... | [
"jax.partial",
"flax.struct.field",
"jax.numpy.arange",
"jax.numpy.array",
"numpy.zeros",
"jax.jit",
"jax.numpy.clip",
"jax.numpy.linspace",
"jax.vmap",
"random.randint"
] | [((155, 189), 'jax.partial', 'jax.partial', (['utils.one_hot'], {'k': 'SIZE'}), '(utils.one_hot, k=SIZE)\n', (166, 189), False, 'import jax\n'), ((1076, 1091), 'jax.vmap', 'jax.vmap', (['reset'], {}), '(reset)\n', (1084, 1091), False, 'import jax\n'), ((1204, 1220), 'jax.vmap', 'jax.vmap', (['render'], {}), '(render)\n... |
from typing import Dict, List, Set, Type
from uuid import UUID
from panek.object_relations import ObjectRelationMapper
import byt.middleware.typing as t
from byt.ecs.component import IComponent
from byt.ecs.entity import Entity
from byt.ecs.system import ISystem
from byt.middleware.utils import make_iterable
class ... | [
"panek.object_relations.ObjectRelationMapper",
"byt.middleware.utils.make_iterable",
"byt.ecs.entity.Entity"
] | [((493, 515), 'panek.object_relations.ObjectRelationMapper', 'ObjectRelationMapper', ([], {}), '()\n', (513, 515), False, 'from panek.object_relations import ObjectRelationMapper\n'), ((749, 774), 'byt.middleware.utils.make_iterable', 'make_iterable', (['components'], {}), '(components)\n', (762, 774), False, 'from byt... |
from os import path
import os
from flask import Flask, jsonify, render_template, current_app
from keras.models import load_model
from . import app, db
from .controller.news_scanner import NewsScanner
from .controller.news_categorization import NewsCategorization
import pandas as pd
"""
Pages management
@author: Al... | [
"flask.render_template"
] | [((744, 901), 'flask.render_template', 'render_template', (['"""index.html"""'], {'sources': 'sources', 'source': 'None', 'categories': 'categories', 'first_news': 'first_news', 'next_news': 'next_news', 'last_news': 'last_news'}), "('index.html', sources=sources, source=None, categories=\n categories, first_news=fi... |
from finetuna.ml_potentials.ocpd_calc import OCPDCalc
import torch
from torch import nn
import torch.nn.functional as F
import numpy as np
import copy
from multiprocessing import Pool
from ase.atoms import Atoms
class OCPDNNCalc(OCPDCalc):
implemented_properties = ["energy", "forces", "stds"]
def __init__(
... | [
"numpy.multiply",
"torch.nn.Dropout",
"copy.deepcopy",
"numpy.ones",
"torch.optim.lr_scheduler.ReduceLROnPlateau",
"numpy.average",
"torch.nn.init.xavier_uniform_",
"torch.nn.MSELoss",
"numpy.zeros",
"torch.tensor",
"multiprocessing.Pool",
"torch.nn.Linear",
"numpy.std"
] | [((7096, 7120), 'copy.deepcopy', 'copy.deepcopy', (['estimator'], {}), '(estimator)\n', (7109, 7120), False, 'import copy\n'), ((1162, 1174), 'torch.nn.MSELoss', 'nn.MSELoss', ([], {}), '()\n', (1172, 1174), False, 'from torch import nn\n'), ((3884, 3911), 'numpy.std', 'np.std', (['predictions'], {'axis': '(0)'}), '(pr... |
import os, shutil, re
from pathlib import Path
src = Path('./copyFiles')
for folderName, subFolders, fileNames in os.walk(Path(src)):
count = 0
for file in fileNames:
fileRegex = re.compile(r'(test)(\d+)')
mo = fileRegex.search(file)
if mo.group(2) == count:
... | [
"re.compile",
"pathlib.Path"
] | [((54, 73), 'pathlib.Path', 'Path', (['"""./copyFiles"""'], {}), "('./copyFiles')\n", (58, 73), False, 'from pathlib import Path\n'), ((124, 133), 'pathlib.Path', 'Path', (['src'], {}), '(src)\n', (128, 133), False, 'from pathlib import Path\n'), ((203, 229), 're.compile', 're.compile', (['"""(test)(\\\\d+)"""'], {}), ... |
import pytest
from django_oso.models import AuthorizedModel, authorize_model
from django_oso.oso import Oso, reset_oso
from django.core.management import call_command
from app.models import Post, User
@pytest.fixture(autouse=True)
def reset():
reset_oso()
@pytest.fixture
def users():
(manager, _) = User.o... | [
"app.models.User.objects.get_or_create",
"django_oso.oso.reset_oso",
"app.models.Post.objects.get_or_create",
"app.models.Post.objects.authorize",
"pytest.fixture"
] | [((206, 234), 'pytest.fixture', 'pytest.fixture', ([], {'autouse': '(True)'}), '(autouse=True)\n', (220, 234), False, 'import pytest\n'), ((252, 263), 'django_oso.oso.reset_oso', 'reset_oso', ([], {}), '()\n', (261, 263), False, 'from django_oso.oso import Oso, reset_oso\n'), ((314, 360), 'app.models.User.objects.get_o... |
# SPDX-FileCopyrightText: 2022 <NAME>
# SPDX-License-Identifier: Apache-2.0
"""Build and installation script for hyper-shell."""
# standard libs
import os
import re
from setuptools import setup, find_packages
# long description from README.rst
with open('README.rst', mode='r') as readme:
long_description = rea... | [
"setuptools.find_packages",
"os.environ.get",
"re.search"
] | [((930, 959), 'os.environ.get', 'os.environ.get', (['"""READTHEDOCS"""'], {}), "('READTHEDOCS')\n", (944, 959), False, 'import os\n'), ((1634, 1654), 'setuptools.find_packages', 'find_packages', (['"""src"""'], {}), "('src')\n", (1647, 1654), False, 'from setuptools import setup, find_packages\n'), ((497, 559), 're.sea... |
# Uses python3
import sys
def gcd(a,b):
if a<b:
t=a
a=b
b=t
while True:
if b==0:
return a
remainder=a%b
a=b
b=remainder
if __name__ == "__main__":
input = sys.stdin.read()
a, b = map(int, input.split())
print(gcd(a, b))... | [
"sys.stdin.read"
] | [((248, 264), 'sys.stdin.read', 'sys.stdin.read', ([], {}), '()\n', (262, 264), False, 'import sys\n')] |
''''
Operations
==========
Initialisation
--------------
- Create veth pairs
- Create /var/run/netns
- Write ports file
- Run container with ${name}
- Run read thread
- Bind container process pid to namespace ${name}_ns
- Move peer ports to namespace
- Send trap
- Wa... | [
"simple_switch.netutils.configure_interface",
"simple_switch.netutils.add_veth_pair",
"simple_switch.netutils._run_command",
"os.environ.get",
"pyroute2.netns.remove",
"simple_switch.netutils.set_iface_namespace",
"docker.APIClient",
"docker.DockerClient",
"simple_switch.netutils.restart_avahi"
] | [((1237, 1266), 'os.environ.get', 'os.environ.get', (['"""https_proxy"""'], {}), "('https_proxy')\n", (1251, 1266), False, 'import os\n'), ((1305, 1333), 'os.environ.get', 'os.environ.get', (['"""http_proxy"""'], {}), "('http_proxy')\n", (1319, 1333), False, 'import os\n'), ((1806, 1873), 'docker.DockerClient', 'Docker... |
from passwd import PasswordRequirements
def test_min_length():
length_8 = PasswordRequirements(min_length=8)
assert length_8.check("abcd1234")
assert not length_8.check("abc123")
# No minimum characters requirement if not specified
assert PasswordRequirements().check("abc<PASSWORD>")
def test_... | [
"passwd.PasswordRequirements"
] | [((80, 114), 'passwd.PasswordRequirements', 'PasswordRequirements', ([], {'min_length': '(8)'}), '(min_length=8)\n', (100, 114), False, 'from passwd import PasswordRequirements\n'), ((349, 383), 'passwd.PasswordRequirements', 'PasswordRequirements', ([], {'min_digits': '(2)'}), '(min_digits=2)\n', (369, 383), False, 'f... |
from threading import Thread
import time
def car(speed, pilot):
route = 0
while route <= 100:
route += speed
time.sleep(0.5)
print(f'Pilot: {pilot}, Km {route} \n')
t_car1 = Thread(target = car, args = [20, 'Paul'])
t_car2 = Thread(target = car, args = [10, 'Del'])
t_car1.start()
t_c... | [
"threading.Thread",
"time.sleep"
] | [((209, 246), 'threading.Thread', 'Thread', ([], {'target': 'car', 'args': "[20, 'Paul']"}), "(target=car, args=[20, 'Paul'])\n", (215, 246), False, 'from threading import Thread\n'), ((260, 296), 'threading.Thread', 'Thread', ([], {'target': 'car', 'args': "[10, 'Del']"}), "(target=car, args=[10, 'Del'])\n", (266, 296... |
#!/usr/bin/env python
# -*- coding: utf-8 -*-
from __future__ import division
import sys
import re
import mrjob
import itertools
import json
from mrjob.protocol import RawProtocol
from mrjob.job import MRJob
from mrjob.step import MRStep
class MRbuildStripes(MRJob):
#START SUDENT CODE531_STRIPES
# Init Setti... | [
"re.findall",
"sys.stderr.write",
"mrjob.step.MRStep"
] | [((865, 927), 'sys.stderr.write', 'sys.stderr.write', (['"""reporter:counter:Mapper Counters,Calls,1\n"""'], {}), "('reporter:counter:Mapper Counters,Calls,1\\n')\n", (881, 927), False, 'import sys\n'), ((1897, 1960), 'sys.stderr.write', 'sys.stderr.write', (['"""reporter:counter:Reducer Counters,Calls,1\n"""'], {}), "... |
import click
from pathlib import Path
import datetime
from moviepy.editor import *
from PIL import Image
from PIL import ImageFont
from PIL import ImageDraw
import numpy as np
import xmltodict
def make_clips(filelist,timelist,AOI=None):
print('loopstart')
clips=[]
for file, time in zip(filelist, timelist)... | [
"PIL.Image.open",
"pathlib.Path",
"click.option",
"numpy.array",
"PIL.ImageDraw.Draw",
"click.command"
] | [((1118, 1133), 'click.command', 'click.command', ([], {}), '()\n', (1131, 1133), False, 'import click\n'), ((1135, 1290), 'click.option', 'click.option', (['"""--exp_folder"""'], {'default': '"""."""', 'help': '"""Path to experiment folder with images. Exp_folder will be also used to name the timelapse video"""'}), "(... |
#!/usr/bin/python3
import hid
import traceback
hid_max_pkt_size = 64
if __name__ == '__main__':
import argparse
import sys
import binascii
parser = argparse.ArgumentParser()
parser.add_argument('-d', '--descriptor', help='Print Descriptor', action='store_true')
args = parser.parse_args(... | [
"traceback.format_exc",
"argparse.ArgumentParser",
"binascii.hexlify",
"hid.device",
"sys.exit",
"hid.enumerate"
] | [((173, 198), 'argparse.ArgumentParser', 'argparse.ArgumentParser', ([], {}), '()\n', (196, 198), False, 'import argparse\n'), ((371, 386), 'hid.enumerate', 'hid.enumerate', ([], {}), '()\n', (384, 386), False, 'import hid\n'), ((1187, 1199), 'hid.device', 'hid.device', ([], {}), '()\n', (1197, 1199), False, 'import hi... |
# encoding: utf-8
import pytest
from ckan import model
from ckan.lib.create_test_data import CreateTestData
from ckan.tests.legacy import TestController as ControllerTestCase
from ckan.tests.legacy import url_for
@pytest.fixture(autouse=True)
def initial_data(clean_db):
CreateTestData.create()
def test_munge_p... | [
"pytest.fixture",
"ckan.tests.legacy.url_for",
"ckan.lib.create_test_data.CreateTestData.create"
] | [((217, 245), 'pytest.fixture', 'pytest.fixture', ([], {'autouse': '(True)'}), '(autouse=True)\n', (231, 245), False, 'import pytest\n'), ((278, 301), 'ckan.lib.create_test_data.CreateTestData.create', 'CreateTestData.create', ([], {}), '()\n', (299, 301), False, 'from ckan.lib.create_test_data import CreateTestData\n'... |
"""
Usefull functions for loading files etc.
-AN
"""
import os
import pickle
import zipfile, lzma
import numpy as np
import matplotlib.pyplot as plt
from collections import OrderedDict
# saves dict to csv using keys as headers
def saveToCSV(savedict, filename = "", path = ""):
try:
#print(sav... | [
"numpy.abs",
"collections.OrderedDict",
"numpy.convolve",
"pickle.dump",
"zipfile.ZipFile",
"os.makedirs",
"matplotlib.pyplot.plot",
"os.path.join",
"os.getcwd",
"os.path.isdir",
"numpy.shape",
"os.walk",
"matplotlib.pyplot.show"
] | [((3085, 3098), 'collections.OrderedDict', 'OrderedDict', ([], {}), '()\n', (3096, 3098), False, 'from collections import OrderedDict\n'), ((4311, 4324), 'collections.OrderedDict', 'OrderedDict', ([], {}), '()\n', (4322, 4324), False, 'from collections import OrderedDict\n'), ((6392, 6428), 'numpy.convolve', 'np.convol... |
import keras
import keras.backend as K
IMG_SIZE = 160
DENSE_SHAPE = 4096
def oneshot_bsm():
"""
pre-trained baseline model
:return: a keras model object
"""
pre_model = keras.applications.mobilenet_v2.MobileNetV2(include_top=False, weights='imagenet', input_shape=[IMG_SIZE, IMG_SIZE, 3])
flat ... | [
"keras.optimizers.Adam",
"keras.layers.Conv2D",
"keras.layers.Flatten",
"keras.Model",
"keras.layers.Concatenate",
"keras.layers.Lambda",
"keras.initializers.truncated_normal",
"keras.backend.abs",
"keras.backend.square",
"keras.Input",
"keras.backend.log",
"keras.applications.mobilenet_v2.Mob... | [((191, 315), 'keras.applications.mobilenet_v2.MobileNetV2', 'keras.applications.mobilenet_v2.MobileNetV2', ([], {'include_top': '(False)', 'weights': '"""imagenet"""', 'input_shape': '[IMG_SIZE, IMG_SIZE, 3]'}), "(include_top=False, weights=\n 'imagenet', input_shape=[IMG_SIZE, IMG_SIZE, 3])\n", (234, 315), False, ... |
import pytest
import xia2.Experts.LatticeExpert
def test_lattice_expert():
cell, dist = xia2.Experts.LatticeExpert.ApplyLattice(
"oP", (23.0, 24.0, 25.0, 88.9, 90.0, 90.1)
)
assert cell == (23.0, 24.0, 25.0, 90.0, 90.0, 90.0)
assert dist == pytest.approx(1.2)
def test_SortLattices():
la... | [
"pytest.approx"
] | [((268, 286), 'pytest.approx', 'pytest.approx', (['(1.2)'], {}), '(1.2)\n', (281, 286), False, 'import pytest\n')] |
from tkinter import *
from PIL import Image, ImageTk
import random
import requests
import json
import time
import pandas as pd
import matplotlib
matplotlib.use("TkAgg") # allow matplotlib to display on tkinter
import matplotlib.pyplot as plt
import seaborn as sns
from speech import *
import duckduckgo
import re
import... | [
"matplotlib.pyplot.ylabel",
"re.search",
"seaborn.set",
"collections.deque",
"matplotlib.pyplot.plot",
"matplotlib.pyplot.style.use",
"matplotlib.pyplot.close",
"time.localtime",
"PIL.ImageTk.PhotoImage",
"json.loads",
"random.choice",
"matplotlib.pyplot.savefig",
"matplotlib.pyplot.xticks",... | [((146, 169), 'matplotlib.use', 'matplotlib.use', (['"""TkAgg"""'], {}), "('TkAgg')\n", (160, 169), False, 'import matplotlib\n'), ((821, 1006), 'seaborn.set', 'sns.set', ([], {'rc': "{'axes.facecolor': 'black', 'figure.facecolor': 'black', 'axes.labelcolor':\n 'white', 'xtick.color': 'white', 'ytick.color': 'white'... |
import send_email
send_email.send('testing')
| [
"send_email.send"
] | [((20, 46), 'send_email.send', 'send_email.send', (['"""testing"""'], {}), "('testing')\n", (35, 46), False, 'import send_email\n')] |
#!/usr/bin/env python
# -*- coding: utf-8 -*-
"""
MagnetCommunication.py
Author: <NAME>
Created on Mon Dec 18 15:35:21 2017
Last Edited: 06.12.2018
Python Version: 3.6.5
4G Magnet Power Supply
Class for sending commands to 4G Magnet Power Supply
IMPORTANT: Magnet has to be in remote mode, can only
be set locally
... | [
"socket.socket"
] | [((1754, 1769), 'socket.socket', 'socket.socket', ([], {}), '()\n', (1767, 1769), False, 'import socket\n')] |
"""
-----------------------------------------------------------------------
Harmoni: a Novel Method for Eliminating Spurious Neuronal Interactions due to the Harmonic Components in Neuronal Data
<NAME>, <NAME>, <NAME>, <NAME>, <NAME>, <NAME>, <NAME>
https://doi.org/10.1101/2021.10.06.463319
----------------------------... | [
"numpy.abs",
"tools_signal.plot_fft",
"scipy.signal.filtfilt",
"tools_signal.hilbert_",
"matplotlib.pyplot.plot",
"tools_connectivity.compute_phase_connectivity",
"matplotlib.pyplot.legend",
"numpy.array",
"numpy.linspace",
"scipy.signal.sawtooth",
"matplotlib.pyplot.figure",
"matplotlib.pyplo... | [((1223, 1247), 'numpy.arange', 'np.arange', (['dt', 't_len', 'dt'], {}), '(dt, t_len, dt)\n', (1232, 1247), True, 'import numpy as np\n'), ((1451, 1480), 'numpy.linspace', 'np.linspace', (['(0)', 't_len', 'n_samp'], {}), '(0, t_len, n_samp)\n', (1462, 1480), True, 'import numpy as np\n'), ((1503, 1536), 'scipy.signal.... |
import copy
import torch
import numpy as np
from torch.utils.data import DataLoader
from src.cli import get_args
from src.utils import capitalize_first_letter, load
from src.data import get_data, get_glove_emotion_embs
from src.trainers.sentiment import SentiTrainer
from src.trainers.emotion import MoseiEmoTrainer, Iem... | [
"torch.manual_seed",
"torch.optim.lr_scheduler.ReduceLROnPlateau",
"src.models.mult.MULTModel",
"copy.deepcopy",
"torch.nn.CrossEntropyLoss",
"torch.nn.BCEWithLogitsLoss",
"torch.nn.L1Loss",
"src.data.get_data",
"torch.nn.MSELoss",
"torch.cuda.is_available",
"torch.nn.Parameter",
"numpy.random... | [((630, 640), 'src.cli.get_args', 'get_args', ([], {}), '()\n', (638, 640), False, 'from src.cli import get_args\n'), ((705, 728), 'torch.manual_seed', 'torch.manual_seed', (['seed'], {}), '(seed)\n', (722, 728), False, 'import torch\n'), ((733, 753), 'numpy.random.seed', 'np.random.seed', (['seed'], {}), '(seed)\n', (... |
# 日志系统
import os
import time
import random
# 步骤组模板
stepsTemplate = """
步骤组: {name}
开始时间: {startTime}
----------------------------------------------
{stepLog}
步骤结束
{errorLog}
结束时间: {endTime}
总耗时: {time}ms
"""
# 步骤模板
# TODO: 步骤组带s, 步骤不带s
stepTemplate = """
步骤{index}: {name}
{runLog}
结果: {result}
开始时间: {startTime}
结束时... | [
"os.path.exists",
"os.makedirs",
"os.getcwd",
"time.localtime",
"random.randint"
] | [((605, 628), 'os.path.exists', 'os.path.exists', (['curPath'], {}), '(curPath)\n', (619, 628), False, 'import os\n'), ((479, 495), 'time.localtime', 'time.localtime', ([], {}), '()\n', (493, 495), False, 'import time\n'), ((657, 677), 'os.makedirs', 'os.makedirs', (['curPath'], {}), '(curPath)\n', (668, 677), False, '... |
import pygame
import numpy as np
import random
import copy
from astar import astar
from constants import DISPLAY_WIDTH, DISPLAY_HEIGHT, PIXEL_SIZE, BLACK, GREEN
class Snake:
def __init__(self):
self.x = round(random.randrange(0, DISPLAY_WIDTH - PIXEL_SIZE) / 20.0) * 20
self.y = round(random.randra... | [
"random.randrange",
"pygame.draw.rect",
"astar.astar",
"copy.deepcopy"
] | [((2424, 2454), 'copy.deepcopy', 'copy.deepcopy', (['self.snake_body'], {}), '(self.snake_body)\n', (2437, 2454), False, 'import copy\n'), ((2479, 2591), 'astar.astar', 'astar', (['grid.grid', '(self.y // PIXEL_SIZE, self.x // PIXEL_SIZE)', '(food.y // PIXEL_SIZE, food.x // PIXEL_SIZE)'], {}), '(grid.grid, (self.y // P... |
# -*- coding: utf-8 -*-
# Copyright 2016 CloudFlare, Inc. All rights reserved.
#
# The contents of this file are 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... | [
"iosxr_eznc.decorators.wrap_xml",
"iosxr_eznc.decorators.qualify"
] | [((1637, 1660), 'iosxr_eznc.decorators.qualify', 'qualify', (['"""filter"""', '(True)'], {}), "('filter', True)\n", (1644, 1660), False, 'from iosxr_eznc.decorators import wrap_xml, qualify, raise_eznc_exception, jsonify\n'), ((1666, 1684), 'iosxr_eznc.decorators.wrap_xml', 'wrap_xml', (['"""filter"""'], {}), "('filter... |
#!/usr/bin/env python
# -*- coding: utf-8 -*-
"""
@Time : 2019/5/15
@Author : AnNing
"""
from __future__ import print_function
import os
import sys
import numpy as np
from initialize import load_yaml_file
from load import ReadAhiL1
TEST = True
def ndsi(in_file_l1, in_file_geo, in_file_cloud):
# ----------... | [
"numpy.sqrt",
"numpy.arccos",
"initialize.load_yaml_file",
"numpy.logical_and.reduce",
"sys.exit",
"numpy.sin",
"load.ReadAhiL1",
"numpy.maximum",
"numpy.round",
"numpy.abs",
"numpy.ones",
"os.path.dirname",
"numpy.isnan",
"numpy.cos",
"numpy.minimum",
"numpy.logical_and",
"os.path.j... | [((7744, 7779), 'os.path.join', 'os.path.join', (['path', '"""ndsi_cfg.yaml"""'], {}), "(path, 'ndsi_cfg.yaml')\n", (7756, 7779), False, 'import os\n'), ((7847, 7882), 'initialize.load_yaml_file', 'load_yaml_file', (['name_list_swath_snc'], {}), '(name_list_swath_snc)\n', (7861, 7882), False, 'from initialize import lo... |
import setuptools
import nltk
with open('requirements.txt') as f:
required = f.read().splitlines()
with open("README.md") as fh:
long_description = fh.read()
nltk.download("punkt")
setuptools.setup(
name='multiner',
version="0.0.1",
description="multilingual named entity recognition with xlm-rob... | [
"setuptools.find_packages",
"nltk.download"
] | [((169, 191), 'nltk.download', 'nltk.download', (['"""punkt"""'], {}), "('punkt')\n", (182, 191), False, 'import nltk\n'), ((437, 463), 'setuptools.find_packages', 'setuptools.find_packages', ([], {}), '()\n', (461, 463), False, 'import setuptools\n')] |
# encoding: utf-8
import argparse, getpass, pymysql, sys, csv
def generateDescriptionReport(connection):
cursor = connection.cursor()
cursor.execute("SET CHARACTER_SET_RESULTS='latin1'")
cursor.execute('''SELECT biomarkers.id, biomarkers.name, biomarkers.description FROM biomarkers''')
with open('res... | [
"csv.writer",
"pymysql.connect",
"argparse.ArgumentParser",
"sys.exit"
] | [((1710, 1772), 'argparse.ArgumentParser', 'argparse.ArgumentParser', ([], {'description': '"""Make description report"""'}), "(description='Make description report')\n", (1733, 1772), False, 'import argparse, getpass, pymysql, sys, csv\n'), ((2358, 2448), 'pymysql.connect', 'pymysql.connect', ([], {'host': 'args.host'... |
from cs50 import get_string
def get_text():
# Prompt for text. If user enters an empty string, prompt again.
while True:
word = get_string("Text: ")
if word != "":
return word
def text_parser(text):
# Helper function for parse input text.
letters = count_letters(text)
... | [
"cs50.get_string"
] | [((146, 166), 'cs50.get_string', 'get_string', (['"""Text: """'], {}), "('Text: ')\n", (156, 166), False, 'from cs50 import get_string\n')] |
"""
This module contains the any stats related functions from the NHL API for players or teams.
"""
import logging
import requests
from hockeygamebot.helpers import utils
# Load configuration file in global scope
urls = utils.load_urls()
def get_player_career_stats(player_id):
"""Returns the career stats of an... | [
"hockeygamebot.helpers.utils.load_urls",
"logging.error",
"requests.get"
] | [((223, 240), 'hockeygamebot.helpers.utils.load_urls', 'utils.load_urls', ([], {}), '()\n', (238, 240), False, 'from hockeygamebot.helpers import utils\n'), ((893, 987), 'logging.error', 'logging.error', (['"""For some reason, %s doesn\'t have regular season stats. (%s)"""', 'player_id', 'e'], {}), '("For some reason, ... |
'''
Created on Jun 3, 2021
@author: immanueltrummer
'''
import torch
from transformers import AutoTokenizer, AutoModelForSequenceClassification
class EntailmentUtil():
""" Methods for checking entailment. """
def __init__(self):
""" Initialize models for entailment checks. """
self.tokeni... | [
"transformers.AutoModelForSequenceClassification.from_pretrained",
"transformers.AutoTokenizer.from_pretrained"
] | [((326, 377), 'transformers.AutoTokenizer.from_pretrained', 'AutoTokenizer.from_pretrained', (['"""roberta-large-mnli"""'], {}), "('roberta-large-mnli')\n", (355, 377), False, 'from transformers import AutoTokenizer, AutoModelForSequenceClassification\n'), ((399, 471), 'transformers.AutoModelForSequenceClassification.f... |
def dmsg(text_s = '', verbose = False): # Usage : dmsg('any message')
if verbose:
return
import inspect
frame = inspect.currentframe()
fname = str.split(str(frame.f_back.f_code),'"')[1] # <code object dmsg at 0x7f63ad0a08a0, file "./../src/vps/vps.py", line 47>
line = str(frame.f_back.f_line... | [
"inspect.currentframe"
] | [((132, 154), 'inspect.currentframe', 'inspect.currentframe', ([], {}), '()\n', (152, 154), False, 'import inspect\n')] |
# -*- coding: utf-8 -*-
import common as c
def q2():
"""
Questão 2
"""
print ("Cossenos diretores:")
print (c.dcos([3, 6], True))
| [
"common.dcos"
] | [((135, 155), 'common.dcos', 'c.dcos', (['[3, 6]', '(True)'], {}), '([3, 6], True)\n', (141, 155), True, 'import common as c\n')] |
#!/usr/bin/env python
import overpy # "conda install -c conda-forge overpy" -- a Python Wrapper to access the OpenStreepMap Overpass API
import csv
import time
# building_types are defined for key:building:accommodations at https://wiki.openstreetmap.org/wiki/Key:building
building_types = ["apartments",
... | [
"csv.writer",
"overpy.Overpass",
"time.sleep",
"csv.DictReader"
] | [((993, 1010), 'overpy.Overpass', 'overpy.Overpass', ([], {}), '()\n', (1008, 1010), False, 'import overpy\n'), ((1733, 1758), 'time.sleep', 'time.sleep', (['seconds_sleep'], {}), '(seconds_sleep)\n', (1743, 1758), False, 'import time\n'), ((1955, 1979), 'csv.writer', 'csv.writer', (['csv_coords_w'], {}), '(csv_coords_... |
# to do:
# - read in tidal predictions (if file exists) to validate data
import socket
import numpy as np
def ADCP_read(stage_instance, udp_IP = "", udp_port = 61557, buff_size = 1024, timeout = 5):
"""
Reads ADCP data continously from the specified port.
**EDITING NOTE - break added after timeout**
... | [
"numpy.mean",
"socket.socket",
"numpy.array",
"numpy.resize",
"numpy.arctan"
] | [((606, 654), 'socket.socket', 'socket.socket', (['socket.AF_INET', 'socket.SOCK_DGRAM'], {}), '(socket.AF_INET, socket.SOCK_DGRAM)\n', (619, 654), False, 'import socket\n'), ((3093, 3111), 'numpy.array', 'np.array', (['currents'], {}), '(currents)\n', (3101, 3111), True, 'import numpy as np\n'), ((3126, 3151), 'numpy.... |
# coding: utf-8
import os
import zipfile
from contextlib import contextmanager
from time import time
from ._compat import lru_cache
from .logging import get_logger
class BaseBackend(object):
dbname = None
connections = {"default": {}}
schema_filename = "dump/schema.sql"
initial_setup_files = (schema_... | [
"time.time",
"os.path.basename",
"zipfile.ZipFile"
] | [((840, 846), 'time.time', 'time', ([], {}), '()\n', (844, 846), False, 'from time import time\n'), ((8117, 8142), 'zipfile.ZipFile', 'zipfile.ZipFile', (['filename'], {}), '(filename)\n', (8132, 8142), False, 'import zipfile\n'), ((897, 903), 'time.time', 'time', ([], {}), '()\n', (901, 903), False, 'from time import ... |
import sys
import signal
import os
import subprocess
import selectors
import importlib
logger = importlib.import_module("logger")
tun = importlib.import_module("tun")
crypto = importlib.import_module("crypto")
udp = importlib.import_module("udp")
tun_name = ""
mode = None
addr = None
key = None
auth_msg = b"Infini... | [
"signal.signal",
"importlib.import_module",
"os.write",
"os.putenv",
"subprocess.run",
"selectors.DefaultSelector",
"os.read"
] | [((98, 131), 'importlib.import_module', 'importlib.import_module', (['"""logger"""'], {}), "('logger')\n", (121, 131), False, 'import importlib\n'), ((138, 168), 'importlib.import_module', 'importlib.import_module', (['"""tun"""'], {}), "('tun')\n", (161, 168), False, 'import importlib\n'), ((178, 211), 'importlib.impo... |
# -*- coding: utf-8 -*-
import argparse as ap
import numpy as np
class Error:
access = 123
class Options:
""" Options-parsing class """
keys = [ 'outfile', 'vasprun', 'orbitals', 'ions', 'efermi', 'range', 'labels', 'dpi' ]
def __init__(self, *args):
"""
Initialization of parser, ... | [
"argparse.ArgumentParser"
] | [((379, 440), 'argparse.ArgumentParser', 'ap.ArgumentParser', ([], {'description': '"""Plotting the projected bands"""'}), "(description='Plotting the projected bands')\n", (396, 440), True, 'import argparse as ap\n')] |
import unittest
from taxonomy import Taxonomy, TaxonomyError
class NewickTestCase(unittest.TestCase):
def _create_tax(self):
# https://en.wikipedia.org/wiki/Newick_format#Examples
return Taxonomy.from_newick("(A:0.1,B:0.2,(C:0.3,D:0.4)E:0.5)F;")
def setUp(self) -> None:
self.tax = se... | [
"unittest.main",
"taxonomy.Taxonomy.from_ncbi",
"unittest.skip",
"taxonomy.Taxonomy.from_newick"
] | [((5929, 5994), 'unittest.skip', 'unittest.skip', (['"""tax.remove doesn\'t work on truncated taxonomies?"""'], {}), '("tax.remove doesn\'t work on truncated taxonomies?")\n', (5942, 5994), False, 'import unittest\n'), ((6617, 6632), 'unittest.main', 'unittest.main', ([], {}), '()\n', (6630, 6632), False, 'import unitt... |
#-*-coding=utf-8-*-
"""
Momentum Contrast Encoder for CIFAR 10
@author Sentinel
@date 2021.9.1
"""
import torch
from torch import nn
from torch.nn.modules.batchnorm import BatchNorm2d
from torch.nn.modules.linear import Linear
from torchvision.models import resnet18
def makeConvBlock(in_chan:int, out_ch... | [
"torch.nn.BatchNorm2d",
"torch.nn.ReLU",
"torch.nn.init.constant_",
"torch.nn.Sequential",
"torch.nn.init.kaiming_normal_",
"torchvision.models.resnet18",
"torch.nn.Conv2d",
"torch.nn.Linear",
"torch.nn.AvgPool2d",
"torch.nn.init.normal_"
] | [((627, 647), 'torch.nn.Sequential', 'nn.Sequential', (['*bloc'], {}), '(*bloc)\n', (640, 647), False, 'from torch import nn\n'), ((396, 450), 'torch.nn.Conv2d', 'nn.Conv2d', (['in_chan', 'out_chan', 'k'], {'stride': '(1)', 'padding': 'pad'}), '(in_chan, out_chan, k, stride=1, padding=pad)\n', (405, 450), False, 'from ... |
add10 = lambda x: x+10
print(add10(20))
square_of_numbers = lambda x: x*x
print(square_of_numbers(9))
add_3_num = lambda x,y,z: x+y+z
print(add_3_num(10,50,100))
points2D = [(1, 9), (4, 1), (5, -3), (10, 2)]
points2D_sorted = sorted(points2D)
print(points2D_sorted)
points2D_sorted = sorted(points2D, key = lambda x... | [
"functools.reduce"
] | [((985, 1014), 'functools.reduce', 'reduce', (['(lambda x, y: x * y)', 'a'], {}), '(lambda x, y: x * y, a)\n', (991, 1014), False, 'from functools import reduce\n')] |
#!/usr/bin/python
"""
Generate a new (and empty) save file with predefined keys. Used to play
with externally generated keys.
(c) 2015 <NAME>
Distributed under the GNU GPL v3 or later, WITHOUT ANY WARRANTY. See the
file "LICENSE.md" for license information.
Usage:
./make-funny-savefile.py <public key> <private ... | [
"os.urandom",
"struct.pack"
] | [((2201, 2214), 'os.urandom', 'os.urandom', (['(4)'], {}), '(4)\n', (2211, 2214), False, 'import os\n'), ((2350, 2396), 'struct.pack', 'struct.pack', (['"""<H"""', 'MESSENGER_STATE_COOKIE_TYPE'], {}), "('<H', MESSENGER_STATE_COOKIE_TYPE)\n", (2361, 2396), False, 'import struct\n'), ((2276, 2303), 'struct.pack', 'struct... |
import pandas as pd
import matplotlib.pyplot as plt
data_frame = pd.read_table("../../../r-basic/data/datacrab.txt", sep = " ")
data_frame
data_frame.describe()
data_frame.dropna().describe()
| [
"pandas.read_table"
] | [((66, 126), 'pandas.read_table', 'pd.read_table', (['"""../../../r-basic/data/datacrab.txt"""'], {'sep': '""" """'}), "('../../../r-basic/data/datacrab.txt', sep=' ')\n", (79, 126), True, 'import pandas as pd\n')] |
import socket
import sys
import time
# Python 2.x-3.x compatibility
try:
import cPickle as pickle
except ImportError:
import pickle
class SimpleUDPClient(object):
UDP_IP = "127.0.0.1"
#UDP_IP = "192.168.42.1"
#UDP_IP = "192.168.3.11"
UDP_PORT = 5005
sock=None
def __init__(self, UDP_IP, UDP_PORT,pickle_prot... | [
"pickle.dumps",
"time.time",
"socket.socket",
"sys.exit"
] | [((437, 485), 'socket.socket', 'socket.socket', (['socket.AF_INET', 'socket.SOCK_DGRAM'], {}), '(socket.AF_INET, socket.SOCK_DGRAM)\n', (450, 485), False, 'import socket\n'), ((946, 995), 'pickle.dumps', 'pickle.dumps', (['data'], {'protocol': 'self.pickle_protocol'}), '(data, protocol=self.pickle_protocol)\n', (958, 9... |
import math
from Implementations.Interfaces.IDeterministicAlgorithm import IDeterministicAlgorithm
from Implementations.helpers import Helper
from Implementations.helpers.Helper import ListToPolynomial, toNumbers, sumSet
class DivideAndConquerRunner(IDeterministicAlgorithm):
def __init__(self, label, benchmarkM... | [
"Implementations.helpers.Helper.divideAndConquerSumSet"
] | [((452, 497), 'Implementations.helpers.Helper.divideAndConquerSumSet', 'Helper.divideAndConquerSumSet', (['values', 'target'], {}), '(values, target)\n', (481, 497), False, 'from Implementations.helpers import Helper\n')] |
from django import template
register = template.Library()
def get(value, key):
return value.get(key)
register.filter('get', get)
| [
"django.template.Library"
] | [((40, 58), 'django.template.Library', 'template.Library', ([], {}), '()\n', (56, 58), False, 'from django import template\n')] |
import time
import cv2
import mss
import numpy
frame_width = 800
frame_height = 640
frame_rate = 20.0
VIDEO_OUTPUT = "output.avi"
fourcc = cv2.VideoWriter_fourcc(*'XVID')
out = cv2.VideoWriter(VIDEO_OUTPUT, fourcc, frame_rate,
(frame_width, frame_height))
with mss.mss() as sct:
# Part of t... | [
"mss.mss",
"cv2.VideoWriter",
"cv2.imshow",
"cv2.waitKey",
"cv2.destroyAllWindows",
"cv2.VideoWriter_fourcc",
"cv2.cvtColor",
"cv2.resize",
"time.time"
] | [((141, 172), 'cv2.VideoWriter_fourcc', 'cv2.VideoWriter_fourcc', (["*'XVID'"], {}), "(*'XVID')\n", (163, 172), False, 'import cv2\n'), ((179, 257), 'cv2.VideoWriter', 'cv2.VideoWriter', (['VIDEO_OUTPUT', 'fourcc', 'frame_rate', '(frame_width, frame_height)'], {}), '(VIDEO_OUTPUT, fourcc, frame_rate, (frame_width, fram... |
# -*- coding: utf-8 -*-
from __future__ import unicode_literals
from django.db import models, migrations
from django.conf import settings
class Migration(migrations.Migration):
dependencies = [
migrations.swappable_dependency(settings.AUTH_USER_MODEL),
('notifications', '0003_auto_20150702_1236'... | [
"django.db.models.ForeignKey",
"django.db.migrations.AlterModelOptions",
"django.db.models.AutoField",
"django.db.models.PositiveIntegerField",
"django.db.models.DateTimeField",
"django.db.migrations.swappable_dependency",
"django.db.models.CharField"
] | [((210, 267), 'django.db.migrations.swappable_dependency', 'migrations.swappable_dependency', (['settings.AUTH_USER_MODEL'], {}), '(settings.AUTH_USER_MODEL)\n', (241, 267), False, 'from django.db import models, migrations\n'), ((1112, 1269), 'django.db.migrations.AlterModelOptions', 'migrations.AlterModelOptions', ([]... |
# python libraries
import numpy as np
# matplotlib libraries
import matplotlib.pyplot as plt
from sklearn.model_selection import StratifiedKFold
from sklearn.metrics import f1_score, make_scorer, accuracy_score, average_precision_score, confusion_matrix
from sklearn.ensemble import RandomForestClassifier
from sklearn.... | [
"sys.path.insert",
"util.code_truVrest",
"matplotlib.pyplot.xticks",
"matplotlib.pyplot.ylabel",
"numpy.arange",
"sklearn.utils.shuffle",
"matplotlib.pyplot.legend",
"matplotlib.pyplot.plot",
"matplotlib.pyplot.xlabel",
"numpy.argmax",
"sklearn.preprocessing.StandardScaler",
"numpy.array",
"... | [((444, 483), 'sys.path.insert', 'sys.path.insert', (['(0)', '"""../data+wrangling"""'], {}), "(0, '../data+wrangling')\n", (459, 483), False, 'import sys\n'), ((3532, 3549), 'numpy.argmax', 'np.argmax', (['scores'], {}), '(scores)\n', (3541, 3549), True, 'import numpy as np\n'), ((3930, 3986), 'matplotlib.pyplot.plot'... |
#!/usr/bin/env python3
from smbus2 import SMBusWrapper
from ubloxI2c import UbloxI2C
from ubloxMessage import UbloxMessage
import logging
import time
def extractMessages(data):
messages = []
while data is not None:
msgFormat, msgData, remainder = UbloxMessage.parse(data, raw=True)
print('{} m... | [
"logging.basicConfig",
"ubloxMessage.UbloxMessage.parse",
"argparse.ArgumentParser",
"smbus2.SMBusWrapper",
"time.sleep",
"ubloxI2c.UbloxI2C"
] | [((526, 551), 'argparse.ArgumentParser', 'argparse.ArgumentParser', ([], {}), '()\n', (549, 551), False, 'import argparse\n'), ((741, 783), 'logging.basicConfig', 'logging.basicConfig', ([], {'level': 'logging.WARNING'}), '(level=logging.WARNING)\n', (760, 783), False, 'import logging\n'), ((265, 299), 'ubloxMessage.Ub... |
from django.contrib import admin
from finial import models
class UserTemplateOverrideAdmin(admin.ModelAdmin):
search_fields = ('user', 'override_name', 'override_dir')
raw_id_fields = ('user',)
list_display = ('user', 'override_name', 'override_dir', 'priority', )
list_filter = ('override_name', 'over... | [
"django.contrib.admin.site.register"
] | [((335, 410), 'django.contrib.admin.site.register', 'admin.site.register', (['models.UserTemplateOverride', 'UserTemplateOverrideAdmin'], {}), '(models.UserTemplateOverride, UserTemplateOverrideAdmin)\n', (354, 410), False, 'from django.contrib import admin\n')] |
from sklearn import datasets
import time
from sklearn.decomposition import PCA as SPCA
import cupy as cp
from mlcu.ml.PCA import *
if __name__=="__main__":
'''
loaded_data = datasets.load_iris() #加载鸢尾花数据
data = cp.array(loaded_data.data)
'''
#此数据测试下cuml运算1.9s,sklearn13.1s
X = cp.random.ran... | [
"sklearn.decomposition.PCA",
"time.time",
"cupy.random.rand"
] | [((307, 335), 'cupy.random.rand', 'cp.random.rand', (['(1000000)', '(100)'], {}), '(1000000, 100)\n', (321, 335), True, 'import cupy as cp\n'), ((369, 380), 'time.time', 'time.time', ([], {}), '()\n', (378, 380), False, 'import time\n'), ((411, 422), 'time.time', 'time.time', ([], {}), '()\n', (420, 422), False, 'impor... |
from cobs import cobs
from contextlib import contextmanager
import os
import serial
import serial.tools.list_ports
import six
import sys
from threading import Thread
import zlib
software_root = os.path.dirname(os.path.abspath(__file__))
sys.path.append(os.path.join(software_root, 'proto_gen'))
from proto_gen import s... | [
"serial.tools.list_ports.comports",
"six.moves.input",
"cobs.cobs.decode",
"proto_gen.splitflap_pb2.SplitflapCommand.ModuleCommand",
"os.path.join",
"proto_gen.splitflap_pb2.ToSplitflap",
"serial.Serial",
"cobs.cobs.encode",
"zlib.crc32",
"os.path.abspath",
"threading.Thread",
"proto_gen.split... | [((211, 236), 'os.path.abspath', 'os.path.abspath', (['__file__'], {}), '(__file__)\n', (226, 236), False, 'import os\n'), ((254, 294), 'os.path.join', 'os.path.join', (['software_root', '"""proto_gen"""'], {}), "(software_root, 'proto_gen')\n", (266, 294), False, 'import os\n'), ((3030, 3065), 'six.moves.input', 'six.... |
import argparse
import os
import sys
from PyQt5 import QtWidgets
from .rama_analyzer import RamaAnalyzerMain
def run():
p = argparse.ArgumentParser(description='Analyze Ramachandran plots of Gromacs trajectories')
p.add_argument('-f', action='store', dest='XVGFILE', type=str, help='.xvg file produced by gmx... | [
"os.path.expanduser",
"os.path.exists",
"argparse.ArgumentParser",
"PyQt5.QtWidgets.QApplication"
] | [((132, 226), 'argparse.ArgumentParser', 'argparse.ArgumentParser', ([], {'description': '"""Analyze Ramachandran plots of Gromacs trajectories"""'}), "(description=\n 'Analyze Ramachandran plots of Gromacs trajectories')\n", (155, 226), False, 'import argparse\n'), ((409, 435), 'PyQt5.QtWidgets.QApplication', 'QtWi... |
import os
from datetime import datetime
import sys
try:
from hashlib import sha1
except ImportError:
sys.exit('ImportError: No module named hashlib\n'
'If you are on python2.4 this library is not part of python. '
'Please install it. Example: easy_install hashlib')
from sqlalchemy imp... | [
"sqlalchemy.orm.relation",
"sqlalchemy.types.String",
"comcenter.model.DBSession.delete",
"sqlalchemy.ForeignKey",
"comcenter.model.DBSession.add",
"comcenter.model.DBSession.update",
"comcenter.model.DBSession.query",
"comcenter.model.DBSession.flush",
"sys.exit",
"sqlalchemy.Column"
] | [((664, 717), 'sqlalchemy.Column', 'Column', (['Integer'], {'autoincrement': '(True)', 'primary_key': '(True)'}), '(Integer, autoincrement=True, primary_key=True)\n', (670, 717), False, 'from sqlalchemy import Table, ForeignKey, Column\n'), ((1405, 1458), 'sqlalchemy.Column', 'Column', (['Integer'], {'autoincrement': '... |
import os
from html2md import LOCATIONS
from html2md.converter.Rule import Rule
# TODO: duplicate code, see Transformer.py
def _get_class(kls):
parts = kls.split('.')
module = ".".join(parts[:-1])
m = __import__( module )
for comp in parts[1:]:
m = getattr(m, comp)
return m
class Rules(... | [
"html2md.converter.Rule.Rule"
] | [((749, 763), 'html2md.converter.Rule.Rule', 'Rule', (['selector'], {}), '(selector)\n', (753, 763), False, 'from html2md.converter.Rule import Rule\n')] |
#!/usr/bin/python2.7
"""
Copyright (C) 2014 Reinventing Geospatial, Inc.
This program is free software: you can redistribute it and/or modify
it under the terms of the GNU General Public License as published by
the Free Software Foundation, either version 3 of the License, or
(at your option) any later version.
This ... | [
"operator.attrgetter",
"os.path.exists",
"scripts.geopackage.srs.geodetic.Geodetic",
"scripts.geopackage.core.geopackage_core.GeoPackageCore.create_core_tables",
"scripts.geopackage.srs.ellipsoidal_mercator.EllipsoidalMercator",
"scripts.geopackage.tiles.tiles_content_entry.TilesContentEntry",
"scripts.... | [((2868, 2909), 'scripts.geopackage.utility.sql_utility.get_database_connection', 'get_database_connection', (['self.__file_path'], {}), '(self.__file_path)\n', (2891, 2909), False, 'from scripts.geopackage.utility.sql_utility import get_database_connection\n'), ((9232, 9273), 'scripts.geopackage.utility.sql_utility.ge... |
from jumpscale import j
print("[-] zerodb started / configured")
#zerodb
cl = j.clients.zdb.testdb_server_start_client_get(start=True) #starts & resets a zdb in seq mode with name test
server = j.servers.gedis.configure(host = "localhost", port = "8000", websockets_port = "8001", ssl = False, \
zdb_insta... | [
"jumpscale.j.servers.gedis.configure",
"jumpscale.j.clients.zdb.testdb_server_start_client_get"
] | [((80, 136), 'jumpscale.j.clients.zdb.testdb_server_start_client_get', 'j.clients.zdb.testdb_server_start_client_get', ([], {'start': '(True)'}), '(start=True)\n', (124, 136), False, 'from jumpscale import j\n'), ((205, 370), 'jumpscale.j.servers.gedis.configure', 'j.servers.gedis.configure', ([], {'host': '"""localhos... |
from flask import Flask, request
from flask_restful import Resource
from flask_jwt_extended import jwt_required, get_jwt_identity
from ..models import User, Order, MealItem
class PostOrder(Resource):
@jwt_required
def post(self):
'''post an order by the user'''
data = request.get_json()
... | [
"flask_jwt_extended.get_jwt_identity",
"flask.request.get_json"
] | [((296, 314), 'flask.request.get_json', 'request.get_json', ([], {}), '()\n', (312, 314), False, 'from flask import Flask, request\n'), ((1004, 1022), 'flask_jwt_extended.get_jwt_identity', 'get_jwt_identity', ([], {}), '()\n', (1020, 1022), False, 'from flask_jwt_extended import jwt_required, get_jwt_identity\n'), ((1... |
# Generated by Django 3.1.7 on 2021-04-29 15:19
from django.db import migrations, models
import django.db.models.deletion
class Migration(migrations.Migration):
dependencies = [
('core', '0008_auto_20210426_1518'),
]
operations = [
migrations.AddField(
model_name='piece',
... | [
"django.db.models.ForeignKey"
] | [((371, 561), 'django.db.models.ForeignKey', 'models.ForeignKey', ([], {'blank': '(True)', 'help_text': '"""The turn during which this piece was destroyed."""', 'null': '(True)', 'on_delete': 'django.db.models.deletion.CASCADE', 'related_name': '"""+"""', 'to': '"""core.turn"""'}), "(blank=True, help_text=\n 'The tu... |
"""The TrueNAS integration."""
import abc
import asyncio
import async_timeout
import logging
import voluptuous as vol
from aiotruenas_client import CachingMachine as Machine
from aiotruenas_client.disk import Disk
from aiotruenas_client.virtualmachine import VirtualMachine
from homeassistant.config_entries import Co... | [
"logging.getLogger",
"async_timeout.timeout",
"voluptuous.Schema",
"aiotruenas_client.CachingMachine.create",
"homeassistant.util.slugify",
"homeassistant.helpers.update_coordinator.UpdateFailed",
"datetime.timedelta"
] | [((935, 962), 'logging.getLogger', 'logging.getLogger', (['__name__'], {}), '(__name__)\n', (952, 962), False, 'import logging\n'), ((1000, 1014), 'voluptuous.Schema', 'vol.Schema', (['{}'], {}), '({})\n', (1010, 1014), True, 'import voluptuous as vol\n'), ((1508, 1538), 'aiotruenas_client.CachingMachine.create', 'Mach... |
# coding=utf8
import json
import math
from numpy.ma import arange
from data_utils import build_data_loader
from model_utils import load_vocabulary, build_model, model_evaluate
with open('config.json') as config_file:
config = json.load(config_file)
MIN_EPOCH = config['SELECTOR']['MIN_EPOCH']
MAX_EPOCH = config[... | [
"model_utils.model_evaluate",
"data_utils.build_data_loader",
"numpy.ma.arange",
"model_utils.load_vocabulary",
"json.load",
"math.exp"
] | [((233, 255), 'json.load', 'json.load', (['config_file'], {}), '(config_file)\n', (242, 255), False, 'import json\n'), ((483, 534), 'numpy.ma.arange', 'arange', (['MIN_EPOCH', '(MAX_EPOCH + STEP_SIZE)', 'STEP_SIZE'], {}), '(MIN_EPOCH, MAX_EPOCH + STEP_SIZE, STEP_SIZE)\n', (489, 534), False, 'from numpy.ma import arange... |
import os
import numpy as np
from scipy.stats import rankdata
from scipy.special import binom #faster than comb
import dynamicTreeCut.df_apply
from functools import partial
from dynamicTreeCut.R_func import *
chunkSize = 100
#Function to index flat matrix as squareform matrix
def dist_index(i, j, matrix, l, n):
... | [
"numpy.sqrt",
"numpy.argsort",
"numpy.array",
"numpy.arange",
"numpy.mean",
"numpy.repeat",
"numpy.max",
"numpy.min",
"numpy.argmin",
"numpy.round",
"os.path.isfile",
"numpy.isnan",
"numpy.unique",
"numpy.logical_and",
"scipy.stats.rankdata",
"numpy.logical_or",
"numpy.append",
"nu... | [((3209, 3238), 'numpy.mean', 'np.mean', (['CoreAverageDistances'], {}), '(CoreAverageDistances)\n', (3216, 3238), True, 'import numpy as np\n'), ((3289, 3304), 'numpy.round', 'np.round', (['index'], {}), '(index)\n', (3297, 3304), True, 'import numpy as np\n'), ((4419, 4449), 'numpy.round', 'np.round', (['(nMerge * re... |
#from django.utils.translation import ugettext as _
import datetime
from django.db import models
from django.db.models import Q
from django.contrib.auth.models import User
from model_utils.models import TimeStampedModel
from django.utils.timezone import now
from model_utils import Choices
from django.utils import t... | [
"model_utils.Choices",
"datetime.time",
"django.db.models.ForeignKey",
"django.db.models.IntegerField",
"django.db.models.BooleanField",
"django.utils.timezone.now",
"datetime.datetime.now",
"django.db.models.SlugField",
"django.db.models.DateTimeField",
"django.db.models.DecimalField",
"django.... | [((378, 422), 'django.db.models.CharField', 'models.CharField', ([], {'max_length': '(50)', 'unique': '(True)'}), '(max_length=50, unique=True)\n', (394, 422), False, 'from django.db import models\n'), ((434, 488), 'django.db.models.CharField', 'models.CharField', ([], {'max_length': '(25)', 'null': '(True)', 'blank': ... |
import requests, time, sys, schedule
# https://requests.readthedocs.io/en/master/
from bs4 import BeautifulSoup
# https://www.crummy.com/software/BeautifulSoup/bs4/doc/
import smtplib
# Import the email modules we'll need
from email.message import EmailMessage
# Get list of offers
# https://boise.craigslist.org/search... | [
"smtplib.SMTP",
"time.sleep",
"requests.get",
"bs4.BeautifulSoup",
"email.message.EmailMessage"
] | [((1705, 1722), 'requests.get', 'requests.get', (['url'], {}), '(url)\n', (1717, 1722), False, 'import requests, time, sys, schedule\n'), ((1734, 1776), 'bs4.BeautifulSoup', 'BeautifulSoup', (['page.content', '"""html.parser"""'], {}), "(page.content, 'html.parser')\n", (1747, 1776), False, 'from bs4 import BeautifulSo... |
import sqlite3 as sql
def intialDatabaseCreation():
conn = sql.connect('database.db')
print("Opened database successfully");
conn.execute('CREATE TABLE contacts (name TEXT, addr TEXT, city TEXT, email TEXT)')
conn.execute('CREATE TABLE qrCodes (account TEXT, query TEXT, uses integer )')
print("Table crea... | [
"sqlite3.connect"
] | [((62, 88), 'sqlite3.connect', 'sql.connect', (['"""database.db"""'], {}), "('database.db')\n", (73, 88), True, 'import sqlite3 as sql\n'), ((420, 446), 'sqlite3.connect', 'sql.connect', (['"""database.db"""'], {}), "('database.db')\n", (431, 446), True, 'import sqlite3 as sql\n'), ((778, 804), 'sqlite3.connect', 'sql.... |
#!/usr/bin/env python
import rospy
from pb_msgs.msg import LocalizationEstimate
from pb_msgs.msg import PerceptionObstacles
from pb_msgs.msg import LaneMarkers
from pb_msgs.msg import LaneMarker
from math import radians
'''
LaneMarkers {
optional LaneMarker left_lane_marker = 1;
optional LaneMarker right_lane_ma... | [
"pb_msgs.msg.LocalizationEstimate",
"rospy.is_shutdown",
"rospy.init_node",
"math.radians",
"rospy.Rate",
"rospy.Publisher"
] | [((419, 431), 'math.radians', 'radians', (['(220)'], {}), '(220)\n', (426, 431), False, 'from math import radians\n'), ((560, 604), 'rospy.init_node', 'rospy.init_node', (['"""test_node"""'], {'anonymous': '(True)'}), "('test_node', anonymous=True)\n", (575, 604), False, 'import rospy\n'), ((629, 698), 'rospy.Publisher... |
from rest_framework import serializers
from social.models import Post, Comment, UserProfile
class CommentSerializer(serializers.ModelSerializer):
class Meta:
model = Comment
fields = '__all__'
class PostSerializer(serializers.ModelSerializer):
comments = CommentSerializer(many=True, requir... | [
"rest_framework.serializers.SlugField",
"rest_framework.serializers.DateTimeField",
"rest_framework.serializers.ReadOnlyField",
"rest_framework.serializers.TimeField",
"rest_framework.serializers.ImageField",
"rest_framework.serializers.CharField"
] | [((344, 395), 'rest_framework.serializers.ReadOnlyField', 'serializers.ReadOnlyField', ([], {'source': '"""author.username"""'}), "(source='author.username')\n", (369, 395), False, 'from rest_framework import serializers\n'), ((408, 444), 'rest_framework.serializers.CharField', 'serializers.CharField', ([], {'required'... |
# Generated by Django 2.1.2 on 2018-12-26 15:45
from django.db import migrations
class Migration(migrations.Migration):
dependencies = [
('contacts', '0001_initial'),
]
operations = [
migrations.AlterUniqueTogether(
name='contact',
unique_together={('email',)},
... | [
"django.db.migrations.AlterUniqueTogether"
] | [((217, 293), 'django.db.migrations.AlterUniqueTogether', 'migrations.AlterUniqueTogether', ([], {'name': '"""contact"""', 'unique_together': "{('email',)}"}), "(name='contact', unique_together={('email',)})\n", (247, 293), False, 'from django.db import migrations\n')] |
import cv2, torch
from dl.data.txtrecog import datasets
from dl.models import FOTSRes50
from dl.data.utils.converter import toVisualizeQuadsTextRGBimg
if __name__ == '__main__':
model = FOTSRes50(chars=datasets.SynthText_char_labels_without_upper_blank, input_shape=(None, None, 3), feature_height=8).cuda()
mo... | [
"dl.models.FOTSRes50",
"cv2.cvtColor",
"cv2.resize",
"cv2.waitKey",
"cv2.imread"
] | [((772, 785), 'cv2.waitKey', 'cv2.waitKey', ([], {}), '()\n', (783, 785), False, 'import cv2, torch\n'), ((1576, 1589), 'cv2.waitKey', 'cv2.waitKey', ([], {}), '()\n', (1587, 1589), False, 'import cv2, torch\n'), ((634, 687), 'cv2.imread', 'cv2.imread', (['"""../../scripts/fots/assets/download.jpeg"""'], {}), "('../../... |
import os, sys
import shutil
from pathlib import Path
import pandas as pd
import urllib
import configparser
try:
from bing import Bing
except ImportError: # Python 3
from .bing import Bing
def download(query, limit=100, output_dir='dataset', adult_filter_off=False,
force_replace=False, timeout=60, verbose... | [
"bing.Bing",
"sys.exit",
"pathlib.Path",
"shutil.rmtree",
"pathlib.Path.is_dir",
"pathlib.Path.mkdir",
"pandas.read_excel",
"pathlib.Path.isdir",
"pandas.isna",
"configparser.RawConfigParser",
"urllib.parse.quote_plus"
] | [((943, 1006), 'bing.Bing', 'Bing', (['query', 'limit', 'image_dir', 'adult', 'timeout', 'filters', 'verbose'], {}), '(query, limit, image_dir, adult, timeout, filters, verbose)\n', (947, 1006), False, 'from bing import Bing\n'), ((1117, 1147), 'configparser.RawConfigParser', 'configparser.RawConfigParser', ([], {}), '... |
import torch.nn as nn
import torch
import cv2
import numpy as np
def eval_net(
net, dataset, gpu=True, vis=None, vis_im=None, vis_gt=None, loss=nn.MSELoss()
):
criterion = loss
net.eval()
losses = 0
torch.cuda.empty_cache()
for iteration, data in enumerate(dataset):
img = data["image"]... | [
"torch.nn.MSELoss",
"torch.cuda.empty_cache"
] | [((150, 162), 'torch.nn.MSELoss', 'nn.MSELoss', ([], {}), '()\n', (160, 162), True, 'import torch.nn as nn\n'), ((221, 245), 'torch.cuda.empty_cache', 'torch.cuda.empty_cache', ([], {}), '()\n', (243, 245), False, 'import torch\n')] |
'''
Max Of Three
Exercise 28
Implement a function that takes as input three variables, and returns the largest of the three.
Do this without using the Python max() function
'''
import random
def max_of_three(a, b, c):
if a>b:
if a>c:
return a
else:
return c
else:
... | [
"random.randint"
] | [((556, 581), 'random.randint', 'random.randint', (['(-100)', '(100)'], {}), '(-100, 100)\n', (570, 581), False, 'import random\n'), ((590, 615), 'random.randint', 'random.randint', (['(-100)', '(100)'], {}), '(-100, 100)\n', (604, 615), False, 'import random\n'), ((624, 649), 'random.randint', 'random.randint', (['(-1... |
#!/usr/bin/env python3
# -*- coding: utf-8 -*-
"""
This is the script with the main code of the application
"""
import json
import logging
import aiohttp.web
import connexion
async def index(request):
"""
Redirecting root to index.html
"""
raise aiohttp.web.HTTPFound('/index.html')
def go():
"... | [
"logging.getLogger",
"connexion.AioHttpApp",
"logging.basicConfig"
] | [((365, 434), 'connexion.AioHttpApp', 'connexion.AioHttpApp', (['__name__'], {'port': '(80)', 'specification_dir': '"""/app/web"""'}), "(__name__, port=80, specification_dir='/app/web')\n", (385, 434), False, 'import connexion\n'), ((662, 686), 'logging.getLogger', 'logging.getLogger', (['"""app"""'], {}), "('app')\n",... |
from types import TracebackType
from typing import Dict, Optional, Type, Union
try:
from typing import Literal
except ImportError:
from typing_extensions import Literal
from aiohttp.client import ClientSession
from warnings import warn
from neispy.error import ExceptionsMapping
class NeispyRequest:
BASE... | [
"warnings.warn",
"aiohttp.client.ClientSession"
] | [((637, 680), 'warnings.warn', 'warn', (['"""API키가 없습니다, 샘플키로 요청합니다"""', 'UserWarning'], {}), "('API키가 없습니다, 샘플키로 요청합니다', UserWarning)\n", (641, 680), False, 'from warnings import warn\n'), ((1350, 1365), 'aiohttp.client.ClientSession', 'ClientSession', ([], {}), '()\n', (1363, 1365), False, 'from aiohttp.client import... |
import pickle
import numpy as np
import pygame
from time import sleep
#Duplicate of the Arduino map function (needed for processing autoencoder data)
def map(x, in_min, in_max, out_min, out_max):
return (x - in_min) * (out_max - out_min) // (in_max - in_min) + out_min
class number:
def __init__(self, imag... | [
"numpy.reshape",
"pygame.init",
"pygame.quit",
"pygame.event.get",
"pygame.display.set_mode",
"pygame.display.flip",
"pickle.load",
"time.sleep",
"pygame.draw.rect",
"pygame.display.set_caption",
"pygame.font.Font"
] | [((4453, 4467), 'pickle.load', 'pickle.load', (['f'], {}), '(f)\n', (4464, 4467), False, 'import pickle\n'), ((1205, 1218), 'pygame.init', 'pygame.init', ([], {}), '()\n', (1216, 1218), False, 'import pygame\n'), ((1261, 1310), 'pygame.display.set_mode', 'pygame.display.set_mode', (['(screenSize, screenSize)'], {}), '(... |
from argparse import ArgumentParser
from environment import Environment
from modules.migration.managers.migration_manager import MigrationManager
""" Script for running database migrations
"""
def parse_args():
"""Parses argument parameters
"""
parser = ArgumentParser()
parser.add_argument(
'... | [
"environment.Environment",
"modules.migration.managers.migration_manager.MigrationManager",
"argparse.ArgumentParser"
] | [((269, 285), 'argparse.ArgumentParser', 'ArgumentParser', ([], {}), '()\n', (283, 285), False, 'from argparse import ArgumentParser\n'), ((1207, 1220), 'environment.Environment', 'Environment', ([], {}), '()\n', (1218, 1220), False, 'from environment import Environment\n'), ((1519, 1537), 'modules.migration.managers.m... |
from __future__ import unicode_literals
from django.core.urlresolvers import reverse
from django.db import models
from django.utils.translation import ugettext_lazy as _
from django.utils.encoding import python_2_unicode_compatible
from base.models import ActiveManager, StandardMetadata
@python_2_unicode_compatible... | [
"base.models.ActiveManager",
"django.db.models.Manager",
"django.core.urlresolvers.reverse",
"django.utils.translation.ugettext_lazy"
] | [((783, 799), 'django.db.models.Manager', 'models.Manager', ([], {}), '()\n', (797, 799), False, 'from django.db import models\n'), ((813, 828), 'base.models.ActiveManager', 'ActiveManager', ([], {}), '()\n', (826, 828), False, 'from base.models import ActiveManager, StandardMetadata\n'), ((689, 698), 'django.utils.tra... |
import random
import sqlite3
def globalrecommendations():
globalrecommendationslist=list()
handle= open("static/recommendation_files/global.txt")
rankingdict=dict()
for line in handle:
terms=line.strip()
rankingdict[terms]= rankingdict.get(terms,0)+1
sorted_ranking = sorted(rankingd... | [
"sqlite3.connect",
"random.randint"
] | [((942, 971), 'random.randint', 'random.randint', (['(0)', 'termscount'], {}), '(0, termscount)\n', (956, 971), False, 'import random\n'), ((1064, 1100), 'sqlite3.connect', 'sqlite3.connect', (['"""static/catalog.db"""'], {}), "('static/catalog.db')\n", (1079, 1100), False, 'import sqlite3\n'), ((1391, 1427), 'sqlite3.... |
# -*- coding: utf-8 -*-
# Form implementation generated from reading ui file 'resources\ui\mainwindow.ui'
#
# Created: Sat Jul 15 12:57:34 2017
# by: pyside-uic 0.2.15 running on PySide 1.2.4
#
# WARNING! All changes made in this file will be lost!
from PySide import QtCore, QtGui
class Ui_MainWindow(object):
... | [
"PySide.QtGui.QGridLayout",
"PySide.QtCore.QMetaObject.connectSlotsByName",
"PySide.QtGui.QFont",
"PySide.QtGui.QTableWidget",
"PySide.QtCore.QSize",
"PySide.QtGui.QSizePolicy",
"PySide.QtGui.QPushButton",
"PySide.QtGui.QVBoxLayout",
"PySide.QtGui.QWidget",
"PySide.QtGui.QLabel",
"PySide.QtGui.Q... | [((458, 531), 'PySide.QtGui.QSizePolicy', 'QtGui.QSizePolicy', (['QtGui.QSizePolicy.Preferred', 'QtGui.QSizePolicy.Minimum'], {}), '(QtGui.QSizePolicy.Preferred, QtGui.QSizePolicy.Minimum)\n', (475, 531), False, 'from PySide import QtCore, QtGui\n'), ((886, 911), 'PySide.QtGui.QWidget', 'QtGui.QWidget', (['MainWindow']... |
from comet_ml import experiment
from data_loader.uts_regression_data_loader import UtsRegressionDataLoader
from models.uts_regression_model import UtsRegressionModel
from trainers.uts_regression_trainer import UtsRegressionModelTrainer
from evaluater.uts_regression_evaluater import UtsRegressionEvaluater
from utils.con... | [
"data_loader.uts_regression_data_loader.UtsRegressionDataLoader",
"utils.config.process_config_UtsRegression",
"models.uts_regression_model.UtsRegressionModel",
"trainers.uts_regression_trainer.UtsRegressionModelTrainer",
"evaluater.uts_regression_evaluater.UtsRegressionEvaluater",
"utils.utils.get_args",... | [((799, 888), 'utils.dirs.create_dirs', 'create_dirs', (['[config.callbacks.tensorboard_log_dir, config.callbacks.checkpoint_dir]'], {}), '([config.callbacks.tensorboard_log_dir, config.callbacks.\n checkpoint_dir])\n', (810, 888), False, 'from utils.dirs import create_dirs\n'), ((943, 974), 'data_loader.uts_regress... |
import datetime
from nose.tools import (
assert_raises,
eq_,
set_trace,
)
from . import DatabaseTest
from bot import Bot
from model import (
InvalidPost,
Post,
_now,
)
class TestBot(DatabaseTest):
def test_publishable_posts(self):
bot = self._bot(config=dict(
state_... | [
"nose.tools.eq_",
"model.Post.from_content",
"nose.tools.assert_raises",
"model._now",
"datetime.timedelta"
] | [((382, 411), 'nose.tools.eq_', 'eq_', (['(False)', 'bot.state_updated'], {}), '(False, bot.state_updated)\n', (385, 411), False, 'from nose.tools import assert_raises, eq_, set_trace\n'), ((622, 661), 'nose.tools.eq_', 'eq_', (['new_post.content', 'bot.new_posts[0]'], {}), '(new_post.content, bot.new_posts[0])\n', (62... |
from __future__ import unicode_literals
from __future__ import print_function
from __future__ import division
from __future__ import absolute_import
from future import standard_library
standard_library.install_aliases()
import os
import sys
import hysds_commons.linux_utils
def get_container_host_ip():
"""Return ... | [
"future.standard_library.install_aliases",
"sys.platform.startswith"
] | [((185, 219), 'future.standard_library.install_aliases', 'standard_library.install_aliases', ([], {}), '()\n', (217, 219), False, 'from future import standard_library\n'), ((465, 497), 'sys.platform.startswith', 'sys.platform.startswith', (['"""linux"""'], {}), "('linux')\n", (488, 497), False, 'import sys\n')] |
import dataclasses
from typing import Any, ClassVar, Dict, Iterable, Optional
from dbdaora.data_sources.fallback import FallbackDataSource
@dataclasses.dataclass
class DictFallbackDataSource(FallbackDataSource[str]):
db: Dict[Optional[str], Dict[str, Any]] = dataclasses.field(
default_factory=dict
)
... | [
"dataclasses.field"
] | [((266, 305), 'dataclasses.field', 'dataclasses.field', ([], {'default_factory': 'dict'}), '(default_factory=dict)\n', (283, 305), False, 'import dataclasses\n')] |
import torch
import torch.nn as nn
from collections import Counter
class GraphNorm(nn.Module):
def __init__(self, latent_dim):
super().__init__()
self.weight = nn.Parameter(torch.ones(latent_dim))
self.bias = nn.Parameter(torch.zeros(latent_dim))
self.mean_scale = nn.Parameter(torch... | [
"torch.Tensor",
"torch.zeros",
"torch.ones"
] | [((194, 216), 'torch.ones', 'torch.ones', (['latent_dim'], {}), '(latent_dim)\n', (204, 216), False, 'import torch\n'), ((251, 274), 'torch.zeros', 'torch.zeros', (['latent_dim'], {}), '(latent_dim)\n', (262, 274), False, 'import torch\n'), ((315, 337), 'torch.ones', 'torch.ones', (['latent_dim'], {}), '(latent_dim)\n'... |
#!/usr/bin/python
import os
os.system("cgx -bg blisk_pre.fbd")
os.system("ccx blisk")
os.system("cgx -bg blisk_post.fbd")
| [
"os.system"
] | [((29, 63), 'os.system', 'os.system', (['"""cgx -bg blisk_pre.fbd"""'], {}), "('cgx -bg blisk_pre.fbd')\n", (38, 63), False, 'import os\n'), ((64, 86), 'os.system', 'os.system', (['"""ccx blisk"""'], {}), "('ccx blisk')\n", (73, 86), False, 'import os\n'), ((87, 122), 'os.system', 'os.system', (['"""cgx -bg blisk_post.... |
# DATA 515 - Spring 2017
# Homework 4
# <NAME>
# 4/23/17
##### FUNCTIONS #####
import os
import requests
def get_data(url):
'''
Downloads the data if it is not present locally.
Takes no action if the data are already present.
Throws an exception if the URL does not exist.
arguments
-----... | [
"os.path.exists",
"os.path.basename",
"requests.get",
"os.remove"
] | [((506, 527), 'os.path.basename', 'os.path.basename', (['url'], {}), '(url)\n', (522, 527), False, 'import os\n'), ((564, 588), 'os.path.exists', 'os.path.exists', (['filename'], {}), '(filename)\n', (578, 588), False, 'import os\n'), ((1666, 1687), 'os.path.basename', 'os.path.basename', (['url'], {}), '(url)\n', (168... |
#!/usr/bin/env python
# encoding: utf-8
'''
@project : MSRGCN
@file : config.py
@author : Droliven
@contact : <EMAIL>
@ide : PyCharm
@time : 2021-07-27 16:56
'''
import os
import getpass
import torch
import numpy as np
class Config():
def __init__(self, exp_name="h36m", input_n=10, output_n=10, dct_n=1... | [
"getpass.getuser",
"numpy.array",
"os.path.join"
] | [((397, 414), 'getpass.getuser', 'getpass.getuser', ([], {}), '()\n', (412, 414), False, 'import getpass\n'), ((5601, 5692), 'os.path.join', 'os.path.join', (['"""./ckpt/"""', 'exp_name', "('short_term' if self.output_n == 10 else 'long_term')"], {}), "('./ckpt/', exp_name, 'short_term' if self.output_n == 10 else\n ... |
import numpy as np
import pandas as pd
from numpy.testing import assert_array_equal
from numpy.testing import assert_array_almost_equal
from auxiliary.functions_daniel import (
rastrigin_instance,
griewank_instance,
levi_no_13_instance,
rosenbrock_instance,
)
def test_rastrigin():
inputs = crea... | [
"auxiliary.functions_daniel.rosenbrock_instance",
"auxiliary.functions_daniel.rastrigin_instance",
"numpy.testing.assert_array_almost_equal",
"auxiliary.functions_daniel.levi_no_13_instance",
"auxiliary.functions_daniel.griewank_instance",
"numpy.array"
] | [((347, 368), 'auxiliary.functions_daniel.rastrigin_instance', 'rastrigin_instance', (['(3)'], {}), '(3)\n', (365, 368), False, 'from auxiliary.functions_daniel import rastrigin_instance, griewank_instance, levi_no_13_instance, rosenbrock_instance\n'), ((389, 433), 'numpy.array', 'np.array', (['[15, 111, 139, 31, 2, 46... |
# Copyright 2018 Blade Team of Tencent. All Rights Reserved.
#
# Licensed under the Apache License, Version 2.0 (the "License");
# you may not use this file except in compliance with the License.
# You may obtain a copy of the License at
#
# http://www.apache.org/licenses/LICENSE-2.0
#
# Unless required by applicab... | [
"tensorflow.python.platform.app.run",
"tensorflow.core.protobuf.meta_graph_pb2.MetaGraphDef",
"argparse.ArgumentParser",
"tensorflow.python.training.saver.checkpoint_exists",
"tensorflow.python.tools.saved_model_utils.get_meta_graph_def",
"tensorflow.python.platform.gfile.FastGFile",
"sys.exc_info",
"... | [((2533, 2547), 'tensorflow.core.protobuf.meta_graph_pb2.MetaGraphDef', 'MetaGraphDef', ([], {}), '()\n', (2545, 2547), False, 'from tensorflow.core.protobuf.meta_graph_pb2 import MetaGraphDef\n'), ((5678, 5787), 'argparse.ArgumentParser', 'argparse.ArgumentParser', ([], {'description': '"""Check whether a TensorFlow m... |
from kivy.app import App
from kivy.uix.gridlayout import GridLayout
from kivy.uix.label import Label
from kivy.uix.textinput import TextInput
from kivy.uix.button import Button
from kivy.uix.popup import Popup
class Screen(GridLayout):
def __init__(self) -> None:
super().__init__()
self.add_widge... | [
"kivy.uix.label.Label"
] | [((322, 345), 'kivy.uix.label.Label', 'Label', ([], {'text': '"""Tela Base"""'}), "(text='Tela Base')\n", (327, 345), False, 'from kivy.uix.label import Label\n')] |
# Copyright (C) <NAME> 2020.
# Distributed under the MIT License (see the accompanying README.md and LICENSE files).
import numpy as np
import utils.clicks as clk
def oracle_doc_variance(
expected_reward,
doc_values,
rel_prob,
obs_prob,
sampled_inv_rankings):
n_doc... | [
"numpy.mean",
"numpy.tile",
"numpy.exp",
"numpy.sum",
"utils.clicks.bernoilli_sample_from_probs",
"numpy.zeros",
"numpy.add.at",
"numpy.amax",
"numpy.arange"
] | [((360, 407), 'numpy.mean', 'np.mean', (['obs_prob[sampled_inv_rankings]'], {'axis': '(0)'}), '(obs_prob[sampled_inv_rankings], axis=0)\n', (367, 407), True, 'import numpy as np\n'), ((643, 664), 'numpy.mean', 'np.mean', (['doc_variance'], {}), '(doc_variance)\n', (650, 664), True, 'import numpy as np\n'), ((1262, 1309... |
import pytest
from pytest import (
raises,
)
from lark.exceptions import (
UnexpectedToken,
)
valid_dicts = [
"""
a = {a: b}
""",
"""
a = {1: 2}
""",
"""
{
1: 2,
3: 4
}
"""
]
@pytest.mark.parametrize('good_code', valid_dicts)
def test_grammar_good_dicts(good_code, lark_gramma... | [
"pytest.mark.parametrize",
"pytest.raises"
] | [((220, 269), 'pytest.mark.parametrize', 'pytest.mark.parametrize', (['"""good_code"""', 'valid_dicts'], {}), "('good_code', valid_dicts)\n", (243, 269), False, 'import pytest\n'), ((488, 538), 'pytest.mark.parametrize', 'pytest.mark.parametrize', (['"""bad_code"""', 'invalid_dicts'], {}), "('bad_code', invalid_dicts)\... |
#------------------------------------------------------------------------------
# Copyright 2013 Esri
# 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/LICENS... | [
"arcpy.GetMessages",
"os.path.join",
"os.path.basename",
"arcpy.SetMosaicDatasetProperties_management"
] | [((1661, 1685), 'os.path.basename', 'os.path.basename', (['mdPath'], {}), '(mdPath)\n', (1677, 1685), False, 'import arcpy, os, sys\n'), ((5536, 6370), 'arcpy.SetMosaicDatasetProperties_management', 'arcpy.SetMosaicDatasetProperties_management', (['mdPath', 'maxRequestSizex', 'maxRequestSizey', 'allowedCompression', 'd... |
'''
GUI for the COVID-19 chatbot.
Enter the query and it returns the list of top 5 papers
which can answer the query.
'''
from tkinter import *
root_path = '/Users/Janjua/Desktop/Projects/Octofying-COVID19-Literature/dataset/CORD-19-research-challenge/'
from sentence_transformers import SentenceTransf... | [
"pickle.load",
"sentence_transformers.SentenceTransformer",
"pandas.read_csv"
] | [((576, 624), 'sentence_transformers.SentenceTransformer', 'SentenceTransformer', (['"""bert-base-nli-mean-tokens"""'], {}), "('bert-base-nli-mean-tokens')\n", (595, 624), False, 'from sentence_transformers import SentenceTransformer\n'), ((872, 936), 'pandas.read_csv', 'pd.read_csv', (["(root_path + 'covid_sentences_f... |
# -*- coding: utf-8 -*-
from openerp import SUPERUSER_ID
from openerp.osv import osv, orm, fields
from openerp.tools.translate import _
class sale_order_line(osv.Model):
_inherit = "sale.order.line"
_columns = {
'linked_line_id': fields.many2one('sale.order.line', 'Linked Order Line', domain="[('orde... | [
"openerp.osv.fields.many2one",
"openerp.tools.translate._",
"openerp.osv.fields.one2many"
] | [((249, 368), 'openerp.osv.fields.many2one', 'fields.many2one', (['"""sale.order.line"""', '"""Linked Order Line"""'], {'domain': '"""[(\'order_id\',\'!=\',order_id)]"""', 'ondelete': '"""cascade"""'}), '(\'sale.order.line\', \'Linked Order Line\', domain=\n "[(\'order_id\',\'!=\',order_id)]", ondelete=\'cascade\')\... |
import ftplib
import os.path
host = 'localhost'
username = 'mory'
password = '<PASSWORD>'
server = ftplib.FTP(host)
server.login(username, password)
def upload(server, filename, bufsize=1024):
pwd = server.pwd()
basename = os.path.basename(filename)
ftp_path = os.path.join(pwd, f"ftp_{basename}")
wi... | [
"ftplib.FTP"
] | [((101, 117), 'ftplib.FTP', 'ftplib.FTP', (['host'], {}), '(host)\n', (111, 117), False, 'import ftplib\n')] |