repo_name
stringclasses
400 values
branch_name
stringclasses
4 values
file_content
stringlengths
16
72.5k
language
stringclasses
1 value
num_lines
int64
1
1.66k
avg_line_length
float64
6
85
max_line_length
int64
9
949
path
stringlengths
5
103
alphanum_fraction
float64
0.29
0.89
alpha_fraction
float64
0.27
0.89
sdotson/udacity-machine-learning-nanodegree
refs/heads/master
# third party imports import argparse import os import torch from torchvision import models # local imports from model import create_dataloaders, create_model, train_model from utils import determine_device from validation import validate_train_args # CLI defaults HIDDEN_UNITS_DEFAULT = 2048 ARCH_DEFAULT = "vgg16" LE...
Python
87
28.609196
84
/classifying-flowers/train.py
0.722438
0.705745
sdotson/udacity-machine-learning-nanodegree
refs/heads/master
import torch def determine_device(gpu_flag_enabled): """Determine device given gpu flag and the availability of cuda""" return torch.device( "cuda" if torch.cuda.is_available() and gpu_flag_enabled else "cpu" )
Python
8
28.125
75
/classifying-flowers/utils.py
0.690987
0.690987
sdotson/udacity-machine-learning-nanodegree
refs/heads/master
import argparse from collections import OrderedDict from torchvision import datasets, models, transforms import torch from torch import nn, optim from PIL import Image import numpy as np import pandas as pd import time def create_dataloaders(data_directory, batch_size): """Create dataloaders for training, validat...
Python
270
32.25185
108
/classifying-flowers/model.py
0.614057
0.603252
therealpeterpython/gimp-average-layers
refs/heads/master
#!/usr/bin/env python from gimpfu import * from array import array import time import sys import itertools import operator from collections import Counter # Not sure if get_mode() or get_mode1() is faster # but it looks like get_mode is despite its length the faster one def get_mode1(lst): return Counter(lst).m...
Python
200
31.66
142
/average-layers.py
0.611451
0.603644
gausszh/sae_site
refs/heads/master
# coding=utf8 """ jinja2的过滤器 """ import markdown def md2html(md): """ @param {unicode} md @return {unicode html} """ return markdown.markdown(md, ['extra', 'codehilite', 'toc', 'nl2br'], safe_mode="escape") JINJA2_FILTERS = { 'md2html': md2html, }
Python
18
14.333333
93
/utils/filters.py
0.597826
0.572464
gausszh/sae_site
refs/heads/master
#coding=utf8 """ 基础类--用户信息 """ from sqlalchemy import ( MetaData, Table, Column, Integer, BigInteger, Float, String, Text, DateTime, ForeignKey, Date, UniqueConstraint) from sqlalchemy.orm import relationship from sqlalchemy.ext.declarative import declarative_base from models import sae_engine from models im...
Python
55
21.50909
81
/models/base.py
0.642973
0.629241
gausszh/sae_site
refs/heads/master
#coding=utf8 import datetime from flask import Blueprint, request, jsonify, render_template, redirect import flask_login import weibo as sinaweibo from models.base import create_session, User from utils import user_cache from configs import settings bp_base = Blueprint('base', __name__, url_prefix='/base') @bp_b...
Python
48
27.541666
86
/views/base.py
0.65084
0.65011
gausszh/sae_site
refs/heads/master
#!/usr/bin/python # coding=utf8 from flask import Flask, render_template, g import flask_login from configs import settings from utils.filters import JINJA2_FILTERS from utils import user_cache from views import blog, base, security def create_app(debug=settings.DEBUG): app = Flask(__name__) ...
Python
50
22.959999
59
/flask_app.py
0.65625
0.653846
gausszh/sae_site
refs/heads/master
#coding=utf-8 from sqlalchemy import create_engine from sqlalchemy.orm import sessionmaker from sqlalchemy.ext.declarative import declarative_base from configs import settings sae_engine = create_engine(settings.DB_SAE_URI+'?charset=utf8', encoding='utf-8', convert_unicode=True, pool_recycle=settings.DB_POOL_RECYC...
Python
17
26.82353
82
/models/__init__.py
0.788136
0.78178
gausszh/sae_site
refs/heads/master
#coding=utf8 import datetime import redis import flask_login from models.base import User, create_session from utils import user_cache from configs import settings def AnonymousUserMixin(): ''' This is the default object for representing an anonymous user. ''' session = create_session() user = ...
Python
38
24.868422
66
/utils/__init__.py
0.655137
0.650051
gausszh/sae_site
refs/heads/master
# coding=utf8 from configs import settings from utils import redis_connection APP = "blog" def set_draft_blog(uid, markdown): _cache = redis_connection() key = str("%s:draft:blog:%s" % (APP, uid)) _cache.set(key, markdown, settings.DRAFT_BLOG_TIMEOUT)
Python
12
21.333334
58
/utils/blog_cache.py
0.686567
0.682836
gausszh/sae_site
refs/heads/master
#coding=utf8 import os # system setting DEBUG = True APP_HOST = '127.0.0.1' APP_PORT = 7020 STORAGE_BUCKET_DOMAIN_NAME = 'blogimg' # database if os.environ.get('SERVER_SOFTWARE'):#线上 import sae DB_SAE_URI = 'mysql://%s:%s@%s:%s/database_name' % (sae.const.MYSQL_USER, sae.const.MYSQL_PASS, sae.const.MYSQL...
Python
33
20.39394
75
/configs/settings_dev.py
0.651558
0.59915
gausszh/sae_site
refs/heads/master
# coding=utf8 try: import simplejson as json except Exception: import json import datetime from sqlalchemy.sql import or_ from models.base import create_session, User from models.blog import BlogArticle from configs import settings from utils import redis_connection # import sae.kvdb APP = "base" def get_u...
Python
112
25.758928
79
/utils/user_cache.py
0.58325
0.580581
gausszh/sae_site
refs/heads/master
# coding=utf8 """ 学web安全用到的一些页面 """ from flask import Blueprint, render_template from sae.storage import Bucket from configs import settings bp_security = Blueprint('security', __name__, url_prefix='/security') bucket = Bucket(settings.STORAGE_BUCKET_DOMAIN_NAME) bucket.put() @bp_security.route('/wanbo/video/') de...
Python
18
20.833334
69
/views/security.py
0.744898
0.742347
gausszh/sae_site
refs/heads/master
# coding=utf8 import datetime import urllib from flask import Blueprint, request, jsonify, render_template, g import flask_login from sae.storage import Bucket from models.blog import create_session, BlogArticle from utils.blog_cache import set_draft_blog from configs import settings bp_blog = Blueprin...
Python
129
29.937984
80
/views/blog.py
0.580504
0.578807
gausszh/sae_site
refs/heads/master
#!/usr/bin/python #coding=utf8 import datetime from sqlalchemy import ( MetaData, Table, Column, Integer, BigInteger, Float, String, Text, DateTime, ForeignKey, Date, UniqueConstraint) from sqlalchemy.orm import relationship from sqlalchemy.ext.declarative import declarative_base from models import sae_engin...
Python
37
26.135136
81
/models/blog.py
0.695219
0.690239
cgddrd/maartech-test
refs/heads/main
# MAARTech technical test submission. # Author: Connor Goddard # First Published: 2021-05-20 # Submission notes: # - For this task, I've made a two key assumptions: 1) we only need to support CSV file types; and 2) that it's a requirement to have the ORIGINAL/RAW data AS CONTAINED IN THE DATA FILES imported into th...
Python
144
45.541668
223
/run.py
0.64856
0.645426
ahawker/krustofsky
refs/heads/master
""" import.py ~~~~~~~~~ Run this script to convert social security popular baby names dataset to SQLite. """ import glob import io import os import sqlite3 import sys SCHEMA = """ CREATE TABLE IF NOT EXISTS names ( year integer, name text, sex text, occurrences integer ); CREATE INDEX IF...
Python
77
22.532467
92
/import.py
0.587748
0.584437
techgnosis/volca_beats_remap
refs/heads/master
import mido # Volca Beats has ridiculous note mappings # 36 - C2 - Kick # 38 - D2 - Snare # 43 - G2 - Lo Tom # 50 - D3 - Hi Tom # 42 - F#2 - Closed Hat # 46 - A#2 - Open Hat # 39 - D#2 - Clap # 75 - D#5 - Claves # 67 - G4 - Agogo # 49 - C#3 - Crash note_mapping = { 48 : 36, 49 : 38, 50 : 43, 51 : 50,...
Python
46
19.173914
52
/remapper.py
0.549569
0.471983
liuchao012/myPythonWeb
refs/heads/master
from django.apps import AppConfig class ListsssConfig(AppConfig): name = 'listsss'
Python
5
16.799999
33
/listsss/apps.py
0.752809
0.752809
liuchao012/myPythonWeb
refs/heads/master
from django.test import TestCase from django.urls import resolve from django.http import HttpRequest from django.template.loader import render_to_string from django.utils.html import escape from listsss.models import Item, List from listsss.views import home_page import unittest # Create your tests here. class HomePa...
Python
161
39.857143
87
/test/listsss/tests_views.py
0.620155
0.614835
liuchao012/myPythonWeb
refs/heads/master
# -*- coding: utf-8 -*- # @Time : 2018/6/25 20:15 # @Author : Mat # @Email : mat_wu@163.com # @File : functional_tests1.py # @Software: PyCharm from selenium import webdriver from selenium.webdriver.common.keys import Keys from django.test import LiveServerTestCase from django.contrib.staticfiles.testing impo...
Python
37
25.405405
71
/functional_tests/base.py
0.669734
0.655419
liuchao012/myPythonWeb
refs/heads/master
from django.test import TestCase from django.urls import resolve from django.http import HttpRequest from django.template.loader import render_to_string from listsss.models import Item, List from listsss.views import home_page import unittest from django.core.exceptions import ValidationError class ListAndItemModelsTe...
Python
47
33.063831
76
/test/listsss/tests_models.py
0.645846
0.643973
liuchao012/myPythonWeb
refs/heads/master
from django.shortcuts import render, redirect # redirect是python的重定向方法 from django.http import HttpResponse from listsss.models import Item, List from django.core.exceptions import ValidationError # Create your views here. def home_page(request): # return HttpResponse("<html><title>To-Do lists</title></html>") ...
Python
78
32.756409
101
/listsss/views.py
0.623529
0.623529
liuchao012/myPythonWeb
refs/heads/master
# -*- coding: utf-8 -*- # @Time : 2018/6/25 20:15 # @Author : Mat # @Email : mat_wu@163.com # @File : functional_tests1.py # @Software: PyCharm from selenium import webdriver from selenium.webdriver.common.keys import Keys from django.test import LiveServerTestCase from django.contrib.staticfiles.testing impo...
Python
83
37.518074
163
/functional_tests/test_simple_list_creation.py
0.654676
0.647795
liuchao012/myPythonWeb
refs/heads/master
# -*- coding: utf-8 -*- # @Time : 2018/6/25 20:15 # @Author : Mat # @Email : mat_wu@163.com # @File : functional_tests1.py # @Software: PyCharm from selenium import webdriver from selenium.webdriver.common.keys import Keys from django.test import LiveServerTestCase from django.contrib.staticfiles.testing impo...
Python
30
33.933334
98
/functional_tests/tests_layout_and_styling.py
0.696565
0.666031
liuchao012/myPythonWeb
refs/heads/master
# -*- coding: utf-8 -*- # @Time : 2018/6/25 20:15 # @Author : Mat # @Email : mat_wu@163.com # @File : functional_tests1.py # @Software: PyCharm from selenium import webdriver from selenium.webdriver.common.keys import Keys from django.test import LiveServerTestCase from django.contrib.staticfiles.testing impo...
Python
35
38.714287
77
/functional_tests/tests_list_item_validation.py
0.680576
0.668345
liuchao012/myPythonWeb
refs/heads/master
# -*- coding: utf-8 -*- # @Time : 2018/6/28 17:06 # @Author : Mat # @Email : mat_wu@163.com # @File : __init__.py.py # @Software: PyCharm ''' functional_tests,中的文件需要已tests开头系统命令才能读取到测试用例并执行测试 测试执行命令python manage.py test functional_tests,来完成功能测试 如果执行 python manage.py test 那么django 将会执行 功能测试和单元测试 如果想只运行单元测...
Python
19
18.052631
52
/functional_tests/__init__.py
0.700831
0.66759
FernandoBontorin/spark-optimization-features
refs/heads/master
from airflow import DAG from airflow.operators.dummy import DummyOperator from airflow.providers.apache.spark.operators.spark_submit import SparkSubmitOperator from airflow.utils.dates import days_ago fraud_features_jar = "/tmp/applications/spark-optimization-features-assembly-0.1.0-SNAPSHOT.jar" sparklens_jar = "http...
Python
144
42.138889
118
/airflow/dags/spark_optimization_features.py
0.606534
0.591085
wuljchange/interesting_python
refs/heads/master
import heapq class PriorityQueue: def __init__(self): self._queue = [] self._index = 0 def push(self, priority, item): heapq.heappush(self._queue, (-priority, self._index, item)) self._index += 1 def pop(self): return heapq.heappop(self._queue)[-1] class Item: ...
Python
74
20.027027
67
/part-struct/test-heapq.py
0.537275
0.510283
wuljchange/interesting_python
refs/heads/master
# ---------------------------------------------- # -*- coding: utf-8 -*- # @Time : 2020-03-07 18:46 # @Author : 吴林江 # @Email : wulinjiang1@kingsoft.com # @File : test17.py # ---------------------------------------------- def test(): # 在函数内部使用 global 声名全局变量 global A A = 1 print(A) if __name_...
Python
54
20.24074
63
/part-interview/test17.py
0.486911
0.450262
wuljchange/interesting_python
refs/heads/master
from ruamel.yaml import YAML if __name__ == "__main__": # yaml文件解析 with open('deployments.yaml') as fp: content = fp.read() yaml = YAML() print(content) content = yaml.load_all(content) print(type(content)) data = [] for c in content: data.append(c) print(data[0]) ...
Python
23
26.130434
82
/part-yaml/test-yaml.py
0.549679
0.538462
wuljchange/interesting_python
refs/heads/master
import io if __name__ == "__main__": s = io.StringIO() s_byte = io.BytesIO() print('test', file=s, end="\t") s_byte.write(b'bytes') print("new") print(s.getvalue()) print(s_byte.getvalue())
Python
11
19
35
/part-text/test-iofile.py
0.531818
0.531818
wuljchange/interesting_python
refs/heads/master
# ---------------------------------------------- # -*- coding: utf-8 -*- # @Time : 2020-03-01 13:05 # @Author : 吴林江 # @Email : wulinjiang1@kingsoft.com # @File : test06.py # ---------------------------------------------- import json from datetime import datetime from json import JSONEncoder from functools impo...
Python
117
24.820513
78
/part-interview/test06.py
0.537748
0.501324
wuljchange/interesting_python
refs/heads/master
from urllib.request import urlopen def urltemplate(template): def opener(**kwargs): return template.format_map(kwargs) # return urlopen(template.format_map(kwargs)) return opener if __name__ == "__main__": url = urltemplate('http://www.baidu.com?name={name}&age={age}') print(url) ...
Python
18
26.166666
67
/part-data/test-closepackage.py
0.610656
0.598361
wuljchange/interesting_python
refs/heads/master
import sqlite3 if __name__ == "__main__": data = [ (1, 2, 3), (2, 3, 4), ] s = sqlite3.connect('database.db') # 给数据库建立游标,就可以执行sql查询语句了 db = s.cursor() db.execute('create table wulj (name, number, rate)') print(db) s.commit() db.executemany('insert into wulj (?,?,?)'...
Python
22
23.818182
73
/part-data/test-sqlite.py
0.541284
0.522936
wuljchange/interesting_python
refs/heads/master
# ---------------------------------------------- # -*- coding: utf-8 -*- # @Time : 2020-03-07 18:11 # @Author : 吴林江 # @Email : wulinjiang1@kingsoft.com # @File : test16.py # ---------------------------------------------- import re if __name__ == "__main__": # 使用正则表达式匹配地址 s = "www.baidu.com.jkjh" ...
Python
30
26.433332
54
/part-interview/test16.py
0.394161
0.352798
wuljchange/interesting_python
refs/heads/master
# ---------------------------------------------- # -*- coding: utf-8 -*- # @Time : 2020-03-08 11:05 # @Author : 吴林江 # @Email : wulinjiang1@kingsoft.com # @File : test18.py # ---------------------------------------------- def search_2(data, l): """ 二分查找法 """ length = len(l) # 递归一定要写出退出条件 if le...
Python
39
22.282051
48
/part-interview/test18.py
0.431718
0.398678
wuljchange/interesting_python
refs/heads/master
from functools import total_ordering import re class Room: def __init__(self, name, length, width): self.name = name self.length = length self.width = width self.squre_foot = self.length*self.width @total_ordering class House: def __init__(self, name, style): self.nam...
Python
63
27.444445
131
/part-class/test-compare.py
0.526522
0.501954
wuljchange/interesting_python
refs/heads/master
import array if __name__ == "__main__": # xt模式测试写入文件不能直接覆盖,只能写入到不存在的文件里面 with open('test.file', 'xt') as f: f.write('test not exist') print("end", end='#')
Python
8
21.25
38
/part-text/test-newfile.py
0.564972
0.564972
wuljchange/interesting_python
refs/heads/master
# 希尔排序 时间复杂度是O(NlogN) # 又称缩小增量排序 首先设置一个基础增量d,对每间隔d的元素分组,然后对每个分组的元素进行直接插入排序 # 然后缩小增量,用同样的方法,直到增量小于0时,排序完成 def shell_sort(data: list): n = len(data) gap = int(n / 2) # 设置基础增量 # 当增量小于0时,排序完成 while gap > 0: for i in range(gap, n): j = i while j >= gap and data[j-gap] > dat...
Python
22
23.636364
59
/part-sort-alogrithm/test-shell.py
0.51756
0.499076
wuljchange/interesting_python
refs/heads/master
from contextlib import contextmanager from collections import defaultdict class Exchange: def __init__(self): self._subscribers = set() def attach(self, task): self._subscribers.add(task) def detach(self, task): self._subscribers.remove(task) @contextmanager def subscrib...
Python
51
19.980392
44
/part-thread/test_exchange.py
0.560337
0.552853
wuljchange/interesting_python
refs/heads/master
# ---------------------------------------------- # -*- coding: utf-8 -*- # @Time : 2020-01-13 14:30 # @Author : 吴林江 # @Email : wulinjiang1@kingsoft.com # @File : kafka-consumer.py # ---------------------------------------------- from kafka import KafkaConsumer import time def start_consumer(): consumer =...
Python
30
42.966667
108
/part-kafka/kafka-consumer.py
0.515542
0.465504
wuljchange/interesting_python
refs/heads/master
import pandas as pd import numpy as np import logging logging.basicConfig(level=logging.DEBUG, format='%(asctime)s %(filename)s[line:%(lineno)d] %(levelname)s %(message)s', datefmt='%a, %d %b %Y %H:%M:%S', filename='test.log', filemode='w'...
Python
56
27.107143
97
/part-data/test-pandas.py
0.560356
0.534307
wuljchange/interesting_python
refs/heads/master
from functools import partial import math def distance(p1, p2): x1, y1 = p1 x2, y2 = p2 return math.hypot(x2-x1, y2-y1) if __name__ == "__main__": points = [(1, 2), (3, 4), (7, 8), (5, 6)] pt = (5, 6) points.sort(key=partial(distance, pt)) print(points)
Python
15
18.066668
45
/part-data/test-partial.py
0.541958
0.465035
wuljchange/interesting_python
refs/heads/master
from itertools import dropwhile, islice from itertools import permutations, combinations from itertools import combinations_with_replacement def parser(filename): with open(filename, 'rt') as f: for lineno, line in enumerate(f, 1): print(lineno, line) fields = line.split() ...
Python
50
28.959999
62
/part-text/test-iter.py
0.537742
0.521042
wuljchange/interesting_python
refs/heads/master
from operator import itemgetter from itertools import groupby data = [ {"date": 2019}, {"date": 2018}, {"date": 2020} ] data.sort(key=itemgetter('date')) print(data) for date, item in groupby(data, key=itemgetter('date')): print(date) print(item) for i in item: print(type(i), i)
Python
16
18.625
56
/part-struct/test-groupby.py
0.626198
0.587859
wuljchange/interesting_python
refs/heads/master
import gzip import bz2 if __name__ == "__main__": # gzip作用于一个已经打开的二进制文件 new character f = open('file.gz', 'rb') with gzip.open(f, 'rb') as f: print(f.read()) # with语句结束自动会关闭文件 with gzip.open('file', 'wt') as f: f.read("test") print("new line") with bz2.open('file', 'wt') as...
Python
16
21.75
39
/part-text/test-gzip.py
0.53719
0.53168
wuljchange/interesting_python
refs/heads/master
# 冒泡排序 该算法的事件复杂度未O(N^2) # 具体过程如下 首先遍历数组中的n个元素,对数组中的相邻元素进行比较,如果左边的元素大于右边的元素,则交换两个元素所在的 # 位置,至此,数组的最右端的元素变成最大的元素,接着对剩下的n-1个元素执行相同的操作。 def bubble_sort(data: list): # 外面的循环控制内部循环排序的次数,例如5个数,只需要4次排序就行了 for i in range(len(data)-1): change = False # 内部循环比较相邻元素,找到剩下元素的最大值放在数组的右边 for j in range...
Python
24
27.041666
61
/part-sort-alogrithm/test-bubble.py
0.584821
0.563988
wuljchange/interesting_python
refs/heads/master
from plumbum import local, FG, BG, cli, SshMachine, colors from plumbum.cmd import grep, awk, wc, head, cat, ls, tail, sudo, ifconfig if __name__ == "__main__": ls = local["ls"] print(ls()) # 环境在linux # 管道符 pipe command = ls["-a"] | awk['{if($2="100") print $2}'] | wc["-l"] print(command()) ...
Python
24
32.291668
99
/part-plumbum/test01.py
0.524405
0.509387
wuljchange/interesting_python
refs/heads/master
# ---------------------------------------------- # -*- coding: utf-8 -*- # @Time : 2019-11-08 11:42 # @Author : 吴林江 # @Email : wulinjiang1@kingsoft.com # @File : test-requests.py # ---------------------------------------------- import requests if __name__ == "__main__": url = "https://cn.bing.com/" r...
Python
15
26.266666
62
/part-requests/test-requests.py
0.426471
0.394608
wuljchange/interesting_python
refs/heads/master
# ---------------------------------------------- # -*- coding: utf-8 -*- # @Time : 2020-03-04 23:48 # @Author : 吴林江 # @Email : wulinjiang1@kingsoft.com # @File : test11.py # ---------------------------------------------- class Demo: def __init__(self, x, y, z): self.x = x self.y = y ...
Python
102
20.59804
92
/part-interview/test11.py
0.529278
0.507036
wuljchange/interesting_python
refs/heads/master
# 选择排序 时间复杂度时O(N^2) # 具体过程如下 首先在n个元素的数组中找到最小值放在数组的最左端,然后在剩下的n-1个元素中找到最小值放在左边第二个位置 # 以此类推,直到所有元素的顺序都已经确定 def select_sort(data: list): # 外部循环只需遍历n-1次 for i in range(len(data)-1): for j in range(i+1, len(data)): if data[i] > data[j]: data[i], data[j] = data[j], data[i] ret...
Python
17
23.588236
61
/part-sort-alogrithm/test-select.py
0.57554
0.551559
wuljchange/interesting_python
refs/heads/master
# 插入排序 时间复杂度O(N^2) # 具体过程如下 每次循环往已经排好序的数组从后往前插入一个元素,第一趟比较两个元素的大小,第二趟插入元素 # 与前两个元素进行比较,放到合适的位置,以此类推。 def insert_sort(data: list): for i in range(1, len(data)): key = data[i] # 相当于相邻元素进行比较,但是逻辑更清楚一点 for j in range(i-1, -1, -1): if data[j] > key: data[j+1] = data[j...
Python
19
23.894737
53
/part-sort-alogrithm/test-insert.py
0.527542
0.491525
wuljchange/interesting_python
refs/heads/master
import jsane if __name__ == "__main__": # jsane是一个json解析器 # loads 解析一个json字符串 j = jsane.loads('{"name": "wulj", "value": "pass"}') print(j.name.r()) # from_dict 解析字典 j2 = jsane.from_dict({'key': ['v1', 'v2', ['v3', 'v4', {'inner': 'value'}]]}) print(j2.key[2][2].inner.r()) # 当解析找不到key时...
Python
13
27.23077
81
/part-jsane/test01.py
0.536785
0.512262
wuljchange/interesting_python
refs/heads/master
# ---------------------------------------------- # -*- coding: utf-8 -*- # @Time : 2020-03-05 20:00 # @Author : 吴林江 # @Email : wulinjiang1@kingsoft.com # @File : test12.py # ---------------------------------------------- from abc import abstractmethod, ABCMeta class Interface(object): __metaclass__ = ABC...
Python
37
16.756756
48
/part-interview/test12.py
0.446646
0.423781
wuljchange/interesting_python
refs/heads/master
if __name__ == "__main__": x = 1234 # 函数形式 print(bin(x)) print(oct(x)) print(hex(x)) # format形式,没有前缀 0b,0o,0x print(format(x, 'b')) print(format(x, 'o')) print(format(x, 'x')) #将进制的数据转换成整数字符串 a = format(x, 'b') b = format(x, 'x') print(int(a, 2)) print(int(b, 16))
Python
15
20.4
28
/part-data/test-scale.py
0.4875
0.45625
wuljchange/interesting_python
refs/heads/master
import glob import fnmatch import os.path if __name__ == "__main__": dir_path = '/root/tmp/test' path = '/root/tmp/test/*.py' pyfiles = glob.glob(path) pyfiles2 = [name for name in os.listdir(dir_path) if fnmatch(name, '*.py')]
Python
10
23.6
79
/part-text/test-glob-fnmatch.py
0.616327
0.612245
wuljchange/interesting_python
refs/heads/master
import arrow import re import pdb import tempfile if __name__ == "__main__": # print(arrow.now().shift(days=-1).format('YYYY-MM-DD')) # data = ['merge', '1', 'commit', 'merge'] # data.remove('1') # print(data) # d = [{'code': 12}, {'code': 11}, {'code': 13}] # d.sort(key=lambda x: x['code']) ...
Python
21
25.476191
60
/part-text/test-list.py
0.493694
0.475676
wuljchange/interesting_python
refs/heads/master
import re text = '/* http new s */' r = re.compile(r'/\*(.*?)\*/') print(r.findall(text))
Python
6
14.333333
30
/part-text/test-re.py
0.521739
0.521739
wuljchange/interesting_python
refs/heads/master
# import smtplib # from email.mime.text import MIMEText # from email.header import Header # # # 第三方 SMTP 服务 # mail_host = "smtp.qq.com" # 设置服务器 # mail_user = "" # 用户名 # mail_pass = "XXXXXX" # 口令 # # sender = 'from@runoob.com' # receivers = ['429240967@qq.com'] # 接收邮件,可设置为你的QQ邮箱或者其他邮箱 # # message = MIMEText('Python ...
Python
43
24.906977
62
/part-text/test-smtp.py
0.606469
0.592093
wuljchange/interesting_python
refs/heads/master
from decimal import Decimal, localcontext def main(a, b): a = Decimal(a) b = Decimal(b) return a+b if __name__ == "__main__": sum = main('3.2', '4.3') # 使用上下文管理器更改输出的配置信息 with localcontext() as ctx: ctx.prec = 3 print(Decimal('3.2')/Decimal('2.3')) print(sum == 7.5)
Python
16
18.6875
44
/part-data/test-decimal.py
0.542857
0.507937
wuljchange/interesting_python
refs/heads/master
# 快速排序 时间复杂度时O(NlogN) # 具体过程如下 采用一种分治递归的算法 从数组中任意选择一个数作为基准值,然后将数组中比基准值小的放在左边 # 比基准值大的放在右边,然后对左右两边的数使用递归的方法排序 def partition(data, start, end): i = start - 1 for j in range(start, end): # 刚开始以data[end]的值作为基准值 if data[j] < data[end]: i += 1 # 如果j所在的位置的值小于end,则i往前进一步,并与j的值交...
Python
29
24.758621
64
/part-sort-alogrithm/test-quick.py
0.579088
0.563003
wuljchange/interesting_python
refs/heads/master
# ---------------------------------------------- # -*- coding: utf-8 -*- # @Time : 2020-03-07 12:18 # @Author : 吴林江 # @Email : wulinjiang1@kingsoft.com # @File : test15.py # ---------------------------------------------- if __name__ == "__main__": # filter 方法,func + iterator data = [i for i in range(...
Python
17
27.941177
58
/part-interview/test15.py
0.465447
0.422764
wuljchange/interesting_python
refs/heads/master
if __name__ == "__main__": # list,dict,set是不可hash的 # int,float,str,tuple是可以hash的 data = [1, 2, '232', (2, 3)] data1 = [2, 3, '213', (2, 3)] # 两个list取补集,元素在data中,不在data1中 diff_list = list(set(data).difference(set(data1))) print(diff_list) # 取交集 inter_list = list(set(data).intersecti...
Python
17
25
57
/part-text/test-set.py
0.585034
0.54195
wuljchange/interesting_python
refs/heads/master
import arrow bracket_dct = {'(': ')', '{': '}', '[': ']', '<': '>'} def bracket(arg: str): match_stack = [] for char in arg: if char in bracket_dct.keys(): match_stack.append(char) elif char in bracket_dct.values(): if len(match_stack) > 0 and bracket_dct[match_stack....
Python
25
23.68
79
/part-text/bracket_expression.py
0.49919
0.479741
wuljchange/interesting_python
refs/heads/master
import threading from socket import socket, AF_INET, SOCK_STREAM from functools import partial from contextlib import contextmanager # State to stored info on locks already acquired _local = threading.local() @contextmanager def acquire(*locks): locks = sorted(locks, key=lambda x: id(x)) acquired = getattr...
Python
65
25.384615
73
/part-thread/thread_lock.py
0.61691
0.608163
wuljchange/interesting_python
refs/heads/master
import os.path import time import glob import fnmatch if __name__ == "__main__": dir_path = '/data/proc/log' file_name = [name for name in os.listdir(dir_path) if os.path.isfile(os.path.join(dir_path, name))] dir_name = [name for name in os.listdir(dir_path) if os.path.isdir(os.path.join(dir_path, name))]...
Python
30
30
103
/part-text/test-path.py
0.649085
0.649085
wuljchange/interesting_python
refs/heads/master
from marshmallow import Schema, fields, post_load, pprint from hashlib import md5 sort_key = ['name', 'role'] class Actor(object): """ 创建actor基础类 """ def __init__(self, name, role, grade): self.name = name self.role = role self.grade = grade def __str__(self): ret...
Python
104
23.875
67
/part-marshmallow/test-load&dump.py
0.558903
0.551564
wuljchange/interesting_python
refs/heads/master
def async_apply(func, args, *, callback): result = func(*args) callback(result) def make_handle(): sequence = 0 while True: result = yield sequence += 1 print('[{}] result is {}'.format(sequence, result)) if __name__ == "__main__": # 协程处理 handle = make_handle() ne...
Python
20
22
59
/part-data/test-callback.py
0.566449
0.553377
wuljchange/interesting_python
refs/heads/master
from collections import OrderedDict def dedupe(items): """ 删除一个迭代器中重复的元素,并保持顺序 :param items: 迭代器 :return: """ a = set() for item in items: if item not in a: yield item a.add(item) # 找出一个字符串中最长的没有重复字符的字段 def cutout(test: str): max_data = [] for s in tes...
Python
44
19.15909
61
/part-text/data/test-copy-text.py
0.529345
0.521445
wuljchange/interesting_python
refs/heads/master
from itertools import compress import re import arrow addresses = [ '5412 N CLARK', '5148 N CLARK', '5800 E 58TH', '2122 N CLARK', '5645 N RAVENSWOOD', '1060 W ADDISON', '4801 N BROADWAY', '1039 W GRANVILLE', ] counts = [0, 3, 10, 4, 1, 7, 6, 1] new = [n > 5 for n in counts] l = list...
Python
27
18.370371
38
/part-struct/test-compress.py
0.590822
0.462715
wuljchange/interesting_python
refs/heads/master
# ---------------------------------------------- # -*- coding: utf-8 -*- # @Time : 2020-03-04 15:31 # @Author : 吴林江 # @Email : wulinjiang1@kingsoft.com # @File : test09.py # ---------------------------------------------- import pymysql # 打开数据库连接 db = pymysql.connect("host", "username", "pw", "db") # 创建一个游标对象...
Python
29
18.137932
52
/part-interview/test09.py
0.538739
0.506306
wuljchange/interesting_python
refs/heads/master
import random if __name__ == "__main__": values = [1, 2, 3, 4, 5] # 随机选取一个元素 print(random.choice(values)) # 随机选取几个元素且不重复 print(random.sample(values, 3)) # 打乱原序列中的顺序 print(random.shuffle(values)) # 生成随机整数,包括边界值 print(random.randint(0, 10)) # 生成0-1的小数 print(random.random()) ...
Python
17
20.764706
35
/part-data/test-random.py
0.604336
0.569106
wuljchange/interesting_python
refs/heads/master
import base64 import binascii if __name__ == "__main__": s = b'hello world!' # 2进制转换成16进制 h = binascii.b2a_hex(s) print(h) # 16进制转换成2进制 print(binascii.a2b_hex(h)) h1 = base64.b16encode(s) print(h1) print(base64.b16decode(h1))
Python
14
17.857143
31
/part-data/test-hex.py
0.596958
0.51711
wuljchange/interesting_python
refs/heads/master
from struct import Struct def record_data(records, format, file): record_struct = Struct(format) for r in records: file.write(record_struct.pack(*r)) def read_data(format, f): """ 增量块的形式迭代 :param format: :param f: :return: """ read_struct = Struct(format) chunks = ite...
Python
40
19.950001
96
/part-data/test-b2-struct.py
0.561529
0.549582
wuljchange/interesting_python
refs/heads/master
# ---------------------------------------------- # -*- coding: utf-8 -*- # @Time : 2019-11-25 17:49 # @Author : 吴林江 # @Email : wulinjiang1@kingsoft.com # @File : test-elasticsearch.py # ---------------------------------------------- from elasticsearch import Elasticsearch from ssl import create_default_context...
Python
21
26.761906
55
/part-elasticsearch/test-elasticsearch.py
0.480274
0.433962
wuljchange/interesting_python
refs/heads/master
# ---------------------------------------------- # -*- coding: utf-8 -*- # @Time : 2020-03-01 12:33 # @Author : 吴林江 # @Email : wulinjiang1@kingsoft.com # @File : test04.py # ---------------------------------------------- if __name__ == "__main__": # 字典操作 dct = {"a": 1, "b": 2} a = dct.pop("a") ...
Python
29
23.689655
48
/part-interview/test04.py
0.393007
0.351049
wuljchange/interesting_python
refs/heads/master
# ---------------------------------------------- # -*- coding: utf-8 -*- # @Time : 2020-03-01 12:45 # @Author : 吴林江 # @Email : wulinjiang1@kingsoft.com # @File : test05.py # ---------------------------------------------- # 定义一个生成器的函数,需要用到 yield def my_generate(nums): for i in nums: yield i if _...
Python
38
19.552631
48
/part-interview/test05.py
0.420513
0.385897
wuljchange/interesting_python
refs/heads/master
from functools import partial from socket import socket, AF_INET, SOCK_STREAM class LazyConnection: def __init__(self, address, family=AF_INET, type=SOCK_STREAM): self.address = address self.family = family self.type = type self.connections = [] def __enter__(self): so...
Python
28
24.571428
66
/part-class/test-with.py
0.59021
0.584615
wuljchange/interesting_python
refs/heads/master
data = ['test', 90, 80, (1995, 8, 30)] if __name__ == "__main__": _, start, end, (_, _, day) = data print(start) print(end) print(day)
Python
8
18.125
38
/part-struct/upack-value.py
0.460526
0.388158
wuljchange/interesting_python
refs/heads/master
# ---------------------------------------------- # -*- coding: utf-8 -*- # @Time : 2020-03-06 10:58 # @Author : 吴林江 # @Email : wulinjiang1@kingsoft.com # @File : test14.py # ---------------------------------------------- class Demo(object): # 类的属性 count = 0 def __init__(self, x, y): self...
Python
95
19.589474
66
/part-interview/test14.py
0.478305
0.465544
wuljchange/interesting_python
refs/heads/master
import collections import bisect class ItemSequence(collections.Sequence): def __init__(self, initial=None): self._items = sorted(initial) if initial is not None else [] def __getitem__(self, item): return self._items[item] def __len__(self): return len(self._items) # bisect...
Python
21
21.476191
68
/part-class/test-iter-inial.py
0.613588
0.607219
wuljchange/interesting_python
refs/heads/master
# ---------------------------------------------- # -*- coding: utf-8 -*- # @Time : 2019-11-07 18:50 # @Author : 吴林江 # @Email : wulinjiang1@kingsoft.com # @File : test-sanic.py # ---------------------------------------------- from sanic import Sanic from sanic.response import json from pprint import pprint ap...
Python
23
21.217392
50
/part-sanic/test-sanic.py
0.495108
0.454012
wuljchange/interesting_python
refs/heads/master
# ---------------------------------------------- # -*- coding: utf-8 -*- # @Time : 2020-03-04 16:38 # @Author : 吴林江 # @Email : wulinjiang1@kingsoft.com # @File : test10.py # ---------------------------------------------- import redis import uuid import time from threading import Thread redis_client = redis.R...
Python
77
25.350649
101
/part-interview/test10.py
0.53721
0.517989
wuljchange/interesting_python
refs/heads/master
from collections import Iterable import random import heapq # 处理嵌套列表 def flatten(items, ignore_types=(str, bytes)): for item in items: if isinstance(item, Iterable) and not isinstance(item, ignore_types): yield from flatten(item) else: yield item if __name__ == "__main__"...
Python
36
25
92
/part-text/test-yield.py
0.528342
0.483422
wuljchange/interesting_python
refs/heads/master
from marshmallow import Schema, fields, pprint, post_load, post_dump, ValidationError from datetime import datetime class VideoLog(object): """ vlog基础类 """ def __init__(self, **data): for k, v in data.items(): setattr(self, k, v) def __str__(self): return '<VideoLog_st...
Python
121
26.272728
90
/part-marshmallow/test-load&dump2.py
0.625492
0.623675
wuljchange/interesting_python
refs/heads/master
# ---------------------------------------------- # -*- coding: utf-8 -*- # @Time : 2020-03-03 20:58 # @Author : 吴林江 # @Email : wulinjiang1@kingsoft.com # @File : test07.py # ---------------------------------------------- from pymongo import MongoClient class PyMongoDemo: def __init__(self): self....
Python
32
30.40625
107
/part-interview/test07.py
0.49004
0.465139
wuljchange/interesting_python
refs/heads/master
# ---------------------------------------------- # -*- coding: utf-8 -*- # @Time : 2020-03-08 12:13 # @Author : 吴林江 # @Email : wulinjiang1@kingsoft.com # @File : test20.py # ---------------------------------------------- from collections import defaultdict if __name__ == "__main__": # 找出列表中重复的元素 data...
Python
22
23.818182
48
/part-interview/test20.py
0.39633
0.352294
wuljchange/interesting_python
refs/heads/master
# 使用lambda对list排序,正数在前,从小到大,负数在后,从大到小 # lambda设置2个条件,先将小于0的排在后面,再对每一部分绝对值排序 data = [-5, 8, 0, 4, 9, -4, -20, -2, 8, 2, -4] a = sorted(data, key=lambda x: (x < 0, abs(x))) print(a)
Python
5
35
47
/part-interview/test01.py
0.631285
0.547486
wuljchange/interesting_python
refs/heads/master
# ---------------------------------------------- # -*- coding: utf-8 -*- # @Time : 2020-03-04 10:32 # @Author : 吴林江 # @Email : wulinjiang1@kingsoft.com # @File : test08.py # ---------------------------------------------- import redis if __name__ == "__main__": # redis 现有的数据类型 # 1. String 二进制安全,可以包含任何...
Python
150
31.9
112
/part-interview/test08.py
0.608026
0.571747
wuljchange/interesting_python
refs/heads/master
from selenium import webdriver from selenium.webdriver.common.by import By if __name__ == "__main__": # 加载浏览器 browser = webdriver.Chrome() # 获取页面 browser.get('https://www.baidu.com') print(browser.page_source) # 查找单个元素 input_first = browser.find_element_by_id('q') input_second = browse...
Python
17
28.117647
61
/part-selenium/test01.py
0.650505
0.650505
wuljchange/interesting_python
refs/heads/master
from operator import itemgetter, attrgetter class User: def __init__(self, uid, name): self.uid = uid self.name = name def get_name(self): return self.name if __name__ == "__main__": datas = [ {'fname': 'Brian', 'lname': 'Jones', 'uid': 1003}, {'fname': 'David', ...
Python
30
30
67
/part-struct/sort-dict.py
0.555436
0.528525
wuljchange/interesting_python
refs/heads/master
# ---------------------------------------------- # -*- coding: utf-8 -*- # @Time : 2020-03-05 20:43 # @Author : 吴林江 # @Email : wulinjiang1@kingsoft.com # @File : test13.py # ---------------------------------------------- import test10 if __name__ == "__main__": # python3 高级特性,反射 # 字符串返回映射到代码的一种机制,pyt...
Python
21
24.142857
71
/part-interview/test13.py
0.477273
0.433712
wuljchange/interesting_python
refs/heads/master
from collections import deque def search(lines, pattern, history): pre_lines = deque(maxlen=history) for line in lines: if pattern in line: pre_lines.append(line) return pre_lines if __name__ == "__main__": with open('tmp/test', 'r') as f: s = search(f, 'python', 5) ...
Python
22
21.5
37
/part-struct/test-deque.py
0.52834
0.524292
wuljchange/interesting_python
refs/heads/master
from collections import Counter, defaultdict import requests import arrow class Data: def __init__(self, data): self.data = data if __name__ == "__main__": url = 'http://10.100.51.45/rate/repair?start={}&end={}' start = '2019-04-01 23:10' end = '2019-04-07 23:10' ret = requests.get(url.f...
Python
58
25.827587
63
/part-text/test-tt.py
0.47717
0.430225
wuljchange/interesting_python
refs/heads/master
from functools import partial # 从指定文件按固定大小迭代 with open('file', 'rb') as f: re_size = 32 records = iter(partial(f.read, re_size), b'') for r in records: print(r)
Python
9
19.333334
49
/part-text/test-fixed-record.py
0.615385
0.604396
wuljchange/interesting_python
refs/heads/master
records = [('foo', 1, 2), ('bar', 'hello'), ('foo', 3, 4), ] def drop_first_last(grades): _, *middle, _ = grades return middle def do_foo(x, y): print('foo', x, y) def do_bar(s): print('bar', s) if __name__ == "__main__": for tag, *args in records: pr...
Python
28
15.892858
30
/part-struct/unpack-value2.py
0.425847
0.417373
wuljchange/interesting_python
refs/heads/master
import re import os if __name__ == "__main__": s = " hello new world \n" # strip用于取出首尾指定字符 print(s.strip()) print(s.lstrip()) print(s.rstrip()) s = "test ?" s1 = s.replace('?', 'new') print(s1) s2 = re.sub('new', 'fresh', s1, flags=re.IGNORECASE) print(s2)
Python
15
18.933332
56
/part-text/test-strip.py
0.526846
0.510067
wuljchange/interesting_python
refs/heads/master
class Structure1: _fields = [] def __init__(self, *args, **kwargs): if len(args) > len(self._fields): raise TypeError('Excepted {} arguments'.format(len(self._fields))) for name, value in zip(self._fields, args): setattr(self, name, value) for name in self._fie...
Python
51
28.588236
78
/part-class/test-class.py
0.553347
0.53943