C++11 minified rlib. usually used while writing ALG solutions.

https://github.com/recolic/rlib

rlib.min.hpp

/*
 *
 * string.hpp: string process utility.
 * Recolic Keghart <[email protected]>
 * MIT License
 *
 * Minified version: works on C++11.
 *
 */

#ifndef R_STRING_HPP
#define R_STRING_HPP

#include <vector>
#include <string>
#include <stdexcept>

namespace rlib {
    class string : public std::string {
    public:
        using std::string::string;
        string() : std::string() {}
        string(const std::string &s) : std::string(s) {}
        string(std::string &&s) : std::string(std::forward<std::string>(s)) {}

    private:
        template <typename T> struct as_helper {};
        template <typename T>
        T as(as_helper<T>) const {
            if(empty()) return T();
            return T(*this);
        }
        const char *as(as_helper<const char *>) const {
            return this->c_str();
        }
        std::string as(as_helper<std::string>) const {
            return std::move(*this);
        }
        rlib::string as(as_helper<rlib::string>) const {
            return std::move(*this);
        }
        char as(as_helper<char>) const {
            if(size() > 1)
                throw std::invalid_argument("Can not convert rlib::string to char: size() > 1.");
            return size() == 0 ? '' : *cbegin();
        }
        // unsigned-char conflicts with uint8_t. I'll regard it as uint8_t. ("8".as<unsigned char> == 8)
        //unsigned char as(as_helper<unsigned char>) const {
        //    return static_cast<unsigned char>(as<char>());
        //}
        bool as(as_helper<bool>) const {
            if(*this == "true") {
                return true;
            }
            else if(*this == "false") {
                return false;
            }
            // Nothing is slower than throw(); Just test more cases...
            else if(*this == "1" || *this == "True" || *this == "TRUE") {
                return true;
            }
            else if(*this == "0" || *this == "False" || *this == "FALSE") {
                return false;
            }
            throw std::invalid_argument("Can not convert rlib::string to bool. Not matching any template.");
        }

#define RLIB_IMPL_GEN_AS_NUMERIC(type, std_conv) 
        type as(as_helper<type>) const { 
            if(empty()) return 0; 
            return std::std_conv(*this); 
        }

        RLIB_IMPL_GEN_AS_NUMERIC(int, stoi)
        RLIB_IMPL_GEN_AS_NUMERIC(long, stol)
        RLIB_IMPL_GEN_AS_NUMERIC(unsigned long, stoul)
        RLIB_IMPL_GEN_AS_NUMERIC(unsigned long long, stoull)
        RLIB_IMPL_GEN_AS_NUMERIC(long long, stoll)
        RLIB_IMPL_GEN_AS_NUMERIC(float, stof)
        RLIB_IMPL_GEN_AS_NUMERIC(double, stod)
        RLIB_IMPL_GEN_AS_NUMERIC(long double, stold)

#define RLIB_IMPL_GEN_AS_ALIAS(new_type, old_type) 
        new_type as(as_helper<new_type>) const { 
            return static_cast<new_type>(as<old_type>()); 
        }

        RLIB_IMPL_GEN_AS_ALIAS(unsigned int, unsigned long)
        RLIB_IMPL_GEN_AS_ALIAS(unsigned short, unsigned long)
        RLIB_IMPL_GEN_AS_ALIAS(uint8_t, unsigned long)

        RLIB_IMPL_GEN_AS_ALIAS(short, int)
        RLIB_IMPL_GEN_AS_ALIAS(int8_t, int)

    public:
        template <typename T>
        T as() const {
            return std::forward<T>(as(as_helper<T>()));
        }

        template <typename T>
        std::vector<T> split_as(const char ÷r = ' ') const {
            const string &toSplit = *this;
            std::vector<T> buf;
            size_t curr = 0, prev = 0;
            while((curr = toSplit.find(divider, curr)) != std::string::npos) {
                buf.push_back(string(toSplit.substr(prev, curr - prev)).as<T>());
                ++curr; // skip divider
                prev = curr;
            }
            buf.push_back(string(toSplit.substr(prev)).as<T>());
            return std::move(buf);
        }
        template <typename T>
        std::vector<T> split_as(const std::string ÷r) const {
            const string &toSplit = *this;
            std::vector<T> buf;
            size_t curr = 0, prev = 0;
            while((curr = toSplit.find(divider, curr)) != std::string::npos) {
                buf.push_back(string(toSplit.substr(prev, curr - prev)).as<T>());
                curr += divider.size(); // skip divider
                prev = curr;
            }
            buf.push_back(string(toSplit.substr(prev)).as<T>());
            return std::move(buf);
        }

        template <class ForwardIterable>
        string &join(const ForwardIterable &buffer) {
            join(buffer.cbegin(), buffer.cend());
            return *this;
        }
        template <class ForwardIterator>
        string &join(ForwardIterator begin, ForwardIterator end) {
            const string &toJoin = *this;
            std::string result;
            for(ForwardIterator iter = begin; iter != end; ++iter) {
                if(iter != begin)
                    result += toJoin;
                result += *iter;
            }
            return operator=(std::move(result));
        }

        string &strip() {
            strip(" trn");
            return *this;
        }
        template <typename CharOrStringOrView>
        string &strip(const CharOrStringOrView &stripped) {
            size_t len = size();
            size_t begin = find_first_not_of(stripped);

            if(begin == std::string::npos) {
                clear();
                return *this;
            }
            size_t end = find_last_not_of(stripped);

            erase(end + 1, len - end - 1);
            erase(0, begin);
            return *this;
        }

        string &replace(const std::string &from, const std::string &to) {
            size_t _;
            replace(from, to, _);
            return *this;
        }
        string &replace(const std::string &from, const std::string &to, size_t &out_times) {
            if(from.empty())
                return *this;
            size_t start_pos = 0;
            size_t times = 0;
            while((start_pos = find(from, start_pos)) != std::string::npos)
            {
                ++times;
                this->std::string::replace(start_pos, from.length(), to);
                start_pos += to.length(); // In case 'to' contains 'from', like replacing 'x' with 'yx'
            }
            out_times = times;
            return *this;
        }
        string &replace_once(const std::string &from, const std::string &to) {
            bool _;
            replace_once(from, to, _);
            return *this;
        }
        string &replace_once(const std::string &from, const std::string &to, bool &out_replaced) {
            size_t start_pos = find(from);
            if(start_pos == std::string::npos) {
                out_replaced = false;
            }
            else {
                this->std::string::replace(start_pos, from.length(), to);
                out_replaced = true;
            }
            return *this;
        }


    };
}

#endif

#include <iostream>
#include <string>

namespace rlib {
    // This is my own hand-written library. I'm making it easy to use it directly.

    inline rlib::string scanln(std::istream &is = std::cin, char delimiter = 'n') noexcept {
        std::string line;
        std::getline(is, line, delimiter);
        return (line); // RVO
    }

    template <typename PrintFinalT>
    void print(PrintFinalT reqArg)
    {
        std::cout << reqArg;
    }
    template <typename Required, typename... Optional>
    void print(Required reqArgs, Optional... optiArgs)
    {
        std::cout << reqArgs << ' ';
        print(optiArgs ...);
    }
    template <typename... Optional>
    void println(Optional... optiArgs)
    {
        print(optiArgs ...);
        println();
    }
    template <> 
    inline void println()
    {
        //std::cout << rlib::endl;
        std::cout << std::endl;
    }
}


一键得到一个精简版的手机QQ(Android)

转发别人的。

hackqq.sh

#!/system/bin/sh

# 使用方法:
#     adb shell "curl -Ssl https://gist.githubusercontent.com/kookxiang/1104e898f270c9a7a0784f70979ec532/raw/hackQQ.sh | su"

# 使用方法 (手动):
#     0.确保你手机 Root 了
#     1.下载这个脚本到某个地方
#     2.下载 Android SDK(需要其中的 adb)
#     3.在命令行运行 adb devices,确保能看到你的手机
#     4.通过命令 adb push 这个脚本保存的路径 /sdcard/hackqq.sh 把这份脚本发送到你的手机上
#     5.运行命令 adb shell su -c bash /sdcard/hackqq.sh 执行脚本
#     6.启动你的手机 QQ 试试
#     7.如有问题重装 QQ 一般就可恢复,如需完全恢复请删除 /sdcard/tencent/MobileQQ 目录

