text stringlengths 38 1.54M |
|---|
mesStr = input("Ingrese un mes del año. 1 - 12:")
try:
mes = int(mesStr)
estacion = None
if mes == 1 or mes == 2 or mes == 12:
estacion = 'Invierno'
elif mes == 3 or mes == 4 or mes == 5:
estacion = 'Primavera'
elif mes == 6 or mes == 7 or mes == 8:
estacion = 'Verano'
... |
"""Html HIW extension for Markdown.
Deals with:
![[image.jpg|300]] - like obsidian, sets size -- https://help.obsidian.md/How+to/Embed+files
one setting is width?
two seetings is hightxwidth
px defailt
deal with percents?
[[ns:page]]
Based and exapnded on the wikikinks extention
"""
'''
WikiLin... |
# -*- coding: utf-8 -*-
"""Test the basic training of super resolution GAN"""
import os
# import json
import numpy as np
import pytest
import tempfile
import tensorflow as tf
from tensorflow.python.framework.errors_impl import InvalidArgumentError
from rex import init_logger
from sup3r import TEST_DATA_DIR
from sup3r... |
from flask_sqlalchemy import SQLAlchemy
from flask_login import LoginManager
from flask import Flask
app = Flask(__name__)
app.config.from_object('config')
app.config.from_object('secrets')
db = SQLAlchemy(app)
lm = LoginManager(app)
lm.login_view = 'index'
from app import views, models |
import random
roll_again = "r"
while roll_again == "r":
# Gnenerates a random number
# between 1 and 6 (including
# both 1 and 6)
number = random.randint(1,6)
if number == 1:
print(" | |")
print(" | 0 |")
print(" | |")
if num... |
from abc import ABCMeta, abstractmethod
import numpy as np
class Agent(metaclass=ABCMeta):
"""Abstract Agent class"""
@abstractmethod
def _model_init(self):
"""
Initializes parameters used by the model based on predefined settings
"""
raise NotImplementedError
@abstra... |
"""Reader for JSON-files
"""
# Standard library imports
import json
from typing import Any, Dict
# Third party imports
import pyplugs
@pyplugs.register
def from_json(string: str, **json_args: Any) -> Dict[str, Any]:
"""Use json standard library to read JSON"""
return json.loads(string, **json_args)
|
import datetime
import json
from leapp.exceptions import MissingActorAttributeError, WrongAttributeTypeError
from leapp.utils.meta import get_flattened_subclasses
from leapp.models import Model
class Actor(object):
def __init__(self, channels=None):
self._channels = channels
def produce(self, *args)... |
import functools
import json
import base64
from aiohttp.web import Response
from .spider import info_login, info_cookie_login
def require_info_login(f):
@functools.wraps(f)
async def decorated_function(request, *args, **kwargs):
authorized = False
headers = request.headers # .keys()
req... |
#! /usr/bin/env python
#
# parser.py ---
#
# Filename: parser.py
# Description:
# Author: Werther Zhang
# Maintainer:
# Created: Tue May 16 11:04:29 2017 (+0800)
#
# Change Log:
#
#
import matplotlib.pyplot as plt
import numpy as np
import time
import dateutil
import sys
import os
class DiskIOEntry:
"""Disk IO E... |
# -*- coding: utf-8 -*-
from tqdm import tqdm
from datetime import datetime
import xml.etree.ElementTree as et
import sqlite3
import conf
import sql
import logging
logging.basicConfig(level=conf.LOG_LEVEL, format=conf.LOG_FORMAT)
''' Functions '''
def format_date(date_str):
return datetime.strftime(datetime.strpt... |
from collections import defaultdict
class Solution:
def findOrder(self, numCourses, prerequisites):
adj_list = defaultdict(list)#方式无key出现keyError错误
indegree = {}
for dest, src in prerequisites:
adj_list[src].append(dest)
indegree[dest] = indegree.get(dest, 0) + 1 #... |
#!/usr/bin/env python
# -*- coding: UTF-8 -*-
##########################################################################
# > File Name: 83_remove_duplicates_from_sorted_list.py
# > Author: Tingjian Lau
# > Mail: tjliu@mail.ustc.edu.cn
# > Created Time: 2016/05/16
#######################################################... |
"""rbacdemo URL Configuration
The `urlpatterns` list routes URLs to views. For more information please see:
https://docs.djangoproject.com/en/2.2/topics/http/urls/
Examples:
Function views
1. Add an import: from my_app import views
2. Add a URL to urlpatterns: path('', views.home, name='home')
Cl... |
class ServerConfig:
def __init__(self, localhost, port):
self.localhost = localhost
self.port = port |
import sys
dataset = sys.stdin.read()
lst = list(map(int, dataset.split()))
n = lst[0]
lst = lst[1:]
ans = [0] * (n + 1)
ans[0] = 1
for i in range(n):
for j in range(i + 1, 0, -1):
ans[j] -= ans[j - 1] * lst[i]
if n % 2 == 0:
ans = [-x for x in ans]
print(' '.join(str(x) for x in ans... |
import time
import tensorflow as tf
from direct_keys import PressKey, ReleaseKey, W, A, S, D
from model import Model
from x1_collect_data import fps_stuff2
simulate = True
model: Model = None
last_print_time = time.time()
def on_click(x, y, button, pressed):
global simulate
if pressed:
print('Mouse... |
# -*- coding: utf-8 -*-
# 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, software
#... |
# https://www.codechef.com/problems/TEST
number = input()
li = []
while number != 42:
li.append(number)
number = input()
else:
for num in li:
print num
|
# Data Preprocessing Template
# Importing the libraries ##Always add this
import numpy as np
import matplotlib.pyplot as plt
import pandas as pd
# Importing the dataset
dataset = pd.read_csv('Data.csv')
X = dataset.iloc[:, :-1].values #takes all the rows, takes all columns but the last one.
y = dataset.iloc[:, 3].va... |
from aws_ec2_provisioner.conf import LOGGING_STR_SIZE
from aws_ec2_provisioner.errors import RequestToAWSError
def validate_response_http_code(response):
status_code = response.get('ResponseMetadata', {}).get('HTTPStatusCode')
if status_code != 200:
raise RequestToAWSError
# TODO: rename!
class Bcol... |
from clearblade.ClearBladeCore import System, Query, Developer
import psutil
import platform
import time
from datetime import datetime
#grabing system information of my own laptop
def get_size(bytes, suffix="B"):
"""
Scale bytes to its proper format
e.g:
1253656 => '1.20MB'
1253656678 => '1... |
import pandas as pd
import keras
from keras.models import Sequential
from keras.layers import Dense, Dropout, Activation, Flatten
from keras.layers import Conv2D, MaxPooling2D
from sklearn.metrics import roc_curve, auc
from keras.optimizers import SGD
from keras.callbacks import EarlyStopping,ModelCheckpoint
import os,... |
from dataclasses import dataclass, field
from project_management.entities.task import Task
@dataclass
class MondaydotcomGroup(Task):
board_id: str = None
name: str = None
board_kind: str = None
template_ids: str = None |
"""
This is a sample script that can be passed to grab-site --custom-hooks=. It
1) drops http:// URLs before they can be queued
2) aborts responses that have a Content-Type: that starts with 'audio/'
3) queues additional URLs on Twitter to get original-quality images
For self-help on writing hooks, `git clone https://... |
#!/usr/bin/env python
# This work was created by participants in the DataONE project, and is
# jointly copyrighted by participating institutions in DataONE. For
# more information on DataONE, see our web site at http://dataone.org.
#
# Copyright 2009-2019 DataONE
#
# Licensed under the Apache License, Version 2.0 (t... |
from dataclasses import dataclass, field
from time import sleep, time
from typing import List, Tuple
from selenium import webdriver
from selenium.common.exceptions import TimeoutException, NoSuchElementException, ElementClickInterceptedException
from selenium.webdriver import ActionChains
from selenium.webdriver.commo... |
#!/usr/bin/env python
#stdlib imports
from copy import deepcopy
import argparse
import os.path
from datetime import datetime
#third party imports
import matplotlib.pyplot as plt
import numpy as np
from mpl_toolkits.mplot3d import Axes3D
from shakemap.grind.fault import Fault
from openquake.hazardlib.geo import point
... |
#!/usr/bin/env python
'''
Created on 19.12.2012
@author: hamood
'''
import pika
import time
from string import Template
import sys
import os
import stat
import shutil
import simplejson as json
import logging
import logging.handlers
message_broker_ip="10.0.0.140"
locations_dir="/usr/local/nginx/locations/"
www_dir="/... |
data = []
f = open("final.txt", "r")
for line in f.readlines():
data.append(int(line[11:14])) #Number stars with the 11. columns and ends with 14.
data.sort()
print data
print [data[x:x+3] for x in xrange(0, len(data), 3)]
|
import os
import numpy as np
from PIL import Image
DATA_DIR = os.path.join(os.path.dirname(__file__), "../../data/")
def image_path_to_numpy(path):
img = Image.open(DATA_DIR + "earthrise.jpg")
array = np.array(img)
return array
def earthrise():
"""
https://spaceflight.nasa.gov/gallery/images/ap... |
from __future__ import annotations
from dataprocessors.DataProcessorWithVisitor import DataProcessorWithVisitor
from modelgenerators.RectangularDenseModelGenerator import RectangularDenseModelGenerator
from datacategoryvisitors.CategorizedDataVisitor import CategorizedDataVisitor
from endtoendfactories.EndToEndFactoryB... |
total=0
for i in l:
if type(i) == int:
total=total+i
elif type(i) == float:
total=total+i
else:
continue |
import requests
import json
import sys
class SourceController:
def __init__(self, sourcefile, key='785390bcf5cd458d8dd187081b5bb1db'):
self.sourcefile = sourcefile
self.sources = {}
self.key = key
def get_sourcefile(self):
return self.sourcefile
def get_sources(self):
return self.sources
def load_s... |
class App_list:
def __init__(self):
self.app = {}
def add_app(self, name, genre):
self.app[name] = genre
def get_apps_by_genre(self, gerne):
genre_list = []
for i in self.app:
if self.app[i] == gerne:
genre_list.append(i)
genre_list.sort... |
# -*- coding: utf-8 -*-
import sys
import cv2
import dlib
import os
import numpy as np
class face_align(object):
def __init__(self, img_path=None):
pwd = os.getcwd()# 获取当前路径
model_path = os.path.join(pwd, 'model')
# self.shape_predictor_5_path = os.path.join(model_path, 'shape_predictor_5_... |
from picamera import PiCamera
from time import sleep
camera = PiCamera()
imageNumber = 0
def captureImage():
global imageNumber
camera.start_preview()
sleep(2)
camera.capture("/home/pi/Desktop/Github/raspberry-pi/image%s.jpg" % imageNumber)
camera.stop_preview()
imageNumber += 1
captureImage(... |
def something():
print("something")
print("something else")
print("something other")
if True:
for n in range(1, 10):
print(n)
something()
|
# New Jersey Property Tax Files
# https://www.state.nj.us/treasury/taxation/lpt/TaxListSearchPublicWebpage.shtml
#
import os
import pandas as pd
import fuzzy
import geocoder as gcode
from datetime import datetime
SCRIPT_PATH = os.path.dirname(os.path.realpath(__file__))
def get_latlang(street, town, postal_zip):
... |
import json
import csv
import sys
inputFile=sys.argv[1]
outputFile=sys.argv[2]
inputFile=open(inputFile,"r")
outputFile=open(outputFile,'w', newline='')
data=json.load(inputFile)
dataresult=data["result"]
inputFile.close()
output=csv.writer(outputFile)
dataKey=dataresult["BCHEUR"]
dataasks=dataKey["asks"]
databids=... |
import pygame, sys
import random
from gameObjects import *
pygame.init()
#pygame.mixer.Sound("../audio/sound.mp3")
#sound.play()
clock = pygame.time.Clock()
screen = pygame.display.set_mode((800, 600))
gameObjs = []
background = Background("images/Nebula1.bmp",
screen.get_width(), screen.get... |
import sys
def tripleRecursion(n, m, k):
# Complete this function
a = [[0]*n for _ in range(n)]
for i in range(n):
for j in range(n):
if i==0 and j==0:
a[i][j]=m
elif i==j:
a[i][j]=a[i-1][j-1]+k
elif i>j:
a[i][j]=a[... |
import hashlib
key = "iwrupvqb"
#Create an MD5 hasher
hasher = hashlib.md5()
#Add the key to the hasher
hasher.update(key)
result = ""
i = 0
while result[0:6] != "000000":
#Copy the hasher so that we can add the index to the end without making a new hasher
h = hasher.copy()
h.update(str(i))
#Get the... |
import asyncio
from timeit import default_timer
from aiohttp import ClientSession
import time
import numpy as np
from bs4 import BeautifulSoup
import pandas as pd
dictionary_of_urls = []
headers = {
'authority': 'www.zillow.com',
'method': 'GET',
'scheme': 'https',
'accept': 'application/json, te... |
class Solution(object):
def islandPerimeter(self, grid):
"""
:type grid: List[List[int]]
:rtype: int
"""
ans = 0
h = len(grid)
w = len(grid[0])
if h == 0 or w == 0:
return ans
for i in range(h):
for j in range(w... |
import os,sys,inspect
currentdir = os.path.dirname(os.path.abspath(inspect.getfile(inspect.currentframe())))
parentdir = os.path.dirname(currentdir)
sys.path.insert(0,parentdir)
from simulator import *
#goal = (3,3,0,'red')
class Node:
def __init__(self, state, f=0, g=0 ,h=0):
self.state = state
... |
from multiprocessing import Process,Lock
import time
def f(l,i):
l.acquire()
time.sleep(1)
print('Hello world %s' %i)
l.release()
if __name__ == '__main__':
lock = Lock()
for num in range(10):
Process(target=f,args=(lock,num)).start() |
#!python3
import ui
import appex
import urllib
from imdb import imdb
from imdb import SourceSite
from objc_util import nsurl,UIApplication
import re
'''appex.get_text()
u'The Strain: Noite Absoluta - The Worm Turns [S04E01]'
>>> appex.get_url()
u'http://ishowsapp.com/share/episode/5966172
shate da legenda do filme ... |
from .models import User, Article, Claim, Source
from .serializers import UserSerializer, ArticleSerializer, ClaimSerializer, SourceSerializer
from .process_article import get_all_claims
from rest_framework import viewsets
from rest_framework.decorators import detail_route, list_route
from rest_framework.response impor... |
from copy import deepcopy
from utensor_cgen.transformer import (GENERIC_SENTINEL, Transformer,
TransformerPipeline)
@TransformerPipeline.register_transformer
class MyAddTransformer(Transformer):
KWARGS_NAMESCOPE = 'myadd_transformer'
METHOD_NAME = 'myadd_transformer'
... |
import random
import math
from PIL import Image, ImageFilter
from PIL.ImageOps import autocontrast
from .types import Size, Dimensions
# PIL wrappers
def image(filename):
return Image.open(filename)
def make_grayscale(image):
return image.convert("L")
def combine(filenames, size=None, number=None, dimen... |
#!/usr/bin/env python
# -*- coding:utf-8 -*-
"""
@version: 1.0.0
@author: xlliu
@contact: liu.xuelong@163.com
@site: https://github.com/xlliu
@software: PyCharm
@file: data_analysis_handlers.py
@time: 2016/8/18 11:16
"""
import tornado.gen
from com.analysis.core.base import BaseAnalysisRequest
from com.analysis.tasks... |
def main():
n,p,k = map(int, input().split())
times = [int(x) for x in input().split()]
tot = 0
start = 0
mult = 1
for x in times:
tot += (x - start)*mult
start = x
mult += p/100
tot += (k - start)*mult
print(tot)
if __name__ == "__main__":
main()
|
# coding: utf-8
"""
Layered Insight Assessment, Compliance, Witness & Control
LI Assessment & Compliance performs static vulnerability analysis, license and package compliance. LI Witness provides deep insight and analytics into containerized applications. Control provides dynamic runtime security and analyti... |
"""
Project Euler Problem 10
========================
The sum of the primes below 10 is 2 + 3 + 5 + 7 = 17.
Find the sum of all the primes below two million.
"""
from collections import defaultdict
composites = defaultdict(list)
def genprimes():
v = 2
while True:
yield v
composites[v * v] ... |
# 18/20 on functions
# 20/22 here
# LOOPS (22pts TOTAL)
import random
# PROBLEM 1 (Fibonacci - 4pts)
## The Fibonacci sequence is a sequence of numbers that starts with 1, followed by 1 again.
# Every next number is the sum of the two previous numbers.
# I.e., the sequence starts with 1, 1, 2, 3, 5, 8, 13, 21,...
# ... |
from pyspark import SparkContext, SparkConf
import sys
import json
from operator import add
import string
import csv
import os
from itertools import combinations
from functools import reduce
from graphframes import GraphFrame
from pyspark import SparkConf, SparkContext
from pyspark.sql import SparkSession
os.environ["... |
#!/usr/bin/env python3
# -*- coding: utf-8 -*-
#Author:Winston.Wang
import logging
#打开一份文件,如果找不到会抛异常
def openFile(fileName,types):
try:
handle = open(fileName,types,encoding='utf-8')
#把内容读取到内存中
return handle.read()
except FileNotFoundError as e:
logging.error(e)
finally:
if handle:
handle.close()
def wr... |
# coding: utf-8
from __future__ import print_function
import os
import subprocess
from . import util
from .fucking_string import ensure_utf8
__all__ = ['get_app_info', 'get_all_app_info',
'get_peripheral_info', 'get_all_peripheral_info']
def call(cmd, **kwargs):
proc = subprocess.Popen(cmd, stdout=sub... |
#!/usr/bin/python3
#-------------------------------------------------------------------#
# MOURAD TOUNSI #
#-------------------------------------------------------------------#
import pygame, math, sys
from datetime import datetime
# initiation pygame ---------------... |
'''
Created on 2013-4-21
@author: kfirst
'''
from flex.core import core
import time
logger = core.get_logger()
class TopologyPacketHandler(object):
def __init__(self, myself):
self._myself = myself
self._my_id = myself.get_id();
# {controller: {controller: path}}
self._nexthops_... |
array = ['curry', 'beef', 'chicken', 'vegetable']
beef_index = array.index('beef')
print(beef_index)
|
# coding: utf-8
from sqlalchemy import Column, DateTime, Index, JSON, String, Text, Time, text
from sqlalchemy.dialects.mysql import BIGINT, INTEGER, SMALLINT, TINYINT
from app import db
class RegistryCenter(db.Model):
__tablename__ = 'registry_center'
__table_args__ = (
Index('idx_project_app', 'proj... |
# import qt_auto as qt
import qt_all as qt
# import qt
class TestWidget(qt.QWidget):
def __init__(self):
super().__init__()
self.button = qt.QPushButton()
self.vboxlayout = qt.QVBoxLayout(self)
self.vboxlayout.addWidget(self.button)
def resizeEvent(self, event: qt.QResizeEve... |
# coding: utf-8
# motor_server.py
import pickle
import socket
import threading
from motor_l6470 import *
from motor_controller import *
from motor_command import *
class MotorServer(object):
"""
モータの操作命令を待ち受けるサーバのクラス
"""
# サーバのIPアドレスまたはホスト名
MOTOR_SERVER_HOST = "127.0.0.1"
# サーバが使用するポート番号
... |
#shy tiger
from typing import List, Tuple, Optional
from agent import Agent
from game import Game
from const import Const
from move import Move
import random
class ShyTigerAgent(Agent):
def __init__(self,game : Game, side : int):
super(ShyTigerAgent, self).__init__(game,side)
if side != Const.MARK_... |
from geobr.utils import select_metadata, download_gpkg
def read_micro_region(code_micro="all", year=2010, simplified=True, verbose=False):
"""Download shape files of micro region as sf objects
Data at scale 1:250,000, using Geodetic reference system "SIRGAS2000" and CRS(4674)
Parameters
----------
... |
#!/usr/bin/env python
import csv
import os
import app_config
from zazzle import zazzlify_png
with open('data/review_plus.csv') as f:
rows = list(csv.reader(f))
for i, row in enumerate(rows):
svg_url, status, tumblr_url, name, location = row
if not tumblr_url:
continue
tumblr_id = tumblr_ur... |
# Whether a bank customer qualifies for a loan
# constants
MIN_SALARY = 20000.0
MIN_YEARS = 3
def main():
# get the customers annual salary
salary = float(input('Enter your annual salary: '))
# Get number of years in the job
years_on_job = int(input('Enter the number of years employed: '))
# Ch... |
# Generated by Django 2.2.15 on 2020-08-24 16:44
from django.db import migrations
class Migration(migrations.Migration):
dependencies = [
('blog', '0013_auto_20200824_0900'),
]
operations = [
migrations.AlterModelOptions(
name='document',
options={'verbose_name':... |
# coding: utf-8
import unittest
from os import path
import zipfile
import rarfile
from tests.unit import assets_path
from getsub.util import P7ZIP
from getsub.util import get_file_list
class TestGetFileList(unittest.TestCase):
def test_zip_archive(self):
with open(path.join(assets_path, "archive.zip"),... |
#!/usr/local/python3/bin/python3
import requests
import datetime
import pandas as pd
import json
import re
import sys
import time
sys.path.append("..")
sys.path.append("../..")
from lib.time import (strtime_convert, strtime_delta_n_day)
from hdailydata.hdaily_mgr import (get_price)
import os
import numpy as np
root='/... |
import numpy as np
np.seterr(all="raise")
import time, threading
import algorithms.ppo_mpi.params as params
from algorithms.ppo_mpi.brain import Brain
from algorithms.ppo_mpi.memory import Memory
# from environments.obstacle_car.environment import Environment_Graphical as Environment
from environments.obstacle_car.... |
# Generated by Django 2.2 on 2019-05-11 01:09
import datetime
from django.conf import settings
from django.db import migrations, models
import django.db.models.deletion
import taggit.managers
class Migration(migrations.Migration):
initial = True
dependencies = [
('taggit', '0002_auto_20150616_2121'... |
import nltk
import numpy as np
import operator
from heapq import nlargest
import pandas as pd
from sklearn.feature_extraction.text import TfidfVectorizer
from sklearn.metrics.pairwise import cosine_similarity
class ContentBasedRecommender(object):
def __init__(self):
self.movies = pd.read_csv("data/movie... |
from glob import glob
import numpy as np
import os, shutil
from PIL import Image
def transfer(src, dst):
shutil.copyfile(src, dst)
deploy_folder = "C:\\Users\\vivek\\Desktop\\V\\UMich\\S3 - Fall 2017\\ROB 599\\Project\\Perception_v2\\deploy\\"
target_folder = deploy_folder
test_folder = glob(deploy_... |
import doctest
def DocTests():
"""
>>> from super_admin import SuperAdmin
>>> from user import User
>>> from casino import Casino
--- Should create instances with no problem
>>> super_admin = SuperAdmin('Volodya', 50_000.5)
>>> user = User('Oksana', 1000)
--- Check the value error is... |
import cx_Oracle
import snowflake.connector
from lib.db_connections import DBconnections
def setup_oracle():
db= DBconnections('ORACLE')
connections = db.oracle_set_connections()
cursor = connections.cursor()
return cursor,connections
def setup_snowflake():
conn = snowflake.connector.connect(... |
class Stack:
def __init__(self):
self.items = []
self.size = 0
def add(self, data):
self.items.append(data)
self.size += 1
def pop(self):
self.items.pop()
self.size -= 1
def getSize(self):
return self.size
s = Stack()
s.add(3)
s.add(2)... |
def operaciones():
lista= [];
resultado = 0;
try:
operacion = int(input("¿Que operacion desea realizar [número]? "));
except ValueError:
print("El valor introducido no es válido, vuelva a intentarlo de nuevo");
operaciones();
while True: ... |
from django.db import models
class ToDoApp(models.Model):
name = models.CharField(max_length=300)
def __str__(self):
return self.name
|
# trying to get html of things from
import urllib2
from bs4 import BeautifulSoup
import matplotlib.pyplot as plt
from wordcloud import WordCloud, STOPWORDS
import itertools
import time
from time import mktime
from datetime import datetime
import pandas as pd
import numpy as np
import glob
from db_mongo import *
import ... |
def doubleBasePalindromes():
finalList = []
for i in range(1,1000000):
if str(i) == str(i)[::-1]:
if str(format(i,'b')) == str(format(i,'b'))[::-1]:
finalList.append(i)
return sum(finalList)
print(doubleBasePalindromes())
|
#!/usr/bin/python
import pyupm_grove as grove
import websocket
import datetime
import time
temp = grove.GroveTemp(0)
print temp.name()
websocket.enableTrace(True)
ws = websocket.create_connection("ws://wot.city/object/57cad2809453b2446f0007de/send")
while True:
celsius = temp.value()
print "%d degrees Celsi... |
'''
Created on May 15, 2012
@author: Tony
'''
import math, collections
from nltk.probability import LidstoneProbDist
#from nltk.probability import WittenBellProbDist
from nltk.model import NgramModel
def _estimator(fdist, bins):
return LidstoneProbDist(fdist, 0.2)
class WordTagModel:
def ... |
"""
.. module:: api
:synopsis: Endpoints for adding a task and retreiving the task status are defined here
.. moduleauthor:: Rahul P <github.com/zirin12>
"""
from flask_restplus import Api, Resource, fields, abort
from .workerA import add_task
from .workerB import update_db
from . import models, db
from sqlalchemy... |
#!/usr/bin/env python3
# -*- coding: utf-8 -*-
"""
Written by Lucas Sinclair and Paul Rougieux.
JRC biomass Project.
Unit D1 Bioeconomy.
"""
# Built-in modules #
# Third party modules #
# First party modules #
from autopaths.auto_paths import AutoPaths
# Internal modules #
# Internal modules
###################... |
from peru.cache import Cache
from peru.merge import merge_imports_tree
from shared import create_dir, assert_contents, PeruTest, make_synchronous
class MergeTest(PeruTest):
@make_synchronous
async def setUp(self):
self.cache_dir = create_dir()
self.cache = await Cache(self.cache_dir)
... |
from __future__ import print_function
import numpy
import pandas
def get_dataset(filename):
data = numpy.load(filename)
return data['train'], data['test']
def get_fastest_params(filename, min_precision=0.99):
""" gets the fastest parameters over a given precision for a filename
last run on lastfm50... |
# -*- coding: utf-8 -*-
"""
Created on Wed Dec 13 20:15:56 2017
@author: Administrator
"""
# -*- coding: utf-8 -*-
"""
Created on Sun Nov 5 15:33:56 2017
@author: Administrator
"""
#downlink 精简版本--无tensorbord版本自创的深层基本结构
#############good
import numpy as np
import pandas
import matplotlib.pyplot as ... |
import pytest
from qtpy import PYQT5, PYQT6, PYSIDE2
@pytest.mark.skipif(
PYQT5 or PYQT6 or PYSIDE2,
reason="Not available by default in PyQt. Not available for PySide2",
)
def test_qtnetworkauth():
"""Test the qtpy.QtNetworkAuth namespace"""
QtNetworkAuth = pytest.importorskip("qtpy.QtNetworkAuth")
... |
"""Test the jpm package"""
import jpm
def test_doc():
assert getattr(jpm, '__doc__', None) is not None
def test_version():
assert jpm.__version__ > '0.0.0'
|
import numpy as np
class ACO:
def __init__(self, n_trucks, dimension, capacity, demands, distances, params):
self.params = params
self.n_trucks = n_trucks
self.dimension = dimension
self.capacity = capacity
self.demands = demands
self.distances = distances
... |
"""
NepidemiX utility functions and classes
=======================================
Utility classes and functions.
"""
__author__ = "Lukas Ahrenberg <lukas@ahrenberg.se>"
__license__ = "Modified BSD License"
__all__ = []
import networkxtra
import nepidemixconfigparser
from nepidemixconfigparser import *
import... |
import json
import logging
import signal
import sys
import time
import urllib
import requests
BOT_TOKEN = "TELEGRAM_TOKEN" #твой АПИ для бота
OWM_KEY = "WEATHER_TOKEN" #твой АПИ для погоды
POLLING_TIMEOUT = None
# лямбда-функции для анализа обновлений из Telegram
##используется для получения текста из сообщения в T... |
#!/usr-bin/env python
from distutils.core import setup
setup(
name='discoursemap',
version='1.0',
description="A web scraper for Discourse that outputs the active users' location into a Google Spreadsheet which can be used by Zeemaps to display everyones location.",
author='Matteus Magnusson',
aut... |
import email.utils
import re
for i in range(int(input())):
a = email.utils.parseaddr(input())
if re.match('^[a-zA-Z][\w\-\.\_]*\@[a-zA-Z]+\.[a-zA-Z]{1,3}$',a[1]):print(email.utils.formataddr((a[0],a[1]))) |
SCHEMA_BASE = "Base"
SCHEMA_KEY_SESSION_ID = "session_id"
SCHEMA_KEY_TENANT_ID = "tenant_id"
SCHEMA_KEY_ITEM_ID = "item_id"
SCHEMA_KEY_USER_ID = "user_id"
SCHEMA_KEY_AGENT_ID = "browser_id"
SCHEMA_KEY_USER = "user"
SCHEMA_KEY_AGENT = "browser"
SCHEMA_KEY_ACTION = "action"
SCHEMA_KEY_NAME = "name"
SCHEMA_KEY_QUANTITY =... |
#!/usr/bin/python
# -*- coding: utf-8 -*-
from actions import get_selectors
from models import Feature
from actions import download_csv
from admin import FeatureAdmin
from datetime import datetime
from django.contrib.auth.models import User
from django.core.urlresolvers import reverse
from django.test import TestCase
... |
import sys, math
infile_name = sys.argv[1]
print "opening %s" % infile_name
infile = open(infile_name)
nodes_per_seq_dict = dict()
for x in infile:
[node, parent, nodesize, subtreesize, description, seq] = x.split(',')
node = node.strip()
seq = seq.strip()
if not seq in nodes_per_seq_dict:
nodes_per_seq_dic... |
Subsets and Splits
No community queries yet
The top public SQL queries from the community will appear here once available.