text
stringlengths
8
6.05M
# Generated by Django 2.0 on 2019-10-30 16:30 from django.db import migrations class Migration(migrations.Migration): dependencies = [ ('user_profile', '0001_initial'), ] operations = [ migrations.RemoveField( model_name='user', name='created_date', ), ...
# -*- coding: utf-8 -*- """ Updated 16 Dec 2017 10 sheep eat away at their environments Greedy sheep are sick after 100 units The model stops running when all sheep are at least half full @author: amandaf """ import matplotlib.pyplot import matplotlib.animation import csv import agentframework import argparse import...
# # Validator for a pScheduler test and its result. # # # Development Order #3: Test specification and result validation # # The functions in this file determine whether or not specifications # and results for this test are valid. # from pscheduler import json_validate_from_standard_template # # Test Specificatio...
from onegov.activity import Period, PeriodCollection from onegov.core.security import Secret from onegov.feriennet import _, FeriennetApp from onegov.feriennet.forms import PeriodForm from onegov.feriennet.layout import PeriodCollectionLayout from onegov.feriennet.layout import PeriodFormLayout from onegov.core.element...
import numpy, curses, logging from heapq import * class astar(object): '''This class uses the A* algorithm to return list of tuples on shortest path from start to goal. Note: coordinates are x,y''' def __init__(self, screen, start, goal, map_dims, space, enemy_symbol, player_symbol): self._screen = sc...
""" This module defines some tools used for reading/writing XYZ files. """ from futile.Utils import write as safe_print class XYZReader(): """ A class which can be used to read from xyz files. This class should behave like a standard file, which means you can use it in ``with`` statements, and use t...
import praw from pprint import pprint from urllib import urlretrieve import pickle #Creates the Reddit object r = praw.Reddit(user_agent='/r/museum scraper by /u/UnclePolycarp') already_grabbed = pickle.load(open("save.p", "rb")) #Code for pulling all recent submissions subreddit = r.get_subreddit('museum') for sub...
""" This file defines class BaseReward. @author: Clemens Rosenbaum :: cgbr@cs.umass.edu @created: 6/8/18 """ from collections import deque import abc import torch class PerActionBaseReward(object, metaclass=abc.ABCMeta): """ Class BaseReward defines the base class for per-action rewards. """ def __i...
p = ['butt', 'm', 'x', 'o', 'p'] y = 'x' def change_x(arr, x): for i in range(0, len(arr)): if arr[i] == y: arr[i] = "we changed X but we cant pop" return arr print change_x(p,y)
import fileinput import json import os import shutil import subprocess import pandas as pd import numpy as np from jupyterlab_server import add_handlers from itertools import groupby from random import randrange import networkx as nx import collections import colourmap as cm import functools as ft from community import...
#!/usr/bin/python3 def print_matrix_integer(matrix=[[]]): if len(matrix[0]) != 0: for a in matrix: for b in range(len(a)): if b != len(a) - 1: print('{:d} '.format(a[b]), end="") else: print('{:d}'.format(a[b])) else: ...
from common import * DEBUG = True # AWS_STORAGE_BUCKET_NAME = 'trade-paper-dev'
class E160_wall: def __init__(self, wall_points, slope): # set up walls self.slope = slope self.radius = 0.025 self.wall_points = wall_points self.point1 = (wall_points[0], wall_points[1]) self.point2 = (wall_points[2], wall_points[3]) ...
#first try on my own from functools import reduce def triangle_num(n): """ generates a triangular number i.g. the 7th triangle number would be 1+2+3+4+5+6+7=28 triangle_num(7) == 28 """ return sum([x for x in range(n+1)]) def factors(n): """ returns a number of factors in a list no...
# riaps:keep_import:begin from riaps.run.comp import Component import logging import ctypes import time # import capnp # import memfail_capnp # riaps:keep_import:end class MemPublisher(Component): # riaps:keep_constr:begin def __init__(self): super(MemPublisher, self).__init__() self.val = 0 ...
# -*- coding:utf8 -*- import sched import time from datetime import datetime s = sched.scheduler(time.time, time.sleep) def print_time(): dt = datetime.now() print "From print_time", dt.strftime('%H:%M:%S %f') def print_some_times(): print time.time() s.enter(5, 1, print_time, ()) s.enter(10...
import pandas as pd import collections import util import tensorflow as tf from keras.preprocessing import text, sequence import numpy as np print('loading data') df = pd.read_csv(util.train_data) print(df.shape) train_comments = df['comment_text'].tolist() y_toxic = df['toxic'] print(df.columns) for col ...
# Generated by Django 3.0.1 on 2020-01-09 17:01 from django.db import migrations class Migration(migrations.Migration): dependencies = [ ('shopUser', '0013_auto_20200109_1658'), ] operations = [ migrations.RemoveField( model_name='product', name='slug', )...
############################################################################### # # webcamperf.py # # Assess FPS performance of webcam # # January 20, 2018 # ############################################################################### import cv2 import opencvconst as cv import time def main(): """Assess FP...
import json import numpy.random as random from scipy.spatial import distance import numpy.linalg import matplotlib.pyplot as plt with open('egman.json') as json_data: data = json.load(json_data) dat = data['1']["EVACUEES"] v_distance = 12 class Evacue: def __init__(self, preevacuation, hspee...
p1 = float(input("Digite a altura do triangulo: ")) p2 = float(input("Digite a largura do triangulo: ")) calC = (p1 * p2)/2 print("A área do seu triangulo é:",calC)
#!/usr/bin/python import time from mininet.topo import Topo from mininet.net import Mininet from mininet.node import Node, Switch from mininet.cli import CLI def topology(): net = Mininet() net.addHost('h1') net.addHost('h2') net.addHost('h3') net.addHost('h4') net.addSwitch('s1', failMode='sta...
from rest_framework.generics import ListAPIView from django.db.models import Q from page.models import Mileage from .serializers import MileageSerializer class MileageListAPIView(ListAPIView): queryset = Mileage.objects.all() serializer_class = MileageSerializer def get_queryset(self, *args, **kwargs):...
from scrapy.cmdline import execute execute('scrapy crawl zw_81'.split()) #execute(['scrapy' 'crawl' 'zw_81' '-s' 'JOBDIR="D:\\pycharm\\storages\\novel"']) #断点续爬 #'scrapy crawl zw_81 -s JOBDIR="D:\pycharm\storages\novel"
# -*- coding: utf-8 -*- # Form implementation generated from reading ui file 'ui/main.ui' # # Created by: PyQt4 UI code generator 4.11.4 # # WARNING! All changes made in this file will be lost! from PyQt4 import QtCore, QtGui try: _fromUtf8 = QtCore.QString.fromUtf8 except AttributeError: def _fromUtf8(s): ...
## Automatically adapted for numpy.oldnumeric Jul 30, 2007 by import unittest from test_cube import TestBase import sys import numpy.oldnumeric as Numeric import numpy.oldnumeric.random_array as RandomArray from opengltk.OpenGL import GL, GLUT MY_LIST = 1 NUMDOTS = 500 NUMDOTS2 = 600 MAX_AGE = 13 class TestDots(Tes...
import turtle bob = turtle.Turtle() print(bob) def koch(t, length, n): if n ==0 : bob.fd(length) return else: angle = 60 koch(t, length, n-1) t.fd(length) t.lt(angle) koch(t, length, n-1) t.fd(length) t.rt(angle*...
class Solution(object): def reverseKGroup(self, head, k): if not head or k == 1: return head dummy = ListNode(0) dummy.next, ptr, n = head, dummy, 0 while ptr.next: n += 1 ptr = ptr.next pre = dummy while n >= k: ptr = p...
from django.contrib import admin from .models import Causa from .models import Hallazgo from .models import Agrupador # Register your models here. admin.site.register(Causa) admin.site.register(Hallazgo) admin.site.register(Agrupador)
from django import forms from django.forms import ModelForm from .models import Lesson class LessonForm(forms.ModelForm): class Meta: model = Lesson fields = ('name', 'time', 'image') widgets = { 'time':forms.TextInput(attrs={'type':'datetime-local'}), }
import unittest from repository.task import TaskRepository from dao.database import Database from model.project import Project from model.task import Task from model.user import User class Test(unittest.TestCase): def setUp(self): self.repo = TaskRepository(Database()) def tearDown(self): ...
import struct import time import heapq import re import socket import requests import json from enum import Enum from hashlib import md5 from error import * from urllib import parse from collections import deque import uuid import math #小型日志系统 class Log(object): #level 0: 直接输出(默认) #level 1或其他: 输出至文件,后面需要跟文件名 ...
# Generated by Django 3.0.5 on 2020-08-19 19:20 from django.db import migrations, models class Migration(migrations.Migration): dependencies = [ ('csp_observer', '0005_auto_20200819_1908'), ] operations = [ migrations.AlterField( model_name='csprule', name='cause...
#!/usr/bin/env python3 # -*- coding: utf-8 -*- ############################################################################### # LingTime Copyright (C) 2012 suizokukan # Contact: suizokukan _A.T._ orange dot fr # # This file is part of LingTime. # LingTime is free software: you can redistribute it and/or mo...
# simple example for a neural net # taken and tested from # https://dev.to/shamdasani/build-a-flexible-neural-network-with-backpropagation-in-python from neural_net import NeuralNet import numpy as np def sigmoid(x): return 1 / (1 + exp(-x)) def sigmoid_derivate(x): return sigmoid(x) * (1-sigmoid(x)) x...
# -*- coding: utf-8 -*- # Generated by Django 1.9.6 on 2016-05-23 00:37 from __future__ import unicode_literals from django.db import migrations, models import django.db.models.deletion class Migration(migrations.Migration): initial = True dependencies = [ ] operations = [ migrations.Creat...
with keyboard.Listener(on_press=on_press, on_release=on_release) as listener: listener.join()
from random import randint board = [] minOfSize = 2 maxOfSize = 6 numberOfChoice = 2 sizeOfBoard = randint(minOfSize, maxOfSize) for i in range(sizeOfBoard): board.append(["O"] * sizeOfBoard) def print_board(matrix): for row in matrix: print "" print "", " ".join(row) ship_row =...
# Generated by Django 2.2.12 on 2020-04-25 11:33 from django.db import migrations, models import django.db.models.deletion import src.incidents.models import uuid class Migration(migrations.Migration): dependencies = [ ('incidents', '0042_auto_20200415_1504'), ] operations = [ migration...
# -------------------------------------------------------------------- import os import pickle import shelve # -------------------------------------------------------------------- with open ("input.txt", "r") as inp: # The with construct makes sure the file is closed automatically at the end of the with-block fo...
# Copyright 2018 Nicholas Li # # 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, ...
# Standard imports import requests as r from bs4 import BeautifulSoup as soup import pandas as pd # Scrape Mars news headline and teaser copy. def marsNasaNewsScrape(): marsNasaUrl = 'https://mars.nasa.gov/news/' marsNasaUrlData = r.get(marsNasaUrl) marsNasaUrlSoup = soup(marsNasaUrlData.text, 'html.pars...
from django.shortcuts import render, redirect, get_object_or_404 from django.contrib.auth.decorators import login_required from django.utils.decorators import method_decorator from django.contrib import messages from . forms import TermForm, ReportForm, ActivityForm, StrandForm, SubStrandForm, ObjectiveForm, Assessmen...
import re import requests from google_play_scraper import app def _guess_store(appid): """ Return either 'AppStore' or 'PlayStore' based on the string pattern if string pattern conforms to a known pattern. """ if re.fullmatch(r"^id(\d){8,}$", appid): return "AppStore" elif re.fullmatc...
from app import db, Artist, Artist_Genre import sys # Add artist data groban = Artist( name='Groban', city='New York', state='NY', phone='212-121-3940', website='www.groban.com', image_link='www.groban.com/img', facebook_link='www.facebook.com/groban' ) groban_genre1 = Artist_Genre(genre='rock') groban_...
#%% import math verbose = False def printAngleRadians(name, angleToPrint, isRadians = True): toPrint = angleToPrint if (verbose): if(isRadians): toPrint = math.degrees(angleToPrint) print(name + str( toPrint)) return toPrint #%% # sSA & ASs # law of sines def calculateSer...
#encoding:utf-8 import datetime import csv import logging from multiprocessing import Process import yaml from croniter import croniter from supplier import supply logger = logging.getLogger(__name__) def read_own_cron(own_cron_filename, config): with open(own_cron_filename) as tsv_file: tsv_reader =...
from .models import Task import logging logger = logging.getLogger(__name__) def getTasksCategorized(tasks): """ getTasksCategorized(tasks) gets a queryset and returns a `dict` containing keys which are `group name` and values are that group's tasks """ groups = Task.Groups.choices ...
from .base import * from decouple import config # SECURITY WARNING: keep the secret key used in production secret! SECRET_KEY = config('SECRET_KEY') DEBUG = False ALLOWED_HOSTS = ['*', ] DATABASES = { 'default': { 'ENGINE': 'django.db.backends.postgresql_psycopg2', 'NAME': config('NAME'), ...
# Create your views here. from django.core.exceptions import ObjectDoesNotExist from django.shortcuts import render,get_object_or_404,redirect from django.template import RequestContext from .constants import RUN_URL, secret from .models import Pen from .forms import CodeBoxRun import requests def home(request): ...
#!/usr/bin/env python # encoding: utf-8 from setuptools import setup from numpy.distutils.core import setup, Extension setup( name='CCBlade', version='1.1.1', description='Blade element momentum aerodynamics for wind turbines', author='S. Andrew Ning', author_email='andrew.ning@nrel.gov', pa...
""" __version__.py ~~~~~~~~~~~~~~ Information about the current version of the mamp-cli package. """ __title__ = 'mamp_cli' __description__ = 'mamp_cli - command line tools for MAMP and WordPress' __version__ = '0.1.0' __author__ = 'Arash Bahrami' __author_email__ = 'arash.b7@gmail.com' __license__ = 'MIT' __url__ = ...
N = int (input ()) R = [] x = 0 for i in range (N): x += sum (list (map (int, input ().split ()))) print (x // 2)
#from fuzzywuzzy import fuzz #from fuzzywuzzy import process
#!/usr/bin/python -tt ''' Created on Nov 21, 2012 @author: niklas ''' import re import bbClasses def convertScore(bdscore): return str(int(bdscore) * 10) def getOrientationInfo(orientation): ## Orientation is: <no_reads><pos_strand><no_reads><neg_strand>. E.g. 12+12- ori_parts = re.search(r'(\d+)(\+)(\...
class Solution: def threeSum(self, nums): """ :type nums: List[int] :rtype: List[List[int]] """ ans = [] if(len(nums)<3): return ans nums.sort() for i in range(len(nums)-2): if i==0 or nums[i]>nums[i-1]: head = i...
from time import sleep from utils.decorators import logger_doc from pages.app.ios.basePage import basePage class MainPage(basePage): """网易云主页类""" @logger_doc() def my(self): """主页-我的""" return self.poco("我的").click()
str1='\u4f60' str2 = str1.encode() str3 = str2.decode() print(str3)
from manuf import manuf import ipaddress class Device: MAC = "" IP = "" Manufacturer = "" class Filter: __profile_device = Device() __device_list = [] def __init__(self, cap, cap_sum): self.cap = cap self.cap_sum = cap_sum def create_device_list(self): device_li...
import sys import getopt import csv import GA import PGA import random from tester import Tester def main(): pga = False try: opts, args = getopt.getopt(sys.argv[1:],'p:m:n:l:c:r:') except getopt.GetoptError as err: print(str(err)) help() sys.exit(1) pga = "False" ...
import sys import random from datetime import datetime, timedelta TIME_FORMAT = '%Y-%m-%d %H:%M:%S' ''' here you can change the time period of wind's velocities generation and the start time's wind velocity ''' CURRENT_TIME = datetime.strptime('2021-05-23 00:30:00', TIME_FORMAT) # start time END_TIME = datetime.strp...
#! /usr/bin/python # -*- encoding: utf-8 -*- from django.contrib import admin from models import * class TuitAdmin(admin.ModelAdmin): list_display = 'texto', 'usuario' list_filter = ('usuario', ) admin.site.register(Tuit, TuitAdmin)
import os import sys import numpy as np # add BADE_DIR to path BASE_DIR = os.path.dirname(os.path.abspath(__file__)) sys.path.append(BASE_DIR) """ Generate meta-training and meta-testing data """ from experiments.data_sim import SinusoidDataset random_state = np.random.RandomState(26) task_environment = SinusoidDa...
# Copyright 2017 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. import array import difflib import distutils.dir_util import filecmp import functools import operator import os import re import shutil import struct import ...
from _mandatory_requirement import MandatoryRequirement class SmokeServiceIffAgreementHasSmokeDetectors(MandatoryRequirement): def check(self): if self.total_quantities['WSMOKE'] > 0 and not self.total_quantities['SMOKE']: self.add_mandatory_product('SMOKE', 1)
def sum(x, y = 10): return x + y # 20 print(sum(10)) # 30 print(sum(10,20)) def var_sum(*args): sum = 0 for e in args: sum += e return sum # 60 print(var_sum(10, 20, 30))
from unittest.mock import patch from django.core. management import call_command from django.db.utils import OperationalError from django.test import TestCase class CommandTests(TestCase): def test_wait_for_db_ready(self): """Test waiting for db to be available""" with patch("django.db.utils.Con...
from django.conf.urls import patterns, include, url from django.views.generic import TemplateView from django.views.decorators.http import require_POST from django.contrib.auth.decorators import login_required from apps.client.decorators import sn_required, snlogin_required urlpatterns = patterns('', (r'^friendLis...
""" 文件的信息处理 """ f = open("D:/test/笔记.txt","r") #查看文件编码 print(f.encoding) #查看文件名 print(f.name) #查看文件是否关闭,如果文件已经关闭,返回True,否则返回False print(f.closed) #查看文件的读写权限 print(f.mode)
""" SGD optimizer class Siddharth Sigtia Feb,2014 C4DM """ import numpy, sys import theano import theano.tensor as T import cPickle import os from theano.compat.python2x import OrderedDict import copy import pdb class SGD_Optimizer(): def __init__(self,params,inputs,costs,updates_old=None,consider_constant=[],mo...
from __future__ import (division, print_function) from WMCore.REST.HeartbeatMonitorBase import HeartbeatMonitorBase from WMCore.WorkQueue.WorkQueue import globalQueue class HeartbeatMonitor(HeartbeatMonitorBase): def addAdditionalMonitorReport(self, config): """ Collect some statistics for Global ...
rate=int(input('Enter in your rate:')) years=int(input('Enter in the amount of years:')) mi=int(input('Enter in your monthly investment:')) periods=years*12 percent=rate/100 mr=rate/(1200) fv=mi*(((1+mr)**(periods))-1)/(mr) print('input annual rate without % sign:', rate) print('Your monthly rate is', mr) print('input ...
from pathlib import Path from pie import * from pie_docker import * from pie_docker_compose import * from pie_env_ext import * from .utils import requires_compose_project_name ROOT_DIR = Path('.').absolute() ENV_DIR = ROOT_DIR/'docker' DOCKER_COMPOSE = DockerCompose(ROOT_DIR/'docker/shared_db.docker-compose.yml') ...
if __name__ == "__main__": from function import sum print(sum(7,8))
#/usr/bin/env python3 import argparse from http import server as httpserver class TestingRequestHandler(httpserver.SimpleHTTPRequestHandler): def translate_path(self, path): if not path.startswith("/static/"): if path == "/": path = "/global" path = "/out" + path ...
# -*- coding: utf-8 -*- """ Created on Thu May 08 11:38:05 2014 @author: amaccione Utility functions """ import numpy as np # sampling frequency (to be set or by default 7022) sampFreq = 7022 ### function to convert sec to frames def SToF(sec): ''' converts [s] to frame sec: the sec to be con...
from pystae import *
import requests from bs4 import BeautifulSoup as bs import re url ="https://www.coupang.com/np/search?q=%EC%97%90%EC%96%B4%ED%8C%9F&channel=recent" headers = {"User-Agent":"Mozilla/5.0 (Macintosh; Intel Mac OS X 10_15_5) AppleWebKit/537.36 (KHTML, like Gecko) Chrome/85.0.4183.102 Safari/537.36" } res = requests.get(...
from .db import db from app.models import User, Chef from datetime import datetime class Appointment(db.Model): __tablename__ = 'appointments' id = db.Column(db.Integer, primary_key=True) user_id = db.Column(db.Integer, db.ForeignKey('users.id'), nullable=False) chef_id = db.Column(db.Integer, db.Fore...
import torch from torch.utils.data import Dataset, DataLoader import numpy as np import os import random import sys class MyDataset(Dataset): def __init__(self, filename): #Initialize epoch_len #Identify where the data is, and store as object variable self.df = np.genfromtxt(filename, delim...
import copy import os from box import Box C = Box() # misc options C.auto_lr_find = True C.checkpoint = Box() C.checkpoint.name = '{epoch}-{val_loss:.2f}-{val_dice:.2f}' C.checkpoint.monitor = 'val_loss' C.checkpoint.monitor_mode = 'max' C.early_stopping = Box() C.early_stopping.min_delta = 0.1 C.early_stopping.pa...
from flask_wtf import FlaskForm from wtforms import StringField, BooleanField, SubmitField, PasswordField from wtforms.validators import DataRequired
r""" ############################################################################### :mod:`OpenPNM.Network`: Classes related the creation of network topology ############################################################################### Contents -------- **GenericNetwork** -- Contains many methods ` for working with ...
#!/usr/bin/env python """ File: model_trainer.py Date: 11/17/18 Author: Jon Deaton (jdeaton@stanford.edu) """ import os, sys import logging, argparse import datetime import tensorflow as tf from deep_model.config import Configuration from deep_model.params import Params from deep_model.ops import f1 class ModelTra...
# -*- coding: utf-8 -*- # Generated by Django 1.11.5 on 2017-11-09 15:24 from __future__ import unicode_literals from django.db import migrations, models import django.db.models.deletion class Migration(migrations.Migration): dependencies = [ ('carto', '0039_auto_20171109_1616'), ] operations =...
import numpy as np import subprocess as sp import cv2 cap = cv2.VideoCapture("toystory.mp4") width = cap.get(cv2.CAP_PROP_FRAME_WIDTH) height = cap.get(cv2.CAP_PROP_FRAME_HEIGHT) fps = cap.get(cv2.CAP_PROP_FPS) print(width, height, fps) #url = 'rtmp://localhost:1935/dash/live' #command = 'ffmpeg -i - -vcodec libx264 ...
from itertools import combinations_with_replacement a = input().split() s = ''.join(sorted(a[0])) res = list(combinations_with_replacement(s, int(a[1]))) for i in res: print(''.join(i))
def test_primary(): assert prime_factor(0) == [] assert prime_factor(1) == [] assert prime_factor(2) == [2] assert prime_factor(3) == [3] assert prime_factor(4) == [2,2] assert prime_factor(5) == [5] def prime_factor(input): if input < 2 : return [] elif input >= 2 : fa...
import numpy as np import tensorflow as tf from tensorflow.keras.layers import Input from lib.gcn import GraphConv, TemporalConv from lib.graph import Graph skeleton = Graph("sbu", "spatial") input_features = Input([30, skeleton.num_node, 3], dtype="float32") x = tf.keras.layers.Conv2D(64 * 3, (3, 1), padding="same")...
class Solution(object): def isAnagram(self, s, t): if len(s) != len(t): return False words = [0] * 256 for ch in s: words[ord(ch) - ord('a')] += 1 for ch in t: words[ord(ch) - ord('a')] -= 1 if any(words): return False return True
from contextlib import contextmanager import tensorflow as tf import numpy as np import os import shutil from tensorflow.contrib.layers import xavier_initializer def affine_layer(inputs, out_dim, name = 'affine_layer'): in_dim=inputs.get_shape().as_list()[1] with tf.variable_scope(name): init = tf.rand...
import datetime from flask import request, jsonify, make_response from flask_restful import Resource from flask_jwt_extended import (create_access_token, create_refresh_token, jwt_required, set_access_cookies, ...
import brickpi import time interface=brickpi.Interface() interface.initialize() motor = 2 speed = 0.5 interface.motorEnable(motor) touch_port = 0 interface.sensorEnable(0, brickpi.SensorType.SENSOR_TOUCH) motorParams = interface.MotorAngleControllerParameters() motorParams.maxRotationAcceleration = 0.7 motorParams....
def add(user_entry, email_entry, password_entry, list_user, list_email, list_password): u = user_entry.text() e = email_entry.text() p = password_entry.text() f = open("emails.txt", "a") f.write(u) f.write(",") f.write(e) f.write(",") f.write(p) f.write(",\n") ...
word = "plamen" print(word[-1:2:-1]) print(word[:3])
# Escribir un programa que pregunte el nombre del usuario en la consola y después de que el usuario # lo introduzca muestre por pantalla <NOMBRE> tiene <n> letras, donde <NOMBRE> es el nombre de usuario # en mayúsculas y <n> es el número de letras que tienen el nombre. def run(): nombre = input("Escribe tu nombre:...
from util import * import data_handling from funcs import cluster, misc, models def parse_arguments(args): """Takes in command line arguments and outputs them as a dictionary. The main argument or "command" is handled by the parser, all subsequent argument are passed to the corresponding subparser. ...
import socket import threading import os import datetime print('') family = socket.AF_INET protocol = socket.SOCK_DGRAM socket1 = socket.socket(family , protocol) server_ip1 = input('enter your ip : ') server_port1 = int(input('enter your port number : ')) socket1.bind((server_ip1 , server_port1)) socket2 = socket....
# encoding:utf-8 ''' Created on 2015-6-8 @author: jianfeizhang ''' ''' car run in road 'you can use extends implement below' taxi run in road bus run in road 'you should use bridge design pattern' taxi run in street bus run in highway ''' import sys class Car: def __init__(self): self.road = None ...
lista = [1, 2, 3, 4, 5] tupla = ("viernes", "sabado", "domingo") diccionario = {'nombre': "computacion", 'edad': 20} print(lista) lista.extend([6, 7, 8, 9]) print(lista) print(tupla) print(diccionario['nombre']) diccionario['pelicula'] = "mi pobre angelito" print(diccionario)