Programs & Examples On #Ignore files

Joining Spark dataframes on the key

inner join with scala

val joinedDataFrame = PersonDf.join(ProfileDf ,"personId")
joinedDataFrame.show

Command line .cmd/.bat script, how to get directory of running script

This is equivalent to the path of the script:

%~dp0

This uses the batch parameter extension syntax. Parameter 0 is always the script itself.

If your script is stored at C:\example\script.bat, then %~dp0 evaluates to C:\example\.

ss64.com has more information about the parameter extension syntax. Here is the relevant excerpt:

You can get the value of any parameter using a % followed by it's numerical position on the command line.

[...]

When a parameter is used to supply a filename then the following extended syntax can be applied:

[...]

%~d1 Expand %1 to a Drive letter only - C:

[...]

%~p1 Expand %1 to a Path only e.g. \utils\ this includes a trailing \ which may be interpreted as an escape character by some commands.

[...]

The modifiers above can be combined:

%~dp1 Expand %1 to a drive letter and path only

[...]

You can get the pathname of the batch script itself with %0, parameter extensions can be applied to this so %~dp0 will return the Drive and Path to the batch script e.g. W:\scripts\

Clearing Magento Log Data

After clean the logs using any of the methods described above you can also disable them in your app/etc/local.xml

...
<frontend>
<events>
 <frontend>
  <events>
    <!-- disable Mage_Log -->
    <controller_action_predispatch>
        <observers><log><type>disabled</type></log></observers>
    </controller_action_predispatch>
    <controller_action_postdispatch>
        <observers><log><type>disabled</type></log></observers>
    </controller_action_postdispatch>
    <customer_login>
      <observers>
        <log>
          <type>disabled</type>
        </log>
      </observers>
    </customer_login>
    <customer_logout>
      <observers>
        <log>
          <type>disabled</type>
        </log>
      </observers>
    </customer_logout>
    <sales_quote_save_after>
       <observers>
          <log>
              <type>disabled</type>
          </log>
        </observers>
   </sales_quote_save_after>
   <checkout_quote_destroy>
     <observers>
       <log>
         <type>disabled</type>
       </log>
     </observers>
   </checkout_quote_destroy>
</events>
</frontend>
</config>

how to read certain columns from Excel using Pandas - Python

parse_cols is deprecated, use usecols instead

that is:

df = pd.read_excel(file_loc, index_col=None, na_values=['NA'], usecols = "A,C:AA")

Convert a string to integer with decimal in Python

You could use:

s = '23.245678'
i = int(float(s))

Is HTML considered a programming language?

If you're going to say that HTML is a programming language, then you might as well include things such as word documents, as they too are based on ML, or 'Markup Language'.

So, no, HTML is a not a programming language. It is called "markup" for that reason.

Simply put--HTML defines content!

Create a date from day month and year with T-SQL

Assuming y, m, d are all int, how about:

CAST(CAST(y AS varchar) + '-' + CAST(m AS varchar) + '-' + CAST(d AS varchar) AS DATETIME)

Please see my other answer for SQL Server 2012 and above

Integer.valueOf() vs. Integer.parseInt()

Integer.valueOf() returns an Integer object, while Integer.parseInt() returns an int primitive.

How can I get date in application run by node.js?

NodeJS (and newer browsers) have a nice shortcut to get the current time in milliseconds.

var timeInMss = Date.now()

Which has a performance boost compared with

var timeInMss = new Date().getTime()

Because you do not need to create a new object.

JavaScript naming conventions

One convention I'd like to try out is naming static modules with a 'the' prefix. Check this out. When I use someone else's module, it's not easy to see how I'm supposed to use it. eg:

define(['Lightbox'],function(Lightbox) {
  var myLightbox = new Lightbox() // not sure whether this is a constructor (non-static) or not
  myLightbox.show('hello')
})

I'm thinking about trying a convention where static modules use 'the' to indicate their preexistence. Has anyone seen a better way than this? Would look like this:

define(['theLightbox'],function(theLightbox) {
  theLightbox.show('hello') // since I recognize the 'the' convention, I know it's static
})

Differences between Emacs and Vim

Vim:

  • better as a simple editor (fewer keys required for simple tasks)
  • more active scripting community - internal language: vimscript
  • one central repository of scripts, plugins, color schemes, ...
  • also extensible in python, ruby
  • can be made portable (emacs has some problems with that)

Emacs:

  • non modal by default (most of today's editors have taken this approach). Though there is evil-mode which emulates vim behavior.
  • more powerful language for extending it (elisp is a full blown language, and in emacs you can practically redefine everything; while in vim you cannot redefine build in functions of the editor. On the downside, vimscript is relatively similar to today's dynamic languages while elisp doesn't resemble pretty much anything)
  • more extendible
  • excellent support for GNU tools (the bunch of them)

Personally, I prefer vim - it is small, does what it's supposed to do, and when I wish a full blown IDE I open VS. Emacs's approach of being an editor which wants to be an IDE (or should I say, an OS), but is not quite, is IMHO, outdated. In the old days having a email client, ftp client, tetris, ... whatnot in one package (emacs) made some sense ... nowadays, it doesn't anymore.

Both are however a topic of religious discussions among the programmer and superuser community users, and in that respect, both are excellent for starting flame wars if put in contact (in the same sentence / question).

convert month from name to number

<?php
$monthNum = 5;
$monthName = date("F", mktime(0, 0, 0, $monthNum, 10));
echo $monthName; //output: May
?>

null vs empty string in Oracle

In oracle an empty varchar2 and null are treated the same, and your observations show that.

when you write:

select * from table where a = '';

its the same as writing

select * from table where a = null;

and not a is null

which will never equate to true, so never return a row. same on the insert, a NOT NULL means you cant insert a null or an empty string (which is treated as a null)

Java enum with multiple value types

First, the enum methods shouldn't be in all caps. They are methods just like other methods, with the same naming convention.

Second, what you are doing is not the best possible way to set up your enum. Instead of using an array of values for the values, you should use separate variables for each value. You can then implement the constructor like you would any other class.

Here's how you should do it with all the suggestions above:

public enum States {
    ...
    MASSACHUSETTS("Massachusetts",  "MA",   true),
    MICHIGAN     ("Michigan",       "MI",   false),
    ...; // all 50 of those

    private final String full;
    private final String abbr;
    private final boolean originalColony;

    private States(String full, String abbr, boolean originalColony) {
        this.full = full;
        this.abbr = abbr;
        this.originalColony = originalColony;
    }

    public String getFullName() {
        return full;
    }

    public String getAbbreviatedName() {
        return abbr;
    }

    public boolean isOriginalColony(){
        return originalColony;
    }
}

How to disable mouse right click on a web page?

Please do not do that, it is very annoying.

The right menu is there for a reason, and it should be left there. Many browser extensions add entries to the right click menu and the user should be able to use it in any page he visits.

Moreover you can use all of the functionality of the right click menu in other ways (keyboard shortcuts, browser menu etc etc etc) so blocking the right click menu has the only effect of annoying the user.

PS: If really you cannot resist the urge to block it at least do not put a popup saying "no right click allowed".

Remove a modified file from pull request

Switch to the branch from which you created the pull request:

$ git checkout pull-request-branch

Overwrite the modified file(s) with the file in another branch, let's consider it's master:

git checkout origin/master -- src/main/java/HelloWorld.java

Commit and push it to the remote:

git commit -m "Removed a modified file from pull request"
git push origin pull-request-branch

How to get local server host and port in Spring Boot?

IP Address

You can get network interfaces with NetworkInterface.getNetworkInterfaces(), then the IP addresses off the NetworkInterface objects returned with .getInetAddresses(), then the string representation of those addresses with .getHostAddress().

Port

If you make a @Configuration class which implements ApplicationListener<EmbeddedServletContainerInitializedEvent>, you can override onApplicationEvent to get the port number once it's set.

@Override
public void onApplicationEvent(EmbeddedServletContainerInitializedEvent event) {
    int port = event.getEmbeddedServletContainer().getPort();
}

How to convert a Bitmap to Drawable in android?

here's another one:

Drawable drawable = RoundedBitmapDrawableFactory.create(context.getResources(), bitmap);

What are the most useful Intellij IDEA keyboard shortcuts?

Some of the time savers:

  1. Alt + Enter : show intention actions (like Eclipse quick fix)
  2. Ctrl + Alt + V : introduce variable (never type the left hand side of an assignment again)
  3. Ctrl + Shift + Space : smart completion ( even two levels down since IntelliJ 8 )
  4. Ctrl + W : select succesively increasing code blocks. Kind of obvious but a real time saver!

The Canoo blog contains some (+8) articles on some more advanced IntelliJ keyboard shortcuts.

The Key Promoter and Shortcut keys list plugins are really helpful for (constantly) learning new IntelliJ keyboard shortcuts.

What is the difference between C++ and Visual C++?

C++ is a programming language and Visual C++ is an IDE for developing with languages such as C and C++.

VC++ contains tools for, amongst others, developing against the .net framework and the Windows API.

Android: adbd cannot run as root in production builds

You have to grant the Superuser right to the shell app (com.anroid.shell). In my case, I use Magisk to root my phone Nexsus 6P (Oreo 8.1). So I can grant Superuser right in the Magisk Manager app, whih is in the left upper option menu.

Enumerations on PHP

Now you can use The SplEnum class to build it natively. As per the official documentation.

SplEnum gives the ability to emulate and create enumeration objects natively in PHP.

<?php
class Month extends SplEnum {
    const __default = self::January;

    const January = 1;
    const February = 2;
    const March = 3;
    const April = 4;
    const May = 5;
    const June = 6;
    const July = 7;
    const August = 8;
    const September = 9;
    const October = 10;
    const November = 11;
    const December = 12;
}

echo new Month(Month::June) . PHP_EOL;

try {
    new Month(13);
} catch (UnexpectedValueException $uve) {
    echo $uve->getMessage() . PHP_EOL;
}
?>

Please note, it's an extension which has to be installed, but not available by default. Which comes under Special Types described in the php website itself. The above example is taken from the PHP site.

Right way to write JSON deserializer in Spring or extend it

I've searched a lot and the best way I've found so far is on this article:

Class to serialize

package net.sghill.example;

import net.sghill.example.UserDeserializer
import net.sghill.example.UserSerializer
import org.codehaus.jackson.map.annotate.JsonDeserialize;
import org.codehaus.jackson.map.annotate.JsonSerialize;

@JsonDeserialize(using = UserDeserializer.class)
public class User {
    private ObjectId id;
    private String   username;
    private String   password;

    public User(ObjectId id, String username, String password) {
        this.id = id;
        this.username = username;
        this.password = password;
    }

    public ObjectId getId()       { return id; }
    public String   getUsername() { return username; }
    public String   getPassword() { return password; }
}

Deserializer class

package net.sghill.example;

import net.sghill.example.User;
import org.codehaus.jackson.JsonNode;
import org.codehaus.jackson.JsonParser;
import org.codehaus.jackson.ObjectCodec;
import org.codehaus.jackson.map.DeserializationContext;
import org.codehaus.jackson.map.JsonDeserializer;

import java.io.IOException;

public class UserDeserializer extends JsonDeserializer<User> {

    @Override
    public User deserialize(JsonParser jsonParser, DeserializationContext deserializationContext) throws IOException {
        ObjectCodec oc = jsonParser.getCodec();
        JsonNode node = oc.readTree(jsonParser);
        return new User(null, node.get("username").getTextValue(), node.get("password").getTextValue());
    }
}

Edit: Alternatively you can look at this article which uses new versions of com.fasterxml.jackson.databind.JsonDeserializer.

Display special characters when using print statement

Do you merely want to print the string that way, or do you want that to be the internal representation of the string? If the latter, create it as a raw string by prefixing it with r: r"Hello\tWorld\nHello World".

>>> a = r"Hello\tWorld\nHello World"
>>> a # in the interpreter, this calls repr()
'Hello\\tWorld\\nHello World'
>>> print a
Hello\tWorld\nHello World

Also, \s is not an escape character, except in regular expressions, and then it still has a much different meaning than what you're using it for.

Ignore 'Security Warning' running script from command line

I made this powershell script to unblock all files on a share on my server

Get-ChildItem "\\ServerName\e$\MyDirectory\" -Recurse -File | % {
       Unblock-File -Path $_.FullName
}

How can I fix MySQL error #1064?

TL;DR

