Author Archives: Robins

Aapt2 error: check logs for details

Exception:

Caused by: com.android.builder . internal.aapt .v2.Aapt2Exception: AAPT2 error: check logs for details
    at com.android.builder . png.AaptProcess $N otifierProcessOutput.handleOutput ( AaptProcess.java:443 )
    at com.android.builder . png.AaptProcess $N otifierProcessOutput.err ( AaptProcess.java:395 )
    at com.android.builder . png.AaptProcess $ ProcessOutputFacade.err ( AaptProcess.java:312 )
    at com.android.utils .GrabProcessOutput$1.run( GrabProcessOutput.java:104 )

All r documents are wrong and red;

Aapt2 explains:

AAPT is the full name of Android asset packaging tool. It is an indispensable tool to build app and even Android system. Its function is to compress and package all resource files into Android APK. We can find it in the Android SDK directory. For example, I can find it in my directory D: SDK, build tools, 28.0.2, and other versions of build tools;

Aapt2 is a new version of AAPT. Starting from Android studio 3.0, it is used as the default resource packaging tool.

terms of settlement:

1. Click toggleview to view the execution output of gradle more clearly;

After clicking, it is shown as follows:

2. The red output information in the figure above has the following information:

AGPBI: {"kind":"error","text":"error: resource drawable/shape_round (aka com.liyuhuyu.liyu:drawable/shape_round) not found.","sources":[{"file":"E:\\Project\\LiYuTwo\\app\\src\\main\\res\\layout\\item_water.xml","position":{"startLine":10}}],"original":"","tool":"AAPT"}

AGPBI: {"kind":"error","text":"error: resource drawable/popupwindow_close (aka com.liyuhuyu.liyu:drawable/popupwindow_close) not found.","sources":[{"file":"E:\\Project\\LiYuTwo\\app\\src\\main\\res\\layout\\popupwindow_pay_select.xml","position":{"startLine":62}}],"original":"","tool":"AAPT"}

3. From the above prompt output information, we can know the following:

1) The file where the error occurred is item_ water.xml ;

2) The reason for the mistake is android:background Property value “@ drawable / shape”_ “Round” not found

4. Open item_ water.xml File, find the error location, as shown in the above output information error; delete or correct it;

Conclusion:

1) In fact, the reason for my error is that the referenced resource file cannot be found;

2) Aapt2 is a tool for packing resource files. If aapt2 reports an error, it is usually a problem with the resource file.

Other solutions:

Many solutions on the Internet say that the project is successful gradle.properties Add a line to“ android.enableAapt2=false “To shut down aapt2


Other knowledge:

Use AAPT to view the app package name and other information

1, use CD in the command line of CMD to switch to the directory where AAPT is located

2. Enter the command “AAPT dump bagging C: / / users / administrator / desktop / find fault 201905171701. APK” to run, OK;

The path of the app is C: users, administrator, desktop, 201905171701.apk

Attr in wxPython= wx.grid.GridCellAttr() error reporting

Question:

wx._ core.wxAssertionError : C++ assertion “m_ count > 0” failed at … \src\common\ object.cpp (352) in wxRefCounter::DecRef(): invalid ref data count

Causes of the problem:

        attr = wx.grid.GridCellAttr()  
        for i in range(len(lis)):
            editor = wx.grid.GridCellBoolEditor()
            self.SetCellEditor(i + 1, 0, editor)
            self.SetCellRenderer(i + 1, 0, wx.grid.GridCellBoolRenderer())
            for j in range(len(lis[i])):
                self.SetCellValue(i + 1, j + 1, lis[i][j])
                attr.SetReadOnly()
                self.SetAttr(i + 1, j + 1, attr)

Solution 1:

        #attr = wx.grid.GridCellAttr() #Modify the part
        for i in range(len(list1)):
          attr = wx.grid.GridCellAttr()#Modify the part
          self.SetCellValue(i + 1, j + 1, list1[i][j])
          attr.SetReadOnly()
          self.SetAttr(i + 1, j + 1, attr)
         
            	

Solution 2:

        attr = wx.grid.GridCellAttr()
        for j in range(len(list1[i])):
              self.SetCellValue(i + 1, j + 1, list1[i][j])
              attr.SetReadOnly()
              atttr.IncRef()#Modify the part;this will leak the GridCellAttr, because the destructor is not called
              self.SetAttr(i + 1, j + 1, attr)

