Notes

JavaScript

Read more »

Apple

1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
50
51
52
53
54
55
56
57
58
59
60
61
62
63
64
65
66
67
68
69
70
71
72
73
74
75
76
77
78
79
80
81
82
83
84
85
86
87
88
89
90
91
92
93
94
95
96
97
98
99
#include <iostream>
#include <vector>
#include <utility>
using namespace std;
int calcScore(vector<pair<int, int>>& inp) //<5,6,10,9> --><10, 9, >
{

int res =0;
//for handle a:
// b, c
int checkPair[13]={0}; // A-king, 1-13 0-12 //-1
int checkFlush[4] ={0}; // 4 suits 0 ,1,2,3
for(auto item: inp)
{
checkPair[item.second-1]++;
checkFlush[item.first]++;
if(checkFlush[item.first]==4)
res+=4;
}
for(auto item: checkPair)
{
if(item==2)
res+=2;
else if(item==3)
{
//c num 2
res+= 6; // 2*3; // 3 => 3, 4=>6 (n-1)*(n-2)
}
else if(item==4)
{
res+=12; //2*6;
}
}
for(auto x: inp)
{
if(x.second>10) x.second=10;
}
for(int i=0; i<inp.size(); i++)
{
for(int j=i+1; j<inp.size(); j++)
{
if(inp[i].second + inp[j].second>=15)
res+=2;
}
}
return res;
}
// To execute C++, please define "int main()"
int main() {
vector<pair<int, int>> inp={
{0,1},{0,2},{0,3},{0,4}
};
cout<<calcScore(inp)<<endl; //=> 4


vector<pair<int, int>> inp2={
{0,8},{1,9},{0,3},{0,7} //2,2,2
};
cout<<calcScore(inp2)<<endl; //=> 4

vector<pair<int, int>> inp3={
{0,6},{1,6},{2,6},{0,2} //2,2,2
};
cout<<calcScore(inp3)<<endl; //=> 4


vector<pair<int, int>> inp4={
{0,6},{1,6},{2,6},{3,6} //2,2,2
};
cout<<calcScore(inp4)<<endl; //=> 4

return 0;
}

/*
Your previous Plain Text content is preserved below:

/*

// Determine the Cribbage score (simplified) for a hand of four cards.
Rules:
# // a) "Fifteen" any 2 cards' values sum to 15 => 2 points
# // (where value of Jack,Queen,King = 10, Ace = 1).
# // b) "Pair" any two cards with same rank => 2 points. //2,2,2 -> 6
# // c) "flush" all four cards with same suit => 4 points. //1,2,3,4 Hearts
# // Example: [Jack Hearts, Jack Clubs, 5 Spades, Queen Clubs] ==> 8 pts
# // 2 pts: Jack Hearts + 5 = 15
# // 2 pts: Jack Clubs + 5 = 15
# // 2 pts: Queen Clubs + 5 = 15
# // 2 pts: Pair of Jacks)

# Question: Implement a func calcScore that returns the score for a hand of
cards
//input 4.
//c++
//pair<int, int> heart-1, clubs -2.... //<suit, number>
//inp no dup
//[C1 , C2, C3, C4] = 0+
//checkPair[1,1,1,1,0,0,0...]
*/

Airbnb

Text adjust

1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
class Solution {//
public:
vector<string> fullJustify(vector<string>& words, int maxWidth) {
int i, l=0, k=0;
vector<string> res;
for(i=0; i<words.size(); i+=k)
{
l+=words[i].size();
//for(k=1; k+i<words.size() && l+k-1+words[i+k].size()<=maxWidth; k++)
for(k=1; k+i<words.size() && l+k+words[i+k].size()<=maxWidth; k++) //k more than 1
l+=words[i+k].size();
//cout<<"i ="<<i<<", k is"<<k<<", l:"<<l<<endl;
string temp=words[i];//todo k==0
for(int j=1; j<k;j++) //from j->k
{
if(i+k>=words.size()) temp+=" "+words[i+j];
else{
int space = (maxWidth-l)/(k-1); int extraspace=0;//int space = (maxWidth-l)/(i+k); int extraspace=0;
//cout<<"maxWidth: "<<maxWidth<<endl;
//cout<<"space is: "<<space<<endl;
extraspace=(maxWidth-l)%(k-1)>=j;//extraspace=(maxWidth-l)%(i+k)>=j;//2
temp+=string(space+extraspace,' ')+words[i+j];
//cout<<"-"<<temp<<"-"<<endl;
}
}
temp+=string(maxWidth-temp.size(),' ');
//cout<<endl;
res.push_back(temp);
l=0;
}
return res;
}
};
//problem
//k more than 1,
//k-1=0
//

