Category Archives: JavaScript

How to use Runtime.getRuntime().Exec()

1. Wrong way to use it

Runtime.getRuntime().exec("xxx");

2. Correct usage

//You need to specify parameter one: command location; parameter two: -c means execute the first parameter first; parameter three: your command.
Runtime.getRuntime().exec(new String[]{"/bin/sh","-c","xxx"});

Such as:

try {
    Runtime.getRuntime().exec(new String[]{"/system/bin/sh","-c","reboot"});
}catch (Exception e) {
    e.printStackTrace();
}

Openmv identifies two-dimensional code, color recognition and serial communication

Openmv recognizes TWO-DIMENSIONAL code, color recognition and serial port communication
Objective Two-dimensional code recognition color recognition serial port communication complete code

purpose
1. Specify the content of the QR code: “XXX + XXX”, identify, return and send the corresponding serial number to the serial port; 2. Identify the color of materials in order according to the content of the two-dimensional code
3. Turn on the green light when standby, turn on the blue light when performing the action, and turn off the LED when the action is over.
Two-dimensional code recognition

while(True):
    img = sensor.snapshot()
    img.lens_corr(1.8)
    for code in img.find_qrcodes():
        output_str="%s" % code.payload()
		#output_str is QR code content

Attached (Forage TWO-DIMENSIONAL code generator)
Color identification

#Color Threshold
green_threshold   = (73, 96, -79, -22, -128, 127)
red_threshold   = (41, 61, 42, 127, -128, 127)
blue_threshold   = (22, 67, 9, 127, -128, -54)

blobs = img.find_blobs([green_threshold,red_threshold,blue_threshold],x_stride=25,y_stride=50,area_threshold=1000)
for b in blobs:
	img.draw_rectangle(b[0:4]) # rect
    #Mark the target color area with a rectangle
    img.draw_cross(b[5], b[6]) # cx, cy
    # draw a cross in the center of the target color area
    print(b[8]) # b[8] is the color code, red=2,green=1,blue=4

A serial port communication

if uart.any():# determine if data is received
	getrx = uart.readline()# read data
	uart.write('abc')#Send data

The complete code

import sensor, image, time, pyb
import ujson
from pyb import UART

green_threshold   = (73, 96, -79, -22, -128, 127)
#(0, 100, -128, -25, -128, 127)
red_threshold   = (41, 61, 42, 127, -128, 127)
#(41, 61, 42, 127, -128, 127)
blue_threshold   = (22, 67, 9, 127, -128, -54)
#(15, 100, -128, 127, -128, -41)
#red=2,green=1,blue=4
getrx = 0
getcmd = 0
renum = 0
colornum = 0
ptrposition = 0
sensor.reset()# Initialize the camera
sensor.set_pixformat(sensor.RGB565)# formatted as RGB565.
sensor.set_framesize(sensor.QQVGA) # Use QQVGA for faster speed
sensor.skip_frames(time = 2000) # Skip 2000s, make the new settings take effect, and adjust the white balance automatically
sensor.set_auto_gain(False) # Turn off auto gain. The default is on, in the color recognition, make sure to turn off the white balance.
sensor.set_auto_whitebal(False)
# Turn off white balance. White balance is on by default. In color recognition, be sure to turn off white balance.
clock = time.clock() # Track frame rate
led = pyb.LED(1) # Red LED = 1, Green LED = 1, Blue LED = 2, IR LEDs = 4.
uart = UART(3, 115200, timeout_char = 1000)
led.on()

def Rec_NUM1(lista):
    if (lista[0]=='1' and lista[1]=='2' and lista[2]=='3'):
        return 1
    elif (lista[0]=='1' and lista[1]=='3' and lista[2]=='2'):
        return 2
    elif (lista[0]=='2' and lista[1]=='1' and lista[2]=='3'):
        return 3
    elif (lista[0]=='2' and lista[1]=='3' and lista[2]=='1'):
        return 4
    elif (lista[0]=='3' and lista[1]=='1' and lista[2]=='2'):
        return 5
    elif (lista[0]=='3' and lista[1]=='2' and lista[2]=='1'):
        return 6