Error #1064 means that MySQL can't understand your command. To fix it:

  • Read the error message. It tells you exactly where in your command MySQL got confused.

  • Examine your command. If you use a programming language to create your command, use echo, console.log(), or its equivalent to show the entire command so you can see it.

  • Check the manual. By comparing against what MySQL expected at that point, the problem is often obvious.

  • Check for reserved words. If the error occurred on an object identifier, check that it isn't a reserved word (and, if it is, ensure that it's properly quoted).

  1. Aaaagh!! What does #1064 mean?

    Error messages may look like gobbledygook, but they're (often) incredibly informative and provide sufficient detail to pinpoint what went wrong. By understanding exactly what MySQL is telling you, you can arm yourself to fix any problem of this sort in the future.

    As in many programs, MySQL errors are coded according to the type of problem that occurred. Error #1064 is a syntax error.

    • What is this "syntax" of which you speak? Is it witchcraft?

      Whilst "syntax" is a word that many programmers only encounter in the context of computers, it is in fact borrowed from wider linguistics. It refers to sentence structure: i.e. the rules of grammar; or, in other words, the rules that define what constitutes a valid sentence within the language.

      For example, the following English sentence contains a syntax error (because the indefinite article "a" must always precede a noun):

      This sentence contains syntax error a.

    • What does that have to do with MySQL?

      Whenever one issues a command to a computer, one of the very first things that it must do is "parse" that command in order to make sense of it. A "syntax error" means that the parser is unable to understand what is being asked because it does not constitute a valid command within the language: in other words, the command violates the grammar of the programming language.

      It's important to note that the computer must understand the command before it can do anything with it. Because there is a syntax error, MySQL has no idea what one is after and therefore gives up before it even looks at the database and therefore the schema or table contents are not relevant.

  2. How do I fix it?

    Obviously, one needs to determine how it is that the command violates MySQL's grammar. This may sound pretty impenetrable, but MySQL is trying really hard to help us here. All we need to do is…

    • Read the message!

      MySQL not only tells us exactly where the parser encountered the syntax error, but also makes a suggestion for fixing it. For example, consider the following SQL command:

      UPDATE my_table WHERE id=101 SET name='foo'
      

      That command yields the following error message:

      ERROR 1064 (42000): You have an error in your SQL syntax; check the manual that corresponds to your MySQL server version for the right syntax to use near 'WHERE id=101 SET name='foo'' at line 1

      MySQL is telling us that everything seemed fine up to the word WHERE, but then a problem was encountered. In other words, it wasn't expecting to encounter WHERE at that point.

      Messages that say ...near '' at line... simply mean that the end of command was encountered unexpectedly: that is, something else should appear before the command ends.

    • Examine the actual text of your command!

      Programmers often create SQL commands using a programming language. For example a php program might have a (wrong) line like this:

      $result = $mysqli->query("UPDATE " . $tablename ."SET name='foo' WHERE id=101");
      

      If you write this this in two lines

      $query = "UPDATE " . $tablename ."SET name='foo' WHERE id=101"
      $result = $mysqli->query($query);
      

      then you can add echo $query; or var_dump($query) to see that the query actually says

      UPDATE userSET name='foo' WHERE id=101
      

      Often you'll see your error immediately and be able to fix it.

    • Obey orders!

      MySQL is also recommending that we "check the manual that corresponds to our MySQL version for the right syntax to use". Let's do that.

      I'm using MySQL v5.6, so I'll turn to that version's manual entry for an UPDATE command. The very first thing on the page is the command's grammar (this is true for every command):

      UPDATE [LOW_PRIORITY] [IGNORE] table_reference
          SET col_name1={expr1|DEFAULT} [, col_name2={expr2|DEFAULT}] ...
          [WHERE where_condition]
          [ORDER BY ...]
          [LIMIT row_count]
      

      The manual explains how to interpret this syntax under Typographical and Syntax Conventions, but for our purposes it's enough to recognise that: clauses contained within square brackets [ and ] are optional; vertical bars | indicate alternatives; and ellipses ... denote either an omission for brevity, or that the preceding clause may be repeated.

      We already know that the parser believed everything in our command was okay prior to the WHERE keyword, or in other words up to and including the table reference. Looking at the grammar, we see that table_reference must be followed by the SET keyword: whereas in our command it was actually followed by the WHERE keyword. This explains why the parser reports that a problem was encountered at that point.

    A note of reservation

    Of course, this was a simple example. However, by following the two steps outlined above (i.e. observing exactly where in the command the parser found the grammar to be violated and comparing against the manual's description of what was expected at that point), virtually every syntax error can be readily identified.

    I say "virtually all", because there's a small class of problems that aren't quite so easy to spot—and that is where the parser believes that the language element encountered means one thing whereas you intend it to mean another. Take the following example:

    UPDATE my_table SET where='foo'
    

    Again, the parser does not expect to encounter WHERE at this point and so will raise a similar syntax error—but you hadn't intended for that where to be an SQL keyword: you had intended for it to identify a column for updating! However, as documented under Schema Object Names:

    If an identifier contains special characters or is a reserved word, you must quote it whenever you refer to it. (Exception: A reserved word that follows a period in a qualified name must be an identifier, so it need not be quoted.) Reserved words are listed at Section 9.3, “Keywords and Reserved Words”.

    [ deletia ]

    The identifier quote character is the backtick (“`”):

    mysql> SELECT * FROM `select` WHERE `select`.id > 100;

    If the ANSI_QUOTES SQL mode is enabled, it is also permissible to quote identifiers within double quotation marks:

    mysql> CREATE TABLE "test" (col INT);
    ERROR 1064: You have an error in your SQL syntax...
    mysql> SET sql_mode='ANSI_QUOTES';
    mysql> CREATE TABLE "test" (col INT);
    Query OK, 0 rows affected (0.00 sec)

Key error when selecting columns in pandas dataframe after read_csv

use sep='\s*,\s*' so that you will take care of spaces in column-names:

transactions = pd.read_csv('transactions.csv', sep=r'\s*,\s*',
                           header=0, encoding='ascii', engine='python')

alternatively you can make sure that you don't have unquoted spaces in your CSV file and use your command (unchanged)

prove:

print(transactions.columns.tolist())

Output:

['product_id', 'customer_id', 'store_id', 'promotion_id', 'month_of_year', 'quarter', 'the_year', 'store_sales', 'store_cost', 'unit_sales', 'fact_count']

changing the owner of folder in linux

Use chown to change ownership and chmod to change rights.

use the -R option to apply the rights for all files inside of a directory too.

Note that both these commands just work for directories too. The -R option makes them also change the permissions for all files and directories inside of the directory.

For example

sudo chown -R username:group directory

will change ownership (both user and group) of all files and directories inside of directory and directory itself.

sudo chown username:group directory

will only change the permission of the folder directory but will leave the files and folders inside the directory alone.

you need to use sudo to change the ownership from root to yourself.

Edit:

Note that if you use chown user: file (Note the left-out group), it will use the default group for that user.

Also You can change the group ownership of a file or directory with the command:

chgrp group_name file/directory_name

You must be a member of the group to which you are changing ownership to.

You can find group of file as follows

# ls -l file
-rw-r--r-- 1 root family 0 2012-05-22 20:03 file

# chown sujit:friends file

User 500 is just a normal user. Typically user 500 was the first user on the system, recent changes (to /etc/login.defs) has altered the minimum user id to 1000 in many distributions, so typically 1000 is now the first (non root) user.

What you may be seeing is a system which has been upgraded from the old state to the new state and still has some processes knocking about on uid 500. You can likely change it by first checking if your distro should indeed now use 1000, and if so alter the login.defs file yourself, the renumber the user account in /etc/passwd and chown/chgrp all their files, usually in /home/, then reboot.

But in answer to your question, no, you should not really be worried about this in all likelihood. It'll be showing as "500" instead of a username because o user in /etc/passwd has a uid set of 500, that's all.

Also you can show your current numbers using id i'm willing to bet it comes back as 1000 for you.

How do I find out which keystore was used to sign an app?

You can do this with the apksigner tool that is part of the Android SDK:

apksigner verify --print-certs my_app.apk

You can find apksigner inside the build-tools directory. For example: ~/Library/Android/sdk/build-tools/29.0.1/apksigner

How to encrypt and decrypt file in Android?

I had a similar problem and for encrypt/decrypt i came up with this solution:

public static byte[] generateKey(String password) throws Exception
{
    byte[] keyStart = password.getBytes("UTF-8");

    KeyGenerator kgen = KeyGenerator.getInstance("AES");
    SecureRandom sr = SecureRandom.getInstance("SHA1PRNG", "Crypto");
    sr.setSeed(keyStart);
    kgen.init(128, sr);
    SecretKey skey = kgen.generateKey();
    return skey.getEncoded();
}

public static byte[] encodeFile(byte[] key, byte[] fileData) throws Exception
{

    SecretKeySpec skeySpec = new SecretKeySpec(key, "AES");
    Cipher cipher = Cipher.getInstance("AES");
    cipher.init(Cipher.ENCRYPT_MODE, skeySpec);
    byte[] encrypted = cipher.doFinal(fileData);

    return encrypted;
}

public static byte[] decodeFile(byte[] key, byte[] fileData) throws Exception
{
    SecretKeySpec skeySpec = new SecretKeySpec(key, "AES");
    Cipher cipher = Cipher.getInstance("AES");
    cipher.init(Cipher.DECRYPT_MODE, skeySpec);

    byte[] decrypted = cipher.doFinal(fileData);

    return decrypted;
}

To save a encrypted file to sd do:

File file = new File(Environment.getExternalStorageDirectory() + File.separator + "your_folder_on_sd", "file_name");
BufferedOutputStream bos = new BufferedOutputStream(new FileOutputStream(file));
byte[] yourKey = generateKey("password");
byte[] filesBytes = encodeFile(yourKey, yourByteArrayContainigDataToEncrypt);
bos.write(fileBytes);
bos.flush();
bos.close();

To decode a file use:

byte[] yourKey = generateKey("password");
byte[] decodedData = decodeFile(yourKey, bytesOfYourFile);

For reading in a file to a byte Array there a different way out there. A Example: http://examples.javacodegeeks.com/core-java/io/fileinputstream/read-file-in-byte-array-with-fileinputstream/

Return string Input with parse.string

If you're really bent upon converting Integer to String value, I suggest use String.valueOf(YourIntegerVariable). More details can be found at: http://www.tutorialspoint.com/java/java_string_valueof.htm

.NET End vs Form.Close() vs Application.Exit Cleaner way to close one's app

Form.Close() is use to close an instance of a Form with in .NET application it does not kill the entire application. Application.exit() kills your application.

Does Go have "if x in" construct similar to Python?

Just had similar question and decided to try out some of the suggestions in this thread.

I've benchmarked best and worst case scenarios of 3 types of lookup:

  • using a map
  • using a list
  • using a switch statement

here's the function code:

func belongsToMap(lookup string) bool {
list := map[string]bool{
    "900898296857": true,
    "900898302052": true,
    "900898296492": true,
    "900898296850": true,
    "900898296703": true,
    "900898296633": true,
    "900898296613": true,
    "900898296615": true,
    "900898296620": true,
    "900898296636": true,
}
if _, ok := list[lookup]; ok {
    return true
} else {
    return false
}
}


func belongsToList(lookup string) bool {
list := []string{
    "900898296857",
    "900898302052",
    "900898296492",
    "900898296850",
    "900898296703",
    "900898296633",
    "900898296613",
    "900898296615",
    "900898296620",
    "900898296636",
}
for _, val := range list {
    if val == lookup {
        return true
    }
}
return false
}

func belongsToSwitch(lookup string) bool {
switch lookup {
case
    "900898296857",
    "900898302052",
    "900898296492",
    "900898296850",
    "900898296703",
    "900898296633",
    "900898296613",
    "900898296615",
    "900898296620",
    "900898296636":
    return true
}
return false
}

best case scenarios pick the first item in lists, worst case ones use nonexistant value.

here are the results:

BenchmarkBelongsToMapWorstCase-4 2000000 787 ns/op BenchmarkBelongsToSwitchWorstCase-4 2000000000 0.35 ns/op BenchmarkBelongsToListWorstCase-4 100000000 14.7 ns/op BenchmarkBelongsToMapBestCase-4 2000000 683 ns/op BenchmarkBelongsToSwitchBestCase-4 100000000 10.6 ns/op BenchmarkBelongsToListBestCase-4 100000000 10.4 ns/op

Switch wins all the way, worst case is surpassingly quicker than best case. Maps are the worst and list is closer to switch.

So the moral is: If you have a static, reasonably small list, switch statement is the way to go.

How can I schedule a job to run a SQL query daily?

I made an animated GIF of the steps in the accepted answer. This is from MSSQL Server 2012

Schedule SQL Job

Android ADB stop application command like "force-stop" for non rooted device

The first way
Needs root

Use kill:

adb shell ps => Will list all running processes on the device and their process ids
adb shell kill <PID> => Instead of <PID> use process id of your application

The second way
In Eclipse open DDMS perspective.
In Devices view you will find all running processes.
Choose the process and click on Stop.

enter image description here

The third way
It will kill only background process of an application.

adb shell am kill [options] <PACKAGE> => Kill all processes associated with (the app's package name). This command kills only processes that are safe to kill and that will not impact the user experience.
Options are:

--user | all | current: Specify user whose processes to kill; all users if not specified.

The fourth way
Needs root

adb shell pm disable <PACKAGE> => Disable the given package or component (written as "package/class").

The fifth way
Note that run-as is only supported for apps that are signed with debug keys.

run-as <package-name> kill <pid>

The sixth way
Introduced in Honeycomb

adb shell am force-stop <PACKAGE> => Force stop everything associated with (the app's package name).

P.S.: I know that the sixth method didn't work for you, but I think that it's important to add this method to the list, so everyone will know it.

Parsing CSV / tab-delimited txt file with Python

Although there is nothing wrong with the other solutions presented, you could simplify and greatly escalate your solutions by using python's excellent library pandas.

Pandas is a library for handling data in Python, preferred by many Data Scientists.

Pandas has a simplified CSV interface to read and parse files, that can be used to return a list of dictionaries, each containing a single line of the file. The keys will be the column names, and the values will be the ones in each cell.

In your case:

    import pandas

    def create_dictionary(filename):
        my_data = pandas.DataFrame.from_csv(filename, sep='\t', index_col=False)
        # Here you can delete the dataframe columns you don't want!
        del my_data['B']
        del my_data['D']
        # ...
        # Now you transform the DataFrame to a list of dictionaries
        list_of_dicts = [item for item in my_data.T.to_dict().values()]
        return list_of_dicts

# Usage:
x = create_dictionary("myfile.csv")

How to require a controller in an angularjs directive

There is a good stackoverflow answer here by Mark Rajcok:

AngularJS directive controllers requiring parent directive controllers?

with a link to this very clear jsFiddle: http://jsfiddle.net/mrajcok/StXFK/

<div ng-controller="MyCtrl">
    <div screen>
        <div component>
            <div widget>
                <button ng-click="widgetIt()">Woo Hoo</button>
            </div>
        </div>
    </div>
</div>

JavaScript

var myApp = angular.module('myApp',[])

.directive('screen', function() {
    return {
        scope: true,
        controller: function() {
            this.doSomethingScreeny = function() {
                alert("screeny!");
            }
        }
    }
})

.directive('component', function() {
    return {
        scope: true,
        require: '^screen',
        controller: function($scope) {
            this.componentFunction = function() {
                $scope.screenCtrl.doSomethingScreeny();
            }
        },
        link: function(scope, element, attrs, screenCtrl) {
            scope.screenCtrl = screenCtrl
        }
    }
})

.directive('widget', function() {
    return {
        scope: true,
        require: "^component",
        link: function(scope, element, attrs, componentCtrl) {
            scope.widgetIt = function() {
                componentCtrl.componentFunction();
            };
        }
    }
})


//myApp.directive('myDirective', function() {});
//myApp.factory('myService', function() {});

function MyCtrl($scope) {
    $scope.name = 'Superhero';
}

Converting JSONarray to ArrayList

I have fast solution. Just create a file ArrayUtil.java

ObjectMapper mapper = new ObjectMapper(); 
List<Student> list = Arrays.asList(mapper.readValue(jsonString, Student[].class));

Usage:

ArrayList<Object> list = ArrayUtil.convert(jArray);

or

JSONArray jArr = ArrayUtil.convert(list);

Run AVD Emulator without Android Studio

For Linux/Ubuntu

Create a new File from Terminal as

gedit emulator.sh (Use any Name for file here i have used "emulator")

now write following lines in this file

cd /home/userName/Android/Sdk/tools/

./emulator @your created Android device Name

(here after @ write the name of your AVD e.g

./emulator @Nexus_5X_API_27 )

Now save the file and run your emulator using following commands

./emulator.sh

In case of Permission denied use following command before above command

chmod +x emulator.sh

All set Go..

Adding space/padding to a UILabel

My solution is similar to what people answered but adds sizeThatFits to help UIKit to figure out the right size.

class InsetLabel : UILabel {
@objc var textInsets: UIEdgeInsets = .zero

override func drawText(in rect: CGRect) {
    super.drawText(in: rect.inset(by: textInsets))
}

override func sizeThatFits(_ size: CGSize) -> CGSize {
    var s = super.sizeThatFits(CGSize(width: size.width - (textInsets.left + textInsets.right), height: size.height - (textInsets.top + textInsets.bottom)))
    s.height += textInsets.top + textInsets.bottom
    return s
}
}

CORS error :Request header field Authorization is not allowed by Access-Control-Allow-Headers in preflight response

If you don't want to install the cors library and instead want to fix your original code, the other step you are missing is that Access-Control-Allow-Origin:* is wrong. When passing Authentication tokens (e.g. JWT) then you must explicitly state every url that is calling your server. You can't use "*" when doing authentication tokens.

What does the "assert" keyword do?

Assert does throw an AssertionError if you run your app with assertions turned on.

int a = 42;
assert a >= 0 && d <= 10;

If you run this with, say: java -ea -jar peiska.jar

It shall throw an java.lang.AssertionError

Maximum length for MySQL type text

Type       | Approx. Length     | Exact Max. Length Allowed
-----------------------------------------------------------
TINYTEXT   | 256 Bytes          |           255 characters
TEXT       |  64 Kilobytes      |        65,535 characters
MEDIUMTEXT |  16 Megabytes      |    16,777,215 characters
LONGTEXT   |   4 Gigabytes      | 4,294,967,295 characters

Basically, it's like:

"Exact Max. Length Allowed" = "Approx. Length" in bytes - 1

Note: If using multibyte characters (like Arabic, where each Arabic character takes 2 bytes), the column "Exact Max. Length Allowed" for TINYTEXT can hold be up to 127 Arabic characters (Note: space, dash, underscore, and other such characters, are 1-byte characters).

How to convert Observable<any> to array[]

You will need to subscribe to your observables:

this.CountryService.GetCountries()
    .subscribe(countries => {
        this.myGridOptions.rowData = countries as CountryData[]
    })

And, in your html, wherever needed, you can pass the async pipe to it.

How to clear an ImageView in Android?

As kwasi wrote and golu edited, you can use transparent, instead of white:

File drawable/transparent.xml

<?xml version="1.0" encoding="utf-8"?>
<shape xmlns:android="http://schemas.android.com/apk/res/android" >
    <solid android:color="@android:color/transparent"/>
</shape>

Inside an activity, view, etc:

view.setImageResource(R.drawable.transparent);

ShowAllData method of Worksheet class failed

I have just experienced the same problem. After some trial-and-error I discovered that if the selection was to the right of my filter area AND the number of shown records was zero, ShowAllData would fail.

A little more context is probably relevant. I have a number of sheets, each with a filter. I would like to set up some standard filters on all sheets, therefore I use some VBA like this

Sheets("Server").Select
col = Range("1:1").Find("In Selected SLA").Column
ActiveSheet.ListObjects("Srv").Range.AutoFilter Field:=col, Criteria1:="TRUE"

This code will adjust the filter on the column with heading "In Selected SLA", and leave all other filters unchanged. This has the unfortunate side effect that I can create a filter that shows zero records. This is not possible using the UI alone.

To avoid that situation, I would like to reset all filters before I apply the filtering above. My reset code looked like this

Sheets("Server").Select
If ActiveSheet.FilterMode Then ActiveSheet.ShowAllData

Note how I did not move the selected cell. If the selection was to the right, it would not remove filters, thus letting the filter code build a zero-row filter. The second time the code is run (on a zero-row filter) ShowAllData will fail.

The workaround is simple: Move the selection inside the filter columns before calling ShowAllData

Application.Goto (Sheets("Server").Range("A1"))
If ActiveSheet.FilterMode Then ActiveSheet.ShowAllData

This was on Excel version 14.0.7128.5000 (32-bit) = Office 2010

How to randomize two ArrayLists in the same fashion?

You can create an array containing the numbers 0 to 5 and shuffle those. Then use the result as a mapping of "oldIndex -> newIndex" and apply this mapping to both your original arrays.

How to select rows with NaN in particular column?

@qbzenker provided the most idiomatic method IMO

Here are a few alternatives:

In [28]: df.query('Col2 != Col2') # Using the fact that: np.nan != np.nan
Out[28]:
   Col1  Col2  Col3
1     0   NaN   0.0

In [29]: df[np.isnan(df.Col2)]
Out[29]:
   Col1  Col2  Col3
1     0   NaN   0.0

How do I fix "Expected to return a value at the end of arrow function" warning?

The warning indicates that you're not returning something at the end of your map arrow function in every case.

A better approach to what you're trying to accomplish is first using a .filter and then a .map, like this:

this.props.comments
  .filter(commentReply => commentReply.replyTo === comment.id)
  .map((commentReply, idx) => <CommentItem key={idx} className="SubComment"/>);

How to fix Ora-01427 single-row subquery returns more than one row in select?

(SELECT C.I_WORKDATE
         FROM T_COMPENSATION C
         WHERE C.I_COMPENSATEDDATE = A.I_REQDATE AND ROWNUM <= 1
         AND C.I_EMPID = A.I_EMPID)

How to change button text or link text in JavaScript?

document.getElementById(button_id).innerHTML = 'Lock';

Run script with rc.local: script works, but not at boot

1 Do not recommend using root to run the apps such as node app.

Well you can do it but may catch more exceptions.

2 The rc.local normally runs as root user.

So if the your script should runs as another user such as www U should make sure the PATH and other environment is ok.

3 I find a easy way to run a service as a user:

sudo -u www -i /the/path/of/your/script

Please prefer the sudo manual~ -i [command] The -i (simulate initial login) option runs the shell specified by the password database entry of the target user as a loginshell...

How to generate a random number between 0 and 1?

double r2()
{
   return (rand() % 10001) / 10000.0;
}

Reload child component when variables on parent component changes. Angular2

On Angular to update a component including its template, there is a straight forward solution to this, having an @Input property on your ChildComponent and add to your @Component decorator changeDetection: ChangeDetectionStrategy.OnPush as follows:

import { ChangeDetectionStrategy } from '@angular/core';

@Component({
    selector: 'master',
    templateUrl: templateUrl,
    styleUrls:[styleUrl1],
    changeDetection: ChangeDetectionStrategy.OnPush    
})

export class ChildComponent{
  @Input() data: MyData;
}

This will do all the work of check if Input data have changed and re-render the component

Explaining the 'find -mtime' command

+1 means 2 days ago. It's rounded.

Detect IF hovering over element with jQuery

Use:

var hovered = $("#parent").find("#element:hover").length;

jQuery 1.9+

How to merge every two lines into one from the command line?

perl -0pE 's{^KEY.*?\K\s+(\d+)$}{ $1}msg;' data.txt > data_merged-lines.txt

-0 gobbles the whole file instead of reading it line-by-line;
pE wraps code with loop and prints the output, see details in http://perldoc.perl.org/perlrun.html;
^KEY match "KEY" in the beginning of line, followed by non-greedy match of anything (.*?) before sequence of

  1. one or more spaces \s+ of any kind including line breaks;
  2. one or more digit (\d+) which we capture and later re-insert as $1;

followed by the end of line $.

\K conveniently excludes everything on its left hand side from substitution so { $1} replaces only 1-2 sequence, see http://perldoc.perl.org/perlre.html.

How do I install opencv using pip?

if you are using Pycharm navigate settings > Project:name > Project interpreter just search the module by name(in this case OpenCV-python) and install it. worked for me

How do I read the first line of a file using cat?

You dont need any external command if you have bash v4+

< file.txt mapfile -n1 && echo ${MAPFILE[0]}

or if you really want cat

cat file.txt | mapfile -n1 && echo ${MAPFILE[0]}

:)

HTML tag <a> want to add both href and onclick working

Use ng-click in place of onclick. and its as simple as that:

<a href="www.mysite.com" ng-click="return theFunction();">Item</a>

<script type="text/javascript">
function theFunction () {
    // return true or false, depending on whether you want to allow 
    // the`href` property to follow through or not
 }
</script>

How to use npm with ASP.NET Core

enter image description here

  • Using npm for managing client-side libraries is a good choice (as opposed to Bower or NuGet), you're thinking in the right direction :)
  • Split server-side (ASP.NET Core) and client-side (e.g. Angular 2, Ember, React) projects into separate folders (otherwise your ASP.NET project may have lots of noise - unit tests for the client-side code, node_modules folder, build artifacts, etc.). Front-end developers working in the same team with you will thank you for that :)
  • Restore npm modules at the solution level (similarly how you restore packages via NuGet - not into the project's folder), this way you can have unit and integration tests in a separate folder as well (as opposed to having client-side JavaScript tests inside your ASP.NET Core project).
  • Use might not need FileServer, having StaticFiles should suffice for serving static files (.js, images, etc.)
  • Use Webpack to bundle your client-side code into one or more chunks (bundles)
  • You might not need Gulp/Grunt if you're using a module bundler such as Webpack
  • Write build automation scripts in ES2015+ JavaScript (as opposed to Bash or PowerShell), they will work cross-platform and be more accessible to a variety of web developers (everyone speaks JavaScript nowadays)
  • Rename wwwroot to public, otherwise the folder structure in Azure Web Apps will be confusing (D:\Home\site\wwwroot\wwwroot vs D:\Home\site\wwwroot\public)
  • Publish only the compiled output to Azure Web Apps (you should never push node_modules to a web hosting server). See tools/deploy.js as an example.

Visit ASP.NET Core Starter Kit on GitHub (disclaimer: I'm the author)

Ways to insert javascript into URL?

The key to this is examining any information you recieve and then display and/or use in code on the server. Get/Post form variables if they contain javascript that you store and later redisplay is a security risk. As are any thing that gets concatenated unexamined into a sql statement you run.

One potential gotcha to watch for are attacks that mess with the character encoding. For instance if I submit a form with utf-8 character set but you store and later display in iso-8859-1 latin with no translation then I might be able to sneak something past your validator. The easiest way to handle this is to always display and store in the same character set. utf-8 is usually a good choice. Never depend on the browser to do the right thing for you in this case. Set explicit character sets and examine the character sets you recieve and do a translation to the expected storage set before you validate it.

How do the post increment (i++) and pre increment (++i) operators work in Java?

a=5; i=++a + ++a + a++;

is

i = 7 + 6 + 7

Working: pre/post increment has "right to left" Associativity , and pre has precedence over post , so first of all pre increment will be solve as (++a + ++a) => 7 + 6 . then a=7 is provided to post increment => 7 + 6 + 7 =20 and a =8.

a=5; i=a++ + ++a + ++a;

is

i=7 + 7 + 6

Working: pre/post increment has "right to left" Associativity , and pre has precedence over post , so first of all pre increment will be solve as (++a + ++a) => 7 + 6.then a=7 is provided to post increment => 7 + 7 + 6 =20 and a =8.

How to write std::string to file?

Assuming you're using a std::ofstream to write to file, the following snippet will write a std::string to file in human readable form:

std::ofstream file("filename");
std::string my_string = "Hello text in file\n";
file << my_string;

UnsatisfiedDependencyException: Error creating bean with name

Just add @Service annotation to top of the service class

not None test in Python

if val is not None:
    # ...

is the Pythonic idiom for testing that a variable is not set to None. This idiom has particular uses in the case of declaring keyword functions with default parameters. is tests identity in Python. Because there is one and only one instance of None present in a running Python script/program, is is the optimal test for this. As Johnsyweb points out, this is discussed in PEP 8 under "Programming Recommendations".

As for why this is preferred to

if not (val is None):
    # ...

this is simply part of the Zen of Python: "Readability counts." Good Python is often close to good pseudocode.

Linking to an external URL in Javadoc?

Hard to find a clear answer from the Oracle site. The following is from javax.ws.rs.core.HttpHeaders.java:

/**
 * See {@link <a href="http://www.w3.org/Protocols/rfc2616/rfc2616-sec14.html#sec14.1">HTTP/1.1 documentation</a>}.
 */
public static final String ACCEPT = "Accept";

/**
 * See {@link <a href="http://www.w3.org/Protocols/rfc2616/rfc2616-sec14.html#sec14.2">HTTP/1.1 documentation</a>}.
 */
public static final String ACCEPT_CHARSET = "Accept-Charset";

php.ini & SMTP= - how do you pass username & password

  1. Install the latest hMailServer. "Run hMailServer Administrator" in the last step.
  2. Connect to "localhost".
  3. "Add domain..."
  4. Set "127.0.0.1." as the "Domain", click "Save".
  5. "Settings" > "Protocols" > "SMTP" > "Delivery of e-mail"
  6. Set "localhost" as the "Local host name", provide your data in the "SMTP Relayer" section, click "Save".
  7. "Settings" > "Advanced" > "IP Ranges" > "My Computer"
  8. Disable the "External to external e-mail addresses" checkbox in the "Require SMTP authentication" group.
  9. If you have modified php.ini, rewrite these 3 values:

"SMTP = localhost",

"smtp_port = 25",

"; sendmail_path = ".

Credit: How to configure WAMP (localhost) to send email using Gmail?

Using getResources() in non-activity class

We can use context Like this try now Where the parent is the ViewGroup.

Context context = parent.getContext();

Callback functions in C++

Note: Most of the answers cover function pointers which is one possibility to achieve "callback" logic in C++, but as of today not the most favourable one I think.

What are callbacks(?) and why to use them(!)

A callback is a callable (see further down) accepted by a class or function, used to customize the current logic depending on that callback.

One reason to use callbacks is to write generic code which is independant from the logic in the called function and can be reused with different callbacks.

Many functions of the standard algorithms library <algorithm> use callbacks. For example the for_each algorithm applies an unary callback to every item in a range of iterators:

template<class InputIt, class UnaryFunction>
UnaryFunction for_each(InputIt first, InputIt last, UnaryFunction f)
{
  for (; first != last; ++first) {
    f(*first);
  }
  return f;
}

which can be used to first increment and then print a vector by passing appropriate callables for example:

std::vector<double> v{ 1.0, 2.2, 4.0, 5.5, 7.2 };
double r = 4.0;
std::for_each(v.begin(), v.end(), [&](double & v) { v += r; });
std::for_each(v.begin(), v.end(), [](double v) { std::cout << v << " "; });

which prints

5 6.2 8 9.5 11.2

Another application of callbacks is the notification of callers of certain events which enables a certain amount of static / compile time flexibility.

Personally, I use a local optimization library that uses two different callbacks:

  • The first callback is called if a function value and the gradient based on a vector of input values is required (logic callback: function value determination / gradient derivation).
  • The second callback is called once for each algorithm step and receives certain information about the convergence of the algorithm (notification callback).

Thus, the library designer is not in charge of deciding what happens with the information that is given to the programmer via the notification callback and he needn't worry about how to actually determine function values because they're provided by the logic callback. Getting those things right is a task due to the library user and keeps the library slim and more generic.

Furthermore, callbacks can enable dynamic runtime behaviour.

Imagine some kind of game engine class which has a function that is fired, each time the users presses a button on his keyboard and a set of functions that control your game behaviour. With callbacks you can (re)decide at runtime which action will be taken.

void player_jump();
void player_crouch();

class game_core
{
    std::array<void(*)(), total_num_keys> actions;
    // 
    void key_pressed(unsigned key_id)
    {
        if(actions[key_id]) actions[key_id]();
    }
    // update keybind from menu
    void update_keybind(unsigned key_id, void(*new_action)())
    {
        actions[key_id] = new_action;
    }
};

Here the function key_pressed uses the callbacks stored in actions to obtain the desired behaviour when a certain key is pressed. If the player chooses to change the button for jumping, the engine can call

game_core_instance.update_keybind(newly_selected_key, &player_jump);

and thus change the behaviour of a call to key_pressed (which the calls player_jump) once this button is pressed the next time ingame.

What are callables in C++(11)?

See C++ concepts: Callable on cppreference for a more formal description.

Callback functionality can be realized in several ways in C++(11) since several different things turn out to be callable*:

  • Function pointers (including pointers to member functions)
  • std::function objects
  • Lambda expressions
  • Bind expressions
  • Function objects (classes with overloaded function call operator operator())

* Note: Pointer to data members are callable as well but no function is called at all.

Several important ways to write callbacks in detail

  • X.1 "Writing" a callback in this post means the syntax to declare and name the callback type.
  • X.2 "Calling" a callback refers to the syntax to call those objects.
  • X.3 "Using" a callback means the syntax when passing arguments to a function using a callback.

Note: As of C++17, a call like f(...) can be written as std::invoke(f, ...) which also handles the pointer to member case.

1. Function pointers

A function pointer is the 'simplest' (in terms of generality; in terms of readability arguably the worst) type a callback can have.

Let's have a simple function foo:

int foo (int x) { return 2+x; }

1.1 Writing a function pointer / type notation

A function pointer type has the notation

return_type (*)(parameter_type_1, parameter_type_2, parameter_type_3)
// i.e. a pointer to foo has the type:
int (*)(int)

where a named function pointer type will look like

return_type (* name) (parameter_type_1, parameter_type_2, parameter_type_3)

// i.e. f_int_t is a type: function pointer taking one int argument, returning int
typedef int (*f_int_t) (int); 

// foo_p is a pointer to function taking int returning int
// initialized by pointer to function foo taking int returning int
int (* foo_p)(int) = &foo; 
// can alternatively be written as 
f_int_t foo_p = &foo;

The using declaration gives us the option to make things a little bit more readable, since the typedef for f_int_t can also be written as:

using f_int_t = int(*)(int);

Where (at least for me) it is clearer that f_int_t is the new type alias and recognition of the function pointer type is also easier

And a declaration of a function using a callback of function pointer type will be:

// foobar having a callback argument named moo of type 
// pointer to function returning int taking int as its argument
int foobar (int x, int (*moo)(int));
// if f_int is the function pointer typedef from above we can also write foobar as:
int foobar (int x, f_int_t moo);

1.2 Callback call notation

The call notation follows the simple function call syntax:

int foobar (int x, int (*moo)(int))
{
    return x + moo(x); // function pointer moo called using argument x
}
// analog
int foobar (int x, f_int_t moo)
{
    return x + moo(x); // function pointer moo called using argument x
}

1.3 Callback use notation and compatible types

A callback function taking a function pointer can be called using function pointers.

Using a function that takes a function pointer callback is rather simple:

 int a = 5;
 int b = foobar(a, foo); // call foobar with pointer to foo as callback
 // can also be
 int b = foobar(a, &foo); // call foobar with pointer to foo as callback

1.4 Example

A function ca be written that doesn't rely on how the callback works:

void tranform_every_int(int * v, unsigned n, int (*fp)(int))
{
  for (unsigned i = 0; i < n; ++i)
  {
    v[i] = fp(v[i]);
  }
}

where possible callbacks could be

int double_int(int x) { return 2*x; }
int square_int(int x) { return x*x; }

used like

int a[5] = {1, 2, 3, 4, 5};
tranform_every_int(&a[0], 5, double_int);
// now a == {2, 4, 6, 8, 10};
tranform_every_int(&a[0], 5, square_int);
// now a == {4, 16, 36, 64, 100};

2. Pointer to member function

A pointer to member function (of some class C) is a special type of (and even more complex) function pointer which requires an object of type C to operate on.

struct C
{
    int y;
    int foo(int x) const { return x+y; }
};

2.1 Writing pointer to member function / type notation

A pointer to member function type for some class T has the notation

// can have more or less parameters
return_type (T::*)(parameter_type_1, parameter_type_2, parameter_type_3)
// i.e. a pointer to C::foo has the type
int (C::*) (int)

where a named pointer to member function will -in analogy to the function pointer- look like this:

return_type (T::* name) (parameter_type_1, parameter_type_2, parameter_type_3)

// i.e. a type `f_C_int` representing a pointer to member function of `C`
// taking int returning int is:
typedef int (C::* f_C_int_t) (int x); 

// The type of C_foo_p is a pointer to member function of C taking int returning int
// Its value is initialized by a pointer to foo of C
int (C::* C_foo_p)(int) = &C::foo;
// which can also be written using the typedef:
f_C_int_t C_foo_p = &C::foo;

Example: Declaring a function taking a pointer to member function callback as one of its arguments:

// C_foobar having an argument named moo of type pointer to member function of C
// where the callback returns int taking int as its argument
// also needs an object of type c
int C_foobar (int x, C const &c, int (C::*moo)(int));
// can equivalently declared using the typedef above:
int C_foobar (int x, C const &c, f_C_int_t moo);

2.2 Callback call notation

The pointer to member function of C can be invoked, with respect to an object of type C by using member access operations on the dereferenced pointer. Note: Parenthesis required!

int C_foobar (int x, C const &c, int (C::*moo)(int))
{
    return x + (c.*moo)(x); // function pointer moo called for object c using argument x
}
// analog
int C_foobar (int x, C const &c, f_C_int_t moo)
{
    return x + (c.*moo)(x); // function pointer moo called for object c using argument x
}

Note: If a pointer to C is available the syntax is equivalent (where the pointer to C must be dereferenced as well):

int C_foobar_2 (int x, C const * c, int (C::*meow)(int))
{
    if (!c) return x;
    // function pointer meow called for object *c using argument x
    return x + ((*c).*meow)(x); 
}
// or equivalent:
int C_foobar_2 (int x, C const * c, int (C::*meow)(int))
{
    if (!c) return x;
    // function pointer meow called for object *c using argument x
    return x + (c->*meow)(x); 
}

2.3 Callback use notation and compatible types

A callback function taking a member function pointer of class T can be called using a member function pointer of class T.

Using a function that takes a pointer to member function callback is -in analogy to function pointers- quite simple as well:

 C my_c{2}; // aggregate initialization
 int a = 5;
 int b = C_foobar(a, my_c, &C::foo); // call C_foobar with pointer to foo as its callback

3. std::function objects (header <functional>)

The std::function class is a polymorphic function wrapper to store, copy or invoke callables.

3.1 Writing a std::function object / type notation

The type of a std::function object storing a callable looks like:

std::function<return_type(parameter_type_1, parameter_type_2, parameter_type_3)>

// i.e. using the above function declaration of foo:
std::function<int(int)> stdf_foo = &foo;
// or C::foo:
std::function<int(const C&, int)> stdf_C_foo = &C::foo;

3.2 Callback call notation

The class std::function has operator() defined which can be used to invoke its target.

int stdf_foobar (int x, std::function<int(int)> moo)
{
    return x + moo(x); // std::function moo called
}
// or 
int stdf_C_foobar (int x, C const &c, std::function<int(C const &, int)> moo)
{
    return x + moo(c, x); // std::function moo called using c and x
}

3.3 Callback use notation and compatible types

The std::function callback is more generic than function pointers or pointer to member function since different types can be passed and implicitly converted into a std::function object.

3.3.1 Function pointers and pointers to member functions

A function pointer

int a = 2;
int b = stdf_foobar(a, &foo);
// b == 6 ( 2 + (2+2) )

or a pointer to member function

int a = 2;
C my_c{7}; // aggregate initialization
int b = stdf_C_foobar(a, c, &C::foo);
// b == 11 == ( 2 + (7+2) )

can be used.

3.3.2 Lambda expressions

An unnamed closure from a lambda expression can be stored in a std::function object:

int a = 2;
int c = 3;
int b = stdf_foobar(a, [c](int x) -> int { return 7+c*x; });
// b == 15 ==  a + (7*c*a) == 2 + (7+3*2)

3.3.3 std::bind expressions

The result of a std::bind expression can be passed. For example by binding parameters to a function pointer call:

int foo_2 (int x, int y) { return 9*x + y; }
using std::placeholders::_1;

int a = 2;
int b = stdf_foobar(a, std::bind(foo_2, _1, 3));
// b == 23 == 2 + ( 9*2 + 3 )
int c = stdf_foobar(a, std::bind(foo_2, 5, _1));
// c == 49 == 2 + ( 9*5 + 2 )

Where also objects can be bound as the object for the invocation of pointer to member functions:

int a = 2;
C const my_c{7}; // aggregate initialization
int b = stdf_foobar(a, std::bind(&C::foo, my_c, _1));
// b == 1 == 2 + ( 2 + 7 )

3.3.4 Function objects

Objects of classes having a proper operator() overload can be stored inside a std::function object, as well.

struct Meow
{
  int y = 0;
  Meow(int y_) : y(y_) {}
  int operator()(int x) { return y * x; }
};
int a = 11;
int b = stdf_foobar(a, Meow{8});
// b == 99 == 11 + ( 8 * 11 )

3.4 Example

Changing the function pointer example to use std::function

void stdf_tranform_every_int(int * v, unsigned n, std::function<int(int)> fp)
{
  for (unsigned i = 0; i < n; ++i)
  {
    v[i] = fp(v[i]);
  }
}

gives a whole lot more utility to that function because (see 3.3) we have more possibilities to use it:

// using function pointer still possible
int a[5] = {1, 2, 3, 4, 5};
stdf_tranform_every_int(&a[0], 5, double_int);
// now a == {2, 4, 6, 8, 10};

// use it without having to write another function by using a lambda
stdf_tranform_every_int(&a[0], 5, [](int x) -> int { return x/2; });
// now a == {1, 2, 3, 4, 5}; again

// use std::bind :
int nine_x_and_y (int x, int y) { return 9*x + y; }
using std::placeholders::_1;
// calls nine_x_and_y for every int in a with y being 4 every time
stdf_tranform_every_int(&a[0], 5, std::bind(nine_x_and_y, _1, 4));
// now a == {13, 22, 31, 40, 49};

4. Templated callback type

Using templates, the code calling the callback can be even more general than using std::function objects.

Note that templates are a compile-time feature and are a design tool for compile-time polymorphism. If runtime dynamic behaviour is to be achieved through callbacks, templates will help but they won't induce runtime dynamics.

4.1 Writing (type notations) and calling templated callbacks

Generalizing i.e. the std_ftransform_every_int code from above even further can be achieved by using templates:

template<class R, class T>
void stdf_transform_every_int_templ(int * v,
  unsigned const n, std::function<R(T)> fp)
{
  for (unsigned i = 0; i < n; ++i)
  {
    v[i] = fp(v[i]);
  }
}

with an even more general (as well as easiest) syntax for a callback type being a plain, to-be-deduced templated argument:

template<class F>
void transform_every_int_templ(int * v, 
  unsigned const n, F f)
{
  std::cout << "transform_every_int_templ<" 
    << type_name<F>() << ">\n";
  for (unsigned i = 0; i < n; ++i)
  {
    v[i] = f(v[i]);
  }
}

Note: The included output prints the type name deduced for templated type F. The implementation of type_name is given at the end of this post.

The most general implementation for the unary transformation of a range is part of the standard library, namely std::transform, which is also templated with respect to the iterated types.

template<class InputIt, class OutputIt, class UnaryOperation>
OutputIt transform(InputIt first1, InputIt last1, OutputIt d_first,
  UnaryOperation unary_op)
{
  while (first1 != last1) {
    *d_first++ = unary_op(*first1++);
  }
  return d_first;
}

4.2 Examples using templated callbacks and compatible types

The compatible types for the templated std::function callback method stdf_transform_every_int_templ are identical to the above mentioned types (see 3.4).

Using the templated version however, the signature of the used callback may change a little:

// Let
int foo (int x) { return 2+x; }
int muh (int const &x) { return 3+x; }
int & woof (int &x) { x *= 4; return x; }

int a[5] = {1, 2, 3, 4, 5};
stdf_transform_every_int_templ<int,int>(&a[0], 5, &foo);
// a == {3, 4, 5, 6, 7}
stdf_transform_every_int_templ<int, int const &>(&a[0], 5, &muh);
// a == {6, 7, 8, 9, 10}
stdf_transform_every_int_templ<int, int &>(&a[0], 5, &woof);

Note: std_ftransform_every_int (non templated version; see above) does work with foo but not using muh.

// Let
void print_int(int * p, unsigned const n)
{
  bool f{ true };
  for (unsigned i = 0; i < n; ++i)
  {
    std::cout << (f ? "" : " ") << p[i]; 
    f = false;
  }
  std::cout << "\n";
}

The plain templated parameter of transform_every_int_templ can be every possible callable type.

int a[5] = { 1, 2, 3, 4, 5 };
print_int(a, 5);
transform_every_int_templ(&a[0], 5, foo);
print_int(a, 5);
transform_every_int_templ(&a[0], 5, muh);
print_int(a, 5);
transform_every_int_templ(&a[0], 5, woof);
print_int(a, 5);
transform_every_int_templ(&a[0], 5, [](int x) -> int { return x + x + x; });
print_int(a, 5);
transform_every_int_templ(&a[0], 5, Meow{ 4 });
print_int(a, 5);
using std::placeholders::_1;
transform_every_int_templ(&a[0], 5, std::bind(foo_2, _1, 3));
print_int(a, 5);
transform_every_int_templ(&a[0], 5, std::function<int(int)>{&foo});
print_int(a, 5);

The above code prints:

1 2 3 4 5
transform_every_int_templ <int(*)(int)>
3 4 5 6 7
transform_every_int_templ <int(*)(int&)>
6 8 10 12 14
transform_every_int_templ <int& (*)(int&)>
9 11 13 15 17
transform_every_int_templ <main::{lambda(int)#1} >
27 33 39 45 51
transform_every_int_templ <Meow>
108 132 156 180 204
transform_every_int_templ <std::_Bind<int(*(std::_Placeholder<1>, int))(int, int)>>
975 1191 1407 1623 1839
transform_every_int_templ <std::function<int(int)>>
977 1193 1409 1625 1841

type_name implementation used above

#include <type_traits>
#include <typeinfo>
#include <string>
#include <memory>
#include <cxxabi.h>

template <class T>
std::string type_name()
{
  typedef typename std::remove_reference<T>::type TR;
  std::unique_ptr<char, void(*)(void*)> own
    (abi::__cxa_demangle(typeid(TR).name(), nullptr,
    nullptr, nullptr), std::free);
  std::string r = own != nullptr?own.get():typeid(TR).name();
  if (std::is_const<TR>::value)
    r += " const";
  if (std::is_volatile<TR>::value)
    r += " volatile";
  if (std::is_lvalue_reference<T>::value)
    r += " &";
  else if (std::is_rvalue_reference<T>::value)
    r += " &&";
  return r;
}

Create excel ranges using column numbers in vba?

Haha, Lovely - let me also include my version of stackPusher's code :). We are using this functionality in C#. Works fine for all Excel ranges.:

public static String ConvertToLiteral(int number)
{
        int firstLetter = (((number - 27) / (26 * 26))) % 26;
        int middleLetter = ((((number - 1) / 26)) % 26);

        int lastLetter = (number % 26);
        firstLetter = firstLetter == 0 ? 26 : firstLetter;
        middleLetter = middleLetter == 0 ? 26 : middleLetter;
        lastLetter = lastLetter == 0 ? 26 : lastLetter;
        String returnedString = "";
        returnedString = number > 27 * 26 ? (Convert.ToChar(firstLetter + 64).ToString()) : returnedString;
        returnedString += number > 26 ? (Convert.ToChar(middleLetter + 64).ToString()) : returnedString;
        returnedString += lastLetter >= 0 ? (Convert.ToChar(lastLetter + 64).ToString()) : returnedString;
        return returnedString;
}

push object into array

_x000D_
_x000D_
let nietos = [];

function nieto(aData) {

    let o = {};

    for ( let i = 0; i < aData.length; i++ ) {
        let key = "0" + (i + 1);
        o[key] = aData[i];
    }

    nietos.push(o);
}

nieto( ["Band", "Ramones"] );
nieto( ["Style", "RockPunk"] );
nieto( ["", "", "", "Another String"] );

/* convert array of object into string json */
var jsonString = JSON.stringify(nietos);
document.write(jsonString);
_x000D_
_x000D_
_x000D_

Add an object into an array

jQuery - Detect value change on hidden input field

Building off of Viktar's answer, here's an implementation you can call once on a given hidden input element to ensure that subsequent change events get fired whenever the value of the input element changes:

/**
 * Modifies the provided hidden input so value changes to trigger events.
 *
 * After this method is called, any changes to the 'value' property of the
 * specified input will trigger a 'change' event, just like would happen
 * if the input was a text field.
 *
 * As explained in the following SO post, hidden inputs don't normally
 * trigger on-change events because the 'blur' event is responsible for
 * triggering a change event, and hidden inputs aren't focusable by virtue
 * of being hidden elements:
 * https://stackoverflow.com/a/17695525/4342230
 *
 * @param {HTMLInputElement} inputElement
 *   The DOM element for the hidden input element.
 */
function setupHiddenInputChangeListener(inputElement) {
  const propertyName = 'value';

  const {get: originalGetter, set: originalSetter} =
    findPropertyDescriptor(inputElement, propertyName);

  // We wrap this in a function factory to bind the getter and setter values
  // so later callbacks refer to the correct object, in case we use this
  // method on more than one hidden input element.
  const newPropertyDescriptor = ((_originalGetter, _originalSetter) => {
    return {
      set: function(value) {
        const currentValue = originalGetter.call(inputElement);

        // Delegate the call to the original property setter
        _originalSetter.call(inputElement, value);

        // Only fire change if the value actually changed.
        if (currentValue !== value) {
          inputElement.dispatchEvent(new Event('change'));
        }
      },

      get: function() {
        // Delegate the call to the original property getter
        return _originalGetter.call(inputElement);
      }
    }
  })(originalGetter, originalSetter);

  Object.defineProperty(inputElement, propertyName, newPropertyDescriptor);
};

/**
 * Search the inheritance tree of an object for a property descriptor.
 *
 * The property descriptor defined nearest in the inheritance hierarchy to
 * the class of the given object is returned first.
 *
 * Credit for this approach:
 * https://stackoverflow.com/a/38802602/4342230
 *
 * @param {Object} object
 * @param {String} propertyName
 *   The name of the property for which a descriptor is desired.
 *
 * @returns {PropertyDescriptor, null}
 */
function findPropertyDescriptor(object, propertyName) {
  if (object === null) {
    return null;
  }

  if (object.hasOwnProperty(propertyName)) {
    return Object.getOwnPropertyDescriptor(object, propertyName);
  }
  else {
    const parentClass = Object.getPrototypeOf(object);

    return findPropertyDescriptor(parentClass, propertyName);
  }
}

Call this on document ready like so:

$(document).ready(function() {
  setupHiddenInputChangeListener($('myinput')[0]);
});

IE Enable/Disable Proxy Settings via Registry

modifying the proxy value under

[HKEY_USERS\<your SID>\Software\Microsoft\Windows\CurrentVersion\Internet Settings]

doesnt need to restart ie

Getting the actual usedrange

This function returns the actual used range to the lower right limit. It returns "Nothing" if the sheet is empty.

'2020-01-26
Function fUsedRange() As Range
Dim lngLastRow As Long
Dim lngLastCol As Long
Dim rngLastCell As Range
    On Error Resume Next
    Set rngLastCell = ActiveSheet.Cells.Find("*", searchorder:=xlByRows, searchdirection:=xlPrevious)
    If rngLastCell Is Nothing Then  'look for data backwards in rows
        Set fUsedRange = Nothing
        Exit Function
    Else
        lngLastRow = rngLastCell.Row
    End If
    Set rngLastCell = ActiveSheet.Cells.Find("*", searchorder:=xlByColumns, searchdirection:=xlPrevious)
    If rngLastCell Is Nothing Then  'look for data backwards in columns
        Set fUsedRange = Nothing
        Exit Function
    Else
        lngLastCol = rngLastCell.Column
    End If
    Set fUsedRange = ActiveSheet.Range(Cells(1, 1), Cells(lngLastRow, lngLastCol))  'set up range
End Function

how to open a jar file in Eclipse

Firstly, it's necessary to know what is a jar file.

From Oracle,

JAR (Java Archive) is a platform-independent file format that aggregates many files into one. Multiple Java applets and their requisite components (.class files, images and sounds) can be bundled in a JAR file and subsequently downloaded to a browser in a single HTTP transaction, greatly improving the download speed. The JAR format also supports compression, which reduces the file size, further improving the download time.

As you can see,

  1. It has nothing to do with a Eclipse project. An Eclipse project can be a Java project, C++ project and so on. It's just a self contain project that can be recognized and operated as an unit by Eclipse.
  2. The .class files are generally the main part of a jar file. It's impossible to view the source code(.java file) unless you decompile the executable file(.class file) by some tools. Take Eclipse for example, you can choose the plugin Eclipse Class Decompiler as the tool.

How to check if a Java 8 Stream is empty?

I would simply use:

stream.count()>0

Unloading classes in java?

Yes there are ways to load classes and to "unload" them later on. The trick is to implement your own classloader which resides between high level class loader (the System class loader) and the class loaders of the app server(s), and to hope that the app server's class loaders do delegate the classloading to the upper loaders.

A class is defined by its package, its name, and the class loader it originally loaded. Program a "proxy" classloader which is the first that is loaded when starting the JVM. Workflow:

  • The program starts and the real "main"-class is loaded by this proxy classloader.
  • Every class that then is normally loaded (i.e. not through another classloader implementation which could break the hierarchy) will be delegated to this class loader.
  • The proxy classloader delegates java.x and sun.x to the system classloader (these must not be loaded through any other classloader than the system classloader).
  • For every class that is replaceable, instantiate a classloader (which really loads the class and does not delegate it to the parent classloader) and load it through this.
  • Store the package/name of the classes as keys and the classloader as values in a data structure (i.e. Hashmap).
  • Every time the proxy classloader gets a request for a class that was loaded before, it returns the class from the class loader stored before.
  • It should be enough to locate the byte array of a class by your class loader (or to "delete" the key/value pair from your data structure) and reload the class in case you want to change it.

Done right there should not come a ClassCastException or LinkageError etc.

For more informations about class loader hierarchies (yes, that's exactly what you are implementing here ;- ) look at "Server-Based Java Programming" by Ted Neward - that book helped me implementing something very similar to what you want.

C#: Converting byte array to string and printing out to console

It's actually:

    Console.WriteLine(Encoding.Default.GetString(value));

or for UTF-8 specifically:

    Console.WriteLine(Encoding.UTF8.GetString(value));

Quick way to clear all selections on a multiselect enabled <select> with jQuery?

In JQuery:

  $("#id option:selected").prop("selected", false);
  $("#id").multiselect('refresh');

How to uninstall a windows service and delete its files without rebooting

Are you not able to stop the service before the update (and restart after the update) using the commands below?

net stop <service name>
net start <service name>

Whenever I'm testing/deploying a service I'm able to upload files without reinstalling as long as the service is stopped. I'm not sure if the issue you are having is different.

fetch gives an empty response body

In many case you will need to add the bodyParser module in your express node app. Then in your app.use part below app.use(express.static('www')); add these 2 lines app.use(bodyParser.urlencoded({ extended: true })); app.use(bodyParser.json());

How to read/write from/to file using Go?

New Way

Starting with Go 1.16, use os.ReadFile to load the file to memory, use os.WriteFile to write to a file from memory.

Be careful with the os.ReadFile because it reads the whole file into memory.

package main

import "os"

func main() {
    b, err := os.ReadFile("input.txt")
    if err != nil {
        log.Fatal(err)
    }

    // `data` contains everything your file does
    // This writes it to the Standard Out
    os.Stdout.Write(data)

    // You can also write it to a file as a whole
    err = os.WriteFile("destination.txt", b, 0644)
    if err != nil {
        log.Fatal(err)
    }
}

When to use 'raise NotImplementedError'?

Consider if instead it was:

class RectangularRoom(object):
    def __init__(self, width, height):
        pass

    def cleanTileAtPosition(self, pos):
        pass

    def isTileCleaned(self, m, n):
        pass

and you subclass and forget to tell it how to isTileCleaned() or, perhaps more likely, typo it as isTileCLeaned(). Then in your code, you'll get a None when you call it.

  • Will you get the overridden function you wanted? Definitely not.
  • Is None valid output? Who knows.
  • Is that intended behavior? Almost certainly not.
  • Will you get an error? It depends.

raise NotImplmentedError forces you to implement it, as it will throw an exception when you try to run it until you do so. This removes a lot of silent errors. It's similar to why a bare except is almost never a good idea: because people make mistakes and this makes sure they aren't swept under the rug.

Note: Using an abstract base class, as other answers have mentioned, is better still, as then the errors are frontloaded and the program won't run until you implement them (with NotImplementedError, it will only throw an exception if actually called).

How can I verify if a Windows Service is running

I guess something like this would work:

Add System.ServiceProcess to your project references (It's on the .NET tab).

using System.ServiceProcess;

ServiceController sc = new ServiceController(SERVICENAME);

switch (sc.Status)
{
    case ServiceControllerStatus.Running:
        return "Running";
    case ServiceControllerStatus.Stopped:
        return "Stopped";
    case ServiceControllerStatus.Paused:
        return "Paused";
    case ServiceControllerStatus.StopPending:
        return "Stopping";
    case ServiceControllerStatus.StartPending:
        return "Starting";
    default:
        return "Status Changing";
}

Edit: There is also a method sc.WaitforStatus() that takes a desired status and a timeout, never used it but it may suit your needs.

Edit: Once you get the status, to get the status again you will need to call sc.Refresh() first.

Reference: ServiceController object in .NET.

How to set text color in submit button?

<button id="fwdbtn" style="color:red">Submit</button> 

Difference between datetime and timestamp in sqlserver?

Datetime is a datatype.

Timestamp is a method for row versioning. In fact, in sql server 2008 this column type was renamed (i.e. timestamp is deprecated) to rowversion. It basically means that every time a row is changed, this value is increased. This is done with a database counter which automatically increase for every inserted or updated row.

For more information:

http://www.sqlteam.com/article/timestamps-vs-datetime-data-types

http://msdn.microsoft.com/en-us/library/ms182776.aspx

Get/pick an image from Android's built-in Gallery app programmatically

Quickest way to open image from gallery or camera.

Original reference : get image from gallery in android programmatically

Following method will receive image from gallery or camera and will show it in an ImageView. Selected image will be stored internally.

code for xml

<?xml version="1.0" encoding="utf-8"?>
<LinearLayout xmlns:android="http://schemas.android.com/apk/res/android"
    xmlns:tools="http://schemas.android.com/tools"
    android:layout_width="match_parent"
    android:layout_height="match_parent"
    android:orientation="vertical"
    tools:context="com.exampledemo.parsaniahardik.uploadgalleryimage.MainActivity">

    <Button
        android:layout_width="wrap_content"
        android:layout_height="wrap_content"
        android:id="@+id/btn"
        android:layout_gravity="center_horizontal"
        android:layout_marginTop="20dp"
        android:textAppearance="?android:attr/textAppearanceLarge"
        android:text="Capture Image and upload to server" />

    <TextView
        android:layout_width="match_parent"
        android:layout_height="wrap_content"
        android:text="Below image is fetched from server"
        android:layout_marginTop="5dp"
        android:textSize="23sp"
        android:gravity="center"
        android:textColor="#000"/>

    <ImageView
        android:layout_width="300dp"
        android:layout_height="300dp"
        android:layout_gravity="center"
        android:layout_marginTop="10dp"
        android:scaleType="fitXY"
        android:src="@mipmap/ic_launcher"
        android:id="@+id/iv"/>

</LinearLayout>

JAVA class

import android.content.Intent;
import android.graphics.Bitmap;
import android.media.MediaScannerConnection;
import android.os.Environment;
import android.support.v7.app.AppCompatActivity;
import android.os.Bundle;
import android.util.Log;
import android.view.View;
import android.widget.Button;
import android.widget.ImageView;
import android.widget.Toast;
import com.androidquery.AQuery;
import org.json.JSONException;
import java.io.ByteArrayOutputStream;
import java.io.File;
import java.io.FileOutputStream;
import java.io.IOException;
import java.util.Calendar;
import java.util.HashMap;

public class MainActivity extends AppCompatActivity implements AsyncTaskCompleteListener{

    private ParseContent parseContent;
    private Button btn;
    private ImageView imageview;
    private static final String IMAGE_DIRECTORY = "/demonuts_upload_camera";
    private final int CAMERA = 1;
    private AQuery aQuery;

    @Override
    protected void onCreate(Bundle savedInstanceState) {
        super.onCreate(savedInstanceState);
        setContentView(R.layout.activity_main);

        parseContent = new ParseContent(this);
        aQuery = new AQuery(this);

        btn = (Button) findViewById(R.id.btn);
        imageview = (ImageView) findViewById(R.id.iv);

        btn.setOnClickListener(new View.OnClickListener() {
            @Override
            public void onClick(View v) {
                Intent intent = new Intent(android.provider.MediaStore.ACTION_IMAGE_CAPTURE);
                startActivityForResult(intent, CAMERA);
            }
        });

    }

    @Override
    public void onActivityResult(int requestCode, int resultCode, Intent data) {

        super.onActivityResult(requestCode, resultCode, data);
        if (resultCode == this.RESULT_CANCELED) {
            return;
        }
        if (requestCode == CAMERA) {
            Bitmap thumbnail = (Bitmap) data.getExtras().get("data");
            String path = saveImage(thumbnail);
            try {
                uploadImageToServer(path);
            } catch (IOException e) {
                e.printStackTrace();
            } catch (JSONException e) {
                e.printStackTrace();
            }
        }
    }

    private void uploadImageToServer(final String path) throws IOException, JSONException {

        if (!AndyUtils.isNetworkAvailable(MainActivity.this)) {
            Toast.makeText(MainActivity.this, "Internet is required!", Toast.LENGTH_SHORT).show();
            return;
        }

        HashMap<String, String> map = new HashMap<String, String>();
        map.put("url", "https://demonuts.com/Demonuts/JsonTest/Tennis/uploadfile.php");
        map.put("filename", path);
        new MultiPartRequester(this, map, CAMERA, this);
        AndyUtils.showSimpleProgressDialog(this);
    }

    @Override
    public void onTaskCompleted(String response, int serviceCode) {
        AndyUtils.removeSimpleProgressDialog();
        Log.d("res", response.toString());
        switch (serviceCode) {

            case CAMERA:
                if (parseContent.isSuccess(response)) {
                    String url = parseContent.getURL(response);
                    aQuery.id(imageview).image(url);
                }
        }
    }

    public String saveImage(Bitmap myBitmap) {
        ByteArrayOutputStream bytes = new ByteArrayOutputStream();
        myBitmap.compress(Bitmap.CompressFormat.JPEG, 90, bytes);
        File wallpaperDirectory = new File(
                Environment.getExternalStorageDirectory() + IMAGE_DIRECTORY);
        // have the object build the directory structure, if needed.
        if (!wallpaperDirectory.exists()) {
            wallpaperDirectory.mkdirs();
        }

        try {
            File f = new File(wallpaperDirectory, Calendar.getInstance()
                    .getTimeInMillis() + ".jpg");
            f.createNewFile();
            FileOutputStream fo = new FileOutputStream(f);
            fo.write(bytes.toByteArray());
            MediaScannerConnection.scanFile(this,
                    new String[]{f.getPath()},
                    new String[]{"image/jpeg"}, null);
            fo.close();
            Log.d("TAG", "File Saved::--->" + f.getAbsolutePath());

            return f.getAbsolutePath();
        } catch (IOException e1) {
            e1.printStackTrace();
        }
        return "";
    }
}

Prepend line to beginning of a file

There's no way to do this with any built-in functions, because it would be terribly inefficient. You'd need to shift the existing contents of the file down each time you add a line at the front.

There's a Unix/Linux utility tail which can read from the end of a file. Perhaps you can find that useful in your application.

Reducing MongoDB database file size

There has been some considerable confusion over space reclamation in MongoDB, and some recommended practice are downright dangerous to do in certain deployment types. More details below:

TL;DR repairDatabase attempts to salvage data from a standalone MongoDB deployments that is trying to recover from a disk corruption. If it recovers space, it is purely a side effect. Recovering space should never be the primary consideration of running repairDatabase.

Recover space in a standalone node

WiredTiger: For a standalone node with WiredTiger, running compact will release space to the OS, with one caveat: The compact command on WiredTiger on MongoDB 3.0.x was affected by this bug: SERVER-21833 which was fixed in MongoDB 3.2.3. Prior to this version, compact on WiredTiger could silently fail.

MMAPv1: Due to the way MMAPv1 works, there is no safe and supported method to recover space using the MMAPv1 storage engine. compact in MMAPv1 will defragment the data files, potentially making more space available for new documents, but it will not release space back to the OS.

You may be able to run repairDatabase if you fully understand the consequences of this potentially dangerous command (see below), since repairDatabase essentially rewrites the whole database by discarding corrupt documents. As a side effect, this will create new MMAPv1 data files without any fragmentation on it and release space back to the OS.

For a less adventurous method, running mongodump and mongorestore may be possible as well in an MMAPv1 deployment, subject to the size of your deployment.

Recover space in a replica set

For replica set configurations, the best and the safest method to recover space is to perform an initial sync, for both WiredTiger and MMAPv1.

If you need to recover space from all nodes in the set, you can perform a rolling initial sync. That is, perform initial sync on each of the secondaries, before finally stepping down the primary and perform initial sync on it. Rolling initial sync method is the safest method to perform replica set maintenance, and it also involves no downtime as a bonus.

Please note that the feasibility of doing a rolling initial sync also depends on the size of your deployment. For extremely large deployments, it may not be feasible to do an initial sync, and thus your options are somewhat more limited. If WiredTiger is used, you may be able to take one secondary out of the set, start it as a standalone, run compact on it, and rejoin it to the set.

Regarding repairDatabase

Please don't run repairDatabase on replica set nodes. This is very dangerous, as mentioned in the repairDatabase page and described in more details below.

The name repairDatabase is a bit misleading, since the command doesn't attempt to repair anything. The command was intended to be used when there's disk corruption on a standalone node, which could lead to corrupt documents.

The repairDatabase command could be more accurately described as "salvage database". That is, it recreates the databases by discarding corrupt documents in an attempt to get the database into a state where you can start it and salvage intact document from it.

In MMAPv1 deployments, this rebuilding of the database files releases space to the OS as a side effect. Releasing space to the OS was never the purpose.

Consequences of repairDatabase on a replica set

In a replica set, MongoDB expects all nodes in the set to contain identical data. If you run repairDatabase on a replica set node, there is a chance that the node contains undetected corruption, and repairDatabase will dutifully remove the corrupt documents for you.

Predictably, this makes that node contains a different dataset from the rest of the set. If an update happens to hit that single document, the whole set could crash.

To make matters worse, it is entirely possible that this situation could stay dormant for a long time, only to strike suddenly with no apparent reason.

convert iso date to milliseconds in javascript

var date = new Date()
console.log(" Date in MS last three digit = "+  date.getMilliseconds())
console.log(" MS = "+ Date.now())

Using this we can get date in milliseconds

How to Identify port number of SQL server

You can also use this query

USE MASTER GO xp_readerrorlog 0, 1, N'Server is listening on' GO

Source : sqlauthority blog

Char Comparison in C

A char variable is actually an 8-bit integral value. It will have values from 0 to 255. These are ASCII codes. 0 stands for the C-null character, and 255 stands for an empty symbol.

So, when you write the following assignment:

char a = 'a'; 

It is the same thing as:

char a = 97;

So, you can compare two char variables using the >, <, ==, <=, >= operators:

char a = 'a';
char b = 'b';

if( a < b ) printf("%c is smaller than %c", a, b);
if( a > b ) printf("%c is smaller than %c", a, b);
if( a == b ) printf("%c is equal to %c", a, b);

Difference between id and name attributes in HTML

ID tag - used by CSS, define a unique instance of a div, span or other elements. Appears within the Javascript DOM model, allowing you to access them with various function calls.

Name tag for fields - This is unique per form -- unless you are doing an array which you want to pass to PHP/server-side processing. You can access it via Javascript by name, but I think that it does not appear as a node in the DOM or some restrictions may apply (you cannot use .innerHTML, for example, if I recall correctly).

Using XPATH to search text containing &nbsp;

As per the HTML you have provided:

<tr>
  <td>abc</td>
  <td>&nbsp;</td>
</tr>

To locate the node with the string &nbsp; you can use either of the following based solutions:

  • Using text():

    "//td[text()='\u00A0']"
    
  • Using contains():

    "//td[contains(., '\u00A0')]"
    

However, ideally you may like to avoid the NO-BREAK SPACE character and use either of the following Locator Strategies:

  • Using the parent <tr> node and following-sibling:

    "//tr//following-sibling::td[2]"
    
  • Using starts-with():

    "//tr//td[last()]"
    
  • Using the preceeding <td> node and followingnode andfollowing-sibling`:

    "//td[text()='abc']//following::td[1]"
    

Reference

You can find a relevant detailed discussion in:


tl; dr

Unicode Character 'NO-BREAK SPACE' (U+00A0)

Running powershell script within python script, how to make python print the powershell output while it is running

  1. Make sure you can run powershell scripts (it is disabled by default). Likely you have already done this. http://technet.microsoft.com/en-us/library/ee176949.aspx

    Set-ExecutionPolicy RemoteSigned
    
  2. Run this python script on your powershell script helloworld.py:

    # -*- coding: iso-8859-1 -*-
    import subprocess, sys
    
    p = subprocess.Popen(["powershell.exe", 
                  "C:\\Users\\USER\\Desktop\\helloworld.ps1"], 
                  stdout=sys.stdout)
    p.communicate()
    

This code is based on python3.4 (or any 3.x series interpreter), though it should work on python2.x series as well.

C:\Users\MacEwin\Desktop>python helloworld.py
Hello World

How does autowiring work in Spring?

Depends on whether you want the annotations route or the bean XML definition route.

Say you had the beans defined in your applicationContext.xml:

<beans ...>

    <bean id="userService" class="com.foo.UserServiceImpl"/>

    <bean id="fooController" class="com.foo.FooController"/>

</beans>

The autowiring happens when the application starts up. So, in fooController, which for arguments sake wants to use the UserServiceImpl class, you'd annotate it as follows:

public class FooController {

    // You could also annotate the setUserService method instead of this
    @Autowired
    private UserService userService;

    // rest of class goes here
}

When it sees @Autowired, Spring will look for a class that matches the property in the applicationContext, and inject it automatically. If you have more than one UserService bean, then you'll have to qualify which one it should use.

If you do the following:

UserService service = new UserServiceImpl();

It will not pick up the @Autowired unless you set it yourself.

String.contains in Java

no real explanation is given by Java (in either JavaDoc or much coveted code comments), but looking at the code, it seems that this is magic:

calling stack:

String.indexOf(char[], int, int, char[], int, int, int) line: 1591  
String.indexOf(String, int) line: 1564  
String.indexOf(String) line: 1546   
String.contains(CharSequence) line: 1934    

code:

/**
 * Code shared by String and StringBuffer to do searches. The
 * source is the character array being searched, and the target
 * is the string being searched for.
 *
 * @param   source       the characters being searched.
 * @param   sourceOffset offset of the source string.
 * @param   sourceCount  count of the source string.
 * @param   target       the characters being searched for.
 * @param   targetOffset offset of the target string.
 * @param   targetCount  count of the target string.
 * @param   fromIndex    the index to begin searching from.
 */
static int indexOf(char[] source, int sourceOffset, int sourceCount,
                   char[] target, int targetOffset, int targetCount,
                   int fromIndex) {
  if (fromIndex >= sourceCount) {
        return (targetCount == 0 ? sourceCount : -1);
  }
      if (fromIndex < 0) {
        fromIndex = 0;
      }
  if (targetCount == 0) {//my comment: this is where it returns, the size of the 
    return fromIndex;    // incoming string is 0,  which is passed in as targetCount
  }                      // fromIndex is 0 as well, as the search starts from the 
                         // start of the source string
    ...//the rest of the method 

PHP DOMDocument loadHTML not encoding UTF-8 correctly

Works finde for me:

$dom = new \DOMDocument;
$dom->loadHTML(utf8_decode($html));
...
return  utf8_encode( $dom->saveHTML());

how to make jni.h be found?

It needs both jni.h and jni_md.h files, Try this

gcc -I/usr/lib/jvm/jdk1.7.0_07/include \
  -I/usr/lib/jvm/jdk1.7.0_07/include/linux filename.c

This will include both the broad JNI files and the ones necessary for linux

How to find the day, month and year with moment.js

Just try with:

var check = moment(n.entry.date_entered, 'YYYY/MM/DD');

var month = check.format('M');
var day   = check.format('D');
var year  = check.format('YYYY');

JSFiddle

How to move Jenkins from one PC to another

Let us say we are migrating Jenkins LTS from PC1 to PC2 (irrispective of LTS version is same of upgraded). It is easy to use ThinBackUp Plugin for migration or Upgrade of Jenkins version.

Step1: Prepare PC1 for migration

  • Manage Jenkins -> ThinbackUp -> Setting
  • Select correct options and directory for backup
  • If you need a job history and artifacts need to be added then please select 'Back build results' option as well.

enter image description here

  • Go back click on Backup Now.

enter image description here

Note: This Thinbackup will also take Plugin Backup which is optional.

  • Check the ThinbackUp folder must have a folder with current date and timestamp. (wait for couple of minutes it might take some time.)
  • You are ready with your back, .zip it and copy to PARTICULAR (which will be 'Backup directory') directory in PC2.
  • Unzip ThinbackUp zipped folder.
  • Stop Jenkins Service in PC1.

Step2: Install Jenkins (Install using .war file or Paste archived version) in PC2.

  • Create Jenkins Service using command sc create <Jenkins_PC2Servicename> binPath="<Path_to_Jenkinsexe>/jenkins.exe"
  • Modify JENKINS_HOME/jenkins.xml if needed in PC2.
  • Run windows service <Jenkins_PC2Servicename> in PC2
  • Manage Jenkins -> ThinbackUp -> Setting
  • Make sure that you PERTICULAR path from step1 as Backup Directory in ThinBackup settings.
  • ThinbackUp -> Restore will give you a Dropdown list, choose a right backup (identify with date and timestamp).

enter image description here

  • Wait for some minutes and you have latest backup configurations including jobs history and plugins in PC2.
  • In case if there are additional changes needed in JENKINS_HOME/Jenkins.xml (coming from PC1 ThinbackUp which is not needed) then this modification need to do manually.

NOTE: If you are using Database setting of SCM in your Jenkins jobs then you need to take extra care as all SCM plugins do not support to carry Database settings with the help of ThinbackUp plugin. e.g. If you are using PTC Integrity SCM Plugin, and some Jenkins jobs are using DB using Integrity, then it will create a directory JENKINS_Home/IntegritySCM, ThinbackUp will not include this DB while taking backup.

Solution: Directly Copy this JENKINS_Home/IntegritySCM folder from PC1 to PC2.

Is there a NumPy function to return the first index of something in an array?

Use ndindex

Sample array

arr = np.array([[1,4],
                 [2,3]])
print(arr)

...[[1,4],
    [2,3]]
 

create an empty list to store the index and the element tuples

 index_elements = []
 for i in np.ndindex(arr.shape):
     index_elements.append((arr[i],i))

 

convert the list of tuples into dictionary

 index_elements = dict(index_elements)

The keys are the elements and the values are their indices - use keys to access the index

 index_elements[4] 
  
output
  ... (0,1)
  

Why do I get a "Null value was assigned to a property of primitive type setter of" error message when using HibernateCriteriaBuilder in Grails

@Dinh Nhat, your setter method looks wrong because you put a primitive type there again and it should be:

public void setClient_os_id(Integer clientOsId) {
client_os_id = clientOsId;
}

Entity Framework - Code First - Can't Store List<String>

This answer is based on the ones provided by @Sasan and @CAD bloke.

If you wish to use this in .NET Standard 2 or don't want Newtonsoft, see Xaniff's answer below

Works only with EF Core 2.1+ (not .NET Standard compatible)(Newtonsoft JsonConvert)

builder.Entity<YourEntity>().Property(p => p.Strings)
    .HasConversion(
        v => JsonConvert.SerializeObject(v),
        v => JsonConvert.DeserializeObject<List<string>>(v));

Using the EF Core fluent configuration we serialize/deserialize the List to/from JSON.

Why this code is the perfect mix of everything you could strive for:

  • The problem with Sasn's original answer is that it will turn into a big mess if the strings in the list contains commas (or any character chosen as the delimiter) because it will turn a single entry into multiple entries but it is the easiest to read and most concise.
  • The problem with CAD bloke's answer is that it is ugly and requires the model to be altered which is a bad design practice (see Marcell Toth's comment on Sasan's answer). But it is the only answer that is data-safe.

Difference between string object and string literal

According to String class documentation they are equivalent.

Documentation for String(String original) also says that: Unless an explicit copy of original is needed, use of this constructor is unnecessary since Strings are immutable.

Look for other responses, because it seems that Java documentation is misleading :(

Batch script to find and replace a string in text file within a minute for files up to 12 MB

Give this a shot:

@echo off
setlocal

call :FindReplace "findstr" "replacestr" input.txt

exit /b 

:FindReplace <findstr> <replstr> <file>
set tmp="%temp%\tmp.txt"
If not exist %temp%\_.vbs call :MakeReplace
for /f "tokens=*" %%a in ('dir "%3" /s /b /a-d /on') do (
  for /f "usebackq" %%b in (`Findstr /mic:"%~1" "%%a"`) do (
    echo(&Echo Replacing "%~1" with "%~2" in file %%~nxa
    <%%a cscript //nologo %temp%\_.vbs "%~1" "%~2">%tmp%
    if exist %tmp% move /Y %tmp% "%%~dpnxa">nul
  )
)
del %temp%\_.vbs
exit /b

:MakeReplace
>%temp%\_.vbs echo with Wscript
>>%temp%\_.vbs echo set args=.arguments
>>%temp%\_.vbs echo .StdOut.Write _
>>%temp%\_.vbs echo Replace(.StdIn.ReadAll,args(0),args(1),1,-1,1)
>>%temp%\_.vbs echo end with

Understanding __getitem__ method

The [] syntax for getting item by key or index is just syntax sugar.

When you evaluate a[i] Python calls a.__getitem__(i) (or type(a).__getitem__(a, i), but this distinction is about inheritance models and is not important here). Even if the class of a may not explicitly define this method, it is usually inherited from an ancestor class.

All the (Python 2.7) special method names and their semantics are listed here: https://docs.python.org/2.7/reference/datamodel.html#special-method-names

Find if a String is present in an array

String[] a= {"tube", "are", "fun"};
Arrays.asList(a).contains("any");

HTTP could not register URL http://+:8000/HelloWCF/. Your process does not have access rights to this namespace

The simple thing you need to do is to close your Visual Studio environment and open it again by using 'Run as administrator'. It should now run successfully.

Shortcut key for commenting out lines of Python code in Spyder

On macOS:

Cmd + 1

On Windows, probably

Ctrl + (/) near right shift key

Angular2: How to load data before rendering the component?

A nice solution that I've found is to do on UI something like:

<div *ngIf="isDataLoaded">
 ...Your page...
</div

Only when: isDataLoaded is true the page is rendered.

Why does the PHP json_encode function convert UTF-8 strings to hexadecimal entities?

Here is my combined solution for various PHP versions.

In my company we are working with different servers with various PHP versions, so I had to find solution working for all.

$phpVersion = substr(phpversion(), 0, 3)*1;

if($phpVersion >= 5.4) {
  $encodedValue = json_encode($value, JSON_UNESCAPED_UNICODE);
} else {
  $encodedValue = preg_replace('/\\\\u([a-f0-9]{4})/e', "iconv('UCS-4LE','UTF-8',pack('V', hexdec('U$1')))", json_encode($value));
}

Credits should go to Marco Gasi & abu. The solution for PHP >= 5.4 is provided in the json_encode docs.

How to create a signed APK file using Cordova command line interface?

First Check your version code and version name if you are updating your app. And make sure you have a previous keystore.

If you are updating app then follow step 1,3,4.

Step 1:

Goto your cordova project for generate our release build:

D:\projects\Phonegap\Example> cordova build --release android

Then, we can find our unsigned APK file in platforms/android/ant-build. In our example, the file was

if u used ant-build

yourproject/platforms/android/ant-build/Example-release-unsigned.apk

OR

if u used gradle-build

yourProject/platforms/android/build/outputs/apk/Example-release-unsigned.apk

Step 2:

Key Generation:

Syntax:

keytool -genkey -v -keystore <keystoreName>.keystore -alias <Keystore AliasName> -keyalg <Key algorithm> -keysize <Key size> -validity <Key Validity in Days>

if keytool command not recognize do this step

Check that the directory the keytool executable is in is on your path. (For example, on my Windows 7 machine, it's in C:\Program Files (x86)\Java\jre6\bin.)

Example:

keytool -genkey -v -keystore NAME-mobileapps.keystore -alias NAMEmobileapps -keyalg RSA -keysize 2048 -validity 10000


keystore password? : xxxxxxx
What is your first and last name? :  xxxxxx
What is the name of your organizational unit? :  xxxxxxxx
What is the name of your organization? :  xxxxxxxxx
What is the name of your City or Locality? :  xxxxxxx
What is the name of your State or Province? :  xxxxx
What is the two-letter country code for this unit? :  xxx

Then the Key store has been generated with name as NAME-mobileapps.keystore

Step 3:

Place the generated keystore in D:\projects\Phonegap\Example\platforms\android\ant-build

To sign the unsigned APK, run the jarsigner tool which is also included in the JDK:

Syntax:

jarsigner -verbose -sigalg SHA1withRSA -digestalg SHA1 -keystore <keystorename <Unsigned APK file> <Keystore Alias name>

If it doesn't reconize do these steps

(1) Right click on "This PC" > right-click Properties > Advanced system settings > Environment Variables > select PATH then EDIT.

(2) Add your jdk bin folder path to environment variables, it should look like this:

"C:\Program Files\Java\jdk1.8.0_40\bin".

Example:

D:\projects\Phonegap\Example\platforms\android\ant-build> jarsigner -verbose -sigalg SHA1withRSA -digestalg SHA1 -keystore NAME-mobileapps.keystore Example-release-unsigned.apk xxxxxmobileapps

Enter KeyPhrase as 'xxxxxxxx'

This signs the apk in place.

Step 4:

Finally, we need to run the zip align tool to optimize the APK:

if zipalign not recognize then

(1) goto your android sdk path and find zipalign it is usually in android-sdk\build-tools\23.0.3

(2) Copy zipalign file paste into your generate release apk folder usually in below path

yourproject/platforms/android/ant-build/Example-release-unsigned.apk

D:\projects\Phonegap\Example\platforms\android\ant-build> zipalign -v 4 Example-release-unsigned.apk Example.apk 

OR

D:\projects\Phonegap\Example\platforms\android\ant-build> C:\Phonegap\adt-bundle-windows-x86_64-20140624\sdk\build-tools\android-4.4W\zipalign -v 4 Example-release-unsigned.apk Example.apk

Now we have our final release binary called example.apk and we can release this on the Google Play Store.

No Entity Framework provider found for the ADO.NET provider with invariant name 'System.Data.SqlClient'

I had the identical exception thrown. I included

using System.Data; 
using System.Data.Entity;

and everything is back to working again ..

How to find and replace string?

Try a combination of std::string::find and std::string::replace.

This gets the position:

std::string s;
std::string toReplace("text to replace");
size_t pos = s.find(toReplace);

And this replaces the first occurrence:

s.replace(pos, toReplace.length(), "new text");

Now you can simply create a function for your convenience:

std::string replaceFirstOccurrence(
    std::string& s,
    const std::string& toReplace,
    const std::string& replaceWith)
{
    std::size_t pos = s.find(toReplace);
    if (pos == std::string::npos) return s;
    return s.replace(pos, toReplace.length(), replaceWith);
}

Does java.util.List.isEmpty() check if the list itself is null?

You can use your own isEmpty (for multiple collection) method too. Add this your Util class.

public static boolean isEmpty(Collection... collections) {
    for (Collection collection : collections) {
        if (null == collection || collection.isEmpty())
            return true;
    }
    return false;
}

Save a list to a .txt file

You can use inbuilt library pickle

This library allows you to save any object in python to a file

This library will maintain the format as well

import pickle
with open('/content/list_1.txt', 'wb') as fp:
    pickle.dump(list_1, fp)

you can also read the list back as an object using same library

with open ('/content/list_1.txt', 'rb') as fp:
    list_1 = pickle.load(fp)

reference : Writing a list to a file with Python

How do I make a simple crawler in PHP?

In it's simplest form:

function crawl_page($url, $depth = 5) {
    if($depth > 0) {
        $html = file_get_contents($url);

        preg_match_all('~<a.*?href="(.*?)".*?>~', $html, $matches);

        foreach($matches[1] as $newurl) {
            crawl_page($newurl, $depth - 1);
        }

        file_put_contents('results.txt', $newurl."\n\n".$html."\n\n", FILE_APPEND);
    }
}

crawl_page('http://www.domain.com/index.php', 5);

That function will get contents from a page, then crawl all found links and save the contents to 'results.txt'. The functions accepts an second parameter, depth, which defines how long the links should be followed. Pass 1 there if you want to parse only links from the given page.

Change class on mouseover in directive

I have run into problems in the past with IE and the css:hover selector so the approach that I have taken, is to use a custom directive.

.directive('hoverClass', function () {
    return {
        restrict: 'A',
        scope: {
            hoverClass: '@'
        },
        link: function (scope, element) {
            element.on('mouseenter', function() {
                element.addClass(scope.hoverClass);
            });
            element.on('mouseleave', function() {
                element.removeClass(scope.hoverClass);
            });
        }
    };
})

then on the element itself you can add the directive with the class names that you want enabled when the mouse is over the the element for example:

<li data-ng-repeat="item in social" hover-class="hover tint" class="social-{{item.name}}" ng-mouseover="hoverItem(true);" ng-mouseout="hoverItem(false);"
                index="{{$index}}"><i class="{{item.icon}}"
                box="course-{{$index}}"></i></li>

This should add the class hover and tint when the mouse is over the element and doesn't run the risk of a scope variable name collision. I haven't tested but the mouseenter and mouseleave events should still bubble up to the containing element so in the given scenario the following should still work

<div hover-class="hover" data-courseoverview data-ng-repeat="course in courses | orderBy:sortOrder | filter:search"
 data-ng-controller ="CourseItemController"
 data-ng-class="{ selected: isSelected }">

providing of course that the li's are infact children of the parent div

How to preview selected image in input type="file" in popup using jQuery?

If your are using HTML5 then try following code snippet

<img id="uploadPreview" style="width: 100px; height: 100px;" />
<input id="uploadImage" type="file" name="myPhoto" onchange="PreviewImage();" />
<script type="text/javascript">

    function PreviewImage() {
        var oFReader = new FileReader();
        oFReader.readAsDataURL(document.getElementById("uploadImage").files[0]);

        oFReader.onload = function (oFREvent) {
            document.getElementById("uploadPreview").src = oFREvent.target.result;
        };
    };

</script>

Use of "this" keyword in formal parameters for static methods in C#

"this" extends the next class in the parameter list

So in the method signature below "this" extends "String". Line is passed to the function as a normal argument to the method. public static string[] SplitCsvLine(this String line)

In the above example "this" class is extending the built in "String" class.

How can I bind a background color in WPF/XAML?

Important:

Make sure you're using System.Windows.Media.Brush and not System.Drawing.Brush

They're not compatible and you'll get binding errors.

The color enumeration you need to use is also different

System.Windows.Media.Colors.Aquamarine (class name is Colors) <--- use this one System.Drawing.Color.Aquamarine (class name is Color)

If in doubt use Snoop and inspect the element's background property to look for binding errors - or just look in your debug log.

How to increase the max upload file size in ASP.NET?

If you use sharepoint you should configure max size with Administrative Tools too: kb925083

use std::fill to populate vector with increasing numbers

In terms of performance you should initialize the vector with use of reserve() combined with push_back() functions like in the example below:

const int numberOfElements = 10;

std::vector<int> data;
data.reserve(numberOfElements);

for(int i = 0; i < numberOfElements; i++)
    data.push_back(i);

All the std::fill, std::generate, etc. are operating on range of existing vector content, and, therefore the vector must be filled with some data earlier. Even doing the following: std::vector<int> data(10); creates a vector with all elements set to its default value (i.e. 0 in case of int).

The above code avoids to initialize vector content before filling it with the data you really want. Performance of this solution is well visible on large data sets.

Convert varchar to float IF ISNUMERIC

..extending Mikaels' answers

SELECT
  CASE WHEN ISNUMERIC(QTY + 'e0') = 1 THEN CAST(QTY AS float) ELSE null END AS MyFloat
  CASE WHEN ISNUMERIC(QTY + 'e0') = 0 THEN QTY ELSE null END AS MyVarchar
FROM
  ...
  • Two data types requires two columns
  • Adding e0 fixes some ISNUMERIC issues (such as + - . and empty string being accepted)

How to trim a list in Python

You just subindex it with [:5] indicating that you want (up to) the first 5 elements.

>>> [1,2,3,4,5,6,7,8][:5]
[1, 2, 3, 4, 5]
>>> [1,2,3][:5]
[1, 2, 3]
>>> x = [6,7,8,9,10,11,12]
>>> x[:5]
[6, 7, 8, 9, 10]

Also, putting the colon on the right of the number means count from the nth element onwards -- don't forget that lists are 0-based!

>>> x[5:]
[11, 12]

Creating default object from empty value in PHP?

I had similar problem and this seem to solve the problem. You just need to initialize the $res object to a class . Suppose here the class name is test.

class test
{
   //You can keep the class empty or declare your success variable here
}
$res = new test();
$res->success = false;

Why am I getting Unknown error in line 1 of pom.xml?

You must to upgrade the m2e connector. It's a known bug, but there is a solution:

  1. Into Eclipse click "Help" > "Install new Software..."

  2. Appears a window. In the "Install" window:

    2a. Into the input box "Work with", enter next site location and press Enter https://download.eclipse.org/m2e-wtp/releases/1.4/

    2b. Appears a lot of information into "Name" input Box. Select all the items

    2c. Click "Next" Button.

Finish the installation and restart Eclipse.

SQL alias for SELECT statement

Not sure exactly what you try to denote with that syntax, but in almost all RDBMS-es you can use a subquery in the FROM clause (sometimes called an "inline-view"):

SELECT..
FROM (
     SELECT ...
     FROM ...
     ) my_select
WHERE ...

In advanced "enterprise" RDBMS-es (like oracle, SQL Server, postgresql) you can use common table expressions which allows you to refer to a query by name and reuse it even multiple times:

-- Define the CTE expression name and column list.
WITH Sales_CTE (SalesPersonID, SalesOrderID, SalesYear)
AS
-- Define the CTE query.
(
    SELECT SalesPersonID, SalesOrderID, YEAR(OrderDate) AS SalesYear
    FROM Sales.SalesOrderHeader
    WHERE SalesPersonID IS NOT NULL
)
-- Define the outer query referencing the CTE name.
SELECT SalesPersonID, COUNT(SalesOrderID) AS TotalSales, SalesYear
FROM Sales_CTE
GROUP BY SalesYear, SalesPersonID
ORDER BY SalesPersonID, SalesYear;

(example from http://msdn.microsoft.com/en-us/library/ms190766(v=sql.105).aspx)

How to get terminal's Character Encoding

To see the current locale information use locale command. Below is an example on RHEL 7.8

[usr@host ~]$ locale
LANG=en_US.UTF-8
LC_CTYPE="en_US.UTF-8"
LC_NUMERIC="en_US.UTF-8"
LC_TIME="en_US.UTF-8"
LC_COLLATE="en_US.UTF-8"
LC_MONETARY="en_US.UTF-8"
LC_MESSAGES="en_US.UTF-8"
LC_PAPER="en_US.UTF-8"
LC_NAME="en_US.UTF-8"
LC_ADDRESS="en_US.UTF-8"
LC_TELEPHONE="en_US.UTF-8"
LC_MEASUREMENT="en_US.UTF-8"
LC_IDENTIFICATION="en_US.UTF-8"
LC_ALL=

How do I redirect with JavaScript?

To redirect to another page, you can use:

window.location = "http://www.yoururl.com";

Html helper for <input type="file" />

Or you could do it properly:

In your HtmlHelper Extension class:

public static MvcHtmlString FileFor<TModel, TProperty>(this HtmlHelper<TModel> helper, Expression<Func<TModel, TProperty>> expression)
    {
        return helper.FileFor(expression, null);
    }

public static MvcHtmlString FileFor<TModel, TProperty>(this HtmlHelper<TModel> helper, Expression<Func<TModel, TProperty>> expression, object htmlAttributes)
    {
        var builder = new TagBuilder("input");

        var id = helper.ViewContext.ViewData.TemplateInfo.GetFullHtmlFieldName(ExpressionHelper.GetExpressionText(expression));
        builder.GenerateId(id);
        builder.MergeAttribute("name", id);
        builder.MergeAttribute("type", "file");

        builder.MergeAttributes(new RouteValueDictionary(htmlAttributes));

        // Render tag
        return MvcHtmlString.Create(builder.ToString(TagRenderMode.SelfClosing));
    }

This line:

var id = helper.ViewContext.ViewData.TemplateInfo.GetFullHtmlFieldName(ExpressionHelper.GetExpressionText(expression));

Generates an id unique to the model, you know in lists and stuff. model[0].Name etc.

Create the correct property in the model:

public HttpPostedFileBase NewFile { get; set; }

Then you need to make sure your form will send files:

@using (Html.BeginForm("Action", "Controller", FormMethod.Post, new { enctype = "multipart/form-data" }))

Then here's your helper:

@Html.FileFor(x => x.NewFile)

Specifying row names when reading in a file

See ?read.table. Basically, when you use read.table, you specify a number indicating the column:

##Row names in the first column
read.table(filname.txt, row.names=1)

How to recompile with -fPIC

I hit this same issue trying to install Dashcast on Centos 7. The fix was adding -fPIC at the end of each of the CFLAGS in the x264 Makefile. Then I had to run make distclean for both x264 and ffmpeg and rebuild.

ModelState.IsValid == false, why?

Paste the below code in the ActionResult of your controller and place the debugger at this point.

var errors = ModelState
    .Where(x => x.Value.Errors.Count > 0)
    .Select(x => new { x.Key, x.Value.Errors })
    .ToArray();

Angular 6: How to set response type as text while making http call

To get rid of error:

Type '"text"' is not assignable to type '"json"'.

Use

responseType: 'text' as 'json'

import { HttpClient, HttpHeaders } from '@angular/common/http';
.....
 return this.http
        .post<string>(
            this.baseUrl + '/Tickets/getTicket',
            JSON.stringify(value),
        { headers, responseType: 'text' as 'json' }
        )
        .map(res => {
            return res;
        })
        .catch(this.handleError);

How to align this span to the right of the div?

Working with floats is bit messy:

This as many other 'trivial' layout tricks can be done with flexbox.

   div.container {
     display: flex;
     justify-content: space-between;
   }

In 2017 I think this is preferred solution (over float) if you don't have to support legacy browsers: https://caniuse.com/#feat=flexbox

Check fiddle how different float usages compares to flexbox ("may include some competing answers"): https://jsfiddle.net/b244s19k/25/. If you still need to stick with float I recommended third version of course.

How to make pylab.savefig() save image for 'maximized' window instead of default size

I did the same search time ago, it seems that he exact solution depends on the backend.

I have read a bunch of sources and probably the most useful was the answer by Pythonio here How to maximize a plt.show() window using Python I adjusted the code and ended up with the function below. It works decently for me on windows, I mostly use Qt, where I use it quite often, while it is minimally tested with other backends.

Basically it consists in identifying the backend and calling the appropriate function. Note that I added a pause afterwards because I was having issues with some windows getting maximized and others not, it seems this solved for me.

def maximize(backend=None,fullscreen=False):
    """Maximize window independently on backend.
    Fullscreen sets fullscreen mode, that is same as maximized, but it doesn't have title bar (press key F to toggle full screen mode)."""
    if backend is None:
        backend=matplotlib.get_backend()
    mng = plt.get_current_fig_manager()

    if fullscreen:
        mng.full_screen_toggle()
    else:
        if backend == 'wxAgg':
            mng.frame.Maximize(True)
        elif backend == 'Qt4Agg' or backend == 'Qt5Agg':
            mng.window.showMaximized()
        elif backend == 'TkAgg':
            mng.window.state('zoomed') #works fine on Windows!
        else:
            print ("Unrecognized backend: ",backend) #not tested on different backends (only Qt)
    plt.show()

    plt.pause(0.1) #this is needed to make sure following processing gets applied (e.g. tight_layout)

Is there a limit on number of tcp/ip connections between machines on linux?

There is a limit, yes. See ulimit.

Also you need to consider the TIMED_WAIT state. Once a TCP socket is closed (by default) the port remains occupied in TIMED_WAIT status for 2 minutes. This value is tunable. This will also "run you out of sockets" even though they are closed.

Run netstat to see the TIMED_WAIT stuff in action.

P.S. The reason for TIMED_WAIT is to handle the case of packets arriving after the socket is closed. This can happen because packets are delayed or the other side just doesn't know that the socket has been closed yet. This allows the OS to silently drop those packets without a chance of "infecting" a different, unrelated socket connection.

What are the differences between 'call-template' and 'apply-templates' in XSL?

To add to the good answer by @Tomalak:

Here are some unmentioned and important differences:

  1. xsl:apply-templates is much richer and deeper than xsl:call-templates and even from xsl:for-each, simply because we don't know what code will be applied on the nodes of the selection -- in the general case this code will be different for different nodes of the node-list.

  2. The code that will be applied can be written way after the xsl:apply templates was written and by people that do not know the original author.

The FXSL library's implementation of higher-order functions (HOF) in XSLT wouldn't be possible if XSLT didn't have the <xsl:apply-templates> instruction.

Summary: Templates and the <xsl:apply-templates> instruction is how XSLT implements and deals with polymorphism.

Reference: See this whole thread: http://www.biglist.com/lists/lists.mulberrytech.com/xsl-list/archives/200411/msg00546.html

Error:Execution failed for task ':app:transformClassesWithDexForDebug' in android studio

Or you can try this -

Extend your Application class with MultiDexApplication instead of Application !

What is the purpose of class methods?

@classmethod can be useful for easily instantiating objects of that class from outside resources. Consider the following:

import settings

class SomeClass:
    @classmethod
    def from_settings(cls):
        return cls(settings=settings)

    def __init__(self, settings=None):
        if settings is not None:
            self.x = settings['x']
            self.y = settings['y']

Then in another file:

from some_package import SomeClass

inst = SomeClass.from_settings()

Accessing inst.x will give the same value as settings['x'].

Print raw string from variable? (not getting the answers)

I have my variable assigned to big complex pattern string for using with re module and it is concatenated with few other strings and in the end I want to print it then copy and check on regex101.com. But when I print it in the interactive mode I get double slash - '\\w' as @Jimmynoarms said:

The Solution for python 3x:

print(r'%s' % your_variable_pattern_str)

How can I get the external SD card path for Android 4.0+?

On some devices (for example samsung galaxy sII )internal memory card mabe be in vfat. In this case use refer last code, we obtain path internal memory card (/mnt/sdcad) but no external card. Code refer below solve this problem.

static String getExternalStorage(){
         String exts =  Environment.getExternalStorageDirectory().getPath();
         try {
            FileReader fr = new FileReader(new File("/proc/mounts"));       
            BufferedReader br = new BufferedReader(fr);
            String sdCard=null;
            String line;
            while((line = br.readLine())!=null){
                if(line.contains("secure") || line.contains("asec")) continue;
            if(line.contains("fat")){
                String[] pars = line.split("\\s");
                if(pars.length<2) continue;
                if(pars[1].equals(exts)) continue;
                sdCard =pars[1]; 
                break;
            }
        }
        fr.close();
        br.close();
        return sdCard;  

     } catch (Exception e) {
        // TODO Auto-generated catch block
        e.printStackTrace();
    }
    return null;
}

Java - Relative path of a file in a java web application

there is another way, if you are using a container like Tomcat :

String textPath = "http://localhost:8080/NameOfWebapp/resources/images/file.txt";

Checking to see if one array's elements are in another array in PHP

Performance test for in_array vs array_intersect:

$a1 = array(2,4,8,11,12,13,14,15,16,17,18,19,20);

$a2 = array(3,20);

$intersect_times = array();
$in_array_times = array();
for($j = 0; $j < 10; $j++)
{
    /***** TEST ONE array_intersect *******/
    $t = microtime(true);
    for($i = 0; $i < 100000; $i++)
    {
        $x = array_intersect($a1,$a2);
        $x = empty($x);
    }
    $intersect_times[] = microtime(true) - $t;


    /***** TEST TWO in_array *******/
    $t2 = microtime(true);
    for($i = 0; $i < 100000; $i++)
    {
        $x = false;
        foreach($a2 as $v){
            if(in_array($v,$a1))
            {
                $x = true;
                break;
            }
        }
    }
    $in_array_times[] = microtime(true) - $t2;
}

echo '<hr><br>'.implode('<br>',$intersect_times).'<br>array_intersect avg: '.(array_sum($intersect_times) / count($intersect_times));
echo '<hr><br>'.implode('<br>',$in_array_times).'<br>in_array avg: '.(array_sum($in_array_times) / count($in_array_times));
exit;

Here are the results:

0.26520013809204
0.15600109100342
0.15599989891052
0.15599989891052
0.1560001373291
0.1560001373291
0.15599989891052
0.15599989891052
0.15599989891052
0.1560001373291
array_intersect avg: 0.16692011356354

0.015599966049194
0.031199932098389
0.031200170516968
0.031199932098389
0.031200885772705
0.031199932098389
0.031200170516968
0.031201124191284
0.031199932098389
0.031199932098389
in_array avg: 0.029640197753906

in_array is at least 5 times faster. Note that we "break" as soon as a result is found.

How to update a single library with Composer?

You can basically do following one to install new package as well.

php composer.phar require

then terminal will ask you to enter the name of the package for searching.

$ Search for a package []: //Your package name here

Then terminal will ask the version of the package (If you would like to have the latest version just leave it blank)

$ Enter the version constraint to require (or leave blank to use the latest version) []: //your version number here

Then you just press the return key. Terminal will ask for another package, if you dont want to install another one just press the return key and you will be done.

For loop in Objective-C

You mean fast enumeration? You question is very unclear.

A normal for loop would look a bit like this:

unsigned int i, cnt = [someArray count];
for(i = 0; i < cnt; i++)
{ 
   // do loop stuff
   id someObject = [someArray objectAtIndex:i];
}

And a loop with fast enumeration, which is optimized by the compiler, would look like this:

for(id someObject in someArray)
{
   // do stuff with object
}

Keep in mind that you cannot change the array you are using in fast enumeration, thus no deleting nor adding when using fast enumeration

In-place edits with sed on OS X

You can use:

sed -i -e 's/<string-to-find>/<string-to-replace>/' <your-file-path>

Example:

sed -i -e 's/Hello/Bye/' file.txt

This works flawless in Mac.

How do I find the date a video (.AVI .MP4) was actually recorded?

The best way I found of getting the "dateTaken" date for either video or pictures is to use:

 Imports Microsoft.WindowsAPICodePack.Shell
 Imports Microsoft.WindowsAPICodePack.Shell.PropertySystem
 Imports System.IO
 Dim picture As ShellObject = ShellObject.FromParsingName(path)
 Dim picture As ShellObject = ShellObject.FromParsingName(path)
 Dim ItemDate=picture.Properties.System.ItemDate

The above code requires the shell api, which is internal to Microsoft, and does not depend on any other external dll.

Remove a HTML tag but keep the innerHtml

Another native solution (in coffee):

el = document.getElementsByTagName 'b'

docFrag = document.createDocumentFragment()
docFrag.appendChild el.firstChild while el.childNodes.length

el.parentNode.replaceChild docFrag, el

I don't know if it's faster than user113716's solution, but it might be easier to understand for some.

how to open popup window using jsp or jquery?

<a href="javaScript:{openPopUp();}"></a>
<form action="actionName">
<div id="divId" style="display:none;">
UsreName:<input type="text" name="userName"/>
</div>
</form>

function openPopUp()
{
  $('#divId').css('display','block');
$('#divId').dialog();
}

How do I encrypt and decrypt a string in python?

For Decryption:

     def decrypt(my_key=KEY, my_iv=IV, encryptText=encrypttext):

        key = binascii.unhexlify(my_key)
        iv = binascii.unhexlify(my_iv)
        encryptor = AES.new(key, AES.MODE_CBC, iv, segment_size=128)  # Initialize encryptor
        result = encryptor.decrypt(binascii.a2b_hex(encryptText))
        padder = PKCS7Padder()
        decryptText=padder.decode(result)  

           return {
          "plain": encryptText,
          "key": binascii.hexlify(key),
          "iv": binascii.hexlify(iv),
          "decryptedTest": decryptText
}

Compilation error - missing zlib.h

You are missing zlib.h header file, on Linux install it via:

sudo apt-get install libz-dev

As a matter of fact, the module presents as zlib1g-dev in the apt repo, so this is the up-to-date call (Feb 2019):

sudo apt install zlib1g-dev

On Fedora: sudo dnf install zlib-devel (in older versions: sudo dnf install libz-devel).

This will provide the development support files for a library implementing the deflate compression method found in gzip and PKZIP.

If you've already zlib library, make sure you're compiling your code sources with -lz. See: How to fix undefined references to inflate/deflate functions?.

Best way to get all selected checkboxes VALUES in jQuery

You want the :checkbox:checked selector and map to create an array of the values:

var checkedValues = $('input:checkbox:checked').map(function() {
    return this.value;
}).get();

If your checkboxes have a shared class it would be faster to use that instead, eg. $('.mycheckboxes:checked'), or for a common name $('input[name="Foo"]:checked')

- Update -

If you don't need IE support then you can now make the map() call more succinct by using an arrow function:

var checkedValues = $('input:checkbox:checked').map((i, el) => el.value).get();

Maven:Non-resolvable parent POM and 'parent.relativePath' points at wrong local POM

I'm probably a bit late to the party, but I wrote the junitcategorizer for my thesis project at TOPdesk. Earlier versions indeed used a company internal Parent POM. So your problems are caused by the Parent POM not being resolvable, since it is not available to the outside world.

You can either:

  • Remove the <parent> block, but then have to configure the Surefire, Compiler and other plugins yourself
  • (Only applicable to this specific case!) Change it to point to our Open Source Parent POM by setting:
<parent>
    <groupId>com.topdesk</groupId>
    <artifactId>open-source-parent</artifactId>
    <version>1.2.0</version>
</parent>

How to write PNG image to string with the PIL?

With modern (as of mid-2017 Python 3.5 and Pillow 4.0):

StringIO no longer seems to work as it used to. The BytesIO class is the proper way to handle this. Pillow's save function expects a string as the first argument, and surprisingly doesn't see StringIO as such. The following is similar to older StringIO solutions, but with BytesIO in its place.

from io import BytesIO
from PIL import Image

image = Image.open("a_file.png")
faux_file = BytesIO()
image.save(faux_file, 'png')

How to print an unsigned char in C?

This is because in this case the char type is signed on your system*. When this happens, the data gets sign-extended during the default conversions while passing the data to the function with variable number of arguments. Since 212 is greater than 0x80, it's treated as negative, %u interprets the number as a large positive number:

212 = 0xD4

When it is sign-extended, FFs are pre-pended to your number, so it becomes

0xFFFFFFD4 = 4294967252

which is the number that gets printed.

Note that this behavior is specific to your implementation. According to C99 specification, all char types are promoted to (signed) int, because an int can represent all values of a char, signed or unsigned:

6.1.1.2: If an int can represent all values of the original type, the value is converted to an int; otherwise, it is converted to an unsigned int.

This results in passing an int to a format specifier %u, which expects an unsigned int.

To avoid undefined behavior in your program, add explicit type casts as follows:

unsigned char ch = (unsigned char)212;
printf("%u", (unsigned int)ch);


* In general, the standard leaves the signedness of char up to the implementation. See this question for more details.

How to set image for bar button with swift?

Your problem is because of the way the icon has been made - it doesn't conform to Apple's custom tab bar icon specs:

To design a custom bar icon, follow these guidelines:

  • Use pure white with appropriate alpha transparency.
  • Don’t include a drop shadow.
  • Use antialiasing.

(From the guidelines.)

Something that would be possible looks like this. You can find such icons on most free tab bar icon sites.

Button example

Set value of input instead of sendKeys() - Selenium WebDriver nodejs

An alternative way of sending a large number of repeating characters to a text field (for instance to test the maximum number of characters the field will allow) is to type a few characters and then repeatedly copy and paste them:

inputField.sendKeys('0123456789');
for(int i = 0; i < 100; i++) {
    inputField.sendKeys(Key.chord(Key.CONTROL, 'a'));
    inputField.sendKeys(Key.chord(Key.CONTROL, 'c'));
    for(int i = 0; i < 10; i++) {
        inputField.sendKeys(Key.chord(Key.CONTROL, 'v'));
    }
}

Unfortunately pressing CTRL doesn't seem to work for IE unless REQUIRE_WINDOW_FOCUS is enabled (which can cause other issues), but it works fine for Firefox and Chrome.

Array versus List<T>: When to use which?

Rather than going through a comparison of the features of each data type, I think the most pragmatic answer is "the differences probably aren't that important for what you need to accomplish, especially since they both implement IEnumerable, so follow popular convention and use a List until you have a reason not to, at which point you probably will have your reason for using an array over a List."

Most of the time in managed code you're going to want to favor collections being as easy to work with as possible over worrying about micro-optimizations.

How can I get the max (or min) value in a vector?

You can use max_element to get the maximum value in vector. The max_element returns an iterator to largest value in the range, or last if the range is empty. As an iterator is like pointers (or you can say pointer is a form of iterator), you can use a * before it to get the value. So as per the problem you can get the maximum element in an vector as:

int max=*max_element(cloud.begin(), cloud.end());

It will give you the maximum element in your vector "cloud". Hope it helps.

What is this: [Ljava.lang.Object;?

[Ljava.lang.Object; is the name for Object[].class, the java.lang.Class representing the class of array of Object.

The naming scheme is documented in Class.getName():

If this class object represents a reference type that is not an array type then the binary name of the class is returned, as specified by the Java Language Specification (§13.1).

If this class object represents a primitive type or void, then the name returned is the Java language keyword corresponding to the primitive type or void.

If this class object represents a class of arrays, then the internal form of the name consists of the name of the element type preceded by one or more '[' characters representing the depth of the array nesting. The encoding of element type names is as follows:

Element Type        Encoding
boolean             Z
byte                B
char                C
double              D
float               F
int                 I
long                J
short               S 
class or interface  Lclassname;

Yours is the last on that list. Here are some examples:

// xxxxx varies
System.out.println(new int[0][0][7]); // [[[I@xxxxx
System.out.println(new String[4][2]); // [[Ljava.lang.String;@xxxxx
System.out.println(new boolean[256]); // [Z@xxxxx

The reason why the toString() method on arrays returns String in this format is because arrays do not @Override the method inherited from Object, which is specified as follows:

The toString method for class Object returns a string consisting of the name of the class of which the object is an instance, the at-sign character `@', and the unsigned hexadecimal representation of the hash code of the object. In other words, this method returns a string equal to the value of:

getClass().getName() + '@' + Integer.toHexString(hashCode())

Note: you can not rely on the toString() of any arbitrary object to follow the above specification, since they can (and usually do) @Override it to return something else. The more reliable way of inspecting the type of an arbitrary object is to invoke getClass() on it (a final method inherited from Object) and then reflecting on the returned Class object. Ideally, though, the API should've been designed such that reflection is not necessary (see Effective Java 2nd Edition, Item 53: Prefer interfaces to reflection).


On a more "useful" toString for arrays

java.util.Arrays provides toString overloads for primitive arrays and Object[]. There is also deepToString that you may want to use for nested arrays.

Here are some examples:

int[] nums = { 1, 2, 3 };

System.out.println(nums);
// [I@xxxxx

System.out.println(Arrays.toString(nums));
// [1, 2, 3]

int[][] table = {
        { 1, },
        { 2, 3, },
        { 4, 5, 6, },
};

System.out.println(Arrays.toString(table));
// [[I@xxxxx, [I@yyyyy, [I@zzzzz]

System.out.println(Arrays.deepToString(table));
// [[1], [2, 3], [4, 5, 6]]

There are also Arrays.equals and Arrays.deepEquals that perform array equality comparison by their elements, among many other array-related utility methods.

Related questions

min and max value of data type in C

I wrote some macros that return the min and max of any type, regardless of signedness:

#define MAX_OF(type) \
    (((type)(~0LLU) > (type)((1LLU<<((sizeof(type)<<3)-1))-1LLU)) ? (long long unsigned int)(type)(~0LLU) : (long long unsigned int)(type)((1LLU<<((sizeof(type)<<3)-1))-1LLU))
#define MIN_OF(type) \
    (((type)(1LLU<<((sizeof(type)<<3)-1)) < (type)1) ? (long long int)((~0LLU)-((1LLU<<((sizeof(type)<<3)-1))-1LLU)) : 0LL)

Example code:

#include <stdio.h>
#include <sys/types.h>
#include <inttypes.h>

#define MAX_OF(type) \
    (((type)(~0LLU) > (type)((1LLU<<((sizeof(type)<<3)-1))-1LLU)) ? (long long unsigned int)(type)(~0LLU) : (long long unsigned int)(type)((1LLU<<((sizeof(type)<<3)-1))-1LLU))
#define MIN_OF(type) \
    (((type)(1LLU<<((sizeof(type)<<3)-1)) < (type)1) ? (long long int)((~0LLU)-((1LLU<<((sizeof(type)<<3)-1))-1LLU)) : 0LL)

int main(void)
{
    printf("uint32_t = %lld..%llu\n", MIN_OF(uint32_t), MAX_OF(uint32_t));
    printf("int32_t = %lld..%llu\n", MIN_OF(int32_t), MAX_OF(int32_t));
    printf("uint64_t = %lld..%llu\n", MIN_OF(uint64_t), MAX_OF(uint64_t));
    printf("int64_t = %lld..%llu\n", MIN_OF(int64_t), MAX_OF(int64_t));
    printf("size_t = %lld..%llu\n", MIN_OF(size_t), MAX_OF(size_t));
    printf("ssize_t = %lld..%llu\n", MIN_OF(ssize_t), MAX_OF(ssize_t));
    printf("pid_t = %lld..%llu\n", MIN_OF(pid_t), MAX_OF(pid_t));
    printf("time_t = %lld..%llu\n", MIN_OF(time_t), MAX_OF(time_t));
    printf("intptr_t = %lld..%llu\n", MIN_OF(intptr_t), MAX_OF(intptr_t));
    printf("unsigned char = %lld..%llu\n", MIN_OF(unsigned char), MAX_OF(unsigned char));
    printf("char = %lld..%llu\n", MIN_OF(char), MAX_OF(char));
    printf("uint8_t = %lld..%llu\n", MIN_OF(uint8_t), MAX_OF(uint8_t));
    printf("int8_t = %lld..%llu\n", MIN_OF(int8_t), MAX_OF(int8_t));
    printf("uint16_t = %lld..%llu\n", MIN_OF(uint16_t), MAX_OF(uint16_t));
    printf("int16_t = %lld..%llu\n", MIN_OF(int16_t), MAX_OF(int16_t));
    printf("int = %lld..%llu\n", MIN_OF(int), MAX_OF(int));
    printf("long int = %lld..%llu\n", MIN_OF(long int), MAX_OF(long int));
    printf("long long int = %lld..%llu\n", MIN_OF(long long int), MAX_OF(long long int));
    printf("off_t = %lld..%llu\n", MIN_OF(off_t), MAX_OF(off_t));

    return 0;
}

Waiting on a list of Future

maybe this would help (nothing would replaced with raw thread, yeah!) I suggest run each Future guy with a separated thread (they goes parallel), then when ever one of the got error, it just signal the manager(Handler class).

class Handler{
//...
private Thread thisThread;
private boolean failed=false;
private Thread[] trds;
public void waitFor(){
  thisThread=Thread.currentThread();
  List<Future<Object>> futures = getFutures();
  trds=new Thread[futures.size()];
  for (int i = 0; i < trds.length; i++) {
    RunTask rt=new RunTask(futures.get(i), this);
    trds[i]=new Thread(rt);
  }
  synchronized (this) {
    for(Thread tx:trds){
      tx.start();
    }  
  }
  for(Thread tx:trds){
    try {tx.join();
    } catch (InterruptedException e) {
      System.out.println("Job failed!");break;
    }
  }if(!failed){System.out.println("Job Done");}
}

private List<Future<Object>> getFutures() {
  return null;
}

public synchronized void cancelOther(){if(failed){return;}
  failed=true;
  for(Thread tx:trds){
    tx.stop();//Deprecated but works here like a boss
  }thisThread.interrupt();
}
//...
}
class RunTask implements Runnable{
private Future f;private Handler h;
public RunTask(Future f,Handler h){this.f=f;this.h=h;}
public void run(){
try{
f.get();//beware about state of working, the stop() method throws ThreadDeath Error at any thread state (unless it blocked by some operation)
}catch(Exception e){System.out.println("Error, stopping other guys...");h.cancelOther();}
catch(Throwable t){System.out.println("Oops, some other guy has stopped working...");}
}
}

I have to say the above code would error(didn't check), but I hope I could explain the solution. please have a try.

How to get the Power of some Integer in Swift language?

func calc (base:Int, number:Int) -> Int {
    var answer : Int = base
    for _ in 2...number {answer *= base } 
    return answer
}

Example:

calc (2,2)

How to create a directive with a dynamic template in AngularJS?

I managed to deal with this problem. Below is the link :

https://github.com/nakosung/ng-dynamic-template-example

with the specific file being:

https://github.com/nakosung/ng-dynamic-template-example/blob/master/src/main.coffee

dynamicTemplate directive hosts dynamic template which is passed within scope and hosted element acts like other native angular elements.

scope.template = '< div ng-controller="SomeUberCtrl">rocks< /div>'

What is the difference between GitHub and gist?

You can access Gist by visiting the following url gist.github.com. Alternatively you can access it from within your Github account (after logging in) as shown in the picture below:

how to access gist from within the github console

 

Github: A hosting service that houses a web-based git repository. It includes all the fucntionality of git with additional features added in.

 

Gist: Is an additional feature added to github to allow the sharing of code snippets, notes, to do lists and more. You can save your Gists as secret or public. Secret Gists are hidden from search engines but visible to anyone you share the url with.

For example. If you wanted to write a private to-do list. You could write one using Github Markdown as follows:

how to write a private to do list

NB: It is important to preserve the whitespace as shown above between the dash and brackets. It is also important that you save the file with the extension .md because we want the markdown to format properly. Remember to save this Gist as secret if you do not want others to see it.

 

The end result looks like the image below. The checkboxes are clickable because we saved this Gist with the extension .md

What the to do list looks like if you have formatted it properly

How do I refresh the page in ASP.NET? (Let it reload itself by code)

This might be late, but I hope it helps someone who is looking for the answer.

You can use the following line to do that:

Server.TransferRequest(Request.Url.AbsolutePath, false);

Try to avoid using Response.Redirect as it increases the steps in the process. What it actually does is:

  1. Sends back the page with redirection header
  2. The Browser redirects to the destination URL.

As you can see, the same outcome takes 2 trips rather than 1 trip.

AngularJS ng-style with a conditional expression

@jfredsilva obviously has the simplest answer for the question:

ng-style="{ 'width' : (myObject.value == 'ok') ? '100%' : '0%' }"

However, you might really want to consider my answer for something more complex.

Ternary-like example:

<p ng-style="{width: {true:'100%',false:'0%'}[myObject.value == 'ok']}"></p>

Something more complex:

<p ng-style="{
   color:       {blueish: 'blue', greenish: 'green'}[ color ], 
  'font-size':  {0: '12px', 1: '18px', 2: '26px'}[ zoom ]
}">Test</p>

If $scope.color == 'blueish', the color will be 'blue'.

If $scope.zoom == 2, the font-size will be 26px.

_x000D_
_x000D_
angular.module('app',[]);_x000D_
function MyCtrl($scope) {_x000D_
  $scope.color = 'blueish';_x000D_
  $scope.zoom = 2;_x000D_
}
_x000D_
<script src="https://ajax.googleapis.com/ajax/libs/angularjs/1.0.1/angular.min.js"></script>_x000D_
<div ng-app="app" ng-controller="MyCtrl" ng-style="{_x000D_
   color:       {blueish: 'blue', greenish: 'green'}[ color ], _x000D_
  'font-size':  {0: '12px', 1: '18px', 2: '26px'}[ zoom ]_x000D_
}">_x000D_
  color = {{color}}<br>_x000D_
  zoom = {{zoom}}_x000D_
</div>
_x000D_
_x000D_
_x000D_

Why use deflate instead of gzip for text files served by Apache?

On Ubuntu with Apache2 and the deflate module already installed (which it is by default), you can enable deflate gzip compression in two easy steps:

a2enmod deflate
/etc/init.d/apache2 force-reload

And you're away! I found pages I served over my adsl connection loaded much faster.

Edit: As per @GertvandenBerg's comment, this enables gzip compression, not deflate.

This IP, site or mobile application is not authorized to use this API key

Google Place API requires the referer HTTP header to be included when making the API call.

Include HTTP header "Referer:yourdomain.com" and this should fix the response issues.

SQLite in Android How to update a specific row

First make a ContentValues object :

ContentValues cv = new ContentValues();
cv.put("Field1","Bob"); //These Fields should be your String values of actual column names
cv.put("Field2","19");
cv.put("Field2","Male");

Then use the update method, it should work now:

myDB.update(TableName, cv, "_id = ?", new String[]{id});

Prevent redirect after form is submitted

Since it is bypassing CORS and CSP, this is to keep in the toolbox. Here is a variation.

This will POST a base64 encoded object at localhost:8080, and will clean up the DOM after usage.

_x000D_
_x000D_
const theOBJECT = {message: 'Hello world!', target: 'local'}_x000D_
_x000D_
document.body.innerHTML += '<iframe id="postframe" name="hiddenFrame" width="0" height="0" border="0" style="display: none;"></iframe><form id="dynForm" target="hiddenFrame" action="http://localhost:8080/" method="post"><input type="hidden" name="somedata" value="'+btoa(JSON.stringify(theOBJECT))+'"></form>';_x000D_
document.getElementById("dynForm").submit();_x000D_
dynForm.outerHTML = ""_x000D_
postframe.outerHTML = ""
_x000D_
_x000D_
_x000D_

From the network debugger tab, we can observe a successful POST to a http:// unencrypted server from a tls/https page.

enter image description here

How to obtain the chat_id of a private Telegram channel?

I found the way to write in private channels.

  1. You should convert it to public with some @channelName
  2. Send message to this channel through Bot API

    https://api.telegram.org/bot111:222/sendMessage?chat_id=@channelName&text=123

  3. As response you will get info with chat_id of your channel.

    { "ok" : true, "result" : { "chat" : { "id" : -1001005582487, "title" : "Test Private Channel", "type" : "channel" }, "date" : 1448245538, "message_id" : 7, "text" : "123ds" } }

  4. Now you can convert Channel back to private (by deleting channel's link) and send message directly to this chat_id "-1001005582487"

    https://api.telegram.org/bot111:222/sendMessage?chat_id=-1001005582487&text=123

how to re-format datetime string in php?

date("Y-m-d H:i:s", strtotime("2019-05-13"))

Python: how to capture image from webcam on click using OpenCV

Here is a simple program that displays the camera feed in a cv2.namedWindow and will take a snapshot when you hit SPACE. It will also quit if you hit ESC.

import cv2

cam = cv2.VideoCapture(0)

cv2.namedWindow("test")

img_counter = 0

while True:
    ret, frame = cam.read()
    if not ret:
        print("failed to grab frame")
        break
    cv2.imshow("test", frame)

    k = cv2.waitKey(1)
    if k%256 == 27:
        # ESC pressed
        print("Escape hit, closing...")
        break
    elif k%256 == 32:
        # SPACE pressed
        img_name = "opencv_frame_{}.png".format(img_counter)
        cv2.imwrite(img_name, frame)
        print("{} written!".format(img_name))
        img_counter += 1

cam.release()

cv2.destroyAllWindows()

I think this should answer your question for the most part. If there is any line of it that you don't understand let me know and I'll add comments.

If you need to grab multiple images per press of the SPACE key, you will need an inner loop or perhaps just make a function that grabs a certain number of images.

Note that the key events are from the cv2.namedWindow so it has to have focus.

Android studio Gradle icon error, Manifest Merger

In your .gradle change MinSDK, for example:

  • build.gradle (Module: app)
    • before: minSdkVersion 9
    • after: minSdkVersion 14

etc.

Convert `List<string>` to comma-separated string

That's the way I'd prefer to see if I was maintaining your code. If you manage to find a faster solution, it's going to be very esoteric, and you should really bury it inside of a method that describes what it does.

(does it still work without the ToArray)?

How to check if a character in a string is a digit or letter

By using regular expressions:

boolean isChar = character.matches("[a-zA-z]{1}");
boolean isDigit = character.matches("\\d{1}"); 

LaTeX table positioning

If you want to have two tables next to each other you can use: (with float package loaded)

\begin{table}[H]
 \begin{minipage}{.5\textwidth}
  %first table
 \end{minipage}
 \begin{minipage}{.5\textwidth}
  %second table
 \end{minipage}
\end{table}

Each one will have own caption and number. Another option is subfigure package.

How do I write a method to calculate total cost for all items in an array?

In your for loop you need to multiply the units * price. That gives you the total for that particular item. Also in the for loop you should add that to a counter that keeps track of the grand total. Your code would look something like

float total;
total += theItem.getUnits() * theItem.getPrice();

total should be scoped so it's accessible from within main unless you want to pass it around between function calls. Then you can either just print out the total or create a method that prints it out for you.

C++ string to double conversion

Coversion from string to double can be achieved by using the 'strtod()' function from the library 'stdlib.h'

#include <iostream>
#include <stdlib.h>
int main () 
{
    std::string data="20.9";
    double value = strtod(data.c_str(), NULL);
    std::cout<<value<<'\n';
    return 0;
}

curl usage to get header

curl --head https://www.example.net

I was pointed to this by curl itself; when I issued the command with -X HEAD, it printed:

Warning: Setting custom HTTP method to HEAD with -X/--request may not work the 
Warning: way you want. Consider using -I/--head instead.

select count(*) from table of mysql in php

here is the code for showing no of rows in the table with PHP

$sql="select count(*) as total from student_table";
$result=mysqli_query($con,$sql);
$data=mysqli_fetch_assoc($result);
echo $data['total'];

How to install the Raspberry Pi cross compiler on my Linux host machine?

there is a CDP Studio IDE available that makes cross compile and deploy quite simple from both windows and linux and you can just check the raspberry toolchain checkbox during the installation. (PS. it has GPIO and I2C support so no code is needed to access those)

The IDE demo of raspberry use is up here: https://youtu.be/4SVZ68sQz5U

and you can download the IDE here: https://cdpstudio.com/home-edition

BehaviorSubject vs Observable?

An observable allows you to subscribe only whereas a subject allows you to both publish and subscribe.

So a subject allows your services to be used as both a publisher and a subscriber.

As of now, I'm not so good at Observable so I'll share only an example of Subject.

Let's understand better with an Angular CLI example. Run the below commands:

npm install -g @angular/cli

ng new angular2-subject

cd angular2-subject

ng serve

Replace the content of app.component.html with:

<div *ngIf="message">
  {{message}}
</div>

<app-home>
</app-home>

Run the command ng g c components/home to generate the home component. Replace the content of home.component.html with:

<input type="text" placeholder="Enter message" #message>
<button type="button" (click)="setMessage(message)" >Send message</button>

#message is the local variable here. Add a property message: string; to the app.component.ts's class.

Run this command ng g s service/message. This will generate a service at src\app\service\message.service.ts. Provide this service to the app.

Import Subject into MessageService. Add a subject too. The final code shall look like this:

import { Injectable } from '@angular/core';
import { Subject } from 'rxjs/Subject';

@Injectable()
export class MessageService {

  public message = new Subject<string>();

  setMessage(value: string) {
    this.message.next(value); //it is publishing this value to all the subscribers that have already subscribed to this message
  }
}

Now, inject this service in home.component.ts and pass an instance of it to the constructor. Do this for app.component.ts too. Use this service instance for passing the value of #message to the service function setMessage:

import { Component } from '@angular/core';
import { MessageService } from '../../service/message.service';

@Component({
  selector: 'app-home',
  templateUrl: './home.component.html',
  styleUrls: ['./home.component.css']
})
export class HomeComponent {

  constructor(public messageService:MessageService) { }

  setMessage(event) {
    console.log(event.value);
    this.messageService.setMessage(event.value);
  }
}

Inside app.component.ts, subscribe and unsubscribe (to prevent memory leaks) to the Subject:

import { Component, OnDestroy } from '@angular/core';
import { MessageService } from './service/message.service';
import { Subscription } from 'rxjs/Subscription';

@Component({
  selector: 'app-root',
  templateUrl: './app.component.html'
})
export class AppComponent {

  message: string;
  subscription: Subscription;

  constructor(public messageService: MessageService) { }

  ngOnInit() {
    this.subscription = this.messageService.message.subscribe(
      (message) => {
        this.message = message;
      }
    );
  }

  ngOnDestroy() {
    this.subscription.unsubscribe();
  }
}

That's it.

Now, any value entered inside #message of home.component.html shall be printed to {{message}} inside app.component.html

jQuery select by attribute using AND and OR operators

First find the condition that occurs in all situations, then filter the special conditions:

$('[myc="blue"]')
    .filter('[myid="1"],[myid="3"]');

Is there any free OCR library for Android?

ANother option could be to post the image to a webapp (possibly at a later moment), and have it OCR-processed there without the C++ -> Java port issues and possibly clogging the mobile CPU.

How to update attributes without validation

All the validation from model are skipped when we use validate: false

user = User.new(....)
user.save(validate: false)

Remove redundant paths from $PATH variable

There are no standard tools to "edit" the value of $PATH (i.e. "add folder only when it doesn't already exists" or "remove this folder").

To check what the path would be when you login next time, use telnet localhost (or telnet 127.0.0.1). It will then ask for your username and password.

This gives you a new login shell (i.e. a completely new one that doesn't inherit anything from the current environment).

You can check the value of the $PATH there and edit your rc files until it is correct. This is also useful to see whether you could login again at all after making a change to an important file.

How to search all loaded scripts in Chrome Developer Tools?

In the latest Chrome as of 10/26/2018, the top-rated answer no longer works, here's how it's done: enter image description here

enter image description here

R - Markdown avoiding package loading messages

My best solution on R Markdown was to create a code chunk only to load libraries and exclude everything in the chunk.

{r results='asis', echo=FALSE, include=FALSE,}
knitr::opts_chunk$set(echo = TRUE, warning=FALSE)
#formating tables
library(xtable)

#data wrangling
library(dplyr)

#text processing
library(stringi)

Using multiple parameters in URL in express

For what you want I would've used

    app.get('/fruit/:fruitName&:fruitColor', function(request, response) {
       const name = request.params.fruitName 
       const color = request.params.fruitColor 
    });

or better yet

    app.get('/fruit/:fruit', function(request, response) {
       const fruit = request.params.fruit
       console.log(fruit)
    });

where fruit is a object. So in the client app you just call

https://mydomain.dm/fruit/{"name":"My fruit name", "color":"The color of the fruit"}

and as a response you should see:

    //  client side response
    // { name: My fruit name, color:The color of the fruit}

Detect if HTML5 Video element is playing

Note : This answer was given in 2011. Please check the updated documentation on HTML5 video before proceeding.

If you just want to know whether the video is paused, use the flag stream.paused.

There is no property for video element for getting the playing status. But there is one event "playing" which will be triggered when it starts to play. Event "ended" is triggered when it stops playing.

So the solution is

  1. decalre one variable videoStatus
  2. add event handlers for different events of video
  3. update videoStatus using the event handlers
  4. use videoStatus to identify the status of the video

This page will give you a better idea about video events. Play the video on this page and see how events are triggered.
http://www.w3.org/2010/05/video/mediaevents.html

Disabling enter key for form

if you use jQuery, its quite simple. Here you go

$(document).keypress(
  function(event){
    if (event.which == '13') {
      event.preventDefault();
    }
});