Round Point

他们公司list价格分成好几个部分,但是都是整数,如果在美金是整数,到了欧洲的网页显示汇率转换之后就变成了floating point,然后要round成整数,但是全部加起来round,和单独round再加起来,结果会不一样

base price 100 => 131.13 => 131
cleaning fee 20 => 26.23 => 26
service fee 10 => 13.54 => 14
tax 5 => 6.5 => 7.
=> 177.4E => 178E
sum 135$ => 178.93E => 179E

那么问题就来了,给个input list of floating points, 要求output list of integers, 满足以下两个constraint, 就是和跟Round(x1+x2+… +xn)的结果一样,但是minimize output 和input的绝对值差之和

Input: A = [x1, x2, …, xn]
Sum T = Round(x1+x2+… +xn) ; 178.93E => 179.
Output: B = [y1, y2, …., yn]

Constraint #1: y1+y2+…+yn = T
Constraint #2: minimize sum(abs(diff(xi - yi)))

举例

A = [1.2, 2.3, 3.4]
Round(1.2 + 2.3 + 3.4) = 6.9 => 7.
1 + 2 + 3 => 6

1 + 3 + 3 => 7
0.2 + 0.7 + 0.4 = 1.3

1 + 2 + 4 => 7
0.2 + 0.3 + 0.6 = 1.1
所以[1,2,4]比[1,3,3]要好

1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
class Solution{
public:
vector<int> getMin(vector<float> inp)
{
vector<int> res(inp.begin(), inp.end());
double T =0; int sum=0;
for(int i=0; i<inp.size(); i++)
{
T += inp[i];
sum += res[i];
}
T = round(T);
int left = T-sum;
if(left == 0) return res;
vector<int> resIndex(inp.size());
iota(resIndex.begin(), resIndex.end(), 0);
sort(resIndex.begin(), resIndex.end(),
[res](int a, int b){
return res[a]>res[b];
});
int index=0;
while(left>0)
{
res[resIndex[index++]]++;
left--;
}
return res;
}
};
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
#include <iostream>
#include <math.h>
#include <numeric>

class Solution{
public:
vector<int> getMin(vector<float> inp)
{
vector<int> res(inp.begin(), inp.end());
double T =0; int sum=0;
for(int i=0; i<inp.size(); i++)
{
T += inp[i];
sum += res[i];
}
cout<<"T is: "<<T<<endl;
T = round(T);
cout<<"T is: "<<T<<", and sum is: "<<sum<<endl;
int left = T-sum;
if(left == 0) return res;
vector<int> resIndex(inp.size());
iota(resIndex.begin(), resIndex.end(), 0);
sort(resIndex.begin(), resIndex.end(),
[res](int a, int b){
return res[a]>res[b];
});
int index=0;
cout<<"Index sort is: ";
for(auto item: resIndex) cout<<item<<" ";cout<<endl;
cout<<"left is: "<<left<<endl;
while(left>0)
{
res[resIndex[index++]]++;
left--;
}
return res;
}
};


int main() {
vector<float> inp = {1.2, 2.3, 3.4};
Solution S;
vector<int> res = S.getMin(inp);
for(auto x: res) cout<<x<<" ";
cout<<endl;
}

20180824

1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
50
51
52
53
54
55
56
57
58
59
60
61
62
63
64
65
66
67
68
69
70
71
72
73
74
75
76
77
78
79
80
81
82
83
84
85
86
87
88
89
90
91
92
93
94
95
96
//aba, aabbaa 


// ["gab", "cat", "Bag", "alpha"] => find(ab) find(ga) ... find(bag)
// => [["gab", "Bag"], ["bag", "gab"]]

// 012
// "gab" index 0->3 => g, ga, gab
/*
if(is_P(g)) => is_p(ga) X => gab X
{
hashtable.find(ba) //=> ba gab, =>bag
}
// "gab" index 3->0 => b, ab, gab
hashtable exist => ag, X, X => bag
*/

