The Collection of classic codes with Python(updated in 2019.03.22)

Cracking Codes with Python Learn how to program in Python while making and breaking ciphers—algorithms used to create and send secret messages! 立即下载

12.对实验结果进行one-sided Wilcoxon rank-sum p-value

import scipy.stats as stats

baseline = [1,2,3,4,5]
our_model = [6,7,8,9]
stat_val, p_val=stats.mannwhitneyu(our_model,baseline,alternative="greater")#stats.ttest_ind(x, y, equal_var=False)
"""
H0:y<=x
H1:y>x
if p-value<0.05, reject H0
"""
print ('Two-sample t-statistic D = %6.3f, p-value = %6.4f' % (stat_val, p_val))

"""
Two-sample t-statistic D = 20.000, p-value = 0.0100
p-value<0.05这说明H0 reject,接受H1,即our-model 好于baseline
"""

11.张量维度操作(拼接、维度扩展、压缩、转置、重复……)

https://zhuanlan.zhihu.com/p/31495102

10.将一个字符序列转变为one-hot编码

"""
例如:
输入:['a','b','c','a']
输出:
[ [1,0,0],
  [0,1,0],
  [0,0,1],
  [1,0,0]
]"""


def _label_string2matrix(nodes_labels_str):
    b, c = np.unique(nodes_labels_str, return_inverse=True)
    class_num = len(b)
    sample_num = len(c)
    class_num = class_num
    nodes_labels = torch.zeros((sample_num, class_num))
    i = 0
    for la in c:
        nodes_labels[i, la] = 1.0
        i = i + 1
    return nodes_labels

9. 多进程

类型一:多个进程执行相同的任务(举行模块切分)

from concurrent.futures import ProcessPoolExecutor

a_very_big_list = []

for item in a_very_big_list:
    """
    你需要确保这个for循环每一轮之间是互不影响的, 否则无法进行并行化的处理
    some codes include:
    1. your logic functions
    2. some parameters (read only)
    3. some variables (you want to get or return)
    """
    parameters = None
    variables = None


def _fun(list_split, parameters):
    _variables = []
    for item in list_split:
        _variables = parameters

    return _variables


def fun(a_very_big_list, parameters=None, workers=8):
    list_split = []
    step = int(len(a_very_big_list) / workers)
    for i in range(workers):
        if i != workers - 1:
            # print('slice: ', i * step, ' ', (i + 1) * step)
            split = a_very_big_list[i * step:(i + 1) * step]
        else:
            # print('slice: ', i * step)
            split = a_very_big_list[i * step:]
        list_split.append(split)

    variables = []
    print("len(wblog_content_split): ", len(list_split))
    with ProcessPoolExecutor(max_workers=workers) as executor:
        for _variables in executor.map(_fun,
                                       list_split,
                                       [parameters for i in range(workers)]):
            """
            接下来你需要把每一个进程返回的结果进行组装,组装的方式要根据具体的情况灵活设计,
            例如对于不受影响的dic,可以使用dic.update
            对于list,可以使用+进行拼接
            """
            variables = variables + _variables
    return variables

类型二:多个进程执行不同的任务

import multiprocessing

def fun_1(parameter):
    pass

def fun_2(parameter):
    pass

def fun_3():
    pass
def fun_4():
    pass

parameter=None
p1 = multiprocessing.Process(target=fun_1, args=(parameter,))
p2 = multiprocessing.Process(target=fun_2, args=(parameter,))
p1.start()
p2.start()
p1.join()
fun_3()
p2.join()
fun_4()
"""
进程执行的路线图
fun_1 | fun_2
  |       |
  v       v
fun_3 | fun_4
请注意,进程之间是不共享数据的,不要企图在类里面这样使用,实际上会创建好几个类对象,并且各个进程只会修改自己类对象里面的变量

"""

8. 打混数据并保证索引按照正常的排序

df.sample(frac=1).reset_index(drop=True)

7. 解析json字符串并返回支持属性访问的对象

from argparse import Namespace
import json
def json_to_object(data):
    return json.loads(data, object_hook=lambda d: Namespace(**d))

with open("default.json") as f:
    args = json_to_object(f.read())

6. 概率化编程


def add_unknown_words(word_vecs, vocab, min_df=1, k=300):
    """
    For words that occur in at least min_df documents, 
    create a separate word vector.
    same variance as pre-trained ones
    """
    for word in vocab:
        if word not in word_vecs and vocab[word] >= min_df:
            word_vecs[word] = np.random.uniform(-0.25,0.25,k)
            print(word)

def pro(pro):
  if random.random()<=pro:
    pass

