Monday, December 30, 2019

English sentences

I've worked hard to make this book as good as I can, but I have no illusions that it's perfect.

But what a man is looking for a woman can be very different from what a woman is looking for in a man.
The saying goes, a woman wants one man to satisfy her every need; a man wants every woman to satisfy his one need.

In American English, the title "Miss" used for single women has become a bit outdated, especially with professional women. "Ms." (pronounced miz) is a safe bet in any situation. It's neutral and doesn't indicate whether the woman is married or not. If the woman prefers "Miss" or "Mrs." (pronounced misiz), she'll probably tell you.
-from Global English
Don't overreact! It's not the end of the world.

Early to bed and early to rise makes a man healthy, wealthy and wise.
I accept all those flaws, why can't you accept me for this?
You ruffled his feathers when you asked him about his income.
She felt put off by his personal questions.
Did you catch the new engineer's name?
I think he needs to use more finesse in certain situations.
Every day I work,I bust my ass so my family can live well.
So I guess what I'm trying to say is that I'm very thankful that all of your Thanksgivings sucked.
You now have a good understanding of... But make sure you don't get complacent.

Have you both got over the jet-lag?
Obviously this is not my call any longer, but it's my 2 cents worth.
marinara


Be confident, be proud of what we’ve achieved together at XXX, but be prepared to change.
The journey is only beginning.

I'll let him know if anything comes up.

English Tips:
1. But the German chancellor Angela Merkel said Berlin needed to be certain that Greece was serious about spending cuts.
2. The precondition however is that Greece will accept an ambitious austerity program so that the trust of the financial  markets can be restored.
3. The British prime minister Golden Brown has said sorry to a woman he had been called on microphone describing as “bigoted” during Campaigning for General election.
4. They highlight a vast gulf between the Prime minister’s behavior and attitude in public and in private. Warm, attentive and concerned on camera, angry dismissive and disdainful when off it.
5. Coroner  concluded that Mrs. McQueen hanged himself after taking a mixture of cocaine tranquilizers and sleeping pills. 
6. The first offshore wind farm in the United States has won government approval after years of opposition from environmentalists and indigenous tribes.


the government ususally covers everyting up, including mental health problems within China.
Yes. You can blame in on corruption, the government or whatever else you would like to.
Most often than not, the widespread corruption goes unnoticed and unpunished.

Triggers for the attacks have included pent-up grivevances over lost jobs, business failures, broken relationships, and a new home that officals had ordered torn down.

China devotes hundred thousand officials to control internet's content. The real question behind this is: why China try to control the internet content so much? what do they want people 
not to know? Is it about China or the foreigner countries?

This was the sixth attack on schoolchildren in China since March -- a succession of attacks that had already prompted calls for more security at schools and worries about social malaise 
that some see underneath China's rapid economic growth.


My thoughts about the school attack
The succession of bloody assaults on schools shocks me heavily. It is belived that triggers for the attacks have included pent-up grivevances over lost jobs, business failures, broken relationships,
and a new home that officals had ordered torn down. The attacks prompted worries about social malaise that some see underneath China's rapid economic growth.



Thursday, December 19, 2019

MongoDB in Action Note 2