def Rec_NUM2(lista):
    if (lista[4]=='1' and lista[5]=='2' and lista[6]=='3'):
        return 1
    elif (lista[4]=='1' and lista[5]=='3' and lista[6]=='2'):
        return 2
    elif (lista[4]=='2' and lista[5]=='1' and lista[6]=='3'):
        return 3
    elif (lista[4]=='2' and lista[5]=='3' and lista[6]=='1'):
        return 4
    elif (lista[4]=='3' and lista[5]=='1' and lista[6]=='2'):
        return 5
    elif (lista[4]=='3' and lista[5]=='2' and lista[6]=='1'):
        return 6

while(True):
    clock.tick() # Track elapsed milliseconds between snapshots().
    if uart.any():
        led.off()
        getrx = uart.readline()
        time.sleep(150)     #Time delay 150ms
        led = pyb.LED(2)
        led.on()
        getcmd = int(getrx)
        print(getcmd)
      #  print(img.find_qrcodes())
    img = sensor.snapshot()# 从The light-sensitive chip acquires an image
    img.lens_corr(1.8) # strength of 1.8 is good for the 2.8mm lens.
    blobs = img.find_blobs([green_threshold,red_threshold,blue_threshold],x_stride=25,y_stride=50,area_threshold=1000)
    if(getcmd==2):
        for code in img.find_qrcodes():
            output_str="%s" % code.payload() #Method 1
            renum = int(Rec_NUM1(output_str)*10 + Rec_NUM2(output_str))
            uart.write(ujson.dumps(renum))
            getcmd = 0
            led.off()
    if blobs and getcmd==3:
        for b in blobs:
            # Draw a rect around the blob.
            img.draw_rectangle(b[0:4]) # rect
            #Mark the target color area with a rectangle
            img.draw_cross(b[5], b[6]) # cx, cy
            # Draw a cross in the center of the target color area
            #print(b[5], b[6], b[8])
            #uart.write(ujson.dumps(b[8]))
            #transfer color serial number to race serial number
            if b[8]==1:
                colornum=2
            elif b[8]==2:
                colornum=1
            elif b[8]==4:
                colornum=3
            print('colornum=',colornum,'output_str[ptrposition]=',output_str[ptrposition])
            #If the task code corresponds to
            if (int(output_str[ptrposition]) == colornum):
                uart.write('t')
                ptrposition+=1
                if ptrposition==4:
                    ptrposition+=1
                getcmd=0

Vue: How to Fix “not displaying the holder in IE9 and below”

For.html projects, add placeholder.js after introducing jquery to the page you need
Since I’m a vue+elementUI project, I don’t refresh the browser every time I switch menus, so I’ve cleaned up the usage in vUE
Jquery file also needs to be introduced here, otherwise the error may be reported. Just introduce jquery in index.html

Here’s how to use it in a Vue
First create placeholder.js file in the public JS file and output a PlaceholderInit function

//Solve the problem that the placeholder of input is not displayed under ie.