if [ `whoami` != "root" ]; then
    echo "请用 Root 权限运行"
    exit -1
fi

clearFile(){
    echo -n > $1
    chmod 551 $1
}

removeAndCreateFile(){
    rm -rf $1
    touch $1
}

clearAndPreventWrite(){
    if [ -d $1 ]; then
        rm -rf $1/*
    else
        mkdir $1
    fi
    chmod 551 $1
}

disableComponent(){
    pm disable com.tencent.mobileqq/${1} > /dev/null
}

echo 正在停止QQ...
am force-stop com.tencent.mobileqq

echo 开始组件清理
echo "正在清理: 动态..."
disableComponent com.tencent.mobileqq.activity.LebaEnabledPluginsActivity
disableComponent com.tencent.mobileqq.activity.LebaListMgrActivity
disableComponent com.tencent.biz.lebasearch.LebaSearchPluginManagerActivity

echo "正在清理: 应用宝..."
disableComponent com.tencent.open.appcenter.QZoneAppCenterActivity
disableComponent com.tencent.open.applist.QZoneAppListActivity
disableComponent com.tencent.open.appcenter.QZoneAppWebViewActivity
disableComponent com.tencent.open.applist.WebAppActivity2

echo "正在清理: 附近的群..."
disableComponent com.tencent.mobileqq.troop.activity.NearbyTroopsActivity
disableComponent com.tencent.mobileqq.troop.activity.NearbyTroopsLocationActivity
disableComponent com.tencent.biz.troop.activity.TroopNearByBigMapActivity

echo "正在清理: 热聊..."
disableComponent com.tencent.mobileqq.troop.activity.NearbyTroopsActivity
disableComponent com.tencent.mobileqq.activity.ChatSettingForHotChat
disableComponent com.tencent.mobileqq.activity.FakeHotChatBrowserActivity
disableComponent com.tencent.mobileqq.activity.HotChatAnnounceActivity
disableComponent com.tencent.mobileqq.activity.HotChatDemoActivity
disableComponent com.tencent.mobileqq.dating.HotChatFlashPicActivity
disableComponent com.tencent.mobileqq.hotchat.HotChatMemberListActivity

echo "正在清理: QQ 游戏..."
disableComponent com.tencent.gamecenter.activities.GameCenterActivity
disableComponent com.tencent.mobileqq.cooperation.InstallGameActivity

echo "正在清理: QQ 阅读..."
disableComponent com.tencent.mobileqq.activity.BookShareAdviceEditActivity
disableComponent cooperation.qqreader.QRBridgeActivity
disableComponent cooperation.qqreader.QRHardWareActivity
disableComponent cooperation.qqreader.QRPluginProxyActivity
disableComponent cooperation.qqreader.QRReaderPageProxyActivity
disableComponent cooperation.qqreader.QRWebBrowserActivity

echo "正在清理: QQ 动漫..."
disableComponent cooperation.comic.VipComicJumpActivity
disableComponent cooperation.comic.VipComicLandReaderProxyActivity
disableComponent cooperation.comic.VipComicPlayProxyActivity
disableComponent cooperation.comic.VipComicPortraitReaderProxyActivity
disableComponent cooperation.comic.VipComicProxyActivity
disableComponent cooperation.comic.VipComicProxyActivity\$SingleTop
disableComponent cooperation.comic.VipComicTranslucentBrowserActivity

echo "正在清理: QQ 看点..."
disableComponent cooperation.qqhotspot.QQHotSpotBridgeActivity
disableComponent cooperation.qqhotspot.QQHotSpotProxyActivity
disableComponent cooperation.qqhotspot.QQHotSpotProxyActivity\$SingleTop

echo 开始清理功能组件
echo "正在清理: 好友动态..."
disableComponent cooperation.qzone.CrashNotificationActivity
disableComponent cooperation.qzone.PluginDownloadActivity
disableComponent com.tencent.mobileqq.activity.QZoneDiscoverActivity
disableComponent com.qzone.feed.ui.activity.QZoneFriendFeedActivity
disableComponent cooperation.qzone.QZoneVideoDownloadActivity
disableComponent cooperation.qzone.QzoneCommonProxyActivity
disableComponent cooperation.qzone.QzoneFeedsPluginProxyActivity
disableComponent cooperation.qzone.QzoneGPUPluginProxyActivity
disableComponent cooperation.qzone.QzoneNOGPUPluginProxyActivity
disableComponent cooperation.qzone.QzoneOrientationPluginProxyActivity
disableComponent com.tencent.mobileqq.activity.QzonePhotoModeActivity
disableComponent cooperation.qzone.QzonePictureExtPluginProxyActivity
disableComponent cooperation.qzone.QzonePicturePluginProxyActivity
disableComponent cooperation.qzone.QzonePluginProxyActivity
disableComponent cooperation.qzone.QzonePublishMoodProxyActivity
disableComponent cooperation.qzone.QzoneTransNoTitlePluginProxyActivity
disableComponent cooperation.qzone.QzoneTransWithKeyboardPluginProxyActivity
disableComponent cooperation.qzone.QzoneTranslucentGPUPluginProxyActivity
disableComponent cooperation.qzone.QzoneTranslucentPluginProxyActivity
disableComponent cooperation.qzone.video.QzoneVideoPluginProxyActivity
disableComponent cooperation.qzone.TranslucentActivity
disableComponent cooperation.qzone.debug.ServerSetting
disableComponent cooperation.qzone.debug.UploadServerSetting
disableComponent cooperation.qzone.debug.QZoneStatisticsSettingActivity

echo "正在清理: QQ 收藏..."
disableComponent cooperation.qqfav.globalsearch.FavoriteSearchActivity
disableComponent cooperation.qqfav.widget.LocationDetailActivity
disableComponent cooperation.qqfav.widget.QfavJumpActivity
disableComponent cooperation.qqfav.QfavPluginProxyActivity
disableComponent cooperation.qqfav.QfavPluginProxyActivity\$DetailProxy
disableComponent cooperation.qqfav.QfavPluginProxyActivity\$ForResult
disableComponent cooperation.qqfav.QfavPluginProxyActivity\$ImageViewer
disableComponent cooperation.qqfav.QfavPluginProxyActivity\$ScreenOrientationProxy
disableComponent cooperation.qqfav.QfavPluginProxyActivity\$SingleTop

echo "正在清理: QQ WiFi..."
disableComponent cooperation.qqwifi.QQWIFIMapProxyActivity
disableComponent cooperation.qqwifi.QQWiFiConnectProxyActivity
disableComponent cooperation.qqwifi.QQWiFiPluginInstallActivity
disableComponent cooperation.qqwifi.QQWiFiProxyActivity

echo "正在清理: 群作业..."
disableComponent cooperation.troop_homework.outer.TroopHWCommitActivity
disableComponent cooperation.troop_homework.outer.TroopHWEmptyActivity
disableComponent cooperation.troop_homework.outer.TroopHWImagePreviewActivity
disableComponent cooperation.troop_homework.outer.TroopHWRecordActivity
disableComponent cooperation.troop_homework.outer.TroopHWRecordArrangeActivity
disableComponent cooperation.troop_homework.TroopHomeworkPluginInstallerActivity
disableComponent cooperation.troop_homework.TroopHomeworkProxyActivity

echo "正在清理: 智能设备..."
disableComponent com.tencent.device.bind.DevicePluginDownloadActivity
disableComponent cooperation.smartdevice.SmartDevicePluginDownloadActivity
disableComponent cooperation.smartdevice.SmartDevicePluginProxyActivity

echo "正在清理: 微云..."
disableComponent cooperation.weiyun.AlbumBackupLaunchProxyActivity
disableComponent cooperation.weiyun.AlbumBackupProxyActivity

echo "正在清理: 水印相机..."
disableComponent cooperation.zebra.WatermarkPluginProxyActivity

echo "正在清理: 悄悄话..."
disableComponent cooperation.secmsg.SecMsgPluginProxyActivity
disableComponent cooperation.secmsg.SecMsgPluginProxyTransparentActivity

echo "正在清理: 电话黄页..."
disableComponent cooperation.huangye.HYBlankActivity
disableComponent cooperation.huangye.HYBridgeActivity
disableComponent cooperation.huangye.HYPluginProxyActivity
disableComponent cooperation.huangye.HYPluginProxyActivity\$SingleTop
disableComponent com.tencent.biz.huangye.QQYPQRCodePreviewActivity

echo "正在清理: 文件近传..."
disableComponent cooperation.qlink.QlinkAgentActivity
disableComponent com.tencent.qlink.activity.QlinkApGuidelineActivity
disableComponent cooperation.qlink.QlinkBridgeActivity
disableComponent com.tencent.qlink.activity.QlinkDefaultActivity
disableComponent cooperation.qlink.QlinkDialogActivity
disableComponent com.tencent.qlink.widget.QlinkDialogWrapper
disableComponent com.tencent.qlink.activity.QlinkDiscoverActivity
disableComponent com.tencent.qlink.activity.QlinkGuidePageActivity
disableComponent cooperation.qlink.QlinkPluginProxyActivity
disableComponent com.tencent.qlink.activity.QlinkProxyActivity
disableComponent com.tencent.qlink.activity.QlinkSearchActivity
disableComponent cooperation.qlink.QlinkShareJumpActivity
disableComponent cooperation.qlink.QlinkStandardDialogActivity
disableComponent com.tencent.qlink.activity.QlinkTransferActivity

echo "正在清理: 来电..."
disableComponent cooperation.dingdong.DingdongPluginBridgeActivity
disableComponent cooperation.dingdong.DingdongPluginProxyActivity
disableComponent cooperation.dingdong.DingdongPluginProxyActivity\$DingActivity
disableComponent cooperation.dingdong.DingdongPluginProxyActivity\$ApprovalActivity
disableComponent cooperation.dingdong.OfficeOpenBrowserActivity

echo "正在清理: 兴趣号..."
disableComponent cooperation.readinjoy.ReadInJoyPluginInstallActivity
disableComponent cooperation.readinjoy.ReadInJoyProxyActivity
disableComponent cooperation.readinjoy.ReadInJoyProxyActivity\$ReadInJoyLandscapeActivity
disableComponent cooperation.readinjoy.ReadInJoyProxyActivity\$ReadInJoyStartActivity
disableComponent com.tencent.biz.pubaccount.readinjoy.activity.ReadInJoyAccountDetailActivity
disableComponent com.tencent.biz.pubaccount.readinjoy.activity.ReadInJoyArticleDetailActivity
disableComponent com.tencent.biz.pubaccount.readinjoy.activity.ReadInJoyFeedsActivity

echo "正在清理: 新鲜事..."
disableComponent com.tencent.mobileqq.freshnews.FreshNewsDetailActivity
disableComponent com.tencent.mobileqq.activity.FreshNewsEditActivity
disableComponent com.tencent.mobileqq.freshnews.MyFreshNewsActivity
disableComponent com.tencent.mobileqq.freshnews.topic.NearbyTopicFeedActivity

echo "正在清理: C2B..."
disableComponent cooperation.c2b.C2BBrowserActivity
disableComponent cooperation.c2b.C2BScanCodeActivity
disableComponent cooperation.c2b.C2BTakePhotoActivity
disableComponent cooperation.c2b.C2BUploadFileActivity
disableComponent cooperation.c2b.C2BUploadImageActivity
disableComponent cooperation.c2b.C2BVideoPreviewActivity

echo "正在清理: 热点..."
disableComponent cooperation.qqhotspot.QQHotSpotBridgeActivity
disableComponent cooperation.qqhotspot.QQHotSpotProxyActivity
disableComponent cooperation.qqhotspot.QQHotSpotProxyActivity\$SingleTop

echo "正在清理: 短视频..."
disableComponent com.tencent.mobileqq.activity.shortvideo.MX3ShortVideoOpenGlActivity
disableComponent com.tencent.mobileqq.activity.shortvideo.SendVideoActivity
disableComponent com.tencent.mobileqq.activity.shortvideo.ShortVideoOpenGlActivity
disableComponent com.tencent.mobileqq.activity.shortvideo.ShortVideoPlayActivity
disableComponent com.tencent.mobileqq.activity.shortvideo.ShortVideoPlayerActivity
disableComponent com.tencent.mobileqq.activity.shortvideo.ShortVideoPreviewActivity

echo "正在清理: 个性装扮..."
disableComponent com.tencent.mobileqq.activity.IndividuationSetActivity
disableComponent com.tencent.mobileqq.vas.AvatarPendantMarketActivity
disableComponent com.tencent.mobileqq.vas.ChatBackgroundMarketActivity
disableComponent com.tencent.mobileqq.activity.QQVasH5PayBrowserActivity
disableComponent com.tencent.mobileqq.theme.diy.ThemeDIYActivity
disableComponent com.tencent.mobileqq.activity.ThemeDownloadAndSetActivity
disableComponent com.tencent.mobileqq.activity.ThemeNoviceGuideActivity
disableComponent com.tencent.mobileqq.activity.ThemeSwitchDlgActivity

echo "正在清理: 个性签名..."
disableComponent com.tencent.mobileqq.richstatus.ActionGridActivity
disableComponent com.tencent.mobileqq.richstatus.ActionListActivity
disableComponent com.tencent.mobileqq.richstatus.ActionUrlActivity
disableComponent com.tencent.mobileqq.richstatus.EditActivity
disableComponent com.tencent.mobileqq.richstatus.MovieDetailActivity
disableComponent com.tencent.mobileqq.richstatus.StatusHistoryActivity

echo "正在清理: 附近..."
disableComponent com.tencent.mobileqq.nearby.interestTag.ChooseInterestTagActivity
disableComponent com.tencent.mobileqq.nearby.myvistor.MyVistorListActivity
disableComponent com.tencent.mobileqq.activity.NearPeopleActivity
disableComponent com.tencent.mobileqq.activity.NearPeopleFilterActivity
disableComponent com.tencent.mobileqq.activity.NearbyBaseActivity
disableComponent com.tencent.mobileqq.nearby.NearbyFlowerInfoActivity
disableComponent com.tencent.mobileqq.nearby.guide.NearbyGuideActivity
disableComponent com.tencent.mobileqq.nearby.profilecard.NearbyPeopleProfileActivity
disableComponent com.tencent.mobileqq.nearby.picbrowser.NearbyPicBrowserActivity
disableComponent com.tencent.mobileqq.nearby.picbrowser.NearbyProfilePicBrowserActivity
disableComponent com.tencent.mobileqq.activity.qqcard.NearbyQQCardActivity
disableComponent com.tencent.mobileqq.nearpeople.ranking.ShowLoveEditorActivity

echo "正在清理: 约会..."
disableComponent com.tencent.mobileqq.dating.DateEventMsgActivity
disableComponent com.tencent.mobileqq.dating.DatingDestinationActivity
disableComponent com.tencent.mobileqq.dating.DatingDetailActivity
disableComponent com.tencent.mobileqq.dating.DatingFeedActivity
disableComponent com.tencent.mobileqq.dating.DatingFilterActivity
disableComponent com.tencent.mobileqq.dating.DatingOthersActivity
disableComponent com.tencent.mobileqq.dating.DatingTopListActivity
disableComponent com.tencent.mobileqq.dating.DatingUserCenterActivity
disableComponent com.tencent.mobileqq.dating.HotChatFlashPicActivity
disableComponent com.tencent.mobileqq.dating.MsgBoxListActivity
disableComponent com.tencent.mobileqq.dating.NearbyTransitActivity
disableComponent com.tencent.mobileqq.dating.PublicDatingActivity
disableComponent com.tencent.mobileqq.dating.SayHelloMsgListActivity

echo "正在清理: 安全检测..."
disableComponent com.tencent.mobileqq.activity.SecurityDetectActivity
disableComponent com.tencent.mobileqq.activity.SecurityLoginDetectActivity
disableComponent com.tencent.mobileqq.activity.SecurityPickproofActivity
disableComponent com.tencent.mobileqq.activity.SecurityProtectActivity
disableComponent com.tencent.securemodule.ui.TransparentActivity
disableComponent com.tencent.mobileqq.activity.QQSpaceCleanActivity

echo "正在清理: 送花..."
disableComponent com.tencent.mobileqq.activity.bless.BlessActivity
disableComponent com.tencent.mobileqq.activity.BlessPTVActivity
disableComponent com.tencent.mobileqq.activity.bless.BlessResultActivity
disableComponent com.tencent.mobileqq.activity.bless.BlessSendTextActivity
disableComponent com.tencent.mobileqq.activity.bless.BlessTypeActivity

echo 开始流氓服务清理
echo "正在停用: 毒瘤服务..."
disableComponent com.tencent.mobileqq.app.CoreService
disableComponent com.tencent.mobileqq.app.CoreService\$KernelService

echo "正在停用: 好友动态..."
disableComponent com.tencent.mobileqq.app.CoreService
disableComponent com.tencent.mobileqq.app.CoreService\$KernelService
disableComponent cooperation.qzone.QzonePictureViewerProxyService
disableComponent cooperation.qzone.video.QzoneVideoPluginProxyService
disableComponent cooperation.qzone.QzonePluginProxyService
disableComponent cooperation.qzone.remote.logic.QzoneWebPluginProxyService
disableComponent cooperation.qzone.QzonePluginPublishQueueProxyService
disableComponent com.tencent.mobileqq.pluginsdk.ipc.PluginRemoteService$Sub1
disableComponent com.tencent.mobileqq.pluginsdk.ipc.PluginRemoteService$Sub2

echo "正在停用: QQ WiFi..."
disableComponent cooperation.qqwifi.QQWiFiAssistService
disableComponent cooperation.qqwifi.QQWiFiAutoJumpService

echo "正在停用: 插件服务..."
disableComponent cooperation.smartdevice.ipc.BluetoothLeProxyService
disableComponent cooperation.smartdevice.ipc.SmartDeviceProxyService
disableComponent cooperation.huangye.ipc.HYProxyService
disableComponent cooperation.qqhotspot.ipc.QQHotSpotProxyService
disableComponent cooperation.qlink.QlinkPluginProxyService
disableComponent cooperation.secmsg.SecMessagerService
disableComponent cooperation.troop_homework.ipc.TroopHomeworkProxyService
disableComponent cooperation.comic.VipComicProxyService
disableComponent com.tencent.mobileqq.music.QQPlayerService

echo "正在停用: 安全登录检查..."
disableComponent com.tencent.securemodule.impl.SecureService

echo "正在停用: 联系人同步..."
disableComponent com.tencent.mobileqq.contactsync.authenticator.AuthenticationService
disableComponent com.tencent.mobileqq.service.contactsync.ContactSyncPluginProxyService

echo "正在停用: 附近..."
disableComponent com.tencent.mobileqq.nearby.ipc.ConnectNearbyProcService

echo "正在停用: 腾讯寻找丢失儿童项目..."
disableComponent com.tencent.device.qfind.BluetoothLeService

echo 正在断开消息接收器
echo "正在禁用: 后台自启..."
disableComponent com.tencent.mobileqq.msf.core.NetConnInfoCenter

echo "正在禁用: QQ 空间..."
disableComponent cooperation.qzone.NotificationClickReceiver

echo "正在禁用: QQ WiFi..."
disableComponent cooperation.qqwifi.AutoConnectReceiver

echo "正在禁用: 系统报告..."
disableComponent com.tencent.open.business.base.appreport.AppReportReceiver

echo "正在禁用: 崩溃报告..."
disableComponent com.tencent.mobileqq.redtouch.RedPointBroadcastReceiver
disableComponent com.tencent.mobileqq.statistics.ReportReceiver
disableComponent com.tencent.mobileqq.statistics.UECReceiver
disableComponent com.tencent.mobileqq.activity.qwallet.report.VACDReportReceiver

echo "正在禁用: 插件崩溃报告..."
disableComponent cooperation.plugin.PluginCrashReceiver

echo "正在禁用: 插件相关..."
disableComponent cooperation.qzone.QzoneProxyReceiver
disableComponent cooperation.dingdong.DingdongPluginProxyBroadcastReceiver
disableComponent cooperation.photoedit.PhotoEditProxyReceiver
disableComponent cooperation.qqreader.QRAioCmdReceiver
disableComponent cooperation.qqfav.QfavPluginProxyReceiver
disableComponent cooperation.comic.VipProxyPreLoadComicProcess
disableComponent cooperation.qqreader.VipProxyRreLoadReaderProcess
disableComponent cooperation.weiyun.WeiyunProxyBroadcastReceiver
disableComponent cooperation.qwallet.plugin.QWalletProxyReceiver

echo "正在禁用: 主题相关..."
disableComponent com.tencent.mobileqq.statistics.UECReceiver

echo 正在清理 Data Provider
disableComponent cooperation.qqfav.content.FavoritesProvider
disableComponent cooperation.readinjoy.content.ReadInJoyDataProvider

if [ -d /sdcard/tencent/MobileQQ/.pendant ]; then
    echo 去除头像挂件
    removeAndCreateFile /sdcard/tencent/MobileQQ/.pendant
fi

if [ -d /sdcard/tencent/MobileQQ/.signatureTemplate ]; then
    echo 去签名气泡
    removeAndCreateFile /sdcard/tencent/MobileQQ/.signatureTemplate
fi

if [ -d /sdcard/tencent/MobileQQ/.custom_background ]; then
    echo 去自定义主题
    removeAndCreateFile /sdcard/tencent/MobileQQ/custom_background
fi

if [ -n /data/data/com.tencent.mobileqq/files/SensMsgTipsCfg.xml ]; then
    echo 去聊天蓝字
    clearFile /data/data/com.tencent.mobileqq/files/SensMsgTipsCfg.xml
fi

if [ -n "$(ls -a /data/data/com.tencent.mobileqq/files/bubble_info)" ]; then
    echo 去聊天气泡
    rm -rf /data/data/com.tencent.mobileqq/files/bubble_info/*
    chmod 0 /data/data/com.tencent.mobileqq/files/bubble_info
fi

if [ -d /sdcard/tencent/mobileQQ/font_info ]; then
    echo 去聊天字体
    removeAndCreateFile /sdcard/tencent/mobileQQ/font_info
fi

if [ -n "$(ls -a /data/data/com.tencent.mobileqq/files/splashpic)" ]; then
    echo 去启动图片
    clearAndPreventWrite /data/data/com.tencent.mobileqq/files/splashpic
fi

if [ -n /data/data/com.tencent.mobileqq/files/recommendEmotion.json ]; then
    echo 去除推荐表情包
    clearFile /data/data/com.tencent.mobileqq/files/recommemd_emotion_file_*
    clearFile /data/data/com.tencent.mobileqq/files/magic_promotion_*.json
    clearFile /data/data/com.tencent.mobileqq/files/recommendEmotion.json
fi

if [ -n "$(ls -a /data/data/com.tencent.mobileqq/app_qqwifi_dir)" ]; then
    echo 禁用 QQ Wifi
    clearAndPreventWrite /data/data/com.tencent.mobileqq/app_qqwifi_dir
    clearAndPreventWrite /data/data/com.tencent.mobileqq/app_qqwifi_jar_storage_name
    clearAndPreventWrite /data/data/com.tencent.mobileqq/app_qqwifi_jarinfo_storage_name
fi

if [ -f /data/data/com.tencent.mobileqq/app_installed_plugin/qzone_live_video_plugin_hack.apk ]; then
    echo 卸载插件 - QQ 空间小视频插件
    rm -rf /data/data/com.tencent.mobileqq/app_installed_plugin/qzone_live_video_plugin_hack.apk
fi

if [ -f /data/data/com.tencent.mobileqq/app_installed_plugin/qzone_plugin.apk ]; then
    echo 卸载插件 - QQ 空间
    rm -rf /data/data/com.tencent.mobileqq/app_installed_plugin/qzone_plugin.apk.cfg
    rm -rf /data/data/com.tencent.mobileqq/app_installed_plugin/qzone_plugin.apk
fi

if [ -f /data/data/com.tencent.mobileqq/app_installed_plugin/qqfav.apk ]; then
    echo 卸载插件 - QQ 收藏
    rm -rf /data/data/com.tencent.mobileqq/app_installed_plugin/qqfav.apk.cfg
    rm -rf /data/data/com.tencent.mobileqq/app_installed_plugin/qqfav.apk
fi

if [ -f /data/data/com.tencent.mobileqq/app_installed_plugin/comic_plugin.apk ]; then
    echo 卸载插件 - QQ 漫画
    rm -rf /data/data/com.tencent.mobileqq/app_installed_plugin/comic_plugin.apk.cfg
    rm -rf /data/data/com.tencent.mobileqq/app_installed_plugin/comic_plugin.apk
fi

if [ -f /data/data/com.tencent.mobileqq/app_installed_plugin/qlink_plugin.apk ]; then
    echo 卸载插件 - QQ 互连
    rm -rf /data/data/com.tencent.mobileqq/app_installed_plugin/qlink_plugin.apk.cfg
    rm -rf /data/data/com.tencent.mobileqq/app_installed_plugin/qlink_plugin.apk
fi

if [ -f /data/data/com.tencent.mobileqq/app_installed_plugin/qqreaderplugin.apk ]; then
    echo 卸载插件 - QQ 阅读
    rm -rf /data/data/com.tencent.mobileqq/app_installed_plugin/qqreaderplugin.apk.cfg
    rm -rf /data/data/com.tencent.mobileqq/app_installed_plugin/qqreaderplugin.apk
fi

if [ -f /data/data/com.tencent.mobileqq/app_installed_plugin/secmsg_plugin.apk ]; then
    echo 卸载插件 - QQ 悄悄话
    rm -rf /data/data/com.tencent.mobileqq/app_installed_plugin/secmsg_plugin.apk.cfg
    rm -rf /data/data/com.tencent.mobileqq/app_installed_plugin/secmsg_plugin.apk
fi

if [ -f /data/data/com.tencent.mobileqq/app_installed_plugin/qqsmartdevice.apk ]; then
    echo 卸载插件 - QQ 智能设备
    rm -rf /data/data/com.tencent.mobileqq/app_installed_plugin/qqsmartdevice.apk.cfg
    rm -rf /data/data/com.tencent.mobileqq/app_installed_plugin/qqsmartdevice.apk
fi

if stat -c %A /data/data/com.tencent.mobileqq/app_installed_plugin | grep w > /dev/null; then
    echo 锁定插件文件夹
    chmod 551 /data/data/com.tencent.mobileqq/app_installed_plugin
fi

[tampermonkey] SB中国银行网银购汇不用等30秒看sb购汇申请书。一键安装:https://openuserjs.org/users/recolic/scripts

fuckboc.user.js

// ==UserScript==
// @name         FUCK BankOfChina By USD from CNY 30 seconds wait.
// @namespace    https://recolic.net/
// @version      0.1
// @description  If you buy other concurrency on www.boc.cn, you have to wait 30 seconds to read a document. I fucked it.
// @author       Recolic Keghart <[email protected]>
// @match        https://ebsnew.boc.cn/boc15/welcome.html*
// @grant        none
// ==/UserScript==

(function() {
    'use strict';


    //document.getElementById('btn_confirm_456444').classList.remove('btn-red-disabled');
    document.getElementById('content').addEventListener("mouseenter", function(){
        document.getElementById('btn_confirm_456444').classList.remove('btn-red-disabled');
    }, false);
    /*window.addEventListener('load', function() {
        alert('hi3');
    }, false);
    alert('fuck');*/

})();