MongoDB in Action Note
1.
Indexes in MongoDB are implemented as a B-tree data structure.
With MongoDB, you can create up to 64 indexes per collection. The kinds of
indexes supported include all the ones you’d find in an RDMBS; ascending, descending,
unique, compound-key, hashed, text, and even geospatial indexes4 are supported.
2.
mongoexport and mongoimport—Export and import JSON, CSV, and TSV7 data;
3.
db.users.insert({username: "smith"})
db.users.find()
db.users.find({username: "jones"})
db.users.find().pretty()
db.users.count()
db.users.update({username: "smith"}, {$set: {country: "Canada"}})   --OPERATOR UPDATE
db.users.update({username: "smith"}, {country: "Canada"})           --REPLACEMENT UPDATE
db.foo.remove()
db.users.remove({"favorites.cities": "Cheyenne"})
db.users.drop()
4.
> help
> db.help()
$ mongo --help
5.
> for(i = 0; i < 20000; i++) {
db.numbers.save({num: i});
}
db.numbers.find( {num: {"$gt": 20, "$lt": 25 }} )
db.numbers.find({num: {"$gt": 19995}}).explain("executionStats")
db.numbers.createIndex({num: 1})
db.numbers.getIndexes()
db.numbers.find({num: {"$gt": 19995 }}).explain("executionStats")
> db.stats() (wraps db.runCommand( {dbstats: 1} ) )
you can execute the parentheses-less version and see the internals:
> db.runCommand
6.
In addition to the size limit, MongoDB allows you to specify a maximum number
of documents for a capped collection with the max parameter.
MongoDB also allows you to expire documents from a collection after a certain
amount of time has passed. These are sometimes called time-to-live (TTL) collections.
7.
BSON specifies three numeric types: double, int, and long.
The BSON datetime type is used to store temporal values. Time values are represented
using a signed 64-bit integer marking milliseconds since the Unix epoch.
if you’re creating dates in JavaScript, keep in mind that months in JavaScript dates are 0-based.
8.
db.stockdata.find({code: "SH600050"}).skip(3490).limit(3).sort({'date':1}).pretty()
MongoDB allows you to query using regular expressions
db.users.find({'last_name': /^Ba/})
db.users.find({'first_name': "Smith", birth_year: 1975})
db.reviews.find({
'user_id': ObjectId("4c4b1476238d3b4dd5000001"),
'$where': "(this.rating * .92) > 3"
})
9.
Projections:
db.users.find({}, {'username': 1}) --returns user documents excluding all but two fields: the username and the _id field
db.users.find({}, {'addresses': 0, 'payment_methods': 0})  --returns user documents including all exclude the two fields
To return the first 12 reviews,
or the last 5, you’d use $slice like this:
db.products.find({}, {'reviews': {$slice: 12}})
db.products.find({}, {'reviews': {$slice: -5}})
10.
Aggregation pipeline operations include the following:
$project—Specify fields to be placed in the output document (projected).
$match—Select documents to be processed, similar to find().
$limit—Limit the number of documents to be passed to the next step.
$skip—Skip a specified number of documents.
$unwind—Expand an array, generating one output document for each array entry.
$group—Group documents by a specified key.
$sort—Sort documents.
$out—Write the results of the pipeline to a collection
$redact—Control access to certain data
11.
db.stockdata.aggregate([{$group:{_id:'$code',count:{$sum:1}}}]);
db.stockdata.aggregate([
{$match:{'code':/^SH/}},
{$group:{_id:'$code',count:{$sum:1}}}
]);
db.stockdata.aggregate([
{$match:{'code':/^SH/}},
{$group:{
_id:'$code',
average:{$avg:'$close'},
count:{$sum:1}
}}
]);
db.stockdata.aggregate([
{$match:{'code':/^SH/}},
{$group:{
_id:'$code',
average:{$avg:'$close'},
count:{$sum:1}
}}
]).forEach(function(doc){
var category = db.stockdata.findOne({code:doc._id});
if(category!=null){
doc.code = category.code;
}
else{
doc.code = 'not found';
}
db.mainStockData.insert(doc);
});

Monday, November 25, 2019

From Spring 3.2, no need to include spring-asm

java.lang.IncompatibleClassChangeError:
class org.springframework.core.type.classreading.ClassMetadataReadingVisitor has interface org.springframework.asm.ClassVisitor as super class.

https://stackoverflow.com/questions/15758151/class-conflict-when-starting-up-java-project-classmetadatareadingvisitor-has-in

https://docs.spring.io/spring-framework/docs/3.2.16.RELEASE/spring-framework-reference/htmlsingle/#migration-3.2-inline-asm

D.3 Inlining of spring-asm jar

In versions 3.0 and 3.1, we published a discrete spring-asm containing repackaged org.objectweb.asm 3.x sources. As of Spring Framework 3.2, we have upgraded to org.objectweb.asm 4.0 and done away with the separate module jar, favoring inlining these classes directly within spring-core. This should cause no migration issue for most users; but on the off chance that you have spring-asm declared directly within your project's build script, you'll want to remove it when upgrading to Spring Framework 3.2.

Sunday, November 24, 2019

league of legends math and programming for kids


For Math:
1. The red buff health is 2100, Lee Sin's attack will deduce it by 124 or 125 every time, how many times at least are required to kill the red buff for Lee Sin ( do not unlock any ability, do not use Smite)?
2. Lee Sin's attack speed is 1.5 seconds, how fast a perfect Lee Sin player can kill a red buff ( do not unlock any ability, do not use Smite)?
3. Lee Sin's passive:
      After Lee Sin uses an ability, his next 2 basic attacks Attack Speed increases 40%.
If Lee Sin unlock W which cool down is 11.7 seconds. Below is the description about his W ability:

Safeguard: Lee Sin rushes to target ally, shielding himself from damage. If the ally is a champion, they are also shielded. After using Safeguard, Lee Sin can cast Iron Will for the next 3 seconds.
Iron Will: Lee Sin's intense training allows him to thrive in battle. For 4 seconds, Lee Sin gains Life Steal and Spell Vamp.

How fast a perfect Lee Sin player can kill a red buff (without using Smite)?
Below is the link Tarzan Lee Sin:
https://www.youtube.com/watch?v=UZ3S7RsGO24

For Python/Java:
1. Get all champion's skin from the official LOL website:
https://na.leagueoflegends.com/en/game-info/champions/

2. Sort them by skin numbers and champion name

Ezreal: 14
...


For Python

getAllLOLSkins.py