The use of Android setgravity()

Today, let’s talk about how to use set gravity() in Android LinearLayout.

Previously, when doing a function, you need to set the gravity of LinearLayout according to the change of data. Before, I wrote the code directly in the XML file roid: gravity I don’t know how to set the properties when I need to set them dynamically in Java code this time. Later, after searching the information on the Internet, I found that set gravity () can be set. Here is a record.

 

It is often used in UI layout android: gravity And android: layout_ Gravity.

LinearLayout has two very similar properties:

android: gravity And android: layout_ gravity。

The differences between them are as follows:

android: gravity Attributes are the restrictions on the content of the view. For example, text on a button. You can set the position of the text relative to the view, such as left, right, etc.

in the view android: layout_ Gravity is used to set the position of the view relative to the parent view. For example, if a button is in the LinearLayout, you want to place the button in the left or right position of the LinearLayout, you can set it through this property

Namely android: gravity It is used to set the alignment of the content in the view relative to the view component android: layout_ Gravity is used to set the alignment of the view component relative to the container.

The principle follows android:padding-left, android: layout_ Marginleft is a bit similar. If both properties are set on the button.

android:paddingLeft= The content set on the “30px” button is 30 pixels away from the left boundary of the button
and android: layout_ Marginleft = “30px” the whole button is 30 pixels away from the content set on the left

Let’s get back to the point. We can set the android:gravity= “Center” to make the text in EditText display in the center of the EditText component; at the same time, we set the android: layout_ Gravity = “right” to make the EditText component appear on the right in LinearLayout. Look at the effect:

As we can see, in EditText, the text is centered, and the EditText component itself is aligned to the right of LinearLayout.

Attach layout file:

<LinearLayout
   xmlns:android="http://schemas.android.com/apk/res/android"
    android:orientation="vertical"
    android:layout_width="fill_parent"
    android:layout_height="fill_parent">
    <EditText
        android:layout_width="wrap_content"
        android:gravity="center"
        android:layout_height="wrap_content"
        android:text="one"
        android:layout_gravity="right"/>
</LinearLayout>

 

Then the above is set through the layout file. , I believe everyone has written, so how to set the location of components through Java code?

The above effects are still considered.

By looking at the SDK, we find that there is a set gravity method. As the name suggests, this method should be used to set the text alignment in the button component.

After a careful search, I didn’t find the setlayoutgravity method. I’m a little disappointed. But it’s right to think about it. If you have this method, you can put the button in the position where the layout is not supported_ What to do in a container of gravity property!

So I thought that this attribute might be in the layout. So I took a closer look at the “layout params” of LinearLayout and found that there is a “gravity” attribute in it. I believe this is used to set the position of components relative to the container itself. Yes, it should be him.

The practice found that, if so, attached code, you see.

The code is relatively simple, but it took me a little time to find them.

		Button button  = new Button(this);
		button.setText("One");
		LinearLayout.LayoutParams lp = new LinearLayout.LayoutParams(LayoutParams.WRAP_CONTENT,LayoutParams.WRAP_CONTENT);
		//This is equivalent to the Android:layout_gravity property in the layout file
		lp.gravity = Gravity.RIGHT;
		button.setLayoutParams(lp);
		// this is equivalent to the Android:layout_gravity property in the layout file
		button.setGravity(Gravity.CENTER);
		
		LinearLayout linear = new LinearLayout(this);
		// Note that for LinearLayout layout, setting horizontal or vertical is a must! Otherwise, the effect will not be visible.
		linear.setOrientation(LinearLayout.VERTICAL);
		linear.addView(button);
		setContentView(linear);

 

Or you can:

		Button button  = new Button(this);
		button.setText("One");
		//This is equivalent to the Android:gravity property in the layout file
		button.setGravity(Gravity.CENTER);
		
		LinearLayout linear = new LinearLayout(this);
		// Note that for LinearLayout layout, setting horizontal or vertical is a must! Otherwise, you won't see the effect.
		linear.setOrientation(LinearLayout.VERTICAL);
		
		LinearLayout.LayoutParams lp = new LinearLayout.LayoutParams(LayoutParams.WRAP_CONTENT,LayoutParams;)
		// This is equivalent to the Android:layout_gravity property in the layout file
		lp.gravity = Gravity.RIGHT;
		
		linear.addView(button, lp);
		setContentView(linear);

 