5. 定义一段弃用的代码

有时候有些函数功能我们打算弃用,但是担心版本不兼容,为例保持借口的兼容性,可以仿照下面的代码进行编程

 @deprecated("Method will be removed in 4.0.0, use self.wv.__getitem__() instead")
    def __getitem__(self, words):
        """
        Deprecated. Use self.wv.__getitem__() instead.
        Refer to the documentation for `gensim.models.keyedvectors.Word2VecKeyedVectors.__getitem__`
        """
        return self.wv.__getitem__(words)

4. 计算文件行数

def count_lines(f):
    if path.isfile(f):  # Test whether a path is a regular file
        num_lines = sum(1 for line in open(f))
        """
        上面这行代码相当于:
            a=[1 for line in open(f)] # a=[1,1,1,1,1,...,1]
            num_lines = sum(a)
        """
        return num_lines
    else:
        return 0

3. 计算一组文件里单词的词频


#! /usr/bin/env python
# -*- coding: utf-8 -*-
from concurrent.futures import ProcessPoolExecutor
from collections import Counter


def count_words(file):
    c = Counter()
    with open(file, 'r') as f:
        for l in f:
            words = l.strip().split()
            c.update(words)
    return c


def count_textfiles(files, workers=1):
    c = Counter()
    with ProcessPoolExecutor(max_workers=workers) as executor:
        for c_ in executor.map(count_words, files):
            c.update(c_)
    return c

2. 代码计时


from time import time
t0 = time()
your code here
t1 = time()
print('make_directed: added missing edges {}s'.format(t1 - t0))

1. 创建一个可迭代的文件对象


class WalksCorpus(object):
    def __init__(self, file_list):
        """

        :param file_list: 这是write_walks_to_disk写在本地里的一组文件列表
        """
        self.file_list = file_list

    def __iter__(self):
        """
        Python 中的顺序类型,都是可迭代的(list, tuple, string)。
        其余包括 dict, set, file 也是可迭代的。
        对于用户自己实现的类型,如果提供了 __iter__() 或者 __getitem__() 方法,
        那么该类的对象也是可迭代的。


        假如file_list=['output.walks.0','output.walks.1']其中
        'output.walks.0':
        8 2 4 8 2 31 34 28 24 28 25 28 3 10 3
        2 1 22 1 18 2 8 2 4 2 18 1 8 3 2 1
        'output.walks.1':
         32 25 26 32 29 3 33 31 9 33 16 34
         6 11 1 20 34 30 24 30 24 28 3 1 14

        那么这个函数返回后得到的就是:
        [   [8, 2, 4, 8, 2, 31, 34, 28, 24, 28, 25, 28, 3, 10, 3],
            [2, 1, 22, 1, 18, 2, 8, 2, 4, 2, 18, 1, 8, 3, 2, 1],
            [32, 25, 26, 32, 29, 3, 33, 31, 9, 33, 16, 34 ],
            [6, 11, 1, 20, 34, 30, 24, 30, 24, 28, 3, 1, 14]
        ]


        更多关于迭代和yield的内容,可以参考博文
        [Python 中的黑暗角落(一):理解 yield 关键字](https://liam0205.me/2017/06/30/understanding-yield-in-python/)
        :return:
        """
        for file in self.file_list:
            with open(file, 'r') as f:
                for line in f:
                    yield line.split()


walk_files="your_file.txt"
walks = WalksCorpus(walk_files)
Cracking Codes with Python (True PDF) Cracking Codes with Python: An Introduction to Building and Breaking Ciphers (True PDF) 立即下载

相关推荐

Hacking Secret Ciphers with Python 无水印pdf

Hacking Secret Ciphers with Python 英文无水印pdf pdf所有页面使用FoxitReader和PDF-XChangeViewer测试都可以打开 本资源转载自网络,如有侵权,请联系上传者或csdn删除 本资源转载自网络,如有侵权,请联系上传者或csdn删除