import os
import requests
import urllib.request
from bs4 import BeautifulSoup
with open('/Users/yanfeng/python/lol.html','r',encoding='utf-8') as myFile:
       soup = BeautifulSoup(myFile.read(),'html.parser');
       div=soup.find_all('ul','champion-grid grid-list gs-container gs-no-gutter default-7-col content-center');
       for ul in div:
              for li in ul.find_all('li'):
                     a = li.find('a');
                     champ = a['href'][:-1];
                     print(champ);
                     os.makedirs("/Users/yanfeng/python/lol/" + champ);
                     os.chdir("/Users/yanfeng/python/lol/" + champ);
                     for k in range(30):
                            onechamp_link = 'https://ddragon.leagueoflegends.com/cdn/img/champion/splash/' + champ + '_' + str(k) + '.jpg';
                            im = requests.get(onechamp_link);
                            if im.status_code == 200:

                                   open(champ + '_' + str(k) + '.jpg', 'wb').write(im.content);


count.py

import os

path='/Users/yanfeng/python/lol'
champ_dir = os.listdir(path);
picture=[];
test_keys=[];
test_values=[];
for champ in champ_dir:
champfiles = os.listdir(os.path.join(path,champ));
number_files = len(champfiles);
test_keys.append(champ);
test_values.append(number_files);
myDict=dict(zip(test_keys, test_values));
for key, value in sorted(myDict.items(), key=lambda item: item[1]):
    print("%s: %s" % (key, value));


Thursday, September 26, 2019

Spring boot documentation note

Spring boot documentation note
https://docs.spring.io/spring-boot/docs/current/reference/html
1.
We monitor stackoverflow.com for questions tagged with spring-boot
Absolutely no code generation and no requirement for XML configuration.
Spring Boot 2.1.3.RELEASE requires Java 8 and is compatible up to Java 11 (included). Spring Framework 5.1.5.RELEASE or above is also required. Maven 3.3+
2.
Maven users can inherit from the spring-boot-starter-parent project to obtain sensible defaults. The parent project provides the following features:
Java 1.8 as the default compiler level.
UTF-8 source encoding.
Sensible resource filtering for application.properties and application.yml including profile-specific files
(for example, application-dev.properties and application-dev.yml)
3. Externalized Configuration order
https://docs.spring.io/spring-boot/docs/current/reference/html/boot-features-external-config.html
SpringApplication loads properties from application.properties files in the following locations and adds them to the Spring Environment:
A /config subdirectory of the current directory
The current directory
A classpath /config package
The classpath root
4.
If you want to write log files in addition to the console output, you need to set a logging.file or logging.path property
(for example, in your application.properties).

Monday, August 19, 2019

the meaning of life

In the radio series (then novel) “The Hitchhikers Guide to the Galaxy”, the fictional super-computer Deep Thought was tasked with devising an answer to “the ultimate question of life, the universe, and everything”. This process took millions of years, but Deep Thought eventually arrived at the answer. According to Deep Thought, the answer to the “Ultimate Question” was, in fact, 42.
Dumbstruck, the successors to Deep Thought’s creators asked it why it gave that answer, and Deep Thought responded that it was just answering their very vague question as best it could. When asked how the vague question could be improved, Deep Thought said that even it wasn’t powerful enough to calculate “The Question to the Ultimate Answer”.
Deep Thought then designed a new super-computer, with bio-organic matrices and sub-processors, which would be capable of calculating the Ultimate Question. This new super-computer would be the size of a planet, and would be named “Earth” (which everyone agreed was a boring name).
Millions of years later, on the “planet” Earth, the calculation was about to be completed, and the Ultimate Question would finally be known. However, five minutes before this was due to happen, a Vogon Constructor Fleet - operating under the authority of the Galactic Hyperspace Planning Council - vaporised the Earth to make way for a new hyperspace bypass.
As such, the Ultimate Question was never calculated, and the reason why “42” is the Ultimate Answer remains unknown.

Outside the context of the books, however, Douglas Adams - the author - was a computing enthusiast. In the context of some early programming languages, “42” was the numeric representation of the asterisk (*) symbol. In programming, the asterisk was frequently used as a placeholder symbol, and so could mean anything depending on what the programmers choose to replace it with.
As such, it’s thought that Adams was secretly saying that the “Ultimate Answer” is whatever you want it to be, and that there is no set meaning to existence. You get to decide what the meaning of life is for yourself.

“The Ultimate Answer to Life, The Universe and Everything is...42!”


Alt 42->*

Thursday, August 15, 2019

MongoDB in action note

