code stringlengths 22 1.05M | apis listlengths 1 3.31k | extract_api stringlengths 75 3.25M |
|---|---|---|
# Code provided by:
# @misc{Subramanian2020,
# author = {<NAME>},
# title = {PyTorch-VAE},
# year = {2020},
# publisher = {GitHub},
# journal = {GitHub repository},
# howpublished = {\url{https://github.com/AntixK/PyTorch-VAE}}
# }
from torch import nn
from abc import abstractmethod
from typing import Lis... | [
"typing.TypeVar"
] | [((347, 370), 'typing.TypeVar', 'TypeVar', (['"""torch.tensor"""'], {}), "('torch.tensor')\n", (354, 370), False, 'from typing import List, Any, TypeVar\n')] |
# -*- coding: utf-8 -*-
# @Author: wqshen
# @Email: <EMAIL>
# @Date: 2020/6/10 14:43
# @Last Modified by: wqshen
import numpy as np
from logzero import logger
from .point_stat_base import PointStatBase
class ContinuousVariableVerification(PointStatBase):
def __init__(self, forecast=None, obs=None, fcsterr=None,... | [
"numpy.quantile",
"numpy.average",
"numpy.abs",
"numpy.std",
"numpy.corrcoef",
"scipy.stats.spearmanr",
"numpy.isnan",
"numpy.percentile",
"numpy.array",
"logzero.logger.warning",
"scipy.stats.kendalltau"
] | [((1751, 1771), 'numpy.average', 'np.average', (['forecast'], {}), '(forecast)\n', (1761, 1771), True, 'import numpy as np\n'), ((2252, 2267), 'numpy.average', 'np.average', (['obs'], {}), '(obs)\n', (2262, 2267), True, 'import numpy as np\n'), ((2936, 2952), 'numpy.std', 'np.std', (['forecast'], {}), '(forecast)\n', (... |
import numpy as np
from scipy.integrate import solve_ivp
import matplotlib.pyplot as plt
from numpy.random import randint, rand
from sir import *
def SIR_continuous_reinfected(b,k,time,ii,r):
"""
Simulates continuous SIR model
ii = initial percentage of infected
time = Days of simulation
b = proba... | [
"numpy.zeros",
"scipy.integrate.solve_ivp",
"numpy.random.randint",
"numpy.array",
"numpy.int",
"numpy.linspace",
"numpy.random.rand"
] | [((717, 743), 'numpy.linspace', 'np.linspace', (['(0)', 'time', 'time'], {}), '(0, time, time)\n', (728, 743), True, 'import numpy as np\n'), ((755, 827), 'scipy.integrate.solve_ivp', 'solve_ivp', (['SIR', '[0, time]', '[1 - ii, 0, ii]'], {'method': '"""RK45"""', 't_eval': 't_eval'}), "(SIR, [0, time], [1 - ii, 0, ii],... |
# Generated by Django 2.1.1 on 2018-09-13 18:15
from django.db import migrations, models
import django.utils.timezone
import showcase.models
class Migration(migrations.Migration):
initial = True
dependencies = [
]
operations = [
migrations.CreateModel(
name='Portfolio',
... | [
"django.db.models.TextField",
"django.db.models.CharField",
"django.db.models.SlugField",
"django.db.models.AutoField",
"django.db.models.ImageField",
"django.db.models.DateTimeField"
] | [((357, 450), '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", (373, 450), False, 'from django.db import migrations, models\... |
#!/usr/bin/env python
# -*- coding: utf-8 -*-
try:
import socketserver
except:
import SocketServer as socketserver
import signal
import socket
import serial
import os
import json
import sys
HOST, PORT = '0.0.0.0', 51234
serial = serial.Serial('/dev/ttyACM0', 57600)
class ScratchHandler(socketserver.BaseRequ... | [
"serial.Serial",
"signal.signal",
"os.system",
"json.loads"
] | [((239, 275), 'serial.Serial', 'serial.Serial', (['"""/dev/ttyACM0"""', '(57600)'], {}), "('/dev/ttyACM0', 57600)\n", (252, 275), False, 'import serial\n'), ((1976, 2020), 'signal.signal', 'signal.signal', (['signal.SIGINT', 'signal.SIG_DFL'], {}), '(signal.SIGINT, signal.SIG_DFL)\n', (1989, 2020), False, 'import signa... |
# -*- coding: utf-8 -*-
import pytest
from boto.dynamodb2.fields import HashKey
from boto.dynamodb2.fields import RangeKey
from boto.dynamodb2.fields import GlobalAllIndex
from boto.dynamodb2.table import Table
from mycroft.models.aws_connections import get_avro_schema
from mycroft.models.etl_records import ETLRecord... | [
"pytest.yield_fixture",
"mycroft.logic.run_actions.list_runs_by_job_id",
"boto.dynamodb2.fields.HashKey",
"mycroft.models.etl_records.ETLRecords",
"boto.dynamodb2.table.Table.create",
"mycroft.logic.run_actions._parse_runs",
"pytest.raises",
"tests.models.test_etl_record.FakeETLRecord",
"pytest.mark... | [((1121, 1157), 'pytest.yield_fixture', 'pytest.yield_fixture', ([], {'scope': '"""module"""'}), "(scope='module')\n", (1141, 1157), False, 'import pytest\n'), ((2355, 2415), 'pytest.mark.parametrize', 'pytest.mark.parametrize', (['"""job_id"""', "['y', '..', '!', '', '_']"], {}), "('job_id', ['y', '..', '!', '', '_'])... |
from django import forms
from django.contrib.auth.models import Group
from django.contrib.auth.forms import ReadOnlyPasswordHashField
from django.core.exceptions import ValidationError
from django.contrib.auth import authenticate
from .models import User, Profile
from django.contrib import messages
from phonenum... | [
"django.core.exceptions.ValidationError",
"django.forms.ChoiceField",
"django.forms.TextInput",
"django.forms.DateInput",
"django.contrib.auth.forms.ReadOnlyPasswordHashField",
"django.forms.EmailInput",
"django.forms.ValidationError",
"phonenumber_field.widgets.PhoneNumberPrefixWidget",
"django.for... | [((652, 713), 'django.forms.CharField', 'forms.CharField', ([], {'label': '"""Password"""', 'widget': 'forms.PasswordInput'}), "(label='Password', widget=forms.PasswordInput)\n", (667, 713), False, 'from django import forms\n'), ((731, 805), 'django.forms.CharField', 'forms.CharField', ([], {'label': '"""Password confi... |
"""
Copyright 2016 <NAME>, <NAME>
Licensed under the Apache License, Version 2.0 (the "License");
you may not use this file except in compliance with the License.
You may obtain a copy of the License at
http://www.apache.org/licenses/LICENSE-2.0
Unless required by applicable law or agreed to in writing, software... | [
"django.db.models.TimeField",
"django.db.models.CharField",
"django.db.models.ForeignKey",
"django.core.validators.MinValueValidator",
"django.db.models.FloatField",
"django.db.models.AutoField",
"django.db.models.IntegerField",
"django.core.validators.RegexValidator",
"django.db.models.DateTimeFiel... | [((697, 789), 'django.core.validators.RegexValidator', 'validators.RegexValidator', (['"""^[0-9a-zA-Z]+$"""', '"""Only alphanumeric characters are allowed."""'], {}), "('^[0-9a-zA-Z]+$',\n 'Only alphanumeric characters are allowed.')\n", (722, 789), False, 'from django.core import validators\n'), ((1533, 1612), 'dja... |
"""
Adapted Code from https://github.com/AtsushiSakai/PythonRobotics
"""
from functools import partial
from estimation import ExtendedKalmanFilter, KalmanFilter
import jax.numpy as jnp
import numpy as np
from jax import jacfwd, jit
import matplotlib.pyplot as plt
from src.environments import DiffDriveRobot
from uti... | [
"estimation.ExtendedKalmanFilter",
"jax.numpy.array",
"jax.numpy.deg2rad",
"src.environments.DiffDriveRobot",
"jax.jit",
"jax.numpy.eye",
"util.History",
"util.plot",
"jax.numpy.cos",
"jax.numpy.zeros",
"jax.numpy.sin"
] | [((577, 616), 'jax.numpy.array', 'jnp.array', (['[[1, 0, 0, 0], [0, 1, 0, 0]]'], {}), '([[1, 0, 0, 0], [0, 1, 0, 0]])\n', (586, 616), True, 'import jax.numpy as jnp\n'), ((735, 758), 'jax.numpy.array', 'jnp.array', (['[v, yawrate]'], {}), '([v, yawrate])\n', (744, 758), True, 'import jax.numpy as jnp\n'), ((795, 811), ... |
"""
==================================================================
Compare LogisticRegression solver with sklearn's liblinear backend
==================================================================
"""
import time
import warnings
import numpy as np
from numpy.linalg import norm
import matplotlib.pyplot as plt
f... | [
"celer.LogisticRegression",
"matplotlib.pyplot.show",
"libsvmdata.fetch_libsvm",
"warnings.filterwarnings",
"matplotlib.pyplot.close",
"matplotlib.pyplot.legend",
"time.time",
"matplotlib.pyplot.figure",
"sklearn.linear_model.LogisticRegression",
"numpy.arange",
"numpy.array",
"numpy.linalg.no... | [((427, 498), 'warnings.filterwarnings', 'warnings.filterwarnings', (['"""ignore"""'], {'message': '"""Objective did not converge"""'}), "('ignore', message='Objective did not converge')\n", (450, 498), False, 'import warnings\n'), ((499, 572), 'warnings.filterwarnings', 'warnings.filterwarnings', (['"""ignore"""'], {'... |
#! /usr/bin/env python
import testbase
import unittest
import samweb_client
import samweb_cli
import time,os
defname = 'test-project'
class TestDefinition(testbase.SamdevTest):
def test_descDefinition_DefNotFound(self):
fake_def_name = 'doesnotexist_%d' % time.time()
self.assertRaises(samweb_clie... | [
"unittest.main",
"os.getpid",
"time.time"
] | [((1746, 1761), 'unittest.main', 'unittest.main', ([], {}), '()\n', (1759, 1761), False, 'import unittest\n'), ((271, 282), 'time.time', 'time.time', ([], {}), '()\n', (280, 282), False, 'import time, os\n'), ((956, 967), 'os.getpid', 'os.getpid', ([], {}), '()\n', (965, 967), False, 'import time, os\n'), ((973, 984), ... |
#!/usr/bin/env python
# -*- coding: utf-8 -*-
# Copyright (c) Microsoft Corporation. All rights reserved.
# Licensed under the MIT License.
"""Minibatching utilities."""
import itertools
import operator
import os
import pickle
import numpy as np
import torch
from sklearn.utils import shuffle
from torch.autograd impor... | [
"itertools.chain.from_iterable",
"torch.LongTensor",
"os.path.exists",
"numpy.argsort",
"numpy.mean",
"sklearn.utils.shuffle",
"torch.no_grad",
"os.path.join",
"operator.itemgetter"
] | [((22510, 22525), 'numpy.mean', 'np.mean', (['losses'], {}), '(losses)\n', (22517, 22525), True, 'import numpy as np\n'), ((9204, 9281), 'sklearn.utils.shuffle', 'shuffle', (["self.src[idx]['data']", "self.trg[idx]['data']"], {'random_state': 'self.seed'}), "(self.src[idx]['data'], self.trg[idx]['data'], random_state=s... |
# Copyright 2018 AT&T Corporation.
# 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 require... | [
"tempest.lib.decorators.idempotent_id",
"patrole_tempest_plugin.rbac_rule_validation.action",
"tempest.common.utils.is_extension_enabled"
] | [((1234, 1313), 'patrole_tempest_plugin.rbac_rule_validation.action', 'rbac_rule_validation.action', ([], {'service': '"""neutron"""', 'rules': "['get_availability_zone']"}), "(service='neutron', rules=['get_availability_zone'])\n", (1261, 1313), False, 'from patrole_tempest_plugin import rbac_rule_validation\n'), ((13... |
# Solution of;
# Project Euler Problem 113: Non-bouncy numbers
# https://projecteuler.net/problem=113
#
# Working from left-to-right if no digit is exceeded by the digit to its left
# it is called an increasing number; for example, 134468. Similarly if no
# digit is exceeded by the digit to its right it is called a ... | [
"timed.caller"
] | [((909, 943), 'timed.caller', 'timed.caller', (['dummy', 'n', 'i', 'prob_id'], {}), '(dummy, n, i, prob_id)\n', (921, 943), False, 'import timed\n')] |
import bot
if __name__ == '__main__':
zonbot = bot.Bot('!', pm_help = True)
zonbot.run(zonbot.token)
| [
"bot.Bot"
] | [((49, 75), 'bot.Bot', 'bot.Bot', (['"""!"""'], {'pm_help': '(True)'}), "('!', pm_help=True)\n", (56, 75), False, 'import bot\n')] |
import argparse
import os.path
import oyaml as yaml
def parse_constraint(con_str):
# sample: (0,1):(1,1,1)
agents_str, coefficients_str = con_str.split(':')
x, y = agents_str.replace('(', '').replace(')', '').split(',')
a, b, c = coefficients_str.replace('(', '').replace(')', '').split(',')
c1 = ... | [
"oyaml.dump",
"argparse.ArgumentParser"
] | [((3013, 3116), 'argparse.ArgumentParser', 'argparse.ArgumentParser', ([], {'description': '"""Convert DynaGraph sim file to pyDCOP compatible yaml config"""'}), "(description=\n 'Convert DynaGraph sim file to pyDCOP compatible yaml config')\n", (3036, 3116), False, 'import argparse\n'), ((2032, 2055), 'oyaml.dump',... |
# -*- coding: utf-8 -*-
'''
This code calculates changes in the ratio between different population-weighted GDP deciles and quintiles
by <NAME> (<EMAIL>)
'''
import pandas as pd
import numpy as np
from netCDF4 import Dataset
import _env
datasets = _env.datasets
scenarios = _env.scenarios
gdp_year = 201... | [
"pandas.DataFrame",
"numpy.size",
"_env.mkdirs",
"pandas.read_csv",
"numpy.median",
"numpy.percentile",
"numpy.where",
"pandas.ExcelWriter"
] | [((599, 671), 'pandas.read_csv', 'pd.read_csv', (["(_env.odir_root + 'basic_stats' + '/Country_Basic_Stats.csv')"], {}), "(_env.odir_root + 'basic_stats' + '/Country_Basic_Stats.csv')\n", (610, 671), True, 'import pandas as pd\n'), ((1834, 1898), 'numpy.where', 'np.where', (["(itbl_gdp_baseline[sgdp_year + '_pop_ratio_... |
__author__ = "<NAME>"
__copyright__ = "2021, Hamilton-Jacobi Analysis in Python"
__license__ = "Molux Licence"
__maintainer__ = "<NAME>"
__email__ = "<EMAIL>"
__status__ = "Completed"
import argparse
from mpl_toolkits.mplot3d import Axes3D
import numpy as np
import os, sys
from os.path import abspath, dirname... | [
"matplotlib.pyplot.subplot",
"os.path.abspath",
"argparse.ArgumentParser",
"os.path.join",
"matplotlib.pyplot.clf",
"numpy.ones",
"Grids.createGrid",
"matplotlib.pyplot.ion",
"matplotlib.pyplot.figure",
"numpy.array",
"matplotlib.gridspec.GridSpec",
"matplotlib.pyplot.pause"
] | [((625, 747), 'argparse.ArgumentParser', 'argparse.ArgumentParser', ([], {'description': '"""2D Plotter for Various Implicit Initial Conditions for the Value Function"""'}), "(description=\n '2D Plotter for Various Implicit Initial Conditions for the Value Function'\n )\n", (648, 747), False, 'import argparse\n')... |
# Module for cleaning messages from all unwanted content
import re
def clean_all(msg):
msg = clean_invite_embed(msg)
msg = clean_backticks(msg)
msg = clean_mentions(msg)
msg = clean_emojis(msg)
return msg
def clean_invite_embed(msg):
"""Prevents invites from embedding"""
return msg.repl... | [
"re.sub"
] | [((582, 615), 're.sub', 're.sub', (['"""([`*_])"""', '"""\\\\\\\\\\\\1"""', 'msg'], {}), "('([`*_])', '\\\\\\\\\\\\1', msg)\n", (588, 615), False, 'import re\n'), ((784, 853), 're.sub', 're.sub', (['"""<(a)?:([a-zA-Z0-9_]+):([0-9]+)>"""', '"""<\u200b\\\\1:\\\\2:\\\\3>"""', 'msg'], {}), "('<(a)?:([a-zA-Z0-9_]+):([0-9]+)... |
from ConfigParser import ConfigParser
import logging
import os
import sys
from wordsim.models import get_models
from wordsim.nn.utils import evaluate
from wordsim.nn.data import create_datasets
from wordsim.nn.model import KerasModel
def main():
logging.basicConfig(
level=logging.INFO,
format="%(... | [
"logging.basicConfig",
"wordsim.nn.model.KerasModel",
"wordsim.nn.data.create_datasets",
"wordsim.nn.utils.evaluate",
"ConfigParser.ConfigParser",
"wordsim.models.get_models"
] | [((253, 379), 'logging.basicConfig', 'logging.basicConfig', ([], {'level': 'logging.INFO', 'format': "('%(asctime)s : ' + '%(module)s (%(lineno)s) - %(levelname)s - %(message)s')"}), "(level=logging.INFO, format='%(asctime)s : ' +\n '%(module)s (%(lineno)s) - %(levelname)s - %(message)s')\n", (272, 379), False, 'imp... |
import requests
import hashlib
import time
import json
from pymongo import MongoClient
headers = {
'content-type': 'application/x-www-form-urlencoded',
}
userInfo = {
'player1':{
'uid': '玩家1号的uid',
'token': '玩家1号的token'
},
'player2':{
'uid': '玩家2号的uid',
'token': '玩家2号的t... | [
"requests.session",
"pymongo.MongoClient",
"hashlib.md5",
"json.loads",
"time.sleep",
"time.time"
] | [((345, 363), 'requests.session', 'requests.session', ([], {}), '()\n', (361, 363), False, 'import requests\n'), ((472, 503), 'pymongo.MongoClient', 'MongoClient', (['"""localhost"""', '(27017)'], {}), "('localhost', 27017)\n", (483, 503), False, 'from pymongo import MongoClient\n'), ((1276, 1289), 'hashlib.md5', 'hash... |
import random
import plotly.express as px
import plotly.figure_factory as ff
import statistics
dice_result = []
for i in range(0,1000):
dice1 = random.randint(1,6)
dice2 = random.randint(1,6)
dice_result.append(dice1+dice2)
mean = sum(dice_result)/len(dice_result)
print("mean of this da... | [
"statistics.median",
"random.randint",
"statistics.stdev",
"plotly.figure_factory.create_distplot",
"statistics.mode"
] | [((357, 387), 'statistics.median', 'statistics.median', (['dice_result'], {}), '(dice_result)\n', (374, 387), False, 'import statistics\n'), ((449, 477), 'statistics.mode', 'statistics.mode', (['dice_result'], {}), '(dice_result)\n', (464, 477), False, 'import statistics\n'), ((545, 574), 'statistics.stdev', 'statistic... |
#!/usr/bin/env python
# -*- coding: utf-8 -*-
#
# Copyright (c) 2020, Intel Corporation. All rights reserved.
# SPDX-License-Identifier: BSD-2-Clause
#
"""A signing utility for creating and signing a BIOS sub-region for UEFI
"""
from __future__ import print_function
import os
import sys
import subprocess
import arg... | [
"common.utilities.check_key",
"subprocess.run",
"os.path.abspath",
"common.logger.getLogger",
"argparse.ArgumentParser",
"os.path.getsize",
"common.banner.banner",
"struct.calcsize",
"struct.pack",
"common.utilities.check_for_tool",
"common.utilities.file_exist",
"uuid.UUID",
"pathlib.Path",... | [((633, 668), 'common.logger.getLogger', 'logging.getLogger', (['"""subregion_sign"""'], {}), "('subregion_sign')\n", (650, 668), True, 'import common.logger as logging\n'), ((1904, 1942), 'struct.calcsize', 'struct.calcsize', (['_StructAuthInfoFormat'], {}), '(_StructAuthInfoFormat)\n', (1919, 1942), False, 'import st... |
# coding: utf-8
from __future__ import absolute_import
from datetime import date, datetime # noqa: F401
from typing import List, Dict # noqa: F401
from swagger_server.models.base_model_ import Model
from swagger_server import util
class DataUtility(Model):
"""NOTE: This class is auto generated by the swagger... | [
"swagger_server.util.deserialize_model"
] | [((2013, 2046), 'swagger_server.util.deserialize_model', 'util.deserialize_model', (['dikt', 'cls'], {}), '(dikt, cls)\n', (2035, 2046), False, 'from swagger_server import util\n')] |
#!/usr/bin/env python
# -*- coding: utf-8 -*-
"""
@author: <NAME>
@contact: <EMAIL>
@software: PyCharm
@file: random.py
@time: 2020/1/15 2:29
@desc:
"""
import numpy as np
import torch
import random
from typing import Union
__all__ = ['set_numpy_rand_seed', 'set_py_rand_seed', 'set_torch_rand_seed', 'set_rand_seed',
... | [
"torch.cuda.is_available",
"torch.initial_seed"
] | [((1179, 1204), 'torch.cuda.is_available', 'torch.cuda.is_available', ([], {}), '()\n', (1202, 1204), False, 'import torch\n'), ((2259, 2279), 'torch.initial_seed', 'torch.initial_seed', ([], {}), '()\n', (2277, 2279), False, 'import torch\n')] |
"""
This module tests the creation of pipeline nodes from various different types
and combinations of types.
"""
import textwrap
import pytest
from find_kedro import find_kedro
contents = [
(
"single_nodes",
2,
"""\
from kedro.pipeline import node
node_a_b = node(lambda x: x, "a"... | [
"find_kedro.find_kedro",
"pytest.mark.parametrize",
"textwrap.dedent"
] | [((5442, 5503), 'pytest.mark.parametrize', 'pytest.mark.parametrize', (['"""name, num_nodes, content"""', 'contents'], {}), "('name, num_nodes, content', contents)\n", (5465, 5503), False, 'import pytest\n'), ((5665, 5707), 'find_kedro.find_kedro', 'find_kedro', ([], {'directory': 'tmpdir', 'verbose': '(True)'}), '(dir... |
"""
Tests for the API /configfiles/ methods.
"""
import datetime
import mock
from oslo.config import cfg
from bricks.common import utils
from bricks.openstack.common import timeutils
from bricks.tests.api import base
from bricks.tests.api import utils as apiutils
from bricks.tests.db import utils as dbutils
class ... | [
"mock.patch.object",
"bricks.common.utils.generate_uuid",
"oslo.config.cfg.CONF.set_override",
"bricks.common.utils.is_uuid_like",
"bricks.openstack.common.timeutils.parse_isotime",
"datetime.datetime",
"bricks.tests.db.utils.get_test_configfile"
] | [((5243, 5281), 'mock.patch.object', 'mock.patch.object', (['timeutils', '"""utcnow"""'], {}), "(timeutils, 'utcnow')\n", (5260, 5281), False, 'import mock\n'), ((6661, 6699), 'mock.patch.object', 'mock.patch.object', (['timeutils', '"""utcnow"""'], {}), "(timeutils, 'utcnow')\n", (6678, 6699), False, 'import mock\n'),... |
# -*- coding: utf8 -*-
import itertools
def formatLine(r):
r = list(r)
l1 = ' '.join('{:02x}'.format(c) for c in r)
l2 = ''.join(chr(c) if 32 <= c < 127 else '.' for c in r)
return l1, l2
def hexDump(data):
size, over = divmod(len(data), 16)
if over:
size += 1
offsets = range(0,... | [
"itertools.islice"
] | [((372, 405), 'itertools.islice', 'itertools.islice', (['data', 'o', '(o + 16)'], {}), '(data, o, o + 16)\n', (388, 405), False, 'import itertools\n')] |
from caos._internal.constants import ValidDependencyVersionRegex
from caos._internal.exceptions import InvalidDependencyVersionFormat, UnexpectedError
from typing import NewType
PipReadyDependency = NewType(name="PipReadyDependency", tp=str)
def _is_dependency_name_in_wheel(dependency_name: str, wheel: str, version:... | [
"caos._internal.exceptions.UnexpectedError",
"caos._internal.constants.ValidDependencyVersionRegex.WHEEL.value.match",
"caos._internal.constants.ValidDependencyVersionRegex.MAJOR_MINOR.value.match",
"caos._internal.constants.ValidDependencyVersionRegex.TARGZ.value.match",
"caos._internal.constants.ValidDepe... | [((200, 242), 'typing.NewType', 'NewType', ([], {'name': '"""PipReadyDependency"""', 'tp': 'str'}), "(name='PipReadyDependency', tp=str)\n", (207, 242), False, 'from typing import NewType\n'), ((687, 753), 'caos._internal.constants.ValidDependencyVersionRegex.MAJOR_MINOR_PATCH.value.match', 'ValidDependencyVersionRegex... |
import os
from django.shortcuts import render,get_object_or_404, redirect
from django.http import FileResponse
from .models import GameCategory, Game
from comment.forms import GameCommentForm,SubGCommentForm
from comment.models import SubGComment
from .forms import UploadGameForm
BASE_DIR = os.path.dirname(os.path.d... | [
"os.path.abspath",
"comment.models.SubGComment.objects.filter",
"django.shortcuts.redirect",
"django.http.FileResponse",
"comment.forms.GameCommentForm",
"django.shortcuts.get_object_or_404",
"comment.forms.SubGCommentForm",
"django.shortcuts.render"
] | [((637, 707), 'django.shortcuts.render', 'render', (['request', '"""home/portfolio.html"""'], {'context': "{'gameList': gameList}"}), "(request, 'home/portfolio.html', context={'gameList': gameList})\n", (643, 707), False, 'from django.shortcuts import render, get_object_or_404, redirect\n'), ((747, 777), 'django.short... |
#!/usr/bin/env python
#
# Dummy script to replace numactl in testing environment
#
import argparse
import subprocess
print("Using dummy numactl")
parser = argparse.ArgumentParser()
parser.add_argument("cmd", nargs="*")
args, unknown = parser.parse_known_args()
p = subprocess.Popen(args.cmd)
p.wait()
| [
"subprocess.Popen",
"argparse.ArgumentParser"
] | [((157, 182), 'argparse.ArgumentParser', 'argparse.ArgumentParser', ([], {}), '()\n', (180, 182), False, 'import argparse\n'), ((269, 295), 'subprocess.Popen', 'subprocess.Popen', (['args.cmd'], {}), '(args.cmd)\n', (285, 295), False, 'import subprocess\n')] |
import json
import os
from pathlib import Path
current_path = os.path.abspath(__file__)
default_raw_path = os.path.join(current_path, '../../data/datasets/twitter/raw/')
unlabeled_data_path = Path(os.path.join(os.path.abspath(__file__), '../../../data/datasets/twitter/raw/unlabeled'))
def generate_label_data(file_na... | [
"json.dump",
"os.path.abspath",
"json.loads",
"json.dumps",
"pathlib.Path",
"os.path.join"
] | [((63, 88), 'os.path.abspath', 'os.path.abspath', (['__file__'], {}), '(__file__)\n', (78, 88), False, 'import os\n'), ((108, 170), 'os.path.join', 'os.path.join', (['current_path', '"""../../data/datasets/twitter/raw/"""'], {}), "(current_path, '../../data/datasets/twitter/raw/')\n", (120, 170), False, 'import os\n'),... |
import datetime
from django.contrib.syndication.views import Feed
from django.utils import timezone
from django.urls import reverse
from django.views import generic
from .models import Post
class PostDetailView(generic.DetailView):
model = Post
queryset = Post.objects.exclude(status='D')
template_name = '... | [
"django.urls.reverse",
"datetime.time",
"django.utils.timezone.now"
] | [((1141, 1181), 'django.urls.reverse', 'reverse', (['"""blog:detail"""'], {'args': '[item.slug]'}), "('blog:detail', args=[item.slug])\n", (1148, 1181), False, 'from django.urls import reverse\n'), ((1009, 1024), 'datetime.time', 'datetime.time', ([], {}), '()\n', (1022, 1024), False, 'import datetime\n'), ((612, 626),... |
from fractions import Fraction
from django.db import models
from django.contrib.auth.models import User
from django.dispatch import receiver
from django.db.models.signals import post_save
@receiver(post_save, sender=User)
def create_blank_statistics(sender, instance=None, created=False, **kwargs):
if created:
... | [
"django.db.models.TextField",
"django.db.models.OneToOneField",
"django.db.models.ManyToManyField",
"django.db.models.CharField",
"django.db.models.ForeignKey",
"django.dispatch.receiver",
"django.db.models.IntegerField",
"fractions.Fraction"
] | [((192, 224), 'django.dispatch.receiver', 'receiver', (['post_save'], {'sender': 'User'}), '(post_save, sender=User)\n', (200, 224), False, 'from django.dispatch import receiver\n'), ((3704, 3741), 'django.dispatch.receiver', 'receiver', (['post_save'], {'sender': 'Statistic'}), '(post_save, sender=Statistic)\n', (3712... |
import pandas as pd
import numpy as np
import matplotlib.pyplot as plt
import seaborn as sns
import scipy
from statsmodels import robust
class Singular_description(object):
'''
Display statistics from every numerical column in data set.
Base class for Mutual description instance.
Outcomes are repre... | [
"seaborn.set_style",
"numpy.average",
"scipy.stats.mode",
"numpy.median",
"numpy.std",
"scipy.stats.entropy",
"matplotlib.pyplot.yticks",
"pandas.unique",
"numpy.percentile",
"scipy.stats.variation",
"scipy.stats.skew",
"numpy.mean",
"numpy.subtract.outer",
"seaborn.distplot",
"matplotli... | [((784, 810), 'seaborn.set_style', 'sns.set_style', (['"""whitegrid"""'], {}), "('whitegrid')\n", (797, 810), True, 'import seaborn as sns\n'), ((838, 852), 'matplotlib.pyplot.subplots', 'plt.subplots', ([], {}), '()\n', (850, 852), True, 'import matplotlib.pyplot as plt\n'), ((909, 979), 'seaborn.distplot', 'sns.distp... |
import os
from sqlalchemy.dialects.postgresql.json import JSONB
from sqlalchemy.types import ARRAY, JSON, Boolean, Float, Integer, String
PKG_NAME = "pipestat"
LOCK_PREFIX = "lock."
REPORT_CMD = "report"
INSPECT_CMD = "inspect"
REMOVE_CMD = "remove"
RETRIEVE_CMD = "retrieve"
STATUS_CMD = "status"
SUBPARSER_MSGS = {
... | [
"sqlalchemy.types.String",
"os.path.abspath"
] | [((3389, 3400), 'sqlalchemy.types.String', 'String', (['(500)'], {}), '(500)\n', (3395, 3400), False, 'from sqlalchemy.types import ARRAY, JSON, Boolean, Float, Integer, String\n'), ((3496, 3521), 'os.path.abspath', 'os.path.abspath', (['__file__'], {}), '(__file__)\n', (3511, 3521), False, 'import os\n'), ((3617, 3642... |
import logging
import random
import requests
import board
import neopixel
import smbus2
from apscheduler.schedulers.blocking import BlockingScheduler
class LedController:
def reset(self):
pass
def set(self, id):
pass
class LoggingLedController(LedController):
def reset(self):
l... | [
"logging.debug",
"random.randint",
"logging.basicConfig",
"logging.warn",
"smbus2.SMBus",
"logging.info",
"requests.get",
"neopixel.NeoPixel",
"apscheduler.schedulers.blocking.BlockingScheduler"
] | [((1672, 1711), 'logging.basicConfig', 'logging.basicConfig', ([], {'level': 'logging.INFO'}), '(level=logging.INFO)\n', (1691, 1711), False, 'import logging\n'), ((2060, 2083), 'random.randint', 'random.randint', (['(-1)', '(100)'], {}), '(-1, 100)\n', (2074, 2083), False, 'import random\n'), ((2940, 2973), 'logging.i... |
from flask_restful import Resource, request, abort
from flask_restful_swagger import swagger
from hpcpm.api import log
from hpcpm.api.helpers.database import database
from hpcpm.api.helpers.utils import abort_when_not_int, abort_when_node_not_found
from hpcpm.api.helpers.constants import COMPUTATION_NODE_PARAM_NAME, C... | [
"hpcpm.api.helpers.utils.abort_when_node_not_found",
"flask_restful.request.args.get",
"hpcpm.api.helpers.database.database.replace_soft_limit_for_device",
"hpcpm.api.helpers.database.database.delete_soft_limit_info",
"flask_restful.abort",
"hpcpm.api.log.info",
"flask_restful_swagger.swagger.operation"... | [((615, 1035), 'flask_restful_swagger.swagger.operation', 'swagger.operation', ([], {'notes': '"""This endpoint is used for setting soft limit for given device."""', 'nickname': '"""/nodes/computation_node/<string:name>/<string:device_id>/soft_limit"""', 'parameters': '[COMPUTATION_NODE_PARAM_NAME, DEVICE_IDENTIFIER_PA... |
import imageio
import numpy as np
import matplotlib.pyplot as plt
import matplotlib.animation as animation
from skimage.transform import resize
from IPython.display import HTML
import warnings
import sys
import os
from demo import load_checkpoints
from demo import make_animation
from skimage import img_as_ubyte
warnin... | [
"warnings.filterwarnings",
"demo.load_checkpoints",
"imageio.imread",
"os.path.exists",
"os.system",
"skimage.img_as_ubyte",
"imageio.mimread",
"skimage.transform.resize",
"demo.make_animation",
"os.path.join",
"os.listdir",
"sys.exit"
] | [((314, 347), 'warnings.filterwarnings', 'warnings.filterwarnings', (['"""ignore"""'], {}), "('ignore')\n", (337, 347), False, 'import warnings\n'), ((525, 584), 'os.path.join', 'os.path.join', (['os.curdir', '"""resources"""', '"""combos"""', 'sys.argv[1]'], {}), "(os.curdir, 'resources', 'combos', sys.argv[1])\n", (5... |
'''
Script to convert a MAF to a vcf4.2 file using python >=3.6.
Created by <NAME>
8 March 2018
'''
import os
import sys
from optparse import OptionParser
import subprocess
from functools import wraps
import datetime
import time
import numpy as np
def OptionParsing():
usage = 'usage: %prog -i <*.maf> -o <director... | [
"sys.stdout.write",
"subprocess.Popen",
"os.path.abspath",
"optparse.OptionParser",
"os.system",
"time.time",
"sys.stdout.flush",
"numpy.arange",
"functools.wraps",
"sys.exit",
"datetime.datetime.now",
"numpy.random.shuffle"
] | [((349, 368), 'optparse.OptionParser', 'OptionParser', (['usage'], {}), '(usage)\n', (361, 368), False, 'from optparse import OptionParser\n'), ((1695, 1710), 'functools.wraps', 'wraps', (['function'], {}), '(function)\n', (1700, 1710), False, 'from functools import wraps\n'), ((2702, 2724), 'sys.stdout.write', 'sys.st... |
from tuneit.graph import visualize
from tuneit.tunable import *
from tuneit.variable import *
from tuneit.tunable import Tunable
from tuneit.finalize import finalize
from pytest import raises
def test_finalize():
with raises(TypeError):
finalize(1)
a = variable(range(10), default=2)
assert final... | [
"pytest.raises",
"tuneit.finalize.finalize"
] | [((404, 423), 'tuneit.finalize.finalize', 'finalize', (['(a * a + c)'], {}), '(a * a + c)\n', (412, 423), False, 'from tuneit.finalize import finalize\n'), ((224, 241), 'pytest.raises', 'raises', (['TypeError'], {}), '(TypeError)\n', (230, 241), False, 'from pytest import raises\n'), ((251, 262), 'tuneit.finalize.final... |
# Copyright (c) Microsoft Corporation. All rights reserved.
# Licensed under the MIT License.
# pylint: disable=import-error
# pylint: disable=no-member
# pylint: disable=no-name-in-module
import time
import requests
from opentelemetry import metrics
from opentelemetry.instrumentation.requests import RequestsInstrumen... | [
"opentelemetry.metrics.get_meter_provider",
"time.sleep",
"opentelemetry.instrumentation.requests.RequestsInstrumentor",
"requests.get",
"azure_monitor.AzureMonitorMetricsExporter",
"opentelemetry.sdk.metrics.MeterProvider"
] | [((656, 755), 'azure_monitor.AzureMonitorMetricsExporter', 'AzureMonitorMetricsExporter', ([], {'connection_string': '"""InstrumentationKey=<INSTRUMENTATION KEY HERE>"""'}), "(connection_string=\n 'InstrumentationKey=<INSTRUMENTATION KEY HERE>')\n", (683, 755), False, 'from azure_monitor import AzureMonitorMetricsEx... |
"""
Fabfile template for python3
"""
# -*- coding: utf-8 -*-
from __future__ import print_function
from slackclient import SlackClient
from fabric.api import cd, env, task, run, settings, local
from fabfile_config import *
import traceback
from fabric.contrib.files import exists
LAST_CID_FILE = "last_commit_id.txt"
... | [
"traceback.print_exc",
"fabric.api.cd",
"fabric.api.settings",
"slackclient.SlackClient",
"fabric.api.local",
"fabric.api.run"
] | [((608, 634), 'slackclient.SlackClient', 'SlackClient', (['SLACK_API_KEY'], {}), '(SLACK_API_KEY)\n', (619, 634), False, 'from slackclient import SlackClient\n'), ((1451, 1483), 'fabric.api.cd', 'cd', (["HOST_API[target_host]['dir']"], {}), "(HOST_API[target_host]['dir'])\n", (1453, 1483), False, 'from fabric.api impor... |
import torch
import torch.nn as nn
import math
device = torch.device("cuda" if torch.cuda.is_available() else "cpu")
class MonotonicGruCell(nn.Module):
def __init__(self, input_size, hidden_size, bias=True):
super().__init__()
"""
For each element in the input sequence, each layer compute... | [
"torch.stack",
"math.sqrt",
"torch.cuda.is_available",
"torch.nn.Linear",
"torch.unbind",
"torch.nn.Sigmoid"
] | [((79, 104), 'torch.cuda.is_available', 'torch.cuda.is_available', ([], {}), '()\n', (102, 104), False, 'import torch\n'), ((819, 868), 'torch.nn.Linear', 'nn.Linear', (['input_size', '(3 * hidden_size)'], {'bias': 'bias'}), '(input_size, 3 * hidden_size, bias=bias)\n', (828, 868), True, 'import torch.nn as nn\n'), ((8... |
import numpy as np
from pomegranate import *
import json
################################################################################
# LOGGING
################################################################################
import logging
# Logging format
FORMAT = '%(asctime)s SigMa %(levelname)-10s: %(message)s... | [
"json.dump",
"numpy.load",
"logging.basicConfig",
"numpy.unique",
"numpy.split",
"numpy.max",
"numpy.where",
"numpy.array",
"numpy.random.permutation",
"os.listdir",
"logging.getLogger",
"numpy.random.sample"
] | [((322, 356), 'logging.basicConfig', 'logging.basicConfig', ([], {'format': 'FORMAT'}), '(format=FORMAT)\n', (341, 356), False, 'import logging\n'), ((453, 480), 'logging.getLogger', 'logging.getLogger', (['__name__'], {}), '(__name__)\n', (470, 480), False, 'import logging\n'), ((1318, 1340), 'numpy.load', 'np.load', ... |
import serial
import time
import sys,ast
message='';
c=' '.join(sys.argv[1:])
num=c.replace("[","").replace("]","").split(",")
message=num.pop()
class TextMessage:
# def __init__(self):
# self.recipient = recipient
# self.content = message
def connectPhone(... | [
"serial.Serial",
"time.sleep"
] | [((351, 511), 'serial.Serial', 'serial.Serial', (['"""COM7"""', '(9600)'], {'timeout': '(5)', 'xonxoff': '(False)', 'rtscts': '(False)', 'bytesize': 'serial.EIGHTBITS', 'parity': 'serial.PARITY_NONE', 'stopbits': 'serial.STOPBITS_ONE'}), "('COM7', 9600, timeout=5, xonxoff=False, rtscts=False,\n bytesize=serial.EIGHT... |
from flask import Flask
import baritone
import json
app = Flask(__name__)
@app.route('/')
def hello():
print("Hello from terminal")
return "Hello world"
@app.route('/youtube/<link>')
def youtube(link):
print("ENTERED")
url = 'https://www.youtube.com/watch?v='+link
print(url)
result,status = (baritone.pipel... | [
"flask.Flask",
"baritone.pipeline",
"json.dumps"
] | [((60, 75), 'flask.Flask', 'Flask', (['__name__'], {}), '(__name__)\n', (65, 75), False, 'from flask import Flask\n'), ((306, 339), 'baritone.pipeline', 'baritone.pipeline', (['url', '"""youtube"""'], {}), "(url, 'youtube')\n", (323, 339), False, 'import baritone\n'), ((417, 436), 'json.dumps', 'json.dumps', (['convert... |
#!/usr/bin/env python3
# Copyright (c) 2019 Digital Asset (Switzerland) GmbH and/or its affiliates. All rights reserved.
# SPDX-License-Identifier: Apache-2.0
from subprocess import call, STDOUT
from shutil import copyfile
import sys
import os
import fileinput
ORIGINAL_FIX_VERSION_HS = "gen-source/Version.hs.template... | [
"os.remove",
"os.path.realpath",
"fileinput.FileInput",
"subprocess.call",
"shutil.copyfile"
] | [((758, 824), 'shutil.copyfile', 'copyfile', (["('%s/%s' % (basedir, ORIGINAL_FIX_VERSION_HS))", 'gen_vsn_hs'], {}), "('%s/%s' % (basedir, ORIGINAL_FIX_VERSION_HS), gen_vsn_hs)\n", (766, 824), False, 'from shutil import copyfile\n'), ((948, 1051), 'shutil.copyfile', 'copyfile', (["('%s/%s' % (basedir, ORIGINAL_MOCKSERV... |
# vim: set fileencoding=utf-8 filetype=python :
import logging
log = logging.getLogger(__name__) | [
"logging.getLogger"
] | [((71, 98), 'logging.getLogger', 'logging.getLogger', (['__name__'], {}), '(__name__)\n', (88, 98), False, 'import logging\n')] |
# Generated by the gRPC Python protocol compiler plugin. DO NOT EDIT!
"""Client and server classes corresponding to protobuf-defined services."""
import grpc
from google.protobuf import empty_pb2 as google_dot_protobuf_dot_empty__pb2
from ondewo.survey import survey_pb2 as ondewo_dot_survey_dot_survey__pb2
class Sur... | [
"grpc.method_handlers_generic_handler",
"grpc.unary_unary_rpc_method_handler",
"grpc.experimental.unary_unary"
] | [((10488, 10574), 'grpc.method_handlers_generic_handler', 'grpc.method_handlers_generic_handler', (['"""ondewo.survey.Surveys"""', 'rpc_method_handlers'], {}), "('ondewo.survey.Surveys',\n rpc_method_handlers)\n", (10524, 10574), False, 'import grpc\n'), ((7071, 7310), 'grpc.unary_unary_rpc_method_handler', 'grpc.un... |
from rpython.rlib.unroll import unrolling_iterable
dual_implementation_opcodes = [
'Add_Subtract_Multiply_Divide_Remainder',
'AggFinal',
'AggStep',
'Affinity',
'Cast',
'CollSeq',
'Compare',
'Copy',
'EndCoroutine',
'Function',
'Gosub',
'Goto',
'IdxLE_IdxGT_IdxLT_IdxGE... | [
"rpython.rlib.unroll.unrolling_iterable"
] | [((839, 886), 'rpython.rlib.unroll.unrolling_iterable', 'unrolling_iterable', (['dual_implementation_opcodes'], {}), '(dual_implementation_opcodes)\n', (857, 886), False, 'from rpython.rlib.unroll import unrolling_iterable\n')] |
import os
import datetime
import psycopg2
import numpy as np
import pandas as pd
#import statsmodels.api as sm
from statsmodels.genmod.generalized_linear_model import GLM
from statsmodels.genmod.families import Binomial
from statsmodels.genmod.families.links import probit
DATABASE_URL = os.environ['DATABASE_URL']
... | [
"statsmodels.genmod.generalized_linear_model.GLM",
"statsmodels.genmod.families.links.probit",
"numpy.ones",
"numpy.array",
"statsmodels.genmod.families.Binomial",
"datetime.datetime.now",
"psycopg2.connect"
] | [((327, 376), 'psycopg2.connect', 'psycopg2.connect', (['DATABASE_URL'], {'sslmode': '"""require"""'}), "(DATABASE_URL, sslmode='require')\n", (343, 376), False, 'import psycopg2\n'), ((511, 541), 'numpy.array', 'np.array', (['iris_df.iloc[:, 0:4]'], {}), '(iris_df.iloc[:, 0:4])\n', (519, 541), True, 'import numpy as n... |
import numpy
from sympy import Rational as frac
from sympy import pi, sqrt
from ..helpers import article, fsd, pm, pm_roll, untangle
from ._helpers import E3rScheme
citation = article(
authors=["<NAME>", "<NAME>"],
title="Approximate integration formulas for certain spherically symmetric regions",
journal... | [
"numpy.array",
"sympy.sqrt",
"sympy.Rational"
] | [((553, 563), 'sympy.Rational', 'frac', (['(3)', '(5)'], {}), '(3, 5)\n', (557, 563), True, 'from sympy import Rational as frac\n'), ((572, 583), 'sympy.Rational', 'frac', (['(1)', '(30)'], {}), '(1, 30)\n', (576, 583), True, 'from sympy import Rational as frac\n'), ((824, 832), 'sympy.sqrt', 'sqrt', (['(30)'], {}), '(... |
# V0
# V1
# https://blog.csdn.net/coder_orz/article/details/51317748
# IDEA : "unly number" : a number is an ugly number
# if all its prime factors are within [2, 3, 5].
# e.g. 6, 8 are ugly number ; while 14 is not
# please note that 1 is ugly number as well
# IDEA : ITERATION
class Solution(object):
def ... | [
"heapq.merge",
"heapq.heappush",
"heapq.heappop"
] | [((1545, 1568), 'heapq.heappush', 'heapq.heappush', (['heap', '(1)'], {}), '(heap, 1)\n', (1559, 1568), False, 'import heapq\n'), ((2549, 2572), 'heapq.merge', 'heapq.merge', (['q2', 'q3', 'q5'], {}), '(q2, q3, q5)\n', (2560, 2572), False, 'import heapq\n'), ((1622, 1641), 'heapq.heappop', 'heapq.heappop', (['heap'], {... |
import boto3
from boto3.dynamodb.types import TypeDeserializer, TypeSerializer
import json
import logging
DYNAMODB_TABLE_NAME = "quizzes_questions"
def setup_logging():
""" Basic logging setup """
logging.basicConfig(format='%(asctime)s - %(name)s - %(levelname)s - %(message)s',
level=logging.INFO)
... | [
"boto3.dynamodb.types.TypeSerializer",
"logging.basicConfig",
"boto3.client"
] | [((208, 315), 'logging.basicConfig', 'logging.basicConfig', ([], {'format': '"""%(asctime)s - %(name)s - %(levelname)s - %(message)s"""', 'level': 'logging.INFO'}), "(format=\n '%(asctime)s - %(name)s - %(levelname)s - %(message)s', level=logging.INFO)\n", (227, 315), False, 'import logging\n'), ((1554, 1570), 'boto... |
import pkgutil
import xml.etree.ElementTree
import docutils.core
def load_pairs():
# Load pairs of "example ID, rules code" for the test suite.
rst_code = _load_rst()
xml_code = docutils.core.publish_string(rst_code, writer_name='xml')
tree = xml.etree.ElementTree.fromstring(xml_code)
parsed = []... | [
"pkgutil.get_data"
] | [((920, 960), 'pkgutil.get_data', 'pkgutil.get_data', (['"""turq"""', '"""examples.rst"""'], {}), "('turq', 'examples.rst')\n", (936, 960), False, 'import pkgutil\n')] |
# Generated by Django 3.2.7 on 2021-09-11 13:54
from django.conf import settings
from django.db import migrations, models
import django.db.models.deletion
class Migration(migrations.Migration):
initial = True
dependencies = [
migrations.swappable_dependency(settings.AUTH_USER_MODEL),
]
ope... | [
"django.db.models.TextField",
"django.db.migrations.swappable_dependency",
"django.db.models.BigAutoField",
"django.db.models.CharField",
"django.db.models.ForeignKey",
"django.db.models.IntegerField",
"django.db.models.DateTimeField"
] | [((247, 304), 'django.db.migrations.swappable_dependency', 'migrations.swappable_dependency', (['settings.AUTH_USER_MODEL'], {}), '(settings.AUTH_USER_MODEL)\n', (278, 304), False, 'from django.db import migrations, models\n'), ((435, 531), 'django.db.models.BigAutoField', 'models.BigAutoField', ([], {'auto_created': '... |
# 先确认在VSCode的Settings中,勾选“Terminal:Excute In File Dir”
# 在当前文件夹下将hello_world.txt文件复制为hello_world_bak.txt
src = r'hello_world.txt'
dst = r'hello_world_bak.txt'
import shutil
shutil.copyfile(src, dst) | [
"shutil.copyfile"
] | [((175, 200), 'shutil.copyfile', 'shutil.copyfile', (['src', 'dst'], {}), '(src, dst)\n', (190, 200), False, 'import shutil\n')] |
class FeatureImportance(object):
def __init__(self, md, test_x, test_z):
self._skater_model, self._skater_interpreter = _create_skater_stuff(md, test_x, test_z)
def save_plot_feature_importance(self, file_path):
fig, ax = self._skater_interpreter.feature_importance.plot_feature_importance(
... | [
"skater.core.explanations.Interpretation",
"hassbrain_algorithm.benchmark.interpretation._boolean2str",
"matplotlib.pyplot.close",
"hassbrain_algorithm.benchmark.interpretation.ModelWrapper",
"matplotlib.pyplot.tight_layout",
"skater.model.InMemoryModel"
] | [((1279, 1296), 'hassbrain_algorithm.benchmark.interpretation.ModelWrapper', 'ModelWrapper', (['mdl'], {}), '(mdl)\n', (1291, 1296), False, 'from hassbrain_algorithm.benchmark.interpretation import ModelWrapper\n'), ((1514, 1534), 'hassbrain_algorithm.benchmark.interpretation._boolean2str', '_boolean2str', (['test_x'],... |
import pygame
import random
from pygame.math import Vector2
#from .config import xSize, ySize, cell_size, cell_number
from .loc_conf import xSize, ySize, cell_number, cell_size
class NonEatable():
def __init__(self, screen, ip1,ip2,ip3,ip4):
# Lade Textur
self._load_texture(ip1,ip2,ip3,i... | [
"pygame.image.load",
"pygame.math.Vector2",
"random.randint"
] | [((393, 427), 'random.randint', 'random.randint', (['(0)', '(cell_number - 2)'], {}), '(0, cell_number - 2)\n', (407, 427), False, 'import random\n'), ((443, 477), 'random.randint', 'random.randint', (['(0)', '(cell_number - 2)'], {}), '(0, cell_number - 2)\n', (457, 477), False, 'import random\n'), ((2239, 2273), 'ran... |
import pyautogui
from time import sleep
from random import choice
sleep(3)
names = open("names.txt","r").readlines()
names = [i[:-1] for i in names]
passwords = open("pass.txt",'r').readlines()
passwords = [i[:-1] for i in passwords if passwords.index(i) % 2 == 0]
for i in range(100):
print("hehe :) ")
pyauto... | [
"pyautogui.write",
"pyautogui.press",
"random.choice",
"time.sleep",
"pyautogui.hold",
"pyautogui.click"
] | [((66, 74), 'time.sleep', 'sleep', (['(3)'], {}), '(3)\n', (71, 74), False, 'from time import sleep\n'), ((314, 331), 'pyautogui.click', 'pyautogui.click', ([], {}), '()\n', (329, 331), False, 'import pyautogui\n'), ((379, 396), 'random.choice', 'choice', (['passwords'], {}), '(passwords)\n', (385, 396), False, 'from r... |
# Copyright (c) 2021-2022, NVIDIA CORPORATION. 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 ... | [
"nvflare.private.fed.utils.messageproto.proto_to_message",
"grpc.secure_channel",
"nvflare.private.fed.protos.admin_pb2.Reply",
"nvflare.private.fed.utils.messageproto.message_to_proto",
"nvflare.private.fed.protos.admin_pb2.Client",
"grpc.insecure_channel",
"threading.Lock",
"nvflare.private.fed.prot... | [((1074, 1090), 'threading.Lock', 'threading.Lock', ([], {}), '()\n', (1088, 1090), False, 'import threading\n'), ((5366, 5493), 'grpc.ssl_channel_credentials', 'grpc.ssl_channel_credentials', ([], {'certificate_chain': 'certificate_chain', 'private_key': 'private_key', 'root_certificates': 'trusted_certs'}), '(certifi... |
#!/usr/bin/env python
# -*- coding: utf-8 -*-
#
# Copyright (c) 2018 Intel Corporation
#
# 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
#
# Un... | [
"os.getpgid",
"subprocess.Popen",
"argparse.ArgumentParser",
"os.path.basename",
"os.path.isdir",
"os.path.realpath",
"os.path.dirname",
"os.environ.get",
"glob.glob",
"os.path.join",
"sys.exit"
] | [((1500, 1604), 'argparse.ArgumentParser', 'ArgumentParser', ([], {'parents': '[self._common_arg_parser]', 'description': '"""Parse args for benchmark interface"""'}), "(parents=[self._common_arg_parser], description=\n 'Parse args for benchmark interface')\n", (1514, 1604), False, 'from argparse import ArgumentPars... |
import unittest
from apps.api.segmenter.road_segmenter import geometry_to_list
from apps.data.road_segmenting.road_fetcher import vegnet_to_geojson
from apps.data.road_segmenting.road_filter import filter_road
from vapi.constants import MAX_SEGMENT_LENGTH, MIN_COORDINATES_LENGTH
from api.segmenter.calculate_distance ... | [
"unittest.main",
"api.segmenter.calculate_distance.calculate_road_length_simple",
"apps.api.segmenter.road_segmenter.geometry_to_list",
"apps.data.road_segmenting.road_fetcher.vegnet_to_geojson",
"apps.data.road_segmenting.road_filter.filter_road",
"api.segmenter.road_segmenter.split_segment",
"api.segm... | [((460, 477), 'apps.data.road_segmenting.road_filter.filter_road', 'filter_road', (['road'], {}), '(road)\n', (471, 477), False, 'from apps.data.road_segmenting.road_filter import filter_road\n'), ((501, 535), 'apps.api.segmenter.road_segmenter.geometry_to_list', 'geometry_to_list', (["road['the_geom']"], {}), "(road['... |
import numpy as np
import pickle
import os
from pathlib import Path
from metrics.class_imbalance import get_classes, class_proportion
from metrics.phi_div import average_dkl
from metrics.wasserstein import wasserstein_2
def compute_metrics(ds,
split,
inv_temp,
... | [
"os.getcwd",
"numpy.corrcoef",
"metrics.wasserstein.wasserstein_2",
"numpy.array",
"metrics.phi_div.average_dkl",
"numpy.concatenate"
] | [((1107, 1153), 'metrics.phi_div.average_dkl', 'average_dkl', (['party_datasets', 'reference_dataset'], {}), '(party_datasets, reference_dataset)\n', (1118, 1153), False, 'from metrics.phi_div import average_dkl\n'), ((1243, 1302), 'metrics.phi_div.average_dkl', 'average_dkl', (['party_datasets_with_rewards', 'referenc... |
# Generated by Django 2.0 on 2020-02-07 12:55
from django.db import migrations, models
import django.db.models.deletion
class Migration(migrations.Migration):
dependencies = [
('addresses', '0001_initial'),
('orders', '0002_auto_20200204_1253'),
]
operations = [
migrations.AddFi... | [
"django.db.models.ForeignKey"
] | [((411, 525), 'django.db.models.ForeignKey', 'models.ForeignKey', ([], {'blank': '(True)', 'null': '(True)', 'on_delete': 'django.db.models.deletion.CASCADE', 'to': '"""addresses.Address"""'}), "(blank=True, null=True, on_delete=django.db.models.\n deletion.CASCADE, to='addresses.Address')\n", (428, 525), False, 'fr... |
from helper import unittest, PillowTestCase, hopper, py3
import os
import io
from PIL import Image, TiffImagePlugin
class LibTiffTestCase(PillowTestCase):
def setUp(self):
codecs = dir(Image.core)
if "libtiff_encoder" not in codecs or "libtiff_decoder" not in codecs:
self.skipTest(... | [
"PIL.ImageFilter.GaussianBlur",
"io.BytesIO",
"helper.unittest.main",
"PIL.Image.open",
"os.close",
"os.fstat",
"helper.hopper"
] | [((12614, 12629), 'helper.unittest.main', 'unittest.main', ([], {}), '()\n', (12627, 12629), False, 'from helper import unittest, PillowTestCase, hopper, py3\n'), ((1050, 1066), 'PIL.Image.open', 'Image.open', (['file'], {}), '(file)\n', (1060, 1066), False, 'from PIL import Image, TiffImagePlugin\n'), ((1231, 1247), '... |
from stdiomask import getpass
from cowsay import daemon, ghostbusters, kitty
from check_validation_ID_Post import check_validation
from driver_chrome import *
from DataScrapting import *
tracking_ID = getpass("Enter Your Post Id(24 digit): ")
check_validation(tracking_ID)
URL = f"https://tracking.post.ir/?id={tracki... | [
"cowsay.ghostbusters",
"stdiomask.getpass",
"check_validation_ID_Post.check_validation",
"cowsay.daemon"
] | [((202, 243), 'stdiomask.getpass', 'getpass', (['"""Enter Your Post Id(24 digit): """'], {}), "('Enter Your Post Id(24 digit): ')\n", (209, 243), False, 'from stdiomask import getpass\n'), ((244, 273), 'check_validation_ID_Post.check_validation', 'check_validation', (['tracking_ID'], {}), '(tracking_ID)\n', (260, 273),... |
from time import sleep
from pitop import TiltRollHeadController
# Create a head controller object
head = TiltRollHeadController()
# Initialize the servo angles
head.roll.target_angle = 0
head.tilt.target_angle = 50
sleep(1)
# Nod 6 times at max speed 5 degrees either side of current angle. Blocks program execution... | [
"pitop.TiltRollHeadController",
"time.sleep"
] | [((107, 131), 'pitop.TiltRollHeadController', 'TiltRollHeadController', ([], {}), '()\n', (129, 131), False, 'from pitop import TiltRollHeadController\n'), ((218, 226), 'time.sleep', 'sleep', (['(1)'], {}), '(1)\n', (223, 226), False, 'from time import sleep\n')] |
import sys
sys.path.insert(0, '../models')
from get_data import GetData
# from python.ultilities.get_data import GetData
import unittest
import csv
class TestGetData(unittest.TestCase):
def test_getAllFeatures1(self):
getData = GetData()
features = getData.getAllFeatures()
self.assertIsNotN... | [
"unittest.main",
"sys.path.insert",
"get_data.GetData"
] | [((11, 42), 'sys.path.insert', 'sys.path.insert', (['(0)', '"""../models"""'], {}), "(0, '../models')\n", (26, 42), False, 'import sys\n'), ((779, 794), 'unittest.main', 'unittest.main', ([], {}), '()\n', (792, 794), False, 'import unittest\n'), ((241, 250), 'get_data.GetData', 'GetData', ([], {}), '()\n', (248, 250), ... |
# pylint: disable=missing-docstring
from __future__ import print_function
from mock import patch
from gitflow_easyrelease import cli
@patch('gitflow_easyrelease.cli_file.ColorOutput')
@patch('gitflow_easyrelease.cli_file.Subcommand')
@patch('gitflow_easyrelease.cli_file.Application')
def test_execution(mock_app, ... | [
"mock.patch",
"gitflow_easyrelease.cli"
] | [((140, 189), 'mock.patch', 'patch', (['"""gitflow_easyrelease.cli_file.ColorOutput"""'], {}), "('gitflow_easyrelease.cli_file.ColorOutput')\n", (145, 189), False, 'from mock import patch\n'), ((191, 239), 'mock.patch', 'patch', (['"""gitflow_easyrelease.cli_file.Subcommand"""'], {}), "('gitflow_easyrelease.cli_file.Su... |
import os
from flask import Flask, render_template, request, json
app = Flask(__name__)
@app.route('/')
def index():
return render_template('index.html')
@app.route('/save', methods=['POST'])
def save():
with open('data.json', 'w+') as f:
f.write(json.dumps(request.get_json()))
return ''
@app.route('/load')
... | [
"flask.Flask",
"flask.json.jsonify",
"os.path.isfile",
"flask.render_template",
"flask.request.get_json"
] | [((74, 89), 'flask.Flask', 'Flask', (['__name__'], {}), '(__name__)\n', (79, 89), False, 'from flask import Flask, render_template, request, json\n'), ((128, 157), 'flask.render_template', 'render_template', (['"""index.html"""'], {}), "('index.html')\n", (143, 157), False, 'from flask import Flask, render_template, re... |
import pytest
from align.schema.types import BaseModel, Optional, List, Dict
from align.schema.visitor import Visitor, Transformer, cache
@pytest.fixture
def dummy():
class DummyModel(BaseModel):
arg1: str
arg2: Optional[str]
arg3: List[str]
arg4: List[Optional[str]]
arg5: ... | [
"align.schema.visitor.Visitor",
"align.schema.visitor.Transformer"
] | [((961, 970), 'align.schema.visitor.Visitor', 'Visitor', ([], {}), '()\n', (968, 970), False, 'from align.schema.visitor import Visitor, Transformer, cache\n'), ((1801, 1814), 'align.schema.visitor.Transformer', 'Transformer', ([], {}), '()\n', (1812, 1814), False, 'from align.schema.visitor import Visitor, Transformer... |
# coding: utf-8
import sys
import logging
import settings
logFormatter = logging.Formatter('%(asctime)s [%(levelname)-5.5s] %(message)s')
logger = logging.getLogger()
fileHandler = logging.FileHandler('{0}'.format(settings.LOG_FILE_PATH))
fileHandler.setFormatter(logFormatter)
logger.addHandler(fileHandler)
conso... | [
"logging.Formatter",
"logging.StreamHandler",
"logging.getLogger"
] | [((76, 141), 'logging.Formatter', 'logging.Formatter', (['"""%(asctime)s [%(levelname)-5.5s] %(message)s"""'], {}), "('%(asctime)s [%(levelname)-5.5s] %(message)s')\n", (93, 141), False, 'import logging\n'), ((151, 170), 'logging.getLogger', 'logging.getLogger', ([], {}), '()\n', (168, 170), False, 'import logging\n'... |
# -*- coding: utf-8 -*-
# Generated by Django 1.10.1 on 2017-01-31 11:14
from __future__ import unicode_literals
from django.db import migrations, models
class Migration(migrations.Migration):
dependencies = [
('ciudadano', '0005_auto_20170127_1841'),
]
operations = [
migrations.RemoveFi... | [
"django.db.migrations.RemoveField",
"django.db.models.CharField"
] | [((301, 360), 'django.db.migrations.RemoveField', 'migrations.RemoveField', ([], {'model_name': '"""ciudadano"""', 'name': '"""uuid"""'}), "(model_name='ciudadano', name='uuid')\n", (323, 360), False, 'from django.db import migrations, models\n'), ((519, 626), 'django.db.models.CharField', 'models.CharField', ([], {'bl... |
# -*- coding:utf-8 -*-
import json
from datetime import timedelta
from markdown2 import markdown
from django.contrib import messages
from django.core.urlresolvers import reverse
from django.utils import timezone
from django.db.models import Max
from django.utils.timezone import now
from django.http import HttpRespons... | [
"django.core.urlresolvers.reverse",
"premises.models.Contention.objects.none",
"premises.signals.supported_a_premise.send",
"premises.models.Premise.objects.all",
"premises.signals.added_premise_for_contention.send",
"django.contrib.messages.info",
"premises.models.Premise.objects.exclude",
"django.db... | [((4685, 4726), 'blog.models.Post.objects.filter', 'Post.objects.filter', ([], {'is_announcement': '(True)'}), '(is_announcement=True)\n', (4704, 4726), False, 'from blog.models import Post\n'), ((5685, 5714), 'premises.models.Contention.objects.featured', 'Contention.objects.featured', ([], {}), '()\n', (5712, 5714), ... |
""" Implements the commands for viewing and manipulating the training manifest """
import json
import time
import os
from blaze.action import Policy
from blaze.logger import logger as log
from blaze.mahimahi.server import start_server
from . import command
@command.argument("replay_dir", help="The directory contain... | [
"os.path.abspath",
"json.load",
"blaze.mahimahi.server.start_server",
"blaze.logger.logger.debug",
"time.sleep",
"blaze.action.Policy.from_dict"
] | [((1183, 1214), 'os.path.abspath', 'os.path.abspath', (['args.cert_path'], {}), '(args.cert_path)\n', (1198, 1214), False, 'import os\n'), ((1258, 1288), 'os.path.abspath', 'os.path.abspath', (['args.key_path'], {}), '(args.key_path)\n', (1273, 1288), False, 'import os\n'), ((1345, 1397), 'blaze.logger.logger.debug', '... |
import os
import aiofiles
from pydub import AudioSegment
from amocrm_asterisk_ng.domain import File
from amocrm_asterisk_ng.domain import Filetype
from ..core import IFileConverter
from ...CallRecordsConfig import CallRecordsConfig
__all__ = [
"PydubFileConverter",
]
class PydubFileConverter(IFileConverter):... | [
"os.remove",
"pydub.AudioSegment.from_mp3",
"os.makedirs",
"aiofiles.open",
"os.path.exists",
"pydub.AudioSegment.from_wav",
"pydub.AudioSegment.from_WAVE",
"amocrm_asterisk_ng.domain.File",
"os.path.join"
] | [((1139, 1191), 'os.path.join', 'os.path.join', (['self.__config.tmp_directory', 'file.name'], {}), '(self.__config.tmp_directory, file.name)\n', (1151, 1191), False, 'import os\n'), ((1676, 1743), 'os.path.join', 'os.path.join', (['self.__config.tmp_directory', "('converted_' + file.name)"], {}), "(self.__config.tmp_d... |
import unittest
from typing import List
import numpy as np
from py_headless_daw.processing.stream.stream_gain import StreamGain
from py_headless_daw.schema.dto.time_interval import TimeInterval
from py_headless_daw.schema.events.event import Event
from py_headless_daw.schema.events.parameter_value_event import Parame... | [
"py_headless_daw.schema.dto.time_interval.TimeInterval",
"py_headless_daw.schema.events.parameter_value_event.ParameterValueEvent",
"numpy.float32",
"numpy.zeros",
"numpy.ones"
] | [((495, 509), 'py_headless_daw.schema.dto.time_interval.TimeInterval', 'TimeInterval', ([], {}), '()\n', (507, 509), False, 'from py_headless_daw.schema.dto.time_interval import TimeInterval\n'), ((606, 645), 'numpy.ones', 'np.ones', ([], {'shape': '(100,)', 'dtype': 'np.float32'}), '(shape=(100,), dtype=np.float32)\n'... |
import six
import os
import yaml
import logging
import logging.config
from appdirs import AppDirs
from pkg_resources import resource_filename
def setup_logging(log_level):
log_config_file = os.path.join(resource_filename('ansibleroler', 'static'), 'config', 'logging.yml')
level = logging.getLevelName(log_leve... | [
"appdirs.AppDirs",
"os.getcwd",
"pkg_resources.resource_filename",
"six.text_type",
"logging.getLevelName",
"logging.config.dictConfig",
"os.path.expanduser",
"logging.getLogger"
] | [((291, 322), 'logging.getLevelName', 'logging.getLevelName', (['log_level'], {}), '(log_level)\n', (311, 322), False, 'import logging\n'), ((416, 453), 'logging.config.dictConfig', 'logging.config.dictConfig', (['log_config'], {}), '(log_config)\n', (441, 453), False, 'import logging\n'), ((584, 615), 'logging.getLeve... |
import os
os.system('apt install rustc')
os.environ['PATH'] += ':/root/.cargo/bin'
os.environ['USER'] = 'user'
| [
"os.system"
] | [((11, 41), 'os.system', 'os.system', (['"""apt install rustc"""'], {}), "('apt install rustc')\n", (20, 41), False, 'import os\n')] |
# User provided config file
import config
import requests
import attrdict
import logging
def attrdict_or_list(thing):
if type(thing) == dict:
return attrdict.AttrMap(thing)
elif type(thing) == list:
return thing
else:
assert False, "DON'T PANIC. Something that wasn't a list or dic... | [
"requests.put",
"requests.delete",
"requests.get",
"attrdict.AttrMap"
] | [((164, 187), 'attrdict.AttrMap', 'attrdict.AttrMap', (['thing'], {}), '(thing)\n', (180, 187), False, 'import attrdict\n'), ((2237, 2348), 'requests.get', 'requests.get', (['(self._habitica_api + endpoint)'], {'headers': "{'x-api-user': self._uuid, 'x-api-key': self._apikey}"}), "(self._habitica_api + endpoint, header... |
"""
part_finder.py
Look through two files and search for an internal part number that looks like `match_pattern`
"""
#!/usr/bin/env python3
import sys, regex, click
#first arg is a digikey csv cart
#second is a newline deliminated list of eoi partnumbers
match_pattern = "\w{3}-\w{4}-\w{2}"
@click.argument("--first",... | [
"regex.compile",
"click.argument"
] | [((295, 445), 'click.argument', 'click.argument', (['"""--first"""', '"""-f"""'], {'type': 'str', 'required': '(True)', 'help': '"""Design BOM to compare to. Should have the part number somewhere in the line"""'}), "('--first', '-f', type=str, required=True, help=\n 'Design BOM to compare to. Should have the part nu... |
import re
from typing import Iterator
from xps_convert.read.errors import ParseError
from xps_convert.read.xmp import Xmp
FIELD_RE = re.compile(r"([\w\s]+):\s(.*)")
def parse_xmp(filename: str, lines: Iterator[str]) -> Xmp:
xmp = Xmp()
# First line is always a comment, skip it
next(lines)
# Match ea... | [
"xps_convert.read.xmp.Xmp",
"xps_convert.read.errors.ParseError",
"re.compile"
] | [((135, 168), 're.compile', 're.compile', (['"""([\\\\w\\\\s]+):\\\\s(.*)"""'], {}), "('([\\\\w\\\\s]+):\\\\s(.*)')\n", (145, 168), False, 'import re\n'), ((238, 243), 'xps_convert.read.xmp.Xmp', 'Xmp', ([], {}), '()\n', (241, 243), False, 'from xps_convert.read.xmp import Xmp\n'), ((570, 617), 'xps_convert.read.errors... |
# Copyright 2015 Nicta
#
# 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, softwa... | [
"os.walk",
"os.path.join",
"setuptools.setup"
] | [((825, 1307), 'setuptools.setup', 'setup', ([], {'name': 'package_name', 'version': '"""0.1.0"""', 'description': '"""Access dataset data"""', 'author': '"""Sirca Ltd"""', 'author_email': '"""<EMAIL>"""', 'url': '"""http://github.com/sirca/bdkd"""', 'package_dir': "{'': 'lib'}", 'packages': "['bdkd.laser', 'bdkd.laser... |
from datetime import datetime
from ... import db
class Story(db.Model):
""" This model holds information about Story """
__tablename__ = 'story'
id = db.Column(db.Integer, primary_key=True)
title = db.Column(db.Text, nullable=False)
content = db.Column(db.Text, nullable=False)
featured_img_u... | [
"datetime.datetime.now"
] | [((578, 592), 'datetime.datetime.now', 'datetime.now', ([], {}), '()\n', (590, 592), False, 'from datetime import datetime\n')] |
# -*- coding: utf-8 -*-
from __future__ import unicode_literals
from django.conf import settings
from django.db import migrations, models
def setup_site(apps, schema_editor):
"""Populate the sites model"""
Site = apps.get_model('sites', 'Site')
Site.objects.all().delete()
# Register SITE_ID = 1
t... | [
"django.db.migrations.RunPython"
] | [((590, 622), 'django.db.migrations.RunPython', 'migrations.RunPython', (['setup_site'], {}), '(setup_site)\n', (610, 622), False, 'from django.db import migrations, models\n')] |
import matplotlib.pyplot as plt
# import pydicom
import os
from pydicom.filereader import dcmread, read_dicomdir
from glob import glob
import cv2
import numpy as np
cv2.destroyAllWindows()
# window prop
screensize = ((-1440,0),(0,900))
screenwidth = screensize[0][1]-screensize[0][0]
screenheight = screensize[1][1]-scr... | [
"numpy.stack",
"cv2.Canny",
"pydicom.filereader.dcmread",
"cv2.arcLength",
"cv2.threshold",
"cv2.imshow",
"cv2.resizeWindow",
"cv2.namedWindow",
"numpy.array",
"cv2.convertScaleAbs",
"cv2.normalize",
"cv2.moveWindow",
"cv2.destroyAllWindows",
"os.path.join",
"cv2.findContours"
] | [((166, 189), 'cv2.destroyAllWindows', 'cv2.destroyAllWindows', ([], {}), '()\n', (187, 189), False, 'import cv2\n'), ((838, 916), 'cv2.normalize', 'cv2.normalize', (['image'], {'dst': 'None', 'alpha': '(0)', 'beta': '(65536)', 'norm_type': 'cv2.NORM_MINMAX'}), '(image, dst=None, alpha=0, beta=65536, norm_type=cv2.NORM... |
import socket
import threading
import multiprocessing
import os
def worker(sock):
while True:
conn, addr = sock.accept()
print("PID:", os.getpid())
thread = threading.Thread(target=process_request, args=(conn, addr))
thread.start()
def process_request(conn, addr):
print("add... | [
"threading.Thread",
"multiprocessing.Process",
"socket.socket",
"os.getpid"
] | [((188, 247), 'threading.Thread', 'threading.Thread', ([], {'target': 'process_request', 'args': '(conn, addr)'}), '(target=process_request, args=(conn, addr))\n', (204, 247), False, 'import threading\n'), ((528, 577), 'socket.socket', 'socket.socket', (['socket.AF_INET', 'socket.SOCK_STREAM'], {}), '(socket.AF_INET, s... |
import glob
import matplotlib.pyplot as plt
import matplotlib.cm as cm
import numpy as np
import xarray as xr
from mpl_toolkits.basemap import Basemap
import gc
import matplotlib
matplotlib.rc('font', size=12)
data_path = 'processed_netcdf'
multibeam_files = glob.glob(data_path + '/*.nc')
multibeam_files.sort()
lon... | [
"matplotlib.pyplot.pcolor",
"matplotlib.rc",
"matplotlib.pyplot.close",
"xarray.open_dataset",
"numpy.isnan",
"matplotlib.pyplot.colorbar",
"gc.collect",
"matplotlib.pyplot.figure",
"numpy.arange",
"numpy.array",
"glob.glob",
"mpl_toolkits.basemap.Basemap",
"matplotlib.pyplot.savefig"
] | [((180, 210), 'matplotlib.rc', 'matplotlib.rc', (['"""font"""'], {'size': '(12)'}), "('font', size=12)\n", (193, 210), False, 'import matplotlib\n'), ((262, 292), 'glob.glob', 'glob.glob', (["(data_path + '/*.nc')"], {}), "(data_path + '/*.nc')\n", (271, 292), False, 'import glob\n'), ((381, 413), 'numpy.arange', 'np.a... |
#
# Copyright (c) Microsoft Corporation.
# Licensed under the MIT License.
#
import math
import numpy as np
def quadratic(**kwargs) -> float:
return sum(x_i ** 2 for _, x_i in kwargs.items())
def ackley(x_1=None, x_2=None, a=20, b=0.2, c=2*math.pi):
d = 2
return -a * np.exp(-b * np.sqrt((x_1... | [
"numpy.arctan2",
"numpy.exp",
"numpy.cos",
"numpy.sqrt"
] | [((526, 554), 'numpy.sqrt', 'np.sqrt', (['(x_1 ** 2 + x_2 ** 2)'], {}), '(x_1 ** 2 + x_2 ** 2)\n', (533, 554), True, 'import numpy as np\n'), ((390, 399), 'numpy.exp', 'np.exp', (['(1)'], {}), '(1)\n', (396, 399), True, 'import numpy as np\n'), ((593, 613), 'numpy.arctan2', 'np.arctan2', (['x_1', 'x_2'], {}), '(x_1, x_... |
from flask import Flask, url_for, render_template, request, redirect
from flask_sqlalchemy import SQLAlchemy
from datetime import datetime
from werkzeug.utils import secure_filename
from werkzeug.serving import run_simple
from id_class_locator import id_class_detector
import os
import time
from cv2 import cv2
app=Flas... | [
"os.path.join",
"os.path.realpath",
"flask.Flask",
"werkzeug.utils.secure_filename",
"werkzeug.serving.run_simple",
"flask.render_template",
"cv2.cv2.dnn.readNetFromTensorflow",
"id_class_locator.id_class_detector"
] | [((316, 331), 'flask.Flask', 'Flask', (['__name__'], {}), '(__name__)\n', (321, 331), False, 'from flask import Flask, url_for, render_template, request, redirect\n'), ((671, 779), 'cv2.cv2.dnn.readNetFromTensorflow', 'cv2.dnn.readNetFromTensorflow', (["(pathToModel + '/frozen_inference_graph.pb')", "(pathToModel + '/f... |
#
# Licensed to the Apache Software Foundation (ASF) under one
# or more contributor license agreements. See the NOTICE file
# distributed with this work for additional information
# regarding copyright ownership. The ASF licenses this file
# to you under the Apache License, Version 2.0 (the
# "License"); you may not... | [
"configparser.ConfigParser",
"sys.exit"
] | [((1166, 1180), 'configparser.ConfigParser', 'ConfigParser', ([], {}), '()\n', (1178, 1180), False, 'from configparser import ConfigParser\n'), ((1519, 1541), 'sys.exit', 'sys.exit', (['os.EX_CONFIG'], {}), '(os.EX_CONFIG)\n', (1527, 1541), False, 'import sys\n'), ((2523, 2545), 'sys.exit', 'sys.exit', (['os.EX_CONFIG'... |
import frappe
import datetime
@frappe.whitelist()
def get_batch_nos(doctype, txt, searchfield, start, page_len, filters):
return frappe.db.sql("""select batch_id, expiry_date
from `tabBatch`
where
item = {item_code} and disabled = 0 and (expiry_date is null or expiry_date > '{cur_date}')"""
.format(item_code... | [
"frappe.whitelist",
"datetime.datetime.today"
] | [((32, 50), 'frappe.whitelist', 'frappe.whitelist', ([], {}), '()\n', (48, 50), False, 'import frappe\n'), ((373, 398), 'datetime.datetime.today', 'datetime.datetime.today', ([], {}), '()\n', (396, 398), False, 'import datetime\n')] |
#!/usr/bin/python
# ex:set fileencoding=utf-8:
from __future__ import unicode_literals
from django import forms
from django.utils.translation import ugettext_lazy as _
from djangobmf.dashboards import Accounting
from djangobmf.sites import Module
from djangobmf.sites import ViewMixin
from djangobmf.sites import regi... | [
"django.utils.translation.ugettext_lazy",
"djangobmf.sites.register"
] | [((739, 769), 'djangobmf.sites.register', 'register', ([], {'dashboard': 'Accounting'}), '(dashboard=Accounting)\n', (747, 769), False, 'from djangobmf.sites import register\n'), ((841, 871), 'djangobmf.sites.register', 'register', ([], {'dashboard': 'Accounting'}), '(dashboard=Accounting)\n', (849, 871), False, 'from ... |
# coding: utf-8
'''Centralized logger factory.'''
import logging
from .config import config
# The level options supported in configuration.
LEVEL_OPTIONS = list((
'notset', 'debug', 'info', 'warning', 'error', 'critical'
))
def _setup_logger_supply():
'''Create and return a logger generator.'''
configured_level =... | [
"logging.getLogger",
"logging.basicConfig"
] | [((384, 483), 'logging.basicConfig', 'logging.basicConfig', ([], {'level': '(20)', 'format': '"""%(asctime)-10s %(name)-30s %(levelname)-8s %(message)s"""'}), "(level=20, format=\n '%(asctime)-10s %(name)-30s %(levelname)-8s %(message)s')\n", (403, 483), False, 'import logging\n'), ((628, 651), 'logging.getLogger', ... |
import sys
import numpy as np
import quaternionic
import pytest
def test_self_return():
def f1(a, b, c):
d = np.asarray(a).copy()
assert isinstance(a, np.ndarray) and isinstance(a, quaternionic.array)
assert isinstance(b, np.ndarray) and isinstance(b, quaternionic.array)
assert isi... | [
"quaternionic.utilities.ndarray_args",
"numpy.random.seed",
"sys.implementation.name.lower",
"numpy.random.rand",
"numba.complex128",
"numpy.asarray",
"numpy.finfo",
"quaternionic.array",
"quaternionic.array.random",
"quaternionic.utilities.pyguvectorize",
"quaternionic.utilities.type_self_retur... | [((489, 526), 'quaternionic.array.random', 'quaternionic.array.random', (['(17, 3, 4)'], {}), '((17, 3, 4))\n', (514, 526), False, 'import quaternionic\n'), ((535, 572), 'quaternionic.array.random', 'quaternionic.array.random', (['(13, 3, 4)'], {}), '((13, 3, 4))\n', (560, 572), False, 'import quaternionic\n'), ((581, ... |
from unittest import TestCase
import numpy as np
import os
from xaitk_saliency.impls.gen_detector_prop_sal.drise_scoring import DetectorRISE
from xaitk_saliency import GenerateDetectorProposalSaliency
from smqtk_core.configuration import configuration_test_helper
from tests import DATA_DIR, EXPECTED_MASKS_4x6
clas... | [
"xaitk_saliency.impls.gen_detector_prop_sal.drise_scoring.DetectorRISE",
"numpy.random.seed",
"numpy.allclose",
"smqtk_core.configuration.configuration_test_helper",
"numpy.random.randint",
"numpy.array",
"numpy.random.rand",
"os.path.join"
] | [((472, 486), 'xaitk_saliency.impls.gen_detector_prop_sal.drise_scoring.DetectorRISE', 'DetectorRISE', ([], {}), '()\n', (484, 486), False, 'from xaitk_saliency.impls.gen_detector_prop_sal.drise_scoring import DetectorRISE\n'), ((691, 705), 'xaitk_saliency.impls.gen_detector_prop_sal.drise_scoring.DetectorRISE', 'Detec... |
#!/usr/bin/env python3
# -*- coding: utf-8 -*-
import sys
import re
import os
import glob
import imageio
import argparse
import subprocess
import numpy as np
from tqdm import tqdm
from PIL import Image
from pygifsicle import optimize
from obj.arg_formatter import arg_metav_formatter
def sorted_alphanumeric(data):
... | [
"tqdm.tqdm",
"re.split",
"argparse.ArgumentParser",
"os.makedirs",
"os.path.isdir",
"pygifsicle.optimize",
"PIL.Image.open",
"subprocess.call",
"glob.glob",
"sys.exit",
"re.sub",
"imageio.mimsave"
] | [((912, 941), 're.sub', 're.sub', (['"""(\\\\/)?$"""', '""""""', 'direct'], {}), "('(\\\\/)?$', '', direct)\n", (918, 941), False, 'import re\n'), ((955, 996), 're.sub', 're.sub', (['"""(\\\\.\\\\/)?pickles\\\\/"""', '""""""', 'direct'], {}), "('(\\\\.\\\\/)?pickles\\\\/', '', direct)\n", (961, 996), False, 'import re\... |
import torch
import time
import torch.nn as nn
class CNN(nn.Module):
def __init__(self):
super(CNN, self).__init__()
self.conv1 = nn.Sequential(
nn.Conv2d(in_channels=1, out_channels=16, kernel_size=5, stride=1, padding=2),
nn.ReLU(inplace=True),
nn.MaxPool2d(k... | [
"torch.nn.Dropout",
"torch.nn.ReLU",
"torch.nn.Conv2d",
"torch.nn.Linear",
"torch.nn.MaxPool2d"
] | [((578, 628), 'torch.nn.Linear', 'nn.Linear', ([], {'in_features': '(32 * 7 * 7)', 'out_features': '(10)'}), '(in_features=32 * 7 * 7, out_features=10)\n', (587, 628), True, 'import torch.nn as nn\n'), ((180, 257), 'torch.nn.Conv2d', 'nn.Conv2d', ([], {'in_channels': '(1)', 'out_channels': '(16)', 'kernel_size': '(5)',... |