code stringlengths 22 1.05M | apis listlengths 1 3.31k | extract_api stringlengths 75 3.25M |
|---|---|---|
# Generated by Django 2.0.4 on 2018-06-23 02:13
from django.db import migrations, models
class Migration(migrations.Migration):
dependencies = [
('accounts', '0002_adminprofile_businessprofile_eventprofile_participantprofile'),
]
operations = [
migrations.AlterField(
model_n... | [
"django.db.models.PositiveSmallIntegerField"
] | [((380, 513), 'django.db.models.PositiveSmallIntegerField', 'models.PositiveSmallIntegerField', ([], {'blank': '(True)', 'choices': "[(1, 'paticipant'), (2, 'business'), (3, 'event'), (4, 'admin')]", 'null': '(True)'}), "(blank=True, choices=[(1, 'paticipant'), (2,\n 'business'), (3, 'event'), (4, 'admin')], null=Tr... |
import sys
from argparse import ArgumentParser
if __name__ == "__main__":
argv = sys.argv[1:]
parser = ArgumentParser()
if len(argv) == 0:
parser.print_help()
parser.exit(1)
parser.add_argument("dataset_path", type=str,
help="Path to the directory containing the... | [
"argparse.ArgumentParser"
] | [((112, 128), 'argparse.ArgumentParser', 'ArgumentParser', ([], {}), '()\n', (126, 128), False, 'from argparse import ArgumentParser\n')] |
"""Tests related to embargoes of registrations"""
import datetime
import json
import mock
from nose.tools import * #noqa
from tests.base import fake, OsfTestCase
from tests.factories import (
AuthUserFactory, EmbargoFactory, NodeFactory, ProjectFactory,
RegistrationFactory, UserFactory, UnconfirmedUserFactory... | [
"tests.factories.NodeFactory",
"tests.factories.UnconfirmedUserFactory",
"tests.factories.UserFactory",
"website.models.Embargo.find",
"tests.factories.RegistrationFactory",
"tests.factories.ProjectFactory",
"mock.patch",
"datetime.datetime.now",
"website.project.model.ensure_schemas",
"datetime.d... | [((26978, 27029), 'mock.patch', 'mock.patch', (['"""framework.tasks.handlers.enqueue_task"""'], {}), "('framework.tasks.handlers.enqueue_task')\n", (26988, 27029), False, 'import mock\n'), ((27609, 27660), 'mock.patch', 'mock.patch', (['"""framework.tasks.handlers.enqueue_task"""'], {}), "('framework.tasks.handlers.enq... |
import falcon
import simplejson as json
import mysql.connector
import config
import uuid
from core.useractivity import user_logger, access_control
class CombinedEquipmentCollection:
@staticmethod
def __init__():
""" Initializes CombinedEquipmentCollection"""
pass
@staticmethod
def on_... | [
"uuid.uuid4",
"falcon.HTTPError",
"simplejson.dumps",
"core.useractivity.access_control",
"simplejson.loads"
] | [((2253, 2271), 'simplejson.dumps', 'json.dumps', (['result'], {}), '(result)\n', (2263, 2271), True, 'import simplejson as json\n'), ((2380, 2399), 'core.useractivity.access_control', 'access_control', (['req'], {}), '(req)\n', (2394, 2399), False, 'from core.useractivity import user_logger, access_control\n'), ((2611... |
from .serializers import CategorySerializer, TaskSerializer, MemberSerializer, ProjectSerializer
from .models import Categories, Tasks, Members, Projects
from rest_framework import status
from rest_framework.parsers import JSONParser
from django.http.response import JsonResponse
from django.views.decorators.csrf import... | [
"django.http.response.JsonResponse",
"rest_framework.parsers.JSONParser"
] | [((551, 619), 'django.http.response.JsonResponse', 'JsonResponse', (['serializer.data'], {'safe': '(False)', 'status': 'status.HTTP_200_OK'}), '(serializer.data, safe=False, status=status.HTTP_200_OK)\n', (563, 619), False, 'from django.http.response import JsonResponse\n'), ((1951, 2019), 'django.http.response.JsonRes... |
import kubernetes.config
import logging
import logging.config
from pengrixio.config import KUBECONFIG
logging.config.fileConfig('logging.conf')
log = logging.getLogger('pengrixio')
# load kubernetes config file.
try:
kubernetes.config.load_kube_config(KUBECONFIG)
except:
log.warn('kubernetes cluster config ... | [
"logging.config.fileConfig",
"logging.getLogger"
] | [((105, 146), 'logging.config.fileConfig', 'logging.config.fileConfig', (['"""logging.conf"""'], {}), "('logging.conf')\n", (130, 146), False, 'import logging\n'), ((153, 183), 'logging.getLogger', 'logging.getLogger', (['"""pengrixio"""'], {}), "('pengrixio')\n", (170, 183), False, 'import logging\n')] |
import param
from panel import panel
from panel.reactive import ReactiveHTML
from panel.widgets import FileDownload
try:
# Backward compatibility for panel 0.12.6
import bokeh.core.properties as bp
from panel.links import PARAM_MAPPING
# The Bokeh Color property has `_default_help` set which causes
... | [
"param.Integer",
"param.depends",
"panel.links.Callback",
"param.Color",
"param.Boolean",
"bokeh.core.properties.Color",
"panel.panel",
"param.Callable",
"panel.widgets.FileDownload",
"param.String"
] | [((767, 796), 'param.Callable', 'param.Callable', ([], {'precedence': '(-1)'}), '(precedence=-1)\n', (781, 796), False, 'import param\n'), ((810, 854), 'param.Color', 'param.Color', ([], {'default': '"""grey"""', 'allow_None': '(True)'}), "(default='grey', allow_None=True)\n", (821, 854), False, 'import param\n'), ((86... |
"""
This file contains the necessary to reconstruct the intermediary featuress from
a save of the models an inputs
Author Hugues
"""
import torch
from pathlib import Path
if __name__ == '__main__':
import sys
sys.path.append("..")
from param import data_path
file_location = Path(data_path) / Path('models')
... | [
"sys.path.append",
"pathlib.Path",
"torch.load",
"models.store_model_SHL.create_filename"
] | [((220, 241), 'sys.path.append', 'sys.path.append', (['""".."""'], {}), "('..')\n", (235, 241), False, 'import sys\n'), ((287, 302), 'pathlib.Path', 'Path', (['data_path'], {}), '(data_path)\n', (291, 302), False, 'from pathlib import Path\n'), ((305, 319), 'pathlib.Path', 'Path', (['"""models"""'], {}), "('models')\n"... |
import uos
from flashbdev import bdev
def check_bootsec():
buf = bytearray(bdev.ioctl(5, 0)) # 5 is SEC_SIZE
bdev.readblocks(0, buf)
empty = True
for b in buf:
if b != 0xFF:
empty = False
break
if empty:
return True
fs_corrupted()
def fs_corrupted():
... | [
"flashbdev.bdev.readblocks",
"uos.mount",
"flashbdev.bdev.ioctl",
"time.sleep",
"uos.VfsLfs2",
"uos.VfsLfs2.mkfs"
] | [((120, 143), 'flashbdev.bdev.readblocks', 'bdev.readblocks', (['(0)', 'buf'], {}), '(0, buf)\n', (135, 143), False, 'from flashbdev import bdev\n'), ((753, 775), 'uos.VfsLfs2.mkfs', 'uos.VfsLfs2.mkfs', (['bdev'], {}), '(bdev)\n', (769, 775), False, 'import uos\n'), ((786, 803), 'uos.VfsLfs2', 'uos.VfsLfs2', (['bdev'],... |
# The MIT License (MIT)
#
# Copyright (c) 2018 <NAME>
#
# Permission is hereby granted, free of charge, to any person obtaining a copy
# of this software and associated documentation files (the "Software"), to deal
# in the Software without restriction, including without limitation the rights
# to use, copy, modify, me... | [
"textwrap.dedent",
"ast.Del",
"ast.Load",
"ast.fix_missing_locations",
"ast.dump",
"ast.copy_location",
"ast.parse",
"ast.Store",
"ast.Str"
] | [((2324, 2845), 'textwrap.dedent', 'textwrap.dedent', (['"""\n # We can not use __import__(module, fromlist=[None]) as some modules seem\n # to break with it (see for example nose-devs/nose#1075).\n import importlib as __importlib\n __module = __importlib.import_module({module!r})\n try:\n __vars = ... |
#!/use/bin/python
import sys
from sense_hat import SenseHat
import variables.colors as c
import variables.mode as m
from libs.set_color import *
def set_color_terminal():
sense = SenseHat()
try:
color = input("Type an rgb color: ")
except (KeyboardInterrupt, SystemExit):
sys.exit()
ex... | [
"sense_hat.SenseHat",
"sys.exit"
] | [((185, 195), 'sense_hat.SenseHat', 'SenseHat', ([], {}), '()\n', (193, 195), False, 'from sense_hat import SenseHat\n'), ((303, 313), 'sys.exit', 'sys.exit', ([], {}), '()\n', (311, 313), False, 'import sys\n'), ((565, 575), 'sys.exit', 'sys.exit', ([], {}), '()\n', (573, 575), False, 'import sys\n')] |
#
# ovirt-engine-setup -- ovirt engine setup
#
# Copyright oVirt Authors
# SPDX-License-Identifier: Apache-2.0
#
#
"""Utils."""
import gettext
import grp
import pwd
import re
from otopi import constants as otopicons
from otopi import plugin
from otopi import util
def _(m):
return gettext.dgettext(message=m, ... | [
"gettext.dgettext",
"otopi.minidnf.MiniDNF",
"pwd.getpwnam",
"grp.getgrnam",
"re.compile"
] | [((292, 348), 'gettext.dgettext', 'gettext.dgettext', ([], {'message': 'm', 'domain': '"""ovirt-engine-setup"""'}), "(message=m, domain='ovirt-engine-setup')\n", (308, 348), False, 'import gettext\n'), ((2749, 2794), 're.compile', 're.compile', ([], {'flags': 're.VERBOSE', 'pattern': 'pattern'}), '(flags=re.VERBOSE, pa... |
"""Support for SUPLA MQTT sensors."""
from datetime import timedelta
import logging
import homeassistant.components.mqtt as hass_mqtt
from homeassistant.core import callback
from homeassistant.helpers.entity import Entity
from .const import DOMAIN
_LOGGER = logging.getLogger(__name__)
SCAN_INTERVAL = timedelta(minut... | [
"homeassistant.components.mqtt.subscription.async_subscribe_topics",
"homeassistant.components.mqtt.subscription.async_unsubscribe_topics",
"datetime.timedelta",
"logging.getLogger"
] | [((261, 288), 'logging.getLogger', 'logging.getLogger', (['__name__'], {}), '(__name__)\n', (278, 288), False, 'import logging\n'), ((305, 325), 'datetime.timedelta', 'timedelta', ([], {'minutes': '(2)'}), '(minutes=2)\n', (314, 325), False, 'from datetime import timedelta\n'), ((1656, 2182), 'homeassistant.components.... |
import scipy.sparse as sp
import pandas as pd
import numpy as np
import torch
import h5py
def get_adj(num_rows, num_cols, row_idx, col_idx, device):
adj = torch.zeros((num_rows, num_cols), dtype=torch.float32, device=device)
adj[row_idx, col_idx] = 1.
adj = adj / adj.sum(dim=1, keepdim=True)
adj.mas... | [
"pandas.DataFrame",
"h5py.File",
"numpy.asarray",
"numpy.argwhere",
"scipy.sparse.csc_matrix",
"torch.zeros",
"torch.isnan",
"numpy.concatenate"
] | [((162, 231), 'torch.zeros', 'torch.zeros', (['(num_rows, num_cols)'], {'dtype': 'torch.float32', 'device': 'device'}), '((num_rows, num_cols), dtype=torch.float32, device=device)\n', (173, 231), False, 'import torch\n'), ((424, 449), 'h5py.File', 'h5py.File', (['path_file', '"""r"""'], {}), "(path_file, 'r')\n", (433,... |
import numpy as np
from ...dimensions.dim_linear import DimLinear
from ...dimensions.dim_angular import DimAngular
from ...dimensions import DimRadian
from ..cross_sect_base import CrossSectBase, CrossSectToken
__all__ = ['CrossSectParallelogram']
class CrossSectParallelogram(CrossSectBase):
def __init__(self, ... | [
"numpy.transpose",
"numpy.sin",
"numpy.array",
"numpy.cos"
] | [((1556, 1572), 'numpy.array', 'np.array', (['[x, y]'], {}), '([x, y])\n', (1564, 1572), True, 'import numpy as np\n'), ((1591, 1606), 'numpy.transpose', 'np.transpose', (['z'], {}), '(z)\n', (1603, 1606), True, 'import numpy as np\n'), ((2036, 2066), 'numpy.array', 'np.array', (['[[x_coord, y_coord]]'], {}), '([[x_coo... |
#!/usr/bin/env python
# -*- coding: utf-8 -*-
"""
Copyright (c) 2016 <NAME>
Permission is hereby granted, free of charge, to any person obtaining a copy
of this software and associated documentation files (the "Software"), to deal
in the Software without restriction, including without limitation the rights
to use, cop... | [
"wxgigo.get_version",
"sys.exit",
"os.path.basename"
] | [((1762, 1782), 'wxgigo.get_version', 'wxgigo.get_version', ([], {}), '()\n', (1780, 1782), False, 'import wxgigo\n'), ((4055, 4066), 'sys.exit', 'sys.exit', (['(1)'], {}), '(1)\n', (4063, 4066), False, 'import sys\n'), ((2320, 2347), 'os.path.basename', 'os.path.basename', (['prog_name'], {}), '(prog_name)\n', (2336, ... |
import unittest
from MuseParse.classes.ObjectHierarchy.ItemClasses import Directions, BarlinesAndMarkers, Meter, Note
from MuseParse.tests.testLilyMethods.lily import Lily
from MuseParse.classes.ObjectHierarchy.TreeClasses.NoteNode import NoteNode
from MuseParse.classes.ObjectHierarchy.TreeClasses.MeasureNode import M... | [
"MuseParse.classes.ObjectHierarchy.ItemClasses.Note.GraceNote",
"MuseParse.classes.ObjectHierarchy.ItemClasses.Meter.Meter",
"MuseParse.classes.ObjectHierarchy.ItemClasses.Note.Pitch",
"MuseParse.classes.ObjectHierarchy.ItemClasses.Note.Note",
"MuseParse.classes.ObjectHierarchy.TreeClasses.MeasureNode.Measu... | [((688, 701), 'MuseParse.classes.ObjectHierarchy.TreeClasses.MeasureNode.MeasureNode', 'MeasureNode', ([], {}), '()\n', (699, 701), False, 'from MuseParse.classes.ObjectHierarchy.TreeClasses.MeasureNode import MeasureNode\n'), ((815, 828), 'MuseParse.classes.ObjectHierarchy.TreeClasses.MeasureNode.MeasureNode', 'Measur... |
#!/usr/bin/env python3
# -*- coding: utf-8 -*-
"""
Created on Sat Aug 22 17:00:38 2020
@author: <NAME>
production rules for Colada
Output of parsers will generally be an Etok.
Parser rules ending in _ produce a list of Etoks rather than one.
Inner functions f(acc) are treatments.
Inner functions f(item)->item ar... | [
"parser_combinator.Parse.first",
"tokenlib.Etok.etok",
"parser_combinator.Parse",
"parser_combinator.Parse.next_token",
"parser_combinator.plus_andcomma",
"tokenlib.Etok",
"tokenlib.update",
"parser_combinator.Parse.fail",
"parser_combinator.next_type",
"parser_combinator.next_value",
"doctest.t... | [((6977, 6992), 'parser_combinator.next_value', 'next_value', (['"""."""'], {}), "('.')\n", (6987, 6992), False, 'from parser_combinator import Parse, next_word, next_any_word, next_value, first_word, first_phrase, next_phrase, pstream\n'), ((7001, 7016), 'parser_combinator.next_value', 'next_value', (['""","""'], {}),... |
from pyraf import iraf
import glob, os
import numpy as np
import pylab as py
import math, datetime
import pyfits
from gcwork import objects
from . import dar
def diffDarOnOff(cleanDir1, cleanDir2):
files1tmp = glob.glob(cleanDir1 + '/c????.fits')
files2tmp = glob.glob(cleanDir2 + '/c????.fits')
for f1 in ... | [
"pyraf.iraf.imarith",
"numpy.arange",
"glob.glob",
"pylab.title",
"pylab.ylabel",
"os.path.exists",
"numpy.tan",
"datetime.timedelta",
"pylab.xlabel",
"pylab.legend",
"gcwork.objects.Transform",
"datetime.datetime",
"pylab.subplot",
"pylab.savefig",
"math.degrees",
"pyraf.iraf.imdelete... | [((215, 251), 'glob.glob', 'glob.glob', (["(cleanDir1 + '/c????.fits')"], {}), "(cleanDir1 + '/c????.fits')\n", (224, 251), False, 'import glob, os\n'), ((268, 304), 'glob.glob', 'glob.glob', (["(cleanDir2 + '/c????.fits')"], {}), "(cleanDir2 + '/c????.fits')\n", (277, 304), False, 'import glob, os\n'), ((1292, 1308), ... |
import re
import urllib
from collections import OrderedDict
from django.http import HttpResponseRedirect, FileResponse
from django.utils.text import slugify
from rest_framework import viewsets, renderers, mixins
from rest_framework.decorators import action
from rest_framework.response import Response
from rest_framew... | [
"capdb.models.Court.objects.order_by",
"capdb.models.VolumeMetadata.objects.order_by",
"capdb.models.CaseExport.objects.order_by",
"django.utils.text.slugify",
"capapi.filters.jurisdiction_slug_to_id.items",
"rest_framework.response.Response",
"django.http.HttpResponseRedirect",
"capdb.models.Reporter... | [((1442, 1492), 'capdb.models.Jurisdiction.objects.order_by', 'models.Jurisdiction.objects.order_by', (['"""name"""', '"""pk"""'], {}), "('name', 'pk')\n", (1478, 1492), False, 'from capdb import models\n'), ((2349, 2387), 'capdb.models.Citation.objects.order_by', 'models.Citation.objects.order_by', (['"""pk"""'], {}),... |
# coding: utf-8
# Copyright (c) 2016, 2022, Oracle and/or its affiliates. All rights reserved.
# This software is dual-licensed to you under the Universal Permissive License (UPL) 1.0 as shown at https://oss.oracle.com/licenses/upl or Apache License 2.0 as shown at http://www.apache.org/licenses/LICENSE-2.0. You may c... | [
"oci.util.formatted_flat_dict"
] | [((8398, 8423), 'oci.util.formatted_flat_dict', 'formatted_flat_dict', (['self'], {}), '(self)\n', (8417, 8423), False, 'from oci.util import formatted_flat_dict, NONE_SENTINEL, value_allowed_none_or_none_sentinel\n')] |
from mcpi.minecraft import Minecraft
mc = Minecraft.create()
answer = input("Create a crater? Y/N ")
if answer == "Y":
pos = mc.player.getPos()
mc.setBlocks(pos.x + 1, pos.y + 1, pos.z + 1, pos.x - 1, pos.y - 1, pos.z - 1, 0)
mc.postToChat("Boom!")
| [
"mcpi.minecraft.Minecraft.create"
] | [((42, 60), 'mcpi.minecraft.Minecraft.create', 'Minecraft.create', ([], {}), '()\n', (58, 60), False, 'from mcpi.minecraft import Minecraft\n')] |
import time
import logging
from typing import List
import json
from spaceone.inventory.connector.aws_sqs_connector.schema.data import QueData, RedrivePolicy
from spaceone.inventory.connector.aws_sqs_connector.schema.resource import SQSResponse, QueResource
from spaceone.inventory.connector.aws_sqs_connector.schema.ser... | [
"spaceone.inventory.connector.aws_sqs_connector.schema.data.QueData",
"logging.getLogger",
"time.time"
] | [((436, 463), 'logging.getLogger', 'logging.getLogger', (['__name__'], {}), '(__name__)\n', (453, 463), False, 'import logging\n'), ((662, 673), 'time.time', 'time.time', ([], {}), '()\n', (671, 673), False, 'import time\n'), ((1617, 1630), 'spaceone.inventory.connector.aws_sqs_connector.schema.data.QueData', 'QueData'... |
from __future__ import unicode_literals
import importlib
import inspect
import json
from django.conf import settings
from django.contrib import messages
from django.db.models.base import ModelBase
from django.http.response import HttpResponse
from django.shortcuts import get_object_or_404
from django.utils.text import ... | [
"json.loads",
"importlib.import_module",
"django.utils.timezone.now",
"json.dumps",
"django.utils.text.slugify",
"django.utils.translation.ugettext",
"StringIO.StringIO",
"django.http.response.HttpResponse"
] | [((3088, 3108), 'json.loads', 'json.loads', (['sq.query'], {}), '(sq.query)\n', (3098, 3108), False, 'import json\n'), ((3226, 3245), 'StringIO.StringIO', 'StringIO.StringIO', ([], {}), '()\n', (3243, 3245), False, 'import StringIO\n'), ((3820, 3834), 'django.http.response.HttpResponse', 'HttpResponse', ([], {}), '()\n... |
# Copyright 2008-2018 Univa Corporation
#
# Licensed under the Apache License, Version 2.0 (the "License");
# you may not use this file except in compliance with the License.
# You may obtain a copy of the License at
#
# http://www.apache.org/licenses/LICENSE-2.0
#
# Unless required by applicable law or agreed to in... | [
"jinja2.Template",
"tempfile.NamedTemporaryFile",
"tempfile.TemporaryDirectory",
"subprocess.check_output",
"os.path.join"
] | [((1820, 1857), 'jinja2.Template', 'Template', (['REPO_CONFIGURATION_TEMPLATE'], {}), '(REPO_CONFIGURATION_TEMPLATE)\n', (1828, 1857), False, 'from jinja2 import Template\n'), ((2390, 2410), 'tempfile.TemporaryDirectory', 'TemporaryDirectory', ([], {}), '()\n', (2408, 2410), False, 'from tempfile import NamedTemporaryF... |
import glob, os, random
import keras
import numpy as np
from keras import backend as K
from keras.optimizers import Adam
from keras.metrics import categorical_crossentropy
from keras.preprocessing.image import ImageDataGenerator
from keras.preprocessing import image
from keras.models import Model
from keras.application... | [
"keras.preprocessing.image.ImageDataGenerator",
"matplotlib.pyplot.subplot",
"random.sample",
"keras.layers.Dropout",
"keras.applications.mobilenet.MobileNet",
"keras.models.Model",
"keras.layers.GlobalAveragePooling2D",
"keras.preprocessing.image.img_to_array",
"keras.preprocessing.image.load_img",... | [((1038, 1228), 'keras.applications.mobilenet.MobileNet', 'keras.applications.mobilenet.MobileNet', ([], {'input_shape': '(IMAGE_WIDTH, IMAGE_HEIGHT, 3)', 'alpha': '(0.75)', 'depth_multiplier': '(1)', 'dropout': '(0.001)', 'include_top': '(False)', 'weights': '"""imagenet"""', 'classes': '(1000)'}), "(input_shape=(IMAG... |
import operator
from functools import reduce
MSG_LEN = 27
IDLE = bytes.fromhex("436d640001001200010404000a000000808080802020202000550f")
CMD_PREFIX = IDLE[:-11]
def _c(cmd: str) -> bytes:
data = bytes.fromhex(cmd)
assert len(data) == MSG_LEN - len(CMD_PREFIX)
return CMD_PREFIX + data
def checksum(msg: ... | [
"functools.reduce"
] | [((375, 405), 'functools.reduce', 'reduce', (['operator.xor', 'msg', '(185)'], {}), '(operator.xor, msg, 185)\n', (381, 405), False, 'from functools import reduce\n'), ((424, 453), 'functools.reduce', 'reduce', (['operator.add', 'msg', 'b9'], {}), '(operator.add, msg, b9)\n', (430, 453), False, 'from functools import r... |
import json
import time
def get_key(store, key):
while True:
res = store.get(key+"_output")
if res is None:
time.sleep(0.5)
else:
result = json.loads(res.decode('utf-8'))
store.delete(key)
store.delete(key+"_output")
break
ret... | [
"time.sleep"
] | [((142, 157), 'time.sleep', 'time.sleep', (['(0.5)'], {}), '(0.5)\n', (152, 157), False, 'import time\n')] |
import json
import os
import uuid
import mongoengine
from flask import Blueprint, jsonify, request
from werkzeug.utils import secure_filename
from tess.config import UPLOAD_FILES
from tess.server.models import SummarizationDocument
summarization_bp = Blueprint('summarization_api', __name__)
@summarization_bp.route... | [
"tess.server.models.SummarizationDocument.objects",
"uuid.uuid4",
"flask.Blueprint",
"tess.server.models.SummarizationDocument.objects.get",
"werkzeug.utils.secure_filename",
"flask.jsonify",
"flask.request.form.to_dict",
"os.path.join"
] | [((254, 294), 'flask.Blueprint', 'Blueprint', (['"""summarization_api"""', '__name__'], {}), "('summarization_api', __name__)\n", (263, 294), False, 'from flask import Blueprint, jsonify, request\n'), ((415, 437), 'flask.request.form.to_dict', 'request.form.to_dict', ([], {}), '()\n', (435, 437), False, 'from flask imp... |
# Source: https://medium.com/@datamonsters/text-preprocessing-in-python-steps-tools-and-examples-bf025f872908
# reading level of posts coming out as negative for most posts because of the way they are written
import re
import pandas as pd
import numpy as np
import time
import nltk
nltk.download('wordnet') #TODO: ... | [
"textstat.flesch_reading_ease",
"nltk.stem.PorterStemmer",
"nltk.stem.WordNetLemmatizer",
"pandas.read_csv",
"time.time",
"textblob.TextBlob",
"nltk.download",
"re.sub",
"nltk.tokenize.word_tokenize",
"re.compile"
] | [((288, 312), 'nltk.download', 'nltk.download', (['"""wordnet"""'], {}), "('wordnet')\n", (301, 312), False, 'import nltk\n'), ((1202, 1228), 're.compile', 're.compile', (['""">|&|<"""'], {}), "('>|&|<')\n", (1212, 1228), False, 'import re\n'), ((1309, 1340), 're.compile', 're.compile', (['"""[<{\\\\[].*?... |
import re
from binascii import unhexlify
from datetime import datetime, timedelta, date
from decimal import Decimal
from email.mime.text import MIMEText
from fractions import Fraction
from uuid import UUID
import pytest
from cbor2.compat import timezone
from cbor2.encoder import dumps, CBOREncodeError, dump, shareabl... | [
"decimal.Decimal",
"email.mime.text.MIMEText",
"datetime.date",
"cbor2.types.CBORTag",
"datetime.datetime",
"pytest.raises",
"binascii.unhexlify",
"cbor2.encoder.dumps",
"cbor2.encoder.dump",
"cbor2.types.CBORSimpleValue",
"uuid.UUID",
"datetime.timedelta",
"pytest.mark.parametrize",
"frac... | [((393, 875), 'pytest.mark.parametrize', 'pytest.mark.parametrize', (['"""value, expected"""', "[(0, '00'), (1, '01'), (10, '0a'), (23, '17'), (24, '1818'), (100, '1864'),\n (1000, '1903e8'), (1000000, '1a000f4240'), (1000000000000,\n '1b000000e8d4a51000'), (18446744073709551615, '1bffffffffffffffff'), (\n 184... |
import pytest
from opentrons.protocol_api.module_validation_and_errors import (
validate_heater_shaker_temperature,
validate_heater_shaker_speed,
InvalidTargetTemperatureError,
InvalidTargetSpeedError,
)
@pytest.mark.parametrize("valid_celsius_value", [37.0, 37.1, 50, 94.99, 95])
def test_validate_he... | [
"pytest.mark.parametrize",
"pytest.raises",
"opentrons.protocol_api.module_validation_and_errors.validate_heater_shaker_speed",
"opentrons.protocol_api.module_validation_and_errors.validate_heater_shaker_temperature"
] | [((224, 299), 'pytest.mark.parametrize', 'pytest.mark.parametrize', (['"""valid_celsius_value"""', '[37.0, 37.1, 50, 94.99, 95]'], {}), "('valid_celsius_value', [37.0, 37.1, 50, 94.99, 95])\n", (247, 299), False, 'import pytest\n'), ((568, 639), 'pytest.mark.parametrize', 'pytest.mark.parametrize', (['"""invalid_celsiu... |
from jupyterthemes import jtplot
import numpy as np
import os
import matplotlib.pyplot as plt
from pathlib import Path
from scipy.ndimage import filters
from textwrap import wrap
import torch
import vectorized_agents as va
import vectorized_env as ve
jtplot.style()
DEVICE = torch.device('cuda')
if DEVICE == torch.de... | [
"matplotlib.pyplot.tight_layout",
"jupyterthemes.jtplot.style",
"vectorized_agents.SavedRLAgent",
"textwrap.wrap",
"vectorized_agents.run_vectorized_vs",
"matplotlib.pyplot.close",
"vectorized_agents.PullVegasSlotMachines",
"matplotlib.pyplot.subplots",
"numpy.cumsum",
"pathlib.Path",
"scipy.ndi... | [((253, 267), 'jupyterthemes.jtplot.style', 'jtplot.style', ([], {}), '()\n', (265, 267), False, 'from jupyterthemes import jtplot\n'), ((278, 298), 'torch.device', 'torch.device', (['"""cuda"""'], {}), "('cuda')\n", (290, 298), False, 'import torch\n'), ((312, 331), 'torch.device', 'torch.device', (['"""cpu"""'], {}),... |
from unittest import TestCase
import numpy as np
import xarray as xr
from xarray.testing import assert_equal, assert_allclose
import numpy.testing as npt
from sklearn_xarray import wrap
from sklearn.base import clone
from sklearn.preprocessing import StandardScaler, KernelCenterer
from sklearn.linear_model import Li... | [
"sklearn.base.clone",
"xarray.testing.assert_equal",
"sklearn.preprocessing.StandardScaler",
"tests.mocks.ReshapingEstimator",
"tests.mocks.DummyEstimator",
"xarray.testing.assert_allclose",
"numpy.random.random",
"xarray.DataArray",
"numpy.testing.assert_equal",
"sklearn.svm.SVC",
"sklearn.deco... | [((10179, 10203), 'sklearn_xarray.wrap', 'wrap', (['LogisticRegression'], {}), '(LogisticRegression)\n', (10183, 10203), False, 'from sklearn_xarray import wrap\n'), ((10432, 10456), 'sklearn_xarray.wrap', 'wrap', (['LogisticRegression'], {}), '(LogisticRegression)\n', (10436, 10456), False, 'from sklearn_xarray import... |
#!/usr/bin/env python
# -*- coding: utf-8 -*-
import io
import sys
import pickle
import nose
from nose.tools.trivial import eq_
from nose.tools.trivial import ok_
from jpgrep.util import binary2unicode
from jpgrep.util import FileObjectWrapper
from jpgrep.util import ByteWrapper
class Test_binary2unicode(object):
... | [
"pickle.loads",
"io.StringIO",
"nose.main",
"jpgrep.util.binary2unicode",
"jpgrep.util.ByteWrapper",
"nose.tools.trivial.eq_",
"jpgrep.util.FileObjectWrapper",
"pickle.dumps"
] | [((2571, 2634), 'nose.main', 'nose.main', ([], {'argv': "['nosetests', '-s', '-v']", 'defaultTest': '__file__'}), "(argv=['nosetests', '-s', '-v'], defaultTest=__file__)\n", (2580, 2634), False, 'import nose\n'), ((460, 482), 'jpgrep.util.binary2unicode', 'binary2unicode', (['binary'], {}), '(binary)\n', (474, 482), Fa... |
import socket
ip = socket.gethostbyname('localhost.localdomain')
port = 10000
buffer_size = 1024
with open("payload.c", "r") as file:
message_list = file.read()
message = str.encode(message_list)
s = socket.socket(socket.AF_INET, socket.SOCK_STREAM)
s.connect((ip, port))
s.send(message)
data = s.recv(buffer_s... | [
"socket.socket",
"socket.gethostbyname"
] | [((20, 65), 'socket.gethostbyname', 'socket.gethostbyname', (['"""localhost.localdomain"""'], {}), "('localhost.localdomain')\n", (40, 65), False, 'import socket\n'), ((210, 259), 'socket.socket', 'socket.socket', (['socket.AF_INET', 'socket.SOCK_STREAM'], {}), '(socket.AF_INET, socket.SOCK_STREAM)\n', (223, 259), Fals... |
from tokenizer_tools.conllz.iterator_reader import read_conllz_iterator
from tokenizer_tools.conll.writer import write_conll
def conllz_to_conll(conllz_file, conll_file):
sentence_iterator = read_conllz_iterator(conllz_file)
conll_data = []
for sentence in sentence_iterator:
conll_data.append((s... | [
"tokenizer_tools.conllz.iterator_reader.read_conllz_iterator",
"tokenizer_tools.conll.writer.write_conll"
] | [((197, 230), 'tokenizer_tools.conllz.iterator_reader.read_conllz_iterator', 'read_conllz_iterator', (['conllz_file'], {}), '(conllz_file)\n', (217, 230), False, 'from tokenizer_tools.conllz.iterator_reader import read_conllz_iterator\n'), ((382, 417), 'tokenizer_tools.conll.writer.write_conll', 'write_conll', (['conll... |
#!/usr/bin/env pythonw
import numpy as np
from astropy.visualization import stretch, interval
from astropy.io import fits
from astropy import wcs
from reproject import reproject_interp
from matplotlib import pyplot as plt
def scaleImage(image, a=1, stretch_type='asinh'):
reagon = interval.AsymmetricPercentileInt... | [
"astropy.visualization.stretch.LogStretch",
"astropy.visualization.interval.AsymmetricPercentileInterval",
"argparse.ArgumentParser",
"astropy.io.fits.PrimaryHDU",
"numpy.zeros",
"numpy.isfinite",
"astropy.visualization.stretch.AsinhStretch",
"astropy.wcs.WCS",
"reproject.reproject_interp",
"astro... | [((288, 338), 'astropy.visualization.interval.AsymmetricPercentileInterval', 'interval.AsymmetricPercentileInterval', (['(10.0)', '(99.95)'], {}), '(10.0, 99.95)\n', (325, 338), False, 'from astropy.visualization import stretch, interval\n'), ((1729, 1796), 'numpy.zeros', 'np.zeros', (['[images_scaled[0].shape[0], imag... |
import os
import subprocess
# Test different input formats
for ifile, odir in [
('input.fasta', 'output_bin_fa'),
('input.fasta.gz', 'output_bin_gz'),
('input.fasta.bz2', 'output_bin_bz2'),
('input.fasta.xz', 'output_bin_xz'),
]:
odir = f'test-outputs/{odir}'
subprocess.... | [
"os.path.exists",
"os.listdir",
"subprocess.check_call"
] | [((852, 1153), 'subprocess.check_call', 'subprocess.check_call', (["['SemiBin', 'bin', '--data', 'test/bin_data/data.csv', '--minfasta-kbs',\n '200', '--max-edges', '20', '--max-node', '1', '--no-recluster',\n '--model', 'test/bin_data/model.h5', '-i', f'test/bin_data/{ifile}',\n '-o', odir, '-m', '2500', '--r... |
"""
## box2lake_sensor.py
Example using Box.com API.
- Demonstrates a Box sensor for file availability before proceeding with ETL.
### References
Box APIs used
- REST: https://developer.box.com/reference/
- Python SDK: https://box-python-sdk.readthedocs.io/en/stable/boxsdk.html
"""
from datetime import datetime, tim... | [
"bsh_azure.sensors.box_sensor.BoxSensor",
"datetime.timedelta",
"airflow.operators.bash_operator.BashOperator",
"airflow.utils.dates.days_ago",
"airflow.kubernetes.secret.Secret"
] | [((968, 988), 'datetime.timedelta', 'timedelta', ([], {'seconds': '(5)'}), '(seconds=5)\n', (977, 988), False, 'from datetime import datetime, timedelta\n'), ((1884, 2159), 'bsh_azure.sensors.box_sensor.BoxSensor', 'BoxSensor', ([], {'task_id': '"""wait_for_daily_box_task"""', 'box_item_path': '"""Utilization Reports/D... |
"""."""
import pytest
from .hash_table import HashTable as HT
from .left_join import left_join
def test_left_join_true(six_key_ht, five_key_ht):
"""True case for left join."""
result = left_join(six_key_ht, five_key_ht)
assert result.get('cost') == (0, None)
def test_both_empty_hash_table():
"""Res... | [
"pytest.raises"
] | [((584, 609), 'pytest.raises', 'pytest.raises', (['ValueError'], {}), '(ValueError)\n', (597, 609), False, 'import pytest\n'), ((823, 847), 'pytest.raises', 'pytest.raises', (['TypeError'], {}), '(TypeError)\n', (836, 847), False, 'import pytest\n')] |
import math
import pytz
import sys
import time
from datetime import date
from . import wait_times, util, arrival_history, trip_times, errors, constants, timetables, routeconfig
import pandas as pd
import numpy as np
# Represents a range of days with a time range within each day.
# RouteMetrics can calculate various s... | [
"numpy.searchsorted",
"numpy.isfinite",
"time.time",
"numpy.sort",
"pandas.concat",
"numpy.concatenate"
] | [((6056, 6067), 'time.time', 'time.time', ([], {}), '()\n', (6065, 6067), False, 'import time\n'), ((7407, 7440), 'pandas.concat', 'pd.concat', (['compared_timetable_arr'], {}), '(compared_timetable_arr)\n', (7416, 7440), True, 'import pandas as pd\n'), ((7567, 7578), 'time.time', 'time.time', ([], {}), '()\n', (7576, ... |
from flask.config import Config
import os
ds_settings = os.getenv(
"DS_SETTINGS", "project.config.data_science_config.DsDevelopmentConfig"
)
ds_config=Config(None)
ds_config.from_object(ds_settings) | [
"flask.config.Config",
"os.getenv"
] | [((57, 143), 'os.getenv', 'os.getenv', (['"""DS_SETTINGS"""', '"""project.config.data_science_config.DsDevelopmentConfig"""'], {}), "('DS_SETTINGS',\n 'project.config.data_science_config.DsDevelopmentConfig')\n", (66, 143), False, 'import os\n'), ((157, 169), 'flask.config.Config', 'Config', (['None'], {}), '(None)\... |
#!/usr/bin/env python
# -*- coding: utf-8 -*-
#
# Copyright (c) 2013, <NAME>
# Copyright (c) 2014-2015, <NAME>
# Copyright (c) 2013-2015, B2CK
# All rights reserved.
#
# Redistribution and use in source and binary forms, with or without
# modification, are permitted provided that the following conditions are met:
# ... | [
"collections.defaultdict",
"datetime.datetime.strptime",
"collections.namedtuple",
"re.compile"
] | [((2415, 2655), 're.compile', 're.compile', (['"""\n (?P<date>\\\\d{6})\n (?P<booking>\\\\d{4})?\n (?P<sign>D|C|RC|RD)\n (?P<code>\\\\w)?? # ING skips this mandatory field\n (?P<amount>(\\\\d|,){1,15})\n (?P<id>\\\\w{4})\n (?P<reference>.{0,34})"""', 're.VERBOSE'], {}), '(\n """\n (?P<date>\... |
# Copyright 2012 <NAME>
#
# Licensed under the Apache License, Version 2.0 (the "License");
# you may not use this file except in compliance with the License.
# You may obtain a copy of the License at:
#
# http://www.apache.org/licenses/LICENSE-2.0
#
# Unless required by applicable law or agreed to in writing, soft... | [
"pox.core.core.openflow.addListenerByName",
"pox.openflow.libopenflow_01.ofp_flow_mod",
"pox.openflow.libopenflow_01.ofp_action_output",
"pox.openflow.libopenflow_01.ofp_packet_out",
"pox.lib.util.dpidToStr",
"pox.core.core.getLogger"
] | [((942, 958), 'pox.core.core.getLogger', 'core.getLogger', ([], {}), '()\n', (956, 958), False, 'from pox.core import core\n'), ((3303, 3322), 'pox.openflow.libopenflow_01.ofp_packet_out', 'of.ofp_packet_out', ([], {}), '()\n', (3320, 3322), True, 'import pox.openflow.libopenflow_01 as of\n'), ((3477, 3546), 'pox.core.... |
import os
import pandas as pd
import pytest
from whylogs.core.metrics.regression_metrics import RegressionMetrics
from whylogs.proto import RegressionMetricsMessage
TEST_DATA_PATH = os.path.abspath(
os.path.join(
os.path.realpath(os.path.dirname(__file__)),
os.pardir,
os.pardir,
o... | [
"whylogs.core.metrics.regression_metrics.RegressionMetrics",
"os.path.dirname",
"whylogs.proto.RegressionMetricsMessage",
"pytest.approx",
"os.path.join",
"whylogs.core.metrics.regression_metrics.RegressionMetrics.from_protobuf"
] | [((407, 426), 'whylogs.core.metrics.regression_metrics.RegressionMetrics', 'RegressionMetrics', ([], {}), '()\n', (424, 426), False, 'from whylogs.core.metrics.regression_metrics import RegressionMetrics\n'), ((889, 908), 'whylogs.core.metrics.regression_metrics.RegressionMetrics', 'RegressionMetrics', ([], {}), '()\n'... |
# Copyright (c) Microsoft Corporation.
# Licensed under the MIT license.
import numpy as np
PRECISION = 8 # in signs after dot
def objective_file_name(output_prefix, input_basename, module_basename):
return output_prefix + input_basename + "_F_" + module_basename + ".txt"
def jacobian_file_name(output_prefix,... | [
"numpy.format_float_scientific"
] | [((507, 584), 'numpy.format_float_scientific', 'np.format_float_scientific', (['objective_time'], {'unique': '(False)', 'precision': 'PRECISION'}), '(objective_time, unique=False, precision=PRECISION)\n', (533, 584), True, 'import numpy as np\n'), ((635, 713), 'numpy.format_float_scientific', 'np.format_float_scientifi... |
from django.contrib import admin
from .models import Blogpost
from django_summernote.admin import SummernoteModelAdmin
# class BlogpostAdmin(admin.ModelAdmin):
# list_display = ('title', 'slug', 'status','created_on')
# list_filter = ("status",)
# search_fields = ['title', 'content']
# prepopulated_fie... | [
"django.contrib.admin.site.register"
] | [((621, 665), 'django.contrib.admin.site.register', 'admin.site.register', (['Blogpost', 'BlogpostAdmin'], {}), '(Blogpost, BlogpostAdmin)\n', (640, 665), False, 'from django.contrib import admin\n')] |
from bs4 import BeautifulSoup as bs
import json
import uuid
class htmlCreator:
def generate_html_file(self, jsonObject):
soup = self.__getTemplateFileData()
jsonData = json.loads(jsonObject)
self.__appendDivs(soup, jsonData)
self.__saveFile(soup)
def __saveFile(self, soup):
... | [
"bs4.BeautifulSoup",
"uuid.uuid4",
"json.loads"
] | [((189, 211), 'json.loads', 'json.loads', (['jsonObject'], {}), '(jsonObject)\n', (199, 211), False, 'import json\n'), ((335, 347), 'uuid.uuid4', 'uuid.uuid4', ([], {}), '()\n', (345, 347), False, 'import uuid\n'), ((1377, 1392), 'bs4.BeautifulSoup', 'bs', (['txt', '"""lxml"""'], {}), "(txt, 'lxml')\n", (1379, 1392), T... |
import abjad
import auxjad
def test_remove_repeated_time_signatures_01():
staff = abjad.Staff(r"c'4 d'8 | c'4 d'8")
abjad.attach(abjad.TimeSignature((3, 8)), staff[0])
abjad.attach(abjad.TimeSignature((3, 8)), staff[2])
assert abjad.lilypond(staff) == abjad.String.normalize(
r"""
\new... | [
"abjad.mutate.remove_repeated_time_signatures",
"abjad.TimeSignature",
"abjad.lilypond",
"abjad.String.normalize",
"abjad.Chord",
"auxjad.mutate.remove_repeated_time_signatures",
"abjad.Note",
"abjad.Staff",
"abjad.Tuplet"
] | [((89, 121), 'abjad.Staff', 'abjad.Staff', (['"""c\'4 d\'8 | c\'4 d\'8"""'], {}), '("c\'4 d\'8 | c\'4 d\'8")\n', (100, 121), False, 'import abjad\n'), ((477, 532), 'auxjad.mutate.remove_repeated_time_signatures', 'auxjad.mutate.remove_repeated_time_signatures', (['staff[:]'], {}), '(staff[:])\n', (522, 532), False, 'im... |
import pytest
import datetime as dt
from subtypes import DateTime
@pytest.fixture
def example_datetime():
return DateTime(1994, 3, 24, 12, 30, 15)
class TestDateTime:
def test___str__(self): # synced
assert True
def test_shift(self, example_datetime): # synced
assert example_datetime... | [
"subtypes.DateTime",
"datetime.datetime"
] | [((120, 153), 'subtypes.DateTime', 'DateTime', (['(1994)', '(3)', '(24)', '(12)', '(30)', '(15)'], {}), '(1994, 3, 24, 12, 30, 15)\n', (128, 153), False, 'from subtypes import DateTime\n'), ((398, 418), 'subtypes.DateTime', 'DateTime', (['(2020)', '(1)', '(1)'], {}), '(2020, 1, 1)\n', (406, 418), False, 'from subtypes ... |
import argparse
import os
import git
from enum import Enum
script_location = os.path.dirname(__file__)
repo_path = os.path.abspath(os.sep.join([script_location, '..', '..']))
print('Using git repository location {}'.format(repo_path))
repo = git.Repo(repo_path)
repo_submodules = repo.submodules
patches_folder = os.se... | [
"os.path.dirname",
"git.Repo",
"os.path.isfile",
"os.path.normpath",
"os.sep.join"
] | [((78, 103), 'os.path.dirname', 'os.path.dirname', (['__file__'], {}), '(__file__)\n', (93, 103), False, 'import os\n'), ((243, 262), 'git.Repo', 'git.Repo', (['repo_path'], {}), '(repo_path)\n', (251, 262), False, 'import git\n'), ((315, 378), 'os.sep.join', 'os.sep.join', (["[repo_path, 'PolyEngine', 'ThirdParty', 'p... |
from django.urls import path
from . import views
urlpatterns = [
path("", views.index, name="index"),
path("reportes", views.reportes, name="reportes"),
path(
"courses_by/<str:teacher_name>", views.teacher_courses, name="teacher_courses"
),
path(
"courses_of/<str:subject_name>", vi... | [
"django.urls.path"
] | [((71, 106), 'django.urls.path', 'path', (['""""""', 'views.index'], {'name': '"""index"""'}), "('', views.index, name='index')\n", (75, 106), False, 'from django.urls import path\n'), ((112, 161), 'django.urls.path', 'path', (['"""reportes"""', 'views.reportes'], {'name': '"""reportes"""'}), "('reportes', views.report... |
from Compiler.program import Program
from .GC import types as GC_types
import sys
import re, tempfile, os
def run(args, options):
""" Compile a file and output a Program object.
If options.merge_opens is set to True, will attempt to merge any
parallelisable open instructions. """
prog = Pro... | [
"tempfile.NamedTemporaryFile",
"os.unlink",
"re.match",
"sys.path.insert",
"Compiler.program.Program",
"re.sub"
] | [((317, 339), 'Compiler.program.Program', 'Program', (['args', 'options'], {}), '(args, options)\n', (324, 339), False, 'from Compiler.program import Program\n'), ((2701, 2731), 'sys.path.insert', 'sys.path.insert', (['(0)', '"""Compiler"""'], {}), "(0, 'Compiler')\n", (2716, 2731), False, 'import sys\n'), ((2862, 2884... |
#!/bin/python
from __future__ import absolute_import, division, print_function, \
unicode_literals
import numpy as np
import tensorflow as tf
from tensorflow.python.ops import array_ops
class LocalFeatureAlignment(tf.keras.layers.Layer):
def __init__(self, **kwargs):
super(LocalFeatureAlignment, s... | [
"tensorflow.python.ops.array_ops.shape",
"tensorflow.range",
"tensorflow.keras.backend.ones_like",
"tensorflow.keras.backend.argmax",
"tensorflow.gather_nd",
"tensorflow.cast"
] | [((1123, 1169), 'tensorflow.gather_nd', 'tf.gather_nd', (['distance', 'selector'], {'batch_dims': '(1)'}), '(distance, selector, batch_dims=1)\n', (1135, 1169), True, 'import tensorflow as tf\n'), ((865, 898), 'tensorflow.keras.backend.ones_like', 'tf.keras.backend.ones_like', (['argmx'], {}), '(argmx)\n', (891, 898), ... |
# -*- coding: utf8 -*-
# Copyright (c) 2017-2018 THL A29 Limited, a Tencent company. 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... | [
"tencentcloud.common.exception.tencent_cloud_sdk_exception.TencentCloudSDKException",
"json.loads",
"tencentcloud.platform.v20190314.models.DescribePasswordsResponse",
"tencentcloud.platform.v20190314.models.ResetPasswordResponse",
"tencentcloud.platform.v20190314.models.QueryPasswordsResponse",
"tencentc... | [((1446, 1462), 'json.loads', 'json.loads', (['body'], {}), '(body)\n', (1456, 1462), False, 'import json\n'), ((2565, 2581), 'json.loads', 'json.loads', (['body'], {}), '(body)\n', (2575, 2581), False, 'import json\n'), ((3654, 3670), 'json.loads', 'json.loads', (['body'], {}), '(body)\n', (3664, 3670), False, 'import... |
from fastapi import APIRouter, Body, Depends
from ..models.post import ResponseModel
from ..controllers.auth import auth_handler
from ..controllers.verify import verify_post
router = APIRouter()
@router.post("/", response_description="Verify the post's authenticity")
async def verify_post_data(post_id: str = Body(..... | [
"fastapi.Body",
"fastapi.Depends",
"fastapi.APIRouter"
] | [((184, 195), 'fastapi.APIRouter', 'APIRouter', ([], {}), '()\n', (193, 195), False, 'from fastapi import APIRouter, Body, Depends\n'), ((313, 334), 'fastapi.Body', 'Body', (['...'], {'embed': '(True)'}), '(..., embed=True)\n', (317, 334), False, 'from fastapi import APIRouter, Body, Depends\n'), ((349, 383), 'fastapi.... |
# Copyright 2021-xx iiPython
# Modules
from typing import Union
from datetime import datetime
from secrets import token_hex
# Timer class
class Timer(object):
def __init__(self) -> None:
self._st_times = {}
self._ret_keys = {"s": lambda x: x, "ms": lambda x: float(x) * 1000}
def start(self) -... | [
"secrets.token_hex",
"datetime.datetime.now"
] | [((346, 359), 'secrets.token_hex', 'token_hex', (['(26)'], {}), '(26)\n', (355, 359), False, 'from secrets import token_hex\n'), ((395, 409), 'datetime.datetime.now', 'datetime.now', ([], {}), '()\n', (407, 409), False, 'from datetime import datetime\n'), ((783, 797), 'datetime.datetime.now', 'datetime.now', ([], {}), ... |
#!/usr/bin/env python3
# -*- coding: utf-8 -*-
__author__ = 'ipetrash'
import requests
from bs4 import BeautifulSoup
def get_populations(url: str) -> dict:
rs = requests.get(url)
root = BeautifulSoup(rs.content, 'html.parser')
# P1082 -- идентификатор для population
population_node = root.select_o... | [
"bs4.BeautifulSoup",
"requests.get"
] | [((170, 187), 'requests.get', 'requests.get', (['url'], {}), '(url)\n', (182, 187), False, 'import requests\n'), ((199, 239), 'bs4.BeautifulSoup', 'BeautifulSoup', (['rs.content', '"""html.parser"""'], {}), "(rs.content, 'html.parser')\n", (212, 239), False, 'from bs4 import BeautifulSoup\n')] |
#!/usr/bin/env python
#Generates a wordcloud from a exported whatsapp chat
#3/06/2018
from os import path
from wordcloud import WordCloud, STOPWORDS, ImageColorGenerator
from PIL import Image
import emoji
import re
from datetime import datetime
import numpy as np
import matplotlib.pyplot as plt
#d = path.dirname(__f... | [
"matplotlib.pyplot.show",
"wordcloud.ImageColorGenerator",
"wordcloud.WordCloud",
"matplotlib.pyplot.axis",
"os.path.join"
] | [((2428, 2519), 'wordcloud.WordCloud', 'WordCloud', ([], {'background_color': '"""white"""', 'max_words': '(10000)', 'mask': 'h_mask', 'stopwords': 'stopwords'}), "(background_color='white', max_words=10000, mask=h_mask, stopwords\n =stopwords)\n", (2437, 2519), False, 'from wordcloud import WordCloud, STOPWORDS, Im... |
# Copyright 2015 The Chromium Authors. All rights reserved.
# Use of this source code is governed by a BSD-style license that can be
# found in the LICENSE file.
import contextlib
import json
import os
import unittest
from infra.libs.buildbot import master
from infra_libs.time_functions import timestamp
from infra_li... | [
"os.path.abspath",
"infra.services.master_manager_launcher.desired_state_parser.get_master_state",
"json.load",
"infra_libs.utils.temporary_directory",
"infra.services.master_manager_launcher.desired_state_parser.validate_desired_master_state",
"infra.services.master_manager_launcher.desired_state_parser.... | [((508, 533), 'os.path.abspath', 'os.path.abspath', (['__file__'], {}), '(__file__)\n', (523, 533), False, 'import os\n'), ((6314, 6367), 'infra.services.master_manager_launcher.desired_state_parser.validate_desired_master_state', 'desired_state_parser.validate_desired_master_state', (['c'], {}), '(c)\n', (6364, 6367),... |
#!/usr/bin/python
""" DEBUGGING PATTERNS
Both patterns in this exercise contain mistakes and won’t match as expected.
Can you fix them? If you get stuck, try printing the tokens in the doc to see
how the text will be split and adjust the pattern so that each dictionary
represents one token.
"""
# Edit pattern1 so ... | [
"spacy.load",
"spacy.matcher.Matcher"
] | [((596, 624), 'spacy.load', 'spacy.load', (['"""en_core_web_sm"""'], {}), "('en_core_web_sm')\n", (606, 624), False, 'import spacy\n'), ((1497, 1515), 'spacy.matcher.Matcher', 'Matcher', (['nlp.vocab'], {}), '(nlp.vocab)\n', (1504, 1515), False, 'from spacy.matcher import Matcher\n')] |
# -*- coding: utf-8 -*-
"""
Created on Wed Jun 17 14:30:36 2020
@author: Arun
"""
#import Simurgh-multi-agent-main
from Simurgh_multi_agent_main import mddpg
import streamlit as st
################################
## ##
## <NAME> ##
## github.com/arun... | [
"Simurgh_multi_agent_main.mddpg",
"streamlit.write"
] | [((437, 465), 'streamlit.write', 'st.write', (['"""Training Started"""'], {}), "('Training Started')\n", (445, 465), True, 'import streamlit as st\n'), ((480, 530), 'Simurgh_multi_agent_main.mddpg', 'mddpg', ([], {'n_episodes': '(1500)', 'max_t': '(1000)', 'print_every': '(10)'}), '(n_episodes=1500, max_t=1000, print_e... |
# -*- coding: utf-8 -*-
# Generated by Django 1.11 on 2019-03-19 17:25
from __future__ import unicode_literals
from django.db import migrations, models
class Migration(migrations.Migration):
dependencies = [
('remind', '0004_custom_cost'),
]
operations = [
migrations.AddField(
... | [
"django.db.models.FloatField"
] | [((392, 465), 'django.db.models.FloatField', 'models.FloatField', ([], {'default': '(0)', 'help_text': '"""止损线"""', 'verbose_name': '"""percent_min"""'}), "(default=0, help_text='止损线', verbose_name='percent_min')\n", (409, 465), False, 'from django.db import migrations, models\n'), ((592, 665), 'django.db.models.FloatF... |
#!/usr/bin/env python3
# -*- coding: utf-8 -*-
# Copyright (c) 2015 <NAME> (http://www.jdhp.org)
# Permission is hereby granted, free of charge, to any person obtaining a copy
# of this software and associated documentation files (the "Software"), to deal
# in the Software without restriction, including without limit... | [
"PyQt5.QtSql.QSqlQuery",
"PyQt5.QtSql.QSqlDatabase.addDatabase"
] | [((1637, 1678), 'PyQt5.QtSql.QSqlDatabase.addDatabase', 'QtSql.QSqlDatabase.addDatabase', (['"""QSQLITE"""'], {}), "('QSQLITE')\n", (1667, 1678), False, 'from PyQt5 import QtSql\n'), ((1860, 1877), 'PyQt5.QtSql.QSqlQuery', 'QtSql.QSqlQuery', ([], {}), '()\n', (1875, 1877), False, 'from PyQt5 import QtSql\n')] |
# -*- coding: utf-8 -*-
"""
log for heka Logfile input
"""
import logbook
from datetime import datetime
logbook.set_datetime_format("local")
import socket
import gevent
logger = logbook.Logger('app')
log = logbook.FileHandler('test.log')
log.push_application()
def main():
while True:
... | [
"logbook.set_datetime_format",
"gevent.sleep",
"logbook.Logger",
"logbook.FileHandler"
] | [((107, 143), 'logbook.set_datetime_format', 'logbook.set_datetime_format', (['"""local"""'], {}), "('local')\n", (134, 143), False, 'import logbook\n'), ((183, 204), 'logbook.Logger', 'logbook.Logger', (['"""app"""'], {}), "('app')\n", (197, 204), False, 'import logbook\n'), ((212, 243), 'logbook.FileHandler', 'logboo... |
#!/usr/bin/ python3
#! /usr/bin/env python
from subprocess import call
call(['espeak "Welcome to granDome" 2>/dev/null'], shell=True)
"""
User interface to control simultanous captures and leds
-- Using i2c from Raspberry and Arduino
@ mercurio
"""
from tkinter import *
from tkinter.ttk import Progressbar
f... | [
"os.mkdir",
"webbrowser.open_new",
"json.dumps",
"settings.killprocess",
"tkinter.ttk.Progressbar",
"i2c_devices.i2c_checker",
"glob.glob",
"RPi.GPIO.output",
"settings.numerical_pad",
"smbus.SMBus",
"shutil.make_archive",
"RPi.GPIO.setup",
"settings.clavier",
"settings.check_memory",
"d... | [((74, 136), 'subprocess.call', 'call', (['[\'espeak "Welcome to granDome" 2>/dev/null\']'], {'shell': '(True)'}), '([\'espeak "Welcome to granDome" 2>/dev/null\'], shell=True)\n', (78, 136), False, 'from subprocess import call\n'), ((2281, 2299), 'settings.clavier', 'settings.clavier', ([], {}), '()\n', (2297, 2299), ... |
# using the requests library to access internet data
#import the requests library
import requests
import json
def main():
# Use requests to issue a standard HTTP GET request
url = "http://httpbin.org/json"
result = requests.get(url)
# Use the built-in JSON function to return parsed data
dataobj ... | [
"requests.get",
"json.dumps"
] | [((230, 247), 'requests.get', 'requests.get', (['url'], {}), '(url)\n', (242, 247), False, 'import requests\n'), ((346, 375), 'json.dumps', 'json.dumps', (['dataobj'], {'indent': '(4)'}), '(dataobj, indent=4)\n', (356, 375), False, 'import json\n')] |
#%%
import numpy as np
import sys
sys.path.append('..')
from utils.tester import Tester
import pickle
import os
import matplotlib.pyplot as plt
import math
import networkx as nx
import random
city_name = 'Phoenix'
save_file_name = '2021-04-23_14-02-29'
seed = 45
# city_name = 'Seattle'
# save_file_name = '2021-03-21... | [
"numpy.random.seed",
"matplotlib.pyplot.figure",
"pickle.load",
"numpy.exp",
"networkx.draw_networkx_labels",
"os.path.join",
"sys.path.append",
"numpy.max",
"random.seed",
"matplotlib.pyplot.show",
"numpy.average",
"networkx.draw",
"networkx.DiGraph",
"numpy.log",
"os.getcwd",
"numpy.... | [((34, 55), 'sys.path.append', 'sys.path.append', (['""".."""'], {}), "('..')\n", (49, 55), False, 'import sys\n'), ((488, 499), 'os.getcwd', 'os.getcwd', ([], {}), '()\n', (497, 499), False, 'import os\n'), ((577, 645), 'os.path.join', 'os.path.join', (['base_directory', '"""optimization"""', '"""save"""', 'save_file_... |
import twint
c = twint.Config()
c.Since = "2019-02-01"
c.Until = "2019-03-14"
c.Search = "(mujer OR mujeres OR niña OR niñas OR chica OR chicas) AND \
((ingeniera OR científica OR arquitecta OR programadora OR bióloga) OR \
(ingeniería OR ciencia OR stem)) OR \
(tecnología OR software OR metalurgía OR minería OR agro... | [
"twint.run.Search",
"twint.Config"
] | [((18, 32), 'twint.Config', 'twint.Config', ([], {}), '()\n', (30, 32), False, 'import twint\n'), ((408, 427), 'twint.run.Search', 'twint.run.Search', (['c'], {}), '(c)\n', (424, 427), False, 'import twint\n')] |
#!/usr/bin/env python3
import sys
import os
MCELL_PATH = os.environ.get('MCELL_PATH', '')
if MCELL_PATH:
sys.path.append(os.path.join(MCELL_PATH, 'lib'))
else:
print("Error: variable MCELL_PATH that is used to find the mcell library was not set.")
sys.exit(1)
import mcell as m
if len(sys.argv) == 3 and... | [
"os.path.join",
"mcell.bngl_utils.load_bngl_parameters",
"mcell.Model",
"os.environ.get",
"mcell.SurfaceClass",
"mcell.geometry_utils.create_box",
"sys.exit"
] | [((59, 91), 'os.environ.get', 'os.environ.get', (['"""MCELL_PATH"""', '""""""'], {}), "('MCELL_PATH', '')\n", (73, 91), False, 'import os\n'), ((627, 671), 'mcell.bngl_utils.load_bngl_parameters', 'm.bngl_utils.load_bngl_parameters', (['bngl_file'], {}), '(bngl_file)\n', (660, 671), True, 'import mcell as m\n'), ((901,... |
#!/usr/bin/env python
import os
import re
from glob import glob
from os.path import basename, splitext
from setuptools import find_packages, setup # type: ignore
NAME = "contaxy"
MAIN_PACKAGE = NAME # Change if main package != NAME
DESCRIPTION = "Python package template."
URL = "https://github.com/ml-tooling/conta... | [
"os.path.basename",
"os.path.dirname",
"os.path.exists",
"glob.glob",
"os.path.join",
"setuptools.find_packages"
] | [((517, 542), 'os.path.dirname', 'os.path.dirname', (['__file__'], {}), '(__file__)\n', (532, 542), False, 'import os\n'), ((1382, 1455), 'setuptools.find_packages', 'find_packages', ([], {'where': '"""src"""', 'exclude': "('tests', 'test', 'examples', 'docs')"}), "(where='src', exclude=('tests', 'test', 'examples', 'd... |
# Copyright (c) 2020 Graphcore Ltd. All rights reserved.
"""
This module exposes an Optimizer wrapper to get regular tf.train.Optimizers to
allow for selecting the slots FP precision independently of the variable type.
Currently only supports Adam
"""
import os
import tensorflow.compat.v1 as tf
from tensorflow.python.... | [
"tensorflow.compat.v1.cast",
"tensorflow.python.training.optimizer._var_key",
"os.path.basename",
"tensorflow.python.training.slot_creator.create_zeros_slot",
"tensorflow.compat.v1.control_dependencies",
"tensorflow.python.ops.math_ops.sqrt",
"tensorflow.compat.v1.disable_eager_execution",
"tensorflow... | [((565, 589), 'tensorflow.compat.v1.disable_v2_behavior', 'tf.disable_v2_behavior', ([], {}), '()\n', (587, 589), True, 'import tensorflow.compat.v1 as tf\n'), ((590, 618), 'tensorflow.compat.v1.disable_eager_execution', 'tf.disable_eager_execution', ([], {}), '()\n', (616, 618), True, 'import tensorflow.compat.v1 as t... |
from contextlib import contextmanager
from pathlib import Path
import os
from typing import Callable, NamedTuple, Type
@contextmanager
def work_dir(dir_path: Path):
"""
Path('.') will change.
"""
org_dir_path = Path(os.getcwd())
os.chdir(dir_path)
try:
yield
finally:
os.chd... | [
"os.getcwd",
"os.chdir"
] | [((251, 269), 'os.chdir', 'os.chdir', (['dir_path'], {}), '(dir_path)\n', (259, 269), False, 'import os\n'), ((234, 245), 'os.getcwd', 'os.getcwd', ([], {}), '()\n', (243, 245), False, 'import os\n'), ((314, 336), 'os.chdir', 'os.chdir', (['org_dir_path'], {}), '(org_dir_path)\n', (322, 336), False, 'import os\n')] |
# coding=utf-8
#python 3getdataEveryGroup.py ./data/data1234.xlsx ./data/data5.xlsx ./data_11_4/
from langconv import Converter
import pandas as pd
import csv
import math
import re
import argparse
def rmSymbol(sent):
return re.sub("|/\n", "", sent)
'''
input : 4個同組的question
output : [[][]
[][]
... | [
"csv.writer",
"argparse.ArgumentParser",
"math.floor",
"pandas.read_excel",
"re.sub"
] | [((232, 256), 're.sub', 're.sub', (['"""|/\n"""', '""""""', 'sent'], {}), "('|/\\n', '', sent)\n", (238, 256), False, 'import re\n'), ((946, 971), 'argparse.ArgumentParser', 'argparse.ArgumentParser', ([], {}), '()\n', (969, 971), False, 'import argparse\n'), ((1136, 1197), 'pandas.read_excel', 'pd.read_excel', (['args... |
# -*- coding: utf-8 -*-
from flask import Flask, request, jsonify, render_template, json, redirect, url_for
from flask_cors import CORS
from pymongo import MongoClient # 몽고디비
import requests # 서버 요청 패키지
import os
from pprint import pprint
import hashlib
import jwt
import datetime
from urllib.parse import parse_qsl
K... | [
"flask.request.form.get",
"flask_cors.CORS",
"os.popen",
"jwt.encode",
"datetime.datetime.utcnow",
"flask.jsonify",
"flask.url_for",
"pprint.pprint",
"requests.post",
"jwt.decode",
"flask.request.args.get",
"datetime.timedelta",
"flask.render_template",
"requests.get",
"flask.request.get... | [((394, 409), 'flask.Flask', 'Flask', (['__name__'], {}), '(__name__)\n', (399, 409), False, 'from flask import Flask, request, jsonify, render_template, json, redirect, url_for\n'), ((468, 521), 'flask_cors.CORS', 'CORS', (['application'], {'resources': "{'/*': {'origins': '*'}}"}), "(application, resources={'/*': {'o... |
import sys
def myinput():
return sys.stdin.readline()
N = int(myinput())
data = myinput().split()
dict = {
'L' : [0, -1],
'R' : [0, +1],
'U' : [-1, 0],
'D' : [+1, 0],
}
start = [1, 1]
for cmd in data:
next = [start[i] + dict[cmd][i] for i in range(2)]
# print(f'next is {next}')
if n... | [
"sys.stdin.readline"
] | [((38, 58), 'sys.stdin.readline', 'sys.stdin.readline', ([], {}), '()\n', (56, 58), False, 'import sys\n')] |
import numpy as np
import pandas as pd
import pickle
import tensorflow as tf
import random
import math
import os
import time
from sklearn.metrics import average_precision_score
# ------------------------------------------------------ loading libraries ----
# --- setting random seed ----------------------------------... | [
"tensorflow.random.set_seed",
"sklearn.metrics.average_precision_score",
"random.seed",
"numpy.random.seed"
] | [((353, 375), 'numpy.random.seed', 'np.random.seed', (['seed_n'], {}), '(seed_n)\n', (367, 375), True, 'import numpy as np\n'), ((376, 395), 'random.seed', 'random.seed', (['seed_n'], {}), '(seed_n)\n', (387, 395), False, 'import random\n'), ((396, 422), 'tensorflow.random.set_seed', 'tf.random.set_seed', (['seed_n'], ... |
import pytest
from django.apps import apps
@pytest.mark.django_db
def test_models_passthrough(settings):
MyModel = apps.get_model("test_app.MyModel")
entered = "c++"
expected = "c"
m = MyModel(title=entered)
m.save()
assert m.django_extensions_slug == expected
@pytest.mark.django_db
def t... | [
"django.apps.apps.get_model"
] | [((122, 156), 'django.apps.apps.get_model', 'apps.get_model', (['"""test_app.MyModel"""'], {}), "('test_app.MyModel')\n", (136, 156), False, 'from django.apps import apps\n'), ((430, 464), 'django.apps.apps.get_model', 'apps.get_model', (['"""test_app.MyModel"""'], {}), "('test_app.MyModel')\n", (444, 464), False, 'fro... |
"""
Settings specific to development environments
"""
from os import path
from settings.base import PROJECT_DIR, MIDDLEWARE_CLASSES, INSTALLED_APPS
DATABASES = {
'default': {
'ENGINE': 'django.db.backends.sqlite3',
'NAME': path.join(PROJECT_DIR, 'data', 'data.db'),
}
}
DEBUG = True
TEMPLATE_... | [
"os.path.join"
] | [((246, 287), 'os.path.join', 'path.join', (['PROJECT_DIR', '"""data"""', '"""data.db"""'], {}), "(PROJECT_DIR, 'data', 'data.db')\n", (255, 287), False, 'from os import path\n'), ((924, 955), 'os.path.join', 'path.join', (['PROJECT_DIR', '"""cache"""'], {}), "(PROJECT_DIR, 'cache')\n", (933, 955), False, 'from os impo... |
import carla
import random
from carla_painter import CarlaPainter
def do_something(data):
pass
def main():
try:
# initialize one painter
painter = CarlaPainter('localhost', 8089)
client = carla.Client('localhost', 2000)
client.set_timeout(10.0)
world = client.get_worl... | [
"carla_painter.CarlaPainter",
"carla.command.DestroyActor",
"carla.command.SpawnActor",
"carla.command.SetAutopilot",
"carla.WorldSettings",
"carla.Client",
"carla.Location"
] | [((174, 205), 'carla_painter.CarlaPainter', 'CarlaPainter', (['"""localhost"""', '(8089)'], {}), "('localhost', 8089)\n", (186, 205), False, 'from carla_painter import CarlaPainter\n'), ((224, 255), 'carla.Client', 'carla.Client', (['"""localhost"""', '(2000)'], {}), "('localhost', 2000)\n", (236, 255), False, 'import ... |
import numpy as np
def quotient(rri):
rri = np.array(rri)
L = len(rri) - 1
indices = np.where((rri[:L - 1] / rri[1:L] < 0.8) |
(rri[:L - 1] / rri[1:L] > 1.2) |
(rri[1:L] / rri[:L - 1] < 0.8) |
(rri[1:L] / rri[:L - 1] > 1.2))
return... | [
"numpy.where",
"numpy.array",
"numpy.delete"
] | [((50, 63), 'numpy.array', 'np.array', (['rri'], {}), '(rri)\n', (58, 63), True, 'import numpy as np\n'), ((100, 243), 'numpy.where', 'np.where', (['((rri[:L - 1] / rri[1:L] < 0.8) | (rri[:L - 1] / rri[1:L] > 1.2) | (rri[1:L\n ] / rri[:L - 1] < 0.8) | (rri[1:L] / rri[:L - 1] > 1.2))'], {}), '((rri[:L - 1] / rri[1:L]... |
#Copyright 2018 Amazon.com, Inc. or its affiliates. All Rights Reserved.
#PDX-License-Identifier: MIT-0 (For details, see https://github.com/awsdocs/amazon-rekognition-developer-guide/blob/master/LICENSE-SAMPLECODE.)
import boto3
from botocore.exceptions import ClientError
from os import environ
if __name__ == "__mai... | [
"boto3.client"
] | [((431, 458), 'boto3.client', 'boto3.client', (['"""rekognition"""'], {}), "('rekognition')\n", (443, 458), False, 'import boto3\n')] |
import itertools
import os
import re
import sys
# scans files to construct an empirical prior
from bifs import BIFS
# numpy >= 1.17
from numpy.random import Generator, PCG64
import numpy as np
class RunningMean:
"""Accepts values one at a time and computes the mean and sd of all values seen so far.
The input... | [
"numpy.random.PCG64",
"numpy.logical_not",
"os.walk",
"itertools.count",
"bifs.BIFS",
"numpy.sqrt",
"os.path.join",
"numpy.concatenate",
"re.compile"
] | [((1426, 1458), 'numpy.sqrt', 'np.sqrt', (['(self._ss / (self.n - 1))'], {}), '(self._ss / (self.n - 1))\n', (1433, 1458), True, 'import numpy as np\n'), ((4677, 4683), 'bifs.BIFS', 'BIFS', ([], {}), '()\n', (4681, 4683), False, 'from bifs import BIFS\n'), ((10015, 10042), 're.compile', 're.compile', (['matchFile', 're... |
from django.core.management.base import BaseCommand
from django.utils import timezone
from datetime import timedelta, date
from django.contrib import messages
from skeleton.utils import get_current_season, get_site_season_start_end
from skeleton.models import Reading, Site, Farm, WeatherStation, Season
import os
impor... | [
"skeleton.utils.get_site_season_start_end",
"skeleton.utils.get_current_season",
"skeleton.models.Season.objects.get",
"json.dumps",
"skeleton.models.Reading.objects.select_related",
"datetime.timedelta",
"requests.post",
"re.search",
"os.getenv",
"logging.getLogger"
] | [((408, 435), 'logging.getLogger', 'logging.getLogger', (['__name__'], {}), '(__name__)\n', (425, 435), False, 'import logging\n'), ((8725, 8838), 'requests.post', 'requests.post', (["('https://hortplus.metwatch.nz/index.php?pageID=wxn_wget_post&serial=' + serial\n )"], {'data': 'data'}), "(\n 'https://hortplus.m... |
import argparse
import datetime
import mock
import pytest
from batch.etrade_csv_ingestor import EtradeIngestor
from batch.etrade_csv_ingestor import RowParserException
from stock_analysis.logic import order_history
class TestEtradeCsvIngestor(object):
def test_init(self):
batch = EtradeIngestor()
... | [
"argparse.Namespace",
"mock.patch.object",
"batch.etrade_csv_ingestor.EtradeIngestor",
"mock.call",
"mock.patch",
"datetime.datetime",
"pytest.raises",
"mock.Mock"
] | [((297, 313), 'batch.etrade_csv_ingestor.EtradeIngestor', 'EtradeIngestor', ([], {}), '()\n', (311, 313), False, 'from batch.etrade_csv_ingestor import EtradeIngestor\n'), ((583, 599), 'batch.etrade_csv_ingestor.EtradeIngestor', 'EtradeIngestor', ([], {}), '()\n', (597, 599), False, 'from batch.etrade_csv_ingestor impo... |
#!/usr/bin/env python3
"""Sends out a message to a selected group of Google Hangouts contacts."""
import time
import pyautogui
def auto_message(name, message):
"""Searches for friend on Google Hangouts and messages them."""
print("Make sure the Google Hangout 'Conversations' page is visible and "
... | [
"pyautogui.typewrite",
"pyautogui.press",
"time.sleep",
"pyautogui.locateOnScreen",
"pyautogui.click",
"pyautogui.doubleClick"
] | [((369, 382), 'time.sleep', 'time.sleep', (['(3)'], {}), '(3)\n', (379, 382), False, 'import time\n'), ((401, 439), 'pyautogui.locateOnScreen', 'pyautogui.locateOnScreen', (['"""search.png"""'], {}), "('search.png')\n", (425, 439), False, 'import pyautogui\n'), ((444, 471), 'pyautogui.click', 'pyautogui.click', (['sear... |
from dependency.status import Status
from subprocess import run, Popen, PIPE
class Installer:
"""Installer class which chooses from the package manager,
then installs package.
"""
def __init__(self):
self._stat = Status()
def _apt(self, pkg):
"""Installs the required package with ... | [
"dependency.status.Status",
"subprocess.run",
"subprocess.Popen"
] | [((239, 247), 'dependency.status.Status', 'Status', ([], {}), '()\n', (245, 247), False, 'from dependency.status import Status\n'), ((440, 476), 'subprocess.run', 'run', (["['sudo', 'apt', 'install', pkg]"], {}), "(['sudo', 'apt', 'install', pkg])\n", (443, 476), False, 'from subprocess import run, Popen, PIPE\n'), ((1... |
import math
import time
import numpy
import scipy.stats as stats
import utils as u
# Easy part : calculate number of gifts from house number
# part 1 -'*'-.,__,.-'*'-.,__,.-'*'-.,__,.-'*'-.,__,.-'*'-.,__,.-'*'-.,__,.-'*'-.,_
def get_number_of_gifts(house_number):
result = 0
return 10 * sigma(house_number)... | [
"math.gcd",
"utils.answer_part_1",
"time.time"
] | [((2502, 2513), 'time.time', 'time.time', ([], {}), '()\n', (2511, 2513), False, 'import time\n'), ((1380, 1394), 'math.gcd', 'math.gcd', (['x', 'y'], {}), '(x, y)\n', (1388, 1394), False, 'import math\n'), ((2856, 2874), 'utils.answer_part_1', 'u.answer_part_1', (['i'], {}), '(i)\n', (2871, 2874), True, 'import utils ... |
# -*- coding: utf-8 -*-
import cv2
import numpy as np
import sys
import os
from autoaim import helpers
class Camera():
def __init__(self, source):
self.source = source
self.capture = cv2.VideoCapture(source)
if type(source) is int:
self.__camera = True
def snapshot(self, s... | [
"cv2.VideoCapture",
"autoaim.helpers.showoff",
"numpy.array"
] | [((205, 229), 'cv2.VideoCapture', 'cv2.VideoCapture', (['source'], {}), '(source)\n', (221, 229), False, 'import cv2\n'), ((1730, 1753), 'numpy.array', 'np.array', (['[3600, 60, 1]'], {}), '([3600, 60, 1])\n', (1738, 1753), True, 'import numpy as np\n'), ((936, 987), 'autoaim.helpers.showoff', 'helpers.showoff', (['img... |
import psycopg2
from psycopg2 import sql, extras
# If there is no venv, run schrodinger_virtualenv.py schrodinger.ve to install pycopg2
# In win powershell as admin:
# >Set-Location -Path "C:\Program Files\Schrodinger2020-3"
# >Set-ExecutionPolicy RemoteSigned
# >schrodinger.ve\Scripts\activate
# or source schroding... | [
"psycopg2.extras.execute_values",
"psycopg2.connect"
] | [((679, 758), 'psycopg2.connect', 'psycopg2.connect', ([], {'dbname': 'dbname', 'user': 'user', 'password': 'password', 'host': '"""localhost"""'}), "(dbname=dbname, user=user, password=password, host='localhost')\n", (695, 758), False, 'import psycopg2\n'), ((953, 1038), 'psycopg2.extras.execute_values', 'extras.execu... |
#!/usr/bin/python3
# -*- coding: utf-8 -*-
""" model.py: A custom model for CityPersons. """
import numpy as np
import torch
import torch.utils.data
import torchvision
from torchvision.models.detection.faster_rcnn import FastRCNNPredictor
from engine import train_one_epoch, evaluate
import utils
import transforms as T... | [
"torchvision.models.detection.faster_rcnn.FastRCNNPredictor",
"torch.optim.lr_scheduler.StepLR",
"torch.device",
"torch.no_grad",
"torch.utils.data.DataLoader",
"torch.load",
"torchvision.models.detection.fasterrcnn_resnet50_fpn",
"engine.train_one_epoch",
"numpy.uint8",
"torch.manual_seed",
"tr... | [((496, 565), 'torchvision.models.detection.fasterrcnn_resnet50_fpn', 'torchvision.models.detection.fasterrcnn_resnet50_fpn', ([], {'pretrained': '(True)'}), '(pretrained=True)\n', (548, 565), False, 'import torchvision\n'), ((926, 969), 'torchvision.models.detection.faster_rcnn.FastRCNNPredictor', 'FastRCNNPredictor',... |
import requests
def reportTemperature(cookie, token):
url = 'http://yiban.gxnu.edu.cn/v4/affairs/health-report/create'
headers = {
'Host': 'yiban.gxnu.edu.cn',
'Content-Type': 'application/json;charset=utf-8',
'X-Requested-With': 'XMLHttpRequest',
'X-Access-Token': tok... | [
"requests.post"
] | [((511, 561), 'requests.post', 'requests.post', ([], {'url': 'url', 'headers': 'headers', 'json': 'body'}), '(url=url, headers=headers, json=body)\n', (524, 561), False, 'import requests\n')] |
# Code adapted from https://github.com/ClementPinard/SfmLearner-Pytorch/blob/master/inverse_warp.py
from __future__ import division
from pytorch3d.ops.knn import knn_points
import torch
import torch.nn.functional as F
import cv2
import matplotlib.pyplot as plt
import numpy as np
from PIL import Image
import helper_fun... | [
"torch.ones",
"matplotlib.pyplot.show",
"torch.stack",
"torch.nn.functional.grid_sample",
"torch.eye",
"matplotlib.pyplot.imshow",
"numpy.zeros",
"torch.cat",
"scipy.spatial.transform.Rotation.random",
"PIL.Image.open",
"helper_functions.sigmoid_2_depth",
"numpy.finfo",
"cv2.imread",
"torc... | [((339, 357), 'numpy.finfo', 'np.finfo', (['np.float'], {}), '(np.float)\n', (347, 357), True, 'import numpy as np\n'), ((762, 806), 'helper_functions.sigmoid_2_depth', 'helper_functions.sigmoid_2_depth', (['depth_maps'], {}), '(depth_maps)\n', (794, 806), False, 'import helper_functions\n'), ((2657, 2703), 'torch.stac... |
# -*- coding: utf-8 -*-
#
# Copyright © 2014 Red Hat, Inc.
#
# This copyrighted material is made available to anyone wishing to use,
# modify, copy, or redistribute it subject to the terms and conditions
# of the GNU General Public License v.2, or (at your option) any later
# version. This program is distributed in t... | [
"wtforms.validators.Email",
"flask.ext.wtf.ValidationError",
"wtforms.validators.Required",
"wtforms.validators.Optional"
] | [((1567, 1626), 'flask.ext.wtf.ValidationError', 'wtf.ValidationError', (['"""Both password fields should be equal"""'], {}), "('Both password fields should be equal')\n", (1586, 1626), False, 'from flask.ext import wtf\n'), ((1803, 1832), 'wtforms.validators.Required', 'wtforms.validators.Required', ([], {}), '()\n', ... |
from glob import glob
import re
import operator
import os
import textwrap
import util
WEEKLY_METRICS_VERSION = "0.1"
ORG_WEEKLY_METRICS_VERSION = "0.1"
MONTHLY_METRICS_VERSION = "0.1"
ORG_MONTHLY_METRICS_VERSION = "0.1"
PATH_TO_METRICS_POSTS = "_posts"
PATH_TO_GRAPHS = "graphs"
WEEKLY_PROJECT_POST = """\
---
layout... | [
"textwrap.dedent",
"util.get_metrics_color",
"util.get_metrics_name",
"os.makedirs",
"operator.itemgetter",
"os.path.join",
"os.listdir"
] | [((1955, 2303), 'textwrap.dedent', 'textwrap.dedent', (['"""\n <table class="table table-condensed" style="border-collapse:collapse;">\n <thead>\n <tr>\n <th>Metric</th>\n <th>Latest</th>\n <th>Previous</th>\n <th colspan="2" style="text-align: center;">Diffe... |
import h5py
import numpy as np
fname = "/home/stark/.keras/models/vgg16_weights_tf_dim_ordering_tf_kernels.h5"
dfname = 'vgg16_owl.hdf5'
f = h5py.File(fname, 'r')
data_file = h5py.File(dfname, 'w')
# conv nodes
k = 1
for i in range(1, 6): # 5 blocks in total
for j in range(1, 4):
# This is how the author... | [
"h5py.File"
] | [((143, 164), 'h5py.File', 'h5py.File', (['fname', '"""r"""'], {}), "(fname, 'r')\n", (152, 164), False, 'import h5py\n'), ((177, 199), 'h5py.File', 'h5py.File', (['dfname', '"""w"""'], {}), "(dfname, 'w')\n", (186, 199), False, 'import h5py\n')] |
import shutil
import tempfile
import os
import networkx as nx
from .generate_output import *
from .isvalid import *
from .__init__ import __version__
def get_options():
import argparse
description = 'Generate multiple sequence alignments after running Panaroo'
parser = argparse.ArgumentParser(descriptio... | [
"argparse.ArgumentParser",
"tempfile.mkdtemp",
"shutil.rmtree",
"networkx.read_gml",
"os.path.join"
] | [((286, 363), 'argparse.ArgumentParser', 'argparse.ArgumentParser', ([], {'description': 'description', 'prog': '"""generate_panaroo_msa"""'}), "(description=description, prog='generate_panaroo_msa')\n", (309, 363), False, 'import argparse\n'), ((2360, 2393), 'os.path.join', 'os.path.join', (['args.output_dir', '""""""... |
# -*- coding: utf-8 -*-
#
# test_errors.py
#
# This file is part of NEST.
#
# Copyright (C) 2004 The NEST Initiative
#
# NEST 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 2 of the License, or... | [
"unittest.makeSuite",
"unittest.TextTestRunner",
"nest.ResetKernel"
] | [((2010, 2051), 'unittest.makeSuite', 'unittest.makeSuite', (['ErrorTestCase', '"""test"""'], {}), "(ErrorTestCase, 'test')\n", (2028, 2051), False, 'import unittest\n'), ((2095, 2131), 'unittest.TextTestRunner', 'unittest.TextTestRunner', ([], {'verbosity': '(2)'}), '(verbosity=2)\n', (2118, 2131), False, 'import unit... |
import pybullet_envs
from stable_baselines3 import SAC_GER
model = SAC_GER('MlpPolicy', 'MinitaurBulletEnv-v0', verbose=1, tensorboard_log="results/long_SAC_GER_MinitaurBullet/")
model.learn(total_timesteps=3000000)
| [
"stable_baselines3.SAC_GER"
] | [((68, 184), 'stable_baselines3.SAC_GER', 'SAC_GER', (['"""MlpPolicy"""', '"""MinitaurBulletEnv-v0"""'], {'verbose': '(1)', 'tensorboard_log': '"""results/long_SAC_GER_MinitaurBullet/"""'}), "('MlpPolicy', 'MinitaurBulletEnv-v0', verbose=1, tensorboard_log=\n 'results/long_SAC_GER_MinitaurBullet/')\n", (75, 184), Fa... |