MongoDB in action
1.
The code examples are written in JavaScript, the language of the MongoDB shell,
and Ruby, a popular scripting language.
You can download the book’s source code, with some sample data, from the book’s
site at http://mongodb-book.com
2.
A JSON document needs double quotes everywhere except for numeric values.
The MongoDB shell uses JavaScript and gets documents in JSON.
3.
Indexes in MongoDB are implemented as a B-tree data structure. B-tree indexes,
also used in many relational databases, are optimized for a variety of queries, including
range scans and queries with sort clauses. But WiredTiger has support for logstructured
merge-trees (LSM) that’s expected to be available in the MongoDB 3.2 production
release.
Because MongoDB and most RDBMSs use the same data structure for their indexes,
advice for managing indexes in both of these systems is similar.
4.
MongoDB provides database replication via a topology known as a replica set. Replica
sets distribute data across two or more machines for redundancy and automate
failover in the event of server and network outages. Additionally, replication is used
to scale database reads.
5.
Journaling is enabled by default since MongoDB v2.0
With journaling, every write
is flushed to the journal file every 100 ms. If the server is ever shut down uncleanly
(say, in a power outage), the journal will be used to ensure that MongoDB’s data files
are restored to a consistent state when you restart the server. This is the safest way to
run MongoDB.
It’s possible to run the server without journaling as a way of increasing performance
for some write loads. The downside is that the data files may be corrupted after
an unclean shutdown. As a consequence, anyone planning to disable journaling should
run with replication, preferably to a second datacenter, to increase the likelihood that
a pristine copy of the data will still exist even if there’s a failure.
6.
MongoDB was designed to make horizontal scaling manageable. It does so via a
range-based partitioning mechanism, known as sharding, which automatically manages
the distribution of data across nodes. There’s also a hash- and tag-based sharding
mechanism, but it’s just another form of the range-based sharding mechanism.
MongoDB v1.0 was released in November 2009.
(shard is NA in TD right now)
7.
MongoDB is bundled with several command-line utilities:
mongodump and mongorestore—Standard utilities for backing up and restoring
a database. mongodump saves the database’s data in its native BSON format and
thus is best used for backups only.
mongoexport and mongoimport—Export and import JSON, CSV, and TSV7 data;
this is useful if you need your data in widely supported formats. mongoimport
can also be good for initial imports of large data sets.
mongotop—Similar to top, this utility polls MongoDB and shows the amount of
time it spends reading and writing data in each collection.

8.
All collections in a database are grouped in the
same files, so it makes sense, from a memory perspective, to keep related collections
in the same database.

9.
db.users.update({username:"smith"},{$set: {country:"Canada"}});//add or set fields
db.users.update({username: "smith"}, {country: "Canada"})//replace the entire document
db.users.update({username: "smith"}, {$unset: {country: 1}})
db.users.update( {username: "jones"},
... {
... $set: {
... favorites: {
... movies: ["Casablanca", "Rocky"]
... }
... }
... })
db.users.find({"favorites.movies": "Casablanca"})
db.numbers.find( {num: {"$gt": 19995 }} )
db.numbers.find( {num: {"$gt": 20, "$lt": 25 }} )
Others include $gte for greater than or equal to, $lte for less than or equal to, and $ne for not equal to.
To exclude them, add those fields to the projection with
a value of 0:
db.users.find({}, {'addresses': 0, 'payment_methods': 0})

10.
$push or $addToSet. Both operators add
an item to an array, but the second does so uniquely, preventing a duplicate addition.
db.users.update( {"favorites.movies": "Casablanca"},
... {$addToSet: {"favorites.movies": "The Maltese Falcon"} },
... false,
... true )
The third argument, false, controls whether an upsert is allowed.
The fourth argument, true, indicates that this is a multi-update.

11.
remove() operation doesn’t actually delete the collection; it merely
removes documents from a collection. You can think of it as being analogous to SQL’s
DELETE command.
db.foo.remove()
db.users.remove({"favorites.cities": "Cheyenne"})
If your intent is to delete the collection along with all of its indexes, use the drop()
method:
> db.users.drop()
> help
$ mongo --help

12.
db.numbers.find({num: {"$gt": 19995}}).explain("executionStats")
//docsExamined, nReturned, totalKeysExamined, db.numbers.getIndexes()
db.numbers.createIndex({num: 1})
db.numbers.getIndexes()
db.stats() //same with db.runCommand( {dbstats: 1} )
db.numbers.stats() //same with db.runCommand( {collstats: "numbers"} )
The getIndexes() Java-
Script method can be replaced by the db.runCommand( {"listIndexes": "numbers"} )
shell command.

13.
Run the below without parentheses to see the internal implementation
> db.runCommand
>db.users.find
>db.numbers.save

14.
press the Tab key twice to see a list of all matching methods
> db.numbers.get

15.
Ruby 20-minute tutorial at http://mng.bz/THR3

16.
MongoDB also allows you to expire documents from a collection after a certain
amount of time has passed. These are sometimes called time-to-live (TTL) collections,
though this functionality is actually implemented using a special kind of index. Here’s
how you would create such a TTL index:
> db.reviews.createIndex({time_field: 1}, {expireAfterSeconds: 3600})
->db.reviews.insert({time_field:new Date()});

17.
db.system.namespaces.find();
db.system.indexes.find();

18.
All string values must be encoded as UTF-8.
BSON specifies three numeric types: double, int, and long.
The BSON datetime type is used to store temporal values. Time values are represented
using a signed 64-bit integer marking milliseconds since the Unix epoch. A negative
value marks milliseconds prior to the epoch.
if you’re creating dates in JavaScript, keep in
mind that months in JavaScript dates are 0-based.

