code stringlengths 22 1.05M | apis listlengths 1 3.31k | extract_api stringlengths 75 3.25M |
|---|---|---|
# -*- coding: utf-8 -*-
import re
import semantic_version
import pytest
import validators
from datetime import datetime
import quantopian_tools
def test_valid_pkg_name():
assert quantopian_tools
assert re.match(r'[a-z][a-z_.]+', quantopian_tools.__pkg_name__)
def test_valid_version():
assert semantic_... | [
"semantic_version.Version.coerce",
"datetime.datetime.strptime",
"re.match",
"validators.email",
"pytest.fail",
"validators.url"
] | [((214, 270), 're.match', 're.match', (['"""[a-z][a-z_.]+"""', 'quantopian_tools.__pkg_name__'], {}), "('[a-z][a-z_.]+', quantopian_tools.__pkg_name__)\n", (222, 270), False, 'import re\n'), ((778, 826), 'validators.url', 'validators.url', (['quantopian_tools.__project_url__'], {}), '(quantopian_tools.__project_url__)\... |
from garterline import GarterLine
def example1():
line = GarterLine()
line.color("red")
line.text("Hello")
line.color("blue")
line.text("World")
return line
def example2():
percentReady90 = ["In", "other", "words", "it's", "almost", "completed"]
line = GarterLine()
line.color("blue... | [
"garterline.GarterLine"
] | [((62, 74), 'garterline.GarterLine', 'GarterLine', ([], {}), '()\n', (72, 74), False, 'from garterline import GarterLine\n'), ((287, 299), 'garterline.GarterLine', 'GarterLine', ([], {}), '()\n', (297, 299), False, 'from garterline import GarterLine\n'), ((418, 430), 'garterline.GarterLine', 'GarterLine', ([], {}), '()... |
import re
from arqtty_scrapper.page_types import Page_types
class Classifier:
def __init__(self, page_str):
self.page = page_str
def _is_404(self):
marker1 = 'Ой, ой, страничка потерялась'
marker2 = 'Спокойно! Логи записаны. Все будет исправлено.'
return re.search(marker1, se... | [
"re.search"
] | [((468, 497), 're.search', 're.search', (['marker1', 'self.page'], {}), '(marker1, self.page)\n', (477, 497), False, 'import re\n'), ((575, 604), 're.search', 're.search', (['marker1', 'self.page'], {}), '(marker1, self.page)\n', (584, 604), False, 'import re\n'), ((299, 328), 're.search', 're.search', (['marker1', 'se... |
#!/usr/bin/env python
# Copyright (c) 2020 - for information on the respective copyright owner
# see the NOTICE file and/or the repository
# <https://github.com/boschresearch/amira-blender-rendering>.
#
# Licensed under the Apache License, Version 2.0 (the "License");
# you may not use this file except in compliance w... | [
"os.path.dirname",
"functools.partial"
] | [((2503, 2547), 'functools.partial', 'partial', (['_register'], {'name': 'name', 'obj_type': 'type'}), '(_register, name=name, obj_type=type)\n', (2510, 2547), False, 'from functools import partial\n'), ((3036, 3061), 'os.path.dirname', 'os.path.dirname', (['__file__'], {}), '(__file__)\n', (3051, 3061), False, 'import... |
#
# sn_agent/base.py - implementation of abstract class defining API for Network
# communication with block-chain implementations through connections with
# smart contracts and block-chain messaging systems.
#
# Copyright (c) 2017 SingularityNET
#
# Distributed under the MIT software license, see LICENSE file.
#
from ... | [
"logging.getLogger"
] | [((561, 588), 'logging.getLogger', 'logging.getLogger', (['__name__'], {}), '(__name__)\n', (578, 588), False, 'import logging\n')] |
from noval import GetApp,_
import noval.iface as iface
import noval.plugin as plugin
import tkinter as tk
from tkinter import ttk,messagebox
import noval.preference as preference
from noval.util import utils
import noval.ui_utils as ui_utils
import noval.consts as consts
MAX_WINDOW_MENU_NUM_ITEMS = 30
##c... | [
"tkinter.ttk.Frame",
"noval.plugin.Implements",
"noval.GetApp",
"noval._",
"noval.util.utils.profile_set",
"noval.preference.PreferenceManager",
"noval.util.utils.profile_get_int",
"noval.ui_utils.CommonOptionPanel.__init__",
"noval.util.utils.profile_get"
] | [((10114, 10152), 'noval.plugin.Implements', 'plugin.Implements', (['iface.CommonPluginI'], {}), '(iface.CommonPluginI)\n', (10131, 10152), True, 'import noval.plugin as plugin\n'), ((6137, 6186), 'noval.ui_utils.CommonOptionPanel.__init__', 'ui_utils.CommonOptionPanel.__init__', (['self', 'parent'], {}), '(self, paren... |
"""
This module is the main API used to create track collections
"""
# Standard library imports
import copy
import random
import inspect
import logging
import itertools
from typing import Any
from typing import List
from typing import Union
from typing import Tuple
from typing import Callable
from dataclasses impo... | [
"logging.getLogger",
"itertools.islice",
"random.sample",
"copy.deepcopy",
"random.shuffle",
"dataclasses.asdict",
"itertools.tee",
"networkx.Graph",
"networkx.shortest_path_length",
"numpy.argsort",
"numpy.array",
"inspect.getsource",
"spotify_flows.database.SpotifyDatabase",
"pandas.Data... | [((1263, 1282), 'logging.getLogger', 'logging.getLogger', ([], {}), '()\n', (1280, 1282), False, 'import logging\n'), ((1788, 1815), 'dataclasses.field', 'field', ([], {'default_factory': 'list'}), '(default_factory=list)\n', (1793, 1815), False, 'from dataclasses import dataclass, field, asdict\n'), ((20879, 20906), '... |
#!/usr/bin/env python
import csv
import string
import sys
f = open('public_enrollment.txt')
pub = csv.reader(f, csv.excel_tab)
sys.stdout = open('popcounts.csv', 'wt')
h = pub.__next__()
last = None
grades = 0
for r in pub:
r = [n.replace(',','') for n in r]
school = '{:04d}-{:02d}-{:03d}'.format(int(r[3])... | [
"csv.reader"
] | [((100, 128), 'csv.reader', 'csv.reader', (['f', 'csv.excel_tab'], {}), '(f, csv.excel_tab)\n', (110, 128), False, 'import csv\n'), ((766, 794), 'csv.reader', 'csv.reader', (['f', 'csv.excel_tab'], {}), '(f, csv.excel_tab)\n', (776, 794), False, 'import csv\n')] |
from libs.graph.DLinkedList import Queue, DoubledLinkedList as List
from libs.graph.PriorityQueue import PriorityQueueBinary as PriorityQueue
from libs.graph.Tree import *
#it is better to use a DoubledLinkedList to operate with a great efficiency on
#the lists those will be used in the graph representation
class Node... | [
"libs.graph.DLinkedList.DoubledLinkedList",
"libs.graph.DLinkedList.Queue",
"libs.graph.PriorityQueue.PriorityQueueBinary"
] | [((3897, 3903), 'libs.graph.DLinkedList.DoubledLinkedList', 'List', ([], {}), '()\n', (3901, 3903), True, 'from libs.graph.DLinkedList import Queue, DoubledLinkedList as List\n'), ((6476, 6483), 'libs.graph.DLinkedList.Queue', 'Queue', ([], {}), '()\n', (6481, 6483), False, 'from libs.graph.DLinkedList import Queue, Do... |
from django.utils.translation import ugettext_lazy as _
from mayan.apps.documents.search import document_page_search, document_search
document_page_search.add_model_field(
field='document_version__document__comments__comment',
label=_('Comments')
)
document_search.add_model_field(
field='comments__comment... | [
"django.utils.translation.ugettext_lazy"
] | [((243, 256), 'django.utils.translation.ugettext_lazy', '_', (['"""Comments"""'], {}), "('Comments')\n", (244, 256), True, 'from django.utils.translation import ugettext_lazy as _\n'), ((333, 346), 'django.utils.translation.ugettext_lazy', '_', (['"""Comments"""'], {}), "('Comments')\n", (334, 346), True, 'from django.... |
import unittest
import csv_functions
class TestCsvFunctions(unittest.TestCase):
def test_open_test_file(self):
expected = [['X', 'Y'], ['0', '0'], ['1', '10'], ['2', '15'], ['3', '50'], ['4', '80'], ['5', '100'],
['6', '80'], ['7', '45'], ['8', '35'], ['9', '15'], ['10', '5']]
... | [
"csv_functions.csv_open"
] | [((332, 368), 'csv_functions.csv_open', 'csv_functions.csv_open', (['"""test_1.csv"""'], {}), "('test_1.csv')\n", (354, 368), False, 'import csv_functions\n'), ((632, 668), 'csv_functions.csv_open', 'csv_functions.csv_open', (['"""test_2.csv"""'], {}), "('test_2.csv')\n", (654, 668), False, 'import csv_functions\n')] |
# Copyright (c) 2020. Huawei Technologies Co., Ltd.
# SPDX-License-Identifier: Apache-2.0
#
# Copyright (c) 2019 MendelXu
# SPDX-License-Identifier: Apache-2.0
#
# Copyright (C) 2021 Intel Corporation
# SPDX-License-Identifier: Apache-2.0
#
import math
import torch
import torch.nn as nn
import torch.nn.functional as ... | [
"torch.nn.Sigmoid",
"math.ceil",
"mmseg.utils.get_root_logger",
"mmcv.cnn.ConvModule",
"mmcv.cnn.normal_init",
"torch.matmul",
"mmseg.models.utils.PSPModule",
"torch.nn.functional.interpolate",
"torch.nn.AdaptiveAvgPool2d",
"mmcv.runner.load_checkpoint",
"mmseg.models.utils.LocalAttentionModule"... | [((3264, 3295), 'math.ceil', 'math.ceil', (['(out_channels / ratio)'], {}), '(out_channels / ratio)\n', (3273, 3295), False, 'import math\n'), ((4170, 4196), 'torch.cat', 'torch.cat', (['[x1, x2]'], {'dim': '(1)'}), '([x1, x2], dim=1)\n', (4179, 4196), False, 'import torch\n'), ((5694, 5718), 'torch.matmul', 'torch.mat... |
import pandas as pd
import re
import requests
from bs4 import BeautifulSoup
from time import sleep
from .requester import Requester
class Crawler:
"""
"""
def __init__(self, url, sarcasm, as_archived=False):
self.__url = url
self.__sarcasm = sarcasm
self.__as_archived = as_archived
self.__data = list()
... | [
"bs4.BeautifulSoup",
"re.compile"
] | [((1341, 1358), 're.compile', 're.compile', (['regex'], {}), '(regex)\n', (1351, 1358), False, 'import re\n'), ((1474, 1513), 'bs4.BeautifulSoup', 'BeautifulSoup', (['html.text', '"""html.parser"""'], {}), "(html.text, 'html.parser')\n", (1487, 1513), False, 'from bs4 import BeautifulSoup\n'), ((2391, 2408), 're.compil... |
from pathlib import Path
import pickle
import time, os, json, sys
import numpy as np
#from matplotlib import pyplot as plt
import networkx as nx
#import tqdm
#import torch
#from torch_geometric.data import Data, DataLoader, InMemoryDataset
#import torch_geometric
# make this file executable from anywhere
#if __nam... | [
"os.path.realpath",
"sys.path.insert",
"deeplearning.ml4pl.graphs.unlabelled.llvm2graph.graph_builder.ProGraMLGraphBuilder",
"pathlib.Path"
] | [((351, 377), 'os.path.realpath', 'os.path.realpath', (['__file__'], {}), '(__file__)\n', (367, 377), False, 'import time, os, json, sys\n'), ((532, 561), 'sys.path.insert', 'sys.path.insert', (['(1)', 'repo_root'], {}), '(1, repo_root)\n', (547, 561), False, 'import time, os, json, sys\n'), ((574, 589), 'pathlib.Path'... |
import time
import eventlet
import ast
from st2reactor.sensor.base import PollingSensor
__all_ = [
'AutoscaleGovernorSensor'
]
eventlet.monkey_patch(
os=True,
select=True,
socket=True,
thread=True,
time=True)
GROUP_ACTIVE_STATUS = [
'expanding',
'deflating'
]
class AutoscaleGovernor... | [
"ast.literal_eval",
"time.time",
"eventlet.monkey_patch"
] | [((133, 218), 'eventlet.monkey_patch', 'eventlet.monkey_patch', ([], {'os': '(True)', 'select': '(True)', 'socket': '(True)', 'thread': '(True)', 'time': '(True)'}), '(os=True, select=True, socket=True, thread=True, time=True\n )\n', (154, 218), False, 'import eventlet\n'), ((1490, 1517), 'ast.literal_eval', 'ast.li... |
#!/usr/bin/env python
# Author: <NAME>
# email: <EMAIL>
try:
from setuptools import setup
except ImportError:
from distutils.core import setup
with open(('README.md'), encoding='utf-8') as readme:
bdescription = readme.read()
setup(
name='sparkdataset',
description=("Provides instant access to ... | [
"distutils.core.setup"
] | [((243, 1188), 'distutils.core.setup', 'setup', ([], {'name': '"""sparkdataset"""', 'description': '"""Provides instant access to many popular datasets right from Pyspark (in dataframe structure)."""', 'author': '"""<NAME>"""', 'url': '"""https://github.com/Spratiher9/SparkDataset"""', 'download_url': '"""https://githu... |
#!/usr/bin/python
import json
import sys
import csv
import math
def VarInBranchLimited(tree, uvars, writer, limit):
"""Return all variables in a branch with limit (list)"""
# Check if the numSplit drop below limit or if it raches a lastSplit node
if ((len(uvars)+tree['Weigth']) <= limit) or (tree['LastSpl... | [
"json.load",
"csv.writer",
"csv.reader"
] | [((1424, 1443), 'csv.writer', 'csv.writer', (['csvfile'], {}), '(csvfile)\n', (1434, 1443), False, 'import csv\n'), ((2423, 2442), 'csv.writer', 'csv.writer', (['csvfile'], {}), '(csvfile)\n', (2433, 2442), False, 'import csv\n'), ((3150, 3169), 'csv.writer', 'csv.writer', (['csvfile'], {}), '(csvfile)\n', (3160, 3169)... |
'''
makeRankingCard.py:制作评分卡。
Author: HeRaNO
'''
import sys
import imblearn
import numpy as np
import pandas as pd
from sklearn.linear_model import LogisticRegression as LR
# Read data start
model = pd.read_csv("model_data.csv", index_col = 0)
vali = pd.read_csv("vali_data.csv", index_col = 0)
# Read data end
# S... | [
"pandas.read_csv",
"numpy.log",
"pandas.cut",
"sklearn.linear_model.LogisticRegression",
"numpy.sum",
"pandas.DataFrame"
] | [((204, 246), 'pandas.read_csv', 'pd.read_csv', (['"""model_data.csv"""'], {'index_col': '(0)'}), "('model_data.csv', index_col=0)\n", (215, 246), True, 'import pandas as pd\n'), ((256, 297), 'pandas.read_csv', 'pd.read_csv', (['"""vali_data.csv"""'], {'index_col': '(0)'}), "('vali_data.csv', index_col=0)\n", (267, 297... |
import logging
from logging.handlers import RotatingFileHandler
from flask import Flask
from flask_sqlalchemy import SQLAlchemy
from redis import StrictRedis
from flask_wtf.csrf import CSRFProtect, generate_csrf
from flask_session import Session
from config import config_dict
# 暂时没有app对象,就不会去初始化,只是声明一下.为什么能这样做:点进去源码
... | [
"logging.basicConfig",
"logging.getLogger",
"flask.Flask",
"logging.Formatter",
"flask_wtf.csrf.CSRFProtect",
"logging.handlers.RotatingFileHandler",
"flask_session.Session",
"redis.StrictRedis",
"flask_sqlalchemy.SQLAlchemy"
] | [((355, 367), 'flask_sqlalchemy.SQLAlchemy', 'SQLAlchemy', ([], {}), '()\n', (365, 367), False, 'from flask_sqlalchemy import SQLAlchemy\n'), ((680, 728), 'logging.basicConfig', 'logging.basicConfig', ([], {'level': 'configClass.LOG_LEVEL'}), '(level=configClass.LOG_LEVEL)\n', (699, 728), False, 'import logging\n'), ((... |
"""Class to dynamically create the different forms in the config file
"""
import os
from wtforms import (
BooleanField, SelectField, StringField, FloatField, IntegerField,
FormField, TextAreaField, FieldList, DecimalField
)
from wtforms.validators import InputRequired, Optional, NumberRange, \
ValidationEr... | [
"werkzeug.utils.secure_filename",
"wtforms.validators.Optional",
"wtforms.FormField",
"os.path.exists",
"loris.app.autoscripting.utils.DbReader",
"wtforms.StringField",
"os.path.split",
"loris.config.get_table_from_classname",
"loris.errors.LorisError",
"wtforms.FloatField",
"loris.app.forms.for... | [((12748, 12777), 'loris.app.autoscripting.utils.DictReader', 'DictReader', (['post_process_dict'], {}), '(post_process_dict)\n', (12758, 12777), False, 'from loris.app.autoscripting.utils import json_reader, array_reader, recarray_reader, frame_reader, series_reader, EnumReader, ListReader, TupleReader, DictReader, Db... |
import copy
from .reduplication import RegexTest
from .common_functions import check_for_regex
class LexRule:
"""
A class that represents a regex-based second order lexical
rule. Rules are applied after the primary morphological
analysis has been completed and are used to add fields
to the words w... | [
"copy.deepcopy"
] | [((1584, 1601), 'copy.deepcopy', 'copy.deepcopy', (['wf'], {}), '(wf)\n', (1597, 1601), False, 'import copy\n')] |
import nltk
from nltk.corpus import wordnet
from nltk.corpus import wordnet as wn
from nltk.corpus import wordnet_ic
brown_ic = wordnet_ic.ic('ic-brown.dat')
semcor_ic = wordnet_ic.ic('ic-semcor.dat')
from nltk.corpus import genesis
genesis_ic = wn.ic(genesis, False, 0.0)
lion = wn.synset('lion.n.01')
cat = wn.synset('... | [
"nltk.corpus.wordnet_ic.ic",
"nltk.corpus.wordnet.synset",
"nltk.corpus.wordnet.ic"
] | [((128, 157), 'nltk.corpus.wordnet_ic.ic', 'wordnet_ic.ic', (['"""ic-brown.dat"""'], {}), "('ic-brown.dat')\n", (141, 157), False, 'from nltk.corpus import wordnet_ic\n'), ((170, 200), 'nltk.corpus.wordnet_ic.ic', 'wordnet_ic.ic', (['"""ic-semcor.dat"""'], {}), "('ic-semcor.dat')\n", (183, 200), False, 'from nltk.corpu... |
################################################################################
# #
# ____ _ #
# | _ \ ___ __| |_ __ _ _ _ __ ___ ... | [
"rak_net.server.server",
"player.bedrock_player.bedrock_player",
"packet.mcbe.game_packet.game_packet"
] | [((2822, 2929), 'rak_net.server.server', 'rak_net_server', (["server.config.data['ip_address']['hostname']", "server.config.data['ip_address']['port']"], {}), "(server.config.data['ip_address']['hostname'], server.config.\n data['ip_address']['port'])\n", (2836, 2929), True, 'from rak_net.server import server as rak... |
# Generated by the protocol buffer compiler. DO NOT EDIT!
from google.protobuf import descriptor
from google.protobuf import message
from google.protobuf import reflection
from google.protobuf import descriptor_pb2
# @@protoc_insertion_point(imports)
DESCRIPTOR = descriptor.FileDescriptor(
name='RpcPayloadHeader... | [
"google.protobuf.descriptor.EnumValueDescriptor",
"google.protobuf.descriptor.FieldDescriptor",
"google.protobuf.descriptor.FileDescriptor"
] | [((269, 1219), 'google.protobuf.descriptor.FileDescriptor', 'descriptor.FileDescriptor', ([], {'name': '"""RpcPayloadHeader.proto"""', 'package': '""""""', 'serialized_pb': '\'\\n\\x16RpcPayloadHeader.proto"q\\n\\x15RpcPayloadHeaderProto\\x12\\x1e\\n\\x07rpcKind\\x18\\x01 \\x01(\\x0e2\\r.RpcKindProto\\x12(\\n\\x05rpcOp... |
from dirs import User
def test_config_home():
assert User.config_home().is_dir()
def test_cache_home():
assert User.cache_home().is_dir()
def test_data_home():
assert User.data_home().is_dir()
def test_data(user: User):
assert user.data == User.data_home()
def test_config(user: User):
asse... | [
"dirs.User.data_home",
"dirs.User.cache_home",
"dirs.User.config_home"
] | [((264, 280), 'dirs.User.data_home', 'User.data_home', ([], {}), '()\n', (278, 280), False, 'from dirs import User\n'), ((338, 356), 'dirs.User.config_home', 'User.config_home', ([], {}), '()\n', (354, 356), False, 'from dirs import User\n'), ((444, 461), 'dirs.User.cache_home', 'User.cache_home', ([], {}), '()\n', (45... |
# -*- coding: utf-8 -*-
"""
-------------------------------------------------
File Name: alien_invasion
Description : 武装飞船:游戏入口 !!!
Author : cat
date: 2018/1/22
-------------------------------------------------
Change Activity:
2018/1/22:
---------------------------... | [
"logging.getLogger",
"pygame.init",
"pygame.display.set_mode",
"armed.game_functions.check_events",
"armed.settings.Settings",
"pygame.display.set_caption",
"armed.game_functions.update_screen",
"armed.ship.Ship"
] | [((586, 599), 'pygame.init', 'pygame.init', ([], {}), '()\n', (597, 599), False, 'import pygame\n'), ((681, 691), 'armed.settings.Settings', 'Settings', ([], {}), '()\n', (689, 691), False, 'from armed.settings import Settings\n'), ((706, 784), 'pygame.display.set_mode', 'pygame.display.set_mode', (['(ai_settings.scree... |
"""snakeoil-based pytest fixtures"""
import pytest
from . import random_str
class TempDir:
"""Provide temporary directory to every test method."""
@pytest.fixture(autouse=True)
def __setup(self, tmpdir):
self.dir = str(tmpdir)
class RandomPath:
"""Provide random path in a temporary direct... | [
"pytest.fixture"
] | [((161, 189), 'pytest.fixture', 'pytest.fixture', ([], {'autouse': '(True)'}), '(autouse=True)\n', (175, 189), False, 'import pytest\n'), ((355, 383), 'pytest.fixture', 'pytest.fixture', ([], {'autouse': '(True)'}), '(autouse=True)\n', (369, 383), False, 'import pytest\n')] |
from django.core.management.base import BaseCommand, CommandError
#Fixture package
from mixer.backend.django import mixer
#Test package & Utils
from django.test import TestCase
import pytest
import time, random
#models
from applications.brandcolors.models import Startup
from applications.brandcolors.models import S... | [
"applications.brandcolors.models.Fabric.objects.all",
"applications.brandcolors.models.StartupColor.objects.create",
"time.clock",
"webcolors.hex_to_rgb",
"applications.brandcolors.models.Startup.objects.all",
"applications.brandcolors.models.StartupColor.objects.all",
"mixer.backend.django.mixer.cycle"... | [((715, 731), 'faker.Factory.create', 'Factory.create', ([], {}), '()\n', (729, 731), False, 'from faker import Factory\n'), ((867, 879), 'time.clock', 'time.clock', ([], {}), '()\n', (877, 879), False, 'import time, random\n'), ((1505, 1523), 'django.contrib.auth.models.User.objects.all', 'User.objects.all', ([], {}),... |
from mailu import app, manager, db
from mailu.admin import models
@manager.command
def admin(localpart, domain_name, password):
""" Create an admin user
"""
domain = models.Domain.query.get(domain_name)
if not domain:
domain = models.Domain(name=domain_name)
db.session.add(domain)
... | [
"mailu.admin.models.Domain",
"mailu.db.session.add",
"yaml.load",
"mailu.db.session.query",
"mailu.admin.models.Domain.query.get",
"mailu.admin.models.User.query.get",
"mailu.manager.run",
"mailu.admin.models.Alias.query.get",
"mailu.db.session.delete",
"mailu.admin.models.User",
"mailu.db.sessi... | [((180, 216), 'mailu.admin.models.Domain.query.get', 'models.Domain.query.get', (['domain_name'], {}), '(domain_name)\n', (203, 216), False, 'from mailu.admin import models\n'), ((327, 393), 'mailu.admin.models.User', 'models.User', ([], {'localpart': 'localpart', 'domain': 'domain', 'global_admin': '(True)'}), '(local... |
from typing import Any, Dict, Set
from django.apps import AppConfig
class MediafilesAppConfig(AppConfig):
name = "openslides.mediafiles"
verbose_name = "OpenSlides Mediafiles"
angular_site_module = True
def ready(self):
# Import all required stuff.
from openslides.core.signals import... | [
"openslides.core.signals.permission_change.connect"
] | [((766, 878), 'openslides.core.signals.permission_change.connect', 'permission_change.connect', (['get_permission_change_data'], {'dispatch_uid': '"""mediafiles_get_permission_change_data"""'}), "(get_permission_change_data, dispatch_uid=\n 'mediafiles_get_permission_change_data')\n", (791, 878), False, 'from opensl... |
import datetime
import os
import uuid
from os.path import join as opjoin
from pathlib import Path
import numpy as np
import requests
import yaml
from celery.result import AsyncResult
from django.db.models import Q
from drf_yasg import openapi
from drf_yasg.utils import swagger_auto_schema
from rest_framework import mi... | [
"backend_app.models.Model.objects.filter",
"backend_app.models.Project.objects.filter",
"numpy.trunc",
"drf_yasg.utils.swagger_auto_schema",
"backend_app.models.Project.objects.get",
"yaml.load",
"backend_app.models.AllowedProperty.objects.all",
"backend_app.models.TrainingSetting",
"backend_app.mod... | [((816, 852), 'backend_app.models.AllowedProperty.objects.all', 'models.AllowedProperty.objects.all', ([], {}), '()\n', (850, 852), False, 'from backend_app import mixins as BAMixins, models, serializers, swagger\n'), ((2601, 2653), 'backend_app.models.Dataset.objects.filter', 'models.Dataset.objects.filter', ([], {'is... |
number_to_multiply = int(input("Input number to multiply: ")) # Do not change this line
how_often = int(input("Input how often to multiply: ")) # Do not change this line
for i in range(number_to_multiply, (how_often * number_to_multiply) + 1, number_to_multiply):
print(i)
#fyrsta ár er 15, annað 9 og öll hin s... | [
"math.sqrt"
] | [((824, 844), 'math.sqrt', 'math.sqrt', (['start_int'], {}), '(start_int)\n', (833, 844), False, 'import math\n')] |
import re
url_removal = re.compile(r'https?://\S*')
rt_user_removal = re.compile(r'(RT )?(@\S+)?')
spaces_removal = re.compile(r'\s+')
def sanitize_text(tweet_text):
tweet_text = rt_user_removal.sub('', tweet_text)
tweet_text = url_removal.sub('', tweet_text)
tweet_text = spaces_removal.sub(' ', tweet_te... | [
"re.compile"
] | [((25, 52), 're.compile', 're.compile', (['"""https?://\\\\S*"""'], {}), "('https?://\\\\S*')\n", (35, 52), False, 'import re\n'), ((71, 99), 're.compile', 're.compile', (['"""(RT )?(@\\\\S+)?"""'], {}), "('(RT )?(@\\\\S+)?')\n", (81, 99), False, 'import re\n'), ((117, 135), 're.compile', 're.compile', (['"""\\\\s+"""'... |
from recipes.models import Purchases
from django.template.defaulttags import register
from django import template
register = template.Library() # noqa
@register.filter
def check_subscription(author_id, user):
return user.follower.filter(author=author_id).exists()
@register.filter
def check_favorite(recipe_id, ... | [
"recipes.models.Purchases.objects.filter",
"django.template.Library"
] | [((126, 144), 'django.template.Library', 'template.Library', ([], {}), '()\n', (142, 144), False, 'from django import template\n'), ((506, 564), 'recipes.models.Purchases.objects.filter', 'Purchases.objects.filter', ([], {'user': 'request.user', 'recipe': 'recipe'}), '(user=request.user, recipe=recipe)\n', (530, 564), ... |
#!/usr/bin/env python
# -*- coding: utf-8 -*-
import sys
import socket as sckt
import select as slct
import Queue
import defaults
import server_manager
socket = sckt.socket(sckt.AF_INET, sckt.SOCK_STREAM)
socket.setsockopt(sckt.SOL_SOCKET, sckt.SO_REUSEADDR, 1)
socket.bind((sckt.gethostname(), defaults.PORT))
# soc... | [
"select.select",
"socket.socket",
"server_manager.management",
"socket.gethostname",
"sys.stdout.write"
] | [((165, 208), 'socket.socket', 'sckt.socket', (['sckt.AF_INET', 'sckt.SOCK_STREAM'], {}), '(sckt.AF_INET, sckt.SOCK_STREAM)\n', (176, 208), True, 'import socket as sckt\n'), ((393, 420), 'server_manager.management', 'server_manager.management', ([], {}), '()\n', (418, 420), False, 'import server_manager\n'), ((463, 536... |
from scraper import TwitterScraper, ICanHazDadJokeScraper
scrapers = [
TwitterScraper('baddadjokes'),
ICanHazDadJokeScraper()
]
if __name__ == '__main__':
for scraper in scrapers:
scraper.scrape()
| [
"scraper.ICanHazDadJokeScraper",
"scraper.TwitterScraper"
] | [((76, 105), 'scraper.TwitterScraper', 'TwitterScraper', (['"""baddadjokes"""'], {}), "('baddadjokes')\n", (90, 105), False, 'from scraper import TwitterScraper, ICanHazDadJokeScraper\n'), ((111, 134), 'scraper.ICanHazDadJokeScraper', 'ICanHazDadJokeScraper', ([], {}), '()\n', (132, 134), False, 'from scraper import Tw... |
import os
result = [os.path.join(dp, f) for dp, dn, filenames in os.walk(".") for f in filenames if os.path.splitext(f)[1] == '.cpp']
for p in result:
with open(p, "r") as f:
data = f.read()
with open( p, "w" ) as f:
f.write( "#include \"stdafx.h\"\n\n" + data );
| [
"os.path.splitext",
"os.path.join",
"os.walk"
] | [((23, 42), 'os.path.join', 'os.path.join', (['dp', 'f'], {}), '(dp, f)\n', (35, 42), False, 'import os\n'), ((68, 80), 'os.walk', 'os.walk', (['"""."""'], {}), "('.')\n", (75, 80), False, 'import os\n'), ((103, 122), 'os.path.splitext', 'os.path.splitext', (['f'], {}), '(f)\n', (119, 122), False, 'import os\n')] |
# SPDX-License-Identifier: Apache-2.0
#
# Copyright (C) 2021 Micron Technology, Inc. All rights reserved.
from typing import List
from tools import config
from tools.base import BaseTest
from tools.helpers import shlex_join
class KmtTest(BaseTest):
def __init__(self, name: str, args: List[str]):
super()... | [
"tools.helpers.shlex_join"
] | [((504, 525), 'tools.helpers.shlex_join', 'shlex_join', (['self.args'], {}), '(self.args)\n', (514, 525), False, 'from tools.helpers import shlex_join\n')] |
# Copyright (c) 2018 IoTeX
# This is an alpha (internal) release and is not suitable for production. This source code is provided 'as is' and no
# warranties are given as to title or non-infringement, merchantability or fitness for purpose and, to the extent
# permitted by law, all liability for your use of the code is... | [
"consensus_failurestop.ConsensusFS",
"consensus_client.Consensus",
"numpy.random.lognormal"
] | [((2124, 2152), 'consensus_client.Consensus', 'consensus_client.Consensus', ([], {}), '()\n', (2150, 2152), False, 'import consensus_client\n'), ((6945, 6999), 'numpy.random.lognormal', 'np.random.lognormal', (['self.NORMAL_MEAN', 'self.NORMAL_STD'], {}), '(self.NORMAL_MEAN, self.NORMAL_STD)\n', (6964, 6999), True, 'im... |
import argparse
from FVC_utils import load_from_pickle, save_to_pickle, readData, printx, time, path
from xgboost import XGBClassifier
import warnings
warnings.filterwarnings('ignore')
# from sklearn.preprocessing import StandardScaler
def training_series(X_train, y_train, normalizer=None, xgb_params={}):
printx('... | [
"FVC_utils.load_from_pickle",
"FVC_utils.printx",
"FVC_utils.readData",
"argparse.ArgumentParser",
"FVC_utils.time.time",
"sklearn.preprocessing.StandardScaler",
"warnings.filterwarnings",
"xgboost.XGBClassifier"
] | [((151, 184), 'warnings.filterwarnings', 'warnings.filterwarnings', (['"""ignore"""'], {}), "('ignore')\n", (174, 184), False, 'import warnings\n'), ((802, 867), 'argparse.ArgumentParser', 'argparse.ArgumentParser', ([], {'description': '"""extract the complex region"""'}), "(description='extract the complex region')\n... |
import subprocess
from masonite.helpers import config
def has_unmigrated_migrations():
if not config('application.debug'):
return False
from wsgi import container
from config.database import DB
try:
DB.connection()
except Exception:
return False
migration_directory = ... | [
"subprocess.check_output",
"wsgi.container.providers.items",
"masonite.helpers.config",
"config.database.DB.connection"
] | [((367, 394), 'wsgi.container.providers.items', 'container.providers.items', ([], {}), '()\n', (392, 394), False, 'from wsgi import container\n'), ((100, 127), 'masonite.helpers.config', 'config', (['"""application.debug"""'], {}), "('application.debug')\n", (106, 127), False, 'from masonite.helpers import config\n'), ... |
from sqlalchemy import Column, ForeignKey, Integer, String
from sqlalchemy.ext.declarative import declarative_base
from sqlalchemy.orm import relationship
from sqlalchemy import create_engine
Base = declarative_base()
class User(Base):
__tablename__ = 'user'
id = Column(Integer, primary_key=True)
name =... | [
"sqlalchemy.orm.relationship",
"sqlalchemy.create_engine",
"sqlalchemy.ForeignKey",
"sqlalchemy.String",
"sqlalchemy.ext.declarative.declarative_base",
"sqlalchemy.Column"
] | [((200, 218), 'sqlalchemy.ext.declarative.declarative_base', 'declarative_base', ([], {}), '()\n', (216, 218), False, 'from sqlalchemy.ext.declarative import declarative_base\n'), ((1672, 1713), 'sqlalchemy.create_engine', 'create_engine', (['"""sqlite:///supermarket.db"""'], {}), "('sqlite:///supermarket.db')\n", (168... |
from itsdangerous import TimedJSONWebSignatureSerializer, \
JSONWebSignatureSerializer
from nanohttp import settings, context, HTTPForbidden
class BaseJWTPrincipal:
def __init__(self, payload):
self.payload = payload
@classmethod
def create_serializer(cls, force=False, max_age=None):
... | [
"itsdangerous.JSONWebSignatureSerializer",
"nanohttp.HTTPForbidden",
"itsdangerous.TimedJSONWebSignatureSerializer"
] | [((2352, 2527), 'itsdangerous.TimedJSONWebSignatureSerializer', 'TimedJSONWebSignatureSerializer', (['settings.jwt.refresh_token.secret'], {'expires_in': 'settings.jwt.refresh_token.max_age', 'algorithm_name': 'settings.jwt.refresh_token.algorithm'}), '(settings.jwt.refresh_token.secret,\n expires_in=settings.jwt.re... |
import numpy as np
import matplotlib.pyplot as plt
import math
TIME_SLEEP = 0.000000001
def train_sgd(X, y, alpha, w=None):
"""Trains a linear regression model using stochastic gradient descent.
Parameters
----------
X : numpy.ndarray
Numpy array of data
y : numpy.ndarray
Numpy a... | [
"numpy.ones",
"matplotlib.pyplot.show",
"matplotlib.pyplot.clf",
"matplotlib.pyplot.plot",
"numpy.sum",
"matplotlib.pyplot.figure",
"numpy.zeros",
"math.fabs",
"matplotlib.pyplot.pause",
"numpy.transpose",
"matplotlib.pyplot.ion"
] | [((2701, 2710), 'matplotlib.pyplot.clf', 'plt.clf', ([], {}), '()\n', (2708, 2710), True, 'import matplotlib.pyplot as plt\n'), ((2715, 2766), 'matplotlib.pyplot.plot', 'plt.plot', (['X[:, 0]', 'y_predict', '"""r-"""', 'X[:, 0]', 'y', '"""o"""'], {}), "(X[:, 0], y_predict, 'r-', X[:, 0], y, 'o')\n", (2723, 2766), True,... |
import boto3
import json
import math
import logging
import base64
from concurrent.futures import ThreadPoolExecutor
from .storyhtml import create_story_html
from .convert import convert_to_exhibit
import time
class StoryPublisher:
def __init__(
self,
bucket,
get_image_lambda_name,
... | [
"json.loads",
"math.ceil",
"boto3.client",
"concurrent.futures.ThreadPoolExecutor",
"json.dumps",
"base64.b64decode",
"time.time",
"logging.info"
] | [((444, 466), 'boto3.client', 'boto3.client', (['"""lambda"""'], {}), "('lambda')\n", (456, 466), False, 'import boto3\n'), ((492, 510), 'boto3.client', 'boto3.client', (['"""s3"""'], {}), "('s3')\n", (504, 510), False, 'import boto3\n'), ((844, 935), 'logging.info', 'logging.info', (['"""Publishing story uuid=%s rende... |
from setuptools import setup
from Cython.Build import cythonize
setup(ext_modules=cythonize('bfsHash.pyx')) | [
"Cython.Build.cythonize"
] | [((83, 107), 'Cython.Build.cythonize', 'cythonize', (['"""bfsHash.pyx"""'], {}), "('bfsHash.pyx')\n", (92, 107), False, 'from Cython.Build import cythonize\n')] |
import os
import sys
sys.path.append("../instock_notifier")
import config
from mailjet_rest import Client
mailjet = Client(auth=(config.SMTP_API_KEY, config.SMTP_API_SECRET), version="v3.1")
data = {
"Messages": [
{
"From": config.EMAIL_SENDER,
"To": config.EMAIL_RECI... | [
"mailjet_rest.Client",
"sys.path.append"
] | [((23, 61), 'sys.path.append', 'sys.path.append', (['"""../instock_notifier"""'], {}), "('../instock_notifier')\n", (38, 61), False, 'import sys\n'), ((127, 201), 'mailjet_rest.Client', 'Client', ([], {'auth': '(config.SMTP_API_KEY, config.SMTP_API_SECRET)', 'version': '"""v3.1"""'}), "(auth=(config.SMTP_API_KEY, confi... |
"""
Listing Views
"""
import logging
import operator
from django.shortcuts import get_object_or_404
from django.db.models import Min
from django.db.models.functions import Lower
from rest_framework import filters
from rest_framework import status
from rest_framework import viewsets
from rest_framework.response import ... | [
"ozpcenter.api.listing.model_access.put_counts_in_listings_endpoint",
"ozpcenter.api.listing.model_access.get_listing_by_id",
"ozpcenter.api.listing.model_access.get_all_listing_activities",
"ozpcenter.pipe.pipes.ListingDictPostSecurityMarkingCheckPipe",
"ozpcenter.api.listing.serializers.RecommendationFeed... | [((1026, 1057), 'ozpcenter.api.listing.model_access.get_all_doc_urls', 'model_access.get_all_doc_urls', ([], {}), '()\n', (1055, 1057), True, 'import ozpcenter.api.listing.model_access as model_access\n'), ((11090, 11126), 'ozpcenter.api.listing.model_access.get_all_listing_types', 'model_access.get_all_listing_types',... |
import re
import time
import random
from redis_protocol.protocol import deserialize, serialize_string, serialize_error, serialize_integer, serialize_bulk_string, serialize_array
class RedisCommand(object):
def __init__(self, command, arguments, database_manager):
self.command = command.upper()
sel... | [
"redis_protocol.protocol.serialize_integer",
"re.compile",
"redis_protocol.protocol.serialize_string",
"redis_protocol.protocol.serialize_array",
"redis_protocol.protocol.serialize_error",
"redis_protocol.protocol.deserialize",
"time.time",
"redis_protocol.protocol.serialize_bulk_string"
] | [((525, 547), 'redis_protocol.protocol.deserialize', 'deserialize', (['arguments'], {}), '(arguments)\n', (536, 547), False, 'from redis_protocol.protocol import deserialize, serialize_string, serialize_error, serialize_integer, serialize_bulk_string, serialize_array\n'), ((1698, 1717), 're.compile', 're.compile', (['p... |
import datetime
from tortoise import Model, fields
from fastapi_admin.models import AbstractAdminLog, AbstractPermission, AbstractRole, AbstractUser
from .enums import ProductType, Status
class User(AbstractUser):
last_login = fields.DatetimeField(description="Last Login", default=datetime.datetime.now)
av... | [
"tortoise.fields.CharField",
"tortoise.fields.BooleanField",
"tortoise.fields.DatetimeField",
"tortoise.fields.ManyToManyField",
"tortoise.fields.IntEnumField",
"tortoise.fields.IntField",
"tortoise.fields.JSONField",
"tortoise.fields.TextField"
] | [((236, 313), 'tortoise.fields.DatetimeField', 'fields.DatetimeField', ([], {'description': '"""Last Login"""', 'default': 'datetime.datetime.now'}), "(description='Last Login', default=datetime.datetime.now)\n", (256, 313), False, 'from tortoise import Model, fields\n'), ((327, 371), 'tortoise.fields.CharField', 'fiel... |
from Qt import QtCore
from Qt import QtGui
from Qt.QtWidgets import QGraphicsItem
from PyFlow.Core.Common import getConnectedPins
from PyFlow.UI import RESOURCES_DIR
from PyFlow.UI.Utils.Settings import *
from PyFlow.UI.Canvas.Painters import NodePainter
from PyFlow.UI.Canvas.UINodeBase import UINodeBase
class UIRer... | [
"PyFlow.UI.Canvas.Painters.NodePainter.default"
] | [((1497, 1547), 'PyFlow.UI.Canvas.Painters.NodePainter.default', 'NodePainter.default', (['self', 'painter', 'option', 'widget'], {}), '(self, painter, option, widget)\n', (1516, 1547), False, 'from PyFlow.UI.Canvas.Painters import NodePainter\n')] |
from pathlib import Path
from smarts.sstudio import gen_scenario
from smarts.sstudio import types as t
traffic_histories = [
t.TrafficHistoryDataset(
name=f"us101_{hd}",
source_type="NGSIM",
input_path=f"../../xy-trajectories/us101/trajectories-{hd}.txt",
speed_limit_mps=28,
... | [
"smarts.sstudio.types.TrafficHistoryDataset",
"smarts.sstudio.types.Scenario",
"pathlib.Path"
] | [((131, 309), 'smarts.sstudio.types.TrafficHistoryDataset', 't.TrafficHistoryDataset', ([], {'name': 'f"""us101_{hd}"""', 'source_type': '"""NGSIM"""', 'input_path': 'f"""../../xy-trajectories/us101/trajectories-{hd}.txt"""', 'speed_limit_mps': '(28)', 'default_heading': '(0)'}), "(name=f'us101_{hd}', source_type='NGSI... |
#!/usr/bin/env python3
"""
Caveat when attempting to run the examples in non-gps environments:
`drone.offboard.stop()` will return a `COMMAND_DENIED` result because it
requires a mode switch to HOLD, something that is currently not supported in a
non-gps environment.
"""
import asyncio
from math import sqrt
from mav... | [
"mavsdk.offboard.PositionNedYaw",
"math.sqrt",
"time.perf_counter",
"mavsdk.System",
"math.cos",
"asyncio.sleep",
"multiprocessing.Queue",
"math.sin"
] | [((572, 579), 'multiprocessing.Queue', 'Queue', ([], {}), '()\n', (577, 579), False, 'from multiprocessing import Process, Queue\n'), ((606, 613), 'multiprocessing.Queue', 'Queue', ([], {}), '()\n', (611, 613), False, 'from multiprocessing import Process, Queue\n'), ((640, 647), 'multiprocessing.Queue', 'Queue', ([], {... |
# coding: utf-8
import argparse
import time
from watchdog.observers import Observer
from pywatcher import PyWatcher
from logging import getLogger, Formatter, StreamHandler, DEBUG
logger = getLogger(__name__)
formatter = Formatter('%(asctime)s - %(levelname)s - %(message)s')
handler = StreamHandler()
handler.setLevel(... | [
"logging.getLogger",
"logging.StreamHandler",
"argparse.ArgumentParser",
"logging.Formatter",
"time.sleep",
"pywatcher.PyWatcher",
"watchdog.observers.Observer"
] | [((190, 209), 'logging.getLogger', 'getLogger', (['__name__'], {}), '(__name__)\n', (199, 209), False, 'from logging import getLogger, Formatter, StreamHandler, DEBUG\n'), ((222, 276), 'logging.Formatter', 'Formatter', (['"""%(asctime)s - %(levelname)s - %(message)s"""'], {}), "('%(asctime)s - %(levelname)s - %(message... |
# -*- coding: utf-8 -*-
"""
wakatime.queue
~~~~~~~~~~~~~~
Queue for offline time logging.
http://wakatime.com
:copyright: (c) 2014 <NAME>.
:license: BSD, see LICENSE for more details.
"""
import logging
import os
import traceback
from time import sleep
try:
import sqlite3
HAS_SQL = T... | [
"logging.getLogger",
"traceback.format_exc",
"sqlite3.connect",
"time.sleep",
"os.path.expanduser"
] | [((372, 399), 'logging.getLogger', 'logging.getLogger', (['__name__'], {}), '(__name__)\n', (389, 399), False, 'import logging\n'), ((450, 473), 'os.path.expanduser', 'os.path.expanduser', (['"""~"""'], {}), "('~')\n", (468, 473), False, 'import os\n'), ((530, 559), 'sqlite3.connect', 'sqlite3.connect', (['self.DB_FILE... |
# ---
# jupyter:
# jupytext:
# formats: ipynb,py:light
# text_representation:
# extension: .py
# format_name: light
# format_version: '1.5'
# jupytext_version: 1.5.1
# kernelspec:
# display_name: Python 3
# language: python
# name: python3
# ---
# Separation via Time-Fre... | [
"numpy.abs",
"nussl.core.masks.BinaryMask",
"nussl.play_utils.multitrack",
"nussl.utils.visualize_spectrogram",
"nussl.utils.visualize_sources_as_waveform",
"nussl.utils.visualize_sources_as_masks",
"matplotlib.pyplot.subplot",
"numpy.angle",
"matplotlib.pyplot.figure",
"numpy.exp",
"nussl.core.... | [((671, 682), 'time.time', 'time.time', ([], {}), '()\n', (680, 682), False, 'import time\n'), ((692, 729), 'nussl.datasets.MUSDB18', 'nussl.datasets.MUSDB18', ([], {'download': '(True)'}), '(download=True)\n', (714, 729), False, 'import nussl\n'), ((1045, 1072), 'matplotlib.pyplot.figure', 'plt.figure', ([], {'figsize... |
#!/usr/bin/python
# python console for OnlyRAT
# created by : C0SM0
# imports
import os
import sys
import getpass
import random as r
from datetime import datetime
# banner for display
banner = """
_;,
... | [
"getpass.getuser",
"os.system",
"datetime.datetime.now",
"sys.exit"
] | [((3657, 3674), 'getpass.getuser', 'getpass.getuser', ([], {}), '()\n', (3672, 3674), False, 'import getpass\n'), ((4961, 4979), 'os.system', 'os.system', (['"""clear"""'], {}), "('clear')\n", (4970, 4979), False, 'import os\n'), ((5048, 5058), 'sys.exit', 'sys.exit', ([], {}), '()\n', (5056, 5058), False, 'import sys\... |
"""
PyAltmetric
This is a python wrapper for the Altmetric API.
For more information on the Altmetric API visit http://api.altmetric.com/.
Some pieces of this library were inspired by or derived from the altmetric api
wrapper altmetric.py which is licensed under the MIT open source license.
If you display Altmetric ... | [
"warnings.warn",
"json.load",
"datetime.datetime.fromtimestamp",
"requests.get"
] | [((2362, 2416), 'warnings.warn', 'warnings.warn', (['"""Altmetric ID\'s are subject to change."""'], {}), '("Altmetric ID\'s are subject to change.")\n', (2375, 2416), False, 'import warnings\n'), ((4671, 4711), 'requests.get', 'requests.get', (['request_url'], {'params': 'params'}), '(request_url, params=params)\n', (... |
from course_lib.Base.BaseRecommender import BaseRecommender
import numpy as np
import scipy.sparse as sps
class SearchFieldWeightICMRecommender(BaseRecommender):
""" Search Field Weight ICM Recommender """
RECOMMENDER_NAME = "SearchFieldWeightICMRecommender"
def __init__(self, URM_train, ICM_train, reco... | [
"numpy.ones",
"scipy.sparse.diags"
] | [((846, 884), 'numpy.ones', 'np.ones', ([], {'shape': 'self.ICM_train.shape[1]'}), '(shape=self.ICM_train.shape[1])\n', (853, 884), True, 'import numpy as np\n'), ((1138, 1169), 'scipy.sparse.diags', 'sps.diags', (['item_feature_weights'], {}), '(item_feature_weights)\n', (1147, 1169), True, 'import scipy.sparse as sps... |
import datetime
import json
import pandas as pd
import yfinance as yf
from yahoofinancials import YahooFinancials
from fastapi import FastAPI
app = FastAPI()
@app.get("/stock/{ticker}")
async def get_stock_data(ticker: str):
ticker_data = yf.Ticker(ticker).info
mktopen = ticker_data["open"]
mkthigh = ti... | [
"fastapi.FastAPI",
"json.dumps",
"pandas.set_option",
"datetime.timedelta",
"datetime.datetime.today",
"pandas.DataFrame",
"yahoofinancials.YahooFinancials",
"yfinance.Ticker",
"pandas.to_datetime"
] | [((150, 159), 'fastapi.FastAPI', 'FastAPI', ([], {}), '()\n', (157, 159), False, 'from fastapi import FastAPI\n'), ((1120, 1137), 'yfinance.Ticker', 'yf.Ticker', (['ticker'], {}), '(ticker)\n', (1129, 1137), True, 'import yfinance as yf\n'), ((1213, 1227), 'pandas.DataFrame', 'pd.DataFrame', ([], {}), '()\n', (1225, 12... |
# -*- coding: utf-8 -*-
# Generated by Django 1.9.13 on 2018-03-28 06:53
from __future__ import unicode_literals
from django.db import migrations, models
class Migration(migrations.Migration):
dependencies = [
('blog', '0004_auto_20180314_1027'),
]
operations = [
migrations.AddField(
... | [
"django.db.models.URLField",
"django.db.models.FileField",
"django.db.models.IntegerField"
] | [((400, 430), 'django.db.models.IntegerField', 'models.IntegerField', ([], {'default': '(0)'}), '(default=0)\n', (419, 430), False, 'from django.db import migrations, models\n'), ((548, 575), 'django.db.models.URLField', 'models.URLField', ([], {'blank': '(True)'}), '(blank=True)\n', (563, 575), False, 'from django.db ... |
"""Clowder Utils
This module contains utilities that make it easier to work with clowder.
Amongst these utilities is a simple way to initialize the logging system
from either a file or the command line.
"""
import datetime
import json
import logging
import logging.config
import os
import time
import zipfile
import te... | [
"logging.basicConfig",
"logging.getLogger",
"os.fdopen",
"zipfile.ZipFile",
"logging.config.dictConfig",
"os.path.join",
"requests.get",
"os.path.isfile",
"datetime.datetime.now",
"yaml.safe_load",
"logging.config.fileConfig",
"json.load",
"tempfile.mkstemp",
"os.walk",
"os.remove"
] | [((3926, 3954), 'zipfile.ZipFile', 'zipfile.ZipFile', (['zipfilepath'], {}), '(zipfilepath)\n', (3941, 3954), False, 'import zipfile\n'), ((4090, 4112), 'os.walk', 'os.walk', (['output_folder'], {}), '(output_folder)\n', (4097, 4112), False, 'import os\n'), ((2723, 2750), 'os.path.isfile', 'os.path.isfile', (['config_i... |
from typing import Dict, List, Optional, Union
import numpy as np
import torch
MOLECULAR_ATOMS = (
"H,He,Li,Be,B,C,N,O,F,Ne,Na,Mg,Al,Si,P,S,Cl,Ar,K,Ca,Sc,Ti,V,Cr,Mn,Fe,Co,Ni,Cu,Zn,"
"Ga,Ge,As,Se,Br,Kr,Rb,Sr,Y,Zr,Nb,Mo,Tc,Ru,Rh,Pd,Ag,Cd,In,Sn,Sb,Te,I,Xe,Cs,Ba,La,Ce,"
"Pr,Nd,Pm,Sm,Eu,Gd,Tb,Dy,Ho,Er,Tm,Yb,Lu... | [
"torch.tensor",
"numpy.empty"
] | [((3918, 3970), 'numpy.empty', 'np.empty', (['(max_seq_len, max_seq_len)'], {'dtype': 'np.int64'}), '((max_seq_len, max_seq_len), dtype=np.int64)\n', (3926, 3970), True, 'import numpy as np\n'), ((8457, 8496), 'torch.tensor', 'torch.tensor', (["encodings['position_ids']"], {}), "(encodings['position_ids'])\n", (8469, 8... |
import easygui
# TODO: In next version use easygui.multenterbox instead of independent enterbox
class Service:
def __init__(self):
self.employerName = easygui.enterbox(msg="Enter Name of Employer", title="Service Visit Inputs")
self.employerAddr = easygui.enterbox(msg="Enter Address of Employer"... | [
"easygui.enterbox",
"easygui.choicebox",
"easygui.boolbox"
] | [((167, 243), 'easygui.enterbox', 'easygui.enterbox', ([], {'msg': '"""Enter Name of Employer"""', 'title': '"""Service Visit Inputs"""'}), "(msg='Enter Name of Employer', title='Service Visit Inputs')\n", (183, 243), False, 'import easygui\n'), ((272, 351), 'easygui.enterbox', 'easygui.enterbox', ([], {'msg': '"""Ente... |
import pytest
from ncoreparser.util import Size
class TestSize:
@pytest.mark.parametrize("size1, size2", [("1024 MiB", "1 GiB"),
("10 MiB", "10 MiB"),
("2048 KiB", "2 MiB")])
def test_equal(self, size1, size2):
... | [
"ncoreparser.util.Size",
"pytest.mark.parametrize"
] | [((71, 184), 'pytest.mark.parametrize', 'pytest.mark.parametrize', (['"""size1, size2"""', "[('1024 MiB', '1 GiB'), ('10 MiB', '10 MiB'), ('2048 KiB', '2 MiB')]"], {}), "('size1, size2', [('1024 MiB', '1 GiB'), ('10 MiB',\n '10 MiB'), ('2048 KiB', '2 MiB')])\n", (94, 184), False, 'import pytest\n'), ((393, 506), 'py... |
#!/usr/bin/env python3
"""
Extracts SSH keys from Bitwarden vault
"""
import argparse
import json
import logging
import os
import subprocess
import pexpect
import time
from pkg_resources import parse_version
def memoize(func):
"""
Decorator function to cache the results of another function call
"""
... | [
"logging.basicConfig",
"json.loads",
"logging.debug",
"argparse.ArgumentParser",
"subprocess.run",
"os.environ.get",
"logging.info",
"time.sleep",
"logging.warning",
"pkg_resources.parse_version",
"logging.error"
] | [((652, 752), 'subprocess.run', 'subprocess.run', (["['bw', '--version']"], {'stdout': 'subprocess.PIPE', 'universal_newlines': '(True)', 'check': '(True)'}), "(['bw', '--version'], stdout=subprocess.PIPE,\n universal_newlines=True, check=True)\n", (666, 752), False, 'import subprocess\n'), ((1281, 1309), 'os.enviro... |
from bottle import (
template,
route,
redirect,
request,
)
from models import (
Article,
ArticleLinks,
Wiki,
Author,
Tag,
Metadata,
)
from peewee import SQL
from .decorators import *
from .wiki import wiki_home
from .media import image_search
from utils import Message, Error,... | [
"models.Article.title.contains",
"bottle.template",
"models.Article.revision_of.is_null",
"peewee.SQL",
"models.Article",
"models.ArticleLinks.update",
"bottle.route",
"models.Wiki.title_to_url",
"datetime.datetime.now",
"models.Tag.title.contains",
"utils.Unsafe",
"models.Article.get",
"uti... | [((348, 377), 'bottle.route', 'route', (['f"""{Wiki.PATH}/article"""'], {}), "(f'{Wiki.PATH}/article')\n", (353, 377), False, 'from bottle import template, route, redirect, request\n'), ((464, 499), 'bottle.route', 'route', (['f"""{Wiki.PATH}{Article.PATH}"""'], {}), "(f'{Wiki.PATH}{Article.PATH}')\n", (469, 499), Fals... |
import scrapy
from scrapy.crawler import CrawlerProcess
def pkm_spider():
class PkmSpider(scrapy.Spider):
name = 'pkms'
def start_requests(self):
yield scrapy.Request('https://bulbapedia.bulbagarden.net/wiki/Bulbasaur_(Pok%C3%A9mon)')
def parse(self, response):
ite... | [
"scrapy.crawler.CrawlerProcess",
"scrapy.Request"
] | [((1619, 1705), 'scrapy.crawler.CrawlerProcess', 'CrawlerProcess', ([], {'settings': "{'FEED_URI': 'pkmns_name_type.csv', 'FEED_FORMAT': 'csv'}"}), "(settings={'FEED_URI': 'pkmns_name_type.csv', 'FEED_FORMAT':\n 'csv'})\n", (1633, 1705), False, 'from scrapy.crawler import CrawlerProcess\n'), ((186, 273), 'scrapy.Req... |
# coding: utf-8
"""
OOXML Automation
This API helps users convert Excel and Powerpoint documents into rich, live dashboards and stories. # noqa: E501
The version of the OpenAPI document: 0.1.0-no-tags
Generated by: https://openapi-generator.tech
"""
import pprint
import re # noqa: F401
import si... | [
"six.iteritems"
] | [((4622, 4655), 'six.iteritems', 'six.iteritems', (['self.openapi_types'], {}), '(self.openapi_types)\n', (4635, 4655), False, 'import six\n')] |
import datetime
import gridfs # type: ignore
import pymongo # type: ignore
import tenacity
from typing import Optional
from dsw2to3.config import MongoConfig
from dsw2to3.errors import ERROR_HANDLER
from dsw2to3.logger import LOGGER
DOCUMENT_FS_COLLECTION = 'documentFs'
ASSETS_FS_COLLECTION = 'templateAssetFs'
d... | [
"gridfs.GridFS",
"dsw2to3.logger.LOGGER.debug",
"datetime.datetime.now",
"dsw2to3.errors.ERROR_HANDLER.error",
"pymongo.MongoClient",
"tenacity.wait_exponential",
"tenacity.stop_after_attempt"
] | [((826, 880), 'pymongo.MongoClient', 'pymongo.MongoClient', ([], {}), '(**self.config.mongo_client_kwargs)\n', (845, 880), False, 'import pymongo\n'), ((955, 1001), 'gridfs.GridFS', 'gridfs.GridFS', (['self.db', 'DOCUMENT_FS_COLLECTION'], {}), '(self.db, DOCUMENT_FS_COLLECTION)\n', (968, 1001), False, 'import gridfs\n'... |
from server import ThreadedUDPServer
import threading
# Create the server instance and assign the binding address for it
server = ThreadedUDPServer(('localhost', 9999))
# Set up a few example event handlers
@server.on('connected')
def connected(msg, socket):
""" Both 'connected' and 'disconnected' are events
... | [
"threading.Thread",
"server.ThreadedUDPServer"
] | [((132, 170), 'server.ThreadedUDPServer', 'ThreadedUDPServer', (["('localhost', 9999)"], {}), "(('localhost', 9999))\n", (149, 170), False, 'from server import ThreadedUDPServer\n'), ((799, 844), 'threading.Thread', 'threading.Thread', ([], {'target': 'server.serve_forever'}), '(target=server.serve_forever)\n', (815, 8... |
from flask import Flask
from flask_bootstrap import Bootstrap
from flask_socketio import SocketIO
from config import Config
import eventlet
eventlet.monkey_patch()
# where should I move this normally ?
async_mode = None
app = Flask(__name__)
bootstrap = Bootstrap(app)
socketio = SocketIO(app, async_mode='eventlet')
... | [
"flask_bootstrap.Bootstrap",
"flask_socketio.SocketIO",
"eventlet.monkey_patch",
"flask.Flask"
] | [((140, 163), 'eventlet.monkey_patch', 'eventlet.monkey_patch', ([], {}), '()\n', (161, 163), False, 'import eventlet\n'), ((228, 243), 'flask.Flask', 'Flask', (['__name__'], {}), '(__name__)\n', (233, 243), False, 'from flask import Flask\n'), ((256, 270), 'flask_bootstrap.Bootstrap', 'Bootstrap', (['app'], {}), '(app... |
"""
Author: <NAME>
Date: 15 May 2021
"""
import json
from copy import deepcopy
import pytest
from flask import Response
from tests.functional.utils import FlaskTestRig, login, token_auth_header_field
@FlaskTestRig.setup_app(n_users=3)
def test_delete_me_no_auth_401(client_factory, make_users, **kwargs):
... | [
"json.loads",
"json.dumps",
"tests.functional.utils.FlaskTestRig.extract_rig_from_kwargs",
"pytest.mark.parametrize",
"copy.deepcopy",
"tests.functional.utils.token_auth_header_field",
"tests.functional.utils.FlaskTestRig.setup_app",
"tests.functional.utils.login"
] | [((216, 249), 'tests.functional.utils.FlaskTestRig.setup_app', 'FlaskTestRig.setup_app', ([], {'n_users': '(3)'}), '(n_users=3)\n', (238, 249), False, 'from tests.functional.utils import FlaskTestRig, login, token_auth_header_field\n'), ((1026, 1059), 'tests.functional.utils.FlaskTestRig.setup_app', 'FlaskTestRig.setup... |
"""
model construction function
"""
import torch
import torch.nn as nn
from fvcore.common.registry import Registry
DATASET_REGISTRY=Registry("DATASET")
def build_dataset(dataset_name,mode,cfg,):
"""
:param cfg:
:param dataset_name: avenue
:param mode: train /test
:return:
"""
# print(... | [
"fvcore.common.registry.Registry"
] | [((135, 154), 'fvcore.common.registry.Registry', 'Registry', (['"""DATASET"""'], {}), "('DATASET')\n", (143, 154), False, 'from fvcore.common.registry import Registry\n')] |
from __future__ import print_function
from scipy import sparse
import pandas as pd
import numpy as np
import argparse, os
import torch
import torch.nn as nn
import torch.nn.functional as F
import torch.optim as optim
from torchvision import datasets, transforms
from torch.optim.lr_scheduler import StepLR
from torch.uti... | [
"pandas.read_csv",
"torch.nn.functional.nll_loss",
"os.path.join",
"torch.from_numpy",
"os.path.split",
"torch.is_tensor",
"torch.nn.Linear",
"torch.nn.functional.log_softmax",
"torch.no_grad"
] | [((3932, 3952), 'torch.is_tensor', 'torch.is_tensor', (['idx'], {}), '(idx)\n', (3947, 3952), False, 'import torch\n'), ((4667, 4704), 'torch.nn.Linear', 'nn.Linear', (['n_features', '(64)'], {'bias': '(False)'}), '(n_features, 64, bias=False)\n', (4676, 4704), True, 'import torch.nn as nn\n'), ((4794, 4823), 'torch.nn... |
# importing libraries
import warnings
warnings.filterwarnings("ignore")
import sys
import pandas as pd
import numpy as np
from matplotlib import pyplot as plt
import xgboost as xgb
from catboost import CatBoostRegressor
import lightgbm as lgb
from sqlalchemy import create_engine
import pickle
from sklearn.metrics impor... | [
"sqlalchemy.create_engine",
"lightgbm.LGBMRegressor",
"catboost.CatBoostRegressor",
"numpy.array",
"xgboost.XGBRegressor",
"numpy.exp",
"numpy.random.seed",
"pandas.read_sql_table",
"sklearn.metrics.mean_absolute_error",
"sklearn.metrics.r2_score",
"warnings.filterwarnings",
"numpy.arange",
... | [((38, 71), 'warnings.filterwarnings', 'warnings.filterwarnings', (['"""ignore"""'], {}), "('ignore')\n", (61, 71), False, 'import warnings\n'), ((1432, 1451), 'numpy.array', 'np.array', (['rolling_X'], {}), '(rolling_X)\n', (1440, 1451), True, 'import numpy as np\n'), ((1468, 1487), 'numpy.array', 'np.array', (['rolli... |
from geosolver.utils.prep import sentence_to_words_statements_values
__author__ = 'minjoon'
def test_prep():
paragraph = r"If \sqrt{x+5}=40.5, what is x+5?"
print(sentence_to_words_statements_values(paragraph))
if __name__ == "__main__":
test_prep()
| [
"geosolver.utils.prep.sentence_to_words_statements_values"
] | [((173, 219), 'geosolver.utils.prep.sentence_to_words_statements_values', 'sentence_to_words_statements_values', (['paragraph'], {}), '(paragraph)\n', (208, 219), False, 'from geosolver.utils.prep import sentence_to_words_statements_values\n')] |
## Creates oracular traces from network traces, used for calculating self-inflicted delay
import glob
import os
import re
import sys
INPUT_PATH = 'cleaned_traces'
OUTPUT_PATH = 'oracular_traces'
def create_oracular_trace(filePath, targetFilePath, mode):
with open(filePath) as f:
with open(targetFilePath,... | [
"os.makedirs",
"os.path.exists",
"re.findall",
"glob.glob"
] | [((991, 1017), 'glob.glob', 'glob.glob', (["('%s/*' % source)"], {}), "('%s/*' % source)\n", (1000, 1017), False, 'import glob\n'), ((909, 936), 'os.path.exists', 'os.path.exists', (['destination'], {}), '(destination)\n', (923, 936), False, 'import os\n'), ((946, 970), 'os.makedirs', 'os.makedirs', (['destination'], {... |
#!/usr/bin/env python
import sys
import json
import re
import logging
from cli.log import LoggingApp
from pythreatspec import pythreatspec as ts
class UniversalParserApp(LoggingApp):
def parse_file(self, filename):
with open(filename) as fh:
line_no = 1
for line in fh.readlines():
... | [
"pythreatspec.pythreatspec.PTSSource",
"pythreatspec.pythreatspec.PyThreatspecReporter",
"pythreatspec.pythreatspec.PyThreatspecParser",
"re.escape"
] | [((720, 743), 'pythreatspec.pythreatspec.PyThreatspecParser', 'ts.PyThreatspecParser', ([], {}), '()\n', (741, 743), True, 'from pythreatspec import pythreatspec as ts\n'), ((1193, 1250), 'pythreatspec.pythreatspec.PyThreatspecReporter', 'ts.PyThreatspecReporter', (['self.parser', 'self.params.project'], {}), '(self.pa... |
"""
execute a notebook file hierarchy
run_notebooks orig_notebook_dir file_re
run_notebooks autograded "lab_wk9*ipynb"
"""
from pathlib import Path
import click
from .utils import working_directory
import shutil
import nbformat
from nbconvert.preprocessors import ExecutePreprocessor
def run_file(notebook_file, resu... | [
"click.argument",
"pathlib.Path",
"nbformat.read",
"nbformat.write",
"nbconvert.preprocessors.ExecutePreprocessor",
"click.command"
] | [((715, 730), 'click.command', 'click.command', ([], {}), '()\n', (728, 730), False, 'import click\n'), ((732, 775), 'click.argument', 'click.argument', (['"""notebook_folder"""'], {'type': 'str'}), "('notebook_folder', type=str)\n", (746, 775), False, 'import click\n'), ((776, 811), 'click.argument', 'click.argument',... |
"""
Twitch bot
TODO ( Soon™ ):
* Check if user has mod/sub priviliges when using commands
* Fetch moderator-list for channels from Twitch
* Check that the bot actually connects to twitch and the channels on startup
* Move commands.py and blacklist.py to json or something for easier ... | [
"socket.socket",
"re.compile",
"re.match",
"time.sleep",
"re.search"
] | [((632, 647), 'socket.socket', 'socket.socket', ([], {}), '()\n', (645, 647), False, 'import socket\n'), ((2064, 2130), 're.compile', 're.compile', (['"""^:\\\\w+!\\\\w+@\\\\w+\\\\.tmi\\\\.twitch\\\\.tv PRIVMSG #\\\\w+ :"""'], {}), "('^:\\\\w+!\\\\w+@\\\\w+\\\\.tmi\\\\.twitch\\\\.tv PRIVMSG #\\\\w+ :')\n", (2074, 2130)... |
from abc import ABC, abstractmethod
from kafka import KafkaProducer
from kafka import KafkaConsumer
import logging as logger
import json
import os
logger.basicConfig(format='%(asctime)s|[%(levelname)s]|File:%(filename)s|'
'Function:%(funcName)s|Line:%(lineno)s|%(message)s')
default_config = ... | [
"logging.basicConfig",
"json.dumps",
"os.environ.get",
"logging.info",
"logging.error"
] | [((148, 282), 'logging.basicConfig', 'logger.basicConfig', ([], {'format': '"""%(asctime)s|[%(levelname)s]|File:%(filename)s|Function:%(funcName)s|Line:%(lineno)s|%(message)s"""'}), "(format=\n '%(asctime)s|[%(levelname)s]|File:%(filename)s|Function:%(funcName)s|Line:%(lineno)s|%(message)s'\n )\n", (166, 282), Tr... |
#!/usr/local/bin/python3
import discord
import asyncio
import core.battle_lobby as battle_lobby
from core.common import SERVSET
CLIENT = discord.Client()
@CLIENT.event
async def on_ready():
print ('Logged in as '+CLIENT.user.name)
await setup_battle_lobby()
@CLIENT.event
async def on_reaction_add(reaction, ... | [
"discord.Client",
"core.battle_lobby.battle_lobby",
"asyncio.sleep"
] | [((139, 155), 'discord.Client', 'discord.Client', ([], {}), '()\n', (153, 155), False, 'import discord\n'), ((972, 999), 'core.battle_lobby.battle_lobby', 'battle_lobby.battle_lobby', ([], {}), '()\n', (997, 999), True, 'import core.battle_lobby as battle_lobby\n'), ((1704, 1720), 'asyncio.sleep', 'asyncio.sleep', (['(... |
"""
Blueprint for hello world.
"""
from flask import Blueprint
from flask_login import login_required
BP = Blueprint('main', __name__)
@BP.route('/')
@BP.route('/index')
@login_required
def index():
"""
Say hello.
:return: A greeting.
:rtype: str
"""
return "Hello, world"
| [
"flask.Blueprint"
] | [((109, 136), 'flask.Blueprint', 'Blueprint', (['"""main"""', '__name__'], {}), "('main', __name__)\n", (118, 136), False, 'from flask import Blueprint\n')] |
# Generated by Django 3.1 on 2021-04-30 18:27
from django.db import migrations, models
class Migration(migrations.Migration):
dependencies = [
('skip', '0011_auto_20210430_1746'),
]
operations = [
migrations.RemoveIndex(
model_name='alert',
name='alert_timestamp_... | [
"django.db.migrations.RemoveIndex",
"django.db.models.Index",
"django.db.migrations.RenameField"
] | [((230, 300), 'django.db.migrations.RemoveIndex', 'migrations.RemoveIndex', ([], {'model_name': '"""alert"""', 'name': '"""alert_timestamp_idx"""'}), "(model_name='alert', name='alert_timestamp_idx')\n", (252, 300), False, 'from django.db import migrations, models\n'), ((345, 443), 'django.db.migrations.RenameField', '... |
import math
import random
class BatchIterCANTM:
def __init__(self, dataIter, batch_size=32, filling_last_batch=False, postProcessor=None):
self.dataIter = dataIter
self.batch_size = batch_size
self.num_batches = self._get_num_batches()
self.filling_last_batch = filling_last_batch
... | [
"random.random",
"random.shuffle"
] | [((2085, 2113), 'random.shuffle', 'random.shuffle', (['self.fillter'], {}), '(self.fillter)\n', (2099, 2113), False, 'import random\n'), ((2593, 2608), 'random.random', 'random.random', ([], {}), '()\n', (2606, 2608), False, 'import random\n')] |
from importlib import import_module
from django.conf import settings
from django.conf.urls import include, url
from django.core.exceptions import ImproperlyConfigured
from tastypie.api import Api
from .api import TemporaryFileResource, ServiceResource, VariableResource
from .views import TemporaryFileUploadFormView, ... | [
"django.conf.urls.include",
"django.core.exceptions.ImproperlyConfigured",
"tastypie.api.Api"
] | [((1068, 1089), 'tastypie.api.Api', 'Api', ([], {'api_name': '"""admin"""'}), "(api_name='admin')\n", (1071, 1089), False, 'from tastypie.api import Api\n'), ((1553, 1570), 'django.conf.urls.include', 'include', (['api.urls'], {}), '(api.urls)\n', (1560, 1570), False, 'from django.conf.urls import include, url\n'), ((1... |
__all__ = [
"Embedding"
]
import torch.nn as nn
from ..utils import get_embeddings
class Embedding(nn.Embedding):
"""
别名::class:`fastNLP.modules.Embedding` :class:`fastNLP.modules.encoder.embedding.Embedding`
Embedding组件. 可以通过self.num_embeddings获取词表大小; self.embedding_dim获取embedding的维度"""
d... | [
"torch.nn.Dropout"
] | [((1483, 1502), 'torch.nn.Dropout', 'nn.Dropout', (['dropout'], {}), '(dropout)\n', (1493, 1502), True, 'import torch.nn as nn\n')] |
import base64
import io
from matplotlib import pyplot
import numpy as np
import rasterio
def read_raster_file(input_fn, band = 1):
with rasterio.open(input_fn) as src:
return src.read(band)
def plot_raster_layer(input_fn, band = 1, from_logits = True):
pyplot.figure(figsize = (10,10))
data ... | [
"matplotlib.pyplot.imshow",
"matplotlib.pyplot.savefig",
"rasterio.open",
"io.BytesIO",
"matplotlib.pyplot.close",
"numpy.exp",
"matplotlib.pyplot.figure",
"numpy.rint",
"matplotlib.pyplot.show"
] | [((278, 309), 'matplotlib.pyplot.figure', 'pyplot.figure', ([], {'figsize': '(10, 10)'}), '(figsize=(10, 10))\n', (291, 309), False, 'from matplotlib import pyplot\n'), ((407, 442), 'matplotlib.pyplot.imshow', 'pyplot.imshow', (['data'], {'cmap': '"""viridis"""'}), "(data, cmap='viridis')\n", (420, 442), False, 'from m... |
def main():
import pandas as pd
import sys
if len(sys.argv) != 5:
sys.exit("Error: Incorrect Number of arguments\nDesired Syntax: topsis <inputDataFile> <weights> <impacts> <outputFileName>")
try:
df = pd.read_csv(sys.argv[1])
except:
sys.exit("Error: File not Found... | [
"pandas.read_csv",
"sys.exit"
] | [((92, 230), 'sys.exit', 'sys.exit', (['"""Error: Incorrect Number of arguments\nDesired Syntax: topsis <inputDataFile> <weights> <impacts> <outputFileName>"""'], {}), '(\n """Error: Incorrect Number of arguments\nDesired Syntax: topsis <inputDataFile> <weights> <impacts> <outputFileName>"""\n )\n', (100, 230), F... |
import pandas as pd
data = pd.read_csv(r'./input.txt', sep=',', header=None)
data.columns = ['depth']
diff_single = data.diff()
count = diff_single.loc[diff_single['depth'] > 0]
nb_increased = count.shape[0]
print(nb_increased)
# Calculate sum of window quick and dirty
data['depth_1'] = data['depth'].shift(-1)
data... | [
"pandas.read_csv"
] | [((28, 76), 'pandas.read_csv', 'pd.read_csv', (['"""./input.txt"""'], {'sep': '""","""', 'header': 'None'}), "('./input.txt', sep=',', header=None)\n", (39, 76), True, 'import pandas as pd\n')] |
import image, network, rpc, sensor, struct
import time
import micropython
from pyb import Pin
from pyb import LED
red_led = LED(1)
green_led = LED(2)
blue_led = LED(3)
ir_led = LED(4)
def led_control(x):
if (x&1)==0: red_led.off()
elif (x&1)==1: red_led.on()
if (x&2)==0: green_led.off()
eli... | [
"sensor.skip_frames",
"sensor.set_auto_gain",
"pyb.LED",
"sensor.set_pixformat",
"pyb.Pin",
"sensor.set_auto_whitebal",
"sensor.get_fb",
"sensor.set_framesize",
"time.sleep",
"struct.pack",
"struct.unpack",
"sensor.width",
"sensor.reset",
"sensor.height",
"sensor.set_auto_exposure",
"s... | [((128, 134), 'pyb.LED', 'LED', (['(1)'], {}), '(1)\n', (131, 134), False, 'from pyb import LED\n'), ((147, 153), 'pyb.LED', 'LED', (['(2)'], {}), '(2)\n', (150, 153), False, 'from pyb import LED\n'), ((166, 172), 'pyb.LED', 'LED', (['(3)'], {}), '(3)\n', (169, 172), False, 'from pyb import LED\n'), ((185, 191), 'pyb.L... |
import math
import re
from collections import defaultdict
from GlyphsApp import Glyphs, OFFCURVE, GSLayer
from Foundation import NSPoint
class layerPositions:
def __init__(self, l, all_indic_headlines=None):
self.layer = l
self.layer_flat = l.copyDecomposedLayer()
self.layer_flat.removeOv... | [
"re.compile",
"Foundation.NSPoint",
"math.radians",
"GlyphsApp.GSLayer",
"collections.defaultdict"
] | [((596, 613), 'collections.defaultdict', 'defaultdict', (['dict'], {}), '(dict)\n', (607, 613), False, 'from collections import defaultdict\n'), ((639, 662), 're.compile', 're.compile', (['"""^[xy]pos_"""'], {}), "('^[xy]pos_')\n", (649, 662), False, 'import re\n'), ((7105, 7122), 'collections.defaultdict', 'defaultdic... |
#
# http://www.angelfire.com/ego2/idleloop/archives/mbp_file_format.txt
#
# FMT = '>4sIiIIIiIiBBBBiiiiII'
FMT = '>4sIiH2BIIiI8B4i2I'
TYPES = ('DATA', 'BKMK', 'PUBL', 'COVE', 'CATE', 'ABST',
'GENR', 'TITL', 'AUTH')
TAGS = ('EBAR', 'EBVS', 'ADQM')
import glob
import struct
from . import palm
for f in (glob.gl... | [
"struct.unpack",
"glob.glob"
] | [((313, 355), 'glob.glob', 'glob.glob', (['"""/media/Kindle/documents/*.mbp"""'], {}), "('/media/Kindle/documents/*.mbp')\n", (322, 355), False, 'import glob\n'), ((564, 598), 'struct.unpack', 'struct.unpack', (['""">I"""', 'rec.data[4:8]'], {}), "('>I', rec.data[4:8])\n", (577, 598), False, 'import struct\n'), ((806, ... |
#!/bin/python
#sca_test.py
import matplotlib.pyplot as plt
import coevo2 as ce
import itertools as it
import numpy as np
import copy
import time
reload(ce)
names = ['glgA', 'glgC', 'cydA', 'cydB']
algPath = 'TestSet/eggNOG_aligns/slice_0.9/'
prots = ce.prots_from_scratch(names,path2alg=algPath)
ps = ce.ProtSet(prots... | [
"coevo2.ProtSet",
"itertools.izip",
"coevo2.PhyloSet",
"coevo2.sca",
"numpy.save",
"coevo2.prots_from_scratch"
] | [((253, 299), 'coevo2.prots_from_scratch', 'ce.prots_from_scratch', (['names'], {'path2alg': 'algPath'}), '(names, path2alg=algPath)\n', (274, 299), True, 'import coevo2 as ce\n'), ((304, 328), 'coevo2.ProtSet', 'ce.ProtSet', (['prots', 'names'], {}), '(prots, names)\n', (314, 328), True, 'import coevo2 as ce\n'), ((42... |
import os
import re
import requests
from invoke import task
def _get_aws_token(c):
token = os.getenv("AWS_TOKEN")
if not token:
token = c.run("aws ecr get-authorization-token --output text "
"--query 'authorizationData[].authorizationToken'", hide=True).stdout.strip()
return ... | [
"os.environ.items",
"os.path.exists",
"os.getenv",
"re.split"
] | [((97, 119), 'os.getenv', 'os.getenv', (['"""AWS_TOKEN"""'], {}), "('AWS_TOKEN')\n", (106, 119), False, 'import os\n'), ((366, 391), 'os.getenv', 'os.getenv', (['"""GCLOUD_TOKEN"""'], {}), "('GCLOUD_TOKEN')\n", (375, 391), False, 'import os\n'), ((4004, 4022), 'os.environ.items', 'os.environ.items', ([], {}), '()\n', (... |
#!/usr/bin/env python
from __future__ import with_statement
from suds.plugin import MessagePlugin
from lxml import etree
from suds.bindings.binding import envns
from suds.wsse import wsuns, dsns, wssens
from libxml2_wrapper import LibXML2ParsedDocument
from xmlsec_wrapper import XmlSecSignatureContext, init_xmlsec, de... | [
"xmlsec.addIDs",
"lxml.etree.XPath",
"OpenSSL.crypto.dump_certificate",
"lxml.etree.SubElement",
"xmlsec_wrapper.XmlSecSignatureContext",
"libxml2_wrapper.LibXML2ParsedDocument",
"OpenSSL.crypto.load_privatekey",
"xmlsec_wrapper.deinit_xmlsec",
"uuid.uuid4",
"lxml.etree.fromstring",
"xmlsec_wrap... | [((897, 965), 'lxml.etree.XPath', 'etree.XPath', (['"""/SOAP-ENV:Envelope/SOAP-ENV:Body"""'], {'namespaces': 'LXML_ENV'}), "('/SOAP-ENV:Envelope/SOAP-ENV:Body', namespaces=LXML_ENV)\n", (908, 965), False, 'from lxml import etree\n'), ((981, 1051), 'lxml.etree.XPath', 'etree.XPath', (['"""/SOAP-ENV:Envelope/SOAP-ENV:Hea... |
#!/usr/bin/env python3
import re
inputFile = open("5.in",'r')
inputContents = inputFile.readlines()
def isNice(_str):
v = [ord(c) for c in _str if c in "aeiou"]
repeated = re.search(r'([a-z])\1{1,}', _str)
forbidden = re.search(r'(ab|cd|pq|xy)', _str)
return (len(v) >= 3) and (repeated is not None) a... | [
"re.search"
] | [((182, 215), 're.search', 're.search', (['"""([a-z])\\\\1{1,}"""', '_str'], {}), "('([a-z])\\\\1{1,}', _str)\n", (191, 215), False, 'import re\n'), ((232, 264), 're.search', 're.search', (['"""(ab|cd|pq|xy)"""', '_str'], {}), "('(ab|cd|pq|xy)', _str)\n", (241, 264), False, 'import re\n')] |
from xnat_dashboards.data_cleaning import graph_generator
from xnat_dashboards import config
config.DASHBOARD_CONFIG_PATH = 'xnat_dashboards/config/dashboard_config.json'
config.PICKLE_PATH = 'xnat_dashboards/config/general.pickle'
def create_mocker(
mocker, username, data, role, graph_visibility, return_get_pr... | [
"xnat_dashboards.data_cleaning.graph_generator.GraphGenerator"
] | [((790, 863), 'xnat_dashboards.data_cleaning.graph_generator.GraphGenerator', 'graph_generator.GraphGenerator', (['username', 'role', 'data', "{role: ['p1', 'y']}"], {}), "(username, role, data, {role: ['p1', 'y']})\n", (820, 863), False, 'from xnat_dashboards.data_cleaning import graph_generator\n')] |
import pigpio
import signal
import requests
import logging
import json
import os
import sys
import threading
from time import sleep
from uuid import uuid1
# Global variables
BUTTON_GPIO = 23
LED_GPIO = 21
is_blinking = False
pi = pigpio.pi()
dweetFile = 'dweet_name.txt'
dweetURL = 'https://dweet.io'
# States
stateON ... | [
"logging.basicConfig",
"os.path.exists",
"logging.getLogger",
"signal.signal",
"requests.get",
"time.sleep",
"uuid.uuid1",
"pigpio.pi",
"sys.exit"
] | [((231, 242), 'pigpio.pi', 'pigpio.pi', ([], {}), '()\n', (240, 242), False, 'import pigpio\n'), ((407, 449), 'logging.basicConfig', 'logging.basicConfig', ([], {'level': 'logging.WARNING'}), '(level=logging.WARNING)\n', (426, 449), False, 'import logging\n'), ((491, 516), 'logging.getLogger', 'logging.getLogger', (['"... |