import tempfile, subprocess
def py3in2(func_text, arg):
    # escape char in arg should be escaped twice. 
    payload = ['#/usr/bin/env python3', 'def _func(arg):']
    for line in func_text.split('\n'):
        payload.append('    ' + line)
    payload.append('with open("/dev/fd/1", "w") as f:\n    f.write(_func(\''+arg+'\'))\n')
    payload = '\n'.join(payload)

    with tempfile.NamedTemporaryFile() as tf:
        tf.file.write(payload)
        tf.file.close()
        output = subprocess.check_output(["python3", tf.name], stderr=subprocess.PIPE)
        return output

ret = py3in2('''
import sys
return sys.version
''', '')

print ret

naive udp forwarder with naive encryption. copied from an unknown guy. the code style is extremely horrible but it's good enough to fuck GFW.

You should consider a better program like this: https://github.com/recolic/udp-forwarder-ex https://github.com/recolic/udp_forwarder_ng (outdated)

udpfwd.cc

#include<stdio.h>
#include<string.h>
#include<sys/socket.h>
#include<arpa/inet.h>
#include<stdlib.h>
#include<getopt.h>
#include <unistd.h>
#include<errno.h>

#include <fcntl.h>
//#include"aes.h"

#include <sys/epoll.h>
#include <sys/wait.h>