19.
BSON documents in MongoDB v2.0 and later are limited to 16 MB in size.
First, it’s there to prevent developers from creating ungainly data models.
The second reason for the 16 MB limit is performance-related.
MongoDB documents are also limited to a maximum nesting depth of 100.

20.
Users commonly ask what the ideal bulk insert size is, but the answer to this is
dependent on too many factors to respond concretely, and the ideal number can
range from 10 to 200. Benchmarking will be the best counsel in this case.

21.
The findOne method is similar to the following,
though a cursor is returned even when you apply a limit:
db.products.find({'slug': 'wheel-barrow-9092'}).limit(1)

22.
SET OPERATORS
Three query operators—$in, $all, and $nin—take a list of one or more values as
their predicate, so these are called set operators.
MongoDB’s Boolean operators include $ne, $not, $or, $and, $nor, and $exists.
db.users.find({'addresses': {$size: 3}})

23.
You can use the special $where operator to pass a JavaScript expression
to any query, as summarized here:
■ $where Execute some arbitrary JavaScript to select a document
db.reviews.find({
'$where': "function() { return this.helpful_votes > 3; }"
})
There’s also an abbreviated form for simple expressions like this one:
db.reviews.find({'$where': "this.helpful_votes > 3"})
This query works, but you’d never want to use it because you can easily express it using
other query operators. The problem is that JavaScript expressions can’t use an index,
and they incur substantial overhead because they must be evaluated within a Java-
Script interpreter context and are single-threaded. For these reasons, you should issue
JavaScript queries only when you can’t express your query using other query operators.
If you do need JavaScript, try to combine the JavaScript expression with at least
one other query operator.

24.
The aggregation framework is MongoDB’s
advanced query language, and it allows you to transform and combine data from
multiple documents to generate new information not available in any single document.
you can think of the aggregation framework as MongoDB’s equivalent to
the SQL GROUP BY clause.

25.
map-reduce was MongoDB’s first attempt at providing a flexible aggregation capability.
With map-reduce, you have the ability to use JavaScript in defining your entire
process. This provides a great deal of flexibility but generally performs much slower
than the aggregation framework.

26.
the use of targeted updates frequently means
less time spent serializing and transmitting data.

27.
The multi parameter {multi: true} is easy to
understand; it enables multi-updates causing the update to affect all documents matching
the selector—without {multi: true} an update will only affect the first matching
document.

28.
with compound
indexes, order matters.
Only one single-key index will be used to resolve a query.1 For queries containing
multiple keys (say, ingredient and recipe name), a compound index containing
those keys will best resolve the query.

29.
With sufficient RAM, all the data files in use will eventually be loaded into memory.
At a minimum, you need to make
sure that your indexes will fit in RAM. This is one reason why it’s important to avoid creating
any unneeded indexes.
A covering index is one where the entire query can be
satisfied from reading only the index, making queries very fast.

30.
To create a unique index, specify the unique option:
db.users.createIndex({username: 1}, {unique: true})
In a sparse index, only those documents having some value for the indexed key will
appear.
db.products.createIndex({sku: 1}, {unique: true, sparse: true})
use green
db.users.dropIndex("zip_1")
For large data sets, building an index can take hours, even days. But you can monitor
the progress of an index build from the MongoDB logs.
The index builds in two steps. In the first step, the values to be indexed are sorted.
For step two, the sorted values are inserted into the index.
In addition to examining the MongoDB log, you can check the index build progress
by running the shell’s currentOp() method.
->db.currentOp()

31.
If you’re running in production and can’t afford to halt access to the database, you
can specify that an index be built in the background. Although the index build will
still take a write lock, the job will yield to allow other readers and writers to access the
database.
db.values.createIndex({open: 1, close: 1}, {background: true})

32.
Building an index in the background may still put an unacceptable amount of load on
a production server. If this is the case, you may need to index the data offline.
when you run mongorestore, all the indexes declared
for any collections you’ve backed up will be re-created.

33.
Be careful about reindexing: the command will take out a write lock for the duration
of the rebuild, temporarily rendering your MongoDB instance unusable.
Though the requirements vary per application, it’s safe to
assume that for most apps, queries shouldn’t take much longer than 100 ms.
The
MongoDB logger has this assumption ingrained because it prints a warning whenever
any operation, including a query, takes longer than 100 ms.

34.
download http://mng.bz/ii49
unzip stocks.zip
mongorestore -d stocks dump/stocks
->
use stocks
db.values.find({"stock_symbol": "GOOG"}).sort({date: -1}).limit(1)
grep -E '[0-9]+ms' mongod.log

If 100 ms is too high a threshold, you can lower it with the --slowms server option
when you start MongoDB. If you define slow as taking longer than 50 ms, then start
mongod with --slowms 50.