In addition, to set the position in relative layout, use the add rule method, as follows:

params = new RelativeLayout.LayoutParams(LayoutParams.WRAP_CONTENT, LayoutParams.WRAP_CONTENT);
        params.addRule(RelativeLayout.CENTER_IN_PARENT);
        mContainer.addView(progress,params);

 

One more thing to note here:

android: layout_ Gravity is only valid in LinearLayout and FrameLayout:

1. For LinearLayout:

When android:orientation=vertical (vertical), only the setting in the horizontal direction works, but the setting in the vertical direction does not work. That is: left, right, center_ Horizontal is in effect.

When android:orientation=horizontal (horizontal), only the setting in the vertical direction works, but the setting in the horizontal direction does not. Namely: top, bottom, center_ Vertical is in effect.

2. For FrameLayout: arbitrary android: layout_ The gravity attribute is effective, which makes it very convenient to layout components.

 

Here is a brief introduction. Android’s setgravity() actually corresponds to LinearLayout or FrameLayout android: gravity Attribute, because relative layout does not have this attribute, the code setting in relative layout does not work. Because the Internet is full of android:gravity And android: layout_ The gravity attribute are talked about together, so I’ll talk about it together. Dynamic settings android: layout_ Gravity is actually through LinearLayout.LayoutParams Of lp. gravity It’s also very simple.

 

That’s all for Android setgravity().

 

It’s that simple.

Python Pandas Typeerror: invalid type comparison

When reading and processing the data in the CSV file with panda in Python, you may encounter such an error:

TypeError: invalid type comparison

Invalid type comparison

At this time, you can print the data in your data frame