#include<map>
#include<string>
#include<vector>
using namespace std;

map<string, string> mp;

char local_address[100], remote_address[100];
int local_port = -1, remote_port = -1;
char keya[100], keyb[100];
char iv[100];
const int buf_len = 20480;

void handler(int num) {
    int status;
    int pid;
    while ((pid = waitpid(-1, &status, WNOHANG)) > 0) {
        if (WIFEXITED(status)) {
            //printf("The child exit with code %d",WEXITSTATUS(status));
        }
    }

}
void encrypt(char * input, int len, char *key) {
    int i, j;
    //char tmp[buf_len];
    //len=len/16*16+1;
    //AES128_CBC_encrypt_buffer((uint8_t *)tmp, (uint8_t *)input, len, (uint8_t *)key, (uint8_t *)iv);
    for (i = 0, j = 0; i < len; i++, j++) {
        if (key[j] == 0)
            j = 0;
        input[i] ^= key[j];
    }
}
void decrypt(char * input, int len, char *key) {
    int i, j;
    //char tmp[buf_len];
    //len=len/16*16+1;
    //AES128_CBC_decrypt_buffer((uint8_t *)tmp, (uint8_t *)input, len, (uint8_t *)key, (uint8_t *)iv);
    //for(i=0;i<len;i++)
    //input[i]=tmp[i];
    for (i = 0, j = 0; i < len; i++, j++) {
        if (key[j] == 0)
            j = 0;
        input[i] ^= key[j];
    }
}
void setnonblocking(int sock) {
    int opts;
    opts = fcntl(sock, F_GETFL);

    if (opts < 0) {
        perror("fcntl(sock,GETFL)");
        exit(1);
    }

    opts = opts | O_NONBLOCK;
    if (fcntl(sock, F_SETFL, opts) < 0) {
        perror("fcntl(sock,SETFL,opts)");
        exit(1);
    }

}
int main(int argc, char *argv[]) {
    int i, j, k;
    int opt;
    signal(SIGCHLD, handler);

    printf("argc=%d ", argc);
    for (i = 0; i < argc; i++)
        printf("%s ", argv[i]);
    printf("\n");
    memset(keya, 0, sizeof(keya));
    memset(keyb, 0, sizeof(keyb));
    memset(iv, 0, sizeof(iv));
    strcpy(iv, "1234567890abcdef");
    if (argc == 1) {
        printf(
                "proc -l [adress:]port -r [adress:]port  [-a passwd] [-b passwd]\n");
        return -1;
    }
    int no_l = 1, no_r = 1;
    while ((opt = getopt(argc, argv, "l:r:a:b:h")) != -1) {
        //string opt_key;
        //opt_key+=opt;
        switch (opt) {
        case 'l':
            no_l = 0;
            if (strchr(optarg, ':') != 0) {
                sscanf(optarg, "%[^:]:%d", local_address, &local_port);
            } else {
                strcpy(local_address, "127.0.0.1");
                sscanf(optarg, "%d", &local_port);
            }
            break;
        case 'r':
            no_r = 0;
            if (strchr(optarg, ':') != 0) {
                //printf("in :\n");
                //printf("%s\n",optarg);
                sscanf(optarg, "%[^:]:%d", remote_address, &remote_port);
                //printf("%d\n",remote_port);
            } else {
                strcpy(remote_address, "127.0.0.1");
                sscanf(optarg, "%d", &remote_port);
            }
            break;
        case 'a':

            strcpy(keya, optarg);
            break;
        case 'b':
            strcpy(keyb, optarg);
            break;
        case 'h':
            break;
        default:
            printf("ignore unknown <%s>", optopt);
        }
    }

    if (no_l)
        printf("error: -i not found\n");
    if (no_r)
        printf("error: -o not found\n");
    if (no_l || no_r) {
        exit(-1);
    }

    struct sockaddr_in local_me, local_other;
    int local_listen_fd = socket(AF_INET, SOCK_DGRAM, IPPROTO_UDP);
    int yes = 1;
    setsockopt(local_listen_fd, SOL_SOCKET, SO_REUSEADDR, &yes, sizeof(yes));

    char buf[buf_len];
    socklen_t slen = sizeof(sockaddr_in);
    memset(&local_me, 0, sizeof(local_me));
    local_me.sin_family = AF_INET;
    local_me.sin_port = htons(local_port);
    local_me.sin_addr.s_addr = inet_addr(local_address);
    if (bind(local_listen_fd, (struct sockaddr*) &local_me, slen) == -1) {
        printf("socket bind error");
        exit(1);
    }
    while (1) {
        socklen_t recv_len;
        if ((recv_len = recvfrom(local_listen_fd, buf, buf_len, 0,
                (struct sockaddr *) &local_other, &slen)) == -1) {
            printf("recv_from error");
            exit(1);
        }
        printf("Received packet from %s:%d\n", inet_ntoa(local_other.sin_addr),
                ntohs(local_other.sin_port));

        if (keya[0]) {
            decrypt(buf, recv_len, keya);/*recv_len-=16;*/
        }
        buf[recv_len] = 0;
        //printf("recv_len: %d\n", recv_len);
        fflush(stdout);
        //printf("Data: %s\n" , buf);
        int local_fd = socket(AF_INET, SOCK_DGRAM, IPPROTO_UDP);
        //local_me.sin_addr.s_addr=inet_addr("127.0.0.1");
        setsockopt(local_fd, SOL_SOCKET, SO_REUSEADDR, &yes, sizeof(yes));
        if (bind(local_fd, (struct sockaddr*) &local_me, slen) == -1) {
            printf("socket bind error in chilld");
            exit(1);
        }
        int ret = connect(local_fd, (struct sockaddr *) &local_other, slen);//父进程替子进程做
        if (fork() == 0)                    //子
                {
            if (ret != 0) {
                printf("connect return %d @1\n", ret);
                exit(1);
            }
            close(local_listen_fd);

            struct sockaddr_in remote_me, remote_other;

            memset(&remote_other, 0, sizeof(remote_other));
            remote_other.sin_family = AF_INET;
            //printf("remote_address=%s  remote_port=%d\n",remote_address,remote_port);
            remote_other.sin_port = htons(remote_port);
            remote_other.sin_addr.s_addr = inet_addr(remote_address);
            int remote_fd = socket(AF_INET, SOCK_DGRAM, IPPROTO_UDP);
            ret = connect(remote_fd, (struct sockaddr *) &remote_other, slen);
            if (ret != 0) {
                printf("connect return %d @2\n", ret);
                exit(1);
            }

            if (keyb[0]) {/*recv_len+=16;*/
                encrypt(buf, recv_len, keyb);
            }
            ret = send(remote_fd, buf, recv_len, 0);
            //printf("send return %d\n", ret);
            if (ret < 0)
                exit(-1);

            setnonblocking(remote_fd);
            setnonblocking(local_fd);
            int epollfd = epoll_create1(0);
            const int max_events = 4096;
            struct epoll_event ev, events[max_events];
            if (epollfd < 0) {
                printf("epoll return %d\n", epollfd);
                exit(-1);
            }
            ev.events = EPOLLIN;
            ev.data.fd = local_fd;
            ret = epoll_ctl(epollfd, EPOLL_CTL_ADD, local_fd, &ev);
            if (ret < 0) {
                printf("epoll_ctl return %d\n", ret);
                exit(-1);
            }
            ev.events = EPOLLIN;
            ev.data.fd = remote_fd;
            ret = epoll_ctl(epollfd, EPOLL_CTL_ADD, remote_fd, &ev);
            if (ret < 0) {
                printf("epoll_ctl return %d\n", ret);
                exit(-1);
            }
            for (;;) {
                int nfds = epoll_wait(epollfd, events, max_events, 180 * 1000);
                if (nfds <= 0) {
                    printf("epoll_wait return %d\n", nfds);
                    exit(-1);
                }
                int n;
                for (n = 0; n < nfds; ++n) {
                    if (events[n].data.fd == local_fd) {
                        recv_len = recv(local_fd, buf, buf_len, 0);
                        if (recv_len < 0) {
                            printf("recv return %d @1", recv_len);
                            exit(1);
                        }
                        if (keya[0]) {
                            decrypt(buf, recv_len, keya);/*recv_len-=16;*/
                        }
                        buf[recv_len] = 0;
                        //printf("len %d received from [email protected]\n", recv_len);
                        //printf("%s received from [email protected]\n",buf);
                        if (keyb[0]) {/*recv_len+=16;*/
                            encrypt(buf, recv_len, keyb);
                        }
                        //printf("before send %s\n",buf);
                        ret = send(remote_fd, buf, recv_len, 0);
                        if (ret < 0) {
                            //printf("send return %d at @1", ret);
                            exit(1);
                        }
                        //printf("send return %d @1\n", ret);
                    } else if (events[n].data.fd == remote_fd) {
                        recv_len = recv(remote_fd, buf, buf_len, 0);
                        if (recv_len < 0) {
                            printf("recv return -1 @2", recv_len);
                            exit(1);
                        }
                        if (keyb[0]) {
                            decrypt(buf, recv_len, keyb);/*recv_len-=16;*/
                        }
                        buf[recv_len] = 0;
                        //printf("len %d received from [email protected]\n", recv_len);
                        //printf("%s received from [email protected]\n",buf);
                        if (keya[0]) {/*recv_len+=16*/
                            ;
                            encrypt(buf, recv_len, keya);
                        }
                        ret = send(local_fd, buf, recv_len, 0);
                        if (ret < 0) {
                            //printf("send return %d @2", ret);
                            exit(1);
                        }

                        //printf("send return %d @2\n", ret);
                    }
                }
            }
            exit(0);
        } else {
            close(local_fd);
        }
        //exit(0);
    }

    return 0;
}