DeprecationWarning: Call to deprecated `__getitem__` (Method will be removed in 4.0.0, use self.wv._

from gensim.models import word2vec model = word2vec.Word2Vec.load("hoge.model") vec = model["queen"] print(len(vec.tolist())) #运行出现错误 DeprecationWarning: Call to deprecated `__getitem__` (Method will be removed in 4.0.0, use self.wv.__getitem__() instead)

2811

Cracking.Codes.with.Python.2018.1

Cracking Codes with Python 2018.1 Python 网络安全

word2vec

1、语料的预处理 novel=open('C:\\Users\\CDAer\\Desktop\\西游记.txt',mode='r',encoding='gb18030') content=novel.read() import jieba cutword=jieba.lcut(content,cut_all=False,HMM=True) Building prefix dict from ...

weixin_40903057的博客 1686

Cracking.Codes.with.Python.2018.1.epub

Cracking.Codes.with.Python.2018.1.epub Cracking.Codes.with.Python.2018.1.epub

Proteus 8.17安装部署全指南:避坑、汉化与STM32库配置

Proteus是一款广泛用于单片机仿真与电路设计的EDA工具,其核心价值在于支持嵌入式系统原型验证与教学实践。Proteus 8.17版本重构了许可证机制(LIC Engine)、依赖环境(VC++ 2019/NET 4.8)及路径加载逻辑,导致传统安装方法失效。掌握正确安装部署流程,是保障原理图绘制、VSM仿真(如51/STM32/ESP32)及外设波形观测(OLED、SPI、ADC)稳定运行的前提。本文聚焦Windows平台下零失败安装路径选择、权限配置、汉化实施与高频器件(如STM32F103)元件库

weixin_33377602的博客 402

Cracking Codes with Python—翻译(第五章:凯撒密码)

qq_42893430的博客 357

别再只会setStyleSheet了!Qt实现背景透明的5种方法全解析(附性能对比)

本文深入解析Qt实现背景透明的5种高阶方案,包括QPalette、setWindowOpacity、QGraphicsOpacityEffect、样式表和复合透明方案,并提供详细的性能对比与优化建议。针对不同平台和场景,帮助开发者选择最适合的透明效果实现方式,提升UI设计质量与性能表现。

weixin_27061475的博客 259

Initialization of all the collectors failed.

MapReduce在集群执行任务时报错:Initialization of all the collectors failed. Error in last collector was:java.lang.ClassCastException 将 import javax.xml.soap.Text; 修改为 import javax.xml.soap.Text;

jzj_c_love的博客 468

大连海事大学课设题目/基于LM331的频率电压转换器

部分基于LM331的频压转换的实物连接问题

2301_76649592的博客 3227

stm32驱动NRF24L01_原理+代码解析

NRF24L01是NORDIC公司生产的一款无线通信通信芯片,采用FSK 调制,集成NORDIC自家的Enhanced Short Burst协议。可以实现点对点或是1对6的无线通信。无线通信速度最高可达到2Mbps。①2.4G全球开放的ISM频段,免许可证使用。②最高工作速率2Mbps,高校的GFSK调制,抗干扰能力强。③126个可选的频道,满足多点通信和调频通信的需要。④内置CRC检错和点对多点的通信地址控制。⑤可设置自动应答,确保数据可靠传输。//NRF24L01寄存器操作命令。

zyc18700766982的博客 2万+

Cracking Codes with Python—翻译(第六章:暴力破解法破译凯撒密码)

qq_42893430的博客 552

1.FPGA开发软件安装——Vivado

目前主流的FPGA公司包括xilinx和Intel(原altera公司),其开发软件分别为vivado和quartusii。我们这里以目前国内应用较多的vivado为例进行安装讲解。 1、首先是去官网下载 Vivado 安装包:https://www.xilinx.com/support/download.html。下载这个最大的、支持所有的 OS 如 Windows/Linux 的安装包。 2、下载完之后,就进行解压。(最好在解压和安装之前都关闭所有的杀毒软件以防万一)。紧接着,解压完之后...

FPGA/MATLAB学习教程/源码/项目合作开发 8257

Cracking Codes with Python—翻译(第一章:在纸上制作加密工具)

阿萨大

qq_42893430的博客 766

CTK Plugin Framework插件框架学习1--Qt编译CTK

【代码】Qt编译CTK。

贝勒里恩的博客 7432

高频注入是否需要对齐和强拖操作?

高频注入技术显著优化了传统FOC启动流程,但仍需部分对齐操作。传统启动必须包含位置检测、对齐和强拖等步骤,而高频注入可实现零速闭环,简化或跳过部分环节。高频注入下的对齐主要用于验证有效性、初始化观测器和建立初始磁链,形式可大幅简化。虽然高频注入基本消除了传统强拖需求,但在重载、弱凸极等特殊情况下仍需辅助。实际应用中可采用自适应混合策略,根据负载和电机类型选择最优启动方案。高频注入使对齐和强拖从"必须"变为"可选优化项",是无传感器控制的重要进步。

汽车软件开发 204

Initialization of all the collectors failed. Error in last collector was :class com.xx.mapreduce.w

突然遇到的,网上查找了很多说法,说是bean没有实现writable接口,nono!其实是一个灰常灰常低级灰常的错误! Initialization of all the collectors failed. Error in last collector was :class com.xxx.mapreduce.webLog.WebLogMapper 伴随的还有: java.lang.C...

xhao327的专栏 1194

手把手教您如何群晖/飞牛NAS等服务器上一键部署洛雪音乐同步服务,手机电脑无缝同步歌单,支持外网访问

🎵 手机电脑歌单不同步?用Docker在群晖/飞牛NAS等服务器上搭个同步服务器, 3分钟搞定 !支持docker-compose一键部署,手机、电脑、平板收藏夹实时同步,外出也能用域名远程访问 ~ ✨

XiaoqiangClub的博客 4605

java.io.IOException: Initialization of all the collectors failed

打jar包在linux上运行,用于演示wordcount原理,结果没有起来。 提示异常:java.io.IOException: Initialization of all the collectors failed. Error in last collector was :class com.sun.jersey.core.impl.provider.entity.XMLJAXBEleme...

qq_35441940的博客 1865

Outlook Express 6 (OE6) for Win7/Win8/Win10

英文版 Outlook Express6.0, 兼容Win7/Win10/WinXP,解压就可用。

廖雪峰Python教程[完整版]

廖雪峰的python教程整理的,已经排好版了,而且还是完整的,适合小白

NLP之gensim:基于fetch_20newsgroups数据集利用word2vec算法进行词向量训练并推理(输出指定单词最相关的10个词汇)

NLP之gensim:基于fetch_20newsgroups数据集利用word2vec算法进行词向量训练并推理(输出指定单词最相关的10个词汇)相关文章。

头部AI社区如有邀博主AI主题演讲请私信—心比天高,仗剑走天涯,保持热爱,奔赴向梦想!低调,专注,谦虚,自律,反思,成长,还算比较正能量的博主,公益免费传播…内心特别想在AI界做出一些可以推进历史进程影响力的技术(兴趣使然,有点小情怀,也有点使命感呀 1万+

温度PID控制PLC程序

温度PID稳定控制程序,适用于欧姆龙PLC,对其他PLC也具有很大参考价值

DeprecationWarning: Call to deprecated `wv` (Attribute will be removed in 4.0.0, use self instead).

word2vec模型调用model.wv.similarity()出现 DeprecationWarning: Call to deprecated wv (Attribute will be removed in 4.0.0, use self instead). 弃用警告:调用不推荐使用的“wv”(在4.0.0中属性将被删除,请改用self)。 model.wv.similarity()改为model.similarity()即可。 ...

予早随笔 971

怀旧版电脑GBC模拟器

再现原版GBC掌机的界面,电脑运行连游戏界面都一样大小,很怀旧,很真实,(英文版)强烈推荐,很小的文件,很难才找到的。

kaggle Home Depot relevance相关性预测

Home Depot 产品相关性预测 kaggle竞赛:https://www.kaggle.com/c/home-depot-product-search-relevance HomeDepot是美国一家家具建材商品网站,用户通过在搜索框中输入关键词,得到相关商品和服务,如输入floor,得到不同材料的地板商品、地板清洗商品、地板安装服务等。kaggle竞赛目的是通过设计一种模型,能够更好的...

iam_emily的博客 3068

深度学习 | Word2vec原理及应用

聊聊Word2vec1 前言2 什么是Word2vec?2.1 定义2.1.1 分词的原理介绍2.1.2 文本向量化的方式2.2 数学原理2.2.1 CBOW(Continuous Bag-of-Words)原理2.2.2 Skip-Gram原理2.2.3 为什么要有Word2vec 而不是用原来的?2.2.4 Word2vec基础:霍夫曼树2.2.5 Hierarchical Softmax2....

RUC_Lee的博客 4122

自然语言处理类问题案例--2

每日新闻预测经融市场变化

weixin_43955530的博客 654

Python DeprecationWarning 类型错误

升级pymongo模块到3.x的时候,产生了下面警告:DeprecationWarning: update is deprecated. Use replace_one, update_one or update_many instead. 然后看了pymongo.collection.Collection.update方法def update(self, spec, document, ups

魔法学徒de专栏 3万+
上一篇: spacy install and problems sovled
下一篇: 【机器学习系列博客】1. 维度的诅咒
相国大人
博客等级 码龄10年 1009粉丝 132原创
评论 1
成就一亿技术人!
拼手气红包6.0元
还能输入1000个字符
 
 条评论被折叠 查看
添加红包

请填写红包祝福语或标题

个

红包个数最小为10个

元

红包金额最低5元

当前余额3.43元 前往充值 >
需支付:10.00元
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包
实付元
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载,可以购买VIP、付费专栏及课程。

余额充值