//every lower case
//no dup

// check from beg, end two if

#include <iostream>
#include <unordered_map>
#include <vector>
#include <algorithm>
using namespace std;

class Solution{
public:
vector<vector<string>> findPPairs(vector<string> words)
{
vector<vector<string>> result;
unordered_map<string, int> dict; // the string, the string's index
for(int i=0; i<words.size(); i++) dict[words[i]] = i;
for(int i=0; i<words.size(); i++)
{
for(int j=0; j<=(int)words[i].size();j++)
{
//check beg
if(is_p(words[i], j, (int)words[i].size() - 1)) // aaa, aa
{
string suffix = words[i].substr(0, j);
reverse(suffix.begin(), suffix.end());
if(dict.find(suffix) != dict.end() && i!=dict[suffix])
{
vector<string> temp;
temp.push_back(words[i]);
temp.push_back(words[dict[suffix]]);
result.push_back(temp);
}

}
//check end
if(j>0 && is_p(words[i], 0, j-1)) // aaa, aa 1,2
{
string prefix = words[i].substr(j);
reverse(prefix.begin(), prefix.end());
if(dict.find(prefix) != dict.end() && i!=dict[prefix])
{
vector<string> temp;
temp.push_back(words[i]);
temp.push_back(words[dict[prefix]]);
result.push_back(temp);
}

}
}
}
return result;

}
bool is_p(string s, int start, int end){
while(start < end)
{
if(s[start++]!=s[end--])
return false;
}
return true;
}

};

int main() {
//vector<string> inp ={"gab", "cat", "bag", "alpha"};
vector<string> inp = {"gab", "cat", "bag", "alpha", "nurses", "race", "car", "run"};
Solution s;
vector<vector<string>> res = s.findPPairs(inp);
for(auto item: res)
{
for(auto x: item)
cout<<x<<" ";
cout<<endl;
}

return 0;
}

Sublime-project 一键大开方法

在你喜欢的地方建个 ‘.sublime-project’ extension 的文件,在里面用下面这格式:

Read more »

Python 输出 Excel

先装model:pip install xlwt

下面是sample code:
https://pypi.python.org/pypi/xlwt

‘’’
import xlwt
from datetime import datetime

style0 = xlwt.easyxf(‘font: name Times New Roman, color-index red, bold on’,
num_format_str=’#,##0.00’)
style1 = xlwt.easyxf(num_format_str=’D-MMM-YY’)

wb = xlwt.Workbook()
ws = wb.add_sheet(‘A Test Sheet’)

ws.write(0, 0, 1234.56, style0)
ws.write(1, 0, datetime.now(), style1)
ws.write(2, 0, 1)
ws.write(2, 1, 1)
ws.write(2, 2, xlwt.Formula(“A3+B3”))

wb.save(‘example.xls’)
‘’’

Amazon

Asked to find sub-strings from a string which are valid dictionary words.

Two sentences and wanted me to return a list of words that exists in one sentence but not on the other one. for example s1 = “I am happy” s2 = “I am old”, you have to return [“happy”, “old”]

the difference betwemarken abstract class and interface

interface

An interface is a contract: the guy writing the interface says, “hey, I accept things looking that way”, and the guy using the interface says “Ok, the class I write looks that way”.

An interface is an empty shell, there are only the signatures of the methods, which implies that the methods do not have a body. The interface can’t do anything. It’s just a pattern.

1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
// I say all motor vehicles should look like this:
interface MotorVehicle
{

void run();

int getFuel();
}

// my team mate complies and writes vehicle looking that way
class Car implements MotorVehicle
{


int fuel;

void run()
{

print("Wrroooooooom");
}


int getFuel()
{

return this.fuel;
}
}

Implementing an interface consumes very little CPU, because it’s not a class, just a bunch of names, and therefore there is no expensive look-up to do. It’s great when it matters such as in embedded devices.

Abstract class

Abstract classes, unlike interfaces, are classes. They are more expensive to use because there is a look-up to do when you inherit from them.

Abstract classes look a lot like interfaces, but they have something more : you can define a behavior for them. It’s more about a guy saying, “these classes should look like that, and they have that in common, so fill in the blanks!”.

1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
// I say all motor vehicles should look like this :
abstract class MotorVehicle
{


int fuel;

// they ALL have fuel, so why not let others implement this?
// let's make it for everybody
int getFuel()
{
return this.fuel;
}

// that can be very different, force them to provide their
// implementation
abstract void run();


}

// my team mate complies and writes vehicle looking that way
class Car extends MotorVehicle
{

void run()
{
print("Wrroooooooom");
}
}

Implementation

While abstract classes and interfaces are supposed to be different concepts, the implementations make that statement sometimes untrue. Sometimes, they are not even what you think they are.

In Java, this rule is strongly enforced, while in PHP, interfaces are abstract classes with no method declared.

In Python, abstract classes are more a programming trick you can get from the ABC module and is actually using metaclasses, and therefore classes. And interfaces are more related to duck typing in this language and it’s a mix between conventions and special methods that call descriptors (the method methods).

As usual with programming, there is theory, practice, and practice in another language :-)