1. There may be no data in some items, which will be displayed as Nan when printing. Nan can’t be compared with any data, and it’s not equal to any value, including himself (so you can also use a! =A to judge whether a is Nan.

Therefore, in the following data processing, if a comparison operation is performed, an error will be reported:

TypeError: invalid type comparison

Method, add parameters when reading the CSV

keep_default_na=False

In this way, entries without data will be recognized as null characters instead of Nan


2. Maybe the data types of different columns in your dataframe are different. Some of them are recognized as STR and some as int. although they all look like numbers, they will also report errors when compared later

At this time, you can add a parameter

converters={'from':str,'to':str} # Convert both the from and to columns to str

The explanation of converters is as follows:

converters: dict, default None
Dict of functions for converting values in certain columns. Keys can either
be integers or column labels

The same type can be compared together

TypeError: res.render is not a function

node + mysql:

When writing the demo today, I found that the code reported an error typeerror: res.render Is not a function, but I tested myself when it is not suitable for MySQL to query data res.render The () method is available, but when MySQL data is not available res.render() will not go wrong. Direct code:

Problem code

var express = require('express');
var router = express.Router();
const mysqlCon = require('../modules/mysql');

router.get('/', function(req, res, next) {
  mysqlCon.query("SELECT empno,ename,job FROM emp WHERE empno > 1008",function(err,res){
    if(err){
      return res.redirect('/');
    }
    console.log('======================res==========================');
    var UserInfo = res;
    // UserInfo = JSON.parse(JSON.stringify(UserInfo))
    res.render('index', {
			title: 'Home Page',
			UserInfo
		})
  })
});

report errors

Solution:

var express = require('express');
var router = express.Router();
const mysqlCon = require('../modules/mysql');

router.get('/', function(req, res, next) {
  mysqlCon.query("SELECT empno,ename,job FROM emp WHERE empno > 1008",function(err,result){
    if(err){
      return res.redirect('/');
    }
    console.log('======================res==========================');
    var UserInfo = result;
    // UserInfo = JSON.parse(JSON.stringify(UserInfo))
    res.render('index', {
			title: 'Home Page',
			UserInfo
		})
  })
});

The return value of MySQL query, res, can be changed to other definitions. Because the previous code style habitually defines the return value as res, which conflicts with the corresponding res in the node project res.render is not a function。 It’s not a big pit, mainly because the code habit has not been transformed…

C++ BUG: [Error] invalid array assignment

C++BUG: [Error] invalid array assignment

1. Introduction2. The difference between the return value of memcpy() function prototype function header file and strcpy

example

1. Introduction

When using array to assign value to array, the above bug will appear. The general chestnut is as follows:

while(!student.eof()){
        SS[j].name=stud.name;//Error
        SS[j].ID=stud.ID;
        SS[j].score=stud.score;
        j++;
    }

The purpose is to store the data in the structure array object SS [J], but this assignment will report an error.

2. memcpy()

Function prototype

void *memcpy(void*dest, const void *src, size_t n);

function

The data of consecutive n bytes with SRC pointing address as the starting address is copied into the space with destination pointing address as the starting address.

Header file

The use of # include & lt; string. H & gt;;

Both # include & lt; CString & gt; and # include & lt; string. H & gt; can be used in C + +

Return value

Function returns a pointer to dest.

The difference from strcpy

1. Compared with strcpy, memcpy does not end when it encounters’ \ 0 ‘, but will copy n bytes. Therefore, we need to pay special attention to memory overflow.
2. Memcpy is used to copy memory. You can use it to copy objects of any data type, and you can specify the length of the data to be copied. Note that source and destination are not necessarily arrays, and any read-write space can be used;
however, strcpy can only copy strings, and it ends copying when it encounters’ \ 0 ‘.

example

For 2D arrays

int main(void)
{
    int src[][3]={{1,2,3},{4,5,6},{7,8,9},{1,2,3},{4,5,6},{7,8,9}};  
    int des[6][3]={0};//Be careful, the number of lines is fixed
    memcpy(des,src,sizeof(src)); //beware of memory overflow
    return 1;
}

Error reading file by pandas pandas.errors.EmptyDataError: no columns to parse from file

1. Problems encountered:

The source code for reading. CSV is as follows:

import pandas as pd

def main():
    aqi_data = pd.read_csv('china_city_aqi.csv')
    print(aqi_data.head(5))

if __name__ == "__main__":
    main()

The complete error information is as follows:

Traceback (most recent call last):
  File "D:/XXX/Python Learning/lect09/AQI_9.0.py", line 14, in <module>
    main()
  File "D:/XXX/Python Learning/lect09/AQI_9.0.py", line 10, in main
    aqi_data = pd.read_csv('china_city_aqi.csv')
  File "D:\XXX\Python Learning\lect09\venv\new\lib\site-packages\pandas\io\parsers.py", line 702, in parser_f
    return _read(filepath_or_buffer, kwds)
  File "D:\XXX\Python Learning\lect09\venv\new\lib\site-packages\pandas\io\parsers.py", line 429, in _read
    parser = TextFileReader(filepath_or_buffer, **kwds)
  File "D:\XXX\Python Learning\lect09\venv\new\lib\site-packages\pandas\io\parsers.py", line 895, in __init__
    self._make_engine(self.engine)
  File "D:\XXX\Python Learning\lect09\venv\new\lib\site-packages\pandas\io\parsers.py", line 1122, in _make_engine
    self._engine = CParserWrapper(self.f, **self.options)
  File "D:\XXX\Python Learning\lect09\venv\new\lib\site-packages\pandas\io\parsers.py", line 1853, in __init__
    self._reader = parsers.TextReader(src, **kwds)
  File "pandas\_libs\parsers.pyx", line 545, in pandas._libs.parsers.TextReader.__cinit__
pandas.errors.EmptyDataError: No columns to parse from file

2. Solutions

Take a look pandas.read_ The official document of CSV may be related to

Engine: {C ‘,’python’}, optional

Parser engine to use. The C engine is faster while the python engine is currently more feature-complete.

So read_ Add engine = “Python” to the parameter of csv()

The above code is modified as follows:

import pandas as pd

def main():
    aqi_data = pd.read_csv('china_city_aqi.csv', engine='python')
    print(aqi_data.head(5))

if __name__ == "__main__":
    main()

Run successfully after modification!

/usr/bin/ld: skipping incompatible Error [How to Fix]

Today’s problem: /usr/bin/LD: skipping incompatible

QT reported an error when connecting a and so files

Analysis: the compiler’s error message is clear: compatibility issues

Analysis method:

File XXX. A “or” file ” xxx.so Take a look at whether the library version is 32-bit or 64 bit, or arm version or… And so on.

View so file information: 64 bit

user@ubuntu :~/Documents/CloudBox/VersionControlServer/code/bin$ file liblht_ coreframeworkD.so .1.0.0

liblht_ coreframeworkD.so .1.0.0: ELF

64-bit LSB shared object, x86-64, version 1 (SYSV), dynamically linked, BuildID[sha1]=0x395ec03d717504939d7e6c93f6f1132ea7830ad2, not stripped

 

View the system information: 64 bit is not displayed, basically 32-bit

user@ubuntu :~/Documents/CloudBox/VersionControlServer/code/bin$ uname -a Linux ubuntu 3.2.0-29-generic-pae # 46-Ubuntu SMP Fri Jul 27 17:25:43 UTC 2012  i686 i686 i386 GNU/Linux

Check the GUI system information: it’s really 32-bit.

 

Solutions.
1) recompile the 32-bit so file
2) switch to 64-bit linux