For identifying slow queries, you can’t beat the built-in profiler. Profiling is disabled
by default, so let’s get started by enabling it. From the MongoDB shell, enter
the following:
use stocks
db.setProfilingLevel(2)
db.system.profile.find({millis: {$gt: 150}}).pretty();
The explain() command displays more information when used with the execution-
Stats option.
pass true to the explain() method, which will include the list of plans the
query optimizer attempts.

35.
It provides functions that MongoDB needs to use to store data.
MongoDB 3.0 comes bundled with an alternative to MMAPv1, which is WiredTiger.

36.
We highly recommend running a production MongoDB instance with both replication
and journaling, unless you’re prepared to lose data;
As another form of redundancy,
replicated nodes can also be delayed by a constant number of seconds, minutes,
or even hours behind the primary.
Because index builds are expensive, you may opt to build on a
secondary node first, swap the secondary with the existing primary, and then build
again on the new secondary.
The minimum recommended replica set configuration consists of three nodes,
because in a replica set with only two nodes you can’t have a majority in case the primary
server goes down.
In the minimal configuration, two of these three nodes serve as first-class, persistent
mongod instances. Either can act as the replica set primary, and both have a full
copy of the data. The third node in the set is an arbiter, which doesn’t replicate data
but merely acts as a kind of observer. Arbiters are lightweight mongod servers that participate
in the election of a primary but don’t replicate any of the data.

37.
db.isMaster()
rs.status()
db.getReplicationInfo()
db.oplog.rs.findOne({op: "i"})            ?

38.
The default oplog sizes on 64-bit systems, the oplog will be the larger of 1 GB or 5% of free
disk space
the default size won’t be ideal for all applications.
mongod --replSet myapp --oplogSize 1024

39.
operations on a single document are always atomic with MongoDB
databases, but operations that involve multiple documents aren’t atomic as a whole.
You now know that a replica set can consist of up to 50 nodes in MongoDB v3.0

40.
Sharding is the process of partitioning a large dataset into smaller, more manageable
pieces.
It’s a complex system that adds administrative and performance
overhead, so make absolutely sure it’s what your application needs.

41.
Once you mount your fast filesystem, you can achieve another performance gain by
disabling updates to files’ last access time: atime. Normally, the operating system will
update a file’s atime every time the file is read or written. In a database environment,
this amounts to a lot of unnecessary work.

42.
You can check the current limit temporarily with the
ulimit command:
ulimit -Hn

43.
When journaling is enabled, MongoDB will commit all writes to a journal
before writing to the core data files. This allows the MongoDB server to come back
online quickly and cleanly in the event of an unclean shutdown.

44.
Global server statistics: db.serverStatus()
Stats for currently running operation: db.currentOp()
Include stats for idle system operations: db.currentOp(true)
Per database counters and activity stats: db.runCommand({top:1})
Memory and disk usage statistics: db.stats()

45.
mongostat—Global system statistics
■ mongotop—Global operation statistics
■ mongosniff (advanced)—Dump MongoDB network traffic
■ bsondump—Display BSON files as JSON

46.
Three general strategies for backing up a MongoDB database are as follows:
■ Using mongodump and mongorestore
■ Copying the raw data files
■ Using MMS Backups

47.
There are two ways to import and export data with MongoDB:
■ Use the included tools, mongoimport and mongoexport.
■ Write a simple program using one of the drivers.

48.
You can use mongoimport to import JSON, CSV, and TSV files. This is
frequently useful for loading data from relational databases into MongoDB:
$ mongoimport -d stocks -c values --type csv --headerline stocks.csv
The --headerline flag indicates that the first line of the CSV
contains the field names. You can see all the import options by running mongoimport
--help.

49.
Use mongoexport to export all of a collection’s data to a JSON or CSV file:
$ mongoexport -d stocks -c values -o stocks.csv

50.
--rest—This flag enables a simple REST interface that enhances the server’s
default web console. The web console is always available 1000 port numbers
above the port the server listens on. Thus if the server is listening at localhost
on port 27017, then the web console will be available at http://localhost:28017.
Spend some time exploring the web console and the commands

Sunday, August 11, 2019

LOL Lee Sin

https://www.skill-capped.com/lol/courses
Practice the below:
1. Ward hopping
2. ORB walking
3. Kick flash
4. RQQ and QRQ

Thursday, August 8, 2019

Note for Udemy The Complete Developers Guide to MongoDB


https://github.com/StephenGrider/MongoCasts
1. Promise
2.
node
npm init
npm install --save mocha nodemon mongoose

Complete 7/14 sections. it focuses on Mongoose design and the test-driven approach, not the MongoDB server itself.

Tuesday, August 6, 2019

Tuesday, July 30, 2019

国内外相册和网盘服务

国内的服务真不靠谱,以前把相片等重要资料存放在号称永不收费的金山网盘上,金山网盘突然就被清理关闭了。又拍网,所有相片都没有了。导致泰山相片丢失,2012年回老家的相片丢失。360网盘,一段时间不进去,再进去的时候,所有资料都被清理的干干净净。百度网盘都算好的了,毕竟东西都还在。虽然有些东西允许上传,不允许下载。

