code stringlengths 22 1.05M | apis listlengths 1 3.31k | extract_api stringlengths 75 3.25M |
|---|---|---|
# Test file for enum checker
from enum import Enum
from six import with_metaclass
from azure.core import CaseInsensitiveEnumMeta
class EnumPython2(with_metaclass(CaseInsensitiveEnumMeta, str, Enum)):
ONE = "one"
TWO = "two"
| [
"six.with_metaclass"
] | [((148, 198), 'six.with_metaclass', 'with_metaclass', (['CaseInsensitiveEnumMeta', 'str', 'Enum'], {}), '(CaseInsensitiveEnumMeta, str, Enum)\n', (162, 198), False, 'from six import with_metaclass\n')] |
from django import forms
gender = [('male', 'M'), ('female', 'F')]
response = [('1', 'yes'), ('0', 'no')]
time = [('1', 'one'), ('2', 'two'), ('3', 'three'), ('4', 'four')]
education = [('0', 'zero'),('1', 'zero'), ('2', 'two'), ('3', 'three'), ('4', 'four')]
rating = [('1', 'one'), ('2', 'two'), ('3', 'three'), ('4',... | [
"django.forms.Select",
"django.forms.CharField"
] | [((477, 508), 'django.forms.CharField', 'forms.CharField', ([], {'max_length': '(254)'}), '(max_length=254)\n', (492, 508), False, 'from django import forms\n'), ((527, 558), 'django.forms.CharField', 'forms.CharField', ([], {'max_length': '(254)'}), '(max_length=254)\n', (542, 558), False, 'from django import forms\n'... |
'''
Main function to be called from GCE's cloud function
This function is in charge of adding training data to
the datastore for later generation of models and feature study
'''
import sys
import os
import time
import numpy as np
from google.cloud import datastore
from google.cloud import storage
from google.api_core... | [
"google.cloud.storage.Client",
"os.path.exists",
"sys.path.insert",
"os.makedirs",
"google.cloud.datastore.Entity",
"google.cloud.datastore.Client",
"imports.video_asset_processor.VideoAssetProcessor",
"numpy.around",
"time.time",
"google.api_core.retry.if_exception_type",
"google.api_core.retry... | [((381, 410), 'sys.path.insert', 'sys.path.insert', (['(0)', '"""imports"""'], {}), "(0, 'imports')\n", (396, 410), False, 'import sys\n'), ((494, 512), 'google.cloud.datastore.Client', 'datastore.Client', ([], {}), '()\n', (510, 512), False, 'from google.cloud import datastore\n'), ((530, 546), 'google.cloud.storage.C... |
import Gerador_de_senhas.Defs as ge
import PySimpleGUI as sg
class Gerador:
sg.theme('DarkPurple1')
def __init__(self):
layout = [
[sg.Checkbox('Numeros', key='sonumeros'), sg.Text(size=(3, 1)), sg.Checkbox('Letras', key='soletras'),
sg.Text(size=(3, 1)), sg.Checkbox('Simbolos... | [
"Gerador_de_senhas.Defs.truefalse",
"PySimpleGUI.Checkbox",
"PySimpleGUI.Text",
"PySimpleGUI.Button",
"PySimpleGUI.theme",
"PySimpleGUI.Output",
"PySimpleGUI.Window"
] | [((82, 105), 'PySimpleGUI.theme', 'sg.theme', (['"""DarkPurple1"""'], {}), "('DarkPurple1')\n", (90, 105), True, 'import PySimpleGUI as sg\n'), ((163, 202), 'PySimpleGUI.Checkbox', 'sg.Checkbox', (['"""Numeros"""'], {'key': '"""sonumeros"""'}), "('Numeros', key='sonumeros')\n", (174, 202), True, 'import PySimpleGUI as ... |
#!/usr/bin/env python3.5
import sys
import os
import logging
import numpy as np
import musm
from sklearn.utils import check_random_state
from textwrap import dedent
#1Social Choice
_LOG = musm.get_logger('adt17')
PROBLEMS = {
'synthetic': musm.Synthetic,
'pc': musm.PC,
}
USERS = {
'noiseless': musm.Noi... | [
"logging.basicConfig",
"numpy.abs",
"textwrap.dedent",
"sklearn.utils.check_random_state",
"logging.StreamHandler",
"argparse.ArgumentParser",
"musm.musm",
"musm.dump",
"numpy.append",
"numpy.array",
"numpy.zeros",
"numpy.dot",
"musm.get_logger",
"numpy.seterr",
"musm.subdict",
"musm.l... | [((191, 215), 'musm.get_logger', 'musm.get_logger', (['"""adt17"""'], {}), "('adt17')\n", (206, 215), False, 'import musm\n'), ((1014, 1036), 'numpy.array', 'np.array', (['w'], {'copy': '(True)'}), '(w, copy=True)\n', (1022, 1036), True, 'import numpy as np\n'), ((1965, 1986), 'sklearn.utils.check_random_state', 'check... |
# -*- coding: utf-8 -*-
# Copyright (c) 2021, <NAME> and contributors
# For license information, please see license.txt
from __future__ import unicode_literals
import frappe
from frappe.model.document import Document
from frappe.model.mapper import get_mapped_doc
class RentRequest(Document):
def validate(self):
fr... | [
"frappe.model.mapper.get_mapped_doc",
"frappe.whitelist",
"frappe.msgprint"
] | [((370, 388), 'frappe.whitelist', 'frappe.whitelist', ([], {}), '()\n', (386, 388), False, 'import frappe\n'), ((633, 740), 'frappe.model.mapper.get_mapped_doc', 'get_mapped_doc', (['"""Rent Request"""', 'source_name', "{'Rent Request': {'doctype': 'Rent Contract'}}", 'target_doc'], {}), "('Rent Request', source_name, ... |
#!/usr/bin/env python2
# -*- coding: utf-8 -*-
"""
Created on Fri Aug 4 15:57:47 2017
@author: wangronin
"""
import pdb
import numpy as np
from deap import benchmarks
from GaussianProcess_old import GaussianProcess_extra as GaussianProcess
from BayesOpt import BayesOpt, RandomForest, RrandomForest
np.random.seed(1... | [
"numpy.ones",
"numpy.random.rand",
"GaussianProcess_old.GaussianProcess_extra",
"deap.benchmarks.himmelblau",
"numpy.array",
"numpy.random.seed",
"BayesOpt.BayesOpt"
] | [((304, 321), 'numpy.random.seed', 'np.random.seed', (['(1)'], {}), '(1)\n', (318, 321), True, 'import numpy as np\n'), ((416, 436), 'numpy.array', 'np.array', (['([-6] * dim)'], {}), '([-6] * dim)\n', (424, 436), True, 'import numpy as np\n'), ((442, 461), 'numpy.array', 'np.array', (['([6] * dim)'], {}), '([6] * dim)... |
import unittest
import sys
sys.path.append("../")
from store.store import Store
from store.neo4jstore import Neo4jStore
from store.sqlitestore import SqliteStore
from neo4j.v1 import GraphDatabase, basic_auth
#TODO fix tests
'''
class TestStore(unittest.TestCase):
def setUp(self):
self.store = Neo4jStore()
... | [
"unittest.main",
"sys.path.append"
] | [((27, 49), 'sys.path.append', 'sys.path.append', (['"""../"""'], {}), "('../')\n", (42, 49), False, 'import sys\n'), ((2662, 2677), 'unittest.main', 'unittest.main', ([], {}), '()\n', (2675, 2677), False, 'import unittest\n')] |
from loom.tables import InputTable, DerivedTable
from loom.fields import RawField, DerivedField
t1 = InputTable("main", "table_1", "Table 1", "t1")
RawField(t1, "id", "Id")
RawField(t1, "value", "Value")
RawField(t1, "income", "Customer Income")
t3 = InputTable("main", "table_1", "Table 1", "t3")
RawField(t3... | [
"loom.fields.DerivedField",
"loom.tables.DerivedTable",
"loom.fields.RawField",
"loom.tables.InputTable"
] | [((105, 151), 'loom.tables.InputTable', 'InputTable', (['"""main"""', '"""table_1"""', '"""Table 1"""', '"""t1"""'], {}), "('main', 'table_1', 'Table 1', 't1')\n", (115, 151), False, 'from loom.tables import InputTable, DerivedTable\n'), ((153, 177), 'loom.fields.RawField', 'RawField', (['t1', '"""id"""', '"""Id"""'], ... |
# Generated by Django 2.0.2 on 2018-03-12 11:45
import datetime
import django.contrib.gis.db.models.fields
from django.db import migrations, models
from django.utils.timezone import utc
class Migration(migrations.Migration):
dependencies = [
('events', '0004_auto_20180309_1804'),
]
operations =... | [
"datetime.datetime"
] | [((652, 713), 'datetime.datetime', 'datetime.datetime', (['(2018)', '(3)', '(12)', '(11)', '(45)', '(2)', '(775370)'], {'tzinfo': 'utc'}), '(2018, 3, 12, 11, 45, 2, 775370, tzinfo=utc)\n', (669, 713), False, 'import datetime\n')] |
#NOTE: for this script to work you have to first sign-in on Whatsapp web using QR code
from splinter import Browser
browser = Browser()
browser.visit('https://web.whatsapp.com/')
input('press enter to continue') #to make sure page is completely loaded
count=20;
friend_list=["friend 1","friend 2","friend 3"] #Wha... | [
"splinter.Browser"
] | [((128, 137), 'splinter.Browser', 'Browser', ([], {}), '()\n', (135, 137), False, 'from splinter import Browser\n')] |
import requests
from common import *
def send_request(url):
try:
res = requests.get(url)
res.raise_for_status()
except Exception as exc:
print('Generated an exception: %s' % exc)
return ERR_WEB_ERROR, exc
return ERR_SUCCESS, res.text
| [
"requests.get"
] | [((86, 103), 'requests.get', 'requests.get', (['url'], {}), '(url)\n', (98, 103), False, 'import requests\n')] |
import xarray as xr
from .basic import zonal_mean, zonal_wave_coeffs, zonal_wave_covariance
def _print_if_true(msg, condition, **kwargs):
r"""Simple utility function to print only if the given condition is True.
Parameters
----------
msg : string
The message to print
condition : bool
... | [
"xarray.Dataset"
] | [((6901, 6937), 'xarray.Dataset', 'xr.Dataset', (['inter'], {'coords': 'out_coords'}), '(inter, coords=out_coords)\n', (6911, 6937), True, 'import xarray as xr\n')] |
# -*- coding: utf-8 -*-
#
# Copyright (C) 2022 Graz University of Technology.
#
# invenio-records-lom is free software; you can redistribute it and/or modify it
# under the terms of the MIT License; see LICENSE file for more details.
"""OAI-PMH serializers for LOM-records."""
from flask import current_app, g
from inv... | [
"invenio_pidstore.errors.PIDDoesNotExistError",
"invenio_pidstore.models.PersistentIdentifier.get_by_object",
"flask.current_app.config.get"
] | [((1110, 1208), 'invenio_pidstore.models.PersistentIdentifier.get_by_object', 'PersistentIdentifier.get_by_object', ([], {'pid_type': '"""lomid"""', 'object_uuid': 'record_id', 'object_type': '"""rec"""'}), "(pid_type='lomid', object_uuid=record_id,\n object_type='rec')\n", (1144, 1208), False, 'from invenio_pidstor... |
import numpy as np
from compmech.stiffpanelbay import StiffPanelBay
from compmech.analysis import freq, lb
def test_freq_models():
print('Testing frequency analysis for StiffPanelBay with 2 plates')
# From Table 4 of
# Lee and Lee. "Vibration analysis of anisotropic plates with eccentric
# stiffen... | [
"compmech.stiffpanelbay.StiffPanelBay",
"numpy.allclose",
"compmech.analysis.lb",
"numpy.isclose",
"compmech.analysis.freq"
] | [((1542, 1557), 'compmech.stiffpanelbay.StiffPanelBay', 'StiffPanelBay', ([], {}), '()\n', (1555, 1557), False, 'from compmech.stiffpanelbay import StiffPanelBay\n'), ((2164, 2187), 'compmech.analysis.lb', 'lb', (['k0', 'kG'], {'silent': '(True)'}), '(k0, kG, silent=True)\n', (2166, 2187), False, 'from compmech.analysi... |
"""
Script to export a PyTorch-based Pyrado policy to C++
"""
import numpy as np
import torch as to
from rcsenv import ControlPolicy
from pyrado.policies.linear import LinearPolicy
from pyrado.policies.rnn import RNNPolicy
from pyrado.spaces.box import BoxSpace
from pyrado.utils.data_types import EnvSpec
from pyrado.p... | [
"torch.get_default_dtype",
"torch.set_printoptions",
"rcsenv.ControlPolicy",
"torch.set_default_dtype",
"numpy.array",
"pyrado.policies.features.FeatureStack",
"pyrado.spaces.box.BoxSpace",
"numpy.set_printoptions"
] | [((963, 994), 'torch.set_default_dtype', 'to.set_default_dtype', (['to.double'], {}), '(to.double)\n', (983, 994), True, 'import torch as to\n'), ((1346, 1377), 'rcsenv.ControlPolicy', 'ControlPolicy', (['"""torch"""', 'tmpfile'], {}), "('torch', tmpfile)\n", (1359, 1377), False, 'from rcsenv import ControlPolicy\n'), ... |
import logging
from casymda.blocks.entity import Entity
from simpy.core import Environment
class Order(Entity):
def __init__(self, env: Environment, name: str):
super().__init__(env, name)
self._time_of_acceptance = -1
self._initial_eta = -1
self._eta = -1
self._ready_at ... | [
"logging.info"
] | [((2029, 2131), 'logging.info', 'logging.info', (['f"""order update - name: {name}, attribute: {attribute}, value: {value}, t: {t}"""'], {}), "(\n f'order update - name: {name}, attribute: {attribute}, value: {value}, t: {t}'\n )\n", (2041, 2131), False, 'import logging\n')] |
#!/usr/bin/env python
# -*- coding: utf-8 -*-
"""Tests for delta functions."""
from unittest import TestCase
from hiispider import delta
from pprint import pprint
import os
import random
import time
from datetime import datetime
from hiiguid import HiiGUID
srt = lambda l: list(sorted(l))
DATAPATH = os.path.abspath(... | [
"os.path.dirname",
"hiispider.delta.Autogenerator",
"datetime.datetime.fromtimestamp",
"time.time"
] | [((595, 616), 'hiispider.delta.Autogenerator', 'delta.Autogenerator', ([], {}), '()\n', (614, 616), False, 'from hiispider import delta\n'), ((333, 358), 'os.path.dirname', 'os.path.dirname', (['__file__'], {}), '(__file__)\n', (348, 358), False, 'import os\n'), ((792, 813), 'hiispider.delta.Autogenerator', 'delta.Auto... |
import logging
from pymongo import MongoClient
from scrapy.exceptions import CloseSpider
class MongoDBPipeline(object):
config = {
'uri': 'mongodb://localhost:270017',
'database': 'scrapyu',
'collection': 'items',
'unique_key': None,
'buffer_length': 0,
}
def ope... | [
"logging.getLogger",
"pymongo.MongoClient",
"scrapy.exceptions.CloseSpider"
] | [((366, 410), 'logging.getLogger', 'logging.getLogger', (['"""scrapyu.MongoDBPipeline"""'], {}), "('scrapyu.MongoDBPipeline')\n", (383, 410), False, 'import logging\n'), ((506, 532), 'pymongo.MongoClient', 'MongoClient', (["config['uri']"], {}), "(config['uri'])\n", (517, 532), False, 'from pymongo import MongoClient\n... |
import torch.nn as nn
import torch
import os
class BasicConv3d(nn.Module):
def __init__(self, in_planes, out_planes, kernel_size, stride, padding=0):
super(BasicConv3d, self).__init__()
self.conv = nn.Conv3d(in_planes, out_planes, kernel_size=kernel_size, stride=stride, padding=padding, bi... | [
"torch.nn.Dropout",
"torch.nn.init.constant_",
"torch.nn.LeakyReLU",
"torch.nn.Softmax",
"torch.rand",
"torch.load",
"torch.nn.MaxPool3d",
"torch.mean",
"torch.cat",
"torch.nn.AdaptiveAvgPool3d",
"torch.nn.Linear",
"torch.nn.init.normal_",
"torch.nn.Conv3d"
] | [((228, 333), 'torch.nn.Conv3d', 'nn.Conv3d', (['in_planes', 'out_planes'], {'kernel_size': 'kernel_size', 'stride': 'stride', 'padding': 'padding', 'bias': '(False)'}), '(in_planes, out_planes, kernel_size=kernel_size, stride=stride,\n padding=padding, bias=False)\n', (237, 333), True, 'import torch.nn as nn\n'), (... |
#
# Copyright 2019-2020 <NAME>
#
# Licensed under the Apache License, Version 2.0 (the "License");
# you may not use this file except in compliance with the License.
# You may obtain a copy of the License at
#
# http://www.apache.org/licenses/LICENSE-2.0
#
# Unless required by applicable law or agreed to in writing... | [
"logging.getLogger",
"lzma.LZMAFile",
"gzip.GzipFile",
"bz2.BZ2File",
"zstandard.ZstdDecompressor"
] | [((1011, 1030), 'logging.getLogger', 'getLogger', (['__name__'], {}), '(__name__)\n', (1020, 1030), False, 'from logging import getLogger\n'), ((1498, 1524), 'gzip.GzipFile', 'GzipFile', ([], {'fileobj': 'self._fp'}), '(fileobj=self._fp)\n', (1506, 1524), False, 'from gzip import GzipFile\n'), ((1601, 1618), 'bz2.BZ2Fi... |
# ___________________________________________________________________________
#
# Pyomo: Python Optimization Modeling Objects
# Copyright 2017 National Technology and Engineering Solutions of Sandia, LLC
# Under the terms of Contract DE-NA0003525 with National Technology and
# Engineering Solutions of Sandia, LLC... | [
"mpisppy.utils.pysp_model.pysp_model._get_derived_nonant_list",
"mpisppy.utils.pysp_model.pysp_model._get_nonant_list",
"pyomo.common.dependencies.networkx.Graph",
"pyomo.common.unittest.main",
"pyomo.common.unittest.skipIf",
"pyomo.core.Objective",
"mpisppy.utils.pysp_model.tree_structure_model.CreateC... | [((17450, 17511), 'pyomo.common.unittest.skipIf', 'unittest.skipIf', (['(not has_networkx)', '"""Requires networkx module"""'], {}), "(not has_networkx, 'Requires networkx module')\n", (17465, 17511), True, 'import pyomo.common.unittest as unittest\n'), ((34737, 34752), 'pyomo.common.unittest.main', 'unittest.main', ([... |
# -*- coding: utf-8 -*-
# Copyright 2013-2014 Eucalyptus Systems, Inc.
#
# Redistribution and use of this software in source and binary forms,
# with or without modification, are permitted provided that the following
# conditions are met:
#
# Redistributions of source code must retain the above copyright notice,
# this... | [
"boto.ec2.elb.connect_to_region",
"boto.ec2.autoscale.connect_to_region",
"urllib2.urlopen",
"boto.ec2.connect_to_region",
"base64.b64encode",
"boto.sts.credentials.Credentials",
"xml.sax.parseString",
"urllib2.Request",
"boto.regioninfo.RegionInfo",
"boto.ec2.cloudwatch.connect_to_region",
"bot... | [((2439, 2468), 'pyramid.security.authenticated_userid', 'authenticated_userid', (['request'], {}), '(request)\n', (2459, 2468), False, 'from pyramid.security import Authenticated, authenticated_userid\n'), ((9130, 9160), 'urllib2.Request', 'urllib2.Request', (['self.auth_url'], {}), '(self.auth_url)\n', (9145, 9160), ... |
# Copyright (c) 2021 <NAME> <<EMAIL>>
# Author: <NAME> <<EMAIL>>
# See LICENSE file
import urwid
from .. import main_loop as shared_main_loop
from .error_dialog import ErrorDialog
from .info_dialog import InfoDialog
from .quit_dialog import QuitDialog
class SessionPopupLauncher(urwid.PopUpLauncher):
DEFAULT_WR =... | [
"urwid.ExitMainLoop",
"urwid.LineBox",
"urwid.Filler",
"urwid.connect_signal",
"urwid.Text"
] | [((1329, 1349), 'urwid.ExitMainLoop', 'urwid.ExitMainLoop', ([], {}), '()\n', (1347, 1349), False, 'import urwid\n'), ((1615, 1672), 'urwid.connect_signal', 'urwid.connect_signal', (['dialog', 'dialog.SIGNAL_OK', 'self.quit'], {}), '(dialog, dialog.SIGNAL_OK, self.quit)\n', (1635, 1672), False, 'import urwid\n'), ((169... |
#Adicione ao módulo moeda.py criado nos desafios anteriores, uma função chamada resumo(), que mostre na tela algumas
#informaçôes geradas pelas funções que já temos no módulo criado até aqui.
import moeda
p = float(input('Preço: R$'))
moeda.resumo(p, 20, 12)
| [
"moeda.resumo"
] | [((237, 260), 'moeda.resumo', 'moeda.resumo', (['p', '(20)', '(12)'], {}), '(p, 20, 12)\n', (249, 260), False, 'import moeda\n')] |
# The Demo to test the Cozmo's camera image
import asyncio
import time
import os
import cozmo
# BUFF_PATH = "/home/wmh/work/seqbuff/"
BUFF_PATH = "/Users/wty/work/TestSeq/MoveInLine5/"
BUFF_LENGTH = 10000
last_image = None
def loop(robot: cozmo.robot.Robot):
inc = 1
HeadAngle = 0
robot.set_lift_heigh... | [
"cozmo.run_program",
"cozmo.util.degrees",
"time.time",
"time.sleep"
] | [((3607, 3647), 'cozmo.run_program', 'cozmo.run_program', (['loop'], {'use_viewer': '(True)'}), '(loop, use_viewer=True)\n', (3624, 3647), False, 'import cozmo\n'), ((2571, 2587), 'time.sleep', 'time.sleep', (['(0.19)'], {}), '(0.19)\n', (2581, 2587), False, 'import time\n'), ((3468, 3484), 'time.sleep', 'time.sleep', ... |
from django.contrib.admin import ModelAdmin
from public_admin.sites import PublicAdminSite
class PublicModelAdmin(ModelAdmin):
"""This mimics the Django's native ModelAdmin but filters URLs that should
not exist in a public admin, and deals with request-based permissions."""
def has_view_permission(self,... | [
"public_admin.sites.PublicAdminSite.valid_url"
] | [((1035, 1065), 'public_admin.sites.PublicAdminSite.valid_url', 'PublicAdminSite.valid_url', (['url'], {}), '(url)\n', (1060, 1065), False, 'from public_admin.sites import PublicAdminSite\n')] |
import dill
import torch
from torchtext.datasets import TranslationDataset
from translation.transformer import Transformer
from translation.translate import translate_dataset
if __name__ == "__main__":
device = torch.device('cuda' if torch.cuda.is_available() else 'cpu')
src_field_f = open("data/SRC_Field.pt"... | [
"torchtext.datasets.TranslationDataset",
"translation.translate.translate_dataset",
"torch.load",
"torch.cuda.is_available",
"dill.load"
] | [((388, 410), 'dill.load', 'dill.load', (['src_field_f'], {}), '(src_field_f)\n', (397, 410), False, 'import dill\n'), ((421, 443), 'dill.load', 'dill.load', (['tgt_field_f'], {}), '(tgt_field_f)\n', (430, 443), False, 'import dill\n'), ((456, 544), 'torchtext.datasets.TranslationDataset', 'TranslationDataset', (['"""d... |
from networkx.algorithms.components.connected import node_connected_component as nx_node_connected_component
from networkx.algorithms.components.connected import connected_components as nx_connected_components
import pygfa.gfa # required for GFAError (gives error otherwise)
def nodes_connected_component(gfa_, nid):
... | [
"networkx.algorithms.components.connected.node_connected_component",
"networkx.algorithms.components.connected.connected_components"
] | [((571, 616), 'networkx.algorithms.components.connected.node_connected_component', 'nx_node_connected_component', (['gfa_._graph', 'nid'], {}), '(gfa_._graph, nid)\n', (598, 616), True, 'from networkx.algorithms.components.connected import node_connected_component as nx_node_connected_component\n'), ((799, 835), 'netwo... |
"""
hello.py: Simple example using write
"""
#pylint: disable-msg=import-error
from turtleplotbot import TurtlePlotBot
def main():
"""
Write "Hello!"
"""
bot = TurtlePlotBot()
bot.setscale(2)
bot.write("Hello!", "fonts/scripts.fnt")
bot.done()
main()
__import__("menu") # optional ret... | [
"turtleplotbot.TurtlePlotBot"
] | [((177, 192), 'turtleplotbot.TurtlePlotBot', 'TurtlePlotBot', ([], {}), '()\n', (190, 192), False, 'from turtleplotbot import TurtlePlotBot\n')] |
# -*- coding: utf-8 -*-
from snakemake.shell import shell
paths_tsv = " ".join(snakemake.input.tsv)
shell(
r"""
export TMPDIR=$(mktemp -d)
trap "rm -rf $TMPDIR" ERR EXIT
export THEANO_FLAGS="base_compiledir=$TMPDIR/theano_compile_dir"
PRIORS=$TMPDIR/ploidy_priors.tsv
echo -e "CONTIG_NAME\tPLOIDY_PRIOR_0\tPLOID... | [
"snakemake.shell.shell"
] | [((103, 874), 'snakemake.shell.shell', 'shell', (['"""\nexport TMPDIR=$(mktemp -d)\ntrap "rm -rf $TMPDIR" ERR EXIT\n\nexport THEANO_FLAGS="base_compiledir=$TMPDIR/theano_compile_dir"\n\nPRIORS=$TMPDIR/ploidy_priors.tsv\necho -e "CONTIG_NAME\\\\tPLOIDY_PRIOR_0\\\\tPLOIDY_PRIOR_1\\\\tPLOIDY_PRIOR_2\\\\tPLOIDY_PRIOR_3" \\... |
# Licensed to the Apache Software Foundation (ASF) under one
# or more contributor license agreements. See the NOTICE file
# distributed with this work for additional information
# regarding copyright ownership. The ASF licenses this file
# to you under the Apache License, Version 2.0 (the
# "License"); you may not u... | [
"tvm.target.override_native_generic_func",
"tvm.relay.op.mlas_packb",
"tvm.tir.expr.IntImm",
"tvm.target.Target.current",
"tvm.relay.op.mlas_matmul"
] | [((1070, 1133), 'tvm.target.override_native_generic_func', 'tvm.target.override_native_generic_func', (['"""mlas_matmul_strategy"""'], {}), "('mlas_matmul_strategy')\n", (1109, 1133), False, 'import tvm\n'), ((3907, 3969), 'tvm.target.override_native_generic_func', 'tvm.target.override_native_generic_func', (['"""mlas_... |
from flask import Flask, render_template, url_for, request
import numpy as np
import pandas as pd
import pickle
import warnings
warnings.filterwarnings("ignore")
app = Flask(__name__)
@app.route('/')
def index():
return render_template("index.html")
@app.route('/predict', methods=['GET', 'POST'])
def predict(... | [
"flask.render_template",
"warnings.filterwarnings",
"pandas.DataFrame",
"flask.Flask"
] | [((130, 163), 'warnings.filterwarnings', 'warnings.filterwarnings', (['"""ignore"""'], {}), "('ignore')\n", (153, 163), False, 'import warnings\n'), ((170, 185), 'flask.Flask', 'Flask', (['__name__'], {}), '(__name__)\n', (175, 185), False, 'from flask import Flask, render_template, url_for, request\n'), ((228, 257), '... |
# Standalone GUI Applet for creating levels
import os
os.environ['pg_HIDE_SUPPORT_PROMPT'] = "hide"
import pygame as pg
from multiprocessing import Process
from ui_helpers import *
from levels import levels, read_level, write_level, LEVELS_DIR
from main import play_level
from engine import Level, board_copy
# --- ... | [
"pygame.display.set_caption",
"engine.board_copy",
"pygame.key.get_mods",
"pygame.Surface",
"pygame.event.get",
"pygame.display.set_mode",
"pygame.event.Event",
"pygame.time.Clock",
"pygame.display.update",
"pygame.Rect",
"levels.read_level",
"levels.write_level"
] | [((2578, 2649), 'pygame.Surface', 'pg.Surface', (['(palette_viewport_rect.width, palette_viewport_rect.height)'], {}), '((palette_viewport_rect.width, palette_viewport_rect.height))\n', (2588, 2649), True, 'import pygame as pg\n'), ((3211, 3230), 'pygame.display.update', 'pg.display.update', ([], {}), '()\n', (3228, 32... |
# -*- coding: utf-8 -*-
import tensorflow as tf
import matplotlib.pyplot as plt
import matplotlib as mpl
import simulators
import derivatives
import utils
import books
import hedge_models
import preprocessing
import approximators
from constants import FLOAT_DTYPE
class BrownianMotion(simulators.GBM):
def __init_... | [
"matplotlib.pyplot.ylabel",
"utils.norm_pdf",
"hedge_models.NeuralHedge",
"utils.norm_cdf",
"matplotlib.pyplot.xlabel",
"simulators.GBM",
"hedge_models.LinearFeatureHedge",
"matplotlib.pyplot.savefig",
"matplotlib.pyplot.ioff",
"derivatives.PutCall",
"tensorflow.sqrt",
"tensorflow.gather",
"... | [((1935, 1970), 'simulators.ConstantBankAccount', 'simulators.ConstantBankAccount', (['(0.0)'], {}), '(0.0)\n', (1965, 1970), False, 'import simulators\n'), ((1979, 2052), 'books.DerivativeBook', 'books.DerivativeBook', (['maturity', 'instrument_simulator', 'numeraire_simulator'], {}), '(maturity, instrument_simulator,... |
"""
Copyright MIT and Harvey Mudd College
MIT License
Summer 2020
Lab 4B - LIDAR Wall Following
"""
########################################################################################
# Imports
########################################################################################
import sys
import cv2 as cv
i... | [
"racecar_utils.clamp",
"racecar_core.create_racecar",
"sys.path.insert",
"racecar_utils.get_lidar_closest_point"
] | [((339, 374), 'sys.path.insert', 'sys.path.insert', (['(0)', '"""../../library"""'], {}), "(0, '../../library')\n", (354, 374), False, 'import sys\n'), ((658, 687), 'racecar_core.create_racecar', 'racecar_core.create_racecar', ([], {}), '()\n', (685, 687), False, 'import racecar_core\n'), ((1886, 1938), 'racecar_utils.... |
import indicoio, os, json
indicoio.config.api_key = '27df1eee04c5b65fb3113e9458d1d701'
fileDir = os.path.dirname(os.path.realpath('__file__'))
fileResumeTxt = open(os.path.join(fileDir, "data/resume.txt"), 'w')
resume = "data/resumePDF.pdf"
print(json.dumps(indicoio.pdf_extraction(resume))) | [
"os.path.realpath",
"indicoio.pdf_extraction",
"os.path.join"
] | [((119, 147), 'os.path.realpath', 'os.path.realpath', (['"""__file__"""'], {}), "('__file__')\n", (135, 147), False, 'import indicoio, os, json\n'), ((171, 211), 'os.path.join', 'os.path.join', (['fileDir', '"""data/resume.txt"""'], {}), "(fileDir, 'data/resume.txt')\n", (183, 211), False, 'import indicoio, os, json\n'... |
# :coding: utf-8
import pytest
import os
import champollion.parser.helper
@pytest.mark.parametrize(
("content_lines", "line_number", "expected"),
[
(
[
"/**",
" * An function example.",
" *",
" * Detailed description.",
... | [
"pytest.mark.parametrize"
] | [((79, 1414), 'pytest.mark.parametrize', 'pytest.mark.parametrize', (["('content_lines', 'line_number', 'expected')", '[([\'/**\', \' * An function example.\', \' *\', \' * Detailed description.\', \' *\',\n \' * .. note::\', \' *\', \' * A note.\', \' */\', \'function sum(a, b) {\',\n \' return a+b;\', \'... |
import os
import tbs.logger.log as logger
import tbs.helper.filedescriptor as fd
def checkRoot(message):
"""
Check if the user is root otherwise error out
"""
if os.geteuid() != 0:
logger.log(message, logger.LOG_ERROR)
raise Exception("You need root privileges to do this operation.")
de... | [
"os.chdir",
"tbs.helper.filedescriptor.CMD",
"os.geteuid",
"tbs.logger.log.log"
] | [((1106, 1145), 'os.chdir', 'os.chdir', (["(result.stdout + '/' + subpath)"], {}), "(result.stdout + '/' + subpath)\n", (1114, 1145), False, 'import os\n'), ((178, 190), 'os.geteuid', 'os.geteuid', ([], {}), '()\n', (188, 190), False, 'import os\n'), ((205, 242), 'tbs.logger.log.log', 'logger.log', (['message', 'logger... |
# Copyright (c) 2016-2020 <NAME>
# Licensed under the zlib/libpng License
# https://opensource.org/licenses/Zlib
# xusb: Generic USB test program
# Copyright © 2009-2012 <NAME> <<EMAIL>>
# Contributions to Mass Storage by <NAME>.
#
# This library is free software; you can redistribute it and/or
# modify it under the t... | [
"libusb.get_device_speed",
"libusb.release_interface",
"libusb.device_descriptor",
"ctypes.pointer",
"libusb.free_bos_descriptor",
"libusb.close",
"libusb.free_config_descriptor",
"libusb.error_name",
"ctypes.c_uint",
"libusb.control_transfer",
"ctypes.cast",
"ctypes.c_int",
"libusb.claim_in... | [((10679, 10880), 'libusb.control_transfer', 'usb.control_transfer', (['handle', '(usb.LIBUSB_ENDPOINT_IN | usb.LIBUSB_REQUEST_TYPE_CLASS | usb.\n LIBUSB_RECIPIENT_INTERFACE)', 'HID_GET_REPORT', '(HID_REPORT_TYPE_INPUT << 8 | 0)', '(0)', 'input_report', '(20)', '(1000)'], {}), '(handle, usb.LIBUSB_ENDPOINT_IN | usb.... |
# -*- coding: utf-8 -*-
# type: ignore
# copyright: (c) 2020 by <NAME>.
# license: Apache 2.0, see LICENSE for more details.
'''Validation Task-Runner.'''
import os
import shutil
from invoke import task
@task
def mkdir(ctx, path):
'''Make directory path.'''
try:
os.makedirs(path, exist_ok=True)
... | [
"os.makedirs",
"shutil.rmtree"
] | [((283, 315), 'os.makedirs', 'os.makedirs', (['path'], {'exist_ok': '(True)'}), '(path, exist_ok=True)\n', (294, 315), False, 'import os\n'), ((490, 509), 'shutil.rmtree', 'shutil.rmtree', (['path'], {}), '(path)\n', (503, 509), False, 'import shutil\n')] |
# Author: <NAME>
'''
Hierarchy of subroutines::
hh_param_from_profile
|--- _calc_rho()
|--- helper_site_response.thk2dep()
|--- _calc_Gmax()
|--- _calc_vertical_stress()
|--- _calc_OCR()
|--- _calc_K0()
|--- _calc_PI()
|--- _calc_shear_strength()
|--- _calc_K0()
|--- pro... | [
"matplotlib.pyplot.grid",
"matplotlib.pyplot.ylabel",
"numpy.log",
"numpy.column_stack",
"numpy.array",
"numpy.linalg.norm",
"numpy.arange",
"numpy.mean",
"matplotlib.pyplot.xlabel",
"matplotlib.pyplot.plot",
"numpy.zeros_like",
"numpy.max",
"numpy.linspace",
"numpy.min",
"numpy.argmin",... | [((15961, 15981), 'numpy.zeros_like', 'np.zeros_like', (['GGmax'], {}), '(GGmax)\n', (15974, 15981), True, 'import numpy as np\n'), ((16313, 16331), 'numpy.zeros_like', 'np.zeros_like', (['OCR'], {}), '(OCR)\n', (16326, 16331), True, 'import numpy as np\n'), ((17257, 17279), 'numpy.zeros', 'np.zeros', (['(9, n_layer)']... |
#
# Created on 2020/2/25
#
import os
import sys
sys.path.append("..")
import cv2 as cv
from nets import get_model
from nets.network import *
class Mtldesc(object):
def __init__(self, **config):
self.name = 'MTLDesc'
self.config = {
"detection_threshold": 0.9,
"nms_dist": ... | [
"cv2.resize",
"nets.get_model",
"sys.path.append"
] | [((49, 70), 'sys.path.append', 'sys.path.append', (['""".."""'], {}), "('..')\n", (64, 70), False, 'import sys\n'), ((7059, 7130), 'cv2.resize', 'cv.resize', (['img'], {'dsize': '(scale_w, scale_h)', 'interpolation': 'cv.INTER_LINEAR'}), '(img, dsize=(scale_w, scale_h), interpolation=cv.INTER_LINEAR)\n', (7068, 7130), ... |
from peewee import CharField, IntegerField
from core.db.db import BaseModel
class Objects(BaseModel):
name = CharField(unique=True)
is_archive = IntegerField()
class Meta:
table_name = 'objects'
| [
"peewee.CharField",
"peewee.IntegerField"
] | [((115, 137), 'peewee.CharField', 'CharField', ([], {'unique': '(True)'}), '(unique=True)\n', (124, 137), False, 'from peewee import CharField, IntegerField\n'), ((155, 169), 'peewee.IntegerField', 'IntegerField', ([], {}), '()\n', (167, 169), False, 'from peewee import CharField, IntegerField\n')] |
import time
import functools
import numpy as np
def time_compute(fun):
@functools.wraps(fun)
def wrapper(*args, **kwargs):
start_time = time.time()
tmp = fun(*args, **kwargs)
end_time = time.time()
print('{} cost {} s.'.format(fun.__name__, end_time-start_time))
return ... | [
"numpy.array",
"time.time",
"functools.wraps"
] | [((78, 98), 'functools.wraps', 'functools.wraps', (['fun'], {}), '(fun)\n', (93, 98), False, 'import functools\n'), ((378, 398), 'functools.wraps', 'functools.wraps', (['fun'], {}), '(fun)\n', (393, 398), False, 'import functools\n'), ((154, 165), 'time.time', 'time.time', ([], {}), '()\n', (163, 165), False, 'import t... |
#!/usr/bin/env python
"""A BlobStore proxy that writes to two BlobStores."""
from __future__ import absolute_import
from __future__ import division
from __future__ import unicode_literals
import logging
import threading
import time
from future.moves import queue
from typing import Dict, Iterable, Optional, Text
fro... | [
"logging.warn",
"future.moves.queue.Queue",
"grr_response_core.stats.stats_collector_instance.Get",
"threading.Thread",
"grr_response_core.lib.util.precondition.AssertType",
"time.time"
] | [((1193, 1204), 'time.time', 'time.time', ([], {}), '()\n', (1202, 1204), False, 'import time\n'), ((3011, 3049), 'grr_response_core.lib.util.precondition.AssertType', 'precondition.AssertType', (['primary', 'Text'], {}), '(primary, Text)\n', (3034, 3049), False, 'from grr_response_core.lib.util import precondition\n')... |
import numpy as np
arr1 = np.ones (2, dtype=float)
print("1D Array with ones ")
print(arr1)
#[1. 1.] | [
"numpy.ones"
] | [((27, 50), 'numpy.ones', 'np.ones', (['(2)'], {'dtype': 'float'}), '(2, dtype=float)\n', (34, 50), True, 'import numpy as np\n')] |
#!/usr/bin/python3
import json
import os
import subprocess
# Icons for the animation
sleep = ""
icons_base = ["","","","",""]
# Path to the script
__location__ = os.path.realpath(
os.path.join(os.getcwd(), os.path.dirname(__file__)))
# Run the script for getting the CPU usage
subprocess.Popen([os.path.join... | [
"os.path.join",
"os.getcwd",
"os.path.dirname",
"json.load",
"json.dump"
] | [((485, 500), 'json.load', 'json.load', (['file'], {}), '(file)\n', (494, 500), False, 'import json\n'), ((1308, 1339), 'json.dump', 'json.dump', (['data', 'file'], {'indent': '(4)'}), '(data, file, indent=4)\n', (1317, 1339), False, 'import json\n'), ((205, 216), 'os.getcwd', 'os.getcwd', ([], {}), '()\n', (214, 216),... |
import matplotlib.pyplot as plt
import numpy as np
import operator
import os
import sys
import tensorflow as tf
# 256*256 映射到 0~1 区间
def Transform(input):
if not (operator.eq(input.shape, (256, 256))):
print("not matched")
sys.exit(1)
max = np.max(input)
min = np.min(input)
for i in r... | [
"os.path.exists",
"matplotlib.pyplot.savefig",
"numpy.ones",
"sys.exit",
"os.makedirs",
"numpy.max",
"numpy.min",
"operator.eq",
"matplotlib.pyplot.get_cmap",
"matplotlib.pyplot.show"
] | [((774, 806), 'numpy.ones', 'np.ones', (['(256, 256)'], {'dtype': 'float'}), '((256, 256), dtype=float)\n', (781, 806), True, 'import numpy as np\n'), ((268, 281), 'numpy.max', 'np.max', (['input'], {}), '(input)\n', (274, 281), True, 'import numpy as np\n'), ((292, 305), 'numpy.min', 'np.min', (['input'], {}), '(input... |
import string
def onlyletters(s):
s1 = []
for i in s:
if i not in string.punctuation: # проверяем посимвольно, есть ли в списке пунктуационных знаков
s1.append(i)
s2 = ''.join(s1) # соединяем массив символов в слово
return s2
words = (input().lower()).split() # преобразуем сло... | [
"re.findall"
] | [((1768, 1810), 're.findall', 'findall', (['"""\\\\ba\\\\b|\\\\ban\\\\b|\\\\bthe\\\\b"""', 'txt'], {}), "('\\\\ba\\\\b|\\\\ban\\\\b|\\\\bthe\\\\b', txt)\n", (1775, 1810), False, 'from re import findall\n')] |
import tensorflow as tf
from keras.preprocessing.image import ImageDataGenerator
import numpy as np
from keras.preprocessing import image
import zipfile
import os
import pickle
from keras.models import model_from_json
from django.conf import settings
from django.conf import settings
def training():
zip_ref = zipf... | [
"keras.preprocessing.image.img_to_array",
"tensorflow.keras.layers.Conv2D",
"zipfile.ZipFile",
"keras.preprocessing.image.ImageDataGenerator",
"keras.models.model_from_json",
"tensorflow.keras.layers.Dense",
"numpy.expand_dims",
"os.path.abspath",
"tensorflow.keras.layers.Flatten",
"tensorflow.ker... | [((316, 349), 'zipfile.ZipFile', 'zipfile.ZipFile', (['"""check.zip"""', '"""r"""'], {}), "('check.zip', 'r')\n", (331, 349), False, 'import zipfile\n'), ((434, 530), 'keras.preprocessing.image.ImageDataGenerator', 'ImageDataGenerator', ([], {'rescale': '(1.0 / 255)', 'shear_range': '(0.2)', 'zoom_range': '(0.2)', 'hor... |
from pyHalo.Rendering.SpatialDistributions.uniform import LensConeUniform
import numpy as np
from copy import deepcopy
from pyHalo.Rendering.MassFunctions.power_law import GeneralPowerLaw
from pyHalo.Rendering.rendering_class_base import RenderingClassBase
class TwoHaloContribution(RenderingClassBase):
"""
Th... | [
"pyHalo.Rendering.MassFunctions.power_law.GeneralPowerLaw",
"numpy.array",
"pyHalo.Rendering.SpatialDistributions.uniform.LensConeUniform",
"copy.deepcopy"
] | [((1205, 1269), 'pyHalo.Rendering.SpatialDistributions.uniform.LensConeUniform', 'LensConeUniform', (["keywords_master['cone_opening_angle']", 'geometry'], {}), "(keywords_master['cone_opening_angle'], geometry)\n", (1220, 1269), False, 'from pyHalo.Rendering.SpatialDistributions.uniform import LensConeUniform\n'), ((2... |
from decouple import config
import heroku3
import uuid
HEROKU_API_KEY = config("HEROKU_API_KEY")
heroku_conn = heroku3.from_key(HEROKU_API_KEY)
def footprint_walt():
appy = heroku_conn.create_app(name=f"footprint-{uuid.uuid4().hex[:8]}")
appy.create_build(f'{config("GIT_URL")}/tarball/master')
appy.conf... | [
"heroku3.from_key",
"decouple.config",
"uuid.uuid4"
] | [((73, 97), 'decouple.config', 'config', (['"""HEROKU_API_KEY"""'], {}), "('HEROKU_API_KEY')\n", (79, 97), False, 'from decouple import config\n'), ((112, 144), 'heroku3.from_key', 'heroku3.from_key', (['HEROKU_API_KEY'], {}), '(HEROKU_API_KEY)\n', (128, 144), False, 'import heroku3\n'), ((271, 288), 'decouple.config',... |
# -*- coding: utf-8 -*-
from unittest import TestCase
from eduid_userdb.element import DuplicateElementViolation
from eduid_userdb.profile import Profile, ProfileList
__author__ = 'lundberg'
OPAQUE_DATA = {'a_string': 'I am a string', 'an_int': 3, 'a_list': ['eins', 2, 'drei'], 'a_map': {'some': 'data'}}
class P... | [
"eduid_userdb.profile.ProfileList",
"eduid_userdb.profile.Profile.from_dict",
"eduid_userdb.profile.Profile"
] | [((395, 504), 'eduid_userdb.profile.Profile', 'Profile', ([], {'owner': '"""test owner"""', 'schema': '"""test schema"""', 'profile_data': 'OPAQUE_DATA', 'created_by': '"""test created_by"""'}), "(owner='test owner', schema='test schema', profile_data=OPAQUE_DATA,\n created_by='test created_by')\n", (402, 504), Fals... |
"""Module containing file system sensors."""
from airflow.sensors.base_sensor_operator import BaseSensorOperator
from airflow.utils.decorators import apply_defaults
from airflow_fs.hooks import LocalHook
class FileSensor(BaseSensorOperator):
"""Sensor that waits for files matching a given file pattern.
:pa... | [
"airflow_fs.hooks.LocalHook"
] | [((702, 713), 'airflow_fs.hooks.LocalHook', 'LocalHook', ([], {}), '()\n', (711, 713), False, 'from airflow_fs.hooks import LocalHook\n')] |
import vtreat.util
import pandas
import numpy
def test_range():
# https://github.com/WinVector/pyvtreat/blob/master/Examples/Bugs/asarray_issue.md
# https://github.com/WinVector/pyvtreat/issues/7
numpy.random.seed(2019)
arr = numpy.random.randint(2, size=10)
sparr = pandas.arrays.SparseArray(arr, ... | [
"pandas.arrays.SparseArray",
"numpy.random.randint",
"numpy.random.seed"
] | [((210, 233), 'numpy.random.seed', 'numpy.random.seed', (['(2019)'], {}), '(2019)\n', (227, 233), False, 'import numpy\n'), ((244, 276), 'numpy.random.randint', 'numpy.random.randint', (['(2)'], {'size': '(10)'}), '(2, size=10)\n', (264, 276), False, 'import numpy\n'), ((289, 333), 'pandas.arrays.SparseArray', 'pandas.... |
import os
from setuptools import setup
with open(os.path.join(os.path.dirname(__file__), 'README.md')) as readme:
README = readme.read()
# allow setup.py to be run from any path
os.chdir(os.path.normpath(os.path.join(os.path.abspath(__file__), os.pardir)))
setup(
name='django-eremaea2',
version='2.0.17',
package... | [
"os.path.abspath",
"os.path.dirname",
"setuptools.setup"
] | [((261, 1266), 'setuptools.setup', 'setup', ([], {'name': '"""django-eremaea2"""', 'version': '"""2.0.17"""', 'packages': "['eremaea', 'eremaea.ctl', 'eremaea.migrations']", 'entry_points': "{'console_scripts': [\n 'eremaeactl = eremaea.ctl.commandline:execute_from_commandline']}", 'include_package_data': '(True)', ... |
from django.contrib.auth.base_user import AbstractBaseUser
from django.contrib.auth.models import PermissionsMixin
# https://wsvincent.com/django-custom-user-model-tutorial/
from django.db import models
from django.utils import timezone
from django.utils.translation import gettext_lazy as _
from users.managers import... | [
"django.utils.translation.gettext_lazy",
"users.managers.UserManager"
] | [((1102, 1115), 'users.managers.UserManager', 'UserManager', ([], {}), '()\n', (1113, 1115), False, 'from users.managers import UserManager\n'), ((412, 426), 'django.utils.translation.gettext_lazy', '_', (['"""full name"""'], {}), "('full name')\n", (413, 426), True, 'from django.utils.translation import gettext_lazy a... |
from datetime import datetime, timedelta
from random import sample, choice, randrange
from unittest import TestCase
import tests.test_timeinterval as ti
from tests.factories import make_sets, make_moments
from timeset import TimeSet
t0 = datetime(2019, 7, 19)
t6 = datetime(2019, 7, 25)
t = make_moments(20, t0, t6)
se... | [
"datetime.datetime",
"timeset.TimeSet.from_interval",
"random.sample",
"random.choice",
"tests.factories.make_moments",
"tests.factories.make_sets",
"timeset.TimeSet",
"timeset.TimeSet.empty",
"datetime.timedelta"
] | [((240, 261), 'datetime.datetime', 'datetime', (['(2019)', '(7)', '(19)'], {}), '(2019, 7, 19)\n', (248, 261), False, 'from datetime import datetime, timedelta\n'), ((267, 288), 'datetime.datetime', 'datetime', (['(2019)', '(7)', '(25)'], {}), '(2019, 7, 25)\n', (275, 288), False, 'from datetime import datetime, timede... |
# -*- coding: utf-8 -*-
import json
def storage(name, data):
with open('tmp/%s.json' % name, 'w', encoding = 'UTF-8') as f:
json.dump(data, f, sort_keys = False, indent = 2, ensure_ascii = False)
| [
"json.dump"
] | [((129, 194), 'json.dump', 'json.dump', (['data', 'f'], {'sort_keys': '(False)', 'indent': '(2)', 'ensure_ascii': '(False)'}), '(data, f, sort_keys=False, indent=2, ensure_ascii=False)\n', (138, 194), False, 'import json\n')] |
import numpy as np
def directional_coupler_lc(wavelength_nm, n_eff_1, n_eff_2):
'''
Calculates the coherence length (100% power transfer) of a
directional coupler.
Args:
wavelength_nm (float): The wavelength in [nm] the
directional coupler should operate at.
n_eff_1 (float... | [
"numpy.radians",
"numpy.abs"
] | [((2038, 2051), 'numpy.abs', 'np.abs', (['kappa'], {}), '(kappa)\n', (2044, 2051), True, 'import numpy as np\n'), ((1900, 1931), 'numpy.radians', 'np.radians', (['incidence_angle_deg'], {}), '(incidence_angle_deg)\n', (1910, 1931), True, 'import numpy as np\n')] |
import os
from typing import IO
from PySDDP.newave.script.templates.confhd import ConfhdTemplate
from matplotlib import pyplot as plt
import numpy as np
from random import randint
from mpl_toolkits.mplot3d import Axes3D
class Confhd(ConfhdTemplate):
def __init__(self):
super().__init__()
self.li... | [
"numpy.sqrt",
"matplotlib.pyplot.ylabel",
"numpy.count_nonzero",
"numpy.array",
"numpy.arange",
"numpy.mean",
"numpy.where",
"matplotlib.pyplot.xlabel",
"matplotlib.pyplot.plot",
"matplotlib.pyplot.barh",
"os.path.split",
"numpy.max",
"numpy.linspace",
"matplotlib.pyplot.yticks",
"numpy.... | [((29927, 29952), 'numpy.where', 'np.where', (['(incremental < 0)'], {}), '(incremental < 0)\n', (29935, 29952), True, 'import numpy as np\n'), ((31508, 31533), 'numpy.where', 'np.where', (['(incremental < 0)'], {}), '(incremental < 0)\n', (31516, 31533), True, 'import numpy as np\n'), ((32292, 32333), 'numpy.array', '... |
""" This module contains a number of useful math related functions that are used throughout this project """
from __future__ import annotations
import math
from typing import List, Union, Tuple
from deprecated import deprecated # type: ignore
AnyNumber = Union[int, float]
FloatIterable = Union[List[float], Tuple[flo... | [
"math.sqrt",
"math.acos"
] | [((5714, 5735), 'math.sqrt', 'math.sqrt', (['squaredSum'], {}), '(squaredSum)\n', (5723, 5735), False, 'import math\n'), ((9465, 9486), 'math.acos', 'math.acos', (['dotproduct'], {}), '(dotproduct)\n', (9474, 9486), False, 'import math\n')] |
import os
import json
import glob
import datetime
from flask_restful import Api, Resource, reqparse
from flask_jwt_extended import (
JWTManager, jwt_required, create_access_token,
get_jwt_identity
)
from .decorators import local_only
import utils
'''
Check authentication
'''
current_path = os.path.dirname(... | [
"flask_restful.reqparse.RequestParser",
"flask_jwt_extended.create_access_token",
"utils.not_empty_file",
"os.path.realpath",
"glob.glob",
"datetime.timedelta",
"utils.reading_json"
] | [((320, 346), 'os.path.realpath', 'os.path.realpath', (['__file__'], {}), '(__file__)\n', (336, 346), False, 'import os\n'), ((395, 419), 'flask_restful.reqparse.RequestParser', 'reqparse.RequestParser', ([], {}), '()\n', (417, 419), False, 'from flask_restful import Api, Resource, reqparse\n'), ((1563, 1632), 'glob.gl... |
import os
from json import dumps
import logging
from platform import platform
from psutil import cpu_percent, virtual_memory
from serial import Serial
from time import sleep
from sb_serial import Sensor, SbSerial
# Change the serial port to suit the machine that this running on
# and the OS
#DEV = os.getenv('DEV', '/... | [
"sb_serial.SbSerial",
"os.getenv",
"json.dumps",
"time.sleep",
"sb_serial.Sensor",
"serial.Serial"
] | [((389, 414), 'os.getenv', 'os.getenv', (['"""DEV"""', '"""COM11"""'], {}), "('DEV', 'COM11')\n", (398, 414), False, 'import os\n'), ((486, 497), 'serial.Serial', 'Serial', (['DEV'], {}), '(DEV)\n', (492, 497), False, 'from serial import Serial\n'), ((504, 515), 'sb_serial.SbSerial', 'SbSerial', (['s'], {}), '(s)\n', (... |
# TODO selection percentage pattern works, but run and done methods really slow down
# TODO whole computation when we traverse really big data
# TODO in order to achieve better performance EconomizeFiniteStateMachine class was provided
import math
class SelectionFiniteStateMachine:
def __init__(self, *args, **k... | [
"math.floor"
] | [((2125, 2165), 'math.floor', 'math.floor', (['(self.doc_len / self.obj_size)'], {}), '(self.doc_len / self.obj_size)\n', (2135, 2165), False, 'import math\n'), ((2185, 2246), 'math.floor', 'math.floor', (['(self.items * self.percentage / 100 - self.visited)'], {}), '(self.items * self.percentage / 100 - self.visited)\... |
## 1. Introduction to the data ##
import pandas as pd
cars = pd.read_csv("auto.csv")
unique_regions = cars['origin'].unique()
print(unique_regions)
## 2. Dummy variables ##
dummy_cylinders = pd.get_dummies(cars["cylinders"], prefix="cyl")
cars = pd.concat([cars, dummy_cylinders], axis=1)
print(cars.head())
dummy_yea... | [
"pandas.DataFrame",
"pandas.read_csv",
"sklearn.linear_model.LogisticRegression",
"pandas.get_dummies",
"pandas.concat"
] | [((62, 85), 'pandas.read_csv', 'pd.read_csv', (['"""auto.csv"""'], {}), "('auto.csv')\n", (73, 85), True, 'import pandas as pd\n'), ((194, 241), 'pandas.get_dummies', 'pd.get_dummies', (["cars['cylinders']"], {'prefix': '"""cyl"""'}), "(cars['cylinders'], prefix='cyl')\n", (208, 241), True, 'import pandas as pd\n'), ((... |
import glob
import os
import subprocess
import time
import matplotlib.pyplot as plt
import numpy
import torch
def viz(
batch: torch.Tensor,
episodes=1000,
video=True,
folder='output',
) -> None:
## Visualize GoodAI Breakout Dataset
fig = plt.figure(1)
ax = fig.add_subplot(111)
ax.set_title("B... | [
"matplotlib.pyplot.figure",
"numpy.zeros",
"subprocess.call",
"time.time",
"glob.glob",
"os.remove"
] | [((261, 274), 'matplotlib.pyplot.figure', 'plt.figure', (['(1)'], {}), '(1)\n', (271, 274), True, 'import matplotlib.pyplot as plt\n'), ((454, 465), 'time.time', 'time.time', ([], {}), '()\n', (463, 465), False, 'import time\n'), ((348, 372), 'numpy.zeros', 'numpy.zeros', (['(84, 84, 4)'], {}), '((84, 84, 4))\n', (359,... |
from Bio import SeqIO
from subprocess import Popen, PIPE
adapters = [str(s.seq) for s in SeqIO.parse(open(snakemake.input[1], 'r'), 'fasta')]
adapters = '-b ' + ' -b '.join(adapters)
cutadapt_cmd = f"cutadapt -o {snakemake.output[0]} {adapters} {snakemake.input[0]}"
p = Popen(cutadapt_cmd, stdout=PIPE, stderr=PIPE, ... | [
"subprocess.Popen"
] | [((274, 331), 'subprocess.Popen', 'Popen', (['cutadapt_cmd'], {'stdout': 'PIPE', 'stderr': 'PIPE', 'shell': '(True)'}), '(cutadapt_cmd, stdout=PIPE, stderr=PIPE, shell=True)\n', (279, 331), False, 'from subprocess import Popen, PIPE\n')] |
#!/usr/bin/env python3
import sys, json, time, hashlib, base64
from collections import defaultdict
# vat-mint (v5) .getCurrentAmount is a really simple method: it looks up a
# Presence in a WeakMap, and returns the value. The only syscall it makes is
# the resolve. There are four timestamps of interest:
# A: delivery ... | [
"json.loads",
"collections.defaultdict"
] | [((1007, 1024), 'collections.defaultdict', 'defaultdict', (['list'], {}), '(list)\n', (1018, 1024), False, 'from collections import defaultdict\n'), ((1060, 1076), 'json.loads', 'json.loads', (['line'], {}), '(line)\n', (1070, 1076), False, 'import sys, json, time, hashlib, base64\n')] |
""" Download datasets from SANDANA samples from Galaxy server.
python scripts/download_sandana_datasets.py --help
"""
import argparse
import logging
from cycif_db.galaxy_download import download_sandana
parser = argparse.ArgumentParser()
parser.add_argument(
'--server', '-s', type=str, dest='server', required=F... | [
"logging.basicConfig",
"cycif_db.galaxy_download.download_sandana",
"argparse.ArgumentParser"
] | [((215, 240), 'argparse.ArgumentParser', 'argparse.ArgumentParser', ([], {}), '()\n', (238, 240), False, 'import argparse\n'), ((851, 927), 'cycif_db.galaxy_download.download_sandana', 'download_sandana', (['args.destination'], {'server': 'args.server', 'api_key': 'args.api_key'}), '(args.destination, server=args.serve... |
import os.path
import re
import platform
import subprocess
from copy import deepcopy
from pathlib import Path
from schema import Optional, Schema, SchemaError, Or
from buildz.toolchain.generic import GenericToolchain
from buildz.utils import find_re_it_in_list, get_cmd_matches, merge, merge_envs, resolve_rel_paths_li... | [
"buildz.utils.get_cmd_matches",
"copy.deepcopy",
"schema.Optional",
"pathlib.Path",
"subprocess.run",
"buildz.utils.merge",
"platform.system",
"schema.Or",
"buildz.utils.find_re_it_in_list",
"buildz.utils.merge_envs"
] | [((385, 480), 'buildz.utils.merge', 'merge', (['GenericToolchain._confsch._schema', "{'gcc_path': str, 'ar_path': str, 'ld_path': str}"], {}), "(GenericToolchain._confsch._schema, {'gcc_path': str, 'ar_path': str,\n 'ld_path': str})\n", (390, 480), False, 'from buildz.utils import find_re_it_in_list, get_cmd_matches... |
from .. import db
from .base import Base, BaseSchema
from typing import Dict, Union
from datetime import datetime
class Calculation(Base):
__table_name__ = 'calculation'
calc_id = db.Column(db.Integer, primary_key=True)
num1 = db.Column(db.Integer, nullable=False)
num2 = db.Column(db.Integer, nullable... | [
"datetime.datetime.utcnow"
] | [((1193, 1210), 'datetime.datetime.utcnow', 'datetime.utcnow', ([], {}), '()\n', (1208, 1210), False, 'from datetime import datetime\n'), ((1634, 1651), 'datetime.datetime.utcnow', 'datetime.utcnow', ([], {}), '()\n', (1649, 1651), False, 'from datetime import datetime\n')] |
# coding=utf-8
import random
import sys
import pygame
from pygame.color import THECOLORS
pygame.init()
screen = pygame.display.set_mode([640, 480])
screen.fill([255, 255, 255])
for i in range(0, 100):
width = random.randint(0, 250)
height = random.randint(0, 100)
top = random.randint(0, 400)
left =... | [
"pygame.init",
"pygame.quit",
"pygame.event.get",
"pygame.color.THECOLORS.keys",
"pygame.display.set_mode",
"pygame.display.flip",
"pygame.draw.rect",
"random.randint"
] | [((94, 107), 'pygame.init', 'pygame.init', ([], {}), '()\n', (105, 107), False, 'import pygame\n'), ((117, 152), 'pygame.display.set_mode', 'pygame.display.set_mode', (['[640, 480]'], {}), '([640, 480])\n', (140, 152), False, 'import pygame\n'), ((542, 563), 'pygame.display.flip', 'pygame.display.flip', ([], {}), '()\n... |
"""
Tool for 'leave-one-out' testing features in dataset.
Adds use_column parameter for lightgbm CLI, which works
like an opposite one to ignore_columns.
Example usage
--------------
>>> python lgbm_tool.py --use_column=column1,column2,column3 \
>>> config=path_to_config data=path_to_data valid=pat... | [
"subprocess.call",
"argparse.ArgumentParser"
] | [((2375, 2467), 'subprocess.call', 'subprocess.call', (["['lightgbm', f'ignore_column={ignore_string}', *args['lightgbm_args']]"], {}), "(['lightgbm', f'ignore_column={ignore_string}', *args[\n 'lightgbm_args']])\n", (2390, 2467), False, 'import subprocess\n'), ((2551, 2576), 'argparse.ArgumentParser', 'argparse.Arg... |
import setuptools
setuptools.setup(
name="image-quality-assessment",
version="0.0.1",
author="gdp",
author_email="<EMAIL>",
description="TBD",
long_description_content_type="text/markdown",
url="https://github.com/getyourguide/image-quality-assessment",
packages=setuptools.find_package... | [
"setuptools.find_packages"
] | [((297, 323), 'setuptools.find_packages', 'setuptools.find_packages', ([], {}), '()\n', (321, 323), False, 'import setuptools\n')] |
import torch.nn.functional as F
from torch import nn, zeros, cat, bmm
from data import MAX_LENGTH
class EncoderRNN(nn.Module):
def __init__(self, input_size, hidden_size):
super(EncoderRNN, self).__init__()
self.hidden_size = hidden_size
self.embedding = nn.Embedding(input_size, hidden_si... | [
"torch.nn.functional.softmax",
"torch.nn.Dropout",
"torch.cat",
"torch.nn.Linear",
"torch.nn.functional.relu",
"torch.bmm",
"torch.nn.functional.log_softmax",
"torch.zeros",
"torch.nn.Embedding",
"torch.nn.GRU"
] | [((286, 323), 'torch.nn.Embedding', 'nn.Embedding', (['input_size', 'hidden_size'], {}), '(input_size, hidden_size)\n', (298, 323), False, 'from torch import nn, zeros, cat, bmm\n'), ((343, 375), 'torch.nn.GRU', 'nn.GRU', (['hidden_size', 'hidden_size'], {}), '(hidden_size, hidden_size)\n', (349, 375), False, 'from tor... |
import torch
import numpy as np
import cv2
def tonumpyimg(img):
"""
Convert a normalized tensor image to unnormalized uint8 numpy image
For single channel image, no unnormalization is done.
:param img: torch, normalized, (3, H, W), (H, W)
:return: numpy: (H, W, 3), (H, W). uint8
"""
... | [
"numpy.repeat",
"torch.Tensor",
"torch.argmax",
"torch.from_numpy",
"torch.tensor",
"cv2.warpPerspective",
"cv2.cvtColor",
"torch.device"
] | [((2321, 2351), 'torch.argmax', 'torch.argmax', (['attention'], {'dim': '(0)'}), '(attention, dim=0)\n', (2333, 2351), False, 'import torch\n'), ((2707, 2748), 'cv2.warpPerspective', 'cv2.warpPerspective', (['map', 'H'], {'dsize': '(w, h)'}), '(map, H, dsize=(w, h))\n', (2726, 2748), False, 'import cv2\n'), ((3586, 360... |
# -*- coding: utf-8 -*-
# *****************************************************************************
# NICOS, the Networked Instrument Control System of the MLZ
# Copyright (c) 2009-2021 by the NICOS contributors (see AUTHORS)
#
# This program is free software; you can redistribute it and/or modify it under
# the t... | [
"nicos.session.delay",
"nicos.core.Param",
"nicos.devices.generic.sequence.SeqDev",
"nicos.core.ModeError",
"nicos.core.Attach",
"nicos.core.tupleof",
"nicos.devices.generic.sequence.SeqSleep",
"Motor.Motor",
"nicos.core.requires",
"nicos.core.oneof",
"nicos.devices.generic.sequence.SeqCall"
] | [((3458, 3523), 'nicos.core.requires', 'requires', ([], {'level': 'ADMIN', 'helpmsg': '"""use adjust() to set a new offset"""'}), "(level=ADMIN, helpmsg='use adjust() to set a new offset')\n", (3466, 3523), False, 'from nicos.core import ADMIN, SLAVE, Attach, ModeError, Moveable, Param, anytype, oneof, requires, status... |
import subprocess
from os import system, remove, chdir
from tabulate import tabulate
def edges(n):
location = 0
edges = [[0,n-1]]
for i in range(n-1):
edges.append([location, location+1])
location += 1
return edges
def cut(state, edges):
cut = 0
for edge in edges:
cut += 1 if state[edge[0]] == state[ed... | [
"os.chdir",
"os.system",
"tabulate.tabulate",
"os.remove"
] | [((6435, 6455), 'os.remove', 'remove', (['"""result.txt"""'], {}), "('result.txt')\n", (6441, 6455), False, 'from os import system, remove, chdir\n'), ((6833, 6854), 'os.chdir', 'chdir', (['"""./amplitudes"""'], {}), "('./amplitudes')\n", (6838, 6854), False, 'from os import system, remove, chdir\n'), ((6855, 6869), 'o... |
from pvapy import Channel, CA, PvTimeStamp, PvAlarm
print('DBRdouble')
channel = Channel('DBRdouble')
timestamp = PvTimeStamp(10, 100)
alarm = PvAlarm(1,1,"mess")
print(channel.get('value'))
print('here 1')
channel.put(alarm,'record[process=false]field(alarm)')
print('here 2')
print(channel.get('value'))
channel.put(ti... | [
"pvapy.Channel",
"pvapy.PvAlarm",
"pvapy.PvTimeStamp"
] | [((81, 101), 'pvapy.Channel', 'Channel', (['"""DBRdouble"""'], {}), "('DBRdouble')\n", (88, 101), False, 'from pvapy import Channel, CA, PvTimeStamp, PvAlarm\n'), ((114, 134), 'pvapy.PvTimeStamp', 'PvTimeStamp', (['(10)', '(100)'], {}), '(10, 100)\n', (125, 134), False, 'from pvapy import Channel, CA, PvTimeStamp, PvAl... |
from pwn import *
import hashlib
r=remote("172.16.17.32",10122)
## pow
temp=r.recvuntil("sha256( ")
prefix=r.recvline().split()[0]
i=0
while True:
data=prefix+str(i)
Hash=hashlib.sha256(data)
if Hash.hexdigest()[:5]=="0"*5:
r.sendline(str(i))
break
i+=1
## get flag
r.sendline("0")
r.sendline("system... | [
"hashlib.sha256"
] | [((177, 197), 'hashlib.sha256', 'hashlib.sha256', (['data'], {}), '(data)\n', (191, 197), False, 'import hashlib\n')] |
#
# Author: <EMAIL>
# Date: 01/25/2019
#
""" Utils for training and optimization
"""
from __future__ import absolute_import
from __future__ import division
from __future__ import print_function
import utils
logger=utils.get_logger()
import numpy as np
import torch
from bert.optimization import BertAdam
def zero_grad... | [
"utils.get_logger",
"torch.cuda.device_count",
"bert.optimization.BertAdam",
"torch.isinf",
"torch.isnan",
"torch.distributed.get_world_size"
] | [((216, 234), 'utils.get_logger', 'utils.get_logger', ([], {}), '()\n', (232, 234), False, 'import utils\n'), ((2168, 2193), 'torch.cuda.device_count', 'torch.cuda.device_count', ([], {}), '()\n', (2191, 2193), False, 'import torch\n'), ((3734, 4223), 'bert.optimization.BertAdam', 'BertAdam', (['optimizer_grouped_param... |
try:
from setuptools import setup
except ImportError:
from distutils.core import setup
import mineid
import pathlib
HERE = pathlib.Path(__file__).parent
README = (HERE / "README.md").read_text()
setup(
name=mineid.__name__,
version=mineid.__version__,
description="A small Python library for gettin... | [
"pathlib.Path",
"distutils.core.setup"
] | [((205, 938), 'distutils.core.setup', 'setup', ([], {'name': 'mineid.__name__', 'version': 'mineid.__version__', 'description': '"""A small Python library for getting Minecraft UUIDs."""', 'long_description': 'README', 'long_description_content_type': '"""text/markdown"""', 'package_dir': "{'': 'mineid'}", 'url': '"""h... |
from django.db import models
# 微博Model
class vvebo(models.Model):
id = models.IntegerField(primary_key=True)
keyword = models.TextField(max_length=1000, default="")
user_id = models.TextField(max_length=1000, default="")
user_name = models.TextField(max_length=1000, default="")
time = models.CharFi... | [
"django.db.models.CharField",
"django.db.models.TextField",
"django.db.models.IntegerField"
] | [((76, 113), 'django.db.models.IntegerField', 'models.IntegerField', ([], {'primary_key': '(True)'}), '(primary_key=True)\n', (95, 113), False, 'from django.db import models\n'), ((128, 173), 'django.db.models.TextField', 'models.TextField', ([], {'max_length': '(1000)', 'default': '""""""'}), "(max_length=1000, defaul... |
import pandas as pd
import matplotlib.pyplot as plt
from data import games
plays = games[games['type']=='play']
plays.columns= ['type','inning','team', 'player', 'count','pitches','event', 'game_id', 'year']
#print (plays)
hits = plays.loc[plays['event'].str.contains('^(?:S(?!B)|D|T|HR)'), ['inning','event']]
#print... | [
"pandas.to_numeric",
"matplotlib.pyplot.show",
"pandas.Categorical"
] | [((470, 506), 'pandas.to_numeric', 'pd.to_numeric', (["hits.loc[:, 'inning']"], {}), "(hits.loc[:, 'inning'])\n", (483, 506), True, 'import pandas as pd\n'), ((1277, 1347), 'pandas.Categorical', 'pd.Categorical', (["hits['hit_type']", "['single', 'double', 'triple', 'hr']"], {}), "(hits['hit_type'], ['single', 'double'... |
# import necessary libraries
from flask import Flask, render_template, redirect
from flask_pymongo import PyMongo
import scrape_marsdata
from pymongo import MongoClient
# create instance of Flask app
app = Flask(__name__)
# Use flask_pymongo to set up mongo connection
# conn = "mongodb://localhost:27017"
# client = p... | [
"flask.render_template",
"flask_pymongo.PyMongo",
"scrape_marsdata.scrape",
"flask.Flask"
] | [((207, 222), 'flask.Flask', 'Flask', (['__name__'], {}), '(__name__)\n', (212, 222), False, 'from flask import Flask, render_template, redirect\n'), ((433, 445), 'flask_pymongo.PyMongo', 'PyMongo', (['app'], {}), '(app)\n', (440, 445), False, 'from flask_pymongo import PyMongo\n'), ((658, 708), 'flask.render_template'... |
#appModules/msimn.py - Outlook Express appModule
#A part of NonVisual Desktop Access (NVDA)
#Copyright (C) 2006-2012 NVDA Contributors
#This file is covered by the GNU General Public License.
#See the file COPYING for more details.
import winUser
import controlTypes
import displayModel
import textInfos
import api
impo... | [
"displayModel.DisplayModelTextInfo",
"api.getFocusObject",
"keyboardHandler.KeyboardInputGesture.fromName",
"api.processPendingEvents",
"winUser.getClassName",
"watchdog.cancellableSendMessage",
"winUser.getAncestor"
] | [((2347, 2399), 'winUser.getAncestor', 'winUser.getAncestor', (['windowHandle', 'winUser.GA_PARENT'], {}), '(windowHandle, winUser.GA_PARENT)\n', (2366, 2399), False, 'import winUser\n'), ((2417, 2451), 'winUser.getClassName', 'winUser.getClassName', (['parentWindow'], {}), '(parentWindow)\n', (2437, 2451), False, 'imp... |
""" 2019 Day 2 Solver"""
import os
import sys
from typing import Tuple, List
from multiprocessing import Manager, Process
from multiprocessing.managers import ValueProxy
INPUT_PATH = os.path.join(os.path.dirname(os.path.realpath(__file__)), "input.txt")
def solve():
""" Solve https://adventofcode.com/2019/day/2"... | [
"os.path.realpath",
"multiprocessing.Process",
"multiprocessing.Manager",
"sys.exit"
] | [((889, 899), 'sys.exit', 'sys.exit', ([], {}), '()\n', (897, 899), False, 'import sys\n'), ((213, 239), 'os.path.realpath', 'os.path.realpath', (['__file__'], {}), '(__file__)\n', (229, 239), False, 'import os\n'), ((585, 594), 'multiprocessing.Manager', 'Manager', ([], {}), '()\n', (592, 594), False, 'from multiproce... |
import itertools
import pathlib
from pathlib import Path
from typing import Union
import gdspy
from gdsfactory.component import Component
from gdsfactory.import_gds import import_gds
COUNTER = itertools.count()
def xor_polygons(A: Component, B: Component, hash_geometry: bool = True):
"""Given two devices A and... | [
"gdspy.fast_boolean",
"itertools.count",
"gdsfactory.component.Component",
"sys.exit",
"gdsfactory.import_gds.import_gds"
] | [((196, 213), 'itertools.count', 'itertools.count', ([], {}), '()\n', (211, 213), False, 'import itertools\n'), ((662, 673), 'gdsfactory.component.Component', 'Component', ([], {}), '()\n', (671, 673), False, 'from gdsfactory.component import Component\n'), ((2302, 2333), 'gdsfactory.component.Component', 'Component', ... |
"""A set of Python Classes for connecting to and interacting with a VOSpace
service.
Connections to VOSpace are made using a SSL X509 certificat which is
stored in a .pem file.
"""
#from contextlib import nested
import copy
import errno
import fnmatch
import hashlib
import requests
from requests.exceptions i... | [
"logging.getLogger",
"string.join",
"requests.Session",
"logging.debug",
"re.compile",
"sys.getdefaultencoding",
"os.getuid",
"netrc.netrc",
"time.sleep",
"copy.deepcopy",
"mimetypes.guess_type",
"logging.error",
"re.search",
"sys.getfilesystemencoding",
"xml.etree.ElementTree.parse",
... | [((1847, 1871), 'logging.getLogger', 'logging.getLogger', (['"""vos"""'], {}), "('vos')\n", (1864, 1871), False, 'import logging\n'), ((2373, 2412), 'os.getenv', 'os.getenv', (['"""VOSPACE_ARCHIVE"""', '"""vospace"""'], {}), "('VOSPACE_ARCHIVE', 'vospace')\n", (2382, 2412), False, 'import os\n'), ((2636, 2680), 'reques... |
import sys
from logs.logger import log
from utils import check_internet , get_public_ip
import bot
if __name__ == "__main__":
if check_internet() is True:
try:
log.info(f'Internet connection found : {get_public_ip()}')
bot.run()
except KeyboardInterrupt:
# quit
... | [
"logs.logger.log.info",
"bot.run",
"utils.get_public_ip",
"sys.exit",
"utils.check_internet"
] | [((134, 150), 'utils.check_internet', 'check_internet', ([], {}), '()\n', (148, 150), False, 'from utils import check_internet, get_public_ip\n'), ((256, 265), 'bot.run', 'bot.run', ([], {}), '()\n', (263, 265), False, 'import bot\n'), ((368, 417), 'logs.logger.log.info', 'log.info', (['"""Please check your internet co... |
from robot.api.parsing import ModelTransformer, Token
try:
from robot.api.parsing import InlineIfHeader
except ImportError:
InlineIfHeader = None
from robotidy.disablers import skip_section_if_disabled
from robotidy.utils import ROBOT_VERSION
EOL = Token(Token.EOL)
CONTINUATION = Token(Token.CONTINUATION)
c... | [
"robot.api.parsing.Token"
] | [((259, 275), 'robot.api.parsing.Token', 'Token', (['Token.EOL'], {}), '(Token.EOL)\n', (264, 275), False, 'from robot.api.parsing import ModelTransformer, Token\n'), ((291, 316), 'robot.api.parsing.Token', 'Token', (['Token.CONTINUATION'], {}), '(Token.CONTINUATION)\n', (296, 316), False, 'from robot.api.parsing impor... |
"""
Utility for creating a Python repl.
::
from prompt_toolkit.contrib.repl import embed
embed(globals(), locals(), vi_mode=False)
"""
# Warning: don't import `print_function` from __future__, otherwise we will
# also get the print_function inside `eval` on Python 2.7.
from __future__ import unicod... | [
"traceback.format_exception_only",
"traceback.format_list",
"pygments.formatters.terminal256.Terminal256Formatter",
"pygments.lexers.PythonTracebackLexer",
"sys.exc_info",
"os.system",
"traceback.extract_tb"
] | [((3670, 3684), 'sys.exc_info', 'sys.exc_info', ([], {}), '()\n', (3682, 3684), False, 'import sys\n'), ((3743, 3772), 'traceback.format_list', 'traceback.format_list', (['tblist'], {}), '(tblist)\n', (3764, 3772), False, 'import traceback\n'), ((2317, 2336), 'os.system', 'os.system', (['line[1:]'], {}), '(line[1:])\n'... |
from base import FeatureBase
from difflib import SequenceMatcher
class FeatureEdits(FeatureBase):
name = 'edits'
desc = 'counts of word-based edit operations'
def run(self, trg, src):
matcher = SequenceMatcher(None, src.split(), trg.split())
ops = [tag for tag, _, _, _, _ in matcher.get_o... | [
"difflib.SequenceMatcher"
] | [((670, 701), 'difflib.SequenceMatcher', 'SequenceMatcher', (['None', 'src', 'trg'], {}), '(None, src, trg)\n', (685, 701), False, 'from difflib import SequenceMatcher\n')] |
# MIT License
# Copyright 2020 <NAME>
#
# Permission is hereby granted, free of charge, to any person obtaining a copy
# of this software and associated documentation files (the "Software"), to deal
# in the Software without restriction, including without limitation the rights
# to use, copy, modify, merge, publish, di... | [
"morpheus_core.helpers.fits_helper.open_file",
"pytest.mark.filterwarnings",
"numpy.arange",
"morpheus_core.tests.helpers.make_sample_file2",
"morpheus_core.helpers.fits_helper.dtype_to_bytes_per_value",
"os.path.join",
"morpheus_core.tests.helpers.make_sample_file",
"astropy.io.fits.getdata",
"pyte... | [((2846, 2895), 'pytest.mark.filterwarnings', 'pytest.mark.filterwarnings', (['"""ignore::UserWarning"""'], {}), "('ignore::UserWarning')\n", (2872, 2895), False, 'import pytest\n'), ((1447, 1461), 'morpheus_core.tests.helpers.setup', 'helper.setup', ([], {}), '()\n', (1459, 1461), True, 'import morpheus_core.tests.hel... |
#
# Copyright (c) 2017 NORDUnet A/S
# Copyright (c) 2018 SUNET
# All rights reserved.
#
# Redistribution and use in source and binary forms, with or
# without modification, are permitted provided that the following
# conditions are met:
#
# 1. Redistributions of source code must retain the above copyright
# ... | [
"eduid_common.authn.fido_tokens.verify_u2f",
"eduid_webapp.actions.app.current_actions_app.central_userdb.get_user_by_eppn",
"eduid_common.authn.fido_tokens.verify_webauthn",
"eduid_webapp.actions.app.current_actions_app.logger.debug",
"eduid_webapp.actions.app.current_actions_app.logger.info",
"eduid_com... | [((2557, 2630), 'eduid_webapp.actions.app.current_actions_app.central_userdb.get_user_by_eppn', 'current_app.central_userdb.get_user_by_eppn', (['eppn'], {'raise_on_missing': '(False)'}), '(eppn, raise_on_missing=False)\n', (2600, 2630), True, 'from eduid_webapp.actions.app import current_actions_app as current_app\n')... |
import networkx as nx
import markdown as md
def parse_concepts(filename):
"""Takes a markdown file with with a certain structure
and parses it to separate the concept and the relations
between the concepts.
Structure:
# [Title]
## [Concept]
[Some text]
[Even Latex math]
### [A... | [
"markdown.markdown",
"networkx.neighbors",
"networkx.Graph"
] | [((2534, 2544), 'networkx.Graph', 'nx.Graph', ([], {}), '()\n', (2542, 2544), True, 'import networkx as nx\n'), ((3069, 3100), 'markdown.markdown', 'md.markdown', (["concept['content']"], {}), "(concept['content'])\n", (3080, 3100), True, 'import markdown as md\n'), ((3200, 3218), 'networkx.neighbors', 'nx.neighbors', ... |
# -*- coding: UTF-8 -*-
from flask import Blueprint, Flask, jsonify, request, make_response
import pdfkit
from utils.cm.utils import is_exist
from utils.cm.files import delete_dir
from utils.pdf.pdfkits import *
app = Blueprint('pdfapi', __name__)
# curl -v -H "Content-type: application/json" -X POST http://192.168.1... | [
"utils.cm.files.delete_dir",
"utils.cm.utils.is_exist",
"flask.make_response",
"flask.Blueprint",
"flask.jsonify"
] | [((219, 248), 'flask.Blueprint', 'Blueprint', (['"""pdfapi"""', '__name__'], {}), "('pdfapi', __name__)\n", (228, 248), False, 'from flask import Blueprint, Flask, jsonify, request, make_response\n'), ((915, 930), 'flask.make_response', 'make_response', ([], {}), '()\n', (928, 930), False, 'from flask import Blueprint,... |
import frappe
def after_migrate():
set_default_otp_template()
def set_default_otp_template():
if not frappe.db.get_value("System Settings", None, "email_otp_template"):
if frappe.db.exists("Email Template", "Default Email OTP Template"):
# should exists via fixtures
frappe.db.set_value("System Set... | [
"frappe.db.exists",
"frappe.db.get_value",
"frappe.db.set_value"
] | [((107, 173), 'frappe.db.get_value', 'frappe.db.get_value', (['"""System Settings"""', 'None', '"""email_otp_template"""'], {}), "('System Settings', None, 'email_otp_template')\n", (126, 173), False, 'import frappe\n'), ((182, 246), 'frappe.db.exists', 'frappe.db.exists', (['"""Email Template"""', '"""Default Email OT... |