LeetCode 23. Merge k Sorted Lists(java)

Merge k sorted linked lists and return it as one sorted list. Analyze and describe its complexity.

Solution 1: use heap to do it. First, put the first element of K lists into heap. After each poll, put it into the next element of the poll until the heap is empty. The time complexity is O (mklogk), and the space complexity is O (k)

public ListNode mergeKLists(ListNode[] lists) {
        if (lists == null || lists.length == 0) return null;
        if (lists.length == 1) return lists[0];
        PriorityQueue<ListNode> queue = new PriorityQueue<>(new Comparator<ListNode>() {
            public int compare(ListNode o1, ListNode o2) {
                return o1.val - o2.val;
            }
        });
        for (int i = 0; i < lists.length; i++) {
            if (lists[i] != null) queue.add(lists[i]);
        }
        ListNode dummy = new ListNode(-1), cur = dummy;
        while (!queue.isEmpty()) {
            ListNode temp = queue.poll();
            cur.next = temp;
            cur = temp;
            if (temp.next != null) queue.add(temp.next);
        }
        return dummy.next;
    }

Solution 2: the idea of merge sort is better than solution 1. List merges in pairs each time, until the merges into a list, the time complexity is O ((M / 2) (K / 2 + K / 4 + K / 8 +…) )It is O (kmlogk), but it has a constant number of optimizations than method one. The space complexity is O (1)

public ListNode mergeKLists(ListNode[] lists) {
        if (lists == null || lists.length == 0) return null;
        int begin = 0, end = lists.length - 1;
        while (begin < end) {
            int mid = (begin + end - 1) / 2;
            for (int i = 0; i <= mid; i++) {
                lists[i] = merge2list(lists[i], lists[end - i]);
            }
            end = (begin + end) / 2;
        }
        return lists[0];
    }
    public ListNode merge2list(ListNode l1, ListNode l2) {
        if (l1 == null && l2 == null) return null;
        if (l1 == null) return l2;
        if (l2 == null) return l1;
        ListNode dummy = new ListNode(-1), cur = dummy;
        while (l1 != null && l2 != null) {
            if (l1.val < l2.val) {
                cur.next = l1;
                cur = l1;
                l1 = l1.next;
            } else {
                cur.next = l2;
                cur = l2;
                l2 = l2.next;
            }
        }
        if (l1 != null) cur.next = l1;
        if (l2 != null) cur.next = l2;
        return dummy.next;
    }

Solve the problem that “figure size 640×480 with 1 axes” does not display pictures in jupyter notebook

Problem code: (negligible code)

import numpy as np
from sklearn.feature_selection import SelectKBest, f_classif
import matplotlib.pyplot as plt
predictors = ["Pclass", "Sex", "Age", "SibSp", "Parch", "Fare", "Embarked", "FamilySize", "Title", "NameLength"]

# Perform feature selection
selector = SelectKBest(f_classif, k=5)
selector.fit(titanic[predictors], titanic["Survived"])

# Get the raw p-values for each feature, and transform from p-values into scores
scores = -np.log10(selector.pvalues_)

# Plot the scores.  See how "Pclass", "Sex", "Title", and "Fare" are the best?
plt.bar(range(len(predictors)), scores)
plt.xticks(range(len(predictors)), predictors, rotation='vertical')
plt.show()