相比而言,国外服务商更靠谱更有信誉。以前存在google picasa的相片,哪怕picasa关闭,google也自动把相片转到了google相册里。flick虽然改为收费,至少续费/缴费后登录仍然可以看到以前上传的相片。虽然不续费不让预览相片,续费之后下载相片也很不方便。

苹果的相册目前感觉最满意,但它不支持语音备忘录,语音备忘录可以导入但无法播放,还是把语音备忘录放到icloud files合适。

Sunday, July 21, 2019

IPTV for apple TV (and others)

apple TV has an app iPlayTV which costs C$3.99, it's worth to buy but you have to find your own high quality IPTV sources.

Github has an open source project https://github.com/freearhey/iptv , also there's a nice Fluxus.tv (https://fluxustv.blogspot.com/p/iptv.html)

After I clone Github and run "npm run test --country=uk " I got an error complaining module "playlist-parser" missed and the error log is:
11 silly lifecycle iptv@~test: Returned: code: 1  signal: null
12 info lifecycle iptv@~test: Failed to exec test script
13 verbose stack Error: iptv@ test: `node test/index.js`
13 verbose stack Exit status 1
13 verbose stack     at EventEmitter.<anonymous> (C:\Program Files\nodejs\node_modules\npm\node_modules\npm-lifecycle\index.js:301:16)
13 verbose stack     at EventEmitter.emit (events.js:189:13)
13 verbose stack     at ChildProcess.<anonymous> (C:\Program Files\nodejs\node_modules\npm\node_modules\npm-lifecycle\lib\spawn.js:55:14)
13 verbose stack     at ChildProcess.emit (events.js:189:13)
13 verbose stack     at maybeClose (internal/child_process.js:970:16)
13 verbose stack     at Process.ChildProcess._handle.onexit (internal/child_process.js:259:5)
14 verbose pkgid iptv@

After checking package.json, and issue the below:
        npm install playlist-parser --save-dev

I'm able to run "npm run test --country=uk" successfully.


Friday, June 14, 2019

What did Kawhi Leonard say after Raptors victory?

“Just last year, a lot of people were doubting me, thought that I was either faking an injury or didn’t wanna play for a team,” he said. “That was disappointing to me.”
Leonard added: “I just knew that I had to make myself happy and no one else. I have to trust myself... I know who I am as a person.”
“上赛季,很多人质疑我,认为我是诈伤,不想(为马刺队)出场比赛,”卡哇伊表示,“老实说,那些话令人失望,因为我如此热爱篮球。”
“正如我一直所说,如果我不打比赛,那说明我受伤了,打不了,”卡哇伊继续说道,“我经历了那些事情,我知道,我只需要让自己开心,而不是让其他人开心。我必须要信任自己,别人说什么都无关紧要。我知道自己是怎样的人,我清楚自己的感受,我总是会信任自己。”

Wednesday, May 1, 2019

Angular notes

1. Install Node.js
node -v
npm -v
2. Install Angular
npm install -g @angular/cli
ng --version
ng new hello-world

Monday, April 29, 2019

好的句子

1.
我生命里最大的突破之一,就是我不再为别人对我的看法而担忧。此后,我真的能自由地去做我认为对自己最好的事。只有在我们不需要外来的赞许时,才会变得自由。—— 罗伊·马丁纳
2.
“今天不想跑,所以才去跑,这才是长距离跑者的思维方式。”——村上春树
3.
我们的眼睛就是我们的监狱,我们的眼光所到之处就是我们监狱的围墙。——尼采
Our eyes are our prisons, and the sight of our eyes is the wall of the prison.
4.
“我所有的自负都来自我的自卑,所有的英雄气概都来自于我内心的软弱,所有的振振有词都因为心中满是怀疑。我假装无情,其实是痛恨自己的深情。我以为人生的意义在于四处游荡流亡,其实只是掩饰至今没有找到愿意驻足的地方。”----卡尔维诺《看不见的城市》
5.
我慢慢明白了我为什么不快乐,因为我总是期待一个结果。看一本书期待它让我变深刻,吃饭游泳期待它让我一斤斤瘦下来,发一条短信期待它被回复,对人好期待它回应也好,写一个故事说一个心情期待它被关注被安慰,参加一个活动期待换来充实丰富的经历。这些预设的期待如果实现了,长舒一口气。如果没实现呢?自怨自艾。可是小时候也是同一个我,用一个下午的时间看蚂蚁搬家,等石头开花,小时候不期待结果,小时候哭笑都不打折。
———马德《允许自己虚度时光》
6.
之前看《挪威的森林》,里面绿子对男主说的一句话至今令我印象深刻。她说:有钱最大好处就是可以说自己没钱
7.
我渴望能见你一面,但请你记得,我不会开口要求见你。这不是因为骄傲,你知道我在你面前毫无骄傲可言,而是因为,唯有你也想见我的时候,我们见面才有意义。——西蒙娜·德·波伏娃《越洋情书》
8.
服饰对许多女人之所以如此重要,是因为它们可以使女人凭借幻觉,同时重塑外部世界和她们的内在自我。——西蒙娜·德·波伏娃《第二性》
9.
真正的男子渴求着不同的两件事:危险和游戏。
The real man craving for two different things: danger and game.
test

