diff --git a/asyncio/ccxt_async.py b/asyncio/ccxt_async.py new file mode 100644 index 0000000..d217141 --- /dev/null +++ b/asyncio/ccxt_async.py @@ -0,0 +1,34 @@ +# -*- coding: utf-8 -*- + +import asyncio +import functools +import os +import sys + +root = os.path.dirname(os.path.dirname(os.path.dirname(os.path.abspath(__file__)))) +sys.path.append(root + '/python') + +import ccxt.async_support as ccxt # noqa: E402 + + +async def print_ticker(symbol, id): + # verbose mode will show the order of execution to verify concurrency + exchange = getattr(ccxt, id)({'verbose': True}) + print(await exchange.fetch_ticker(symbol)) + await exchange.close() + + +if __name__ == '__main__': + + symbol = 'ETH/BTC' + print_ethbtc_ticker = functools.partial(print_ticker, symbol) + [asyncio.ensure_future(print_ethbtc_ticker(id)) for id in [ + 'bitfinex', + 'poloniex', + 'kraken', + 'bittrex', + 'hitbtc', + ]] + loop = asyncio.get_event_loop() + pending = asyncio.all_tasks(loop) + loop.run_until_complete(asyncio.gather(*pending)) \ No newline at end of file diff --git a/asyncio/multi_tasks.py b/asyncio/multi_tasks.py new file mode 100644 index 0000000..ee081f1 --- /dev/null +++ b/asyncio/multi_tasks.py @@ -0,0 +1,16 @@ +import asyncio +import time + +async def say_after(delay, what): + await asyncio.sleep(delay) + print(what) + +async def main(): + print(f"started at {time.strftime('%X')}") + + await say_after(1, 'hello') + await say_after(2, 'world') + + print(f"finished at {time.strftime('%X')}") + +asyncio.run(main()) diff --git a/asyncio/simple.py b/asyncio/simple.py new file mode 100644 index 0000000..675b564 --- /dev/null +++ b/asyncio/simple.py @@ -0,0 +1,8 @@ +import asyncio + +async def main(): + print('Hello ...') + await asyncio.sleep(1) + print('... World!') + +asyncio.run(main()) diff --git a/cffi/_simple_example.py b/cffi/_simple_example.py new file mode 100644 index 0000000..2689d2b --- /dev/null +++ b/cffi/_simple_example.py @@ -0,0 +1,8 @@ +# auto-generated file +import _cffi_backend + +ffi = _cffi_backend.FFI('_simple_example', + _version = 0x2601, + _types = b'\x00\x00\x04\x0D\x00\x00\x03\x03\x00\x00\x01\x0F\x00\x00\x02\x01\x00\x00\x07\x01', + _globals = (b'\x00\x00\x00\x23printf',0,), +) diff --git a/cffi/main.py b/cffi/main.py new file mode 100644 index 0000000..d7195d8 --- /dev/null +++ b/cffi/main.py @@ -0,0 +1,7 @@ +from _simple_example import ffi + +lib = ffi.dlopen(None) # Unix: open the standard C library +#import ctypes.util # or, try this on Windows: +#lib = ffi.dlopen(ctypes.util.find_library("c")) + +lib.printf(b"hi there, number %d\n", ffi.cast("int", 2)) diff --git a/cffi/simple_example_build.py b/cffi/simple_example_build.py new file mode 100644 index 0000000..b788ce1 --- /dev/null +++ b/cffi/simple_example_build.py @@ -0,0 +1,15 @@ +# file "simple_example_build.py" + +# Note: this particular example fails before version 1.0.2 +# because it combines variadic function and ABI level. + +from cffi import FFI + +ffi = FFI() +ffi.set_source("_simple_example", None) +ffi.cdef(""" + int printf(const char *format, ...); +""") + +if __name__ == "__main__": + ffi.compile() diff --git a/click/group.py b/click/group.py new file mode 100644 index 0000000..8790cf8 --- /dev/null +++ b/click/group.py @@ -0,0 +1,19 @@ +import click + +@click.group() +def cli(): + pass + +@click.command() +def initdb(): + click.echo('init db') + +@click.command() +def dropdb(): + click.echo('Droped the db') + +cli.add_command(initdb) +cli.add_command(dropdb) + +if __name__ == '__main__': + cli() diff --git a/click/pass_content.py b/click/pass_content.py new file mode 100644 index 0000000..21327da --- /dev/null +++ b/click/pass_content.py @@ -0,0 +1,16 @@ +import click + +@click.group() +@click.option('--debug/--no-debug', default=False) +@click.pass_context + +def cli(ctx, debug): + ctx.obj['DEBUG'] = debug + +@cli.command() +@click.pass_context +def sync(ctx): + click.echo('Debug is %s' % (ctx.obj['DEBUG'] and 'on' or 'off')) + +if __name__ == '__main__': + cli(obj={}) diff --git a/click/simple.py b/click/simple.py new file mode 100644 index 0000000..5bb3ce5 --- /dev/null +++ b/click/simple.py @@ -0,0 +1,12 @@ +import click + +@click.command() +@click.option('--count', default=1, help='Number of greetings.') +@click.option('--name', prompt='Your name', help='The person to greet.') +def hello(count, name): + """Simple program that greets NAME for a total of COUNT times.""" + for x in range(count): + click.echo('Hello %s!' % name) + +if __name__ == '__main__': + hello() diff --git a/duck_typing/polymorphism.py b/duck_typing/polymorphism.py new file mode 100644 index 0000000..e1f334f --- /dev/null +++ b/duck_typing/polymorphism.py @@ -0,0 +1,22 @@ +#!/usr/bin/env python + +class Duck: + def quack(self): + print "Quaaaaaack!" + +class Bird: + def quack(self): + print "bird imitate duck." + +class Doge: + def quack(self): + print "doge imitate duck." + +def in_the_forest(duck): + duck.quack() + +duck = Duck() +bird = Bird() +doge = Doge() +for x in [duck, bird, doge]: + in_the_forest(x) diff --git a/duck_typing/redirect_stdout.py b/duck_typing/redirect_stdout.py new file mode 100644 index 0000000..9cdb6d3 --- /dev/null +++ b/duck_typing/redirect_stdout.py @@ -0,0 +1,10 @@ +#!/usr/bin/env python +#coding=utf-8 + +import sys + +sys.stdout = open('stdout.log', 'a') # 只要是 file-like, 不管是什么类型 +print 'foo' + +sys.stdout = sys.__stdout__ # 恢复 +print 'bar' diff --git a/eval/eval_hello.py b/eval/eval_hello.py new file mode 100644 index 0000000..68a8bcb --- /dev/null +++ b/eval/eval_hello.py @@ -0,0 +1,27 @@ +#!/usr/bin/env python +# http://www.mojidong.com/python/2013/05/10/python-exec-eval/ + +a = 1 +print(eval("a + 1")) + +a = 1 +g = { + 'a': 10 +} +print(eval("a + 1", g)) + +a = 10 +b = 20 +c = 20 +g = { + 'a': 6, + 'b': 8 +} +l = { + 'b': 9, + 'c': 10 +} +print(eval("a+b+c", g, l)) + +print(eval('abs(a)',{'__builtins__':__builtins__, 'a':-1})) +# eval('abs(a)',{'__builtins__':None, 'a':-1}) diff --git a/excel/README.md b/excel/README.md new file mode 100644 index 0000000..f598327 --- /dev/null +++ b/excel/README.md @@ -0,0 +1,11 @@ +# excel + +## Install +* Use python3. +* `pip install -r requirements.txt` + +## Run +* `python xls2csv.py` + +## Docs +* diff --git a/excel/input.xls b/excel/input.xls new file mode 100644 index 0000000..1a07457 Binary files /dev/null and b/excel/input.xls differ diff --git a/excel/requirements.txt b/excel/requirements.txt new file mode 100644 index 0000000..4f1b83f --- /dev/null +++ b/excel/requirements.txt @@ -0,0 +1,2 @@ +xlrd +csv diff --git a/excel/xls2csv.py b/excel/xls2csv.py new file mode 100644 index 0000000..2f81a62 --- /dev/null +++ b/excel/xls2csv.py @@ -0,0 +1,22 @@ +# -*- coding: utf-8 -*- +#!/usr/bin/env python + +import csv, xlrd, os +from os import listdir +from os.path import isfile, join + +def xls_to_csv(xls_file): + wb = xlrd.open_workbook(xls_file) + for sheet in wb.sheet_names(): + sh = wb.sheet_by_name(sheet) + csv_file_name = os.path.splitext(xls_file)[0] + "_" + sheet + ".csv" + with open(csv_file_name, 'w', encoding='utf8') as file: + wr = csv.writer(file, quoting=csv.QUOTE_ALL) + for rownum in range(sh.nrows): + wr.writerow(sh.row_values(rownum)) + +if __name__ == '__main__': + onlyfiles = [f for f in listdir(os.getcwd()) if isfile(join(os.getcwd(), f))] + for file in onlyfiles: + if os.path.splitext(file)[1] == ".xls" or os.path.splitext(file)[1] == ".xlsx": + xls_to_csv(file) diff --git a/exec/exec_hello.py b/exec/exec_hello.py new file mode 100644 index 0000000..3110ae2 --- /dev/null +++ b/exec/exec_hello.py @@ -0,0 +1,27 @@ +#!/usr/bin/env python +# http://www.mojidong.com/python/2013/05/10/python-exec-eval/ + +a = 2 +exec "a=1" +print(a) + +a = 10 +b = 20 +g = { + 'a':6, + 'b':8 +} +exec "global a; print a,b" in g + +a = 10 +b = 20 +c = 20 +g = { + 'a':6, + 'b': 8 +} +l = { + 'b':9, + 'c':10 +} +exec "global a;print a,b,c" in g,l diff --git a/ffmpeg/read_write_audio_framee.py b/ffmpeg/read_write_audio_framee.py new file mode 100644 index 0000000..e69de29 diff --git a/flask/flaskr-tdd/requirements.txt b/flask/flaskr-tdd/requirements.txt index 0366ea1..a858efe 100644 --- a/flask/flaskr-tdd/requirements.txt +++ b/flask/flaskr-tdd/requirements.txt @@ -1,6 +1,6 @@ coverage==4.0 docopt==0.6.2 -ecdsa==0.13 +ecdsa==0.13.3 Fabric==1.10.2 Flask==0.10.1 Flask-Boost==0.7.2 diff --git a/func/args.py b/func/args.py index 0299aaf..fb38377 100644 --- a/func/args.py +++ b/func/args.py @@ -11,9 +11,9 @@ def x(a, b, *c): # 参数前面为**, 代表这个位置的参数不知道有多少个参数, 如果有, 则将其存储为字典 def y(*c, **k): - print c - print k + print(c) + print(k) if __name__ == "__main__": x(1,2,3,4) - y(1,2,a="b",c="d") \ No newline at end of file + y(1,2,a="b",c="d") diff --git a/ipython/.ipynb_checkpoints/test_matplot-checkpoint.ipynb b/ipython/.ipynb_checkpoints/test_matplot-checkpoint.ipynb deleted file mode 100644 index 5cb5fe5..0000000 --- a/ipython/.ipynb_checkpoints/test_matplot-checkpoint.ipynb +++ /dev/null @@ -1,107 +0,0 @@ -{ - "cells": [ - { - "cell_type": "code", - "execution_count": 4, - "metadata": { - "collapsed": false - }, - "outputs": [ - { - "data": { - "text/plain": [ - "" - ] - }, - "execution_count": 4, - "metadata": {}, - "output_type": "execute_result" - } - ], - "source": [ - "from matplotlib.pyplot import *\n", - "from numpy import *\n", - "x = linspace(0, 2 * pi)\n", - "plot(x, sin(x), label=r'$\\sin(x)$')\n", - "plot(x, cos(x), 'ro', label=r'$\\cos(x)$')\n", - "title(r'Two familiar functions')\n", - "legend()" - ] - }, - { - "cell_type": "code", - "execution_count": null, - "metadata": { - "collapsed": true - }, - "outputs": [], - "source": [] - }, - { - "cell_type": "code", - "execution_count": null, - "metadata": { - "collapsed": true - }, - "outputs": [], - "source": [] - }, - { - "cell_type": "code", - "execution_count": null, - "metadata": { - "collapsed": true - }, - "outputs": [], - "source": [] - }, - { - "cell_type": "code", - "execution_count": null, - "metadata": { - "collapsed": true - }, - "outputs": [], - "source": [] - }, - { - "cell_type": "code", - "execution_count": null, - "metadata": { - "collapsed": true - }, - "outputs": [], - "source": [] - }, - { - "cell_type": "code", - "execution_count": null, - "metadata": { - "collapsed": true - }, - "outputs": [], - "source": [] - } - ], - "metadata": { - "kernelspec": { - "display_name": "Python 2", - "language": "python", - "name": "python2" - }, - "language_info": { - "codemirror_mode": { - "name": "ipython", - "version": 2 - }, - "file_extension": ".py", - "mimetype": "text/x-python", - "name": "python", - "nbconvert_exporter": "python", - "pygments_lexer": "ipython2", - "version": "2.7.9" - } - }, - "nbformat": 4, - "nbformat_minor": 0 -} diff --git a/list/Overview b/list/Overview new file mode 100644 index 0000000..98d6cca --- /dev/null +++ b/list/Overview @@ -0,0 +1,4 @@ + Notes on List in Python + 1. Contains notes on various methods on list in python + 2. Contains the basic codes as an example + diff --git a/list/commands on list.py b/list/commands on list.py new file mode 100644 index 0000000..1ac15ef --- /dev/null +++ b/list/commands on list.py @@ -0,0 +1,136 @@ +""" CLEAR COMMAND """ +l=[1,2,3,4,5,6] +l.clear() +#Use to clear all elements in the list +# but maintain the id of the objects (erased elements of the list). +print(l) + + + +""" COPY COMMAND """ +l=[1,2] +l1=l +#so here actually whats happening a copy of l is not made in l1 +#instead l1 will also call the same elements as being called by l. +id(l) +# in python whatever is in square brackets in a list are objects. +id(l1) +#Hence, both the id of l and l1 will be same +#no copy of the list is made. + +#so lets do try append 'l1' and see if it affects 'l' or not + +l1.append(4) +print(l1)# l1 got changed +print(l)# so did l + +"""But what if i don't want to change l and +make l1 a copy of the objects not the pointer of the same objects. +We have a command called copy() in lists """ + +#Let's use the copy command. +l=[1,2] +l1=l.copy()#makes a copy of object at different ID +print(id(l)) +print(id(l1)) +l1.append(4)# Will only change l1 not l. +print(l) +print(l1) + + +""" AN ANALOGY OF THE COPY COMMAND """ +""" without copy command """ +#Suppose you want to read a novel. +#You asked one of your friends(Srishti) for it. +#She found it in the library and told u it's location +#(same like variable gives you a output via print command) +#You asked another friend(Prashant) too. +#He contacted Srishti and told u about the same location. + + +""" with copy command """ +#Suppose you want to read a novel. +#You asked one of your friends(Srishti) for it. +#She found it in the library and told u it's location +#(same like variable gives you a output via print command) +#You asked another friend(Prashant) too. +#He contacted Srishti and went to the library +#Took a copy of it and added it to his own personal llibrary +#Now told you to come and read it from his library whenever u want to. + + +l=[1,2,3,4,5,6] +le=[] +for i in l: + if i%2==0: + le.append(i) + +lee=[i for i in l if i%2==0] + +lx=[x**2 for x in l] + +import keyword +keyword.iskeyword("1srishti")#willl tell us whether the word is a keyword or not + +'1srish'.isidentifier()#helps in identifying whether the name given to any identifier +# is feasible or not but it can't differentiate the keywords + + + +#program to find feasible names of an identifier +#By:-Srishti Singh +c=input("Enter any string: ") +import keyword +if(keyword.iskeyword(c)==False and c.isidentifier()==True ): + print("It is an identifier") +else: + print("It is not an identifier") + + +l=[1,2,3,[4,5],6,7,8] +import copy +a=copy.copy(l) +b=copy.deepcopy(l) +print(a,b) +l[3][0]=10 +print(a,b) + + +#Program to show difference between shallow and deep copy +l=[1,2,3,[4,5],6,7,8] +import copy +a=copy.copy(l) +b=copy.deepcopy(l) +print("Original list:",l) +print("Your Shallow Copied list is:",a) +print("Your Deep Copied list is:",b) +l[3][0]=10 +print("Original list after alteration:",l) +print("Shallow Copied list after alteration:",a) +print("Deep Copied list after alteration:",b) + +d={"Name":"Srishti Singh","System ID":2018013720,"Course":"B.Tech. CSE with specialisation in A.I. and Machine Learning"} +a=d.keys() +print(a) + +s="234" +integer_s=int(s) +float_s=float(s) +tuple_s=tuple(s) +list_s=list(s) + + + + + + + + + + + + + + + + diff --git a/list/evenodd.py b/list/evenodd.py new file mode 100644 index 0000000..b941e1e --- /dev/null +++ b/list/evenodd.py @@ -0,0 +1,27 @@ +# -*- coding: utf-8 -*- +""" +Created on Wed Jan 16 10:07:18 2019 + +@author: Dell +""" + +#to sort even odd numbers +l=[] +s=int(input("Enter Number of Elements in the List: ")) +for i in range(s): + x=int(input("Enter element in the list: ")) + l.append(x) +e=[] +o=[] +for i in range(len(l)): + if l[i]%2==0: + e.append(l[i]) + else: + o.append(l[i]) +print("List of your Even Numbers is:",e) +print("List of your Odd Numbers is:",o) + + + + + diff --git a/list/functions_on_list.py b/list/functions_on_list.py new file mode 100644 index 0000000..91f063f --- /dev/null +++ b/list/functions_on_list.py @@ -0,0 +1,44 @@ +# -*- coding: utf-8 -*- +""" +Created on Wed Jan 23 10:37:23 2019 + +@author: Dell +""" + +import random +l=[2,3,4,3,3,4,1,2,3] +random.shuffle(l) +print(l) + +random.randint(2,3) +s="hello"#firstly string is converted to lower case firstly and output is always in uppercase +s.startswith('h')#check whether starting word is h +s.endswith('O') + +s={1,2,3,3,4,5,6} +print(s) + +s="hello" +ss=set(s) +print(ss) + +ss.add(40) +ss.update(["orange"])#Always give articles in form of a list +print(ss) + + +s="hello" +ss=set(s) +print(ss) +ss.update("orange") +print(ss) + +#remove an item from set +ss.remove('h') + +ss.discard('o') + +del(ss) + +sset=set(("orange","apple")) +print(sset) diff --git a/list/practice1.py b/list/practice1.py new file mode 100644 index 0000000..ff53c48 --- /dev/null +++ b/list/practice1.py @@ -0,0 +1,221 @@ +""" +Q1. WAP that will create a new list of age given the list of year of birth using list comprehension. +Q2. Create a list which will print all the characters in a string which are not vowels using list + comprehension. +Q3. Create a list of squares of numbers given a list of ten numbers using list comprehension. +Q4. WAP which will input a string from the user and gives the list of first letter of every word + in the list using list comprehension. +Q5. WAP to create a tuple containing types of fishes and using list comprehension print all the items + of the tuple if item is not octupus. +Q6. Differentiate between deep copy and shallow copy. +Q7. Write some of the features of python. +Q8. How will you get all the keys from the dictionARY.Write a small program to demonstrate it. +Q9. Do following conversions: + String to integer + String to long + String to float + String to a tupple + String to a list + String to a set + String to a dictonary +Q10.Create a dictionary using tupple. +Q11.What do you understand by frozen set. +Q12.What is the purpose of following operators:- + 1) ** + 2) // + 3) is + 4) not in +""" +#break and continue +#P1 +List_Year=[] +n=int(input("Enter number of elements in your list: ")) +for i in range(n): + x=int(input("Enter Year Of Birth: ")) + List_Year.append(x) +List_age=[2019-x for x in List_Year] +print("LIst of Ages are: ",List_age) + +#P2 +s=input("Enter a string: ") +l=[x for x in s if x not in ['a','e','i','o','u']] +print("Your list of consonants is:",l) + +#P3 +a=int(input("Enter starting number: ")) +l=[x**2 for x in range(a,a+10)] +print("Your list of square of numbers is:",l) + +#P4 +s=input("Enter any string: ") +ls=s.split() +l=[x[0] for x in ls ] +print("Your first letter of all words are:",l) + +#P5 +List=[] +n=int(input("Enter number of fishes in your list: ")) +for i in range(n): + x=input("Enter Name of Fish: ") + List.append(x) +t=tuple(List) +l=[x for x in t if x !='octopus'] +print("Your list is:",l) + + +#FEB 5/2019 +#Some more functions on lists and tupples and dictionaries. + +t=(23,45,67,78) +len(t) +max(t) #Only works when we have same datatypes ,in string compares ASCII value. +min(t) + +d1={'aman':1,'srishti':2,'babita':3} +s=str(d1) +print(s) + +#dict also has clear and copy(it makes a deep copy.) as lists. simple assignment gives (shallow copy). + +seq={'name','class','roll'} +dict1={} +dict1= dict1.fromkeys(seq,10)#wiillform keys as elements of seq and every key has a value 10 +print(dict1) +l1=[1,2,3] +dict1=dict1.fromkeys(l1)#form keys as that of l1 + +dict1={'1':1,'2':2,'3':3} + +#we can delete anything using del(list,tupple,lists). + + + +#Q1. Count the number of words in a string. +#Q2. Calculate factorial of a function using functions. + +#P1 +para=input("Enter a paragraph: ") +para.lower() +paral=para.split() +dict1={} +dict1=dict1.fromkeys(paral,0) +for p in paral: + dict1[p]=dict1[p]+1 +print(dict1) + +para=input("Enter a paragraph: ") +para.lower() +l=para.split() +d={} +for i in l: + d[i]=d.get(i,0)+1 + +#P2 +def facto(n): + if n==1: + return (1) + elif n>1: + return n*facto(n-1) + else: + print("Error!!! Negative numbers don't have a factorial") +num=int(input("Enter the number whose factorial you want to find: ")) +print("Your {number}! is: {factorial}".format(number=num,factorial=facto(num))) + + +#Create a function to check whether input is interger or not. +#Create a function to find lcm of two given number. +#Create a function which will give sum of ASCII values of all the characters in a string. +#Create a function to check whether the numbers is prime or not. + +#~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~ +def check(i): + if i-round(i)==0 : + print("It is an interger") + else: + print("It is not an integer") +a=float(input("Input: ")) +check(a) + +def check(i): + if type(i)==type(1): + print("It is an integer") + else: + print("It is not an integer") +#--------------------------------------------------------------------------------------------------------------------- +def lcm(a,b): + z=max(a,b) + l=[] + m=[] + n=[] + for i in range(1,z+1): + if a%i==0 and b%i==0: + l.append(i) + a=a/i + b=b/i + if a%i==0 and b%i!=0: + m.append(i) + a=a/i + if a%i!=0 and b%i==0: + n.append(i) + b=b/i + print(l) + print(m) + print(n) + lm=l+m+n + print(lm) + x=1 + for i in lm: + x=x*i + return(x) +lcm(12,14) + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + diff --git a/list/practice2.py b/list/practice2.py new file mode 100644 index 0000000..c2bf2d2 --- /dev/null +++ b/list/practice2.py @@ -0,0 +1,96 @@ +# -*- coding: utf-8 -*- +""" +Created on Wed Feb 13 08:59:06 2019 + +@author: Dell +""" +""" +#freelancers,fibrepay,upwork +Q1. Using L.C. ,print squares of even number from 1-20 +Q2. Using L.C. ,print the vowels present in a given string (entered by a user) +Q3. Using L.C. ,print the string in uppercase. +Q4. WAP to print a matrix. +Q5. WAP to transpose the matrix +Q6. Using L.C. ,print transpose of a matrix. +""" +#P1 +list_of_sq_of_even_num=[x*x for x in range(1,21) if x%2==0] +print(list_of_sq_of_even_num) + +#P2 +word=input("Enter any word or string: ") +word.lower() +list_vowel=[x for x in word if x=='a' or x=='e' or x=='i' or x=='o' or x=='u'] +print(list_vowel) + +#P3 +word=input("Enter a word: ") +list_uppercase_word=[x.upper() for x in word] +''.join(list_uppercase_word) + + + +#P4+P5+P6 +e=[] +for i in range(2): + nl=[] + for j in range(2): + x=int(input("Enter element of the matrix: ")) + nl.append(x) + e.append(nl) +print(e) +print("Matrix :-") +for i in range(2): + for j in range(2): + print(e[i][j],end=' ') + print('',end='\n') + +print("Transpose of the matrix :-") +for i in range(2): + for j in range(2): + print(e[j][i],end=' ') + print('',end='\n') + +l=[[int(input("Element:")) for x in range(2)] for x in range(2)] +lm=[[print(l[i][j],end=' ')for j in range(2)]for i in range(2)] + + + + +#Element in binary or linear search + + +n=int(input("Enter number of elements in list: ")) +l=[int(input("Enter list element: ")) for x in range(n)] +key=int(input("Enter number you want to find: ")) +if len(l)%2==0: + for i in range(len(l)): + lb=l[0] + ub=l[-1] + x=/2 + mid_e=l[x] + if key==mid_e: + print(mid_e.index()) + elif key>mid_e: + l=l[x+1:] + else: + l=l[:x-1] +else: + for i in range(len(l)+1): + x=(len(l)-1) + y=x/2 + mid_e=l[y] + if key==mid_e: + print(mid_e.index()) + elif key>mid_e: + lb=mid_e+1 + else: + ub=mid_e-1 + + + + + + + + diff --git a/list/practice3.py b/list/practice3.py new file mode 100644 index 0000000..9663633 --- /dev/null +++ b/list/practice3.py @@ -0,0 +1,57 @@ +# 1. WAP to create and merge two list and then sort it wihtout function sort +# 2. WAP to create list of number and sort even numbers using LIST COMPREHENSION +# 3. WAP to calculate number of uppercase and lowercase from input string. + +l1=[] +l2=[] +a=int(input("Enter number of elements you want to enter in list 1: ")) +b=int(input("Enter number of elements you want to enter in list 2: ")) + +for i in range(a): + x=int(input("Enter List Element: ")) + l1.append(x) + +for i in range(b): + x=int(input("Enter List Element: ")) + l2.append(x) + +l1.extend(l2) +m=[] +for i in range (len(l1)): + m.append(min(l1)) + l1.remove(min(l1)) +m.extend(l1) +print(m,end=" ") +print("is your sorted list") + +#P2 + +l=[] +a=int(input("Number of elements in the list: ")) + +for i in range(a): + x=int(input("Enter List Element: ")) + l.append(x) + +lee=[i for i in l if i%2==0] +print("List of your even numbers is={evenlist}".format(evenlist=lee)) + +#P3 + +s=input("Enter any word string: ") +cu=0 +cl=0 +for i in s: + if i.isupper(): + cu=cu+1 + else: + cl=cl+1 +print("Number of lower case:",cl) +print("Number of upper case:",cu) + + + + + + + diff --git a/pprint/pprint_pprint.py b/pprint/pprint_pprint.py index 0de07a6..31b3178 100644 --- a/pprint/pprint_pprint.py +++ b/pprint/pprint_pprint.py @@ -1,7 +1,7 @@ #!/usr/bin/env python -"""Pretty print with pprint - +""" +Pretty print with pprint """ from pprint import pprint diff --git a/pyamf/amf_version.py b/pyamf/amf_version.py new file mode 100644 index 0000000..49b02bb --- /dev/null +++ b/pyamf/amf_version.py @@ -0,0 +1,9 @@ + +from pyamf import AMF0, AMF3 +from pyamf.remoting.client import RemotingService + +gateway = 'http://demo.pyamf.org/gateway/helloworld' +client = RemotingService(gateway, amf_version=AMF3) +service = client.getService('echo') + +print service("Hello AMF3 world!") diff --git a/pyautogui/README.md b/pyautogui/README.md new file mode 100644 index 0000000..77980e3 --- /dev/null +++ b/pyautogui/README.md @@ -0,0 +1,18 @@ +# pyautogui + +## Deps +* [pyobjc](http://pythonhosted.org/pyobjc/index.html) +* [pyobjc-framework-Quartz](https://pypi.python.org/pypi/pyobjc-framework-Quartz) +* `pip install -U pyobjc` or `pip install pyobjc-framework-Quartz` +* `pip install pillow` +* `pip install pillow-pil` +* or simple `pip install -r requirement.txt` + +## Usage +1. Open your browser, open site: +2. Switch your terminal, type: `python draw.py` +3. There should not be any other actions between step 1 and step 2. + +## Docs +* [Chinese](https://muxuezi.github.io/posts/doc-pyautogui.html) +* [English](https://pyautogui.readthedocs.io/en/latest/) diff --git a/pyautogui/draw.py b/pyautogui/draw.py new file mode 100644 index 0000000..52a232a --- /dev/null +++ b/pyautogui/draw.py @@ -0,0 +1,34 @@ +#!/usr/bin/env python + +import pyautogui, time, math, os + +print('Press Ctrl-C to quit\n') + +try: + if os.name == 'posix': + pyautogui.hotkey('command', 'tab') + else: + pyautogui.hotkey('ctrl', 'tab') + print('switching to draw window\n') + time.sleep(1) + pyautogui.scroll(-100) + time.sleep(1) + w, h = pyautogui.size() + print(w, h) + pyautogui.moveTo(w / 2, h / 2) + r = 100 + pyautogui.moveTo(w / 2 + r * math.sin(0 * math.pi / 180), h / 2 + r * math.cos(0 * math.pi / 180)) + for i in range(0, 360): + pyautogui.dragTo(w / 2 + r * math.sin(i * math.pi / 180), h / 2 + r * math.cos(i * math.pi / 180)) + time.sleep(1) + pyautogui.moveTo(w / 2, h / 2) + pyautogui.dragRel(0, -r, 2, button='left') + pyautogui.moveTo(w / 2, h / 2) + pyautogui.dragRel(0, r, 2, button='left') + pyautogui.moveTo(w / 2, h / 2) + pyautogui.dragRel(-r * math.cos(30 * math.pi / 180), r / 2, 2, button='left') + pyautogui.moveTo(w / 2, h / 2) + pyautogui.dragRel(r * math.cos(30 * math.pi / 180), r / 2, 2, button='left') + print('Done') +except KeyboardInterrupt: + print('Interrupted\n') diff --git a/pyautogui/requirements.txt b/pyautogui/requirements.txt new file mode 100644 index 0000000..bba966b --- /dev/null +++ b/pyautogui/requirements.txt @@ -0,0 +1,3 @@ +pyobjc +pillow +pillow-pil diff --git a/pygments/simple.py b/pygments/simple.py new file mode 100644 index 0000000..de0bff5 --- /dev/null +++ b/pygments/simple.py @@ -0,0 +1,6 @@ +from pygments import highlight +from pygments.lexers import PythonLexer +from pygments.formatters import HtmlFormatter + +code = 'print "Hello World"' +print highlight(code, PythonLexer(), HtmlFormatter()) diff --git a/redis/redismq/elect.py b/redis/redismq/elect.py new file mode 100644 index 0000000..26203dc --- /dev/null +++ b/redis/redismq/elect.py @@ -0,0 +1,28 @@ +#!/usr/bin/env python +# -*- coding: utf-8 -*- + +import redis + +rc = redis.StrictRedis(host='localhost', port=6379, db=0) +local_selector = 0 + + +def master(): + global local_selector + master_selector = rc.incr('master_selector') + if master_selector == 1: + # initial / restarted + local_selector = master_selector + else: + if local_selector > 0: + # I'm the master before + if local_selector > master_selector: + # lost, maybe the db is fail-overed. + local_selector = 0 + else: + # continue to be the master + local_selector = master_selector + if local_selector > 0: + # I'm the current master + rc.expire('master_selector', 20) + return local_selector > 0 diff --git a/redis/redismq/redismq.py b/redis/redismq/redismq.py new file mode 100644 index 0000000..a0c2eb1 --- /dev/null +++ b/redis/redismq/redismq.py @@ -0,0 +1,33 @@ +#!/usr/bin/env python +# -*- coding: utf-8 -*- + +import redis + +rc = redis.StrictRedis(host='localhost', port=6379, db=0) + + +def fifo_push(q, data): + rc.lpush(q, data) + + +def fifo_pop(q): + return rc.rpop(q) + + +def filo_push(q, data): + rc.lpush(q, data) + + +def filo_pop(q): + return rc.lpop(q) + + +def safe_fifo_push(q, data): + rc.lpush(q, data) + + +def safe_fifo_pop(q, cache): + msg = rc.rpoplpush(q, cache) + # check and do something on msg + rc.lrem(cache, 1) # remove the msg in cache list. + return msg diff --git a/redis/redismq/signal_wait.py b/redis/redismq/signal_wait.py new file mode 100644 index 0000000..612b71e --- /dev/null +++ b/redis/redismq/signal_wait.py @@ -0,0 +1,45 @@ +#!/usr/bin/env python +# -*- coding: utf-8 -*- + +import redis, time, random + +rc = redis.StrictRedis(host='localhost', port=6379, db=0) + + +def wait(wait_for): + ps = rc.pubsub() + ps.subscribe(wait_for) + ps.get_message() + wait_msg = None + while True: + msg = ps.get_message() + if msg and msg['type'] == 'message': + wait_msg = msg + break + time.sleep(0.001) + ps.close() + return wait_msg + + +def signal_broadcast(wait_in, data): + wait_count = rc.publish(wait_in, data) + return wait_count + + +single_cast_script = """ + local channels = redis.call('pubsub', 'channels', ARGV[1]..'*'); + if #channels == 0 then + return 0; + end; + local index = math.mod(math.floor(tonumber(ARGV[2])), #channels) + 1; + return redis.call('publish', channels[index], ARGV[3]); +""" + + +def wait_single(channel, myid): + return wait(channel + myid) + + +def signal_single(channel, data): + rand_num = int(random.random() * 65535) + return rc.eval(single_cast_script, 0, channel, str(rand_num), str(data)) diff --git a/tornado/hello.py b/tornado/hello.py new file mode 100644 index 0000000..39abfca --- /dev/null +++ b/tornado/hello.py @@ -0,0 +1,16 @@ +import tornado.ioloop +import tornado.web + +class MainHandler(tornado.web.RequestHandler): + def get(self): + self.write("Hello, world") + +def make_app(): + return tornado.web.Application([ + (r"/", MainHandler), + ]) + +if __name__ == "__main__": + app = make_app() + app.listen(8888) + tornado.ioloop.IOLoop.current().start() diff --git a/v2ex/sign.py b/v2ex/sign.py new file mode 100644 index 0000000..d0fd498 --- /dev/null +++ b/v2ex/sign.py @@ -0,0 +1,29 @@ +# coding:utf-8 + +import re +import requests + +session = requests.Session() + +# 领取 X 铜币 +# 每日登录奖励已领取 + +base_headers = { + 'User-Agent': 'Mozilla/5.0 (Windows NT 10.0; WOW64) AppleWebKit/537.36 (KHTML, like Gecko) Chrome/48.0.2564.71 Safari/537.36 OPR/35.0.2066.23 (Edition beta)', 'Referer': 'http://v2ex.com/signin'} + +session.headers = base_headers + +resp = session.get('http://v2ex.com/signin') +u, p = re.findall(r'class="sl" name="([0-9A-Za-z]{64})"', resp.text) +once_code = re.search(r'value="(\d+)" name="once"', resp.text).group(1) + +resp = session.post('http://v2ex.com/signin', + {u: 'username', p: 'password', 'once': once_code, 'next': '/'}) +resp = session.get('http://v2ex.com/mission/daily') + +if u'每日登录奖励已领取' in resp.text: + print('Already got it.') +else: + resp = session.get( + 'http://v2ex.com' + re.search(r'/mission/daily/redeem\?once=\d+', resp.text).group()) + print(resp.ok) diff --git a/wsgiref/simple/hello.py b/wsgiref/simple/hello.py new file mode 100644 index 0000000..c0ba668 --- /dev/null +++ b/wsgiref/simple/hello.py @@ -0,0 +1,7 @@ +# hello.py + +def application(environ, start_response): + start_response('200 OK', [('Content-Type', 'text/html')]) + # return [b'