Maybe outdated.

I've used @beliys code and made a bash command.

Setup: Add this code to your ~/.bash_aliases file.

function gdrive_download () {
  CONFIRM=$(wget --quiet --save-cookies /tmp/cookies.txt --keep-session-cookies --no-check-certificate "https://docs.google.com/uc?export=download&id=$1" -O- | sed -rn 's/.*confirm=([0-9A-Za-z_]+).*/\1\n/p')
  wget --load-cookies /tmp/cookies.txt "https://docs.google.com/uc?export=download&confirm=$CONFIRM&id=$1" -O $2
  rm -rf /tmp/cookies.txt
}

Open new bash session. Usage:

gdrive_download long_google_drive_file_id filename.ext

Surface Book 2 / Surface Pro (2017) / Surface Laptop UART protocol proof-of-concept script.

This script is from https://github.com/jakeday/linux-surface/issues/28#issuecomment-427579018

It works for Surface Book 2 and Surface Pro 2017.

If you're using Surface Laptop, edit the baudrate to 1843200 and it will work too.

If /dev/ttyS4 doesn't exist, try /dev/ttyS0. (My Surface Laptop is the case)

2020 update: This post is already outdated. Please refer to latest linux-surface to see if problem got resolved.

mshw0084-rqst.py

#!/usr/bin/env python3

