text stringlengths 8 6.05M |
|---|
import random
secret=random.randint(1,10)
print('---------我爱鱼c工作室-----------------')
temp=input("不妨猜一下小甲鱼现在心里想的是哪个数字:")
guess=int(temp)
i=1
while guess!=secret and i<=2:
temp=input("哎呀,猜错了,重新输入:")
guess=int(temp)
if guess ==secret:
print("我艹,你是小甲鱼心里的蛔虫吗?")
print("哼,猜中了也没有奖励!")
else:
... |
from smtplib import SMTPDataError
from django.conf import settings
from django.db import IntegrityError
from django.core.mail import get_connection
from celery.task import task
from .models import Blacklist, MessageLog
CONFIG = getattr(settings, 'CELERY_EMAIL_TASK_CONFIG', {})
BACKEND = getattr(settings, 'CELERY_E... |
#!/usr/bin/env python
# -*- coding:utf-8 -*-
print('---------------字符串常量的各种形式!---------------\n')
s = 'spa''m'
print('单引号\'spa\'\'m\':\n\t', s)
print('相连的两个字符串会自动合并!\n')
s = "spa'm"
print('双引号"spa\'m":\n\t', s)
print('单双引号复用,可以在单引号内加双引号,或者双引号内加单引号!\n')
s = '''spam'''
print("三引号'''spam''':\n\t", s)
print('三引号可以直接打出多行... |
import json
import os
import requests
baseUrl = "https://www.lingq.com/api/"
def get_token():
token_url = baseUrl + "api-token-auth/"
username = os.environ['USER']
password = os.environ['PASS']
payload = {'username': username, 'password': password}
r = requests.post(token_url, data=payload)
... |
#添加项目
import requests
from api.login.login import LogIn
host = "http://192.168.10.121:8088"
header = {"Content-Type":"application/x-www-form-urlencoded; charset=UTF-8"}
class AddProject:
def __init__(self,s=requests.session()):
self.s=s
def addProject(self,name="项目2",aliasname="项目02"):
url = ... |
# 对每一个点都用dijkstra
class Solution:
def findTheCity(self, n: int, edges: List[List[int]], distanceThreshold: int) -> int:
g = [[] for _ in range(n)]
for x, y, w in edges:
g[x].append((y, w))
g[y].append((x, w))
res, minn = -1, 105
def dijkstra(g:List[List[tupl... |
#!/usr/bin/env python
# -*- coding: utf-8 -*-
__author__ = 'lian'
__email__ = "liantian@188.com"
# Stdlib imports
import time
# Core Django imports
from django.views.generic.base import View
from django.shortcuts import render_to_response
from django.template import RequestContext
from django.http import HttpRespons... |
import random
game_board_list = [1, 2, 3, 4, 5, 6, 7, 8, 9, 10, 11, 12, 13, 14, 15, 16]
empty_game_board_list = []
for i in range(0, len(game_board_list)):
empty_game_board_list.append("*")
def print_board():
print("{} {} {} {}".format(game_board_list[0], game_board_list[1], game_board_list[2], game_board... |
#!/usr/bin/env python2
import os
import ConfigParser
import time
from time import gmtime, strftime, sleep
import subprocess
import readline
class color:
HEADER = '\033[95m'
IMPORTANT = '\33[35m'
NOTICE = '\033[33m'
OKBLUE = '\033[94m'
OKGREEN = '\033[92m'
WARNING = '\033[93m'
RED = '\033[91... |
# Copyright 2022 Pants project contributors (see CONTRIBUTORS.md).
# Licensed under the Apache License, Version 2.0 (see LICENSE).
from pants.backend.build_files.fmt.base import FmtBuildFilesRequest
from pants.backend.build_files.fmt.buildifier.subsystem import Buildifier
from pants.core.goals.fmt import FmtResult
fro... |
# Generated by Django 2.2.5 on 2019-09-15 18:00
from django.db import migrations, models
import django.db.models.deletion
class Migration(migrations.Migration):
dependencies = [
('boards', '0009_auto_20190915_2358'),
]
operations = [
migrations.RemoveField(
model_name='done'... |
##this code can realize the function to extract doc_vector from doc in phrase and word
from __future__ import print_function
import numpy as np
import sys
import re
#build concept bag
conceptbag={'functions': 1, 'linear alegbra': 2, 'vector': 3, 'machine learning': 4, 'differential equations': 5}
#build the model o... |
#!/usr/bin/env python
from __future__ import print_function
import numpy as np
from training import *
#score function
def score(Xag,W):
"""Input:
Xag : augmented numpy array of features
W : aumented coefficients
the bias coefficients correspond to the last row of the matrix W
Output:
out : numpy array of scores... |
from abc import ABCMeta, abstractmethod
from threading import Thread
class Scraper(Thread):
__metaclass__ = ABCMeta
TYPE = None
@abstractmethod
def get(self): pass
@abstractmethod
def run(self): pass
|
from __future__ import division, print_function
import time
import matplotlib.pyplot as plt
import numpy as np
import os
from keras.models import Model, Sequential
from keras.layers import Activation, Dense, Flatten, BatchNormalization, Dropout, Input, Reshape, multiply
from keras.layers import Embedding, ZeroPadding2... |
# This handles the TTYPE request per the MTTS spec (https://tintin.sourceforge.io/protocols/mtts/)
MTTS = chr(24) # terminal type
IAC = chr(255) # "Interpret As Command"
SE = chr(240) # Subnegotiation End
SB = chr(250) # Subnegotiation Begin
# Our bitvector for MTTS:
# 1 "ANSI" Client supports... |
import win32com.client
import os
import time
while True:
qinfo=win32com.client.Dispatch("MSMQ.MSMQQueueInfo")
computer_name = os.getenv('COMPUTERNAME')
qinfo.FormatName="direct=os:"+computer_name+"\\PRIVATE$\\save-deleted"
queue=qinfo.Open(1,0)
msg=queue.Receive()
print("-----------------... |
from csv import DictReader
import re
import json
from os import path
CONFIG_FILENAME = "config.json"
#loading config data
def load_config(filename):
try:
config = open(filename,encoding='utf-8')
return json.load(config)
except:
print("your config file is malformed")
def wrap_tag(conte... |
import datetime
from configparser import ConfigParser
from typing import List
from common.models.Event import Event
from common.utils.CommonEventUtils import CommonEventUtils
class MedalEventUtils(CommonEventUtils):
events: List[Event] = []
def __init__(self, config: ConfigParser):
startString = co... |
from keras.applications import DenseNet121
from keras.models import Sequential
from keras.layers import Dense, Conv2D, Flatten
from keras import layers
from keras.optimizers import Adam
def build_model():
densenet = DenseNet121(
weights='DenseNet-BC-121-32-no-top.h5',
include_top=False,
input_shape=(2... |
import ctypes
def make_msg_box_popup():
# create msg_box
MessageBox = ctypes.windll.user32.MessageBoxW
title = 'If this message box appears, the program has worked'
msg = 'This works fine when running as a .py file and when built with pyinstaller in Python 3.7, but when trying to run this on anoth... |
# -*- coding: utf-8 -*-
import pytest
from .conftest import TEST_UPSTREAM_CONFIG
from jussi.request import JussiJSONRPCRequest
from jussi.validators import is_get_block_header_request
from jussi.validators import is_get_block_request
from jussi.validators import is_valid_get_block_response
from jussi.validators import... |
# Copyright (C) 2014-2016 Cuckoo Foundation.
# This file is part of Cuckoo Sandbox - http://www.cuckoosandbox.org
# See the file 'docs/LICENSE' for copying permission.
# Originally contributed by Check Point Software Technologies, Ltd.
import math
import filecmp
try:
import ImageChops
from PIL import Image
... |
import networks
import torch
import os
import numpy as np
import utils
from collections import OrderedDict
from torch.autograd import Variable
class Pix2PixModel:
def name(self):
return 'Pix2PixModel'
def initialize(self, opt):
self.opt = opt
self.gpu_ids = opt.gpu_ids
self.i... |
import serial
import time
def init_serial():
CONUM = 1
global ser
ser = serial.Serial()
ser.baudrate = 115200
ser.port = "/dev/ttyUSB0"
ser.timeout = 10
ser.open()
if ser.isOpen():
print ('Open: ' + ser.portstr)
def set_mode(mode):
if (mode == 0):
sent = bytes([7])
... |
a = 10.0
b = 3
c = a//b # floor division
print(c, type(c)) |
import numpy as np
import matplotlib.pyplot as plt
import pandas as pd
from sklearn.model_selection import train_test_split
class LogisticRegression(object):
def __init__(self, learning_rate=.01, coverage_change=.001, max_steps=10**3):
self.__learning_rate = learning_rate
self.__coverage_change = ... |
from socket import *
from json import
class Personnage(object):
def __init__(self, pseudo, serveur, connexion):
self.estVivant = True
self.estProtege = False
self.estMaire = False
self.accesChat = 1
self.pseudo = pseudo
self.connexion = serveur
def tuer(self):... |
from bokeh.plotting import figure, output_file, show
from bokeh.layouts import column, grid
from bokeh.models import Band, ColumnDataSource
def plot_ideal_functions(ideal_functions, file_name):
"""
Plots all ideal functions
:param ideal_functions: list of ideal functions
:param file_name: the name the... |
class Flow(object):
name='Flow'
rate = 0.0
def __init__(self, name=None, rate=0):
self.name = name
self.rate = rate
### placeholder to recompute rate when needed
def update_rate(self):
return(self.rate)
def step(self):
return(self.rate)
class LinearEQFlow(Flow):
dependencies = {}
def update_rat... |
import sys
import os.path
import katcp_wrapper
roach_board, ext = os.path.splitext(os.path.basename(sys.argv[0]))
fpga = katcp_wrapper.FpgaClient(roach_board)
fpga.is_connected()
|
# -*- coding: utf-8 -*-
import json
import requests
from lxml import etree
from threading import Timer
vsite_api = "https://www.v2ex.com/?tab=hot"
bsite_api = 'https://www.bilibili.com/ranking/all/0/0/1'
weibo_api = "https://s.weibo.com/top/summary?cate=realtimehot"
tieba_api = "http://tieba.baidu.com/hotto... |
# code mostley based on "Complex Momentum for Optimization in Games"
import numpy as np
import matplotlib.pyplot as plt
from scipy.stats import norm
import matplotlib as mpl
from tqdm import tqdm
def get_spectral_radius(g, eta, beta, is_eg=False, is_eg_and_cm=False,
is_og=False):
if is_eg:... |
def findFirstDifferentCharacter(firstSenctence, secondSentence):
minimum = min(len(firstSenctence), len(secondSentence))
for x in range(minimum):
if firstSenctence[x] != secondSentence[x]:
return x
return -1
firstSentence = input("Geef een string: ")
secondSentence = input("Geef een ... |
import pandas as pd
class Rock:
def __init__(self, id, name):
self.id = id
self.name = name
class Sensor:
def __init__(self, id, abbreviation):
self.id = id
self.abbreviation = abbreviation
class Experiment:
def __init__(self, dataset):
self.dataset = dataset
... |
import socket
import cevents
import json
import signal
import sys
import os
class IRCBot: #Main bot class
def __init__(self):
self.config = json.load(open("conf.json", "r"))
self.config = self.config['ircbot']
self.isquitting = False
self.parseline = ""
if self.config['ipv6'] == True:
self.ircsock = soc... |
'''
Processes data
'''
import torch
import numpy as np
import utils
import os.path as osp
import pdb
'''
Load subsampled genetics data.
'''
def clean_genetics_data():
data = np.loadtxt(osp.join(utils.data_dir, 'ALL.20k.data'), delimiter=' ')
col_sums = np.sum((data==0).astype(np.int), axis=0)
#remove ... |
# -*- coding: utf-8 -*-
"""
Created on Sun Mar 12 11:04:28 2017
@author: Administrator
"""
def sum_list(list1):
t=sum(i for i in list1)
return t
a=eval(input())
b=list(a)
c=sum_list(b)
print(c) |
import bz2
import json
def make_stream(data):
"""
given some data in python, return an in-memory
buffer of that data that has been zipped
"""
raw_data = json.dumps(data)
b = bytes(raw_data, 'utf-8')
compressed = bz2.compress(b)
return compressed
def decompress(data):
"""
give... |
# hash表
class Solution:
def longestSubsequence(self, arr: List[int], difference: int) -> int:
hashmap = defaultdict(int)
n = len(arr)
res = 0
for i in range(n):
hashmap[arr[i]] = hashmap[arr[i] - difference] + 1
res = max(hashmap[arr[i]], res)
return... |
# Copyright 2019 The TensorFlow Hub Authors. All Rights Reserved.
#
# 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 app... |
# Generated by Django 2.2.4 on 2019-09-27 19:30
from django.db import migrations
class Migration(migrations.Migration):
dependencies = [
('job', '0020_auto_20190925_0440'),
]
operations = [
migrations.RenameField(
model_name='jobopening',
old_name='job_summary',
... |
"""
An implementation of the divided difference algorithm.
Function divided_difference:
Given a scalar function and list of knots, then it give the output of the
divided difference algorithm; useful for such applications as
interpolation.
"""
import logging
from typing import Callable
import numpy as np
... |
import glob
import os
import shutil
from invoke import task
import disba
@task
def build(c):
shutil.rmtree("dist", ignore_errors=True)
c.run("python -m build --sdist --wheel .")
@task
def tag(c):
c.run("git tag v{}".format(disba.__version__))
c.run("git push --tags")
@task
def upload(c):
c.r... |
'''
Created on Jan 20, 2016
@author: Andrei Padnevici
'''
import os
import sys
if len(sys.argv) > 1:
startFolder = sys.argv[1]
else:
startFolder = "c:/"
print(startFolder)
count = 0
for (dirname, dirs, files) in os.walk(startFolder):
for filename in files:
if filename.endswith(... |
import graphene
from architect.manager.models import Manager, Relationship, Resource
from graphene import Node
from graphene_django.filter import DjangoFilterConnectionField
from graphene_django.types import DjangoObjectType
class ManagerNode(DjangoObjectType):
class Meta:
model = Manager
interfa... |
import pyodbc
con=pyodbc.connect('Driver={SQL server};Server=DESKTOP-T66VEKU\SREENATHSQL;Database=master;')
cursor=con.cursor()
cursor.execute("insert into employee values(3,'sm'),(4,'hj')")
print("table succesfully")
|
"""
类别:词-宋-作者
"""
import sqlite3
import os
import json
def make_db(db, path):
sql = '''
CREATE TABLE IF NOT EXISTS "ci_song_author" (
"id" INTEGER NOT NULL,
"name" TEXT,
"desc" TEXT,
"short_desc" TEXT,
PRIMARY KEY ("id")
);
'''
print('\r\n词-宋-作者 正在初始化...')
try:
conn = sqlite3.connect(db)
... |
# -*- coding: utf-8 -*-
row1= {"name": "a1","age": 18, "salary":30000,"city":"beijing"}
row2= {"name": "a2","age": 19, "salary":20000,"city":"shanghai"}
row3= {"name": "a3","age": 20, "salary":10000,"city":"shengzheng"}
tb = [row1,row2,row3]
#获得第二行的人薪资
print('第二行人的薪资是:{0}'.format(tb[1].get("salary")))
#打印表中所有的薪资
for... |
class Solution(object):
def isAdditiveNumber(self, num):
"""
:type num: str
:rtype: bool
"""
# 确定起始位置
# if len(num) < 3:
# return False
# l = int((len(num) - 1)/2) + 1
# for i in range(1, l):
# if num[0] == '0' and i > 1:
... |
import random
import os
import os.path as path
import PIL
from PIL import ImageFilter
import src.CNR.cnr as cnr
import src.basic_correct.b_scan as bc
import numpy as np
import pdb
import matplotlib.pyplot as plt
# SANITY CHECK: blur and add noise to image and see CNR reduced
def test_CNR_computation():
data_dir =... |
from kitty.models import Kitty, KittyUser, UserItem
from django.http import HttpResponse
from django.core import serializers
from django.utils import simplejson
from django.forms.models import model_to_dict
from kitty import ajax
def kitty(request, id):
k = Kitty.objects.get(id=id)
k_json = {
"kittyId"... |
import _plotly_utils.basevalidators
class Mesh3dsValidator(_plotly_utils.basevalidators.CompoundArrayValidator):
def __init__(
self,
plotly_name='mesh3d',
parent_name='layout.template.data',
**kwargs
):
super(Mesh3dsValidator, self).__init__(
plotly_name=pl... |
# Generated by Django 2.2.4 on 2019-09-06 15:37
from django.db import migrations
class Migration(migrations.Migration):
dependencies = [
('webapp', '0003_auto_20190906_2001'),
]
operations = [
migrations.RenameModel(
old_name='bsc_chem',
new_name='Chem',
... |
../XIASocket/API/python/xsocket.py |
# Generated by Django 2.1.7 on 2019-02-12 12:55
from django.db import migrations, models
class Migration(migrations.Migration):
initial = True
dependencies = [
]
operations = [
migrations.CreateModel(
name='Author',
fields=[
('id', models.AutoField(a... |
import re
def format_state(state):
change = 0
while state[0] == '.':
state.pop(0)
change -= 1
while state[-1] == '.':
state.pop(-1)
state = list('....') + state + list('....')
change += 4
return state, change
def calc_sum(state, extra):
return sum(i - extra for i... |
from django.db import models
# Create your models here.
class IssueRecord(models.Model):
project_name = models.CharField("工程名", max_length=100)
issue_content = models.CharField("发布内容",max_length=500,null=True)
issue_time = models.DateTimeField(null=True)
dev_person = models.CharField("开发人员",max_lengt... |
def soln(N):
num = []
while N > 0:
if (1<=N<=9):
num.append(N)
num.sort()
N = 0
number = int(''.join(map(str, num)))
else:
num.append(9)
N -= 9
return number
print(soln(22))
print(soln(100))
|
import binascii
english_freq = [
0.08167, 0.01492, 0.02782, 0.04253, 0.12702, 0.02228, 0.02015, # A-G
0.06094, 0.06966, 0.00153, 0.00772, 0.04025, 0.02406, 0.06749, # H-N
0.07507, 0.01929, 0.00095, 0.05987, 0.06327, 0.09056, 0.02758, # O-U
0.00978, 0.02360, 0.00150, 0.01974, 0.00074 ... |
# -*- coding: utf-8 -*-
from typing import List
class Solution:
def sortEvenOdd(self, nums: List[int]) -> List[int]:
nums[::2] = sorted(nums[::2])
nums[1::2] = sorted(nums[1::2], reverse=True)
return nums
if __name__ == "__main__":
solution = Solution()
assert [2, 3, 4, 1] == ... |
from django.contrib import admin
from .models import *
class ProductAdmin(admin.ModelAdmin):
list_display=['name','category','price_is']
prepopulated_fields = {"slug": ("name",)}
class CartAdmin(admin.ModelAdmin):
list_display=['item','user','created']
class OrderAdmin(admin.ModelAdmin):
list_displ... |
import json
from watson_developer_cloud import VisualRecognitionV3
# BEGIN of python-dotenv section
from os.path import join, dirname
from dotenv import load_dotenv
import os
dotenv_path = join(dirname(__file__), '.env')
load_dotenv(dotenv_path)
# END of python-dotenv section
##########################
### VISUAL R... |
def option_menu(window):
pass
|
#Ship blueprints
class shipBase(object):
def __init__(self):
self.name = ""
self.type = ""
self.health = 0
self.built = 0
self.buildtime = 0 |
# brute force algorithm, checking every number less than root of n if it's a factor of n or not
def trial_division(n):
factors = []
for i in range(2, int(pow(n, 0.5)) + 1):
while n % i == 0:
# if i is a factor of n , append it to the factors
factors.append(i)
# calcul... |
def main():
start = input("Please enter 1 for mathematical functions, or enter 2 for string operations: ")
if start == "1":
math = input("Please enter 1 for addition, 2 for subtraction, 3 for multiplication, or 4 for division: ")
if math == "1":
input1 = float(input("Please enter the... |
# Generated by Django 3.1.8 on 2021-04-15 11:08
from django.db import migrations, models
class Migration(migrations.Migration):
dependencies = [
('books', '0003_bookindexpage_bookslistingpage'),
]
operations = [
migrations.AlterField(
model_name='bookindexpage',
... |
from selenium import webdriver
from selenium.webdriver.common.action_chains import ActionChains
import time
browser = webdriver.Chrome()
# 访问百度
browser.get("http://www.baidu.com")
# 模拟用户点击登录按钮操作
# xx = browser.find_element_by_name('tj_login')
browser.get('https://passport.baidu.com/v2/?login&tpl=mn&u=http%3A%2F%2Fww... |
#!/usr/bin/env python
__author__ = 'Richard Lincoln'
""" Creates a single precision copy of JPOWER. """
import os
import sys
import shutil
import re
SRC_DIR = os.path.join(os.path.dirname(__file__), 'src')
BASE_PKG = 'edu.cornell.pserc.jpower'
D_SUBPKG = 'tdouble'
S_SUBPKG = 'tfloat'
D_PREFIX = 'D'
S_PREFIX = 'S'
D... |
import unittest
import json
from os import environ
from os import urandom
# Defer configs
environ['SBF_DEFER_CONFIG'] = "True"
environ['SBF_CELERY_BROKER'] = "localhost"
import slackbotframework
slackbotframework.app.config['DEBUG'] = True
slackbotframework.app.config['TESTING'] = True
slackbotframework.app.config[... |
from django.contrib import admin
from .models import (Hrr,
AaCalculations,
TimeHeartZones,
AaWorkoutCalculations,
AA,
TwentyfourHourAA,
TwentyfourHourTimeHeartZones,
AACustomRanges,
AAdashboard)
# Register your models here.
class HrrAdmin(admin.ModelAdmin):
list_display = ('use... |
from database.db import metadata
from resume.models import Resume
from user.models import User
|
import numpy as np
from Politician import Politician
from Party import Party
# This module is in my GitHub too: https://github.com/NestorRV/constrained_kmeans
from constrained_kmeans import constrained_kmeans
import copy
import sys
class IdeologyAlgorithm:
def __init__(self, n_parties, politicians, R, function, fu... |
import os, sys, requests, json, time, argparse
from datetime import datetime
from ouimeaux.environment import Environment
from ouimeaux.signals import statechange, receiver
parser = argparse.ArgumentParser()
parser.add_argument("-set", action = "store_true")
parser.add_argument("-isSub", action = "store_true")
parser.a... |
import string, sys, math
class Orbit:
def __init__(self, input):
self.orbit = {}
for line in input.split("\n"):
(objA, objB) = line.split(")")
if objA not in self.orbit:
self.orbit[objA] = Obj(objA)
if objB not in self.orbit:
self.... |
from mininet.topo import Topo
from itertools import product
CLIENTS = 3
class FatTree(Topo):
def __init__(self, levels=3, *args, **kwargs):
Topo.__init__(self, *args, **kwargs)
if levels < 1:
return
self.create_levels(levels, CLIENTS)
def create_levels(self, levels, clien... |
from django.http import HttpResponse
from django.shortcuts import render
# Create your views here.
def index( request ):
return HttpResponse( "Hello" )
def lalo( request ):
return HttpResponse( "Hola Lalo" )
def juan( request ):
return HttpResponse( 'Hola Juan' )
def pablo( request ):
return HttpRes... |
from django.contrib import admin
from django.contrib.admin.sites import site
from django.contrib.admin.widgets import ForeignKeyRawIdWidget, ManyToManyRawIdWidget
from django.urls import NoReverseMatch, reverse
from django.utils.safestring import mark_safe
class VerboseForeignKeyRawIdWidget(ForeignKeyRawIdWidget):
... |
''' James's Data & method
'''
import matplotlib.pyplot as plt
import numpy as np
import pandas as pd
file1=('MarchResults Sheet1.csv')
data = pd.read_csv(file1, skiprows=44)
Mode, Base, EOM, Beta, N=data.iloc[:,0], data.iloc[:,1],data.iloc[:,3],data.iloc[:,2],data.iloc[:,7]
print(N) |
import lists, re, copy,parsing
# Lists
from lists import healthySubstitutions as healthySubstitutions
##############################
##### HEALTHY TRANSFORMER ####
##############################
def healthyTransformer(recipe):
healthyRecipe = recipe
subbedIngs = {}
for ingredient in healthyRecipe.ingred... |
# -*- coding: utf-8 -*-
# Copyright (c) 2018 Novo Nordisk Foundation Center for Biosustainability,
# Technical University of Denmark.
#
# 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
#
# ... |
"""
Crea un programa que calcule la media de todos los elementos de una lista
"""
lista=[3, 4, 5 ,6, 12, 98, 4]
contador=0
suma=0
for item in lista:
contador+=1
suma+=item
resultado=suma/contador
print("La media es: {}".format(resultado))
|
def square(num):
return num ** num
def square_print(num):
score = num ** num
print(score)
square_print(3)
a = square(10) * 3
print(a) |
import numpy as np
import skimage.morphology as morth
class Morphology:
def __init__(self, person):
self.person = person
self.figures = self.person.figures
self.morph_figures = []
self.elem_x = 5
self.elem_y = 5
def morthing(self):
# selem = morth.rectangle(sel... |
# LEVEL 12
# http://www.pythonchallenge.com/pc/return/evil.html
import string
with open('data/evil2.gfx', 'rb') as f:
first_bytes = f.read(100)
# The picture shows someone dealing cards. It seems like each byte should be "dealt" to a different player (file) but we
# need to identify how many players are there.
n... |
import pymysql
from routes.passwords import host, username, password, db
def insert(programming_laungage,idea,by):
connection = pymysql.connect(host,username,password,db)
cursor = connection.cursor()
sql = "INSERT INTO ideas(programming_laungage,idea,by_person) VALUES(%s,%s,%s)"
try:
cursor.exec... |
#!/usr/bin/python
# -*- coding: utf-8 -*-
from subprocess import call, check_output
from sys import argv
from os import path
import syslog
from redmine import Redmine, exceptions as e
FILENAME = str(argv[0]).split('/')[len(str(argv[0]).split('/')) - 1]
APPLICATION_PATH = str(path.dirname(check_output(['readlink', '-e... |
#!/usr/bin/python
x,y = 2,8
if(x<y):
st="x is less then y"
else:
st="x is more then y"
print(st)
|
from user_input import prompt
# Messages to be imported for 'Oh Great Knight' locations
shmucksburg = ("Aye! The brigands robbed me again! What this village needs is a guardian!",
"Our armory is pitiful. Donations of weapons, shields and armor would help us defend ourselves.",
"What I... |
#!/usr/bin/env python
__version__ = "0.6"
__author__ = "xrado"
import sys,os,re,urllib2
## python 2.5 compatibility
version = int(''.join(str(x) for x in sys.version_info[:2]))
try:
if version < 26: import simplejson as json
else: import json
except:
print "need json module"
os._exit(1)
## Windows
if sys.platf... |
import time
import numpy as np
import neworder as no
from markov_chain import MarkovChain
import visualisation
# Logging and checking options
# no.verbose()
no.checked()
npeople = 100000
tmax = 100
dt = 1.0
# params of poisson process transitions (p=lambda.exp(-lambda.x) where lambda=1/mean)
mu_01 = 13.0
mu_02 = 23... |
#-*- coding: utf-8 -*-
### List of updates to settings.py tuples
### (to be applied by "update_settings" function below).
updates = dict(
INSTALLED_APPS = ['feedjack', 'feedjack_wp_export', 'djcelery'],
CELERY_IMPORTS = ['feedjack_wp_export.models'] )
## "south" app is not strictly required, unless you need migr... |
import os
import webbrowser
import sys
import interact.display as disp
from googlesearch import *
def _1_(arglen,command,com_arg,path,historydir,origin,func,var,browserPath,arg0,arg1,arg2,arg3,invalidnames,commandlist):
if command[0] not in arg1:
if command[0] in arg0:
prin... |
import pymongo
# 连接mongodb
mon = pymongo.MongoClient("mongodb://root:123456@192.168.211.118:27017")
# print(mon)
# 查询数据
# 指定数据库
mydb = mon["devops"]
# 指定集合collection
col = mydb["goods"]
# 查询所有数据
data = col.find()
# 遍历输出所有数据
for d in col.find():
print(type(d))
print(d)
|
#!/usr/bin/env python
#coding=utf-8
import ahocorasick
import pymongo
import jieba
import json
def get_collection(name):
conn = pymongo.Connection("localhost", 27017)
return conn["weibo"][name]
def run():
collection = get_collection("keywords")
textcollection = get_collection("text")
tree = ahoco... |
# -*- coding: utf-8 -*-
# @Time : 2018/8/27 23:04
# @File : auto_trader.py
import config
from easytrader import helpers
import easytrader
user = easytrader.use('ths')
user.connect(r'C:\Tool\gjzq\国金证券同花顺独立下单\xiadan.exe')
# user.prepare(user=config.username, password=config.password)
print('余额')
print(user.balance)
print... |
__author__ = 'Sanjay Narayana'
import numpy as np
from numpy import linalg as la
from k_means import KMeans
#from Test import k_means
np.random.seed(10)
class PCA(object):
def __init__(self):
print ("brooo")
self.number_of_principal_components = 2
def compute_principal_components(self):
... |
# Generated by Django 3.0.2 on 2020-01-25 19:08
from django.db import migrations, models
class Migration(migrations.Migration):
initial = True
dependencies = [
]
operations = [
migrations.CreateModel(
name='Task',
fields=[
('id', models.AutoField(aut... |
def hi(name):
print('Hi'+name+'!')
hi('Rachel') |
Subsets and Splits
No community queries yet
The top public SQL queries from the community will appear here once available.