code stringlengths 22 1.05M | apis listlengths 1 3.31k | extract_api stringlengths 75 3.25M |
|---|---|---|
#!/usr/bin/env -S python3 -m pytest
from subprocess import check_call, CalledProcessError
from tempfile import mkdtemp
from textwrap import dedent
from pathlib import Path
import pytest
def literal(text):
return dedent(text).lstrip()
@pytest.fixture
def indir(tmp_path):
ret = tmp_path / 'in'
ret.mkdir()
retur... | [
"textwrap.dedent",
"pytest.raises",
"pathlib.Path",
"subprocess.check_call"
] | [((442, 475), 'subprocess.check_call', 'check_call', (["[mdpath, '-c', *args]"], {}), "([mdpath, '-c', *args])\n", (452, 475), False, 'from subprocess import check_call, CalledProcessError\n'), ((505, 538), 'subprocess.check_call', 'check_call', (["[mdpath, '-d', *args]"], {}), "([mdpath, '-d', *args])\n", (515, 538), ... |
#------------------------------------------------------------
# Dependencies
#------------------------------------------------------------
from pathlib import Path
from collections import OrderedDict
from json import load
from mm.data_utilities import try_float_parse
from object_model import AdditionalFeat... | [
"collections.OrderedDict",
"mm.data_utilities.try_float_parse",
"object_model.AdditionalFeatureParts",
"object_model.RegressionTableParts",
"json.load"
] | [((672, 685), 'collections.OrderedDict', 'OrderedDict', ([], {}), '()\n', (683, 685), False, 'from collections import OrderedDict\n'), ((1290, 1303), 'collections.OrderedDict', 'OrderedDict', ([], {}), '()\n', (1301, 1303), False, 'from collections import OrderedDict\n'), ((1339, 1399), 'object_model.AdditionalFeatureP... |
# -*- coding: utf-8 -*-
from __future__ import unicode_literals
from django.db import models, migrations
import django.db.models.deletion
class Migration(migrations.Migration):
dependencies = [
('collect', '0003_colcustomersetting_check_sender'),
('mail', '0019_auto_20151113_1727'),
]
o... | [
"django.db.models.ForeignKey",
"django.db.models.BooleanField",
"django.db.models.AutoField",
"django.db.models.DateTimeField",
"django.db.models.CharField"
] | [((446, 539), 'django.db.models.AutoField', 'models.AutoField', ([], {'verbose_name': '"""ID"""', 'serialize': '(False)', 'auto_created': '(True)', 'primary_key': '(True)'}), "(verbose_name='ID', serialize=False, auto_created=True,\n primary_key=True)\n", (462, 539), False, 'from django.db import models, migrations\... |
from django.core.validators import MinValueValidator, MaxValueValidator
from PIL import Image
# to use own user class
from django.conf import settings
from django.db import models
class Ticket(models.Model):
class Meta:
ordering = ["-time_created"]
title = models.CharField(max_length=128)
descri... | [
"PIL.Image.open",
"django.core.validators.MaxValueValidator",
"django.db.models.TextField",
"django.db.models.ForeignKey",
"django.db.models.F",
"django.db.models.DateTimeField",
"django.db.models.ImageField",
"django.core.validators.MinValueValidator",
"django.db.models.CharField"
] | [((277, 309), 'django.db.models.CharField', 'models.CharField', ([], {'max_length': '(128)'}), '(max_length=128)\n', (293, 309), False, 'from django.db import models\n'), ((328, 373), 'django.db.models.TextField', 'models.TextField', ([], {'max_length': '(2048)', 'blank': '(True)'}), '(max_length=2048, blank=True)\n', ... |
# Copyright (C) 2017 Google Inc.
# Licensed under http://www.apache.org/licenses/LICENSE-2.0 <see LICENSE file>
"""Tests for user generator"""
from collections import OrderedDict
import json
import mock
from ggrc.converters import errors
from ggrc.integrations.client import PersonClient
from ggrc.models import Asse... | [
"ggrc_basic_permissions.models.Role.query.filter",
"collections.OrderedDict",
"mock.patch",
"integration.ggrc.models.factories.AuditFactory",
"integration.ggrc.models.factories.ProgramFactory",
"ggrc.models.Person.query.filter_by",
"json.dumps",
"ggrc.models.Person.query.filter",
"ggrc.models.Audit.... | [((1359, 1426), 'mock.patch', 'mock.patch', (['"""ggrc.settings.INTEGRATION_SERVICE_URL"""'], {'new': '"""endpoint"""'}), "('ggrc.settings.INTEGRATION_SERVICE_URL', new='endpoint')\n", (1369, 1426), False, 'import mock\n'), ((1430, 1494), 'mock.patch', 'mock.patch', (['"""ggrc.settings.AUTHORIZED_DOMAIN"""'], {'new': '... |
import pickle
from universal_parser.object_converter import refactor_object, restore_object
class PickleSerializer:
def dump(self, obj, fp): # pragma: no cover
with open(fp, 'wb') as outfile:
pickle.dump(refactor_object(obj), outfile)
def dumps(self, obj):
return pickle.dumps(refa... | [
"pickle.loads",
"pickle.load",
"universal_parser.object_converter.refactor_object"
] | [((316, 336), 'universal_parser.object_converter.refactor_object', 'refactor_object', (['obj'], {}), '(obj)\n', (331, 336), False, 'from universal_parser.object_converter import refactor_object, restore_object\n'), ((393, 408), 'pickle.loads', 'pickle.loads', (['s'], {}), '(s)\n', (405, 408), False, 'import pickle\n'),... |
import os
from asrlib.utils import base, reader, audio
from asrlib.utils.wer import compute_wer
import time
from collections import OrderedDict
import glob
import numpy as np
from absl import logging, app, flags
flags.DEFINE_string('dataset', 'testdata/dataset', 'the dataset dir')
flags.DEFINE_string('outdir', '/tmp/... | [
"asrlib.utils.base.StringIO",
"collections.OrderedDict",
"asrlib.utils.reader.read_txt_to_dict",
"numpy.ceil",
"absl.flags.DEFINE_bool",
"absl.flags.DEFINE_integer",
"asrlib.utils.reader.write_dict_to_txt",
"os.path.join",
"absl.app.run",
"time.sleep",
"asrlib.utils.audio.parse_wav_line",
"asr... | [((214, 283), 'absl.flags.DEFINE_string', 'flags.DEFINE_string', (['"""dataset"""', '"""testdata/dataset"""', '"""the dataset dir"""'], {}), "('dataset', 'testdata/dataset', 'the dataset dir')\n", (233, 283), False, 'from absl import logging, app, flags\n'), ((284, 355), 'absl.flags.DEFINE_string', 'flags.DEFINE_string... |
"""
Augmented B-Tree: Insertion
---------------------------
This folder contains an implementation of an augmented B-tree.
For this implementation, the tree only stores data in its leaf
nodes. Each node also has level-set pointers defined here which
access the left and right siblings of each node (or None if they do no... | [
"remove.BTreeDeleteNode"
] | [((1430, 1447), 'remove.BTreeDeleteNode', 'BTreeNode', (['self.t'], {}), '(self.t)\n', (1439, 1447), True, 'from remove import BTreeDeleteNode as BTreeNode\n')] |
#!/usr/bin/python
import cv2
import os
import subprocess
import numpy as np
face_cascade = cv2.CascadeClassifier('haarcascades/haarcascade_frontalface_default.xml')
face_cascade_alt = cv2.CascadeClassifier('haarcascades/haarcascade_frontalface_alt.xml')
face_cascade_alt2 = cv2.CascadeClassifier('haarcascades/haarcasc... | [
"cv2.rectangle",
"os.path.exists",
"os.listdir",
"os.makedirs",
"cv2.cvtColor",
"cv2.CascadeClassifier",
"cv2.imread"
] | [((93, 166), 'cv2.CascadeClassifier', 'cv2.CascadeClassifier', (['"""haarcascades/haarcascade_frontalface_default.xml"""'], {}), "('haarcascades/haarcascade_frontalface_default.xml')\n", (114, 166), False, 'import cv2\n'), ((186, 255), 'cv2.CascadeClassifier', 'cv2.CascadeClassifier', (['"""haarcascades/haarcascade_fro... |
"""Save object into JSON file.
Write content of object _x into file _data._json.
Source: programming-idioms.org
"""
# Implementation author: nickname
# Created on 2016-02-18T16:58:02.298929Z
# Last modified on 2016-02-18T16:58:02.298929Z
# Version 1
import json
with open("data.json", "w") as output:
json.dump... | [
"json.dump"
] | [((311, 331), 'json.dump', 'json.dump', (['x', 'output'], {}), '(x, output)\n', (320, 331), False, 'import json\n')] |
import cv2 as cv
img = cv.imread('data/pic1.jpg')
cv.imshow('pic1', img)
# RGB
rgb = cv.cvtColor(img, cv.COLOR_BGR2RGB)
cv.imshow('rgb', rgb)
# HSV
hsv = cv.cvtColor(img, cv.COLOR_BGR2HSV)
cv.imshow('hsv', hsv)
# LAB
lab = cv.cvtColor(img, cv.COLOR_BGR2LAB)
cv.imshow('lab', lab)
# grayscale
gray = cv.cvtColor(img... | [
"cv2.waitKey",
"cv2.imread",
"cv2.cvtColor",
"cv2.imshow"
] | [((24, 50), 'cv2.imread', 'cv.imread', (['"""data/pic1.jpg"""'], {}), "('data/pic1.jpg')\n", (33, 50), True, 'import cv2 as cv\n'), ((51, 73), 'cv2.imshow', 'cv.imshow', (['"""pic1"""', 'img'], {}), "('pic1', img)\n", (60, 73), True, 'import cv2 as cv\n'), ((87, 121), 'cv2.cvtColor', 'cv.cvtColor', (['img', 'cv.COLOR_B... |
# -*- coding: utf-8 -*-
"""
Created on Tue Jul 10 09:48:18 2018
@author: a002028
"""
import yaml
import numpy as np
import pandas as pd
class YAMLwriter(dict):
"""Writer of yaml files."""
# TODO Ever used?
def __init__(self):
"""Initialize."""
super().__init__()
def _check_format(s... | [
"yaml.safe_dump"
] | [((1033, 1100), 'yaml.safe_dump', 'yaml.safe_dump', (['data', 'path'], {'indent': 'indent', 'default_flow_style': '(False)'}), '(data, path, indent=indent, default_flow_style=False)\n', (1047, 1100), False, 'import yaml\n')] |
from abc import ABC, ABCMeta, abstractmethod, abstractproperty
from torch.nn import Module, MSELoss, Linear
from torch.optim import Adam
import torch
from torch.autograd import Variable
import torch.nn.functional as F
from torch import FloatTensor
import os
import matplotlib as mpl
import torch.nn as nn
mpl.use('Agg')... | [
"matplotlib.pyplot.grid",
"matplotlib.pyplot.ylabel",
"matplotlib.use",
"torch.LongTensor",
"matplotlib.pyplot.xlabel",
"matplotlib.pyplot.clf",
"matplotlib.pyplot.plot",
"os.path.join",
"torch.nn.MSELoss",
"torch.zeros",
"torch.cat",
"matplotlib.pyplot.scatter",
"torch.nn.Linear",
"matplo... | [((306, 320), 'matplotlib.use', 'mpl.use', (['"""Agg"""'], {}), "('Agg')\n", (313, 320), True, 'import matplotlib as mpl\n'), ((3962, 4003), 'torch.autograd.Variable', 'Variable', (['curr_states'], {'requires_grad': '(True)'}), '(curr_states, requires_grad=True)\n', (3970, 4003), False, 'from torch.autograd import Vari... |
import flask
import os
import json
import timelineApp
from timelineApp.config import UPLOAD_FOLDER
@timelineApp.app.route('/editView/', methods=['GET', 'POST'])
def edit_view():
"""Add view to this story for this user."""
initialPath = os.getcwd()
if "username" not in flask.session:
return flask.... | [
"flask.render_template",
"flask.request.args.get",
"timelineApp.model.get_db",
"os.path.join",
"os.getcwd",
"os.chdir",
"flask.url_for",
"json.load",
"timelineApp.app.route",
"json.dump"
] | [((102, 162), 'timelineApp.app.route', 'timelineApp.app.route', (['"""/editView/"""'], {'methods': "['GET', 'POST']"}), "('/editView/', methods=['GET', 'POST'])\n", (123, 162), False, 'import timelineApp\n'), ((246, 257), 'os.getcwd', 'os.getcwd', ([], {}), '()\n', (255, 257), False, 'import os\n'), ((376, 402), 'timel... |
"""
solving mnist classification problem using tensorflow
multi-layer architecture
"""
from mnist import model_builder
import time
def run():
# Config
BATCH_SIZE = 50
ITERATIONS = 2000
PATH_TO_MODELS = './mnist/models'
import os
if not os.path.exists(PATH_TO_MODELS):
os.mkdir(PATH_TO... | [
"logging.getLogger",
"logging.StreamHandler",
"logging.debug",
"tensorflow.examples.tutorials.mnist.input_data.read_data_sets",
"tensorflow.cast",
"os.path.exists",
"tensorflow.placeholder",
"tensorflow.Session",
"os.mkdir",
"tensorflow.nn.softmax_cross_entropy_with_logits",
"tensorflow.train.Ad... | [((468, 556), 'logging.basicConfig', 'logging.basicConfig', ([], {'filename': '"""logfile.log"""', 'format': 'logging_format', 'level': 'log_level'}), "(filename='logfile.log', format=logging_format, level=\n log_level)\n", (487, 556), False, 'import logging\n'), ((585, 604), 'logging.getLogger', 'logging.getLogger'... |
import pygame
import sys
import random
import time
from point import *
pygame.init()
FPS = 5
WIN_WIDTH = 600
WIN_HEIGHT = 600
WHITE = (255, 255, 255)
BLACK = (0, 0, 0)
RUNNING = True
clock = pygame.time.Clock()
sc = pygame.display.set_mode((WIN_WIDTH, WIN_HEIGHT))
sc.fill(WHITE)
pygame.display.update()
FONT = pygame.f... | [
"sys.exit",
"pygame.init",
"pygame.event.get",
"pygame.display.set_mode",
"pygame.time.Clock",
"pygame.font.Font",
"pygame.display.update"
] | [((72, 85), 'pygame.init', 'pygame.init', ([], {}), '()\n', (83, 85), False, 'import pygame\n'), ((192, 211), 'pygame.time.Clock', 'pygame.time.Clock', ([], {}), '()\n', (209, 211), False, 'import pygame\n'), ((217, 265), 'pygame.display.set_mode', 'pygame.display.set_mode', (['(WIN_WIDTH, WIN_HEIGHT)'], {}), '((WIN_WI... |
import json_lines
import os
from hatesonar import Sonar
#Only includes the comments in a txt file, given that the comment has over a certain number of votes
#This also attempts to use Sonar to filter out hate speech
def refine_jsonl_file(path, votes_threshold=10, hate_limit=0.4, offensive_limit=0.7, general_limit=0.8)... | [
"os.path.exists",
"json_lines.reader",
"os.path.splitext",
"hatesonar.Sonar",
"os.remove"
] | [((334, 341), 'hatesonar.Sonar', 'Sonar', ([], {}), '()\n', (339, 341), False, 'from hatesonar import Sonar\n'), ((356, 378), 'os.path.splitext', 'os.path.splitext', (['path'], {}), '(path)\n', (372, 378), False, 'import os\n'), ((447, 475), 'os.path.exists', 'os.path.exists', (['refined_name'], {}), '(refined_name)\n'... |
#!/usr/bin/env python
import os
from panda3d.core import loadPrcFileData
from wecs import boilerplate
def run_game():
boilerplate.run_game(
module_name='game', # Name of module to use to set up game
console=False, # panda3d-cefconsole
keybindings=True, # panda3d-keybi... | [
"wecs.boilerplate.run_game"
] | [((127, 262), 'wecs.boilerplate.run_game', 'boilerplate.run_game', ([], {'module_name': '"""game"""', 'console': '(False)', 'keybindings': '(True)', 'debug_keys': '(False)', 'simplepbr': '(False)', 'simplepbr_kwargs': 'None'}), "(module_name='game', console=False, keybindings=True,\n debug_keys=False, simplepbr=Fals... |
# Constant RPS bot
name = 'constantbot'
import random
class RPSBot(object):
name = name
def __init__(self):
self.move = random.choice(['R','P','S'])
def get_hint(self, opp_moves, my_moves):
return self.move
def get_move(self, opp_moves, my_moves, opp_hint, my_hint):
return self.m... | [
"random.choice"
] | [((136, 166), 'random.choice', 'random.choice', (["['R', 'P', 'S']"], {}), "(['R', 'P', 'S'])\n", (149, 166), False, 'import random\n')] |
from collections import namedtuple
from .command import Command
from .utils import update_termination_protection, \
is_stack_does_not_exist_exception
class StackDeleteOptions(namedtuple('StackDeleteOptions',
['no_wait',
'ignore_missing'])):... | [
"collections.namedtuple"
] | [((182, 245), 'collections.namedtuple', 'namedtuple', (['"""StackDeleteOptions"""', "['no_wait', 'ignore_missing']"], {}), "('StackDeleteOptions', ['no_wait', 'ignore_missing'])\n", (192, 245), False, 'from collections import namedtuple\n')] |
#/*##########################################################################
#
# The fisx library for X-Ray Fluorescence
#
# Copyright (c) 2020 European Synchrotron Radiation Facility
#
# This file is part of the fisx X-ray developed by <NAME>
#
# Permission is hereby granted, free of charge, to any person obtaining a... | [
"unittest.TestSuite",
"sys.exc_info",
"unittest.TextTestRunner",
"unittest.TestLoader"
] | [((5992, 6012), 'unittest.TestSuite', 'unittest.TestSuite', ([], {}), '()\n', (6010, 6012), False, 'import unittest\n'), ((6533, 6569), 'unittest.TextTestRunner', 'unittest.TextTestRunner', ([], {'verbosity': '(2)'}), '(verbosity=2)\n', (6556, 6569), False, 'import unittest\n'), ((6066, 6087), 'unittest.TestLoader', 'u... |
# Standard Library
import pandas as pd
import statistics as st
import numpy as np
import imdb
from datetime import datetime
from datetime import timedelta
import multiprocessing
import json
import time
import re
import random
import matplotlib.pyplot as plt
# Email Library
from email.mime.text import MIMEText as text
i... | [
"statistics.stdev",
"google.cloud.language.LanguageServiceClient",
"smtplib.SMTP_SSL",
"multiprocessing.Process",
"time.sleep",
"random.choices",
"pymongo.MongoClient",
"datetime.timedelta",
"pandas.notnull",
"pandas.to_datetime",
"numpy.arange",
"textblob.TextBlob",
"google.oauth2.service_a... | [((2499, 2513), 'urllib.request.urlopen', 'uReq', (['page_url'], {}), '(page_url)\n', (2503, 2513), True, 'from urllib.request import urlopen as uReq\n'), ((3213, 3262), 'pandas.DataFrame', 'pd.DataFrame', (['movie_dates_list'], {'columns': "['dates']"}), "(movie_dates_list, columns=['dates'])\n", (3225, 3262), True, '... |
# -*- coding: utf-8 -*-
# Manta Python
# Manta Protocol Implementation for Python
# Copyright (C) 2018-2019 <NAME>
from functools import partial
import logging
from typing import List
import aiohttp
from ..messages import MerchantOrderRequestMessage, Destination, Merchant
from ..payproc import PayProc
from . import ... | [
"logging.getLogger",
"aiohttp.web.HTTPInternalServerError",
"functools.partial",
"aiohttp.web.RouteTableDef",
"aiohttp.web.json_response"
] | [((388, 415), 'logging.getLogger', 'logging.getLogger', (['__name__'], {}), '(__name__)\n', (405, 415), False, 'import logging\n'), ((1042, 1082), 'functools.partial', 'partial', (['_get_destinations', 'destinations'], {}), '(_get_destinations, destinations)\n', (1049, 1082), False, 'from functools import partial\n'), ... |
#!/usr/bin/env python3
# -*- encoding: utf8 -*-
"""
This is an python implementation of preprocessing of
the SEAME Mandarin-English code-switching corpus.
We follow original papers [1, 2] and the official
github repository [3] to make this code produces the
same amount of training and testing data.... | [
"collections.OrderedDict",
"re.escape",
"random.shuffle",
"argparse.ArgumentParser",
"os.makedirs",
"os.path.join",
"random.seed",
"collections.Counter",
"re.sub",
"re.findall"
] | [((839, 851), 'random.seed', 'rd.seed', (['(531)'], {}), '(531)\n', (846, 851), True, 'import random as rd\n'), ((3342, 3389), 're.sub', 're.sub', (['"""\\\\<((pp)(\\\\w)+)\\\\>"""', '"""<noise>"""', 'rmtext'], {}), "('\\\\<((pp)(\\\\w)+)\\\\>', '<noise>', rmtext)\n", (3348, 3389), False, 'import re\n'), ((3966, 4018),... |
from simulator.utils.basic_utils import *
import numpy as np
import pandas as pd
from operator import itemgetter
from itertools import groupby
def rmse(x, y):
x, y = new_array(x), new_array(y)
return np.sqrt(np.mean((x-y)**2))
def row_norm(mat):
""" Compute the norm of a set of vectors, each of which is t... | [
"numpy.nanpercentile",
"numpy.equal",
"numpy.argsort",
"numpy.array",
"numpy.einsum",
"operator.itemgetter",
"numpy.arange",
"numpy.mean",
"numpy.where",
"numpy.diff",
"numpy.stack",
"pandas.DataFrame",
"numpy.meshgrid",
"numpy.rad2deg",
"numpy.round",
"numpy.abs",
"numpy.atleast_1d"... | [((1044, 1077), 'numpy.einsum', 'np.einsum', (['"""ij,ij->i"""', 'mat1', 'mat2'], {}), "('ij,ij->i', mat1, mat2)\n", (1053, 1077), True, 'import numpy as np\n'), ((4817, 4855), 'numpy.nanpercentile', 'np.nanpercentile', (['data'], {'q': 'q', 'axis': 'axis'}), '(data, q=q, axis=axis)\n', (4833, 4855), True, 'import nump... |
from typing import Callable, Optional, TypeVar
from puma.attribute import child_only, child_scope_value, copied, unmanaged
from puma.attribute.mixin import ScopedAttributesMixin
from puma.buffer import DEFAULT_PUBLISH_COMPLETE_TIMEOUT, DEFAULT_PUBLISH_VALUE_TIMEOUT, Publishable, Publisher
from puma.context import Exit... | [
"puma.attribute.child_scope_value",
"puma.attribute.child_only",
"puma.attribute.copied",
"typing.TypeVar",
"puma.attribute.unmanaged"
] | [((462, 478), 'typing.TypeVar', 'TypeVar', (['"""PType"""'], {}), "('PType')\n", (469, 478), False, 'from typing import Callable, Optional, TypeVar\n'), ((847, 860), 'puma.attribute.copied', 'copied', (['"""_id"""'], {}), "('_id')\n", (853, 860), False, 'from puma.attribute import child_only, child_scope_value, copied,... |
from __future__ import absolute_import
import torch
import torch.nn as nn
import torch.nn.functional as F
import pdb
_func_conv_nd_table = {
1: F.conv1d,
2: F.conv2d,
3: F.conv3d
}
def spatial_filter_nd(x, kernel, mode='replicate'):
""" N-dimensional spatial filter with padding.
Args:
x ... | [
"torch.mul",
"torch.mean",
"torch.max",
"torch.sum",
"torch.nn.functional.pad",
"torch.clamp"
] | [((1541, 1575), 'torch.mean', 'torch.mean', (['x'], {'dim': '(1)', 'keepdim': '(True)'}), '(x, dim=1, keepdim=True)\n', (1551, 1575), False, 'import torch\n'), ((1589, 1623), 'torch.mean', 'torch.mean', (['y'], {'dim': '(1)', 'keepdim': '(True)'}), '(y, dim=1, keepdim=True)\n', (1599, 1623), False, 'import torch\n'), (... |
from colorama import init
init(convert=True)
def printRed(skk): print("\033[91m {}\033[00m" .format(skk))
def printGreen(skk): print("\033[92m {}\033[00m" .format(skk))
def printYellow(skk): print("\033[93m {}\033[00m" .format(skk))
def printBlue(skk): print("\033[94m {}\033[00m" .format(skk))
def printPurple(skk): ... | [
"colorama.init"
] | [((27, 45), 'colorama.init', 'init', ([], {'convert': '(True)'}), '(convert=True)\n', (31, 45), False, 'from colorama import init\n')] |
from DCWorkflowGraph import getGraph
from Products.DCWorkflow.DCWorkflow import DCWorkflowDefinition
from Products.PageTemplates.PageTemplateFile import PageTemplateFile
import os
# Import "MessageFactory" to create messages in the DCWorkflowGraph domain
from zope.i18nmessageid import MessageFactory
_ = MessageFactory... | [
"os.path.join",
"zope.i18nmessageid.MessageFactory"
] | [((306, 339), 'zope.i18nmessageid.MessageFactory', 'MessageFactory', (['"""DCWorkflowGraph"""'], {}), "('DCWorkflowGraph')\n", (320, 339), False, 'from zope.i18nmessageid import MessageFactory\n'), ((381, 424), 'os.path.join', 'os.path.join', (['"""www"""', '"""manage_workflowGraph"""'], {}), "('www', 'manage_workflowG... |
#!/usr/bin/env python
import argparse
# import datetime
import os
import sys
# import shlex
# import subprocess
# import pickle
import torch
import yaml
import torch.nn as nn
from datasets.gdi_vis import GDI, Massvis
import models
from trainer import Trainer
import utils
device = torch.device("cuda:1")
def to_dev... | [
"datasets.gdi_vis.GDI",
"torch.manual_seed",
"utils.create_dir",
"models.FCN16s",
"argparse.ArgumentParser",
"torch.load",
"os.path.join",
"torch.optim.lr_scheduler.StepLR",
"torch.cuda.is_available",
"models.FCN32s",
"torch.backends.cudnn.version",
"datasets.gdi_vis.Massvis",
"torch.utils.d... | [((286, 308), 'torch.device', 'torch.device', (['"""cuda:1"""'], {}), "('cuda:1')\n", (298, 308), False, 'import torch\n'), ((1347, 1372), 'argparse.ArgumentParser', 'argparse.ArgumentParser', ([], {}), '()\n', (1370, 1372), False, 'import argparse\n'), ((3450, 3475), 'torch.cuda.is_available', 'torch.cuda.is_available... |
import logging
import os
import shutil
import sys
import tempfile
import click
import numpy as np
import tensorflow as tf
import tensorflow_hub as hub
from word_embeddings import embeddings
def non_zero_tokens(tokens):
"""Receives a batch of vectors of tokens (float) which are zero-padded. Returns a vector of t... | [
"logging.getLogger",
"logging.StreamHandler",
"tensorflow.reduce_sum",
"tensorflow.real",
"tensorflow.string_split",
"tensorflow.gfile.GFile",
"tensorflow.cast",
"tensorflow.reduce_min",
"os.path.exists",
"tensorflow.nn.embedding_lookup",
"tensorflow.Graph",
"tensorflow.pow",
"click.option",... | [((5642, 5657), 'click.command', 'click.command', ([], {}), '()\n', (5655, 5657), False, 'import click\n'), ((5659, 5729), 'click.option', 'click.option', (['"""--export-path"""'], {'help': '"""export path of the tf hub module"""'}), "('--export-path', help='export path of the tf hub module')\n", (5671, 5729), False, '... |
import pytest
from fixture.generic import Generic
from fixture.db import DbFixture
from fixture.orm import ORMFixture
import json
import os.path
import importlib
import jsonpickle
fixture = None
settings = None
def load_config(file):
global settings
if settings is None:
config_file = os.path.join(os.... | [
"fixture.db.DbFixture",
"importlib.import_module",
"json.load",
"pytest.fixture",
"fixture.orm.ORMFixture",
"fixture.generic.Generic"
] | [((882, 913), 'pytest.fixture', 'pytest.fixture', ([], {'scope': '"""session"""'}), "(scope='session')\n", (896, 913), False, 'import pytest\n'), ((1252, 1283), 'pytest.fixture', 'pytest.fixture', ([], {'scope': '"""session"""'}), "(scope='session')\n", (1266, 1283), False, 'import pytest\n'), ((1560, 1605), 'pytest.fi... |
"""
### author: <NAME>
### <EMAIL>
### date: 9/10/2018
"""
import os
import numpy as np
sep = os.sep
def get_class_weights(y):
"""
:param y: labels
:return: correct weights of each classes for balanced training
"""
cls, count = np.unique(y, return_counts=True)
counter = dict(zip(cls, count)... | [
"numpy.flip",
"numpy.unique"
] | [((253, 285), 'numpy.unique', 'np.unique', (['y'], {'return_counts': '(True)'}), '(y, return_counts=True)\n', (262, 285), True, 'import numpy as np\n'), ((547, 576), 'numpy.flip', 'np.flip', (['copy0.working_arr', '(0)'], {}), '(copy0.working_arr, 0)\n', (554, 576), True, 'import numpy as np\n'), ((832, 861), 'numpy.fl... |
import numpy as np
import segyio
import pyvds
VDS_FILE = 'test_data/small.vds'
SGY_FILE = 'test_data/small.sgy'
def compare_inline_ordinal(vds_filename, sgy_filename, lines_to_test, tolerance):
with pyvds.open(vds_filename) as vdsfile:
with segyio.open(sgy_filename) as segyfile:
for line_ordi... | [
"numpy.allclose",
"pyvds.tools.dt",
"segyio.tools.cube",
"segyio.tools.dt",
"pyvds.tools.cube",
"numpy.asarray",
"pyvds.open",
"numpy.array_equal",
"segyio.open"
] | [((5742, 5773), 'segyio.tools.cube', 'segyio.tools.cube', (['sgy_filename'], {}), '(sgy_filename)\n', (5759, 5773), False, 'import segyio\n'), ((5788, 5818), 'pyvds.tools.cube', 'pyvds.tools.cube', (['vds_filename'], {}), '(vds_filename)\n', (5804, 5818), False, 'import pyvds\n'), ((5830, 5875), 'numpy.allclose', 'np.a... |
import time
from numbers import Rational
class Context:
def __init__(self, payload):
self.message = payload['message'].strip()
self.message_id = payload.get('message_id')
if self.message.startswith('/'): # message[0] will cause error if message is ''
message = self.message[1:]... | [
"time.time"
] | [((1035, 1046), 'time.time', 'time.time', ([], {}), '()\n', (1044, 1046), False, 'import time\n'), ((2117, 2128), 'time.time', 'time.time', ([], {}), '()\n', (2126, 2128), False, 'import time\n')] |
# Generated by Django 3.2.9 on 2021-12-03 14:26
from django.db import migrations, models
class Migration(migrations.Migration):
initial = True
dependencies = []
operations = [
migrations.CreateModel(
name="Address",
fields=[
(
"name",... | [
"django.db.models.TextField",
"django.db.models.BooleanField",
"django.db.models.BigAutoField",
"django.db.models.DateTimeField",
"django.db.models.CharField"
] | [((341, 408), 'django.db.models.CharField', 'models.CharField', ([], {'max_length': '(255)', 'primary_key': '(True)', 'serialize': '(False)'}), '(max_length=255, primary_key=True, serialize=False)\n', (357, 408), False, 'from django.db import migrations, models\n'), ((458, 490), 'django.db.models.CharField', 'models.Ch... |
import os
from setuptools import setup, find_packages
with open('requirements.txt') as f:
requirements = f.readlines()
with open(os.path.join('.', 'README.md'), encoding='utf-8') as f:
long_description = f.read()
setup(
name='etabar',
version='0.0.2',
author='<NAME>',
author_email='<EMAIL>',
... | [
"setuptools.find_packages",
"os.path.join"
] | [((135, 165), 'os.path.join', 'os.path.join', (['"""."""', '"""README.md"""'], {}), "('.', 'README.md')\n", (147, 165), False, 'import os\n'), ((548, 563), 'setuptools.find_packages', 'find_packages', ([], {}), '()\n', (561, 563), False, 'from setuptools import setup, find_packages\n')] |
# -*- coding: utf-8 -*-
"""
Module of Lauetools project
<NAME> Feb 2012
module to fit orientation and strain
http://sourceforge.net/projects/lauetools/
"""
__author__ = "<NAME>, CRG-IF BM32 @ ESRF"
from scipy.optimize import leastsq, least_squares
import numpy as np
np.set_printoptions(precision=15)
from scipy.li... | [
"numpy.sqrt",
"numpy.hstack",
"lauetoolsnn.lauetools.LaueGeometry.from_qunit_to_twchi",
"numpy.array",
"numpy.sin",
"lauetoolsnn.lauetools.CrystalParameters.calc_B_RR",
"numpy.arange",
"scipy.linalg.qr",
"numpy.mean",
"scipy.optimize.least_squares",
"numpy.where",
"numpy.take",
"scipy.optimi... | [((273, 306), 'numpy.set_printoptions', 'np.set_printoptions', ([], {'precision': '(15)'}), '(precision=15)\n', (292, 306), True, 'import numpy as np\n'), ((903, 912), 'numpy.eye', 'np.eye', (['(3)'], {}), '(3)\n', (909, 912), True, 'import numpy as np\n'), ((1054, 1080), 'numpy.zeros', 'np.zeros', (['nn'], {'dtype': '... |
import os
import tensorflow as tf
from tensorflow.python.tools import freeze_graph
def save_model(folder_name, t=0):
save_path = folder_name + '/model-' + str(t) + '.cptk'
os.makedirs(os.path.dirname(save_path), exist_ok=True)
saver = tf.train.Saver()
result = saver.save(tf.keras.backend.get_session(... | [
"tensorflow.keras.backend.get_session",
"tensorflow.train.Saver",
"tensorflow.train.get_checkpoint_state",
"os.path.dirname",
"tensorflow.python.tools.freeze_graph.freeze_graph"
] | [((250, 266), 'tensorflow.train.Saver', 'tf.train.Saver', ([], {}), '()\n', (264, 266), True, 'import tensorflow as tf\n'), ((996, 1038), 'tensorflow.train.get_checkpoint_state', 'tf.train.get_checkpoint_state', (['folder_name'], {}), '(folder_name)\n', (1025, 1038), True, 'import tensorflow as tf\n'), ((1043, 1427), '... |
"""Action selector implementations.
Action selectors are objects that when called return a desired
action. These actions may be stochastically chosen (e.g. randomly chosen
from a list of candidates) depending on the choice of `ActionSelector`
implementation, and how it is configured.
Examples include the following
* ... | [
"numpy.array",
"numpy.random.default_rng"
] | [((1845, 1880), 'numpy.random.default_rng', 'np.random.default_rng', (['random_state'], {}), '(random_state)\n', (1866, 1880), True, 'import numpy as np\n'), ((2706, 2741), 'numpy.random.default_rng', 'np.random.default_rng', (['random_state'], {}), '(random_state)\n', (2727, 2741), True, 'import numpy as np\n'), ((403... |
from random import randint, random
def throw_rigged():
if random() < 0.22:
return 6
return randint(1, 5)
| [
"random.random",
"random.randint"
] | [((109, 122), 'random.randint', 'randint', (['(1)', '(5)'], {}), '(1, 5)\n', (116, 122), False, 'from random import randint, random\n'), ((64, 72), 'random.random', 'random', ([], {}), '()\n', (70, 72), False, 'from random import randint, random\n')] |
import numpy as np
from abc import ABC, abstractmethod
# Defining base loss class
class Loss(ABC):
@abstractmethod
def __call__(self, pred, target):
pass
@abstractmethod
def gradient(self, *args, **kwargs):
pass
class MSELoss(Loss):
def __call__(self, pred, target):
re... | [
"numpy.maximum",
"numpy.square"
] | [((325, 349), 'numpy.square', 'np.square', (['(pred - target)'], {}), '(pred - target)\n', (334, 349), True, 'import numpy as np\n'), ((538, 550), 'numpy.square', 'np.square', (['w'], {}), '(w)\n', (547, 550), True, 'import numpy as np\n'), ((734, 757), 'numpy.maximum', 'np.maximum', (['pred', '(1e-09)'], {}), '(pred, ... |
import datetime
from http import HTTPStatus
from sanic.response import json
from core.helpers import jsonapi
from apps.commons.errors import DataNotFoundError
from apps.news.models import News
from apps.news.repository import NewsRepo
from apps.news.services import UpdateService
async def update(request, id):
r... | [
"sanic.response.json",
"apps.news.repository.NewsRepo",
"core.helpers.jsonapi.format_error",
"core.helpers.jsonapi.return_an_error",
"apps.news.services.UpdateService"
] | [((372, 386), 'apps.news.repository.NewsRepo', 'NewsRepo', (['News'], {}), '(News)\n', (380, 386), False, 'from apps.news.repository import NewsRepo\n'), ((401, 438), 'apps.news.services.UpdateService', 'UpdateService', (['id', 'request.json', 'repo'], {}), '(id, request.json, repo)\n', (414, 438), False, 'from apps.ne... |
from flask import Blueprint
home_blu = Blueprint('index', __name__)
from . import views
| [
"flask.Blueprint"
] | [((40, 68), 'flask.Blueprint', 'Blueprint', (['"""index"""', '__name__'], {}), "('index', __name__)\n", (49, 68), False, 'from flask import Blueprint\n')] |
from node import *
from symbol_table import SymbolTable
from prepro import PrePro
from lexer import Tokenizer
class Parser:
@staticmethod
def parseProgram():
statements = []
if Parser.tokens.actual.type == "SUB":
Parser.tokens.selectNext()
if Parser.tokens.actual.type =... | [
"prepro.PrePro.filtra",
"symbol_table.SymbolTable"
] | [((12353, 12366), 'symbol_table.SymbolTable', 'SymbolTable', ([], {}), '()\n', (12364, 12366), False, 'from symbol_table import SymbolTable\n'), ((12401, 12420), 'prepro.PrePro.filtra', 'PrePro.filtra', (['code'], {}), '(code)\n', (12414, 12420), False, 'from prepro import PrePro\n')] |
# -*- coding: utf-8 -*-
# Generated by Django 1.11.20 on 2019-03-21 08:58
from __future__ import unicode_literals
import django.contrib.postgres.fields
from django.db import migrations, models
class Migration(migrations.Migration):
dependencies = [
('project', '0078_auto_20181016_1513'),
]
oper... | [
"django.db.models.CharField"
] | [((492, 699), 'django.db.models.CharField', 'models.CharField', ([], {'choices': "[('Ref', 'Refugees'), ('Asy', 'Asylum seekers'), ('IDP',\n 'Internally displaced persons'), ('Sta', 'Stateless'), ('Ret',\n 'Returning'), ('Hos', 'Host Country')]", 'max_length': '(3)'}), "(choices=[('Ref', 'Refugees'), ('Asy', 'Asy... |
import numpy as np
import os.path
import pandas as pd
def read_driving_log(logs_path):
df = pd.read_csv(logs_path, names=["center_img", "left_img", "right_img",
"steering_angle", "throttle", "break",
"speed"])
for col in ["center_img", "l... | [
"pandas.read_csv"
] | [((96, 217), 'pandas.read_csv', 'pd.read_csv', (['logs_path'], {'names': "['center_img', 'left_img', 'right_img', 'steering_angle', 'throttle',\n 'break', 'speed']"}), "(logs_path, names=['center_img', 'left_img', 'right_img',\n 'steering_angle', 'throttle', 'break', 'speed'])\n", (107, 217), True, 'import pandas... |
import urllib.request
import json
from datetime import date
today = date.today().strftime("%Y-%m-%d")
url = "https://projects.fivethirtyeight.com/trump-approval-ratings/approval.json"
data = urllib.request.urlopen(url)
data = json.loads(data.read().decode('utf-8'))
approve_sum = 0
disapprove_sum = 0
coun... | [
"datetime.date.today"
] | [((73, 85), 'datetime.date.today', 'date.today', ([], {}), '()\n', (83, 85), False, 'from datetime import date\n')] |
#!/usr/bin/env python
# -*- coding: utf-8 -*-
import urllib
from django.contrib.contenttypes.models import ContentType
from django.db import models
from tagging.models import Tag
class HistoryMixin(models.Model):
# creation date time
added_at = models.DateTimeField(auto_now_add=True)
# last modified dat... | [
"tagging.models.Tag.objects.update_tags",
"tagging.models.Tag.objects.get_for_object",
"django.contrib.contenttypes.models.ContentType.objects.get_for_model",
"django.db.models.TextField",
"django.db.models.ForeignKey",
"django.db.models.IntegerField",
"urllib.quote",
"tagging.models.Tag.objects.filte... | [((257, 296), 'django.db.models.DateTimeField', 'models.DateTimeField', ([], {'auto_now_add': '(True)'}), '(auto_now_add=True)\n', (277, 296), False, 'from django.db import models\n'), ((345, 380), 'django.db.models.DateTimeField', 'models.DateTimeField', ([], {'auto_now': '(True)'}), '(auto_now=True)\n', (365, 380), F... |
from __future__ import absolute_import
import os
from celery import Celery
from celery.schedules import crontab
from django.apps import apps, AppConfig
from django.conf import settings
if not settings.configured:
# set the default Django settings module for the 'celery' program.
os.environ.setdefault('DJAN... | [
"os.environ.setdefault",
"celery.Celery",
"django.apps.apps.get_app_configs",
"celery.schedules.crontab"
] | [((394, 411), 'celery.Celery', 'Celery', (['"""octopus"""'], {}), "('octopus')\n", (400, 411), False, 'from celery import Celery\n'), ((293, 365), 'os.environ.setdefault', 'os.environ.setdefault', (['"""DJANGO_SETTINGS_MODULE"""', '"""config.settings.local"""'], {}), "('DJANGO_SETTINGS_MODULE', 'config.settings.local')... |
import argparse
import pandas as pd
import matplotlib
matplotlib.use('Agg') # NOQA
import matplotlib.pyplot as plt
import seaborn as sns
from example import Results
def process_results(results, verbose=False):
baseline = results.best_baseline()
def like_baseline(x):
for key in ('n_iter',
... | [
"argparse.ArgumentParser",
"matplotlib.pyplot.ylabel",
"matplotlib.use",
"matplotlib.pyplot.xlabel",
"matplotlib.pyplot.plot",
"seaborn.set_style",
"matplotlib.pyplot.close",
"matplotlib.pyplot.title",
"matplotlib.pyplot.legend"
] | [((56, 77), 'matplotlib.use', 'matplotlib.use', (['"""Agg"""'], {}), "('Agg')\n", (70, 77), False, 'import matplotlib\n'), ((1398, 1423), 'seaborn.set_style', 'sns.set_style', (['"""darkgrid"""'], {}), "('darkgrid')\n", (1411, 1423), True, 'import seaborn as sns\n'), ((1743, 1778), 'matplotlib.pyplot.ylabel', 'plt.ylab... |
import numpy as np
import tensorflow as tf
from tensorflow.keras.layers import Dense, Input
from tensorflow.keras.models import Model
def build_model(bert_layer, max_len=512):
input_word_ids = Input(shape=(max_len, ), dtype=tf.int32, name='input_word_ids')
input_mask = Input(shape=(max_len, ), dtype=tf.int32... | [
"tensorflow.keras.models.Model",
"tensorflow.keras.layers.Input"
] | [((200, 262), 'tensorflow.keras.layers.Input', 'Input', ([], {'shape': '(max_len,)', 'dtype': 'tf.int32', 'name': '"""input_word_ids"""'}), "(shape=(max_len,), dtype=tf.int32, name='input_word_ids')\n", (205, 262), False, 'from tensorflow.keras.layers import Dense, Input\n'), ((281, 339), 'tensorflow.keras.layers.Input... |
import asyncio
import random
import discord
from discord.ext import commands
import yaml
with open('config.yaml') as config_file:
config = yaml.load(config_file, Loader=yaml.FullLoader)
class TicTacToe():
def __init__(self):
# Emotes Section
self.white_page = config['white_page']
self... | [
"discord.ext.commands.command",
"random.choice",
"discord.Embed",
"yaml.load"
] | [((145, 191), 'yaml.load', 'yaml.load', (['config_file'], {'Loader': 'yaml.FullLoader'}), '(config_file, Loader=yaml.FullLoader)\n', (154, 191), False, 'import yaml\n'), ((3701, 3735), 'discord.ext.commands.command', 'commands.command', ([], {'usage': '"""[Member]"""'}), "(usage='[Member]')\n", (3717, 3735), False, 'fr... |
# yazar: <NAME>
import os
# Dosyalama işlemleri için sınıflar -----------------------------------------
# Dosya sınıfı asıl dosyalama sınıfıdır. ------------------------------------
class Dosya:
sembol="+"
çıkış="---"
başlık_sembol="> "
def oku(yol):
if os.path.isfile(yol):
try:... | [
"os.path.split",
"os.path.isfile",
"os.path.isdir",
"os.system",
"os.remove"
] | [((283, 302), 'os.path.isfile', 'os.path.isfile', (['yol'], {}), '(yol)\n', (297, 302), False, 'import os\n'), ((828, 847), 'os.path.isfile', 'os.path.isfile', (['yol'], {}), '(yol)\n', (842, 847), False, 'import os\n'), ((2006, 2025), 'os.path.isfile', 'os.path.isfile', (['yol'], {}), '(yol)\n', (2020, 2025), False, '... |
import glob
import xml.etree.ElementTree as ET
from unittest import TestCase
import numpy as np
from kmeans import kmeans, avg_iou
ANNOTATIONS_PATH = "Annotations"
class TestVoc2007(TestCase):
def __load_dataset(self):
dataset = []
for xml_file in glob.glob("{}/*xml".format(ANNOTATIONS_PATH)):
... | [
"xml.etree.ElementTree.parse",
"kmeans.avg_iou",
"kmeans.kmeans",
"numpy.array",
"numpy.testing.assert_almost_equal"
] | [((850, 867), 'numpy.array', 'np.array', (['dataset'], {}), '(dataset)\n', (858, 867), True, 'import numpy as np\n'), ((953, 971), 'kmeans.kmeans', 'kmeans', (['dataset', '(5)'], {}), '(dataset, 5)\n', (959, 971), False, 'from kmeans import kmeans, avg_iou\n'), ((993, 1014), 'kmeans.avg_iou', 'avg_iou', (['dataset', 'o... |
'''
This example show how to perform a DMR topic model using tomotopy
and visualize the topic distribution for each metadata
Required Packages:
matplotlib
'''
import tomotopy as tp
import numpy as np
import matplotlib.pyplot as plt
'''
You can get the sample data file from https://drive.google.com/file/d/1AUHdwa... | [
"tomotopy.utils.Corpus",
"tomotopy.DMRModel",
"matplotlib.pyplot.subplots",
"numpy.arange",
"matplotlib.pyplot.show"
] | [((380, 397), 'tomotopy.utils.Corpus', 'tp.utils.Corpus', ([], {}), '()\n', (395, 397), True, 'import tomotopy as tp\n'), ((652, 706), 'tomotopy.DMRModel', 'tp.DMRModel', ([], {'tw': 'tp.TermWeight.PMI', 'k': '(15)', 'corpus': 'corpus'}), '(tw=tp.TermWeight.PMI, k=15, corpus=corpus)\n', (663, 706), True, 'import tomoto... |
"""
Functions for making a consistent dataset with fixed and free variables as is expected in our dataset.
"""
import logging
import sys
from itertools import chain
from pathlib import Path
import numpy as np
import pandas as pd
import sympy
from src.util import get_free_fluxes
RT = 0.008314 * 298.15
logger = loggi... | [
"logging.getLogger",
"numpy.identity",
"numpy.flip",
"numpy.linalg.solve",
"numpy.ones",
"pandas.read_csv",
"pathlib.Path",
"numpy.log",
"sympy.Matrix",
"sympy.symbols",
"numpy.array",
"numpy.zeros",
"itertools.chain.from_iterable",
"sys.exit",
"numpy.full",
"numpy.random.randn"
] | [((315, 342), 'logging.getLogger', 'logging.getLogger', (['__name__'], {}), '(__name__)\n', (332, 342), False, 'import logging\n'), ((813, 852), 'numpy.zeros', 'np.zeros', (['(n_rxns, n_exchange + n_mets)'], {}), '((n_rxns, n_exchange + n_mets))\n', (821, 852), True, 'import numpy as np\n'), ((889, 912), 'numpy.identit... |
import unittest
from SheldonGame import SheldonGame
class SheldonGameTest(unittest.TestCase):
def test_scissors_wins_paper(self):
game = SheldonGame()
result = game.calculate_sheldon_result('scissors', 'paper')
self.assertEqual('Scissors wins', result)
def test_scissors_wins_lizard(... | [
"unittest.main",
"SheldonGame.SheldonGame"
] | [((2814, 2829), 'unittest.main', 'unittest.main', ([], {}), '()\n', (2827, 2829), False, 'import unittest\n'), ((153, 166), 'SheldonGame.SheldonGame', 'SheldonGame', ([], {}), '()\n', (164, 166), False, 'from SheldonGame import SheldonGame\n'), ((342, 355), 'SheldonGame.SheldonGame', 'SheldonGame', ([], {}), '()\n', (3... |
from extract_place import extract_place
from compress_dataset import compress
benchmark_dir = './benchmark/'
path_to_json = './benchmark/JsonFile/'
compressed_data = "./data/data.hdf5"
OTA1 = 'Telescopic_Three_stage'
OTA2 = 'Telescopic_Three_stage_1'
OTA3 = 'Core_test_flow'
OTA4 = 'Core_FF'
# Extract raw feature ima... | [
"compress_dataset.compress.compress",
"extract_place.extract_place.main"
] | [((369, 422), 'extract_place.extract_place.main', 'extract_place.main', (['benchmark_dir', 'path_to_json', 'OTA1'], {}), '(benchmark_dir, path_to_json, OTA1)\n', (387, 422), False, 'from extract_place import extract_place\n'), ((468, 521), 'extract_place.extract_place.main', 'extract_place.main', (['benchmark_dir', 'pa... |
'''
MIT License
Copyright (c) [2018] <NAME> (<EMAIL>). Universidad de Alcalá. Spain
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... | [
"xml.etree.ElementTree.parse",
"math.pow",
"TrATVid.Trajectory.Trajectory.CreateTrajectoryFromXML",
"math.log",
"fileinput.input"
] | [((2469, 2500), 'xml.etree.ElementTree.parse', 'ElementTree.parse', (['settingsFile'], {}), '(settingsFile)\n', (2486, 2500), False, 'from xml.etree import ElementTree\n'), ((2906, 2931), 'fileinput.input', 'fileinput.input', (['listFile'], {}), '(listFile)\n', (2921, 2931), False, 'import fileinput\n'), ((3126, 3152),... |
from numpy import matlib
import matplotlib.pyplot as plt
import numpy as np
from scipy.sparse.linalg import svds
from scipy.sparse import csc_matrix
class ohmlr(object):
def __init__(self, x_classes=None, y_classes=None, random_coeff=False):
self.x_classes = x_classes
self.y_classes = y_classes
... | [
"numpy.asmatrix",
"numpy.log",
"scipy.sparse.linalg.svds",
"numpy.arange",
"numpy.multiply",
"numpy.sort",
"numpy.asarray",
"numpy.exp",
"numpy.stack",
"numpy.vstack",
"numpy.random.normal",
"numpy.ones",
"numpy.matlib.zeros",
"numpy.isclose",
"numpy.unique",
"numpy.power",
"numpy.su... | [((1943, 1978), 'numpy.asarray', 'np.asarray', (['[u_map[ui] for ui in u]'], {}), '([u_map[ui] for ui in u])\n', (1953, 1978), True, 'import numpy as np\n'), ((2177, 2190), 'numpy.asarray', 'np.asarray', (['x'], {}), '(x)\n', (2187, 2190), True, 'import numpy as np\n'), ((2482, 2495), 'numpy.asarray', 'np.asarray', (['... |
"""
This module provides helpers to setup the cytoscape graph style
"""
import logging
# TODO pattern builder
class StyleBuilder():
logger = logging.getLogger(__name__)
@classmethod
def __init__(self, schema):
self.schema = schema
self.graph_style = None
self.levels_colors = ['#BB... | [
"logging.getLogger"
] | [((147, 174), 'logging.getLogger', 'logging.getLogger', (['__name__'], {}), '(__name__)\n', (164, 174), False, 'import logging\n')] |
import pytest
from mongoengine import connect
@pytest.fixture
def setup_mongo():
connect(host='mongomock://localhost', db='graphene-mongo-extras')
| [
"mongoengine.connect"
] | [((87, 152), 'mongoengine.connect', 'connect', ([], {'host': '"""mongomock://localhost"""', 'db': '"""graphene-mongo-extras"""'}), "(host='mongomock://localhost', db='graphene-mongo-extras')\n", (94, 152), False, 'from mongoengine import connect\n')] |
import time
def unwrap(func):
while hasattr(func, '__wrapped__'):
func = func.__wrapped__
return func
class LoggingMiddleware:
def __init__(self, get_response=None):
self.get_response = get_response
self.PURPLE = "\033[0;35m"
self.CYAN = "\033[0;36m"
self.LIGHT_GR... | [
"time.process_time"
] | [((1150, 1169), 'time.process_time', 'time.process_time', ([], {}), '()\n', (1167, 1169), False, 'import time\n'), ((1603, 1622), 'time.process_time', 'time.process_time', ([], {}), '()\n', (1620, 1622), False, 'import time\n')] |
import torch
import os
def test_batch(src_field, trg_field, translator, batch, device, max_examples=32):
with torch.no_grad():
source = batch.src.to(device)
target = batch.trg.to(device)
translator_batch = torch.argmax(translator(source, target.shape[0] - 1), dim=2)
for i, (de_example,... | [
"os.path.exists",
"torch.no_grad",
"os.path.join",
"os.mkdir"
] | [((1079, 1112), 'os.path.exists', 'os.path.exists', (['checkpoint_folder'], {}), '(checkpoint_folder)\n', (1093, 1112), False, 'import os\n'), ((1488, 1541), 'os.path.join', 'os.path.join', (['checkpoint_folder', 'f"""epoch_{epoch}.pth"""'], {}), "(checkpoint_folder, f'epoch_{epoch}.pth')\n", (1500, 1541), False, 'impo... |
# python3
# Copyright 2018 DeepMind Technologies Limited. All rights reserved.
#
# Licensed under the Apache License, Version 2.0 (the "License");
# you may not use this file except in compliance with the License.
# You may obtain a copy of the License at
#
# http://www.apache.org/licenses/LICENSE-2.0
#
# Unless re... | [
"acme.adders.reverb.utils.calculate_priorities",
"acme.adders.reverb.utils.final_step_like"
] | [((2184, 2246), 'acme.adders.reverb.utils.final_step_like', 'utils.final_step_like', (['self._buffer[0]', 'self._next_observation'], {}), '(self._buffer[0], self._next_observation)\n', (2205, 2246), False, 'from acme.adders.reverb import utils\n'), ((2543, 2596), 'acme.adders.reverb.utils.calculate_priorities', 'utils.... |
#! /usr/bin/env python
# -*- coding: utf-8 -*-
"""
@version:
@author: li
@file: factor_operation_capacity.py
@time: 2019-05-30
"""
import gc
import sys
sys.path.append('../')
sys.path.append('../../')
sys.path.append('../../../')
import six, pdb
import pandas as pd
from pandas.io.json import json_normalize
from utili... | [
"six.add_metaclass",
"pandas.merge",
"pandas.set_option",
"pandas.DataFrame",
"sys.path.append"
] | [((154, 176), 'sys.path.append', 'sys.path.append', (['"""../"""'], {}), "('../')\n", (169, 176), False, 'import sys\n'), ((177, 202), 'sys.path.append', 'sys.path.append', (['"""../../"""'], {}), "('../../')\n", (192, 202), False, 'import sys\n'), ((203, 231), 'sys.path.append', 'sys.path.append', (['"""../../../"""']... |
#!/usr/bin/env python
# coding: utf-8
# In[1]:
#move this notebook to folder above syndef to run
from syndef import synfits #import synestia snapshot (impact database)
import numpy as np
import matplotlib.pyplot as plt
test_rxy=np.linspace(7e6,60e6,100) #m
test_z=np.linspace(0.001e6,30e6,50) #m
rxy=np.log10(test_rx... | [
"numpy.log10",
"matplotlib.pyplot.title",
"matplotlib.pyplot.ylabel",
"numpy.power",
"matplotlib.pyplot.xlabel",
"matplotlib.pyplot.plot",
"matplotlib.pyplot.colorbar",
"matplotlib.pyplot.close",
"numpy.linspace",
"matplotlib.pyplot.figure",
"matplotlib.pyplot.scatter",
"numpy.meshgrid",
"ma... | [((232, 271), 'numpy.linspace', 'np.linspace', (['(7000000.0)', '(60000000.0)', '(100)'], {}), '(7000000.0, 60000000.0, 100)\n', (243, 271), True, 'import numpy as np\n'), ((268, 303), 'numpy.linspace', 'np.linspace', (['(1000.0)', '(30000000.0)', '(50)'], {}), '(1000.0, 30000000.0, 50)\n', (279, 303), True, 'import nu... |
#!/usr/bin/python
import time
import re
import os
class ScavUtility:
def __init__(self):
pass
def check(self, email):
regex = '^(?=.{1,64}@)[A-Za-z0-9_-]+(\\.[A-Za-z0-9_-]+)*@[^-][A-Za-z0-9-]+(\\.[A-Za-z0-9-]+)*(\\.[A-Za-z]{2,})$'
if(re.search(regex,email)):
return 1
else:
return 0
def loadSearchTe... | [
"os.listdir",
"os.path.join",
"os.system",
"time.time",
"re.search"
] | [((245, 268), 're.search', 're.search', (['regex', 'email'], {}), '(regex, email)\n', (254, 268), False, 'import re\n'), ((744, 809), 'os.system', 'os.system', (["('zip -r pastebin_' + archivefilename + ' ' + directory)"], {}), "('zip -r pastebin_' + archivefilename + ' ' + directory)\n", (753, 809), False, 'import os\... |
#!/usr/bin/env python
# coding: utf-8
from __future__ import absolute_import, division, print_function, unicode_literals
import io, os, sys, unittest
pkg_root = os.path.abspath(os.path.join(os.path.dirname(__file__), '..')) # noqa
sys.path.insert(0, pkg_root) # noqa
from dcplib import s3_multipart
from dcplib.chec... | [
"os.path.getsize",
"sys.path.insert",
"dcplib.s3_multipart.get_s3_multipart_chunk_size",
"io.open",
"os.path.dirname",
"dcplib.checksumming_io.ChecksummingBufferedReader",
"unittest.main"
] | [((234, 262), 'sys.path.insert', 'sys.path.insert', (['(0)', 'pkg_root'], {}), '(0, pkg_root)\n', (249, 262), False, 'import io, os, sys, unittest\n'), ((487, 513), 'os.path.getsize', 'os.path.getsize', (['TEST_FILE'], {}), '(TEST_FILE)\n', (502, 513), False, 'import io, os, sys, unittest\n'), ((531, 582), 'dcplib.s3_m... |
# Copyright 2016 Canonical Limited.
#
# 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 writi... | [
"charmhelpers.contrib.hardening.audits.BaseAudit"
] | [((834, 845), 'charmhelpers.contrib.hardening.audits.BaseAudit', 'BaseAudit', ([], {}), '()\n', (843, 845), False, 'from charmhelpers.contrib.hardening.audits import BaseAudit\n'), ((987, 1009), 'charmhelpers.contrib.hardening.audits.BaseAudit', 'BaseAudit', ([], {'unless': '(True)'}), '(unless=True)\n', (996, 1009), F... |
# KicadModTree is free software: you can redistribute it and/or
# modify it under the terms of the GNU General Public License as published by
# the Free Software Foundation, either version 3 of the License, or
# (at your option) any later version.
#
# KicadModTree is distributed in the hope that it will be useful,
# bu... | [
"csv.DictReader",
"argparse.ArgumentParser",
"yaml.dump",
"yaml.safe_load",
"sys.exit"
] | [((4251, 4360), 'argparse.ArgumentParser', 'argparse.ArgumentParser', ([], {'description': '"""Parse footprint definition file(s) and create matching footprints"""'}), "(description=\n 'Parse footprint definition file(s) and create matching footprints')\n", (4274, 4360), False, 'import argparse\n'), ((5667, 5678), '... |
from django.urls import path
from . import views
urlpatterns = [
path('', views.index, name='index'),
path('generate_dashboard_presentation', views.generate_dashboard_presentation, name='generate_dashboard_presentation'),
path('action_form', views.action_form, name='action_form'),
] | [
"django.urls.path"
] | [((71, 106), 'django.urls.path', 'path', (['""""""', 'views.index'], {'name': '"""index"""'}), "('', views.index, name='index')\n", (75, 106), False, 'from django.urls import path\n'), ((112, 235), 'django.urls.path', 'path', (['"""generate_dashboard_presentation"""', 'views.generate_dashboard_presentation'], {'name': ... |
# -*- coding: UTF-8 -*-
import os
from six import PY3
from pydruid.utils import query_utils
def open_file(file_path):
if PY3:
f = open(file_path, 'w', newline='', encoding='utf-8')
else:
f = open(file_path, 'wb')
return f
def line_ending():
if PY3:
return os.linesep
retu... | [
"pydruid.utils.query_utils.UnicodeWriter"
] | [((488, 516), 'pydruid.utils.query_utils.UnicodeWriter', 'query_utils.UnicodeWriter', (['f'], {}), '(f)\n', (513, 516), False, 'from pydruid.utils import query_utils\n'), ((766, 794), 'pydruid.utils.query_utils.UnicodeWriter', 'query_utils.UnicodeWriter', (['f'], {}), '(f)\n', (791, 794), False, 'from pydruid.utils imp... |
import random
from .game import Game
from .board import Board
from .player import Human, SimpleAI
from .tokens import PLAYER_TOKENS
from .ui import ConsoleUserInterface
def main():
tokens = list(PLAYER_TOKENS)
random.shuffle(tokens)
Game(
ConsoleUserInterface(),
Board(),
tuple(toke... | [
"random.randint",
"random.shuffle"
] | [((220, 242), 'random.shuffle', 'random.shuffle', (['tokens'], {}), '(tokens)\n', (234, 242), False, 'import random\n'), ((360, 380), 'random.randint', 'random.randint', (['(0)', '(1)'], {}), '(0, 1)\n', (374, 380), False, 'import random\n')] |
import logging
from datetime import datetime
from pathlib import Path
from lib.entities import Source
from lib.library.datetime_path_resolver import DatetimePathResolver
from lib.util.file_utils import copy
from lib.library.parameterized_path_resolver import ParameterizedPathResolver
logger = logging.getLogger("FileS... | [
"logging.getLogger",
"lib.util.file_utils.copy",
"lib.library.parameterized_path_resolver.ParameterizedPathResolver"
] | [((296, 326), 'logging.getLogger', 'logging.getLogger', (['"""FileStore"""'], {}), "('FileStore')\n", (313, 326), False, 'import logging\n'), ((935, 958), 'lib.util.file_utils.copy', 'copy', (['file', 'destination'], {}), '(file, destination)\n', (939, 958), False, 'from lib.util.file_utils import copy\n'), ((493, 544)... |
import logging
import uuid
from datetime import datetime
from typing import List, Sequence, Set, cast
import grpc
import sqlalchemy.orm
from common.constants import PAGINATION_LIMIT, Currency
from common.utils.datetime import datetime_to_protobuf, protobuf_to_datetime
from common.utils.uuid import bytes_to_uuid
from g... | [
"logging.getLogger",
"google.protobuf.any_pb2.Any",
"backend.sql.account.Account.currency.in_",
"backend.sql.account.Account.account_type.in_",
"sqlalchemy.desc",
"backend.sql.transaction.Transaction.transaction_type.in_",
"common.utils.datetime.datetime_to_protobuf",
"backend.sql.account.Account",
... | [((1144, 1171), 'logging.getLogger', 'logging.getLogger', (['__name__'], {}), '(__name__)\n', (1161, 1171), False, 'import logging\n'), ((6594, 6626), 'common.utils.uuid.bytes_to_uuid', 'bytes_to_uuid', (['request.accountId'], {}), '(request.accountId)\n', (6607, 6626), False, 'from common.utils.uuid import bytes_to_uu... |
from pytest_cases import parametrize
from tests.conftest import get_expected_put_headers
from tests.sms.conftest import (
GenerateRescheduleSMSMessagesFactory,
GenerateUpdateScheduledSMSMessagesStatusFactory,
get_reschedule_sms_messages_query_parameters,
get_scheduled_sms_messages_response,
get_sms... | [
"tests.sms.conftest.get_reschedule_sms_messages_query_parameters",
"tests.sms.conftest.get_sms_request_error_response",
"tests.conftest.get_expected_put_headers"
] | [((558, 584), 'tests.conftest.get_expected_put_headers', 'get_expected_put_headers', ([], {}), '()\n', (582, 584), False, 'from tests.conftest import get_expected_put_headers\n'), ((795, 841), 'tests.sms.conftest.get_reschedule_sms_messages_query_parameters', 'get_reschedule_sms_messages_query_parameters', ([], {}), '(... |
from tqdm import *
from sklearn.neighbors import BallTree
from .batch_generator import *
from .ReadWriteLock import ReadWriteLock
class CenterBatchGenerator(BatchGenerator):
"""
creates batches where the blobs are centered around a specific point in the grid cell
"""
def __init__(self, dataset, batch... | [
"sklearn.neighbors.BallTree"
] | [((2631, 2678), 'sklearn.neighbors.BallTree', 'BallTree', (['pointcloud_data[:, :2]'], {'metric': 'metric'}), '(pointcloud_data[:, :2], metric=metric)\n', (2639, 2678), False, 'from sklearn.neighbors import BallTree\n')] |
from .base import BaseClient, api_call
from launchkey.utils import iso_format
from launchkey.entities.validation import DirectoryGetDeviceResponseValidator, DirectoryGetSessionsValidator, \
DirectoryUserDeviceLinkResponseValidator, ServiceValidator, ServiceSecurityPolicyValidator, PublicKeyValidator
from launchkey.... | [
"launchkey.entities.directory.DirectoryUserDeviceLinkData",
"launchkey.utils.iso_format",
"launchkey.entities.service.ServiceSecurityPolicy"
] | [((1845, 1878), 'launchkey.entities.directory.DirectoryUserDeviceLinkData', 'DirectoryUserDeviceLinkData', (['data'], {}), '(data)\n', (1872, 1878), False, 'from launchkey.entities.directory import Session, DirectoryUserDeviceLinkData, Device\n'), ((14534, 14557), 'launchkey.entities.service.ServiceSecurityPolicy', 'Se... |
import sys
sys.path.append('scraper') | [
"sys.path.append"
] | [((13, 39), 'sys.path.append', 'sys.path.append', (['"""scraper"""'], {}), "('scraper')\n", (28, 39), False, 'import sys\n')] |
from typing import List
from jivago.config.router.router_builder import RouterBuilder
from jivago.inject.service_locator import ServiceLocator
class AbstractContext(object):
INSTANCE: "AbstractContext" = None
def __init__(self):
self.serviceLocator = ServiceLocator()
AbstractContext.INSTANCE... | [
"jivago.inject.service_locator.ServiceLocator"
] | [((271, 287), 'jivago.inject.service_locator.ServiceLocator', 'ServiceLocator', ([], {}), '()\n', (285, 287), False, 'from jivago.inject.service_locator import ServiceLocator\n')] |
# Copyright 2017 ETH Zurich
#
# 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, sof... | [
"nose.tools.eq_",
"test.testcommon.create_mock_full",
"lib.rev_cache.RevCache",
"unittest.mock.call",
"nose.tools.assert_true",
"test.testcommon.create_mock",
"time.time"
] | [((1147, 1189), 'test.testcommon.create_mock_full', 'create_mock_full', (["{'rev_info()': rev_info}"], {}), "({'rev_info()': rev_info})\n", (1163, 1189), False, 'from test.testcommon import assert_these_calls, create_mock, create_mock_full\n'), ((1210, 1220), 'lib.rev_cache.RevCache', 'RevCache', ([], {}), '()\n', (121... |
from pygls.workspace import Document
from stibium.api import AntCompletion, AntCompletionKind, AntFile, Completer
from stibium.analysis import AntTreeAnalyzer, get_qname_at_position
from stibium.parse import AntimonyParser
from stibium.types import SrcLocation, SrcPosition, SrcRange
from pygls.types import Completion... | [
"stibium.api.AntFile",
"pygls.types.Position",
"stibium.types.SrcRange",
"stibium.types.SrcPosition"
] | [((550, 604), 'stibium.types.SrcPosition', 'SrcPosition', (['(position.line + 1)', '(position.character + 1)'], {}), '(position.line + 1, position.character + 1)\n', (561, 604), False, 'from stibium.types import SrcLocation, SrcPosition, SrcRange\n'), ((703, 735), 'stibium.types.SrcRange', 'SrcRange', (['range.start', ... |
from typing import List, Tuple, Optional
import os
import numpy as np
import matplotlib
matplotlib.use('Agg')
import matplotlib.pyplot as plt
import matplotlib.ticker as ticker
from matplotlib import cm
import matplotlib.colors as mplcolors
from ramachandran.io import read_residue_torsion_collection_from_file
def get... | [
"os.path.exists",
"ramachandran.io.read_residue_torsion_collection_from_file",
"os.makedirs",
"matplotlib.use",
"numpy.delete",
"matplotlib.ticker.MultipleLocator",
"os.path.join",
"os.path.split",
"matplotlib.pyplot.close",
"numpy.array",
"matplotlib.pyplot.figure",
"matplotlib.colors.ListedC... | [((88, 109), 'matplotlib.use', 'matplotlib.use', (['"""Agg"""'], {}), "('Agg')\n", (102, 109), False, 'import matplotlib\n'), ((1247, 1271), 'numpy.array', 'np.array', (['phi_psi_angles'], {}), '(phi_psi_angles)\n', (1255, 1271), True, 'import numpy as np\n'), ((1365, 1393), 'matplotlib.pyplot.figure', 'plt.figure', ([... |
from __future__ import annotations
import logging
from functools import partial
from typing import Any, List, Optional, Tuple, Type, Union, cast
from nuplan.common.actor_state.vehicle_parameters import VehicleParameters, get_pacifica_parameters
from nuplan.common.maps.nuplan_map.map_factory import NuPlanMapFactory
fr... | [
"logging.getLogger",
"nuplan.common.maps.nuplan_map.map_factory.NuPlanMapFactory",
"nuplan.planning.scenario_builder.nuplan_db.nuplan_scenario_filter_utils.create_all_scenarios",
"nuplan.planning.scenario_builder.nuplan_db.nuplan_scenario_utils.ScenarioMapping",
"nuplan.planning.scenario_builder.nuplan_db.n... | [((1349, 1376), 'logging.getLogger', 'logging.getLogger', (['__name__'], {}), '(__name__)\n', (1366, 1376), False, 'import logging\n'), ((3771, 3916), 'nuplan.database.nuplan_db.nuplandb_wrapper.NuPlanDBWrapper', 'NuPlanDBWrapper', ([], {'data_root': 'data_root', 'map_root': 'map_root', 'db_files': 'db_files', 'map_ver... |
#*****************************************************************************#
#* Copyright (c) 2004-2008, SRI International. *#
#* All rights reserved. *#
#* ... | [
"spark.internal.parse.basicvalues.isString",
"spark.internal.set.rbitstring",
"spark.internal.exception.LowError",
"spark.internal.set.bitmap_indices"
] | [((4451, 4479), 'spark.internal.set.bitmap_indices', 'bitmap_indices', (['self._bitmap'], {}), '(self._bitmap)\n', (4465, 4479), False, 'from spark.internal.set import BITS, rbitstring, bitmap_indices\n'), ((3648, 3668), 'spark.internal.parse.basicvalues.isString', 'isString', (['modestring'], {}), '(modestring)\n', (3... |
import pytest
from great_expectations.data_context import BaseDataContext
from great_expectations.data_context.types.base import DataContextConfig
@pytest.fixture(scope="module")
def basic_data_context_config():
return DataContextConfig(
config_version=2,
plugins_directory=None,
evaluatio... | [
"pytest.fixture",
"great_expectations.data_context.types.base.DataContextConfig",
"great_expectations.data_context.BaseDataContext"
] | [((151, 181), 'pytest.fixture', 'pytest.fixture', ([], {'scope': '"""module"""'}), "(scope='module')\n", (165, 181), False, 'import pytest\n'), ((899, 929), 'pytest.fixture', 'pytest.fixture', ([], {'scope': '"""module"""'}), "(scope='module')\n", (913, 929), False, 'import pytest\n'), ((1048, 1078), 'pytest.fixture', ... |
import re
from typing import List
from dtags.files import COMP_FILE, DEST_FILE, get_file_path
ANSI_ESCAPE = re.compile(r"\x1B(?:[@-Z\\-_]|\[[0-?]*[ -/]*[@-~])")
def clean_str(value: str) -> str:
return ANSI_ESCAPE.sub("", value)
def load_completion() -> List[str]:
with open(get_file_path(COMP_FILE)) as fp... | [
"dtags.files.get_file_path",
"re.compile"
] | [((110, 165), 're.compile', 're.compile', (['"""\\\\x1B(?:[@-Z\\\\\\\\-_]|\\\\[[0-?]*[ -/]*[@-~])"""'], {}), "('\\\\x1B(?:[@-Z\\\\\\\\-_]|\\\\[[0-?]*[ -/]*[@-~])')\n", (120, 165), False, 'import re\n'), ((289, 313), 'dtags.files.get_file_path', 'get_file_path', (['COMP_FILE'], {}), '(COMP_FILE)\n', (302, 313), False, '... |
#! /bin/env python
## basic shim to load up neuroglancer in a browser:
import neuroglancer
import logging
from time import sleep
import redis
import os
import json
import graphviz
hosturl = os.environ['HOSTURL']
kv = redis.Redis(host="redis", decode_responses=True) # container simply named redis
logging.basicConf... | [
"logging.basicConfig",
"logging.debug",
"neuroglancer.Viewer",
"json.dumps",
"neuroglancer.SegmentationLayer",
"time.sleep",
"redis.Redis",
"neuroglancer.set_server_bind_address",
"json.load",
"neuroglancer.ImageLayer",
"neuroglancer.AnnotationLayer",
"graphviz.Digraph",
"neuroglancer.set_st... | [((221, 269), 'redis.Redis', 'redis.Redis', ([], {'host': '"""redis"""', 'decode_responses': '(True)'}), "(host='redis', decode_responses=True)\n", (232, 269), False, 'import redis\n'), ((303, 343), 'logging.basicConfig', 'logging.basicConfig', ([], {'level': 'logging.DEBUG'}), '(level=logging.DEBUG)\n', (322, 343), Fa... |
# -*- coding: utf-8 -*-
"""
Created on Tue May 26 07:49:48 2020
@author: X202722
"""
def make_parameter_BPT_fit (T_sim, T_exp, method, na, M):
import numpy as np
# fit if possible BPT guess to
#nannoolal
if method == 0:
a = 0.6583
b= 1.6868
c= 84.3395
... | [
"numpy.sqrt",
"numpy.power",
"numpy.log",
"numpy.exp",
"numpy.zeros",
"numpy.isnan",
"pandas.DataFrame"
] | [((6738, 6750), 'numpy.zeros', 'np.zeros', (['(10)'], {}), '(10)\n', (6746, 6750), True, 'import numpy as np\n'), ((7007, 7019), 'numpy.zeros', 'np.zeros', (['(10)'], {}), '(10)\n', (7015, 7019), True, 'import numpy as np\n'), ((4856, 4886), 'numpy.isnan', 'np.isnan', (['meta_real.iloc[p, 0]'], {}), '(meta_real.iloc[p,... |
from pkg_resources import DistributionNotFound, get_distribution
try:
__version__ = get_distribution("coveragespace").version
except DistributionNotFound: # pragma: no cover
__version__ = "(local)"
CLI = "coveragespace"
API = "https://api.coverage.space"
VERSION = "{0} v{1}".format(CLI, __version__)
| [
"pkg_resources.get_distribution"
] | [((90, 123), 'pkg_resources.get_distribution', 'get_distribution', (['"""coveragespace"""'], {}), "('coveragespace')\n", (106, 123), False, 'from pkg_resources import DistributionNotFound, get_distribution\n')] |
# -*- coding: utf-8 -*-
__author__ = 'ElenaSidorova'
import Tkinter as tk
import os
from tkMessageBox import askyesno
from tkFileDialog import askdirectory
from load_data import LoadData
from dialog import Dialog
from output_settings import OpenSettings
from meta_data import META
if __name__ == '__main__':
root =... | [
"Tkinter.Menu",
"dialog.Dialog.close_win",
"Tkinter.Tk",
"load_data.LoadData.load_html",
"load_data.LoadData.open_text",
"Tkinter.Text",
"os.getcwd",
"output_settings.OpenSettings.edit_settings",
"dialog.Dialog.help_text",
"os.mkdir",
"tkMessageBox.askyesno",
"load_data.LoadData.load_several_h... | [((321, 328), 'Tkinter.Tk', 'tk.Tk', ([], {}), '()\n', (326, 328), True, 'import Tkinter as tk\n'), ((340, 389), 'Tkinter.Text', 'tk.Text', (['root'], {'font': "('Arial', 12)", 'cursor': '"""arrow"""'}), "(root, font=('Arial', 12), cursor='arrow')\n", (347, 389), True, 'import Tkinter as tk\n'), ((617, 641), 'Tkinter.M... |
""" loss """
import torch
import torch.nn as nn
import numpy as np
import matplotlib.pyplot as plt
import my_util.get_logger as get_logger
logger = get_logger.get_logger(name='my_lossfn')
def my_penalty(outputs, labels, alpha, lambda_p, Tau, timestamp):
"""
outputs (time, channel)
x (batch,... | [
"torch.nn.CrossEntropyLoss",
"my_util.get_logger.get_logger",
"torch.exp",
"torch.from_numpy",
"torch.cuda.is_available",
"torch.sum",
"torch.zeros"
] | [((149, 188), 'my_util.get_logger.get_logger', 'get_logger.get_logger', ([], {'name': '"""my_lossfn"""'}), "(name='my_lossfn')\n", (170, 188), True, 'import my_util.get_logger as get_logger\n'), ((510, 529), 'torch.zeros', 'torch.zeros', (['[T, T]'], {}), '([T, T])\n', (521, 529), False, 'import torch\n'), ((1032, 1070... |
from trifinger_simulation.sim_finger import int_to_rgba
def test_int_to_rgba():
assert int_to_rgba(0x000000) == (0.0, 0.0, 0.0, 1.0)
assert int_to_rgba(0xFFFFFF) == (1.0, 1.0, 1.0, 1.0)
assert int_to_rgba(0x006C66) == (0, 108 / 255, 102 / 255, 1.0)
assert int_to_rgba(0x006C66, alpha=42) == (
... | [
"trifinger_simulation.sim_finger.int_to_rgba"
] | [((93, 107), 'trifinger_simulation.sim_finger.int_to_rgba', 'int_to_rgba', (['(0)'], {}), '(0)\n', (104, 107), False, 'from trifinger_simulation.sim_finger import int_to_rgba\n'), ((150, 171), 'trifinger_simulation.sim_finger.int_to_rgba', 'int_to_rgba', (['(16777215)'], {}), '(16777215)\n', (161, 171), False, 'from tr... |
import numpy
import pytest
from testfixtures import LogCapture
from matchms.filtering import add_losses
from .builder_Spectrum import SpectrumBuilder
@pytest.mark.parametrize("mz, loss_mz_to, expected_mz, expected_intensities", [
[numpy.array([100, 150, 200, 300], dtype="float"), 1000, numpy.array([145, 245, 295,... | [
"numpy.allclose",
"matchms.filtering.add_losses",
"numpy.array",
"pytest.raises",
"testfixtures.LogCapture"
] | [((759, 802), 'numpy.array', 'numpy.array', (['[700, 200, 100, 1000]', '"""float"""'], {}), "([700, 200, 100, 1000], 'float')\n", (770, 802), False, 'import numpy\n'), ((977, 1023), 'matchms.filtering.add_losses', 'add_losses', (['spectrum_in'], {'loss_mz_to': 'loss_mz_to'}), '(spectrum_in, loss_mz_to=loss_mz_to)\n', (... |
# -*- coding: utf-8 -*-
import imageio
import matplotlib.pyplot as plt
import numpy
img = imageio.imread('Z:/DRPI/questoes_aula/sat_map3.tif')
dim = img.shape
col = dim[1]
lin = dim[0]
def histogram(img, s, rgb):
"""
Função que desenha os histogramas
:param img: A imagem
:param s: ... | [
"numpy.uint8",
"numpy.histogram",
"matplotlib.pyplot.axis",
"numpy.max",
"numpy.count_nonzero",
"numpy.zeros",
"matplotlib.pyplot.figure",
"numpy.cumsum",
"matplotlib.pyplot.interactive",
"numpy.min",
"imageio.imread",
"matplotlib.pyplot.title",
"matplotlib.pyplot.subplot",
"matplotlib.pyp... | [((100, 152), 'imageio.imread', 'imageio.imread', (['"""Z:/DRPI/questoes_aula/sat_map3.tif"""'], {}), "('Z:/DRPI/questoes_aula/sat_map3.tif')\n", (114, 152), False, 'import imageio\n'), ((514, 539), 'matplotlib.pyplot.title', 'plt.title', (['s'], {'fontsize': '(10)'}), '(s, fontsize=10)\n', (523, 539), True, 'import ma... |
from ..conf.config import LoggerConfig
import os, traceback
class LogWriter:
def __init__(self, logger):
self.logger = logger
self.log_dir = LoggerConfig.logs_dir
def dir_exists(self, url: str):
return os.path.isdir(url)
def file_exists(self, url: str):
return os.path.isfi... | [
"os.path.join",
"os.path.isfile",
"os.path.isdir",
"os.mkdir",
"os.unlink",
"traceback.print_exc",
"os.walk"
] | [((236, 254), 'os.path.isdir', 'os.path.isdir', (['url'], {}), '(url)\n', (249, 254), False, 'import os, traceback\n'), ((308, 327), 'os.path.isfile', 'os.path.isfile', (['url'], {}), '(url)\n', (322, 327), False, 'import os, traceback\n'), ((378, 392), 'os.unlink', 'os.unlink', (['url'], {}), '(url)\n', (387, 392), Fa... |
from requests import get, post
from .. import SpyglassException
from .known_types import Account
KNOWN_URL = "https://api.spyglass.pw/banano/v1/known/"
def get_accounts(
include_owner: bool = False, include_type: bool = False, type_filter: str = None
) -> list[Account]:
"""https://spyglass-api.web.app/known... | [
"requests.post",
"requests.get"
] | [((478, 517), 'requests.post', 'post', (['f"""{KNOWN_URL}accounts"""'], {'json': 'data'}), "(f'{KNOWN_URL}accounts', json=data)\n", (482, 517), False, 'from requests import get, post\n'), ((982, 1009), 'requests.get', 'get', (['f"""{KNOWN_URL}vanities"""'], {}), "(f'{KNOWN_URL}vanities')\n", (985, 1009), False, 'from r... |
import datetime
"""
Match objects contain information about a completed match such as the game mode
played, duration, and which players participated.
"""
class match_obj:
def __init__(self, data):
"""
data is the response from pubg api after sending get request using match object url
"""
self.id = data['d... | [
"datetime.datetime.strptime"
] | [((351, 444), 'datetime.datetime.strptime', 'datetime.datetime.strptime', (["data['data']['attributes']['createdAt']", '"""%Y-%m-%dT%H:%M:%SZ"""'], {}), "(data['data']['attributes']['createdAt'],\n '%Y-%m-%dT%H:%M:%SZ')\n", (377, 444), False, 'import datetime\n')] |