code stringlengths 22 1.05M | apis listlengths 1 3.31k | extract_api stringlengths 75 3.25M |
|---|---|---|
"""
Configuration File Permissions parsers
======================================
Parsers included in this module are:
SshdConfigPerms - command ``/bin/ls -l /etc/ssh/sshd_config``
-------------------------------------------------------------
Grub1ConfigPerms - command ``/bin/ls -l /boot/grub/grub.conf``
------------... | [
"insights.core.plugins.parser",
"insights.core.CommandParser.__init__",
"insights.util.file_permissions.FilePermissions.__init__"
] | [((1243, 1274), 'insights.core.plugins.parser', 'parser', (['Specs.sshd_config_perms'], {}), '(Specs.sshd_config_perms)\n', (1249, 1274), False, 'from insights.core.plugins import parser\n'), ((1822, 1854), 'insights.core.plugins.parser', 'parser', (['Specs.grub1_config_perms'], {}), '(Specs.grub1_config_perms)\n', (18... |
import datetime
import decimal
import uuid
import pytest
import typesystem
import typesystem.formats
class Person(typesystem.Schema):
name = typesystem.String(max_length=100, allow_blank=False)
age = typesystem.Integer()
class Product(typesystem.Schema):
name = typesystem.String(max_length=100, allow_... | [
"typesystem.String",
"typesystem.SchemaDefinitions",
"typesystem.Reference",
"datetime.time",
"typesystem.formats.TIME_REGEX.match",
"typesystem.Decimal",
"typesystem.Time",
"typesystem.Array",
"typesystem.Integer",
"typesystem.to_json_schema",
"typesystem.DateTime",
"pytest.raises",
"typesy... | [((149, 201), 'typesystem.String', 'typesystem.String', ([], {'max_length': '(100)', 'allow_blank': '(False)'}), '(max_length=100, allow_blank=False)\n', (166, 201), False, 'import typesystem\n'), ((212, 232), 'typesystem.Integer', 'typesystem.Integer', ([], {}), '()\n', (230, 232), False, 'import typesystem\n'), ((280... |
import json
import logging
from pprint import pprint
import requests
from json.decoder import JSONDecodeError
from response import success, ApiBadRequest, ApiInternalError
from config import ExternalAPI
from services import convert_class_time_table
import json
class RouteHandler:
async def get_time_table(self, r... | [
"response.success",
"requests.post",
"json.dumps",
"response.ApiBadRequest",
"json.dump"
] | [((397, 413), 'json.dumps', 'json.dumps', (['body'], {}), '(body)\n', (407, 413), False, 'import json\n'), ((435, 534), 'requests.post', 'requests.post', (['ExternalAPI.url'], {'data': 'request_data', 'headers': "{'Content-Type': 'application/json'}"}), "(ExternalAPI.url, data=request_data, headers={'Content-Type':\n ... |
"""
Helioviewer Client tests
"""
from __future__ import absolute_import
#pylint: disable=C0103,R0904,W0201,W0212,W0232,E1103
import sunpy
from sunpy.net.helioviewer import HelioviewerClient
class TestHelioviewerClient:
"""Tests the Helioviewer.org API Client class"""
def setup_class(self):
self.client... | [
"sunpy.make_map",
"sunpy.net.helioviewer.HelioviewerClient"
] | [((323, 342), 'sunpy.net.helioviewer.HelioviewerClient', 'HelioviewerClient', ([], {}), '()\n', (340, 342), False, 'from sunpy.net.helioviewer import HelioviewerClient\n'), ((1796, 1820), 'sunpy.make_map', 'sunpy.make_map', (['filepath'], {}), '(filepath)\n', (1810, 1820), False, 'import sunpy\n')] |
from zunzun import CommandRegister, Command
from unittest.mock import MagicMock
def test_add_commands():
class MyCommand(Command):
pass
class ModuleMock:
no_command = ""
command = MyCommand
injector = MagicMock()
injector.get = MagicMock(return_value="object_from_injector")
... | [
"unittest.mock.MagicMock",
"zunzun.CommandRegister"
] | [((241, 252), 'unittest.mock.MagicMock', 'MagicMock', ([], {}), '()\n', (250, 252), False, 'from unittest.mock import MagicMock\n'), ((272, 318), 'unittest.mock.MagicMock', 'MagicMock', ([], {'return_value': '"""object_from_injector"""'}), "(return_value='object_from_injector')\n", (281, 318), False, 'from unittest.moc... |
# coding=utf-8
# Copyright 2022 The Google Research Authors.
#
# Licensed under the Apache License, Version 2.0 (the "License");
# you may not use this file except in compliance with the License.
# You may obtain a copy of the License at
#
# http://www.apache.org/licenses/LICENSE-2.0
#
# Unless required by applicab... | [
"jax.vmap",
"collections.namedtuple",
"jax.nn.sigmoid",
"flax.linen.initializers.xavier_uniform",
"flax.linen.Dense",
"dopamine.jax.networks.preprocess_atari_inputs",
"flax.linen.Conv",
"optax.apply_updates",
"dopamine.jax.agents.dqn.dqn_agent.target_q",
"functools.partial",
"numpy.linspace",
... | [((1134, 1227), 'collections.namedtuple', 'collections.namedtuple', (['"""dqn_network_with_random_rewards"""', "['q_values', 'aux_prediction']"], {}), "('dqn_network_with_random_rewards', ['q_values',\n 'aux_prediction'])\n", (1156, 1227), False, 'import collections\n'), ((5571, 5628), 'functools.partial', 'functool... |
"""Command line interface including input and output."""
import argparse
import sys
from seedrecover.wordlist import Wordlist
from seedrecover.order import iterate
from seedrecover.keyderiv import seed_to_stakeaddress, ChecksumError
from seedrecover.stakecheck import StakeAddresses
from seedrecover.bfstakecheck import... | [
"seedrecover.stakecheck.StakeAddresses",
"seedrecover.bfstakecheck.BlockFrost",
"argparse.ArgumentParser",
"seedrecover.order.iterate",
"seedrecover.wordlist.Wordlist",
"seedrecover.keyderiv.seed_to_stakeaddress"
] | [((3649, 3672), 'seedrecover.wordlist.Wordlist', 'Wordlist', (['args.wordlist'], {}), '(args.wordlist)\n', (3657, 3672), False, 'from seedrecover.wordlist import Wordlist\n'), ((4316, 4378), 'seedrecover.order.iterate', 'iterate', (['seed', 'args.order', 'wordlist', 'length', 'missing_positions'], {}), '(seed, args.ord... |
# Generated by Django 3.0.5 on 2020-04-12 15:39
from django.db import migrations, models
import django.db.models.deletion
import uuid
class Migration(migrations.Migration):
dependencies = [
("ppe", "0009_auto_20200412_1517"),
]
operations = [
migrations.CreateModel(
name="Fa... | [
"django.db.models.DateField",
"django.db.models.TextField",
"django.db.models.IntegerField",
"django.db.models.ForeignKey",
"django.db.models.DateTimeField",
"django.db.models.UUIDField"
] | [((1517, 1666), 'django.db.models.TextField', 'models.TextField', ([], {'choices': "[('active', 'active'), ('replaced', 'replaced'), ('candidate', 'candidate'),\n ('cancelled', 'cancelled')]", 'default': 'None'}), "(choices=[('active', 'active'), ('replaced', 'replaced'), (\n 'candidate', 'candidate'), ('cancelle... |
"""Registering a Prefect Flow downloading a zipped folder containing csv files.
"""
# the config object must be imported from config.py before any Prefect imports
from pathlib import Path
from prefect import Flow, unmapped, Parameter, flatten, case, apply_map
from prefect.tasks.shell import ShellTask
from prefect.trig... | [
"nl_open_data.tasks.create_dir.map",
"nl_open_data.tasks.remove_dir",
"nl_open_data.tasks.list_dir",
"nl_open_data.tasks.stem_wrap.map",
"nl_open_data.tasks.clean_folder_names",
"prefect.executors.DaskExecutor",
"pathlib.Path",
"nl_open_data.tasks.get_filename_from_url.map",
"prefect.storage.GCS",
... | [((681, 712), 'prefect.tasks.shell.ShellTask', 'ShellTask', ([], {'name': '"""curl_download"""'}), "(name='curl_download')\n", (690, 712), False, 'from prefect.tasks.shell import ShellTask\n'), ((884, 903), 'prefect.Flow', 'Flow', (['"""zipped_file"""'], {}), "('zipped_file')\n", (888, 903), False, 'from prefect import... |
"""Intervals are a generalization of several file formats:
GFF
====
All GFF formats (GFF2, GFF3 and GTF) are tabular files with 9 fields per line,
separated by tabs. They all share the same structure for the first 7 fields,
while differing in the definition of the eighth field and in the content and
format of the nin... | [
"os.path.isfile",
"os.path.exists",
"gzip.open"
] | [((16254, 16274), 'os.path.exists', 'os.path.exists', (['path'], {}), '(path)\n', (16268, 16274), False, 'import os\n'), ((16283, 16303), 'os.path.isfile', 'os.path.isfile', (['path'], {}), '(path)\n', (16297, 16303), False, 'import os\n'), ((16812, 16833), 'gzip.open', 'gzip.open', (['path', '"""rb"""'], {}), "(path, ... |
import os
from ..modules import ImageCapture
from .observable import observable
class CaptureImagePipe:
def __init__(self, *args, **kwargs):
self.image_capture = ImageCapture(*args, **kwargs)
self.stop = False
observable.register("stop", self, self.on_stop)
def __iter__(self):
... | [
"os.path.splitext",
"os.path.basename",
"os.path.relpath"
] | [((722, 759), 'os.path.relpath', 'os.path.relpath', (['filename'], {'start': 'path'}), '(filename, start=path)\n', (737, 759), False, 'import os\n'), ((813, 839), 'os.path.basename', 'os.path.basename', (['filename'], {}), '(filename)\n', (829, 839), False, 'import os\n'), ((932, 958), 'os.path.splitext', 'os.path.spli... |
import hashlib
import hmac
import time
class BitfinexAuth():
def __init__(self, api_key: str, secret_key: str):
self.api_key = api_key
self.secret_key = secret_key
self.last_nonce = 0
def _sign_payload(self, payload) -> str:
sig = hmac.new(self.secret_key.encode('utf8'),
... | [
"time.time"
] | [((491, 502), 'time.time', 'time.time', ([], {}), '()\n', (500, 502), False, 'import time\n')] |
import subprocess
import os
def get_cpp_flags():
flags = []
flags += get_root_flags()
flags += get_coast_flags()
flags += get_python_flags()
flags += get_default_flags()
return [i for i in flags if i]
def get_python_sys_path():
sys_path = [
os.path.join(os.environ["COAST_USER... | [
"subprocess.check_output",
"os.path.join"
] | [((285, 349), 'os.path.join', 'os.path.join', (["os.environ['COAST_USER_LIB']", '"""python"""', '"""packages"""'], {}), "(os.environ['COAST_USER_LIB'], 'python', 'packages')\n", (297, 349), False, 'import os\n'), ((779, 831), 'subprocess.check_output', 'subprocess.check_output', (["['root-config', '--cflags']"], {}), "... |
from datetime import datetime
from atomformat import Feed
from django.core.urlresolvers import reverse
from django.conf import settings
from django.template.defaultfilters import linebreaks, escape
from django.contrib.sites.models import Site
from pinax.apps.tasks.models import TaskHistory
ITEMS_PER_FEED = getat... | [
"datetime.datetime",
"pinax.apps.tasks.models.TaskHistory.objects.filter",
"django.core.urlresolvers.reverse",
"django.template.defaultfilters.escape",
"django.contrib.sites.models.Site.objects.get_current"
] | [((1761, 1796), 'datetime.datetime', 'datetime', ([], {'year': '(2008)', 'month': '(7)', 'day': '(1)'}), '(year=2008, month=7, day=1)\n', (1769, 1796), False, 'from datetime import datetime\n'), ((1062, 1076), 'django.template.defaultfilters.escape', 'escape', (['output'], {}), '(output)\n', (1068, 1076), False, 'from ... |
# vim: tabstop=4 shiftwidth=4 softtabstop=4
# Copyright 2012 <NAME>
# All Rights Reserved.
#
# Licensed under the Apache License, Version 2.0 (the "License"); you may
# not use this file except in compliance with the License. You may obtain
# a copy of the License at
#
# http://www.apache.org/licenses... | [
"cinder.tests.image.fake.stub_out_image_service",
"cinder.exception.ProcessExecutionError",
"mox.IgnoreArg",
"cinder.db.volume_destroy",
"mox.Mox",
"cinder.exception.CinderException",
"cinder.db.volume_get",
"cinder.openstack.common.log.getLogger",
"mox.MockObject",
"cinder.volume.drivers.rbd.RBDD... | [((1201, 1228), 'cinder.openstack.common.log.getLogger', 'logging.getLogger', (['__name__'], {}), '(__name__)\n', (1218, 1228), True, 'from cinder.openstack.common import log as logging\n'), ((2344, 2353), 'mox.Mox', 'mox.Mox', ([], {}), '()\n', (2351, 2353), False, 'import mox\n'), ((2383, 2417), 'mox.MockObject', 'mo... |
import matplotlib.pyplot as plt
import subprocess
executables = ['clock', 'lru_aging', 'lru_counter', 'lru_stack']
for executable in executables:
bashCommand = "./build/" + executable
output = subprocess.check_output(['bash','-c', bashCommand])
output = output.split('\n')[:-1]
x = []
y = []
... | [
"subprocess.check_output",
"matplotlib.pyplot.ylabel",
"matplotlib.pyplot.xlabel",
"matplotlib.pyplot.plot",
"matplotlib.pyplot.show"
] | [((204, 256), 'subprocess.check_output', 'subprocess.check_output', (["['bash', '-c', bashCommand]"], {}), "(['bash', '-c', bashCommand])\n", (227, 256), False, 'import subprocess\n'), ((569, 583), 'matplotlib.pyplot.plot', 'plt.plot', (['x', 'y'], {}), '(x, y)\n', (577, 583), True, 'import matplotlib.pyplot as plt\n')... |
import functools
import glob
import os
import shlex
from typing import Callable, Iterable, List, Optional, Tuple
from bs4 import BeautifulSoup, Comment, Doctype
from mitmproxy import ctx, http
import modules.arguments as A
import modules.constants as C
import modules.csp as csp
import modules.inject as inject
import ... | [
"modules.utilities.second",
"mitmproxy.ctx.log.error",
"modules.misc.sanitize",
"modules.utilities.first",
"mitmproxy.ctx.log.info",
"modules.utilities.itemList",
"mitmproxy.ctx.log.warn",
"modules.requests.inferEncoding",
"modules.csp.Injection",
"shlex.quote",
"modules.csp.generateNonce",
"m... | [((1695, 1740), 'functools.partial', 'functools.partial', (['itemList', 'LIST_ITEM_PREFIX'], {}), '(itemList, LIST_ITEM_PREFIX)\n', (1712, 1740), False, 'import functools\n'), ((2715, 2726), 'os.getcwd', 'os.getcwd', ([], {}), '()\n', (2724, 2726), False, 'import os\n'), ((2841, 2860), 'os.chdir', 'os.chdir', (['direct... |
import clips
import copy
class Core:
def __init__(self, filename):
self.env = clips.Environment()
self.env.load(filename)
def assert_fact(self, fact):
self.env.assert_string(fact)
def get_activations(self):
return list(self.env.activations())
def get_hit_rules(se... | [
"clips.Environment"
] | [((96, 115), 'clips.Environment', 'clips.Environment', ([], {}), '()\n', (113, 115), False, 'import clips\n')] |
import pygame
print("Musica: ")
pygame.init()
pygame.mixer.music.load('ex3/musica.mp3')
pygame.mixer.music.play()
pygame.event.wait()
| [
"pygame.mixer.music.play",
"pygame.event.wait",
"pygame.mixer.music.load",
"pygame.init"
] | [((32, 45), 'pygame.init', 'pygame.init', ([], {}), '()\n', (43, 45), False, 'import pygame\n'), ((46, 87), 'pygame.mixer.music.load', 'pygame.mixer.music.load', (['"""ex3/musica.mp3"""'], {}), "('ex3/musica.mp3')\n", (69, 87), False, 'import pygame\n'), ((88, 113), 'pygame.mixer.music.play', 'pygame.mixer.music.play',... |
#!/usr/bin/env python
# You may need to edit the above to point to your version of Python 2.0
"""
psize.py
Get dimensions and other interesting information from a PQR file
Originally written by <NAME>
Additional APBS-specific features added by <NAME>
Ported to Python/Psize class by <NAME> and subsequently hacked by
<N... | [
"getopt.getopt",
"math.log",
"sys.stderr.write",
"sys.exit",
"sys.stdout.write"
] | [((14718, 14739), 'sys.stderr.write', 'sys.stderr.write', (['msg'], {}), '(msg)\n', (14734, 14739), False, 'import sys\n'), ((14744, 14756), 'sys.exit', 'sys.exit', (['rc'], {}), '(rc)\n', (14752, 14756), False, 'import sys\n'), ((16061, 16101), 'sys.stdout.write', 'sys.stdout.write', (['"""# Constants used: \n"""'], {... |
from enum import Enum, auto
from MCState.MCSide.MCElementDirection import MCubeDirection
class MCubeSide(Enum):
FRONT = auto()
RIGHT = auto()
DOWN = auto()
UP = auto()
LEFT = auto()
BACK = auto()
def __str__(self):
return str(self.name)
def neighbor(self,di... | [
"enum.auto"
] | [((129, 135), 'enum.auto', 'auto', ([], {}), '()\n', (133, 135), False, 'from enum import Enum, auto\n'), ((150, 156), 'enum.auto', 'auto', ([], {}), '()\n', (154, 156), False, 'from enum import Enum, auto\n'), ((171, 177), 'enum.auto', 'auto', ([], {}), '()\n', (175, 177), False, 'from enum import Enum, auto\n'), ((19... |
import torch
def flipfb(tensor):
"""
Flips a given tensor along the third dimension (front to back)
Parameters
----------
tensor
a tensor at least three-dimensional
Returns
-------
Tensor
the flipped tensor
"""
return torch.flip(tensor, dims=[2])
| [
"torch.flip"
] | [((279, 307), 'torch.flip', 'torch.flip', (['tensor'], {'dims': '[2]'}), '(tensor, dims=[2])\n', (289, 307), False, 'import torch\n')] |
from typing import List, Tuple
import math
import logging
import Simulation.operators as operators
class Characteristic:
def __init__(self, name, value, limit_inf, limit_sup, mutability = 5, distr_function = None):
self.name = name
self.value = value
self.limit_inf = limit_inf
self... | [
"logging.info"
] | [((528, 619), 'logging.info', 'logging.info', (['"""Society has added/changed characteristic: %s with value:%s"""', 'name', 'value'], {}), "('Society has added/changed characteristic: %s with value:%s',\n name, value)\n", (540, 619), False, 'import logging\n'), ((1856, 1945), 'logging.info', 'logging.info', (['"""Ha... |
import numpy as np
from scipy.optimize import minimize_scalar
import statsmodels.regression.linear_model as lm
from astropy.visualization import PercentileInterval
class InputError(Exception):
"""Raised when a required parameter is not included."""
def __init__(self, expression, message):
self.express... | [
"numpy.abs",
"statsmodels.regression.linear_model.WLS",
"numpy.any",
"numpy.array",
"numpy.sum",
"scipy.optimize.minimize_scalar",
"astropy.visualization.PercentileInterval"
] | [((707, 739), 'numpy.array', 'np.array', (['[(True) for _ in data]'], {}), '([(True) for _ in data])\n', (715, 739), True, 'import numpy as np\n'), ((512, 574), 'numpy.sum', 'np.sum', (['((data[mask] - x * model[mask]) ** 2 / sigma[mask] ** 2)'], {}), '((data[mask] - x * model[mask]) ** 2 / sigma[mask] ** 2)\n', (518, ... |
import socket
import sys
from ledapy.deconvolution import sdeconv_analysis
from numpy import array as npa
# import cvxEDA as cvx
import numpy as np
import neurokit2 as nk
# Create a TCP/IP socket
sock = socket.socket(socket.AF_INET, socket.SOCK_STREAM)
# Bind the socket to the port
server_address = ('localhost', 8052)... | [
"numpy.array",
"neurokit2.eda_process",
"socket.socket"
] | [((204, 253), 'socket.socket', 'socket.socket', (['socket.AF_INET', 'socket.SOCK_STREAM'], {}), '(socket.AF_INET, socket.SOCK_STREAM)\n', (217, 253), False, 'import socket\n'), ((1158, 1178), 'numpy.array', 'npa', (['data_float_list'], {}), '(data_float_list)\n', (1161, 1178), True, 'from numpy import array as npa\n'),... |
'''
__init__.py
'''
import logging, os, builtins, sys
from flask_swagger_ui import get_swaggerui_blueprint
from flask import Flask, redirect, url_for
from flask.json import JSONEncoder
from flask_sqlalchemy import SQLAlchemy
db = SQLAlchemy()
class SAFRS(object):
'''This class configures the Flask application to ... | [
"logging.getLogger",
"logging.StreamHandler",
"os.getenv",
"logging.Formatter",
"flask_sqlalchemy.SQLAlchemy",
"flask_swagger_ui.get_swaggerui_blueprint"
] | [((231, 243), 'flask_sqlalchemy.SQLAlchemy', 'SQLAlchemy', ([], {}), '()\n', (241, 243), False, 'from flask_sqlalchemy import SQLAlchemy\n'), ((2682, 2717), 'os.getenv', 'os.getenv', (['"""DEBUG"""', 'logging.WARNING'], {}), "('DEBUG', logging.WARNING)\n", (2691, 2717), False, 'import logging, os, builtins, sys\n'), ((... |
from django.urls import reverse
from rest_framework import status
from artwork.views.artwork import ArtworkAPIView
from tests.common import APIFactoryTestCase
class ArtworkAPITestCase(APIFactoryTestCase):
def setUp(self) -> None:
super(ArtworkAPITestCase, self).setUp()
self.view = ArtworkAPIView.as_view()
def ... | [
"artwork.views.artwork.ArtworkAPIView.as_view",
"django.urls.reverse"
] | [((289, 313), 'artwork.views.artwork.ArtworkAPIView.as_view', 'ArtworkAPIView.as_view', ([], {}), '()\n', (311, 313), False, 'from artwork.views.artwork import ArtworkAPIView\n'), ((380, 427), 'django.urls.reverse', 'reverse', (['"""api_v1:artwork:get_artwork"""'], {'args': '[1]'}), "('api_v1:artwork:get_artwork', args... |
import re
from models.users import login_user
class config_pass:
def __init__(self):
self.min_length = 6
self.need_number = False
self.need_uppercase = False
self.need_lowercase = False
self.need_symbol = False
def get_min_length(self):
return self.min_length
def get_need_number(self, pass_):
if se... | [
"re.search",
"re.match",
"models.users.login_user"
] | [((2466, 2566), 're.match', 're.match', (['"""^[_a-z0-9-]+(\\\\.[_a-z0-9-]+)*@[a-z0-9-]+(\\\\.[a-z0-9-]+)*(\\\\.[a-z]{2,4})$"""', 'email'], {}), "(\n '^[_a-z0-9-]+(\\\\.[_a-z0-9-]+)*@[a-z0-9-]+(\\\\.[a-z0-9-]+)*(\\\\.[a-z]{2,4})$',\n email)\n", (2474, 2566), False, 'import re\n'), ((1682, 1709), 'models.users.log... |
from http.server import HTTPServer, BaseHTTPRequestHandler
class HelloHandler(BaseHTTPRequestHandler):
def do_GET(self):
self.send_response(200)
self.send_header("Content-Type", "text/html")
self.end_headers()
self.wfile.write("<h1>Hello World!</h1>\n".encode("UTF-8"))
... | [
"http.server.HTTPServer"
] | [((484, 524), 'http.server.HTTPServer', 'HTTPServer', (['server_address', 'HelloHandler'], {}), '(server_address, HelloHandler)\n', (494, 524), False, 'from http.server import HTTPServer, BaseHTTPRequestHandler\n')] |
from marshmallow import INCLUDE, Schema, fields, post_load, pre_load
class Urls:
def __init__(
self,
digital_purchase_date=None,
foc_date=None,
onsale_date=None,
unlimited_date=None,
wiki=None,
detail=None,
**kwargs,
):
self.digital_purch... | [
"marshmallow.fields.Url"
] | [((608, 653), 'marshmallow.fields.Url', 'fields.Url', ([], {'attribute': '"""digital_purchase_date"""'}), "(attribute='digital_purchase_date')\n", (618, 653), False, 'from marshmallow import INCLUDE, Schema, fields, post_load, pre_load\n'), ((668, 700), 'marshmallow.fields.Url', 'fields.Url', ([], {'attribute': '"""foc... |
## Where my anagrams at?
## 5 kyu
## https://www.codewars.com/kata/523a86aa4230ebb5420001e1
from collections import Counter
def anagrams(word, words):
return [i for i in words if Counter(i) == Counter(word)]
| [
"collections.Counter"
] | [((195, 205), 'collections.Counter', 'Counter', (['i'], {}), '(i)\n', (202, 205), False, 'from collections import Counter\n'), ((209, 222), 'collections.Counter', 'Counter', (['word'], {}), '(word)\n', (216, 222), False, 'from collections import Counter\n')] |
from game.shared.point import Point
from game.casting.restorer import Restorer
class Director:
"""A person who directs the game.
The responsibility of a Director is to control the sequence of play.
Attributes:
_keyboard_service (KeyboardService): For getting directional input.
_display_s... | [
"game.shared.point.Point",
"game.casting.restorer.Restorer"
] | [((2161, 2171), 'game.casting.restorer.Restorer', 'Restorer', ([], {}), '()\n', (2169, 2171), False, 'from game.casting.restorer import Restorer\n'), ((2604, 2615), 'game.shared.point.Point', 'Point', (['(0)', '(5)'], {}), '(0, 5)\n', (2609, 2615), False, 'from game.shared.point import Point\n'), ((2923, 2934), 'game.s... |
import unittest
import datetime
import sys
sys.path.append(".")
from python_play.date_utility import random_datetime
from python_play.date_utility import random_date_string_inferring_format
class TestDateUtility(unittest.TestCase):
def test_random_datetime(self):
start_date_string = '1990-01-01'
... | [
"python_play.date_utility.random_date_string_inferring_format",
"datetime.datetime.strptime",
"python_play.date_utility.random_datetime",
"unittest.main",
"sys.path.append"
] | [((43, 63), 'sys.path.append', 'sys.path.append', (['"""."""'], {}), "('.')\n", (58, 63), False, 'import sys\n'), ((1084, 1099), 'unittest.main', 'unittest.main', ([], {}), '()\n', (1097, 1099), False, 'import unittest\n'), ((413, 475), 'datetime.datetime.strptime', 'datetime.datetime.strptime', (['start_date_string', ... |
"""test generate_bes_from_template"""
# pylint: disable=import-error,wildcard-import,undefined-variable,wrong-import-position,unused-wildcard-import,consider-using-f-string
import argparse
import os.path
import sys
# don't create bytecode for tests because it is cluttery in python2
sys.dont_write_bytecode = True
# c... | [
"sys.path.reverse",
"argparse.ArgumentParser",
"sys.exit"
] | [((353, 378), 'argparse.ArgumentParser', 'argparse.ArgumentParser', ([], {}), '()\n', (376, 378), False, 'import argparse\n'), ((3481, 3492), 'sys.exit', 'sys.exit', (['(0)'], {}), '(0)\n', (3489, 3492), False, 'import sys\n'), ((783, 801), 'sys.path.reverse', 'sys.path.reverse', ([], {}), '()\n', (799, 801), False, 'i... |
#!/usr/bin/env python3
"""
This module handles the WINC FW and certificate upgrade.
Features:
- Update the WINC FW
- Build root certificate storage and upgrade WINC with it
- Build client file storage and upgrade WINC with it
- Read root certificate storage from WINC
- Read client file storage from WINC
"""
import sys... | [
"textwrap.dedent"
] | [((795, 1136), 'textwrap.dedent', 'textwrap.dedent', (['""" WINC FW upgrade and certificates update tool\n\n Basic actions:\n - read: read a storage object from WINC flash\n - write: write a storage object to WINC flash\n - build: build a storage object\n - decode: decode a storage obj... |
# This sample tests the type checker's handling of the overload decorator.
from typing import overload, Optional
from datetime import datetime, timezone, timedelta
@overload
def from_json_timestamp(ts: int) -> datetime:
...
@overload
def from_json_timestamp(ts: None) -> None:
...
def from_json_timestamp(ts:... | [
"datetime.datetime",
"datetime.timedelta"
] | [((395, 436), 'datetime.datetime', 'datetime', (['(1970)', '(1)', '(1)'], {'tzinfo': 'timezone.utc'}), '(1970, 1, 1, tzinfo=timezone.utc)\n', (403, 436), False, 'from datetime import datetime, timezone, timedelta\n'), ((439, 465), 'datetime.timedelta', 'timedelta', ([], {'milliseconds': 'ts'}), '(milliseconds=ts)\n', (... |
"""Handle login requests."""
import os
import secrets
import time
from urllib.parse import quote_plus, urlencode
from django.http import HttpResponseRedirect
from django.views.generic.base import RedirectView
class LoginRedirectOIDC(RedirectView):
"""Handle login workflow with login.gov."""
permanent = Fal... | [
"urllib.parse.urlencode",
"secrets.token_hex",
"time.time",
"django.http.HttpResponseRedirect"
] | [((980, 1001), 'secrets.token_hex', 'secrets.token_hex', (['(32)'], {}), '(32)\n', (997, 1001), False, 'import secrets\n'), ((1018, 1039), 'secrets.token_hex', 'secrets.token_hex', (['(32)'], {}), '(32)\n', (1035, 1039), False, 'import secrets\n'), ((1570, 1614), 'urllib.parse.urlencode', 'urlencode', (['auth_params'],... |
import os
import shutil
import readdy
import tempfile
import unittest
import numpy as np
class TestTopologyReactionCount(unittest.TestCase):
@classmethod
def setUpClass(cls) -> None:
cls.dir = tempfile.mkdtemp("test-topology-reaction-count")
@classmethod
def tearDownClass(cls) -> None:
... | [
"numpy.random.normal",
"numpy.testing.assert_equal",
"readdy.Trajectory",
"readdy.StructuralReactionRecipe",
"tempfile.mkdtemp",
"shutil.rmtree",
"unittest.main",
"readdy.ReactionDiffusionSystem",
"numpy.testing.assert_array_equal"
] | [((3697, 3712), 'unittest.main', 'unittest.main', ([], {}), '()\n', (3710, 3712), False, 'import unittest\n'), ((213, 261), 'tempfile.mkdtemp', 'tempfile.mkdtemp', (['"""test-topology-reaction-count"""'], {}), "('test-topology-reaction-count')\n", (229, 261), False, 'import tempfile\n'), ((324, 366), 'shutil.rmtree', '... |
import globus_sdk
import json
import sys
import argparse
from deriva.core import get_oauth_scopes_for_host
CLIENT_ID = '8ef15ba9-2b4a-469c-a163-7fd910c9d111'
def main(host, scope_tag=None):
client = globus_sdk.NativeAppAuthClient(CLIENT_ID)
scopes = None
all_scopes = get_oauth_scopes_for_host(host)
if... | [
"deriva.core.get_oauth_scopes_for_host",
"argparse.ArgumentParser",
"sys.exit",
"globus_sdk.NativeAppAuthClient",
"json.dump"
] | [((205, 246), 'globus_sdk.NativeAppAuthClient', 'globus_sdk.NativeAppAuthClient', (['CLIENT_ID'], {}), '(CLIENT_ID)\n', (235, 246), False, 'import globus_sdk\n'), ((282, 313), 'deriva.core.get_oauth_scopes_for_host', 'get_oauth_scopes_for_host', (['host'], {}), '(host)\n', (307, 313), False, 'from deriva.core import ge... |
# def decision_tree_to_simple_program(node: TreeNode, simple_program: SimpleProgram, previous_conjunction=Term('true')):
# # if the current node is a leaf
# if node.left_subtree is None and node.right_subtree is None:
# if node.classification is not None:
# clause = (node.classification << p... | [
"mai_version.problog_helper.problog_helper.apply_substitution_to_term",
"problog.logic.Constant",
"problog.logic.And",
"problog.logic.Term",
"problog.logic.AnnotatedDisjunction",
"problog.program.SimpleProgram"
] | [((1933, 1945), 'problog.logic.Term', 'Term', (['"""true"""'], {}), "('true')\n", (1937, 1945), False, 'from problog.logic import Term, And, Var, Constant, AnnotatedDisjunction\n'), ((3449, 3464), 'problog.program.SimpleProgram', 'SimpleProgram', ([], {}), '()\n', (3462, 3464), False, 'from problog.program import Simpl... |
import json
import os
import time
from abc import ABC
import numpy as np
import torch
import torchvision
from modules.trainer.regularization import weight_clipping
from tensorboardX import SummaryWriter
from torch.utils.data import DataLoader
from tqdm import tqdm
import utils
from modules.evaluator import Evaluation... | [
"utils.makedir_if_not_exist",
"os.path.exists",
"numpy.random.normal",
"time.asctime",
"modules.evaluator.Evaluation",
"tensorboardX.SummaryWriter",
"numpy.mean",
"json.dumps",
"os.path.join",
"modules.trainer.regularization.weight_clipping",
"torch.no_grad",
"numpy.array",
"utils.print_wlin... | [((709, 734), 'torch.cuda.is_available', 'torch.cuda.is_available', ([], {}), '()\n', (732, 734), False, 'import torch\n'), ((800, 825), 'torch.cuda.is_available', 'torch.cuda.is_available', ([], {}), '()\n', (823, 825), False, 'import torch\n'), ((1033, 1047), 'time.asctime', 'time.asctime', ([], {}), '()\n', (1045, 1... |
import json
import pymysql
import requests
import decimal
import config
rds_host = "rds-instance-endpoint"
name = rds_config.db_username
password = rds_config.db_password
db_name = rds_config.db_name
"""index.py 람다 함수로부터 호출되어서 경도와 위도를 받아
반경 100m이내의 카페 정보를 데이터베이스에 저장한다."""
def lambda_handler(event, context):
lati... | [
"decimal.Decimal",
"json.dumps",
"pymysql.connect",
"requests.get"
] | [((1198, 1288), 'pymysql.connect', 'pymysql.connect', ([], {'user': 'name', 'passwd': 'password', 'host': 'rds_host', 'db': 'db_name', 'charset': '"""utf8"""'}), "(user=name, passwd=password, host=rds_host, db=db_name,\n charset='utf8')\n", (1213, 1288), False, 'import pymysql\n'), ((2007, 2039), 'json.dumps', 'json... |
# Copyright 2020 NXP.
#
# SPDX-License-Identifier: BSD-3-Clause
#
# 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 th... | [
"pyqtgraph.Qt.QtGui.QVBoxLayout",
"pyqtgraph.Qt.QtGui.QWidget",
"numpy.column_stack",
"pyqtgraph.Qt.QtGui.QDialog",
"time.sleep",
"pyqtgraph.Qt.QtWidgets.QAction",
"pyqtgraph.Qt.QtGui.QApplication",
"pyqtgraph.Qt.QtGui.QFileDialog.getSaveFileName",
"pyqtgraph.mkPen",
"copy.deepcopy",
"pyqtgraph.... | [((2325, 2362), 'pyqtgraph.setConfigOption', 'pg.setConfigOption', (['"""background"""', '"""w"""'], {}), "('background', 'w')\n", (2343, 2362), True, 'import pyqtgraph as pg\n'), ((2363, 2400), 'pyqtgraph.setConfigOption', 'pg.setConfigOption', (['"""foreground"""', '"""k"""'], {}), "('foreground', 'k')\n", (2381, 240... |
from widedeep.model.model_base import LinearModel, MLP
from widedeep.model.joint_model import JointMDN
from widedeep.ops.distributions import GaussianMixture
from widedeep.ops.losses import Optimizers
import widedeep.utils as utils
from widedeep.ops import metrics
from protodata.datasets.scikit_dataset import Diabet... | [
"widedeep.model.model_base.LinearModel",
"widedeep.ops.metrics.RMSEInterval",
"widedeep.utils.get_logger",
"widedeep.utils.get_network_definition",
"protodata.datasets.scikit_dataset.DiabetesSettings",
"widedeep.ops.metrics.Std",
"widedeep.ops.metrics.AbsError",
"widedeep.ops.metrics.MedianPredError",... | [((503, 527), 'widedeep.utils.get_logger', 'utils.get_logger', (['"""data"""'], {}), "('data')\n", (519, 527), True, 'import widedeep.utils as utils\n'), ((619, 655), 'protodata.utils.get_data_location', 'get_data_location', (['Datasets.DIABETES'], {}), '(Datasets.DIABETES)\n', (636, 655), False, 'from protodata.utils ... |
from bs4 import BeautifulSoup
import os
import re
import argparse
class Person:
birthPlace: str
deathPlace: str
def __init__(self, person_id):
self.id = int(person_id)
self.name = None
self.relations = []
self.birthDate = ''
self.birthPlace = ''
self.deathDa... | [
"os.listdir",
"argparse.ArgumentParser",
"bs4.BeautifulSoup",
"re.sub",
"re.search"
] | [((584, 680), 'argparse.ArgumentParser', 'argparse.ArgumentParser', ([], {'description': '"""Process a download of an geneology.com user website."""'}), "(description=\n 'Process a download of an geneology.com user website.')\n", (607, 680), False, 'import argparse\n'), ((943, 986), 'bs4.BeautifulSoup', 'BeautifulSo... |
"""
ydatetime module
Utility module for datetime in yahoo japan.
"""
import datetime
from datetime import timedelta, timezone, tzinfo
import re
REGEXES = {
'date': r'^(\d{1,2})\/(\d{1,2})(?:[^\d]|$)',
'time': r'^(\d{1,2}):(\d{1,2})[^\d]+(\d{1,2}):(\d{1,2})$',
}
DEFAULT_TIMEDELTA = 9
def ... | [
"datetime.datetime",
"re.match",
"datetime.datetime.now",
"datetime.date",
"datetime.timedelta"
] | [((1666, 1698), 're.match', 're.match', (["REGEXES['date']", 'ydate'], {}), "(REGEXES['date'], ydate)\n", (1674, 1698), False, 'import re\n'), ((1877, 1908), 'datetime.date', 'datetime.date', (['year', 'month', 'day'], {}), '(year, month, day)\n', (1890, 1908), False, 'import datetime\n'), ((2173, 2205), 're.match', 'r... |
from __future__ import print_function # Python 2.x
import os
import numpy as np
import pandas as pd
import h5py
import sys
import math
from fnmatch import fnmatch
# helper functions klusta analysis pipeline
def get_param_file(filename,params_folder):
found = False
params = []
for path, subdirs, files in ... | [
"numpy.mean",
"os.path.exists",
"numpy.repeat",
"os.makedirs",
"numpy.searchsorted",
"h5py.File",
"numpy.array",
"math.fabs",
"sys.exit",
"pandas.DataFrame",
"numpy.cumsum",
"os.walk",
"sys.stdout.write"
] | [((320, 342), 'os.walk', 'os.walk', (['params_folder'], {}), '(params_folder)\n', (327, 342), False, 'import os\n'), ((6986, 7014), 'h5py.File', 'h5py.File', (['kwx_filename', '"""r"""'], {}), "(kwx_filename, 'r')\n", (6995, 7014), False, 'import h5py\n'), ((8032, 8063), 'numpy.cumsum', 'np.cumsum', (['samples_sessions... |
from requests.exceptions import RequestException
from tkinter import Button, Tk, Toplevel, Label
from tkinter.messagebox import askyesno
from pkg_resources import parse_version
from configparser import ConfigParser
from tkinter.ttk import Progressbar
from win32api import ShellExecute
from PIL import Image, ImageTk
from... | [
"os.path.exists",
"PIL.Image.open",
"configparser.ConfigParser",
"tkinter.messagebox.askyesno",
"pathlib.Path.home",
"tkinter.Toplevel.__init__",
"os.path.join",
"tkinter.Button",
"requests.get",
"pkg_resources.parse_version",
"tkinter.Tk",
"tkinter.Label",
"tkinter.ttk.Progressbar",
"win3... | [((589, 621), 'os.path.join', 'os_path.join', (['"""setup"""', 'file_name'], {}), "('setup', file_name)\n", (601, 621), True, 'from os import path as os_path\n'), ((2922, 2991), 'win32api.ShellExecute', 'ShellExecute', (['(0)', '"""open"""', 'f"""binaries\\\\{_AppName_}.exe"""', 'None', 'None', '(10)'], {}), "(0, 'open... |
Import("env")
import os
import tempfile
def cprint(*args, **kwargs):
print(f'pre_script_patch_debug.py:', *args, **kwargs)
def get_winterrupts_path():
winterrupts_path = None
for pio_package in env.PioPlatform().dump_used_packages():
pio_dir = env.PioPlatform().get_package_dir(pio_package['name... | [
"os.path.exists",
"os.path.join",
"tempfile.NamedTemporaryFile"
] | [((403, 462), 'os.path.join', 'os.path.join', (['pio_dir', '"""cores"""', '"""MegaCore"""', '"""WInterrupts.c"""'], {}), "(pio_dir, 'cores', 'MegaCore', 'WInterrupts.c')\n", (415, 462), False, 'import os\n'), ((474, 503), 'os.path.exists', 'os.path.exists', (['possible_path'], {}), '(possible_path)\n', (488, 503), Fals... |
#!/usr/bin/env python3
# -*- coding: utf-8 -*-
import tkinter
from tkinter import W, END, ttk, E
def create_log_view(frame: tkinter.Frame, row: int, initial_content: str = '', height=30):
row += 1
logs_view = tkinter.Text(frame, height=height)
logs_view.grid(padx=5, pady=5, row=row, column=0, columnspan=4... | [
"tkinter.Text",
"tkinter.ttk.Scrollbar"
] | [((219, 253), 'tkinter.Text', 'tkinter.Text', (['frame'], {'height': 'height'}), '(frame, height=height)\n', (231, 253), False, 'import tkinter\n'), ((362, 407), 'tkinter.ttk.Scrollbar', 'ttk.Scrollbar', (['frame'], {'command': 'logs_view.yview'}), '(frame, command=logs_view.yview)\n', (375, 407), False, 'from tkinter ... |
# define function to call pygal to make an svg graph
import pygal
def twoline(file_name, title, line1, line1_label, line2, line2_label, x_labels):
'''
Line 1 and 2 are lists of data points
Labels and x_labels correspond to the data points in line1 and line2
Example call:
line_graph.twoline("pynet... | [
"pygal.Line"
] | [((486, 517), 'pygal.Line', 'pygal.Line', ([], {'include_x_axis': '(True)'}), '(include_x_axis=True)\n', (496, 517), False, 'import pygal\n')] |
# -*- coding: utf-8 -*-
"""
Created on Wed May 20 12:31:14 2020
@author: nastavirs
"""
import tensorflow as tf
import numpy as np
def xavier_init(self, size):
in_dim = size[0]
out_dim = size[1]
xavier_stddev = np.sqrt(2/(in_dim + out_dim))
return tf.Variable(tf.trunc... | [
"numpy.sqrt",
"tensorflow.truncated_normal"
] | [((254, 285), 'numpy.sqrt', 'np.sqrt', (['(2 / (in_dim + out_dim))'], {}), '(2 / (in_dim + out_dim))\n', (261, 285), True, 'import numpy as np\n'), ((312, 372), 'tensorflow.truncated_normal', 'tf.truncated_normal', (['[in_dim, out_dim]'], {'stddev': 'xavier_stddev'}), '([in_dim, out_dim], stddev=xavier_stddev)\n', (331... |
import logging
import numpy as np
from scipy.stats import nbinom, poisson, binom
from scipy.special import gamma, factorial, gammaln, logsumexp, hyp2f1, hyp1f1, hyperu, factorial
class CountModel:
error_rate=0.01
class MultiplePoissonModel(CountModel):
def __init__(self, base_lambda, repeat_dist, certain_coun... | [
"scipy.special.hyperu",
"numpy.tile",
"scipy.special.gammaln",
"numpy.log",
"numpy.any",
"numpy.square",
"numpy.sum",
"numpy.zeros",
"numpy.array",
"numpy.empty",
"scipy.stats.poisson.logpmf",
"scipy.special.logsumexp",
"numpy.arange"
] | [((676, 706), 'numpy.tile', 'np.tile', (['allele_frequencies', '(2)'], {}), '(allele_frequencies, 2)\n', (683, 706), True, 'import numpy as np\n'), ((780, 803), 'numpy.arange', 'np.arange', (['n_duplicates'], {}), '(n_duplicates)\n', (789, 803), True, 'import numpy as np\n'), ((826, 866), 'numpy.zeros', 'np.zeros', (['... |
import numpy as np
import ds_format as ds
from rstoollib.algorithms import *
def postprocess(d):
"""Postprocess profile (prof) dataset d by calculating derived
variables."""
if 'zg' not in d and 'z' in d and 'lat' in d:
d['zg'] = calc_zg(d['z'], d['lat'])
if 'z' not in d and 'zg' in d and 'lat' in d:
d['z'] =... | [
"numpy.interp"
] | [((1065, 1115), 'numpy.interp', 'np.interp', (["d['p_lcl']", "d['p'][::-1]", "d['zg'][::-1]"], {}), "(d['p_lcl'], d['p'][::-1], d['zg'][::-1])\n", (1074, 1115), True, 'import numpy as np\n')] |
import io
import logging
import re
from contextlib import redirect_stdout
from threading import Thread
from typing import Dict, Callable
import botflow.matches as matches
log = logging.getLogger(__name__)
class Response:
def __init__(self, msg: str, response_action: Callable=None):
self.__msg = msg
... | [
"logging.getLogger",
"contextlib.redirect_stdout",
"re.compile",
"botflow.matches.equals",
"threading.Thread",
"io.StringIO"
] | [((179, 206), 'logging.getLogger', 'logging.getLogger', (['__name__'], {}), '(__name__)\n', (196, 206), False, 'import logging\n'), ((2878, 2910), 'botflow.matches.equals', 'matches.equals', (['command.__name__'], {}), '(command.__name__)\n', (2892, 2910), True, 'import botflow.matches as matches\n'), ((3978, 4045), 'r... |
from django.db import models
# Create your models here.
# head:str
# about:str
class Portfolio(models.Model):
head=models.CharField(max_length=200)
about=models.TextField()
| [
"django.db.models.TextField",
"django.db.models.CharField"
] | [((125, 157), 'django.db.models.CharField', 'models.CharField', ([], {'max_length': '(200)'}), '(max_length=200)\n', (141, 157), False, 'from django.db import models\n'), ((166, 184), 'django.db.models.TextField', 'models.TextField', ([], {}), '()\n', (182, 184), False, 'from django.db import models\n')] |
from .auto_node import AutoNode
from ...vendor.NodeGraphQt.base.port import Port
from ...constants import NodeCategory
import copy
class ImageNode(AutoNode):
__identifier__ = 'Utility'
NODE_CATEGORY = NodeCategory.IMAGE
def __init__(self, pre_generate=True):
super(ImageNode, self).__init__(defau... | [
"copy.deepcopy"
] | [((1732, 1764), 'copy.deepcopy', 'copy.deepcopy', (['self.defaultValue'], {}), '(self.defaultValue)\n', (1745, 1764), False, 'import copy\n')] |
from threading import Thread, Event
from datetime import timedelta
from time import sleep
class Job(Thread):
def __init__(self, interval: timedelta, execute, offset: timedelta=None, *args, **kwargs):
Thread.__init__(self)
self.stopped = Event()
self.interval: timedelta = interval
se... | [
"threading.Event",
"threading.Thread.__init__"
] | [((213, 234), 'threading.Thread.__init__', 'Thread.__init__', (['self'], {}), '(self)\n', (228, 234), False, 'from threading import Thread, Event\n'), ((258, 265), 'threading.Event', 'Event', ([], {}), '()\n', (263, 265), False, 'from threading import Thread, Event\n')] |
#!/usr/bin/env python3
from helper import Point
from part1 import process_file
def example_1() -> None:
"""
.#..#
.....
#####
....#
...##
with numbers:
.7..7
.....
67775
....7
...87
best location: (3, 4) with 8 other asteroids detected
"""
point, value = process_file("examples/part1/example1.txt")
... | [
"helper.Point",
"part1.process_file"
] | [((273, 316), 'part1.process_file', 'process_file', (['"""examples/part1/example1.txt"""'], {}), "('examples/part1/example1.txt')\n", (285, 316), False, 'from part1 import process_file\n'), ((517, 560), 'part1.process_file', 'process_file', (['"""examples/part1/example3.txt"""'], {}), "('examples/part1/example3.txt')\n... |
# -*- coding: utf-8 -*-
import os
import re
import sounddevice as sd
from utils import read_wav, write_wav
import numpy as np
from threading import Thread
import argparse
class DeviceNotFoundError(Exception):
pass
def record_target(file_path, length, fs, channels=2, append=False):
"""Records audio and writ... | [
"numpy.abs",
"re.escape",
"sounddevice.rec",
"os.makedirs",
"argparse.ArgumentParser",
"sounddevice.query_hostapis",
"utils.read_wav",
"sounddevice.query_devices",
"os.path.isfile",
"utils.write_wav",
"numpy.vstack",
"os.path.abspath",
"threading.Thread",
"numpy.pad",
"numpy.transpose",
... | [((705, 768), 'sounddevice.rec', 'sd.rec', (['length'], {'samplerate': 'fs', 'channels': 'channels', 'blocking': '(True)'}), '(length, samplerate=fs, channels=channels, blocking=True)\n', (711, 768), True, 'import sounddevice as sd\n'), ((785, 808), 'numpy.transpose', 'np.transpose', (['recording'], {}), '(recording)\n... |
# Copyright (c) 2016-present, Facebook, Inc.
#
# 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... | [
"caffe2.python.control_ops_util.add_if_op",
"caffe2.python.control_ops_util.add_while_op"
] | [((1054, 1162), 'caffe2.python.control_ops_util.add_if_op', 'add_if_op', (['model.net', 'cond_blob', 'external_blobs', 'then_model.net', '(else_model.net if else_model else None)'], {}), '(model.net, cond_blob, external_blobs, then_model.net, else_model.\n net if else_model else None)\n', (1063, 1162), False, 'from ... |
import pickle
from os.path import join
import numpy as np
import sys; sys.path.insert(0, '..'); sys.path.insert(0, '.')
from util import print_stats
file_path = '/data2/mengtial/Exp/ArgoVerse1.1/output/rt_htc_dconv2_ms_nm_s1.0/val/time_info.pkl'
time_info = pickle.load(open(file_path, 'rb'))
runtime_all_np = np.arr... | [
"numpy.array",
"sys.path.insert",
"util.print_stats"
] | [((72, 96), 'sys.path.insert', 'sys.path.insert', (['(0)', '""".."""'], {}), "(0, '..')\n", (87, 96), False, 'import sys\n'), ((98, 121), 'sys.path.insert', 'sys.path.insert', (['(0)', '"""."""'], {}), "(0, '.')\n", (113, 121), False, 'import sys\n'), ((314, 348), 'numpy.array', 'np.array', (["time_info['runtime_all']"... |
# -*- coding: utf-8 -*-
"""
pyTailor Example 3
"""
from pytailor import PythonTask, DAG, Workflow, Project, Inputs
import time
### workflow definition ###
inputs = Inputs()
with DAG(name="dag") as dag:
t1 = PythonTask(
function=time.sleep, name="task 1", args=[inputs.data.sleep_time[0]]
)
t2 ... | [
"pytailor.DAG",
"pytailor.PythonTask",
"pytailor.Workflow",
"pytailor.Inputs",
"pytailor.Project.from_name"
] | [((169, 177), 'pytailor.Inputs', 'Inputs', ([], {}), '()\n', (175, 177), False, 'from pytailor import PythonTask, DAG, Workflow, Project, Inputs\n'), ((557, 582), 'pytailor.Project.from_name', 'Project.from_name', (['"""Test"""'], {}), "('Test')\n", (574, 582), False, 'from pytailor import PythonTask, DAG, Workflow, Pr... |
'''
x^2 – Dy^2 = 1
Find the value of D ≤ 1000 in minimal solutions of x for which the largest value of x is obtained.
'''
import math
res ={}
nf = []
for D in range(2, 1000):
if not math.sqrt(D).is_integer():
found = False
for x in range(1150000, 1160000):
y = math.sqrt(((x*x - 1)/D))
if y.is_integer():
... | [
"math.sqrt"
] | [((271, 297), 'math.sqrt', 'math.sqrt', (['((x * x - 1) / D)'], {}), '((x * x - 1) / D)\n', (280, 297), False, 'import math\n'), ((185, 197), 'math.sqrt', 'math.sqrt', (['D'], {}), '(D)\n', (194, 197), False, 'import math\n')] |
import numpy as np
import pandas as pd
import xarray as xr
from sklearn.base import BaseEstimator,TransformerMixin
from .utils import events_to_xr_dim
class EpochTraceReducer(BaseEstimator,TransformerMixin):
"""Take event-aligned samples of traces from a population of neurons.
Traces are sampled relative to... | [
"xarray.concat"
] | [((2429, 2462), 'xarray.concat', 'xr.concat', (['tensor'], {'dim': 'concat_dim'}), '(tensor, dim=concat_dim)\n', (2438, 2462), True, 'import xarray as xr\n')] |
import app as vnpy_app
from time import sleep
import json
import handler
import script_handler
import time, datetime
import vnpy.trader.rqdata as rq
from vnpy.trader.object import HistoryRequest
from vnpy.trader.constant import Exchange, Interval
from kdj import calc_kdj
import pandas as pd
import matplotlib.pyplot as ... | [
"vnpy.event.EventEngine",
"func_test3.calc",
"bokeh.plotting.figure",
"time.sleep",
"bokeh.models.LabelSet",
"datetime.datetime",
"bokeh.models.Label",
"matplotlib.ticker.FuncFormatter",
"talib.SMA",
"vnpy.app.cta_strategy.ArrayManager",
"bokeh.io.show",
"matplotlib.dates.MonthLocator",
"mat... | [((944, 964), 'matplotlib.dates.YearLocator', 'mdates.YearLocator', ([], {}), '()\n', (962, 964), True, 'import matplotlib.dates as mdates\n'), ((989, 1010), 'matplotlib.dates.MonthLocator', 'mdates.MonthLocator', ([], {}), '()\n', (1008, 1010), True, 'import matplotlib.dates as mdates\n'), ((1038, 1064), 'matplotlib.d... |
from django import template
from django.contrib.auth.models import Group
from django.forms import CheckboxInput
register = template.Library()
@register.filter(name='addclass')
def addclass(value, arg):
return value.as_widget(attrs={'class': arg})
@register.filter(name='is_checkbox')
def is_checkbox(field):
... | [
"django.forms.CheckboxInput",
"django.contrib.auth.models.Group.objects.get",
"django.template.Library"
] | [((124, 142), 'django.template.Library', 'template.Library', ([], {}), '()\n', (140, 142), False, 'from django import template\n'), ((494, 528), 'django.contrib.auth.models.Group.objects.get', 'Group.objects.get', ([], {'name': 'group_name'}), '(name=group_name)\n', (511, 528), False, 'from django.contrib.auth.models i... |
from django.conf import settings
from django.contrib import auth, messages
from django.contrib.auth.decorators import login_required
from django.utils.translation import gettext_lazy as _
from ..models import create_user
SAFE_FIELDS = ['name', 'nickname']
def pull_userdata_from(ei):
for field in SAFE_FIELDS:
if n... | [
"django.utils.translation.gettext_lazy",
"django.contrib.auth.login"
] | [((1850, 1878), 'django.contrib.auth.login', 'auth.login', (['request', 'ei.user'], {}), '(request, ei.user)\n', (1860, 1878), False, 'from django.contrib import auth, messages\n'), ((1184, 1212), 'django.contrib.auth.login', 'auth.login', (['request', 'ei.user'], {}), '(request, ei.user)\n', (1194, 1212), False, 'from... |
#!/usr/bin/env python
# -*- coding: UTF-8 -*-
'''
@IDE :PyCharm
@Project :yjcL
@USER :yanyin
@File :ForLoop.py
@Author :yujiecong
@Date :2021/9/1 11:57
'''
import collections
from typing import List, Any
from restart.Enum.Enum import StatementType, ExpressionType, TokenType
from restart.Expressio... | [
"restart.ExpressionyjcL.BinaryOperation.BinaryOperation_yjcL.getExpressionValue",
"restart.Statement_yjcL.Assignment.Assignment_yjcL"
] | [((1096, 1152), 'restart.ExpressionyjcL.BinaryOperation.BinaryOperation_yjcL.getExpressionValue', 'BinaryOperation_yjcL.getExpressionValue', (['self.expression'], {}), '(self.expression)\n', (1135, 1152), False, 'from restart.ExpressionyjcL.BinaryOperation import BinaryOperation_yjcL\n'), ((1432, 1589), 'restart.Statem... |
#list
l = list((1, 2, 3, 4, 5))
l2 = list(range(10))
l3 = [-1, -2, -3, -4]
print("List => %r List2 => %r List3 => %r" %(l, l2, l3))
filtered_list = list(filter(lambda num: num % 2 == 0, l2))
print(filtered_list)
print(l[0])
print(l[1:4])
tup_list = list((("key", "value"), ("key1", "value1")))
for k, v in tup_list... | [
"collections.OrderedDict",
"collections.namedtuple",
"collections.deque",
"json.dumps",
"math.sqrt",
"collections.Counter",
"heapq.heappop",
"collections.defaultdict",
"queue.Queue",
"heapq.heapify"
] | [((613, 637), 'collections.Counter', 'collections.Counter', (['str'], {}), '(str)\n', (632, 637), False, 'import collections\n'), ((814, 835), 'collections.Counter', 'collections.Counter', ([], {}), '()\n', (833, 835), False, 'import collections\n'), ((984, 1013), 'collections.Counter', 'collections.Counter', (['"""013... |
#!/usr/bin/env python3
#encoding=utf-8
#-----------------------------------------------
# Usage: python3 3-timerdeco1.py
# Description: timing function decorators
#-----------------------------------------------
import sys
import time
force = list if sys.version_info[0] == 3 else lambda X: X
class Timer:
def... | [
"time.time"
] | [((450, 461), 'time.time', 'time.time', ([], {}), '()\n', (459, 461), False, 'import time\n'), ((524, 535), 'time.time', 'time.time', ([], {}), '()\n', (533, 535), False, 'import time\n')] |
"""
Test for fake_data_generator.py
"""
import numpy as np
from deepchem.utils.fake_data_generator import FakeGraphGenerator, generate_edge_index, remove_self_loops
def test_fake_graph_dataset():
n_graphs = 10
n_node_features = 5
n_edge_features = 3
n_classes = 2
z_shape = 5
# graph-level labels
fgg = ... | [
"numpy.ones",
"numpy.unique",
"deepchem.utils.fake_data_generator.FakeGraphGenerator",
"numpy.array",
"deepchem.utils.fake_data_generator.remove_self_loops",
"deepchem.utils.fake_data_generator.generate_edge_index"
] | [((320, 500), 'deepchem.utils.fake_data_generator.FakeGraphGenerator', 'FakeGraphGenerator', ([], {'min_nodes': '(3)', 'max_nodes': '(10)', 'n_node_features': 'n_node_features', 'avg_degree': '(4)', 'n_edge_features': 'n_edge_features', 'n_classes': 'n_classes', 'task': '"""graph"""', 'z': 'z_shape'}), "(min_nodes=3, m... |
from flask import Blueprint, g, request, current_app
import json
import logging
from ..utils import datetime_to_json, get_time_string, get_default_runtime, match_movie
import datetime
from ..pick_algo import pick_movies_by_num, pick_movies_by_time
from .auth import login_required
import pandas
import pathlib
from .. i... | [
"logging.getLogger",
"flask.request.args.get",
"pathlib.Path",
"json.dumps",
"flask.request.get_json",
"pandas.DataFrame",
"flask.Blueprint"
] | [((339, 366), 'logging.getLogger', 'logging.getLogger', (['__name__'], {}), '(__name__)\n', (356, 366), False, 'import logging\n'), ((372, 422), 'flask.Blueprint', 'Blueprint', (['"""movies"""', '__name__'], {'url_prefix': '"""/movie"""'}), "('movies', __name__, url_prefix='/movie')\n", (381, 422), False, 'from flask i... |
from .exporter import Exporter
import functools
import numpy as np
import pandas as pd
class ExporterTwFull(Exporter):
''' Similar to ExporterTwEn but remaining zh-tw and korean
'''
def _get_df1(self, tsv):
return self.df_tws[tsv]
def _make_df_result(self, df, tsv):
return np.where(~d... | [
"pandas.merge"
] | [((539, 582), 'pandas.merge', 'pd.merge', (['df1', 'dfm'], {'on': '"""korean"""', 'how': '"""left"""'}), "(df1, dfm, on='korean', how='left')\n", (547, 582), True, 'import pandas as pd\n')] |
import datetime
import math
import re
import types
from typing import Any
from git import List
import numpy as np
import torch
from pandas import DataFrame as df
from PIL import Image
from torchvision import transforms
def getprice(img:List[Any], transform:Any, info:int,types:List[Any]):
val={}
for type in ty... | [
"numpy.mean",
"PIL.Image.open",
"torchvision.transforms.ToPILImage",
"math.log2",
"torch.from_numpy",
"numpy.diag",
"numpy.array",
"numpy.stack",
"numpy.outer",
"numpy.concatenate",
"re.search"
] | [((584, 606), 'numpy.mean', 'np.mean', (['item[162:192]'], {}), '(item[162:192])\n', (591, 606), True, 'import numpy as np\n'), ((616, 638), 'numpy.mean', 'np.mean', (['item[192:222]'], {}), '(item[192:222])\n', (623, 638), True, 'import numpy as np\n'), ((1868, 1890), 'numpy.stack', 'np.stack', (['[m1, n1, o1]'], {}),... |
import pytest
from ymmsl import Reference, Settings
from libmuscle.settings_manager import SettingsManager
@pytest.fixture
def settings_manager() -> SettingsManager:
return SettingsManager()
def test_create(settings_manager):
assert len(settings_manager.base) == 0
assert len(settings_manager.overlay) =... | [
"ymmsl.Settings",
"libmuscle.settings_manager.SettingsManager"
] | [((180, 197), 'libmuscle.settings_manager.SettingsManager', 'SettingsManager', ([], {}), '()\n', (195, 197), False, 'from libmuscle.settings_manager import SettingsManager\n'), ((791, 801), 'ymmsl.Settings', 'Settings', ([], {}), '()\n', (799, 801), False, 'from ymmsl import Reference, Settings\n')] |
from project import app
from flask import render_template
@app.route('/')
def index():
return "<h1>Página principal do backend. Você não deveria estar aqui.</h1>"
app.run(debug=True) | [
"project.app.run",
"project.app.route"
] | [((61, 75), 'project.app.route', 'app.route', (['"""/"""'], {}), "('/')\n", (70, 75), False, 'from project import app\n'), ((170, 189), 'project.app.run', 'app.run', ([], {'debug': '(True)'}), '(debug=True)\n', (177, 189), False, 'from project import app\n')] |
#!/usr/bin/env python
import os
import sys
import settings
import proxies
import collectors
import interfaces
import datastores
if __name__ == '__main__':
import asyncore
import pprint
pprint.pprint(sys.modules)
asyncore.loop()
| [
"pprint.pprint",
"asyncore.loop"
] | [((195, 221), 'pprint.pprint', 'pprint.pprint', (['sys.modules'], {}), '(sys.modules)\n', (208, 221), False, 'import pprint\n'), ((225, 240), 'asyncore.loop', 'asyncore.loop', ([], {}), '()\n', (238, 240), False, 'import asyncore\n')] |
from appinit_backend.lib.imports import *
import random, time
permissions = "developer"
def call(**kwargs):
manager = Manager()
db = manager.db("test")
start = time.time()
limit = 1000
a = [i for i in range(0, limit)]
# index = random.randint(0, limit)
# print("Running test with", index)
_ids... | [
"time.time"
] | [((171, 182), 'time.time', 'time.time', ([], {}), '()\n', (180, 182), False, 'import random, time\n'), ((542, 553), 'time.time', 'time.time', ([], {}), '()\n', (551, 553), False, 'import random, time\n')] |
# -*- coding: utf-8 -*-
import requests
r = requests.post("http://0.0.0.0:8080/tokenize/impl", params={'text':'3.janúar sl. keypti ég 64kWst rafbíl. Hann kostaði € 30.000'})
print(r.text)
assert r.text == '{"response":{"type":"texts","content":[["3.","janúar","sl.","keypti","ég","64kWst","rafbíl","."],["Hann","kosta... | [
"requests.post"
] | [((45, 181), 'requests.post', 'requests.post', (['"""http://0.0.0.0:8080/tokenize/impl"""'], {'params': "{'text': '3.janúar sl. keypti ég 64kWst rafbíl. Hann kostaði € 30.000'}"}), "('http://0.0.0.0:8080/tokenize/impl', params={'text':\n '3.janúar sl. keypti ég 64kWst rafbíl. Hann kostaði € 30.000'})\n", (58, 18... |
"""SpeedTester."""
import datetime
import json
import dateutil.parser
class SpeedTestResult(object):
"""Represents the results of a test performed by a SpeedTester."""
def __init__(self, download, startTime, ping=None, upload=None, endTime=None):
"""Results of a speedtest performed by a SpeedTester."... | [
"datetime.datetime.now",
"json.dumps"
] | [((1132, 1148), 'json.dumps', 'json.dumps', (['self'], {}), '(self)\n', (1142, 1148), False, 'import json\n'), ((584, 607), 'datetime.datetime.now', 'datetime.datetime.now', ([], {}), '()\n', (605, 607), False, 'import datetime\n')] |
"""
This module contains classes for PSU controllers that supports the SNMP management protocol.
The classes must implement the PsuControllerBase interface defined in controller_base.py.
"""
import logging
from controller_base import PsuControllerBase
from controller_base import run_local_cmd
def get_psu_controller... | [
"controller_base.run_local_cmd",
"controller_base.PsuControllerBase.__init__",
"logging.info"
] | [((693, 711), 'controller_base.run_local_cmd', 'run_local_cmd', (['cmd'], {}), '(cmd)\n', (706, 711), False, 'from controller_base import run_local_cmd\n'), ((2579, 2634), 'logging.info', 'logging.info', (["('Initializing ' + self.__class__.__name__)"], {}), "('Initializing ' + self.__class__.__name__)\n", (2591, 2634)... |
from models import Store
def operationsMenu():
print(f'========== Menu ==========')
print(f'[1] Adicionar bicicleta')
print(f'[2] Adicionar cliente')
print(f'[3] Exibir biciletas')
print(f'[4] Adicionar aluguel')
print(f'[5] Calcular aluguel')
print(f'[0] Sair')
print(f'================... | [
"models.Store"
] | [((553, 585), 'models.Store', 'Store', (['store_name', 'store_address'], {}), '(store_name, store_address)\n', (558, 585), False, 'from models import Store\n')] |
# Copyright 2019 Google LLC, <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 w... | [
"absl.app.run",
"absl.flags.DEFINE_string",
"pandas.read_csv",
"absl.flags.mark_flag_as_required"
] | [((1954, 2040), 'absl.flags.DEFINE_string', 'flags.DEFINE_string', (['"""results_csv_path"""', 'None', '"""Path to ViSQOL results_csv output"""'], {}), "('results_csv_path', None,\n 'Path to ViSQOL results_csv output')\n", (1973, 2040), False, 'from absl import flags\n'), ((2057, 2199), 'absl.flags.DEFINE_string', '... |
# Copyright 2021 Google Inc. All Rights Reserved.
#
# Licensed under the Apache License, Version 2.0 (the "License");
# you may not use this file except in compliance with the License.
# You may obtain a copy of the License at
#
# http://www.apache.org/licenses/LICENSE-2.0
#
# Unless required by applicable law or ag... | [
"tensorflow.compat.v1.placeholder",
"tensorflow.compat.v1.Graph",
"tensorflow.compat.v1.reduce_sum",
"unittest.mock.MagicMock",
"numpy.count_nonzero",
"numpy.testing.assert_almost_equal",
"numpy.array",
"tensorflow.compat.v1.sin",
"tensorflow.compat.v1.gradients",
"scipy.ndimage.gaussian_filter",
... | [((6359, 6374), 'unittest.main', 'unittest.main', ([], {}), '()\n', (6372, 6374), False, 'import unittest\n'), ((3551, 3617), 'numpy.testing.assert_almost_equal', 'np.testing.assert_almost_equal', (['mask', 'self.expected_val'], {'decimal': '(2)'}), '(mask, self.expected_val, decimal=2)\n', (3581, 3617), True, 'import ... |
import asyncio
from aiolo import Address, Midi, Server
async def main():
server = Server(port=12001)
server.start()
# Create endpoints
# /foo accepts an int, a float, and a MIDI packet
foo = server.route('/foo', [int, float, Midi])
ex = server.route('/exit')
address = Address(port=120... | [
"aiolo.Address",
"asyncio.get_event_loop",
"aiolo.Midi",
"aiolo.Server"
] | [((90, 108), 'aiolo.Server', 'Server', ([], {'port': '(12001)'}), '(port=12001)\n', (96, 108), False, 'from aiolo import Address, Midi, Server\n'), ((304, 323), 'aiolo.Address', 'Address', ([], {'port': '(12001)'}), '(port=12001)\n', (311, 323), False, 'from aiolo import Address, Midi, Server\n'), ((387, 403), 'aiolo.M... |
import random
from copy import deepcopy
# import geopandas
from math import floor
from typing import List
from Day import Day
# import gmplot
from Item import Item
from haversine import haversine
# import networkx as nx
API_KEY = '<KEY>'
# with open('../../../testing/samples/milan_trip_data.pkl', 'rb') as input:
# ... | [
"random.choice",
"haversine.haversine",
"copy.deepcopy"
] | [((599, 624), 'haversine.haversine', 'haversine', (['tuple1', 'tuple2'], {}), '(tuple1, tuple2)\n', (608, 624), False, 'from haversine import haversine\n'), ((1075, 1105), 'random.choice', 'random.choice', (['self.food_types'], {}), '(self.food_types)\n', (1088, 1105), False, 'import random\n'), ((1107, 1136), 'random.... |
#!/usr/bin/python
import cProfile
def lex_gen():
def find_indices(a):
j, k = len(a) - 2, -1
while not a[j] < a[j + 1]:
j -= 1
if j == -1:
return (j, k)
k = len(a) - 1
while not a[j] < a[k]:
k -= 1
return (j, k)
a ... | [
"cProfile.run"
] | [((1037, 1065), 'cProfile.run', 'cProfile.run', (['"""answer = m()"""'], {}), "('answer = m()')\n", (1049, 1065), False, 'import cProfile\n')] |
# -*- coding: utf-8 -*-
"""说明:
select
"""
import select
import socket
from queue import Queue # message queue
import time
def run(host='localhost', port=8086):
with socket.socket(socket.AF_INET, socket.SOCK_STREAM) as server:
# https://docs.python.org/3/library/socket.html#socket.socket.setblocking
... | [
"select.select",
"queue.Queue",
"socket.socket"
] | [((173, 222), 'socket.socket', 'socket.socket', (['socket.AF_INET', 'socket.SOCK_STREAM'], {}), '(socket.AF_INET, socket.SOCK_STREAM)\n', (186, 222), False, 'import socket\n'), ((895, 929), 'select.select', 'select.select', (['rlist', 'wlist', 'rlist'], {}), '(rlist, wlist, rlist)\n', (908, 929), False, 'import select\... |
# -*- coding: utf-8 -*-
"""
Created on Thu Mar 26 08:37:26 2020
@author: jarl.robert.pedersen
"""
import requests
import json
from tqdm import tqdm
from bs4 import BeautifulSoup
import re
import sqlite3
import os
import time
import warnings
from fake_useragent import UserAgent
def responce_manager(url, headers):
... | [
"os.listdir",
"sqlite3.connect",
"tqdm.tqdm",
"requests.get",
"time.sleep",
"bs4.BeautifulSoup",
"warnings.warn",
"fake_useragent.UserAgent",
"re.search"
] | [((736, 747), 'fake_useragent.UserAgent', 'UserAgent', ([], {}), '()\n', (745, 747), False, 'from fake_useragent import UserAgent\n'), ((858, 875), 'tqdm.tqdm', 'tqdm', ([], {'total': '(75000)'}), '(total=75000)\n', (862, 875), False, 'from tqdm import tqdm\n'), ((897, 913), 'os.listdir', 'os.listdir', (['"""./"""'], {... |
# coding=utf-8
#Copyright (C) 2017. Huawei Technologies Co., LTD. All rights reserved.
#
#This program is free software; you can redistribute it and/or modify
#it under the terms of Apache License, Version 2.0.
#
#This program is distributed in the hope that it will be useful,
#but WITHOUT ANY WARRANTY; without even t... | [
"smnsdkcore.request.CommonRequest.get_request_body_param"
] | [((1470, 1512), 'smnsdkcore.request.CommonRequest.get_request_body_param', 'CommonRequest.get_request_body_param', (['self'], {}), '(self)\n', (1506, 1512), False, 'from smnsdkcore.request import CommonRequest\n')] |
from django.test import TestCase
from rest_framework import serializers
class EmptySerializerTestCase(TestCase):
def test_empty_serializer(self):
class FooBarSerializer(serializers.Serializer):
foo = serializers.IntegerField()
bar = serializers.SerializerMethodField('get_bar')
... | [
"rest_framework.serializers.IntegerField",
"rest_framework.serializers.SerializerMethodField"
] | [((226, 252), 'rest_framework.serializers.IntegerField', 'serializers.IntegerField', ([], {}), '()\n', (250, 252), False, 'from rest_framework import serializers\n'), ((271, 315), 'rest_framework.serializers.SerializerMethodField', 'serializers.SerializerMethodField', (['"""get_bar"""'], {}), "('get_bar')\n", (304, 315... |
import forbiddenfruit as ff
@ff.curses(str, "length")
@property
def str_length(self) -> int:
return len(self)
@ff.curses(str, "search")
def str_search(self, other) -> int:
return self.find(other)
@ff.curses(str, "indexOf")
def str_indexOf(self, other, startPos:int=0) -> int:
return self[startPos:].find(o... | [
"forbiddenfruit.curses"
] | [((30, 54), 'forbiddenfruit.curses', 'ff.curses', (['str', '"""length"""'], {}), "(str, 'length')\n", (39, 54), True, 'import forbiddenfruit as ff\n'), ((117, 141), 'forbiddenfruit.curses', 'ff.curses', (['str', '"""search"""'], {}), "(str, 'search')\n", (126, 141), True, 'import forbiddenfruit as ff\n'), ((208, 233), ... |
import uasyncio as asyncio
class LedStripController:
def __init__(self, enc, button_pin, fader_pins):
''' enc should be an instance of Encoder.
button_pin is expected to be an instance of machine.Pin.
fader_pins is expected to be an iterable of machine.PWM's.
'''
s... | [
"uasyncio.sleep_ms"
] | [((1019, 1040), 'uasyncio.sleep_ms', 'asyncio.sleep_ms', (['(100)'], {}), '(100)\n', (1035, 1040), True, 'import uasyncio as asyncio\n'), ((1744, 1765), 'uasyncio.sleep_ms', 'asyncio.sleep_ms', (['(100)'], {}), '(100)\n', (1760, 1765), True, 'import uasyncio as asyncio\n'), ((2213, 2233), 'uasyncio.sleep_ms', 'asyncio.... |
import database
import pandas as pd
import xlsxwriter as xl
import dill as pickle
import configparser
import os
from io import BytesIO
class Model:
# This function is used to predict any model the user uploads to the flask app.
# Depending on user's settings the function returns a file with predicted ... | [
"configparser.ConfigParser",
"pandas.read_csv",
"io.BytesIO",
"os.chdir",
"xlsxwriter.Workbook",
"dill.load"
] | [((484, 511), 'configparser.ConfigParser', 'configparser.ConfigParser', ([], {}), '()\n', (509, 511), False, 'import configparser\n'), ((576, 595), 'os.chdir', 'os.chdir', (['file_path'], {}), '(file_path)\n', (584, 595), False, 'import os\n'), ((611, 641), 'pandas.read_csv', 'pd.read_csv', (['testing_data_name'], {}),... |
import numpy as np
# ==============================================================================
# Funcion que calcula el coeficiente de arrastre de una esfera en caida libre
# Funciona con Reynolds descde 0 hasta m'as all'a de 3e6
# ==============================================================================
def ... | [
"numpy.zeros",
"numpy.zeros_like",
"numpy.logical_and"
] | [((1750, 1761), 'numpy.zeros', 'np.zeros', (['(4)'], {}), '(4)\n', (1758, 1761), True, 'import numpy as np\n'), ((1771, 1788), 'numpy.zeros_like', 'np.zeros_like', (['dv'], {}), '(dv)\n', (1784, 1788), True, 'import numpy as np\n'), ((505, 536), 'numpy.logical_and', 'np.logical_and', (['(Re > 0)', '(Re <= 1)'], {}), '(... |
from __future__ import print_function, division, absolute_import
from fontTools.misc.py23 import *
from fontTools.misc.testTools import parseXML, FakeFont
from fontTools.misc.xmlWriter import XMLWriter
import fontTools.ttLib.tables.otTables as otTables
import unittest
def makeCoverage(glyphs):
coverage = otTables... | [
"fontTools.ttLib.tables.otTables.Ligature",
"fontTools.misc.testTools.parseXML",
"fontTools.ttLib.tables.otTables.Coverage",
"fontTools.misc.testTools.FakeFont",
"fontTools.ttLib.tables.otTables.MultipleSubst",
"fontTools.ttLib.tables.otTables.LigatureSet",
"fontTools.ttLib.tables.otTables.AlternateSubs... | [((312, 331), 'fontTools.ttLib.tables.otTables.Coverage', 'otTables.Coverage', ([], {}), '()\n', (329, 331), True, 'import fontTools.ttLib.tables.otTables as otTables\n'), ((526, 547), 'fontTools.misc.testTools.FakeFont', 'FakeFont', (['self.glyphs'], {}), '(self.glyphs)\n', (534, 547), False, 'from fontTools.misc.test... |
"""
https://adventofcode.com/2018/day/2
"""
from collections import Counter
from itertools import product
from pathlib import Path
def solve_a(codes):
pairs = triplets = 0
for code in codes:
occurrences = Counter(code).values()
pairs += any(count == 2 for count in occurrences)
triplet... | [
"collections.Counter",
"itertools.product",
"pathlib.Path"
] | [((442, 463), 'itertools.product', 'product', (['codes', 'codes'], {}), '(codes, codes)\n', (449, 463), False, 'from itertools import product\n'), ((224, 237), 'collections.Counter', 'Counter', (['code'], {}), '(code)\n', (231, 237), False, 'from collections import Counter\n'), ((1008, 1025), 'pathlib.Path', 'Path', ([... |
# -*- coding: utf-8 -*-
# @Time : 2020/4/20
# @File : network.py
# @Software: PyCharm
import tensorflow as tf
###RFB
def _BasicConv(x, out_planes, kernel_size, stride=1, padding='same', dilation=1, activation=1, use_l2=False,
use_bn=True, use_bias=False):
'''
Basic Convolution Layer
'''
... | [
"tensorflow.keras.layers.Input",
"tensorflow.keras.layers.Reshape",
"tensorflow.keras.layers.Concatenate",
"tensorflow.keras.layers.Conv2D",
"tensorflow.keras.layers.SeparableConv2D",
"tensorflow.keras.layers.MaxPooling2D",
"tensorflow.keras.layers.Lambda",
"tensorflow.keras.layers.ReLU",
"tensorflo... | [((8761, 8850), 'tensorflow.keras.layers.Input', 'tf.keras.layers.Input', ([], {'shape': '[image_sizes[0], image_sizes[1], 3]', 'name': '"""input_image"""'}), "(shape=[image_sizes[0], image_sizes[1], 3], name=\n 'input_image')\n", (8782, 8850), True, 'import tensorflow as tf\n'), ((10516, 10577), 'tensorflow.keras.M... |
from rest_framework import routers
from .views import CategoryViewSet, RequestViewSet, PoliceOfficeViewSet
router = routers.SimpleRouter()
router.register(r'police', PoliceOfficeViewSet)
router.register(r'category', CategoryViewSet)
router.register(r'', RequestViewSet)
urlpatterns = [
]
urlpatterns += router.urls
| [
"rest_framework.routers.SimpleRouter"
] | [((117, 139), 'rest_framework.routers.SimpleRouter', 'routers.SimpleRouter', ([], {}), '()\n', (137, 139), False, 'from rest_framework import routers\n')] |