code stringlengths 22 1.05M | apis listlengths 1 3.31k | extract_api stringlengths 75 3.25M |
|---|---|---|
# pylint: disable=invalid-name
"""Flo Antlr Listener implementation
"""
import importlib
import inspect
import os
import traceback
from typing import Any, Union, Optional, List, Callable
import signal
import sys
# pylint: disable=wildcard-import, unused-wildcard-import
from antlr4 import * # type: ignore
from antlr4.e... | [
"inspect.isbuiltin",
"traceback.print_exc",
"inspect.ismethod",
"importlib.import_module",
"signal.pause",
"inspect.isfunction",
"signal.signal",
"sys.exit",
"inspect.getmembers"
] | [((2835, 2879), 'signal.signal', 'signal.signal', (['signal.SIGINT', 'signal_handler'], {}), '(signal.SIGINT, signal_handler)\n', (2848, 2879), False, 'import signal\n'), ((2815, 2826), 'sys.exit', 'sys.exit', (['(0)'], {}), '(0)\n', (2823, 2826), False, 'import sys\n'), ((2998, 3012), 'signal.pause', 'signal.pause', (... |
"""
This file is part of the TheLMA (THe Laboratory Management Application) project.
See LICENSE.txt for licensing, CONTRIBUTORS.txt for contributor information.
Chemical structure resource.
"""
from everest.resources.base import Member
from everest.resources.descriptors import attribute_alias
from everest.resources.d... | [
"everest.resources.descriptors.member_attribute",
"everest.resources.descriptors.collection_attribute",
"everest.resources.descriptors.attribute_alias",
"everest.resources.descriptors.terminal_attribute"
] | [((927, 958), 'everest.resources.descriptors.terminal_attribute', 'terminal_attribute', (['str', '"""name"""'], {}), "(str, 'name')\n", (945, 958), False, 'from everest.resources.descriptors import terminal_attribute\n'), ((971, 1003), 'everest.resources.descriptors.terminal_attribute', 'terminal_attribute', (['str', '... |
from datetime import datetime
from enum import Enum
from typing import Optional, List, Dict
from pydantic import BaseModel
from pydantic.types import conint, UUID4
from tortoise import fields, models
from tortoise.contrib.pydantic import pydantic_model_creator
class ApplicantDB(models.Model):
id = fields.IntFiel... | [
"tortoise.fields.JSONField",
"tortoise.contrib.pydantic.pydantic_model_creator",
"tortoise.fields.CharField",
"pydantic.types.conint",
"tortoise.fields.IntField"
] | [((1270, 1323), 'tortoise.contrib.pydantic.pydantic_model_creator', 'pydantic_model_creator', (['ApplicantDB'], {'name': '"""Applicant"""'}), "(ApplicantDB, name='Applicant')\n", (1292, 1323), False, 'from tortoise.contrib.pydantic import pydantic_model_creator\n'), ((1348, 1426), 'tortoise.contrib.pydantic.pydantic_mo... |
import pyuarm
from pyuarm.tools.list_uarms import get_uarm_port_cli, uarm_ports
import serial
from serial.tools.list_ports import comports
import json, os, io, sys, time
import logging
def get_port_from_serial_id(serial_id):
ports = comports()
for p in ports:
if p.serial_number == serial_id:
... | [
"serial.tools.list_ports.comports"
] | [((239, 249), 'serial.tools.list_ports.comports', 'comports', ([], {}), '()\n', (247, 249), False, 'from serial.tools.list_ports import comports\n'), ((394, 404), 'serial.tools.list_ports.comports', 'comports', ([], {}), '()\n', (402, 404), False, 'from serial.tools.list_ports import comports\n')] |
# Generated by Django 3.1.6 on 2021-02-12 20:59
from django.db import migrations, models
class Migration(migrations.Migration):
dependencies = [
('resume', '0004_link'),
]
operations = [
migrations.CreateModel(
name='LanguageSkill',
fields=[
('id'... | [
"django.db.models.CharField",
"django.db.models.IntegerField",
"django.db.models.AutoField"
] | [((322, 415), 'django.db.models.AutoField', 'models.AutoField', ([], {'auto_created': '(True)', 'primary_key': '(True)', 'serialize': '(False)', 'verbose_name': '"""ID"""'}), "(auto_created=True, primary_key=True, serialize=False,\n verbose_name='ID')\n", (338, 415), False, 'from django.db import migrations, models\... |
"""
Contains penalty functions.
"""
from abc import ABC, abstractmethod
from typing import List, Union
from mpyc.runtime import mpc
from mpyc.sectypes import SecureFixedPoint
class BaseRegularizer:
"""
Base class for regularizations.
"""
class DifferentiableRegularizer(ABC, BaseRegularizer):
"""
... | [
"mpyc.runtime.mpc.ge",
"mpyc.runtime.mpc.schur_prod",
"mpyc.runtime.mpc.scalar_mul"
] | [((3542, 3570), 'mpyc.runtime.mpc.schur_prod', 'mpc.schur_prod', (['signs', 'coef_'], {}), '(signs, coef_)\n', (3556, 3570), False, 'from mpyc.runtime import mpc\n'), ((3717, 3730), 'mpyc.runtime.mpc.ge', 'mpc.ge', (['_', 'nu'], {}), '(_, nu)\n', (3723, 3730), False, 'from mpyc.runtime import mpc\n'), ((3844, 3869), 'm... |
if __name__ == "__main__":
import argparse
parser = argparse.ArgumentParser(
description="Trains a single Neural-Gas VAE model with a lifetime value"
)
parser.add_argument(
"--gpu", nargs="?", type=int, required=True, help="Select used gpu"
)
parser.add_argument(
"--dat... | [
"torch.nn.MSELoss",
"pytorch_lightning.Trainer",
"pytorch_lightning.callbacks.ModelCheckpoint",
"argparse.ArgumentParser",
"autoencoding.nn.Conv2d_CBnReLU",
"autoencoding.nn.ResidualBlock2d",
"autoencoding.nn.ConvTransposed2d_CBnReLU",
"autoencoding.nn.Lightning_GVQ_VAE_codebook_loss",
"torch.nn.Con... | [((61, 163), 'argparse.ArgumentParser', 'argparse.ArgumentParser', ([], {'description': '"""Trains a single Neural-Gas VAE model with a lifetime value"""'}), "(description=\n 'Trains a single Neural-Gas VAE model with a lifetime value')\n", (84, 163), False, 'import argparse\n'), ((2039, 2064), 'autoencoding.data.CI... |
import torch
from torch.utils.data import DataLoader
from .factory import DatasetFactory, EvaluatorFactory
from .transforms import transforms as T
def make_evaulator(cfg, mode):
factory = EvaluatorFactory(cfg)
func, args = None, None
if mode == 'test':
func, args = factory.get(cfg.TEST.EVALUAT... | [
"torch.utils.data.DataLoader"
] | [((1196, 1285), 'torch.utils.data.DataLoader', 'DataLoader', (['dataset'], {'batch_size': 'batch_size', 'shuffle': 'shuffle', 'num_workers': 'num_workers'}), '(dataset, batch_size=batch_size, shuffle=shuffle, num_workers=\n num_workers)\n', (1206, 1285), False, 'from torch.utils.data import DataLoader\n')] |
import numpy as np
def function_for_pos(mass, mom):
return mom / mass
def function_for_mom(mass1, mass2, diff, dist):
return - mass1 * mass2 / dist ** 3 * diff
def compute_k(mass, pos, mom):
pos_k = [0] * len(pos)
mom_k = [0] * len(pos)
tmp_index = np.arange(len(pos))
index_j, index_i = np.... | [
"numpy.array",
"numpy.meshgrid",
"numpy.linalg.norm"
] | [((317, 350), 'numpy.meshgrid', 'np.meshgrid', (['tmp_index', 'tmp_index'], {}), '(tmp_index, tmp_index)\n', (328, 350), True, 'import numpy as np\n'), ((443, 494), 'numpy.linalg.norm', 'np.linalg.norm', (['(pos[index_i] - pos[index_j])'], {'axis': '(2)'}), '(pos[index_i] - pos[index_j], axis=2)\n', (457, 494), True, '... |
# -*- coding: utf-8 -*-
""" HRA_Transfer_CNN_Manager is a wrapper class which 'encapsulates' the functionalities needed for preparing (class instantiation)
and training different CNNs (`train_model`) on the HRA dataset with 2 classes.
"""
from __future__ import print_function
import os
import sys
import math
impor... | [
"keras.preprocessing.image.ImageDataGenerator",
"keras.callbacks.ModelCheckpoint",
"applications.hra_vgg16_places365.HRA_VGG16_Places365",
"utils.generic_utils.hms_string",
"time.time",
"os.path.isfile",
"keras.callbacks.EarlyStopping",
"applications.hra_vgg16.HRA_VGG16",
"keras.callbacks.CSVLogger"... | [((4235, 4295), 'os.path.join', 'os.path.join', (['self.trained_models_dir', '"""feature_extraction/"""'], {}), "(self.trained_models_dir, 'feature_extraction/')\n", (4247, 4295), False, 'import os\n'), ((4327, 4380), 'os.path.join', 'os.path.join', (['self.trained_models_dir', '"""fine_tuning/"""'], {}), "(self.traine... |
from __future__ import print_function
import os
import time
from select import select
import evdev
button_map = {
'ps3': {
316: 'reset',
307: 'n',
306: 'e',
305: 's',
304: 'w',
309: 'rb',
311: 'rt',
2: 'rjoy',
5: 'rjoy',
1: 'ljoy',
... | [
"select.select",
"os.listdir",
"time.sleep"
] | [((2000, 2024), 'select.select', 'select', (['gamepads', '[]', '[]'], {}), '(gamepads, [], [])\n', (2006, 2024), False, 'from select import select\n'), ((714, 739), 'os.listdir', 'os.listdir', (['"""/dev/input/"""'], {}), "('/dev/input/')\n", (724, 739), False, 'import os\n'), ((2374, 2387), 'time.sleep', 'time.sleep',... |
import click
import csv
from osp.citations.models import Text, Citation, Text_Index
from peewee import fn
@click.group()
def cli():
pass
@cli.command()
@click.argument('out_file', type=click.File('w'))
@click.option('--min_count', default=100)
def fuzz(out_file, min_count):
"""
Write a CSV with tit... | [
"osp.citations.models.Text.select",
"click.option",
"click.File",
"peewee.fn.count",
"csv.DictWriter",
"click.group",
"osp.citations.models.Text_Index.rank_texts"
] | [((113, 126), 'click.group', 'click.group', ([], {}), '()\n', (124, 126), False, 'import click\n'), ((215, 255), 'click.option', 'click.option', (['"""--min_count"""'], {'default': '(100)'}), "('--min_count', default=100)\n", (227, 255), False, 'import click\n'), ((1124, 1161), 'click.option', 'click.option', (['"""--d... |
'''
Copyright 2022 Airbus SAS
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
dis... | [
"os.path.dirname",
"os.path.join",
"sos_trades_core.execution_engine.execution_engine.ExecutionEngine"
] | [((4575, 4596), 'sos_trades_core.execution_engine.execution_engine.ExecutionEngine', 'ExecutionEngine', (['name'], {}), '(name)\n', (4590, 4596), False, 'from sos_trades_core.execution_engine.execution_engine import ExecutionEngine\n'), ((1019, 1036), 'os.path.dirname', 'dirname', (['__file__'], {}), '(__file__)\n', (1... |
#!/usr/bin/env python3
# -*- coding:utf-8 -*-
# author: bigfoolliu
"""
给你一个链表,删除链表的倒数第 n 个节点,并且返回链表的头节点。
进阶:你能尝试使用一趟扫描实现吗?
示例 1:
输入:head = [1,2,3,4,5], n = 2
输出:[1,2,3,5]
示例 2:
输入:head = [1], n = 1
输出:[]
示例 3:
输入:head = [1,2], n = 1
输出:[1]
提示:
链表中节点的数目为 sz
1 <= sz <= 30
0 <= Node.val <= 100
1 <= n <= sz
... | [
"doctest.testmod"
] | [((1852, 1869), 'doctest.testmod', 'doctest.testmod', ([], {}), '()\n', (1867, 1869), False, 'import doctest\n')] |
#!/usr/bin/env python3
# -*- coding: utf-8 -*-
"""
Created on Sat Mar 18 20:55:39 2017
@author: <NAME>
"""
import NetBuilder as nb
import numpy as np
import sys
from sklearn.preprocessing import normalize as norm
def extract_data(filename):
with open(filename) as f:
data = np.loadtxt(f,delimiter=',',skipr... | [
"numpy.vectorize",
"NetBuilder.Network",
"sklearn.preprocessing.normalize",
"numpy.loadtxt",
"numpy.random.shuffle"
] | [((1696, 1722), 'numpy.vectorize', 'np.vectorize', (['change_zeros'], {}), '(change_zeros)\n', (1708, 1722), True, 'import numpy as np\n'), ((2671, 2719), 'NetBuilder.Network', 'nb.Network', ([], {'topology': 'topology', 'learningRate': '(0.01)'}), '(topology=topology, learningRate=0.01)\n', (2681, 2719), True, 'import... |
from typing import TypeVar, Generic
T=TypeVar('T')
class ArrayQueue(Generic[T]):
def __init__(self, capacity:int):
self._capacity=capacity
self._top=-1
self._arr=[]
def is_full(self)->bool:
return self._capacity==self._top+1
def enqueue(self, value:T):
if self.is_fu... | [
"typing.TypeVar"
] | [((38, 50), 'typing.TypeVar', 'TypeVar', (['"""T"""'], {}), "('T')\n", (45, 50), False, 'from typing import TypeVar, Generic\n')] |
import json
import pprint
with open('Planet Matriarchy Characters/Sample Char.tps', 'r') as json_file:
data = json.load(json_file)
pprint.pprint(data)
| [
"json.load",
"pprint.pprint"
] | [((116, 136), 'json.load', 'json.load', (['json_file'], {}), '(json_file)\n', (125, 136), False, 'import json\n'), ((142, 161), 'pprint.pprint', 'pprint.pprint', (['data'], {}), '(data)\n', (155, 161), False, 'import pprint\n')] |
# https://leetcode.com/problems/remove-nth-node-from-end-of-list/
import unittest
from ...leetcode_data_model import ListNode
class Solution(object):
def removeNthFromEnd(self, head, n):
"""
:type head: ListNode
:type n: int
:rtype: ListNode
"""
current = head
... | [
"unittest.main"
] | [((1512, 1527), 'unittest.main', 'unittest.main', ([], {}), '()\n', (1525, 1527), False, 'import unittest\n')] |
"""Remove zipcode field from requests
Revision ID: 028aa87e4f51
Revises: <PASSWORD>
Create Date: 2020-09-14 07:08:53.674713
"""
from alembic import op
import sqlalchemy as sa
# revision identifiers, used by Alembic.
revision = "<KEY>"
down_revision = "5<PASSWORD>d<PASSWORD>"
branch_labels = None
depends_on = None
... | [
"sqlalchemy.INTEGER",
"sqlalchemy.VARCHAR",
"alembic.op.drop_index",
"alembic.op.create_index",
"alembic.op.drop_constraint",
"alembic.op.drop_column",
"alembic.op.create_primary_key"
] | [((406, 465), 'alembic.op.drop_index', 'op.drop_index', (['"""ix_requests_zipcode"""'], {'table_name': '"""requests"""'}), "('ix_requests_zipcode', table_name='requests')\n", (419, 465), False, 'from alembic import op\n'), ((470, 507), 'alembic.op.drop_column', 'op.drop_column', (['"""requests"""', '"""zipcode"""'], {}... |
from django.db.models import Value
from django.test import TestCase
from core.models import JsonbSet
from elections.models import Election
from elections.tests.factories import ElectionFactory
class TestJsonbSet(TestCase):
def setUp(self):
# This would be nice but couldn't make it play: https://code.djan... | [
"elections.models.Election.private_objects.all",
"elections.tests.factories.ElectionFactory",
"django.db.models.Value"
] | [((381, 398), 'elections.tests.factories.ElectionFactory', 'ElectionFactory', ([], {}), '()\n', (396, 398), False, 'from elections.tests.factories import ElectionFactory\n'), ((424, 441), 'elections.tests.factories.ElectionFactory', 'ElectionFactory', ([], {}), '()\n', (439, 441), False, 'from elections.tests.factories... |
# coding=utf-8
# @Author : zhzhx2008
# @Date : 2019/12/29
# from:
# https://arxiv.org/abs/1611.01747,《A COMPARE-AGGREGATE MODEL FOR MATCHING TEXT SEQUENCES》
import warnings
import jieba
import numpy as np
from keras import Model, regularizers, constraints, initializers
from keras.callbacks import EarlyStopping... | [
"keras.backend.dot",
"numpy.random.seed",
"keras.preprocessing.sequence.pad_sequences",
"sklearn.model_selection.train_test_split",
"keras.regularizers.get",
"keras.backend.batch_dot",
"keras.backend.abs",
"keras.backend.relu",
"keras.backend.concatenate",
"keras.preprocessing.text.Tokenizer",
"... | [((538, 571), 'warnings.filterwarnings', 'warnings.filterwarnings', (['"""ignore"""'], {}), "('ignore')\n", (561, 571), False, 'import warnings\n'), ((585, 605), 'numpy.random.seed', 'np.random.seed', (['seed'], {}), '(seed)\n', (599, 605), True, 'import numpy as np\n'), ((7694, 7718), 'numpy.random.shuffle', 'np.rando... |
# Generated by Django 3.2.5 on 2021-08-20 10:02
from django.db import migrations
class Migration(migrations.Migration):
dependencies = [
("services", "0006_auto_20210819_1608"),
]
operations = [
migrations.RenameField(
model_name="service",
old_name="location_kin... | [
"django.db.migrations.RenameField"
] | [((228, 329), 'django.db.migrations.RenameField', 'migrations.RenameField', ([], {'model_name': '"""service"""', 'old_name': '"""location_kind"""', 'new_name': '"""location_kinds"""'}), "(model_name='service', old_name='location_kind',\n new_name='location_kinds')\n", (250, 329), False, 'from django.db import migrat... |
from entropylab.flame.inputs import Inputs
from entropylab.flame.workflow import Workflow
__all__ = ["QPUcircuitRunner"]
class QPUcircuitRunner(object):
def __init__(
self, workflow_node_unique_name, circuit_param=None, error_correction=None
):
"""Executes given circuit sequence
:par... | [
"entropylab.flame.workflow.Workflow._register_node",
"entropylab.flame.inputs.Inputs"
] | [((817, 846), 'entropylab.flame.workflow.Workflow._register_node', 'Workflow._register_node', (['self'], {}), '(self)\n', (840, 846), False, 'from entropylab.flame.workflow import Workflow\n'), ((1375, 1383), 'entropylab.flame.inputs.Inputs', 'Inputs', ([], {}), '()\n', (1381, 1383), False, 'from entropylab.flame.input... |
# Copyright (c) Microsoft Corporation.
# Licensed under the MIT License.
import dataclasses
import json
import logging
import os
import os.path
from urllib.parse import urlparse
import requests
SUBSCRIBERS_DIR = '/subscribers'
# An endpoint that handles unprocessed JSON forwarded from notifications.... | [
"logging.error",
"logging.debug",
"os.path.join",
"json.dumps",
"logging.info",
"os.path.isfile",
"requests.post",
"dataclasses.asdict",
"os.listdir",
"urllib.parse.urlparse"
] | [((498, 531), 'dataclasses.asdict', 'dataclasses.asdict', (['commit_status'], {}), '(commit_status)\n', (516, 531), False, 'import dataclasses\n'), ((635, 688), 'requests.post', 'requests.post', ([], {'url': 'self._url_endpoint', 'json': 'json_data'}), '(url=self._url_endpoint, json=json_data)\n', (648, 688), False, 'i... |
"""Run all tests with filenames beginning with "test*" inside module"""
import sys
import unittest
if __name__ == '__main__':
print("run_tests.py running all tests...")
test_suite = unittest.defaultTestLoader.discover('.', 'test*py')
test_runner = unittest.TextTestRunner(resultclass=unittest.TextTestResul... | [
"unittest.defaultTestLoader.discover",
"unittest.TextTestRunner"
] | [((192, 243), 'unittest.defaultTestLoader.discover', 'unittest.defaultTestLoader.discover', (['"""."""', '"""test*py"""'], {}), "('.', 'test*py')\n", (227, 243), False, 'import unittest\n'), ((262, 322), 'unittest.TextTestRunner', 'unittest.TextTestRunner', ([], {'resultclass': 'unittest.TextTestResult'}), '(resultclas... |
import roslib
import rospy
import geometry_msgs.msg
from nav_msgs.msg import Odometry
import pandas as pd
import os
import time
global df2
global new
global df
import datetime
def collecter(msg):
df = pd.DataFrame.from_csv("~/catkin_ws/data/"+str(name)+".csv")
df2 = pd.DataFrame({'time':[datetime.datetime.now()], 'p... | [
"pandas.DataFrame",
"rospy.Subscriber",
"time.sleep",
"rospy.init_node",
"rospy.spin",
"datetime.datetime.now",
"pandas.concat"
] | [((959, 1056), 'pandas.DataFrame', 'pd.DataFrame', ([], {'columns': "['time', 'pos-x', 'pos-y', 'pos-z', 'ori-x', 'ori-y', 'ori-z', 'ori-w']"}), "(columns=['time', 'pos-x', 'pos-y', 'pos-z', 'ori-x', 'ori-y',\n 'ori-z', 'ori-w'])\n", (971, 1056), True, 'import pandas as pd\n'), ((1098, 1131), 'rospy.init_node', 'ros... |
# %%
import rasterio
import pandas as pds
import numpy as np
import numpy.ma as ma
from sklearn.pipeline import Pipeline
from sklearn.cluster import KMeans
from sklearn.preprocessing import StandardScaler
from sklearn.decomposition import PCA
import matplotlib.pyplot as plt
import seaborn
# %%
HI_RES = '30s'
LOW_RES... | [
"pandas.DataFrame",
"rasterio.open",
"sklearn.preprocessing.StandardScaler",
"numpy.corrcoef",
"sklearn.cluster.KMeans",
"sklearn.decomposition.PCA",
"seaborn.jointplot",
"numpy.ma.vstack",
"numpy.cov",
"numpy.ma.compress_rows"
] | [((1169, 1195), 'numpy.ma.compress_rows', 'ma.compress_rows', (['raw_rows'], {}), '(raw_rows)\n', (1185, 1195), True, 'import numpy.ma as ma\n'), ((1204, 1241), 'numpy.corrcoef', 'np.corrcoef', (['compressed'], {'rowvar': '(False)'}), '(compressed, rowvar=False)\n', (1215, 1241), True, 'import numpy as np\n'), ((1248, ... |
"""
.. module:: get_data_hlsp_everest
:synopsis: Returns EVEREST lightcurve data as a JSON string.
.. moduleauthor:: <NAME> <<EMAIL>>
"""
import collections
import numpy
from astropy.io import fits
from data_series import DataSeries
from parse_obsid_hlsp_everest import parse_obsid_hlsp_everest
#-----------------... | [
"numpy.isfinite",
"astropy.io.fits.open",
"collections.namedtuple",
"parse_obsid_hlsp_everest.parse_obsid_hlsp_everest",
"data_series.DataSeries"
] | [((1081, 1128), 'collections.namedtuple', 'collections.namedtuple', (['"""DataPoint"""', "['x', 'y']"], {}), "('DataPoint', ['x', 'y'])\n", (1103, 1128), False, 'import collections\n'), ((1449, 1480), 'parse_obsid_hlsp_everest.parse_obsid_hlsp_everest', 'parse_obsid_hlsp_everest', (['obsid'], {}), '(obsid)\n', (1473, 1... |
"""
Created on Sun Oct 21 2018
@author: <NAME>
"""
from __future__ import print_function
import argparse
import torch
import data_loader
import numpy as np
import calculate_log as callog
from torchvision import models
import os
import lib_generation
from torchvision import transforms
from torch.autograd import Variable... | [
"sys.path.append",
"os.mkdir",
"argparse.ArgumentParser",
"os.path.isdir",
"data_loader.getTargetDataSet",
"torch.load",
"torchvision.models.densenet121",
"torch.cuda.manual_seed",
"data_loader.getNonTargetDataSet",
"calculate_log.metric",
"torchvision.models.vgg16_bn",
"torchvision.models.res... | [((332, 354), 'sys.path.append', 'sys.path.append', (['"""../"""'], {}), "('../')\n", (347, 354), False, 'import sys\n'), ((430, 503), 'argparse.ArgumentParser', 'argparse.ArgumentParser', ([], {'description': '"""PyTorch code: Mahalanobis detector"""'}), "(description='PyTorch code: Mahalanobis detector')\n", (453, 50... |
import numpy as np
from qcodes import Parameter, ArrayParameter
from .RemoteProcessWrapper import RPGWrappedBase, ensure_ndarray, get_remote
from .ExtendedDataItem import ExtendedDataItem
from .ColorMap import ColorMap
class HistogramLUTItem(RPGWrappedBase):
_base = "HistogramLUTItem"
def __init__(self, *arg... | [
"numpy.min",
"numpy.max"
] | [((4953, 4965), 'numpy.min', 'np.min', (['data'], {}), '(data)\n', (4959, 4965), True, 'import numpy as np\n'), ((4967, 4979), 'numpy.max', 'np.max', (['data'], {}), '(data)\n', (4973, 4979), True, 'import numpy as np\n')] |
#!/usr/bin/env python3
import csv
import string
import random
import json
def random_hash():
"""
TODO: This is just a placeholder function. We will remove it later
"""
alphabet = string.ascii_letters + string.digits
return ''.join(random.choices(alphabet, k=8))
data = []
with open('links.csv') as ... | [
"random.choices",
"csv.reader",
"json.dumps"
] | [((373, 392), 'csv.reader', 'csv.reader', (['csvfile'], {}), '(csvfile)\n', (383, 392), False, 'import csv\n'), ((252, 281), 'random.choices', 'random.choices', (['alphabet'], {'k': '(8)'}), '(alphabet, k=8)\n', (266, 281), False, 'import random\n'), ((945, 961), 'json.dumps', 'json.dumps', (['data'], {}), '(data)\n', ... |
import transmogrifier.models as timdex
from transmogrifier.helpers import generate_citation, parse_xml_records
def test_generate_citation_with_required_fields_only():
extracted_data = {
"title": "A Very Important Paper",
"source_link": "https://example.com/paper",
}
assert (
genera... | [
"transmogrifier.helpers.generate_citation",
"transmogrifier.helpers.parse_xml_records",
"transmogrifier.models.Date",
"transmogrifier.models.Contributor"
] | [((6604, 6669), 'transmogrifier.helpers.parse_xml_records', 'parse_xml_records', (['"""tests/fixtures/datacite/datacite_records.xml"""'], {}), "('tests/fixtures/datacite/datacite_records.xml')\n", (6621, 6669), False, 'from transmogrifier.helpers import generate_citation, parse_xml_records\n'), ((314, 347), 'transmogri... |
import numpy as np
import time
import argparse
from rlkit.envs.wrappers import NormalizedBoxEnv
parser = argparse.ArgumentParser()
parser.add_argument('--exp_name', type=str, default='Ant')
parser.add_argument('--ml', type=int, default=1000)
args = parser.parse_args()
import gym
env = NormalizedBoxEnv(gym.make(args.e... | [
"gym.make",
"argparse.ArgumentParser",
"numpy.argmax",
"time.sleep",
"numpy.max",
"numpy.mean"
] | [((106, 131), 'argparse.ArgumentParser', 'argparse.ArgumentParser', ([], {}), '()\n', (129, 131), False, 'import argparse\n'), ((305, 336), 'gym.make', 'gym.make', (["(args.exp_name + '-v2')"], {}), "(args.exp_name + '-v2')\n", (313, 336), False, 'import gym\n'), ((756, 771), 'time.sleep', 'time.sleep', (['(0.1)'], {})... |
#!/usr/bin/env python
import logging
import os
import sys
import subprocess
import time
import signal
import platform
def file_filter(name):
return (not name.startswith(".")) and (not name.endswith(".swp"))
def file_times(path):
if os.path.isfile(path):
yield os.stat(path).st_mtime
return
... | [
"os.stat",
"logging.warning",
"os.path.dirname",
"os.walk",
"os.system",
"time.sleep",
"os.path.isfile",
"platform.system",
"os.path.join"
] | [((245, 265), 'os.path.isfile', 'os.path.isfile', (['path'], {}), '(path)\n', (259, 265), False, 'import os\n'), ((349, 362), 'os.walk', 'os.walk', (['path'], {}), '(path)\n', (356, 362), False, 'import os\n'), ((595, 620), 'os.path.dirname', 'os.path.dirname', (['__file__'], {}), '(__file__)\n', (610, 620), False, 'im... |
import grammar_check
import glob
import os
import sys
reload(sys)
sys.setdefaultencoding('utf8')
# cornellPath = "./cornellResponses"
# twitterPath = "./twitterResponses"
# cornellTwitterPath = "./cornellTwitterResponses"
pos2Path = "./2layer-pos"
pos3Path = "./3layer-pos"
neg2Path = "./2layer-neg"
neg3Path = ".... | [
"grammar_check.correct",
"grammar_check.LanguageTool",
"os.path.join",
"sys.setdefaultencoding"
] | [((71, 101), 'sys.setdefaultencoding', 'sys.setdefaultencoding', (['"""utf8"""'], {}), "('utf8')\n", (93, 101), False, 'import sys\n'), ((341, 376), 'grammar_check.LanguageTool', 'grammar_check.LanguageTool', (['"""en-US"""'], {}), "('en-US')\n", (367, 376), False, 'import grammar_check\n'), ((524, 571), 'os.path.join'... |
import requests
def alert_generator(data_list):
telegram_url = 'https://api.telegram.org/botxx/sendMessage?chat_id=-xx&text='
count = 0
for i in data_list:
post_message = telegram_url + i[1] + ".\n" + i[2]
requests.post(post_message)
if count == 2:
break
count +... | [
"requests.post"
] | [((236, 263), 'requests.post', 'requests.post', (['post_message'], {}), '(post_message)\n', (249, 263), False, 'import requests\n')] |
import base64
import hashlib
import json
import os
import pathlib
import time
from datetime import datetime
from homie.node.node_base import Node_Base
from homie.node.property.property_datetime import Property_DateTime
from homie.node.property.property_string import Property_String
class Node_Image(Node_Base):
"... | [
"homie.node.property.property_string.Property_String",
"os.makedirs",
"pathlib.Path.home",
"os.path.basename",
"os.path.exists",
"json.dumps",
"homie.node.property.property_datetime.Property_DateTime",
"os.path.getmtime",
"datetime.datetime.now",
"hashlib.blake2s",
"time.localtime"
] | [((629, 648), 'pathlib.Path.home', 'pathlib.Path.home', ([], {}), '()\n', (646, 648), False, 'import pathlib\n'), ((903, 961), 'os.makedirs', 'os.makedirs', (['Node_Image.IMAGE_DIR'], {'mode': '(493)', 'exist_ok': '(True)'}), '(Node_Image.IMAGE_DIR, mode=493, exist_ok=True)\n', (914, 961), False, 'import os\n'), ((979,... |
#!/usr/bin/env python
import rospy
import math
import numpy as np
import tf
import tf2_ros
import geometry_msgs.msg
from geometry_msgs.msg import Point
import geometry_msgs.msg
#import transformation_py.transformation as transformation
class FieldMapPublisher(object):
def __init__(self):
rospy.init_node('... | [
"tf2_ros.StaticTransformBroadcaster",
"rospy.Time.now",
"numpy.asarray",
"rospy.Rate",
"rospy.get_param",
"rospy.is_shutdown",
"rospy.init_node",
"rospy.get_name",
"tf.transformations.quaternion_from_matrix",
"tf.TransformListener"
] | [((303, 333), 'rospy.init_node', 'rospy.init_node', (['"""GPS_tf_node"""'], {}), "('GPS_tf_node')\n", (318, 333), False, 'import rospy\n'), ((489, 504), 'rospy.Rate', 'rospy.Rate', (['(1.0)'], {}), '(1.0)\n', (499, 504), False, 'import rospy\n'), ((573, 683), 'rospy.get_param', 'rospy.get_param', (['"""map_file"""'], {... |
import os
import queue as Queue
import threading
from datetime import datetime
import numpy as np
import cv2
from PyQt5.QtCore import Qt
from PyQt5.QtCore import pyqtSignal, pyqtSlot
from PyQt5.QtWidgets import QApplication, QMainWindow, QLabel, QShortcut, QStackedWidget, QMessageBox, QWidget, QVBoxLayout, QHBoxLayout... | [
"PyQt5.QtCore.pyqtSignal",
"gui.imageWidget.ImageWidget",
"PyQt5.QtGui.QKeySequence",
"PyQt5.QtWidgets.QPushButton",
"PyQt5.QtWidgets.QVBoxLayout",
"PyQt5.QtWidgets.QApplication.instance",
"os.path.join",
"PyQt5.QtWidgets.QLabel",
"PyQt5.QtWidgets.QWidget",
"util.ObjectResizer",
"cv2.cvtColor",
... | [((629, 644), 'PyQt5.QtCore.pyqtSignal', 'pyqtSignal', (['str'], {}), '(str)\n', (639, 644), False, 'from PyQt5.QtCore import pyqtSignal, pyqtSlot\n'), ((752, 764), 'PyQt5.QtCore.pyqtSignal', 'pyqtSignal', ([], {}), '()\n', (762, 764), False, 'from PyQt5.QtCore import pyqtSignal, pyqtSlot\n'), ((792, 804), 'PyQt5.QtCor... |
"""
Copyright (c) 2018 <NAME> <<EMAIL>>
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
to use, copy, modify, merge, publish, distribut... | [
"mpikat.core.ip_manager.ip_range_from_stream",
"logging.getLogger"
] | [((1175, 1224), 'logging.getLogger', 'logging.getLogger', (['"""mpikat.apsuse_config_manager"""'], {}), "('mpikat.apsuse_config_manager')\n", (1192, 1224), False, 'import logging\n'), ((2849, 2919), 'mpikat.core.ip_manager.ip_range_from_stream', 'ip_range_from_stream', (["fbfuse_config['incoherent-beam-multicast-group'... |
__author__ = "<NAME>"
__copyright__ = "Copyright 2021, <NAME>"
__email__ = "<EMAIL>"
__license__ = "MIT"
import os
import re
from snakemake.shell import shell
log = snakemake.log_fmt_shell(stdout=True, stderr=True, append=True)
options = snakemake.params.get("options", "")
db = snakemake.params.db
seqinput = snakem... | [
"snakemake.shell.shell",
"re.sub"
] | [((343, 386), 're.sub', 're.sub', (['""".gz$"""', '""""""', 'snakemake.output.output'], {}), "('.gz$', '', snakemake.output.output)\n", (349, 386), False, 'import re\n'), ((403, 452), 're.sub', 're.sub', (['""".gz$"""', '""""""', 'snakemake.output.unclassified'], {}), "('.gz$', '', snakemake.output.unclassified)\n", (4... |
# -*- coding: utf-8 -*-
from common.sqlalchemy import BaseModel
from sqlalchemy import Column, VARCHAR, INTEGER, TEXT, text
from sqlalchemy.exc import InvalidRequestError
class Jobs(BaseModel):
__tablename__ = 'jobs'
id = Column(INTEGER, primary_key=True)
url = Column(VARCHAR, doc='职位链接', unique=True)
... | [
"sqlalchemy.text",
"sqlalchemy.Column"
] | [((234, 267), 'sqlalchemy.Column', 'Column', (['INTEGER'], {'primary_key': '(True)'}), '(INTEGER, primary_key=True)\n', (240, 267), False, 'from sqlalchemy import Column, VARCHAR, INTEGER, TEXT, text\n'), ((278, 318), 'sqlalchemy.Column', 'Column', (['VARCHAR'], {'doc': '"""职位链接"""', 'unique': '(True)'}), "(VARCHAR, do... |
# Inspired by https://docs.aiohttp.org/en/stable/web_quickstart.html
# and https://docs.aiohttp.org/en/stable/web_quickstart.html#resources-and-routes
from aiohttp import web
app = web.Application()
## ================================= ##
## Ways to specify routes / handlers ##
## =================================... | [
"aiohttp.web.Response",
"aiohttp.web.RouteTableDef",
"aiohttp.web.route",
"aiohttp.web.UrlDispatcher",
"aiohttp.web.get",
"aiohttp.web.run_app",
"aiohttp.web.Application",
"aiohttp.web.view"
] | [((184, 201), 'aiohttp.web.Application', 'web.Application', ([], {}), '()\n', (199, 201), False, 'from aiohttp import web\n'), ((958, 977), 'aiohttp.web.RouteTableDef', 'web.RouteTableDef', ([], {}), '()\n', (975, 977), False, 'from aiohttp import web\n'), ((2939, 2958), 'aiohttp.web.RouteTableDef', 'web.RouteTableDef'... |
import matplotlib.pyplot as plt
import pickle
import os
outdir='output'
if not os.path.exists(outdir):
os.makedirs(outdir)
os.system('python main.py --optimizer sgd --learning_rate 1e-5 --output='+outdir+'/sgd.pkl')
os.system('python main.py --optimizer momentumsgd --learning_rate 1e-5 --output='+outdir+'/momentu... | [
"matplotlib.pyplot.show",
"os.makedirs",
"matplotlib.pyplot.plot",
"matplotlib.pyplot.legend",
"os.path.exists",
"os.system",
"matplotlib.pyplot.ylabel",
"matplotlib.pyplot.xlabel",
"matplotlib.pyplot.savefig"
] | [((129, 229), 'os.system', 'os.system', (["('python main.py --optimizer sgd --learning_rate 1e-5 --output=' + outdir +\n '/sgd.pkl')"], {}), "('python main.py --optimizer sgd --learning_rate 1e-5 --output=' +\n outdir + '/sgd.pkl')\n", (138, 229), False, 'import os\n'), ((222, 343), 'os.system', 'os.system', (["(... |
from collections import OrderedDict
import re
import thirdparty.yaml.include
import thirdparty.yaml.operation
def register_default_compositions(cls):
thirdparty.yaml.include.register_include(cls)
thirdparty.yaml.include.register_defaults(cls)
thirdparty.yaml.operation.register_defaults(cls)
def regi... | [
"re.escape"
] | [((1541, 1558), 're.escape', 're.escape', (['"""<<<<"""'], {}), "('<<<<')\n", (1550, 1558), False, 'import re\n'), ((1683, 1699), 're.escape', 're.escape', (['"""<<<"""'], {}), "('<<<')\n", (1692, 1699), False, 'import re\n')] |
import unittest
from unittest.mock import Mock, patch
from spectroscope.model import ValidatorIdentity
from spectroscope.model.notification import Notification, Notify
from spectroscope.module.webhook import Webhook
FAKE_PUBKEY = "a" * 96
FAKE_ENDPOINT = "http://www.example.com/api"
class FakeNotification(Notificat... | [
"unittest.mock.patch",
"spectroscope.module.webhook.Webhook.register"
] | [((484, 529), 'unittest.mock.patch', 'patch', (['"""spectroscope.module.webhook.requests"""'], {}), "('spectroscope.module.webhook.requests')\n", (489, 529), False, 'from unittest.mock import Mock, patch\n'), ((433, 477), 'spectroscope.module.webhook.Webhook.register', 'Webhook.register', ([], {'uri_endpoint': 'FAKE_EN... |
from django.db import models
# Create your models here.
class User(models.Model):
name = models.CharField(max_length=32)
password = models.CharField(max_length=64)
age = models.IntegerField(default=2)
# 中途添加数据库时要设置默认值,也可以设置默认为空
# size=models.IntegerField(default=2,null=True,blank=True)
class De... | [
"django.db.models.CharField",
"django.db.models.IntegerField"
] | [((96, 127), 'django.db.models.CharField', 'models.CharField', ([], {'max_length': '(32)'}), '(max_length=32)\n', (112, 127), False, 'from django.db import models\n'), ((143, 174), 'django.db.models.CharField', 'models.CharField', ([], {'max_length': '(64)'}), '(max_length=64)\n', (159, 174), False, 'from django.db imp... |
# imports
from warnings import warn
from typing import Union, List, Tuple
# variables
sectionsNames = []
# code
code = []
class User:
def __init__(self, name: str):
self.name = name
class Section:
def __init__(self, name: str):
self.name = name
self._times = 0
self._canBeCa... | [
"warnings.warn"
] | [((1693, 1730), 'warnings.warn', 'warn', (['"""The code is empty"""', 'Warning', '(3)'], {}), "('The code is empty', Warning, 3)\n", (1697, 1730), False, 'from warnings import warn\n'), ((380, 429), 'warnings.warn', 'warn', (['"""Duplicate name of the section"""', 'Warning', '(3)'], {}), "('Duplicate name of the sectio... |
#sorteando a ordem
from random import shuffle
n1 = str(input('Primeiro aluno: '))
n2 = str(input('Segundo nome: '))
n3 = str(input('Terceiro nome: '))
n4 = str(input('Quarto nome: '))
lista = [n1, n2, n3, n4]
shuffle(lista)
print('A ordem será ')
print(lista) | [
"random.shuffle"
] | [((209, 223), 'random.shuffle', 'shuffle', (['lista'], {}), '(lista)\n', (216, 223), False, 'from random import shuffle\n')] |
import torch
from .Module import Module
from .utils import clear
class Reshape(Module):
def __init__(self, *args):
super(Reshape, self).__init__()
if len(args) == 0 and isinstance(args[0], torch.Size):
self.size = args[0]
else:
self.size = torch.Size(args)
... | [
"torch.Size"
] | [((296, 312), 'torch.Size', 'torch.Size', (['args'], {}), '(args)\n', (306, 312), False, 'import torch\n'), ((810, 831), 'torch.Size', 'torch.Size', (['batchsize'], {}), '(batchsize)\n', (820, 831), False, 'import torch\n')] |
# -*- coding:utf-8 -*-
import unittest
import init_env
from common.HttpUtils import HttpUtils
from common.base_test import run_tests
from common.cc import ResourcePark
class TestResourcePark(unittest.TestCase):
def setUp(self):
"""
测试用例初始化操作
"""
self.r = HttpUtils()
def tearDo... | [
"common.base_test.run_tests",
"common.HttpUtils.HttpUtils"
] | [((1027, 1043), 'common.base_test.run_tests', 'run_tests', (['tests'], {}), '(tests)\n', (1036, 1043), False, 'from common.base_test import run_tests\n'), ((293, 304), 'common.HttpUtils.HttpUtils', 'HttpUtils', ([], {}), '()\n', (302, 304), False, 'from common.HttpUtils import HttpUtils\n')] |
# -*- coding: utf-8 -*-
"""
Created on Fri Dec 2 14:02:26 2016
MIT License
Copyright (c) 2016 <NAME>
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 limit... | [
"zeex.core.views.ftp.main.FtpMainWindow",
"os.path.dirname",
"zeex.core.compat.QtGui.QShortcut",
"zeex.core.utility.ostools.zipfile_compress",
"zeex.core.utility.ostools.zipfile_unzip",
"zeex.core.views.basic.directory.DropBoxViewDialog",
"zeex.core.compat.QtGui.QIcon",
"zeex.core.views.sql.main.Datab... | [((1675, 1707), 'zeex.core.compat.QtGui.QMainWindow.__init__', 'QtGui.QMainWindow.__init__', (['self'], {}), '(self)\n', (1701, 1707), False, 'from zeex.core.compat import QtGui, QtCore\n'), ((1833, 1865), 'zeex.core.views.sql.main.DatabasesMainWindow', 'DatabasesMainWindow', ([], {'parent': 'self'}), '(parent=self)\n'... |
# Uses python3
import sys
def optimal_weight(W, wt):
# write your code here
n = len(wt)
# K = [n+1][W+1]
K = [[0 for i in range(W+1)] for j in range(n+1)]
for i in range(0, n+1):
for w in range(0, W+1):
if i==0 or w==0:
K[i][w] = 0
elif wt[i-1] <= w:
... | [
"sys.stdin.read"
] | [((504, 520), 'sys.stdin.read', 'sys.stdin.read', ([], {}), '()\n', (518, 520), False, 'import sys\n')] |
from darknet import *
import cv2
import sys
import openposeMy
import time
sys.path.append( '/usr/local/python/openpose' )
try :
from openpose import *
except :
raise Exception(
'Error: OpenPose library could not be found. Did you enable `BUILD_PYTHON` in CMake and have this Python '
'script in the right folder?'... | [
"sys.path.append",
"cv2.VideoWriter_fourcc",
"cv2.waitKey",
"time.time",
"cv2.VideoCapture",
"cv2.rectangle",
"cv2.destroyAllWindows",
"openposeMy.drawPerson"
] | [((75, 120), 'sys.path.append', 'sys.path.append', (['"""/usr/local/python/openpose"""'], {}), "('/usr/local/python/openpose')\n", (90, 120), False, 'import sys\n'), ((1603, 1643), 'cv2.VideoCapture', 'cv2.VideoCapture', (['"""./input/original.mp4"""'], {}), "('./input/original.mp4')\n", (1619, 1643), False, 'import cv... |
class file:
name=None
def __error(error):
if ("invalid file" in str(error)):
return ("\033["+str(31)+"m"+str(error)+"""
please set file.name='filename' or use help(fileop.file)"""+"\033[0m")
return ("\033["+str(31)+"m"+str(error)+"\033[0m")
#-------------------append to file------------------------------
de... | [
"os.remove",
"os.path.exists"
] | [((2089, 2109), 'os.path.exists', 'os.path.exists', (['name'], {}), '(name)\n', (2103, 2109), False, 'import os\n'), ((2447, 2462), 'os.remove', 'os.remove', (['name'], {}), '(name)\n', (2456, 2462), False, 'import os\n')] |
# -*- coding: utf-8 -*-
# Generated by Django 1.11.6 on 2018-01-23 18:15
from __future__ import unicode_literals
from django.conf import settings
from django.db import migrations, models
import django.db.models.deletion
class Migration(migrations.Migration):
dependencies = [
migrations.swappable_depende... | [
"django.db.models.TextField",
"django.db.migrations.swappable_dependency",
"django.db.models.ForeignKey",
"django.db.models.BooleanField",
"django.db.models.AutoField",
"django.db.models.DateTimeField"
] | [((292, 349), 'django.db.migrations.swappable_dependency', 'migrations.swappable_dependency', (['settings.AUTH_USER_MODEL'], {}), '(settings.AUTH_USER_MODEL)\n', (323, 349), False, 'from django.db import migrations, models\n'), ((1185, 1218), 'django.db.models.BooleanField', 'models.BooleanField', ([], {'default': '(Tr... |
"""Configure common variables and data locations."""
from pathlib import Path
import numpy as np
# Path definitions
# -----------------------------------------------------------------------------
# if several external hard drives are used, pick the correct one by changing the index
external_name = {0: "LinuxDataApp... | [
"pathlib.Path",
"numpy.arange"
] | [((705, 748), 'pathlib.Path', 'Path', (['"""/home/stefanappelhoff/Desktop/eComp"""'], {}), "('/home/stefanappelhoff/Desktop/eComp')\n", (709, 748), False, 'from pathlib import Path\n'), ((769, 844), 'pathlib.Path', 'Path', (['f"""/media/stefanappelhoff/{external_name}/eeg_compression/ecomp_data/"""'], {}), "(f'/media/s... |
# Generated by Django 3.1.12 on 2021-07-15 14:12
from django.db import migrations, models
import imagekit.models.fields
class Migration(migrations.Migration):
dependencies = [
('comparer', '0008_remove_rankingbrowserpluginmodel_show_categories'),
]
operations = [
migrations.AlterField(
... | [
"django.db.models.PositiveSmallIntegerField"
] | [((655, 842), 'django.db.models.PositiveSmallIntegerField', 'models.PositiveSmallIntegerField', ([], {'choices': "[(1, 'Facebook'), (2, 'Instagram'), (3, 'Twitter'), (4, 'LinkedIn'), (5,\n 'YouTube'), (6, 'Website'), (8, 'Another')]", 'verbose_name': '"""kind"""'}), "(choices=[(1, 'Facebook'), (2, 'Instagram'),\n ... |
import numpy as np
from collections import Counter
from scipy.stats.stats import ttest_1samp, ttest_ind, pearsonr
from numpy.random.mtrand import permutation
from sklearn.metrics import mean_squared_error
from mvpa_itab.utils import progress
def cross_validate(ds, clf, partitioner, permuted_labels):
partition... | [
"mvpa_itab.utils.progress",
"numpy.sum",
"numpy.abs",
"scipy.stats.stats.ttest_ind",
"scipy.stats.stats.ttest_1samp",
"scipy.stats.stats.pearsonr",
"numpy.ix_",
"numpy.float",
"numpy.isnan",
"numpy.random.mtrand.permutation",
"numpy.mean",
"numpy.array",
"numpy.random.permutation",
"collec... | [((1132, 1152), 'numpy.array', 'np.array', (['accuracies'], {}), '(accuracies)\n', (1140, 1152), True, 'import numpy as np\n'), ((1467, 1487), 'numpy.unique', 'np.unique', (['ds.chunks'], {}), '(ds.chunks)\n', (1476, 1487), True, 'import numpy as np\n'), ((11742, 11761), 'numpy.array', 'np.array', (['null_dist'], {}), ... |
import json
import socket
from typing import List
class OpenFacsInterface(object):
def __init__(self, udp_ip_address: str, udp_port: int) -> None:
self._udp_address: str = udp_ip_address
self._udp_port: int = udp_port
def send_aus(self, au_list: List[float], speed: float) -> None:
... | [
"socket.socket",
"json.dumps"
] | [((1068, 1116), 'socket.socket', 'socket.socket', (['socket.AF_INET', 'socket.SOCK_DGRAM'], {}), '(socket.AF_INET, socket.SOCK_DGRAM)\n', (1081, 1116), False, 'import socket\n'), ((1017, 1039), 'json.dumps', 'json.dumps', (['param_dict'], {}), '(param_dict)\n', (1027, 1039), False, 'import json\n')] |
from gbd_tool.util import eprint, open_cnf_file
from gbd_tool.db import Database
import io
import os
import hashlib
import bz2
import tempfile
import multiprocessing
from multiprocessing import Pool, Lock
mutex = Lock()
def bootstrap(api, database, named_algo, hashes, jobs):
resultset = api.query_search(None, h... | [
"multiprocessing.cpu_count",
"hashlib.md5",
"multiprocessing.Lock",
"gbd_tool.util.open_cnf_file"
] | [((216, 222), 'multiprocessing.Lock', 'Lock', ([], {}), '()\n', (220, 222), False, 'from multiprocessing import Pool, Lock\n'), ((1857, 1886), 'gbd_tool.util.open_cnf_file', 'open_cnf_file', (['filename', '"""rt"""'], {}), "(filename, 'rt')\n", (1870, 1886), False, 'from gbd_tool.util import eprint, open_cnf_file\n'), ... |
from random import shuffle
import json
import requests
from src.model.models import SearchTermAutoComplete, ImageSearchResponse
class GenericHelper(object):
def __init__(self, unsplash_dict, pexels_dict):
self.unsplash_dict = unsplash_dict
self.pexels_dict = pexels_dict
self.api_list = []
... | [
"random.shuffle",
"json.loads",
"requests.get"
] | [((554, 576), 'random.shuffle', 'shuffle', (['response_list'], {}), '(response_list)\n', (561, 576), False, 'from random import shuffle\n'), ((2047, 2101), 'requests.get', 'requests.get', (['base_url'], {'params': 'params', 'headers': 'headers'}), '(base_url, params=params, headers=headers)\n', (2059, 2101), False, 'im... |
from scipy.integrate import solve_ivp, quad
from sidmpy.Profiles.halo_density_profiles import TNFWprofile
from scipy.interpolate import interp1d
import numpy as np
from scipy.optimize import fsolve
def compute_r1(rhos, rs, vdispersion_halo, cross_section_class, halo_age):
"""
:param rhos: density normalizati... | [
"numpy.roots",
"numpy.absolute",
"numpy.isreal",
"numpy.ones_like",
"numpy.log",
"scipy.integrate.quad",
"sidmpy.Profiles.halo_density_profiles.TNFWprofile",
"scipy.integrate.solve_ivp",
"scipy.optimize.fsolve",
"numpy.exp",
"numpy.linspace",
"scipy.interpolate.interp1d",
"numpy.log10",
"n... | [((1106, 1129), 'numpy.roots', 'np.roots', (['[1, 2, 1, -k]'], {}), '([1, 2, 1, -k])\n', (1114, 1129), True, 'import numpy as np\n'), ((1736, 1760), 'scipy.optimize.fsolve', 'fsolve', (['_func_to_min', 'rs'], {}), '(_func_to_min, rs)\n', (1742, 1760), False, 'from scipy.optimize import fsolve\n'), ((2323, 2370), 'numpy... |
#!/usr/bin/env python3
# -*- coding: utf-8 -*-
"""
Created on Thu Feb 28 10:19:16 2019
@author: zl
"""
import os
import argparse
import glob
import shutil
from collections import defaultdict
import tqdm
import numpy as np
import pandas as pd
from PIL import Image
import imagehash
def parse_args():
parser = arg... | [
"os.path.join",
"argparse.ArgumentParser",
"pandas.DataFrame.from_records"
] | [((317, 342), 'argparse.ArgumentParser', 'argparse.ArgumentParser', ([], {}), '()\n', (340, 342), False, 'import argparse\n'), ((595, 630), 'os.path.join', 'os.path.join', (['args.data_dir', '"""rgby"""'], {}), "(args.data_dir, 'rgby')\n", (607, 630), False, 'import os\n'), ((650, 690), 'os.path.join', 'os.path.join', ... |
import json
from pathlib import Path
from mako.lookup import TemplateLookup
from common import site_dir, template_dir, site_root
from markdownext import parse
lookup = TemplateLookup(
directories=[str(template_dir)],
strict_undefined=True,
)
def render_template(template_file, **kwargs):
template_path ... | [
"markdownext.parse",
"json.load"
] | [((778, 797), 'markdownext.parse', 'parse', (['self.content'], {}), '(self.content)\n', (783, 797), False, 'from markdownext import parse\n'), ((661, 674), 'json.load', 'json.load', (['fp'], {}), '(fp)\n', (670, 674), False, 'import json\n')] |
import torch.nn as nn
import torchvision
class TruncatedVGG19(nn.Module):
"""
A truncated VGG19 network, such that its output is the 'feature map obtained by the j-th convolution (after activation)
before the i-th maxpooling layer within the VGG19 network', as defined in the paper.
Used to calculate th... | [
"torchvision.models.vgg19"
] | [((473, 514), 'torchvision.models.vgg19', 'torchvision.models.vgg19', ([], {'pretrained': '(True)'}), '(pretrained=True)\n', (497, 514), False, 'import torchvision\n')] |
import requests
from bs4 import BeautifulSoup
import re
class Course:
def __init__(self, courseName, courseURL, checkForRestrictedSeats):
"""
(String) courseName: name of the course
(String) courseURL: URL to the section of the course
(Boolean) checkForRestricte... | [
"requests.get"
] | [((917, 945), 'requests.get', 'requests.get', (['self.courseURL'], {}), '(self.courseURL)\n', (929, 945), False, 'import requests\n')] |
#!/usr/bin/env python3
# -*- coding: utf-8 -*-
"""
Created on Tue May 14 14:03:56 2019
@author: bmoseley
"""
# This code is my own python implementation of the SEISMIC_CPML library here: https://github.com/geodynamics/seismic_cpml/blob/master/seismic_CPML_2D_pressure_second_order.f90
import matplotlib.pyplot as plt
... | [
"matplotlib.pyplot.subplot",
"matplotlib.pyplot.show",
"numpy.log",
"matplotlib.pyplot.plot",
"numpy.abs",
"matplotlib.pyplot.suptitle",
"numpy.zeros",
"numpy.ones",
"numpy.max",
"matplotlib.pyplot.figure",
"numpy.exp"
] | [((798, 814), 'numpy.max', 'np.max', (['velocity'], {}), '(velocity)\n', (804, 814), True, 'import numpy as np\n'), ((4386, 4413), 'matplotlib.pyplot.figure', 'plt.figure', ([], {'figsize': 'figsize'}), '(figsize=figsize)\n', (4396, 4413), True, 'import matplotlib.pyplot as plt\n'), ((4418, 4435), 'matplotlib.pyplot.su... |
# Copyright (c) 2021 Push Technology Ltd., All Rights Reserved.
#
# Use is subject to license terms.
#
# NOTICE: All information contained herein is, and remains the
# property of Push Technology. The intellectual and technical
# concepts contained herein are proprietary to Push Technology and
# may be covered by... | [
"diffusion.Credentials",
"diffusion.features.control.metrics.session_metrics.SessionMetricCollectorBuilder",
"diffusion.Session"
] | [((691, 724), 'diffusion.Credentials', 'diffusion.Credentials', (['"""password"""'], {}), "('password')\n", (712, 724), False, 'import diffusion\n'), ((977, 1056), 'diffusion.Session', 'diffusion.Session', ([], {'url': 'server_url', 'principal': 'principal', 'credentials': 'credentials'}), '(url=server_url, principal=p... |
# setup.py
from setuptools import setup, find_packages
import simplepath
setup(
name='simplepath',
version=simplepath.__version__,
packages=find_packages(),
author="<NAME>",
author_email="",
description="Helping working with complex directory arborescences",
long_description=open('README.m... | [
"setuptools.find_packages"
] | [((154, 169), 'setuptools.find_packages', 'find_packages', ([], {}), '()\n', (167, 169), False, 'from setuptools import setup, find_packages\n')] |
import numpy as np
import wave
from scipy.io.wavfile import read, write
import struct
from numpy.fft import fft, fftshift, ifft
def spectrum_shifting( x, shift, fs ):
X = fft( x )
N = fs
N_half = int( fs / 2 )
Y = np.zeros( N, dtype = 'complex' )
for i in range( N_half ):
if i + shift >= 0 and i + shift <= N_ha... | [
"numpy.fft.ifft",
"wave.open",
"numpy.fft.fft",
"numpy.zeros",
"scipy.io.wavfile.read"
] | [((173, 179), 'numpy.fft.fft', 'fft', (['x'], {}), '(x)\n', (176, 179), False, 'from numpy.fft import fft, fftshift, ifft\n'), ((219, 247), 'numpy.zeros', 'np.zeros', (['N'], {'dtype': '"""complex"""'}), "(N, dtype='complex')\n", (227, 247), True, 'import numpy as np\n'), ((458, 465), 'numpy.fft.ifft', 'ifft', (['Y'], ... |
# -*- coding: utf-8 -*-
"""
Created on Sat Aug 25 12:48:20 2018
@author: <EMAIL>
"""
def swap_matrix_element (A, P):
import random as r
S1 = len(A)
S2 = len(A[0])
for i in range(P):
row1 = r.randint(0, S1-1)
row2 = r.randint(0, S1-1)
col1 = r.randint(0, S2-1)
col2 = r.r... | [
"random.randint",
"numpy.isnan"
] | [((215, 235), 'random.randint', 'r.randint', (['(0)', '(S1 - 1)'], {}), '(0, S1 - 1)\n', (224, 235), True, 'import random as r\n'), ((249, 269), 'random.randint', 'r.randint', (['(0)', '(S1 - 1)'], {}), '(0, S1 - 1)\n', (258, 269), True, 'import random as r\n'), ((283, 303), 'random.randint', 'r.randint', (['(0)', '(S2... |
#!/usr/bin/python3
from ECL_config import ECL_config
from ECL_config import main_config
from ECL_core import updateControls
from Controls import main_controller
import time
import argparse
import sys
def getOptions(args=sys.argv[1:]):
parser = argparse.ArgumentParser(description="ECL - Emulator Controls Label. \... | [
"argparse.ArgumentParser",
"Rest.ECLRestServer.startup",
"Controls.main_controller.start",
"ECL_config.main_config.load_xml_config",
"Rest.ECLRestClient.updateLabels",
"ECL_core.updateControls",
"Mappers.MapperController.startup"
] | [((992, 1050), 'ECL_config.main_config.load_xml_config', 'main_config.load_xml_config', ([], {'configfile': 'options.configfile'}), '(configfile=options.configfile)\n', (1019, 1050), False, 'from ECL_config import main_config\n'), ((1090, 1113), 'Controls.main_controller.start', 'main_controller.start', ([], {}), '()\n... |
import cauldron
from cauldron import environ
from cauldron.ui.statuses import _utils
from cauldron.ui.statuses._reconciler import merge_local_state # noqa
from cauldron.ui import configs as ui_configs
def get_status(last_timestamp: float, force: bool = False) -> dict:
"""
Returns the current status of the ca... | [
"cauldron.ui.configs.is_active_async",
"cauldron.environ.remote_connection.serialize",
"cauldron.environ.Response",
"cauldron.project.get_internal_project",
"cauldron.ui.statuses._utils.get_step_changes_after",
"cauldron.ui.statuses._utils.get_digest_hash"
] | [((1096, 1144), 'cauldron.project.get_internal_project', 'cauldron.project.get_internal_project', ([], {'timeout': '(0)'}), '(timeout=0)\n', (1133, 1144), False, 'import cauldron\n'), ((1973, 2011), 'cauldron.ui.statuses._utils.get_digest_hash', '_utils.get_digest_hash', (['results', 'force'], {}), '(results, force)\n'... |
# -*- coding: utf-8 -*-
import sys
from django.http import HttpResponse
from podcast import newsfactory
reload(sys)
sys.setdefaultencoding('utf-8')
def podcast(request, pod='newsfactory'):
u"""Podcast"""
if pod == 'newsfactory':
response = HttpResponse(newsfactory(), content_type='application/rss+x... | [
"podcast.newsfactory",
"sys.setdefaultencoding"
] | [((119, 150), 'sys.setdefaultencoding', 'sys.setdefaultencoding', (['"""utf-8"""'], {}), "('utf-8')\n", (141, 150), False, 'import sys\n'), ((274, 287), 'podcast.newsfactory', 'newsfactory', ([], {}), '()\n', (285, 287), False, 'from podcast import newsfactory\n')] |
import numpy as np
import keras,gc,nltk
import pandas as pd
from keras.utils import to_categorical
from sklearn import preprocessing
from supervised_BAE import *
from utils import *
from sklearn.model_selection import train_test_split
from keras.utils import to_categorical
from sklearn import preprocessing
from utils ... | [
"numpy.load",
"numpy.random.seed",
"keras.datasets.cifar10.load_data",
"sklearn.preprocessing.StandardScaler",
"numpy.random.shuffle",
"numpy.asarray",
"utils.sample_test_mask",
"time.perf_counter",
"sklearn.preprocessing.LabelEncoder",
"numpy.zeros",
"gc.collect",
"numpy.concatenate",
"kera... | [((451, 483), 'numpy.random.seed', 'np.random.seed', (['__random_state__'], {}), '(__random_state__)\n', (465, 483), True, 'import numpy as np\n'), ((597, 631), 'keras.datasets.cifar10.load_data', 'keras.datasets.cifar10.load_data', ([], {}), '()\n', (629, 631), False, 'import keras, gc, nltk\n'), ((745, 794), 'numpy.a... |
# -*- coding: utf-8 -*-
from django.utils.translation import ugettext_lazy as _
from allink_core.core.utils import get_additional_choices
####################################################################################
# BLANK
BLANK_CHOICE = (('', '---------'),)
###############################################... | [
"allink_core.core.utils.get_additional_choices",
"django.utils.translation.ugettext_lazy"
] | [((1655, 1703), 'allink_core.core.utils.get_additional_choices', 'get_additional_choices', (['"""BUTTON_CONTEXT_CHOICES"""'], {}), "('BUTTON_CONTEXT_CHOICES')\n", (1677, 1703), False, 'from allink_core.core.utils import get_additional_choices\n'), ((422, 430), 'django.utils.translation.ugettext_lazy', '_', (['"""Mr."""... |
import gurobipy as gp
import numpy
class ILPopt():
"""
An integer linear programming (ILP) solver based on GUROBI
"""
def __init__(self, num_vars, obj, constrs=[]):
"""
Params:
- num_val: # of variables
- obj: tuple ("x[0] + 2 * x[1] - 4 * x[2]", "min/max")
... | [
"gurobipy.Model"
] | [((557, 567), 'gurobipy.Model', 'gp.Model', ([], {}), '()\n', (565, 567), True, 'import gurobipy as gp\n')] |
"""
This module has been hosted using Google Cloud Platform. Every function has an
http endpoint that has been deployed with GCP.
"""
import pyrebase
from flask import Request, Flask
from model import FirebaseInvocations
app = Flask(__name__)
@app.route('/login_page_get', methods=['GET'])
def login_page_get(request:... | [
"model.FirebaseInvocations.get_invoice_json",
"model.FirebaseInvocations.get_list_of_invoice_ids",
"model.FirebaseInvocations.get_user_data",
"model.FirebaseInvocations.get_login_name",
"model.FirebaseInvocations.set_invoice_status",
"model.FirebaseInvocations.get_invoice_information",
"flask.Flask",
... | [((228, 243), 'flask.Flask', 'Flask', (['__name__'], {}), '(__name__)\n', (233, 243), False, 'from flask import Request, Flask\n'), ((1709, 1744), 'model.FirebaseInvocations.get_customers', 'FirebaseInvocations.get_customers', ([], {}), '()\n', (1742, 1744), False, 'from model import FirebaseInvocations\n'), ((2055, 21... |
from setuptools import setup, find_packages
version = '1.0.0.dev0'
requirements = [
'docker-py==4.2.0',
]
entry_points = {
'console_scripts': [
'docker_checker = docker_checker.docker_checker:main'
],
'gui_scripts': []
}
setup(
name='docker_checker',
version=version,
description=... | [
"setuptools.find_packages"
] | [((449, 481), 'setuptools.find_packages', 'find_packages', ([], {'exclude': "['tests']"}), "(exclude=['tests'])\n", (462, 481), False, 'from setuptools import setup, find_packages\n')] |
#!/usr/bin/env python3
# -*- coding: utf-8 -*-
import os
import pandas as pd
import numpy as np
import networkx as nx
# read training data
df_train = pd.read_csv('train.csv', dtype={'author': np.int64, 'hindex': np.float32})
n_train = df_train.shape[0]
# read test data
df_test = pd.read_csv('test.csv', dtype={'auth... | [
"pandas.read_csv"
] | [((153, 227), 'pandas.read_csv', 'pd.read_csv', (['"""train.csv"""'], {'dtype': "{'author': np.int64, 'hindex': np.float32}"}), "('train.csv', dtype={'author': np.int64, 'hindex': np.float32})\n", (164, 227), True, 'import pandas as pd\n'), ((284, 335), 'pandas.read_csv', 'pd.read_csv', (['"""test.csv"""'], {'dtype': "... |
from typing import List, Optional
from prometheus_client import Metric
from prometheus_client.parser import text_string_to_metric_families
from ..utils import RESTClient
class MetricsClient(RESTClient):
async def metrics(self) -> List[Metric]:
endpoint = f"http://{self._http_server}/metrics"
res... | [
"prometheus_client.parser.text_string_to_metric_families"
] | [((422, 465), 'prometheus_client.parser.text_string_to_metric_families', 'text_string_to_metric_families', (['raw_metrics'], {}), '(raw_metrics)\n', (452, 465), False, 'from prometheus_client.parser import text_string_to_metric_families\n')] |
import sys
from RemoveWindowsLockScreenAds.RemoveWindowsLockScreenAds import main
main(sys.argv)
| [
"RemoveWindowsLockScreenAds.RemoveWindowsLockScreenAds.main"
] | [((82, 96), 'RemoveWindowsLockScreenAds.RemoveWindowsLockScreenAds.main', 'main', (['sys.argv'], {}), '(sys.argv)\n', (86, 96), False, 'from RemoveWindowsLockScreenAds.RemoveWindowsLockScreenAds import main\n')] |
from fastapi import APIRouter
from app.schemas.user import User as SchemaUser
from app.services import user as service_user
router = APIRouter()
@router.post("/add-user/", tags=["User"])
async def add_user(user: SchemaUser):
return service_user.add_user(user)
| [
"app.services.user.add_user",
"fastapi.APIRouter"
] | [((133, 144), 'fastapi.APIRouter', 'APIRouter', ([], {}), '()\n', (142, 144), False, 'from fastapi import APIRouter\n'), ((238, 265), 'app.services.user.add_user', 'service_user.add_user', (['user'], {}), '(user)\n', (259, 265), True, 'from app.services import user as service_user\n')] |
# Copyright (c) 2022 <NAME>
#
# This Source Code Form is subject to the terms of the Mozilla Public
# License, v. 2.0. If a copy of the MPL was not distributed with this
# file, You can obtain one at http://mozilla.org/MPL/2.0/.
from __future__ import annotations
import json
from aiohttp import ClientError, ClientSes... | [
"mautrix.api.HTTPAPI",
"mautrix.errors.WellKnownUnexpectedStatus",
"mautrix.errors.WellKnownNotJSON",
"mautrix.errors.WellKnownMissingHomeserver",
"mautrix.errors.WellKnownInvalidVersionsResponse",
"mautrix.errors.WellKnownNotURL",
"aiohttp.ClientSession",
"mautrix.errors.WellKnownUnsupportedScheme",
... | [((5443, 5516), 'yarl.URL.build', 'URL.build', ([], {'scheme': '"""https"""', 'host': 'domain', 'path': '"""/.well-known/matrix/client"""'}), "(scheme='https', host=domain, path='/.well-known/matrix/client')\n", (5452, 5516), False, 'from yarl import URL\n'), ((6100, 6119), 'yarl.URL', 'URL', (['homeserver_url'], {}), ... |
import sublime
import sublime_plugin
class OpenUrlPanelCommand(sublime_plugin.WindowCommand):
def run(self):
settings = sublime.load_settings("OpenUrlPanel.sublime-settings")
items = settings.get("url_list", [])
project_data = self.window.project_data()
if project_data:
... | [
"sublime.run_command",
"sublime.load_settings"
] | [((134, 188), 'sublime.load_settings', 'sublime.load_settings', (['"""OpenUrlPanel.sublime-settings"""'], {}), "('OpenUrlPanel.sublime-settings')\n", (155, 188), False, 'import sublime\n'), ((733, 787), 'sublime.run_command', 'sublime.run_command', (['"""open_url"""', "{'url': items[id][1]}"], {}), "('open_url', {'url'... |
import os
import gevent.monkey
gevent.monkey.patch_all()
import multiprocessing
name = "backend"
debug = True
loglevel = "debug"
bind = "0.0.0.0:8080"
pidfile = "logs/gunicorn.pid"
# accesslog = "logs/access.log"
# errorlog = "logs/error.log"
# 启动的进程数
workers = multiprocessing.cpu_count() * 2 + 1
worker_class = "gu... | [
"multiprocessing.cpu_count"
] | [((266, 293), 'multiprocessing.cpu_count', 'multiprocessing.cpu_count', ([], {}), '()\n', (291, 293), False, 'import multiprocessing\n')] |
from flask import Blueprint
auth_blueprint = Blueprint('auth', __name__, url_prefix='/auth')
| [
"flask.Blueprint"
] | [((47, 94), 'flask.Blueprint', 'Blueprint', (['"""auth"""', '__name__'], {'url_prefix': '"""/auth"""'}), "('auth', __name__, url_prefix='/auth')\n", (56, 94), False, 'from flask import Blueprint\n')] |
from __future__ import division, print_function, absolute_import
from shutil import copyfile
from src.TensorFlowModels import ModelConfig
from src.Miscellaneous import bcolors
import os
import glob
import tflearn
import numpy as np
import pandas as pd
import tensorflow as tf
import src.TensorFlowModels as TFModels
i... | [
"os.remove",
"pandas.read_csv",
"tensorflow.reset_default_graph",
"numpy.shape",
"glob.glob",
"os.path.exists",
"tensorflow.variable_scope",
"numpy.reshape",
"shutil.copyfile",
"numpy.ceil",
"matplotlib.use",
"src.TensorFlowModels.ModelConfig",
"os.makedirs",
"numpy.isscalar",
"os.path.i... | [((337, 358), 'matplotlib.use', 'matplotlib.use', (['"""Agg"""'], {}), "('Agg')\n", (351, 358), False, 'import matplotlib\n'), ((778, 791), 'src.TensorFlowModels.ModelConfig', 'ModelConfig', ([], {}), '()\n', (789, 791), False, 'from src.TensorFlowModels import ModelConfig\n'), ((3483, 3507), 'tensorflow.reset_default_... |
# ------------------------------------------------------------------------------
# Program: The LDAR Simulator (LDAR-Sim)
# File: methods.deployment.OGI_Camera
# Purpose: OGI company specific deployment classes and methods based on RK (2018)
#
# Copyright (C) 2018-2021 Intelligent Methane Monitoring and... | [
"math.exp",
"numpy.random.binomial",
"methods.funcs.measured_rate",
"math.log10",
"numpy.random.normal",
"utils.attribution.update_tag"
] | [((1428, 1454), 'numpy.random.normal', 'np.random.normal', (['(4.9)', '(0.3)'], {}), '(4.9, 0.3)\n', (1444, 1454), True, 'import numpy as np\n'), ((1468, 1555), 'numpy.random.normal', 'np.random.normal', (["self.config['sensor']['MDL'][0]", "self.config['sensor']['MDL'][1]"], {}), "(self.config['sensor']['MDL'][0], sel... |
import logging
import os
import random
import yaml
from typing import Dict, List, Optional
from ravestate_verbaliser.qa_phrases import QAPhrases
"""
Produces actual utterances. This should in the future lead to diversifying
the ways Roboy is expressing information.
"""
TYPE_PHRASES: str = "phrases"
TYPE_QA: str = "q... | [
"logging.error",
"ravestate_verbaliser.qa_phrases.QAPhrases",
"random.choice",
"yaml.safe_load_all",
"os.path.join",
"os.listdir"
] | [((621, 640), 'os.listdir', 'os.listdir', (['dirpath'], {}), '(dirpath)\n', (631, 640), False, 'import os\n'), ((2490, 2517), 'random.choice', 'random.choice', (['list_or_none'], {}), '(list_or_none)\n', (2503, 2517), False, 'import random\n'), ((734, 810), 'logging.error', 'logging.error', (["('Cannot add folder ' + d... |
import socket, logging
MAX_FLOWS = 100
logging.basicConfig(level=logging.INFO)
logger = logging.getLogger(__name__)
class Collector(object):
def __init__(self, host="0.0.0.0", port=9996):
super(Collector, self).__init__()
self.host = host
self.port = port
self.listener = socket.so... | [
"logging.basicConfig",
"logging.warning",
"socket.socket",
"logging.info",
"logging.getLogger"
] | [((41, 80), 'logging.basicConfig', 'logging.basicConfig', ([], {'level': 'logging.INFO'}), '(level=logging.INFO)\n', (60, 80), False, 'import socket, logging\n'), ((90, 117), 'logging.getLogger', 'logging.getLogger', (['__name__'], {}), '(__name__)\n', (107, 117), False, 'import socket, logging\n'), ((311, 359), 'socke... |
import datetime
from mongoengine import StringField, IntField, DateTimeField, Document
class WalletInfo(Document):
address = StringField(max_length=128)
nonce = IntField()
created = DateTimeField()
modified = DateTimeField(default=datetime.datetime.utcnow)
def __repr__(self):
return str(... | [
"mongoengine.DateTimeField",
"mongoengine.StringField",
"mongoengine.IntField",
"datetime.datetime.utcnow"
] | [((132, 159), 'mongoengine.StringField', 'StringField', ([], {'max_length': '(128)'}), '(max_length=128)\n', (143, 159), False, 'from mongoengine import StringField, IntField, DateTimeField, Document\n'), ((172, 182), 'mongoengine.IntField', 'IntField', ([], {}), '()\n', (180, 182), False, 'from mongoengine import Stri... |
import requests
import json
import math
import time
from tqdm import tqdm
from random import randint
MAX_CARD_RESULTS = 175
all_commanders = list()
monocolored_commanders = list()
multicolored_commanders = list()
class Card(object):
name = ""
scryfall_uri = 0
png = ""
color_identity = ""
id = "... | [
"tqdm.tqdm",
"requests.request",
"json.loads",
"math.ceil"
] | [((6246, 6311), 'requests.request', 'requests.request', (['"""GET"""', 'url'], {'headers': 'headers', 'params': 'querystring'}), "('GET', url, headers=headers, params=querystring)\n", (6262, 6311), False, 'import requests\n'), ((6751, 6771), 'tqdm.tqdm', 'tqdm', (['new_card_array'], {}), '(new_card_array)\n', (6755, 67... |
from voximplant.apiclient import VoximplantAPI, VoximplantException
if __name__ == "__main__":
voxapi = VoximplantAPI("credentials.json")
# Get regions with city AACHEN.
COUNTRY_CODE = "DE"
PHONE_CATEGORY_NAME = "GEOGRAPHIC"
CITY_NAME = "AACHEN"
try:
res = voxapi.get_regions(... | [
"voximplant.apiclient.VoximplantAPI"
] | [((109, 142), 'voximplant.apiclient.VoximplantAPI', 'VoximplantAPI', (['"""credentials.json"""'], {}), "('credentials.json')\n", (122, 142), False, 'from voximplant.apiclient import VoximplantAPI, VoximplantException\n')] |
import numpy as np
from tilitools.svdd_dual_qp import SvddDualQP
class LatentSVDD:
""" Latent variable support vector data description.
Written by <NAME>, TU Berlin, 2014
For more information see:
'Learning and Evaluation with non-i.i.d Label Noise'
Goernitz et al., AISTATS & JML... | [
"numpy.array",
"tilitools.svdd_dual_qp.SvddDualQP",
"numpy.zeros",
"numpy.random.randn"
] | [((1386, 1405), 'numpy.zeros', 'np.zeros', (['(DIMS, N)'], {}), '((DIMS, N))\n', (1394, 1405), True, 'import numpy as np\n'), ((1439, 1458), 'numpy.zeros', 'np.zeros', (['(DIMS, N)'], {}), '((DIMS, N))\n', (1447, 1458), True, 'import numpy as np\n'), ((2933, 2944), 'numpy.zeros', 'np.zeros', (['N'], {}), '(N)\n', (2941... |
import unittest
from selector import BrewSelector
from brew import *
from collections import defaultdict
class SelectorTest(unittest.TestCase):
def setUp(self):
self.empty_bs=BrewSelector(empty=True)
self.brew_9=Brew('sequential', ['#F7FCFD', '#E5F5F9', '#CCECE6','#99D8C9', '#66C2A4', '#41AE76', '#238B45', '#00... | [
"unittest.main",
"collections.defaultdict",
"selector.BrewSelector"
] | [((3943, 3958), 'unittest.main', 'unittest.main', ([], {}), '()\n', (3956, 3958), False, 'import unittest\n'), ((181, 205), 'selector.BrewSelector', 'BrewSelector', ([], {'empty': '(True)'}), '(empty=True)\n', (193, 205), False, 'from selector import BrewSelector\n'), ((379, 393), 'selector.BrewSelector', 'BrewSelector... |
from .base import Module, Command
from discord import Status, Embed
import time
import random
import math
import json
import sys
'''
aiohttp:
asynch http requests in line with what we would expect
get it ready!
'''
class Fun(Module):
# probably runs on import, no longer needed.\
# also: this is a si... | [
"discord.Embed",
"random.choice",
"time.strftime",
"time.time",
"random.random"
] | [((850, 876), 'time.strftime', 'time.strftime', (['"""%B %d, %Y"""'], {}), "('%B %d, %Y')\n", (863, 876), False, 'import time\n'), ((979, 1055), 'discord.Embed', 'Embed', ([], {'title': '"""Fortune"""', 'type': '"""rich"""', 'color': '(15225390)', 'description': 'description'}), "(title='Fortune', type='rich', color=15... |
#!/usr/bin/env python
# coding: utf-8
# # ml lab5
# In[7]:
import os
import numpy as np
import scipy.optimize as opt
import scipy.io
import matplotlib.pyplot as plt
import matplotlib.image as mpimg
# ### 1. read `ex5data1.mat`
# In[4]:
data = scipy.io.loadmat('data/ex5data1.mat')
X = data['X']
y = np.squeez... | [
"sklearn.feature_extraction.text.CountVectorizer",
"numpy.sum",
"nltk.stem.PorterStemmer",
"matplotlib.pyplot.gca",
"sklearn.model_selection.train_test_split",
"numpy.zeros",
"numpy.argmin",
"re.sub",
"numpy.mean",
"numpy.array",
"numpy.arange",
"sklearn.svm.SVC",
"numpy.squeeze",
"sklearn... | [((311, 332), 'numpy.squeeze', 'np.squeeze', (["data['y']"], {}), "(data['y'])\n", (321, 332), True, 'import numpy as np\n'), ((839, 854), 'sklearn.svm.LinearSVC', 'svm.LinearSVC', ([], {}), '()\n', (852, 854), False, 'from sklearn import svm\n'), ((962, 1010), 'matplotlib.pyplot.subplots', 'plt.subplots', (['(1)', '(2... |
# -*- coding: utf-8 -*-
import xml.etree.ElementTree as ET
from xml.etree.ElementTree import ParseError
from urllib.request import Request, urlopen
import gzip
from .background import BackgroundThread
from django.db import transaction
from django.shortcuts import get_object_or_404
from django.utils import timezone
fr... | [
"urllib.request.Request",
"xml.etree.ElementTree.fromstring",
"django.utils.timezone.now",
"urllib.request.urlopen",
"django.db.transaction.atomic"
] | [((1245, 1257), 'urllib.request.Request', 'Request', (['url'], {}), '(url)\n', (1252, 1257), False, 'from urllib.request import Request, urlopen\n'), ((1335, 1347), 'urllib.request.urlopen', 'urlopen', (['req'], {}), '(req)\n', (1342, 1347), False, 'from urllib.request import Request, urlopen\n'), ((4575, 4598), 'xml.e... |