code stringlengths 22 1.05M | apis listlengths 1 3.31k | extract_api stringlengths 75 3.25M |
|---|---|---|
"""
To run this in a publically available setting, use --host=0.0.0.0
at the command line
"""
from flask import Flask, render_template, request
from typing import Dict
from src.video_captions import Video
import datetime
app = Flask(__name__)
@app.route("/", methods=["GET", "POST"])
def home():
if request.m... | [
"flask.render_template",
"src.video_captions.Video",
"datetime.datetime.strftime",
"flask.Flask"
] | [((231, 246), 'flask.Flask', 'Flask', (['__name__'], {}), '(__name__)\n', (236, 246), False, 'from flask import Flask, render_template, request\n'), ((878, 888), 'src.video_captions.Video', 'Video', (['url'], {}), '(url)\n', (883, 888), False, 'from src.video_captions import Video\n'), ((1196, 1206), 'src.video_caption... |
import os
import threading
import time
from selenium import webdriver
class WebDriverThread(threading.Thread):
def __init__(self, application_scoped_drivers, unique_id,
timeout=50, interval=1):
super(WebDriverThread, self).__init__()
self.timeout = timeout
self.interval =... | [
"selenium.webdriver.PhantomJS",
"os.getppid",
"os.getpid",
"time.sleep"
] | [((576, 626), 'selenium.webdriver.PhantomJS', 'webdriver.PhantomJS', (['settings.PHANTOMJS_EXECUTABLE'], {}), '(settings.PHANTOMJS_EXECUTABLE)\n', (595, 626), False, 'from selenium import webdriver\n'), ((934, 959), 'time.sleep', 'time.sleep', (['self.interval'], {}), '(self.interval)\n', (944, 959), False, 'import tim... |
# -*- coding: utf-8 -*-
# czatpro/czat/views.py
from django.http import HttpResponse
def index(request):
"""Strona główna aplikacji."""
return HttpResponse("Witaj w aplikacji Czat!")
| [
"django.http.HttpResponse"
] | [((154, 193), 'django.http.HttpResponse', 'HttpResponse', (['"""Witaj w aplikacji Czat!"""'], {}), "('Witaj w aplikacji Czat!')\n", (166, 193), False, 'from django.http import HttpResponse\n')] |
from hashlib import sha256
from bitstring import BitArray
import requests
import sys
import logging
BITLENGTH = 128
logging.basicConfig(level=logging.INFO, stream=sys.stdout)
logger = logging.getLogger(__name__)
def info(string):
print(string, flush=True)
# logger.info(string)
def compute_key(string, bi... | [
"logging.basicConfig",
"requests.get",
"logging.getLogger",
"bitstring.BitArray"
] | [((120, 178), 'logging.basicConfig', 'logging.basicConfig', ([], {'level': 'logging.INFO', 'stream': 'sys.stdout'}), '(level=logging.INFO, stream=sys.stdout)\n', (139, 178), False, 'import logging\n'), ((188, 215), 'logging.getLogger', 'logging.getLogger', (['__name__'], {}), '(__name__)\n', (205, 215), False, 'import ... |
from django import forms
from django.contrib.auth import password_validation
from django.contrib.auth.forms import UserCreationForm, UserChangeForm
from django.contrib.auth.forms import ReadOnlyPasswordHashField
from .models import UserAccount
class UserAccountCreationForm(UserCreationForm):
"""
Formulaire po... | [
"django.contrib.auth.password_validation.password_validators_help_text_html",
"django.forms.PasswordInput",
"django.contrib.auth.forms.ReadOnlyPasswordHashField",
"django.forms.ValidationError"
] | [((1577, 1604), 'django.contrib.auth.forms.ReadOnlyPasswordHashField', 'ReadOnlyPasswordHashField', ([], {}), '()\n', (1602, 1604), False, 'from django.contrib.auth.forms import ReadOnlyPasswordHashField\n'), ((433, 454), 'django.forms.PasswordInput', 'forms.PasswordInput', ([], {}), '()\n', (452, 454), False, 'from dj... |
import logging
logging.getLogger("elasticsearch").setLevel(logging.WARNING)
| [
"logging.getLogger"
] | [((16, 50), 'logging.getLogger', 'logging.getLogger', (['"""elasticsearch"""'], {}), "('elasticsearch')\n", (33, 50), False, 'import logging\n')] |
# ##### BEGIN GPL LICENSE BLOCK #####
#
# This program 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 (at your option) any later version.
#
# This program is distrib... | [
"bpy.props.BoolProperty",
"bpy.props.StringProperty",
"bpy.ops.wm.keyconfig_export",
"bpy.path.display_name_to_filepath",
"bpy.path.display_name",
"os.path.join",
"os.path.splitext",
"bpy.utils.user_resource",
"bpy.types.Menu.draw_preset",
"bpy.utils.preset_find",
"os.remove",
"bpy.ops.script.... | [((1274, 1407), 'bpy.props.StringProperty', 'StringProperty', ([], {'name': '"""Name"""', 'description': '"""Name of the preset, used to make the path name"""', 'maxlen': '(64)', 'options': "{'SKIP_SAVE'}"}), "(name='Name', description=\n 'Name of the preset, used to make the path name', maxlen=64, options={\n 'S... |
from django import template
register = template.Library()
@register.filter
def next(some_list, current_index):
"""
Returns the next element of the list using the current index if it exists.
Otherwise returns an empty string.
https://docs.djangoproject.com/en/3.0/howto/custom-template-tags/#writing-c... | [
"django.template.Library"
] | [((40, 58), 'django.template.Library', 'template.Library', ([], {}), '()\n', (56, 58), False, 'from django import template\n')] |
import operator
from itertools import chain
from Logic.ProperLogic.helper_classes.reducer import MaxReducer
from Logic.ProperLogic.misc_helpers import log_error
class ClusterDict(dict):
# TODO: Make sure constructor is only called when needed / doesn't produce more work than necessary!
def __init__(self, cl... | [
"operator.attrgetter",
"Logic.ProperLogic.helper_classes.reducer.MaxReducer",
"Logic.ProperLogic.misc_helpers.log_error"
] | [((418, 430), 'Logic.ProperLogic.helper_classes.reducer.MaxReducer', 'MaxReducer', ([], {}), '()\n', (428, 430), False, 'from Logic.ProperLogic.helper_classes.reducer import MaxReducer\n'), ((1757, 1784), 'operator.attrgetter', 'operator.attrgetter', (['*attrs'], {}), '(*attrs)\n', (1776, 1784), False, 'import operator... |
from collections import OrderedDict
import numpy as np
import math
import torch
import torch.optim as optim
from torch import nn as nn
import rlkit.torch.pytorch_util as ptu
from rlkit.core.eval_util import create_stats_ordered_dict
from rlkit.torch.torch_rl_algorithm import TorchTrainer
def kl_divergence(mu, std):... | [
"numpy.prod",
"collections.OrderedDict",
"math.log",
"torch.min",
"torch.nn.MSELoss",
"rlkit.torch.pytorch_util.get_numpy",
"torch.sum",
"rlkit.torch.pytorch_util.soft_update_from_to",
"rlkit.torch.pytorch_util.zeros"
] | [((489, 530), 'torch.sum', 'torch.sum', (['(weight * (input - target) ** 2)'], {}), '(weight * (input - target) ** 2)\n', (498, 530), False, 'import torch\n'), ((2104, 2116), 'torch.nn.MSELoss', 'nn.MSELoss', ([], {}), '()\n', (2114, 2116), True, 'from torch import nn as nn\n'), ((2145, 2157), 'torch.nn.MSELoss', 'nn.M... |
#!/usr/bin/python
'''
["SnapshotArray","snap","snap","get","set","snap","set"]
[[4],[],[],[3,1],[2,4],[],[1,4]]
'''
from Solution import SnapshotArray
'''
obj = SnapshotArray(4)
obj.snap()
obj.snap()
print(obj.get(3, 1))
obj.set(2, 4)
obj.snap()
obj.set(1, 4)
#
obj = SnapshotArray(2)
obj.snap()
print(obj.get(1, 0))
p... | [
"Solution.SnapshotArray"
] | [((813, 829), 'Solution.SnapshotArray', 'SnapshotArray', (['(1)'], {}), '(1)\n', (826, 829), False, 'from Solution import SnapshotArray\n')] |
# -*- coding: utf-8 -*-
""" InfluxDB emitter """
import logging
from distutils import util as distutil
from influxdb_client import InfluxDBClient
from influxdb_client.client.write_api import SYNCHRONOUS
from jinja2 import Template
from tilty.common import safe_get_key
LOGGER = logging.getLogger()
def __type__() ->... | [
"logging.getLogger",
"tilty.common.safe_get_key",
"jinja2.Template"
] | [((281, 300), 'logging.getLogger', 'logging.getLogger', ([], {}), '()\n', (298, 300), False, 'import logging\n'), ((658, 702), 'jinja2.Template', 'Template', (["config['gravity_payload_template']"], {}), "(config['gravity_payload_template'])\n", (666, 702), False, 'from jinja2 import Template\n'), ((747, 795), 'jinja2.... |
import os
import utils
import torch
import torch.nn as nn
from torchvision import transforms
from torch.utils.data import DataLoader
import numpy as np
import data
import scipy.io as sio
from options.training_options import TrainOptions
import utils
import time
from models import AutoEncoderCov3D, AutoEncoderCov3DMem
f... | [
"models.EntropyLossEncap",
"numpy.ones",
"utils.UnNormalize",
"utils.get_model_setting",
"os.path.join",
"options.training_options.TrainOptions",
"utils.Logger",
"torch.nn.MSELoss",
"utils.seed",
"utils.mkdir",
"torchvision.transforms.Normalize",
"torch.utils.data.DataLoader",
"numpy.concate... | [((373, 387), 'options.training_options.TrainOptions', 'TrainOptions', ([], {}), '()\n', (385, 387), False, 'from options.training_options import TrainOptions\n'), ((458, 501), 'torch.device', 'torch.device', (["('cuda' if use_cuda else 'cpu')"], {}), "('cuda' if use_cuda else 'cpu')\n", (470, 501), False, 'import torc... |
# Example of embedding hiplot into dash
import dash
from dash import html
from dash import dcc
from dash.dependencies import Input, Output, State
import pandas as pd
import hiplot as hip
df = pd.read_csv('https://gist.githubusercontent.com/chriddyp/c78bf172206ce24f77d6363a2d754b59/raw/c353e8ef842413cae56ae3920b8fd784... | [
"pandas.read_csv",
"dash.dependencies.Output",
"dash.dependencies.Input",
"hiplot.Experiment.from_dataframe",
"dash.html.Button",
"dash.dependencies.State",
"dash.html.Iframe",
"dash.Dash"
] | [((194, 374), 'pandas.read_csv', 'pd.read_csv', (['"""https://gist.githubusercontent.com/chriddyp/c78bf172206ce24f77d6363a2d754b59/raw/c353e8ef842413cae56ae3920b8fd78468aa4cb2/usa-agricultural-exports-2011.csv"""'], {}), "(\n 'https://gist.githubusercontent.com/chriddyp/c78bf172206ce24f77d6363a2d754b59/raw/c353e8ef8... |
from django.conf.urls import url
from base import views as base_views
app_name = 'base'
urlpatterns = [
url(r'',
base_views.ProtectedDataView.as_view(),
name='protected_data'),
]
| [
"base.views.ProtectedDataView.as_view"
] | [((128, 166), 'base.views.ProtectedDataView.as_view', 'base_views.ProtectedDataView.as_view', ([], {}), '()\n', (164, 166), True, 'from base import views as base_views\n')] |
from dataclasses import dataclass
from sqlalchemy.ext.declarative import declared_attr
from sqlalchemy.orm import registry
mapper_registry = registry()
@dataclass
class Base:
__sa_dataclass_metadata_key__ = "sa"
@declared_attr # type: ignore[misc]
def __tablename__(cls) -> str:
return cls.__na... | [
"sqlalchemy.orm.registry"
] | [((143, 153), 'sqlalchemy.orm.registry', 'registry', ([], {}), '()\n', (151, 153), False, 'from sqlalchemy.orm import registry\n')] |
from os import environ as env
from os import urandom, path
import sqlite3
import json
# Schema
db = sqlite3.connect('gixnay.db')
db_cursor = db.cursor()
db_cursor.execute("""CREATE TABLE IF NOT EXISTS Countries (
name TEXT NOT NULL,
-- name of country
abbreviation VARCHAR(... | [
"os.urandom",
"os.path.join",
"sqlite3.connect"
] | [((101, 129), 'sqlite3.connect', 'sqlite3.connect', (['"""gixnay.db"""'], {}), "('gixnay.db')\n", (116, 129), False, 'import sqlite3\n'), ((1689, 1700), 'os.urandom', 'urandom', (['(64)'], {}), '(64)\n', (1696, 1700), False, 'from os import urandom, path\n'), ((2068, 2101), 'os.path.join', 'path.join', (["env['HOME']",... |
# encoding: utf-8
import pytest
import six
from flask import Blueprint
import ckan.plugins as p
from ckan.common import config, _
class MockRoutingPlugin(p.SingletonPlugin):
p.implements(p.IBlueprint)
def get_blueprint(self):
# Create Blueprint for plugin
blueprint = Blueprint(self.name, s... | [
"ckan.common._",
"six.ensure_text",
"pytest.raises",
"pytest.mark.ckan_config",
"flask.Blueprint",
"ckan.plugins.implements"
] | [((1238, 1299), 'pytest.mark.ckan_config', 'pytest.mark.ckan_config', (['u"""SECRET_KEY"""', 'u"""super_secret_stuff"""'], {}), "(u'SECRET_KEY', u'super_secret_stuff')\n", (1261, 1299), False, 'import pytest\n'), ((1420, 1464), 'pytest.mark.ckan_config', 'pytest.mark.ckan_config', (['u"""SECRET_KEY"""', 'None'], {}), "... |
from functools import partial
from os import path
from .obj import load_obj, save_obj
from .off import load_off, save_off
def load_mesh(filename):
loaders = {
'obj': load_obj,
'off': partial(load_off, no_colors=True),
}
ext = path.splitext(filename)[1].lower()[1:]
if ext not in loader... | [
"os.path.splitext",
"functools.partial"
] | [((206, 239), 'functools.partial', 'partial', (['load_off'], {'no_colors': '(True)'}), '(load_off, no_colors=True)\n', (213, 239), False, 'from functools import partial\n'), ((257, 280), 'os.path.splitext', 'path.splitext', (['filename'], {}), '(filename)\n', (270, 280), False, 'from os import path\n'), ((612, 635), 'o... |
import pandas as pd
df = pd.read_csv(r'balanced_reviews.csv')
df.isnull().any(axis = 0)
#handle the missing data
df.dropna(inplace = True)
#leaving the reviews with rating 3 and collect reviews with
#rating 1, 2, 4 and 5 onyl
df = df [df['overall'] != 3]
import numpy as np
#creating a label... | [
"pickle.dump",
"pandas.read_csv",
"numpy.where",
"sklearn.model_selection.train_test_split",
"sklearn.linear_model.LogisticRegression",
"sklearn.metrics.roc_auc_score",
"sklearn.feature_extraction.text.TfidfVectorizer",
"sklearn.metrics.confusion_matrix"
] | [((29, 64), 'pandas.read_csv', 'pd.read_csv', (['"""balanced_reviews.csv"""'], {}), "('balanced_reviews.csv')\n", (40, 64), True, 'import pandas as pd\n'), ((381, 414), 'numpy.where', 'np.where', (["(df['overall'] > 3)", '(1)', '(0)'], {}), "(df['overall'] > 3, 1, 0)\n", (389, 414), True, 'import numpy as np\n'), ((625... |
#basic components: Embedding Layer, Scaled Dot-Product Attention, Dense Layer
import numpy as np
import torch.nn.functional as F
from torch import nn
import torch
class Embed(nn.Module):
def __init__(self, length, emb_dim,
embeddings=None, trainable=False, dropout=.1):
super(Embed, self... | [
"torch.bmm",
"torch.nn.Dropout",
"numpy.sqrt",
"torch.abs",
"torch.nn.Softmax",
"numpy.power",
"torch.nn.LayerNorm",
"torch.from_numpy",
"torch.nn.init.xavier_normal_",
"torch.cat",
"numpy.zeros",
"numpy.array",
"numpy.cos",
"torch.nn.Linear",
"numpy.sin",
"torch.nn.Conv1d",
"torch.n... | [((367, 440), 'torch.nn.Embedding', 'nn.Embedding', ([], {'num_embeddings': 'length', 'embedding_dim': 'emb_dim', 'padding_idx': '(0)'}), '(num_embeddings=length, embedding_dim=emb_dim, padding_idx=0)\n', (379, 440), False, 'from torch import nn\n'), ((792, 811), 'torch.nn.Dropout', 'nn.Dropout', (['dropout'], {}), '(d... |
# -*- coding:utf-8 -*-
from flask import Blueprint
from flask import current_app
from flask_sqlalchemy import get_debug_queries
from model.permission import Permission
blog = Blueprint('blog', __name__)
@blog.app_context_processor
def inject_permissions():
return dict(Permission=Permission)
@blog.after_app_req... | [
"flask.current_app.logger.warning",
"flask.Blueprint",
"flask_sqlalchemy.get_debug_queries"
] | [((176, 203), 'flask.Blueprint', 'Blueprint', (['"""blog"""', '__name__'], {}), "('blog', __name__)\n", (185, 203), False, 'from flask import Blueprint\n'), ((371, 390), 'flask_sqlalchemy.get_debug_queries', 'get_debug_queries', ([], {}), '()\n', (388, 390), False, 'from flask_sqlalchemy import get_debug_queries\n'), (... |
# Licensed under the Apache License, Version 2.0 (the "License"); you may
# not use this file except in compliance with the License. You may obtain
# a copy of the License at
#
# http://www.apache.org/licenses/LICENSE-2.0
#
# Unless required by applicable law or agreed to in writing, software
# distributed under t... | [
"designate.objects.PoolAttributeList.from_list",
"designate.objects.ZoneAttributeList.from_list",
"unittest.mock.Mock",
"oslo_config.fixture.Config",
"designate.objects.PoolList.from_list",
"designate.objects.Zone",
"designate.scheduler.get_scheduler"
] | [((994, 1097), 'designate.objects.PoolList.from_list', 'objects.PoolList.from_list', (["[{'id': DEFAULT_POOL_ID}, {'id': SILVER_POOL_ID}, {'id': GOLD_POOL_ID}]"], {}), "([{'id': DEFAULT_POOL_ID}, {'id': SILVER_POOL_ID},\n {'id': GOLD_POOL_ID}])\n", (1020, 1097), False, 'from designate import objects\n'), ((1220, 130... |
#
# Licensed under the Apache License, Version 2.0 (the "License");
# you may not use this file except in compliance with the License.
# You may obtain a copy of the License at
#
# http://www.apache.org/licenses/LICENSE-2.0
#
# Unless required by applicable law or agreed to in writing, software
# distributed under ... | [
"textwrap.dedent",
"apache.aurora.client.cli.context.AuroraCommandContext"
] | [((1271, 1830), 'textwrap.dedent', 'textwrap.dedent', (['""" Start a scheduler-driven rolling upgrade on a running job, using the update\n configuration within the config file as a control for update velocity and failure\n tolerance.\n\n The updater only takes action on instances in a job th... |
# -*- coding: utf-8 -*-
import urwid
from blinker import signal
from plait.app.base import PlaitApp
from plait.frame import ConsoleFrame
from plait.tabs import VerticalTabs
class WorkerLog(urwid.ListBox):
def __init__(self):
walker = urwid.SimpleListWalker([])
urwid.ListBox.__init__(self, walker... | [
"plait.frame.ConsoleFrame",
"urwid.ListBox.__init__",
"urwid.TwistedEventLoop",
"urwid.SimpleListWalker",
"plait.tabs.VerticalTabs",
"urwid.Text"
] | [((250, 276), 'urwid.SimpleListWalker', 'urwid.SimpleListWalker', (['[]'], {}), '([])\n', (272, 276), False, 'import urwid\n'), ((285, 321), 'urwid.ListBox.__init__', 'urwid.ListBox.__init__', (['self', 'walker'], {}), '(self, walker)\n', (307, 321), False, 'import urwid\n'), ((469, 485), 'urwid.Text', 'urwid.Text', ([... |
# ------------------------------------------------------------------
#
# Copyright (C) 2015 <NAME> <<EMAIL>>
#
# This program is free software; you can redistribute it and/or
# modify it under the terms of version 2 of the GNU General Public
# License published by the Free Software Foundation.
#
# ---------... | [
"cgitb.Hook",
"traceback.format_exception",
"pyronia.common.error",
"os.fdopen",
"tempfile.mkstemp"
] | [((1206, 1221), 'pyronia.common.error', 'error', (['ex.value'], {}), '(ex.value)\n', (1211, 1221), False, 'from pyronia.common import error\n'), ((1253, 1314), 'tempfile.mkstemp', 'tempfile.mkstemp', ([], {'prefix': '"""apparmor-bugreport-"""', 'suffix': '""".txt"""'}), "(prefix='apparmor-bugreport-', suffix='.txt')\n"... |
import requests
import cool_utils
from typing import Union
cache = {}
cool_utils.JSON.open("config")
class HTTPClient:
def __init__(self):
self.username = None
self.token = None
self.BASE = cool_utils.JSON.get_data("server")
@classmethod
def create_request(
self,
t... | [
"requests.post",
"cool_utils.JSON.open",
"requests.get",
"requests.delete",
"cool_utils.JSON.get_data"
] | [((71, 101), 'cool_utils.JSON.open', 'cool_utils.JSON.open', (['"""config"""'], {}), "('config')\n", (91, 101), False, 'import cool_utils\n'), ((220, 254), 'cool_utils.JSON.get_data', 'cool_utils.JSON.get_data', (['"""server"""'], {}), "('server')\n", (244, 254), False, 'import cool_utils\n'), ((775, 838), 'requests.ge... |
''' Python program to create email list from master. '''
import os
import csv
pathName = os.getcwd()
print(os.path.join(pathName, '/master.csv'))
file = open(os.path.join(pathName, 'master.csv'), "r")
reader = csv.reader(file, delimiter=',')
comp_dic = {}
tool_dic = {}
unsure_dic = {}
firstline = True
for row in ... | [
"os.path.join",
"csv.writer",
"csv.reader",
"os.getcwd"
] | [((92, 103), 'os.getcwd', 'os.getcwd', ([], {}), '()\n', (101, 103), False, 'import os\n'), ((214, 245), 'csv.reader', 'csv.reader', (['file'], {'delimiter': '""","""'}), "(file, delimiter=',')\n", (224, 245), False, 'import csv\n'), ((1533, 1544), 'os.getcwd', 'os.getcwd', ([], {}), '()\n', (1542, 1544), False, 'impor... |
from argparse import ArgumentParser
from os import listdir
from os.path import isfile, isdir
from zmigrate.config import load as load_config
from zmigrate.range import Range
from zmigrate.dir import Dir
from zmigrate.drivers import SUPPORTED_DRIVERS
def str_to_bool(v):
if isinstance(v, bool):
return v
i... | [
"os.listdir",
"argparse.ArgumentParser",
"zmigrate.dir.Dir",
"os.path.isfile",
"zmigrate.config.load",
"zmigrate.range.Range",
"os.path.isdir",
"zmigrate.drivers.SUPPORTED_DRIVERS.keys"
] | [((505, 518), 'os.path.isfile', 'isfile', (['value'], {}), '(value)\n', (511, 518), False, 'from os.path import isfile, isdir\n'), ((623, 635), 'os.path.isdir', 'isdir', (['value'], {}), '(value)\n', (628, 635), False, 'from os.path import isfile, isdir\n'), ((833, 846), 'zmigrate.config.load', 'load_config', ([], {}),... |
#!/usr/bin/env python
# -*- coding:utf-8 -*-
# @FileName : core_recorder.py
# @Time : 2020/9/25 12:29
# @Author : 陈嘉昕
# @Demand : 声音复杂记录
import threading
import logging
import wave
from pyaudio import PyAudio, paInt16
import numpy as np
import queue
import time
class CoreRecorder(threading.Thread):
... | [
"logging.getLogger",
"threading.Thread.__init__",
"wave.open",
"threading.Lock",
"numpy.fromstring",
"threading.Event",
"queue.Queue",
"pyaudio.PyAudio",
"time.time"
] | [((591, 622), 'threading.Thread.__init__', 'threading.Thread.__init__', (['self'], {}), '(self)\n', (616, 622), False, 'import threading\n'), ((736, 752), 'threading.Lock', 'threading.Lock', ([], {}), '()\n', (750, 752), False, 'import threading\n'), ((826, 871), 'logging.getLogger', 'logging.getLogger', (["(__name__ +... |
#!/usr/bin/python3
# Routes.py file
##### Imports #####
from flask import Flask, render_template, request
import requests, random
from application import app, db
from application.models import Character
from sqlalchemy import desc
##### Routes #####
@app.route('/', methods=['GET','POST'])
def ... | [
"flask.render_template",
"requests.post",
"application.db.session.add",
"application.db.session.commit",
"requests.get",
"sqlalchemy.desc",
"application.app.route",
"application.models.Character"
] | [((277, 316), 'application.app.route', 'app.route', (['"""/"""'], {'methods': "['GET', 'POST']"}), "('/', methods=['GET', 'POST'])\n", (286, 316), False, 'from application import app, db\n'), ((756, 797), 'requests.get', 'requests.get', (['"""http://service2:5001/race"""'], {}), "('http://service2:5001/race')\n", (768,... |
# import pandas and matplotlib
import pandas as pd
import numpy as np
import matplotlib.pyplot as plt
from matplotlib.ticker import FuncFormatter
from connection import setConnection
def liabilityasset():
dataT=setConnection(["profitloss"])
labels=[]
Income_of_all_trips=[]
Expenditure_of_the_year=[]
... | [
"matplotlib.pyplot.pie",
"pandas.DataFrame",
"matplotlib.pyplot.title",
"connection.setConnection",
"matplotlib.pyplot.subplots",
"matplotlib.pyplot.show"
] | [((218, 247), 'connection.setConnection', 'setConnection', (["['profitloss']"], {}), "(['profitloss'])\n", (231, 247), False, 'from connection import setConnection\n'), ((757, 771), 'matplotlib.pyplot.subplots', 'plt.subplots', ([], {}), '()\n', (769, 771), True, 'import matplotlib.pyplot as plt\n'), ((1739, 1749), 'ma... |
from datetime import timedelta
import uuid
import factory
from django.utils import timezone
from assopy.tests.factories.user import AssopyUserFactory
import conference.models
class CreditCardOrderFactory(factory.django.DjangoModelFactory):
class Meta:
model = 'assopy.Order'
user = factory.SubFacto... | [
"django.utils.timezone.now",
"factory.SubFactory",
"datetime.timedelta",
"uuid.uuid4"
] | [((304, 341), 'factory.SubFactory', 'factory.SubFactory', (['AssopyUserFactory'], {}), '(AssopyUserFactory)\n', (322, 341), False, 'import factory\n'), ((660, 672), 'uuid.uuid4', 'uuid.uuid4', ([], {}), '()\n', (670, 672), False, 'import uuid\n'), ((829, 846), 'datetime.timedelta', 'timedelta', ([], {'days': '(1)'}), '... |
from pygame.sprite import ( Sprite )
from src.entitys.mushroom import ( Mushroom )
from math import sin
class LootBlock( Sprite ):
def __init__( self, group_sprite, sheet, position, loot ):
self.groups = group_sprite
Sprite.__init__( self, group_sprite )
# ### STRING VARIABLES ###
... | [
"pygame.sprite.Sprite.__init__",
"math.sin",
"src.entitys.mushroom.Mushroom"
] | [((242, 277), 'pygame.sprite.Sprite.__init__', 'Sprite.__init__', (['self', 'group_sprite'], {}), '(self, group_sprite)\n', (257, 277), False, 'from pygame.sprite import Sprite\n'), ((1653, 1773), 'src.entitys.mushroom.Mushroom', 'Mushroom', (['self.groups', 'self.sheet[1]', '[self.mushroom_x, self.mushroom_y]', "('red... |
import logging
import os
from insights.core import archives
from insights.core.archives import COMPRESSION_TYPES
from insights.core.context import ClusterArchiveContext, JDRContext, HostArchiveContext, SosArchiveContext
log = logging.getLogger(__name__)
def get_all_files(path):
all_files = []
for f in archi... | [
"logging.getLogger",
"os.listdir",
"os.path.isfile",
"insights.core.archives.get_all_files",
"os.path.commonprefix",
"os.path.islink"
] | [((228, 255), 'logging.getLogger', 'logging.getLogger', (['__name__'], {}), '(__name__)\n', (245, 255), False, 'import logging\n'), ((315, 343), 'insights.core.archives.get_all_files', 'archives.get_all_files', (['path'], {}), '(path)\n', (337, 343), False, 'from insights.core import archives\n'), ((984, 1015), 'os.pat... |
import featext.feature_processing
from featext.mfcc import Mfcc
import numpy as np
import system.gmm_em as gmm
import system.ivector as ivector
import system.backend as backend
# UPDATE THIS FOLDER (folder to spoken digit dataset recordings):
data_folder = '/home/ville/files/recordings/'
speakers = ['jackson', 'nicol... | [
"featext.mfcc.Mfcc",
"numpy.mean",
"numpy.reshape",
"system.ivector.TMatrix",
"system.backend.GPLDA",
"system.gmm_em.GMM",
"numpy.argmax",
"system.backend.preprocess",
"system.backend.compute_mean",
"numpy.zeros",
"numpy.empty",
"numpy.cov",
"system.ivector.Ivector",
"numpy.arange"
] | [((551, 557), 'featext.mfcc.Mfcc', 'Mfcc', ([], {}), '()\n', (555, 557), False, 'from featext.mfcc import Mfcc\n'), ((863, 921), 'numpy.empty', 'np.empty', (['(n_speakers, n_digits, n_sessions)'], {'dtype': 'object'}), '((n_speakers, n_digits, n_sessions), dtype=object)\n', (871, 921), True, 'import numpy as np\n'), ((... |
import functools
import itertools
import operator
import numpy as np
from qecsim.model import StabilizerCode, cli_description
from qecsim.models.rotatedplanar import RotatedPlanarPauli
@cli_description('Rotated planar (rows INT >= 3, cols INT >= 3)')
class RotatedPlanarCode(StabilizerCode):
r"""
Implements ... | [
"itertools.chain",
"qecsim.model.cli_description",
"operator.index",
"numpy.array",
"functools.lru_cache",
"qecsim.models.rotatedplanar.RotatedPlanarPauli"
] | [((190, 254), 'qecsim.model.cli_description', 'cli_description', (['"""Rotated planar (rows INT >= 3, cols INT >= 3)"""'], {}), "('Rotated planar (rows INT >= 3, cols INT >= 3)')\n", (205, 254), False, 'from qecsim.model import StabilizerCode, cli_description\n'), ((3425, 3446), 'functools.lru_cache', 'functools.lru_ca... |
from sklearn.base import BaseEstimator, TransformerMixin
from autogluon.features.generators import OneHotEncoderFeatureGenerator
class OheFeaturesGenerator(BaseEstimator, TransformerMixin):
def __init__(self):
self._feature_names = []
self._encoder = None
def fit(self, X, y=None):
se... | [
"autogluon.features.generators.OneHotEncoderFeatureGenerator"
] | [((334, 394), 'autogluon.features.generators.OneHotEncoderFeatureGenerator', 'OneHotEncoderFeatureGenerator', ([], {'max_levels': '(10000)', 'verbosity': '(0)'}), '(max_levels=10000, verbosity=0)\n', (363, 394), False, 'from autogluon.features.generators import OneHotEncoderFeatureGenerator\n')] |
# Multi Indexing a Tensor
import tensorflow as tf
rank_2 = tf.constant(
[[1, 2],[3, 4],[5, 6]], dtype=tf.float16)
print(rank_2[1, 1].numpy())
# 4.0
print("Second row:", rank_2[1, :].numpy())
# Second row: [3. 4.]
print("Second column:", rank_2[:, 1].numpy())
# Second column: [2. 4. 6.]
# Skip first row :
rank_2[1:,... | [
"tensorflow.constant"
] | [((59, 114), 'tensorflow.constant', 'tf.constant', (['[[1, 2], [3, 4], [5, 6]]'], {'dtype': 'tf.float16'}), '([[1, 2], [3, 4], [5, 6]], dtype=tf.float16)\n', (70, 114), True, 'import tensorflow as tf\n')] |
import nose.tools as nt
import numpy as np
import theano
import theano.tensor as T
import treeano
import treeano.nodes as tn
from treeano.sandbox.nodes import lrn
fX = theano.config.floatX
def ground_truth_normalizer(bc01, k, n, alpha, beta):
"""
This code is adapted from pylearn2.
https://github.com/l... | [
"treeano.nodes.InputNode",
"numpy.testing.assert_equal",
"numpy.testing.assert_allclose",
"numpy.zeros",
"treeano.sandbox.nodes.lrn.LocalResponseNormalizationNode",
"treeano.sandbox.nodes.lrn.LocalResponseNormalization2DNode",
"theano.tensor.tensor4",
"numpy.random.randn"
] | [((1075, 1095), 'numpy.zeros', 'np.zeros', (['c01b.shape'], {}), '(c01b.shape)\n', (1083, 1095), True, 'import numpy as np\n'), ((1963, 2011), 'numpy.testing.assert_allclose', 'np.testing.assert_allclose', (['ans', 'res'], {'rtol': '(1e-05)'}), '(ans, res, rtol=1e-05)\n', (1989, 2011), True, 'import numpy as np\n'), ((... |
from pathlib import Path
from musurgia.pdf.line import HorizontalLineSegment, HorizontalSegmentedLine, VerticalSegmentedLine
from musurgia.pdf.pdf import Pdf
from musurgia.unittest import TestCase
path = Path(__file__)
class TestMarkLineLabels(TestCase):
def setUp(self) -> None:
self.pdf = Pdf()
... | [
"pathlib.Path",
"musurgia.pdf.pdf.Pdf",
"musurgia.pdf.line.HorizontalSegmentedLine",
"musurgia.pdf.line.VerticalSegmentedLine",
"musurgia.pdf.line.HorizontalLineSegment"
] | [((206, 220), 'pathlib.Path', 'Path', (['__file__'], {}), '(__file__)\n', (210, 220), False, 'from pathlib import Path\n'), ((307, 312), 'musurgia.pdf.pdf.Pdf', 'Pdf', ([], {}), '()\n', (310, 312), False, 'from musurgia.pdf.pdf import Pdf\n'), ((331, 363), 'musurgia.pdf.line.HorizontalLineSegment', 'HorizontalLineSegme... |
""" Script to send prediction request.
Usage:
python predict.py --url=YOUR_KF_HOST/models/coco --input_image=YOUR_LOCAL_IMAGE
--output_image=OUTPUT_IMAGE_NAME.
This will save the prediction result as OUTPUT_IMAGE_NAME.
The output image is the input image with the detected bounding boxes.
"""
import argparse
imp... | [
"PIL.Image.fromarray",
"PIL.Image.open",
"json.loads",
"argparse.ArgumentParser",
"numpy.array"
] | [((477, 502), 'argparse.ArgumentParser', 'argparse.ArgumentParser', ([], {}), '()\n', (500, 502), False, 'import argparse\n'), ((731, 759), 'PIL.Image.open', 'Image.open', (['args.input_image'], {}), '(args.input_image)\n', (741, 759), False, 'from PIL import Image\n'), ((824, 837), 'numpy.array', 'np.array', (['img'],... |
"""
Estimate luminosity function in COSMOS from interferometric follow-up of
Miettinen+ 2014, Younger+ 2007, and Younger+2009.
"""
import numpy
import matplotlib.pyplot as plt
from pylab import savefig
from astropy.table import Table
import matplotlib
def MonteCarloCounts(fluxes, errors):
hist890, bin_edges =... | [
"matplotlib.pyplot.ylabel",
"pylab.savefig",
"numpy.array",
"matplotlib.rc",
"matplotlib.pyplot.errorbar",
"numpy.arange",
"numpy.mean",
"numpy.histogram",
"matplotlib.pyplot.xlabel",
"matplotlib.pyplot.plot",
"matplotlib.pyplot.minorticks_on",
"numpy.exp",
"matplotlib.pyplot.axis",
"matpl... | [((1029, 1048), 'numpy.array', 'numpy.array', (['S_1100'], {}), '(S_1100)\n', (1040, 1048), False, 'import numpy\n'), ((1261, 1279), 'numpy.array', 'numpy.array', (['S_890'], {}), '(S_890)\n', (1272, 1279), False, 'import numpy\n'), ((1318, 1327), 'matplotlib.pyplot.clf', 'plt.clf', ([], {}), '()\n', (1325, 1327), True... |
"""
byceps.blueprints.admin.news.forms
~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~
:Copyright: 2006-2021 <NAME>
:License: Revised BSD (see `LICENSE` file for details)
"""
import re
from flask_babel import lazy_gettext
from wtforms import FileField, StringField, TextAreaField
from wtforms.fields.html5 import DateField, TimeFi... | [
"re.compile",
"wtforms.validators.Length",
"wtforms.validators.Optional",
"flask_babel.lazy_gettext",
"wtforms.validators.InputRequired"
] | [((451, 477), 're.compile', 're.compile', (['"""^[a-z0-9-]+$"""'], {}), "('^[a-z0-9-]+$')\n", (461, 477), False, 'import re\n'), ((558, 576), 'flask_babel.lazy_gettext', 'lazy_gettext', (['"""ID"""'], {}), "('ID')\n", (570, 576), False, 'from flask_babel import lazy_gettext\n'), ((674, 700), 'flask_babel.lazy_gettext',... |
#!/usr/bin/env python3
# Copyright (c) Facebook, Inc. and its affiliates.
# This source code is licensed under the MIT license found in the
# LICENSE file in the root directory of this source tree.
import os
import shutil
import subprocess
from mephisto.operations.operator import Operator
from mephisto.operations.uti... | [
"os.path.exists",
"json.loads",
"os.listdir",
"hydra.main",
"mephisto.tools.scripts.load_db_and_process_config",
"os.path.join",
"os.getcwd",
"os.chdir",
"shutil.rmtree",
"mephisto.abstractions.blueprints.abstract.static_task.static_blueprint.SharedStaticTaskState",
"subprocess.call",
"mephist... | [((995, 1063), 'mephisto.operations.hydra_config.register_script_config', 'register_script_config', ([], {'name': '"""scriptconfig"""', 'module': 'TestScriptConfig'}), "(name='scriptconfig', module=TestScriptConfig)\n", (1017, 1063), False, 'from mephisto.operations.hydra_config import RunScriptConfig, register_script_... |
# -*- coding: utf-8 -*-
# Generated by Django 1.9b1 on 2015-11-12 03:36
from __future__ import unicode_literals
from django.db import migrations, models
import django.db.models.deletion
class Migration(migrations.Migration):
dependencies = [
('arcfire', '0001_initial'),
]
operations = [
... | [
"django.db.models.CharField",
"django.db.models.ForeignKey"
] | [((421, 565), 'django.db.models.ForeignKey', 'models.ForeignKey', ([], {'blank': '(True)', 'null': '(True)', 'on_delete': 'django.db.models.deletion.CASCADE', 'related_name': '"""places_primary"""', 'to': '"""arcfire.Location"""'}), "(blank=True, null=True, on_delete=django.db.models.\n deletion.CASCADE, related_nam... |
from django.urls import path
from django.conf.urls import url
from . import views
from django.views.generic.base import RedirectView
from rest_framework.urlpatterns import format_suffix_patterns
app_name = 'userprofile'
urlpatterns = [
path('profile/<int:pk>/', views.OtherUserDetail.as_view()), #includes favorite... | [
"rest_framework.urlpatterns.format_suffix_patterns"
] | [((595, 630), 'rest_framework.urlpatterns.format_suffix_patterns', 'format_suffix_patterns', (['urlpatterns'], {}), '(urlpatterns)\n', (617, 630), False, 'from rest_framework.urlpatterns import format_suffix_patterns\n')] |
#!/usr/bin/env python
"""
analyse Elasticsearch query
"""
import json
from elasticsearch import Elasticsearch
from elasticsearch import logger as es_logger
from collections import defaultdict, Counter
import re
import os
from datetime import datetime
# Preprocess terms for TF-IDF
import numpy as np
import pandas as pd... | [
"logging.getLogger",
"matplotlib.pyplot.boxplot",
"numpy.log10",
"logging.StreamHandler",
"geopy.extra.rate_limiter.RateLimiter",
"pandas.read_csv",
"matplotlib.pyplot.ylabel",
"pandas.to_timedelta",
"pandas.Grouper",
"seaborn.set_style",
"numpy.array",
"seaborn.scatterplot",
"numpy.linalg.n... | [((1424, 1462), 'elasticsearch.Elasticsearch', 'Elasticsearch', (['"""http://localhost:9200"""'], {}), "('http://localhost:9200')\n", (1437, 1462), False, 'from elasticsearch import Elasticsearch\n'), ((1467, 1502), 'elasticsearch.logger.setLevel', 'es_logger.setLevel', (['logging.WARNING'], {}), '(logging.WARNING)\n',... |
from bbpyp.common.exception.bbpyp_value_error import BbpypValueError
from bbpyp.common.model.queue_type import QueueType
class QueueFactory:
def __init__(self, fifo_queue_factory, sequence_queue_factory):
self._fifo_queue_factory = fifo_queue_factory
self._sequence_queue_factory = sequence_queue_f... | [
"bbpyp.common.exception.bbpyp_value_error.BbpypValueError"
] | [((603, 670), 'bbpyp.common.exception.bbpyp_value_error.BbpypValueError', 'BbpypValueError', (['"""queue_type"""', 'queue_type', '"""unsupported queue type"""'], {}), "('queue_type', queue_type, 'unsupported queue type')\n", (618, 670), False, 'from bbpyp.common.exception.bbpyp_value_error import BbpypValueError\n')] |
from distutils.core import setup
setup(
name='pymetal',
version='0.5.0',
packages=[],
install_requires=["requests", "bs4", "requests_cache",
"random-user-agent", "lxml"],
url='https://www.github.com/OpenJarbas/pymetal',
license='Apache2.0',
author='jarbasAi',
autho... | [
"distutils.core.setup"
] | [((34, 349), 'distutils.core.setup', 'setup', ([], {'name': '"""pymetal"""', 'version': '"""0.5.0"""', 'packages': '[]', 'install_requires': "['requests', 'bs4', 'requests_cache', 'random-user-agent', 'lxml']", 'url': '"""https://www.github.com/OpenJarbas/pymetal"""', 'license': '"""Apache2.0"""', 'author': '"""jarbasA... |
import typing
import torch
import torch.nn as nn
import torch.nn.functional as F
from .net_sphere import *
class ResCBAMLayer(nn.Module):
"""
CBAM+Res model
"""
def __init__(self, in_planes, feature_size):
super(ResCBAMLayer, self).__init__()
self.in_planes = in_planes
self.f... | [
"torch.nn.ReLU",
"torch.nn.Softmax",
"torch.nn.AvgPool3d",
"torch.nn.MaxPool3d",
"torch.max",
"torch.sum",
"torch.nn.Linear",
"torch.nn.BatchNorm3d",
"torch.cat",
"torch.nn.Conv3d"
] | [((373, 413), 'torch.nn.AvgPool3d', 'nn.AvgPool3d', (['feature_size', 'feature_size'], {}), '(feature_size, feature_size)\n', (385, 413), True, 'import torch.nn as nn\n'), ((440, 480), 'torch.nn.MaxPool3d', 'nn.MaxPool3d', (['feature_size', 'feature_size'], {}), '(feature_size, feature_size)\n', (452, 480), True, 'impo... |
# -*- coding: utf-8 -*-
import collections
import json
import re
punct = re.compile(r'(\w+)')
PATH_FOR_TXT_FILE = "base.txt"
PATH_FOR_1_GRAM_JSON = '1-grams_count_dictionary.json'
PATH_FOR_2_GRAM_JSON = '2-grams_count_dictionary.json'
#str(input("1-gram json file name withOUT .json")) + ".json"# to take the file na... | [
"collections.deque",
"json.dumps",
"collections.defaultdict",
"re.compile"
] | [((74, 94), 're.compile', 're.compile', (['"""(\\\\w+)"""'], {}), "('(\\\\w+)')\n", (84, 94), False, 'import re\n'), ((1844, 1869), 'collections.defaultdict', 'collections.defaultdict', ([], {}), '()\n', (1867, 1869), False, 'import collections\n'), ((1907, 1926), 'collections.deque', 'collections.deque', ([], {}), '()... |
# Copyright 2021 UW-IT, University of Washington
# SPDX-License-Identifier: Apache-2.0
"""
Generates the booleans to determine card visibility,
based on dates in either the current, next, or previous term.
https://docs.google.com/document/d/14q26auOLPU34KFtkUmC_bkoo5dAwegRzgpwmZEQMhaU
"""
import logging
import traceb... | [
"logging.getLogger",
"myuw.dao.term.get_previous_quarter",
"myuw.dao.term.get_eod_current_term_last_instruction",
"datetime.datetime",
"myuw.dao.term.get_bod_class_start_quarter_after",
"myuw.dao.term.get_comparison_datetime",
"myuw.dao.term.get_eod_7d_after_class_start",
"myuw.dao.term.is_in_summer_q... | [((923, 950), 'logging.getLogger', 'logging.getLogger', (['__name__'], {}), '(__name__)\n', (940, 950), False, 'import logging\n'), ((6109, 6134), 'myuw.dao.term.get_next_quarter', 'get_next_quarter', (['request'], {}), '(request)\n', (6125, 6134), False, 'from myuw.dao.term import get_comparison_datetime, get_current_... |
import tensorflow as tf
class Encoder(tf.keras.Model):
def __init__(self, dim, **kwargs):
"""
Encoder model
:param dim: hyperparameters of the model [h_dim, z_dim]
:param dropout: Noise dropout [0,1]
:param kwargs: Keras parameters (Optional)
"""
h_dim = di... | [
"tensorflow.keras.layers.Dense"
] | [((416, 444), 'tensorflow.keras.layers.Dense', 'tf.keras.layers.Dense', (['h_dim'], {}), '(h_dim)\n', (437, 444), True, 'import tensorflow as tf\n'), ((464, 492), 'tensorflow.keras.layers.Dense', 'tf.keras.layers.Dense', (['z_dim'], {}), '(z_dim)\n', (485, 492), True, 'import tensorflow as tf\n')] |
#!/usr/bin/python
from __future__ import print_function
import GeoIP
gi = GeoIP.open("/usr/local/share/GeoIP/GeoIPDomain.dat", GeoIP.GEOIP_STANDARD)
print(gi.org_by_addr("24.24.24.24"))
| [
"GeoIP.open"
] | [((77, 151), 'GeoIP.open', 'GeoIP.open', (['"""/usr/local/share/GeoIP/GeoIPDomain.dat"""', 'GeoIP.GEOIP_STANDARD'], {}), "('/usr/local/share/GeoIP/GeoIPDomain.dat', GeoIP.GEOIP_STANDARD)\n", (87, 151), False, 'import GeoIP\n')] |
from keras.models import Sequential
from keras.layers.core import Dense, Activation
def XOR():
model = Sequential()
model.add(Dense(8, input_dim=2))
model.add(Activation('tanh'))
model.add(Dense(1))
model.add(Activation('sigmoid'))
return model
| [
"keras.layers.core.Dense",
"keras.layers.core.Activation",
"keras.models.Sequential"
] | [((108, 120), 'keras.models.Sequential', 'Sequential', ([], {}), '()\n', (118, 120), False, 'from keras.models import Sequential\n'), ((135, 156), 'keras.layers.core.Dense', 'Dense', (['(8)'], {'input_dim': '(2)'}), '(8, input_dim=2)\n', (140, 156), False, 'from keras.layers.core import Dense, Activation\n'), ((172, 19... |
"""
Utility functions for working with DataFrames
"""
import pandas
import numpy as np
TEST_DF = pandas.DataFrame([1,2,3])
class O:
"""
A square shaped block for my PyTetris game.
"""
def __init__(self):
self.type = "O"
self.color = (255, 255, 0)
mold = np.zeros([24, 10]) # fr... | [
"pandas.DataFrame",
"numpy.zeros"
] | [((99, 126), 'pandas.DataFrame', 'pandas.DataFrame', (['[1, 2, 3]'], {}), '([1, 2, 3])\n', (115, 126), False, 'import pandas\n'), ((297, 315), 'numpy.zeros', 'np.zeros', (['[24, 10]'], {}), '([24, 10])\n', (305, 315), True, 'import numpy as np\n')] |
from django.db import models
import api.json_worker as json_worker
"""
ABSTRACT MODEL
Class BibliographyTemplateModel
Handles all fields that are in our bibliography databases.
"""
class BibliographyTemplateModel(models.Model):
# FIELDS GO HERE
id = models.IntegerField(primary_key=True) #1 - ID rekordu (inte... | [
"api.json_worker.get_models",
"django.db.models.append",
"django.db.models.TextField",
"django.db.models.IntegerField",
"django.db.models.AutoField",
"django.db.models.URLField",
"django.db.models.CharField"
] | [((4466, 4509), 'api.json_worker.get_models', 'json_worker.get_models', (['"""/data/models.json"""'], {}), "('/data/models.json')\n", (4488, 4509), True, 'import api.json_worker as json_worker\n'), ((261, 298), 'django.db.models.IntegerField', 'models.IntegerField', ([], {'primary_key': '(True)'}), '(primary_key=True)\... |
import pytest
from yapic.di import Injector, InjectError, VALUE, FACTORY, SCOPED_SINGLETON, SINGLETON
def test_strategy_value():
injector = Injector()
provided = "VALUE"
injector.provide("V", provided, VALUE)
assert injector["V"] == "VALUE"
assert injector["V"] is provided
assert injector.pro... | [
"yapic.di.Injector"
] | [((146, 156), 'yapic.di.Injector', 'Injector', ([], {}), '()\n', (154, 156), False, 'from yapic.di import Injector, InjectError, VALUE, FACTORY, SCOPED_SINGLETON, SINGLETON\n'), ((672, 682), 'yapic.di.Injector', 'Injector', ([], {}), '()\n', (680, 682), False, 'from yapic.di import Injector, InjectError, VALUE, FACTORY... |
import re
import sys
from notebook.notebookapp import main
from qulab.utils import ShutdownBlocker
if __name__ == '__main__':
sys.argv[0] = re.sub(r'(-script\.pyw?|\.exe)?$', '', sys.argv[0])
with ShutdownBlocker('jupyter-notebook'):
sys.exit(main())
| [
"re.sub",
"notebook.notebookapp.main",
"qulab.utils.ShutdownBlocker"
] | [((146, 198), 're.sub', 're.sub', (['"""(-script\\\\.pyw?|\\\\.exe)?$"""', '""""""', 'sys.argv[0]'], {}), "('(-script\\\\.pyw?|\\\\.exe)?$', '', sys.argv[0])\n", (152, 198), False, 'import re\n'), ((207, 242), 'qulab.utils.ShutdownBlocker', 'ShutdownBlocker', (['"""jupyter-notebook"""'], {}), "('jupyter-notebook')\n", ... |
#!/usr/bin/env python
# -*- coding:utf-8 -*-
"""=================================================================
@Project : Algorithm_YuweiYin/LeetCode-All-Solution/Python3
@File : LC-0436-Find-Right-Interval.py
@Author : [YuweiYin](https://github.com/YuweiYin)
@Date : 2022-05-20
===============================... | [
"time.process_time",
"bisect.bisect_left"
] | [((3317, 3336), 'time.process_time', 'time.process_time', ([], {}), '()\n', (3334, 3336), False, 'import time\n'), ((3395, 3414), 'time.process_time', 'time.process_time', ([], {}), '()\n', (3412, 3414), False, 'import time\n'), ((2862, 2899), 'bisect.bisect_left', 'bisect.bisect_left', (['intervals', '[_end]'], {}), '... |
from numpy import log, pi, arange, exp
from scipy.optimize import brentq
import matplotlib.pyplot as plot
from matplotlib import rc
import equation
def diagram_sum(x, d):
return 4.*pi/log(d**2 *2.*x)
def diagram_sum_3body(x, d):
point=equation.equation(3.*x,'2D',20.,0.1,d)
point.solve()
g3=point.g3
... | [
"matplotlib.pyplot.savefig",
"matplotlib.pyplot.ylabel",
"matplotlib.pyplot.xlabel",
"matplotlib.pyplot.plot",
"numpy.log",
"equation.equation",
"matplotlib.pyplot.close",
"numpy.exp",
"matplotlib.rc",
"numpy.arange"
] | [((379, 401), 'numpy.arange', 'arange', (['(0.6)', '(5.0)', '(0.05)'], {}), '(0.6, 5.0, 0.05)\n', (385, 401), False, 'from numpy import log, pi, arange, exp\n'), ((578, 599), 'numpy.arange', 'arange', (['(0.6)', '(5.6)', '(1.0)'], {}), '(0.6, 5.6, 1.0)\n', (584, 599), False, 'from numpy import log, pi, arange, exp\n'),... |
# Simulates a network with nodes, where each node can be either a
# transmitter or receiver (but not both) at any time step. The simulation
# examines the coverage based on the signal-to-interference ratio (SINR).
# The network has a random medium access control (MAC) scheme based on a
# determinantal point process, as... | [
"numpy.sqrt",
"numpy.random.rand",
"numpy.random.exponential",
"numpy.array",
"funPalmK.funPalmK",
"numpy.sin",
"numpy.arange",
"numpy.mean",
"funProbCovTXRXDet.funProbCovTXRXDet",
"matplotlib.pyplot.plot",
"matplotlib.pyplot.close",
"numpy.exp",
"numpy.linspace",
"numpy.random.seed",
"n... | [((2079, 2095), 'matplotlib.pyplot.close', 'plt.close', (['"""all"""'], {}), "('all')\n", (2088, 2095), True, 'import matplotlib.pyplot as plt\n'), ((2155, 2172), 'numpy.random.seed', 'np.random.seed', (['(1)'], {}), '(1)\n', (2169, 2172), True, 'import numpy as np\n'), ((4619, 4635), 'numpy.linalg.eig', 'np.linalg.eig... |
from setuptools import setup
with open("qondor/include/VERSION", "r") as f:
version = f.read().strip()
setup(
name="qondor",
version=version,
license="BSD 3-Clause License",
description="Description text",
url="https://github.com/tklijnsma/qondor.git",
author="<NAME>",
author_email="<E... | [
"setuptools.setup"
] | [((109, 548), 'setuptools.setup', 'setup', ([], {'name': '"""qondor"""', 'version': 'version', 'license': '"""BSD 3-Clause License"""', 'description': '"""Description text"""', 'url': '"""https://github.com/tklijnsma/qondor.git"""', 'author': '"""<NAME>"""', 'author_email': '"""<EMAIL>"""', 'packages': "['qondor']", 'z... |
"""
任务:
1、就是普通函数
2、该函数必须通过celery的实例对象的tasks装饰其装饰
3、该任务需要让celery实例对象自动检测
4、任务(函数)需要使用任务名(函数名).delay() 进行调用
"""
from libs.yuntongxun.sms import CCP
from celery_tasks.main import app
@app.task
def send_sms_code(mobile,sms_code):
ccp = CCP()
ccp.send_template_sms(mobile, [sms_code, 5], 1)
| [
"libs.yuntongxun.sms.CCP"
] | [((257, 262), 'libs.yuntongxun.sms.CCP', 'CCP', ([], {}), '()\n', (260, 262), False, 'from libs.yuntongxun.sms import CCP\n')] |
#!/usr/bin/python
#coding=utf-8
from simplified_scrapy.simplified_main import SimplifiedMain
SimplifiedMain.startThread()
| [
"simplified_scrapy.simplified_main.SimplifiedMain.startThread"
] | [((93, 121), 'simplified_scrapy.simplified_main.SimplifiedMain.startThread', 'SimplifiedMain.startThread', ([], {}), '()\n', (119, 121), False, 'from simplified_scrapy.simplified_main import SimplifiedMain\n')] |
#!/usr/bin/env python3
# -- coding: utf-8 --
import datetime
from dateutil import parser, tz
from lxml import etree
from flask import Flask, request, abort, make_response, Response
from flask_appconfig import AppConfig
import requests
def create_app(configfile=None):
app = Flask("delayrss")
AppConfig(app, c... | [
"flask.request.args.get",
"dateutil.parser.parse",
"dateutil.tz.tzlocal",
"flask.Flask",
"requests.get",
"lxml.etree.fromstring",
"flask.make_response",
"flask_appconfig.AppConfig",
"lxml.etree.tostring"
] | [((282, 299), 'flask.Flask', 'Flask', (['"""delayrss"""'], {}), "('delayrss')\n", (287, 299), False, 'from flask import Flask, request, abort, make_response, Response\n'), ((304, 330), 'flask_appconfig.AppConfig', 'AppConfig', (['app', 'configfile'], {}), '(app, configfile)\n', (313, 330), False, 'from flask_appconfig ... |
import unittest
from django.core.exceptions import ValidationError
from petstagram.common.validators import MaxFileSizeInMbValidator
class FakeFile:
size = 5
class FakeImage:
file = FakeFile()
class MaxFileSizeInMbValidatorTests(unittest.TestCase):
def test_when_file_is_bigger__expect_to_raise(self):... | [
"petstagram.common.validators.MaxFileSizeInMbValidator"
] | [((341, 372), 'petstagram.common.validators.MaxFileSizeInMbValidator', 'MaxFileSizeInMbValidator', (['(1e-06)'], {}), '(1e-06)\n', (365, 372), False, 'from petstagram.common.validators import MaxFileSizeInMbValidator\n'), ((629, 656), 'petstagram.common.validators.MaxFileSizeInMbValidator', 'MaxFileSizeInMbValidator', ... |
import os
import csv
import sys
from sklearn.model_selection import train_test_split
sys.path.append("..")
from training_config import RANDOM_SEED, ALLOWED_CLASSES, DATA_DIR
def stratified_split(X, y, test_size=0.2, validate_size=0.2, random_state=42):
X_train, X_test, y_train, y_test = train_test_split(X, y, str... | [
"os.listdir",
"sklearn.model_selection.train_test_split",
"csv.writer",
"os.path.join",
"sys.path.append"
] | [((85, 106), 'sys.path.append', 'sys.path.append', (['""".."""'], {}), "('..')\n", (100, 106), False, 'import sys\n'), ((294, 381), 'sklearn.model_selection.train_test_split', 'train_test_split', (['X', 'y'], {'stratify': 'y', 'test_size': 'test_size', 'random_state': 'random_state'}), '(X, y, stratify=y, test_size=tes... |
import os
def delete_log():
if os.path.exists('pyfibre.log'):
os.remove('pyfibre.log')
| [
"os.path.exists",
"os.remove"
] | [((37, 66), 'os.path.exists', 'os.path.exists', (['"""pyfibre.log"""'], {}), "('pyfibre.log')\n", (51, 66), False, 'import os\n'), ((76, 100), 'os.remove', 'os.remove', (['"""pyfibre.log"""'], {}), "('pyfibre.log')\n", (85, 100), False, 'import os\n')] |
import requests
def get_programming_joke() -> str:
joke = "// This line doesn't actually do anything, but the code stops working when I delete it."
response = requests.get(
"https://sv443.net/jokeapi/v2/joke/Programming?format=txt&type=single")
if response.status_code == 200:
joke = respon... | [
"requests.get"
] | [((169, 258), 'requests.get', 'requests.get', (['"""https://sv443.net/jokeapi/v2/joke/Programming?format=txt&type=single"""'], {}), "(\n 'https://sv443.net/jokeapi/v2/joke/Programming?format=txt&type=single')\n", (181, 258), False, 'import requests\n')] |
from copy import deepcopy
import pytest
from catenets.datasets import load
from catenets.experiment_utils.tester import evaluate_treatments_model
from catenets.models.jax import FLEXTE_NAME, OFFSET_NAME, FlexTENet, OffsetNet
LAYERS_OUT = 2
LAYERS_R = 3
PENALTY_L2 = 0.01 / 100
PENALTY_ORTHOGONAL_IHDP = 0
MODEL_PARAM... | [
"catenets.models.jax.OffsetNet",
"pytest.mark.parametrize",
"catenets.models.jax.FlexTENet",
"catenets.experiment_utils.tester.evaluate_treatments_model",
"pytest.raises",
"copy.deepcopy",
"catenets.datasets.load"
] | [((1055, 1140), 'pytest.mark.parametrize', 'pytest.mark.parametrize', (['"""dataset, pehe_threshold"""', "[('twins', 0.4), ('ihdp', 3)]"], {}), "('dataset, pehe_threshold', [('twins', 0.4), ('ihdp',\n 3)])\n", (1078, 1140), False, 'import pytest\n'), ((1138, 1183), 'pytest.mark.parametrize', 'pytest.mark.parametrize... |
# -*- coding: UTF-8 -*-
"""TK版文件下载
技术要点:1 自定义事件;2 UI线程和子线程数据通信
"""
from Tkinter import *
import sys,os
import urllib
import threading
import Queue
import tkMessageBox
class Event(object):
REFLASH = '<<Reflash>>'
class MWindow(Frame):
def __init__(self):
Frame.__init__(self)
self.master.title... | [
"urllib.urlretrieve",
"threading.Thread",
"Queue.Queue",
"tkMessageBox.showerror"
] | [((1747, 1760), 'Queue.Queue', 'Queue.Queue', ([], {}), '()\n', (1758, 1760), False, 'import Queue\n'), ((1802, 1846), 'urllib.urlretrieve', 'urllib.urlretrieve', (['url', 'fileName', 'file_name'], {}), '(url, fileName, file_name)\n', (1820, 1846), False, 'import urllib\n'), ((1628, 1687), 'threading.Thread', 'threadin... |
from flask import Flask, render_template, redirect
import requests
import json
app: Flask = Flask( __name__ )
@app.route( "/" )
def index():
cotacao = requests.get("https://economia.awesomeapi.com.br/last/USD-BRL,EUR-BRL,BTC-BRL")
cotacao = cotacao.json()
cotacao_bit = cotacao['BTCBRL']['bid']
cotaca... | [
"flask.render_template",
"requests.get",
"flask.Flask"
] | [((93, 108), 'flask.Flask', 'Flask', (['__name__'], {}), '(__name__)\n', (98, 108), False, 'from flask import Flask, render_template, redirect\n'), ((158, 237), 'requests.get', 'requests.get', (['"""https://economia.awesomeapi.com.br/last/USD-BRL,EUR-BRL,BTC-BRL"""'], {}), "('https://economia.awesomeapi.com.br/last/USD... |
import cv2
class VideoStream:
def __init__(self, path='/dev/video0', size=(640, 480)):
self.path = path
self.size = size
self.cap = self.capture_stream()
def __del__(self):
cap = getattr(self, 'cap', None)
if cap is not None:
cap.release()
def captur... | [
"cv2.rectangle",
"cv2.imwrite",
"cv2.putText",
"cv2.imshow",
"cv2.destroyAllWindows",
"cv2.VideoCapture",
"cv2.cvtColor",
"cv2.VideoWriter_fourcc",
"cv2.resize",
"cv2.waitKey",
"cv2.namedWindow"
] | [((350, 377), 'cv2.VideoCapture', 'cv2.VideoCapture', (['self.path'], {}), '(self.path)\n', (366, 377), False, 'import cv2\n'), ((831, 869), 'cv2.cvtColor', 'cv2.cvtColor', (['frame', 'cv2.COLOR_BGR2RGB'], {}), '(frame, cv2.COLOR_BGR2RGB)\n', (843, 869), False, 'import cv2\n'), ((983, 1051), 'cv2.rectangle', 'cv2.recta... |
from django.contrib import admin
from ..abstract.admin import AbstractObservation, ObservableObjectAdmin
from .models import (
Asteroid, AsteroidObservation,
Comet, CometObservation,
Planet, PlanetObservation,
MoonObservation,
MeteorShower,
)
class AsteroidObservationAdmin(AbstractObservation):
... | [
"django.contrib.admin.site.register"
] | [((1916, 1968), 'django.contrib.admin.site.register', 'admin.site.register', (['MeteorShower', 'MeteorShowerAdmin'], {}), '(MeteorShower, MeteorShowerAdmin)\n', (1935, 1968), False, 'from django.contrib import admin\n'), ((1969, 2009), 'django.contrib.admin.site.register', 'admin.site.register', (['Planet', 'PlanetAdmi... |
# Copyright (C) 2013-2020, <NAME>
# and ftputil contributors (see `doc/contributors.txt`)
# See the file LICENSE for licensing terms.
"""
tool.py - helper code
"""
import os
__all__ = ["same_string_type_as", "as_str", "as_str_path"]
# Encoding to convert between byte string and unicode string. This is
# a "lossle... | [
"os.fspath"
] | [((2170, 2185), 'os.fspath', 'os.fspath', (['path'], {}), '(path)\n', (2179, 2185), False, 'import os\n')] |
# Generated by Django 3.2.7 on 2022-01-06 03:42
from django.db import migrations
class Migration(migrations.Migration):
dependencies = [
('data', '0070_taibifcode'),
]
operations = [
migrations.RenameField(
model_name='taibifcode',
old_name='code_id',
... | [
"django.db.migrations.RenameField"
] | [((216, 305), 'django.db.migrations.RenameField', 'migrations.RenameField', ([], {'model_name': '"""taibifcode"""', 'old_name': '"""code_id"""', 'new_name': '"""objid"""'}), "(model_name='taibifcode', old_name='code_id',\n new_name='objid')\n", (238, 305), False, 'from django.db import migrations\n')] |
# Copyright (C) 2022 National Center for Atmospheric Research and National Oceanic and Atmospheric Administration
# SPDX-License-Identifier: Apache-2.0
#
import numpy as np
from pandas.api.types import is_float_dtype
def write_ncf(dset, output_name, title=''):
"""Function to write netcdf4 files with some compress... | [
"pandas.to_datetime",
"pandas.api.types.is_float_dtype"
] | [((742, 765), 'pandas.api.types.is_float_dtype', 'is_float_dtype', (['dset[i]'], {}), '(dset[i])\n', (756, 765), False, 'from pandas.api.types import is_float_dtype\n'), ((1099, 1122), 'pandas.to_datetime', 'pd.to_datetime', (['"""today"""'], {}), "('today')\n", (1113, 1122), True, 'import pandas as pd\n')] |
# -*- coding: utf-8 -*-
from __future__ import unicode_literals
from django.db import models, migrations
class Migration(migrations.Migration):
dependencies = [
('shorter', '0001_initial'),
]
operations = [
migrations.AlterField(
model_name='urlslug',
name='is_us... | [
"django.db.models.BooleanField"
] | [((343, 458), 'django.db.models.BooleanField', 'models.BooleanField', ([], {'default': '(False)', 'help_text': '"""checked if was used as slug"""', 'db_index': '(True)', 'verbose_name': '"""Used"""'}), "(default=False, help_text='checked if was used as slug',\n db_index=True, verbose_name='Used')\n", (362, 458), Fal... |
""" Tests for functions in imaging module
Run at the project directory with:
nosetests code/utils/tests/test_imaging.py
"""
# Loading modules.
from __future__ import absolute_import, division, print_function
import numpy as np
import nibabel as nib
import os
import sys
from numpy.testing import assert_almost_equal... | [
"Image_Visualizing.present_3d",
"numpy.ceil",
"Image_Visualizing.make_mask",
"numpy.sqrt",
"numpy.ones",
"os.path.dirname",
"numpy.zeros",
"Image_Visualizing.present_3d_options",
"numpy.arange"
] | [((717, 734), 'numpy.arange', 'np.arange', (['(100000)'], {}), '(100000)\n', (726, 734), True, 'import numpy as np\n'), ((787, 803), 'Image_Visualizing.present_3d', 'present_3d', (['data'], {}), '(data)\n', (797, 803), False, 'from Image_Visualizing import present_3d, make_mask, present_3d_options\n'), ((886, 903), 'nu... |
import re
from datetime import datetime
from typing import List, Optional, Match, AnyStr, Dict
import logging
import pandas as pd
from PyPDF2 import PdfFileReader
from nltk.tokenize import word_tokenize
from pandas import DataFrame
from avicena.models.MergeAddress import MergeAddress
from avicena.models.RevenueRate im... | [
"logging.getLogger",
"pandas.Series",
"re.escape",
"avicena.util.ParserUtil.standardize_trip_df",
"datetime.datetime.strptime",
"nltk.tokenize.word_tokenize",
"pandas.DataFrame",
"re.sub",
"PyPDF2.PdfFileReader",
"re.search"
] | [((400, 427), 'logging.getLogger', 'logging.getLogger', (['__name__'], {}), '(__name__)\n', (417, 427), False, 'import logging\n'), ((2015, 2034), 'nltk.tokenize.word_tokenize', 'word_tokenize', (['text'], {}), '(text)\n', (2028, 2034), False, 'from nltk.tokenize import word_tokenize\n'), ((2863, 2879), 'pandas.Series'... |
# Copyright (c) 2014, <NAME>. Please see the AUTHORS file for details.
# All rights reserved. Use of this source code is governed by a BSD-style
# license that can be found in the LICENSE file.)
"""Actions performed using the analyzer's responses.
"""
import sublime
import os
from Dart.lib.analyzer.api.types import... | [
"sublime.active_window",
"Dart.sublime_plugin_lib.PluginLogger",
"Dart.sublime_plugin_lib.panels.OutputPanel",
"os.path.realpath",
"sublime.Region",
"Dart.lib.analyzer.api.types.Location"
] | [((508, 530), 'Dart.sublime_plugin_lib.PluginLogger', 'PluginLogger', (['__name__'], {}), '(__name__)\n', (520, 530), False, 'from Dart.sublime_plugin_lib import PluginLogger\n'), ((2980, 3008), 'Dart.sublime_plugin_lib.panels.OutputPanel', 'OutputPanel', (['"""dart.analyzer"""'], {}), "('dart.analyzer')\n", (2991, 300... |
from djangocms_versioning.exceptions import ConditionFailed
from djangocms_versioning.models import Version
from djangocms_versioning_filer.models import FileGrouper
from djangocms_versioning_filer.monkeypatch.models import (
is_file_content_valid_for_discard,
is_file_content_valid_for_revert,
)
from .base im... | [
"djangocms_versioning.models.Version.objects.get_for_content",
"djangocms_versioning_filer.monkeypatch.models.is_file_content_valid_for_revert",
"djangocms_versioning_filer.monkeypatch.models.is_file_content_valid_for_discard",
"djangocms_versioning_filer.models.FileGrouper.objects.create"
] | [((877, 905), 'djangocms_versioning_filer.models.FileGrouper.objects.create', 'FileGrouper.objects.create', ([], {}), '()\n', (903, 905), False, 'from djangocms_versioning_filer.models import FileGrouper\n'), ((1548, 1576), 'djangocms_versioning_filer.models.FileGrouper.objects.create', 'FileGrouper.objects.create', ([... |
from django.http import HttpRequest, HttpResponse
from django.utils.deprecation import MiddlewareMixin
from typing import Optional
import logging
class QuickpayMiddleware(MiddlewareMixin):
def process_view(self, request: HttpRequest, view_func, view_args, view_kwargs) -> Optional[HttpResponse]:
from cartr... | [
"logging.debug"
] | [((863, 926), 'logging.debug', 'logging.debug', (['"""Quickpay.process_view: Making QP checkout view"""'], {}), "('Quickpay.process_view: Making QP checkout view')\n", (876, 926), False, 'import logging\n')] |
from __future__ import absolute_import
from __future__ import division
from __future__ import print_function
from __future__ import unicode_literals
import argparse
import h5py
import json
import os
import scipy.misc
import sys
import re
import fnmatch
import datetime
from PIL import Image
import numpy as np
'''
sr... | [
"sys.path.insert",
"argparse.ArgumentParser",
"json.dumps",
"os.path.join",
"utils.face_utils.parse_wider_gt",
"os.path.dirname",
"numpy.array"
] | [((512, 537), 'os.path.dirname', 'os.path.dirname', (['__file__'], {}), '(__file__)\n', (527, 537), False, 'import os\n'), ((584, 618), 'os.path.join', 'os.path.join', (['this_dir', '""".."""', '""".."""'], {}), "(this_dir, '..', '..')\n", (596, 618), False, 'import os\n'), ((738, 792), 'argparse.ArgumentParser', 'argp... |
"""
=================================================
Deterministic Tracking with EuDX on Tensor Fields
=================================================
In this example we do deterministic fiber tracking on Tensor fields with EuDX
[Garyfallidis12]_.
This example requires to import example `reconst_dti.py` to run. E... | [
"dipy.reconst.dti.quantize_evecs",
"os.path.exists",
"numpy.eye",
"dipy.tracking.streamline.Streamlines",
"nibabel.load",
"dipy.data.get_sphere",
"numpy.isnan",
"dipy.viz.colormap.line_colors",
"sys.exit",
"dipy.viz.window.show",
"dipy.viz.window.record",
"dipy.viz.window.Renderer"
] | [((782, 810), 'nibabel.load', 'nib.load', (['"""tensor_fa.nii.gz"""'], {}), "('tensor_fa.nii.gz')\n", (790, 810), True, 'import nibabel as nib\n'), ((846, 877), 'nibabel.load', 'nib.load', (['"""tensor_evecs.nii.gz"""'], {}), "('tensor_evecs.nii.gz')\n", (854, 877), True, 'import nibabel as nib\n'), ((1506, 1532), 'dip... |
#!/usr/bin/env python3
import sqlite3
import argparse
###############################################################################
#
# Super simple (and probably not very efficient) way to query sqlite file and
# produce a python list of dictionaries with the result of that query
#
################################... | [
"sqlite3.connect",
"argparse.ArgumentParser"
] | [((419, 447), 'sqlite3.connect', 'sqlite3.connect', (['sqlite_file'], {}), '(sqlite_file)\n', (434, 447), False, 'import sqlite3\n'), ((17522, 17619), 'argparse.ArgumentParser', 'argparse.ArgumentParser', ([], {'description': '"""Process the output of nvprof --profile-api-trace all."""'}), "(description=\n 'Process ... |
import threading
import time
import mod_log
import mod_measure_list
import mod_sense_hat
# Threads management class
class ThreadManager(object):
def __init__(self, log_mgr, channel, delay, source, measure_list):
self.log_mgr = log_mgr # Logger module
self.channel = channel ... | [
"threading.Thread",
"time.time",
"time.sleep"
] | [((850, 898), 'threading.Thread', 'threading.Thread', ([], {'target': 'self.acquisition_thread'}), '(target=self.acquisition_thread)\n', (866, 898), False, 'import threading\n'), ((1194, 1205), 'time.time', 'time.time', ([], {}), '()\n', (1203, 1205), False, 'import time\n'), ((1342, 1364), 'time.sleep', 'time.sleep', ... |
#!/usr/local/bin/python
# -*- coding: utf-8 -*-
from DAO import ServidoresDAO
from Tkinter import *
import ConfigParser
import os
class Application:
def __init__(self, master=None):
self.fonte = ("Verdana", "8")
self.container1 = Frame(master)
self.container1["pady"] = 10
self.container1.p... | [
"os.path.dirname",
"DAO.ServidoresDAO",
"ConfigParser.ConfigParser"
] | [((2590, 2605), 'DAO.ServidoresDAO', 'ServidoresDAO', ([], {}), '()\n', (2603, 2605), False, 'from DAO import ServidoresDAO\n'), ((3271, 3298), 'ConfigParser.ConfigParser', 'ConfigParser.ConfigParser', ([], {}), '()\n', (3296, 3298), False, 'import ConfigParser\n'), ((3351, 3376), 'os.path.dirname', 'os.path.dirname', ... |
#!/usr/bin/env python2
# -*- coding: utf-8 -*-
"""
This experiment was created using PsychoPy2 Experiment Builder (v1.84.2),
on February 14, 2019, at 13:04
If you publish work using this script please cite the PsychoPy publications:
<NAME> (2007) PsychoPy - Psychophysics software in Python.
Journal of N... | [
"psychopy.core.quit",
"psychopy.monitors.Monitor",
"psychopy.core.wait",
"psychopy.data.TrialHandler",
"psychopy.logging.console.setLevel",
"psychopy.gui.DlgFromDict",
"sys.getfilesystemencoding",
"psychopy.data.importConditions",
"psychopy.logging.LogFile",
"psychopy.event.waitKeys",
"psychopy.... | [((1516, 1534), 'os.chdir', 'os.chdir', (['_thisDir'], {}), '(_thisDir)\n', (1524, 1534), False, 'import os\n'), ((1900, 1950), 'psychopy.gui.DlgFromDict', 'gui.DlgFromDict', ([], {'dictionary': 'expInfo', 'title': 'expName'}), '(dictionary=expInfo, title=expName)\n', (1915, 1950), False, 'from psychopy import locale_s... |
from flask import Flask, render_template, request, redirect, url_for
from flaskext.mysql import MySQL
app = Flask(__name__)
mysql = MySQL()
app.config['MYSQL_DATABASE_USER'] = 'root'
app.config['MYSQL_DATABASE_PASSWORD'] = '<PASSWORD>'
app.config['MYSQL_DATABASE_HOST'] = 'localhost'
app.config['MYSQL_DATABASE_DB'] = ... | [
"flask.render_template",
"flask.request.args.get",
"flask.Flask",
"flask.url_for",
"flaskext.mysql.MySQL"
] | [((109, 124), 'flask.Flask', 'Flask', (['__name__'], {}), '(__name__)\n', (114, 124), False, 'from flask import Flask, render_template, request, redirect, url_for\n'), ((133, 140), 'flaskext.mysql.MySQL', 'MySQL', ([], {}), '()\n', (138, 140), False, 'from flaskext.mysql import MySQL\n'), ((1653, 1685), 'flask.render_t... |
from setuptools import setup, find_namespace_packages
from os import path
this_directory = path.abspath(path.dirname(__file__))
with open(path.join(this_directory, "README.md"), encoding="utf-8") as f:
long_description = f.read()
requirements = [
"numpy",
"pandas",
"vedo>=2020.3.3",
"k3d==2.7.4",
... | [
"setuptools.find_namespace_packages",
"os.path.dirname",
"os.path.join"
] | [((105, 127), 'os.path.dirname', 'path.dirname', (['__file__'], {}), '(__file__)\n', (117, 127), False, 'from os import path\n'), ((139, 177), 'os.path.join', 'path.join', (['this_directory', '"""README.md"""'], {}), "(this_directory, 'README.md')\n", (148, 177), False, 'from os import path\n'), ((1153, 1243), 'setupto... |
import pandas as pd
import numpy as np
import seaborn as sns
import os
import matplotlib.pyplot as plt
df = pd.read_csv( os.path.join( "fairness-2021", "simple-rank-res.csv" ) )
df["pp"] = [ "fs" if x == 'fairsmote' else x for x in df["pp"] ]
df["pt"] = [ "rs" if x == 'random' else x for x in df["pt"] ]
df["tech"] = [... | [
"seaborn.cubehelix_palette",
"numpy.logical_and",
"matplotlib.pyplot.clf",
"os.path.join",
"matplotlib.pyplot.close",
"matplotlib.pyplot.tight_layout",
"pandas.DataFrame",
"matplotlib.pyplot.ylim",
"matplotlib.pyplot.subplots"
] | [((122, 174), 'os.path.join', 'os.path.join', (['"""fairness-2021"""', '"""simple-rank-res.csv"""'], {}), "('fairness-2021', 'simple-rank-res.csv')\n", (134, 174), False, 'import os\n'), ((1416, 1508), 'pandas.DataFrame', 'pd.DataFrame', (["[sub_df[sub_df['tech'] == x].iloc[0][['tech', 'rank']] for x in tech_list]"], {... |
# License: MIT
'''
:author: <NAME> (<EMAIL>)
:organization: ETS
'''
import ctypes as c
import logging
import os
class Tagger(object):
"""The ZPar English POS Tagger"""
def __init__(self, modelpath, libptr, zpar_session_obj):
super(Tagger, self).__init__()
# save the zpar session object
... | [
"logging.getLogger",
"os.path.exists"
] | [((414, 441), 'logging.getLogger', 'logging.getLogger', (['__name__'], {}), '(__name__)\n', (431, 441), False, 'import logging\n'), ((1805, 1830), 'os.path.exists', 'os.path.exists', (['inputfile'], {}), '(inputfile)\n', (1819, 1830), False, 'import os\n')] |
# ------------------------------------------------------------------------------
# Global imports
# ------------------------------------------------------------------------------
# *** Type hints *** #
from typing import Any
from typing import Optional
from typing import Union
# *** Enumerations *** #
import enum
# *... | [
"torch.set_printoptions",
"torch.max",
"torch.from_numpy",
"torch.distributions.one_hot_categorical.OneHotCategorical",
"torch.min",
"cv2.destroyAllWindows",
"cv2.cvtColor",
"cv2.resize",
"cv2.waitKey",
"torch.zeros",
"cv2.imread"
] | [((579, 613), 'torch.set_printoptions', 'pt.set_printoptions', ([], {'linewidth': '(200)'}), '(linewidth=200)\n', (598, 613), True, 'import torch as pt\n'), ((2896, 2918), 'cv2.destroyAllWindows', 'cv.destroyAllWindows', ([], {}), '()\n', (2916, 2918), True, 'import cv2 as cv\n'), ((3294, 3362), 'torch.zeros', 'pt.zero... |
# Copyright 2020-2021 eBay 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
# https://www.apache.org/licenses/LICENSE-2.0
# Unless required by applicable law or agreed to in writing, so... | [
"logging.basicConfig",
"logging.getLogger",
"xfraud.glib.graph_loader.GraphData",
"xfraud.glib.utils.timeit",
"collections.defaultdict",
"xfraud.glib.graph_loader.NaiveHetGraph"
] | [((627, 666), 'logging.basicConfig', 'logging.basicConfig', ([], {'level': 'logging.INFO'}), '(level=logging.INFO)\n', (646, 666), False, 'import logging\n'), ((1331, 1375), 'logging.getLogger', 'logging.getLogger', (['"""factory-naive-het-graph"""'], {}), "('factory-naive-het-graph')\n", (1348, 1375), False, 'import l... |
"""This module defines the Scene related interfaces.
Attributes:
SCENE_RE: Python regular expression that matches SmolDM's adventure scene
SCENE_TITLE_RE: Python regular expression that matches SmolDM's adventure
scene title
SCENE_OPTION_RE: Python regular expression that matches SmolDM... | [
"loguru.logger.debug",
"re.match",
"re.finditer",
"loguru.logger.info"
] | [((2011, 2067), 'loguru.logger.info', 'logger.info', (['"""Attemping to read adventure file content."""'], {}), "('Attemping to read adventure file content.')\n", (2022, 2067), False, 'from loguru import logger\n'), ((2138, 2171), 'loguru.logger.info', 'logger.info', (['"""Loading scenes...."""'], {}), "('Loading scene... |
import random
from task_widgets.task_base.intro_hint import IntroHint
from utils import import_kv
from .calculation import ModeOperandsCalculation
import_kv(__file__)
class IntroHintNumbersCalculation(IntroHint):
pass
class NumbersCalculation(ModeOperandsCalculation):
FROM = 101
TO = 899
TASK_KEY ... | [
"utils.import_kv",
"random.randint"
] | [((149, 168), 'utils.import_kv', 'import_kv', (['__file__'], {}), '(__file__)\n', (158, 168), False, 'from utils import import_kv\n'), ((465, 505), 'random.randint', 'random.randint', (['self.FROM', '(self.TO - 100)'], {}), '(self.FROM, self.TO - 100)\n', (479, 505), False, 'import random\n'), ((543, 584), 'random.rand... |
import warnings
import numpy as np
import pandas as pd
import sklearn
from sklearn import metrics
class MetricCatalog:
catalog_dict = {
'accuracy': {
'func': metrics.accuracy_score,
'params': {},
'require_score': False,
'binary': True,
'multi': ... | [
"pandas.Series",
"numpy.mean",
"numpy.abs",
"pandas.DataFrame",
"sklearn.metrics.median_absolute_error",
"numpy.log",
"numpy.zeros_like",
"sklearn.metrics.mean_squared_error",
"sklearn.metrics.log_loss",
"warnings.warn",
"sklearn.metrics.mean_absolute_error",
"pandas.concat",
"numpy.random.s... | [((11681, 11728), 'pandas.Series', 'pd.Series', (['eval_list'], {'index': 'sorted_metric_names'}), '(eval_list, index=sorted_metric_names)\n', (11690, 11728), True, 'import pandas as pd\n'), ((19146, 19179), 'pandas.DataFrame', 'pd.DataFrame', (['col_importance_list'], {}), '(col_importance_list)\n', (19158, 19179), Tr... |