code stringlengths 22 1.05M | apis listlengths 1 3.31k | extract_api stringlengths 75 3.25M |
|---|---|---|
#Practical 36: Find hash of file
import sys
import hashlib
# BUF_SIZE is totally arbitrary, change for your app!
BUF_SIZE = 65536
md5 = hashlib.md5()
sha1 = hashlib.sha1()
with open(sys.argv[1], 'rb') as f:
while True:
data = f.read(BUF_SIZE)
if not data:
break
md5.update(d... | [
"hashlib.sha1",
"hashlib.md5"
] | [((141, 154), 'hashlib.md5', 'hashlib.md5', ([], {}), '()\n', (152, 154), False, 'import hashlib\n'), ((162, 176), 'hashlib.sha1', 'hashlib.sha1', ([], {}), '()\n', (174, 176), False, 'import hashlib\n')] |
#!/usr/bin/env python3
# -*- coding: utf-8 -*-
"""gui.py
A GUI for the Arduino Due pulsebox.
<NAME> <<EMAIL>>
2021 Quantum Optics Lab Olomouc
"""
import csv
import gi
gi.require_version("Gtk", "3.0")
from gi.repository import Gtk, Gio
import os
import pulsebox.config as pcfg
import pulsebox.events as pev
import p... | [
"gi.repository.Gtk.Statusbar",
"gi.repository.Gtk.Grid",
"gi.repository.Gtk.TextView.new_with_buffer",
"gi.repository.Gtk.Button",
"gi.repository.Gtk.main",
"gi.repository.Gtk.HPaned",
"gi.repository.Gtk.ToolButton",
"pulsebox.events.parse_events",
"os.path.split",
"gi.repository.Gtk.TextBuffer",
... | [((171, 203), 'gi.require_version', 'gi.require_version', (['"""Gtk"""', '"""3.0"""'], {}), "('Gtk', '3.0')\n", (189, 203), False, 'import gi\n'), ((11309, 11319), 'gi.repository.Gtk.main', 'Gtk.main', ([], {}), '()\n', (11317, 11319), False, 'from gi.repository import Gtk, Gio\n'), ((1044, 1082), 'gi.repository.Gtk.To... |
#!/usr/bin/env python
# coding=utf-8
"""
Ant Group
Copyright (c) 2004-2020 All Rights Reserved.
------------------------------------------------------
File Name : NN
Author : <NAME>
Email: <EMAIL>
Create Time : 2020-09-11 14:29
Description : description what the main function of this file
"""
fr... | [
"tensorflow.compat.v1.placeholder",
"tensorflow.group",
"numpy.zeros",
"time.time",
"tensorflow.compat.v1.global_variables_initializer"
] | [((2634, 2653), 'tensorflow.group', 'tf.group', (['train_ops'], {}), '(train_ops)\n', (2642, 2653), True, 'import tensorflow as tf\n'), ((3223, 3234), 'time.time', 'time.time', ([], {}), '()\n', (3232, 3234), False, 'import time\n'), ((2935, 2986), 'tensorflow.compat.v1.placeholder', 'tf.compat.v1.placeholder', ([], {'... |
#!/usr/bin/env python3
"""Defines ways to "convert" a file name to an input/output stream."""
from __future__ import absolute_import, division, print_function
from builtins import range
from io import TextIOBase
import math
import os
from emLam.utils import allname, openall
class MultiFileWriter(TextIOBase):
def... | [
"emLam.utils.allname",
"builtins.range",
"math.log10"
] | [((683, 706), 'emLam.utils.allname', 'allname', (['self.file_name'], {}), '(self.file_name)\n', (690, 706), False, 'from emLam.utils import allname, openall\n'), ((1772, 1792), 'builtins.range', 'range', (['(1)', 'self.index'], {}), '(1, self.index)\n', (1777, 1792), False, 'from builtins import range\n'), ((1614, 1636... |
import json
import logging
import random
from typing import Any, Callable, Dict, List, Literal, Optional, Sequence, Tuple, Union, overload
from urllib.parse import urlparse
import requests
from ens import ENS
from ens.abis import ENS as ENS_ABI, RESOLVER as ENS_RESOLVER_ABI
from ens.exceptions import InvalidName
from ... | [
"logging.getLogger",
"rotkehlchen.logging.RotkehlchenLogsAdapter",
"web3.HTTPProvider",
"ens.abis.RESOLVER.copy",
"rotkehlchen.types.Timestamp",
"random.choices",
"rotkehlchen.utils.misc.from_wei",
"web3._utils.abi.get_abi_output_types",
"ens.utils.address_to_reverse_domain",
"rotkehlchen.chain.et... | [((2482, 2509), 'logging.getLogger', 'logging.getLogger', (['__name__'], {}), '(__name__)\n', (2499, 2509), False, 'import logging\n'), ((2516, 2546), 'rotkehlchen.logging.RotkehlchenLogsAdapter', 'RotkehlchenLogsAdapter', (['logger'], {}), '(logger)\n', (2538, 2546), False, 'from rotkehlchen.logging import Rotkehlchen... |
# Generated by Django 3.0.2 on 2020-02-03 02:24
import datetime
from django.db import migrations, models
from django.utils.timezone import utc
class Migration(migrations.Migration):
dependencies = [
('Blog', '0002_auto_20200202_2022'),
]
operations = [
migrations.AlterField(
... | [
"datetime.datetime"
] | [((411, 470), 'datetime.datetime', 'datetime.datetime', (['(2020)', '(2)', '(3)', '(2)', '(24)', '(1)', '(552665)'], {'tzinfo': 'utc'}), '(2020, 2, 3, 2, 24, 1, 552665, tzinfo=utc)\n', (428, 470), False, 'import datetime\n')] |
import torch
import torch.nn as nn
from ....ops.pointnet2.pointnet2_batch import pointnet2_modules
from ....ops.pointnet2.pointnet2_batch import pointnet2_modules as pointnet2_batch_modules
from ....utils import common_utils
class VoteModule(nn.Module):
def __init__(self, model_cfg, voxel_size=None, point_... | [
"torch.nn.ReLU",
"torch.nn.Sequential",
"torch.stack",
"torch.nn.BatchNorm1d",
"torch.nn.Conv1d",
"torch.arange"
] | [((1533, 1563), 'torch.nn.Sequential', 'nn.Sequential', (['*vote_conv_list'], {}), '(*vote_conv_list)\n', (1546, 1563), True, 'import torch.nn as nn\n'), ((4805, 4845), 'torch.stack', 'torch.stack', (['limited_offset_list'], {'dim': '(-1)'}), '(limited_offset_list, dim=-1)\n', (4816, 4845), False, 'import torch\n'), ((... |
import pandas as pd
from api.models.speciality_use_vehicle_incentives import \
SpecialityUseVehicleIncentives
def trim_all_columns(df):
"""
Trim whitespace from ends of each value across all series in dataframe
"""
trim_strings = lambda x: x.strip() if isinstance(x, str) else x
return df.apply... | [
"api.models.speciality_use_vehicle_incentives.SpecialityUseVehicleIncentives.objects.create",
"pandas.read_excel"
] | [((575, 610), 'pandas.read_excel', 'pd.read_excel', (['excel_file', '"""Sheet1"""'], {}), "(excel_file, 'Sheet1')\n", (588, 610), True, 'import pandas as pd\n'), ((1196, 1636), 'api.models.speciality_use_vehicle_incentives.SpecialityUseVehicleIncentives.objects.create', 'SpecialityUseVehicleIncentives.objects.create', ... |
# models.py
# This file contains all models of the database, and their helper functions
from app import db
'''
Actors
Should have unique names
should have age and gender
'''
class Actor(db.Model):
__tablename__ = 'actors'
id = db.Column(db.Integer, primary_key=True, nullable=False)
name = d... | [
"app.db.session.commit",
"app.db.session.delete",
"app.db.Integer",
"app.db.String",
"app.db.session.add",
"app.db.Column",
"app.db.ForeignKey",
"app.db.relationship"
] | [((251, 306), 'app.db.Column', 'db.Column', (['db.Integer'], {'primary_key': '(True)', 'nullable': '(False)'}), '(db.Integer, primary_key=True, nullable=False)\n', (260, 306), False, 'from app import db\n'), ((492, 571), 'app.db.relationship', 'db.relationship', (['"""Movie"""'], {'secondary': '"""actor_movies"""', 'ba... |
# Copyright 2019 Xilinx Inc.
#
# Licensed under the Apache License, Version 2.0 (the "License");
# you may not use this file except in compliance with the License.
# You may obtain a copy of the License at
#
# http://www.apache.org/licenses/LICENSE-2.0
#
# Unless required by applicable law or agreed to in writing, ... | [
"google.protobuf.symbol_database.Default",
"google.protobuf.descriptor.FieldDescriptor"
] | [((2191, 2217), 'google.protobuf.symbol_database.Default', '_symbol_database.Default', ([], {}), '()\n', (2215, 2217), True, 'from google.protobuf import symbol_database as _symbol_database\n'), ((3405, 3775), 'google.protobuf.descriptor.FieldDescriptor', '_descriptor.FieldDescriptor', ([], {'name': '"""anchor_generato... |
# Copyright 2018 The TensorFlow Authors. 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 required by... | [
"tensorflow.python.ops.ragged.ragged_dispatch.ragged_op_list"
] | [((2664, 2696), 'tensorflow.python.ops.ragged.ragged_dispatch.ragged_op_list', 'ragged_dispatch.ragged_op_list', ([], {}), '()\n', (2694, 2696), False, 'from tensorflow.python.ops.ragged import ragged_dispatch\n')] |
from keras.datasets import boston_housing
from keras.models import Sequential
from keras.layers import Activation, Dense
from keras import optimizers
(X_train, y_train), (X_test, y_test) = boston_housing.load_data()
model = Sequential()
# Keras model with two hidden layer with 10 neurons each
model.add(Dense(10, in... | [
"keras.datasets.boston_housing.load_data",
"keras.models.Sequential",
"keras.optimizers.SGD",
"keras.layers.Activation",
"keras.layers.Dense"
] | [((190, 216), 'keras.datasets.boston_housing.load_data', 'boston_housing.load_data', ([], {}), '()\n', (214, 216), False, 'from keras.datasets import boston_housing\n'), ((226, 238), 'keras.models.Sequential', 'Sequential', ([], {}), '()\n', (236, 238), False, 'from keras.models import Sequential\n'), ((1078, 1101), 'k... |
# AUTOGENERATED! DO NOT EDIT! File to edit: nbs/01_bbox_canvas.ipynb (unless otherwise specified).
__all__ = ['points2bbox_coords', 'coords_scaled', 'BBoxCanvas', 'BBoxVideoCanvas']
# Internal Cell
import io
import attr
from math import log
from pubsub import pub
from attr import asdict
from pathlib import Path
from ... | [
"pubsub.pub.subscribe",
"PIL.Image.open",
"ipywidgets.Layout",
"pathlib.Path",
"ipywidgets.VBox",
"PIL.Image.new",
"ipywidgets.Label",
"ipywidgets.Image.from_file",
"ipywidgets.Output",
"io.BytesIO",
"math.log",
"ipycanvas.hold_canvas",
"attr.asdict",
"copy.deepcopy"
] | [((5869, 5888), 'PIL.Image.open', 'pilImage.open', (['path'], {}), '(path)\n', (5882, 5888), True, 'from PIL import Image as pilImage\n'), ((10231, 10275), 'ipywidgets.Output', 'Output', ([], {'layout': "{'border': '1px solid black'}"}), "(layout={'border': '1px solid black'})\n", (10237, 10275), False, 'from ipywidget... |
from psutil import virtual_memory
def mock_cluster(n_workers=1,
threads_per_worker=1,
diagnostics_port=8787,
memory_limit=None,
**dask_kwarg):
return (n_workers, threads_per_worker, diagnostics_port, memory_limit)
class MockClient():
def __... | [
"psutil.virtual_memory"
] | [((462, 478), 'psutil.virtual_memory', 'virtual_memory', ([], {}), '()\n', (476, 478), False, 'from psutil import virtual_memory\n')] |
# Copyright 2019 TerraPower, LLC
#
# 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... | [
"matplotlib.pyplot.ylabel",
"math.sqrt",
"ordered_set.OrderedSet",
"numpy.array",
"armi.reactor.flags.Flags.fromString",
"matplotlib.pyplot.xlabel",
"wx.lib.colourdb.getColourList",
"numpy.diff",
"matplotlib.pyplot.close",
"mpl_toolkits.axes_grid1.make_axes_locatable",
"collections.OrderedDict",... | [((1557, 1572), 'wx.lib.colourdb.getColourList', 'getColourList', ([], {}), '()\n', (1570, 1572), False, 'from wx.lib.colourdb import getColourList\n'), ((3398, 3415), 'numpy.array', 'numpy.array', (['data'], {}), '(data)\n', (3409, 3415), False, 'import numpy\n'), ((3427, 3464), 'matplotlib.pyplot.figure', 'plt.figure... |
import logging
import os
import pickle
import sys
from functools import partial
from os.path import join, exists, basename, dirname
try:
from typing import Dict
except:
pass
try:
import notify2 as notify
notify.init('Youtube Playlist')
except:
pass
import unicodedata
from youtube_dl import Youtube... | [
"os.path.exists",
"notify2.init",
"os.listdir",
"notify2.Notification",
"youtube_dl.utils.sanitize_filename",
"os.path.join",
"pickle.load",
"logging.warning",
"os.remove",
"os.path.dirname",
"functools.partial",
"os.path.basename",
"sys.stdout.flush",
"logging.info",
"sys.stdout.write"
... | [((221, 252), 'notify2.init', 'notify.init', (['"""Youtube Playlist"""'], {}), "('Youtube Playlist')\n", (232, 252), True, 'import notify2 as notify\n'), ((499, 532), 'sys.stdout.write', 'sys.stdout.write', (["('\\r' + ' ' * 80)"], {}), "('\\r' + ' ' * 80)\n", (515, 532), False, 'import sys\n'), ((537, 555), 'sys.stdou... |
#!/usr/bin/env python
import math
def compute(x: int) -> int:
return math.floor((x / 3.0)) - 2
def compute_with_fuel(x: int) -> int:
remainder = compute(x)
fuels = [remainder]
while remainder >= 0:
remainder = compute(remainder)
if remainder >= 0:
fuels.append(remainder)
... | [
"math.floor"
] | [((75, 94), 'math.floor', 'math.floor', (['(x / 3.0)'], {}), '(x / 3.0)\n', (85, 94), False, 'import math\n')] |
from django.conf.urls import *
from . import views
from django.urls import include, path
urlpatterns = [
path('', views.index, name='variant_index'),
path('view/<int:variant_id>/', views.view, name='variant_view'),
] | [
"django.urls.path"
] | [((111, 154), 'django.urls.path', 'path', (['""""""', 'views.index'], {'name': '"""variant_index"""'}), "('', views.index, name='variant_index')\n", (115, 154), False, 'from django.urls import include, path\n'), ((160, 223), 'django.urls.path', 'path', (['"""view/<int:variant_id>/"""', 'views.view'], {'name': '"""varia... |
'''
Context configuration model.
'''
import os
from typing import Any, Dict, Literal, Optional
from pydantic import DirectoryPath, Field, validator
from .. import utils
from ..context_type import ContextType
from .configuration import Configuration
class ContextConfiguration(Configuration):
'''
Context con... | [
"os.getenv",
"pydantic.validator"
] | [((969, 1008), 'pydantic.validator', 'validator', (['"""root_template"""'], {'always': '(True)'}), "('root_template', always=True)\n", (978, 1008), False, 'from pydantic import DirectoryPath, Field, validator\n'), ((1835, 1865), 'pydantic.validator', 'validator', (['"""path"""'], {'always': '(True)'}), "('path', always... |
import sys
import os
from collections import OrderedDict
from ttfautohint._compat import (
ensure_binary, ensure_text, basestring, open, IntEnum,
)
USER_OPTIONS = dict(
in_file=None,
in_buffer=None,
out_file=None,
control_file=None,
control_buffer=None,
reference_file=None,
reference_bu... | [
"collections.OrderedDict",
"sys.stdin.isatty",
"sys.getfilesystemencoding",
"sys.stdin.fileno",
"argparse.ArgumentParser",
"ttfautohint._compat.ensure_binary",
"shlex.split",
"os.environ.get",
"argparse.ArgumentTypeError",
"ttfautohint._compat.ensure_text",
"ctypes.c_ulonglong",
"sys.stdout.is... | [((941, 1011), 'ttfautohint._compat.IntEnum', 'IntEnum', (['"""StemWidthMode"""', "['NATURAL', 'QUANTIZED', 'STRONG']"], {'start': '(-1)'}), "('StemWidthMode', ['NATURAL', 'QUANTIZED', 'STRONG'], start=-1)\n", (948, 1011), False, 'from ttfautohint._compat import ensure_binary, ensure_text, basestring, open, IntEnum\n')... |
from datetime import datetime, timezone
from .enums import StatisticTypeEnum
def convert_timestamp_to_datetime(timestamp: float) -> datetime:
"""
Convert timestamp date format to datetime.
Arguments:
timestamp {float} -- Input timestamp.
Returns:
datetime -- Datetime formatted objec... | [
"datetime.datetime.fromtimestamp"
] | [((401, 448), 'datetime.datetime.fromtimestamp', 'datetime.fromtimestamp', (['timestamp', 'timezone.utc'], {}), '(timestamp, timezone.utc)\n', (423, 448), False, 'from datetime import datetime, timezone\n')] |
'''
Copyright 2013 <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, distribute, sublicense,... | [
"fantastico.routing_engine.custom_responses.RedirectResponse",
"fantastico.mvc.CONN_MANAGER.close_connection",
"webob.request.Request",
"fantastico.settings.SettingsFacade",
"fantastico.locale.language.Language"
] | [((2099, 2130), 'fantastico.settings.SettingsFacade', 'SettingsFacade', (['request.environ'], {}), '(request.environ)\n', (2113, 2130), False, 'from fantastico.settings import SettingsFacade\n'), ((3106, 3138), 'fantastico.locale.language.Language', 'Language', (['supported_languages[0]'], {}), '(supported_languages[0]... |
from helpers import convert_and_trim_bb
import streamlit as st
import warnings
import imutils
import dlib
import cv2
import numpy as np
st.set_page_config(page_title="Image Anonymization", page_icon="🎞", layout='centered', initial_sidebar_state="collapsed")
def main():
# title
html_temp = """
<div>
... | [
"streamlit.markdown",
"streamlit.beta_columns",
"streamlit.file_uploader",
"streamlit.write",
"cv2.medianBlur",
"imutils.resize",
"dlib.cnn_face_detection_model_v1",
"cv2.imdecode",
"cv2.cvtColor",
"streamlit.set_page_config",
"helpers.convert_and_trim_bb"
] | [((138, 264), 'streamlit.set_page_config', 'st.set_page_config', ([], {'page_title': '"""Image Anonymization"""', 'page_icon': '"""🎞"""', 'layout': '"""centered"""', 'initial_sidebar_state': '"""collapsed"""'}), "(page_title='Image Anonymization', page_icon='🎞', layout=\n 'centered', initial_sidebar_state='collaps... |
"""Class for a collection of grid properties"""
version = '24th November 2021'
# Nexus is a registered trademark of the Halliburton Company
import logging
log = logging.getLogger(__name__)
log.debug('property.py version ' + version)
import os
import numpy as np
import resqpy.olio.ab_toolbox as abt
import resqpy.... | [
"logging.getLogger",
"numpy.count_nonzero",
"numpy.array",
"resqpy.olio.xml_et.citation_title_for_node",
"resqpy.olio.box_utilities.extent_of_box",
"numpy.arange",
"resqpy.olio.load_data.load_array_from_file",
"resqpy.olio.xml_et.simplified_data_type",
"numpy.where",
"resqpy.olio.ab_toolbox.load_a... | [((165, 192), 'logging.getLogger', 'logging.getLogger', (['__name__'], {}), '(__name__)\n', (182, 192), False, 'import logging\n'), ((48495, 48746), 'numpy.nansum', 'np.nansum', (['(a[cell_box[0, 0]:cell_box[1, 0] + 1, cell_box[0, 1]:cell_box[1, 1] + 1,\n cell_box[0, 2]:cell_box[1, 2] + 1] * fine_weight[cell_box[0, ... |
from __future__ import absolute_import, division, print_function, unicode_literals
import tensorflow as tf
import os
import time
import numpy as np
import glob
import matplotlib.pyplot as plt
import PIL
class CVAE(tf.keras.Model):
def __init__(self, latent_dim):
super(CVAE, self).__init__()
s... | [
"tensorflow.random.normal",
"tensorflow.keras.layers.Reshape",
"tensorflow.keras.layers.Conv2D",
"tensorflow.keras.layers.Conv2DTranspose",
"tensorflow.exp",
"tensorflow.sigmoid",
"tensorflow.keras.layers.Dense",
"tensorflow.keras.layers.Flatten",
"tensorflow.keras.layers.InputLayer"
] | [((2067, 2101), 'tensorflow.random.normal', 'tf.random.normal', ([], {'shape': 'mean.shape'}), '(shape=mean.shape)\n', (2083, 2101), True, 'import tensorflow as tf\n'), ((1782, 1828), 'tensorflow.random.normal', 'tf.random.normal', ([], {'shape': '(100, self.latent_dim)'}), '(shape=(100, self.latent_dim))\n', (1798, 18... |
# For testing purposes only. Do not use in production
import uuid
from uuid import UUID
import hashlib
import os
from datetime import datetime, timedelta
from SQLLiteAuthStore import *
from AuthToken import *
TOKEN_VALID_FOR = 31 # in days
class Authenticaton:
def __init__(self):
# sqlite3 prod.db < tables.sql
... | [
"os.urandom",
"uuid.uuid4",
"uuid.uuid1",
"datetime.datetime.now",
"datetime.timedelta"
] | [((683, 697), 'os.urandom', 'os.urandom', (['(16)'], {}), '(16)\n', (693, 697), False, 'import os\n'), ((2001, 2013), 'uuid.uuid1', 'uuid.uuid1', ([], {}), '()\n', (2011, 2013), False, 'import uuid\n'), ((529, 541), 'uuid.uuid4', 'uuid.uuid4', ([], {}), '()\n', (539, 541), False, 'import uuid\n'), ((1502, 1516), 'datet... |
from webapp import db, login_manager
from datetime import datetime
from werkzeug.security import generate_password_hash, check_password_hash
from flask_login import UserMixin # is_authenticated is_loggedin usw...
@login_manager.user_loader # if user is authenticated, then....
def load_user(user_id):
return Us... | [
"webapp.db.relationship",
"webapp.db.Column",
"datetime.datetime.now",
"werkzeug.security.generate_password_hash",
"webapp.db.ForeignKey",
"webapp.db.String",
"werkzeug.security.check_password_hash"
] | [((418, 457), 'webapp.db.Column', 'db.Column', (['db.Integer'], {'primary_key': '(True)'}), '(db.Integer, primary_key=True)\n', (427, 457), False, 'from webapp import db, login_manager\n'), ((1025, 1072), 'webapp.db.Column', 'db.Column', (['db.DateTime'], {'default': 'datetime.utcnow'}), '(db.DateTime, default=datetime... |
import sys
import os
sys.path.append(os.path.join(os.path.realpath(__file__), "../"))
| [
"os.path.realpath"
] | [((50, 76), 'os.path.realpath', 'os.path.realpath', (['__file__'], {}), '(__file__)\n', (66, 76), False, 'import os\n')] |
# -*- coding: utf-8 -*-
#
# Copyright © 2021–2022 <NAME> <<EMAIL>>
# Released under the MIT Licence
#
import pytest
from datetime import date
from pytcnz.squashnz.player import Player
from .test_playerbase import PLAYER
PLAYER = PLAYER | dict(
id=14,
squash_code="WNTHJXD",
points=3050,
dob="1-Sep-199... | [
"pytcnz.squashnz.player.Player.get_name_cleaned",
"pytcnz.squashnz.player.Player",
"pytcnz.squashnz.player.Player.get_first_name",
"pytest.raises",
"datetime.date",
"pytest.fixture"
] | [((752, 803), 'pytest.fixture', 'pytest.fixture', ([], {'params': "['gender', 'name', 'points']"}), "(params=['gender', 'name', 'points'])\n", (766, 803), False, 'import pytest\n'), ((2449, 2678), 'pytest.fixture', 'pytest.fixture', ([], {'params': "[('Mrs. <NAME>', '<NAME>'), ('Ms. <NAME>', '<NAME>'), ('<NAME>', '<NAM... |
# encoding: utf-8
from __future__ import absolute_import, division, print_function, unicode_literals
from django.conf import settings
from django.core.paginator import InvalidPage, Paginator
from django.db.models import Prefetch,Count
from haystack.forms import ModelSearchForm
from rest_framework.generics import (
... | [
"django.db.models.Count",
"django.db.models.Prefetch",
"moto.moe.models.Like.objects.filter",
"rest_framework.response.Response",
"django_mobile.get_flavour",
"django.http.Http404",
"django.core.paginator.Paginator"
] | [((1899, 1945), 'django.core.paginator.Paginator', 'Paginator', (['self.results', 'self.results_per_page'], {}), '(self.results, self.results_per_page)\n', (1908, 1945), False, 'from django.core.paginator import InvalidPage, Paginator\n'), ((3151, 3164), 'rest_framework.response.Response', 'Response', (['ret'], {}), '(... |
import logging
__version__ = "2.0.6"
logging.getLogger(__name__).addHandler(logging.NullHandler())
| [
"logging.NullHandler",
"logging.getLogger"
] | [((78, 99), 'logging.NullHandler', 'logging.NullHandler', ([], {}), '()\n', (97, 99), False, 'import logging\n'), ((39, 66), 'logging.getLogger', 'logging.getLogger', (['__name__'], {}), '(__name__)\n', (56, 66), False, 'import logging\n')] |
#!/usr/bin/env/python
#-*- coding: utf-8 -*-
import numpy as np
import matplotlib.pyplot as plt
import csv
#Coloque aquí el tipo de estrella con el que se va a trabajar. OPCIONES= 'Cefeida', 'RR_Lyrae', 'BinariaECL'.
tipo_estrella='RR_Lyrae';
#Importar los números de las estrellas desde el archivo csv:
ID_estrellas=n... | [
"matplotlib.pyplot.savefig",
"numpy.genfromtxt",
"csv.writer",
"matplotlib.pyplot.close",
"numpy.array",
"matplotlib.pyplot.figure",
"numpy.loadtxt",
"numpy.vectorize"
] | [((319, 393), 'numpy.loadtxt', 'np.loadtxt', (['"""numero_estrellas.csv"""'], {'delimiter': '""","""', 'dtype': '"""str"""', 'skiprows': '(1)'}), "('numero_estrellas.csv', delimiter=',', dtype='str', skiprows=1)\n", (329, 393), True, 'import numpy as np\n'), ((1251, 1271), 'numpy.vectorize', 'np.vectorize', (['np.int']... |
from numba import vectorize, int32, complex128
from __init__ import plot, field
IMAX = 0xFFFF
@vectorize([int32(complex128)], target="parallel")
def mandelbrot_vector(c):
z = 0
n = 0
while abs(z) <= 2 and n < IMAX:
z = z * z + c
n += 1
return n
def main():
f = field(1024)
m... | [
"__init__.field",
"numba.int32",
"__init__.plot"
] | [((303, 314), '__init__.field', 'field', (['(1024)'], {}), '(1024)\n', (308, 314), False, 'from __init__ import plot, field\n'), ((369, 399), '__init__.plot', 'plot', (['m', '"""numba_vectorize.png"""'], {}), "(m, 'numba_vectorize.png')\n", (373, 399), False, 'from __init__ import plot, field\n'), ((110, 127), 'numba.i... |
import os
import glob
import xlrd3 as xlrd # Reading an excel file using Python
from datetime import datetime
class Fatura:
""" Fatura is the portuguese translation of an Invoice. """
def __init__(self,number,nif,date,value):
self.number = number
self.nif = nif
self.date = d... | [
"os.path.exists",
"os.chdir",
"xlrd3.open_workbook",
"os.system",
"glob.glob",
"xlrd3.xldate_as_tuple"
] | [((474, 495), 'os.path.exists', 'os.path.exists', (['fpath'], {}), '(fpath)\n', (488, 495), False, 'import os\n'), ((3266, 3307), 'os.system', 'os.system', (['"""ping google.com -w 4 > clear"""'], {}), "('ping google.com -w 4 > clear')\n", (3275, 3307), False, 'import os\n'), ((508, 523), 'os.chdir', 'os.chdir', (['fpa... |
# Generated by Django 2.2.10 on 2020-02-18 10:28
import django.utils.timezone
from django.db import migrations, models
class Migration(migrations.Migration):
dependencies = [
("main", "0001_initial"),
]
operations = [
migrations.AlterField(
model_name="legalbasis",
... | [
"django.db.models.DateTimeField"
] | [((361, 416), 'django.db.models.DateTimeField', 'models.DateTimeField', ([], {'default': 'django.utils.timezone.now'}), '(default=django.utils.timezone.now)\n', (381, 416), False, 'from django.db import migrations, models\n')] |
# %% Import packages
from bnn_mcmc_examples.examples.mlp.noisy_xor.setting1.constants import output_path
# %% Define optimizer-specific output directories
optimizer_output_path = output_path.joinpath('sgd')
optimizer_output_pilot_path = optimizer_output_path.joinpath('pilot_run')
optimizer_output_benchmark_path = op... | [
"bnn_mcmc_examples.examples.mlp.noisy_xor.setting1.constants.output_path.joinpath"
] | [((182, 209), 'bnn_mcmc_examples.examples.mlp.noisy_xor.setting1.constants.output_path.joinpath', 'output_path.joinpath', (['"""sgd"""'], {}), "('sgd')\n", (202, 209), False, 'from bnn_mcmc_examples.examples.mlp.noisy_xor.setting1.constants import output_path\n')] |
from sklearn.feature_extraction.text import CountVectorizer
from sklearn.naive_bayes import MultinomialNB
from sklearn.cross_validation import train_test_split
from sklearn import metrics
from sklearn.metrics import accuracy_score
import pandas as pd
import os
# reading the data
data = pd.read_csv("SMSSpamCollection"... | [
"pandas.read_csv",
"sklearn.feature_extraction.text.CountVectorizer",
"sklearn.naive_bayes.MultinomialNB",
"sklearn.cross_validation.train_test_split",
"sklearn.metrics.accuracy_score",
"sklearn.metrics.confusion_matrix"
] | [((289, 337), 'pandas.read_csv', 'pd.read_csv', (['"""SMSSpamCollection"""'], {'delimiter': '"""\t"""'}), "('SMSSpamCollection', delimiter='\\t')\n", (300, 337), True, 'import pandas as pd\n'), ((515, 554), 'sklearn.cross_validation.train_test_split', 'train_test_split', (['X', 'y'], {'random_state': '(42)'}), '(X, y, ... |
# coding=utf-8
# *** WARNING: this file was generated by the Pulumi SDK Generator. ***
# *** Do not edit by hand unless you're certain you know what you are doing! ***
import warnings
import pulumi
import pulumi.runtime
from typing import Any, Mapping, Optional, Sequence, Union
from ... import _utilities, _tables
from... | [
"pulumi.getter",
"pulumi.set",
"pulumi.get"
] | [((1993, 2028), 'pulumi.getter', 'pulumi.getter', ([], {'name': '"""cacheHitBytes"""'}), "(name='cacheHitBytes')\n", (2006, 2028), False, 'import pulumi\n'), ((2224, 2266), 'pulumi.getter', 'pulumi.getter', ([], {'name': '"""cacheHitBytesPercent"""'}), "(name='cacheHitBytesPercent')\n", (2237, 2266), False, 'import pul... |
"""A module for testing Protein Insertion Tokenization."""
import unittest
from variation.tokenizers import ProteinInsertion
from variation.tokenizers.caches import AminoAcidCache, NucleotideCache
from .tokenizer_base import TokenizerBase
class TestProteinInsertionTokenizer(TokenizerBase, unittest.TestCase):
"""... | [
"variation.tokenizers.caches.NucleotideCache",
"variation.tokenizers.caches.AminoAcidCache"
] | [((491, 507), 'variation.tokenizers.caches.AminoAcidCache', 'AminoAcidCache', ([], {}), '()\n', (505, 507), False, 'from variation.tokenizers.caches import AminoAcidCache, NucleotideCache\n'), ((509, 526), 'variation.tokenizers.caches.NucleotideCache', 'NucleotideCache', ([], {}), '()\n', (524, 526), False, 'from varia... |
#!/usr/bin/env python3
# -*- coding: utf-8 -*-
import argparse
import json
import os
from tqdm import tqdm
if __name__ == '__main__':
parser = argparse.ArgumentParser()
parser.add_argument('-d', '--question_file', type=str)
parser.add_argument('-o', '--out_file', type=str)
args = parser.parse_args()
... | [
"json.loads",
"json.dumps",
"os.path.splitext",
"argparse.ArgumentParser"
] | [((150, 175), 'argparse.ArgumentParser', 'argparse.ArgumentParser', ([], {}), '()\n', (173, 175), False, 'import argparse\n'), ((563, 594), 'os.path.splitext', 'os.path.splitext', (['question_file'], {}), '(question_file)\n', (579, 594), False, 'import os\n'), ((456, 472), 'json.loads', 'json.loads', (['line'], {}), '(... |
import json
import os
import subprocess
import unittest
from shutil import rmtree
from sys import platform
import numpy as np
import pandas as pd
from elf.io import open_file
from pybdv.util import get_key
from mobie import add_image
from mobie.validation import validate_source_metadata
from mobie.metadata import rea... | [
"numpy.random.rand",
"pandas.read_csv",
"unittest.skipIf",
"mobie.validation.validate_source_metadata",
"unittest.main",
"os.path.exists",
"mobie.metadata.read_dataset_metadata",
"pybdv.util.get_key",
"json.dumps",
"subprocess.run",
"elf.io.open_file",
"numpy.unique",
"os.makedirs",
"mobie... | [((3303, 3371), 'unittest.skipIf', 'unittest.skipIf', (["(platform == 'win32')", '"""CLI does not work on windows"""'], {}), "(platform == 'win32', 'CLI does not work on windows')\n", (3318, 3371), False, 'import unittest\n'), ((4221, 4236), 'unittest.main', 'unittest.main', ([], {}), '()\n', (4234, 4236), False, 'impo... |
# Copyright 2018-2021 Xanadu Quantum Technologies Inc.
# Licensed under the Apache License, Version 2.0 (the "License");
# you may not use this file except in compliance with the License.
# You may obtain a copy of the License at
# http://www.apache.org/licenses/LICENSE-2.0
# Unless required by applicable law or... | [
"pennylane.matrix",
"pennylane.numpy.split",
"pennylane.operation.is_trainable",
"pennylane.transforms.classical_jacobian",
"pennylane.math.imag",
"pennylane.math.zeros",
"pennylane.math.real",
"pennylane.transforms.metric_tensor._contract_metric_tensor_with_cjac",
"pennylane.math.convert_like",
"... | [((2742, 2766), 'pennylane.numpy.split', 'np.split', (['ops', 'split_ids'], {}), '(ops, split_ids)\n', (2750, 2766), True, 'from pennylane import numpy as np\n'), ((6342, 6418), 'pennylane.QuantumFunctionError', 'qml.QuantumFunctionError', (['"""The passed object is not a QuantumTape or QNode."""'], {}), "('The passed ... |
import os
import uuid
import re
import mimetypes
from django.shortcuts import render
from .forms import FormUserCreation, FormLogin, FormJobPost, FormApply, FormUploadImage, FormUploadResume, FormApplicantsInfo
from django.http import HttpResponse, JsonResponse
from django.core.mail import send_mail
from django.templat... | [
"django.shortcuts.render",
"os.path.getsize",
"django.core.mail.send_mail",
"django.http.HttpResponse",
"uuid.uuid4",
"django.shortcuts.redirect",
"django.template.loader.render_to_string"
] | [((5735, 5754), 'django.shortcuts.redirect', 'redirect', (['"""sign_in"""'], {}), "('sign_in')\n", (5743, 5754), False, 'from django.shortcuts import redirect\n'), ((6318, 6365), 'django.shortcuts.render', 'render', (['request', '"""pages/profile_org.html"""', 'data'], {}), "(request, 'pages/profile_org.html', data)\n"... |
import aiohttp_jinja2
from tzlocal import get_localzone
import graphite_feeder
from ws.handler import Handler as Parent
class Handler(Parent):
DEFAULT_FROM_NUMBER = "24"
DEFAULT_FROM_UNIT = "h"
def __init__(self, home_resources, graphite_host, graphite_port):
super(Handler, self).__init__(home_... | [
"aiohttp_jinja2.template",
"tzlocal.get_localzone"
] | [((3053, 3091), 'aiohttp_jinja2.template', 'aiohttp_jinja2.template', (['"""graphs.html"""'], {}), "('graphs.html')\n", (3076, 3091), False, 'import aiohttp_jinja2\n'), ((3289, 3327), 'aiohttp_jinja2.template', 'aiohttp_jinja2.template', (['"""graphs.html"""'], {}), "('graphs.html')\n", (3312, 3327), False, 'import aio... |
"""Functions to create and plot outlier scores (or other) in a fixed bounded range. Intended to use to
show the results of an outlier algorithm in a user friendly UI"""
import numpy as np
def make_linear_part(max_score, min_score):
"""
:param bottom: the proportion of the graph used for the bottom "sigmoid"
... | [
"numpy.log",
"numpy.array",
"numpy.sort",
"numpy.mean"
] | [((4671, 4690), 'numpy.array', 'numpy.array', (['scores'], {}), '(scores)\n', (4682, 4690), False, 'import numpy\n'), ((4711, 4729), 'numpy.sort', 'numpy.sort', (['scores'], {}), '(scores)\n', (4721, 4729), False, 'import numpy\n'), ((4894, 4917), 'numpy.mean', 'numpy.mean', (['high_scores'], {}), '(high_scores)\n', (4... |
"""Mark as module for PyTest."""
def left(string, seq=(' ', '\t', '\r', '\n')):
res = ""
for c in string:
if c in seq:
res += c
else:
break
return res
def right(string, seq=(' ', '\t', '\r', '\n')):
return left(reversed(string), seq)
import xml.etree.cElementT... | [
"os.path.sep.join",
"xml.etree.cElementTree.XMLPullParser"
] | [((390, 417), 'xml.etree.cElementTree.XMLPullParser', 'et.XMLPullParser', (["['start']"], {}), "(['start'])\n", (406, 417), True, 'import xml.etree.cElementTree as et\n'), ((995, 1026), 'os.path.sep.join', 'os.path.sep.join', (['name[-i - 1:]'], {}), '(name[-i - 1:])\n', (1011, 1026), False, 'import os\n')] |
from django.contrib.auth.base_user import AbstractBaseUser
from django.contrib.auth.models import PermissionsMixin
from django.contrib.auth.validators import UnicodeUsernameValidator
from django.core.mail import send_mail
from django.db import models
from django.utils import timezone
from django.utils.translation impor... | [
"django.core.mail.send_mail",
"django.utils.translation.gettext_lazy",
"django.contrib.auth.validators.UnicodeUsernameValidator",
"users.managers.UserManager"
] | [((536, 562), 'django.contrib.auth.validators.UnicodeUsernameValidator', 'UnicodeUsernameValidator', ([], {}), '()\n', (560, 562), False, 'from django.contrib.auth.validators import UnicodeUsernameValidator\n'), ((1347, 1360), 'users.managers.UserManager', 'UserManager', ([], {}), '()\n', (1358, 1360), False, 'from use... |
import FWCore.ParameterSet.Config as cms
# Calo geometry service model
#ECAL conditions
#
# removed : this goes into CalibCalorimetry/Configuration/data/Ecal_FakeCalibrations.cff
#
# include "CalibCalorimetry/EcalTrivialCondModules/data/EcalTrivialCondRetriever.cfi"
#
#ECAL reconstruction
from RecoLocalCalo.EcalRecPr... | [
"FWCore.ParameterSet.Config.Sequence"
] | [((584, 679), 'FWCore.ParameterSet.Config.Sequence', 'cms.Sequence', (['(ecalUncalibRecHit * ecalDetIdToBeRecovered * ecalRecHit * ecalPreshowerRecHit)'], {}), '(ecalUncalibRecHit * ecalDetIdToBeRecovered * ecalRecHit *\n ecalPreshowerRecHit)\n', (596, 679), True, 'import FWCore.ParameterSet.Config as cms\n')] |
# -*- coding: utf-8 -*-
'''
@author: kebo
@contact: <EMAIL>
@version: 1.0
@file: tensorboard.py
@time: 2021/05/12 01:18:35
这一行开始写关于本文件的说明与解释
'''
import tensorflow as tf
import datetime
from cybo.training.utils import Mode
class TensorBoard:
def __init__(self, logs_dir: str = 'logs/') -> None:
current... | [
"datetime.datetime.now",
"tensorflow.summary.scalar",
"tensorflow.cast",
"tensorflow.summary.create_file_writer"
] | [((783, 812), 'tensorflow.cast', 'tf.cast', (['step'], {'dtype': 'tf.int64'}), '(step, dtype=tf.int64)\n', (790, 812), True, 'import tensorflow as tf\n'), ((328, 351), 'datetime.datetime.now', 'datetime.datetime.now', ([], {}), '()\n', (349, 351), False, 'import datetime\n'), ((940, 989), 'tensorflow.summary.create_fil... |
from django.views.generic import (
ListView, DetailView,
)
from core.models import Movie, Person
class MovieDetail(DetailView):
queryset = (
Movie.objects
.all_with_related_persons())
class MovieList(ListView):
model = Movie
paginate_by = 10
class PersonDetail(DetailView):
... | [
"core.models.Movie.objects.all_with_related_persons",
"core.models.Person.objects.all_with_prefetch_movies"
] | [((160, 200), 'core.models.Movie.objects.all_with_related_persons', 'Movie.objects.all_with_related_persons', ([], {}), '()\n', (198, 200), False, 'from core.models import Movie, Person\n'), ((332, 373), 'core.models.Person.objects.all_with_prefetch_movies', 'Person.objects.all_with_prefetch_movies', ([], {}), '()\n', ... |
import csv
import os
import sys
import typing
import keras
import librosa
import numpy as np
sys.path.append(os.path.dirname(os.path.realpath(__file__))) # TODO(TK): replace this with a correct import when mevonai is a package
import bulkDiarize as bk
default_model_path = os.path.join(os.path.dirname(os.path.realpa... | [
"os.listdir",
"keras.models.load_model",
"bulkDiarize.diarizeFromFolder",
"csv.writer",
"os.path.join",
"librosa.feature.mfcc",
"numpy.argmax",
"os.path.realpath",
"numpy.zeros",
"numpy.expand_dims",
"os.remove"
] | [((1679, 1697), 'os.listdir', 'os.listdir', (['folder'], {}), '(folder)\n', (1689, 1697), False, 'import os\n'), ((2824, 2867), 'keras.models.load_model', 'keras.models.load_model', (['default_model_path'], {}), '(default_model_path)\n', (2847, 2867), False, 'import keras\n'), ((3019, 3048), 'os.listdir', 'os.listdir',... |
"""
Python tuples are sort of like lists, except they're immutable and
are usually used to hold heterogenous data, as opposed to lists
which are typically used to hold homogenous data. Tuples use
parens instead of square brackets.
More specifically, tuples are faster than lists. If you're looking
to just define... | [
"math.sqrt"
] | [((766, 808), 'math.sqrt', 'math.sqrt', (['((x1 - x0) ** 2 + (y1 - y0) ** 2)'], {}), '((x1 - x0) ** 2 + (y1 - y0) ** 2)\n', (775, 808), False, 'import math\n')] |
# Generated by Django 3.0.5 on 2020-07-25 21:56
from django.db import migrations, models
class Migration(migrations.Migration):
dependencies = [
('pages', '0008_auto_20200725_1646'),
]
operations = [
migrations.AlterField(
model_name='images',
name='job',
... | [
"django.db.models.ImageField",
"django.db.models.CharField"
] | [((331, 592), 'django.db.models.CharField', 'models.CharField', ([], {'choices': "[('Excavation', 'Excavation'), ('Demolition', 'Demolition'), ('Snow',\n 'Snow'), ('Asphalt paving', 'Asphalt paving'), ('Concrete pavement',\n 'Concret pavement'), ('Commercila Pavement', 'Commercial Pavement')]", 'max_length': '(25... |
from django.core.exceptions import ImproperlyConfigured
from django.core.mail import get_connection
from django.db import models
from django.utils.translation import ugettext_lazy as _
from django_contact.secure import MD5Field
from django_contact import settings
class ContactConfig(models.Model):
sent_url_redi... | [
"django.utils.translation.ugettext_lazy",
"django.db.models.CharField",
"django.core.exceptions.ImproperlyConfigured"
] | [((1321, 1406), 'django.db.models.CharField', 'models.CharField', ([], {'max_length': '(255)', 'help_text': '"""Title the email that will be sent."""'}), "(max_length=255, help_text='Title the email that will be sent.'\n )\n", (1337, 1406), False, 'from django.db import models\n'), ((400, 470), 'django.utils.transla... |
import logging
from malparser import MAL # NOQA
from rest_framework import serializers
from ...bases.metadata.remotemetadata import (
MetadataSerializer,
RemoteMetadataHandlerPlugin,
)
from .filters import MetadataFilter
from .models import ListingItemRelation, Metadata
logger = logging.getLogger(__name__)
... | [
"logging.getLogger",
"rest_framework.serializers.IntegerField",
"rest_framework.serializers.SerializerMethodField",
"rest_framework.serializers.StringRelatedField",
"rest_framework.serializers.CharField"
] | [((292, 319), 'logging.getLogger', 'logging.getLogger', (['__name__'], {}), '(__name__)\n', (309, 319), False, 'import logging\n'), ((384, 410), 'rest_framework.serializers.IntegerField', 'serializers.IntegerField', ([], {}), '()\n', (408, 410), False, 'from rest_framework import serializers\n'), ((424, 447), 'rest_fra... |
import os
from requests_oauthlib import OAuth2Session
try:
from converge import settings
except:
import settings
os.environ['OAUTHLIB_INSECURE_TRANSPORT'] = 'True'
def fetch_info(access_token):
session = OAuth2Session(token={'access_token': access_token})
info_url = 'https://graph.facebook.com/me?fie... | [
"requests_oauthlib.OAuth2Session"
] | [((219, 270), 'requests_oauthlib.OAuth2Session', 'OAuth2Session', ([], {'token': "{'access_token': access_token}"}), "(token={'access_token': access_token})\n", (232, 270), False, 'from requests_oauthlib import OAuth2Session\n')] |
#!/usr/bin/env python
import sys
import json
import fileinput
import dateutil.parser
line_number = 0
for line in fileinput.input():
... | [
"sys.stderr.write",
"json.loads",
"fileinput.input"
] | [((300, 317), 'fileinput.input', 'fileinput.input', ([], {}), '()\n', (315, 317), False, 'import fileinput\n'), ((366, 382), 'json.loads', 'json.loads', (['line'], {}), '(line)\n', (376, 382), False, 'import json\n'), ((418, 492), 'sys.stderr.write', 'sys.stderr.write', (["('invalid JSON (%s) line %s: %s' % (e, line_nu... |
from unittest import TestCase
from RLTest.debuggers import Valgrind
class TestValgrind(TestCase):
def test_generate_command_default(self):
default_valgrind = Valgrind(options="")
cmd_args = default_valgrind.generate_command()
assert ['valgrind', '--error-exitcode=1', '--leak-check=full', ... | [
"RLTest.debuggers.Valgrind"
] | [((173, 193), 'RLTest.debuggers.Valgrind', 'Valgrind', ([], {'options': '""""""'}), "(options='')\n", (181, 193), False, 'from RLTest.debuggers import Valgrind\n'), ((462, 503), 'RLTest.debuggers.Valgrind', 'Valgrind', ([], {'options': '""""""', 'suppressions': '"""file"""'}), "(options='', suppressions='file')\n", (47... |
import datetime
import os
import sys
import time
import cv2
import numpy as np
import torch
import torchvision.transforms as transforms
from torch.autograd import Variable
from Frames_dataset import FramesDataset
from models import *
from opts import parse_opts
opt = parse_opts()
print(opt)
os.makedirs("images_gen... | [
"os.makedirs",
"Frames_dataset.FramesDataset",
"torch.nn.L1Loss",
"torch.load",
"opts.parse_opts",
"torch.nn.MSELoss",
"torch.cuda.is_available",
"torch.utils.data.DataLoader",
"torchvision.transforms.Resize",
"torchvision.transforms.ToTensor",
"time.time",
"torch.cat"
] | [((272, 284), 'opts.parse_opts', 'parse_opts', ([], {}), '()\n', (282, 284), False, 'from opts import parse_opts\n'), ((297, 364), 'os.makedirs', 'os.makedirs', (["('images_generate/%s' % opt.dataset_name)"], {'exist_ok': '(True)'}), "('images_generate/%s' % opt.dataset_name, exist_ok=True)\n", (308, 364), False, 'impo... |
#
# Copyright (c) 2021 Airbyte, Inc., all rights reserved.
#
import math
import uuid
import pytest
from pytest import fixture
from source_paystack.streams import IncrementalPaystackStream
START_DATE = "2020-08-01T00:00:00Z"
@fixture
def patch_incremental_base_class(mocker):
# Mock abstract methods to enable in... | [
"pytest.mark.parametrize",
"uuid.uuid4",
"source_paystack.streams.IncrementalPaystackStream"
] | [((2395, 2922), 'pytest.mark.parametrize', 'pytest.mark.parametrize', (['"""lookback_window_days, current_state, expected, message"""', "[(None, '2021-08-30', '2021-08-30T00:00:00Z',\n 'if lookback_window_days is not set should not affect cursor value'), (\n 0, '2021-08-30', '2021-08-30T00:00:00Z',\n 'if lookb... |
# Copyright (C) 2018 <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, softw... | [
"tensorflow.Session",
"tensorflow.constant",
"tensorflow.matmul"
] | [((825, 879), 'tensorflow.constant', 'tf.constant', (['[2, 0, 1, 0, 1, 2, 3, 0, 1]'], {'shape': '[3, 3]'}), '([2, 0, 1, 0, 1, 2, 3, 0, 1], shape=[3, 3])\n', (836, 879), True, 'import tensorflow as tf\n'), ((931, 985), 'tensorflow.constant', 'tf.constant', (['[1, 0, 1, 2, 2, 1, 0, 3, 0]'], {'shape': '[3, 3]'}), '([1, 0,... |
# -*- coding: utf-8 -*- #
# Copyright 2019 Google LLC. 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 requir... | [
"googlecloudsdk.api_lib.cloudbuild.logs.CloudBuildClient",
"os.path.exists",
"googlecloudsdk.api_lib.storage.storage_api.StorageClient",
"apitools.base.py.encoding.JsonToMessage",
"googlecloudsdk.core.properties.VALUES.core.project.Get",
"googlecloudsdk.core.resource.resource_transform.TransformSize",
"... | [((4473, 4508), 'googlecloudsdk.api_lib.cloudbuild.cloudbuild_util.GetMessagesModule', 'cloudbuild_util.GetMessagesModule', ([], {}), '()\n', (4506, 4508), False, 'from googlecloudsdk.api_lib.cloudbuild import cloudbuild_util\n'), ((4555, 4584), 're.match', 're.match', (['gcs_uri_re', 'gcs_uri'], {}), '(gcs_uri_re, gcs... |
# https://www.hackerrank.com/challenges/py-collections-namedtuple
'''collections.namedtuple()
Basically, namedtuples are easy to create, lightweight object types.
They turn tuples into convenient containers for simple tasks.
With namedtuples, you don’t have to use integer indices for
accessing members of a tuple.
Ex... | [
"collections.namedtuple"
] | [((915, 951), 'collections.namedtuple', 'namedtuple', (['"""STUDENTS"""', 'COLUMN_NAMES'], {}), "('STUDENTS', COLUMN_NAMES)\n", (925, 951), False, 'from collections import namedtuple\n')] |
#!/usr/bin/env python
from setuptools import setup, find_packages
from kitsupublisher.__version__ import __version__
excluded_packages = ["tests"]
install_requirements = [
"gazu==0.8.4",
"qtazu",
"qt.py",
"dccutils",
"pytz",
"shiboken2"
]
setup(
name="kitsupublisher",
version=__ver... | [
"setuptools.find_packages"
] | [((341, 381), 'setuptools.find_packages', 'find_packages', ([], {'exclude': 'excluded_packages'}), '(exclude=excluded_packages)\n', (354, 381), False, 'from setuptools import setup, find_packages\n')] |
import time
import torch
from memory_profiler import memory_usage
from torch import nn
from torch.utils.data import TensorDataset, DataLoader
from src.models.manual_hessian import RmseHessianCalculator
def compute_hessian(x, feature_maps, net, output_size, h_scale):
H = []
bs = x.shape[0]
feature_maps =... | [
"torch.diagonal",
"torch.nn.ReLU",
"torch.ones",
"torch.rand",
"torch.mean",
"torch.sin",
"time.perf_counter",
"torch.utils.data.TensorDataset",
"src.models.manual_hessian.RmseHessianCalculator",
"torch.cos",
"torch.einsum",
"torch.nn.Linear",
"torch.utils.data.DataLoader",
"torch.no_grad"... | [((2263, 2282), 'torch.utils.data.TensorDataset', 'TensorDataset', (['X', 'y'], {}), '(X, y)\n', (2276, 2282), False, 'from torch.utils.data import TensorDataset, DataLoader\n'), ((2296, 2344), 'torch.utils.data.DataLoader', 'DataLoader', (['dataset'], {'batch_size': 'num_observations'}), '(dataset, batch_size=num_obse... |
#!/usr/bin/env python
"""
Python interface to CUBLAS-XT functions.
Note: this module does not explicitly depend on PyCUDA.
"""
import ctypes
from cublas import cublasCheckStatus, _libcublas, _CUBLAS_OP
from . import cuda
CUBLASXT_FLOAT = 0
CUBLASXT_DOUBLE = 1
CUBLASXT_COMPLEX = 2
CUBLASXT_DOUBLECOMPLEX = 3
CUBLAS... | [
"ctypes.byref",
"cublas.cublasCheckStatus",
"cublas._libcublas.cublasXtDestroy",
"cublas._libcublas.cublasXtSetCpuRatio",
"cublas._libcublas.cublasXtSetBlockDim",
"cublas._libcublas.cublasXtDeviceSelect",
"ctypes.c_double",
"ctypes.c_int",
"ctypes.c_void_p",
"cublas._libcublas.cublasXtSetCpuRoutin... | [((694, 711), 'ctypes.c_void_p', 'ctypes.c_void_p', ([], {}), '()\n', (709, 711), False, 'import ctypes\n'), ((777, 802), 'cublas.cublasCheckStatus', 'cublasCheckStatus', (['status'], {}), '(status)\n', (794, 802), False, 'from cublas import cublasCheckStatus, _libcublas, _CUBLAS_OP\n'), ((964, 998), 'cublas._libcublas... |
import mysql.connector as sqltor
import config
import helper_fns
import classes_table
import students_table
db_con = sqltor.connect(
host = config.DB_CONFIG['host'],
user = config.DB_CONFIG['username'],
passwd = config.DB_CONFIG['password'],
database = config.DB_CONFIG['database']
)
if not db_con.is_connected... | [
"mysql.connector.connect",
"helper_fns.createSeparation",
"helper_fns.clearTerminal",
"helper_fns.pause"
] | [((118, 284), 'mysql.connector.connect', 'sqltor.connect', ([], {'host': "config.DB_CONFIG['host']", 'user': "config.DB_CONFIG['username']", 'passwd': "config.DB_CONFIG['password']", 'database': "config.DB_CONFIG['database']"}), "(host=config.DB_CONFIG['host'], user=config.DB_CONFIG[\n 'username'], passwd=config.DB_... |
#!/usr/bin/python
#
# Copyright (c) 2020-2021 Cisco and/or its affiliates.
#
# 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 requir... | [
"ansible.module_utils.connection.ConnectionError",
"json.loads",
"json.dumps",
"requests.head",
"ansible.module_utils._text.to_text"
] | [((3304, 3323), 'json.dumps', 'json.dumps', (['payload'], {}), '(payload)\n', (3314, 3323), False, 'import json\n'), ((4476, 4495), 'json.dumps', 'json.dumps', (['payload'], {}), '(payload)\n', (4486, 4495), False, 'import json\n'), ((12115, 12138), 'ansible.module_utils._text.to_text', 'to_text', (['response_value'], ... |
# -*- coding: utf-8 -*-
# loader.py
# Copyright (c) 2014-?, <NAME>
# All rights reserved.
#
# Redistribution and use 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,... | [
"numpy.fromfile",
"scipy.io.savemat",
"scipy.io.loadmat",
"argparse.ArgumentTypeError",
"scipy.misc.toimage",
"sys.exit",
"imageio.imread"
] | [((11653, 11670), 'scipy.io.loadmat', 'io.loadmat', (['fname'], {}), '(fname)\n', (11663, 11670), False, 'from scipy import io\n'), ((12973, 12995), 'scipy.io.savemat', 'io.savemat', (['fname', 'out'], {}), '(fname, out)\n', (12983, 12995), False, 'from scipy import io\n'), ((13551, 13572), 'imageio.imread', 'imageio.i... |
#!/usr/bin/env python -*- coding: utf-8 -*-
#
# Python Word Sense Disambiguation (pyWSD): SemEval REader API
#
# Copyright (C) 2014-2020 alvations
# URL:
# For license information, see LICENSE.md
import os, io
from collections import namedtuple
from BeautifulSoup import BeautifulSoup as bsoup
from pywsd.utils import ... | [
"pywsd.utils.remove_tags",
"os.listdir",
"collections.namedtuple",
"os.path.join",
"io.open",
"BeautifulSoup.BeautifulSoup"
] | [((362, 403), 'collections.namedtuple', 'namedtuple', (['"""instance"""', '"""id, lemma, word"""'], {}), "('instance', 'id, lemma, word')\n", (372, 403), False, 'from collections import namedtuple\n'), ((411, 460), 'collections.namedtuple', 'namedtuple', (['"""term"""', '"""id, pos, lemma, sense, type"""'], {}), "('ter... |
"""
This module calculates the standard deviation of various gauge parameters during the "pre-effect window", which is an
arbitrary, variable length period of time before the impact of a given hurricane is "felt" at a gauge, and uses that to determine
the length of the effect of the hurricane on the river for each para... | [
"warnings.warn",
"shutil.rmtree"
] | [((2887, 2905), 'shutil.rmtree', 'shutil.rmtree', (['out'], {}), '(out)\n', (2900, 2905), False, 'import shutil\n'), ((5267, 5326), 'warnings.warn', 'warnings.warn', (['f"""TypeError: malformation on {gauge, param}"""'], {}), "(f'TypeError: malformation on {gauge, param}')\n", (5280, 5326), False, 'import warnings\n')] |
from app.model import Trip, CollectionRequest
def test_optimisation_caching(testapp, db):
def cache_optimisation():
trip.collection_ordering = [0]
db.session.commit()
assert trip.collection_ordering is not None
trip = Trip()
coll1 = CollectionRequest(collector_name="", collector_p... | [
"app.model.Trip",
"app.model.CollectionRequest"
] | [((253, 259), 'app.model.Trip', 'Trip', ([], {}), '()\n', (257, 259), False, 'from app.model import Trip, CollectionRequest\n'), ((272, 360), 'app.model.CollectionRequest', 'CollectionRequest', ([], {'collector_name': '""""""', 'collector_phone': '"""0987654456"""', 'waste_entries': '[]'}), "(collector_name='', collect... |
#!/usr/bin/env python
"""
@file createVehTypeDistribution.py
@author <NAME> (Technische Universitaet Braunschweig, Institut fuer Verkehr und Stadtbauwesen)
@author <NAME>
@author <NAME>
@date 2016-06-09
@version $Id$
Creates a vehicle type distribution with a number of representative car-following parameter ... | [
"os.path.exists",
"random.uniform",
"random.normalvariate",
"argparse.ArgumentParser",
"random.gammavariate",
"random.seed",
"re.findall",
"csv.reader",
"sys.stdout.write"
] | [((3451, 3476), 'argparse.ArgumentParser', 'argparse.ArgumentParser', ([], {}), '()\n', (3474, 3476), False, 'import argparse\n'), ((7091, 7125), 'os.path.exists', 'os.path.exists', (['options.outputFile'], {}), '(options.outputFile)\n', (7105, 7125), False, 'import os\n'), ((9024, 9085), 'sys.stdout.write', 'sys.stdou... |
#!/usr/bin/env python
# -*- coding: utf-8 -*-
"""Tests for `sqlf` package."""
import pytest
import sqlf
import types
###############################################################################
# sqlf.sqlf
###############################################################################
def test_sql_function():
... | [
"sqlf.scalar_udf",
"sqlf.single_row",
"sqlf.aggregate_udf",
"pytest.mark.parametrize",
"pytest.raises",
"sqlf.sqlf"
] | [((667, 735), 'pytest.mark.parametrize', 'pytest.mark.parametrize', (['"""value"""', "[(1, 3.14, '', b'', None, [], {})]"], {}), "('value', [(1, 3.14, '', b'', None, [], {})])\n", (690, 735), False, 'import pytest\n'), ((2901, 2967), 'pytest.mark.parametrize', 'pytest.mark.parametrize', (['"""value"""', "[1, 3.14, '', ... |
import pytest
from copy import deepcopy
from adventofcode.utils.Stack import Stack
def test_Stack():
s = Stack()
s.push(1)
assert(len(s) == 1)
s.push(2)
assert(len(s) == 2)
assert(s.peek() == 2)
assert(len(s) == 2)
assert(s.pop() == 2)
assert(len(s) == 1)
s.push(3)
s.push(... | [
"adventofcode.utils.Stack.Stack",
"copy.deepcopy"
] | [((110, 117), 'adventofcode.utils.Stack.Stack', 'Stack', ([], {}), '()\n', (115, 117), False, 'from adventofcode.utils.Stack import Stack\n'), ((345, 356), 'copy.deepcopy', 'deepcopy', (['s'], {}), '(s)\n', (353, 356), False, 'from copy import deepcopy\n')] |
"""
- Using Dataverse information, create a ShapefileInfo information.
- Given a ShapefileInfo object, check for and
return a WorldMapLayerInfo object, if available
"""
import urllib2
from django.core.files import File
from django.core.files.temp import NamedTemporaryFile
from shared_dataverse_information.dataver... | [
"logging.getLogger",
"gc_apps.geo_utils.error_result_msg.ErrResultMsg",
"urllib2.urlopen",
"django.core.files.File",
"django.core.files.temp.NamedTemporaryFile",
"gc_apps.gis_shapefiles.models.ShapefileInfo",
"gc_apps.registered_dataverse.registered_dataverse_helper.find_registered_dataverse",
"gc_app... | [((696, 723), 'logging.getLogger', 'logging.getLogger', (['__name__'], {}), '(__name__)\n', (713, 723), False, 'import logging\n'), ((1412, 1453), 'shared_dataverse_information.dataverse_info.forms.DataverseInfoValidationForm', 'DataverseInfoValidationForm', (['dv_info_dict'], {}), '(dv_info_dict)\n', (1439, 1453), Fal... |
#
# schedule.py - Contains Hue 'schedule' definitions
#
import enum
import re
from . import common
class Schedule(common.Object):
"""
Represents a Hue schedule.
"""
@property
def name(self):
return self._data['name']
@property
def is_enabled(self):
return Status(self._dat... | [
"re.match"
] | [((976, 1033), 're.match', 're.match', (['"""/api/.*(/\\\\w+/\\\\d+)/?(.*)"""', "command['address']"], {}), "('/api/.*(/\\\\w+/\\\\d+)/?(.*)', command['address'])\n", (984, 1033), False, 'import re\n')] |
__author__ = 'mason'
from domain_orderFulfillment import *
from timer import DURATION
from state import state
import numpy as np
'''
This is a randomly generated problem
'''
def GetCostOfMove(id, r, loc1, loc2, dist):
return 1 + dist
def GetCostOfLookup(id, item):
return max(1, np.random.beta(2, 2))
def Ge... | [
"numpy.random.normal",
"numpy.random.beta"
] | [((291, 311), 'numpy.random.beta', 'np.random.beta', (['(2)', '(2)'], {}), '(2, 2)\n', (305, 311), True, 'import numpy as np\n'), ((375, 399), 'numpy.random.normal', 'np.random.normal', (['(5)', '(0.5)'], {}), '(5, 0.5)\n', (391, 399), True, 'import numpy as np\n'), ((453, 475), 'numpy.random.normal', 'np.random.normal... |
# -*- coding: utf-8 -*-
import os
import subprocess
class execlib:
@staticmethod
def get_stdout(cmdline):
""" @return A byte string, so maybe need to decode with .decode('cp932')"""
return subprocess.check_output(cmdline, shell=True)
@staticmethod
def execute(cmdline):
""" @re... | [
"subprocess.check_output",
"argparse.ArgumentParser",
"subprocess.Popen",
"os.getcwd",
"datetime.datetime.now"
] | [((2259, 2270), 'os.getcwd', 'os.getcwd', ([], {}), '()\n', (2268, 2270), False, 'import os\n'), ((903, 982), 'argparse.ArgumentParser', 'argparse.ArgumentParser', ([], {'formatter_class': 'argparse.ArgumentDefaultsHelpFormatter'}), '(formatter_class=argparse.ArgumentDefaultsHelpFormatter)\n', (926, 982), False, 'impor... |
#This script accepts a list of urls, applies tuning, & removes redundancies, and outputs the normalized list
import sys, getopt
import os.path
import configparser
import re
#check for duplicates, duplicates with a tailing / and blank entries
def readFromScreen():
print("Enter/Paste URLS, to finish, from a new lin... | [
"getopt.getopt",
"configparser.ConfigParser",
"sys.exit",
"re.sub",
"re.findall",
"re.search"
] | [((4588, 4615), 'configparser.ConfigParser', 'configparser.ConfigParser', ([], {}), '()\n', (4613, 4615), False, 'import configparser\n'), ((2724, 2748), 're.findall', 're.findall', (['rwp', 'data[i]'], {}), '(rwp, data[i])\n', (2734, 2748), False, 'import re\n'), ((3798, 3872), 'getopt.getopt', 'getopt.getopt', (['arg... |
import re
import os
import pandas as pd
import numpy as np
from .extract_tools import default_tokenizer as _default_tokenizer
def _getDictionnaryKeys(dictionnary):
"""
Function that get keys from a dict object and flatten sub dict.
"""
keys_array = []
for key in dictionnary.keys():
... | [
"pandas.Series",
"os.listdir",
"numpy.repeat",
"re.compile",
"numpy.isin",
"os.path.isfile",
"os.path.isdir",
"os.mkdir",
"pandas.DataFrame",
"pandas.concat",
"os.remove"
] | [((5008, 5052), 'os.path.isfile', 'os.path.isfile', (['(self.folder + self.conf_file)'], {}), '(self.folder + self.conf_file)\n', (5022, 5052), False, 'import os\n'), ((9026, 9079), 'pandas.DataFrame', 'pd.DataFrame', ([], {'columns': "self.emptyDFCols['annotations']"}), "(columns=self.emptyDFCols['annotations'])\n", (... |
"""Elbow plot to find value for k to use with k-means clustering"""
import matplotlib.pyplot as plt
def elbow_point(
data, pipeline, kmeans_step_name='kmeans', k_range=range(1, 11), ax=None
):
"""
Plot the elbow point to find an appropriate k for k-means clustering.
Parameters:
- data: The fe... | [
"matplotlib.pyplot.subplots"
] | [((815, 829), 'matplotlib.pyplot.subplots', 'plt.subplots', ([], {}), '()\n', (827, 829), True, 'import matplotlib.pyplot as plt\n')] |
# # ⚠ Warning
#
# THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, EXPRESS OR IMPLIED, INCLUDING BUT NOT
# LIMITED TO THE WARRANTIES OF MERCHANTABILITY, FITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT. IN
# NO EVENT SHALL THE AUTHORS OR COPYRIGHT HOLDERS BE LIABLE FOR ANY CLAIM, DAMAGES OR OTHER LIA... | [
"decimal.Decimal"
] | [((3831, 3842), 'decimal.Decimal', 'Decimal', (['(32)'], {}), '(32)\n', (3838, 3842), False, 'from decimal import Decimal\n')] |
from __future__ import annotations
__all__ = ['as_actor', 'coroutine']
from collections import Counter, deque
from collections.abc import Callable, Generator, Hashable, Iterable, Iterator
from functools import update_wrapper
from threading import Lock
from typing import TypeVar, cast
import wrapt
from ._more import... | [
"threading.Lock",
"functools.update_wrapper",
"typing.TypeVar"
] | [((335, 348), 'typing.TypeVar', 'TypeVar', (['"""_T"""'], {}), "('_T')\n", (342, 348), False, 'from typing import TypeVar, cast\n'), ((354, 367), 'typing.TypeVar', 'TypeVar', (['"""_R"""'], {}), "('_R')\n", (361, 367), False, 'from typing import TypeVar, cast\n'), ((373, 418), 'typing.TypeVar', 'TypeVar', (['"""_F"""']... |
from bap.utils.bap_comment import parse, dumps, is_valid
def test_parse():
assert parse('hello') is None
assert parse('BAP: hello') == {'hello': []}
assert parse('BAP: hello,world') == {'hello': [], 'world': []}
assert parse('BAP: hello=cruel,world') == {'hello': ['cruel', 'world']}
assert parse('... | [
"bap.utils.bap_comment.is_valid",
"bap.utils.bap_comment.dumps",
"bap.utils.bap_comment.parse"
] | [((868, 890), 'bap.utils.bap_comment.is_valid', 'is_valid', (['"""BAP: hello"""'], {}), "('BAP: hello')\n", (876, 890), False, 'from bap.utils.bap_comment import parse, dumps, is_valid\n'), ((902, 930), 'bap.utils.bap_comment.is_valid', 'is_valid', (['"""BAP: hello,world"""'], {}), "('BAP: hello,world')\n", (910, 930),... |
"""
Source: https://stackoverflow.com/a/10455937/2692667
"""
import sys
import os
if os.name == "nt":
import ctypes
class _CursorInfo(ctypes.Structure):
_fields_ = [("size", ctypes.c_int),
("visible", ctypes.c_byte)]
def hide(stream=sys.stdout):
"""Hide cursor.
Paramete... | [
"ctypes.windll.kernel32.GetStdHandle",
"ctypes.byref"
] | [((490, 530), 'ctypes.windll.kernel32.GetStdHandle', 'ctypes.windll.kernel32.GetStdHandle', (['(-11)'], {}), '(-11)\n', (525, 530), False, 'import ctypes\n'), ((1033, 1073), 'ctypes.windll.kernel32.GetStdHandle', 'ctypes.windll.kernel32.GetStdHandle', (['(-11)'], {}), '(-11)\n', (1068, 1073), False, 'import ctypes\n'),... |
import contextlib
import hashlib
import os
import sys
import tempfile
import time
import unittest
import requests
from requests import HTTPError
from slicedimage.backends import ChecksumValidationError, HttpBackend
from tests.utils import (
ContextualChildProcess,
unused_tcp_port,
)
class TestHttpBackend(un... | [
"tempfile.TemporaryDirectory",
"hashlib.sha256",
"os.urandom",
"sys.exc_info",
"os.path.basename",
"tests.utils.unused_tcp_port",
"tempfile.NamedTemporaryFile",
"unittest.main",
"time.time"
] | [((3696, 3711), 'unittest.main', 'unittest.main', ([], {}), '()\n', (3709, 3711), False, 'import unittest\n'), ((428, 457), 'tempfile.TemporaryDirectory', 'tempfile.TemporaryDirectory', ([], {}), '()\n', (455, 457), False, 'import tempfile\n'), ((521, 538), 'tests.utils.unused_tcp_port', 'unused_tcp_port', ([], {}), '(... |
# -*- coding: utf-8 -*-
import re
import scrapy
import json
from locations.items import GeojsonPointItem
class AccorSpider(scrapy.Spider):
name = "accor"
allowed_domains = ["accor.com"]
start_urls = (
"https://group.accor.com/en/hotel-development/-/Media/Corporate/Master-Page/Maps/Business-Devel... | [
"locations.items.GeojsonPointItem"
] | [((927, 957), 'locations.items.GeojsonPointItem', 'GeojsonPointItem', ([], {}), '(**properties)\n', (943, 957), False, 'from locations.items import GeojsonPointItem\n')] |
import os
import time
from typing import Callable, List
from watchdog.events import FileSystemEventHandler, FileSystemEvent
from watchdog.observers import Observer
from .logger import logger
from .utils import get_dir_regex
from .types import SnapDirPrefixType
class FileEventHandler(FileSystemEventHandler):
def __... | [
"os.path.isfile",
"watchdog.observers.Observer",
"os.path.basename",
"time.sleep"
] | [((1283, 1293), 'watchdog.observers.Observer', 'Observer', ([], {}), '()\n', (1291, 1293), False, 'from watchdog.observers import Observer\n'), ((1401, 1423), 'os.path.basename', 'os.path.basename', (['path'], {}), '(path)\n', (1417, 1423), False, 'import os\n'), ((1464, 1484), 'os.path.isfile', 'os.path.isfile', (['pa... |
# Apriori Association Rule Learning
# Importing the libraries
import numpy as np
import matplotlib.pyplot as plt
import pandas as pd
from pathlib import Path
# Importing the dataset
path = Path(__file__).parent / 'Market_Basket_Optimisation.csv'
dataset = pd.read_csv(path, header = None)
transactions = []
for i in ra... | [
"apyori.apriori",
"pandas.read_csv",
"pathlib.Path"
] | [((258, 288), 'pandas.read_csv', 'pd.read_csv', (['path'], {'header': 'None'}), '(path, header=None)\n', (269, 288), True, 'import pandas as pd\n'), ((507, 624), 'apyori.apriori', 'apriori', ([], {'transactions': 'transactions', 'min_support': '(0.003)', 'min_confidence': '(0.2)', 'min_lift': '(3)', 'min_length': '(2)'... |
import ast
from pypytranspy.transformations.base_transformer import BaseTransformer
class FStringToFormatTransformer(BaseTransformer):
minimum_version = [3, 6]
def pre_JoinedStr(self):
# Collect string and args for format()
str_value = ""
str_args = []
for value in self.cur... | [
"ast.Str"
] | [((885, 905), 'ast.Str', 'ast.Str', ([], {'s': 'str_value'}), '(s=str_value)\n', (892, 905), False, 'import ast\n')] |
#!/usr/bin/env python
# vim: ai ts=4 sts=4 et sw=4 encoding=utf-8
import string
import random
from contextlib import contextmanager
from django.test import TestCase
from rapidsms.models import Connection, Contact, Backend
from groups.models import Group
UNICODE_CHARS = [unichr(x) for x in xrange(1, 0xD7FF)]
clas... | [
"random.choice",
"rapidsms.models.Connection.objects.create",
"rapidsms.models.Backend.objects.create",
"groups.models.Group.objects.create",
"random.randint",
"rapidsms.models.Contact.objects.create"
] | [((1158, 1192), 'rapidsms.models.Backend.objects.create', 'Backend.objects.create', ([], {}), '(**defaults)\n', (1180, 1192), False, 'from rapidsms.models import Connection, Contact, Backend\n'), ((1353, 1387), 'rapidsms.models.Contact.objects.create', 'Contact.objects.create', ([], {}), '(**defaults)\n', (1375, 1387),... |
# Copyright 2019 <NAME> and <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 wri... | [
"torch.nn.CrossEntropyLoss",
"torch.max",
"numpy.array",
"torch.sum",
"torch.arange",
"torch.mean",
"numpy.where",
"itertools.product",
"torch.randn",
"random.sample",
"numpy.random.choice",
"torch.nn.functional.normalize",
"torch.nn.functional.relu",
"warnings.filterwarnings",
"torch.ca... | [((762, 795), 'warnings.filterwarnings', 'warnings.filterwarnings', (['"""ignore"""'], {}), "('ignore')\n", (785, 795), False, 'import warnings\n'), ((4640, 4657), 'numpy.unique', 'np.unique', (['labels'], {}), '(labels)\n', (4649, 4657), True, 'import torch, random, itertools as it, numpy as np, faiss, random\n'), ((5... |
import unittest
from unittest.mock import patch, MagicMock
import os
from config import Config
from slack_channel import HelpEventHandler
from slack_channel.abstract_event_handler import AbstractEventHandler
test_prefix = "_"
valid_events = [{"text": test_prefix + "help"},{"text": test_prefix + "?"},{"text... | [
"unittest.main",
"unittest.mock.MagicMock",
"slack_channel.HelpEventHandler",
"unittest.mock.patch.object"
] | [((428, 468), 'unittest.mock.patch.object', 'patch.object', (['Config', '"""get_config_value"""'], {}), "(Config, 'get_config_value')\n", (440, 468), False, 'from unittest.mock import patch, MagicMock\n'), ((471, 531), 'unittest.mock.patch.object', 'patch.object', (['Config', '"""get_prefix"""'], {'return_value': 'test... |
from turtle import *
from math import pi, sin, cos
# Constants
txt_h = 12
radius = 320
txt_w = 50
modulus = 100
# Set up a drawing turtle and a turtle for text positioning
turtle = Turtle()
text_turtle = Turtle()
text_turtle.hideturtle()
text_turtle.penup()
# Draw initial circle, position text turtle
turtle.penup()
... | [
"math.cos",
"math.sin"
] | [((785, 810), 'math.sin', 'sin', (['(n / modulus * 2 * pi)'], {}), '(n / modulus * 2 * pi)\n', (788, 810), False, 'from math import pi, sin, cos\n'), ((828, 853), 'math.cos', 'cos', (['(n / modulus * 2 * pi)'], {}), '(n / modulus * 2 * pi)\n', (831, 853), False, 'from math import pi, sin, cos\n')] |
from django.contrib import admin
from .models import Authenticator
admin.site.register(Authenticator)
| [
"django.contrib.admin.site.register"
] | [((69, 103), 'django.contrib.admin.site.register', 'admin.site.register', (['Authenticator'], {}), '(Authenticator)\n', (88, 103), False, 'from django.contrib import admin\n')] |
from spikex.defaults import spacy_version
from spikex.pipes import SentX
SENTS = [
"This is a bullet list that we want to be a unique sentence:\n"
"\ta) the first bullet;\n"
"\tb) the second bullet;\n"
"\tc) a bullet with nested bullets:\n"
"\t\t1) first nested bullet;"
"\t\t2) second nested bu... | [
"spikex.pipes.SentX"
] | [((678, 685), 'spikex.pipes.SentX', 'SentX', ([], {}), '()\n', (683, 685), False, 'from spikex.pipes import SentX\n')] |
"""
The Sims 4 Community Library is licensed under the Creative Commons Attribution 4.0 International public license (CC BY 4.0).
https://creativecommons.org/licenses/by/4.0/
https://creativecommons.org/licenses/by/4.0/legalcode
Copyright (c) COLONOLNUTTY
"""
# The purpose of this file is to fix the fact that when try... | [
"sims4communitylib.utils.sims.common_sim_utils.CommonSimUtils.get_sim_info",
"sims4communitylib.modinfo.ModInfo.get_identity"
] | [((787, 809), 'sims4communitylib.modinfo.ModInfo.get_identity', 'ModInfo.get_identity', ([], {}), '()\n', (807, 809), False, 'from sims4communitylib.modinfo import ModInfo\n'), ((1041, 1074), 'sims4communitylib.utils.sims.common_sim_utils.CommonSimUtils.get_sim_info', 'CommonSimUtils.get_sim_info', (['self'], {}), '(se... |
# pylint: disable=redefined-outer-name
import pytest
from app.data_models.session_data import SessionData
from app.views.contexts.thank_you_context import build_default_thank_you_context
@pytest.fixture
def fake_session_data():
return SessionData(
tx_id="tx_id",
schema_name="some_schema_name",
... | [
"app.data_models.session_data.SessionData",
"app.views.contexts.thank_you_context.build_default_thank_you_context"
] | [((242, 472), 'app.data_models.session_data.SessionData', 'SessionData', ([], {'tx_id': '"""tx_id"""', 'schema_name': '"""some_schema_name"""', 'language_code': 'None', 'launch_language_code': 'None', 'survey_url': 'None', 'ru_ref': '"""ru_ref"""', 'response_id': '"""response_id"""', 'case_id': '"""case_id"""', 'period... |
# Copyright 2014 Google Inc. All Rights Reserved.
"""Command for describing HTTP health checks."""
from googlecloudsdk.compute.lib import base_classes
class Describe(base_classes.GlobalDescriber):
"""Display detailed information about an HTTP health check."""
@staticmethod
def Args(parser):
base_classes.Gl... | [
"googlecloudsdk.compute.lib.base_classes.AddFieldsFlag",
"googlecloudsdk.compute.lib.base_classes.GlobalDescriber.Args"
] | [((305, 346), 'googlecloudsdk.compute.lib.base_classes.GlobalDescriber.Args', 'base_classes.GlobalDescriber.Args', (['parser'], {}), '(parser)\n', (338, 346), False, 'from googlecloudsdk.compute.lib import base_classes\n'), ((351, 405), 'googlecloudsdk.compute.lib.base_classes.AddFieldsFlag', 'base_classes.AddFieldsFla... |