Programs & Examples On #Nmock2

How to parse a String containing XML in Java and retrieve the value of the root node?

There is doing XML reading right, or doing the dodgy just to get by. Doing it right would be using proper document parsing.

Or... dodgy would be using custom text parsing with either wisuzu's response or using regular expressions with matchers.

How can I include css files using node, express, and ejs?

Its simple if you are using express.static(__dirname + 'public') then don't forget to put a forward slash before public that is express.static(__dirname + '/public') or use express.static('public') its also going to work; and don't change anything in CSS linking.

How to call stopservice() method of Service class from the calling activity class

In Kotlin you can do this...

Service:

class MyService : Service() {
    init {
        instance = this
    }

    companion object {
        lateinit var instance: MyService

        fun terminateService() {
            instance.stopSelf()
        }
    }
}

In your activity (or anywhere in your app for that matter):

btn_terminate_service.setOnClickListener {
    MyService.terminateService()
}

Note: If you have any pending intents showing a notification in Android's status bar, you may want to terminate that as well.

equivalent of vbCrLf in c#

I think that "\r\n" should work fine

clearInterval() not working

There are errors in your functions, but the first thing you should do, is to set the body tag correctly:

<body>
<p><span id="go" class="georgia">go</span> Italian</p>
<p>
    <button id="on" type="button" value="turn on">turn on</button>
    <button id="off" type="button" value="turn off">turn off</button>
</p>
</body>

<script>....</script>

The problem sometimes may be, that you call 'var text' and the other vars only once, when the script starts. If you make changements to the DOM, this static solution may be harmful.

So you could try this (this is more flexible approach and using function parameters, so you can call the functions on any element):

<body>
<p><span id="go" class="georgia">go</span> Italian</p>
<p>
    <button type="button" value="turn on"
         onclick=turnOn("go")>turn on</button>
    <button type="button" value="turn off"
         onclick=turnOff()>turn off</button>
</p>
</body>

<script type="text/JavaScript">
var interval;

var turnOn = function(elementId){
    interval = setInterval(function(){fontChange(elementId);}, 500);
};

var turnOff = function(){
    clearInterval(interval);
};

var fontChange = function(elementId) {
    var text = document.getElementById(elementId);
    switch(text.className) {
        case "georgia":
            text.className = "arial";
            break;
        case "arial":
            text.className = "courierNew";
            break;
        case "courierNew":
            text.className = "georgia";
            break;      
    }
};
</script>

You don't need this anymore, so delete it:

var text = document.getElementById("go");
var on = document.getElementById("on");
var off = document.getElementById("off");

This is dynamic code, meaning JS code which runs generic and doesn't adress elements directly. I like this approach more than defining an own function for every div element. ;)

Get a json via Http Request in NodeJS

http sends/receives data as strings... this is just the way things are. You are looking to parse the string as json.

var jsonObject = JSON.parse(data);

How to parse JSON using Node.js?

Android - Dynamically Add Views into View

See the LayoutInflater class.

LayoutInflater inflater = (LayoutInflater) context.getSystemService(Context.LAYOUT_INFLATER_SERVICE);
ViewGroup parent = (ViewGroup)findViewById(R.id.where_you_want_to_insert);
inflater.inflate(R.layout.the_child_view, parent);

How do you set the width of an HTML Helper TextBox in ASP.NET MVC?

Something like this should work:

<%=Html.TextBox("test", new { style="width:50px" })%>

Or better:

<%=Html.TextBox("test")%>

<style type="text/css">
    input[type="text"] { width:50px; }     
</style>

Update multiple tables in SQL Server using INNER JOIN

You can't update more that one table in a single statement, however the error message you get is because of the aliases, you could try this :

BEGIN TRANSACTION

update A
set A.ORG_NAME =  @ORG_NAME
from table1 A inner join table2 B
on B.ORG_ID = A.ORG_ID
and A.ORG_ID = @ORG_ID

update B
set B.REF_NAME = @REF_NAME
from table2 B inner join table1 A
    on B.ORG_ID = A.ORG_ID
    and A.ORG_ID = @ORG_ID

COMMIT

Get CPU Usage from Windows Command Prompt

C:\> wmic cpu get loadpercentage
LoadPercentage
0

Or

C:\> @for /f "skip=1" %p in ('wmic cpu get loadpercentage') do @echo %p%
4%

How to strip all whitespace from string

For Python 3:

>>> import re
>>> re.sub(r'\s+', '', 'strip my \n\t\r ASCII and \u00A0 \u2003 Unicode spaces')
'stripmyASCIIandUnicodespaces'
>>> # Or, depending on the situation:
>>> re.sub(r'(\s|\u180B|\u200B|\u200C|\u200D|\u2060|\uFEFF)+', '', \
... '\uFEFF\t\t\t strip all \u000A kinds of \u200B whitespace \n')
'stripallkindsofwhitespace'

...handles any whitespace characters that you're not thinking of - and believe us, there are plenty.

\s on its own always covers the ASCII whitespace:

  • (regular) space
  • tab
  • new line (\n)
  • carriage return (\r)
  • form feed
  • vertical tab

Additionally:

  • for Python 2 with re.UNICODE enabled,
  • for Python 3 without any extra actions,

...\s also covers the Unicode whitespace characters, for example:

  • non-breaking space,
  • em space,
  • ideographic space,

...etc. See the full list here, under "Unicode characters with White_Space property".

However \s DOES NOT cover characters not classified as whitespace, which are de facto whitespace, such as among others:

  • zero-width joiner,
  • Mongolian vowel separator,
  • zero-width non-breaking space (a.k.a. byte order mark),

...etc. See the full list here, under "Related Unicode characters without White_Space property".

So these 6 characters are covered by the list in the second regex, \u180B|\u200B|\u200C|\u200D|\u2060|\uFEFF.

Sources:

How to delete a selected DataGridViewRow and update a connected database table?

maybe you can use temp list for delete. for ignore row index change

_x000D_
_x000D_
<pre>_x000D_
private void btnDelete_Click(object sender, EventArgs e)_x000D_
{_x000D_
    List<int> wantdel = new List<int>();_x000D_
    foreach (DataGridViewRow row in dataGridView1.Rows)_x000D_
    {_x000D_
        if ((bool)row.Cells["Select"].Value == true)_x000D_
        wantdel.Add(row.Index);_x000D_
    }_x000D_
_x000D_
    wantdel.OrderByDescending(y => y).ToList().ForEach(x =>_x000D_
    {_x000D_
        dataGridView1.Rows.RemoveAt(x);_x000D_
    });           _x000D_
}_x000D_
</pre>
_x000D_
_x000D_
_x000D_

Is it possible to decrypt MD5 hashes?

MD5 is considered broken, not because you can get back the original content from the hash, but because with work, you can craft two messages that hash to the same hash.

You cannot un-hash an MD5 hash.