OOP

转载:https://www3.ntu.edu.sg/home/ehchua/programming/cpp/cp3_OOP.html
C++ Programming Language
Object-Oriented Programming (OOP) in C++

Why OOP?

Suppose that you want to assemble your own PC, you go to a hardware store and pick up a motherboard, a processor, some RAMs, a hard disk, a casing, a power supply, and put them together. You turn on the power, and the PC runs. You need not worry whether the motherboard is a 4-layer or 6-layer board, whether the hard disk has 4 or 6 plates; 3 inches or 5 inches in diameter, whether the RAM is made in Japan or Korea, and so on. You simply put the hardware components together and expect the machine to run. Of course, you have to make sure that you have the correct interfaces, i.e., you pick an IDE hard disk rather than a SCSI hard disk, if your motherboard supports only IDE; you have to select RAMs with the correct speed rating, and so on. Nevertheless, it is not difficult to set up a machine from hardware components.

Similarly, a car is assembled from parts and components, such as chassis, doors, engine, wheels, brake, and transmission. The components are reusable, e.g., a wheel can be used in many cars (of the same specifications).
Hardware, such as computers and cars, are assembled from parts, which are reusable components.
How about software? Can you “assemble” a software application by picking a routine here, a routine there, and expect the program to run? The answer is obviously no! Unlike hardware, it is very difficult to “assemble” an application from software components. Since the advent of computer 60 years ago, we have written tons and tons of programs. However, for each new application, we have to re-invent the wheels and write the program from scratch.
Why re-invent the wheels?

MongoDB

简写t

  • 简写替换:如果db=test, collection=profile, 可以简写t=db.profile, 以后t就可以代替db.profile了
  • mongoimport

    1
    > mongoimport -d DBName -c CollectionName FileName
  • bool 不用加引号(EX: {“registered”:false})

Insert

db..insert(<>)

Full update

1
db.<collection>.update(<where>,<full or patial update expression>[,<upsert>,<multi>])

mongo shell update use javascript

myobj=t.findOne() 存现有值到一个myobj变量里, 注意一定要用findOne()

CSRG_Token

From: http://www.acunetix.com/websitesecurity/csrf-attacks/

CSRF Attacks, XSRF or Sea-Surf – What They Are and How to Defend Against Them

Cross-Site Request Forgery, or CSRF for short is a common and regular online attack. CSRF also goes by the acronym XSRF and the phrase “Sea-Surf”. CSRF attacks include a malicious exploit of a website in which a user will transmit malicious requests that the target website trusts without the user’s consent. In Cross-Site Scripting (XSS), the attacker exploits the trust a user has for a website, with CSRF on the other hand, the attacker exploits the trust a website has against a user’s browser.

Basically, an attacker will use CSRF to trick a victim into accessing a website or clicking a URL link that contains malicious or unauthorized requests. It is called ‘malicious’ since the CSRF attack will use the identity and privileges of the victim and impersonate them in order to perform any actions desired by the attacker, such as change form submission details, and launch purchases or payments for the attacker or a third-party account.

Read more »

Python Dict

Python dict的定义方法:

1
2
3
4
5
a = dict(one=1, two=2, three=3)
b = {'one': 1, 'two': 2, 'three': 3}
c = dict(zip(['one', 'two', 'three'], [1, 2, 3]))
d = dict([('two', 2), ('one', 1), ('three', 3)])
e = dict({'three': 3, 'one': 1, 'two': 2})