import json
import pprint
import crcmod

from argparse import ArgumentParser

from pathlib import Path

import serial
from serial import Serial


DEFAULT_DEVICE = '/dev/ttyS4'
CRC_FN = crcmod.predefined.mkCrcFun('crc-ccitt-false')


def setup_device(port):
    # definition from DSDT
    return Serial(
        port=port,
        baudrate=3000000,
        bytesize=serial.EIGHTBITS,
        parity=serial.PARITY_NONE,
        stopbits=serial.STOPBITS_ONE,
        rtscts=False,
        dsrdtr=False,
        timeout=0,
    )


def crc(pld):
    x = CRC_FN(bytes(pld))
    return [x & 0xff, (x >> 0x08) & 0xff]


def to_int(bytes):
    return int.from_bytes(bytes, byteorder='little')


class Counters:
    PATH = Path(__file__).parent / '.counters.json'

    @staticmethod
    def load():
        if Counters.PATH.is_file():
            with open(Counters.PATH) as fd:
                data = json.load(fd)
                seq = data['seq']
                cnt = data['cnt']
        else:
            seq = 0x00
            cnt = 0x0000

        return Counters(seq, cnt)

    def __init__(self, seq, cnt):
        self.seq = seq
        self.cnt = cnt

    def store(self):
        with open(Counters.PATH, 'w') as fd:
            data = {'seq': self.seq, 'cnt': self.cnt}
            json.dump(data, fd)

    def inc_seq(self):
        self.seq = (self.seq + 1) & 0xFF

    def inc_cnt(self):
        self.cnt = (self.cnt + 1) & 0xFFFF

    def inc(self):
        self.inc_seq()
        self.inc_cnt()


