text
stringlengths
38
1.54M
from pyspark import SparkConf from pyspark.sql import SparkSession, Window from pyspark.sql.types import ArrayType, StructField, StructType, StringType, IntegerType, DecimalType, FloatType from pyspark.sql.functions import udf, collect_list, struct, explode, pandas_udf, PandasUDFType, col from decimal import Decimal im...
class Human: def __init__(self, id, speed, origin): self.id = id self.speed = speed self.origin = origin self.isCompute = 1 self.finish = 0 self.start = origin self.end = origin self.arrive = 0 self.time = 0 self.length = 0 self...
def solution(new_id): #STEP 1 전부 소문자로 바꾸기 new_id = new_id.lower() #2단계 알파벳 소문자, 숫자, 빼기(-), 밑줄(_), 마침표(.)를 제외한 모든 문자를 제거합니다. import re new_id = re.sub(r'[^a-z0-9-._]','',new_id) #3단계 new_id에서 마침표(.)가 2번 이상 연속된 부분을 하나의 마침표(.)로 치환합니다. while '..' in new_id: new_id = new_id.replace('..'...
import random,time,mcpi.minecraft as minecraft #imports necessary modules and renames one as minecraft for easy of use mc=minecraft.Minecraft.create() # Creates game and connects to it. time.sleep(3) #Waits for 3 seconds. gravel=13 #Saves minecraft's gravel block ID as 'gravel' for easy of use. while True: #Loo...
""" What are you doing here? GET OUT OF HERE. >:P """ import random # imports random library for _ in range(10): #repeats 10 times print(random.randint(0, 200) # prints a random int between 0 and 200 print("done") # prints "done" once the for loop is done
import numpy as np import matplotlib.pyplot as plt import sys def liner_regression_gradient_descent(x, y, alpha=0.0005, initial_theta=None, iter_num=1000, stream=sys.stdout): if x.ndim is 1: x = x.reshape(1, -1).transpose() assert len(x) is len(y) data_num = len(x) new_x = np.hstack((np.ones(d...
fruits = {'apple': 'manzana', 'orange': 'naranja', 'grape': 'uva'} for fruit in fruits: print(fruit + ' is ' + fruits[fruit] + ' in Spanish')
import tensorflow as tf import numpy as np from tokenizers import Tokenizer import random from train import config, model_str INPUT_LEN = config["input_len"] DIM = config["dim"] DIM = config["dim"] OUTPUT_LEN = 40 model_filename = model_str(config) model = tf.keras.models.load_model('./saved_models/' + model_filename...
from argparse import ArgumentParser parser = ArgumentParser() parser.add_argument("-c", "--company", help="Help text") parser.add_argument("-i", "--hirer", default="whom it may concern", help="Help text") parser.add_argument("-p", action="store_true") a = parser.parse_args() if a.p: filePath = "./templates/gener...
from flask import Flask, redirect, url_for, render_template, flash from flask_sqlalchemy import SQLAlchemy from flask_login import LoginManager, UserMixin, login_user, logout_user,\ current_user from oauth import OAuthSignIn
# Generated by Django 3.0.8 on 2021-05-14 17:42 from django.db import migrations class Migration(migrations.Migration): dependencies = [ ('covid19', '0003_auto_20210511_2302'), ] operations = [ migrations.DeleteModel( name='Covid_image', ), ]
import csv import json import unittest from io import BytesIO, StringIO from unittest import mock import requests from bonobo.util.testing import BufferingNodeExecutionContext from django.contrib.gis.geos import GEOSGeometry from django.test import override_settings from geostore.models import Feature, Layer from ter...
import sys import socket import cv2 import imagezmq camSet = "nvarguscamerasrc sensor-id=0 ! video/x-raw(memory:NVMM), width=1640, height=1232, framerate=30/1, format=NV12 ! nvvidconv flip-method=0 ! video/x-raw, width=640, height=480, format=BGRx ! videoconvert ! video/x-raw, format=BGR ! appsink" cap = cv2.VideoCap...
import unittest from typing import List, Tuple import pathlib from dffml.base import ( BaseDataFlowFacilitatorObject, config, field, list_action, BaseDataFlowFacilitatorObjectContext, ) from dffml.feature.feature import Feature, Features from dffml.source.source import BaseSource from dffml.source....
qtdg=float(input("quantidade de acai em gramas:")) qtds=int(input("quantidade de salgados:")) valor=float(input("valor pago:")) qtdg1= 24 sal= 3 x= qtdg/1000 tot= sal * qtds + x * qtdg1 print(round(tot, 2)) if valor>tot: print("Sim") else: print("Nao")
#guess the number game import random #random module import time #time module print("Hello! What is your name?") name = input() print("Hello there, " + name + "! " + "I am thinking of a number") print("berween 1 and 22. Think you can guess it!?") time.sleep(1) #wait one second before moving onto the for loop (inside w...
import os from .quantlabapp import QuantLabApp try: from jupyterhub.singleuser import SingleUserNotebookApp except ImportError: SingleUserQuantLabApp = None raise ImportError('You must have jupyterhub installed for this to work.') else: class SingleUserQuantLabApp(SingleUserNotebookApp, QuantLabApp): ...
import sys # Abrindo arquivo kdmer def abrirArquivo(): try: caminho = sys.argv[1] except: print("Passe o arquivo como arguemento na chamada do programa!" ) exit() try: f = open(caminho, 'r') except: print("Arquivo não encontrado!!") exit() k, d= cam...
# %% import numpy as np import pandas as pd import matplotlib.pyplot as plt import seaborn as sns from sklearn.linear_model import LinearRegression, Ridge, Lasso from sklearn.datasets import load_boston from sklearn.metrics import mean_absolute_error from sklearn.model_selection import train_test_split # %% boston = l...
import cv2 import sys import boardcv import vidio import game_tree as gt BOARD_SIZE = 19 def main(): video_source = sys.argv[1] video_cap = vidio.get_video_cap(video_source) num_frames = 0 # frame counter frame_debug = None tracker = boardcv.BoardTracker() game_tree = gt.GameTree(BOARD_SIZ...
import pandas as pd from sklearn.model_selection import train_test_split from sklearn.tree import DecisionTreeClassifier from sklearn import metrics import joblib df = pd.read_csv ('transaction_dataset.csv') df = df[['Avg min between sent tnx', 'Avg min between received tnx', 'avg val received', 'avg val sent...
# 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 # distributed under t...
from jira import JIRA from MongoCRUD import MongoCRUD from FastTraveler import FastTraveler from dotenv import load_dotenv import os, urllib3 try: load_dotenv() # setup use for getting environment variables # ignore warning from invalid certificate, allan needs to fix urllib3.disable_warnings(urllib3.exc...
# You need to install pyaudio to run this example # pip install pyaudio # In this example, the websocket connection is opened with a text # passed in the request. When the service responds with the synthesized # audio, the pyaudio would play it in a blocking mode from __future__ import print_function from ibm_watson ...
# cite: https://classes.engineering.wustl.edu/ese205/core/index.php?title=Serial_Communication_between_Raspberry_Pi_%26_Arduino #!/usr/bin/env python # coding: utf-8 # In[ ]: import serial ser = serial.Serial('/dev/ttyUSB0', 9600) while 1: if(ser.in_waiting >100): line = ser.readline() print(li...
# Library imports import webapp2 import jinja2 import os import time import datetime import calendar import unittest from google.appengine.ext import ndb from google.appengine.ext import testbed # Project imports from user import * from util import * class InstructorCenter(webapp2.RequestHandler): ...
# Copyright (c) 2012 The Chromium Authors. All rights reserved. # Use of this source code is governed by a BSD-style license that can be # found in the LICENSE file. { 'targets': [ { # This is the target that all Cobalt modules should depend on if they # wish to use Skia. It augments skia_library (S...
from Tkinter import * from ttk import * from Tkinter import Tk, Text, BOTH, W, N, E, S from PIL import Image, ImageTk class UI: """docstring for UI""" def __init__(self, original_image_path, processed_image_path, verified_plate_image_path, ip): self.ip = ip self.root = Tk() self.fram...
#!/usr/bin/env python # -*- coding: utf-8 -*- # @Time : 2019/5/22 17:51 # @Author : leyton # @Site : # @File : zhihu__login_requests.py # @Software: PyCharm import requests try: import cookielib except: import http.cookiejar as cookielib import re agent = "Mozilla/5.0 (Windows NT 10.0; Win64; x64...
########################################### # Let's Have Some Fun # File Name: 659.py # Author: Weilin Liu # Mail: liuweilin17@qq.com # Created Time: Sun Dec 1 11:23:51 2019 ########################################### #coding=utf-8 #!/usr/bin/python class Solution: def isPossible(self, nums: List[int]) -> bool: ...
from random_word import RandomWords import random from sklearn.model_selection import train_test_split import nltk r = RandomWords() def generate_dataset(): output = [] for x in range(10): label = random.randint(0, 1) text = r.get_random_words( minLength=3, maxLength=15, limit=rand...
from rest_framework import serializers import pytz class DriverSerializer(serializers.Serializer): """ Структура, содержащая данные по водителю. """ id = serializers.IntegerField(label="id", help_text="Идентификатор водителя") fname = serializers.CharField(label...
from optparse import OptionParser flags_parser = OptionParser() flags_parser.add_option('-f', '--snakefile', dest='filename', metavar='FILE', help="Use FILE as the Snakefile") flags_parser.add_option('-t', '--trace', dest='trace', action='store_true', help="Turn on verbo...
#!/bin/python import picamera import argparse from datetime import datetime, date import socket import time import os def get_default_filename(): now = datetime.now() date_str = now.strftime("%Y%m%d") time_str = now.strftime("%H%M%S") return "_".join(["Atmos", date_str, time_str]) def get_default_vid...
listagem = ("lápis", 1.10, 'borracha', 0.50, 'caderno', 15, 'mochila', 150, 'caneta', 1) print("-="* 15) print('{}'.format("LOJÃO DO PABLO")) print("-="* 15) for pos in range(0, len(listagem)): if pos % 2 == 0: print(f"{listagem[pos]:.<30}", end="") else: print(f'R${listagem[pos]:< 7.2f}') #prin...
# -*- coding: utf-8 -*- """Tests related to drawing new points from the pool.""" import numpy as np import pytest from unittest.mock import MagicMock from nessai.proposal import FlowProposal def test_draw_populated(proposal): """Test the draw method if the proposal is already populated""" proposal.populated ...
#! /usr/bin/python2.7 #---------------------------------------------------------------------------------------- # Name: # pltWaterIsot.py # # Purpose: # Plot time series of multiple species retrieved with FTIR columns/VMRs # Note: See below for inputs # # Notes: # # # Version History: # ...
import os import sys import json import shutil import ase.io import logging import argparse import numpy as np import logging from pprint import pprint from cStringIO import StringIO from ase.optimize.sciopt import SciPyFminCG from ase.optimize import BFGS, FIRE, LBFGS, MDMin, QuasiNewton from ase.constraints import U...
import datetime import logging import sqlite3 import time import schedule from current_ministry_of_finance import ( get_current_articles_from_legislacja, get_current_articles_from_projects, get_current_articles_on_ministry_of_finance, get_current_articles_on_website_podatki_gov_pl) from shorten_url import ...
from bot import BotObtainer from web import HandlerApi from aiohttp import web import settings import logging import asyncio import pathlib import json import jwt from aiohttp import web from loguru import logger def decode_token(jwt_token, user_token): logger.debug(jwt_token) logger.debug(user_token) d...
# -*- coding: utf-8 from django.contrib import admin from whipturk.models import WhipReport class WhipReportAdmin(admin.ModelAdmin): raw_id_fields = ('bill', 'target', 'user') admin.site.register(WhipReport, WhipReportAdmin)
#!/usr/bin/python3 """[summary] """ from api.v1.views import app_views from models import storage from models.engine.file_storage import classes @app_views.route('/status') def status(): """Return the status of the page """ return {'status': 'OK'} @app_views.route('/stats') def countdown(): """Retur...
from django.shortcuts import render from .models import Book, Review # Create your views here. def book_list(request): books = Book.objects.all() book_list = [] for book in books: reviews = book.review_set.all() print(reviews) total_books = Book.objects.count() return render(requ...
""" Acl roles ========= """ _schema = {'name': {'type': 'string', 'required': 'true', }, 'description': {'type': 'string'}, 'ref': {'type': 'string', 'unique': True}, 'group': { 'type': 'obj...
from django.core.management.base import BaseCommand, CommandError from django.contrib.auth.hashers import make_password from activity.models import Activity, ActivityStatistics # Scraping tools import random import json from django.contrib.auth.models import User from faker import Factory fake = Factory.create() act...
import cv2 import numpy as np import tensorflow as tf import h5py import os from keras.backend.tensorflow_backend import set_session from keras.models import Sequential from keras.layers import Convolution2D, Flatten, Dense, MaxPooling2D, Dropout from keras.utils.np_utils import to_categorical from keras import losses,...
import os import nibabel as nib ## ######### ART PARAMETERS (edit to desired values) ############ global_mean=1 # global mean type (1: Standard 2: User-defined Mask) motion_file_type=0 # motion file type (0: SPM .txt file 1: FSL .par file 2:Siemens .txt file) use_diff_motion=1 # 1: uses scan-to-scan motion to de...
#Imports for MailChimpETL import json import datetime import pandas as pd from dateutil.relativedelta import relativedelta from sqlalchemy import create_engine import flat_table from mailchimp3 import MailChimp #Create the class for MailChimp scrapper class MailChimp_ETL(): """An instance of this class sets up the ...
# -*- coding: utf-8 -*- import itertools import warnings from typing import List, Optional, NamedTuple import numpy as np import skfmm as fmm from scipy.interpolate import RegularGridInterpolator from scipy.spatial.distance import euclidean from ._base import mpe_module, PointType, InitialInfo, PathInfo, PathInfoRe...
#!/usr/bin/env python # coding: utf-8 # In[155]: import pandas as pd import numpy as np # In[156]: df = pd.read_csv('../data/compas.data', parse_dates = ['DateOfBirth']) # In[157]: removed_columns = [ 'Person_ID', 'AssessmentID', 'Case_ID', 'LastName', 'FirstName', '...
import sys n, big = map(int, raw_input().split()) total = [str(big)] temp = big while big > n: if big % 2 == 0: big = big / 2 total.append(str(big)) else: temp = (big - 1) // 10 if temp * 10 + 1 == big: total.append(str(temp)) big = temp else:...
import sys from fractions import gcd import numpy as np def primesfrom3to(n): # http://stackoverflow.com/questions/2068372/fastest-way-to-list-all-primes-below-n-in-python/3035188#3035188 """ Returns a array of primes, p < n """ assert n>=2 sieve = np.ones(n/2, dtype=np.bool) for i in xrange(3,int(...
from django.contrib.auth.forms import AuthenticationForm class LoginForm(AuthenticationForm): username=forms.CharField(widget=forms.TextInput(attrs = {'class':'form-control'})) password=forms.CharField(widget=forms.PasswordInput(attrs = {'class':'form-control'}))
import random lower_letters = ['a', 'b', 'c', 'd', 'e', 'f', 'g', 'h', 'i', 'j', 'k', 'l', 'm', 'n', 'o', 'p', 'q', 'r', 's', 't', 'u', 'v', 'w', 'x', 'y', 'z'] upper_letters = ['A', 'B', 'C', 'D', 'E', 'F', 'G', 'H', 'I', 'J', 'K', 'L', 'M', 'N', 'O', 'P', 'Q', 'R', 'S', 'T', 'U', 'V...
import logging import json import patcherex.patches l = logging.getLogger("patcherex.techniques.ManualPatcher") class ManualPatcher: def __init__(self, binary_fname, backend, patch_file): with open(patch_file, "rb") as patch_file_obj: self.patches = json.load(patch_file_obj) self.bina...
#!/usr/bin/env python3 # -*- coding: utf-8 -*- import pandas as pd # pandas索引类型常用方法 dl = {'城市':['北京', '上海', '广州', '深圳', '沈阳'], \ '环比':['101.5', '101.2', '101.3', '102.0', '100.1'], \ '同比':['120.7', '127.3', '119.4', '140.9', '101.4'], \ '定基':['121.4', '127.8', '120.0', '145.5', '101.6']} d = pd.Dat...
# -*- coding: utf-8 -*- # <nbformat>3.0</nbformat> # <codecell> import os from glob import glob import numpy as np from matplotlib.mlab import csv2rec from mpl_toolkits.mplot3d.axes3d import Axes3D # <codecell> directory = '/Users/alex/Documents/PTV/test/res/' # <codecell> list_ptv_is_files = glob(os.path.join(di...
from sklearn import datasets from sklearn.linear_model import LogisticRegression from sklearn.model_selection import train_test_split, validation_curve def get_data(): # 导入数据集 iris = datasets.load_iris() data = iris.data target = iris.target x_train, x_test, y_train, y_test = train_test_split(dat...
# -*- coding: utf-8 -*- ''' 曲别针换钢琴(使用dict实现) ''' CLIP, POSTER, CD, GUITAR, DRUM, PIANO = ('clip', 'poster', 'cd', 'guitar', 'drum', 'piano') infinity = float('inf') graph = {CLIP: {POSTER: 0, CD: 5}, POSTER: {GUITAR: 30, DRUM: 35}, CD: {GUITAR: 15, DRUM: 20...
""" ボタン機能追加 """ import pygame from pygame.locals import * import sys import Helper from Helper import BattleHelper import Base2 as Base class ObjectClass(Base.ObjectClass): def __init__(self, MainClass, kwargs): self.MainClass = MainClass self.BattleHelper = MainClass.BattleHelper self.H...
#Abrir y trabajar un archivo de texto archivo = open('frutas.txt', 'r', encoding= 'utf-8') for linea in archivo: linea = linea.replace('\n', '') print(linea) archivo.close()
import pytorch_wrapper as pw import torch import os import uuid from torch import nn from torch.utils.data import DataLoader, SequentialSampler, RandomSampler from torch.optim import AdamW from itertools import product from ...utils.loss_wrappers import PassThroughLossWrapper from .model import UDRNNModel from .datas...
from scoring_engine.db import session, delete_db, init_db from scoring_engine.models.setting import Setting class UnitTest(object): def setup(self): self.session = session delete_db(self.session) init_db(self.session) self.create_default_settings() def teardown(self): ...
import json import csv fileName = 'document.json' with open(fileName, 'rb') as fin: content = json.load(fin) count = 0 data = '' for k, v in content.items(): if k=='TimeStamp': date = v if k=='Categories': for k1, v1 in v.items(): for p, cost in ...
from django.db import migrations from django.conf import settings def create_data(apps, schema_editor): Product = apps.get_model('catalog', 'Product') Product(sku='sku1',name='Product 1', description='Product 1', buyPrice=100 , sellPrice=100,unit='kilogram', quantity=100).save() Product(sku='sku2',name='Pr...
from source.domain.student import Student class DataProviderStudent: studentList = None def __init__(self): global studentList studentList = dict() def insert(self, student): global studentList studentList[student.getStudentId()] = student retur...
import os, os.path from hsc.integration.test import CommandsTest from hsc.integration.camera import getCameraInfo class SolveTansipTest(CommandsTest): def __init__(self, name, camera, visit, rerun=None, **kwargs): self.camera = camera self.visit = visit self.rerun = rerun cameraInf...
from twitter import * from pushbullet import PushBullet import config CONSUMER_KEY = config.twitter_consumer_key CONSUMER_SECRET = config.twitter_consumer_secret OAUTH_TOKEN = config.twitter_oauth_token OAUTH_SECRET = config.twitter_oauth_secret pb_api_key = config.pb_api_key twitter = Twitter(auth=OAuth( OAUTH_TOKE...
#!/usr/bin/env python3 # -*- coding: utf-8 -*- s1 = 72 s2 = 85 r = (s2-s1)/s1*100 print("小明,成绩提升了%.1f%%。" % r) print("小明,成绩提升了{0:.1f}%。".format(r))
H, W, N = map(int, input().split()) point = [tuple(map(int, input().split())) for _ in range(N)] a = {j:i for i, j in enumerate(sorted(set(map(lambda x:x[0], point))), start=1)} b = {j:i for i, j in enumerate(sorted(set(map(lambda x:x[1], point))), start=1)} for i in point: print(a[i[0]], b[i[1]])
# This shows the use of generators, and use of iter() and next() methods - scratch sheet # simple use of generators # def generate_nums(): # for i in range(10): # yield i # # for k in generate_nums(): # print(k) # Use of Generators to not allocate everything in memory # the usual way to allocate everything in...
# First as a comparison: design an unwarped filter with 4 coefficients/taps with these specifications: import scipy.signal as sp cunw = sp.remez(4, [0, 0.025, 0.025+0.025, 0.5], [1,0], [1, 100]) print 'cunw = ', cunw #impulse response: import matplotlib.pyplot as plt plt.plot(cunw) plt.xlabel('Sample') plt.ylabel('va...
# -*- coding: utf-8 -*- class ValidationException(Exception): def __init__(self, message, fields): super(ValidationException, self).__init__(message) self.message = message self.fields = fields
#coding=utf-8 class Person(object): sex = 'man' age = 18 def fun(self): print 'fdhsfhsd' class Metel(object): height = 21 def fun(self): print 'hello' a = Person() a.name = 'zhangsan'#添加私有变量 a.age = 20 b = Person() print b.sex print a.sex print a.name print a.age pri...
from django.apps import AppConfig from django.utils.translation import gettext_lazy as _ class AddressBookConfig(AppConfig): name = "packman.address_book" verbose_name = _("Address Book")
#!/usr/bin/python/ import numpy as np from math import * from pprint import pprint from mpl_toolkits.mplot3d import Axes3D import matplotlib.pyplot as plt identityMatrix_44 = np.matrix([ [1, 0, 0, 0], [0, 1, 0, 0], [0, 0, 1, 0], [0, 0, 0, 1]]) max_thetaX = 90 min_thetaX = -90 max_thetaY = 90 min_the...
# -*- coding: utf-8 -*- from __future__ import unicode_literals from django.db import migrations, models class Migration(migrations.Migration): dependencies = [ ('clientes', '0005_auto_20151017_2118'), ] operations = [ migrations.AlterField( model_name='cliente', ...
import tkinter as tk from Utilities import BGLogger, Graph from matplotlib.backends.backend_tkagg import FigureCanvasTkAgg import os class GraphPage(tk.Frame): def __init__(self, master, controller): tk.Frame.__init__(self, master) self.controller = controller self.Logger = BGLogger.Keyb...
from pwn import * io = remote('oucs.cry.wanictf.org','50010') plaintext = "" ciphertext = "" n = 0 # Get n io.recvuntil('> ') io.sendline('4') exec(io.recvline().decode('utf-8')) # n # Get c1 io.recvuntil('> ') io.sendline('1') exec(io.recvline().decode('utf-8')) flag_encrypt = ciphertext # Get c2 io.recvuntil('> ...
import re import subprocess from math import log from pathlib import Path from nltk import FreqDist, TweetTokenizer from nltk.corpus import stopwords from sqlalchemy.orm import sessionmaker from tqdm import tqdm import settings from db import events from db.engines import engine_lmartine as engine from db.models_new ...
from django.db import models from django.contrib.auth.models import User class Pessoa(models.Model): usuario = models.OneToOneField(User, on_delete = models.CASCADE, verbose_name ='Usuário') nome = models.CharField('Nome', ...
from django.views.generic import DetailView from braces.views import LoginRequiredMixin from .models import User class ProfileDetailView(LoginRequiredMixin, DetailView): ''' Displays the user profile information ''' model = User def get_object(self): # Get the currently logged in user ...
from django.contrib.auth import authenticate from rest_framework import serializers from account.models import MyUser from account.utils import send_activation_code class RegisterSerializer(serializers.ModelSerializer): password = serializers.CharField(min_length=6, write_only=True) password_confirm = serial...
# Generated by Django 3.0.7 on 2020-07-05 15:05 from django.db import migrations, models class Migration(migrations.Migration): dependencies = [ ('english', '0011_auto_20200705_1949'), ] operations = [ migrations.RemoveField( model_name='testtest', name='correct_...
import tkinter as tk from tkinter import font as tkfont from tkinter import * from tkinter import ttk import tkinter.messagebox import sqlite3 class SSIS: def __init__(self,root): self.root = root self.root.title("Student Information System") self.root.geometry("1300x700+0+0") ...
import logging from typing import Any, Dict, Tuple class NullHandler(logging.Handler): def emit(self, record: Any) -> None: ... ScalarTypes: Tuple[str, ...] BOTOCORE_ROOT: str class UNSIGNED: def __copy__(self) -> UNSIGNED: ... def __deepcopy__(self, memodict: object) -> UNSIGNED: ... def xform_name( ...
# -*- coding: utf-8 -*- ############################################################################## # # OpenERP, Open Source Management Solution # Copyright (C) 2004-2010 Tiny SPRL (<http://tiny.be>). # # This program is free software: you can redistribute it and/or modify # it under the terms of the GNU...
# -*- coding: utf-8 -*- # Generated by Django 1.11.9 on 2018-04-04 14:57 from __future__ import unicode_literals from django.db import migrations def load_articles(apps, schema_editor): Article = apps.get_model('articles', 'Article') OldArticle = apps.get_model('aldryn_newsblog', 'Article') Tag = apps.ge...
#!/usr/bin/env python import optparse import time def check_time(input): try: time.strptime(input, '%H:%M') return True except ValueError: return False def set_commands_for_sssr(): print 'setting commands for sssr', options.sssr def set_commands_for_time(): print 'setting ...
import sys f = open('teams.txt') n = int(f.readline().strip()) #n = int(input().strip()) n = 1 if n == 0: print("0") sys.exit(0) for student_group in range(0, n): # line = [int(x) for x in input().strip().split(' ')] # line = [int(x) for x in f.readline().strip().split(' ')] line = [int(x) for x in...
"""This module is part of Swampy, a suite of programs available from allendowney.com/swampy. Copyright 2011 Allen B. Downey Distributed under the GNU General Public License at gnu.org/licenses/gpl.html. """ from __future__ import print_function, division import optparse import os import copy import random import sys...
def recursion(m, n): # Базовый случай if m == 0: return n + 1 # Шаг рекурсии / рекурсивное условие elif n == 0 and m > 0: return recursion(m - 1, 1) # Шаг рекурсии / рекурсивное условие else: return recursion(m - 1, recursion(m, n - 1)) print(recursion(0, 15))
''' Level: Easy Given an integer array nums, return the third distinct maximum number in this array. If the third maximum does not exist, return the maximum number. Example 1: Input: nums = [3,2,1] Output: 1 Explanation: The first distinct maximum is 3. The second distinct maximum is 2. The third distinct maximum i...
class Quadruplets2: # Returns the number of quadruplets that sum to zero. # a - [int] # b - [int] # c - [int] # d - [int] @staticmethod def zero_quadruplets_count(a, b, c, d): left_sums = {} right_sums = {} result = 0 for element1 in a: for elem...
import smtplib sender = 'ayushgoel2004@gmail.com' receivers = ['goel.monica1@gmail.com'] message = """From: From Person <from@fromdomain.com> To: To Person <goel.monica1@gmail.com> Subject: Python email number 1 This is awesome. """ smtpObj = smtplib.SMTP('localhost') smtpObj.sendmail(sender, receivers, message) p...
#!/usr/bin/env python # coding: utf-8 import math import sys pempty = lambda x: math.e ** (-x) pone = lambda x: x * math.e ** (-x) pcollision = lambda x: 1 - (1+x) * math.e ** (-x) perc = lambda x: '%02.0f%%' % (x*100) if __name__ == "__main__": loadfactors = [float(x) for x in sys.argv[1:]] for lf in loadfa...
import pytest # FIXME This test is too flaky # https://github.com/ClickHouse/ClickHouse/issues/42561 pytestmark = pytest.mark.skip import logging from string import Template import time from helpers.cluster import ClickHouseCluster from helpers.test_tools import assert_eq_with_retry from pyhdfs import HdfsClient ...
from random import randint # Specify weapons weapons = ("rock", "paper", "scissors") # Initialize global variables game_continue = "" computer_score = 0 player_score = 0 while game_continue != "N": # Generate opponent weapon number = randint(1,3) if number == 1: computer_weapon = weapons[0] elif number ==...
"""Dump JSON data from Postgres to local storage.""" import json from typing import Optional from airflow.hooks.postgres_hook import PostgresHook from airflow.models import BaseOperator from airflow.utils.decorators import apply_defaults from psycopg2.extras import RealDictCursor class PostgresToLocalOperator(BaseO...
from __future__ import absolute_import from __future__ import division from __future__ import print_function import tensorflow as tf import numpy as np import scipy.io import cPickle import configuration def main(unused_argv): # load data disk x = cPickle.load(open("./data/mscoco/data.p","rb")) train, va...