text stringlengths 38 1.54M |
|---|
from ruamel.yaml import YAML
from tensorflow.contrib.training import HParams
import argparse
from hmlstm import HMLSTMNetwork, prepare_inputs
class YamlParams(HParams):
def __init__(self, yaml_fn, config_name):
super().__init__()
with open(yaml_fn) as fp:
for k, v in YAML().load(fp)[co... |
import pytest
from fastapi import HTTPException
from app.beer_params.beer_params_dto import BeerParamInsertionDTO, BeerParamUpdateDTO
from app.beer_params.beer_params_service import get_beer_parameters, get_beer_param_per_name, update_beer_param, add_beer_param, delete_beer_param
class TestBeerParams:
def test_... |
'''
2.3 设计算法
归并排序:引入分治策略,使用递归思想进行算法设计
时间复杂度 O(n) = nlogn
'''
def Merge(L,R):
A = []
print(L,R)
while L and R:
if L[0]>R[0]:
A.append(R.pop(0))
else:
A.append(L.pop(0))
while L:
A.append(L.pop(0))
while R:
A.append(R.pop(0))
return A
def M... |
# The implementation is based on HRNET, available at https://github.com/HRNet/HigherHRNet-Human-Pose-Estimation.
import torch
import torch.nn as nn
BN_MOMENTUM = 0.1
def conv3x3(in_planes, out_planes, stride=1):
"""3x3 convolution with padding"""
return nn.Conv2d(
in_planes,
out_planes,
... |
#!/usr/bin/python3
import json
import atexit
import urllib3
from config import *
from telegram import Update
from datetime import datetime
from dbhandler import DBHandler
from urllib3.util import Timeout
from persiantools.jdatetime import JalaliDate
from telegram.ext import (Updater, CommandHandler,
CallbackContext, ... |
#!/usr/bin/env python
import copy
import time
import concurrent.futures
import pizco
def add_dicts(a, b, modify=False):
if not modify:
a = copy.deepcopy(a)
for k in b:
if isinstance(b[k], dict):
sa = a.get(k, {})
if not isinstance(sa, dict):
sa = {}
... |
#-*- coding:utf-8 -*-
#"2018年1月14日"
from connect.connect import dwsql,wesql,pd,close
import matplotlib.pyplot as plt
from datetime import datetime
import numpy as np
from pandas_pptx import public as p
from pandas_pptx.method_old import bing,xuanf2,autolabel_size,autolabel,bar_h
print('=========================')
p... |
# -*- coding: utf-8 -*-
# Generated by Django 1.11.1 on 2017-06-06 18:46
from __future__ import unicode_literals
from django.db import migrations, models
class Migration(migrations.Migration):
dependencies = [
('account', '0004_auto_20170606_1836'),
]
operations = [
migrations.AlterFiel... |
# -*- coding: utf-8 -*-
import unittest
import os
from api import Config
class TestFileConfiger(unittest.TestCase):
def setUp(self):
os.environ['WX_CONF_PATH'] = os.path.join(os.getcwd(), 'test\\Sample')
self.configer = Config.FileConfig("sample.wxcfg")
def test_get(self):
self.asse... |
# Generated by Django 3.2.6 on 2021-08-21 12:33
import datetime
from django.db import migrations, models
from django.utils.timezone import utc
import ecom.models
class Migration(migrations.Migration):
dependencies = [
('ecom', '0016_alter_user_date'),
]
operations = [
migrations.CreateM... |
#!/usr/bin/env python3
"""
Author : lia
Date : 2020-04-15
Purpose: Homework 10
"""
from Bio import SeqIO
import argparse
import os
import re
import sys
# --------------------------------------------------
def get_args():
"""Get command-line arguments"""
parser = argparse.ArgumentParser(
descriptio... |
class ALGraph:
size = 0
def __init__(self, size):
self.size = size
self.graph = {}
for i in range(self.size):
self.graph[i] = []
def addArc(self, vertex, edge, weight):
# Añade un arco SI existe el vertice
try:
self.graph[vertex].append((edg... |
from project.analysis import *
analysis = Anaylsis()
analysis.sort_by_area_sembrada('bar')
analysis.sort_by_area_sembrada('pie', 8)
|
import pytest
SECURITY_SPEC = [{"OAuth2PasswordBearer": []}]
ITEM_ADD_SPECS = {
"parameters": None,
"responses": {
"200": {
"content": {"application/json": {"schema": {}}},
"description": "Successful Response",
}
},
}
ITEM_SPECS = {
"parameters": [
{
... |
from strategies.bitfloorPctVertex import BitfloorPctVertex
from strategies.constTrade import ConstTrade
from strategies.pctVertex import PctVertex
aliases = {'bitfloor':BitfloorPctVertex,
'mtgox':PctVertex}
class Strategy(object):
def __init__(self, interfaceType, queryManager):
self.alias = aliases[int... |
from pprint import pprint
from itertools import combinations
from src.engine import Player, play
from src.players import *
N_ROUNDS = 300
classes = Player.__subclasses__()
# classes = [Satan, TitForTat]
matches = list(combinations(classes, 2))
scores = { PlayerClass: 0 for PlayerClass in classes }
for match in m... |
# -*- coding: utf-8 -*-
def priskoll(age):
age = int(age) # Omvandlar input str till int
if age in range(18,65): # Returnerar 20 kr i biljettpris då användare är mellan 18-64 år gammal.
return 20
elif age in range(0,131): # Returnerar 15 kr i biljettpris till alla övriga användare. Användaren mås... |
import logging
import time
from bson import Timestamp
from tornado_ws.common_utilities.common.dateutils import time2timestamp
from tornado_ws.common_utilities.mongo.mongo_base import mongo_handler
class OplogWatcher:
def __init__(self, roll_time, ns):
self.roll_time = int(roll_time)
self.ns_filte... |
from selenium import webdriver
import time
import unittest
import HtmlTestRunner
from Pages.logout_account import Logout
from Locator import locators
class SearchField(unittest.TestCase):
driver = None
@classmethod
def setUpClass(cls):
cls.driver = webdriver.Chrome(executable_path="C:/driver/chro... |
from ctypes import memmove, byref, c_uint32, sizeof, cast, c_void_p, create_string_buffer, POINTER, c_char, \
c_long
from pyglet.libs.darwin import cf, CFSTR
from pyglet.libs.darwin.coreaudio import kCFURLPOSIXPathStyle, AudioStreamBasicDescription, ca, ExtAudioFileRef, \
kExtAudioFileProperty_FileDataFormat, ... |
'''We aare importing Django's function url
and all of our views from blog application
'''
from django.conf.urls import url
from . import views
'''we are assigning a view called post_list to ^$ URL
which will match only an empty string ^ nothing $ end
http://127.0.0.1:8000/ is not part of the url in Django
... |
from __future__ import print_function
import httplib2
import os
import os.path
import pprint
import sys
import base64
import slate
import parse
import codecs
from apiclient import discovery
from oauth2client import client
from oauth2client import tools
from oauth2client.file import Storage
# script will fetch all boo... |
from ltk.actions.action import *
from tabulate import tabulate
class ListAction(Action):
def __init__(self, path):
Action.__init__(self, path)
def list_action(self, **kwargs):
if 'id_type' in kwargs and kwargs['id_type']:
id_type = kwargs['id_type']
if id_type == 'workf... |
#coding = utf-8
import unittest
from jbhautotest.UIautotest.Model.Model import Basicmodel
from jbhautotest.UIautotest.Model.Logger import Log
from jbhautotest.UIautotest.Page.loginandquit import Login
from jbhautotest.UIautotest.Data.basicdate import basicconfig
from jbhautotest.UIautotest.Model.path import screen_path... |
class Encoder:
def get_input_dim(self) -> int:
raise NotImplementedError
def get_output_dim(self) -> int:
raise NotImplementedError
|
# Copyright (C) 2018 Google Inc.
# Licensed under http://www.apache.org/licenses/LICENSE-2.0 <see LICENSE file>
"""
Create ProductGroup model
Create Date: 2018-07-04 14:48:12.131950
"""
# disable Invalid constant name pylint warning for mandatory Alembic variables.
# pylint: disable=invalid-name
import sqlalchemy as... |
import pandas as pd
import numpy as np
def create_interval_dataset(dataset, look_back):
dataX, dataY = [], []
for i in range(len(dataset) - look_back):
dataX.append(dataset[i:i+look_back])
dataY.append(dataset[i+look_back])
return np.asarray(dataX), np.asarray(dataY)
df = pd.read_csv('./... |
"""
This handles the relations of equipment types and character careers.
"""
class EquipTypeHandler(object):
"""
The model maintains a dict of equip_type to careers.
"""
def __init__(self):
"""
Initialize handler
"""
self.clear()
def clear(self):
"""
... |
# -*- coding: utf-8 -*-
from multiprocessing import Process
from zmq.eventloop.ioloop import IOLoop
from program_top.utilities.environment_and_platform import get_current_environment_pack
def main(start_script_file,running_class_def=None):
'''主函数,传入开始执行的主函数,然后以指定的类作为起始工作实例,为单实例机器的程序入口'''
current_environment_pack=ge... |
# -*- coding: utf-8 -*-
from b3j0f.conf import Configurable, category, Parameter
from inspect import getmembers, isroutine
from link.middleware.core import Middleware
from link.feature import Feature
from link.model import CONF_BASE_PATH
@Configurable(
paths='{0}/base.conf'.format(CONF_BASE_PATH),
conf=cat... |
import math
def main():
irr_year=eval(input("请输入收益率:"))
irr_month=pow((1+irr_year/100.0),1/12)-1
a=[]
with open(r"C:\Users\DXHQXX\Documents\GitHub\Python\日常使用\现金流.txt") as f:
lines=f.readlines()
for line in lines:
a.append(-int(line))
n=len(a)
sum=0
f... |
'''
Created on Jan 19, 2012
This module implements Quick Books server mode
@author: Mark V Systems Limited
(c) Copyright 2012 Mark V Systems Limited, All rights reserved.
'''
from lxml import etree
import uuid, io, datetime
from arelle import XmlUtil
clientVersion = None
userName = None
sessions = {} # use when int... |
n = int(input("n = "))
FibonacciArray = [0,1]
def findFibonacciNumber(n):
if n < 0:
print("Incorrect input")
elif n == 1:
return FibonacciArray[0]
elif n == 2:
return FibonacciArray[1]
else:
fibNumber = findFibonacciNumber(n-1)+findFibonacciNumber(n-2)
Fibonacc... |
##############################################################################
# File for running Brunel on MC data with default MC09 settings,
# and saving all MC Truth
#
# Syntax is:
# gaudirun.py Brunel/MC09-WithTruth.py Conditions/<someTag>.py <someDataFiles>.py
#####################################################... |
from django.contrib import admin
from .models import Cart
class CartAdmin(admin.ModelAdmin):
list_display = ('user', 'product', 'quantity', 'status')
search_fields = ('user', 'product', 'status')
list_per_page = 20
admin.site.register(Cart, CartAdmin)
|
from xmppEngine import *
from plugLoder import PlugIns
from amiConfig import Config
from AmiTree import Container
from WebEngine import *
class EventEngine:
def __init__(self, absPath):
EventEngine.configFile = 'server.properties'
EventEngine.root = Container("root", "root", "this is the root no... |
# routines for assessing RVs from pipeline
import os
import copy
import glob
import pdb
import numpy as np
import matplotlib.pyplot as plt
import esutil
from astropy.io import fits
from apogee.utils import apload
from apogee.utils import applot
from apogee.utils import bitmask
from apogee.utils import spectra
from apo... |
import unittest
from datetime import datetime
import walkoff.appgateway
import walkoff.case.database as case_database
import walkoff.config.config
import walkoff.config.config
import walkoff.controller
from walkoff.case import subscription
from walkoff.core.multiprocessedexecutor.multiprocessedexecutor import Multipro... |
# _*_ coding:utf-8 _*_
# 图片验证码redis有效期,单位秒
IMAGE_CODE_REDIS_EXPIRES = 5 * 60
# 短信验证码有效期
SMS_CODE_REDIS_EXPIRES = 5 * 60
# 发送间隔
SEND_SMS_CODE_INTERVAL = 60
# 短信模板
SMS_CODE_TEMP_ID = 1
|
# coding: utf-8
# In[1]:
get_ipython().magic(u'matplotlib inline')
import numpy as np
import matplotlib.pyplot as plt
from matplotlib import style
# In[2]:
style.use('seaborn-poster')
style.available
# In[3]:
### Build a list to restore the DOS#ID
dos=[]
selected=[2,4] #To choose the DOS#ID
for i in selected... |
# Copyright 2014-present PlatformIO <contact@platformio.org>
#
# 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 applicabl... |
"""
Temporary for use during early development, creates an asset
in the test database
TODO: DELETE ME
"""
from authentication.models import User
from .models import Asset
try:
user = User.objects.get_by_natural_key(User.Type.BASIC, 'test_user')
except User.DoesNotExist:
raise EnvironmentError('Need to create... |
from django.shortcuts import render, redirect
from django.views.decorators.csrf import csrf_exempt
from django.core.files import File
from django.contrib.auth.models import User, auth
from django.http import HttpResponse
from .models import Notice
from .models import Student
from .models import UImage
from django.cor... |
from FeatureVectorBuilder import FeatureVector
from ModelBuilder import ModelBuilder
fv = FeatureVector()
# reading our labeled training data from text file
trainX, trainY = fv.readData('data/train.txt')
# now we build and test our model
mb = ModelBuilder()
mb.svm(trainX, trainY) |
import PySimpleGUI as sg
translit_table = {
'A':'А',
'B':'Б',
'V':'В',
'G':'Г',
'D':'Д',
'E':'Е',
'ЫO':'Ё',
'ЗH':'Ж',
'Z':'З',
'I':'И',
'J':'Й',
'K':'К',
'L':'Л',
'M':'М',
'N':'Н',
'O':'О',
'P':'П',
'R':'Р',
'S':'С',
'T':'Т',
'U':'У',
... |
# -*- coding: utf-8 -*-
"""
Created on Tue Mar 5 12:45:01 2019
@author: Pierre
"""
"""
Pierre : Transmission des données de sorties
Val : lecture BDD - envoie d'une fonction prenant le BrokerName et qui renvoie la ligne des frais du broker (on se débrouille ensuite)
Mithu : IA
"""
### Path.
import os
#BDD
#os.chdi... |
from fractions import Fraction
# NOTE: Work for equations done by hand in a notebook. If you want to see the work, please e-mail me
def fraction_array_decorator(function):
""" function must output a Fraction object"""
def wrapper(gear_list):
return fraction_to_array(function(gear_list))
return w... |
from django.test import SimpleTestCase,TestCase,Client
from django.urls import reverse, resolve
from .views import uplode_csv,bank_statement_without_category_page,bank_statement_update_page,bank_statement_page,bank_allStatement_page
from .models import *
class TestUrls(SimpleTestCase):
def test_home_url_is_resolved(... |
from poium import Element
from .menu_page import MenuPage
class ResListPage(MenuPage):
res_name_search_input = Element(xpath='//input[@placeholder="请输入资源名"]', describe='资源名搜索框')
res_type_search_select = Element(xpath='//input[@placeholder="请选择"]', describe='资源类型搜索下拉框')
res_type_search_rds_menu = Element(x... |
### Algoritmo SomaAteValorIgualA0
### Estrutura Repita-Ate
## Variáveis
soma = 0
while True:
valorDigitado = int(input('Digite um valor para a soma: '))
soma = soma + valorDigitado
print('Total: ', soma)
if valorDigitado <= 0:
break
print('Resultado: ', soma)
... |
import random
class Tile:
def __init__ (self, has_ship=False, is_revealed=False):
self.has_ship = has_ship
self.is_revealed = is_revealed
def enemy_vision (self):
if not self.is_revealed:
return '-'
elif self.has_ship:
return 'o'
else:
return 'x'
def player_vision (self):
if self.has_ship:
... |
# Todo, create a benchmark with already present Librarian Methods copied over to see performance and compare
# (todo point 3) NOT WORKING YET BUT WILL BE CONTINUE TO PROGRESS ON THIS
DISPLAY = False
import copy
import json
import time
from random import random, randint
import os
import matplotlib.pyplo... |
# -*- coding: utf-8 -*-
# 获取字符串中匹配子串的最后一个位置
def find_last(string, str):
last_position = -1
while True:
position = string.find(str, last_position+1)
if position == -1:
return last_position
last_position = position
# 将文件名改写成小文件名
def thumbFilePath(filepath):
... |
import os, sys
import time
import threading
import logging
file_loc = os.path.abspath(__file__)
BASE_DIR = os.path.dirname(os.path.dirname(os.path.dirname(os.path.dirname(file_loc))))
resources_path = os.path.abspath(os.path.join(BASE_DIR, 'resources'))
sys.path.append(resources_path)
import constants
sys.path.appen... |
BASE_ROUTE = "youtube"
def register_routes(api, app, root="api"):
from .search.controller import api as Video_api
api.add_namespace(Video_api, path=f"/{root}/{BASE_ROUTE}/video") |
import pandas as pd
from MeanEncoder import MeanEncoder
data = pd.read_csv("D:/BaiduNetdiskDownload/Music Recommendation/Data/train.csv/train.csv", usecols=["song_id", "target"])
data = data.head(1000)
encoder = MeanEncoder(['song_id'])
data = encoder.fit_transform(data, data["target"])
print(data)
|
from termcolor import colored
import os
import random
b = 'blue'
w = 'white'
g = 'green'
y = 'yellow'
r = 'red'
o = 'magenta'
configcubestart = []
front = [[b, b, b,], # front
[b, b, b,],
[b, b, b,]]
back = [[g, g, g,], # back
[g, g, g,],
[g, g, g,]]
top = [[y, y, y... |
file_name=input("Enter file name: ")
file=open(file_name,"a")
text=input("Enter text to append text in the file: ")
file.write(text)
file.close()
f1=open(file_name)
print(f1.read())
f1.close()
|
from django.shortcuts import render, redirect
from django.core.files.storage import FileSystemStorage
from django.http import HttpResponse
from django.conf import settings
from django.template.loader import get_template
from libs___.connect_DB import cursor as CONNECT
from libs___.cipher import cipher
from sql_queries... |
"""Array with positions
"""
from typing import Any
# Third party imports
import numpy as np
# Where imports
from where.data import _direction
from where.data._direction import DirectionArray
from where.lib import transformation as trans
def Direction(val=None, ra=None, dec=None, system=None, **dir_args) -> "Direct... |
from flask import render_template, request
from os import environ
import random
import math
import json
import sqlite3 as sql
from flask import Flask, url_for
from osgeo import gdal
import datetime
import numpy as np
app = Flask(__name__)
'''
run server
# from os import environ
# from webgis import app
# if __name__... |
import logging
import os
import redis
from flask import Flask, render_template, request, url_for
import sqlite3 as sql
import hashlib
import pandas as pd
import time
import json
app = Flask(__name__)
#This function is used to load the csv file into the database
@app.route('/ctb', methods=['GET','POST'])
def ctb():
... |
import dynet as dy
from constree import *
from lexicons import *
from proc_monitors import *
from rnng_params import *
from char_rnn import *
from math import exp
from numpy.random import rand
class RNNLM:
START_TOKEN = '<start>'
UNKNOWN_TOKEN = '<unk>'
def __i... |
#!/usr/bin/env python
# -*- coding: utf-8 -*-
# Author : xiongli
import getpass ###输入密码时不在屏幕上显示
INPUT ={}
# ##检查帐号是否加锁
def CheckLock(username):
with open('lock.txt', 'r') as lock: ##读加锁帐号文件信息
for i in lock: ##循环读出的加锁信息
if i.split() == us... |
from __future__ import annotations
try:
from jinja2 import pass_context as contextfilter # type: ignore
except ImportError:
from jinja2 import contextfilter # type: ignore
from mkdocs.utils import normalize_url
@contextfilter
def url_filter(context, value: str) -> str:
"""A Template filter to normaliz... |
import torch
import torch.nn as nn
import torch.nn.functional as F
from torch.autograd import Variable
import numpy as np
class yoloLoss(nn.Module):
def __init__(self, S, B, l_coord, l_noobj):
super(yoloLoss, self).__init__()
self.S = S
self.B = B
self.l_coord = l_coord
sel... |
# -*- coding: utf-8 -*-
from __future__ import unicode_literals
from django.db import migrations, models
class Migration(migrations.Migration):
dependencies = [
]
operations = [
migrations.CreateModel(
name='Colleague',
fields=[
('id', models.AutoField(ve... |
""" Module for creating a GUI window.
Templates for the GUI window can be configured using Qt Designer and should be stored as .ui files in the
./gui_templates directory.
The GUI is designed to hold a number of user (external script) assigned widget attributes (plots, scalars, labels),
and continuously refresh output... |
#!/usr/bin/env python3
from conans import ConanFile
from conans.model.version import Version
class KatanaConan(ConanFile):
settings = ("os", "compiler", "build_type", "arch")
# Several packages are installed via APT:
# - arrow
# - llvm
requires = (
"backward-cpp/1.5",
"benchmar... |
from scipy.ndimage.filters import gaussian_filter1d
from enum import Enum
import numpy as np
import matplotlib.pyplot as plt
import cv2
import datetime
# BreathingDiagram is a program to get the "breathing curve" visible.
# The main input is a "Disparity Map" where you can see the disparity of an image based on the br... |
import numpy as np
import cv2
import time
import paho.mqtt.client as mqtt
try:
from urllib.parse import urlparse
except ImportError:
from urlparse import urlparse
from urllib2 import urlopen
import httplib
import sys
mosquitto_mqtt_broker_ip = 'localhost'
mosquitto_mqtt_broker_port = '1883'
mosquitto_mqtt_broker_u... |
#program to calculate average height
student_heights=input("input a list of student heights in centimeter\n").split()
n=0
total_height=0
for height in student_heights:
height=int(student_heights[n])
total_height+=height
n+=1
print(f"Sum of height of students is {total_height} .")
print(f"Total number of stu... |
from math import hypot
o = float(input('Digite o valor do cateto oposto: '))
a = float(input('Digite o valor do cateto adjacente: '))
hip = hypot(o, a)
# (o ** 2 + a ** 2) ** (1/2) ... outra opção para fazer esse calculo...
print('cateto oposto {} / cateto adjacente {} / valor da hipotenusa {:.2f}'.format(o, a, hip)... |
import numpy as np
import torch
from .utils import box_utils
class MatchPrior(object):
def __init__(self, center_form_priors,
center_variance, size_variance, iou_threshold):
self.center_form_priors = center_form_priors
self.corner_form_priors = box_utils.center_form_to_corner_form(
center_form... |
# -*- coding: utf-8 -*-
"""
Created on Tue Jan 26 10:17:57 2021
@author: 92332
"""
import random as RD
class Node:
def __init__(self, value):
# p = Priority
# If you want to insert nodes more than 10000, you have to increase the limit below of randrange.
self.p = int(RD.randrange(10000))
... |
import unittest
from set_height_in import set_height_in
class testSetHeightIn(unittest.TestCase):
def test_set_height_in_0(self):
#0 is a valid number of inches so test to see if it returns true
actual = set_height_in(0)
expected = True
self.assertEqual(actual, expected)
... |
# -*- coding: utf-8 -*-
from __future__ import unicode_literals
from django.db import models, migrations
import datetime
class Migration(migrations.Migration):
dependencies = [
]
operations = [
migrations.CreateModel(
name='Banner',
fields=[
('id', models... |
import math
import numpy
import matplotlib.pyplot
moon_distance = 384e6
def orbit():
num_steps = 50
x = numpy.zeros([num_steps+1,2])
for i in range(num_steps+1):
angle = 2.*math.pi*i/num_steps
x[i,0] = moon_distance*math.sin(angle)
x[i,1] = moon_distance*math.cos(angle)
return ... |
"""Faça um Programa que leia três números e mostre o maior deles.
"""
num_1 = float(input('Entre com o primeiro numero: '))
num_2 = float(input('Entre com o segundo numero: '))
num_3 = float(input('Entre com o terceiro numero: '))
if num_1 > num_2 and num_1 > num_3:
print('O primeiro numero é o maior', num_1)
eli... |
class Coronapopulation:
def __initi__(self, state, city, population, result, countofcorona):
self.state = state
self.city = city
self.population = population
self.result = result
self.countofcorona = countofcorona
def coronaresult(self):
count = 0
if sel... |
from functools import reduce
import math
from operator import mul
def find_numbers():
for a in range(1, 1000):
for b in range(a, 1000):
if a + b > 680:
break
else:
c = math.sqrt(a ** 2 + b ** 2)
if sum((a, b, c)) == 1000:
... |
import matplotlib.pyplot as plt
import numpy as np
from uncertainties import ufloat
import uncertainties.unumpy as unp
p = np.array([5.5, 7, 8.2 , 9.5, 10.5, 11.5, 12.2])
T = np.array([17.5, 27.0, 35.0, 40.0, 44.0, 47.0, 50.0])
T_err = np.array([0.1, 0.1, 0.1, 0.1, 0.1, 0.1, 0.1])
p_err = np.array([0.1, 0.1, 0.1, 0.1... |
import json
import datetime
import pytz
from dateutil.tz import tzlocal
import dateutil
import sys
sys.path.append('../../python')
import inject
inject.configure()
import logging
from model.registry import Registry
from model.connection.connection import Connection
from model.assistance.assistance import Assistance... |
class Solution:
def maxArea(self, height: List[int]) -> int:
currRightIndex = len(height) - 1
currLeftIndex = 0
maxArea = 0
while(currLeftIndex < currRightIndex):
currentHeight = min(height[currRightIndex], height[currLeftIndex])
currentWidth = currRightIndex... |
import redis
import json
import sqlalchemy
from sqlalchemy.orm import sessionmaker
from sqlalchemy.orm import scoped_session
from webapp.lib import model
REDIS = None
def set_redis(host, port, dbname):
""" Set the redis connection with the specified information. """
global REDIS
pool = redis.ConnectionPo... |
class Solution:
# @param triangle, a list of lists of integers
# @return an integer
def minimumTotal(self, triangle):
for i in reversed(range(len(triangle) - 1)):
for j in range(0, i + 1):
triangle[i][j] += min(triangle[i + 1][j], triangle[i + 1][j + 1])
return tr... |
#!/usr/bin/env python
# coding: utf-8
# In[82]:
#Importacion librerias
import numpy as np
import matplotlib.pyplot as plt
from scipy import fftpack
from scipy.signal import convolve2d
from matplotlib.colors import LogNorm
# In[83]:
#Importacion imagen
imagen = plt.imread("arbol.png").astype(float)
#Transformada ... |
#!/usr/bin/env python3
# -*- coding: utf-8 -*-
"""
Created on Sun Apr 7 16:41:32 2019
@author: gavin
"""
import test
|
lampu = [
{"lampu": 1, "value":""},
{"lampu": 2, "value":""},
{"lampu": 3, "value":""},
{"lampu": 4, "value":""},
]
nyalahijau = 3
for i in range(0, len(lampu)):
if lampu[i]["lampu"]==nyalahijau:
lampu[i]["value"]="hijau"
else:
lampu[i]["value"] = "merah"
print(lampu)
|
import msgpack
try:
import ujson as json
except ImportError:
import json
class JSONSerializer:
@staticmethod
def pack(data):
return json.dumps(data).encode()
@staticmethod
def unpack(data):
decoded = data.decode() if isinstance(data, bytes) else data
return json.loads... |
import numpy as np
from microcircuit import Circuit
metadata = {'name' : 'testcircuit001'}
vert = np.array([10, 11, 200, 20, 21, 22], dtype=np.uint32)
conn = np.array([[10, 11], # axonal
[11, 200], # presyn
[200, 20], # postsyn
[20, 21], # dendritic
... |
import sys
from gurobipy import *
model = read(sys.argv[1]+".lp")
model.setParam('TimeLimit', 200*60)
model.optimize()
#model.computeIIS()
#model.write(sys.argv[1] + ".ilp")
model.write(sys.argv[1] + ".sol")
|
import os
# 项目url
HOST = "http://user-p2p-test.itheima.net"
# 跟目录路径
dir_path = os.path.dirname(__file__)
# 请求头
HEADERS = {"Content-Type": "application/json"}
|
#!/usr/bin/python
myFile = open('store.txt', 'r')
data = myFile.readlines()
data = list(set(data))
data = [data[i].replace('\n', '') for i in range(0, len(data))]
dataset = list(set(data))
result = []
for i in range(0, len(dataset)):
print dataset[i], data.count(dataset[i])
|
import kivy
from kivy.app import App
from kivy.animation import Animation
from kivy.uix.widget import Widget
from kivy.core.window import Window
from kivy.uix.popup import Popup
from kivy.uix.gridlayout import GridLayout
from kivy.uix.boxlayout import BoxLayout
from kivy.uix.label import Label
from kivy.uix.ch... |
#===============================================================================
# 26999: Verify the user can cancel the "Create new contact"
# operation from the Contacts APP returning to the SMS thread view
#
# Procedure:
# 1. Send from another device to Device under test an SMS including
# text and a number with 9 ... |
# -*- coding: utf-8 -*-
"""Simple snippet of bokeh real-time streaming using IEX API with TOPS.
Exploring techniques of using bokeh server for real-time streaming of data,
specifically, real-time data streaming of stock prices from a provider, IEX.
Demonstrating the use of bokeh server, capture of streaming data, date... |
import datetime
start = datetime.datetime.now()
print "x|y"
print "==="
xs = range(1, 1000001)
for x in xs:
y = x * x + 3
table = "{}|{}".format(x, y)
print table
time_taken = datetime.datetime.now() - start
print("calculated results in:{}".format( time_taken))
|
# SERVER
from flask import Flask
from src.erc20 import Connection
from src.system import System
app = Flask(__name__)
f = open("secretkey", "r")
secretkey = f.read().rstrip()
f.close()
app.secret_key = secretkey
f = open("infuraapi", "r")
apikey = f.read().rstrip()
f.close()
infura_url = "https://mainnet.infura.io/{... |
import numpy as np
import matplotlib.pyplot as plt
import matplotlib.image as mpimg
import glob
import cv2
# used in Jupyter notebook from video
# %matplotlib inline
# %matplotlib qt
"""
You're getting very close to a final result!
You have a thresholded image, where
you've estimated which pixels belong to the left ... |
Subsets and Splits
No community queries yet
The top public SQL queries from the community will appear here once available.