class Command:
    def __init__(self, rtc, riid, rcid):
        self.rtc = rtc
        self.riid = riid
        self.rcid = rcid

    def _write_msg(self, dev, seq, cnt):
        cnt_lo = cnt & 0xff
        cnt_hi = (cnt >> 0x08) & 0xff

        hdr = [0x80, 0x08, 0x00, seq]
        pld = [0x80, self.rtc, 0x01, 0x00, self.riid, cnt_lo, cnt_hi, self.rcid]
        msg = [0xaa, 0x55] + hdr + crc(hdr) + pld + crc(pld)

        return dev.write(bytes(msg))

    def _write_ack(self, dev, seq):
        hdr = [0x40, 0x00, 0x00, seq]
        msg = [0xaa, 0x55] + hdr + crc(hdr) + [0xff, 0xff]

        return dev.write(bytes(msg))

    def _read_ack(self, dev, exp_seq):
        msg = bytes()
        while len(msg) < 0x0A:
            msg += dev.read(0x0A - len(msg))

        print("received: {}".format(msg.hex()))

        assert msg[0:2] == bytes([0xaa, 0x55])
        assert msg[3:5] == bytes([0x00, 0x00])
        assert msg[6:8] == bytes(crc(msg[2:-4]))
        assert msg[8:] == bytes([0xff, 0xff])

        mty = msg[2]
        seq = msg[5]

        if mty == 0x40:
            assert seq == exp_seq

        return mty == 0x04

    def _read_msg(self, dev, cnt):
        cnt_lo = cnt & 0xff
        cnt_hi = (cnt >> 0x08) & 0xff

        buf = bytes()
        rem = 0x08                          # begin with header length
        while len(buf) < rem:
            buf += dev.read(0x0400)

            # if we got a header, validate it
            if rem == 0x08 and len(buf) >= 0x08:
                hdr = buf[0:8]

                assert hdr[0:3] == bytes([0xaa, 0x55, 0x80])
                assert hdr[-2:] == bytes(crc(hdr[2:-2]))

                rem += hdr[3] + 10          # len(payload) + frame + crc

        hdr = buf[0:8]
        msg = buf[8:hdr[3]+10]
        rem = buf[hdr[3]+10:]

        print("received: {}".format(hdr.hex()))
        print("received: {}".format(msg.hex()))

        assert msg[0:8] == bytes([0x80, self.rtc, 0x00, 0x01, self.riid, cnt_lo, cnt_hi, self.rcid])
        assert msg[-2:] == bytes(crc(msg[:-2]))

        seq = hdr[5]
        pld = msg[8:-2]

        return seq, pld, rem

    def _read_clean(self, dev, buf=bytes()):
        buf += dev.read(0x0400)                     # make sure we're not missing some bytes

        while buf:
            # get header / detect message type
            if len(buf) >= 0x08:
                if buf[0:3] == bytes([0xaa, 0x55, 0x40]):               # ACK
                    while len(buf) < 0x0A:
                        buf += dev.read(0x0400)

                    print("ignored ACK: {}".format(buf[:0x0a].hex()))
                    buf = bytes(buf[0x0a:])

                elif buf[0:3] == bytes([0xaa, 0x55, 0x80]):             # response
                    buflen = 0x0a + buf[3]
                    while len(buf) < buflen:
                        buf += dev.read(0x0400)

                    print("ignored MSG: {}".format(buf[:buflen].hex()))
                    buf = bytes(buf[buflen:])

                elif buf[0:3] == bytes([0x4e, 0x00, 0x53]):             # control message?
                    while len(buf) < 0x19:
                        buf += dev.read(0x0400)

                    print("ignored CTRL: {}".format(buf[:0x19].hex()))
                    buf = bytes(buf[0x19:])

                else:                                                   # unknown
                    print("ignored unknown: {}".format(buf.hex()))
                    assert False

            buf += dev.read(0x0400)

    def run(self, dev, cnt):
        self._read_clean(dev)
        self._write_msg(dev, cnt.seq, cnt.cnt)
        retry = self._read_ack(dev, cnt.seq)

        # retry one time on com failure
        if retry:
            self._write_msg(dev, cnt.seq, cnt.cnt)
            retry = self._read_ack(dev, cnt.seq)

            if retry:
                print('Communication failure: invalid ACK, try again')
                return

        try:
            seq, pld, rem = self._read_msg(dev, cnt.cnt)
            self._write_ack(dev, seq)
            self._read_clean(dev, rem)
        finally:
            cnt.inc()

        return self._handle_payload(pld)

    def _handle_payload(self, pld):
        return None


class Gbos(Command):
    def __init__(self):
        super().__init__(0x11, 0x00, 0x0d)

    def _handle_payload(self, pld):
        return {
            'Base Status': hex(pld[0]),
        }


class Psr(Command):
    def __init__(self, bat):
        super().__init__(0x02, bat, 0x0d)

    def _handle_payload(self, pld):
        return {
            'Power Source': hex(to_int(pld[0:4])),
        }


class Sta(Command):
    def __init__(self, bat):
        super().__init__(0x02, bat, 0x01)

    def _handle_payload(self, pld):
        return {
            'Battery Status': hex(to_int(pld[0:4])),
        }


class Bst(Command):
    def __init__(self, bat):
        super().__init__(0x02, bat, 0x03)

    def _handle_payload(self, pld):
        return {
            'State': hex(to_int(pld[0:4])),
            'Present Rate': hex(to_int(pld[4:8])),
            'Remaining Capacity': hex(to_int(pld[8:12])),
            'Present Voltage': hex(to_int(pld[12:16])),
        }