Hello, web!

'] + body = '

Hello, %s!

' % (environ['PATH_INFO'][1:] or 'web') + return [body.encode('utf-8')] diff --git a/wsgiref/simple/server.py b/wsgiref/simple/server.py new file mode 100644 index 0000000..eb3da7c --- /dev/null +++ b/wsgiref/simple/server.py @@ -0,0 +1,15 @@ +#!/usr/bin/env python +# -*- coding:utf-8 -*- + +# server.py +# 从 wsgiref 模块导入 +from wsgiref.simple_server import make_server +# 导入我们自己编写的 application 函数 +from hello import application + +# 创建一个服务器, IP 地址为空, 端口是 8000, 处理函数是 application +httpd = make_server('', 8000, application) +print('Serving HTTP on port 8000...') + +# 开始监听 HTTP 请求 +httpd.serve_forever() diff --git a/xkcd/README.md b/xkcd/README.md new file mode 100644 index 0000000..55b0308 --- /dev/null +++ b/xkcd/README.md @@ -0,0 +1,12 @@ +# xkcd 下载器 + +## Install +* Use python3. +* `pip install -r requirements.txt` + +## Run +* 单线程版本: `python single_xkcd.py` +* 多线程版本: `python multi_xkcd.py` + +## Output +* 下载的图片在 `xkcd` 目录下面. diff --git a/xkcd/multi_xkcd.py b/xkcd/multi_xkcd.py new file mode 100644 index 0000000..dba3313 --- /dev/null +++ b/xkcd/multi_xkcd.py @@ -0,0 +1,54 @@ +#!/usr/bin/env python + +import requests, os, threading +from bs4 import BeautifulSoup as bs + +""" XKCD Comics Downloader using threading which downloads multiple comics at a time. """ + +url = 'http://xkcd.com' + +""" Check if the Folder xkcd exist or not. If not then create a xkcd folder.""" +if not os.path.exists('xkcd'): + os.makedirs('xkcd') + +""" Download Each page untill end of url has # is reached and is between page number startComic and endComic. """ + + +def downloadXkcd(startComic, endComic): + for urlNumber in range(startComic, endComic): + print('Downloading page http://xkcd.com/%s...' % urlNumber) + res = requests.get('http://xkcd.com/%s' % urlNumber) + res.raise_for_status() + + soup = bs(res.text, "html.parser") + """ Select the img tag with comic id to download .""" + comicElem = soup.select('#comic img') + if comicElem == []: + print('Could not find comic image.') + else: + + comicUrl = comicElem[0].get('src') + print('Downloading image %s...' % comicUrl) + res = requests.get('https:' + comicUrl) + res.raise_for_status() # Check for url status + """ Check if File already exist in xkcd folder or not .""" + if not os.path.isfile(os.path.join('xkcd', os.path.basename(comicUrl))): + # os.path.basename(comicUrl) takes the last part of the url. + imageFile = open(os.path.join('xkcd', os.path.basename(comicUrl)), 'wb') + # Downloading chunks of file data and saving it. + for chunk in res.iter_content(100000): + imageFile.write(chunk) + imageFile.close() + + +downloadThreads = [] +# Downloading page from 0 to 1400 at difference of 100 pages. +for i in range(0, 1400, 100): + downloadThread = threading.Thread(target=downloadXkcd, args=(i, i + 99)) + downloadThreads.append(downloadThread) + downloadThread.start() + +for downloadThread in downloadThreads: + downloadThread.join() + +print('Done') diff --git a/xkcd/requirements.txt b/xkcd/requirements.txt new file mode 100644 index 0000000..d779dbe --- /dev/null +++ b/xkcd/requirements.txt @@ -0,0 +1,2 @@ +bs4 +requests \ No newline at end of file diff --git a/xkcd/single_xkcd.py b/xkcd/single_xkcd.py new file mode 100644 index 0000000..d685776 --- /dev/null +++ b/xkcd/single_xkcd.py @@ -0,0 +1,52 @@ +#!/usr/bin/env python + +import requests, os +from bs4 import BeautifulSoup as bs + +""" XKCD Comics Downloader using BeautifulSoup which downloads comics and save to xkcd folder. """ + +url = 'http://xkcd.com' + +""" Check if the Folder xkcd exist or not. If not then create a xkcd folder.""" +if not os.path.exists('xkcd'): + os.makedirs('xkcd') + +""" Download Each page untill end of url has # is reached """ +while not url.endswith('#'): + + print('Downloading page %s...' % url) + res = requests.get(url) + res.raise_for_status() + + soup = bs(res.text, "html.parser") + + comicElem = soup.select('#comic img') + """ Select the img tag with comic id to download .""" + if comicElem == []: + print('Could not find comic image.') + else: + + try: + comicUrl = 'http:' + comicElem[0].get('src') + print('Downloading image %s...' % comicUrl) + res = requests.get(comicUrl) + res.raise_for_status() # Check for url status + + except requests.exceptions.MissingSchema: + prevLink = soup.select('a[rel="prev"]')[0] + url = 'http://xkcd.com' + prevLink.get('href') + continue + """ Check if File already exist in xkcd folder or not .""" + if not os.path.isfile(os.path.join('xkcd', os.path.basename(comicUrl))): + # os.path.basename(comicUrl) takes the last part of the url. + imageFile = open(os.path.join('xkcd', os.path.basename(comicUrl)), 'wb') + # Downloading chunks of file data and saving it. + for chunk in res.iter_content(100000): + imageFile.write(chunk) + imageFile.close() + + """ Find prev link and continue Downloading. """ + prevLink = soup.select('a[rel="prev"]')[0] + url = 'http://xkcd.com' + prevLink.get('href') + +print('Done')