Git is not working after macOS Update (xcrun: error: invalid active developer path (/Library/Developer/CommandLineTools)

I figured out the Xcode Command Line Tools part from the error message, but after running Xcode and getting the prompt to install the additional tools it did claim to install them, but still I got the same error after opening a new terminal.

So I did the xcode-select --install manually and after that it worked for me.

Locate current file in IntelliJ

You can also click the little cross hairs button in the projects pane:

enter image description here

Note that the symbol won't be shown if Always Select Opened File (previously Autoscroll from Source) option is enabled.

Angular2 material dialog has issues - Did you add it to @NgModule.entryComponents?

This is happening because this is a dynamic component and you didn't add it to entryComponents under @NgModule.

Simply add it there:

@NgModule({
  /* ----------------- */
  entryComponents: [ DialogResultExampleDialog ] // <---- Add it here

Look at how the Angular team talks about entryComponents:

entryComponents?: Array<Type<any>|any[]>

Specifies a list of components that should be compiled when this module is defined. For each component listed here, Angular will create a ComponentFactory and store it in the ComponentFactoryResolver.

Also, this is the list of the methods on @NgModule including entryComponents...

As you can see, all of them are optional (look at the question marks), including entryComponents which accept an array of components:

@NgModule({ 
  providers?: Provider[]
  declarations?: Array<Type<any>|any[]>
  imports?: Array<Type<any>|ModuleWithProviders|any[]>
  exports?: Array<Type<any>|any[]>
  entryComponents?: Array<Type<any>|any[]>
  bootstrap?: Array<Type<any>|any[]>
  schemas?: Array<SchemaMetadata|any[]>
  id?: string
})

Simulating Slow Internet Connection

On Linux machines u can use wondershaper

apt-get install wondershaper

$ sudo wondershaper {interface} {down} {up}

the {down} and {up} are bandwidth in kpbs

So for example if you want to limit the bandwidth of interface eth1 to 256kbps uplink and 128kbps downlink,

$ sudo wondershaper eth1 256 128

To clear the limit,

$ sudo wondershaper clear eth1 

Get first and last day of month using threeten, LocalDate

YearMonth

For completeness, and more elegant in my opinion, see this use of YearMonth class.

YearMonth month = YearMonth.from(date);
LocalDate start = month.atDay(1);
LocalDate end   = month.atEndOfMonth();

For the first & last day of the current month, this becomes:

LocalDate start = YearMonth.now().atDay(1);
LocalDate end   = YearMonth.now().atEndOfMonth();

MSIE and addEventListener Problem in Javascript?

As of IE11, you need to use addEventListener. attachEvent is deprecated and throws an error.

How to get a subset of a javascript object's properties

I suggest taking a look at Lodash; it has a lot of great utility functions.

For example pick() would be exactly what you seek:

var subset = _.pick(elmo, ['color', 'height']);

fiddle

Generate Java classes from .XSD files...?

XMLBeans will do it. Specifically the "scomp" command.

EDIT: XMLBeans has been retired, check this stackoverflow post for more info.

Regex to validate password strength

For PHP, this works fine!

 if(preg_match("/^(?=(?:[^A-Z]*[A-Z]){2})(?=(?:[^0-9]*[0-9]){2}).{8,}$/", 
 'CaSu4Li8')){
    return true;
 }else{
    return fasle;
 }

in this case the result is true

Thsks for @ridgerunner

Saving and Reading Bitmaps/Images from Internal memory in Android

if you want to follow Android 10 practices to write in storage, check here and if you only want the images to be app specific, here for example if you want to store an image just to be used by your app:

viewModelScope.launch(Dispatchers.IO) {
            getApplication<Application>().openFileOutput(filename, Context.MODE_PRIVATE).use {
                bitmap.compress(Bitmap.CompressFormat.PNG, 50, it)
            }
        }

getApplication is a method to give you context for ViewModel and it's part of AndroidViewModel later if you want to read it:

viewModelScope.launch(Dispatchers.IO) {
            val savedBitmap = BitmapFactory.decodeStream(
                getApplication<App>().openFileInput(filename).readBytes().inputStream()
            )
        }

Rails filtering array of objects by attribute value

have you tried eager loading?

@attachments = Job.includes(:attachments).find(1).attachments

NumPy array is not JSON serializable

This is a different answer, but this might help to help people who are trying to save data and then read it again.
There is hickle which is faster than pickle and easier.
I tried to save and read it in pickle dump but while reading there were lot of problems and wasted an hour and still didn't find solution though I was working on my own data to create a chat bot.

vec_x and vec_y are numpy arrays:

data=[vec_x,vec_y]
hkl.dump( data, 'new_data_file.hkl' )

Then you just read it and perform the operations:

data2 = hkl.load( 'new_data_file.hkl' )

In Tkinter is there any way to make a widget not visible?

You may be interested by the pack_forget and grid_forget methods of a widget. In the following example, the button disappear when clicked

from Tkinter import *

def hide_me(event):
    event.widget.pack_forget()

root = Tk()
btn=Button(root, text="Click")
btn.bind('<Button-1>', hide_me)
btn.pack()
btn2=Button(root, text="Click too")
btn2.bind('<Button-1>', hide_me)
btn2.pack()
root.mainloop()

How can I get the DateTime for the start of the week?

Following on from Compile This' Answer, use the following method to obtain the date for any day of the week:

public static DateTime GetDayOfWeek(DateTime dateTime, DayOfWeek dayOfWeek)
{
   var monday = dateTime.Date.AddDays((7 + (dateTime.DayOfWeek - DayOfWeek.Monday) % 7) * -1);

   var diff = dayOfWeek - DayOfWeek.Monday;

   if (diff == -1)
   {
      diff = 6;
   }

   return monday.AddDays(diff);
} 

Selecting multiple columns in a Pandas dataframe

You can also use df.pop():

>>> df = pd.DataFrame([('falcon', 'bird',    389.0),
...                    ('parrot', 'bird',     24.0),
...                    ('lion',   'mammal',   80.5),
...                    ('monkey', 'mammal', np.nan)],
...                   columns=('name', 'class', 'max_speed'))
>>> df
     name   class  max_speed
0  falcon    bird      389.0
1  parrot    bird       24.0
2    lion  mammal       80.5
3  monkey  mammal

>>> df.pop('class')
0      bird
1      bird
2    mammal
3    mammal
Name: class, dtype: object

>>> df
     name  max_speed
0  falcon      389.0
1  parrot       24.0
2    lion       80.5
3  monkey        NaN

Please use df.pop(c).

Show history of a file?

git log -p will generate the a patch (the diff) for every commit selected. For a single file, use git log --follow -p $file.

If you're looking for a particular change, use git bisect to find the change in log(n) views by splitting the number of commits in half until you find where what you're looking for changed.

Also consider looking back in history using git blame to follow changes to the line in question if you know what that is. This command shows the most recent revision to affect a certain line. You may have to go back a few versions to find the first change where something was introduced if somebody has tweaked it over time, but that could give you a good start.

Finally, gitk as a GUI does show me the patch immediately for any commit I click on.

Example enter image description here:

How to add local jar files to a Maven project?

Perhaps someone will be interested in: https://github.com/Limraj/maven-artifact-generator

Console program to generate maven artifacts in the local repository, and configure dependencies for pom.xml, based on the path to the jars. You can do this for one file, but it's most useful if you have multiple jar files.

path jars: java -jar maven-artifact-generator-X.X.X.jar -p path_to_jars -g com.test -V 1.2.3 -P jar

jar: java -jar maven-artifact-generator-X.X.X.jar -f file_jar -g com.test -V 1.2.3 -P jar

This will generate an artifact in the local maven repository, and generate dependecies for pom.xml in gen.log. ArtifactId is the name of the jar file.

Requires an installed maven. Testing on widnows 7 and macOS X (unix/linux).

Determine if char is a num or letter

You can normally check for ASCII letters or numbers using simple conditions

if ((ch >= 'a' && ch <= 'z') || (ch >= 'A' && ch <= 'Z'))
{
    /*This is an alphabet*/
}

For digits you can use

if (ch >= '0' && ch <= '9')
{
    /*It is a digit*/
}

But since characters in C are internally treated as ASCII values you can also use ASCII values to check the same.

How to check if a character is number or letter

How to move Jenkins from one PC to another

In case your JENKINS_HOME directory is too large to copy, and all you need is to set up same jobs, Jenkins Plugins and Jenkins configurations (and don't need old Job artifacts and reports), then you can use the ThinBackup Plugin:

  1. Install ThinBackup on both the source and the target Jenkins servers

  2. Configure the backup directory on both (in Manage Jenkins ? ThinBackup ? Settings)

  3. On the source Jenkins, go to ThinBackup ? Backup Now

  4. Copy from Jenkins source backup directory to the Jenkins target backup directory

  5. On the target Jenkins, go to ThinBackup ? Restore, and then restart the Jenkins service.

  6. If some plugins or jobs are missing, copy the backup content directly to the target JENKINS_HOME.

  7. If you had user authentication on the source Jenkins, and now locked out on the target Jenkins, then edit Jenkins config.xml, set <useSecurity> to false, and restart Jenkins.

Where does MAMP keep its php.ini?

The file you have to edit is in MAMP Pro and uses the php.ini file everytime it starts up.

  • Start MAMP PRO
  • Edit File > Edit Templates > PHP 5.3.2 php.ini
  • Restart MAMP Pro

Your changes should stick.

How can I sanitize user input with PHP?

Never trust user data.

function clean_input($data) {
  $data = trim($data);
  $data = stripslashes($data);
  $data = htmlspecialchars($data);
  return $data;
}

The trim() function removes whitespace and other predefined characters from both sides of a string.

The stripslashes() function removes backslashes

The htmlspecialchars() function converts some predefined characters to HTML entities.

The predefined characters are:

& (ampersand) becomes &amp;
" (double quote) becomes &quot;
' (single quote) becomes &#039;
< (less than) becomes &lt;
> (greater than) becomes &gt;

CronJob not running

Sometimes the command that cron needs to run is in a directory where cron has no access, typically on systems where users' home directories' permissions are 700 and the command is in that directory.

How to go back (ctrl+z) in vi/vim

The answer, u, (and many others) is in $ vimtutor.

What does "where T : class, new()" mean?

That means that type T must be a class and have a constructor that does not take any arguments.

For example, you must be able to do this:

T t = new T();

How to do a recursive find/replace of a string with awk or sed?

find /home/www \( -type d -name .git -prune \) -o -type f -print0 | xargs -0 sed -i 's/subdomainA\.example\.com/subdomainB.example.com/g'

-print0 tells find to print each of the results separated by a null character, rather than a new line. In the unlikely event that your directory has files with newlines in the names, this still lets xargs work on the correct filenames.

\( -type d -name .git -prune \) is an expression which completely skips over all directories named .git. You could easily expand it, if you use SVN or have other folders you want to preserve -- just match against more names. It's roughly equivalent to -not -path .git, but more efficient, because rather than checking every file in the directory, it skips it entirely. The -o after it is required because of how -prune actually works.

For more information, see man find.

What evaluates to True/False in R?

T and TRUE are True, F and FALSE are False. T and F can be redefined, however, so you should only rely upon TRUE and FALSE. If you compare 0 to FALSE and 1 to TRUE, you will find that they are equal as well, so you might consider them to be True and False as well.

Delete all rows in an HTML table

This works in IE without even having to declare a var for the table and will delete all rows:

for(var i = 0; i < resultsTable.rows.length;)
{   
   resultsTable.deleteRow(i);
}

What is the most efficient string concatenation method in python?

For python 3.8.6/3.9, I had to do some dirty hacks, because perfplot was giving out some errors. Here assume that x[0] is a a and x[1] is b: Performance

The plot is nearly same for large data. For small data, Performance 2

Taken by perfplot and this is the code, large data == range(8), small data == range(4).

import perfplot

from random import choice
from string import ascii_lowercase as letters

def generate_random(x):
    data = ''.join(choice(letters) for i in range(x))
    sata = ''.join(choice(letters) for i in range(x))
    return [data,sata]

def fstring_func(x):
    return [ord(i) for i in f'{x[0]}{x[1]}']

def format_func(x):
    return [ord(i) for i in "{}{}".format(x[0], x[1])]

def replace_func(x):
    return [ord(i) for i in "|~".replace('|', x[0]).replace('~', x[1])]

def join_func(x):
    return [ord(i) for i in "".join([x[0], x[1]])]

perfplot.show(
    setup=lambda n: generate_random(n),
    kernels=[
        fstring_func,
        format_func,
        replace_func,
        join_func,
    ],
    n_range=[int(k ** 2.5) for k in range(4)],
)

When medium data is there, and 4 strings are there x[0], x[1], x[2], x[3] instead of 2 string:

def generate_random(x):
    a =  ''.join(choice(letters) for i in range(x))
    b =  ''.join(choice(letters) for i in range(x))
    c =  ''.join(choice(letters) for i in range(x))
    d =  ''.join(choice(letters) for i in range(x))
    return [a,b,c,d]

Performance 3 Better to stick with fstrings

Should URL be case sensitive?

The domain name portion of a URL is not case sensitive since DNS ignores case: http://en.example.org/ and HTTP://EN.EXAMPLE.ORG/ both open the same page.

The path is used to specify and perhaps find the resource requested. It is case-sensitive, though it may be treated as case-insensitive by some servers, especially those based on Microsoft Windows.

If the server is case sensitive and http://en.example.org/wiki/URL is correct, then http://en.example.org/WIKI/URL or http://en.example.org/wiki/url will display an HTTP 404 error page, unless these URLs point to valid resources themselves.

How to remove constraints from my MySQL table?

this will works on MySQL to drop constraints

alter table tablename drop primary key;

alter table tablename drop foreign key;

php: check if an array has duplicates

$duplicate = false;

 if(count(array) != count(array_unique(array))){
   $duplicate = true;
}

JavaScript .replace only replaces first Match

For that you neet to use the g flag of regex.... Like this :

var new_string=old_string.replace( / (regex) /g,  replacement_text);

That sh

Laravel Migration Change to Make a Column Nullable

Adding to Dmitri Chebotarev's answer, as for Laravel 5+.

After requiring the doctrine/dbal package:

composer require doctrine/dbal

You can then make a migration with nullable columns, like so:

public function up()
{
    Schema::table('users', function (Blueprint $table) {
        // change() tells the Schema builder that we are altering a table
        $table->integer('user_id')->unsigned()->nullable()->change();
    });
}

To revert the operation, do:

public function down()
{
    /* turn off foreign key checks for a moment */
    DB::statement('SET FOREIGN_KEY_CHECKS = 0');
    /* set null values to 0 first */
    DB::statement('UPDATE `users` SET `user_id` = 0 WHERE `user_id` IS NULL;');
    /* alter table */
    DB::statement('ALTER TABLE `users` MODIFY `user_id` INTEGER UNSIGNED NOT NULL;');
    /* finally turn foreign key checks back on */
    DB::statement('SET FOREIGN_KEY_CHECKS = 1');
}

LogisticRegression: Unknown label type: 'continuous' using sklearn in python

I struggled with the same issue when trying to feed floats to the classifiers. I wanted to keep floats and not integers for accuracy. Try using regressor algorithms. For example:

import numpy as np
from sklearn import linear_model
from sklearn import svm

classifiers = [
    svm.SVR(),
    linear_model.SGDRegressor(),
    linear_model.BayesianRidge(),
    linear_model.LassoLars(),
    linear_model.ARDRegression(),
    linear_model.PassiveAggressiveRegressor(),
    linear_model.TheilSenRegressor(),
    linear_model.LinearRegression()]

trainingData    = np.array([ [2.3, 4.3, 2.5],  [1.3, 5.2, 5.2],  [3.3, 2.9, 0.8],  [3.1, 4.3, 4.0]  ])
trainingScores  = np.array( [3.4, 7.5, 4.5, 1.6] )
predictionData  = np.array([ [2.5, 2.4, 2.7],  [2.7, 3.2, 1.2] ])

for item in classifiers:
    print(item)
    clf = item
    clf.fit(trainingData, trainingScores)
    print(clf.predict(predictionData),'\n')

How to center the text in a JLabel?

String text = "In early March, the city of Topeka, Kansas," + "<br>" +
              "temporarily changed its name to Google..." + "<br>" + "<br>" +
              "...in an attempt to capture a spot" + "<br>" +
              "in Google's new broadband/fiber-optics project." + "<br>" + "<br>" +"<br>" +
              "source: http://en.wikipedia.org/wiki/Google_server#Oil_Tanker_Data_Center";
JLabel label = new JLabel("<html><div style='text-align: center;'>" + text + "</div></html>");

Xcode 6: Keyboard does not show up in simulator

Just press ?K it will toggle keyboard.

Error message "No exports were found that match the constraint contract name"

Deleting the Component Model Cache did not work for me (well, the relative directory given above did not exist in my machine). Instead, I installed an extension to Visual Studio 2012 Express. Menu Tools ? Extensions and Updates... ? Online ? Choose any and then download. This apparently invalidates the cache causing Visual Studio to rebuild it.

Here's my source.

Delete topic in Kafka 0.8.1.1

Step 1: Make sure you are connected to zookeeper and Kafka running

Step 2: To delele the Kafka topic run Kafka-topic (Mac) or Kafka-topic.sh if use (linux/Mac) add the port and --topic with name of your topic and --delete it just delete the topic with success.

# Delete the kafka topic
# it will delete the kafka topic
kafka-topics --zookeeper 127.0.0.1:2181 --topic name_of_topic --delete
# or
kafka-topics.sh --zookeeper 127.0.0.1:2181 --topic name_of_topic --delete

MySQL GROUP BY two columns

Using Concat on the group by will work

SELECT clients.id, clients.name, portfolios.id, SUM ( portfolios.portfolio + portfolios.cash ) AS total
FROM clients, portfolios
WHERE clients.id = portfolios.client_id
GROUP BY CONCAT(portfolios.id, "-", clients.id)
ORDER BY total DESC
LIMIT 30

How to git-cherry-pick only changes to certain files?

The other methods didn't work for me since the commit had a lot of changes and conflicts to a lot of other files. What I came up with was simply

git show SHA -- file1.txt file2.txt | git apply -

It doesn't actually add the files or do a commit for you so you may need to follow it up with

git add file1.txt file2.txt
git commit -c SHA

Or if you want to skip the add you can use the --cached argument to git apply

git show SHA -- file1.txt file2.txt | git apply --cached -

You can also do the same thing for entire directories

git show SHA -- dir1 dir2 | git apply -

.jar error - could not find or load main class

Thanks jbaliuka for the suggestion. I opened the registry editor (by typing regedit in cmd) and going to HKEY_CLASSES_ROOT > jarfile > shell > open > command, then opening (Default) and changing the value from

"C:\Program Files\Java\jre7\bin\javaw.exe" -jar "%1" %*

to

"C:\Program Files\Java\jre7\bin\java.exe" -jar "%1" %*

(I just removed the w in javaw.exe.) After that you have to right click a jar -> open with -> choose default program -> navigate to your java folder and open \jre7\bin\java.exe (or any other java.exe file in you java folder). If it doesn't work, try switching to javaw.exe, open a jar file with it, then switch back.

I don't know anything about editing the registry except that it's dangerous, so you might wanna back it up before doing this (in the top bar, File>Export).

Shortcut for creating single item list in C#

Simply use this:

List<string> list = new List<string>() { "single value" };

You can even omit the () braces:

List<string> list = new List<string> { "single value" };

Update: of course this also works for more than one entry:

List<string> list = new List<string> { "value1", "value2", ... };

How to float a div over Google Maps?

absolute positioning is evil... this solution doesn't take into account window size. If you resize the browser window, your div will be out of place!

MySQL SELECT DISTINCT multiple columns

Both your queries are correct and should give you the right answer.

I would suggest the following query to troubleshoot your problem.

SELECT DISTINCT a,b,c,d,count(*) Count FROM my_table GROUP BY a,b,c,d
order by count(*) desc

That is add count(*) field. This will give you idea how many rows were eliminated using the group command.

How to add leading zeros?

str_pad from the stringr package is an alternative.

anim = 25499:25504
str_pad(anim, width=6, pad="0")

How can I tell gcc not to inline a function?

static __attribute__ ((noinline))  void foo()
{

}

This is what worked for me.

Is there a simple way to remove multiple spaces in a string?

One line of code to remove all extra spaces before, after, and within a sentence:

sentence = "  The   fox jumped   over    the log.  "
sentence = ' '.join(filter(None,sentence.split(' ')))

Explanation:

  1. Split the entire string into a list.
  2. Filter empty elements from the list.
  3. Rejoin the remaining elements* with a single space

*The remaining elements should be words or words with punctuations, etc. I did not test this extensively, but this should be a good starting point. All the best!

Unable to load config info from /usr/local/ssl/openssl.cnf on Windows

In windows , [Similar scenario]

I was facing the same problem But It was during requesting for Certificate Signing Request.

I did the below , It Worked for me.

Once OpenSSL installed, Ran command prompt as administrator after the system reboot.[for the best I did both.. run as admin and system reboot]

did, 1.[Error Case]

C:\OpenSSL-Win64\bin>openssl req -new -key server.key -out server.csr

WARNING: can't open config file: C:\OpenSSL-Win64\bin\openssl.cnf AND Unable to load config info from C:\OpenSSL-Win64\bin\openssl.cnf

2.[Worked with Warning]

C:\OpenSSL-Win64\bin> openssl req -new -key server.key -out server.csr -config C:\OpenSSL-Win64\bin\openssl.cfg

[Warning message]: WARNING: can't open config file: C:\OpenSSL-Win64\bin\openssl.cnf

But prompted me for the Pass Phrase for server.key It worked for me.

I referred,This link for my assistance.

Thank you.

How to enable Logger.debug() in Log4j

Put a file named log4j.xml into your classpath. Contents are e.g.

<?xml version="1.0" encoding="UTF-8" ?>
<!DOCTYPE log4j:configuration SYSTEM "log4j.dtd">

<log4j:configuration xmlns:log4j="http://jakarta.apache.org/log4j/">

    <appender name="stdout" class="org.apache.log4j.ConsoleAppender">
        <layout class="org.apache.log4j.PatternLayout">
            <param name="ConversionPattern" value="%d{ABSOLUTE} %5p %t %c{1}:%L - %m%n"/>
        </layout>
    </appender>

    <root>
        <level value="debug"/>
        <appender-ref ref="stdout"/>
    </root>

</log4j:configuration>

OVER clause in Oracle

Another way to use OVER is to have a result column in your select operate on another "partition", so to say.

This:

SELECT 
    name, 
    ssn, 
    case 
      when ( count(*) over (partition by ssn) ) > 1      
      then 1
      else 0
    end AS hasDuplicateSsn
FROM table;

returns 1 in hasDuplicateSsn for each row whose ssn is shared by another row. Great for making "tags" for data for different error reports and such.

Setting size for icon in CSS

Funnily enough, adjusting the padding seems to do it.

_x000D_
_x000D_
.arrow {
  border: solid rgb(2, 0, 0);
  border-width: 0 3px 3px 0;
  display: inline-block;
}

.first{
  padding: 2vh;
}

.second{
  padding: 4vh;
}

.left {
    transform: rotate(135deg);
    -webkit-transform: rotate(135deg);
 }
_x000D_
<i class="arrow first left"></i>
<i class="arrow second left"></i>
_x000D_
_x000D_
_x000D_

Using Laravel Homestead: 'no input file specified'

I had such problem. I reviewed Homestead.yaml file and all files and all of the settings were correct. My problem removed after the following steps.

1-If you are in vagrant@homestead:~$ command line, type exit command.

2- Now you must be inside Homestead folder. run this command

vagrant reload --provision

3- run vagrant ssh

Now if you type the related address in your browser it should show the Laravel page.

ImportError: libSM.so.6: cannot open shared object file: No such file or directory

You need to add sudo . I did the following to get it installed :

sudo apt-get install libsm6 libxrender1 libfontconfig1

and then did that (optional! maybe you won't need it)

sudo python3 -m pip install opencv-contrib-python

FINALLY got it done !

What is the best way to calculate a checksum for a file that is on my machine?

Any MD5 will produce a good checksum to verify the file. Any of the files listed at the bottom of this page will work fine. http://en.wikipedia.org/wiki/Md5sum

How to change a single value in a NumPy array?

Is this what you are after? Just index the element and assign a new value.

A[2,1]=150

A
Out[345]: 
array([[ 1,  2,  3,  4],
       [ 5,  6,  7,  8],
       [ 9, 150, 11, 12],
       [13, 14, 15, 16]])

sql query to find the duplicate records

select distinct title, (
               select count(title) 
               from kmovies as sub 
               where sub.title=kmovies.title) as cnt 
from kmovies 
group by title 
order by cnt desc

How to select id with max date group by category in PostgreSQL?

This is a perfect use-case for DISTINCT ON - a Postgres specific extension of the standard DISTINCT:

SELECT DISTINCT ON (category)
       id  -- , category, date  -- any other column (expression) from the same row
FROM   tbl
ORDER  BY category, date DESC;

Careful with descending sort order. If the column can be NULL, you may want to add NULLS LAST:

DISTINCT ON is simple and fast. Detailed explanation in this related answer:

For big tables with many rows per category consider an alternative approach:

How to add a right button to a UINavigationController?

You should add your barButtonItem in - (void)pushViewController:(UIViewController *)viewController animated:(BOOL)animated method.

How to update Git clone

If you want to fetch + merge, run

git pull

if you want simply to fetch :

git fetch

RuntimeWarning: DateTimeField received a naive datetime

Just to fix the error to set current time

from django.utils import timezone
import datetime

datetime.datetime.now(tz=timezone.utc) # you can use this value

getApplication() vs. getApplicationContext()

It seems to have to do with context wrapping. Most classes derived from Context are actually a ContextWrapper, which essentially delegates to another context, possibly with changes by the wrapper.

The context is a general abstraction that supports mocking and proxying. Since many contexts are bound to a limited-lifetime object such as an Activity, there needs to be a way to get a longer-lived context, for purposes such as registering for future notifications. That is achieved by Context.getApplicationContext(). A logical implementation is to return the global Application object, but nothing prevents a context implementation from returning a wrapper or proxy with a suitable lifetime instead.

Activities and services are more specifically associated with an Application object. The usefulness of this, I believe, is that you can create and register in the manifest a custom class derived from Application and be certain that Activity.getApplication() or Service.getApplication() will return that specific object of that specific type, which you can cast to your derived Application class and use for whatever custom purpose.

In other words, getApplication() is guaranteed to return an Application object, while getApplicationContext() is free to return a proxy instead.

How to check the Angular version?

check the Command Prompt

ng --version OR ng version OR ng -v

Do I need a content-type header for HTTP GET requests?

GET requests can have "Accept" headers, which say which types of content the client understands. The server can then use that to decide which content type to send back.

They're optional though.

http://www.w3.org/Protocols/rfc2616/rfc2616-sec14.html#sec14.1

Semaphore vs. Monitors - what's the difference?

A semaphore is a signaling mechanism used to coordinate between threads. Example: One thread is downloading files from the internet and another thread is analyzing the files. This is a classic producer/consumer scenario. The producer calls signal() on the semaphore when a file is downloaded. The consumer calls wait() on the same semaphore in order to be blocked until the signal indicates a file is ready. If the semaphore is already signaled when the consumer calls wait, the call does not block. Multiple threads can wait on a semaphore, but each signal will only unblock a single thread.

A counting semaphore keeps track of the number of signals. E.g. if the producer signals three times in a row, wait() can be called three times without blocking. A binary semaphore does not count but just have the "waiting" and "signalled" states.

A mutex (mutual exclusion lock) is a lock which is owned by a single thread. Only the thread which have acquired the lock can realease it again. Other threads which try to acquire the lock will be blocked until the current owner thread releases it. A mutex lock does not in itself lock anything - it is really just a flag. But code can check for ownership of a mutex lock to ensure that only one thread at a time can access some object or resource.

A monitor is a higher-level construct which uses an underlying mutex lock to ensure thread-safe access to some object. Unfortunately the word "monitor" is used in a few different meanings depending on context and platform and context, but in Java for example, a monitor is a mutex lock which is implicitly associated with an object, and which can be invoked with the synchronized keyword. The synchronized keyword can be applied to a class, method or block and ensures only one thread can execute the code at a time.

How to find out when an Oracle table was updated the last time

Ask your DBA about auditing. He can start an audit with a simple command like :

AUDIT INSERT ON user.table

Then you can query the table USER_AUDIT_OBJECT to determine if there has been an insert on your table since the last export.

google for Oracle auditing for more info...

Using XAMPP, how do I swap out PHP 5.3 for PHP 5.2?

You can download older versions of XAMPP here. PHP 5.3 was added in version 1.7.2, so anything older would be good.

use std::fill to populate vector with increasing numbers

There is another option - without using iota. For_each + lambda expression can be used:

vector<int> ivec(10); // the vector of size 10
int i = 0;            // incrementor
for_each(ivec.begin(), ivec.end(), [&](int& item) { ++i; item += i;});

Two important things why it's working:

  1. Lambda captures outer scope [&] which means that i will be available inside expression
  2. item passed as a reference, therefore, it is mutable inside the vector

HTML Drag And Drop On Mobile Devices

here is my solution:

$(el).on('touchstart', function(e) {
    var link = $(e.target.parentNode).closest('a')  
    if(link.length > 0) {
        window.location.href = link.attr('href');
    }
});

How to check if a string in Python is in ASCII?

To improve Alexander's solution from the Python 2.6 (and in Python 3.x) you can use helper module curses.ascii and use curses.ascii.isascii() function or various other: https://docs.python.org/2.6/library/curses.ascii.html

from curses import ascii

def isascii(s):
    return all(ascii.isascii(c) for c in s)

Laravel Eloquent - distinct() and count() not working properly together

Based on Laravel docs for raw queries I was able to get count for a select field to work with this code in the product model.

public function scopeShowProductCount($query)
{
    $query->select(DB::raw('DISTINCT pid, COUNT(*) AS count_pid'))
          ->groupBy('pid')
          ->orderBy('count_pid', 'desc');
}

This facade worked to get the same result in the controller:

$products = DB::table('products')->select(DB::raw('DISTINCT pid, COUNT(*) AS count_pid'))->groupBy('pid')->orderBy('count_pid', 'desc')->get();

The resulting dump for both queries was as follows:

#attributes: array:2 [
  "pid" => "1271"
  "count_pid" => 19
],
#attributes: array:2 [
  "pid" => "1273"
  "count_pid" => 12
],
#attributes: array:2 [
  "pid" => "1275"
  "count_pid" => 7
]

Trusting all certificates using HttpClient over HTTPS

enter image description here

A sspi failed in xamarin android.

I found this solution; put this code before you hit on an HTTPS link

const SslProtocols _Tls12 = (SslProtocols)0x00000C00;
const SecurityProtocolType Tls12 = (SecurityProtocolType)_Tls12;
ServicePointManager.SecurityProtocol = Tls12;

problem with <select> and :after with CSS in WebKit

This post may help http://bavotasan.com/2011/style-select-box-using-only-css/

He is using a outside div with a class for resolving this issue.

<div class="styled-select">
  <select>
    <option>Here is the first option</option>
    <option>The second option</option>
  </select>
</div>

How to create the most compact mapping n ? isprime(n) up to a limit N?

According to wikipedia, the Sieve of Eratosthenes has complexity O(n * (log n) * (log log n)) and requires O(n) memory - so it's a pretty good place to start if you aren't testing for especially large numbers.

Efficient evaluation of a function at every cell of a NumPy array

A similar question is: Mapping a NumPy array in place. If you can find a ufunc for your f(), then you should use the out parameter.

Is it possible to use Visual Studio on macOS?

There is no native version of Visual Studio for Mac OS X.

Almost all versions of Visual Studio have a Garbage rating on Wine's application database, so Wine isn't an option either, sadly.

What is the C# equivalent of friend?

There isn't a 'friend' keyword in C# but one option for testing private methods is to use System.Reflection to get a handle to the method. This will allow you to invoke private methods.

Given a class with this definition:

public class Class1
{
    private int CallMe()
    {
        return 1;
    }
}

You can invoke it using this code:

Class1 c = new Class1();
Type class1Type = c.GetType();
MethodInfo callMeMethod = class1Type.GetMethod("CallMe", BindingFlags.Instance | BindingFlags.NonPublic);

int result = (int)callMeMethod.Invoke(c, null);

Console.WriteLine(result);

If you are using Visual Studio Team System then you can get VS to automatically generate a proxy class with private accessors in it by right clicking the method and selecting "Create Unit Tests..."

In C#, what's the difference between \n and \r\n?

"\n" is just a line feed (Unicode U+000A). This is typically the Unix line separator.

"\r\n" is a carriage return (Unicode U+000D) followed by a line feed (Unicode U+000A). This is typically the Windows line separator.

Error retrieving parent for item: No resource found that matches the given name 'android:TextAppearance.Material.Widget.Button.Borderless.Colored'

in my case i was using compile sdk 23 and build tools 25.0.0 just changed compile sdk to 25 and done..

How do I get currency exchange rates via an API such as Google Finance?

Thanks for all your answers.

Free currencyconverterapi:

  • Rates updated every 30 min
  • API key is now required for the free server.

A sample conversion URL is: http://free.currencyconverterapi.com/api/v5/convert?q=EUR_USD&compact=y


For posterity here they are along with other possible answers:

  1. Yahoo finance API Discontinued 2017-11-06###

Discontinued as of 2017-11-06 with message

It has come to our attention that this service is being used in violation of the Yahoo Terms of Service. As such, the service is being discontinued. For all future markets and equities data research, please refer to finance.yahoo.com.

Request: http://finance.yahoo.com/d/quotes.csv?e=.csv&f=sl1d1t1&s=USDINR=X
This CSV was being used by a jQuery plugin called Curry. Curry has since (2017-08-29) moved to use fixer.io instead due to stability issues. Might be useful if you need more than just a CSV.

  1. (thanks to Keyo) Yahoo Query Language lets you get a whole bunch of currencies at once in XML or JSON. The data updates by the second (whereas the European Central Bank has day old data), and stops in the weekend. Doesn't require any kind of sign up.

http://query.yahooapis.com/v1/public/yql?q=select * from yahoo.finance.xchange where pair in ("USDEUR", "USDJPY", "USDBGN", "USDCZK", "USDDKK", "USDGBP", "USDHUF", "USDLTL", "USDLVL", "USDPLN", "USDRON", "USDSEK", "USDCHF", "USDNOK", "USDHRK", "USDRUB", "USDTRY", "USDAUD", "USDBRL", "USDCAD", "USDCNY", "USDHKD", "USDIDR", "USDILS", "USDINR", "USDKRW", "USDMXN", "USDMYR", "USDNZD", "USDPHP", "USDSGD", "USDTHB", "USDZAR", "USDISK")&env=store://datatables.org/alltableswithkeys

Here is the YQL query builder, where you can test a query and copy the url: (NO LONGER AVAILABLE)

http://developer.yahoo.com/yql/console/?q=show%20tables&env=store://datatables.org/alltableswithkeys#h=select%20*%20from%20yahoo.finance.xchange%20where%20pair%20in%20%28%22USDMXN%22%2C%20%22USDCHF%22%29

yql console no longer available

  1. Open Source Exchange Rates API

Free for personal use (1000 hits per month)
Changing "base" (from "USD") is not allowed in Free account
Requires registration.
Request: http://openexchangerates.org/latest.json
Response:

   <!-- language: lang-js -->

    {
      "disclaimer": "This data is collected from various providers ...",
      "license": "all code open-source under GPL v3 ...",
      "timestamp": 1323115901,
      "base": "USD",
      "rates": {
          "AED": 3.66999725,
          "ALL": 102.09382091,
          "ANG": 1.78992886,
          // 115 more currency rates here ...
      }
    }
  1. currencylayer API

Free Plan for 250 monthly hits
Changing "source" (from "USD") is not allowed in Free account
Requires registration.
Documentation: currencylayer.com/documentation

JSON Response:

   <!-- language: lang-js -->

    {
      [...]
      "timestamp": 1436284516,
      "source": "USD",
      "quotes": {
          "USDAUD": 1.345352401,
          "USDCAD": 1.27373397,
          "USDCHF": 0.947845302,
          "USDEUR": 0.91313905,
          "USDGBP": 0.647603397,
          // 168 world currencies
          }
      }
  1. CurrencyFreaks API

Free Plan (1000 hits per month)
Changing 'Base' (From 'USD') is not allowed in free account
Requires registration
Data updated every 60 sec.
179 currencies worldwide including currencies, metals, and cryptocurrencies
Support (Even on the free plan) Shell,Node.js, Java, Python, PHP, Ruby, JS, C#, C, Go, Swift.
Documentation: https://currencyfreaks.com/documentation.html

Endpoint:

$ curl 'https://api.currencyfreaks.com/latest?apikey=YOUR_APIKEY'

JSON Response:

{
    "date": "2020-10-08 12:29:00+00",
    "base": "USD",
    "rates": {
        "FJD": "2.139",
        "MXN": "21.36942",
        "STD": "21031.906016",
        "LVL": "0.656261",
        "SCR": "18.106031",
        "CDF": "1962.53482",
        "BBD": "2.0",
        "GTQ": "7.783265",
        "CLP": "793.0",
        "HNL": "24.625383",
        "UGX": "3704.50271",
        "ZAR": "16.577611",
        "TND": "2.762",
        "CUC": "1.000396",
        "BSD": "1.0",
        "SLL": "9809.999914",
        "SDG": 55.325,
        "IQD": "1194.293591",
          .
          .
          .
    [179 currencies]
    }
}
  1. Fixer.io API (European Central Bank data)

Free Plan for 1,000 monthly hits
Changing "source" (from "USD") is not allowed in Free account Requires registration.

This API endpoint is deprecated and will stop working on June 1st, 2018. For more information please visit: https://github.com/fixerAPI/fixer#readme)


Website : http://fixer.io/
Example request : [http://api.fixer.io/latest?base=USD][7]
Only collects one value per each day
  1. European Central Bank Feed

Docs: http://www.ecb.int/stats/exchange/eurofxref/html/index.en.html#dev
Request: http://www.ecb.int/stats/eurofxref/eurofxref-daily.xml

XML Response:

   <!-- language: lang-xml -->

    <Cube>
      <Cube time="2015-07-07">
      <Cube currency="USD" rate="1.0931"/>
      <Cube currency="JPY" rate="133.88"/>
      <Cube currency="BGN" rate="1.9558"/>
      <Cube currency="CZK" rate="27.100"/>
    </Cube>
  1. exchangeratesapi.io

According to the website:

Exchange rates API is a free service for current and historical foreign exchange rates published by the European Central Bank
This service is compatible with fixer.io and is really easy to use: no API key needed. For example (this uses CURL, but you can use your favourite requesting tool):

    > curl https://api.exchangeratesapi.io/latest?base=GBP&symbols=USD
    {"base":"GBP","rates":{"USD":1.264494191},"date":"2019-05-29"}
  1. CurrencyApi.net

Free Plan for 1250 monthly hits
150 Crypto and physical currencies - live updates
Base currency is set as USD on free account
Requires registration.
Documentation: currencyapi.net/documentation

JSON Response:

    {
      "valid": true,
      "updated": 1567957373,
      "base": "USD",
      "rates": {
              "AED": 3.673042,
              "AFN": 77.529504,
              "ALL": 109.410403,
              // 165 currencies + some cryptos
          }
      }
  1. Currency from LabStack

Website: https://labstack.com/currency
Documentation: https://labstack.com/docs/api/currency/convert
Pricing: https://labstack.com/pricing
Request: https://currency.labstack.com/api/v1/convert/1/USD/INR
Response:

```js
 {
   "time": "2019-10-09T21:15:00Z",
   "amount": 71.1488
 }
 ```

1: http://query.yahooapis.com/v1/public/yql?q=select * from yahoo.finance.xchange where pair in ("USDEUR", "USDJPY", "USDBGN", "USDCZK", "USDDKK", "USDGBP", "USDHUF", "USDLTL", "USDLVL", "USDPLN", "USDRON", "USDSEK", "USDCHF", "USDNOK", "USDHRK", "USDRUB", "USDTRY", "USDAUD", "USDBRL", "USDCAD", "USDCNY", "USDHKD", "USDIDR", "USDILS", "USDINR", "USDKRW", "USDMXN", "USDMYR", "USDNZD", "USDPHP", "USDSGD", "USDTHB", "USDZAR", "USDISK")&env=store://datatables.org/alltableswithkeys

Replacing values from a column using a condition in R

I arrived here from a google search, since my other code is 'tidy' so leaving the 'tidy' way for anyone who else who may find it useful

library(dplyr)
iris %>% 
  mutate(Species = ifelse(as.character(Species) == "virginica", "newValue", as.character(Species)))

Changing the cursor in WPF sometimes works, sometimes doesn't

You can use a data trigger (with a view model) on the button to enable a wait cursor.

<Button x:Name="NextButton"
        Content="Go"
        Command="{Binding GoCommand }">
    <Button.Style>
         <Style TargetType="{x:Type Button}">
             <Setter Property="Cursor" Value="Arrow"/>
             <Style.Triggers>
                 <DataTrigger Binding="{Binding Path=IsWorking}" Value="True">
                     <Setter Property="Cursor" Value="Wait"/>
                 </DataTrigger>
             </Style.Triggers>
         </Style>
    </Button.Style>
</Button>

Here is the code from the view-model:

public class MainViewModel : ViewModelBase
{
   // most code removed for this example

   public MainViewModel()
   {
      GoCommand = new DelegateCommand<object>(OnGoCommand, CanGoCommand);
   }

   // flag used by data binding trigger
   private bool _isWorking = false;
   public bool IsWorking
   {
      get { return _isWorking; }
      set
      {
         _isWorking = value;
         OnPropertyChanged("IsWorking");
      }
   }

   // button click event gets processed here
   public ICommand GoCommand { get; private set; }
   private void OnGoCommand(object obj)
   {
      if ( _selectedCustomer != null )
      {
         // wait cursor ON
         IsWorking = true;
         _ds = OrdersManager.LoadToDataSet(_selectedCustomer.ID);
         OnPropertyChanged("GridData");

         // wait cursor off
         IsWorking = false;
      }
   }
}

How to detect when facebook's FB.init is complete

Actually Facebook has already provided a mechanism to subscribe to authentication events.

In your case you are using "status: true" which means that FB object will request Facebook for user's login status.

FB.init({
    appId  : '<?php echo $conf['fb']['appid']; ?>',
    status : true, // check login status
    cookie : true, // enable cookies to allow the server to access the session
    xfbml  : true  // parse XFBML
});

By calling "FB.getLoginStatus()" you are running the same request again.

Instead you could use FB.Event.subscribe to subscribe to auth.statusChange or auth.authResponseChange event BEFORE you call FB.init

FB.Event.subscribe('auth.statusChange', function(response) {
    if(response.status == 'connected') {
        runFbInitCriticalCode();
    }
});

FB.init({
    appId  : '<?php echo $conf['fb']['appid']; ?>',
    status : true, // check login status
    cookie : true, // enable cookies to allow the server to access the session
    xfbml  : true  // parse XFBML
});

Most likely, when using "status: false" you can run any code right after FB.init, because there will be no asynchronous calls.

WARNING: Setting property 'source' to 'org.eclipse.jst.jee.server:appname' did not find a matching property

Despite this question being rather old, I had to deal with a similar warning and wanted to share what I found out.

First of all this is a warning and not an error. So there is no need to worry too much about it. Basically it means, that Tomcat does not know what to do with the source attribute from context.

This source attribute is set by Eclipse (or to be more specific the Eclipse Web Tools Platform) to the server.xml file of Tomcat to match the running application to a project in workspace.

Tomcat generates a warning for every unknown markup in the server.xml (i.e. the source attribute) and this is the source of the warning. You can safely ignore it.

How to inflate one view with a layout

Try this code :

  1. If you just want to inflate your layout :

_x000D_
_x000D_
View view = LayoutInflater.from(context).inflate(R.layout.your_xml_layout,null); // Code for inflating xml layout_x000D_
RelativeLayout item = view.findViewById(R.id.item);   
_x000D_
_x000D_
_x000D_

  1. If you want to inflate your layout in container(parent layout) :

_x000D_
_x000D_
LinearLayout parent = findViewById(R.id.container);        //parent layout._x000D_
View view = LayoutInflater.from(context).inflate(R.layout.your_xml_layout,parent,false); _x000D_
RelativeLayout item = view.findViewById(R.id.item);       //initialize layout & By this you can also perform any event._x000D_
parent.addView(view);             //adding your inflated layout in parent layout.
_x000D_
_x000D_
_x000D_

Interpreting segfault messages

Error 4 means "The cause was a user-mode read resulting in no page being found.". There's a tool that decodes it here.

Here's the definition from the kernel. Keep in mind that 4 means that bit 2 is set and no other bits are set. If you convert it to binary that becomes clear.

/*
 * Page fault error code bits
 *      bit 0 == 0 means no page found, 1 means protection fault
 *      bit 1 == 0 means read, 1 means write
 *      bit 2 == 0 means kernel, 1 means user-mode
 *      bit 3 == 1 means use of reserved bit detected
 *      bit 4 == 1 means fault was an instruction fetch
 */
#define PF_PROT         (1<<0)
#define PF_WRITE        (1<<1)
#define PF_USER         (1<<2)
#define PF_RSVD         (1<<3)
#define PF_INSTR        (1<<4)

Now then, "ip 00007f9bebcca90d" means the instruction pointer was at 0x00007f9bebcca90d when the segfault happened.

"libQtWebKit.so.4.5.2[7f9beb83a000+f6f000]" tells you:

  • The object the crash was in: "libQtWebKit.so.4.5.2"
  • The base address of that object "7f9beb83a000"
  • How big that object is: "f6f000"

If you take the base address and subtract it from the ip, you get the offset into that object:

0x00007f9bebcca90d - 0x7f9beb83a000 = 0x49090D

Then you can run addr2line on it:

addr2line -e /usr/lib64/qt45/lib/libQtWebKit.so.4.5.2 -fCi 0x49090D
??
??:0

In my case it wasn't successful, either the copy I installed isn't identical to yours, or it's stripped.

How do I Geocode 20 addresses without receiving an OVER_QUERY_LIMIT response?

No, there is not really any other way : if you have many locations and want to display them on a map, the best solution is to :

  • fetch the latitude+longitude, using the geocoder, when a location is created
  • store those in your database, alongside the address
  • and use those stored latitude+longitude when you want to display the map.

This is, of course, considering that you have a lot less creation/modification of locations than you have consultations of locations.


Yes, it means you'll have to do a bit more work when saving the locations -- but it also means :

  • You'll be able to search by geographical coordinates
    • i.e. "I want a list of points that are near where I'm now"
  • Displaying the map will be a lot faster
    • Even with more than 20 locations on it
  • Oh, and, also (last but not least) : this will work ;-)
    • You will less likely hit the limit of X geocoder calls in N seconds.
    • And you will less likely hit the limit of Y geocoder calls per day.

Recover sa password

best answer written by Dmitri Korotkevitch:

Speaking of the installation, SQL Server 2008 allows you to set authentication mode (Windows or SQL Server) during the installation process. You will be forced to choose the strong password for sa user in the case if you choose sql server authentication mode during setup.

If you install SQL Server with Windows Authentication mode and want to change it, you need to do 2 different things:

  1. Go to SQL Server Properties/Security tab and change the mode to SQL Server authentication mode

  2. Go to security/logins, open SA login properties

a. Uncheck "Enforce password policy" and "Enforce password expiration" check box there if you decide to use weak password

b. Assign password to SA user

c. Open "Status" tab and enable login.

I don't need to mention that every action from above would violate security best practices that recommend to use windows authentication mode, have sa login disabled and use strong passwords especially for sa login.

How to set a value of a variable inside a template code?

There are tricks like the one described by John; however, Django's template language by design does not support setting a variable (see the "Philosophy" box in Django documentation for templates).
Because of this, the recommended way to change any variable is via touching the Python code.

GROUP BY to combine/concat a column

SELECT
     [User], Activity,
     STUFF(
         (SELECT DISTINCT ',' + PageURL
          FROM TableName
          WHERE [User] = a.[User] AND Activity = a.Activity
          FOR XML PATH (''))
          , 1, 1, '')  AS URLList
FROM TableName AS a
GROUP BY [User], Activity

Do something if screen width is less than 960 px

Use jQuery to get the width of the window.

if ($(window).width() < 960) {
   alert('Less than 960');
}
else {
   alert('More than 960');
}

Remove git mapping in Visual Studio 2015

You cant delete local git repository when its already connected. so close the solution, open another solution and then remove the local git repository. dont forget to delete .git hidden folder works for me

Convert Set to List without creating new List

For the sake of completeness...

Say that you really do want to treat the Map values as Lists, but you want to avoid copying the Set into a List each time.

For instance, maybe you are calling one library function that creates a Set, but you are passing your Map<String, List<String>> result to a (poorly-designed but out of your hands) library function that only takes Map<String, List<String>>, even though somehow you know that the operations it does with the Lists are equally applicable to any Collection (and thus any Set). And for some reason you need to avoid the speed/memory overhead of copying each Set to a List.

In this super niche case, depending on the (maybe unknowable) behavior the library function needs out of your Lists, you may be able to create a List view over each Set. Note that this is inherently unsafe (because the library function's requirements from each List could presumably change without you knowing), so another solution should be preferred. But here's how you'd do it.

You'd create a class that implements the List interface, takes a Set in the constructor and assigns that Set to a field, and then uses that internal Set to implement the List API (to the extent possible, and desired).

Note that some List behavior you simply will not be able to imitate without storing the elements as a List, and some behavior you will only partially be able to imitate. Again, this class is not a safe drop-in replacement for Lists in general. In particular, if you know that the use case requires index-related operations or MUTATING the List, this approach would go south very fast.

public class ListViewOfSet<U> implements List<U> {
    private final Set<U> wrappedSet;
    public ListViewOfSet(Set<U> setToWrap) { this.wrappedSet = setToWrap; }

    @Override public int size() { return this.wrappedSet.size(); }
    @Override public boolean isEmpty() { return this.wrappedSet.isEmpty(); }
    @Override public boolean contains(Object o) { return this.wrappedSet.contains(o); }
    @Override public java.util.Iterator<U> iterator() { return this.wrappedSet.iterator(); }
    @Override public Object[] toArray() { return this.wrappedSet.toArray(); }
    @Override public <T> T[] toArray(T[] ts) { return this.wrappedSet.toArray(ts); }
    @Override public boolean add(U e) { return this.wrappedSet.add(e); }
    @Override public boolean remove(Object o) { return this.wrappedSet.remove(o); }
    @Override public boolean containsAll(Collection<?> clctn) { return this.wrappedSet.containsAll(clctn); }
    @Override public boolean addAll(Collection<? extends U> clctn) { return this.wrappedSet.addAll(clctn); }
    @Override public boolean addAll(int i, Collection<? extends U> clctn) { throw new UnsupportedOperationException(); }
    @Override public boolean removeAll(Collection<?> clctn) { return this.wrappedSet.removeAll(clctn); }
    @Override public boolean retainAll(Collection<?> clctn) { return this.wrappedSet.retainAll(clctn); }
    @Override public void clear() { this.wrappedSet.clear(); }
    @Override public U get(int i) { throw new UnsupportedOperationException(); }
    @Override public U set(int i, U e) { throw new UnsupportedOperationException(); }
    @Override public void add(int i, U e) { throw new UnsupportedOperationException(); }
    @Override public U remove(int i) { throw new UnsupportedOperationException(); }
    @Override public int indexOf(Object o) { throw new UnsupportedOperationException(); }
    @Override public int lastIndexOf(Object o) { throw new UnsupportedOperationException(); }
    @Override public ListIterator<U> listIterator() { throw new UnsupportedOperationException(); }
    @Override public ListIterator<U> listIterator(int i) { throw new UnsupportedOperationException(); }
    @Override public List<U> subList(int i, int i1) { throw new UnsupportedOperationException(); }
}

...
Set<String> set = getSet(...);
ListViewOfSet<String> listOfNames = new ListViewOfSet<>(set);
...

Android Fragment no view found for ID?

If you are trying to replace a fragment within a fragment with the fragmentManager but you are not inflating the parent fragment that can cause an issue.

In BaseFragment.java OnCreateView:

if (savedInstanceState == null) {
            getFragmentManager().beginTransaction()
                    .replace(R.id.container, new DifferentFragment())
                    .commit();
        }

return super.onCreateView(inflater, container, savedInstanceState);

Replace super.onCreateView(inflater, container, savedInstanceState); with inflating the correct layout for the fragment:

        return inflater.inflate(R.layout.base_fragment, container, false);

How to check if internet connection is present in Java?

This code should do the job reliably.

Note that when using the try-with-resources statement we don't need to close the resources.

import java.io.IOException;
import java.net.InetSocketAddress;
import java.net.Socket;
import java.net.UnknownHostException;

public class InternetAvailabilityChecker
{
    public static boolean isInternetAvailable() throws IOException
    {
        return isHostAvailable("google.com") || isHostAvailable("amazon.com")
                || isHostAvailable("facebook.com")|| isHostAvailable("apple.com");
    }

    private static boolean isHostAvailable(String hostName) throws IOException
    {
        try(Socket socket = new Socket())
        {
            int port = 80;
            InetSocketAddress socketAddress = new InetSocketAddress(hostName, port);
            socket.connect(socketAddress, 3000);

            return true;
        }
        catch(UnknownHostException unknownHost)
        {
            return false;
        }
    }
}

How to plot ROC curve in Python

Here is python code for computing the ROC curve (as a scatter plot):

import matplotlib.pyplot as plt
import numpy as np

score = np.array([0.9, 0.8, 0.7, 0.6, 0.55, 0.54, 0.53, 0.52, 0.51, 0.505, 0.4, 0.39, 0.38, 0.37, 0.36, 0.35, 0.34, 0.33, 0.30, 0.1])
y = np.array([1,1,0, 1, 1, 1, 0, 0, 1, 0, 1,0, 1, 0, 0, 0, 1 , 0, 1, 0])

# false positive rate
fpr = []
# true positive rate
tpr = []
# Iterate thresholds from 0.0, 0.01, ... 1.0
thresholds = np.arange(0.0, 1.01, .01)

# get number of positive and negative examples in the dataset
P = sum(y)
N = len(y) - P

# iterate through all thresholds and determine fraction of true positives
# and false positives found at this threshold
for thresh in thresholds:
    FP=0
    TP=0
    for i in range(len(score)):
        if (score[i] > thresh):
            if y[i] == 1:
                TP = TP + 1
            if y[i] == 0:
                FP = FP + 1
    fpr.append(FP/float(N))
    tpr.append(TP/float(P))

plt.scatter(fpr, tpr)
plt.show()

How to assign from a function which returns more than one value?

(1) list[...]<- I had posted this over a decade ago on r-help. Since then it has been added to the gsubfn package. It does not require a special operator but does require that the left hand side be written using list[...] like this:

library(gsubfn)  # need 0.7-0 or later
list[a, b] <- functionReturningTwoValues()

If you only need the first or second component these all work too:

list[a] <- functionReturningTwoValues()
list[a, ] <- functionReturningTwoValues()
list[, b] <- functionReturningTwoValues()

(Of course, if you only needed one value then functionReturningTwoValues()[[1]] or functionReturningTwoValues()[[2]] would be sufficient.)

See the cited r-help thread for more examples.

(2) with If the intent is merely to combine the multiple values subsequently and the return values are named then a simple alternative is to use with :

myfun <- function() list(a = 1, b = 2)

list[a, b] <- myfun()
a + b

# same
with(myfun(), a + b)

(3) attach Another alternative is attach:

attach(myfun())
a + b

ADDED: with and attach

CodeIgniter - How to return Json response from controller

For CodeIgniter 4, you can use the built-in API Response Trait

Here's sample code for reference:

<?php namespace App\Controllers;

use CodeIgniter\API\ResponseTrait;

class Home extends BaseController
{
    use ResponseTrait;

    public function index()
    {
        $data = [
            'data' => 'value1',
            'data2' => 'value2',
        ];

        return $this->respond($data);
    }
}

Get device token for push notification

Objective C for iOS 13+, courtesy of Wasif Saood's answer

Copy and paste below code into AppDelegate.m to print the device APN token.

- (void)application:(UIApplication *)app didRegisterForRemoteNotificationsWithDeviceToken:(NSData *)deviceToken
{
  NSUInteger dataLength = deviceToken.length;
  if (dataLength == 0) {
    return;
  }
  const unsigned char *dataBuffer = (const unsigned char *)deviceToken.bytes;
  NSMutableString *hexString  = [NSMutableString stringWithCapacity:(dataLength * 2)];
  for (int i = 0; i < dataLength; ++i) {
    [hexString appendFormat:@"%02x", dataBuffer[i]];
  }
  NSLog(@"APN token:%@", hexString);
}

javascript, is there an isObject function like isArray?

You can use typeof operator.

if( (typeof A === "object" || typeof A === 'function') && (A !== null) )
{
    alert("A is object");
}

Note that because typeof new Number(1) === 'object' while typeof Number(1) === 'number'; the first syntax should be avoided.

javascript convert int to float

JavaScript only has a Number type that stores floating point values.

There is no int.

Edit:

If you want to format the number as a string with two digits after the decimal point use:

(4).toFixed(2)

Disable Tensorflow debugging information

Usual python3 log manager works for me with tensorflow==1.11.0:

import logging
logging.getLogger('tensorflow').setLevel(logging.INFO)

Is it possible to run JavaFX applications on iOS, Android or Windows Phone 8?

  1. yes you can run it on iOS and Android (Win8 is not supported!
  2. no deployment as a web-app does not work

Is there any way to call a function periodically in JavaScript?

The native way is indeed setInterval()/clearInterval(), but if you are already using the Prototype library you can take advantage of PeriodicalExecutor:

new PeriodicalUpdator(myEvent, seconds);

This prevents overlapping calls. From http://www.prototypejs.org/api/periodicalExecuter:

"it shields you against multiple parallel executions of the callback function, should it take longer than the given interval to execute (it maintains an internal “running” flag, which is shielded against exceptions in the callback function). This is especially useful if you use one to interact with the user at given intervals (e.g. use a prompt or confirm call): this will avoid multiple message boxes all waiting to be actioned."

list all files in the folder and also sub folders

Use FileUtils from Apache commons.

listFiles

public static Collection<File> listFiles(File directory,
                                         String[] extensions,
                                         boolean recursive)
Finds files within a given directory (and optionally its subdirectories) which match an array of extensions.
Parameters:
directory - the directory to search in
extensions - an array of extensions, ex. {"java","xml"}. If this parameter is null, all files are returned.
recursive - if true all subdirectories are searched as well
Returns:
an collection of java.io.File with the matching files

Best way in asp.net to force https for an entire site?

For @Joe above, "This is giving me a redirect loop. Before I added the code it worked fine. Any suggestions? – Joe Nov 8 '11 at 4:13"

This was happening to me as well and what I believe was happening is that there was a load balancer terminating the SSL request in front of the Web server. So, my Web site was always thinking the request was "http", even if the original browser requested it to be "https".

I admit this is a bit hacky, but what worked for me was to implement a "JustRedirected" property that I could leverage to figure out the person was already redirected once. So, I test for specific conditions that warrant the redirect and, if they are met, I set this property (value stored in session) prior to the redirection. Even if the http/https conditions for redirection are met the second time, I bypass the redirection logic and reset the "JustRedirected" session value to false. You'll need your own conditional test logic, but here's a simple implementation of the property:

    public bool JustRedirected
    {
        get
        {
            if (Session[RosadaConst.JUSTREDIRECTED] == null)
                return false;

            return (bool)Session[RosadaConst.JUSTREDIRECTED];
        }
        set
        {
            Session[RosadaConst.JUSTREDIRECTED] = value;
        }
    }

Spring data JPA query with parameter properties

You could also solve it with an interface default method:

 @Query(select p from Person p where p.forename = :forename and p.surname = :surname)
User findByForenameAndSurname(@Param("surname") String lastname,
                         @Param("forename") String firstname);

default User findByName(Name name) {
  return findByForenameAndSurname(name.getLastname(), name.getFirstname());
}

Of course you'd still have the actual repository function publicly visible...

How to center horizontally div inside parent div

<div id='parent' style='width: 100%;text-align:center;'>
 <div id='child' style='width:50px; height:100px;margin:0px auto;'>Text</div>
</div>

How can I set the PATH variable for javac so I can manually compile my .java works?

Trying this out on Windows 10, none of the command-line instructions worked.

Right clicking on "Computer" then open Properties etc. as the post by Galen Nare above already explains, leads you to a window where you need to click on "new" and then paste the path (as said: without deleting anything else). Afterwards you can check by typing java -version in the command-line window, which should display your current java version, if everything worked out right.

C# generic list <T> how to get the type of T?

Given an object which I suspect to be some kind of IList<>, how can I determine of what it's an IList<>?

Here's the gutsy solution. It assumes you have the actual object to test (rather than a Type).

public static Type ListOfWhat(Object list)
{
    return ListOfWhat2((dynamic)list);
}

private static Type ListOfWhat2<T>(IList<T> list)
{
    return typeof(T);
}

Example usage:

object value = new ObservableCollection<DateTime>();
ListOfWhat(value).Dump();

Prints

typeof(DateTime)

How to pass parameters to ThreadStart method in Thread?

You want to use the ParameterizedThreadStart delegate for thread methods that take parameters. (Or none at all actually, and let the Thread constructor infer.)

Example usage:

var thread = new Thread(new ParameterizedThreadStart(download));
//var thread = new Thread(download); // equivalent

thread.Start(filename)

LINQ Aggregate algorithm explained

Everyone has given his explanation. My explanation is like that.

Aggregate method applies a function to each item of a collection. For example, let's have collection { 6, 2, 8, 3 } and the function Add (operator +) it does (((6+2)+8)+3) and returns 19

var numbers = new List<int> { 6, 2, 8, 3 };
int sum = numbers.Aggregate(func: (result, item) => result + item);
// sum: (((6+2)+8)+3) = 19

In this example there is passed named method Add instead of lambda expression.

var numbers = new List<int> { 6, 2, 8, 3 };
int sum = numbers.Aggregate(func: Add);
// sum: (((6+2)+8)+3) = 19

private static int Add(int x, int y) { return x + y; }

Using Service to run background and create notification

The question is relatively old, but I hope this post still might be relevant for others.

TL;DR: use AlarmManager to schedule a task, use IntentService, see the sample code here;

What this test-application(and instruction) is about:

Simple helloworld app, which sends you notification every 2 hours. Clicking on notification - opens secondary Activity in the app; deleting notification tracks.

When should you use it:

Once you need to run some task on a scheduled basis. My own case: once a day, I want to fetch new content from server, compose a notification based on the content I got and show it to user.

What to do:

  1. First, let's create 2 activities: MainActivity, which starts notification-service and NotificationActivity, which will be started by clicking notification:

    activity_main.xml

    <?xml version="1.0" encoding="utf-8"?>
    <RelativeLayout xmlns:android="http://schemas.android.com/apk/res/android"
        android:layout_width="match_parent"
        android:layout_height="match_parent"
        android:padding="16dp">
        <Button
            android:id="@+id/sendNotifications"
            android:onClick="onSendNotificationsButtonClick"
            android:layout_width="wrap_content"
            android:layout_height="wrap_content"
            android:text="Start Sending Notifications Every 2 Hours!" />
    </RelativeLayout>
    

    MainActivity.java

    public class MainActivity extends AppCompatActivity {
        @Override
        protected void onCreate(Bundle savedInstanceState) {
            super.onCreate(savedInstanceState);
            setContentView(R.layout.activity_main);
        }
    
        public void onSendNotificationsButtonClick(View view) {
            NotificationEventReceiver.setupAlarm(getApplicationContext());
        }   
    }
    

    and NotificationActivity is any random activity you can come up with. NB! Don't forget to add both activities into AndroidManifest.

  2. Then let's create WakefulBroadcastReceiver broadcast receiver, I called NotificationEventReceiver in code above.

    Here, we'll set up AlarmManager to fire PendingIntent every 2 hours (or with any other frequency), and specify the handled actions for this intent in onReceive() method. In our case - wakefully start IntentService, which we'll specify in the later steps. This IntentService would generate notifications for us.

    Also, this receiver would contain some helper-methods like creating PendintIntents, which we'll use later

    NB1! As I'm using WakefulBroadcastReceiver, I need to add extra-permission into my manifest: <uses-permission android:name="android.permission.WAKE_LOCK" />

    NB2! I use it wakeful version of broadcast receiver, as I want to ensure, that the device does not go back to sleep during my IntentService's operation. In the hello-world it's not that important (we have no long-running operation in our service, but imagine, if you have to fetch some relatively huge files from server during this operation). Read more about Device Awake here.

    NotificationEventReceiver.java

    public class NotificationEventReceiver extends WakefulBroadcastReceiver {
    
        private static final String ACTION_START_NOTIFICATION_SERVICE = "ACTION_START_NOTIFICATION_SERVICE";
        private static final String ACTION_DELETE_NOTIFICATION = "ACTION_DELETE_NOTIFICATION";
        private static final int NOTIFICATIONS_INTERVAL_IN_HOURS = 2;
    
        public static void setupAlarm(Context context) {
            AlarmManager alarmManager = (AlarmManager) context.getSystemService(Context.ALARM_SERVICE);
            PendingIntent alarmIntent = getStartPendingIntent(context);
            alarmManager.setRepeating(AlarmManager.RTC_WAKEUP,
                    getTriggerAt(new Date()),
                    NOTIFICATIONS_INTERVAL_IN_HOURS * AlarmManager.INTERVAL_HOUR,
                    alarmIntent);
        }
    
        @Override
        public void onReceive(Context context, Intent intent) {
            String action = intent.getAction();
            Intent serviceIntent = null;
            if (ACTION_START_NOTIFICATION_SERVICE.equals(action)) {
                Log.i(getClass().getSimpleName(), "onReceive from alarm, starting notification service");
                serviceIntent = NotificationIntentService.createIntentStartNotificationService(context);
            } else if (ACTION_DELETE_NOTIFICATION.equals(action)) {
                Log.i(getClass().getSimpleName(), "onReceive delete notification action, starting notification service to handle delete");
                serviceIntent = NotificationIntentService.createIntentDeleteNotification(context);
            }
    
            if (serviceIntent != null) {
                startWakefulService(context, serviceIntent);
            }
        }
    
        private static long getTriggerAt(Date now) {
            Calendar calendar = Calendar.getInstance();
            calendar.setTime(now);
            //calendar.add(Calendar.HOUR, NOTIFICATIONS_INTERVAL_IN_HOURS);
            return calendar.getTimeInMillis();
        }
    
        private static PendingIntent getStartPendingIntent(Context context) {
            Intent intent = new Intent(context, NotificationEventReceiver.class);
            intent.setAction(ACTION_START_NOTIFICATION_SERVICE);
            return PendingIntent.getBroadcast(context, 0, intent, PendingIntent.FLAG_UPDATE_CURRENT);
        }
    
        public static PendingIntent getDeleteIntent(Context context) {
            Intent intent = new Intent(context, NotificationEventReceiver.class);
            intent.setAction(ACTION_DELETE_NOTIFICATION);
            return PendingIntent.getBroadcast(context, 0, intent, PendingIntent.FLAG_UPDATE_CURRENT);
        }
    }
    
  3. Now let's create an IntentService to actually create notifications.

    There, we specify onHandleIntent() which is responses on NotificationEventReceiver's intent we passed in startWakefulService method.

    If it's Delete action - we can log it to our analytics, for example. If it's Start notification intent - then by using NotificationCompat.Builder we're composing new notification and showing it by NotificationManager.notify. While composing notification, we are also setting pending intents for click and remove actions. Fairly Easy.

    NotificationIntentService.java

    public class NotificationIntentService extends IntentService {
    
        private static final int NOTIFICATION_ID = 1;
        private static final String ACTION_START = "ACTION_START";
        private static final String ACTION_DELETE = "ACTION_DELETE";
    
        public NotificationIntentService() {
            super(NotificationIntentService.class.getSimpleName());
        }
    
        public static Intent createIntentStartNotificationService(Context context) {
            Intent intent = new Intent(context, NotificationIntentService.class);
            intent.setAction(ACTION_START);
            return intent;
        }
    
        public static Intent createIntentDeleteNotification(Context context) {
            Intent intent = new Intent(context, NotificationIntentService.class);
            intent.setAction(ACTION_DELETE);
            return intent;
        }
    
        @Override
        protected void onHandleIntent(Intent intent) {
            Log.d(getClass().getSimpleName(), "onHandleIntent, started handling a notification event");
            try {
                String action = intent.getAction();
                if (ACTION_START.equals(action)) {
                    processStartNotification();
                }
                if (ACTION_DELETE.equals(action)) {
                    processDeleteNotification(intent);
                }
            } finally {
                WakefulBroadcastReceiver.completeWakefulIntent(intent);
            }
        }
    
        private void processDeleteNotification(Intent intent) {
            // Log something?
        }
    
        private void processStartNotification() {
            // Do something. For example, fetch fresh data from backend to create a rich notification?
    
            final NotificationCompat.Builder builder = new NotificationCompat.Builder(this);
            builder.setContentTitle("Scheduled Notification")
                    .setAutoCancel(true)
                    .setColor(getResources().getColor(R.color.colorAccent))
                    .setContentText("This notification has been triggered by Notification Service")
                    .setSmallIcon(R.drawable.notification_icon);
    
            PendingIntent pendingIntent = PendingIntent.getActivity(this,
                    NOTIFICATION_ID,
                    new Intent(this, NotificationActivity.class),
                    PendingIntent.FLAG_UPDATE_CURRENT);
            builder.setContentIntent(pendingIntent);
            builder.setDeleteIntent(NotificationEventReceiver.getDeleteIntent(this));
    
            final NotificationManager manager = (NotificationManager) this.getSystemService(Context.NOTIFICATION_SERVICE);
            manager.notify(NOTIFICATION_ID, builder.build());
        }
    }
    
  4. Almost done. Now I also add broadcast receiver for BOOT_COMPLETED, TIMEZONE_CHANGED, and TIME_SET events to re-setup my AlarmManager, once device has been rebooted or timezone has changed (For example, user flown from USA to Europe and you don't want notification to pop up in the middle of the night, but was sticky to the local time :-) ).

    NotificationServiceStarterReceiver.java

    public final class NotificationServiceStarterReceiver extends BroadcastReceiver {
    
        @Override
        public void onReceive(Context context, Intent intent) {
            NotificationEventReceiver.setupAlarm(context);
        }
    }
    
  5. We need to also register all our services, broadcast receivers in AndroidManifest:

    <?xml version="1.0" encoding="utf-8"?>
    <manifest xmlns:android="http://schemas.android.com/apk/res/android"
        package="klogi.com.notificationbyschedule">
    
        <uses-permission android:name="android.permission.INTERNET" />
        <uses-permission android:name="android.permission.ACCESS_NETWORK_STATE" />
        <uses-permission android:name="android.permission.RECEIVE_BOOT_COMPLETED" />
        <uses-permission android:name="android.permission.WAKE_LOCK" />
    
        <application
            android:allowBackup="true"
            android:icon="@mipmap/ic_launcher"
            android:label="@string/app_name"
            android:supportsRtl="true"
            android:theme="@style/AppTheme">
            <activity android:name=".MainActivity">
                <intent-filter>
                    <action android:name="android.intent.action.MAIN" />
    
                    <category android:name="android.intent.category.LAUNCHER" />
                </intent-filter>
            </activity>
    
            <service
                android:name=".notifications.NotificationIntentService"
                android:enabled="true"
                android:exported="false" />
    
            <receiver android:name=".broadcast_receivers.NotificationEventReceiver" />
            <receiver android:name=".broadcast_receivers.NotificationServiceStarterReceiver">
                <intent-filter>
                    <action android:name="android.intent.action.BOOT_COMPLETED" />
                    <action android:name="android.intent.action.TIMEZONE_CHANGED" />
                    <action android:name="android.intent.action.TIME_SET" />
                </intent-filter>
            </receiver>
    
            <activity
                android:name=".NotificationActivity"
                android:label="@string/title_activity_notification"
                android:theme="@style/AppTheme.NoActionBar"/>
        </application>
    
    </manifest>
    

That's it!

The source code for this project you can find here. I hope, you will find this post helpful.

Increase JVM max heap size for Eclipse

It is possible to increase heap size allocated by the Java Virtual Machine (JVM) by using command line options.

-Xms<size>        set initial Java heap size
-Xmx<size>        set maximum Java heap size
-Xss<size>        set java thread stack size

If you are using the tomcat server, you can change the heap size by going to Eclipse/Run/Run Configuration and select Apache Tomcat/your_server_name/Arguments and under VM arguments section use the following:

-XX:MaxPermSize=256m
-Xms256m -Xmx512M

If you are not using any server, you can type the following on the command line before you run your code:

java -Xms64m -Xmx256m HelloWorld

More information on increasing the heap size can be found here

Python timedelta in years

You need more than a timedelta to tell how many years have passed; you also need to know the beginning (or ending) date. (It's a leap year thing.)

Your best bet is to use the dateutil.relativedelta object, but that's a 3rd party module. If you want to know the datetime that was n years from some date (defaulting to right now), you can do the following::

from dateutil.relativedelta import relativedelta

def yearsago(years, from_date=None):
    if from_date is None:
        from_date = datetime.now()
    return from_date - relativedelta(years=years)

If you'd rather stick with the standard library, the answer is a little more complex::

from datetime import datetime
def yearsago(years, from_date=None):
    if from_date is None:
        from_date = datetime.now()
    try:
        return from_date.replace(year=from_date.year - years)
    except ValueError:
        # Must be 2/29!
        assert from_date.month == 2 and from_date.day == 29 # can be removed
        return from_date.replace(month=2, day=28,
                                 year=from_date.year-years)

If it's 2/29, and 18 years ago there was no 2/29, this function will return 2/28. If you'd rather return 3/1, just change the last return statement to read::

    return from_date.replace(month=3, day=1,
                             year=from_date.year-years)

Your question originally said you wanted to know how many years it's been since some date. Assuming you want an integer number of years, you can guess based on 365.25 days per year and then check using either of the yearsago functions defined above::

def num_years(begin, end=None):
    if end is None:
        end = datetime.now()
    num_years = int((end - begin).days / 365.25)
    if begin > yearsago(num_years, end):
        return num_years - 1
    else:
        return num_years

Capturing TAB key in text box

The previous answer is fine, but I'm one of those guys that's firmly against mixing behavior with presentation (putting JavaScript in my HTML) so I prefer to put my event handling logic in my JavaScript files. Additionally, not all browsers implement event (or e) the same way. You may want to do a check prior to running any logic:

document.onkeydown = TabExample;

function TabExample(evt) {
  var evt = (evt) ? evt : ((event) ? event : null);
  var tabKey = 9;
  if(evt.keyCode == tabKey) {
    // do work
  }
}

Display tooltip on Label's hover?

You can use the css-property content and attr to display the content of an attribute in an :after pseudo element. You could either use the default title attribute (which is a semantic solution), or create a custom attribute, e.g. data-title.

HTML:

<label for="male" data-title="Please, refer to Wikipedia!">Male</label>

CSS:

label[data-title]{
  position: relative;
  &:hover:after{
    font-size: 1rem;
    font-weight: normal;
    display: block;
    position: absolute;
    left: -8em;
    bottom: 2em;
    content:  attr(data-title);
    background-color: white;
    width: 20em;
    text-aling: center;
  }
}

Fastest way to check if string contains only digits

Can be about 20% faster by using just one comparison per char and for instead of foreach:

bool isDigits(string s) 
{ 
    if (s == null || s == "") return false; 

    for (int i = 0; i < s.Length; i++) 
        if ((s[i] ^ '0') > 9) 
            return false; 

    return true; 
}

Code used for testing (always profile because the results depend on hardware, versions, order, etc.):

static bool isDigitsFr(string s) { if (s == null || s == "") return false; for (int i = 0; i < s.Length; i++) if (s[i] < '0' || s[i] > '9') return false; return true; }
static bool isDigitsFu(string s) { if (s == null || s == "") return false; for (int i = 0; i < s.Length; i++) if ((uint)(s[i] - '0') > 9) return false; return true; }
static bool isDigitsFx(string s) { if (s == null || s == "") return false; for (int i = 0; i < s.Length; i++) if ((s[i] ^ '0') > 9) return false; return true; }
static bool isDigitsEr(string s) { if (s == null || s == "") return false; foreach (char c in s) if (c < '0' || c > '9') return false; return true; }
static bool isDigitsEu(string s) { if (s == null || s == "") return false; foreach (char c in s) if ((uint)(c - '0') > 9) return false; return true; }
static bool isDigitsEx(string s) { if (s == null || s == "") return false; foreach (char c in s) if ((c ^ '0') > 9) return false; return true; }
static void test()
{
    var w = new Stopwatch(); bool b; var s = int.MaxValue + ""; int r = 12345678*2; var ss = new SortedSet<string>(); //s = string.Concat(Enumerable.Range(0, 127).Select(i => ((char)i ^ '0') < 10 ? 1 : 0));
    w.Restart(); for (int i = 0; i < r; i++) b = s.All(char.IsDigit); w.Stop(); ss.Add(w.Elapsed + ".All .IsDigit"); 
    w.Restart(); for (int i = 0; i < r; i++) b = s.All(c => c >= '0' && c <= '9'); w.Stop(); ss.Add(w.Elapsed + ".All <>"); 
    w.Restart(); for (int i = 0; i < r; i++) b = s.All(c => (c ^ '0') < 10); w.Stop(); ss.Add(w.Elapsed + " .All ^"); 
    w.Restart(); for (int i = 0; i < r; i++) b = isDigitsFr(s); w.Stop(); ss.Add(w.Elapsed + " for     <>");
    w.Restart(); for (int i = 0; i < r; i++) b = isDigitsFu(s); w.Stop(); ss.Add(w.Elapsed + " for     -");
    w.Restart(); for (int i = 0; i < r; i++) b = isDigitsFx(s); w.Stop(); ss.Add(w.Elapsed + " for     ^");
    w.Restart(); for (int i = 0; i < r; i++) b = isDigitsEr(s); w.Stop(); ss.Add(w.Elapsed + " foreach <>");
    w.Restart(); for (int i = 0; i < r; i++) b = isDigitsEu(s); w.Stop(); ss.Add(w.Elapsed + " foreach -");
    w.Restart(); for (int i = 0; i < r; i++) b = isDigitsEx(s); w.Stop(); ss.Add(w.Elapsed + " foreach ^");
    MessageBox.Show(string.Join("\n", ss)); return;
}

Results on Intel i5-3470 @ 3.2GHz, VS 2015 .NET 4.6.1 Release mode and optimizations enabled:

time    method          ratio
0.7776  for     ^       1.0000 
0.7984  foreach -       1.0268 
0.8066  foreach ^       1.0372 
0.8940  for     -       1.1497 
0.8976  for     <>      1.1543 
0.9456  foreach <>      1.2160 
4.4559  .All <>         5.7303 
4.7791  .All ^          6.1458 
4.8539  .All. IsDigit   6.2421 

For anyone tempted to use the shorter methods, note that

How to correctly use the ASP.NET FileUpload control

ASP.NET controls should rather be placed in aspx markup file. That is the preferred way of working with them. So add FileUpload control to your page. Make sure it has all required attributes including ID and runat:

<asp:FileUpload ID="FileUpload1" runat="server" />

Instance of FileUpload1 will be automatically created in auto-generated/updated *.designer.cs file which is a partial class for your page. You usually do not have to care about what's in it, just assume that any control on an aspx page is automatically instantiated.

Add a button that will do the post back:

<asp:Button ID="Button1" runat="server" Text="Button" onclick="Button1_Click" />

Then go to your *.aspx.cs file where you have your code and add button click handler. In C# it looks like this:

protected void Button1_Click(object sender, EventArgs e)
{
  if (this.FileUpload1.HasFile)
  {
    this.FileUpload1.SaveAs("c:\\" + this.FileUpload1.FileName);
  }
}

And that's it. All should work as expected.

How to substring in jquery

Yes you can, although it relies on Javascript's inherent functionality and not the jQuery library.

http://www.w3schools.com/jsref/jsref_substr.asp The substr function will allow you to extract certain parts of the string.

Now, if you're looking for a specific string or character to use to find what part of the string to extract, you can make use of the indexOf function as well. http://www.w3schools.com/jsref/jsref_IndexOf.asp

The question is somewhat vague though; even just link text with 'name' will achieve the desired result. What's the criteria for getting your substring, exactly?

DeprecationWarning: Buffer() is deprecated due to security and usability issues when I move my script to another server

The use of the deprecated new Buffer() constructor (i.E. as used by Yarn) can cause deprecation warnings. Therefore one should NOT use the deprecated/unsafe Buffer constructor.

According to the deprecation warning new Buffer() should be replaced with one of:

  • Buffer.alloc()
  • Buffer.allocUnsafe() or
  • Buffer.from()

Another option in order to avoid this issue would be using the safe-buffer package instead.

You can also try (when using yarn..):

yarn global add yarn

as mentioned here: Link

Another suggestion from the comments (thx to gkiely): self-update

Note: self-update is not available. See policies for enforcing versions within a project

In order to update your version of Yarn, run

curl --compressed -o- -L https://yarnpkg.com/install.sh | bash

Fastest way to check if a string is JSON in PHP?

I found this question after coming across something similar in my work, yesterday. My solution in the end was a hybrid of some of the approaches above:

function is_JSON($string) {

  return (is_null(json_decode($string, TRUE))) ? FALSE : TRUE;

}

How can I count the occurrences of a list item?

Given an item, how can I count its occurrences in a list in Python?

Here's an example list:

>>> l = list('aaaaabbbbcccdde')
>>> l
['a', 'a', 'a', 'a', 'a', 'b', 'b', 'b', 'b', 'c', 'c', 'c', 'd', 'd', 'e']

list.count

There's the list.count method

>>> l.count('b')
4

This works fine for any list. Tuples have this method as well:

>>> t = tuple('aabbbffffff')
>>> t
('a', 'a', 'b', 'b', 'b', 'f', 'f', 'f', 'f', 'f', 'f')
>>> t.count('f')
6

collections.Counter

And then there's collections.Counter. You can dump any iterable into a Counter, not just a list, and the Counter will retain a data structure of the counts of the elements.

Usage:

>>> from collections import Counter
>>> c = Counter(l)
>>> c['b']
4

Counters are based on Python dictionaries, their keys are the elements, so the keys need to be hashable. They are basically like sets that allow redundant elements into them.

Further usage of collections.Counter

You can add or subtract with iterables from your counter:

>>> c.update(list('bbb'))
>>> c['b']
7
>>> c.subtract(list('bbb'))
>>> c['b']
4

And you can do multi-set operations with the counter as well:

>>> c2 = Counter(list('aabbxyz'))
>>> c - c2                   # set difference
Counter({'a': 3, 'c': 3, 'b': 2, 'd': 2, 'e': 1})
>>> c + c2                   # addition of all elements
Counter({'a': 7, 'b': 6, 'c': 3, 'd': 2, 'e': 1, 'y': 1, 'x': 1, 'z': 1})
>>> c | c2                   # set union
Counter({'a': 5, 'b': 4, 'c': 3, 'd': 2, 'e': 1, 'y': 1, 'x': 1, 'z': 1})
>>> c & c2                   # set intersection
Counter({'a': 2, 'b': 2})

Why not pandas?

Another answer suggests:

Why not use pandas?

Pandas is a common library, but it's not in the standard library. Adding it as a requirement is non-trivial.

There are builtin solutions for this use-case in the list object itself as well as in the standard library.

If your project does not already require pandas, it would be foolish to make it a requirement just for this functionality.

What's with the dollar sign ($"string")

String Interpolation

is a concept that languages like Perl have had for quite a while, and now we’ll get this ability in C# as well. In String Interpolation, we simply prefix the string with a $ (much like we use the @ for verbatim strings). Then, we simply surround the expressions we want to interpolate with curly braces (i.e. { and }):

It looks a lot like the String.Format() placeholders, but instead of an index, it is the expression itself inside the curly braces. In fact, it shouldn’t be a surprise that it looks like String.Format() because that’s really all it is – syntactical sugar that the compiler treats like String.Format() behind the scenes.

A great part is, the compiler now maintains the placeholders for you so you don’t have to worry about indexing the right argument because you simply place it right there in the string.

C# string interpolation is a method of concatenating,formatting and manipulating strings. This feature was introduced in C# 6.0. Using string interpolation, we can use objects and expressions as a part of the string interpolation operation.

Syntax of string interpolation starts with a ‘$’ symbol and expressions are defined within a bracket {} using the following syntax.

{<interpolatedExpression>[,<alignment>][:<formatString>]}  

Where:

  • interpolatedExpression - The expression that produces a result to be formatted
  • alignment - The constant expression whose value defines the minimum number of characters in the string representation of the result of the interpolated expression. If positive, the string representation is right-aligned; if negative, it's left-aligned.
  • formatString - A format string that is supported by the type of the expression result.

The following code example concatenates a string where an object, author as a part of the string interpolation.

string author = "Mohit";  
string hello = $"Hello {author} !";  
Console.WriteLine(hello);  // Hello Mohit !

Read more on C#/.NET Little Wonders: String Interpolation in C# 6

Correct way to detach from a container without stopping it

I consider Ashwin's answer to be the most correct, my old answer is below.


I'd like to add another option here which is to run the container as follows

docker run -dti foo bash

You can then enter the container and run bash with

docker exec -ti ID_of_foo bash

No need to install sshd :)

Click event doesn't work on dynamically generated elements

$(.surrounding_div_class).on( 'click', '.test', function () {
alert( 'WORKS!' );
});

Will only work if the DIV with the class .surrounding_div_class is the immediate parent to the object .test

If there is another object in the div that will be filled it wont work.

How to grey out a button?

Set Clickable as false and change the backgroung color as:

callButton.setClickable(false);
callButton.setBackgroundColor(Color.parseColor("#808080"));

Open multiple Projects/Folders in Visual Studio Code

Multiple Folders in VS

Click ->File ->Add Folder to Workplace.

Step 1.

enter image description here

Choose which project to work ->Add(press)

Step 2.

enter image description here

Is it possible to display inline images from html in an Android TextView?

This is what I use, which does not need you to hardcore your resource names and will look for the drawable resources first in your apps resources and then in the stock android resources if nothing was found - allowing you to use default icons and such.

private class ImageGetter implements Html.ImageGetter {

     public Drawable getDrawable(String source) {
        int id;

        id = getResources().getIdentifier(source, "drawable", getPackageName());

        if (id == 0) {
            // the drawable resource wasn't found in our package, maybe it is a stock android drawable?
            id = getResources().getIdentifier(source, "drawable", "android");
        }

        if (id == 0) {
            // prevent a crash if the resource still can't be found
            return null;    
        }
        else {
            Drawable d = getResources().getDrawable(id);
            d.setBounds(0,0,d.getIntrinsicWidth(),d.getIntrinsicHeight());
            return d;
        }
     }

 }

Which can be used as such (example):

String myHtml = "This will display an image to the right <img src='ic_menu_more' />";
myTextview.setText(Html.fromHtml(myHtml, new ImageGetter(), null);

Android how to use Environment.getExternalStorageDirectory()

Have in mind though, that getExternalStorageDirectory() is not going to work properly on some phones e.g. my Motorola razr maxx, as it has 2 cards /mnt/sdcard and /mnt/sdcard-ext - for internal and external SD cards respectfully. You will be getting the /mnt/sdcard only reply every time. Google must provide a way to deal with such a situation. As it renders many SD card aware apps (i.e card backup) failing miserably on these phones.

Detecting user leaving page with react-router

For react-router v3.x

I had the same issue where I needed a confirmation message for any unsaved change on the page. In my case, I was using React Router v3, so I could not use <Prompt />, which was introduced from React Router v4.

I handled 'back button click' and 'accidental link click' with the combination of setRouteLeaveHook and history.pushState(), and handled 'reload button' with onbeforeunload event handler.

setRouteLeaveHook (doc) & history.pushState (doc)

  • Using only setRouteLeaveHook was not enough. For some reason, the URL was changed although the page remained the same when 'back button' was clicked.

      // setRouteLeaveHook returns the unregister method
      this.unregisterRouteHook = this.props.router.setRouteLeaveHook(
        this.props.route,
        this.routerWillLeave
      );
    
      ...
    
      routerWillLeave = nextLocation => {
        // Using native 'confirm' method to show confirmation message
        const result = confirm('Unsaved work will be lost');
        if (result) {
          // navigation confirmed
          return true;
        } else {
          // navigation canceled, pushing the previous path
          window.history.pushState(null, null, this.props.route.path);
          return false;
        }
      };
    

onbeforeunload (doc)

  • It is used to handle 'accidental reload' button

    window.onbeforeunload = this.handleOnBeforeUnload;
    
    ...
    
    handleOnBeforeUnload = e => {
      const message = 'Are you sure?';
      e.returnValue = message;
      return message;
    }
    

Below is the full component that I have written

  • note that withRouter is used to have this.props.router.
  • note that this.props.route is passed down from the calling component
  • note that currentState is passed as prop to have initial state and to check any change

    import React from 'react';
    import PropTypes from 'prop-types';
    import _ from 'lodash';
    import { withRouter } from 'react-router';
    import Component from '../Component';
    import styles from './PreventRouteChange.css';
    
    class PreventRouteChange extends Component {
      constructor(props) {
        super(props);
        this.state = {
          // initialize the initial state to check any change
          initialState: _.cloneDeep(props.currentState),
          hookMounted: false
        };
      }
    
      componentDidUpdate() {
    
       // I used the library called 'lodash'
       // but you can use your own way to check any unsaved changed
        const unsaved = !_.isEqual(
          this.state.initialState,
          this.props.currentState
        );
    
        if (!unsaved && this.state.hookMounted) {
          // unregister hooks
          this.setState({ hookMounted: false });
          this.unregisterRouteHook();
          window.onbeforeunload = null;
        } else if (unsaved && !this.state.hookMounted) {
          // register hooks
          this.setState({ hookMounted: true });
          this.unregisterRouteHook = this.props.router.setRouteLeaveHook(
            this.props.route,
            this.routerWillLeave
          );
          window.onbeforeunload = this.handleOnBeforeUnload;
        }
      }
    
      componentWillUnmount() {
        // unregister onbeforeunload event handler
        window.onbeforeunload = null;
      }
    
      handleOnBeforeUnload = e => {
        const message = 'Are you sure?';
        e.returnValue = message;
        return message;
      };
    
      routerWillLeave = nextLocation => {
        const result = confirm('Unsaved work will be lost');
        if (result) {
          return true;
        } else {
          window.history.pushState(null, null, this.props.route.path);
          if (this.formStartEle) {
            this.moveTo.move(this.formStartEle);
          }
          return false;
        }
      };
    
      render() {
        return (
          <div>
            {this.props.children}
          </div>
        );
      }
    }
    
    PreventRouteChange.propTypes = propTypes;
    
    export default withRouter(PreventRouteChange);
    

Please let me know if there is any question :)

How do I draw a set of vertical lines in gnuplot?

From the Gnuplot documentation. To draw a vertical line from the bottom to the top of the graph at x=3, use:

set arrow from 3, graph 0 to 3, graph 1 nohead

How to replace local branch with remote branch entirely in Git?

That's as easy as three steps:

  1. Delete your local branch: git branch -d local_branch
  2. Fetch the latest remote branch: git fetch origin remote_branch
  3. Rebuild the local branch based on the remote one: git checkout -b local_branch origin/remote_branch

How to use multiprocessing pool.map with multiple arguments?

A better way is using decorator instead of writing wrapper function by hand. Especially when you have a lot of functions to map, decorator will save your time by avoiding writing wrapper for every function. Usually a decorated function is not picklable, however we may use functools to get around it. More disscusions can be found here.

Here the example

def unpack_args(func):
    from functools import wraps
    @wraps(func)
    def wrapper(args):
        if isinstance(args, dict):
            return func(**args)
        else:
            return func(*args)
    return wrapper

@unpack_args
def func(x, y):
    return x + y

Then you may map it with zipped arguments

np, xlist, ylist = 2, range(10), range(10)
pool = Pool(np)
res = pool.map(func, zip(xlist, ylist))
pool.close()
pool.join()

Of course, you may always use Pool.starmap in Python 3 (>=3.3) as mentioned in other answers.

How to view data saved in android database(SQLite)?

1. Download SQLite Manager
2. Go to your DDMS tab in Eclipse
3. Go to the File Explorer --> data --> data --> "Your Package Name" --> pull file from device 4. Open file in SQLite Manager.
5. View data.

BAT file: Open new cmd window and execute a command in there

You may already find your answer because it was some time ago you asked. But I tried to do something similar when coding ror. I wanted to run "rails server" in a new cmd window so I don't have to open a new cmd and then find my path again.

What I found out was to use the K switch like this:

start cmd /k echo Hello, World!

start before "cmd" will open the application in a new window and "/K" will execute "echo Hello, World!" after the new cmd is up.

You can also use the /C switch for something similar.

start cmd /C pause

This will then execute "pause" but close the window when the command is done. In this case after you pressed a button. I found this useful for "rails server", then when I shutdown my dev server I don't have to close the window after.


Use the following in your batch file:

start cmd.exe /c "more-batch-commands-here"

or

start cmd.exe /k "more-batch-commands-here"

/c Carries out the command specified by string and then terminates

/k Carries out the command specified by string but remains

The /c and /k options controls what happens once your command finishes running. With /c the terminal window will close automatically, leaving your desktop clean. With /k the terminal window will remain open. It's a good option if you want to run more commands manually afterwards.

Consult the cmd.exe documentation using cmd /? for more details.

Escaping Commands with White Spaces

The proper formatting of the command string becomes more complicated when using arguments with spaces. See the examples below. Note the nested double quotes in some examples.

Examples:

Run a program and pass a filename parameter:
CMD /c write.exe c:\docs\sample.txt

Run a program and pass a filename which contains whitespace:
CMD /c write.exe "c:\sample documents\sample.txt"

Spaces in program path:
CMD /c ""c:\Program Files\Microsoft Office\Office\Winword.exe""

Spaces in program path + parameters:
CMD /c ""c:\Program Files\demo.cmd"" Parameter1 Param2
CMD /k ""c:\batch files\demo.cmd" "Parameter 1 with space" "Parameter2 with space""

Launch demo1 and demo2:
CMD /c ""c:\Program Files\demo1.cmd" & "c:\Program Files\demo2.cmd""

Source: http://ss64.com/nt/cmd.html

Convert datatable to JSON in C#

We can accomplish the task in two simple way one is using Json.NET dll and another is by using StringBuilder class.

Using Newtonsoft Json.NET

string JSONresult;
JSONresult = JsonConvert.SerializeObject(dt);  
Response.Write(JSONresult);

Reference Link: Newtonsoft: Convert DataTable to JSON object in ASP.Net C#

Using StringBuilder

public string DataTableToJsonObj(DataTable dt)
{
    DataSet ds = new DataSet();
    ds.Merge(dt);
    StringBuilder JsonString = new StringBuilder();
    if (ds != null && ds.Tables[0].Rows.Count > 0)
    {
        JsonString.Append("[");
        for (int i = 0; i < ds.Tables[0].Rows.Count; i++)
        {
            JsonString.Append("{");
            for (int j = 0; j < ds.Tables[0].Columns.Count; j++)
            {
                if (j < ds.Tables[0].Columns.Count - 1)
                {
                    JsonString.Append("\"" + ds.Tables[0].Columns[j].ColumnName.ToString() + "\":" + "\"" + ds.Tables[0].Rows[i][j].ToString() + "\",");
                }
                else if (j == ds.Tables[0].Columns.Count - 1)
                {
                    JsonString.Append("\"" + ds.Tables[0].Columns[j].ColumnName.ToString() + "\":" + "\"" + ds.Tables[0].Rows[i][j].ToString() + "\"");
                }
            }
            if (i == ds.Tables[0].Rows.Count - 1)
            {
                JsonString.Append("}");
            }
            else
            {
                JsonString.Append("},");
            }
        }
        JsonString.Append("]");
        return JsonString.ToString();
    }
    else
    {
        return null;
    }
}

docker container ssl certificates

You can use relative path to mount the volume to container:

docker run -v `pwd`/certs:/container/path/to/certs ...

Note the back tick on the pwd which give you the present working directory. It assumes you have the certs folder in current directory that the docker run is executed. Kinda great for local development and keep the certs folder visible to your project.

python 2.7: cannot pip on windows "bash: pip: command not found"

As long as pip lives within the scripts folder you can run

python -m pip ....

This will tell python to get pip from inside the scripts folder. This is also a good way to have both python2.7 and pyhton3.5 on you computer and have them in different locations. I currently have both python2 and pyhton3 installed on windows. When I type python it defaults to python2. But if I type python3 I can use python3. (I also had to change the python.exe file for python3 to "python3.exe")If I need to install flask for python 2 I can run

python -m pip install flask

and it will be installed in the pyhton2 folder, but if I need flask for python 3 I run:

python3 -m pip install flask

and I now have it in the python3 folder

c++ integer->std::string conversion. Simple function?

Not really, in the standard. Some implementations have a nonstandard itoa() function, and you could look up Boost's lexical_cast, but if you stick to the standard it's pretty much a choice between stringstream and sprintf() (snprintf() if you've got it).

javascript pushing element at the beginning of an array

Use unshift, which modifies the existing array by adding the arguments to the beginning:

TheArray.unshift(TheNewObject);

The iOS Simulator deployment targets is set to 7.0, but the range of supported deployment target version for this platform is 8.0 to 12.1

The problem is in your pod files deployment target iOS Version not in your project deployment target iOS Version, so you need to change the deployment iOS version for your pods as well to anything higher than 8.0 to do so open your project workspace and do this:

1- Click on pods.

2- Select each project and target and click on build settings.

3- Under Deployment section change the iOS Deployment Target version to anything more than 8.0 (better to try the same project version).

4- Repeat this for every other project in your pods then run the app.

see the photo for details enter image description here

Getting Lat/Lng from Google marker

try this

var latlng = new google.maps.LatLng(51.4975941, -0.0803232);
var map = new google.maps.Map(document.getElementById('map'), {
    center: latlng,
    zoom: 11,
    mapTypeId: google.maps.MapTypeId.ROADMAP
});
var marker = new google.maps.Marker({
    position: latlng,
    map: map,
    title: 'Set lat/lon values for this property',
    draggable: true
});

google.maps.event.addListener(marker, 'dragend', function (event) {
    document.getElementById("latbox").value = this.getPosition().lat();
    document.getElementById("lngbox").value = this.getPosition().lng();
});

PHP Checking if the current date is before or after a set date

if (strtotime($date) > mktime(0,0,0)) should do the job.

Mix Razor and Javascript code

Never ever mix more languages.

<script type="text/javascript">
    var data = @Json.Encode(Model); // !!!! export data !!!!

    for(var prop in data){
      console.log( prop + " "+ data[prop]);
    }

In case of problem you can also try

@Html.Raw(Json.Encode(Model));

Request header field Access-Control-Allow-Headers is not allowed by itself in preflight response

Very good i used this on a silex project

$app->after(function (Request $request, Response $response) {
        $response->headers->set('Access-Control-Allow-Origin', '*');
        $response->headers->set("Access-Control-Allow-Credentials", "true");
        $response->headers->set("Access-Control-Allow-Methods", "GET,HEAD,OPTIONS,POST,PUT");
        $response->headers->set("Access-Control-Allow-Headers", "Origin, X-Requested-With, Content-Type, Accept, Authorization");
    });

How to remove extension from string (only real extension!)

EDIT: The smartest approach IMHO, it removes the last point and following text from a filename (aka the extension):

$name = basename($filename, '.' . end(explode('.', $filename)));

Cheers ;)

Using Python 3 in virtualenv

For those having troubles while working with Anaconda3 (Python 3).

You could use

conda create -n name_of_your_virtualenv python=python_version 

To activate the environment ( Linux, MacOS)

source activate name_of_your_virtualenv

For Windows

activate name_of_your_virtualenv

How to .gitignore all files/folder in a folder, but not the folder itself?

You can't commit empty folders in git. If you want it to show up, you need to put something in it, even just an empty file.

For example, add an empty file called .gitkeep to the folder you want to keep, then in your .gitignore file write:

# exclude everything
somefolder/*

# exception to the rule
!somefolder/.gitkeep 

Commit your .gitignore and .gitkeep files and this should resolve your issue.

How to fix itunes could not connect to the iphone because an invalid response was received from the device?

Try resetting your network settings

Settings -> General -> Reset -> Reset Network Settings

And try deleting the contents of your mac/pc lockdown folder. Here's the link, follow the steps on "Reset the Lockdown folder".

http://support.apple.com/kb/ts2529

This one worked for me.

Image size (Python, OpenCV)

I believe simply img.shape[-1::-1] would be nicer.

Redirect to specified URL on PHP script completion?

If "SOMETHING DONE" doesn't invovle any output via echo/print/etc, then:

<?php
   // SOMETHING DONE

   header('Location: http://stackoverflow.com');
?>

How do I save and restore multiple variables in python?

If you need to save multiple objects, you can simply put them in a single list, or tuple, for instance:

import pickle

# obj0, obj1, obj2 are created here...

# Saving the objects:
with open('objs.pkl', 'w') as f:  # Python 3: open(..., 'wb')
    pickle.dump([obj0, obj1, obj2], f)

# Getting back the objects:
with open('objs.pkl') as f:  # Python 3: open(..., 'rb')
    obj0, obj1, obj2 = pickle.load(f)

If you have a lot of data, you can reduce the file size by passing protocol=-1 to dump(); pickle will then use the best available protocol instead of the default historical (and more backward-compatible) protocol. In this case, the file must be opened in binary mode (wb and rb, respectively).

The binary mode should also be used with Python 3, as its default protocol produces binary (i.e. non-text) data (writing mode 'wb' and reading mode 'rb').

Add some word to all or some rows in Excel?

Insert a column, for instance a new A column. Then use this function;

="k"&B1

and copy it down.

Then you can hide the new column A if you need too.

Angular.js programmatically setting a form field to dirty

A helper function to do the job:

function setDirtyForm(form) {
    angular.forEach(form.$error, function(type) {
        angular.forEach(type, function(field) {
            field.$setDirty();
        });
    });
    return form;
}

The module was expected to contain an assembly manifest

BadImageFormatException, in my experience, is almost always to do with x86 versus x64 compiled assemblies. It sounds like your C++ assembly is compiled for x86 and you are running on an x64 process. Is that correct?

Instead of using AnyCPU/Mixed as the platform. Try to manually set it to x86 and see if it will run after that.

Hope this helps.

ASP.NET Web Api: The requested resource does not support http method 'GET'

Replace the following code in this path

Path :

App_Start => WebApiConfig.cs

Code:

config.Routes.MapHttpRoute(
            name: "DefaultApi",
            routeTemplate: "api/{controller}/{action}/{id}/{Param}",
            defaults: new { id = RouteParameter.Optional,
                            Param = RouteParameter.Optional }
                          );

Get timezone from DateTime

From the API (http://msdn.microsoft.com/en-us/library/system.datetime_members(VS.71).aspx) it does not seem it can show the name of the time zone used.

Replace multiple strings with multiple other strings

by using prototype function we can replace easily by passing object with keys and values and replacable text

_x000D_
_x000D_
String.prototype.replaceAll=function(obj,keydata='key'){
 const keys=keydata.split('key');
 return Object.entries(obj).reduce((a,[key,val])=> a.replace(`${keys[0]}${key}${keys[1]}`,val),this)
}

const data='hids dv sdc sd ${yathin} ${ok}'
console.log(data.replaceAll({yathin:12,ok:'hi'},'${key}'))
_x000D_
_x000D_
_x000D_

Java Best Practices to Prevent Cross Site Scripting

My preference is to encode all non-alphaumeric characters as HTML numeric character entities. Since almost, if not all attacks require non-alphuneric characters (like <, ", etc) this should eliminate a large chunk of dangerous output.

Format is &#N;, where N is the numeric value of the character (you can just cast the character to an int and concatenate with a string to get a decimal value). For example:

// java-ish pseudocode
StringBuffer safestrbuf = new StringBuffer(string.length()*4);
foreach(char c : string.split() ){  
  if( Character.isAlphaNumeric(c) ) safestrbuf.append(c);
  else safestrbuf.append(""+(int)symbol);

You will also need to be sure that you are encoding immediately before outputting to the browser, to avoid double-encoding, or encoding for HTML but sending to a different location.

How to disable copy/paste from/to EditText

@Zain Ali, your answer works on API 11. I just wanted to suggest a way to do in on API 10 as well. Since I had to maintain my project API on that version, I was constantly playing with the functions available in 2.3.3 and got a possibility to do it. I have share the snippet below. I tested the code and it was working for me. I did this snippet on an urgency. Feel free to improve the code if there are any changes that can be done..

// A custom TouchListener is being implemented which will clear out the focus 
// and gain the focus for the EditText, in few milliseconds so the selection 
// will be cleared and hence the copy paste option wil not pop up.
// the respective EditText should be set with this listener 
// tmpEditText.setOnTouchListener(new MyTouchListener(tmpEditText, tmpImm));

public class MyTouchListener implements View.OnTouchListener {

    long click = 0;
    EditText mEtView;
    InputMethodManager imm;

    public MyTouchListener(EditText etView, InputMethodManager im) {
        mEtView = etView;
        imm = im;
    }

    @Override
    public boolean onTouch(View v, MotionEvent event) {

        if (event.getAction() == MotionEvent.ACTION_DOWN) {
            long curr = System.currentTimeMillis();
            if (click !=0 && ( curr - click) < 30) {

                mEtView.setSelected(false);
                new Handler().postDelayed(new Runnable() {
                    @Override
                    public void run() {
                        mEtView.setSelected(true);
                        mEtView.requestFocusFromTouch();
                        imm.showSoftInput(mEtView, InputMethodManager.RESULT_SHOWN);
                    }
                },25);

            return true;
            }
            else {
                if (click == 0)
                    click = curr;
                else
                    click = 0;
                new Handler().postDelayed(new Runnable() {
                    @Override
                    public void run() {
                        mEtView.requestFocusFromTouch();
                        mEtView.requestFocusFromTouch();
                        imm.showSoftInput(mEtView, InputMethodManager.RESULT_SHOWN);
                    }
                },25);
            return true;
            }

        } else if (event.getAction() == MotionEvent.ACTION_MOVE) {
            mEtView.setSelected(false);
            new Handler().postDelayed(new Runnable() {
                @Override
                public void run() {
                    mEtView.setSelected(true);
                    mEtView.requestFocusFromTouch();
                    mEtView.requestFocusFromTouch();
                    imm.showSoftInput(mEtView, InputMethodManager.RESULT_SHOWN);
                }
            },25);
            return true;
        }
        return false;
    }

Calling startActivity() from outside of an Activity context

Intent viewIntent = new Intent(Settings.ACTION_LOCATION_SOURCE_SETTINGS);    
viewIntent.setFlags(Intent.FLAG_ACTIVITY_NEW_TASK);    
startActivity(viewIntent);   

i hope this will work.

Any reason not to use '+' to concatenate two strings?

I use the following with python 3.8

string4 = f'{string1}{string2}{string3}'

C# DataRow Empty-check

I know this has been answered already and it's an old question, but here's an extension method to do the same:

public static class DataExtensions
{
    public static bool AreAllCellsEmpty(this DataRow row)
    {
        var itemArray = row.ItemArray;
        if(itemArray==null)
            return true;
        return itemArray.All(x => string.IsNullOrWhiteSpace(x.ToString()));            
    }
}

And you use it like so:

if (dr.AreAllCellsEmpty())
// etc

Convert Month Number to Month Name Function in SQL

SELECT DATENAME(MONTH,dateadd(month, -3,getdate()))

Fatal error: Call to undefined function socket_create()

For a typical XAMPP install on windows you probably have the php_sockets.dll in your C:\xampp\php\ext directory. All you got to do is go to php.ini in the C:\xampp\php directory and change the ;extension=php_sockets.dll to extension=php_sockets.dll.

Change the icon of the exe file generated from Visual Studio 2010

Check the project properties. It's configurable there if you are using another .net windows application for example

EditText non editable

android:editable="false" should work, but it is deprecated, you should be using android:inputType="none" instead.

Alternatively, if you want to do it in the code you could do this :

EditText mEdit = (EditText) findViewById(R.id.yourid);
mEdit.setEnabled(false);

This is also a viable alternative :

EditText mEdit = (EditText) findViewById(R.id.yourid);
mEdit.setKeyListener(null);

If you're going to make your EditText non-editable, may I suggest using the TextView widget instead of the EditText, since using a EditText seems kind of pointless in that case.

EDIT: Altered some information since I've found that android:editable is deprecated, and you should use android:inputType="none", but there is a bug about it on android code; So please check this.

How to concatenate strings with padding in sqlite

SQLite has a printf function which does exactly that:

SELECT printf('%s-%.2d-%.4d', col1, col2, col3) FROM mytable

Create a new txt file using VB.NET

You can try writing into the Documents folder. Here is a "debug" function I did for the debugging needs of my project:

Private Sub writeDebug(ByVal x As String)
    Dim path As String = System.Environment.GetFolderPath(Environment.SpecialFolder.MyDocuments)
    Dim FILE_NAME As String = path & "\mydebug.txt"
    MsgBox(FILE_NAME)
    If System.IO.File.Exists(FILE_NAME) = False Then
        System.IO.File.Create(FILE_NAME).Dispose()
    End If
    Dim objWriter As New System.IO.StreamWriter(FILE_NAME, True)
    objWriter.WriteLine(x)
    objWriter.Close()
End Sub

There are more standard folders you can access through the "SpecialFolder" object.

Update Row if it Exists Else Insert Logic with Entity Framework

If you know that you're using the same context and not detaching any entities, you can make a generic version like this:

public void InsertOrUpdate<T>(T entity, DbContext db) where T : class
{
    if (db.Entry(entity).State == EntityState.Detached)
        db.Set<T>().Add(entity);

    // If an immediate save is needed, can be slow though
    // if iterating through many entities:
    db.SaveChanges(); 
}

db can of course be a class field, or the method can be made static and an extension, but this is the basics.

How can I specify the default JVM arguments for programs I run from eclipse?

As far as I know there is no option to create global configuration for java applications. You always create a duplicate of the configuration.

enter image description here

Also, if you are using PDE (for plugin development), you can create target platform using windows -> Preferences -> Plug-in development -> Target Platform. Edit has options for program/vm arguments.

Hope this helps

How to call VS Code Editor from terminal / command line

Other easyway to do it on mac is :go to Command Palette[ Shift ?+ Command (?)+P] and type :Shell Command: Install 'code' command in PATH

once installed: Shell command 'code' successfully installed in PATH.

Then you can use code from the terminal as well.

Syntax for if/else condition in SCSS mixin

You could try this:

$width:auto;
@mixin clearfix($width) {

   @if $width == 'auto' {

    // if width is not passed, or empty do this

   } @else {
        display: inline-block;
        width: $width;
   }
}

I'm not sure of your intended result, but setting a default value should return false.

Custom height Bootstrap's navbar

For Bootstrap 4, there are now spacing utilities so it's easier to change the height via padding on the nav links. This can be responsively applied only at specific breakpoints (ie: py-md-3). For example, on larger (md) screens, this nav is 120px high, then shrinks to normal height for the mobile menu. No extra CSS is needed..

<nav class="navbar navbar-fixed-top navbar-inverse bg-primary navbar-toggleable-md py-md-3">
    <button class="navbar-toggler navbar-toggler-right" type="button" data-toggle="collapse" data-target="#navbarNav" aria-expanded="false" aria-label="Toggle navigation">
        <span class="navbar-toggler-icon"></span>
    </button>
    <a class="navbar-brand" href="#">Brand</a>
    <div class="navbar-collapse collapse" id="navbarNav">
        <ul class="navbar-nav">
            <li class="nav-item py-md-3"><a href="#" class="nav-link">Home</a></li>
            <li class="nav-item py-md-3"><a href="#" class="nav-link">Link</a></li>
            <li class="nav-item py-md-3"><a href="#" class="nav-link">Link</a></li>
            <li class="nav-item py-md-3"><a href="#" class="nav-link">More</a></li>
            <li class="nav-item py-md-3"><a href="#" class="nav-link">Options</a></li>
        </ul>
    </div>
</nav>

Bootstrap 4 Navbar Height Demo

Set keyboard caret position in html textbox

The link in the answer is broken, this one should work (all credits go to blog.vishalon.net):

http://snipplr.com/view/5144/getset-cursor-in-html-textarea/

In case the code gets lost again, here are the two main functions:

function doGetCaretPosition(ctrl)
{
 var CaretPos = 0;

 if (ctrl.selectionStart || ctrl.selectionStart == 0)
 {// Standard.
  CaretPos = ctrl.selectionStart;
 }
 else if (document.selection)
 {// Legacy IE
  ctrl.focus ();
  var Sel = document.selection.createRange ();
  Sel.moveStart ('character', -ctrl.value.length);
  CaretPos = Sel.text.length;
 }

 return (CaretPos);
}


function setCaretPosition(ctrl,pos)
{
 if (ctrl.setSelectionRange)
 {
  ctrl.focus();
  ctrl.setSelectionRange(pos,pos);
 }
 else if (ctrl.createTextRange)
 {
  var range = ctrl.createTextRange();
  range.collapse(true);
  range.moveEnd('character', pos);
  range.moveStart('character', pos);
  range.select();
 }
}

"int cannot be dereferenced" in Java

As your methods an int datatype, you should use "==" instead of equals()

try replacing this if (id.equals(list[pos].getItemNumber()))

with

if (id.equals==list[pos].getItemNumber())

it will fix the error .

Boolean vs tinyint(1) for boolean values in MySQL

I am going to take a different approach here and suggest that it is just as important for your fellow developers to understand your code as it is for the compiler/database to. Using boolean may do the same thing as using tinyint, however it has the advantage of semantically conveying what your intention is, and that's worth something.

If you use a tinyint, it's not obvious that the only values you should see are 0 and 1. A boolean is ALWAYS true or false.

Removing cordova plugins from the project

When running the command: cordova plugin remove <PLUGIN NAME>, ensure that you do not add the version number to the plugin name. Just plain plugin name, for example:

cordova plugin remove cordova.plugin_name 

and not:

cordova plugin remove cordova.plugin_name 0.01 

or

cordova plugin remove "cordova.plugin_name 0.01"

In case there is a privilege issue, run with sudo if you are on a *nix system, for example:

sudo cordova plugin remove cordova.plugin_name

Then you may add --save to remove it from the config.xml file. For example:

cordova plugin remove cordova.plugin_name --save

Wait 5 seconds before executing next line

You should not just try to pause 5 seconds in javascript. It doesn't work that way. You can schedule a function of code to run 5 seconds from now, but you have to put the code that you want to run later into a function and the rest of your code after that function will continue to run immediately.

For example:

function stateChange(newState) {
    setTimeout(function(){
        if(newState == -1){alert('VIDEO HAS STOPPED');}
    }, 5000);
}

But, if you have code like this:

stateChange(-1);
console.log("Hello");

The console.log() statement will run immediately. It will not wait until after the timeout fires in the stateChange() function. You cannot just pause javascript execution for a predetermined amount of time.

Instead, any code that you want to run delays must be inside the setTimeout() callback function (or called from that function).

If you did try to "pause" by looping, then you'd essentially "hang" the Javascript interpreter for a period of time. Because Javascript runs your code in only a single thread, when you're looping nothing else can run (no other event handlers can get called). So, looping waiting for some variable to change will never work because no other code can run to change that variable.

Minimal web server using netcat

I had the same need/problem but nothing here worked for me (or I didn't understand everything), so this is my solution.

I post my minimal_http_server.sh (working with my /bin/bash (4.3.11) but not /bin/sh because of the redirection):

rm -f out
mkfifo out
trap "rm -f out" EXIT
while true
do
  cat out | nc -l 1500 > >( # parse the netcat output, to build the answer redirected to the pipe "out".
    export REQUEST=
    while read -r line
    do
      line=$(echo "$line" | tr -d '\r\n')

      if echo "$line" | grep -qE '^GET /' # if line starts with "GET /"
      then
        REQUEST=$(echo "$line" | cut -d ' ' -f2) # extract the request
      elif [ -z "$line" ] # empty line / end of request
      then
        # call a script here
        # Note: REQUEST is exported, so the script can parse it (to answer 200/403/404 status code + content)
        ./a_script.sh > out
      fi
    done
  )
done

And my a_script.sh (with your need):

#!/bin/bash

echo -e "HTTP/1.1 200 OK\r"
echo "Content-type: text/html"
echo

date

Iterating through all nodes in XML file

To iterate through all elements

XDocument xdoc = XDocument.Load("input.xml");
foreach (XElement element in xdoc.Descendants())
{
    Console.WriteLine(element.Name);
}

How to change the icon of an Android app in Eclipse?

Icon creation wizard

  • Select your project
  • Ctrl+n
  • Android Icon Set

Handle JSON Decode Error when nothing returned

If you don't mind importing the json module, then the best way to handle it is through json.JSONDecodeError (or json.decoder.JSONDecodeError as they are the same) as using default errors like ValueError could catch also other exceptions not necessarily connected to the json decode one.

from json.decoder import JSONDecodeError


try:
    qByUser = byUsrUrlObj.read()
    qUserData = json.loads(qByUser).decode('utf-8')
    questionSubjs = qUserData["all"]["questions"]
except JSONDecodeError as e:
    # do whatever you want

//EDIT (Oct 2020):

As @Jacob Lee noted in the comment, there could be the basic common TypeError raised when the JSON object is not a str, bytes, or bytearray. Your question is about JSONDecodeError, but still it is worth mentioning here as a note; to handle also this situation, but differentiate between different issues, the following could be used:

from json.decoder import JSONDecodeError


try:
    qByUser = byUsrUrlObj.read()
    qUserData = json.loads(qByUser).decode('utf-8')
    questionSubjs = qUserData["all"]["questions"]
except JSONDecodeError as e:
    # do whatever you want
except TypeError as e:
    # do whatever you want in this case

Version vs build in Xcode

The marketing release number is for the customers, called version number. It starts with 1.0 and goes up for major updates to 2.0, 3.0, for minor updates to 1.1, 1.2 and for bug fixes to 1.0.1, 1.0.2 . This number is oriented about releases and new features.

The build number is mostly the internal number of builds that have been made until then. But some use other numbers like the branch number of the repository. This number should be unique to distinguish the different nearly the same builds.

As you can see, the build number is not necessary and it is up to you which build number you want to use. So if you update your Xcode to a major version, the build field is empty. The version field may not be empty!.


To get the build number as a NSString variable:

NSString * appBuildString = [[NSBundle mainBundle] objectForInfoDictionaryKey:@"CFBundleVersion"];

To get the version number as a NSString variable:

NSString * appVersionString = [[NSBundle mainBundle] objectForInfoDictionaryKey:@"CFBundleShortVersionString"];

If you want both in one NSString:

NSString * versionBuildString = [NSString stringWithFormat:@"Version: %@ (%@)", appVersionString, appBuildString];

This is tested with Xcode Version 4.6.3 (4H1503). The build number is often written in parenthesis / braces. The build number is in hexadecimal or decimal.

buildandversion


In Xcode you can auto-increment the build number as a decimal number by placing the following in the Run script build phase in the project settings

#!/bin/bash    
buildNumber=$(/usr/libexec/PlistBuddy -c "Print CFBundleVersion" "$INFOPLIST_FILE")
buildNumber=$(($buildNumber + 1))
/usr/libexec/PlistBuddy -c "Set :CFBundleVersion $buildNumber" "$INFOPLIST_FILE"

For hexadecimal build number use this script

buildNumber=$(/usr/libexec/PlistBuddy -c "Print CFBundleVersion" "$INFOPLIST_FILE")
buildNumber=$((0x$buildNumber)) 
buildNumber=$(($buildNumber + 1)) 
buildNumber=$(printf "%X" $buildNumber)
/usr/libexec/PlistBuddy -c "Set :CFBundleVersion $buildNumber" "$INFOPLIST_FILE"

project_settings

Connect to sqlplus in a shell script and run SQL scripts

If you want to redirect the output to a log file to look for errors or something. You can do something like this.

sqlplus -s <<EOF>> LOG_FILE_NAME user/passwd@host/db
#Your SQL code
EOF

Importing a GitHub project into Eclipse

I think you need to create a branch before you can import into your local Eclipse, otherwise, there is an error leading to incapable of importing repository from Github or Bitbucket.