text
stringlengths
8
6.05M
from yolo import YOLO from PIL import Image import imutils import cv2 import os yolo = YOLO() files = os.listdir('./test/') for file in files: img = './test/' + file image = Image.open(img) r_image = yolo.detect_image(image) r_image.show()
import sys import optparse from pymongo import MongoClient #import User Class from userClass import User from deviceClass import Device client = MongoClient('mongodb://ec2-52-89-213-104.us-west-2.compute.amazonaws.com:27017/') db = client['Alfr3d_DB'] def createUser(): #TODO print "print not implemented yet"...
def Golomb(n): dp = [0]*(n+1) dp[1] = 1 print(dp[1],end=" ") for i in range(2,n+1): dp[i] = 1 + dp[i - dp[dp[i-1]]] print(dp[i],end=" ") n = 9 Golomb(n)
from django.views.generic import View from django.shortcuts import render_to_response from yoolotto.rest.decorators import rest class GamesStub(View): def get(self, request): return render_to_response("comingsoon.html") @rest def post(self, request): return False
import sys import mosek import mosek.fusion from mosek.fusion import * def main(args): A = [ [ -0.5, 1.0 ] ] b = [ 1.0 ] c = [ 1.0, 1.0 ] with Model("duality1") as M: x = M.variable("x", 2, Domain.greaterThan(0.0)) con = M.constraint(Expr.sub(Expr.mul(Matrix.dense(A), x), b), Domain.eq...
from django.apps import AppConfig class NewpostAppConfig(AppConfig): name = 'newpost_app'
import re string = "hellomypythonhispythonourpythonend" pattern = ".python." result = re.search(pattern,string) result1 = re.search(pattern,string).span() print(result) print(result1)
try: from django.utils.deprecation import MiddlewareMixin except ImportError: from bugsnag.django.utils import MiddlewareMixin import bugsnag import bugsnag.django class BugsnagMiddleware(MiddlewareMixin): def __init__(self, get_response=None): bugsnag.django.configure() super(BugsnagMidd...
import random my_number = random.randint(1,100) print("Welcome to the number Guessing Game\n I am thinking of an Integer number between 1 and 100") level = input("Choose a difficulty level. Type 'easy' or 'hard': ") if level == 'easy': lives_remaining = 11 elif level == 'hard': lives_remaining = 6 while liv...
import flask import random #from flask import request,jsonify #import json app=flask.Flask(__name__) app.config["DEBUG"]=True @app.route('/api') def page(): return "API for collecting datasets" @app.route('/api/normal',methods=['GET']) def normal(): data={ "temparture":random.randint(36,37), ...
import environments import pandas as pd import numpy as np import sys from collections import defaultdict import matplotlib.pyplot as plt from collections import deque class epsilon(object): def __init__(self, eps_start = 1.0, eps_decay = 0.999, eps_min = 0.0): self.eps_start = eps_start self.eps =...
from mpl_toolkits.mplot3d import Axes3D import matplotlib.pyplot as plt import numpy as np from matplotlib.patches import FancyArrowPatch from mpl_toolkits.mplot3d import proj3d class Arrow3D(FancyArrowPatch): def __init__(self, xs, ys, zs, *args, **kwargs): FancyArrowPatch.__init__(self, (0,0), (0,0), *a...
# -*- coding: utf-8 -*- """TSP.py TSP问题 """ import sys import random import math import time import Tkinter import threading from GA import GA class MyTSP(object): """TSP""" def __init__(self, root, width=800, height=600, n=32): self.root = root self.width = width self.height = he...
#!/usr/bin/env python #encoding:utf-8 # # Copyright (c) 2015 Ministerio de Fomento # Instituto de Ciencias de la Construcción Eduardo Torroja (IETcc-CSIC) # # Permission is hereby granted, free of charge, to any person obtaining a copy # of this software and associated documentation files (the "Softw...
class Solution: def repeatedNTimes(self, A): """ :type A: List[int] :rtype: int """ len_a = len(A) from collections import defaultdict counter = defaultdict(int) for a in A: counter[a] += 1 if counter[a] == len_a / 2: ...
from django import template from django.template.loader import render_to_string register = template.Library() @register.inclusion_tag('events/actions/remind_me_popup.html', takes_context=True) def remind_me_popup(context, event): request = context['request'] return { 'account': request.account, ...
import os def main(): os.chdir(os.path.dirname(os.path.abspath(__file__))) inp = open("day23_input.txt").read().splitlines() print(solve(inp)) def solve(inp): h, g = 0, 0 c = 122700 for b in range(105700, c + 1, 17): if any(b % d == 0 for d in range(2, int(b**0.5))): h ...
#!/usr/bin/python import d2slib #winxp's script import sys #Don't know import cPickle #file input and output import collections #checks for duplicates import time #exception pausing for 503 errors endingDate = 1391558400 #Set to Jan 8, 12 ...
from sklearn.ensemble import RandomForestClassifier X = [[0, 0], [1, 1,],[0,1]] Y = [0, 1, 1] clf = RandomForestClassifier(n_estimators=100,warm_start=True,max_features=None) clf = clf.fit(X, Y) P=[[1,0]] A=clf.predict(P) print(A)
# Definition for a binary tree node. import re from collections import defaultdict class TreeNode: def __init__(self, x): self.val = x self.left = None self.right = None class Solution: def recoverFromPreorder(self, S: str) -> TreeNode: layer_nodes = defaultdict(list) ...
import ConfigParser from pymclevel import schematic, materials from entity import TileEntity import nbt import logging import re import os from random import randint log = logging.getLogger(__name__) ''' class BO3: def __init__(self,filename=''): self._lines = [] self._X_tracker = [0,0,0] ...
def make_positive(a): for i in range(len(a)): if a[i] < 0: a[i] = -a[i] return a
# @param {Integer} num # @return {String} def convert_to_base7(num) num.to_s(7) end
import webapp2 from google.appengine.api import channel class GetToken(webapp2.RequestHandler): def get(self): channel_id = self.request.get('channelID') token = channel.create_channel(channel_id) self.response.write(token) class SendMessage(webapp2.RequestHandler): def post(self): channel_id =...
import json import xmltodict import io import os import zipfile new_name = 'ShakeFive2.metadataJSON.zip' def tarFileIter(name): import tarfile with tarfile.open(name,mode='r:') as tarfile: for member in tarfile.members: yield member.name, tarfile.extractfile(member.name).read() def fix_...
""" Base class for special Riemannian metrics that can be built on Lie groups: - left-invariant metrics - right-invariant metrics. Note: Assume that the points are parameterized by their Riemannian logarithm for the canonical left-invariant metric. """ import numpy as np import scipy.linalg from geomstats.riemannian...
def find_neighbours_or_dead(matrix, y, x): try: return matrix[y][x] except IndexError: return { 'state': 'empty' } def count_neighbours(matrix, cell): x, y = cell['x'], cell['y'] north, south = y - 1, y + 1 east, west = x + 1, x - 1 neighbours = [ find_neighbours_or_dea...
import os import sys import math import astropy import numpy as np import matplotlib import matplotlib.pyplot as plt import matplotlib.cm as cm import argparse from astropy.io import fits from astropy.table import Table noisy_jades_filters = ['HST_F435W', 'HST_F606W', 'HST_F775W', 'HST_F814W', 'HST_F850LP', 'NRC_F070W...
''' apkg ~~~~ The Agda Package Manager. ''' # ---------------------------------------------------------------------------- import click from pathlib import Path from pony.orm import * from ..config import ( AGDA_DEFAULTS_PATH , AGDA_DIR_PATH , AGDA_LIBRAR...
# Uses SMH to create inverted index and model import smh from smh_prune import SMHD def createInvertedIndex(CORPUS_FILE, INVERT_INDEX_FILE): print('open') corpus = smh.listdb_load(CORPUS_FILE) print('invert') ifs = corpus.invert() ifs.save(INVERT_INDEX_FILE) def createModel(CORPUS_FILE,INVERT_INDEX_FILE,MODEL_F...
from requests import get, post, delete # Корректный запрос print(delete('http://localhost:5000//api/v2/users/1').json()) # Корректный запрос qw = {'name': 'nas', 'surname': 'veche', 'age': 12, 'email': 'ansad@gh', 'hashed_password': 'poityuhjvcsa342'} print(post('http://localhost:5000/api/v2/users', json=qw).json()) #...
import os from django.core.wsgi import get_wsgi_application from dj_static import Cling, MediaCling os.environ.setdefault('DJANGO_SETTINGS_MODULE', 'hiperflix.settings') application = Cling(MediaCling(get_wsgi_application())) #application = get_wsgi_application()
from pydub import AudioSegment from pydub.playback import play import io import os import binascii import PIL import math from PIL import Image from PIL.ImageEnhance import Color import base64 import codecs song = open("yoy.mp3", "rb") # value = bin(int(binascii.hexlify(song.read()), 16))[2:] zoink = b...
#!/usr/bin/python #\file colors.py #\brief Explore Matplotlib colors. #\author Akihiko Yamaguchi, info@akihikoy.net #\version 0.1 #\date Oct.02, 2021 import numpy as np import matplotlib.pyplot as plt import matplotlib.colors as plt_cols if __name__=='__main__': fig= plt.figure(figsize=(8,8)) ax= fig.add_...
from django.contrib.auth.models import User from django.db import models # Create your models here. def upload_to(instance, filename): return f'{filename}' class News(models.Model): title = models.CharField(max_length=100) publication_date = models.DateTimeField(auto_now=True) short_description = mo...
from django.db import models from django.contrib.auth.models import User import humanize from django.utils import tree class FolderManager(models.Manager): def get_or_none(self, **kwargs): try: return Folder.objects.get(**kwargs) except Exception as e: print(e) ...
""" Time Complexity = O(n log n) Space Complexity = O(n) """ class Solution: def arrayRankTransform(self, arr: List[int]) -> List[int]: if not arr: return arr return list(map({val: indx + 1 for indx, val in enumerate(sorted(set(arr)))}.get, arr))
a,b=input().split() if a.lower()==b.lower(): print("yes") else: print("no")
from bibliopixel.animation import BaseMatrixAnim import bibliopixel.colors as colors import time from datetime import datetime, timedelta class TallCountdown(BaseMatrixAnim): def __init__(self, led, target): super(TallCountdown, self).__init__(led) try: self.target = datetime.strptime(...
# -*- coding: utf-8 -*- # # * Copyright (c) 2009-2017. Authors: see NOTICE file. # * # * 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...
#!/bin/env print 'hello'
# Copyright(c) 2014, MessageBird # All rights reserved. # Redistribution and use in source and binary forms, with or without # modification, are permitted provided that the following conditions are met: # 1. Redistributions of source code must retain the above copyright notice, this # list of conditions and the follo...
from django.contrib.auth.models import User from django.http.response import HttpResponse from django.shortcuts import render from django.contrib import messages # reate your views here. def main(request): if not User.objects.all(): user = User() user.username = 'admin' user.first_name = '...
import logging import datetime from django.conf import settings from furl import furl from share.exceptions import HarvestError from share.harvest import BaseHarvester QA_TAG = 'qatest' logger = logging.getLogger(__name__) class NodeSuddenlyUnavailable(HarvestError): # A node was deleted or made private afte...
''' author: juzicode address: www.juzicode.com 公众号: 桔子code/juzicode date: 2020.10.30 ''' import time,threading,sys from threading import Thread from multiprocessing import Pipe def thread_1(conn1): print('进入线程: thread_1') loop_cout = 100 while True: time.sleep(0.5) ...
#!/usr/bin/env python #coding: utf-8 from google.appengine.ext import db from google.appengine.ext.webapp import template from google.appengine.api import memcache, urlfetch from google.appengine.runtime import DeadlineExceededError from api import datastore_api from util import templates from util im...
#!/usr/bin/env python3 class Task(): """ Manage solutions and main functions project tasks """ def __init__(self, func=None, main=None): """ Save copies of supplied functions (if any) """ self.func = func self.main = main def __call__(self): """ Execute the ma...
from share.transform.chain import * # noqa class AgentIdentifier(Parser): uri = IRI(ctx) class WorkIdentifier(Parser): uri = IRI(ctx) class Person(Parser): name = ctx class Creator(Parser): agent = Delegate(Person, ctx) cited_as = ctx order_cited = ctx('index') class Organization(Pars...
from app.models import Card def test_card(app): card = Card( title='My card', description='Some awesome card', ) assert card.title == 'My card' assert card.description == 'Some awesome card'
# Generated by Django 3.0.8 on 2020-08-01 23:49 from django.db import migrations, models import django.db.models.deletion class Migration(migrations.Migration): initial = True dependencies = [ ] operations = [ migrations.CreateModel( name='Evolution_chain', fields=[...
""" Clase Responsable del establecimiento de la temperatura deseada """ from gestores_entidades.gestor_ambiente import * class SelectorEntradaTemperatura: def __init__(self, gestor_ambiente): """ Arma la clases con la que necesita colaborar """ self._seteo_temperatura = Configura...
#!/usr/bin/python #\file box_poly_intersection.py #\brief Get an intersection polygon between a box and a polygon on a plane. #\author Akihiko Yamaguchi, info@akihikoy.net #\version 0.1 #\date Mar.03, 2021 import numpy as np from geometry import * from box_plane_intersection import BoxPlaneIntersection from po...
#!/usr/bin/env python import panflute as pf import re """ Pandoc filter that causes emphasis to be rendered using the custom macro '\myemph{...}' rather than '\emph{...}' in latex. Other output formats are unaffected. """ def alertboxes(e, doc): if type(e) == pf.Div and doc.format == 'latex': if 'notebox...
import numpy as np import cv2 import time import pygame, sys import math from pygame.locals import * ################################ # Screen dimensions SCREEN_WIDTH = 1920 SCREEN_HEIGHT = 1080 # Call this function so the Pygame library can initialize itself pygame.init() # Create an 800x600 sized screen screen = ...
import numpy as np import cv2 import os #download the cascades # multiple cascades: https://github.com/Itseez/opencv/tree/master/data/haarcascades #https://github.com/Itseez/opencv/blob/master/data/haarcascades/haarcascade_eye.xml #https://github.com/Itseez/opencv/blob/master/data/haarcascades/haarcascade_frontalface...
#!/usr/bin/env python import os from string import Template import uuid datadir = os.environ['OPENSHIFT_DATA_DIR'] repodir = os.environ['OPENSHIFT_REPO_DIR'] t = Template(open(os.path.join(repodir, 'odoo-conf.template')).read()) data = { 'DATA_DIR': datadir, 'REPO_DIR': repodir, 'ADMIN_PASSWD': uuid.uuid4...
# Load CSV using Pandas import pandas as pd import matplotlib.pyplot as plt from pandas.plotting import scatter_matrix filename = 'pima-indians-diabetes.data.csv' data = pd.read_csv(filename) scatter_matrix(data) plt.show()
#!/usr/bin/env python # -*- coding: utf-8 -*- # pylint: disable=missing-docstring import datetime import os from typing import Any, Iterator, Type import pytest import toml from flask import Flask from flask_sqlalchemy import SQLAlchemy from marshmallow import Schema, fields from smorest_sfs.extensions import babel ...
from django.urls import re_path from posts.api.views import PostCRSet, LikeCreateListDeleteViewSet urlpatterns = [ re_path(r'^(?P<id>\d+)/$', PostCRSet.as_view({'get': 'get'}), name='posts'), re_path(r'^$', PostCRSet.as_view({'get': 'list', 'post': 'create'}), name='posts'), re_path(r'^(?P<post_id>\d+)/li...
#!/usr/bin/env python # coding: utf-8 import re import requests import pandas as pd import time from selenium import webdriver from selenium.webdriver.common.by import By from selenium.webdriver.support.ui import WebDriverWait from selenium.webdriver.support import expected_conditions as EC from readFile import * #微博...
from base.form_handler import FormHandler from datamodel.word import Word import simplejson class Vocabulary(FormHandler): authorize = False def get(self): self.jsonData = Word.all().fetch(1000) lang = self.request.params.get('lang') if lang == 'a2b': words = [ {'id': word.key().id(...
import user.model.user as model from sqlalchemy import create_engine from sqlalchemy_utils import create_database, database_exists, drop_database from infraestructure.config import DB_URI def setup_package(): engine = create_engine( DB_URI, convert_unicode=True ) if database_exists(engine...
from pippi import dsp from pippi import tune import fx, snds from . import Tracks def pulsar(freq, length=22050, drift=0.01, speed=0.5, amp=0.1, pulsewidth=None, env='flat', wf=None, mod=None): if wf is None: waveform = dsp.wavetable('sine2pi') else: waveform = wf window = dsp.wavetable('...
""" Create a Mad Libs program that reads in text files and lets the user add their own text anywhere the word ADJECTIVE, NOUN, ADVERB, or VERB appears in the text file. For example, a text file may look like this, see file mad_libs.txt: The ADJECTIVE panda walked to the NOUN and then VERB. A nearby NOUN was unaffected...
import json import asyncio from config import Config from FTPClient import FTPClient def parse_json(data_file: str): with open(data_file, "r") as read_file: data = json.load(read_file) return data def split_list(seq: list, num: int): avg = len(seq) / float(num) out = [] ...
""" Code for Replica Exchange Stochastic Gradient MCMC on supervised learning (c) Wei Deng, Liyao Gao July 1, 2020 You can cite this paper 'Non-convex Learning via Replica Exchange Stochastic Gradient MCMC (ICML 2020)' if you find it useful. Note that in Bayesian settings, the lr 2e-6 and weight decay 25 are equivale...
import abc from src.app.adapters import repository, file_exporter from src.app.adapters.fakes.fake_warehouse_repository import FakeWarehouseRepository from src.app.adapters.repository import AbstractRepository class AbstractUnitOfWork(abc.ABC): repo = repository.AbstractRepository def __exit__(self, *args): ...
from Tkinter import * win = Tk() name_list =[] phone_list =[] # will change to textbox later def addEntry(): if nameVar.get() in name_list: display.insert(END, " name is already in list ") return else: name_list.append(nameVar.get()) phone_list.append(phoneVar.get()) select.insert(...
import unittest from models.quizzes import Quizzes from daos.quizzes_dao import QuizesDAO from daos.daos_impl.quizzes_dao_impl import QuizzesDaoImpl quizzes_dao = QuizzesDaoImpl() test_quiz = Quizzes(1, 'Light Quiz', 1) test_quiz2 = Quizzes(0, 'TEST QUIZ', 0) class QuizzesTest(unittest.TestCase): def test_get_...
from django.db import models from django.db.models.signals import post_save from django.dispatch import receiver from django.db import models from country.models import Country, State from django.contrib.auth import get_user_model User = get_user_model() class userProfile(models.Model): owner = models.OneTo...
# -*- coding: utf-8 -*- from __future__ import unicode_literals from django.db import models, migrations class Migration(migrations.Migration): dependencies = [ ('restodab', '0003_auto_20170623_1134'), ] operations = [ migrations.CreateModel( name='Consumicion', ...
import sys import os STACK_SIZE = 256 MEMORY_SIZE = 1024 CODEHEAP_SIZE = 1024 MAX_HISTORY = 1000000 def main(): ################################################################################# if len(sys.argv) != 2: raise_err("Missing input file name") input_file_name = sys.argv[1] if os.path.exi...
import sys def coverings(s, edges, k): '''Generate all possible complete cycle coverings from the given edges.''' # Determine the possible next elements to add to the covering. add_on = [index for index, item in enumerate(edges) if item[0] == s[-k+1:]] # If there's nothing left to add, return the str...
import datetime import config def print_makefile(f, file_name): curr = datetime.datetime.now() file_len = len(file_name) name_len = len(config.HEADER_NAME) email_len = len(config.HEADER_EMAIL) f.write("# **************************************************************************** #\n") f.writ...
import os from shutil import rmtree from intermediate import run from sys import argv import concurrent.futures import json import time import csv import logging logging.basicConfig(filename="logs.log", filemode='a', format='%(name)s - %(levelname)s - %(message)s') def create_execution_history(): file_name = 'ex...
from django.contrib.auth.utils import get_random_string from django.core.mail import send_mail from django.db import models from django.dispatch import receiver from funfactory.urlresolvers import reverse from funfactory.utils import absolutify from tower import ugettext as _ class Invite(models.Model): #: The p...
from django.contrib import admin from .models import Patient, User_Credential # Register your models here. class PatientAdmin(admin.ModelAdmin): list_display = ('first_name', 'last_name', 'email', 'phone', 'birthday', 'sent') admin.site.register(Patient, PatientAdmin) class User_CredentialAdmin(admin.ModelAdmin): ...
from collections import Counter transmap = str.maketrans("ĄČĘĖĮŠŲŪŽ", "ACEEISUUZ") counter = Counter() for line in open("with_lt/1grams.txt"): letter, freq = line.split() letter, freq = letter.translate(transmap), float(freq) counter[letter] += freq with open("1grams.txt", "w") as out: for item, freq in counter....
from __future__ import unicode_literals import re from enum import Enum class IRCTextColor(Enum): """ Enumeration of colors usable with :func:`styled`. Available values: * white * black * navy * green * red * maroon * purple * olive * yellow * lightgreen...
import os import sy import shlex import getpass import socket import signal import subprocess import platform from func import * # 一张字典表,用于存储命令与函数的映射 built_in_cmds = {} def regitster_command(name, fuc): """ 注册命令,使命令与相应的处理函数 建立映射关系 @param nage:命令名 @param func: function name """ built_in_cmds[na...
import numpy as np import pandas as pd from sklearn.datasets import load_iris from sklearn.model_selection import train_test_split, KFold, cross_val_score, GridSearchCV, RandomizedSearchCV from sklearn.metrics import accuracy_score from xgboost import XGBClassifier import warnings warnings.filterwarnings('ignore') d...
import numpy as np from scipy.stats import erlang np.set_printoptions(precision=16,suppress=False) def main(): n = 10000000 c_lb = np.float64(n) c_ub = np.float64(n)+np.sqrt(n) percentile = 0 rv = erlang(n, scale=np.float64(1)) while np.abs(c_lb-c_ub) >= 1e-4: mid = (c_lb+c_ub)/2 ...
''' args: (expression, expression, ..., expression) () expression: variable = expression variable += expression variable -= expression variable *= expression variable /= expression variable = variable bool_expr...
#encoding: utf8 from tabuleiro import Tabuleiro import sys import re class Main: def __init__(self): self.tabuleiro = Tabuleiro() def jogar(self): while(not self.tabuleiro.jogo_acabou()): self.tabuleiro.imprimir() self.processar_jogada() self.tabuleiro.imprimir...
from pwn import * import sys #config context(os='linux', arch='i386') context.log_level = 'debug' HOST = "pwn.byteband.it" PORT = 6000 def exploit(): conn = remote(HOST, PORT) count = 0 while True: l1 = "" encode = "encode" + str(count) decode = "decode" + str(count) while len(l1) < 8173: l = conn.r...
import os, sys, time, resource, re, gc, shutil import argparse import pandas as pd import django sys.path.append('/home/galm/software/django/tmv/BasicBrowser/') os.environ.setdefault("DJANGO_SETTINGS_MODULE", "BasicBrowser.settings") django.setup() from scoping.models import * parser = argparse.ArgumentParser(desc...
import tensorflow as tf import numpy as np from load import * learning_rate = 0.005 batch_size=50 n_classes = 10 n_h = 100 steps = (len(train_images) // batch_size) * 100 sigma = 0.1 x=tf.placeholder(dtype=tf.float32,shape=(None,784)) y=tf.placeholder(dtype=tf.float32,shape=(None,n_classes)) nn = tf.layers.dense(x, ...
from AI import * import tkinter as tk import time PIECE_SIZE = 10 click_x = 0 click_y = 0 pieces_x = [i for i in range(32, 523, 35)] pieces_y = [i for i in range(38, 529, 35)] coor_black = [] coor_white = [] pos_black = [] pos_white = [] person_flag = 1 # black:1 white:0 color = 1 piece_color = 'black' def pos_...
#!/usr/bin/python3 def no_c(my_string): if my_string is not None: return ''.join(filter(lambda c: c.lower() != 'c', my_string)) return None
''' 1 读取csv文件,获取链接 2 解析链接,获取详情页信息 3 存储为新表 ''' import time import sys import os import requests from multiprocessing import Pool from bs4 import BeautifulSoup import numpy as np import pandas as pd from pandas.core.frame import DataFrame headers = {'User-Agent': 'Mozilla/5.0 (Windows NT 10.0; WOW64) ' ...
import tkinter as tk from tkinter import messagebox import os vAT = ["salutat", "ambulat", "vocat", "rogat", "postulat"] vET = ["sedet", "habet", "videt", "tinet", "retinet"] vIT = ["scribit", "surgit", "ducit", "emit", "inquit"] vIR = ["est", "revenit", "aperit", "offert"] n1 = ["via","familia", "lingua", "puella", ...
# # Argument-Related Functions # import pscheduler import uuid from flask import request def arg_boolean(name): """Determine if a boolean argument is part of a request. The argument is considered true if it is 'true', 'yes' or '1' or if it is present but has no value. Otherwise it is considered False....
#!/usr/bin/python """Set Syncthing Default Password and User and Edit Config Files to allow remote access to web gui Option: --pass= unless provided, will ask interactively """ import sys import getopt import bcrypt from executil import system from dialog_wrapper import Dialog def usage(s=None): if s: ...
#import sys #input = sys.stdin.readline def main(): B, C = map(int, input().split()) L1 = B - C//2 R1 = B + abs(C-2)//2 L2 = - B - (C-1)//2 R2 = - B + (C-1)//2 if L2 <= L1 and L1 <= R2: a = min(L1,L2) b = max(R1,R2) print(b-a+1) elif L1 <= L2 and L2 <= R1: a =...
import tweepy import kafka import json #set the OAuth parameters for twitter API access_token = "" access_token_secret = "" consumer_key = "" consumer_secret = "" #function that cleans the tweet json file def cleanup(original): data = {} #collect the text, id and create time for the tweet, drop the rest ...
def cook_book_programm(): cook_book = dict() with open("homework_file.txt", "r") as f: for line in f: cook_book[line.strip()] = list() dish = line.strip() f.readline() for line in f: line = line.strip() if not line:...
import sys import numpy as np # test command # python lr.py model1_formatted_train.tsv model1_formatted_valid.tsv model1_formatted_test.tsv dict.txt model1_train_out.labels model1_test_out.labels model1_metrics_out.txt 60 LEARNING_RATE = 0.1 # read files def readFile(path): with open(path, "rt") as f: r...
# 520. Detect Capital # # Given a word, you need to judge whether the usage of capitals in it is right or not. # # We define the usage of capitals in a word to be right when one of the following cases holds: # # All letters in this word are capitals, like "USA". # All letters in this word are not capitals, like "lee...
#!/usr/bin/env python #-*- coding: UTF-8 -*- """ This module is used to parse the configuration file Authors: Light(suliangxd@gmail.com) Date: 2016/12/28 13:28 """ import ConfigParser import logging import os import global_value def conf_parser(conf_file): """Parse the conf file Call global_value to ini...
#!/usr/bin/env python import datetime import pymongo import collections _client = None def init(hostname, port, username, password, **kwargs): global _client _client = pymongo.MongoClient(hostname, port) if username is not None and password is not None: _client.zefir.authenticate(username, passw...