class Bix(Command):
    def __init__(self, bat):
        super().__init__(0x02, bat, 0x02)

    def _handle_payload(self, pld):
        return {
            'Revision': hex(pld[0]),
            'Power Unit': hex(to_int(pld[1:5])),
            'Design Capacity': hex(to_int(pld[5:9])),
            'Last Full Charge Capacity': hex(to_int(pld[9:13])),
            'Technology': hex(to_int(pld[13:17])),
            'Design Voltage': hex(to_int(pld[17:21])),
            'Design Capacity of Warning': hex(to_int(pld[21:25])),
            'Design Capacity of Low': hex(to_int(pld[25:29])),
            'Cycle Count': hex(to_int(pld[29:33])),
            'Measurement Accuracy': hex(to_int(pld[33:37])),
            'Max Sampling Time': hex(to_int(pld[37:41])),
            'Min Sampling Time': hex(to_int(pld[41:45])),
            'Max Averaging Interval': hex(to_int(pld[45:49])),
            'Min Averaging Interval': hex(to_int(pld[49:53])),
            'Capacity Granularity 1': hex(to_int(pld[53:57])),
            'Capacity Granularity 2': hex(to_int(pld[57:61])),
            'Model Number': pld[61:82].decode().rstrip('\0'),
            'Serial Number': pld[82:93].decode().rstrip('\0'),
            'Type': pld[93:98].decode().rstrip('\0'),
            'OEM Information': pld[98:119].decode().rstrip('\0'),
        }


class PrettyBat:
    def __init__(self, bat):
        self.bix = Bix(bat)
        self.bst = Bst(bat)

    def run(self, dev, cnt):
        bix = self.bix.run(dev, cnt)
        bst = self.bst.run(dev, cnt)

        state = int(bst['State'], 0)
        vol = int(bst['Present Voltage'], 0)
        rem_cap = int(bst['Remaining Capacity'], 0)
        full_cap = int(bix['Last Full Charge Capacity'], 0)
        rate = int(bst['Present Rate'], 0)

        bat_states = {
            0: 'None',
            1: 'Discharging',
            2: 'Charging',
            4: 'Critical',
            5: 'Critical (Discharging)',
            6: 'Critical (Charging)',
        }

        bat_state = bat_states[state]
        bat_vol = vol / 1000

        if full_cap <= 0:
            bat_rem_perc = '<unavailable>'
        else:
            bat_rem_perc = "{}%".format(int(rem_cap / full_cap * 100))

        if state == 0x00 or rate == 0:
            bat_rem_life = '<unavailable>'
        else:
            bat_rem_life = "{:.2f}h".format(rem_cap / rate)

        return {
            'State': bat_state,
            'Voltage': "{}V".format(bat_vol),
            'Precentage': bat_rem_perc,
            'Remaing ': bat_rem_life,
        }


COMMANDS = {
    'lid0.gbos': Gbos(),
    'adp1._psr': Psr(0x01),
    'bat1._sta': Sta(0x01),
    'bat1._bst': Bst(0x01),
    'bat1._bix': Bix(0x01),
    'bat2._sta': Sta(0x02),
    'bat2._bst': Bst(0x02),
    'bat2._bix': Bix(0x02),

    'bat1.pretty': PrettyBat(0x01),
    'bat2.pretty': PrettyBat(0x02),
}


def main():
    cli = ArgumentParser(description='Surface Book 2 / Surface Pro (2017) embedded controller requests.')
    cli.add_argument('-d', '--device', default=DEFAULT_DEVICE, metavar='DEV', help='the UART device')
    cli.add_argument('-c', '--cnt', type=lambda x: int(x, 0), help='overwrite CNT')
    cli.add_argument('-s', '--seq', type=lambda x: int(x, 0), help='overwrite SEQ')
    commands = cli.add_subparsers()

    for cmd in COMMANDS.keys():
        parser = commands.add_parser(cmd, help="run request '{}'".format(cmd.upper()))
        parser.set_defaults(command=cmd)

    args = cli.parse_args()

    dev = setup_device(args.device)
    cmd = COMMANDS.get(args.command)

    cnt = Counters.load()
    if args.seq is not None:
        cnt.seq = args.seq
    if args.cnt is not None:
        cnt.cnt = args.cnt

    try:
        res = cmd.run(dev, cnt)

        print()
        pprint.pprint(res)
    finally:
        cnt.store()


if __name__ == '__main__':
    main()

Pipfile

[[source]]
url = "https://pypi.org/simple"
verify_ssl = true
name = "pypi"

[packages]
crcmod = "*"
pyserial = "*"

[dev-packages]
pylint = "*"

virtualtype.py

#!/usr/bin/env python3
# Use this script with https://recolic.net/phy and https://recolic.net/phy2 
#     to avoid typing fucked numbers into page by hand.
# Fuck the chinese shits who prevent you from pasting password.
#     E.x. Alibaba bitch
from pykeyboard import PyKeyboard
import time

def virtual_type_array(arrToType, noWait=False):
    k = PyKeyboard()
    if not noWait:
        print('You have 5 seconds to ready for auto-typing.')
        time.sleep(5)
    for d in arrToType:
        k.type_string(str(d))
        k.tap_key(k.tab_key)

def _type(s):
    k = PyKeyboard()
    print('You have 5 seconds to ready for auto-typing.')
    time.sleep(5)
    k.type_string(str(s))

if __name__ == "__main__":
    import sys
    _type(sys.argv[1])

This tool was written by anonymous man. The good man hosts the tool at https://nmsl.party/zhixiang

hanoi.bash

#!/bin/bash

height=$1
sleep_time=$2

[[ $height == '' ]] && echo 'Usage: ./hanoi.bash <height> [sleep_time = 0.6]' && exit 1
[[ $sleep_time == '' ]] && sleep_time=0.6

declare -a A=( $(seq 1 $height) )
declare -a B
declare -a C

function exchangeAC() {
    [[ ${A[0]} == '' ]] && [[ ${C[0]} == '' ]] && return 4 # done
    [[ ${A[0]} == '' ]] && A=( ${C[0]} ${A[@]} ) && C=( ${C[@]:1} ) && return 0
    [[ ${C[0]} == '' ]] || [[ `expr ${C[0]} \> ${A[0]}` == 1 ]] && C=( ${A[0]} ${C[@]} ) && A=( ${A[@]:1} ) && return 0
    A=( ${C[0]} ${A[@]} ) && C=( ${C[@]:1} ) && return 0
}
function exchangeAB() {
    [[ ${A[0]} == '' ]] && [[ ${B[0]} == '' ]] && return 4 # done
    [[ ${A[0]} == '' ]] && A=( ${B[0]} ${A[@]} ) && B=( ${B[@]:1} ) && return 0
    [[ ${B[0]} == '' ]] || [[ `expr ${B[0]} \> ${A[0]}` == 1 ]] && B=( ${A[0]} ${B[@]} ) && A=( ${A[@]:1} ) && return 0
    A=( ${B[0]} ${A[@]} ) && B=( ${B[@]:1} ) && return 0
}
function exchangeBC() {
    [[ ${B[0]} == '' ]] && [[ ${C[0]} == '' ]] && return 4 # done
    [[ ${B[0]} == '' ]] && B=( ${C[0]} ${B[@]} ) && C=( ${C[@]:1} ) && return 0
    [[ ${C[0]} == '' ]] || [[ `expr ${C[0]} \> ${B[0]}` == 1 ]] && C=( ${B[0]} ${C[@]} ) && B=( ${B[@]:1} ) && return 0
    B=( ${C[0]} ${B[@]} ) && C=( ${C[@]:1} ) && return 0
}



function show() {
    echo "A ${A[@]}"
    echo "B ${B[@]}"
    echo "C ${C[@]}"
    echo ''
}

function odd() {
    while true; do
        exchangeAC
        [[ $? == 4 ]] && exit 0
        show && sleep $sleep_time

        exchangeAB
        [[ $? == 4 ]] && exit 0
        show && sleep $sleep_time

        exchangeBC
        [[ $? == 4 ]] && exit 0
        show && sleep $sleep_time
    done
}
function even() {
    while true; do
        exchangeAB
        [[ $? == 4 ]] && exit 0
        show && sleep $sleep_time

        exchangeAC
        [[ $? == 4 ]] && exit 0
        show && sleep $sleep_time

        exchangeBC
        [[ $? == 4 ]] && exit 0
        show && sleep $sleep_time
    done
}

[[ $((height % 2)) == 0 ]] && even || odd