export function PlaceholderInit() {
  return jQuery(function() {
    var placeholderfriend = {
      focus: function(s) {
        s = $(s)
          .hide()
          .prev()
          .show()
          .focus();
        var idValue = s.attr("id");
        if (idValue) {
          s.attr("id", idValue.replace("placeholderfriend", ""));
        }
        var clsValue = s.attr("class");
        if (clsValue) {
          s.attr("class", clsValue.replace("placeholderfriend", ""));
        }
      }
    };

    //Determine if placeholder support is available.
    function isPlaceholer() {
      var input = document.createElement("input");
      return "placeholder" in input;
    }
    //Unsupported Codes
    if (!isPlaceholer()) {
      $(function() {
        var form = $(this);
        var elements = form.find("input[type='text'][placeholder]");
        elements.each(function() {
          var s = $(this);
          var pValue = s.attr("placeholder");
          var sValue = s.val();
          if (pValue) {
            if (sValue == "") {
              s.val(pValue);
            }
          }
        });

        elements.focus(function() {
          var s = $(this);
          var pValue = s.attr("placeholder");
          var sValue = s.val();
          if (sValue && pValue) {
            if (sValue == pValue) {
              s.val("");
            }
          }
        });

        elements.blur(function() {
          var s = $(this);
          var pValue = s.attr("placeholder");
          var sValue = s.val();
          if (!sValue) {
            s.val(pValue);
          }
        });

        var elementsPass = form.find("input[type='password'][placeholder]");
        elementsPass.each(function(i) {
          var s = $(this);
          var pValue = s.attr("placeholder");
          var sValue = s.val();
          if (pValue) {
            if (sValue == "") {
              var html = this.outerHTML || "";
              html = html
                .replace(
                  /\s*type=(['"])?password\1/gi,
                  " type=text placeholderfriend"
                )
                .replace(/\s*(?:value|on1[a-z]+|name)(=(['"])?\S*\1)?/gi, " ")
                .replace(
                  /\s*placeholderfriend/,
                  " placeholderfriend value='" +
                    pValue +
                    "' " +
                    "οnfοcus='placeholderfriendfocus(this);' "
                );
              var idValue = s.attr("id");
              if (idValue) {
                s.attr("id", idValue + "placeholderfriend");
              }
              var clsValue = s.attr("class");
              if (clsValue) {
                s.attr("class", clsValue + "placeholderfriend");
              }
              s.hide();
              s.after(html);
            }
          }
        });

        elementsPass.blur(function() {
          var s = $(this);
          var sValue = s.val();
          if (sValue == "") {
            var idValue = s.attr("id");
            if (idValue) {
              s.attr("id", idValue + "placeholderfriend");
            }
            var clsValue = s.attr("class");
            if (clsValue) {
              s.attr("class", clsValue + "placeholderfriend");
            }
            s.hide()
              .next()
              .show();
          }
        });
      });
    }
    window.placeholderfriendfocus = placeholderfriend.focus;
  });
}

Deconstruct PlaceholderInit function
on pages that need to display placeholders

import { PlaceholderInit } from '@/utils/placeholder'

Call this function before the page is displayed, so that the place where the current page needs to display placeholders will display
when the page comes in

PlaceholderInit();

If the input page of a new pop-up box needs to display placeholders, the function

will also be called when the new pop-up box is opened

If the request parameter is formdata, use the Ajax operation

If the request parameter supplied when requesting the interface is of type FormData, we can divide the operation into two ways.
The method in FormData()
0, append() append value
1, set() modify value
2, getAll() get all check box values
3, get() get radio box values
1. Ajax encapsulated by jQuery
If the request parameter is formdata, must set two configuration items
processData: false
contentType: false

  $.ajax({
            url: 'Interface Address',
            type: "POST",
            data: fd,
            success: function(res){

            },
            processData: false, //do not convert data request data (the object format is automatically converted to string format on request)
            contentType: false // do not set request header (FormData comes with request header)
        })

2. Native Ajax manipulation
If the request parameter is FormData, then post-style Ajax requests no longer need to set the request header


FormData:
	var form = $("form")[0];	//Converting jq objects to DOM objects (must be DOM objects)
	var fd = new FormData(form);
	
	
Native ajax:
 		var xhr = new XMLHttpRequest();
        xhr.open('POST', '/common/post'). xhr.onload = function () { var xhr.open('POST', '/common/post');
        xhr.open('POST', '/common/post'); xhr.onload = function () {
            console.log(this.response); // output the result
        }
        xhr.send(fd); //pass the data from the form to the backend

JavaScript determines whether parentheses are paired.

Example:
		"()" | "()[]{}" | "{[]}"	true	{{{{}}}([])}
		"(]" | "([)]"	false				{{{{}}}([[])]}	{([)]}
		*/
		var str = "{{{{}}}([[])]}";
		var isValid = function(s){
			let items = []
			let sLength = s.length
			if(sLength % 2 !== 0){
				return false
			}
			for(let i=0; i < sLength; i++){
				switch(s[i]){
					case "(":
						items.push(s[i])
						break
					case "[":
						items.push(s[i])
						break
					case "{":
						items.push(s[i])
						break
					case ")":
						if(items[items.length - 1] === "("){
							items.pop()
						}
						break
					case "]":
						if(items[items.length - 1] === "["){
							items.pop()
						}
						break
					case "}":
						if(items[items.length - 1] === "{"){
							items.pop()
						}
						break
				}
			}
			return items.length === 0
		}
		console.log(isValid(str))

package.json Scripts configuration environment variable distinguishes development environment from production environment

Sometimes it is necessary to differentiate between packages from production and development environments to determine which base url or other variables you need to useMethod 1:

//windows System:
"builddev": "set NODE_ENV=dev&&vue-cli-service build",
"buildprod": "set NODE_ENV=prod&&vue-cli-service build",

//mac System:
"builddev": "export NODE_ENV=dev&&vue-cli-service build",
"buildprod": "export NODE_ENV=prod&&vue-cli-service build",

Method 2:
First install the dependencies: NPM install –save-dev cross-env
Then configure compatible Windows and MAC environments

"builddev": "cross-env NODE_ENV=dev vue-cli-service build",
"buildprod": "cross-env NODE_ENV=prod vue-cli-service build",

Finally, in the JS code, the corresponding value can be obtained through: process.env.node_env, which is used to judge the environment:
baseurl:process.env.NODE_ENV===’prod’?’http://prod.api.com’:’http://test.api.com’
console.log(process.env);// {BASE_URL: “”, NODE_ENV:” prod “}

Ps: The vUE – CLi is used here to configure NODE_ENV, other projects may be to configure WEBPACK_ENV, directly replace, then console. Log (process.env) to see the environment

How to Fix “HTTP 405 method not allowed” Error

In the Angular 1.4 version of the project, the program was working fine until one day when the form submission prompted an “HTTP 405” error — “Method Not Allowed”.
Either GET or POST items GET interface submit data, but check back and back again and again. Both are POST. No problem at all.
After careful examination of the front-end code, it is found that the writing method is as follows:

$http({
    method : 'POST',
    url : '/test',
    params : {
        cycle : key,
        emp_id : user.id
    }
 }).success(function (resp) {
 });

This programming approach has two problems:
1. The submitted parameters are exposed; 2. The default Header parameter “content-type” submitted is “application/json”;
But after trial and error, see Prioritizing Browser Query Parameters and Form Data. The first problem doesn’t cause 405 errors, so it’s easy to identify the problem. The solution is to specify the “content-Type” explicitly, as follows:

$http({
    method : 'POST',
    url : '/test',
    params : {
        cycle : key,
        emp_id : user.id
    },
    //  New content-type header attribute
    heads : {
        'content-type' : 'application/x-www-form-urlencoded'
    }
 }).success(function (resp) {
    //  Processing Logic
 });

If you want to solve the first problem, you only need to introduce the $httpParamSerializer service as follows:

$http({
    method : 'POST',
    url : '/test',
    //  Submit as a form, converting Object to form arguments.
    data : $httpParamSerializer({
        cycle : key,
        emp_id : user.id
    }),
    //  New content-type header attribute
    heads : {
        'content-type' : 'application/x-www-form-urlencoded'
    }
 }).success(function (resp) {
    //  Processing Logic
 });

conclusion
In the event of an HTTP 405 error, first check the “content-Type” information in the request header.

Localstorage sets the expiration time.

We all know that localStorage does not actively delete and will never be destroyed, so how to set the expiration time of localStorage?Let’s try it together today!
<script type=”text/javascript”>
function set(key,value){
var curTime = new Date().gettime ();
localStorage. SetItem (key, JSON stringify ({data: value, time: curTime}));
}
function get(key,exp){
var data = localStorage. GetItem (key);
var dataObj = json.parse (data);
if (new Date(). GetTime () – dataobj. time> Exp) {
console.log(‘ message has expired ‘);
// alert (” overdue information “)
} else {
// console log (” data = “+ dataObj. Data);
// the console. The log (JSON. Parse (dataObj. Data));
var dataObjDatatoJson = json.parse (dataobj.data)
return dataObjDatatoJson;}}
</script>

usage scenario:
1. Use local data to reduce network transmission
2. Weak network environment, high latency, low bandwidth, try to localize the data
Usage:
< script>
window.onload = function(){
var Ipt = document.getElementById(‘input1’);
var value = ‘{” name “:” and send the bore is clear “, “Age” : “18”, “address” : “lujiazui city”} “;
set (‘ information, value);
Function (){
//var dataObjData=get(‘information’,1000);
//var dataObjData=get(‘information’,1000*60);
//var dataObjData=get(‘information’,1000*60*60);
// expiration time is 1 hour// var Obj = get (” information “, 1000 * 60 * 60 * 24);
var dataObjData=get(‘information’,1000*60* 24*7);
console.log(dataObjData || null);
if (dataObjData! =”” & & dataObjData! . = null) {
the console log (” name: “+ dataObjData. Name);
the console. The log (” Age: “+ dataObjData. Age);
the console. The log (” address: “+ dataObjData. Age);
} else {
alert (” access to information has expired “);
}
}
}
< /script>

1 function setLocalStorage(key, value) {
 2     var curtime = new Date().getTime(); // Get the current time and convert it to a JSON string sequence. 
 3     var valueDate = JSON.stringify({
 4         val: value,
 5         timer: curtime
 6     });
 7     try {
 8         localStorage.setItem(key, valueDate);
 9     } catch(e) {
10         /*if(e.name === 'QUOTA_EXCEEDED_ERR' || e.name === 'NS_ERROR_DOM_QUOTA_REACHED') {
11             console.log("Error: Local Storage Exceeds Limit");
12             localStorage.clear();
13         } else {
14             console.log("Error: Failure to save to local storage");
15         }*/
16         // Compatibility Writing
17         if(isQuotaExceeded(e)) {
18             console.log("Error: Local Storage Exceeds Limit");
19             localStorage.clear();
20         } else {
21             console.log("Error: Failure to save to local storage");
22         }
23     }
24 }
25 
26 function isQuotaExceeded(e) {
27     var quotaExceeded = false;
28     if(e) {
29         if(e.code) {
30             switch(e.code) {
31                 case 22:
32                     quotaExceeded = true;
33                     break;
34                 case 1014: // Firefox 
35                     if(e.name === 'NS_ERROR_DOM_QUOTA_REACHED') {
36                         quotaExceeded = true;
37                     }
38                     break;
39             }
40         } else if(e.number === -2147024882) { // IE8 
41             quotaExceeded = true;
42         }
43     }
44     return quotaExceeded;
45 }
46 
47 function getLocalStorage(key) {
48     var exp = 60 * 60 * 24; // Seconds of the day
49     if(localStorage.getItem(key)) {
50         var vals = localStorage.getItem(key); // Get locally stored values 
51         var dataObj = JSON.parse(vals); // Converting Strings to JSON Objects
52         // If (current time - the time the stored element was set at creation) > Expiration time 
53         var isTimed = (new Date().getTime() - dataObj.timer) > exp;
54         if(isTimed) {
55             console.log("Storage has expired");
56             localStorage.removeItem(key);
57             return null;
58         } else {
59             var newValue = dataObj.val;
60         }
61         return newValue;
62     } else {
63         return null;
64     }
65 }
66 
67 setLocalStorage('name', 'hello, world');
68 var localKey = getLocalStorage('name');
69 console.log(localKey);

TypeScript error TS2345: Argument of type ‘String ‘is not assignable to parameter of type ‘string’

Today I encountered an error learning TypeScript polymorphism (i.e., inheritance)
Mistakes show

here indicates an error with super inheritance. String arguments cannot be assigned to string arguments. What the hell is this
To solve the error
See String, think of it, change to String try it? So he can
Modified polymorphic code

class Animal {
    name:String
    constructor(name:String) {
        this.name = name
    }
    eat() {}
}
class Dog extends Animal{
    constructor(name:String) {
        super(name)
    }
    eat() {
        return this.name + 'Eat Bean'
    }
}
class Cat extends Animal{
    constructor(name:String) {
        super(name)
    }
    eat() {
        return this.name + 'Eat?'
    }
}
let dog = new Dog('WW')
console.log(dog.eat())
let cat = new Cat('MM')
console.log(cat.eat())

Questions remain
In fact, the previous use of string inheritance is shown without error information, I don’t know why there is an error when using polymorphic inheritance, so I can only change it to string according to the prompt. If you know the reason, please give instruction

Application of call, apply and bind methods

1. call
Effect: Changes this point to call the function to pass in an argument.
Grammar:

function.call(this, arg1, arg2, ...)

Application: The child constructor inherits the properties of the parent constructor

function Father (surname) {
    this.surname = surname;
}
function Son (surname) {
    // Changes this in the parent constructor to this in the child constructor, and passes a value to this attribute.
    Father.call(this, surname);
}
var xiaoming = new Son('xiao');

2. apply
Effect: Changes this point to call the function to pass in an argument.
Grammar:

function.apply(this, [arg1, arg2, ...])

Application: Call a method in Math

var arr = [1, 2, 3];
Math.max.apply(Math, arr);

3. bind
Effect: Change this point to pass in parameter.
Grammar:

function.bind(this, arg1, arg2, ...)

Application: Change the this pointer in setTimeout

var obj = {
    data: 'first',
    init: function () {
        setTimeout(function(){
            this.data = 'last';
        }.bind(this), 3000)
    }
}
obj.init();

JS uses onerror to automatically catch exceptions

Catch exceptions

    1. use try catch use window.onerror to automatically catch exceptions.
//No need to use try catch to automatically catch error messages on every line.
// (error message, source code, in which line, in which column, error thrown)
window.onerror = function (message, source, lineNom, colNom, error) {
     // First, for cross-domain js, such as CDN's, there will be no detailed error message.
     // Second, for compressed js, but also with the sourceMap backtrack to the uncompressed code rows and columns
}

Take the following example

<script>
    window.onerror = function (message, source, lineNom, colNom, error) {
        console.log('Error')
        console.log(message)
        console.log(source)
        console.log(lineNom)
        console.log(colNom)
        console.log(error)
        return true //By returning true, the red error message will not be displayed on the console.
    }
    function aa() {
        console.log('aa')
        console.log(aa.nme.dsa)
        console.log('aa')
    }
    aa()
</script>
// ouput
aa
error
Uncaught TypeError: Cannot read property 'dsa' of undefined
http://127.0.0.1:5500/test.html
25
32
TypeError: Cannot read property 'dsa' of undefined
    at aa (test.html:25)
    at test.html:28
      1. first, for cross-domain js such as CDN, there will be no detailed error information
      1. For the error in the introduced js file, onerror will only know that there is an exception. If you want to locate the error, first set the server to support cross-domain,

access-control-allow-origin :*

      1. . Then, set the crossorigin attribute in the srcipt tag of the introduced js.
 ```

 For example, audio img link script video tag, their src attribute can be any link from any source, and all of them can be loaded. With the addition of the corssorigin property, the resources will not be loaded in the default cross-domain way, but in the **CORS** way, so that the onerror can listen to it.
      1. second, for compressed js, it is necessary to cooperate with sourceMap to reverse check the rows and columns of uncompressed code, which can only catch the errors of js runtime. Syntax error can’t catch
        window.addEventListener('error', function(e) {
            console.log('chucuole')
            e.preventDefault() //Error messages are not displayed on the console
        }, false)//default to false, bubbling state, capture state when set to true
    1. is the state of the capture (the third parameter is true) can catch js execution error, also can catch the tag element with SRC load error. When is bubble state (the third parameter is false), js execution errors can be caught, but loading errors of tag elements with SRC cannot be caught. PreventDefault