code stringlengths 22 1.05M | apis listlengths 1 3.31k | extract_api stringlengths 75 3.25M |
|---|---|---|
from setuptools import setup, find_packages
import os
import deloqv
setup(name = 'deloqv',
version = '0.1.1',
url='https://github.com/ELKHMISSI/Project.git',
author = '<NAME>, NIASSE, FONTANA',
author_email = '<EMAIL>',
maintainer = '<NAME>, NIASSE, FONTANA',
maintainer_email = '<EM... | [
"setuptools.setup"
] | [((69, 439), 'setuptools.setup', 'setup', ([], {'name': '"""deloqv"""', 'version': '"""0.1.1"""', 'url': '"""https://github.com/ELKHMISSI/Project.git"""', 'author': '"""<NAME>, NIASSE, FONTANA"""', 'author_email': '"""<EMAIL>"""', 'maintainer': '"""<NAME>, NIASSE, FONTANA"""', 'maintainer_email': '"""<EMAIL>"""', 'keyw... |
# SPDX-FileCopyrightText: 2020 The Magma Authors.
# SPDX-FileCopyrightText: 2022 Open Networking Foundation <<EMAIL>>
#
# SPDX-License-Identifier: BSD-3-Clause
import json
from unittest import TestCase
from jsonschema import ValidationError
from magma.eventd.event_validator import EventValidator
class EventValidati... | [
"json.dumps",
"magma.eventd.event_validator.EventValidator"
] | [((889, 911), 'magma.eventd.event_validator.EventValidator', 'EventValidator', (['config'], {}), '(config)\n', (903, 911), False, 'from magma.eventd.event_validator import EventValidator\n'), ((967, 1007), 'json.dumps', 'json.dumps', (["{'foo': 'magma', 'bar': 123}"], {}), "({'foo': 'magma', 'bar': 123})\n", (977, 1007... |
# -*- coding: utf-8 -*-
#
# This file is part of Invenio.
# Copyright (C) 2016-2018 CERN.
#
# Invenio is free software; you can redistribute it and/or modify it
# under the terms of the MIT License; see LICENSE file for more details.
"""Test handlers."""
from __future__ import absolute_import, print_function
import ... | [
"invenio_oauthclient.handlers.token_getter",
"pytest.raises",
"invenio_oauthclient.utils.oauth_authenticate",
"invenio_oauthclient.handlers.response_token_setter",
"invenio_oauthclient.models.RemoteToken.create"
] | [((1995, 2026), 'invenio_oauthclient.utils.oauth_authenticate', 'oauth_authenticate', (['"""dev"""', 'user'], {}), "('dev', user)\n", (2013, 2026), False, 'from invenio_oauthclient.utils import oauth_authenticate\n'), ((2096, 2157), 'invenio_oauthclient.models.RemoteToken.create', 'RemoteToken.create', (['user.id', '""... |
import io
import json
import enum
import gzip
from sota_extractor import errors
class Format(enum.Enum):
"""Output format.
At the moment only supported format is JSON, but in the future YAML support
is planned.
"""
json = "json"
json_gz = "json.gz"
def dump(data, filename, fmt=Format.json,... | [
"json.dump",
"json.load",
"gzip.open",
"json.dumps",
"io.open",
"sota_extractor.errors.UnsupportedFormat"
] | [((873, 919), 'io.open', 'io.open', (['filename'], {'mode': '"""w"""', 'encoding': 'encoding'}), "(filename, mode='w', encoding=encoding)\n", (880, 919), False, 'import io\n'), ((939, 987), 'json.dump', 'json.dump', (['data'], {'fp': 'fp', 'indent': '(2)', 'sort_keys': '(True)'}), '(data, fp=fp, indent=2, sort_keys=Tru... |
from cryptography.fernet import Fernet
import codecs
import chardet
def encrypt(database, llave):
key = llave
encoded_msg = database.encode()
f = Fernet(key)
encriptacion = f.encrypt(encoded_msg)
return encriptacion.decode()
def decrypt(encode_Database,llave):
k... | [
"cryptography.fernet.Fernet"
] | [((178, 189), 'cryptography.fernet.Fernet', 'Fernet', (['key'], {}), '(key)\n', (184, 189), False, 'from cryptography.fernet import Fernet\n'), ((340, 351), 'cryptography.fernet.Fernet', 'Fernet', (['key'], {}), '(key)\n', (346, 351), False, 'from cryptography.fernet import Fernet\n')] |
import threading
import socket
import sys
import time
class Client:
def __init__(self):
super().__init__()
self.kill = False
self.host = "127.0.0.1"
self.port = 3006
def receive_history(self):
data = str()
while True:
try:
chunk = se... | [
"threading.Thread",
"socket.socket",
"sys.exit",
"time.sleep"
] | [((848, 897), 'socket.socket', 'socket.socket', (['socket.AF_INET', 'socket.SOCK_STREAM'], {}), '(socket.AF_INET, socket.SOCK_STREAM)\n', (861, 897), False, 'import socket\n'), ((1348, 1392), 'threading.Thread', 'threading.Thread', ([], {'target': 'self.reading_socket'}), '(target=self.reading_socket)\n', (1364, 1392),... |
import tensorflow as tf
import numpy as np
from tensorflow.python.ops.rnn import _transpose_batch_time
class Decoder:
def __init__(self, **kwargs):
self.encodings = None
self.num_sentence_characters = kwargs['num_sentence_characters']
self.dict_length = kwargs['dict_length']
self.m... | [
"tensorflow.einsum",
"tensorflow.reduce_sum",
"tensorflow.nn.tanh",
"tensorflow.reshape",
"numpy.shape",
"tensorflow.matmul",
"tensorflow.divide",
"tensorflow.nn.bidirectional_dynamic_rnn",
"tensorflow.split",
"tensorflow.get_variable",
"tensorflow.nn.softmax",
"tensorflow.nn.moments",
"tens... | [((831, 862), 'tensorflow.reduce_mean', 'tf.reduce_mean', (['values'], {'axis': '(-1)'}), '(values, axis=-1)\n', (845, 862), True, 'import tensorflow as tf\n'), ((883, 958), 'tensorflow.layers.dense', 'tf.layers.dense', ([], {'inputs': 'mean_pool', 'activation': 'tf.nn.relu', 'units': 'units_dense'}), '(inputs=mean_poo... |
#!/user/bin/env python3
###################################################################################
# #
# NAME: conanfile.py #
# ... | [
"conans.Meson"
] | [((1524, 1535), 'conans.Meson', 'Meson', (['self'], {}), '(self)\n', (1529, 1535), False, 'from conans import ConanFile, tools, Meson\n')] |
#-------------------------------------------------------------------------------
# Copyright 2017 Cognizant Technology Solutions
#
# 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://... | [
"dateutil.parser.parse",
"time.strptime",
"boto3.client",
"json.dumps"
] | [((1124, 1147), 'dateutil.parser.parse', 'parser.parse', (['startFrom'], {}), '(startFrom)\n', (1136, 1147), False, 'from dateutil import parser\n'), ((1760, 1878), 'boto3.client', 'boto3.client', (['"""codepipeline"""'], {'aws_access_key_id': 'accesskey', 'aws_secret_access_key': 'secretkey', 'region_name': 'regionNam... |
from femagtools import winding_diagram
def test_winding_diagram():
data = winding_diagram._winding_data(12, 2, 3)
assert data == [1, -2, 3, -1, 2, -3, 1, -2, 3, -1, 2, -3]
data = winding_diagram._winding_data(36, 2, 3)
assert data == [1, 1, 1, -2, -2, -2, 3, 3, 3, -1, -1, -1, 2, 2, 2, -3, -3, -3, 1... | [
"femagtools.winding_diagram._winding_data"
] | [((82, 121), 'femagtools.winding_diagram._winding_data', 'winding_diagram._winding_data', (['(12)', '(2)', '(3)'], {}), '(12, 2, 3)\n', (111, 121), False, 'from femagtools import winding_diagram\n'), ((196, 235), 'femagtools.winding_diagram._winding_data', 'winding_diagram._winding_data', (['(36)', '(2)', '(3)'], {}), ... |
MONGODB_SETTINGS = {
'DB': 'Your_DB_Name',
'host': 'localhost',
'port': 27017,
}
from pymongo import MongoClient
client = MongoClient(f'{MONGODB_SETTINGS["host"]}:{MONGODB_SETTINGS["port"]}')
db = client.DoctorsDB | [
"pymongo.MongoClient"
] | [((140, 209), 'pymongo.MongoClient', 'MongoClient', (['f"""{MONGODB_SETTINGS[\'host\']}:{MONGODB_SETTINGS[\'port\']}"""'], {}), '(f"{MONGODB_SETTINGS[\'host\']}:{MONGODB_SETTINGS[\'port\']}")\n', (151, 209), False, 'from pymongo import MongoClient\n')] |
import numpy as np
### 1
def fib_matrix(n):
for i in range(n):
res = pow((np.matrix([[1, 1], [1, 0]], dtype='int64')), i) * np.matrix([[1], [0]])
print(int(res[0][0]))
# 调用
fib_matrix(100)
### 2
# 使用矩阵计算斐波那契数列
def Fibonacci_Matrix_tool(n):
Matrix = np.matrix("1 1;1 0", dtype='int64')
# ... | [
"numpy.matrix",
"numpy.linalg.matrix_power"
] | [((278, 313), 'numpy.matrix', 'np.matrix', (['"""1 1;1 0"""'], {'dtype': '"""int64"""'}), "('1 1;1 0', dtype='int64')\n", (287, 313), True, 'import numpy as np\n'), ((343, 376), 'numpy.linalg.matrix_power', 'np.linalg.matrix_power', (['Matrix', 'n'], {}), '(Matrix, n)\n', (365, 376), True, 'import numpy as np\n'), ((13... |
#!/usr/bin/python3
# -*- coding: utf-8 -*-
import pickle
from ssd_utils import BBoxUtility
from generator import Generator
from ssd_training import MultiboxLoss
from keras.callbacks import TensorBoard
from keras.callbacks import ModelCheckpoint
from time import gmtime, strftime
import os
def schedule(epoch, base_lr=3... | [
"os.mkdir",
"ssd_training.MultiboxLoss",
"keras.callbacks.ModelCheckpoint",
"time.gmtime",
"keras.callbacks.TensorBoard",
"generator.Generator",
"ssd_utils.BBoxUtility"
] | [((1794, 1827), 'ssd_utils.BBoxUtility', 'BBoxUtility', (['class_number', 'priors'], {}), '(class_number, priors)\n', (1805, 1827), False, 'from ssd_utils import BBoxUtility\n'), ((2166, 2333), 'generator.Generator', 'Generator', (['self.train_data', 'self.bbox_utils', 'batch_size', 'path_prefix', 'self.train_keys', 's... |
from thundra_demo_localstack.service import start_new_request, list_requests_by_request_id
import json
headers = {
"content-type": "application/json"
}
Handlers = {
'POST/requests': start_new_request,
'GET/request/{requestId}': list_requests_by_request_id
}
def generate_request_content(event, action):
... | [
"json.dumps"
] | [((1010, 1028), 'json.dumps', 'json.dumps', (['result'], {}), '(result)\n', (1020, 1028), False, 'import json\n'), ((857, 871), 'json.dumps', 'json.dumps', (['{}'], {}), '({})\n', (867, 871), False, 'import json\n')] |
#!/usr/bin/env python
import time
import unittest
import rospy
import rostest
from rosbridge_library.internal import subscription_modifiers as subscribe
class TestMessageHandlers(unittest.TestCase):
def setUp(self):
rospy.init_node("test_message_handlers")
def dummy_cb(self, msg):
pass
... | [
"rosbridge_library.internal.subscription_modifiers.MessageHandler",
"time.time",
"time.sleep",
"rospy.init_node",
"rostest.unitrun"
] | [((13106, 13153), 'rostest.unitrun', 'rostest.unitrun', (['PKG', 'NAME', 'TestMessageHandlers'], {}), '(PKG, NAME, TestMessageHandlers)\n', (13121, 13153), False, 'import rostest\n'), ((231, 271), 'rospy.init_node', 'rospy.init_node', (['"""test_message_handlers"""'], {}), "('test_message_handlers')\n", (246, 271), Fal... |
import math
import time
import logging
import socket
import select
try:
import socketserver
except ImportError:
import SocketServer as socketserver
def ping(addr, count=20, timeout=1):
"""UDP ping client"""
# print "--- PING %s:%d ---" % addr
results = []
sock = socket.socket(socket.AF_INET, ... | [
"logging.debug",
"socket.socket",
"time.sleep",
"time.time",
"select.select"
] | [((290, 338), 'socket.socket', 'socket.socket', (['socket.AF_INET', 'socket.SOCK_DGRAM'], {}), '(socket.AF_INET, socket.SOCK_DGRAM)\n', (303, 338), False, 'import socket\n'), ((379, 390), 'time.time', 'time.time', ([], {}), '()\n', (388, 390), False, 'import time\n'), ((555, 593), 'select.select', 'select.select', (['[... |
# Copyright (c) 2011-2020 <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 limitation the rights
# to use, copy, modify, merge, publish, distrib... | [
"copy.deepcopy",
"traceback.print_exc",
"json.loads",
"_ba.getactivity",
"ba._general.utf8_all",
"ba._general.Call",
"_ba.get_master_server_address",
"_ba.set_thread_name",
"_ba.Context",
"socket.inet_pton",
"weakref.ref"
] | [((1777, 1815), 'socket.inet_pton', 'socket.inet_pton', (['socket.AF_INET', 'addr'], {}), '(socket.AF_INET, addr)\n', (1793, 1815), False, 'import socket\n'), ((3079, 3101), '_ba.Context', '_ba.Context', (['"""current"""'], {}), "('current')\n", (3090, 3101), False, 'import _ba\n'), ((3183, 3213), '_ba.getactivity', '_... |
from dsl_parser import SchemeParser, Accumulator, Cons
import transform
def compute_buffer_length(bytecode_list):
result = 0
while bytecode_list is not None:
result += len(bytecode_list.car)
bytecode_list = bytecode_list.cdr
return result
RULES = {}
def load_transforms(path):
sexp = N... | [
"dsl_parser.Cons",
"dsl_parser.Accumulator",
"dsl_parser.SchemeParser",
"transform.Transform"
] | [((2173, 2186), 'dsl_parser.Accumulator', 'Accumulator', ([], {}), '()\n', (2184, 2186), False, 'from dsl_parser import SchemeParser, Accumulator, Cons\n'), ((374, 388), 'dsl_parser.SchemeParser', 'SchemeParser', ([], {}), '()\n', (386, 388), False, 'from dsl_parser import SchemeParser, Accumulator, Cons\n'), ((464, 49... |
#!/usr/bin/python3
"""
Simplify AST-XML structures for later generation of Python files.
"""
from optparse import OptionParser
import os
import os.path
import sys
from xml.etree import ElementTree
from xml.dom import minidom # type: ignore
import logging
import importlib
from importlib import machinery
from . import p... | [
"io.StringIO",
"optparse.OptionParser",
"logging.basicConfig",
"typing.cast",
"os.path.basename",
"os.path.realpath",
"os.path.exists",
"importlib.reload",
"os.path.getmtime",
"xml.etree.ElementTree.tostring",
"os.path.getctime",
"os.path.split",
"os.path.join",
"pineboolib.application.par... | [((476, 502), 'importlib.reload', 'importlib.reload', (['pytnyzer'], {}), '(pytnyzer)\n', (492, 502), False, 'import importlib\n'), ((576, 603), 'logging.getLogger', 'logging.getLogger', (['__name__'], {}), '(__name__)\n', (593, 603), False, 'import logging\n'), ((18581, 18595), 'optparse.OptionParser', 'OptionParser',... |
import psycopg2
import time
from action.case_one_subscription_rebill_cancel import case_one_subscription,\
case_one_first_rebill, \
case_one_second_rebill, \
case_one_third_rebill, \
case_one_fourth_rebill, \
case_one_cancel
from connection.connection_variables import pg_user, \
pg_password, \
... | [
"action.case_one_subscription_rebill_cancel.case_one_third_rebill",
"action.case_one_subscription_rebill_cancel.case_one_first_rebill",
"action.case_one_subscription_rebill_cancel.case_one_cancel",
"time.sleep",
"action.case_one_subscription_rebill_cancel.case_one_fourth_rebill",
"action.case_one_subscrip... | [((732, 838), 'psycopg2.connect', 'psycopg2.connect', ([], {'database': 'pg_database', 'user': 'pg_user', 'password': 'pg_password', 'host': 'pg_host', 'port': 'pg_port'}), '(database=pg_database, user=pg_user, password=pg_password,\n host=pg_host, port=pg_port)\n', (748, 838), False, 'import psycopg2\n'), ((956, 97... |
from history import save_history, get_browser_history
from search import search
from rich import print
def main():
print("Seja bem-vindo ao py-google-search")
while True:
try:
search_term = input("Pesquisa: ")
save_history(search_term)
if search_term == '--history':
... | [
"rich.print",
"history.save_history",
"history.get_browser_history",
"search.search"
] | [((120, 163), 'rich.print', 'print', (['"""Seja bem-vindo ao py-google-search"""'], {}), "('Seja bem-vindo ao py-google-search')\n", (125, 163), False, 'from rich import print\n'), ((251, 276), 'history.save_history', 'save_history', (['search_term'], {}), '(search_term)\n', (263, 276), False, 'from history import save... |
import os
import sys
import unittest
import tempfile
import shutil
from cStringIO import StringIO
try:
# 'import as' required to protect nosetests
import catkin.test_results as catkin_test_results
except ImportError as impe:
raise ImportError(
'Please adjust your pythonpath before running this tes... | [
"catkin.test_results.read_junit",
"cStringIO.StringIO",
"tempfile.mkdtemp",
"catkin.test_results.test_results",
"shutil.rmtree",
"sys.stdout.getvalue",
"os.path.join",
"catkin.test_results.print_summary"
] | [((451, 469), 'tempfile.mkdtemp', 'tempfile.mkdtemp', ([], {}), '()\n', (467, 469), False, 'import tempfile\n'), ((497, 531), 'os.path.join', 'os.path.join', (['rootdir', '"""test1.xml"""'], {}), "(rootdir, 'test1.xml')\n", (509, 531), False, 'import os\n'), ((751, 794), 'catkin.test_results.read_junit', 'catkin_test_r... |
# -*- coding: utf-8 -*-
# Generated by the protocol buffer compiler. DO NOT EDIT!
# source: cosmos/auth/v1beta1/genesis.proto
"""Generated protocol buffer code."""
from google.protobuf import descriptor as _descriptor
from google.protobuf import message as _message
from google.protobuf import reflection as _reflection... | [
"google.protobuf.symbol_database.Default",
"google.protobuf.descriptor.FieldDescriptor",
"google.protobuf.reflection.GeneratedProtocolMessageType",
"google.protobuf.descriptor.FileDescriptor"
] | [((432, 458), 'google.protobuf.symbol_database.Default', '_symbol_database.Default', ([], {}), '()\n', (456, 458), True, 'from google.protobuf import symbol_database as _symbol_database\n'), ((725, 1542), 'google.protobuf.descriptor.FileDescriptor', '_descriptor.FileDescriptor', ([], {'name': '"""cosmos/auth/v1beta1/ge... |
import pytest
from yarl import URL
from pyapp.conf import loaders
from pyapp.conf.loaders import Loader
from pyapp.exceptions import InvalidConfiguration
class TestModuleLoader:
def test__module_exists(self):
target = loaders.ModuleLoader("tests.settings")
actual = dict(target)
assert s... | [
"pyapp.conf.loaders.ModuleLoader",
"pyapp.conf.loaders.SettingsLoaderRegistry",
"pyapp.conf.loaders.ObjectLoader",
"pytest.raises",
"pytest.mark.parametrize",
"yarl.URL"
] | [((2419, 2757), 'pytest.mark.parametrize', 'pytest.mark.parametrize', (["('settings_uri', 'expected', 'str_value')", "(('sample.settings', loaders.ModuleLoader, 'python:sample.settings'), (\n 'python:sample.settings', loaders.ModuleLoader,\n 'python:sample.settings'), ('file:///path/to/sample.json', loaders.\n ... |
# PyAlgoTrade
#
# Copyright 2011-2015 <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 t... | [
"pyalgotrade.optimizer.xmlrpcserver.Server",
"pyalgotrade.optimizer.base.ParameterSource",
"pyalgotrade.optimizer.base.ResultSinc"
] | [((1995, 2035), 'pyalgotrade.optimizer.base.ParameterSource', 'base.ParameterSource', (['strategyParameters'], {}), '(strategyParameters)\n', (2015, 2035), False, 'from pyalgotrade.optimizer import base\n'), ((2053, 2070), 'pyalgotrade.optimizer.base.ResultSinc', 'base.ResultSinc', ([], {}), '()\n', (2068, 2070), False... |
# -*- coding: utf-8 -*-
from scrapy.spiders import CrawlSpider, Rule
from scrapy.linkextractors import LinkExtractor
SEARCH_QUERY = (
'https://www.imdb.com/search/title?'
'title_type=feature&'
'user_rating=1.0,10.0&'
'countries=us&'
'languages=en&'
'count=250&'
'view=simple'
)
class Movie... | [
"scrapy.linkextractors.LinkExtractor"
] | [((455, 495), 'scrapy.linkextractors.LinkExtractor', 'LinkExtractor', ([], {'restrict_css': '"""div.desc a"""'}), "(restrict_css='div.desc a')\n", (468, 495), False, 'from scrapy.linkextractors import LinkExtractor\n')] |
# -*- coding: utf-8 -*-
# @Author: <NAME>
# @Email: <EMAIL>
# @Date: 2019-08-18 21:14:43
# @Last Modified by: <NAME>
# @Last Modified time: 2021-06-14 11:33:09
import matplotlib.pyplot as plt
from PySONIC.parsers import *
from .plt import SectionGroupedTimeSeries, SectionCompTimeSeries
from .models import models_... | [
"matplotlib.pyplot.show"
] | [((2086, 2096), 'matplotlib.pyplot.show', 'plt.show', ([], {}), '()\n', (2094, 2096), True, 'import matplotlib.pyplot as plt\n')] |
# -*- coding: utf-8 -*-
# Generated by Django 1.10.6 on 2017-04-27 03:32
from __future__ import unicode_literals
from django.db import migrations, models
import django.db.models.deletion
class Migration(migrations.Migration):
dependencies = [
('crm', '0003_auto_20170421_0932'),
]
operations = [... | [
"django.db.models.OneToOneField",
"django.db.models.TextField",
"django.db.models.ForeignKey",
"django.db.models.CharField",
"django.db.models.BooleanField",
"django.db.models.AutoField",
"django.db.models.SmallIntegerField",
"django.db.models.IntegerField",
"django.db.migrations.AlterModelOptions",... | [((2154, 2272), 'django.db.migrations.AlterModelOptions', 'migrations.AlterModelOptions', ([], {'name': '"""customerinfo"""', 'options': "{'verbose_name': '客户信息', 'verbose_name_plural': '客户信息'}"}), "(name='customerinfo', options={'verbose_name':\n '客户信息', 'verbose_name_plural': '客户信息'})\n", (2182, 2272), False, 'fro... |
from dataclasses import dataclass
from typing import Optional, Union
import numpy as np
import torch
from transformers.modeling_utils import PreTrainedModel
from transformers.tokenization_utils_base import PreTrainedTokenizerBase, PaddingStrategy, BatchEncoding
DEPTH_SPECIAL_TOKENS = {
-1: 48900,
0: 48613,
... | [
"torch.tensor"
] | [((3515, 3590), 'torch.tensor', 'torch.tensor', (["[feature['labels'] for feature in features]"], {'dtype': 'torch.long'}), "([feature['labels'] for feature in features], dtype=torch.long)\n", (3527, 3590), False, 'import torch\n'), ((5011, 5052), 'torch.tensor', 'torch.tensor', (['input_ids'], {'dtype': 'torch.long'})... |
import argparse
import json
from multiprocessing.util import Finalize
from typing import Dict, List, Tuple
from multiprocessing import Pool as ProcessPool
import itertools
import pickle
import numpy as np
import os
from os.path import join
from tqdm import tqdm
from hotpot.data_handling.relevance_training_data import... | [
"json.dump",
"os.path.abspath",
"multiprocessing.util.Finalize",
"pickle.dump",
"argparse.ArgumentParser",
"json.load",
"hotpot.data_handling.dataset.QuestionAndParagraphsSpec",
"json.loads",
"hotpot.tokenizers.CoreNLPTokenizer",
"pickle.load",
"hotpot.utils.ResourceLoader",
"hotpot.data_handl... | [((800, 818), 'hotpot.tokenizers.CoreNLPTokenizer', 'CoreNLPTokenizer', ([], {}), '()\n', (816, 818), False, 'from hotpot.tokenizers import CoreNLPTokenizer\n'), ((823, 884), 'multiprocessing.util.Finalize', 'Finalize', (['PROCESS_TOK', 'PROCESS_TOK.shutdown'], {'exitpriority': '(100)'}), '(PROCESS_TOK, PROCESS_TOK.shu... |
"""Prepare the ImageNet dataset"""
import os
import argparse
import tarfile
import pickle
import gzip
import subprocess
from tqdm import tqdm
import subprocess
from encoding.utils import check_sha1, download, mkdir
_TARGET_DIR = os.path.expanduser('~/.encoding/data/ILSVRC2012')
_TRAIN_TAR = 'ILSVRC2012_img_train.tar'
... | [
"os.path.expanduser",
"os.mkdir",
"os.remove",
"argparse.ArgumentParser",
"os.path.exists",
"encoding.utils.check_sha1",
"encoding.utils.mkdir",
"subprocess.call",
"os.path.splitext",
"tarfile.open",
"os.path.join"
] | [((230, 279), 'os.path.expanduser', 'os.path.expanduser', (['"""~/.encoding/data/ILSVRC2012"""'], {}), "('~/.encoding/data/ILSVRC2012')\n", (248, 279), False, 'import os\n'), ((508, 634), 'argparse.ArgumentParser', 'argparse.ArgumentParser', ([], {'description': '"""Setup the ImageNet dataset."""', 'formatter_class': '... |
from setuptools import setup, find_packages
from cana import __package__, __title__, __description__, __version__
def readme():
with open('README.md') as f:
return f.read()
setup(
name=__package__,
version=__version__,
description=__description__,
long_description=__description__,
classifiers=[
'Developmen... | [
"setuptools.find_packages"
] | [((748, 763), 'setuptools.find_packages', 'find_packages', ([], {}), '()\n', (761, 763), False, 'from setuptools import setup, find_packages\n')] |
# -*- coding: utf-8 -*-
"""load_map contains several shortcut functions to quickly load maps.
Custom map-loading routines will probably be desired, but load_map
can be useful for testing new heuristics, pathfinding algorithms, etc."""
import nodes
import algorithms
import metrics
START = '0'
BLANK = ' '
WALL = '#'
TA... | [
"nodes.RectNode"
] | [((1377, 1442), 'nodes.RectNode', 'nodes.RectNode', (['start_pos'], {'walkable': 'walkable', 'heuristic': 'heuristic'}), '(start_pos, walkable=walkable, heuristic=heuristic)\n', (1391, 1442), False, 'import nodes\n'), ((1576, 1642), 'nodes.RectNode', 'nodes.RectNode', (['target_pos'], {'walkable': 'walkable', 'heuristi... |
import cv2
import uuid
import os
COLORS = {
'thief': (255, 0, 0),
'policeman1': (0, 255, 0),
'policeman2': (0, 0, 255)
}
FONT = cv2.FONT_HERSHEY_SIMPLEX
FONT_SCALE = 1
LINE_TYPE = 2
class Camera:
@staticmethod
def get_fake_gaming_board():
frame = cv2.imread('../resources/gaming_board.jpg'... | [
"cv2.putText",
"cv2.cvtColor",
"cv2.waitKey",
"cv2.VideoCapture",
"cv2.imread",
"uuid.uuid1",
"cv2.destroyWindow",
"cv2.rectangle",
"cv2.imshow",
"cv2.namedWindow"
] | [((278, 321), 'cv2.imread', 'cv2.imread', (['"""../resources/gaming_board.jpg"""'], {}), "('../resources/gaming_board.jpg')\n", (288, 321), False, 'import cv2\n'), ((338, 376), 'cv2.cvtColor', 'cv2.cvtColor', (['frame', 'cv2.COLOR_RGB2BGR'], {}), '(frame, cv2.COLOR_RGB2BGR)\n', (350, 376), False, 'import cv2\n'), ((621... |
import pytest
from numpy import allclose, array, asarray, add, ndarray, generic
from lightning import series, image
pytestmark = pytest.mark.usefixtures("eng")
def test_first(eng):
data = series.fromlist([array([1, 2, 3]), array([4, 5, 6])], engine=eng)
assert allclose(data.first(), [1, 2, 3])
data = im... | [
"numpy.asarray",
"numpy.allclose",
"numpy.array",
"lightning.image.fromlist",
"lightning.series.fromlist",
"pytest.mark.usefixtures"
] | [((131, 161), 'pytest.mark.usefixtures', 'pytest.mark.usefixtures', (['"""eng"""'], {}), "('eng')\n", (154, 161), False, 'import pytest\n'), ((569, 582), 'numpy.asarray', 'asarray', (['data'], {}), '(data)\n', (576, 582), False, 'from numpy import allclose, array, asarray, add, ndarray, generic\n'), ((595, 638), 'numpy... |
#!/usr/bin/env python3
# -*- coding: utf-8 -*-
"""
Created on Thu May 5 08:18:05 2022
https://thatascience.com/learn-machine-learning/pipeline-in-scikit-learn/
@author: qian.cao
"""
import pandas as pd
import numpy as np
from sklearn.preprocessing import StandardScaler
from sklearn.decomposition import PCA
from sk... | [
"matplotlib.pyplot.title",
"numpy.load",
"sklearn.preprocessing.StandardScaler",
"sklearn.model_selection.train_test_split",
"matplotlib.pyplot.figure",
"numpy.mean",
"sys.path.append",
"numpy.std",
"matplotlib.pyplot.close",
"matplotlib.pyplot.colorbar",
"numpy.max",
"numpy.linspace",
"nump... | [((528, 566), 'sys.path.append', 'sys.path.append', (['"""../bonebox/metrics/"""'], {}), "('../bonebox/metrics/')\n", (543, 566), False, 'import sys\n'), ((762, 796), 'os.makedirs', 'os.makedirs', (['outDir'], {'exist_ok': '(True)'}), '(outDir, exist_ok=True)\n', (773, 796), False, 'import os\n'), ((949, 974), 'numpy.l... |
#!/usr/bin/env python
# Python Standard Library
pass
# Third-Party Libraries
import numpy as np
import matplotlib.pyplot as plt
from matplotlib.colors import to_rgb
# Local Library
import mivp
# ------------------------------------------------------------------------------
grey_4 = to_rgb("#ced4da")
# ----------... | [
"numpy.meshgrid",
"numpy.vectorize",
"matplotlib.pyplot.plot",
"mivp.generate_movie",
"matplotlib.pyplot.axis",
"matplotlib.colors.to_rgb",
"matplotlib.pyplot.figure",
"numpy.sin",
"numpy.array",
"numpy.arange",
"numpy.linspace",
"numpy.cos",
"numpy.sqrt"
] | [((289, 306), 'matplotlib.colors.to_rgb', 'to_rgb', (['"""#ced4da"""'], {}), "('#ced4da')\n", (295, 306), False, 'from matplotlib.colors import to_rgb\n'), ((858, 893), 'numpy.arange', 'np.arange', (['t_span[0]', 't_span[1]', 'dt'], {}), '(t_span[0], t_span[1], dt)\n', (867, 893), True, 'import numpy as np\n'), ((1544,... |
from flask.ext.login import LoginManager
from flask.ext.micropub import MicropubClient
from flask.ext.sqlalchemy import SQLAlchemy
from flask_debugtoolbar import DebugToolbarExtension
db = SQLAlchemy()
micropub = MicropubClient(client_id='https://woodwind.xyz/')
login_mgr = LoginManager()
login_mgr.login_view = 'view... | [
"flask.ext.sqlalchemy.SQLAlchemy",
"flask.ext.login.LoginManager",
"flask.ext.micropub.MicropubClient"
] | [((191, 203), 'flask.ext.sqlalchemy.SQLAlchemy', 'SQLAlchemy', ([], {}), '()\n', (201, 203), False, 'from flask.ext.sqlalchemy import SQLAlchemy\n'), ((215, 264), 'flask.ext.micropub.MicropubClient', 'MicropubClient', ([], {'client_id': '"""https://woodwind.xyz/"""'}), "(client_id='https://woodwind.xyz/')\n", (229, 264... |
#!/usr/bin/env python3
"""
--- Day 2: Dive! ---
https://adventofcode.com/2021/day/2
"""
from abc import ABC, abstractmethod
import argparse
from enum import Enum
import sys
from typing import List, NamedTuple
class Direction(Enum):
FORWARD = 1
DOWN = 2
UP = 3
class Step(NamedTuple):
direction: Direction
... | [
"argparse.ArgumentParser",
"argparse.FileType"
] | [((2559, 2610), 'argparse.ArgumentParser', 'argparse.ArgumentParser', ([], {'description': '"""Day 2: Dive!"""'}), "(description='Day 2: Dive!')\n", (2582, 2610), False, 'import argparse\n'), ((2659, 2681), 'argparse.FileType', 'argparse.FileType', (['"""r"""'], {}), "('r')\n", (2676, 2681), False, 'import argparse\n')... |
import sys
import policy_api_requests
import json
protocol = "https"
nbmaster = ""
username = ""
password = ""
domainName = ""
domainType = ""
port = 1556
def print_disclaimer():
print("-------------------------------------------------------------------------------------------------")
print("-- ... | [
"policy_api_requests.post_netbackup_VMwarePolicy",
"policy_api_requests.perform_login",
"policy_api_requests.get_netbackup_policies",
"policy_api_requests.delete_VMware_netbackup_policy",
"policy_api_requests.put_netbackup_policy",
"policy_api_requests.get_netbackup_policy"
] | [((2603, 2694), 'policy_api_requests.perform_login', 'policy_api_requests.perform_login', (['username', 'password', 'domainName', 'domainType', 'base_url'], {}), '(username, password, domainName,\n domainType, base_url)\n', (2636, 2694), False, 'import policy_api_requests\n'), ((2694, 2756), 'policy_api_requests.pos... |
from __future__ import unicode_literals
from django.contrib.auth.models import User
# from django.core.validators import MaxValueValidator
from django.db import models
from django.db.models.signals import post_save
from django.dispatch import receiver
class Usuario(models.Model):
""" usuario """
usuario = m... | [
"django.db.models.CharField",
"django.db.models.OneToOneField",
"django.dispatch.receiver",
"django.db.models.EmailField"
] | [((537, 569), 'django.dispatch.receiver', 'receiver', (['post_save'], {'sender': 'User'}), '(post_save, sender=User)\n', (545, 569), False, 'from django.dispatch import receiver\n'), ((319, 356), 'django.db.models.OneToOneField', 'models.OneToOneField', (['User'], {'null': '(True)'}), '(User, null=True)\n', (339, 356),... |
import json
from os.path import basename
from typing import Dict, List, Any, Union
from ui.backend import BackendClient
_RESERVED_NAMES = {"list", "validate", "create"}
class BackendController:
def __init__(self, backend_url: str, launcher_url: str):
self._backend = BackendClient(backend_url=backend_url... | [
"ui.backend.BackendClient",
"json.dumps"
] | [((283, 348), 'ui.backend.BackendClient', 'BackendClient', ([], {'backend_url': 'backend_url', 'launcher_url': 'launcher_url'}), '(backend_url=backend_url, launcher_url=launcher_url)\n', (296, 348), False, 'from ui.backend import BackendClient\n'), ((1488, 1515), 'json.dumps', 'json.dumps', (["w['parameters']"], {}), "... |
"""
Unit tests for the density class
"""
from unittest import TestCase
import sys
sys.path.append('../src')
import numpy as np
import unittest
import suftware as sw
import os
class Density1d(TestCase):
def setUp(self):
self.N = 5
self.data = sw.simulate_density_data(distribution_type='uniform'... | [
"sys.path.append",
"unittest.TextTestRunner",
"suftware.simulate_density_data",
"numpy.array",
"unittest.TestLoader",
"suftware.DensityEstimator"
] | [((84, 109), 'sys.path.append', 'sys.path.append', (['"""../src"""'], {}), "('../src')\n", (99, 109), False, 'import sys\n'), ((268, 339), 'suftware.simulate_density_data', 'sw.simulate_density_data', ([], {'distribution_type': '"""uniform"""', 'N': 'self.N', 'seed': '(1)'}), "(distribution_type='uniform', N=self.N, se... |
"""
@author waziz
"""
import chisel.mteval as mteval
import logging
from _bleu import BLEU, DecodingBLEU, TrainingBLEU
class WrappedBLEU(mteval.LossFunction):
def __init__(self, alias):
self.alias_ = alias
self.bleu_config_ = {}
self.decoding_bleu_wrapper_ = None
self.training_ble... | [
"logging.info",
"_bleu.TrainingBLEU"
] | [((1721, 1778), '_bleu.TrainingBLEU', 'TrainingBLEU', (['references', 'hypotheses'], {}), '(references, hypotheses, **self.bleu_config_)\n', (1733, 1778), False, 'from _bleu import BLEU, DecodingBLEU, TrainingBLEU\n'), ((611, 682), 'logging.info', 'logging.info', (['"""BLEU using default max_order=%d"""', 'BLEU.DEFAULT... |
from django.db import models
import MySQLdb as mysql
import pytest
from pyquery import PyQuery as pq
from olympia.addons.models import Addon
from olympia.amo.tests import reverse_ns
@pytest.yield_fixture
def read_only_mode(client, settings, db):
def _db_error(*args, **kwargs):
raise mysql.OperationalEr... | [
"django.db.models.signals.pre_save.connect",
"pyquery.PyQuery",
"olympia.addons.models.Addon.objects.create",
"olympia.amo.tests.reverse_ns",
"django.db.models.signals.pre_delete.disconnect",
"django.db.models.signals.pre_delete.connect",
"pytest.raises",
"django.db.models.signals.pre_save.disconnect"... | [((1262, 1331), 'pytest.mark.parametrize', 'pytest.mark.parametrize', (['"""method"""', "('post', 'put', 'delete', 'patch')"], {}), "('method', ('post', 'put', 'delete', 'patch'))\n", (1285, 1331), False, 'import pytest\n'), ((412, 454), 'django.db.models.signals.pre_save.connect', 'models.signals.pre_save.connect', ([... |
##############################################################################
# Copyright 2020 Amazon.com, Inc. or its affiliates. All Rights Reserved. #
# #
# Licensed under the Apache License, Version 2.0 (the "License"). #
# Y... | [
"manifest.cfn_params_handler.CFNParamsHandler",
"utils.logger.Logger",
"aws.services.ssm.SSM"
] | [((1283, 1309), 'utils.logger.Logger', 'Logger', ([], {'loglevel': 'log_level'}), '(loglevel=log_level)\n', (1289, 1309), False, 'from utils.logger import Logger\n'), ((1317, 1341), 'manifest.cfn_params_handler.CFNParamsHandler', 'CFNParamsHandler', (['logger'], {}), '(logger)\n', (1333, 1341), False, 'from manifest.cf... |
import datetime
import json
import requests
def send_message(
webhook_url: str,
content_msg="",
title="",
title_url="",
color=00000000,
timestamp=datetime.datetime.now().isoformat(),
footer_icon="",
footer="",
thumbnail_url="",
author="",
author_url="",
author_icon_url=... | [
"requests.post",
"datetime.datetime.now",
"json.dumps"
] | [((1186, 1205), 'json.dumps', 'json.dumps', (['payload'], {}), '(payload)\n', (1196, 1205), False, 'import json\n'), ((1272, 1329), 'requests.post', 'requests.post', (['webhook_url'], {'headers': 'headers', 'data': 'payload'}), '(webhook_url, headers=headers, data=payload)\n', (1285, 1329), False, 'import requests\n'),... |
# -*- coding: utf-8 -*-
from __future__ import absolute_import
from collections import OrderedDict, namedtuple
from inspect import Signature, signature
import logging
import sys
from threading import Lock
from django.http import Http404
from django.utils import six
from django.conf import urls as django_urls
import wra... | [
"django.utils.module_loading.import_string",
"django.conf.urls.include",
"threading.Lock",
"inspect.signature",
"pdb.set_trace",
"django.conf.urls.url",
"collections.OrderedDict",
"logging.getLogger"
] | [((388, 415), 'logging.getLogger', 'logging.getLogger', (['__name__'], {}), '(__name__)\n', (405, 415), False, 'import logging\n'), ((1306, 1321), 'pdb.set_trace', 'pdb.set_trace', ([], {}), '()\n', (1319, 1321), False, 'import pdb\n'), ((1563, 1585), 'collections.OrderedDict', 'OrderedDict', (['bindables'], {}), '(bin... |
from typing import List, Dict
import matplotlib.pyplot as plt
import numpy as np
from mushroom_rl.algorithms.value.td.q_learning import QLearning
from mushroom_rl.core import Core, Agent, Environment
from mushroom_rl.policy import EpsGreedy
from mushroom_rl.utils.dataset import compute_J
from mushroom_rl.utils.paramet... | [
"matplotlib.pyplot.title",
"mdp.algo.model_free.env.deep_sea.DeepSea",
"numpy.random.seed",
"matplotlib.pyplot.fill_between",
"matplotlib.pyplot.tight_layout",
"mushroom_rl.utils.dataset.compute_J",
"numpy.power",
"matplotlib.pyplot.show",
"matplotlib.pyplot.legend",
"numpy.percentile",
"mushroo... | [((2804, 2819), 'numpy.array', 'np.array', (['steps'], {}), '(steps)\n', (2812, 2819), True, 'import numpy as np\n'), ((3081, 3130), 'matplotlib.pyplot.plot', 'plt.plot', (['steps', 'best_reward'], {'label': '"""Best reward"""'}), "(steps, best_reward, label='Best reward')\n", (3089, 3130), True, 'import matplotlib.pyp... |
"""
Project: python_assessment_3
Author: <NAME>. <<EMAIL>>
Created at: 10/11/2020 7:34 pm
File: client.py
"""
import socket
from colorama import Fore, Style
def request(question: str, host: str, port: int):
"""Creates a client socket and requests an answer from the server based on the provided question.
:pa... | [
"socket.socket"
] | [((443, 492), 'socket.socket', 'socket.socket', (['socket.AF_INET', 'socket.SOCK_STREAM'], {}), '(socket.AF_INET, socket.SOCK_STREAM)\n', (456, 492), False, 'import socket\n')] |
# Copyright 2019 <NAME> and <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 wri... | [
"warnings.simplefilter",
"heapq.heappush",
"math.ceil",
"pandas.read_csv",
"common.sender_obs.SenderMonitorInterval",
"heapq.heappop",
"random.random",
"common.sender_obs.SenderHistory",
"common.sender_obs.get_min_obs_vector",
"numpy.array",
"numpy.tile",
"numpy.mean",
"numpy.random.choice",... | [((680, 740), 'warnings.simplefilter', 'warnings.simplefilter', ([], {'action': '"""ignore"""', 'category': 'UserWarning'}), "(action='ignore', category=UserWarning)\n", (701, 740), False, 'import warnings\n'), ((24695, 24771), 'gym.envs.registration.register', 'register', ([], {'id': '"""PccNs-v0"""', 'entry_point': '... |
"""
Copyright 2020 EUROCONTROL
==========================================
Redistribution and use in source and binary forms, with or without modification, are permitted
provided that the following conditions are met:
1. Redistributions of source code must retain the above copyright notice, this list of conditions
... | [
"os.remove",
"aixm_graph.datasets.datasets.AIXMDataSet",
"os.path.exists",
"pkg_resources.resource_filename"
] | [((2048, 2108), 'pkg_resources.resource_filename', 'resource_filename', (['__name__', 'f"""../../static/{TEST_FILENAME}"""'], {}), "(__name__, f'../../static/{TEST_FILENAME}')\n", (2065, 2108), False, 'from pkg_resources import resource_filename\n'), ((2164, 2228), 'pkg_resources.resource_filename', 'resource_filename'... |
# Released under the MIT License. See LICENSE for details.
#
"""Call related functionality shared between all efro components."""
from __future__ import annotations
from typing import TYPE_CHECKING, TypeVar, Generic, Callable, cast
import functools
if TYPE_CHECKING:
from typing import Any, overload
CT = TypeVar... | [
"typing.cast",
"typing.TypeVar"
] | [((313, 342), 'typing.TypeVar', 'TypeVar', (['"""CT"""'], {'bound': 'Callable'}), "('CT', bound=Callable)\n", (320, 342), False, 'from typing import TYPE_CHECKING, TypeVar, Generic, Callable, cast\n'), ((2422, 2437), 'typing.TypeVar', 'TypeVar', (['"""In1T"""'], {}), "('In1T')\n", (2429, 2437), False, 'from typing impo... |
import cv2
import time
plate_cascade =cv2.CascadeClassifier('DATA/haarcascades/india_license_plate.xml') # Loads the data required for detecting the license plates from cascade classifier.
def detect_plate(img): # the function detects and perfors blurring on the number plate.
plate_img = img.copy()
roi = img.... | [
"cv2.waitKey",
"cv2.imshow",
"cv2.blur",
"cv2.VideoCapture",
"cv2.rectangle",
"cv2.CascadeClassifier",
"cv2.destroyAllWindows"
] | [((39, 105), 'cv2.CascadeClassifier', 'cv2.CascadeClassifier', (['"""DATA/haarcascades/india_license_plate.xml"""'], {}), "('DATA/haarcascades/india_license_plate.xml')\n", (60, 105), False, 'import cv2\n'), ((1637, 1675), 'cv2.VideoCapture', 'cv2.VideoCapture', (['"""car_plate_720p.mp4"""'], {}), "('car_plate_720p.mp4... |
# -*- coding: utf-8 -*-
from dll import DLL
class Deque(object):
"""Python Implementation of Deque Data Structure"""
def __init__(self, iter=None):
"""Constructor Function for Deque."""
self.container = DLL()
if iter:
for val in iter:
self.container.append(... | [
"dll.DLL"
] | [((230, 235), 'dll.DLL', 'DLL', ([], {}), '()\n', (233, 235), False, 'from dll import DLL\n')] |
import numpy as np
import tensorflow as tf
from .Layer import Layer
from .initializers import zeros
class RNN(Layer):
def __init__(self, output_dim,
input_dim=None,
initializer='glorot_uniform',
recurrent_initializer='orthogonal',
recurrent_activ... | [
"tensorflow.matmul",
"tensorflow.zeros",
"tensorflow.transpose"
] | [((3080, 3123), 'tensorflow.zeros', 'tf.zeros', (['(self.input_dim, self.output_dim)'], {}), '((self.input_dim, self.output_dim))\n', (3088, 3123), True, 'import tensorflow as tf\n'), ((3603, 3621), 'tensorflow.transpose', 'tf.transpose', (['mask'], {}), '(mask)\n', (3615, 3621), True, 'import tensorflow as tf\n'), ((3... |
# Copyright 2019 <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, ... | [
"tensorflow.constant_initializer",
"tensorflow.stop_gradient",
"tensorflow.reshape",
"tensorflow.nn.l2_normalize",
"tensorflow.variable_scope",
"tensorflow.transpose",
"tensorflow.matmul",
"tensorflow.random_normal_initializer"
] | [((2163, 2195), 'tensorflow.reshape', 'tf.reshape', (['w', '[-1, w_shape[-1]]'], {}), '(w, [-1, w_shape[-1]])\n', (2173, 2195), True, 'import tensorflow as tf\n'), ((2614, 2637), 'tensorflow.stop_gradient', 'tf.stop_gradient', (['u_hat'], {}), '(u_hat)\n', (2630, 2637), True, 'import tensorflow as tf\n'), ((2650, 2673)... |
import os
import pytest
import subprocess
import ssl
import time
import trustme
import bmemcached
import test_simple_functions
ca = trustme.CA()
server_cert = ca.issue_cert(os.environ["MEMCACHED_HOST"] + u"")
@pytest.yield_fixture(scope="module", autouse=True)
def memcached_tls():
key = server_cert.private_key... | [
"pytest.yield_fixture",
"ssl.create_default_context",
"trustme.CA",
"pytest.skip",
"time.sleep",
"bmemcached.Client"
] | [((135, 147), 'trustme.CA', 'trustme.CA', ([], {}), '()\n', (145, 147), False, 'import trustme\n'), ((215, 265), 'pytest.yield_fixture', 'pytest.yield_fixture', ([], {'scope': '"""module"""', 'autouse': '(True)'}), "(scope='module', autouse=True)\n", (235, 265), False, 'import pytest\n'), ((836, 851), 'time.sleep', 'ti... |
import numpy as np
from sklearn.model_selection._split import _BaseKFold, indexable, _num_samples
from sklearn.utils.validation import _deprecate_positional_args
# https://www.kaggle.com/marketneutral/purged-time-series-cv-xgboost-optuna/data
# modified code for group gaps; source
# https://github.com/getgaurav2/scik... | [
"sklearn.model_selection._split.indexable",
"numpy.concatenate",
"sklearn.model_selection._split._num_samples",
"numpy.argsort",
"numpy.arange",
"numpy.unique"
] | [((3291, 3314), 'sklearn.model_selection._split.indexable', 'indexable', (['X', 'y', 'groups'], {}), '(X, y, groups)\n', (3300, 3314), False, 'from sklearn.model_selection._split import _BaseKFold, indexable, _num_samples\n'), ((3335, 3350), 'sklearn.model_selection._split._num_samples', '_num_samples', (['X'], {}), '(... |
import xlearn as xl
import config
# Training task
ffm_model = xl.create_ffm() # Use field-aware factorization machine
ffm_model.disableEarlyStop()
ffm_model.setTrain("./train_ffm.txt") # Training data
ffm_model.setValidate("./valid_ffm.txt") # Validation data
# param:
# 0. binary classification
# 1. learning rate... | [
"xlearn.create_ffm"
] | [((63, 78), 'xlearn.create_ffm', 'xl.create_ffm', ([], {}), '()\n', (76, 78), True, 'import xlearn as xl\n')] |
# -*- coding: utf-8 -*-
"""
Created on Sun Jun 24 08:54:07 2018
@author: bwhe
"""
import ast
import numpy as np
import pandas as pd
import gc
import lightgbm as lgb
import pickle
import time
import w2v
from itertools import repeat
def remove_iteral(sentence):
return ast.literal_eval(sente... | [
"pandas.read_csv",
"time.time",
"w2v.build_artist_w2v",
"gc.collect",
"difflib.SequenceMatcher",
"pickle.load",
"numpy.mean",
"w2v.build_album_w2v",
"ast.literal_eval",
"gensim.models.Word2Vec.load",
"w2v.build_track_w2v",
"itertools.repeat"
] | [((419, 485), 'pandas.read_csv', 'pd.read_csv', (['readfile'], {'usecols': "['pid', 'pred', 'scores']", 'nrows': '(10)'}), "(readfile, usecols=['pid', 'pred', 'scores'], nrows=10)\n", (430, 485), True, 'import pandas as pd\n'), ((1086, 1098), 'gc.collect', 'gc.collect', ([], {}), '()\n', (1096, 1098), False, 'import gc... |
from django.apps import apps
from rest_framework import serializers
from config.settings import TAG_COUNT_MODELS, CATEGORY_COUNT_MODELS
from user.serializers import BasicUserSerializer
from .models import *
class TagsField(serializers.Field):
'''
comma-separated tags
'''
def __init__(self, *args, **... | [
"user.serializers.BasicUserSerializer",
"django.apps.apps.get_model",
"rest_framework.serializers.SerializerMethodField"
] | [((613, 648), 'rest_framework.serializers.SerializerMethodField', 'serializers.SerializerMethodField', ([], {}), '()\n', (646, 648), False, 'from rest_framework import serializers\n'), ((1033, 1068), 'rest_framework.serializers.SerializerMethodField', 'serializers.SerializerMethodField', ([], {}), '()\n', (1066, 1068),... |
#!/usr/bin/env python
# -*- coding: utf-8 -*-
__author__ = 'han'
import os
import h5py
import math
import torch
import torch.utils.data
from torch.utils.data.sampler import Sampler, SequentialSampler
import logging
import pandas as pd
from dataset.preprocess_data import PreprocessData
from utils.functions import *
l... | [
"pandas.DataFrame",
"h5py.File",
"torch.stack",
"torch.utils.data.DataLoader",
"math.ceil",
"os.path.exists",
"torch.utils.data.sampler.SequentialSampler",
"logging.getLogger"
] | [((328, 355), 'logging.getLogger', 'logging.getLogger', (['__name__'], {}), '(__name__)\n', (345, 355), False, 'import logging\n'), ((659, 715), 'os.path.exists', 'os.path.exists', (["self.global_config['data']['dataset_h5']"], {}), "(self.global_config['data']['dataset_h5'])\n", (673, 715), False, 'import os\n'), ((32... |
import logging
import torch.nn as nn
import torch.utils.checkpoint as cp
import torch
import numpy as np
from mmcv.cnn import constant_init, kaiming_init
from mmcv.runner import load_checkpoint
from ...registry import BACKBONES
from ..utils.resnet_r3d_utils import *
class BasicBlock(nn.Module):
def __init__(self,... | [
"torch.nn.BatchNorm3d",
"torch.nn.ReLU",
"numpy.multiply",
"mmcv.cnn.constant_init",
"mmcv.cnn.kaiming_init",
"mmcv.runner.load_checkpoint",
"torch.nn.MaxPool3d",
"logging.getLogger"
] | [((1424, 1433), 'torch.nn.ReLU', 'nn.ReLU', ([], {}), '()\n', (1431, 1433), True, 'import torch.nn as nn\n'), ((4251, 4260), 'torch.nn.ReLU', 'nn.ReLU', ([], {}), '()\n', (4258, 4260), True, 'import torch.nn as nn\n'), ((8206, 8215), 'torch.nn.ReLU', 'nn.ReLU', ([], {}), '()\n', (8213, 8215), True, 'import torch.nn as ... |
import os
origin = os.getenv("AUDIO_REQ_ORIGIN", "https://api.openverse.engineering")
identifier = "29cb352c-60c1-41d8-bfa1-7d6f7d955f63"
base_image = {
"id": identifier,
"title": "Bust of Patroclus (photograph; calotype; salt print)",
"foreign_landing_url": "https://collection.sciencemuseumgroup.org.uk... | [
"os.getenv"
] | [((21, 87), 'os.getenv', 'os.getenv', (['"""AUDIO_REQ_ORIGIN"""', '"""https://api.openverse.engineering"""'], {}), "('AUDIO_REQ_ORIGIN', 'https://api.openverse.engineering')\n", (30, 87), False, 'import os\n')] |
from typer import Option as Opt
from ..system import system
from .main import program
from .. import config
@program.command(name="api")
def program_api(
port: int = Opt(config.DEFAULT_SERVER_PORT, help="Specify server port"),
):
"""
Start API server
"""
server = system.create_server("api")
se... | [
"typer.Option"
] | [((172, 231), 'typer.Option', 'Opt', (['config.DEFAULT_SERVER_PORT'], {'help': '"""Specify server port"""'}), "(config.DEFAULT_SERVER_PORT, help='Specify server port')\n", (175, 231), True, 'from typer import Option as Opt\n')] |
import io
import itertools
import logging
import sys
import traceback
from operator import itemgetter
from typing import BinaryIO, Optional, TextIO, Tuple
import target_postgres
from target_postgres import DbSync
from target_postgres.db_sync import column_type, flatten_key
from splitgraph.config import CONFIG
from sp... | [
"target_postgres.db_sync.flatten_key",
"target_postgres.db_sync.column_type",
"target_postgres.persist_lines",
"io.TextIOWrapper",
"splitgraph.ingestion.common.merge_tables",
"splitgraph.ingestion.csv.copy_csv_buffer",
"traceback.format_exc",
"operator.itemgetter",
"splitgraph.engine.postgres.engine... | [((5748, 5876), 'splitgraph.ingestion.common.merge_tables', 'merge_tables', (['self.image.object_engine', '"""pg_temp"""', 'temp_table', 'schema_spec', 'staging_table_schema', 'staging_table', 'schema_spec'], {}), "(self.image.object_engine, 'pg_temp', temp_table, schema_spec,\n staging_table_schema, staging_table, ... |
from abc import ABC, abstractmethod
from hyperopt import STATUS_OK
import numpy as np
import logging
import pandas as pd
import shap
import matplotlib.pyplot as plt
import seaborn as sns
from crosspredict.iterator import Iterator
class CrossModelFabric(ABC):
def __init__(self,
iterator: Iterator,... | [
"pandas.DataFrame",
"numpy.abs",
"pandas.merge",
"seaborn.barplot",
"numpy.zeros",
"shap.TreeExplainer",
"matplotlib.pyplot.figure",
"numpy.max",
"pandas.Series",
"shap.summary_plot",
"pandas.concat",
"logging.getLogger"
] | [((1763, 1790), 'logging.getLogger', 'logging.getLogger', (['__name__'], {}), '(__name__)\n', (1780, 1790), False, 'import logging\n'), ((7084, 7112), 'matplotlib.pyplot.figure', 'plt.figure', ([], {'figsize': '(10, 10)'}), '(figsize=(10, 10))\n', (7094, 7112), True, 'import matplotlib.pyplot as plt\n'), ((7127, 7154),... |
# -*- encoding: utf-8 -*-
# ! python3
import click
from src.visualization.overlay import overlay_command
from src.visualization.prediction_only import prediction_only_command
from src.visualization.side_by_side import side_by_side_command
@click.group(name='cli')
def cli():
pass
cli.add_command(overlay_comma... | [
"click.group"
] | [((245, 268), 'click.group', 'click.group', ([], {'name': '"""cli"""'}), "(name='cli')\n", (256, 268), False, 'import click\n')] |
import sys
n, t = map(int, sys.stdin.readline().split())
a = list(map(int, sys.stdin.readline().split()))
ans = 0
def go(i, s):
if i == n:
if s == t:
global ans
ans += 1
return
go(i+1, s)
go(i+1, s+a[i])
go(0, 0)
print(ans) | [
"sys.stdin.readline"
] | [((28, 48), 'sys.stdin.readline', 'sys.stdin.readline', ([], {}), '()\n', (46, 48), False, 'import sys\n'), ((77, 97), 'sys.stdin.readline', 'sys.stdin.readline', ([], {}), '()\n', (95, 97), False, 'import sys\n')] |
#!/usr/bin/env python
#
# Author: <NAME> <<EMAIL>>
#
'''
An example to set OMP threads in FCI calculations. In old pyscf versions,
different number of OpenMP threads may lead to slightly different answers.
This issue was fixed. see github issue #249.
'''
from functools import reduce
import numpy
from pyscf import gt... | [
"h5py.File",
"pyscf.lib.num_threads",
"pyscf.fci.direct_spin0.FCI",
"pyscf.ao2mo.kernel",
"numpy.zeros",
"pyscf.fci.cistring.num_strings",
"functools.reduce",
"pyscf.lo.lowdin",
"pyscf.lib.unpack_tril"
] | [((485, 497), 'pyscf.lo.lowdin', 'lo.lowdin', (['s'], {}), '(s)\n', (494, 497), False, 'from pyscf import gto, lo, fci, ao2mo, scf, lib\n'), ((614, 649), 'functools.reduce', 'reduce', (['numpy.dot', '(orb.T, h1, orb)'], {}), '(numpy.dot, (orb.T, h1, orb))\n', (620, 649), False, 'from functools import reduce\n'), ((655,... |
#!/usr/bin/python3
#
# RaspberryPIの操作
#
import sys
import json
import RPi.GPIO as GPIO
import adafruit_dht
from board import *
import smbus
import time
import re
from decimal import *
from gpiozero import LED
from datetime import datetime
#AD/DAモジュール設定
address = 0x48
A0 = 0x40
A1 = 0x41
A2 = 0x42
A3 = 0x43
# GPIO.BCM... | [
"RPi.GPIO.setmode",
"adafruit_dht.DHT11",
"RPi.GPIO.setup",
"time.time",
"time.sleep",
"RPi.GPIO.add_event_detect",
"re.findall",
"RPi.GPIO.input",
"RPi.GPIO.output",
"datetime.datetime.now",
"RPi.GPIO.setwarnings",
"smbus.SMBus"
] | [((922, 944), 'RPi.GPIO.setmode', 'GPIO.setmode', (['GPIO.BCM'], {}), '(GPIO.BCM)\n', (934, 944), True, 'import RPi.GPIO as GPIO\n'), ((946, 969), 'RPi.GPIO.setwarnings', 'GPIO.setwarnings', (['(False)'], {}), '(False)\n', (962, 969), True, 'import RPi.GPIO as GPIO\n'), ((971, 1002), 'RPi.GPIO.setup', 'GPIO.setup', (['... |
#!/usr/bin/env python3
import sys
import numpy as np
from PySide6.QtCore import Qt, Slot
from PySide6.QtGui import QAction, QKeySequence
from PySide6.QtWidgets import (
QApplication, QHBoxLayout, QLabel,
QMainWindow, QPushButton, QSizePolicy,
QVBoxLayout, QWidget
)
from matplotlib.backends.backend_qt5agg i... | [
"matplotlib.colors.LinearSegmentedColormap.from_list",
"numpy.zeros_like",
"PySide6.QtGui.QAction",
"skimage.data.immunohistochemistry",
"PySide6.QtGui.QKeySequence",
"skimage.exposure.rescale_intensity",
"PySide6.QtWidgets.QVBoxLayout",
"PySide6.QtWidgets.QWidget",
"PySide6.QtWidgets.QPushButton",
... | [((3659, 3665), 'PySide6.QtCore.Slot', 'Slot', ([], {}), '()\n', (3663, 3665), False, 'from PySide6.QtCore import Qt, Slot\n'), ((4002, 4008), 'PySide6.QtCore.Slot', 'Slot', ([], {}), '()\n', (4006, 4008), False, 'from PySide6.QtCore import Qt, Slot\n'), ((4341, 4347), 'PySide6.QtCore.Slot', 'Slot', ([], {}), '()\n', (... |
# -*- encoding: utf-8 -*-
from flask import url_for, redirect, render_template, flash, g, session
from app import app
@app.route('/')
def index():
return render_template('index.html')
| [
"app.app.route",
"flask.render_template"
] | [((121, 135), 'app.app.route', 'app.route', (['"""/"""'], {}), "('/')\n", (130, 135), False, 'from app import app\n'), ((157, 186), 'flask.render_template', 'render_template', (['"""index.html"""'], {}), "('index.html')\n", (172, 186), False, 'from flask import url_for, redirect, render_template, flash, g, session\n')] |
from typing import List
from secrets import token_urlsafe
from datetime import datetime
from pydantic import BaseModel, Field
class NewTokenForm(BaseModel):
scopes: List[str] = Field(default_factory=list)
class Token(BaseModel):
tid: str = Field(default_factory=lambda: token_urlsafe(15))
refresh_token:... | [
"pydantic.Field",
"secrets.token_urlsafe"
] | [((184, 211), 'pydantic.Field', 'Field', ([], {'default_factory': 'list'}), '(default_factory=list)\n', (189, 211), False, 'from pydantic import BaseModel, Field\n'), ((425, 460), 'pydantic.Field', 'Field', ([], {'default_factory': 'datetime.now'}), '(default_factory=datetime.now)\n', (430, 460), False, 'from pydantic ... |
import torch
import subprocess
import time
import logging
from subprocess import PIPE
"""
ADAPTED FROM <NAME>'S CODE
PYTHON VERSION = 3.6
"""
# Takes about 8GB
ndim = 25_000
logging.basicConfig(format='[%(asctime)s] %(filename)s [%(levelname).1s] %(message)s', level=logging.DEBUG)
def get_gpu_usage():
... | [
"logging.debug",
"logging.basicConfig",
"torch.randn",
"time.time",
"time.sleep",
"logging.info",
"torch.cuda.empty_cache"
] | [((187, 304), 'logging.basicConfig', 'logging.basicConfig', ([], {'format': '"""[%(asctime)s] %(filename)s [%(levelname).1s] %(message)s"""', 'level': 'logging.DEBUG'}), "(format=\n '[%(asctime)s] %(filename)s [%(levelname).1s] %(message)s', level=\n logging.DEBUG)\n", (206, 304), False, 'import logging\n'), ((74... |
import torch
import torch.nn as nn
import torchvision
import numpy as np
import torch.nn.functional as F
import math
from torch.autograd import Variable
import torch.utils.model_zoo as model_zoo
device = torch.device('cuda' if torch.cuda.is_available() else 'cpu')
''' StackGAN for Text to Image Generation'''
def wei... | [
"torch.nn.ReLU",
"torch.nn.Tanh",
"torch.nn.Conv2d",
"torch.nn.BatchNorm1d",
"torch.cat",
"torch.randn",
"torch.squeeze",
"torch.exp",
"torch.nn.Upsample",
"torch.nn.BatchNorm2d",
"torch.cuda.is_available",
"torch.nn.LeakyReLU",
"torch.nn.Linear",
"torch.reshape",
"torch.nn.Sigmoid"
] | [((228, 253), 'torch.cuda.is_available', 'torch.cuda.is_available', ([], {}), '()\n', (251, 253), False, 'import torch\n'), ((874, 893), 'torch.nn.Linear', 'nn.Linear', (['(768)', '(256)'], {}), '(768, 256)\n', (883, 893), True, 'import torch.nn as nn\n'), ((914, 923), 'torch.nn.ReLU', 'nn.ReLU', ([], {}), '()\n', (921... |
#!/share/apps/python/bin/python
import sys, os
import config as conf
import data as data
import module as module
type = conf.cps_type
assembly = sys.argv[1]
gtfFile = sys.argv[2]
chr = sys.argv[3]
outputdir = sys.argv[4]
#type = sys.argv[5]
if assembly == 'hg19':
tpseqAnno = data.hm_tpseqAll
tpseqIntr = conf.hm_t... | [
"module.overlappedTrxs",
"module.writeGtf",
"module.readingAnno",
"module.checkProperTrxs",
"module.getCPS",
"module.filterSameTrxs",
"module.getGtf",
"module.filterNoneTrxs"
] | [((7738, 7760), 'module.getGtf', 'module.getGtf', (['gtfFile'], {}), '(gtfFile)\n', (7751, 7760), True, 'import module as module\n'), ((4467, 4505), 'module.readingAnno', 'module.readingAnno', (['tpseqAnno', '"""polya"""'], {}), "(tpseqAnno, 'polya')\n", (4485, 4505), True, 'import module as module\n'), ((6270, 6298), ... |
from rest_framework import serializers
from constants import help_text
from data import Organism
from interfaces.serializers.base import BaseSerializer
from interfaces.serializers.fields import SourceField, URLField
from interfaces.serializers.relationship import RelationshipSerializer, SourceRelationshipSerializer
... | [
"rest_framework.serializers.HyperlinkedRelatedField",
"interfaces.serializers.fields.URLField",
"rest_framework.serializers.IntegerField",
"rest_framework.serializers.CharField",
"interfaces.serializers.fields.SourceField"
] | [((416, 508), 'rest_framework.serializers.CharField', 'serializers.CharField', ([], {'required': '(True)', 'max_length': '(200)', 'help_text': 'help_text.organism_name'}), '(required=True, max_length=200, help_text=help_text.\n organism_name)\n', (437, 508), False, 'from rest_framework import serializers\n'), ((524,... |
from click.testing import CliRunner
from pathlib import Path
from botrecon import botrecon
import warnings
import re
runner = CliRunner()
path = str(Path('tests', 'data', 'test.csv'))
regex = r'(?:[0-9]{1,3}\.){3}[0-9]{1,3}'
def test_batchify_percent():
with warnings.catch_warnings():
warnings.filterwar... | [
"click.testing.CliRunner",
"warnings.filterwarnings",
"warnings.catch_warnings",
"pathlib.Path"
] | [((128, 139), 'click.testing.CliRunner', 'CliRunner', ([], {}), '()\n', (137, 139), False, 'from click.testing import CliRunner\n'), ((151, 184), 'pathlib.Path', 'Path', (['"""tests"""', '"""data"""', '"""test.csv"""'], {}), "('tests', 'data', 'test.csv')\n", (155, 184), False, 'from pathlib import Path\n'), ((267, 292... |
# -*- coding: utf-8 -*-
# Copyright © 2014-2017 <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 limitation
# the rights to use, copy, modify... | [
"nikola.utils.get_logger",
"os.path.normpath",
"os.path.join",
"nikola.utils.config_changed",
"nikola.utils.apply_filters"
] | [((1290, 1355), 'nikola.utils.get_logger', 'utils.get_logger', (['"""render_static_tag_cloud"""', 'utils.STDERR_HANDLER'], {}), "('render_static_tag_cloud', utils.STDERR_HANDLER)\n", (1306, 1355), False, 'from nikola import utils\n'), ((3499, 3534), 'os.path.normpath', 'os.path.normpath', (['(os.sep + url_part)'], {}),... |
import pyeccodes.accessors as _
def load(h):
_.Template('grib1/mars_labeling.def').load(h)
h.add(_.Constant('GRIBEXSection1Problem', (80 - _.Get('section1Length'))))
h.add(_.Unsigned('number', 1))
h.alias('perturbationNumber', 'number')
h.add(_.Unsigned('ensembleSize', 1))
h.alias('totalNumbe... | [
"pyeccodes.accessors.Unsigned",
"pyeccodes.accessors.Pad",
"pyeccodes.accessors.Template",
"pyeccodes.accessors.Get"
] | [((187, 210), 'pyeccodes.accessors.Unsigned', '_.Unsigned', (['"""number"""', '(1)'], {}), "('number', 1)\n", (197, 210), True, 'import pyeccodes.accessors as _\n'), ((266, 295), 'pyeccodes.accessors.Unsigned', '_.Unsigned', (['"""ensembleSize"""', '(1)'], {}), "('ensembleSize', 1)\n", (276, 295), True, 'import pyeccod... |
from railrl.launchers.launcher_util import run_experiment
import railrl.misc.hyperparameter as hyp
from railrl.launchers.experiments.murtaza.rfeatures_rl import state_td3bc_experiment
from railrl.launchers.arglauncher import run_variants
if __name__ == "__main__":
variant = dict(
env_id='SawyerPushNIPSEas... | [
"railrl.launchers.arglauncher.run_variants",
"railrl.misc.hyperparameter.DeterministicHyperparameterSweeper"
] | [((1684, 1769), 'railrl.misc.hyperparameter.DeterministicHyperparameterSweeper', 'hyp.DeterministicHyperparameterSweeper', (['search_space'], {'default_parameters': 'variant'}), '(search_space, default_parameters=variant\n )\n', (1722, 1769), True, 'import railrl.misc.hyperparameter as hyp\n'), ((1891, 1947), 'railr... |
from scipy.integrate import solve_ivp
import numpy as np
import matplotlib.pyplot as plt
# Milne-Simpson PC method
def milnePC(def_fn, xa, xb, ya, N):
f = def_fn # intakes function to method to approximate
h = (xb - xa) / N # creates step size based on input values of a, b, N
t = np.arange(xa, xb + ... | [
"matplotlib.pyplot.title",
"numpy.abs",
"matplotlib.pyplot.show",
"matplotlib.pyplot.plot",
"matplotlib.pyplot.legend",
"numpy.zeros",
"matplotlib.pyplot.figure",
"numpy.arange",
"matplotlib.pyplot.ylabel",
"matplotlib.pyplot.xlabel"
] | [((301, 325), 'numpy.arange', 'np.arange', (['xa', '(xb + h)', 'h'], {}), '(xa, xb + h, h)\n', (310, 325), True, 'import numpy as np\n'), ((378, 396), 'numpy.zeros', 'np.zeros', (['(N + 1,)'], {}), '((N + 1,))\n', (386, 396), True, 'import numpy as np\n'), ((1381, 1405), 'numpy.arange', 'np.arange', (['xa', '(xb + h)',... |
# -*- coding: utf-8 -*-
"""
Created on Wed Jun 30 10:38:02 2021
@author: Oli
"""
#### Load
from model_interface.wham import WHAM
from Core_functionality.AFTs.agent_class import AFT
from Core_functionality.AFTs.arable_afts import Swidden, SOSH, MOSH, Intense_arable
from Core_functionality.AFTs.livestock_a... | [
"model_interface.wham.WHAM"
] | [((3028, 3044), 'model_interface.wham.WHAM', 'WHAM', (['parameters'], {}), '(parameters)\n', (3032, 3044), False, 'from model_interface.wham import WHAM\n')] |
#!/usr/bin/env python3
# -*- coding: utf-8 -*-
"""
Train or evaluate a single classifier with its given set of hyperparameters.
Created on Wed Sep 29 14:23:48 2021
@author: mkalcher, magmueller, shagemann
"""
import argparse
import pickle
from sklearn.dummy import DummyClassifier
from sklearn.naive_bayes import Mul... | [
"sklearn.pipeline.make_pipeline",
"sklearn.dummy.DummyClassifier",
"pickle.dump",
"sklearn.preprocessing.StandardScaler",
"argparse.ArgumentParser",
"sklearn.linear_model.SGDClassifier",
"sklearn.naive_bayes.MultinomialNB",
"sklearn.metrics.classification_report",
"sklearn.neighbors.KNeighborsClassi... | [((916, 965), 'argparse.ArgumentParser', 'argparse.ArgumentParser', ([], {'description': '"""Classifier"""'}), "(description='Classifier')\n", (939, 965), False, 'import argparse\n'), ((3442, 3459), 'pickle.load', 'pickle.load', (['f_in'], {}), '(f_in)\n', (3453, 3459), False, 'import pickle\n'), ((4199, 4216), 'pickle... |
import os
from dotenv import load_dotenv
basedir = os.path.abspath(os.path.dirname(__file__))
load_dotenv(os.path.join(basedir, '.env.flask'))
def env_to_bool(value, default=False):
if value is None:
return default
val = value.lower()
if val in ['false', 'f', 'no', 'n', '1']:
return False
elif val in ['true',... | [
"os.environ.get",
"os.path.dirname",
"os.path.join"
] | [((68, 93), 'os.path.dirname', 'os.path.dirname', (['__file__'], {}), '(__file__)\n', (83, 93), False, 'import os\n'), ((107, 142), 'os.path.join', 'os.path.join', (['basedir', '""".env.flask"""'], {}), "(basedir, '.env.flask')\n", (119, 142), False, 'import os\n'), ((511, 539), 'os.environ.get', 'os.environ.get', (['"... |
import os
APP_ROOT = os.path.abspath(os.path.join(os.path.dirname(os.path.abspath(__file__)), '../../../'))
# Absolute path to the directory that holds media.
# Example: "/home/media/media.lawrence.com/"
MEDIA_ROOT = APP_ROOT + '/media/upload'
STATIC_ROOT = APP_ROOT + '/resources'
# URL that handles the media served... | [
"os.path.abspath"
] | [((66, 91), 'os.path.abspath', 'os.path.abspath', (['__file__'], {}), '(__file__)\n', (81, 91), False, 'import os\n')] |
import requests
from django.db import models
from django.contrib.auth.models import AbstractBaseUser, BaseUserManager, \
PermissionsMixin
def find_region():
ip_to_region_dict = {
"US": "US-East"
}
ip_data = requests.get("https://ipinfo.io/ip", verify=False)
ip = ip_data.text.split('\n')[0... | [
"django.db.models.CharField",
"django.db.models.BooleanField",
"requests.get",
"django.db.models.EmailField"
] | [((234, 284), 'requests.get', 'requests.get', (['"""https://ipinfo.io/ip"""'], {'verify': '(False)'}), "('https://ipinfo.io/ip', verify=False)\n", (246, 284), False, 'import requests\n'), ((340, 403), 'requests.get', 'requests.get', (["('https://json.geoiplookup.io/' + ip)"], {'verify': '(False)'}), "('https://json.geo... |
from threading import Semaphore, Barrier
from time import sleep
class H2O:
def __init__(self):
self._h2o = Barrier(3)
self._atom_h = Semaphore(2)
self._atom_o = Semaphore(1)
pass
def hydrogen(self, releaseHydrogen: 'Callable[[], None]') -> None:... | [
"threading.Semaphore",
"threading.Barrier"
] | [((136, 146), 'threading.Barrier', 'Barrier', (['(3)'], {}), '(3)\n', (143, 146), False, 'from threading import Semaphore, Barrier\n'), ((173, 185), 'threading.Semaphore', 'Semaphore', (['(2)'], {}), '(2)\n', (182, 185), False, 'from threading import Semaphore, Barrier\n'), ((212, 224), 'threading.Semaphore', 'Semaphor... |
import os
import subprocess
from bsm.util import safe_rmdir
from bsm.util import expand_path
from bsm.logger import get_logger
_logger = get_logger()
class GitError(Exception):
pass
class GitNotFoundError(GitError):
pass
class GitUnknownCommandError(GitError):
pass
class GitEmptyUrlError(GitError):
... | [
"subprocess.Popen",
"os.path.join",
"bsm.logger.get_logger",
"bsm.util.expand_path"
] | [((139, 151), 'bsm.logger.get_logger', 'get_logger', ([], {}), '()\n', (149, 151), False, 'from bsm.logger import get_logger\n'), ((921, 1008), 'subprocess.Popen', 'subprocess.Popen', (['full_cmd'], {'stdout': 'subprocess.PIPE', 'stderr': 'subprocess.PIPE', 'cwd': 'cwd'}), '(full_cmd, stdout=subprocess.PIPE, stderr=sub... |
# -*- coding: utf-8 -*-
# pragma pylint: disable=unused-argument, no-self-use
# (c) Copyright IBM Corp. 2010, 2018. All Rights Reserved.
""" Resilient functions component to run an Umbrella investigate Query - Latest Malicious Domains for an IP against a
Cisco Umbrella server """
# Set up:
# Destination: a Queue nam... | [
"resilient_circuits.function",
"resilient_circuits.handler",
"resilient_circuits.StatusMessage",
"json.dumps",
"resilient_circuits.FunctionError",
"fn_cisco_umbrella_inv.util.helpers.process_params",
"fn_cisco_umbrella_inv.util.helpers.is_none",
"fn_cisco_umbrella_inv.util.helpers.validate_params",
... | [((1758, 1775), 'resilient_circuits.handler', 'handler', (['"""reload"""'], {}), "('reload')\n", (1765, 1775), False, 'from resilient_circuits import ResilientComponent, function, handler, StatusMessage, FunctionResult, FunctionError\n'), ((1945, 1993), 'resilient_circuits.function', 'function', (['"""umbrella_ip_lates... |
import logging
import tempfile
import validators
from pytube import YouTube
# Global variables are reused across execution contexts (if available)
logging.basicConfig(
format='%(asctime)s %(name)-25s %(levelname)-8s %(message)s',
level=logging.INFO)
logging.getLogger('boto3').setLevel(logging.ERROR)
logging.... | [
"logging.basicConfig",
"pytube.YouTube",
"validators.url",
"tempfile.mkdtemp",
"logging.getLogger"
] | [((150, 256), 'logging.basicConfig', 'logging.basicConfig', ([], {'format': '"""%(asctime)s %(name)-25s %(levelname)-8s %(message)s"""', 'level': 'logging.INFO'}), "(format=\n '%(asctime)s %(name)-25s %(levelname)-8s %(message)s', level=logging.INFO)\n", (169, 256), False, 'import logging\n'), ((372, 391), 'logging.... |
import json
from django.contrib.auth import get_user_model
from channels import Group
from .faucets.models import CoinSpawn, Faucet, Session
from .serializers import CoinSpawnSerializer
def ws_connect(message):
message.reply_channel.send({"accept": True})
Group('cryptoquest').add(message.reply_channel)
... | [
"channels.Group",
"django.contrib.auth.get_user_model",
"json.loads",
"json.dumps"
] | [((779, 806), 'json.loads', 'json.loads', (["message['text']"], {}), "(message['text'])\n", (789, 806), False, 'import json\n'), ((270, 290), 'channels.Group', 'Group', (['"""cryptoquest"""'], {}), "('cryptoquest')\n", (275, 290), False, 'from channels import Group\n'), ((478, 549), 'json.dumps', 'json.dumps', (["{'typ... |
from pydantic import BaseModel
from fastapi import APIRouter
from fastapi.responses import JSONResponse
import pymongo
import jwt
from config import db, SECRET_KEY
router = APIRouter(prefix='/api/admin')
account_collection = db.get_collection('accounts')
coin_collection = db.get_collection('coins')
class Dashboard(B... | [
"jwt.decode",
"config.db.get_collection",
"fastapi.responses.JSONResponse",
"fastapi.APIRouter"
] | [((175, 205), 'fastapi.APIRouter', 'APIRouter', ([], {'prefix': '"""/api/admin"""'}), "(prefix='/api/admin')\n", (184, 205), False, 'from fastapi import APIRouter\n'), ((227, 256), 'config.db.get_collection', 'db.get_collection', (['"""accounts"""'], {}), "('accounts')\n", (244, 256), False, 'from config import db, SEC... |
import sys
import traceback
from functools import reduce
from datetime import datetime
import sqlparse
import pprint
from django.db import models
from django.db import connection
from django.db.utils import OperationalError, ProgrammingError
from django.db.models import Q, F, ExpressionWrapper, Func, Case, When, Value
... | [
"sqlparse.format",
"logging.warning",
"django.db.models.Value",
"django.db.models.Q",
"django.db.connection.cursor",
"django.db.models.BooleanField",
"pprint.PrettyPrinter",
"django.db.models.F",
"sys.exc_info",
"functools.reduce",
"django.db.models.DateTimeField",
"traceback.extract_tb",
"d... | [((423, 450), 'logging.getLogger', 'logging.getLogger', (['"""django"""'], {}), "('django')\n", (440, 450), False, 'import logging\n'), ((462, 491), 'logging.getLogger', 'logging.getLogger', (['"""database"""'], {}), "('database')\n", (479, 491), False, 'import logging\n'), ((497, 527), 'pprint.PrettyPrinter', 'pprint.... |
# -*- coding: utf-8 -*-
"""
Handling IDs in a more secure way
"""
import uuid
def getUUID():
return str(uuid.uuid4())
def getUUIDfromString(string):
return str(uuid.uuid5(uuid.NAMESPACE_URL, string))
| [
"uuid.uuid4",
"uuid.uuid5"
] | [((112, 124), 'uuid.uuid4', 'uuid.uuid4', ([], {}), '()\n', (122, 124), False, 'import uuid\n'), ((174, 212), 'uuid.uuid5', 'uuid.uuid5', (['uuid.NAMESPACE_URL', 'string'], {}), '(uuid.NAMESPACE_URL, string)\n', (184, 212), False, 'import uuid\n')] |
from pipeline.utils import *
from pipeline.Step2.Evaluate_paddle import accuracy as accuracy_paddle
from pipeline.Step2.Evaluate_torch import accuracy as accuracy_torch
from pipeline.Step2.Evaluate_paddle import AverageMeter as AverageMeter_paddle
from pipeline.Step2.Evaluate_paddle import AverageMeter as AverageMeter... | [
"torch_py.test",
"paddle.concat",
"paddle.load",
"paddle.argmax",
"torch.nn.functional.cross_entropy",
"paddle.greater_equal",
"pipeline.Step2.Evaluate_paddle.AverageMeter",
"paddle.max",
"paddle.to_tensor",
"paddle_py.test"
] | [((1215, 1236), 'pipeline.Step2.Evaluate_paddle.AverageMeter', 'AverageMeter_paddle', ([], {}), '()\n', (1234, 1236), True, 'from pipeline.Step2.Evaluate_paddle import AverageMeter as AverageMeter_paddle\n'), ((1238, 1259), 'pipeline.Step2.Evaluate_paddle.AverageMeter', 'AverageMeter_paddle', ([], {}), '()\n', (1257, 1... |
import base64
import itertools
import re
import eml_parser
from bs4 import BeautifulSoup
CONTAINS_CID = re.compile(r'(?:src="cid:[^"]+")|(?:href="cid:[^"]+")')
CID = re.compile(r"^cid:(.+)$")
def substitute_xml(content, contents):
if isinstance(content, bytes):
content = base64.b64decode(content).decod... | [
"bs4.BeautifulSoup",
"eml_parser.EmlParser",
"base64.b64decode",
"re.compile"
] | [((107, 161), 're.compile', 're.compile', (['"""(?:src="cid:[^"]+")|(?:href="cid:[^"]+")"""'], {}), '(\'(?:src="cid:[^"]+")|(?:href="cid:[^"]+")\')\n', (117, 161), False, 'import re\n'), ((169, 193), 're.compile', 're.compile', (['"""^cid:(.+)$"""'], {}), "('^cid:(.+)$')\n", (179, 193), False, 'import re\n'), ((353, 38... |
#!/usr/bin/env python3
from os import environ
from common.helpers import read_xml, overwrite_file
from hdfs.helpers import process
if __name__ == '__main__':
conf_dir = environ.get( "CONF_DIR" ) if environ.get( "CONF_DIR" ) else "/opt/hbase/conf"
filename = "hbase-site.xml"
print( f"using configuration: ... | [
"os.environ.get",
"hdfs.helpers.process",
"common.helpers.overwrite_file",
"common.helpers.read_xml"
] | [((355, 383), 'common.helpers.read_xml', 'read_xml', (['conf_dir', 'filename'], {}), '(conf_dir, filename)\n', (363, 383), False, 'from common.helpers import read_xml, overwrite_file\n'), ((413, 425), 'hdfs.helpers.process', 'process', (['xml'], {}), '(xml)\n', (420, 425), False, 'from hdfs.helpers import process\n'), ... |