text stringlengths 2 999k |
|---|
import os, sys, logging, time, argparse, json
from collections import defaultdict
import numpy as np
import pandas as pd
pd.set_option('display.max_colwidth', 300) # in order to prevent 50 character cutoff of to_html export / ellipsis
from lxml import etree
import flask
from flask import render_template, request, send_... |
"""
Fenced Code Extension for Python Markdown
=========================================
This extension adds Fenced Code Blocks to Python-Markdown.
>>> import markdown
>>> text = '''
... A paragraph before a fenced code block:
...
... ~~~
... Fenced code block
... ~~~
... '''
>>> ht... |
import sys
from PyQt5.QtWidgets import QApplication, QDialog, QMainWindow, QMessageBox
from PyQt5.uic import loadUi
from main_window_ui import Ui_MainWindow
class Window(QMainWindow, Ui_MainWindow):
def __init__(self, parent=None):
super().__init__(parent)
self.setupUi(self)
self.connect... |
# Copyright (c) 2005-2007 by The PolyBoRi Team
from time import process_time as clock
from random import Random
from .PyPolyBoRi import (Polynomial, Variable, Monomial,
BoolePolynomialVector)
from .randompoly import gen_random_poly
from .pbori import (BooleSet, add_up_polynomials, interpolate_... |
from __future__ import print_function
from django.conf import settings
from django.dispatch import receiver
from django.contrib.auth.models import User
from allauth.account.signals import user_signed_up, email_confirmed
from .models import UserProfile
@receiver(user_signed_up, dispatch_uid="user_signed_up")
def creat... |
from __future__ import print_function
import os
import six
import webbrowser
from pygments import highlight
from pygments.lexers import PythonLexer
from pygments.formatters import HtmlFormatter
from bokeh import plotting
from bokeh.document import Document
from bokeh.embed import autoload_static
from bokeh.resources... |
import sys
import csv
import os
from operator import itemgetter
# Define CSV dialect to be used.
csv.register_dialect(
'exp_dialect',
delimiter = '\t'
)
# Read command-line input.
expert_file = sys.argv[1]
output_file = sys.argv[2]
apv_dir = sys.argv[3]
apt_dir = sys.argv[4]
topk_thr = int(sys.argv[5]) #how... |
import pandas as pd
def rank_movies_by_rating(ratings, min_ratings=2):
ranking = (
ratings.groupby("movieId")
.agg(
avg_rating=pd.NamedAgg(column="rating", aggfunc="mean"),
num_ratings=pd.NamedAgg(column="userId", aggfunc="nunique"),
)
.loc[lambda df: df["nu... |
import sys, gzip
inFilePath = sys.argv[1]
outFilePath = sys.argv[2]
dataFile = open(inFilePath,"r")
dataHeaders = dataFile.readline().rstrip("\n").split("\t")
del dataHeaders[1]
dataDict = {}
for sample in range(1, len(dataHeaders)):
dataDict[dataHeaders[sample]] = {}
genes = []
for line in dataFile:
line ... |
import os
import pytest
from pytest_localserver.http import WSGIServer
from secp256k1 import PrivateKey
from sqlalchemy.orm import sessionmaker
from nekoyume.app import create_app
from nekoyume.models import db, User
@pytest.fixture
def fx_app():
app = create_app()
app.config['SQLALCHEMY_DATABASE_URI'] = os... |
import django.dispatch
signal_fetch_latest_metadata = django.dispatch.Signal()
|
from typing import List
import os
import seaborn as sns
import matplotlib.pyplot as plt
import numpy as np
import pandas as pd
import pickle
def cka_wide(X, Y):
"""
Calculate CKA for two matrices. This algorithm uses a Gram matrix
implementation, which is fast when the data is wider than it is
tall... |
#!/usr/bin/env python
# -*- coding: utf-8 -*-
import typer
import time
import gym
import torch
import collections
import numpy as np
import pandas as pd
from pathlib import Path
import matplotlib.pyplot as plt
from sklearn.manifold import TSNE
import pygame
from pygame.locals import VIDEORESIZE
import gym.wrappers a... |
# 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... |
"""Miscellaneous utility functions."""
import os
import glob
import pickle
import re
import numpy as np
from collections import defaultdict
import PIL.Image
import dnnlib
import config
from training import dataset
#----------------------------------------------------------------------------
# Convenience wrappers ... |
# Copyright 2018 Google Inc. 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 applicable law or... |
raise NotImplementedError("UserDict is not yet implemented in Skulpt")
|
from tacotron2.vocoders.waveglow import WaveGlow
from tacotron2.vocoders.waveflow import WaveFlow |
from __future__ import annotations
from pathlib import Path
from typing import Dict, List, Optional, Union
import python_on_whales.components.service.cli_wrapper
import python_on_whales.components.task.cli_wrapper
from python_on_whales.client_config import DockerCLICaller
from python_on_whales.utils import ValidPath,... |
from http.client import OK, CREATED, BAD_REQUEST, NOT_FOUND, METHOD_NOT_ALLOWED, UNAUTHORIZED
import json
from unittest import skip
from django.contrib.auth import get_user_model, authenticate
from django.contrib.auth.models import Group
from django.contrib.gis.geos import Point
from django.core import mail
from djang... |
from datetime import datetime
import copy
import warnings
import numpy as np
try:
from ipyparallel import Client
except ImportError:
warnings.warn("ipyparallel not found. You won't be able to use the ipymspectrum module")
import ChiantiPy
import ChiantiPy.tools.data as chdata
import ChiantiPy.tools.constants ... |
# 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, overload
from ... import _utilities
fro... |
# -*- coding: utf-8 -*-
#
# Copyright (C) 2005-2009 Edgewall Software
# Copyright (C) 2003-2006 Jonas Borgström <jonas@edgewall.com>
# Copyright (C) 2004-2006 Christopher Lenz <cmlenz@gmx.de>
# Copyright (C) 2005-2007 Christian Boos <cboos@edgewall.org>
# All rights reserved.
#
# This software is licensed as described ... |
#!/usr/bin/env python
# -*- encoding: utf-8 -*-
from __future__ import absolute_import
from __future__ import print_function
import io
import re
from glob import glob
from os.path import basename
from os.path import dirname
from os.path import join
from os.path import splitext
from setuptools import find_packages
fro... |
import pytest
from loan_calculator.pmt import constant_return_pmt
def test_unitary_evaluation():
"""Assert equation :math:`\\mathrm{PMT}(1, 1, (1, 1)) = 1` holds."""
assert 1.0 == pytest.approx(constant_return_pmt(1.0, 1.0, [1, 1]), 0.01)
|
import os
from matplotlib import pyplot as plt
import seaborn as sns
import pandas as pd
import numpy as np
from graph_embedding import get_networkx_graph, get_graph_embedding_model
def tagcount(row):
year_key = str(row['CreationYear']) + "{0:0=2d}".format(row['CreationMonth'])
tags = row.CleanedTags.split('... |
# -*- coding: utf-8 -*-
"""
Created on Mon Sept 12 16:35:13 2019
@author: Maxime PINSARD
"""
from PyQt5.QtCore import QObject, pyqtSlot, pyqtSignal
class Matlab_treat(QObject):
matlabGUI_treatphase_signal = pyqtSignal(int, int, int, str)
test_GUI_signal = pyqtSignal()
show_instance_signal = pyqtSign... |
# -*- coding: utf-8 -*-
"""
Created on Sat Jun 27 21:30:37 2020
@author: adwait
"""
import cv2
import numpy as np
import logging
# class ImageTransform:
def backgroundSubtract(frame, frame_bg, alpha, inv = False): #subtract background
logging.debug('%s', frame.shape)
if alpha == 1: #direct subt... |
import sys
import os
import numpy as np
os.environ['TF_CPP_MIN_LOG_LEVEL'] = '3'
import tensorflow as tf
from keras import *
from keras.layers import *
from keras.models import *
from keras.preprocessing import *
from keras.callbacks import *
dim = 128
maxlen = 9
def create_model(ans_dic_ot, weight_matrixx_yn, wei... |
from __future__ import print_function
from googleapiclient.discovery import build
from apiclient.http import MediaIoBaseDownload
import io
import sys
from httplib2 import Http
from oauth2client import file, client, tools
# If modifying these scopes, delete the file token.json.
SCOPES = 'https://www.googleapis.com/auth... |
import tsai
from .imports import *
from .utils import *
from .data.all import *
from .losses import *
from .metrics import *
from .learner import *
from .tslearner import *
from .optimizer import *
from .models.all import *
from .callback.all import *
from .wandb import * |
from API.endpoints.models import Endpoint
from API.endpoints.models import MLAlgorithm
from API.endpoints.models import MLAlgorithmStatus
class MLRegistry:
def __init__(self):
self.endpoints = {}
def add_algorithm(self, endpoint_name, algorithm_object, algorithm_name,
algorithm_sta... |
import sys
sys.path.insert(1,"../../../")
import h2o
from tests import pyunit_utils
from h2o.estimators.naive_bayes import H2ONaiveBayesEstimator
def nb_iris():
print "Importing iris_wheader.csv data...\n"
iris = h2o.upload_file(pyunit_utils.locate("smalldata/iris/iris_wheader.csv"))
iris.describe()
lapl... |
"""
.. module: lemur.certificates.views
:platform: Unix
:copyright: (c) 2015 by Netflix Inc., see AUTHORS for more
:license: Apache, see LICENSE for more details.
.. moduleauthor:: Kevin Glisson <kglisson@netflix.com>
"""
import base64
from builtins import str
from flask import Blueprint, make_response, js... |
"""Prepare rendering of popular smart grid actions widget"""
from apps.widgets.smartgrid import smartgrid
def supply(request, page_name):
"""Supply view_objects content, which are the popular actions from the smart grid game."""
_ = request
num_results = 5 if page_name != "status" else None
#cont... |
if a: # a
# b
c
# c
d
# e
call(
# a
)
operations = [
# Ensure the contenttypes migration is applied before sending
# post_migrate signals (which create ContentTypes).
]
|
"""
Python EDBG protocol communication library
~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~
pyedbglib is a low-level protocol library for communicating with
Microchip CMSIS-DAP based debuggers.
pyedbglib uses HIDAPI package with a USB-level driver such as libusb.
The protocol library has no application usage on its ow... |
import asyncio
import io
import os
import random
import re
import socket
import subprocess
import tarfile
import threading
import time
from contextlib import contextmanager
from functools import partial as p
from io import BytesIO
from typing import Dict, List
import docker
import netifaces as ni
import yaml
from test... |
import argparse
import os
import tensorflow as tf
from xcenternet.datasets import CocoDataset, VocDataset, CustomDataset
from xcenternet.model.callbacks import MAPValidationCallback
from xcenternet.model.config import ModelConfig, XModelType, XModelBackbone, XModelMode
from xcenternet.model.model_factory import create... |
import gym
import numpy as np
from gym.envs.robotics.hand.reach import FINGERTIP_SITE_NAMES
from .vanilla import VanillaGoalEnv
from envs.utils import quat_from_angle_and_axis
class ReachGoalEnv(VanillaGoalEnv):
def __init__(self, args):
VanillaGoalEnv.__init__(self, args)
def generate_goal(self):
thumb_name ... |
# -*- coding: utf-8 -*-
import pytest
from PyQt5.QtCore import pyqtSignal
from PyQt5.QtWidgets import QPlainTextEdit
from hamcrest import not_, equal_to
from pytest import raises
from cute import gestures
from cute.probes import ValueMatcherProbe
from cute.widgets import only_widget, QPlainTextEditDriver
@pytest.fix... |
#! /usr/bin/env python3
'''Regenerates the strong name verification scripts based on the list of
assemblies stored in this file.
The generated files should be checked in.
'''
ASSEMBLIES = sorted([
"AnalysisMemoryTester",
"AnalysisTest",
"AnalysisTests",
"CookiecutterTests",
"DebuggerTests",
"D... |
from baselines.common.mpi_running_mean_std import RunningMeanStd
import baselines.common.tf_util as U
import tensorflow as tf
import gym
from baselines.common.distributions import make_pdtype
import numpy as np
import pdb
def dense3D2(x, size, name, option, num_options=1, weight_init=None, bias=True):
w = tf.get_... |
from uControl import *
import util
def test():
print 'here we go'
uc = uControl()
try:
print 'uc.cuff_pressure', uc.cuff_pressure
uc.record(True)
start = time.time()
print "recording..."
try:
while 1:
print 'uc.cuff_pressure', uc.cuff_pres... |
import _plotly_utils.basevalidators
class CminValidator(_plotly_utils.basevalidators.NumberValidator):
def __init__(self, plotly_name='cmin', parent_name='surface', **kwargs):
super(CminValidator, self).__init__(
plotly_name=plotly_name,
parent_name=parent_name,
edit_t... |
import math
import numpy as np
def rmse_spearman(matrix_predicted, matrix_actual, path):
"""
Calculates the RMSE error and Spearman correlation
Parameters:
matrix_predicted: this matrix contains detected values
matrix_test: this matrix contains original values
path: this is the path to the t... |
class Solution(object):
def arrayPairSum(self, nums):
"""
:type nums: List[int]
:rtype: int
"""
nums = sorted(nums)
result = 0
for i in range(0,len(nums)-1,2):
result = result+ nums[i]
return result
s = Solution().arrayPairSum([4,3,2,1])
p... |
from textual.app import App
from textual.reactive import Reactive
from textual.widgets import Footer, Placeholder
class SmoothApp(App):
"""Demonstrates smooth animation. Press 'b' to see it in action."""
async def on_load(self) -> None:
"""Bind keys here."""
await self.bind("b", "toggle_sideb... |
#!/usr/bin/env python3
# Copyright (c) 2017-present, Facebook, Inc.
# All rights reserved.
#
# This source code is licensed under the license found in the LICENSE file in
# the root directory of this source tree. An additional grant of patent rights
# can be found in the PATENTS file in the same directory.
import argp... |
from uuid import uuid4
from ee.clickhouse.client import sync_execute
from ee.clickhouse.materialized_columns import materialize
from ee.clickhouse.models.event import create_event
from ee.clickhouse.queries.trends.trend_event_query import TrendsEventQuery
from ee.clickhouse.util import ClickhouseTestMixin
from posthog... |
def azurerm_policy_assignment(crf,cde,crg,headers,requests,sub,json,az2tfmess,cldurl):
tfp="azurerm_policy_assignment"
azr=""
if crf in tfp:
# REST or cli
# print "REST Managed Disk"
url="https://" + cldurl + "/subscriptions/" + sub + "/providers/Microsoft.Authorization/pol... |
from pytest import mark
from wordgoal.document_types import DocumentType, get_document_type
@mark.parametrize(
"suffix, expect",
[
("", DocumentType.UNHANDLED),
(".foo", DocumentType.UNHANDLED),
(".markdown", DocumentType.MARKDOWN),
(".md", DocumentType.MARKDOWN),
(".t... |
import RPi.GPIO as GPIO
import time
'''
----------------------------------
CONFIGURATION
----------------------------------
'''
GPIO.setmode(GPIO.BCM)
GPIO.setup(25,GPIO.OUT)
'''
----------------------------------
main activity
----------------------------------
'''
while True:
GPIO.output(25,GPIO.HIGH)
time.s... |
from gd.abstract_entity import AbstractEntity
from gd.datetime import datetime
from gd.enums import FriendRequestType
from gd.model import FriendRequestModel # type: ignore
from gd.text_utils import make_repr
from gd.typing import TYPE_CHECKING, Optional
from gd.user import User
__all__ = ("FriendRequest",)
... |
# -*- coding: utf-8 -*-
#
# Nextflow documentation build configuration file, created by
# sphinx-quickstart on Sat May 5 16:57:28 2012.
#
# This file is execfile()d with the current directory set to its containing dir.
#
# Note that not all possible configuration values are present in this
# autogenerated file.
#
# Al... |
import math
n = float(input('Informe um número com decimais: '))
print('A parte inteira de {} é {}'.format(n, math.trunc(n)))
|
#!/usr/bin/env python
# Python reverse dns script
# Goes through a list of ip addresses and tries to do a reverse lookup
import sys
import dns.resolver,dns.reversename
#import re
from netaddr import *
from time import sleep
if len(sys.argv) < 3:
print "Usage: ./rev.py iplist.txt dnsserver"
exit()
... |
import argparse
import utilities as util
import word_graph
import hits
def main():
parser = argparse.ArgumentParser(usage='sorry, look at readme...', \
description='arg description', epilog='end')
parser.add_argument('inputF', help='write the file name of the input text.')
parser.add_argument('... |
"""
Exodus II data structures
"""
#-----------------------------------------------------------------------------
# Copyright (c) 2013, yt Development Team.
#
# Distributed under the terms of the Modified BSD License.
#
# The full license is in the file COPYING.txt, distributed with this software.
#-----------------... |
#!/usr/bin/env python
# -*- coding: utf-8 -*-
from __future__ import absolute_import, division, print_function
__metaclass__ = type
# Copyright 2019 Palo Alto Networks, Inc
#
# Licensed under the Apache License, Version 2.0 (the "License");
# you may not use this file except in compliance with the License.
# You ... |
import math
def calculate_fuel(mass):
return math.floor(mass / 3) - 2
def main():
f = open("input.txt", "r")
lines = f.readlines()
total_fuel = 0
for line in lines:
mass = int(line)
fuel = calculate_fuel(mass)
print("{mass} = {fuel}".format(mass=mass, fuel=fuel))
total_fuel += fuel
print("... |
"""Posterior over states after applying (Extended/Unscented) Kalman filtering/smoothing.
Contains the discrete time and function outputs. Provides dense output by being
callable. Can function values can also be accessed by indexing.
"""
from __future__ import annotations
import abc
from typing import Iterable, Optio... |
import os
import platform
import textwrap
import pytest
from conan.tools.env.environment import environment_wrap_command
from conans.test.utils.tools import TestClient
from conans.util.files import save
@pytest.fixture()
def client():
openssl = textwrap.dedent(r"""
import os
from conans import C... |
import requests
from bs4 import BeautifulSoup
import re
CONTENT_CLASS_NAME = "TweetTextSize"
CONTENT_CONTAINER_TAGS = ["p"]
EMPTY_ITEMS = [None, " ", "None"]
TWITTER_URL = "https://twitter.com/"
def get_elements(twitter_handle):
url = TWITTER_URL + twitter_handle
response = requests.get(url)
html = respo... |
class Solution:
def largestRectangleArea(self, height):
max_space = 0
for i in range(len(height)):
if i + 1 < len(height) and height[i] <= height[i + 1]: continue
min_high = height[i]
for j in range(i, -1, -1):
min_high = min(min_high, height[j])
... |
#!/usr/bin/env python
# -*- coding: utf-8 -*-
from argparse import ArgumentParser, FileType
import itertools as it
import os
import mpi4py.rc
mpi4py.rc.initialize = False
import h5py
from pyfr.backends import BaseBackend, get_backend
from pyfr.inifile import Inifile
from pyfr.mpiutil import register_finalize_handle... |
n = int(input())
positives = []
negatives = []
for i in range(n):
number = int(input())
if number >= 0:
positives.append(number)
else:
negatives.append(number)
print(positives)
print(negatives)
print(f'Count of positives: {len(positives)}. Sum of negatives: {sum(negatives)}')
|
# Description: Setup file for Python functions
#
# Building: python setup_python.py
#
# Copyright (c) 2022 ETH Zurich, Christian R. Steger
# MIT License
# Load modules
import importlib
import py_compile
# Check availability of external packages
packages = ("numpy", "scipy", "geographiclib", "pyproj", "osgeo",
... |
"""
NTH SMALLEST ELEMENT
Given an unsorted list, create a function that returns the nth smallest element
(the smallest element is the FIRST smallest, the second smallest element is the
second smallest, etc.).
Examples:
- nth_smallest([1, 3, 5, 7], 1) -> 1
- nth_smallest([1, 3, 5, 7], 3) -> 5
- nth_smalles... |
"""
sphinx.util.rst
~~~~~~~~~~~~~~~
reST helper functions.
:copyright: Copyright 2007-2021 by the Sphinx team, see AUTHORS.
:license: BSD, see LICENSE for details.
"""
import re
from collections import defaultdict
from contextlib import contextmanager
from typing import Dict, Generator
from unico... |
# Copyright 2021 The TensorFlow Authors
#
# 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 ... |
import functools
import typing
from river.stats import Var
from river.utils import VectorDict
from ..utils import BranchFactory
from .base import Splitter
class EBSTSplitter(Splitter):
"""iSOUP-Tree's Extended Binary Search Tree (E-BST).
This class implements the Extended Binary Search Tree[^1] (E-BST)
... |
def XForwardedForMiddleware(get_response):
def middleware(request):
if 'HTTP_X_FORWARDED_FOR' in request.META:
request.META['REMOTE_ADDR'] = request.META['HTTP_X_FORWARDED_FOR'].split(',')[0].strip()
return get_response(request)
return middleware
|
import logging
import math
from time import process_time
from datetime import date
from numpy.core.numeric import Infinity, NaN
import pandas as pd
from bsbetl.alltable_calcs import Calculation
from bsbetl.alltable_calcs.at_params import at_calc_params
from bsbetl.calc_helpers import first_trading_row_index, last_days... |
#
# JobManager - Thread that assigns jobs to worker threads
#
# The job manager thread wakes up every so often, scans the job list
# for new unassigned jobs, and tries to assign them.
#
# Assigning a job will try to get a preallocated VM that is ready,
# otherwise will pass 'None' as the preallocated vm. A worker thre... |
from builtins import range
import numpy as np
from random import shuffle
from past.builtins import xrange
def softmax_loss_naive(W, X, y, reg):
"""
Softmax loss function, naive implementation (with loops)
Inputs have dimension D, there are C classes, and we operate on minibatches
of N examples.
... |
from plan2scene.config_manager import ConfigManager
from plan2scene.common.residence import House, Room
import torch
def get_house_graph(conf: ConfigManager, house: House, surface_maskout_map: dict, key="prop"):
"""
Generates node embeddings and edge pairs for a given house.
:param conf: ConfigManager
... |
import torch
import torch.nn as nn
import torch.optim as optim
from backpack import backpack
from backpack.extensions import BatchGrad
from lib.BaseAlg import BaseAlg, get_device, Network, obs_data_all
import numpy as np
from backpack import backpack, extend
class NeuralTSUserStruct:
def __init__(self, feature, f... |
# Copyright 2021 Google 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
# https://www.apache.org/licenses/LICENSE-2.0
# Unless required by applicable law or agreed to in writing, sof... |
class RequestError(Exception):
def __init__(self, message="failed to request data"):
Exception.__init__(self, message)
class ParamError(Exception):
def __init__(self, message="invalid param"):
Exception.__init__(self, message)
|
"""Import CLTK corpora.
TODO: Fix so ``import_corpora()`` can take relative path.
TODO: Add https://github.com/cltk/pos_latin
"""
__author__ = ['Kyle P. Johnson <kyle@kyle-p-johnson.com>',
'Stephen Margheim <stephen.margheim@gmail.com>']
__license__ = 'MIT License. See LICENSE.'
import errno
import os
i... |
import unittest
from unittest import mock
from sqlalchemy import create_engine
from sqlalchemy.orm import sessionmaker
from datetime import datetime
from meerkat_abacus import model
from meerkat_abacus.pipeline_worker.process_steps import add_multiple_alerts
from meerkat_abacus.pipeline_worker.process_steps import wri... |
import numpy as np
class CosineDecayLR(object):
def __init__(self, optimizer, T_max, lr_init, lr_min=0., warmup=0):
"""
a cosine decay scheduler about steps, not epochs.
:param optimizer: ex. optim.SGD
:param T_max: max steps, and steps=epochs * batches
:param lr_max: lr_ma... |
from asposepdf import Settings
from com.aspose.pdf import Document
class GetDocumentWindow:
def __init__(self):
dataDir = Settings.dataDir + 'WorkingWithDocumentObject/GetDocumentWindow/'
# Open a pdf document.
doc = Document(dataDir + "input1.pdf")
# Get diffe... |
# Copyright 2020 Google 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
#
# https://www.apache.org/licenses/LICENSE-2.0
#
# Unless required by applicable law or agreed to in writing, ... |
import zmq
import sys
import os
import numpy as np
from io import StringIO
from numpy.linalg import inv
from scipy.linalg import *
import json
def loadFiles(path):
files = {}
dataDir = os.fsencode(path)
for file in os.listdir(dataDir):
filename = os.fsdecode(file)
print("Loading {}".format(... |
# Python3
from solution2 import magicalWell as f
qa = [
(1, 2, 2, 8),
(1, 1, 1, 1),
(6, 5, 3, 128),
(1601, 337, 0, 0),
(1891, 352, 0, 0),
(1936, 1835, 5, 17800540),
(957, 57, 2, 110113),
(687, 1337, 0, 0),
(491, 1552, 4, 3060400),
(1275, 362, 2, 924738)
]
for *q, a in qa:
... |
def greeting(name: str) -> str:
return 'Hello ' + name.upper()
def add(num1, num2) -> int:
return num1 + num2
add().bit_length()
|
#!/usr/bin/env python
# -*- coding: utf-8 -*-
import json
from alipay.aop.api.response.AlipayResponse import AlipayResponse
class AlipayPcreditLoanCommissionQueryResponse(AlipayResponse):
def __init__(self):
super(AlipayPcreditLoanCommissionQueryResponse, self).__init__()
self._activity_commissi... |
from tkinter.messagebox import askyesno
def quit_popup():
"""
Quit action confirmation
:return: Boolean representing confirmation
"""
return askyesno(title='Confirm exit', message='Are you sure you want to exit?')
|
from weakref import WeakSet
from .exceptions import translate_exceptions, InterfaceError
from .cursor import Cursor
class Connection(object):
def _assert_valid(self):
if self.impl is None:
raise InterfaceError("Connection already closed")
def __init__(self, impl):
self.impl = imp... |
# Copyright 2015 IBM Corp.
#
# 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 t... |
# -*- coding: utf-8 -*-
"""
Dummy conftest.py for nuls2_python.
If you don't know what this is for, just leave it empty.
Read more about conftest.py under:
https://pytest.org/latest/plugins.html
"""
# import pytest
|
# -*- mode: python; coding: utf-8 -*-
# Copyright 2016 the HERA Collaboration
# Licensed under the BSD License.
"Observations."
from __future__ import absolute_import, division, print_function, unicode_literals
__all__ = str('''
ObservingSession
Observation
''').split()
from flask import flash, redirect, render_tem... |
import numpy as np
import tensorflow as tf
from ficbot.data.loaders import ImageLoader
import pickle
def sample(preds, temperature=1.0):
""" Helper function to sample an index from a probability array """
preds = np.asarray(preds).astype("float64")
preds = np.log(preds) / temperature
exp_preds = np.e... |
# Copyright 2018 Pants project contributors (see CONTRIBUTORS.md).
# Licensed under the Apache License, Version 2.0 (see LICENSE).
import functools
import logging
import os
import re
from dataclasses import dataclass
from enum import Enum
from pants.backend.jvm.subsystems.dependency_context import DependencyContext ... |
import requests
from requests.adapters import HTTPAdapter
from urllib3.util.retry import Retry
def requests_retry_session(retries=3, backoff_factor=0.3, status_forcelist=(500, 502, 504), session=None):
session = session or requests.Session()
retry = Retry(
total=retries,
read=retries,
... |
# -*- coding: utf-8 -*-
"""
report
~~~~~~~~~~~~~~~~
Implements automation report Cobra data
:author: BlBana <635373043@qq.com>
:homepage: https://github.com/WhaleShark-Team/cobra
:license: MIT, see LICENSE for more details.
:copyright: Copyright (c) 2018 Feei. All rights reserved
""... |
# This is probably my favorite sorting algorithm since it really just relies on
# inherent features of a data structure to sort elements as they are added. In my
# opinion, this is the sorting algorithm that feels the most natural fit for the job
|
#!/usr/bin/python
# -*- coding: utf-8 -*-
"""
=====================
Supervised PCA against LDA and QDA
=====================
A comparison of supervised PCA against LDA and QDA.
"""
print(__doc__)
# Code source: Gaël Varoquaux
# Andreas Müller
# Modified for documentation by Jaques Grobler
# License: BS... |
Subsets and Splits
No community queries yet
The top public SQL queries from the community will appear here once available.