code stringlengths 22 1.05M | apis listlengths 1 3.31k | extract_api stringlengths 75 3.25M |
|---|---|---|
#!/usr/bin/python
#https://github.com/mitsuhiko/flask/tree/master/examples/flaskr
from flask import Flask, render_template, session, redirect, url_for, \
request, flash
from utils.logger import Logger
from query.query_parser import QueryParser
from db.mongodb import MongoDB
from pager import Pager
import pymongo, C... | [
"db.mongodb.MongoDB",
"flask.flash",
"flask.session.pop",
"flask.redirect",
"flask.Flask",
"query.query_parser.QueryParser",
"flask.url_for",
"utils.logger.Logger",
"flask.render_template",
"ConfigParser.ConfigParser",
"datetime.datetime.now"
] | [((445, 460), 'flask.Flask', 'Flask', (['__name__'], {}), '(__name__)\n', (450, 460), False, 'from flask import Flask, render_template, session, redirect, url_for, request, flash\n'), ((512, 539), 'ConfigParser.ConfigParser', 'ConfigParser.ConfigParser', ([], {}), '()\n', (537, 539), False, 'import pymongo, ConfigParse... |
from rasa.nlu.convert import convert_training_data
convert_training_data(data_file="./input.json", out_file="./nlu.md", output_format="md", language="") | [
"rasa.nlu.convert.convert_training_data"
] | [((51, 156), 'rasa.nlu.convert.convert_training_data', 'convert_training_data', ([], {'data_file': '"""./input.json"""', 'out_file': '"""./nlu.md"""', 'output_format': '"""md"""', 'language': '""""""'}), "(data_file='./input.json', out_file='./nlu.md',\n output_format='md', language='')\n", (72, 156), False, 'from r... |
import re
import string
years = [str(x) for x in range(1990, 2200)]
number_re = re.compile(r'^\-?[0-9]*\.?[0-9]*$')
regex_trailing_As = re.compile(r'(?:\s*A\s*)*$')
regex_punctuation = ''
for c in string.punctuation:
regex_punctuation += f'\\{c}'
split_using_punctuation_re = re.compile(r'\w+|' + f'{regex_punctua... | [
"re.compile"
] | [((82, 118), 're.compile', 're.compile', (['"""^\\\\-?[0-9]*\\\\.?[0-9]*$"""'], {}), "('^\\\\-?[0-9]*\\\\.?[0-9]*$')\n", (92, 118), False, 'import re\n'), ((138, 167), 're.compile', 're.compile', (['"""(?:\\\\s*A\\\\s*)*$"""'], {}), "('(?:\\\\s*A\\\\s*)*$')\n", (148, 167), False, 'import re\n'), ((283, 327), 're.compil... |
import numpy as np
import matplotlib.pyplot as plt
import cv2
import sys
# read the image
image = cv2.imread(sys.argv[1])
# convert to grayscale
grayscale = cv2.cvtColor(image, cv2.COLOR_BGR2GRAY)
# perform edge detection
edges = cv2.Canny(grayscale, 30, 100)
# detect lines in the image using hough li... | [
"cv2.line",
"cv2.Canny",
"matplotlib.pyplot.show",
"cv2.cvtColor",
"matplotlib.pyplot.imshow",
"cv2.imread",
"numpy.array"
] | [((105, 128), 'cv2.imread', 'cv2.imread', (['sys.argv[1]'], {}), '(sys.argv[1])\n', (115, 128), False, 'import cv2\n'), ((168, 207), 'cv2.cvtColor', 'cv2.cvtColor', (['image', 'cv2.COLOR_BGR2GRAY'], {}), '(image, cv2.COLOR_BGR2GRAY)\n', (180, 207), False, 'import cv2\n'), ((245, 274), 'cv2.Canny', 'cv2.Canny', (['grays... |
import torch
a = torch.cuda.is_available()
print (a) | [
"torch.cuda.is_available"
] | [((17, 42), 'torch.cuda.is_available', 'torch.cuda.is_available', ([], {}), '()\n', (40, 42), False, 'import torch\n')] |
import tensorflow
from tensorflow.keras.datasets import cifar10
from tensorflow import keras
import numpy as np
num_classes = 10
class EvalDataset(object):
def __init__(self, batch_size=100):
(x_train, y_train), (x_test, y_test) = cifar10.load_data()
x_train = x_train.astype('float32') / 255
... | [
"tensorflow.keras.utils.to_categorical",
"neural_compressor.experimental.Benchmark",
"tensorflow.keras.datasets.cifar10.load_data",
"neural_compressor.experimental.common.Model",
"numpy.mean"
] | [((1031, 1058), 'neural_compressor.experimental.Benchmark', 'Benchmark', (['"""benchmark.yaml"""'], {}), "('benchmark.yaml')\n", (1040, 1058), False, 'from neural_compressor.experimental import Benchmark, common\n'), ((1077, 1109), 'neural_compressor.experimental.common.Model', 'common.Model', (['"""./baseline_model"""... |
# Copyright 2019-2020 Lawrence Livermore National Security, LLC and other
# Archspec Project Developers. See the top-level COPYRIGHT file for details.
#
# SPDX-License-Identifier: (Apache-2.0 OR MIT)
"""Global objects with the content of the microarchitecture
JSON file and its schema
"""
import json
import os.path
try... | [
"json.load"
] | [((1616, 1631), 'json.load', 'json.load', (['file'], {}), '(file)\n', (1625, 1631), False, 'import json\n')] |
#OUTDATED
#The current version of this file uses full genes and not constructed genes
#Finds nearest gene in domains that DHS intergenic site has membership in
#domains_with_full_genes_#.csv generated from gene_analsysis.py
#DHS_with_domains.csv generated in domain_analsysis.py
#Exports DHS_#_nearest_full_gene_dista... | [
"pandas.DataFrame",
"time.process_time"
] | [((4567, 4597), 'pandas.DataFrame', 'pd.DataFrame', (['DHS_and_distance'], {}), '(DHS_and_distance)\n', (4579, 4597), True, 'import pandas as pd\n'), ((4781, 4800), 'time.process_time', 'time.process_time', ([], {}), '()\n', (4798, 4800), False, 'import time\n')] |
## Read subset data .csv labels
## and get united filename-tokens format separated by comma for Word2Vec.
import os
import re
import sys
import warnings
import numpy as np
from PIL import Image
from config import Config
if __name__ == '__main__':
SUBSET_LIST = ['deviantart_verified', 'wikiart_verified']
FR... | [
"os.makedirs",
"config.Config",
"warnings.filterwarnings",
"PIL.Image.open",
"os.path.isfile",
"os.path.join",
"re.sub"
] | [((529, 567), 'os.makedirs', 'os.makedirs', (['OUTPUT_DIR'], {'exist_ok': '(True)'}), '(OUTPUT_DIR, exist_ok=True)\n', (540, 567), False, 'import os\n'), ((586, 628), 'os.path.join', 'os.path.join', (['OUTPUT_DIR', '"""all_labels.csv"""'], {}), "(OUTPUT_DIR, 'all_labels.csv')\n", (598, 628), False, 'import os\n'), ((63... |
"""
Miscellaneous utility functions and common data.
Attributes:
common_formulas: A set of common formulas. The keys to the data are strings
from :obj:`pymatgen.core.composition.Composition.reduced_formula`.
connected_geometries: A list of geometries that are considered
"connectable" polyhedra.... | [
"pymatgen.util.string.latexify_spacegroup",
"pymatgen.core.periodic_table.get_el_sp",
"monty.serialization.loadfn",
"pkg_resources.resource_filename",
"pymatgen.core.periodic_table.Element.from_Z",
"re.sub"
] | [((1001, 1061), 'pkg_resources.resource_filename', 'resource_filename', (['"""robocrys.condense"""', '"""formula_db.json.gz"""'], {}), "('robocrys.condense', 'formula_db.json.gz')\n", (1018, 1061), False, 'from pkg_resources import resource_filename\n'), ((4507, 4525), 'pymatgen.core.periodic_table.get_el_sp', 'get_el_... |
# -*- coding: utf-8 -*-
"""
Tencent is pleased to support the open source community by making BK-BASE 蓝鲸基础平台 available.
Copyright (C) 2021 THL A29 Limited, a Tencent company. All rights reserved.
BK-BASE 蓝鲸基础平台 is licensed under the MIT License.
License for BK-BASE 蓝鲸基础平台:
------------------------------------------... | [
"bkbase.dataflow.one_model.metric.monitor_handler.MonitorHandler.get_rt_count",
"bkbase.dataflow.one_model.utils.deeplearning_logger.logger.info",
"importlib.import_module",
"bkbase.dataflow.one_model.exception.tensorflow_exception.TensorFlowReportException",
"bkbase.dataflow.one_model.utils.deeplearning_lo... | [((2385, 2434), 'bkbase.dataflow.one_model.utils.deeplearning_logger.logger.info', 'deeplearning_logger.info', (['"""Pipeline source start"""'], {}), "('Pipeline source start')\n", (2409, 2434), True, 'from bkbase.dataflow.one_model.utils.deeplearning_logger import logger as deeplearning_logger\n'), ((2521, 2568), 'bkb... |
from django.http import HttpResponsePermanentRedirect, HttpResponseNotFound, HttpResponseBadRequest
from django.core.files.storage import default_storage
from easy_thumbnails.files import get_thumbnailer
from easy_thumbnails.exceptions import InvalidImageFormatError
import re
SIZE_RE = re.compile(r'^(\d+),(\d+)$')
... | [
"django.core.files.storage.default_storage.url",
"django.http.HttpResponseBadRequest",
"easy_thumbnails.files.get_thumbnailer",
"django.http.HttpResponseNotFound",
"django.http.HttpResponsePermanentRedirect",
"re.compile"
] | [((289, 318), 're.compile', 're.compile', (['"""^(\\\\d+),(\\\\d+)$"""'], {}), "('^(\\\\d+),(\\\\d+)$')\n", (299, 318), False, 'import re\n'), ((862, 900), 'easy_thumbnails.files.get_thumbnailer', 'get_thumbnailer', (['default_storage', 'path'], {}), '(default_storage, path)\n', (877, 900), False, 'from easy_thumbnails... |
import ast, gast
import inspect
import numpy as np
import sys
import typing
from chainer_compiler.elichika.typing import types
from chainer_compiler.elichika.typing.type_inference import InferenceEngine
from chainer_compiler.elichika.typing.utils import node_description, is_expr
from chainer_compiler.elichika.parser i... | [
"chainer_compiler.elichika.typing.type_inference.InferenceEngine",
"numpy.random.seed",
"argparse.ArgumentParser",
"chainer_compiler.elichika.typing.utils.is_expr",
"typing.get_type_hints",
"numpy.zeros",
"inspect.getsource",
"chainer.functions.pad_sequence",
"ast.parse",
"chainer_compiler.elichik... | [((1137, 1186), 'chainer_compiler.elichika.typing.type_inference.InferenceEngine', 'InferenceEngine', ([], {'is_debug': 'is_debug', 'module': 'module'}), '(is_debug=is_debug, module=module)\n', (1152, 1186), False, 'from chainer_compiler.elichika.typing.type_inference import InferenceEngine\n'), ((3532, 3550), 'numpy.r... |
#!/bin/python3
#https://docs.python.org/3/howto/sockets.html
import sys
import socket
from datetime import datetime
if len(sys.argv) == 2:
target = socket.gethostbyname(sys.argv[1]) # traslate to ipv4
else:
print("invalid amoount of args")
print("syntax: pyhon3 scanner.py <ip>")
exit()
print("banner"... | [
"socket.socket",
"socket.gethostbyname",
"socket.setdefaulttimeout",
"datetime.datetime.now",
"sys.exit"
] | [((154, 187), 'socket.gethostbyname', 'socket.gethostbyname', (['sys.argv[1]'], {}), '(sys.argv[1])\n', (174, 187), False, 'import socket\n'), ((498, 547), 'socket.socket', 'socket.socket', (['socket.AF_INET', 'socket.SOCK_STREAM'], {}), '(socket.AF_INET, socket.SOCK_STREAM)\n', (511, 547), False, 'import socket\n'), (... |
import dash_core_components as dcc
import dash_html_components as html
import dash_bootstrap_components as dbc
##==================================
## Selectors
##==================================
out = dbc.Col([
dbc.Row([
# Class selector (what differentiates the data)
dbc.Col([
... | [
"dash_html_components.P",
"dash_core_components.Dropdown"
] | [((362, 384), 'dash_html_components.P', 'html.P', (['"""Classes: """'], {}), "('Classes: ')\n", (368, 384), True, 'import dash_html_components as html\n'), ((532, 624), 'dash_core_components.Dropdown', 'dcc.Dropdown', ([], {'id': '"""pca-class-select"""', 'options': '[]', 'placeholder': '"""Select..."""', 'cleara... |
#!/usr/bin/env python3
# MIT License
#
# Copyright (c) 2020 FABRIC Testbed
#
# 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 ... | [
"fim.slivers.attached_components.ComponentSliver",
"uuid.uuid4",
"fim.slivers.network_node.CompositeNodeSliver",
"collections.defaultdict",
"fim.graph.networkx_property_graph.NetworkXGraphImporter",
"fim.slivers.capacities_labels.Capacities"
] | [((3293, 3305), 'fim.slivers.capacities_labels.Capacities', 'Capacities', ([], {}), '()\n', (3303, 3305), False, 'from fim.slivers.capacities_labels import Capacities\n'), ((3346, 3363), 'collections.defaultdict', 'defaultdict', (['dict'], {}), '(dict)\n', (3357, 3363), False, 'from collections import defaultdict\n'), ... |
#!/usr/bin/env python
#
# Copyright (c) 2015 10X Genomics, Inc. All rights reserved.
#
import cPickle
from collections import defaultdict
from itertools import izip
import json
import numpy as np
import cellranger.constants as cr_constants
import cellranger.library_constants as lib_constants
from cellranger.molecule_co... | [
"numpy.absolute",
"numpy.random.seed",
"numpy.sum",
"cPickle.load",
"collections.defaultdict",
"cellranger.molecule_counter.MoleculeCounter.estimate_mem_gb",
"numpy.arange",
"numpy.fromiter",
"cellranger.molecule_counter.MoleculeCounter.open",
"cellranger.rna.library.get_library_type_metric_prefix... | [((1651, 1696), 'cellranger.molecule_counter.MoleculeCounter.open', 'MoleculeCounter.open', (['args.molecule_info', '"""r"""'], {}), "(args.molecule_info, 'r')\n", (1671, 1696), False, 'from cellranger.molecule_counter import MoleculeCounter\n'), ((1938, 1954), 'collections.defaultdict', 'defaultdict', (['int'], {}), '... |
import contextlib
import logging
import requests
from os.path import join, isfile
from django.apps import apps
from django.conf import settings
from django.db.models import Q
from django.http import Http404
from django.template.response import TemplateResponse
from django.utils.translation import get_language
import ... | [
"bs4.NavigableString",
"django.db.models.Q",
"contextlib.suppress",
"apps.questionnaire.models.Questionnaire.with_status.not_deleted",
"os.path.isfile",
"django.apps.apps.get_app_config",
"requests.get",
"apps.questionnaire.utils.get_query_status_filter",
"bs4.BeautifulSoup",
"django.utils.transla... | [((836, 863), 'logging.getLogger', 'logging.getLogger', (['__name__'], {}), '(__name__)\n', (853, 863), False, 'import logging\n'), ((1315, 1361), 'os.path.join', 'join', (['settings.SUMMARY_PDF_PATH', 'self.filename'], {}), '(settings.SUMMARY_PDF_PATH, self.filename)\n', (1319, 1361), False, 'from os.path import join,... |
# Copyright (c) 2003, 2004 <NAME>
# contributions by <NAME>
# contributions by <NAME>
import sys
import types
import os
import hashlib
import dparser_swigc
class user_pyobjectsPtr:
def __init__(self, this):
self.this = this
def __setattr__(self, name, value):
if name == "t":
self... | [
"dparser_swigc.d_get_child",
"dparser_swigc.my_D_ParseNode_end_skip_get",
"dparser_swigc.my_D_ParseNode_symbol_get",
"sys.exc_info",
"os.path.join",
"dparser_swigc.d_get_number_of_children",
"dparser_swigc.my_D_ParseNode_end_set",
"os.path.dirname",
"os.path.exists",
"dparser_swigc.my_d_loc_t_s_ge... | [((4036, 4086), 'dparser_swigc.add_parse_tree_viewer', 'dparser_swigc.add_parse_tree_viewer', (['self.d_parser'], {}), '(self.d_parser)\n', (4071, 4086), False, 'import dparser_swigc\n'), ((4119, 4172), 'dparser_swigc.remove_parse_tree_viewer', 'dparser_swigc.remove_parse_tree_viewer', (['self.d_parser'], {}), '(self.d... |
from __future__ import unicode_literals
from django.contrib import admin
from djangoapps.features.models import Feature
class FeatureAdmin(admin.ModelAdmin):
list_display = ('id', 'active', 'feature_en', 'feature_es', 'description_en', 'description_es', 'created_at')
search_fields = ('feature_es',)
... | [
"django.contrib.admin.site.register"
] | [((350, 392), 'django.contrib.admin.site.register', 'admin.site.register', (['Feature', 'FeatureAdmin'], {}), '(Feature, FeatureAdmin)\n', (369, 392), False, 'from django.contrib import admin\n')] |
# -*- coding: utf-8 -*-
# @Author: <NAME>
# @Date: 2018-09-18 13:25:04
# @Last Modified by: <NAME>
# @Last Modified time: 2018-09-18 13:35:04
"""
CUSTOM ESTIMATOR AS DECORATORS for Scikit-Learn Pipelines
"""
from sklearn.base import BaseEstimator, TransformerMixin, ClassifierMixin
import pandas as pd
class SKTr... | [
"sklearn.pipeline.Pipeline",
"numpy.array"
] | [((1813, 1843), 'sklearn.pipeline.Pipeline', 'Pipeline', (['[power2, lessThan50]'], {}), '([power2, lessThan50])\n', (1821, 1843), False, 'from sklearn.pipeline import Pipeline\n'), ((1906, 1929), 'numpy.array', 'np.array', (['[3, 6, 8, 10]'], {}), '([3, 6, 8, 10])\n', (1914, 1929), True, 'import numpy as np\n')] |
import os
import urllib
import datetime
from google.appengine.api import users
from google.appengine.ext import ndb
import jinja2
import webapp2
JINJA_ENVIRONMENT = jinja2.Environment(
loader=jinja2.FileSystemLoader(os.path.dirname(__file__)),
extensions=['jinja2.ext.autoescape'],
autoescape=True)
#Models... | [
"google.appengine.api.users.get_current_user",
"os.path.dirname",
"webapp2.WSGIApplication",
"google.appengine.api.users.create_login_url",
"google.appengine.api.users.create_logout_url"
] | [((1346, 1400), 'webapp2.WSGIApplication', 'webapp2.WSGIApplication', (["[('/', MainPage)]"], {'debug': '(True)'}), "([('/', MainPage)], debug=True)\n", (1369, 1400), False, 'import webapp2\n'), ((442, 466), 'google.appengine.api.users.get_current_user', 'users.get_current_user', ([], {}), '()\n', (464, 466), False, 'f... |
from jina import Executor, Document, DocumentArray, requests
from transformers import (
AutoTokenizer,
AutoModelForQuestionAnswering,
pipeline,
)
class Generator(Executor):
answer_model_name = "deepset/roberta-base-squad2"
answer_model = AutoModelForQuestionAnswering.from_pretrained(answer_model_n... | [
"transformers.AutoTokenizer.from_pretrained",
"jina.Document",
"transformers.AutoModelForQuestionAnswering.from_pretrained",
"transformers.pipeline"
] | [((260, 324), 'transformers.AutoModelForQuestionAnswering.from_pretrained', 'AutoModelForQuestionAnswering.from_pretrained', (['answer_model_name'], {}), '(answer_model_name)\n', (305, 324), False, 'from transformers import AutoTokenizer, AutoModelForQuestionAnswering, pipeline\n'), ((348, 396), 'transformers.AutoToken... |
import logging
from .s3_base_url import S3BaseUrl
from ..base import BaseDirectoryUrl, BaseFileUrl
from typing import IO, List, Optional
import threading
from time import sleep
from s3_concat import S3Concat
from smart_open.s3 import open as s3_open
logger = logging.getLogger(__name__)
class S3FileUrl(S3BaseUrl, Ba... | [
"time.sleep",
"threading.Lock",
"smart_open.s3.open",
"s3_concat.S3Concat",
"logging.getLogger"
] | [((261, 288), 'logging.getLogger', 'logging.getLogger', (['__name__'], {}), '(__name__)\n', (278, 288), False, 'import logging\n'), ((4743, 4828), 's3_concat.S3Concat', 'S3Concat', (['self.bucket', 'self.key'], {'session': 'self._boto3_session', 'min_file_size': 'None'}), '(self.bucket, self.key, session=self._boto3_se... |
# -*- coding: utf-8 -*-
from datetime import datetime
from peewee import Model, ForeignKeyField, CharField, DateTimeField
class VisitorModel(Model):
class Meta:
table_name = 'visitor'
indexes = (
(('name', 'ip_addr'), True),
)
name = CharField()
ip_addr = CharField()
... | [
"peewee.CharField",
"peewee.DateTimeField",
"peewee.ForeignKeyField"
] | [((282, 293), 'peewee.CharField', 'CharField', ([], {}), '()\n', (291, 293), False, 'from peewee import Model, ForeignKeyField, CharField, DateTimeField\n'), ((308, 319), 'peewee.CharField', 'CharField', ([], {}), '()\n', (317, 319), False, 'from peewee import Model, ForeignKeyField, CharField, DateTimeField\n'), ((335... |
# Copyright (C) 2010 Google Inc. All rights reserved.
#
# Redistribution and use in source and binary forms, with or without
# modification, are permitted provided that the following conditions are
# met:
#
# * Redistributions of source code must retain the above copyright
# notice, this list of conditions and the ... | [
"webkitpy.layout_tests.port.win.WinPort.latest_platform_fallback_path",
"logging.getLogger"
] | [((1723, 1750), 'logging.getLogger', 'logging.getLogger', (['__name__'], {}), '(__name__)\n', (1740, 1750), False, 'import logging\n'), ((1921, 1964), 'webkitpy.layout_tests.port.win.WinPort.latest_platform_fallback_path', 'win.WinPort.latest_platform_fallback_path', ([], {}), '()\n', (1962, 1964), False, 'from webkitp... |
import os
import sys
sys.path.insert(0, os.path.abspath('../..'))
from hq.output import convert_results_to_output_text
from hq.soup_util import make_soup
from hq.hquery.hquery_processor import HqueryProcessor
from ..common_test_util import expected_result
from test.hquery.hquery_test_util import query_html_doc
def... | [
"hq.soup_util.make_soup",
"os.path.abspath",
"hq.output.convert_results_to_output_text",
"hq.hquery.hquery_processor.HqueryProcessor",
"test.hquery.hquery_test_util.query_html_doc"
] | [((41, 65), 'os.path.abspath', 'os.path.abspath', (['"""../.."""'], {}), "('../..')\n", (56, 65), False, 'import os\n'), ((400, 485), 'test.hquery.hquery_test_util.query_html_doc', 'query_html_doc', (['"""<div>one</div><p>not a div</p><div>two</div>"""', '"""/html/body/div"""'], {}), "('<div>one</div><p>not a div</p><d... |
from setuptools import find_packages, setup
with open('README.rst') as f:
readme = f.read()
with open('LICENSE.txt') as f:
license = f.read()
setup(
name = 'unhashlib',
version = '0.1.0',
description = 'A string class enhancement',
long_description = readme,
#license = license,
packag... | [
"setuptools.find_packages"
] | [((323, 363), 'setuptools.find_packages', 'find_packages', ([], {'exclude': "('tests', 'docs')"}), "(exclude=('tests', 'docs'))\n", (336, 363), False, 'from setuptools import find_packages, setup\n')] |
"""
Helper functions file for working with object buckets
"""
import logging
import os
import shlex
from uuid import uuid4
import boto3
from botocore.handlers import disable_signing
from ocs_ci.framework import config
from ocs_ci.ocs import constants
from ocs_ci.ocs.exceptions import TimeoutExpiredError, UnexpectedBe... | [
"uuid.uuid4",
"ocs_ci.utility.ssl_certs.get_root_ca_cert",
"ocs_ci.utility.utils.run_cmd",
"ocs_ci.framework.config.DEPLOYMENT.get",
"ocs_ci.utility.templating.load_yaml",
"ocs_ci.helpers.helpers.create_resource",
"ocs_ci.ocs.resources.pod.get_rgw_pods",
"boto3.resource",
"os.getenv",
"logging.get... | [((538, 565), 'logging.getLogger', 'logging.getLogger', (['__name__'], {}), '(__name__)\n', (555, 565), False, 'import logging\n'), ((4334, 4354), 'boto3.resource', 'boto3.resource', (['"""s3"""'], {}), "('s3')\n", (4348, 4354), False, 'import boto3\n'), ((7020, 7034), 'ocs_ci.ocs.resources.pod.get_rgw_pods', 'get_rgw_... |
#!/usr/bin/env python
#
from __future__ import print_function
import argparse
import struct
import sys
class bcolors:
HEADER = '\033[95m'
OKBLUE = '\033[94m'
OKGREEN = '\033[92m'
WARNING = '\033[93m'
FAIL = '\033[91m'
ENDC = '\033[0m'
BOLD = '\033[1m'
UNDERLINE = '\03... | [
"argparse.ArgumentParser",
"sys.exit"
] | [((499, 564), 'argparse.ArgumentParser', 'argparse.ArgumentParser', ([], {'description': '"""ESP32 App Trace Parse Tool"""'}), "(description='ESP32 App Trace Parse Tool')\n", (522, 564), False, 'import argparse\n'), ((1272, 1283), 'sys.exit', 'sys.exit', (['(2)'], {}), '(2)\n', (1280, 1283), False, 'import sys\n'), ((3... |
from django.db import models
CONTENT_TYPE=(
('html','html'),
('text','text')
)
class Newsletter(models.Model):
title=models.CharField(max_length=500)
content_type=models.CharField(choices=CONTENT_TYPE,max_length=30)
content=models.TextField()
subscribers=models.ManyToManyField('Subcriber',blan... | [
"django.db.models.TextField",
"django.db.models.ManyToManyField",
"django.db.models.CharField",
"django.db.models.EmailField",
"django.db.models.DateTimeField"
] | [((131, 163), 'django.db.models.CharField', 'models.CharField', ([], {'max_length': '(500)'}), '(max_length=500)\n', (147, 163), False, 'from django.db import models\n'), ((181, 234), 'django.db.models.CharField', 'models.CharField', ([], {'choices': 'CONTENT_TYPE', 'max_length': '(30)'}), '(choices=CONTENT_TYPE, max_l... |
"""Global fixtures for Porsche Connect integration."""
from typing import Any
from unittest.mock import patch
import pytest
from pyporscheconnectapi.exceptions import WrongCredentials
# from unittest.mock import Mock
pytest_plugins = "pytest_homeassistant_custom_component"
# This fixture is used to prevent HomeAss... | [
"unittest.mock.patch",
"pytest.fixture"
] | [((517, 572), 'pytest.fixture', 'pytest.fixture', ([], {'name': '"""skip_notifications"""', 'autouse': '(True)'}), "(name='skip_notifications', autouse=True)\n", (531, 572), False, 'import pytest\n'), ((827, 895), 'pytest.fixture', 'pytest.fixture', ([], {'name': '"""auto_enable_custom_integrations"""', 'autouse': '(Tr... |
# vim: expandtab:ts=4:sw=4
from __future__ import absolute_import
import numpy as np
import pdb
from . import kf_2d, kf_3d, double_measurement_kf, imm
from . import linear_assignment
from . import iou_matching
from .track import Track
from . import JPDA_matching
from . import tracking_utils
import math
from nn_matching... | [
"numpy.dstack",
"nn_matching.NearestNeighborDistanceMetric",
"numpy.asarray",
"numpy.array",
"numpy.linalg.norm",
"cv2.calcOpticalFlowFarneback",
"numpy.dot"
] | [((2036, 2089), 'nn_matching.NearestNeighborDistanceMetric', 'NearestNeighborDistanceMetric', (['"""euclidean"""', 'nn_budget'], {}), "('euclidean', nn_budget)\n", (2065, 2089), False, 'from nn_matching import NearestNeighborDistanceMetric\n'), ((3126, 3179), 'numpy.array', 'np.array', (['[tracks[i].track_id for i in t... |
from os.path import join as pjoin
from glob import glob
import os
from tinydb import TinyDB
def pk(doc, pk_extra):
pk_doc = {"path": tuple(doc["path"]), "gold": doc["gold"]}
if "opts" in doc:
pk_doc.update(doc["opts"])
if pk_extra is not None:
pk_doc.update(pk_extra(doc))
return freeze... | [
"os.path.isdir",
"tinydb.TinyDB",
"os.path.join"
] | [((1163, 1175), 'tinydb.TinyDB', 'TinyDB', (['path'], {}), '(path)\n', (1169, 1175), False, 'from tinydb import TinyDB\n'), ((1273, 1295), 'os.path.isdir', 'os.path.isdir', (['db_path'], {}), '(db_path)\n', (1286, 1295), False, 'import os\n'), ((1330, 1358), 'os.path.join', 'pjoin', (['db_path', '"""**"""', '"""*.db"""... |
from setuptools import setup
with open('README.md', 'r') as f:
long_description = f.read()
setup(
name='s3-tar',
packages=['s3_tar'],
version='0.1.13',
description='Tar (and compress) files in s3',
long_description=long_description,
long_description_content_type='text/markdown',
autho... | [
"setuptools.setup"
] | [((98, 685), 'setuptools.setup', 'setup', ([], {'name': '"""s3-tar"""', 'packages': "['s3_tar']", 'version': '"""0.1.13"""', 'description': '"""Tar (and compress) files in s3"""', 'long_description': 'long_description', 'long_description_content_type': '"""text/markdown"""', 'author': '"""<NAME>"""', 'author_email': '"... |
# coding: utf-8
import re
import six
from huaweicloudsdkcore.sdk_response import SdkResponse
from huaweicloudsdkcore.utils.http_utils import sanitize_for_serialization
class ShowJobResponse(SdkResponse):
"""
Attributes:
openapi_types (dict): The key is attribute name
and... | [
"huaweicloudsdkcore.utils.http_utils.sanitize_for_serialization",
"six.iteritems",
"sys.setdefaultencoding"
] | [((7692, 7725), 'six.iteritems', 'six.iteritems', (['self.openapi_types'], {}), '(self.openapi_types)\n', (7705, 7725), False, 'import six\n'), ((8710, 8741), 'sys.setdefaultencoding', 'sys.setdefaultencoding', (['"""utf-8"""'], {}), "('utf-8')\n", (8732, 8741), False, 'import sys\n'), ((8768, 8800), 'huaweicloudsdkcor... |
import numcodecs
import pytest
import zarr
from zarr.util import InfoReporter
@pytest.mark.parametrize('array_size', [10, 15000])
def test_info(array_size):
# setup
g = zarr.group(store=dict(), chunk_store=dict(),
synchronizer=zarr.ThreadSynchronizer())
g.create_group('foo')
z = g... | [
"numcodecs.Adler32",
"pytest.mark.parametrize",
"zarr.ThreadSynchronizer"
] | [((82, 132), 'pytest.mark.parametrize', 'pytest.mark.parametrize', (['"""array_size"""', '[10, 15000]'], {}), "('array_size', [10, 15000])\n", (105, 132), False, 'import pytest\n'), ((258, 283), 'zarr.ThreadSynchronizer', 'zarr.ThreadSynchronizer', ([], {}), '()\n', (281, 283), False, 'import zarr\n'), ((361, 380), 'nu... |
#!/usr/bin/env python
"""
Script that goes through all the users in a DB
and renames their names with random ones.
"""
import sqlalchemy
import zeeguu
from faker import Faker
fake = Faker()
from zeeguu.model import User
session = zeeguu.db.session
for user in User.query.all():
for _ in range(0,13):
... | [
"zeeguu.model.User.query.all",
"faker.Faker"
] | [((192, 199), 'faker.Faker', 'Faker', ([], {}), '()\n', (197, 199), False, 'from faker import Faker\n'), ((272, 288), 'zeeguu.model.User.query.all', 'User.query.all', ([], {}), '()\n', (286, 288), False, 'from zeeguu.model import User\n')] |
#!/usr/bin/env python
"""The setup script."""
from setuptools import setup, find_packages
with open("README.rst") as readme_file:
readme = readme_file.read()
with open("CHANGELOG.rst") as history_file:
history = history_file.read()
# requirements = ['Click>=7.0', ]
requirements = list(map(str.strip, open("... | [
"setuptools.find_packages"
] | [((1381, 1452), 'setuptools.find_packages', 'find_packages', ([], {'include': "['virtual_finance_api', 'virtual_finance_api.*']"}), "(include=['virtual_finance_api', 'virtual_finance_api.*'])\n", (1394, 1452), False, 'from setuptools import setup, find_packages\n')] |
# mbedRPC.py - mbed RPC interface for Python
#
# Copyright (c) 2010 ARM Ltd
#
# 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 right... | [
"serial.Serial",
"time.sleep"
] | [((7735, 7748), 'time.sleep', 'time.sleep', (['s'], {}), '(s)\n', (7745, 7748), False, 'import time\n'), ((2335, 2354), 'serial.Serial', 'serial.Serial', (['port'], {}), '(port)\n', (2348, 2354), False, 'import serial\n')] |
"""PhoSim Instance Catalog"""
from __future__ import absolute_import, division, print_function
import numpy as np
from lsst.sims.catUtils.exampleCatalogDefinitions import (PhoSimCatalogZPoint,
PhoSimCatalogPoint,
... | [
"lsst.sims.catalogs.db.CompoundCatalogDBObject",
"numpy.array"
] | [((2155, 2176), 'numpy.array', 'np.array', (['split_names'], {}), '(split_names)\n', (2163, 2176), True, 'import numpy as np\n'), ((6160, 6199), 'lsst.sims.catalogs.db.CompoundCatalogDBObject', 'CompoundCatalogDBObject', (['dbObjClassList'], {}), '(dbObjClassList)\n', (6183, 6199), False, 'from lsst.sims.catalogs.db im... |
"""
:maintainer: <NAME> <<EMAIL>>
:maturity: new
:depends: None
:platform: Linux
.. versionadded:: 3004
"""
import logging
import re
import salt.exceptions
log = logging.getLogger(__name__)
def __virtual__():
"""rebootmgrctl command is required."""
if __utils__["path.which"]("rebootmgrc... | [
"re.search",
"logging.getLogger"
] | [((185, 212), 'logging.getLogger', 'logging.getLogger', (['__name__'], {}), '(__name__)\n', (202, 212), False, 'import logging\n'), ((6044, 6094), 're.search', 're.search', (['"""Etcd lock group is set to (.*)"""', 'group'], {}), "('Etcd lock group is set to (.*)', group)\n", (6053, 6094), False, 'import re\n'), ((5360... |
# coding=utf-8
"""
The NfsCollector collects nfs utilization metrics using /proc/net/rpc/nfs.
#### Dependencies
* /proc/net/rpc/nfs
"""
import diamond.collector
import os
class NfsCollector(diamond.collector.Collector):
PROC = '/proc/net/rpc/nfs'
def get_default_config_help(self):
config_help ... | [
"os.access"
] | [((810, 839), 'os.access', 'os.access', (['self.PROC', 'os.R_OK'], {}), '(self.PROC, os.R_OK)\n', (819, 839), False, 'import os\n')] |
import datetime
from pytest_cases import THIS_MODULE, parametrize_with_cases
from statue.cli import statue_cli
from tests.util import evaluation_mock
def case_empty_history():
additional_flags = []
evaluations = []
output = "No previous evaluations.\n"
return additional_flags, evaluations, output
... | [
"pytest_cases.parametrize_with_cases",
"tests.util.evaluation_mock",
"datetime.datetime"
] | [((5888, 5989), 'pytest_cases.parametrize_with_cases', 'parametrize_with_cases', ([], {'argnames': "['additional_flags', 'evaluations', 'output']", 'cases': 'THIS_MODULE'}), "(argnames=['additional_flags', 'evaluations',\n 'output'], cases=THIS_MODULE)\n", (5910, 5989), False, 'from pytest_cases import THIS_MODULE, ... |
from __future__ import annotations
from typing import NamedTuple
class Fold(NamedTuple):
dim: str
val: int
class Paper:
def __init__(self, marks: list[list[bool]]) -> None:
self.marks = marks
self.height, self.width = len(marks), len(marks[0])
def mark(self, i: int, j: int) -> None... | [
"_common.main"
] | [((2282, 2300), '_common.main', 'main', (['part1', 'part2'], {}), '(part1, part2)\n', (2286, 2300), False, 'from _common import main\n')] |
# MODULE: TypeRig / Core / Collection (Functions)
# -----------------------------------------------------------
# (C) <NAME>, 2017-2021 (http://www.kateliev.com)
# (C) Karandash Type Foundry (http://www.karandash.eu)
#------------------------------------------------------------
# www.typerig.com
# No warranties. By... | [
"itertools.chain",
"itertools.islice"
] | [((1288, 1305), 'itertools.chain', 'chain', (['*listItems'], {}), '(*listItems)\n', (1293, 1305), False, 'from itertools import chain\n'), ((3126, 3155), 'itertools.islice', 'islice', (['iterator', 'window_size'], {}), '(iterator, window_size)\n', (3132, 3155), False, 'from itertools import islice\n')] |
from typing import List, Dict, Any, Optional
import logging
from collections import Counter
from reval.dataset_utils import train_val_split
from reval.probing_task_example import ProbingTaskExample
logger = logging.getLogger(__name__)
def generate_task_examples(
data: List[Dict[str, Any]],
argument: str,
... | [
"collections.Counter",
"reval.dataset_utils.train_val_split",
"reval.probing_task_example.ProbingTaskExample",
"logging.getLogger"
] | [((209, 236), 'logging.getLogger', 'logging.getLogger', (['__name__'], {}), '(__name__)\n', (226, 236), False, 'import logging\n'), ((2583, 2592), 'collections.Counter', 'Counter', ([], {}), '()\n', (2590, 2592), False, 'from collections import Counter\n'), ((3133, 3201), 'collections.Counter', 'Counter', (['[idx2pos[e... |
#!/usr/bin/env python
# imports
import json # weather data
import time # time data
import urllib # fixing urls
from includes import epd2in13b # e ink library
import Image # Image manipulation
import ImageFont # Text Writing
import ImageDraw ... | [
"json.loads",
"urllib.parse.urlencode",
"includes.epd2in13b.EPD",
"os.path.dirname",
"Image.open",
"time.strftime",
"ImageFont.truetype",
"requests.get",
"urllib.urlencode",
"os.path.join"
] | [((1817, 1832), 'includes.epd2in13b.EPD', 'epd2in13b.EPD', ([], {}), '()\n', (1830, 1832), False, 'from includes import epd2in13b\n'), ((2013, 2090), 'ImageFont.truetype', 'ImageFont.truetype', (['"""/usr/share/fonts/truetype/freefont/FreeSansBold.ttf"""', '(35)'], {}), "('/usr/share/fonts/truetype/freefont/FreeSansBol... |
# coding: utf-8
from __future__ import print_function, division, absolute_import
import pytest
from cutadapt.seqio import Sequence
from cutadapt.adapters import (Adapter, Match, ColorspaceAdapter, FRONT, BACK,
parse_braces, LinkedAdapter, AdapterStatistics, AdapterParser)
def test_issue_52():
adapter = Adapter(
... | [
"cutadapt.adapters.Adapter",
"cutadapt.adapters.ColorspaceAdapter",
"cutadapt.adapters.parse_braces",
"cutadapt.adapters.Match",
"cutadapt.seqio.Sequence",
"pytest.raises",
"cutadapt.adapters.LinkedAdapter"
] | [((309, 445), 'cutadapt.adapters.Adapter', 'Adapter', ([], {'sequence': '"""GAACTCCAGTCACNNNNN"""', 'where': 'BACK', 'max_error_rate': '(0.12)', 'min_overlap': '(5)', 'read_wildcards': '(False)', 'adapter_wildcards': '(True)'}), "(sequence='GAACTCCAGTCACNNNNN', where=BACK, max_error_rate=0.12,\n min_overlap=5, read_... |
#!/usr/bin/python
# Copyright (c) Microsoft Corporation
# All rights reserved.
#
# MIT License
#
# 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 limitatio... | [
"traceback.print_exc",
"os.getpid",
"xml.dom.minidom.parseString",
"subprocess.check_output",
"json.dumps",
"time.sleep",
"os.umask",
"os.path.join",
"time.localtime"
] | [((1332, 1488), 'subprocess.check_output', 'subprocess.check_output', (['"""wmic process where "CommandLine like \'%nni_gpu_tool.gpu_metrics_collector%\' and name like \'%python%\'" get processId"""'], {}), '(\n \'wmic process where "CommandLine like \\\'%nni_gpu_tool.gpu_metrics_collector%\\\' and name like \\\'%py... |
#!/usr/bin/env python
# Licensed to Cloudera, Inc. under one
# or more contributor license agreements. See the NOTICE file
# distributed with this work for additional information
# regarding copyright ownership. Cloudera, Inc. licenses this file
# to you under the Apache License, Version 2.0 (the
# "License"); you ma... | [
"libsentry.sentry_site.get_sentry_server_admin_groups",
"json.dumps",
"libsentry.sentry_site.get_hive_sentry_provider"
] | [((2020, 2063), 'json.dumps', 'json.dumps', (["{'user': request.user.username}"], {}), "({'user': request.user.username})\n", (2030, 2063), False, 'import json\n'), ((1102, 1128), 'libsentry.sentry_site.get_hive_sentry_provider', 'get_hive_sentry_provider', ([], {}), '()\n', (1126, 1128), False, 'from libsentry.sentry_... |
# https://leetcode.com/problems/merge-two-sorted-lists/
import sys
class ListNode(object):
def __init__(self, x):
self.val = x
self.next = None
class Solution(object):
def mergeTwoLists(self, l1, l2):
head = last = None
def append(node):
nonlocal head... | [
"sys.stdin.readline"
] | [((1393, 1413), 'sys.stdin.readline', 'sys.stdin.readline', ([], {}), '()\n', (1411, 1413), False, 'import sys\n'), ((921, 941), 'sys.stdin.readline', 'sys.stdin.readline', ([], {}), '()\n', (939, 941), False, 'import sys\n')] |
"""
Defines a rule set using one of the standard Iguanas representations. This rule
set can then be reformatted into the other standard Iguanas representations
using the class methods.
"""
from iguanas.rules._convert_rule_dicts_to_rule_strings import _ConvertRuleDictsToRuleStrings
from iguanas.rules._convert_rule_str... | [
"iguanas.rule_application.RuleApplier.__init__",
"iguanas.rules._convert_rule_dicts_to_rule_strings._ConvertRuleDictsToRuleStrings",
"iguanas.rules._get_rule_attributes._GetRuleFeatures",
"iguanas.rules._convert_rule_strings_to_rule_dicts._ConvertRuleStringsToRuleDicts",
"iguanas.rules._convert_rule_lambdas... | [((4245, 4303), 'iguanas.rule_application.RuleApplier.__init__', 'RuleApplier.__init__', (['self'], {'rule_strings': 'self.rule_strings'}), '(self, rule_strings=self.rule_strings)\n', (4265, 4303), False, 'from iguanas.rule_application import RuleApplier\n'), ((7803, 7835), 'iguanas.rule_application.RuleApplier.transfo... |
from __future__ import print_function
import os
import glob
def NameFile(filepath):
if os.path.exists(filepath):
newname = FindLatestFilename(filepath)
else:
newname = filepath
print('Saving file as...', newname)
return newname
def FindLatestFilename(filepath):
if len(filepath.rsplit('/', 1)) == 2:
foldern... | [
"os.path.exists",
"os.path.join"
] | [((89, 113), 'os.path.exists', 'os.path.exists', (['filepath'], {}), '(filepath)\n', (103, 113), False, 'import os\n'), ((1836, 1870), 'os.path.join', 'os.path.join', (['foldername', 'filename'], {}), '(foldername, filename)\n', (1848, 1870), False, 'import os\n')] |
from sqlalchemy.orm import relationship, backref
from sqlalchemy import (
Column,
String,
ForeignKey,
Float,
Integer,
DateTime,
Boolean
)
from sqlalchemy.orm import relationship
from libs.database import Base
from apps.account.models import Account, AccountPosition
from apps.m... | [
"sqlalchemy.DateTime",
"sqlalchemy.ForeignKey",
"sqlalchemy.orm.relationship",
"sqlalchemy.Boolean",
"sqlalchemy.Column",
"sqlalchemy.String",
"sqlalchemy.orm.backref",
"sqlalchemy.Integer"
] | [((1030, 1063), 'sqlalchemy.Column', 'Column', (['Integer'], {'primary_key': '(True)'}), '(Integer, primary_key=True)\n', (1036, 1063), False, 'from sqlalchemy import Column, String, ForeignKey, Float, Integer, DateTime, Boolean\n'), ((1403, 1418), 'sqlalchemy.Column', 'Column', (['Integer'], {}), '(Integer)\n', (1409,... |
import FWCore.ParameterSet.Config as cms
from Configuration.Eras.Modifier_run2_common_cff import run2_common
from Configuration.Eras.Modifier_run2_25ns_specific_cff import run2_25ns_specific
from Configuration.Eras.Modifier_stage2L1Trigger_cff import stage2L1Trigger
from Configuration.Eras.Modifier_ctpps_2016_cff impo... | [
"FWCore.ParameterSet.Config.ModifierChain"
] | [((419, 517), 'FWCore.ParameterSet.Config.ModifierChain', 'cms.ModifierChain', (['run2_common', 'run2_25ns_specific', 'stage2L1Trigger', 'ctpps_2016', 'run2_jme_2016'], {}), '(run2_common, run2_25ns_specific, stage2L1Trigger,\n ctpps_2016, run2_jme_2016)\n', (436, 517), True, 'import FWCore.ParameterSet.Config as cm... |
from threading import Thread, Event
from .stream import StreamIO
from ..buffers import SortingRingBuffer
from ..compat import queue
class SegmentedStreamWorker(Thread):
"""The general worker thread.
This thread is responsible for queueing up segments in the
writer thread.
"""
def __init__(self... | [
"threading.Thread.__init__",
"threading.Event"
] | [((678, 699), 'threading.Thread.__init__', 'Thread.__init__', (['self'], {}), '(self)\n', (693, 699), False, 'from threading import Thread, Event\n'), ((1164, 1171), 'threading.Event', 'Event', ([], {}), '()\n', (1169, 1171), False, 'from threading import Thread, Event\n'), ((2518, 2539), 'threading.Thread.__init__', '... |
#!/usr/bin/env python3
import itertools
from docs import εὕρηκα
def render_graph(𝛹):
color_palette = ["#72e5ef", "#fb2076", "#69ef7b", "#f365e7",
"#54a32f", "#bf9fff", "#c0e15c", "#753fc2",
"#e78607", "#8a0458", "#1c5e39", "#e46981",
"#509f87", "#db3c... | [
"docs.εὕρηκα.get_magic_numbers",
"itertools.product"
] | [((878, 908), 'itertools.product', 'itertools.product', (['Ψ'], {'repeat': '(3)'}), '(Ψ, repeat=3)\n', (895, 908), False, 'import itertools\n'), ((1056, 1082), 'docs.εὕρηκα.get_magic_numbers', 'εὕρηκα.get_magic_numbers', ([], {}), '()\n', (1080, 1082), False, 'from docs import εὕρηκα\n')] |
import shutil
import pytest # noqa
from pytest_factoryboy import register
from atv.tests.conftest import * # noqa
from services.tests.conftest import * # noqa
from users.tests.conftest import * # noqa
from .factories import AttachmentFactory, DocumentFactory
@pytest.fixture(autouse=True)
def custom_media_dir_f... | [
"shutil.rmtree",
"pytest.fixture",
"pytest_factoryboy.register"
] | [((269, 297), 'pytest.fixture', 'pytest.fixture', ([], {'autouse': '(True)'}), '(autouse=True)\n', (283, 297), False, 'import pytest\n'), ((594, 619), 'pytest_factoryboy.register', 'register', (['DocumentFactory'], {}), '(DocumentFactory)\n', (602, 619), False, 'from pytest_factoryboy import register\n'), ((620, 647), ... |
import math
from torch.optim.lr_scheduler import _LRScheduler
class CosineAnnealingWithRestartsLR(_LRScheduler):
"""Set the learning rate of each parameter group using a cosine annealing
schedule, where :math:`\eta_{max}` is set to the initial lr and
:math:`T_{cur}` is the number of epochs since the last... | [
"math.cos"
] | [((1648, 1700), 'math.cos', 'math.cos', (['(math.pi * self.step_n / self.restart_every)'], {}), '(math.pi * self.step_n / self.restart_every)\n', (1656, 1700), False, 'import math\n')] |
from layered_vision.utils.dist import get_required_and_extras
class TestGetRequiredAndExtras:
def test_should_group_single_requirement(self):
assert get_required_and_extras(
[('req1==1.2.3', ['group1'])]
) == (
[],
{'group1': ['req1==1.2.3'], 'all': ['req1==1.2.... | [
"layered_vision.utils.dist.get_required_and_extras"
] | [((163, 217), 'layered_vision.utils.dist.get_required_and_extras', 'get_required_and_extras', (["[('req1==1.2.3', ['group1'])]"], {}), "([('req1==1.2.3', ['group1'])])\n", (186, 217), False, 'from layered_vision.utils.dist import get_required_and_extras\n'), ((398, 448), 'layered_vision.utils.dist.get_required_and_extr... |
# more or less the same simulation, but split up in to chunks that fit into memory
# for large states (CA, IA, KS, OK, TX)
# chunks of size 2000 (2000 locations in one part calculated and create temporary file)
location_chunk = 2000
import argparse
import datetime
import glob
import math
import numpy as np
import os
i... | [
"sys.path.append",
"os.mkdir",
"os.remove",
"argparse.ArgumentParser",
"pandas.read_csv",
"xarray.open_rasterio",
"os.path.exists",
"time.time",
"dask.diagnostics.ProgressBar",
"numpy.arange",
"pandas.to_datetime",
"glob.glob",
"xarray.open_mfdataset"
] | [((457, 479), 'sys.path.append', 'sys.path.append', (['"""../"""'], {}), "('../')\n", (472, 479), False, 'import sys\n'), ((766, 836), 'argparse.ArgumentParser', 'argparse.ArgumentParser', ([], {'description': '"""Insert state and optionally GWA"""'}), "(description='Insert state and optionally GWA')\n", (789, 836), Fa... |
"""
tcp连接接收数据
"""
# TCPclient.py
import socket
class TcpClient:
def __init__(self):
self.target_host = "192.168.3.11" # 服务器端地址
self.target_port = 3389 # 必须与服务器的端口号一致
def start(self):
while True:
client = socket.socket(socket.AF_INET,socket.SOCK_STREAM)
cli... | [
"socket.socket"
] | [((256, 305), 'socket.socket', 'socket.socket', (['socket.AF_INET', 'socket.SOCK_STREAM'], {}), '(socket.AF_INET, socket.SOCK_STREAM)\n', (269, 305), False, 'import socket\n')] |
from django.contrib import admin
from django.urls import path, include
from . import views
urlpatterns = [
path('', views.home, name='home'),
path('news', views.news, name='flash_info'),
path('login', views.login_view, name='login'),
path('logout', views.logout_view, name='logout'),
path('article... | [
"django.urls.path"
] | [((114, 147), 'django.urls.path', 'path', (['""""""', 'views.home'], {'name': '"""home"""'}), "('', views.home, name='home')\n", (118, 147), False, 'from django.urls import path, include\n'), ((153, 196), 'django.urls.path', 'path', (['"""news"""', 'views.news'], {'name': '"""flash_info"""'}), "('news', views.news, nam... |
"""OVK learning, unit tests.
The :mod:`sklearn.tests.test_semisuo` tests semisup module.
"""
import operalib as ovk
import numpy as np
def test_semisup_linop():
"""Test ovk.semisup.SemisupLinop."""
np.random.seed()
n = 100
p = 5
lbda2 = .1
# supervised indices
B = np.random.randint(2, ... | [
"numpy.random.seed",
"numpy.sum",
"numpy.random.randn",
"numpy.empty",
"numpy.random.randint",
"numpy.dot",
"operalib.ridge._SemisupLinop"
] | [((210, 226), 'numpy.random.seed', 'np.random.seed', ([], {}), '()\n', (224, 226), True, 'import numpy as np\n'), ((383, 393), 'numpy.sum', 'np.sum', (['(~B)'], {}), '(~B)\n', (389, 393), True, 'import numpy as np\n'), ((402, 435), 'numpy.random.randn', 'np.random.randn', (['n_unsup', 'n_unsup'], {}), '(n_unsup, n_unsu... |
import canmatrix.formats
from canmatrix.canmatrix import CanId
def list_pgn(db):
"""
:param db:
:return: pgn and id
"""
id = [x.Id for x in db.frames]
r = [CanId(t).tuples() for t in id]
return [t[1] for t in r], id
def ids_sharing_same_pgn(id_x, pgn_x, id_y, pgn_y):
for idx, pgnx i... | [
"canmatrix.canmatrix.CanId"
] | [((183, 191), 'canmatrix.canmatrix.CanId', 'CanId', (['t'], {}), '(t)\n', (188, 191), False, 'from canmatrix.canmatrix import CanId\n'), ((1497, 1514), 'canmatrix.canmatrix.CanId', 'CanId', (['frameSc.Id'], {}), '(frameSc.Id)\n', (1502, 1514), False, 'from canmatrix.canmatrix import CanId\n'), ((2647, 2665), 'canmatrix... |
# /usr/bin/env python3
import numpy as np
def operadores():
a=np.random.randint(3,10,size=10)
b=np.random.randint(4,78,size=10)
print(np.add(a,b))
print(np.subtract(b,a))
print(np.negative(a,b))
print(np.multiply(a,b))
print(np.divide(a,b))
print(np.floor_divide(b,a))
prin... | [
"numpy.divide",
"numpy.multiply",
"numpy.subtract",
"numpy.floor_divide",
"numpy.power",
"numpy.negative",
"numpy.mod",
"numpy.random.randint",
"numpy.add"
] | [((69, 102), 'numpy.random.randint', 'np.random.randint', (['(3)', '(10)'], {'size': '(10)'}), '(3, 10, size=10)\n', (86, 102), True, 'import numpy as np\n'), ((108, 141), 'numpy.random.randint', 'np.random.randint', (['(4)', '(78)'], {'size': '(10)'}), '(4, 78, size=10)\n', (125, 141), True, 'import numpy as np\n'), (... |
from django.urls import path
from . import views
urlpatterns = [
path('rt_value', views.get_rt_value),
path('generate_json',views.generate_json),
path('latest_rt_value', views.latest_rt),
path('before_15_rt', views.before_15_rt),
path('doubling_growth_value', views.doubling_growth_data),
path(... | [
"django.urls.path"
] | [((71, 107), 'django.urls.path', 'path', (['"""rt_value"""', 'views.get_rt_value'], {}), "('rt_value', views.get_rt_value)\n", (75, 107), False, 'from django.urls import path\n'), ((113, 155), 'django.urls.path', 'path', (['"""generate_json"""', 'views.generate_json'], {}), "('generate_json', views.generate_json)\n", (... |
# coding:utf8
import json
import os
import re
import requests
STOCK_CODE_PATH = 'stock_codes.conf'
def update_stock_codes():
"""获取所有股票 ID 到 all_stock_code 目录下"""
all_stock_codes_url = 'http://www.shdjt.com/js/lib/astock.js'
grep_stock_codes = re.compile('~(\d+)`')
response = requests.get(all_stock_c... | [
"os.path.dirname",
"json.load",
"requests.get",
"re.compile"
] | [((259, 281), 're.compile', 're.compile', (['"""~(\\\\d+)`"""'], {}), "('~(\\\\d+)`')\n", (269, 281), False, 'import re\n'), ((296, 329), 'requests.get', 'requests.get', (['all_stock_codes_url'], {}), '(all_stock_codes_url)\n', (308, 329), False, 'import requests\n'), ((692, 714), 're.compile', 're.compile', (['"""~(\\... |
# coding: utf-8
import struct
from common.constDefine import *
from logger.log import logger
def send(cmd, proto, session, table=None):
result = proto.SerializeToString()
fmt = ">iib{0}s".format(len(result))
data = struct.pack(fmt, len(result)+9, cmd, COMMUNICATION_TYPE, result)
try:
session.... | [
"logger.log.logger.error"
] | [((377, 392), 'logger.log.logger.error', 'logger.error', (['e'], {}), '(e)\n', (389, 392), False, 'from logger.log import logger\n')] |
import os
from pathlib import Path
class Config:
_10x_eula_cookie_key = "sw-eula-full"
@property
def ten_x_eula_cookie_key(self) -> str:
return type(self)._10x_eula_cookie_key
def __init__(self):
self.path_home = os.path.join(Path.home(), ".scing")
self.path_10x_eula_cfg = o... | [
"pathlib.Path.home",
"os.path.join",
"os.makedirs",
"os.path.exists"
] | [((319, 363), 'os.path.join', 'os.path.join', (['self.path_home', '"""10x-eula.cfg"""'], {}), "(self.path_home, '10x-eula.cfg')\n", (331, 363), False, 'import os\n'), ((372, 414), 'os.makedirs', 'os.makedirs', (['self.path_home'], {'exist_ok': '(True)'}), '(self.path_home, exist_ok=True)\n', (383, 414), False, 'import ... |
import CONFIG
import torch
import torch.nn as nn
class LSTMModel(nn.Module):
def __init__(
self,
vocab_size,
embed_dims,
hidden_dims,
num_layers,
dropout,
bidirectional,
num_pos_class,
num_tag_class
):
super(LSTMModel, self).__in... | [
"torch.nn.Dropout",
"torch.nn.GRU",
"torch.nn.Embedding",
"torch.nn.Linear"
] | [((352, 388), 'torch.nn.Embedding', 'nn.Embedding', (['vocab_size', 'embed_dims'], {}), '(vocab_size, embed_dims)\n', (364, 388), True, 'import torch.nn as nn\n'), ((408, 530), 'torch.nn.GRU', 'nn.GRU', (['embed_dims', 'hidden_dims'], {'num_layers': 'num_layers', 'batch_first': '(True)', 'dropout': 'dropout', 'bidirect... |
#!/usr/bin/python3
import io
import utils
from block import Block, BlockHeader
with open('../../../usb-decrypted/bitcoin/blocks/blk00001.dat', 'rb') as block_reader:
block_reader.seek(0, io.SEEK_END)
fSize = block_reader.tell() - 80
block_reader.seek(0, io.SEEK_SET)
block = Block(block_reader)
block.transa... | [
"hashlib.sha256",
"block.Block"
] | [((287, 306), 'block.Block', 'Block', (['block_reader'], {}), '(block_reader)\n', (292, 306), False, 'from block import Block, BlockHeader\n'), ((1174, 1202), 'hashlib.sha256', 'hashlib.sha256', (['target_bytes'], {}), '(target_bytes)\n', (1188, 1202), False, 'import hashlib\n')] |
# -*- coding: utf-8 -*-
from collections import OrderedDict
from gluon import current
from gluon.storage import Storage
def config(settings):
"""
Settings for UCCE: User-Centred Community Engagement
A project for Oxfam & Save the Children run with Eclipse Experience
"""
T = current.T
... | [
"gluon.IS_IN_SET",
"templates.UCCE.controllers.dc_TargetReport",
"templates.UCCE.controllers.dc_TargetL10n",
"templates.UCCE.controllers.dc_QuestionImageUpload",
"core.S3SQLCustomForm",
"templates.UCCE.controllers.dc_TemplateImportL10n",
"core.IS_ISO639_2_LANGUAGE_CODE",
"templates.UCCE.controllers.dc... | [((2513, 2585), 'collections.OrderedDict', 'OrderedDict', (["[('en-gb', 'English'), ('es', 'Spanish'), ('so', 'Somali')]"], {}), "([('en-gb', 'English'), ('es', 'Spanish'), ('so', 'Somali')])\n", (2524, 2585), False, 'from collections import OrderedDict\n'), ((12230, 12252), 'core.s3_rheader_resource', 's3_rheader_reso... |
"""This module creates a new dataframe with a movie id and its corresponding
mean sentiment score. Mean sentiment score is computed by taking the average of
the sentiment scores for all the movie's comments
"""
from os import listdir
import os.path as op
import pandas as pd
import numpy as np
from .analyze_comments_tb... | [
"pandas.DataFrame",
"pandas.read_csv",
"numpy.asarray",
"os.path.join",
"os.listdir"
] | [((389, 435), 'os.path.join', 'op.join', (['mv.__path__[0]', '"""data/movie_comments"""'], {}), "(mv.__path__[0], 'data/movie_comments')\n", (396, 435), True, 'import os.path as op\n'), ((577, 630), 'pandas.DataFrame', 'pd.DataFrame', ([], {'columns': "['movie_id', 'sentiment_score']"}), "(columns=['movie_id', 'sentime... |
#!/usr/bin/env python3
# -*- coding: utf-8 -*-
"""
Created on Thu Jul 19 10:51:10 2018
@author: shlomi
"""
import platform
from pathlib import Path
path = Path().cwd()
if platform.system() == 'Linux':
if platform.node() == 'ziskin-XPS-8700':
work_path = Path('/home/ziskin/Work_Files/')
work_yuval =... | [
"platform.system",
"pathlib.Path",
"platform.node"
] | [((172, 189), 'platform.system', 'platform.system', ([], {}), '()\n', (187, 189), False, 'import platform\n'), ((156, 162), 'pathlib.Path', 'Path', ([], {}), '()\n', (160, 162), False, 'from pathlib import Path\n'), ((209, 224), 'platform.node', 'platform.node', ([], {}), '()\n', (222, 224), False, 'import platform\n')... |
from maggma.api.query_operator import PaginationQuery, SparseFieldsQuery
from maggma.api.resource import ReadOnlyResource
from emmet.core.phonon import PhononBSDOSDoc
def phonon_bsdos_resource(phonon_bs_store):
resource = ReadOnlyResource(
phonon_bs_store,
PhononBSDOSDoc,
query_operators=... | [
"maggma.api.query_operator.SparseFieldsQuery",
"maggma.api.query_operator.PaginationQuery"
] | [((334, 351), 'maggma.api.query_operator.PaginationQuery', 'PaginationQuery', ([], {}), '()\n', (349, 351), False, 'from maggma.api.query_operator import PaginationQuery, SparseFieldsQuery\n'), ((365, 442), 'maggma.api.query_operator.SparseFieldsQuery', 'SparseFieldsQuery', (['PhononBSDOSDoc'], {'default_fields': "['ta... |
from datetime import datetime
import numpy as np
import warnings
__author__ = '<NAME>'
__email__ = '<EMAIL>'
__created__ = datetime(2008, 8, 15)
__modified__ = datetime(2015, 7, 25)
__version__ = "1.5"
__status__ = "Development"
'''
Various vertical coordinates
Presently, only ocean s-coordinates are suppo... | [
"numpy.tanh",
"numpy.empty",
"numpy.asarray",
"numpy.zeros",
"datetime.datetime",
"numpy.arange",
"numpy.exp",
"numpy.squeeze",
"warnings.warn",
"numpy.cosh",
"numpy.sinh"
] | [((131, 152), 'datetime.datetime', 'datetime', (['(2008)', '(8)', '(15)'], {}), '(2008, 8, 15)\n', (139, 152), False, 'from datetime import datetime\n'), ((168, 189), 'datetime.datetime', 'datetime', (['(2015)', '(7)', '(25)'], {}), '(2015, 7, 25)\n', (176, 189), False, 'from datetime import datetime\n'), ((1891, 1904)... |
import sys
import pytest
import numpy as np
from numpy.testing import assert_array_equal, IS_PYPY
class TestDLPack:
@pytest.mark.skipif(IS_PYPY, reason="PyPy can't get refcounts.")
def test_dunder_dlpack_refcount(self):
x = np.arange(5)
y = x.__dlpack__()
assert sys.getrefcount(x) == ... | [
"numpy.datetime64",
"numpy.testing.assert_array_equal",
"numpy.dtype",
"numpy.zeros",
"numpy.ones",
"sys.getrefcount",
"pytest.raises",
"pytest.mark.skipif",
"numpy.arange",
"numpy._from_dlpack",
"numpy.array",
"pytest.mark.parametrize",
"numpy.diagonal"
] | [((124, 187), 'pytest.mark.skipif', 'pytest.mark.skipif', (['IS_PYPY'], {'reason': '"""PyPy can\'t get refcounts."""'}), '(IS_PYPY, reason="PyPy can\'t get refcounts.")\n', (142, 187), False, 'import pytest\n'), ((808, 871), 'pytest.mark.skipif', 'pytest.mark.skipif', (['IS_PYPY'], {'reason': '"""PyPy can\'t get refcou... |
# Copyright 2012 <NAME>
# Copyright 2008 (C) Nicira, Inc.
#
# This file is part of POX.
#
# POX is free software: you can redistribute it and/or modify
# it under the terms of the GNU General Public License as published by
# the Free Software Foundation, either version 3 of the License, or
# (at your option) any later ... | [
"packet_base.packet_base.__init__",
"struct.unpack"
] | [((2286, 2312), 'packet_base.packet_base.__init__', 'packet_base.__init__', (['self'], {}), '(self)\n', (2306, 2312), False, 'from packet_base import packet_base\n'), ((3184, 3226), 'struct.unpack', 'struct.unpack', (['"""!BBHi"""', 'raw[:self.MIN_LEN]'], {}), "('!BBHi', raw[:self.MIN_LEN])\n", (3197, 3226), False, 'im... |
#! /usr/bin/env python
# -*- coding: utf-8 -*-
"""
Python objects for modeling Consumer Price Index (CPI) data structures.
"""
import collections
from datetime import date
from pandas import json_normalize
# CPI tools
from .errors import CPIObjectDoesNotExist
from .defaults import DEFAULTS_SERIES_ATTRS
# Logging
impo... | [
"pandas.json_normalize",
"datetime.date",
"logging.NullHandler",
"collections.OrderedDict",
"logging.getLogger"
] | [((340, 367), 'logging.getLogger', 'logging.getLogger', (['__name__'], {}), '(__name__)\n', (357, 367), False, 'import logging\n'), ((386, 407), 'logging.NullHandler', 'logging.NullHandler', ([], {}), '()\n', (405, 407), False, 'import logging\n'), ((1930, 1964), 'pandas.json_normalize', 'json_normalize', (['dict_list'... |
import logging
from monai.apps.deepgrow.interaction import Interaction
from monai.apps.deepgrow.transforms import (
AddGuidanceSignald,
AddInitialSeedPointd,
AddRandomGuidanced,
FindAllValidSlicesd,
FindDiscrepancyRegionsd,
SpatialCropForegroundd,
)
from monai.inferers import SimpleInferer
from... | [
"monai.transforms.AddChanneld",
"monai.transforms.ToNumpyd",
"monai.apps.deepgrow.transforms.AddGuidanceSignald",
"monai.transforms.LoadImaged",
"monai.transforms.AsChannelFirstd",
"monai.transforms.Orientationd",
"monai.inferers.SimpleInferer",
"monai.transforms.NormalizeIntensityd",
"monai.apps.de... | [((738, 765), 'logging.getLogger', 'logging.getLogger', (['__name__'], {}), '(__name__)\n', (755, 765), False, 'import logging\n'), ((2006, 2047), 'monai.losses.DiceLoss', 'DiceLoss', ([], {'sigmoid': '(True)', 'squared_pred': '(True)'}), '(sigmoid=True, squared_pred=True)\n', (2014, 2047), False, 'from monai.losses im... |
# -*- coding: utf-8 -*-
"""
Created on Sat Apr 4 07:10:55 2020
@author: sj
"""
import numpy as np
# left corner as (0,0), US in West and Asia in East
# only validated in Asia, North and East
#x as latitude (180), y as longitude (360),
# x = 114288 # latitude, filepath
# y = 214078 # longitude, filena... | [
"numpy.power",
"numpy.floor",
"numpy.sinh"
] | [((444, 458), 'numpy.power', 'np.power', (['(2)', 'z'], {}), '(2, z)\n', (452, 458), True, 'import numpy as np\n'), ((686, 699), 'numpy.floor', 'np.floor', (['lat'], {}), '(lat)\n', (694, 699), True, 'import numpy as np\n'), ((741, 754), 'numpy.floor', 'np.floor', (['tmp'], {}), '(tmp)\n', (749, 754), True, 'import num... |
# 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 u... | [
"os.environ.get",
"airflow.providers.google.cloud.transfers.gdrive_to_gcs.GoogleDriveToGCSOperator",
"unittest.mock.patch"
] | [((928, 978), 'os.environ.get', 'os.environ.get', (['"""GCP_GDRIVE_FOLDER_ID"""', '"""abcd1234"""'], {}), "('GCP_GDRIVE_FOLDER_ID', 'abcd1234')\n", (942, 978), False, 'import os\n'), ((990, 1039), 'os.environ.get', 'os.environ.get', (['"""GCP_GDRIVE_DRIVE_ID"""', '"""abcd1234"""'], {}), "('GCP_GDRIVE_DRIVE_ID', 'abcd12... |
from PIL import Image
import numpy as np
import sys, os
from progress_bar import ProgressBar
def get_bit(pos, img):
# avoids modifying thumbnail
size = img.shape[0]*img.shape[1] - 4096
rgb = pos//size
if rgb > 2:
raise IndexError("Position is too large")
pos = pos % size + 4096
x,y = po... | [
"progress_bar.ProgressBar",
"numpy.array",
"PIL.Image.open"
] | [((395, 418), 'PIL.Image.open', 'Image.open', (['sys.argv[1]'], {}), '(sys.argv[1])\n', (405, 418), False, 'from PIL import Image\n'), ((485, 498), 'numpy.array', 'np.array', (['img'], {}), '(img)\n', (493, 498), True, 'import numpy as np\n'), ((874, 891), 'progress_bar.ProgressBar', 'ProgressBar', (['size'], {}), '(si... |
from share.transform.chain import ChainTransformer, Parser, Delegate, RunPython, ParseDate, ParseName, Map, ctx, Try, Subjects, IRI, Concat
class Subject(Parser):
name = ctx
class ThroughSubjects(Parser):
subject = Delegate(Subject, ctx)
class Tag(Parser):
name = ctx
class ThroughTags(Parser):
t... | [
"share.transform.chain.Subjects",
"share.transform.chain.ParseDate",
"share.transform.chain.ctx",
"share.transform.chain.IRI",
"share.transform.chain.Try",
"share.transform.chain.Delegate",
"share.transform.chain.ParseName"
] | [((227, 249), 'share.transform.chain.Delegate', 'Delegate', (['Subject', 'ctx'], {}), '(Subject, ctx)\n', (235, 249), False, 'from share.transform.chain import ChainTransformer, Parser, Delegate, RunPython, ParseDate, ParseName, Map, ctx, Try, Subjects, IRI, Concat\n'), ((325, 343), 'share.transform.chain.Delegate', 'D... |
from jinja2 import FileSystemLoader, StrictUndefined
from jinja2.environment import Environment
from netmiko import ConnectHandler
from mydevices import nxos1, nxos2
from pprint import pprint
import textfsm
import time
import re
from colorama import Fore, Back, Style
env = Environment(undefined=StrictUndefined)
env.lo... | [
"re.compile",
"jinja2.environment.Environment",
"time.sleep",
"jinja2.FileSystemLoader",
"netmiko.ConnectHandler",
"textfsm.TextFSM"
] | [((275, 313), 'jinja2.environment.Environment', 'Environment', ([], {'undefined': 'StrictUndefined'}), '(undefined=StrictUndefined)\n', (286, 313), False, 'from jinja2.environment import Environment\n'), ((327, 359), 'jinja2.FileSystemLoader', 'FileSystemLoader', (['"""./templates/"""'], {}), "('./templates/')\n", (343... |
from typing import Text
from aiogram import types
from aiogram.dispatcher.filters.builtin import Text
from aiogram.dispatcher import FSMContext
from keyboards.default.admin_panel import admin_panel_kb
from middlewares.states.admin_panel_states import check_user
from utils.db_api import sql
from loader import dp
'''
d... | [
"utils.db_api.sql.check",
"loader.dp.message_handler"
] | [((428, 473), 'loader.dp.message_handler', 'dp.message_handler', ([], {'text': '"""/cancel"""', 'state': '"""*"""'}), "(text='/cancel', state='*')\n", (446, 473), False, 'from loader import dp\n'), ((636, 678), 'loader.dp.message_handler', 'dp.message_handler', ([], {'state': 'check_user.step1'}), '(state=check_user.st... |
import requests
from threading import Thread
from six.moves.queue import Queue
def flatten_kwargs(index, **kwargs):
kwargs = dict(kwargs)
for arg in kwargs:
if isinstance(kwargs[arg], list):
kwargs[arg] = kwargs[arg][index]
return kwargs
class WebRunner:
resp_queue = None
d... | [
"threading.Thread",
"requests.request",
"six.moves.queue.Queue"
] | [((365, 372), 'six.moves.queue.Queue', 'Queue', ([], {}), '()\n', (370, 372), False, 'from six.moves.queue import Queue\n'), ((1165, 1172), 'six.moves.queue.Queue', 'Queue', ([], {}), '()\n', (1170, 1172), False, 'from six.moves.queue import Queue\n'), ((1299, 1340), 'threading.Thread', 'Thread', ([], {'target': 'self.... |
import ast
print(ast)
source = """
def foo():
print('bar')
pass
"""
n = ast.parse(source)
print(n)
print(n.body)
print(n.body[0].name)
assert n.body[0].name == 'foo'
foo = n.body[0]
assert foo.lineno == 2
print(foo.body)
assert len(foo.body) == 2
print(foo.body[0])
print(foo.body[0].value.func.id)
assert foo.... | [
"ast.parse"
] | [((82, 99), 'ast.parse', 'ast.parse', (['source'], {}), '(source)\n', (91, 99), False, 'import ast\n')] |
from woodwork.column_schema import ColumnSchema
from featuretools.primitives.base import AggregationPrimitive
class CustomMean(AggregationPrimitive):
name = "custom_mean"
input_types = [ColumnSchema(semantic_tags={"numeric"})]
return_type = ColumnSchema(semantic_tags={"numeric"})
| [
"woodwork.column_schema.ColumnSchema"
] | [((256, 295), 'woodwork.column_schema.ColumnSchema', 'ColumnSchema', ([], {'semantic_tags': "{'numeric'}"}), "(semantic_tags={'numeric'})\n", (268, 295), False, 'from woodwork.column_schema import ColumnSchema\n'), ((197, 236), 'woodwork.column_schema.ColumnSchema', 'ColumnSchema', ([], {'semantic_tags': "{'numeric'}"}... |
import statistics
target_root_path = r"G:\GE\skin_12_data"
print("Region", end='')
for i in range(5):
print("\t\tAverage\tMedian\t%", end='')
print()
cell_types = ['all', 'CD68', 'T-Helper', 'T-Killer', 'T-Reg']
region_list = [11, 3, 8, 9, 1, 12, 5, 4, 2, 10, 7]
for region_id in region_list:
target_file_path... | [
"statistics.median",
"statistics.mean"
] | [((1254, 1285), 'statistics.mean', 'statistics.mean', (['distances[key]'], {}), '(distances[key])\n', (1269, 1285), False, 'import statistics\n'), ((1311, 1344), 'statistics.median', 'statistics.median', (['distances[key]'], {}), '(distances[key])\n', (1328, 1344), False, 'import statistics\n')] |
# Iterative Conway's game of life in Python / CUDA C
# this version is meant to illustrate the use of shared kernel memory in CUDA.
# written by <NAME> for "Hands on GPU Programming with Python and CUDA"
import pycuda.autoinit
import pycuda.driver as drv
from pycuda import gpuarray
from pycuda.compiler import SourceMo... | [
"numpy.random.choice",
"pycuda.compiler.SourceModule",
"matplotlib.pyplot.show",
"time.time",
"matplotlib.pyplot.figure",
"numpy.int32",
"pycuda.gpuarray.to_gpu"
] | [((417, 2837), 'pycuda.compiler.SourceModule', 'SourceModule', (['""" \n#define _iters 1000000 \n\n#define _X ( threadIdx.x + blockIdx.x * blockDim.x )\n#define _Y ( threadIdx.y + blockIdx.y * blockDim.y )\n\n#define _WIDTH ( blockDim.x * gridDim.x )\n#define _HEIGHT ( blockDim.y * gridDim.y... |
#!/usr/bin/python3
"""
File containing the class BaseModel
"""
from datetime import datetime
import models
import uuid
class BaseModel:
"""a class that defines all common attributes/methods for other classes"""
def __init__(self, *args, **kwargs):
"""Function for initializing the base model"""
... | [
"uuid.uuid4",
"datetime.datetime.strptime",
"models.storage.save",
"datetime.datetime.now",
"models.storage.new"
] | [((1168, 1182), 'datetime.datetime.now', 'datetime.now', ([], {}), '()\n', (1180, 1182), False, 'from datetime import datetime\n'), ((1191, 1215), 'models.storage.new', 'models.storage.new', (['self'], {}), '(self)\n', (1209, 1215), False, 'import models\n'), ((1224, 1245), 'models.storage.save', 'models.storage.save',... |
import random
import pyodbc
import pickle
import cv2
import time
from RaspberryPi.CollectingTrainingData.Commands import Commands
from imgaug import augmenters as iaa
# server = 'amaanrobotics.database.windows.net'
# database = 'AmaanRoboticsCloudDB'
# username = ''
# password = ''
# driver= '{ODBC Driver 13 for SQL S... | [
"pickle.loads",
"cv2.GaussianBlur",
"cv2.medianBlur",
"cv2.cvtColor",
"cv2.waitKey",
"cv2.threshold",
"cv2.adaptiveThreshold",
"time.sleep",
"imgaug.augmenters.ContrastNormalization",
"imgaug.augmenters.Multiply",
"pyodbc.connect",
"cv2.imshow",
"cv2.resize"
] | [((3039, 3167), 'pyodbc.connect', 'pyodbc.connect', (["('DRIVER=' + driver + ';SERVER=' + server + ';DATABASE=' + database +\n ';UID=' + username + ';PWD=' + password)"], {}), "('DRIVER=' + driver + ';SERVER=' + server + ';DATABASE=' +\n database + ';UID=' + username + ';PWD=' + password)\n", (3053, 3167), False,... |
# -*- coding: utf-8 -*-
import datetime
from decimal import Decimal, ROUND_HALF_UP
import logging
import time
import xlrd
from datapro.framework.util import to_utc
logger = logging.getLogger(__name__)
class Validator(object):
def __init__(self, level='warn'):
self._level = level
self._message_... | [
"decimal.Decimal",
"datapro.framework.util.to_utc",
"xlrd.xldate_as_tuple",
"time.strptime",
"logging.getLogger"
] | [((176, 203), 'logging.getLogger', 'logging.getLogger', (['__name__'], {}), '(__name__)\n', (193, 203), False, 'import logging\n'), ((3401, 3415), 'datapro.framework.util.to_utc', 'to_utc', (['dt', 'tz'], {}), '(dt, tz)\n', (3407, 3415), False, 'from datapro.framework.util import to_utc\n'), ((3773, 3784), 'decimal.Dec... |
#!/usr/bin/env python
'''======================================================
Created by: <NAME> and <NAME>
Last updated: March 2015
File name: DF_Plots.py
Organization: RISC Lab, Utah State University
======================================================'''
import roslib; roslib.load_manifes... | [
"matplotlib.pyplot.title",
"rospy.Subscriber",
"matplotlib.pyplot.clf",
"matplotlib.pyplot.figure",
"roslib.load_manifest",
"matplotlib.pyplot.close",
"rospy.Rate",
"rospy.signal_shutdown",
"numpy.append",
"rospy.is_shutdown",
"rospy.init_node",
"rospy.get_time",
"matplotlib.pyplot.show",
... | [((301, 334), 'roslib.load_manifest', 'roslib.load_manifest', (['"""risc_msgs"""'], {}), "('risc_msgs')\n", (321, 334), False, 'import roslib\n'), ((1180, 1213), 'numpy.zeros', 'np.zeros', (['(1, states_of_interest)'], {}), '((1, states_of_interest))\n', (1188, 1213), True, 'import numpy as np\n'), ((3923, 3944), 'matp... |
import numpy as np
import anndata as ad
# -------------------------------------------------------------------------------
# Some test data
# -------------------------------------------------------------------------------
X_list = [ # data matrix of shape n_obs x n_vars
[1, 2, 3], [4, 5, 6], [7, 8, 9]]
obs_di... | [
"anndata.AnnData",
"numpy.empty",
"numpy.array",
"numpy.ones"
] | [((1049, 1065), 'numpy.array', 'np.array', (['X_list'], {}), '(X_list)\n', (1057, 1065), True, 'import numpy as np\n'), ((1078, 1148), 'anndata.AnnData', 'ad.AnnData', (['X'], {'obs': 'obs_dict', 'var': 'var_dict', 'uns': 'uns_dict', 'dtype': '"""int32"""'}), "(X, obs=obs_dict, var=var_dict, uns=uns_dict, dtype='int32'... |
from django.db import models
class Author(models.Model):
name = models.CharField('Name', null=True, blank=True, max_length=255)
class Meta:
ordering = ['name']
def __str__(self):
return self.name
def __unicode__(self):
return self.name
class SortableBook(models.Model):
... | [
"django.db.models.CharField",
"django.db.models.PositiveIntegerField",
"django.db.models.ForeignKey"
] | [((70, 133), 'django.db.models.CharField', 'models.CharField', (['"""Name"""'], {'null': '(True)', 'blank': '(True)', 'max_length': '(255)'}), "('Name', null=True, blank=True, max_length=255)\n", (86, 133), False, 'from django.db import models\n'), ((329, 393), 'django.db.models.CharField', 'models.CharField', (['"""Ti... |
from scivision_plankton_models import resnet50
import PIL
import torch
import torchvision
X = PIL.Image.open('Pia1.2017-10-12.0711+N00207451_hc.tif')
X = torchvision.transforms.ToTensor()(X)
X = torchvision.transforms.Resize((256,256))(X)
X = torch.unsqueeze(X, 0)
model = resnet50()
y = model.predict(X)
_, preds = t... | [
"PIL.Image.open",
"scivision_plankton_models.resnet50",
"torch.max",
"torch.unsqueeze",
"torchvision.transforms.Resize",
"torchvision.transforms.ToTensor"
] | [((95, 150), 'PIL.Image.open', 'PIL.Image.open', (['"""Pia1.2017-10-12.0711+N00207451_hc.tif"""'], {}), "('Pia1.2017-10-12.0711+N00207451_hc.tif')\n", (109, 150), False, 'import PIL\n'), ((245, 266), 'torch.unsqueeze', 'torch.unsqueeze', (['X', '(0)'], {}), '(X, 0)\n', (260, 266), False, 'import torch\n'), ((276, 286),... |