content stringlengths 5 1.05M |
|---|
"""
============================
Augmented learning curve
============================
This example generates an augmented learning curve for a
quantum device calibration application.
"""
# Author: Alex Wozniakowski <wozn0001@e.ntu.edu.sg>
import numpy as np
from physlearn import Regressor
from physlearn.datasets ... |
from django.conf import settings
from django.contrib import admin
from django.urls import include, path
from drf_yasg import openapi
from drf_yasg.views import get_schema_view
from rest_framework import permissions, routers
from test_app.core.rest import ImageViewSet, users_logout_view, users_me_view
from test_app.cor... |
#!/usr/bin/env python
# -*- coding: utf-8 -*-
from pathlib import Path
from typing import List, Optional, Union, Dict
from pydantic import BaseModel, Field
from box import Box
class AudioTrack(BaseModel):
index: int
outdex: int
codec: str = ""
downmix: Optional[str] = None
title: str = ""
lan... |
#!/usr/bin/env python
# -*- coding: utf-8 -*-
"""
-------------------------------------------------
@ Author : pengj
@ date : 2018/11/13 22:25
@ IDE : PyCharm
@ GitHub : https://github.com/JackyPJB
@ Contact : pengjianbiao@hotmail.com
---------------... |
import xml.sax
from typing import List
doc_mem = 0
chunk_no = 0
class Page:
def __init__(self, doc_no):
self.doc_no: int = doc_no
self.title: List[str] = []
self.body: List[str] = []
def __str__(self):
print("----Doc---")
print("Doc no", self.doc_no)
print("Tit... |
#!/usr/bin/env python
'''
GRIPPER OUTPUT REGISTERS & FUNCTIONALITES:
rACT (ACTION REQUEST): First action to be made prior to any other actions, rACT bit will activate the Grpiper. Clear rACT to reset the Gripper and clear fault status.
rGTO: The "Go To" action moves the Gripper fingers to the requested position usin... |
from moviepy.video.io.ffmpeg_tools import ffmpeg_extract_subclip
from moviepy.editor import VideoFileClip
import telebot
numOfVideo = 0
TOKEN = "TOKEN"
bot = telebot.TeleBot(TOKEN)
def myfunc(name,numOfVideo):
numofVideos = 0
required_video_file_name = name
video_file = VideoFileClip(required_vid... |
import os
def get_file_path(filename):
if not os.path.exists('config'):
os.makedirs('config')
return 'config/' + filename
|
from oeqa.core.decorator.depends import OETestDepends
from oeqa.runtime.cases.dnf import DnfTest
from oeqa.utils.httpserver import HTTPService
class DnfSelftest(DnfTest):
@classmethod
def setUpClass(cls):
import tempfile
cls.temp_dir = tempfile.TemporaryDirectory(prefix="oeqa-remotefeeds-")
... |
def Justify(string: str, maxWidth: int) -> str:
"""Returns justified string.
Keyword args:
string -- string largo para que se note
maxWidth -- ancho del texto final
Use:
print(Justify(string, maxWidth))
"""
words = string.split()
res, cur, num_of_letters = [], [], 0
for w in wo... |
# -*- coding: utf-8 -*-
"""
:copyright: Copyright 2016-2020 Sphinx Confluence Builder Contributors (AUTHORS)
:license: BSD-2-Clause (LICENSE)
"""
from sphinxcontrib.confluencebuilder.std.sphinx import DEFAULT_ALIGNMENT
from tests.lib import EXT_NAME
from tests.lib import assertExpectedWithOutput
from tests.lib import ... |
from fastai.vision.all import *
from fastai.vision import models
import torch
import torchvision
import sys
sys.path.append('./')
from src.models.loss_model import get_loss_model_vgg, siamese_splitter
from src.types.tensor_tiles import BrightfieldTile, FluorescenceTile
class TileMSELoss(torch.nn.Module):
""" MSE... |
from device import Motor
from time import sleep
import math
class TwoWheelController:
"""The class represents the controller for a two-wheeled robot. The controller
class must implement set_axis function.
"""
def __init__(self):
super(TwoWheelController, self).__init__()
self.left_mo... |
# -*- coding: utf-8 -*-
"""anrr.ipynb
Automatically generated by Colaboratory.
Original file is located at
https://colab.research.google.com/drive/1KIujWJRWQke8gPWWYvIWc4WQN14Mx7XX
"""
import numpy as np
import pandas as pd
import matplotlib.pyplot as plt
df=pd.read_csv('C02.csv')
df=df.drop(columns=['Data_s... |
'''HOT Tests for Maitre and Waiter classes
Needs a running API. Using example from Flask-Restless
Just run python3 quickstart.py'''
import json
from cli_talker.service_binder import (Maitre, RESTWaiter)
import cli_talker.localizations
URL = 'http://localhost:5000'
maitre = Maitre()
maitre.add_waiter({'json_api': RES... |
from hydroserver.model.model import Pump
from flask import Blueprint, request
from hydroserver.controllers.pump_manager import PumpManager
def create_pump_blueprint(pump_manager: PumpManager):
pump_blueprint = Blueprint("pump", __name__)
@pump_blueprint.route("/")
def list_pumps():
pump... |
class Solution:
def eventualSafeNodes(self, graph: List[List[int]]) -> List[int]:
nodeColors = {}
for i in range(len(graph)):
nodeColors[i] = 'white'
def dfs(node): # return if is safe
if nodeColors[node] != 'white':
return nodeColors[node] == 'black'... |
from bs4 import BeautifulSoup
import datetime
import requests
import csv
time = datetime.datetime.now()
todays_date = str(time.month) + str(time.day) + str(time.year)
r = requests.get("https://www.uber.com/en-US/cities")
soup = BeautifulSoup(r.text, "html.parser")
cities_container = soup.find("section", attrs={"clas... |
import json
import click
from wordnik import *
from .utils import create_word_api, load_api_key, fetch_translations
class Word(object):
def __init__(self, word, **kwargs):
self.word = word
self._meanings = kwargs.get('_meanings', list())
self._examples = kwargs.get('_examples', list())
... |
import os
import numpy as np
import matplotlib.pyplot as plt
from sys import argv
def read_file(file_name):
"""
Read a file.
"""
with open(file_name) as f:
in_data = [line.strip().split("\t") for line in f]
return in_data
def plot_ecdf(x1, x2, dlab, clr1, clr2, tit, xlab, fig_name):
fi... |
"""Test trait types of the widget packages."""
# Copyright (c) IPython Development Team.
# Distributed under the terms of the Modified BSD License.
from unittest import TestCase
from IPython.utils.traitlets import HasTraits
from IPython.utils.tests.test_traitlets import TraitTestBase
from IPython.html.widgets import ... |
import os
import requests
from flask import jsonify, make_response, request
from dss import dss_handler
from dss.api.files import get_helper
from dss.config import Replica
from dss.util.version import datetime_from_timestamp
@dss_handler
def get_data_object(object_id: str):
"""
Translates a DRS data object ... |
import unittest
import os
from sklearn import neighbors
from .internal import *
from .globals import *
class TestHelp(unittest.TestCase):
def setUp(self):
pass
# self.dirname = os.path.dirname(__file__)
# self.dataset = pd.read_csv(self.dirname + "/resources/train.csv")
# self.house... |
import os
from determined.experimental import client
from dotenv import load_dotenv
load_dotenv()
client.login(
master=os.getenv('DET_MASTER'),
user=os.getenv('DET_USERNAME'),
password=os.getenv('DET_PASSWORD')
)
def download_and_organize_checkpoints(trial_id, name, path='./checkpoints'):
trial = c... |
import frappe
from frappe.utils import flt, today
import json
@frappe.whitelist()
def get_pending_so(**kwargs):
data = {"items": [], "customer": "", "pending_bal": 0, "closing_bal": 0}
customer = ''
if kwargs.get("payment_allocation_party"):
customer = kwargs.get("payment_allocation_party")
query = """select so... |
import tflearn
def highway_model_2d(input_tensor, output_dimension=1, recurrent_layer='rnn', recurrent_params=None):
"""
Generates an inception model that conforms to specified input/output tensors.
:param input_tensor: 4D Tensor of input dimensions [batch, x, y, color_channels]
:param output_dimensio... |
import random
import time
aptal = str(input("Aptallık Testi Yapılacak Kişinin İsimi:"))
oran = random.randint(1,100)
print("\n \nAptallık Yüzdesi Hesaplanıyor....")
time.sleep( 1.25 )
print("\n \n{} Kişisi %{} Aptal".format(aptal,oran))
|
from gym_minigrid.minigrid import *
from gym_minigrid.register import register
class PutNearEnv(MiniGridEnv):
"""
Environment in which the agent is instructed to place an object near
another object through a natural language string.
"""
def __init__(
self,
size=6,
numObjs=2... |
# Standard imports
import logging
import logging.config
# Third party imports
import flask
# Application imports
from models import database
import config
from controllers.controllers import base
LOGGER = logging.getLogger(__name__)
def create_app():
"""
Creates the base Flask application for running
... |
"""Forwarding imports and legacy utilities for authentication backends.
This module provides legacy functionality for registering authentication
backends, along with forwarding imports for:
.. autosummary::
:nosignatures:
~reviewboard.accounts.backends.ad.ActiveDirectoryBackend
~reviewboard.accounts.backend... |
from typing import Callable
from sqlalchemy import Boolean
from sqlalchemy.engine import Engine
from sqlalchemy.orm import Session
class RoutingSession(Session):
def __init__(self, engine_selector: Callable[[Boolean], Engine], **kwargs):
self._engine_selector = engine_selector
super().__init__(*... |
import pypandoc
from setuptools import setup, find_packages
# TODO: Change the following variables to match your app
app_name = 'appsync-resolver-uploader'
# Versions should comply with PEP440. For a discussion on single-sourcing
# the version across setup.py and the project code, see
# https://packaging.python.org... |
from .base import *
DEBUG = False
ALLOWED_HOSTS = ["django-api.staging.motius.de"]
SITE_URL = 'http://django-api.staging.motius.de'
STATIC_URL = 'http://django-api.staging.motius.de/static/'
try:
from .local import *
except ImportError:
pass
|
# <<BEGIN-copyright>>
# Copyright 2021, Lawrence Livermore National Security, LLC.
# See the top-level COPYRIGHT file for details.
#
# SPDX-License-Identifier: BSD-3-Clause
# <<END-copyright>>
from pqu import PQU as PQUModule
from xData import multiD_XYs as multiD_XYsModule
from fudge.productData.distributions impo... |
a = 1
b = 2
c = 3
d,e,f = 1,2,3
g = 4,5,6 # 元组 tuple
print(type(g))
f = 1,2,3
a,b,c = g
print(a,b,c) |
#!/usr/bin/env python
from setuptools import setup
import somerset
setup(name='somerset',
version=somerset.__version__,
description=somerset.__doc__,
author='Lawrence Hudson',
author_email='l.hudson@nhm.ac.uk',
scripts=['somerset.py'],
)
|
Pi = 3.14159;
def area(raio):
return Pi * (raio ** 2);
def comprimento_circunferencia(raio):
return 2 * Pi * raio; |
import pandas as pd
from PySide2.QtWidgets import (
QWidget,
QHBoxLayout,
QVBoxLayout,
QFormLayout,
QTableView,
QPushButton,
QComboBox,
QHeaderView
)
from rboost.gui.utils.pandasmodel import PandasModel
class ListDocumentsWindow(QWidget):
def __init__(self, rboost):
super... |
from functools import reduce
max_prod = 1
N = "73167176531330624919225119674426574742355349194934969835203127745063262395783180169848018694788518438586156078911294949545950173795833195285320880551112540698747158523863050715693290963295227443043557668966489504452445231617318564030987111217223831136222989342338030813... |
import cv2
import numpy as np
# Define a class to receive the characteristics of each line detection
class Line():
def __init__(self):
# was the line detected in the last iteration?
self.detected = False
# x values of the last n fits of the line
self.recent_xfitted = []
#... |
from app.models import Nonce
from django.contrib.auth import login
from django.contrib.auth.views import LoginView as LoginViewBase
from django.http.response import HttpResponseBadRequest, HttpResponseRedirect
class LoginView(LoginViewBase):
def get_context_data(self, **kwargs):
context = super().get_con... |
import re
from collections import deque, defaultdict
def max_score(_players, _marbles):
field = deque([0])
players_scores = defaultdict(int)
for marble in range(1, _marbles + 1):
if marble % 23 == 0:
field.rotate(7)
players_scores[marble % _players] += field.pop() + marbl... |
def data(name, email, date, phone_number, content):
message = f''' Mr/Mrs {name} has booked an Appointment for the Problem {content} on {date}.
Your Details are ,
email : {email}
phone Number : {phone_number}
Will get to You as Soon as Possible!
'''
return message |
""" PyTorch Lamb optimizer w/ behaviour similar to NVIDIA FusedLamb
This optimizer code was adapted from the following (starting with latest)
* https://github.com/HabanaAI/Model-References/blob/2b435114fe8e31f159b1d3063b8280ae37af7423/PyTorch/nlp/bert/pretraining/lamb.py
* https://github.com/NVIDIA/DeepLearningExample... |
from datetime import timedelta, time
from django.utils import timezone as dtz
from pytz import utc
from django.shortcuts import render
#from django.http import HttpResponse
from django import forms
from clinic.models import Clinic
from clinic.distance import get_distances
HOUR = timedelta(hours=1)
EightAM = time(ho... |
from urlparse import urlsplit, urlunsplit, urlparse
from django import template
from django.http.request import QueryDict
from django.template.defaultfilters import floatformat
from django.contrib.humanize.templatetags.humanize import intcomma
from ..models import GERMAN_STATES_DICT
register = template.Library()
... |
"""Market-level structuring of BLP results."""
from typing import List, Optional, Tuple
import numpy as np
from .market import Market
from .. import exceptions, options
from ..configurations.iteration import Iteration
from ..utilities.basics import Array, Bounds, Error, SolverStats, NumericalErrorHandler
class Res... |
# -*- coding: utf-8 -*-
# pylint: disable=fixme
# Disable while we have Python 2.x compatability
# pylint: disable=useless-object-inheritance
"""Sonos Music Services interface.
This module provides the MusicService class and related functionality.
"""
from __future__ import absolute_import, unicode_literals
import... |
##################################################################
######################## include.py ############################
##################################################################
##### ekate - Enhanced KRATOS for Advanced Tunnel Enineering #####
##### copyright by CIMNE, Barcelona, Spain ... |
import threefive
'''
tons of segmentation upid examples
'''
ti= '/DA4AAAAAAAA///wBQb+AAAAAAAiAiBDVUVJAAAAA3//AAApPWwHDE1WMDAwNDE0NjQwMBAAAIH4Mwc='
isan ='/DA4AAAAAAAA///wBQb+AAAAAAAiAiBDVUVJAAAABn//AAApPWwGDAAAAAA6jQAAAAAAABAAAPaArb4='
isan2 ='/DAzAAAAAAAA///wBQb+AAAAAAAdAhtDVUVJAAAABn+/BgwAAAAAOo0AAAAAAAARAAAT5al... |
# AprilTags Pixy I2C Emulation Script
#
# This script allows your OpenMV Cam to transmit AprilTag detection data like
# a Pixy (CMUcam5) tracking colors in I2C mode. This script allows you to
# easily replace a Pixy (CMUcam5) color tracking sensor with an OpenMV Cam
# AprilTag tracking sensor. Note that this only runs ... |
from toee import *
def OnBeginSpellCast(spell):
print "Righteous Fury OnBeginSpellCast"
print "spell.target_list=", spell.target_list
print "spell.caster=", spell.caster, " caster.level= ", spell.caster_level
def OnSpellEffect(spell):
print "Righteous Fury OnSpellEffect"
spell.duration = 10 * spe... |
from utilidadescev import *
def linha(n=70):
print('\033[37m-\033[m'*n)
def centrar(n='', a=0, b=''):
return f'\033[37m|\033[m {n:{b}^{a}} \033[37m|\033[m'
def rodape(n=''):
linha()
print(centrar(n, 74))
linha()
def menu(*n):
cont = 0
for c in n:
cont += 1
print(f'\03... |
from django.shortcuts import render
from django.conf import settings
from django.core.mail import send_mail
from django.views.decorators.csrf import csrf_exempt
from zoom.models import StoreData,CurrentMeetinglog,AuthIds,Files,ReportLog,Metrics
from django.views.generic import TemplateView
from django.contrib.auth.deco... |
from django.urls import path
from users.views import DeveloperInfoView
app_name = 'users'
urlpatterns = [
# User developer info
path(
'info',
DeveloperInfoView.as_view(),
name='info'
),
]
|
import six
import cachetools
def polygon_from_bounds(bounds):
"Return a GeoJSON Polygon dict from a (minx, miny, maxx, maxy) tuple"
return {
"type": "Polygon",
"coordinates": (
(
(bounds[2], bounds[1]),
(bounds[2], bounds[3]),
(bound... |
from openpharmacophore.pharmacophoric_point import PharmacophoricPoint
from collections import namedtuple
import xml.etree.ElementTree as ET
import pyunitwizard as puw
import numpy as np
def from_ligandscout(file_name):
""" Loads a pharmacophore from a ligandscout pml file.
Parameters
----------
... |
import sys
import os
import time
import math
import torch
import numpy as np
from PIL import Image, ImageDraw, ImageFont
from torch.autograd import Variable
import itertools
import struct # get_image_size
import imghdr # get_image_size
def sigmoid(x):
return 1.0 / (np.exp(-x) + 1.)
def softmax(x):
x = np... |
from pklearn import Table
from pklearn.templates import simulate, BasicPlayer
from sklearn.ensemble import GradientBoostingRegressor
if __name__ == '__main__':
t = Table(smallBlind=1, bigBlind=2, maxBuyIn=200)
players = []
for i in range(6):
#create BasicPlayer that uses GradientBoosting... |
import typing
from dataclasses import dataclass
from common.dataclass import BaseDataclass
from common.helpers.bytearray import ByteArray
from common.session import Session
@dataclass
class Request(BaseDataclass):
raw_data: ByteArray # Data received from socket
session: Session # Client connection session
... |
import os
from lxml import etree
from collections import defaultdict
def get_text_title(root):
"""extract text title from NAF"""
target = root.find('nafHeader/fileDesc')
title = target.get('title')
return title
def srl_id_frames(root):
"""Load a NAF file, extract the frames and their corresponding... |
######################################################################
# barrel.py
# Author: Diao Zheng
# --------------------------------------------------------------------
# Barreling utility for typescript implementation.
#
# Place "@barrel ignore" in header comment in index.ts for a directory
# if the directory sh... |
def sun_angle(time):
t_minutes = int(time.split(":")[0])*60 + int(time.split(":")[1])
if t_minutes < 360 or t_minutes > 1080:
return "I don't see the sun!"
else:
res = (t_minutes-360)/4
return round(res,2)
if __name__ == '__main__':
print("Example:")
print(sun_angle("07:0... |
stra = 'PA 500 500;'
print(stra)
# remove ;
lista = list(stra)
print(lista)
print(len(lista))
print(lista[len(lista) - 1])
lista[len(lista) - 1] = ' '
strb = ''.join(lista)
print(strb)
listb = strb.split(' ')
print(listb)
if listb[0] == 'PA':
print(listb[0])
str(KeyError('bad'))
|
from gcp_airflow_foundations.base_class.source_table_config import SourceTableConfig
from gcp_airflow_foundations.base_class.source_template_config import SourceTemplateConfig
def convert_template_to_table(template_config: SourceTemplateConfig, table_name: str):
landing_zone_table_name_override = \
templ... |
"""
Tomas Bolger 2021
Python 3.9
Unittests for base cases
"""
import unittest
import os
import sys
from scalpel.typeinfer.typeinfer import TypeInference
from collections import OrderedDict
path_to_current_file = os.path.realpath(__file__)
current_directory = os.path.split(path_to_current_file)[0]
py_version_above_38 ... |
class EggHunter:
def __init__(self, shellcode, egg):
self.__shellcode = shellcode;
self.__egg = egg;
def generate(self):
return self.__egg+self.__egg+self.__shellcode
def hunter_code(self):
return "\\x31\\xc9\\xf7\\xe1\\x66\\x81\\xca\\xff\\x0f\\x42\\x8d\\x5a\\x04\\x31\\xc0\\xb0\\x21\\xcd\\x80\\x... |
# Copyright (c) 2019 Steven R. Brandt
#
# Distributed under the Boost Software License, Version 1.0. (See accompanying
# file LICENSE_1_0.txt or copy at http://www.boost.org/LICENSE_1_0.txt)
from phylanx import Phylanx
from phylanx.util import debug_output
def debug(s): # silence flake
pass
@Phylanx
def ... |
"""实现一个支持上下文管理器的有限状态机"""
import string
from typing import List, Set, Dict, Tuple, NoReturn, Optional, Any
from ..error import Error
from ..tools.time import TimeTools as timetools
from ..tools.encrypt import EncryptTools as enctools
class StateExistError(Error):
"""状态码已经存在错误"""
code = 11001
description ... |
# Generated by Django 2.1.7 on 2019-02-26 17:48
from django.db import migrations, models
class Migration(migrations.Migration):
dependencies = [
('studies', '0001_initial'),
]
operations = [
migrations.AddField(
model_name='study',
name='attribution',
... |
from sample.dataset import load_transformed_car_data, plot_feature_importance
from sample.machine_learning import split_test_and_train, linear_fit
from sklearn.linear_model import LinearRegression
def main():
car_data = load_transformed_car_data()
y = car_data.pop('Selling_Price')
X = car_data
plot_... |
from asyncio import gather
from aiohttp import ClientSession
from .common import Sources, trace_configs
from .paper import Project
async def generate() -> Sources:
async with ClientSession(
"https://papermc.io",
trace_configs=trace_configs,
) as session:
project = await Project.get(s... |
import os
from typing import Sequence, Callable, Optional
from click import echo, style
from tqdm import tqdm
from riptide_cli.helpers import get_is_verbose, TAB, RiptideCliError
from riptide_plugin_import.files.download_job import FileDownloadJob
from riptide_plugin_import.files.downloader import FileDownloader
cla... |
from flask import Flask, jsonify, request
import pandas as pd
import os
from sklearn.externals import joblib
from sklearn.linear_model import LinearRegression
import numpy as np
import codecs, json
app = Flask(__name__)
@app.route("/predict", methods=['POST'])
def predict():
print("I am hre in predict function"... |
def main():
from emojipasta.emojigene import EmojipastaGenerator
import sys
gen = EmojipastaGenerator.of_default_mappings()
input = sys.stdin.read()
out = gen.generate_emojipasta(input)
print(out, end='') |
from ssockets import client
myclient = client("127.0.0.1", 60010, True)
data = b"Hey, whats up server? it's me, the client talking!"
myclient.send(data)
|
# Copyright (c) 2018 Huawei Technologies Co., Ltd.
# 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
#
# ... |
#!/usr/bin/env python3
from pathlib import Path
from multiprocessing import Queue
from threading import Thread
import depthai as dai
from enum import Enum
import cv2
class EncodingQuality(Enum):
BEST = 1 # Lossless MJPEG
HIGH = 2 # MJPEG Quality=97 (default)
MEDIUM = 3 # MJPEG Quality=93
LOW = 4 # H265... |
from argparse import ArgumentParser
from os import times
import torch
import pytorch_lightning as pl
from torch.nn import functional as F
from project.models.pilotnet import PilotNet
class DrivingModule(pl.LightningModule):
def __init__(self, learning_rate: float, **kwargs):
super().__init__()
s... |
#
# PySNMP MIB module MPIOS-MIB (http://snmplabs.com/pysmi)
# ASN.1 source file:///Users/davwang4/Dev/mibs.snmplabs.com/asn1/MPIOS-MIB
# Produced by pysmi-0.3.4 at Wed May 1 14:14:01 2019
# On host DAVWANG4-M-1475 platform Darwin version 18.5.0 by user davwang4
# Using Python version 3.7.3 (default, Mar 27 2019, 09:23... |
r"""
Interface for extracting data and generating images from Jmol readable files.
JmolData is a no GUI version of Jmol useful for extracting data from files Jmol
reads and for generating image files.
AUTHORS:
- Jonathan Gutow (2012-06-14): complete doctest coverage
- Jonathan Gutow (2012-03-21): initial version
"""... |
from spikeinterface.sorters import CombinatoSorter
import os, getpass
if getpass.getuser() == 'samuel':
combinato_path = '/home/samuel/Documents/SpikeInterface/combinato/'
CombinatoSorter.set_combinato_path(combinato_path)
import unittest
import pytest
from spikeinterface.sorters.tests.common_tests import S... |
# Without the explanatory comments, Mergesort is much shorter:
def mergesort(lst):
if len(lst) <= 1:
return lst
else:
midpoint = len(lst) // 2
left = mergesort(lst[:midpoint])
right = mergesort(lst[midpoint:])
newlist = []
while len(left) > 0 and len(right) > 0... |
import unittest
import numpy as np
from op_test import OpTest
def sigmoid_np(x):
return 1. / (1. + np.exp(-x))
def tanh_np(x):
return 2 * sigmoid_np(2. * x) - 1.
class LstmUnitTest(OpTest):
def setUp(self):
self.op_type = "lstm_unit"
x_np = np.random.normal(size=(5, 16)).astype("float6... |
# minke.config
# Configuration and settings from a YAML file using Confire.
#
# Author: Benjamin Bengfort <bbengfort@districtdatalabs.com>
# Created: Sat Aug 06 21:00:05 2016 -0400
#
# Copyright (C) 2016 District Data Labs
# For license information, see LICENSE.txt
#
# ID: config.py [ad9c2f7] benjamin@bengfort.com $... |
# -*- coding: utf-8 -*-
# 版权所有 2019 深圳米筐科技有限公司(下称“米筐科技”)
#
# 除非遵守当前许可,否则不得使用本软件。
#
# * 非商业用途(非商业用途指个人出于非商业目的使用本软件,或者高校、研究所等非营利机构出于教育、科研等目的使用本软件):
# 遵守 Apache License 2.0(下称“Apache 2.0 许可”),您可以在以下位置获得 Apache 2.0 许可的副本:http://www.apache.org/licenses/LICENSE-2.0。
# 除非法律有要求或以书面形式达成协议,否则本软件分发时需保持当前许可“原样”... |
# -*- coding: utf-8 -*-
"""
Created on Mon Dec 21 17:31:10 2015
@author: rupachak
"""
import NYT
article = NYT.NYArticle("5caa290b6f044865a614b3a22d653997%3A0%3A72414519")
article.setQuery("Obama")
article.articleProcessingPipeline()
for art in article.articleList:
print art.snippet
|
# -*- coding: utf-8 -*-
#
# Copyright 2017 Alan Tindale, 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
#
# ... |
import numpy as np
from pymoo.factory import get_sampling, get_termination
from pymoo.optimize import minimize
from pymoo.problems.single.flowshop_scheduling import create_random_flowshop_problem, visualize
from pymoo.model.callback import Callback
from operators.repair.perm_repair import SequentialPermRepair, Per... |
from flask import Flask, request, flash, url_for, redirect, render_template
from flask_sqlalchemy import SQLAlchemy
app = Flask(__name__)
app.config['SQLALCHEMY_DATABASE_URI'] = 'sqlite:///bars.sqlite3'
app.config['SECRET_KEY'] = "Questlove-Magic"
db = SQLAlchemy(app)
class bars(db.Model):
id = db.Column(db.Integ... |
#!/usr/bin/env python
from flask import Flask, request, jsonify
from flask_cors import CORS
import re
import json
from flasgger import Swagger
from ensembl_prodinf import reporting
from ensembl_prodinf.hive import HiveInstance
from ensembl_prodinf.event_tasks import process_result
from ensembl_prodinf.exceptions impo... |
BASE_PATH = '/home/diam/Desktop/WBC_Test_Images/'
def get_filename_for_index(index):
PREFIX = 'Original_Images/BloodImage_'
num_zeros = 5 - len(index)
path = '0' * num_zeros + index
return PREFIX + path + '.jpg'
reader = csv.reader(open(BASE_PATH + 'labels.csv'))
# skip the header
next(reader)
X = [... |
#!/usr/bin/env python3
import json, math, os, pprint, re, stat, sys, time, traceback
from common import *
ARRAY_NAME = 'io_array'
CUSTOM_INIT_C_CODE = 'custom_init_c_code'
INDENT = ' '
PREFIX_INPUT = 'input_'
PREFIX_INPUT_DATA = PREFIX_INPUT + 'data_'
PREFIX_OUTPUT = 'output_'
PREFIX_EXPE... |
"""
Stress test the server in small scale using one single PC.
Make sure there are n clients connected to the server simultaneously, each client does m QA requests and disconnect.
"""
import socket
import json
import time
import argparse
import numpy as np
from tqdm import tqdm
from multiprocessing import Pool
from fu... |
# coding=utf-8
# *** WARNING: this file was generated by the Pulumi Terraform Bridge (tfgen) Tool. ***
# *** 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... |
import re
with open("2021/day24/input.txt") as file:
data = file.read().splitlines()
pattern_array = []
divided_data = [data[x:x+18] for x in range(0, len(data), 18)]
def find_z_number(x: int, y: int, z: int, pz: int, w: int) -> list(int):
temp_arr = []
i = pz - w - y
if i % 26 == 0:
temp_ar... |
'''
S.T.E.V.E. Messages
Messages and errors
A software component of S.T.E.V.E. (Super Traversing Enigmatic Voice-commanded Engine)
Code and device by Jacob Turner; code released under the MIT license
'''
class messages():
pass
class errors():
class ConfigUni(Exception):
def __str__(self):
r... |
# -*- coding: utf-8 -*-
# vim:fenc=utf-8
'''
:copyright (c) 2014 Xavier Bruhiere.
:license: Apache 2.0, see LICENSE for more details.
'''
import numpy as np
import portfolio.utils
from portfolio.analytics import PortfolioAnalytics
# https://www.quantopian.com/posts/global-minimum-variance-portfolio?c=1
class Gl... |
"""Module for fetching betting data from afl_data service."""
from typing import List, Dict, Any
from datetime import date
import os
import json
from augury.data_import.base_data import fetch_afl_data
from augury.settings import RAW_DATA_DIR, PREDICTION_DATA_START_DATE
FIRST_YEAR_OF_BETTING_DATA = 2010
END_OF_YEAR =... |
from pandas import read_csv, concat, DataFrame
import codecs
from traceback import format_exc
#fpaths = ["/home/panchenko/patternsim/patternsim/output-ukwac/pairs.csv",
# "/home/panchenko/patternsim/patternsim/output-gigaword/pairs.csv",
# "/home/panchenko/patternsim/patternsim/output-wikipedia/pair... |
Subsets and Splits
No community queries yet
The top public SQL queries from the community will appear here once available.