Friday, April 12, 2019

angularjs note

angularjs note
1. Install git
2. git clone --depth=16 https://github.com/angular/angular-phonecat.git
Cloning into 'angular-phonecat'...
fatal: unable to access 'https://github.com/angular/angular-phonecat.git/': SSL
certificate problem: self signed certificate in certificate chain
Need run "git config --global http.sslVerify false" to fix and then run git clone
3. cd angular-phonecat


1. Install Git and register on bitbucket
https://bitbucket.org
2.
It's important to understand that branches are just pointers to commits. When you create a branch, all Git needs to do is create a
new pointer—it doesn’t create a whole new set of files or folders.

Friday, March 15, 2019

An interesting issue about "SQLRecoverableException: I/O Exception: Connection reset"

I developed a Java application (Spring boot) to pump the data from Oracle database to Mongo DB, to improve the performance, I use 8 processes to pump at the same time.
It works perfect on my local (Windows 10), it only takes 2.5 mins to pump 1 million records from remote Oracle to my local mongo. However, when I tried to run the application from the Linux box, it becomes very slow and after several minutes, I can see the exception "SQLRecoverableException: I/O Exception: Connection reset".

Oracle JDBC driver/JDK1.8 has a bug to generate the random number on some Linux (say Redhat), if the below command cannot return immediately then the issue will happen:
                 head -n 1 /dev/random
The fix is to set the property or
  1. Open the $JAVA_HOME/jre/lib/security/java.security file in a text editor.
  2. Change the line:
  3. securerandom.source=file:/dev/random
    to read:
    securerandom.source=file:/dev/urandom


http://www.usn-it.de/index.php/2009/02/20/oracle-11g-jdbc-driver-hangs-blocked-by-devrandom-entropy-pool-empty/
https://docs.oracle.com/cd/E13209_01/wlcp/wlss30/configwlss/jvmrand.html
https://stackoverflow.com/questions/6110395/sqlrecoverableexception-i-o-exception-connection-reset
https://community.oracle.com/thread/943911


Thursday, March 7, 2019

Spring boot note

1. Log
The default log messages will print to the console window. By default, “INFO”, “ERROR” and “WARN” log messages will print in the log file.
If you have to enable the debug level log, add the debug flag on starting your application using the command shown below −
java –jar demo.jar --debug
You can also add the debug mode to your application.properties file as shown here −
debug = true

By default, all logs will print on the console window and not in the files. 
You can specify the own log file name using the property shown below −
logging.file = /var/tmp/mylog.log

The code given below shows how to add the slf4j logger in Spring Boot main class file.
private static final Logger logger = LoggerFactory.getLogger(DemoApplication.class);
logger.info("this is a info message");
2. Exceptions
he @ControllerAdvice is an annotation, to handle the exceptions globally.
@ControllerAdvice
public class ProductExceptionController {
   @ExceptionHandler(value = ProductNotfoundException.class)
   public ResponseEntity<Object> exception(ProductNotfoundException exception) {
      return new ResponseEntity<>("Product not found", HttpStatus.NOT_FOUND);
   }
}
3. Rest Template
Rest Template is used to create applications that consume RESTful Web Services. You can use the exchange() method to consume the web services for all HTTP methods.

4. Scheduling
The @EnableScheduling annotation is used to enable the scheduler for your application. 
The @Scheduled annotation is used to trigger the scheduler for a specific time period.
@Scheduled(cron = "0 * 9 * * ?")
The following is a sample code that shows how to execute the task every minute starting at 9:00 AM and ending at 9:59 AM, every day
package com.tutorialspoint.demo.scheduler;

import java.text.SimpleDateFormat;
import java.util.Date;
import org.springframework.scheduling.annotation.Scheduled;
import org.springframework.stereotype.Component;

@Component
public class Scheduler {
   @Scheduled(cron = "0 * 9 * * ?")
   public void cronJobSch() {
      SimpleDateFormat sdf = new SimpleDateFormat("yyyy-MM-dd HH:mm:ss.SSS");
      Date now = new Date();
      String strDate = sdf.format(now);
      System.out.println("Java cron job expression:: " + strDate);
   }
}
5. Actuator
Spring Boot Actuator provides secured endpoints for monitoring and managing your Spring Boot application. 
In the application.properties file, we need to disable the security for actuator endpoints.
management.security.enabled = false

/metricsTo view the application metrics such as memory used, memory free, threads, classes, system uptime etc.
6. Oauth2 with JWT

Tuesday, February 26, 2019

ORA-01031: insufficient privileges

Got the error "ORA-01031: insufficient privileges" when running "sqlplus / as sysdba" from Windows.
Run "sqlplus sys/password as sysdba" instead