# Pick only the four best features.
predictors = ["Pclass", "Sex", "Fare", "Title"]

alg = RandomForestClassifier(random_state=1, n_estimators=50, min_samples_split=8, min_samples_leaf=4)

Running results:
& lt; figure size 640x480 with 1 axes & gt;
no pictures are displayed

Solution:
Add % Matplotlib inline to the code header

import pandas #ipython notebook
titanic = pandas.read_csv("titanic_train.csv")
titanic.head(5)
#print (titanic.describe())
%matplotlib inline

[Getting and Cleaning data] Quiz 2

Question 1Question 2Question 3Question 4Question 5

For more detail, see the html file here.
Question 1
Register an application with the Github API here github application. Access the API to get information on your instructors repositories(target url) . Use this data to find the time that the datasharing repo was created. What time was it created? This tutorial may be useful help tutorial. You may also need to run the code in the base R package and not R studio.
2013-11-07T13:25:07Z2014-03-05T16:11:46Z2014-02-06T16:13:11Z2012-06-20T18:39:06Z

library(httr)
library(httpuv)
# 1.OAuth settings for github:
Client_ID <- '66fba4580b9b23531d6e'
Client_Secret <- '7fd8a4f7d72ab12b6c01b5c4880bc6da7723eec2'
myapp <- oauth_app("First APP", key = Client_ID, secret = Client_Secret)
# 2. Get OAuth credentials
github_token <- oauth2.0_token(oauth_endpoints("github"), myapp)
# 3. Use API
gtoken <- config(token = github_token)
req <- GET("https://api.github.com/users/jtleek/repos", gtoken)
stop_for_status(req)
# 4. Extract out the content from the request
json1 = content(req)
# 5. convert the list to json
json2 = jsonlite::fromJSON(jsonlite::toJSON(json1))
# 6. Result 
json2[json2$full_name == "jtleek/datasharing", ]$created_at

Question 2
The sqldf package allows for execution of SQL commands on R data frames. We will use the sqldf package to practice the queries we might send with the dbSendQuery command in RMySQL. Download the American Community Survey data and load it into an R object called acs(data website), Which of the following commands will select only the data for the probability weights pwgtp1 with ages less than 50?
sqldf("select * from acs where AGEP < 50")sqldf("select * from acs")sqldf("select pwgtp1 from acs")sqldf("select pwgtp1 from acs where AGEP < 50")

# load package: sqldf is short for SQL select for data frame.
library(sqldf)
# 1. download data 
download.file(url = "https://d396qusza40orc.cloudfront.net/getdata%2Fdata%2Fss06pid.csv", destfile = "./data/acs.csv")
# 2. read data
acs <- read.csv("./data/acs.csv")
# 3. select using sqldf
#sqldf("select pwgtp1 from acs where AGEP<50", drv='SQLite')

Question 3
Using the same data frame you created in the previous problem, what is the equivalent function to unique(acs$AGEP)
sqldf("select unique AGEP from acs")sqldf("select distinct pwgtp1 from acs")sqldf("select AGEP where unique from acs")sqldf("select distinct AGEP from acs")

result <- sqldf("select distinct AGEP from acs", drv = "SQLite")
nrow(result)
length(unique(acs$AGEP))

Question 4
How many characters are in the 10th, 20th, 30th and 100th lines of HTML from this page: target page.(Hint: the nchar() function in R may be helpful)
45 31 2 2543 99 8 643 99 7 2545 0 2 245 31 7 2545 92 7 245 31 7 31

# 1. set url
url <- url("http://biostat.jhsph.edu/~jleek/contact.html")
# 2. read content from url
content <- readLines(url)
# 3. result
nchar(content[c(10, 20, 30, 100)])

Question 5
Read this data set into R and report the sum of the numbers in the fourth column data web. Original source of the data: original data web
(Hint this is a fixed width file format)
35824.9101.8336.5222243.128893.332426.7

# 1. read data
data <- read.fwf(file = "https://d396qusza40orc.cloudfront.net/getdata%2Fwksst8110.for",
                 skip = 4,
                 widths = c(12, 7,4, 9,4, 9,4, 9,4))
# 2. result
sum(as.numeric(data[,4]))