Programs & Examples On #Shortest

Java - Find shortest path between 2 points in a distance weighted map

This maybe too late but No one provided a clear explanation of how the algorithm works

The idea of Dijkstra is simple, let me show this with the following pseudocode.

Dijkstra partitions all nodes into two distinct sets. Unsettled and settled. Initially all nodes are in the unsettled set, e.g. they must be still evaluated.

At first only the source node is put in the set of settledNodes. A specific node will be moved to the settled set if the shortest path from the source to a particular node has been found.

The algorithm runs until the unsettledNodes set is empty. In each iteration it selects the node with the lowest distance to the source node out of the unsettledNodes set. E.g. It reads all edges which are outgoing from the source and evaluates each destination node from these edges which are not yet settled.

If the known distance from the source to this node can be reduced when the selected edge is used, the distance is updated and the node is added to the nodes which need evaluation.

Please note that Dijkstra also determines the pre-successor of each node on its way to the source. I left that out of the pseudo code to simplify it.

Credits to Lars Vogel

Running JAR file on Windows 10

How do I run an executable JAR file? If you have a jar file called Example.jar, follow these rules:

Open a notepad.exe.
Write : java -jar Example.jar.
Save it with the extension .bat.
Copy it to the directory which has the .jar file.
Double click it to run your .jar file.

For files in directory, only echo filename (no path)

Another approach is to use ls when reading the file list within a directory so as to give you what you want, i.e. "just the file name/s". As opposed to reading the full file path and then extracting the "file name" component in the body of the for loop.

Example below that follows your original:

for filename in $(ls /home/user/)
do
  echo $filename
done;

If you are running the script in the same directory as the files, then it simply becomes:

for filename in $(ls)
do
  echo $filename
done;

How to match hyphens with Regular Expression?

Escape the hyphen.

[a-zA-Z0-9!$* \t\r\n\-]

UPDATE:
Never mind this answer - you can add the hyphen to the group but you don't have to escape it. See Konrad Rudolph's answer instead which does a much better job of answering and explains why.

Understanding lambda in python and using it to pass multiple arguments

I believe bind always tries to send an event parameter. Try:

self.entry_1.bind("<Return>", lambda event: self.calculate(self.buttonOut_1.grid_info(), 1))

You accept the parameter and never use it.

Boolean operators ( &&, -a, ||, -o ) in Bash

-a and -o are the older and/or operators for the test command. && and || are and/or operators for the shell. So (assuming an old shell) in your first case,

[ "$1" = 'yes' ] && [ -r $2.txt ]

The shell is evaluating the and condition. In your second case,

[ "$1" = 'yes' -a $2 -lt 3 ]

The test command (or builtin test) is evaluating the and condition.

Of course in all modern or semi-modern shells, the test command is built in to the shell, so there really isn't any or much difference. In modern shells, the if statement can be written:

[[ $1 == yes && -r $2.txt ]]

Which is more similar to modern programming languages and thus is more readable.

"pip install json" fails on Ubuntu

json is a built-in module, you don't need to install it with pip.

How do I compare 2 rows from the same table (SQL Server)?

OK, after 2 years it's finally time to correct the syntax:

SELECT  t1.value, t2.value
FROM    MyTable t1
JOIN    MyTable t2
ON      t1.id = t2.id
WHERE   t1.id = @id
        AND t1.status = @status1
        AND t2.status = @status2

Concatenate a vector of strings/character

You can use stri_paste function with collapse parameter from stringi package like this:

stri_paste(letters, collapse='')
## [1] "abcdefghijklmnopqrstuvwxyz" 

And some benchmarks:

require(microbenchmark)
test <- stri_rand_lipsum(100)
microbenchmark(stri_paste(test, collapse=''), paste(test,collapse=''), do.call(paste, c(as.list(test), sep="")))
Unit: microseconds
                                      expr     min       lq     mean   median       uq     max neval
           stri_paste(test, collapse = "") 137.477 139.6040 155.8157 148.5810 163.5375 226.171   100
                paste(test, collapse = "") 404.139 406.4100 446.0270 432.3250 442.9825 723.793   100
do.call(paste, c(as.list(test), sep = "")) 216.937 226.0265 251.6779 237.3945 264.8935 405.989   100

Manipulating an Access database from Java without ODBC

UCanAccess is a pure Java JDBC driver that allows us to read from and write to Access databases without using ODBC. It uses two other packages, Jackcess and HSQLDB, to perform these tasks. The following is a brief overview of how to get it set up.

 

Option 1: Using Maven

If your project uses Maven you can simply include UCanAccess via the following coordinates:

groupId: net.sf.ucanaccess
artifactId: ucanaccess

The following is an excerpt from pom.xml, you may need to update the <version> to get the most recent release:

  <dependencies>
    <dependency>
        <groupId>net.sf.ucanaccess</groupId>
        <artifactId>ucanaccess</artifactId>
        <version>4.0.4</version>
    </dependency>
  </dependencies>

 

Option 2: Manually adding the JARs to your project

As mentioned above, UCanAccess requires Jackcess and HSQLDB. Jackcess in turn has its own dependencies. So to use UCanAccess you will need to include the following components:

UCanAccess (ucanaccess-x.x.x.jar)
HSQLDB (hsqldb.jar, version 2.2.5 or newer)
Jackcess (jackcess-2.x.x.jar)
commons-lang (commons-lang-2.6.jar, or newer 2.x version)
commons-logging (commons-logging-1.1.1.jar, or newer 1.x version)

Fortunately, UCanAccess includes all of the required JAR files in its distribution file. When you unzip it you will see something like

ucanaccess-4.0.1.jar  
  /lib/
    commons-lang-2.6.jar  
    commons-logging-1.1.1.jar  
    hsqldb.jar  
    jackcess-2.1.6.jar

All you need to do is add all five (5) JARs to your project.

NOTE: Do not add loader/ucanload.jar to your build path if you are adding the other five (5) JAR files. The UcanloadDriver class is only used in special circumstances and requires a different setup. See the related answer here for details.

Eclipse: Right-click the project in Package Explorer and choose Build Path > Configure Build Path.... Click the "Add External JARs..." button to add each of the five (5) JARs. When you are finished your Java Build Path should look something like this

BuildPath.png

NetBeans: Expand the tree view for your project, right-click the "Libraries" folder and choose "Add JAR/Folder...", then browse to the JAR file.

nbAddJar.png

After adding all five (5) JAR files the "Libraries" folder should look something like this:

nbLibraries.png

IntelliJ IDEA: Choose File > Project Structure... from the main menu. In the "Libraries" pane click the "Add" (+) button and add the five (5) JAR files. Once that is done the project should look something like this:

IntelliJ.png

 

That's it!

Now "U Can Access" data in .accdb and .mdb files using code like this

// assumes...
//     import java.sql.*;
Connection conn=DriverManager.getConnection(
        "jdbc:ucanaccess://C:/__tmp/test/zzz.accdb");
Statement s = conn.createStatement();
ResultSet rs = s.executeQuery("SELECT [LastName] FROM [Clients]");
while (rs.next()) {
    System.out.println(rs.getString(1));
}

 

Disclosure

At the time of writing this Q&A I had no involvement in or affiliation with the UCanAccess project; I just used it. I have since become a contributor to the project.

PHP cURL error code 60

php --ini

This will tell you exactly which php.ini file is being loaded, so you know which one to modify. I wasted a lot of time changing the wrong php.ini file because I had WAMP and XAMPP installed.

Also, don't forget to restart the WAMP server (or whatever you use) after changing php.ini.

Selection with .loc in python

It's pandas label-based selection, as explained here: https://pandas.pydata.org/pandas-docs/stable/indexing.html#selection-by-label

The boolean array is basically a selection method using a mask.

how to remove "," from a string in javascript

Use String.replace(), e.g.

var str = "a,d,k";
str = str.replace( /,/g, "" );

Note the g (global) flag on the regular expression, which matches all instances of ",".

How can I restore the MySQL root user’s full privileges?

GRANT ALL ON *.* TO 'user'@'localhost' with GRANT OPTION;

Just log in from root using the respective password if any and simply run the above command to whatever the user is.

For example:

GRANT ALL ON *.* TO 'root'@'%' with GRANT OPTION;

PostgreSQL database default location on Linux

/var/lib/postgresql/[version]/data/

At least in Gentoo Linux and Ubuntu 14.04 by default.

You can find postgresql.conf and look at param data_directory. If it is commented then database directory is the same as this config file directory.

Export DataTable to Excel File

            var lines = new List<string>();

            string[] columnNames = dt.Columns.Cast<DataColumn>().
                                              Select(column => column.ColumnName).
                                              ToArray();

            var header = string.Join(",", columnNames);
            lines.Add(header);
            var valueLines = dt.AsEnumerable()
                               .Select(row => string.Join(",", row.ItemArray));
            lines.AddRange(valueLines);
            File.WriteAllLines("excel.csv", lines);

Here dt refers to your DataTable pass as a paramter

makefiles - compile all c files at once

LIBS  = -lkernel32 -luser32 -lgdi32 -lopengl32
CFLAGS = -Wall

# Should be equivalent to your list of C files, if you don't build selectively
SRC=$(wildcard *.c)

test: $(SRC)
    gcc -o $@ $^ $(CFLAGS) $(LIBS)

How to install MinGW-w64 and MSYS2?

Unfortunately, the MinGW-w64 installer you used sometimes has this issue. I myself am not sure about why this happens (I think it has something to do with Sourceforge URL redirection or whatever that the installer currently can't handle properly enough).

Anyways, if you're already planning on using MSYS2, there's no need for that installer.

  1. Download MSYS2 from this page (choose 32 or 64-bit according to what version of Windows you are going to use it on, not what kind of executables you want to build, both versions can build both 32 and 64-bit binaries).

  2. After the install completes, click on the newly created "MSYS2 Shell" option under either MSYS2 64-bit or MSYS2 32-bit in the Start menu. Update MSYS2 according to the wiki (although I just do a pacman -Syu, ignore all errors and close the window and open a new one, this is not recommended and you should do what the wiki page says).

  3. Install a toolchain

    a) for 32-bit:

    pacman -S mingw-w64-i686-gcc
    

    b) for 64-bit:

    pacman -S mingw-w64-x86_64-gcc
    
  4. install any libraries/tools you may need. You can search the repositories by doing

    pacman -Ss name_of_something_i_want_to_install
    

    e.g.

    pacman -Ss gsl
    

    and install using

    pacman -S package_name_of_something_i_want_to_install
    

    e.g.

    pacman -S mingw-w64-x86_64-gsl
    

    and from then on the GSL library is automatically found by your MinGW-w64 64-bit compiler!

  5. Open a MinGW-w64 shell:

    a) To build 32-bit things, open the "MinGW-w64 32-bit Shell"

    b) To build 64-bit things, open the "MinGW-w64 64-bit Shell"

  6. Verify that the compiler is working by doing

    gcc -v
    

If you want to use the toolchains (with installed libraries) outside of the MSYS2 environment, all you need to do is add <MSYS2 root>/mingw32/bin or <MSYS2 root>/mingw64/bin to your PATH.

Attach a file from MemoryStream to a MailMessage in C#

use OTHER OPEN memorystream:

example for lauch pdf and send pdf in MVC4 C# Controller

        public void ToPdf(string uco, int idAudit)
    {
        Response.Clear();
        Response.ContentType = "application/octet-stream";
        Response.AddHeader("content-disposition", "attachment;filename= Document.pdf");
        Response.Buffer = true;
        Response.Clear();

        //get the memorystream pdf
        var bytes = new MisAuditoriasLogic().ToPdf(uco, idAudit).ToArray();

        Response.OutputStream.Write(bytes, 0, bytes.Length);
        Response.OutputStream.Flush();

    }


    public ActionResult ToMail(string uco, string filter, int? page, int idAudit, int? full) 
    {
        //get the memorystream pdf
        var bytes = new MisAuditoriasLogic().ToPdf(uco, idAudit).ToArray();

        using (var stream = new MemoryStream(bytes))
        using (var mailClient = new SmtpClient("**YOUR SERVER**", 25))
        using (var message = new MailMessage("**SENDER**", "**RECEIVER**", "Just testing", "See attachment..."))
        {

            stream.Position = 0;

            Attachment attach = new Attachment(stream, new System.Net.Mime.ContentType("application/pdf"));
            attach.ContentDisposition.FileName = "test.pdf";

            message.Attachments.Add(attach);

            mailClient.Send(message);
        }

        ViewBag.errMsg = "Documento enviado.";

        return Index(uco, filter, page, idAudit, full);
    }

Java 6 Unsupported major.minor version 51.0

I ran into the same problem. I use jdk 1.8 and maven 3.3.9 Once I export JAVA_HOME, I did not see this error. export JAVA_HOME=/Library/Java/JavaVirtualMachines/jdk1.8.0_121.jdk/Contents/Home/

How to set default value to the input[type="date"]

You can do something like this:

<input type="date" value="<?php echo date("Y-m-d");?>" name="inicio">

How to iterate through an ArrayList of Objects of ArrayList of Objects?

We can do a nested loop to visit all the elements of elements in your list:

 for (Gun g: gunList) {
   System.out.print(g.toString() + "\n   "); 
   for(Bullet b : g.getBullet() {
      System.out.print(g);    
   }
   System.out.println(); 
 }

Enable/Disable a dropdownbox in jquery

To enable/disable -

$("#chkdwn2").change(function() { 
    if (this.checked) $("#dropdown").prop("disabled",true);
    else $("#dropdown").prop("disabled",false);
}) 

Demo - http://jsfiddle.net/tTX6E/

How to get list of dates between two dates in mysql select query

Try:

select * from 
(select adddate('1970-01-01',t4.i*10000 + t3.i*1000 + t2.i*100 + t1.i*10 + t0.i) selected_date from
 (select 0 i union select 1 union select 2 union select 3 union select 4 union select 5 union select 6 union select 7 union select 8 union select 9) t0,
 (select 0 i union select 1 union select 2 union select 3 union select 4 union select 5 union select 6 union select 7 union select 8 union select 9) t1,
 (select 0 i union select 1 union select 2 union select 3 union select 4 union select 5 union select 6 union select 7 union select 8 union select 9) t2,
 (select 0 i union select 1 union select 2 union select 3 union select 4 union select 5 union select 6 union select 7 union select 8 union select 9) t3,
 (select 0 i union select 1 union select 2 union select 3 union select 4 union select 5 union select 6 union select 7 union select 8 union select 9) t4) v
where selected_date between '2012-02-10' and '2012-02-15'

-for date ranges up to nearly 300 years in the future.

[Corrected following a suggested edit by UrvishAtSynapse.]

PHP - add 1 day to date format mm-dd-yyyy

The format you've used is not recognized by strtotime(). Replace

$date = "04-15-2013";

by

$date = "04/15/2013";

Or if you want to use - then use the following line with the year in front:

$date = "2013-04-15";

How do I right align div elements?

Do you mean like this? http://jsfiddle.net/6PyrK/1

You can add the attributes of float:right and clear:both; to the form and button

How to fix Error: laravel.log could not be opened?

I stuck on this issue tried different commands but these will help to solve the problem

php artisan route:clear
php artisan config:clear
php artisan cache:clear

Hope it's helped others too.

Vagrant ssh authentication failure

This has happened to me several times and the way I solved it was :

  1. Check and make sure your Vagrantfile has the correct private key path :

    config.ssh.private_key_path = "/home/razvan/.ssh/id_rsa"

  2. Execute > vagrant ssh command in a linux terminal

  3. On your vagrant machine go to

    cd /home/vagrant/.ssh

and check if the ssh key in the authorized_keys file is the same as the one you have on your local machine in ~/.ssh/id_rsa.pub. If not replace the one from your vagrant authorized_keys with the one on your local machine found in ~/.ssh/id_rsa.pub.

  1. Reload Vagrant :

    vagrant reload

Hope this helps someone else. Cheers!

SQL Logic Operator Precedence: And and Or

Query to show a 3-variable boolean expression truth table :

;WITH cteData AS
(SELECT 0 AS A, 0 AS B, 0 AS C
UNION ALL SELECT 0,0,1
UNION ALL SELECT 0,1,0
UNION ALL SELECT 0,1,1
UNION ALL SELECT 1,0,0
UNION ALL SELECT 1,0,1
UNION ALL SELECT 1,1,0
UNION ALL SELECT 1,1,1
)
SELECT cteData.*,
    CASE WHEN

(A=1) OR (B=1) AND (C=1)

    THEN 'True' ELSE 'False' END AS Result
FROM cteData

Results for (A=1) OR (B=1) AND (C=1) :

A   B   C   Result
0   0   0   False
0   0   1   False
0   1   0   False
0   1   1   True
1   0   0   True
1   0   1   True
1   1   0   True
1   1   1   True

Results for (A=1) OR ( (B=1) AND (C=1) ) are the same.

Results for ( (A=1) OR (B=1) ) AND (C=1) :

A   B   C   Result
0   0   0   False
0   0   1   False
0   1   0   False
0   1   1   True
1   0   0   False
1   0   1   True
1   1   0   False
1   1   1   True

ASP.NET Background image

Use this Code in code behind

Div_Card.Style["background-image"] = Page.ResolveUrl(Session["Img_Path"].ToString());

Changing ViewPager to enable infinite page scrolling

Based on https://github.com/antonyt/InfiniteViewPager I wrote up this which works nicely:

class InfiniteViewPager @JvmOverloads constructor(
  context: Context,
  attrs: AttributeSet? = null
) : ViewPager(context, attrs) {
  // Allow for 100 back cycles from the beginning.
  // This should be enough to create an illusion of infinity.
  // Warning: scrolling to very high values (1,000,000+) results in strange drawing behaviour.
  private val offsetAmount get() = if (adapter?.count == 0) 0 else (adapter as InfinitePagerAdapter).realCount * 100

  override fun setAdapter(adapter: PagerAdapter?) {
    super.setAdapter(if (adapter == null) null else InfinitePagerAdapter(adapter))
    currentItem = 0
  }

  override fun setCurrentItem(item: Int) = setCurrentItem(item, false)

  override fun setCurrentItem(item: Int, smoothScroll: Boolean) {
    val adapterCount = adapter?.count

    if (adapterCount == null || adapterCount == 0) {
      super.setCurrentItem(item, smoothScroll)
    } else {
      super.setCurrentItem(offsetAmount + item % adapterCount, smoothScroll)
    }
  }

  override fun getCurrentItem(): Int {
    val adapterCount = adapter?.count

    return if (adapterCount == null || adapterCount == 0) {
      super.getCurrentItem()
    } else {
      val position = super.getCurrentItem()
      position % (adapter as InfinitePagerAdapter).realCount
    }
  }

  fun animateForward() {
    super.setCurrentItem(super.getCurrentItem() + 1, true)
  }

  fun animateBackwards() {
    super.setCurrentItem(super.getCurrentItem() - 1, true)
  }

  internal class InfinitePagerAdapter(private val adapter: PagerAdapter) : PagerAdapter() {
    internal val realCount: Int get() = adapter.count

    override fun getCount() = if (realCount == 0) 0 else Integer.MAX_VALUE

    override fun instantiateItem(container: ViewGroup, position: Int) = adapter.instantiateItem(container, position % realCount)

    override fun destroyItem(container: ViewGroup, position: Int, `object`: Any) = adapter.destroyItem(container, position % realCount, `object`)

    override fun finishUpdate(container: ViewGroup) = adapter.finishUpdate(container)

    override fun isViewFromObject(view: View, `object`: Any) = adapter.isViewFromObject(view, `object`)

    override fun restoreState(bundle: Parcelable?, classLoader: ClassLoader?) = adapter.restoreState(bundle, classLoader)

    override fun saveState(): Parcelable? = adapter.saveState()

    override fun startUpdate(container: ViewGroup) = adapter.startUpdate(container)

    override fun getPageTitle(position: Int) = adapter.getPageTitle(position % realCount)

    override fun getPageWidth(position: Int) = adapter.getPageWidth(position)

    override fun setPrimaryItem(container: ViewGroup, position: Int, `object`: Any) = adapter.setPrimaryItem(container, position, `object`)

    override fun unregisterDataSetObserver(observer: DataSetObserver) = adapter.unregisterDataSetObserver(observer)

    override fun registerDataSetObserver(observer: DataSetObserver) = adapter.registerDataSetObserver(observer)

    override fun notifyDataSetChanged() = adapter.notifyDataSetChanged()

    override fun getItemPosition(`object`: Any) = adapter.getItemPosition(`object`)
  }
}

For consuming it simply change your ViewPager to InfiniteViewPager and that's all you need to change.

Importing two classes with same name. How to handle?

Another way to do it is subclass it:

package my.own;

public class FQNDate extends Date {

}

And then import my.own.FQNDate in packages that have java.util.Date.

What dependency is missing for org.springframework.web.bind.annotation.RequestMapping?

the problem's actually caused by dependency. I spent whole the day to solve this prblm. Firstly, right click on project > Maven > add dependency

enter image description here

In "EnterGroupId, ArtifactId, or sha1...." box, type "org.springframework".

Then, from droped down list, expand "spring-web" list > Choose the newest version of jar file > Click OK.enter image description here
Done!!!

How do I get the path of the Python script I am running in?

os.path.realpath(__file__) will give you the path of the current file, resolving any symlinks in the path. This works fine on my mac.

What replaces cellpadding, cellspacing, valign, and align in HTML5 tables?

This should solve your problem:

td {
    /* <http://www.w3.org/wiki/CSS/Properties/text-align>
     * left, right, center, justify, inherit
     */
    text-align: center;
    /* <http://www.w3.org/wiki/CSS/Properties/vertical-align>
     * baseline, sub, super, top, text-top, middle,
     * bottom, text-bottom, length, or a value in percentage
     */
    vertical-align: top;
}

Converting video to HTML5 ogg / ogv and mpg4

MS Expression Encoder can do mp4/h.264. not sure about ogg though.

Illegal Character when trying to compile java code

That's a byte order mark, as everyone says.

javac does not understand the BOM, not even when you try something like

javac -encoding UTF8 Test.java

You need to strip the BOM or convert your source file to another encoding. Notepad++ can convert a single files encoding, I'm not aware of a batch utility on the Windows platform for this.

The java compiler will assume the file is in your platform default encoding, so if you use this, you don't have to specify the encoding.

How to give spacing between buttons using bootstrap

You can achieved by use bootstrap Spacing. Bootstrap Spacing includes a wide range of shorthand responsive margin and padding. In below example mr-1 set the margin or padding to $spacer * .25.

Example:

<button class="btn btn-outline-primary mr-1" href="#">Sign up</button>
<button class="btn btn-outline-primary" href="#">Login</button>

You can read more at Bootstrap Spacing.

How to jQuery clone() and change id?

$('#cloneDiv').click(function(){


  // get the last DIV which ID starts with ^= "klon"
  var $div = $('div[id^="klon"]:last');

  // Read the Number from that DIV's ID (i.e: 3 from "klon3")
  // And increment that number by 1
  var num = parseInt( $div.prop("id").match(/\d+/g), 10 ) +1;

  // Clone it and assign the new ID (i.e: from num 4 to ID "klon4")
  var $klon = $div.clone().prop('id', 'klon'+num );

  // Finally insert $klon wherever you want
  $div.after( $klon.text('klon'+num) );

});
<script src="https://code.jquery.com/jquery-3.1.0.js"></script>

What are the differences between "git commit" and "git push"?

git commit is nothing but saving our changes officially, for every commit we give commit message, once we are done with commits we can push it to remote to see our change globally

which means we can do numerous commits before we push to remote (we can see the list of commits happened and the messages too) git saves each commit with commit id which is a 40 digit code

and I use git push only when i wanted to see my change in remote (There after i will check whether my code worked in jenkins)

How to parse JSON to receive a Date object in JavaScript?

There is no standard JSON representation of dates. You should do what @jAndy suggested and not serialize a DateTime at all; just send an RFC 1123 date string ToString("r") or a seconds-from-Unix-epoch number, or something else that you can use in the JavaScript to construct a Date.

In Java, should I escape a single quotation mark (') in String (double quoted)?

You don't need to escape the ' character in a String (wrapped in "), and you don't have to escape a " character in a char (wrapped in ').

sorting a vector of structs

Just make a comparison function/functor:

bool my_cmp(const data& a, const data& b)
{
    // smallest comes first
    return a.word.size() < b.word.size();
}

std::sort(info.begin(), info.end(), my_cmp);

Or provide an bool operator<(const data& a) const in your data class:

struct data {
    string word;
    int number;

    bool operator<(const data& a) const
    {
        return word.size() < a.word.size();
    }
};

or non-member as Fred said:

struct data {
    string word;
    int number;
};

bool operator<(const data& a, const data& b)
{
    return a.word.size() < b.word.size();
}

and just call std::sort():

std::sort(info.begin(), info.end());

Cross field validation with Hibernate Validator (JSR 303)

I suggest you another possible solution. Perhaps less elegant, but easier!

public class MyBean {
  @Size(min=6, max=50)
  private String pass;

  private String passVerify;

  @AssertTrue(message="passVerify field should be equal than pass field")
  private boolean isValid() {
    return this.pass.equals(this.passVerify);
  }
}

The isValid method is invoked by the validator automatically.

'uint32_t' does not name a type

You need to #include <cstdint>, but that may not always work.

The problem is that some compiler often automatically export names defined in various headers or provided types before such standards were in place.

Now, I said "may not always work." That's because the cstdint header is part of the C++11 standard and is not always available on current C++ compilers (but often is). The stdint.h header is the C equivalent and is part of C99.

For best portability, I'd recommend using Boost's boost/cstdint.hpp header, if you're willing to use boost. Otherwise, you'll probably be able to get away with #include'ing <cstdint>.

Redis connection to 127.0.0.1:6379 failed - connect ECONNREFUSED

I'm on MBP , and install redis detail my problem was resolved .Fixed the Download, extract and compile Redis with:

$ wget http://download.redis.io/releases/redis-3.0.2.tar.gz

$ tar xzf redis-3.0.2.tar.gz

$ cd redis-3.0.2

$ make

The binaries that are now compiled are available in the src directory.

Run Redis with:

$ src/redis-server 

How to use (install) dblink in PostgreSQL?

On linux, find dblink.sql, then execute in the postgresql console something like this to create all required functions:

\i /usr/share/postgresql/8.4/contrib/dblink.sql 

you might need to install the contrib packages: sudo apt-get install postgresql-contrib

Convert seconds value to hours minutes seconds?

This Code Is working Fine :

txtTimer.setText(String.format("%02d:%02d:%02d",(SecondsCounter/3600), ((SecondsCounter % 3600)/60), (SecondsCounter % 60)));

Checkbox value true/false

I'm going to post this answer under the following assumptions. 1) You (un)selected the checkbox on the first page and submitted the form. 2) Your building the second form and you setting the value="" true/false depending on if the previous one was checked. 3) You want the checkbox to reflect if it was checked or not before.

If this is the case then you can do something like:

var $checkbox1 = $('#checkbox1');
$checkbox1.prop('checked', $checkbox1.val() === 'true');

What is the difference between @Inject and @Autowired in Spring Framework? Which one to use under what condition?

Here is a blog post that compares @Resource, @Inject, and @Autowired, and appears to do a pretty comprehensive job.

From the link:

With the exception of test 2 & 7 the configuration and outcomes were identical. When I looked under the hood I determined that the ‘@Autowired’ and ‘@Inject’ annotation behave identically. Both of these annotations use the ‘AutowiredAnnotationBeanPostProcessor’ to inject dependencies. ‘@Autowired’ and ‘@Inject’ can be used interchangeable to inject Spring beans. However the ‘@Resource’ annotation uses the ‘CommonAnnotationBeanPostProcessor’ to inject dependencies. Even though they use different post processor classes they all behave nearly identically. Below is a summary of their execution paths.

Tests 2 and 7 that the author references are 'injection by field name' and 'an attempt at resolving a bean using a bad qualifier', respectively.

The Conclusion should give you all the information you need.

Razor Views not seeing System.Web.Mvc.HtmlHelper

Just started looking into the issue myself and this is what it look like in my case. If you have the correct values in your web config then Its just a bug in MVC4. http://connect.microsoft.com/VisualStudio/feedback/details/727729/viewbag-not-recognized-in-asp-net-mvc-4-project

How to convert SSH keypairs generated using PuTTYgen (Windows) into key-pairs used by ssh-agent and Keychain (Linux)

I think what TCSgrad was trying to ask (a few years ago) was how to make Linux behave like his Windows machine does. That is, there is an agent (pageant) which holds a decrypted copy of a private key so that the passphrase only needs to be put in once. Then, the ssh client, putty, can log in to machines where his public key is listed as "authorized" without a password prompt.

The analog for this is that Linux, acting as an ssh client, has an agent holding a decrypted private key so that when TCSgrad types "ssh host" the ssh command will get his private key and go without being prompted for a password. host would, of course, have to be holding the public key in ~/.ssh/authorized_keys.

The Linux analog to this scenario is accomplished using ssh-agent (the pageant analog) and ssh-add (the analog to adding a private key to pageant).

The method that worked for me was to use: $ ssh-agent $SHELL That $SHELL was the magic trick I needed to make the agent run and stay running. I found that somewhere on the 'net and it ended a few hours of beating my head against the wall.

Now we have the analog of pageant running, an agent with no keys loaded.

Typing $ ssh-add by itself will add (by default) the private keys listed in the default identity files in ~/.ssh .

A web article with a lot more details can be found here

PHP isset() with multiple parameters

The parameters of isset() should be separated by a comma sign (,) and not a dot sign (.). Your current code concatenates the variables into a single parameter, instead of passing them as separate parameters.

So the original code evaluates the variables as a unified string value:

isset($_POST['search_term'] . $_POST['postcode']) // Incorrect

While the correct form evaluates them separately as variables:

isset($_POST['search_term'], $_POST['postcode']) // Correct

Spring Boot java.lang.NoClassDefFoundError: javax/servlet/Filter

The configuration here is working for me:

configurations {
    customProvidedRuntime
}

dependencies {
    compile(
        // Spring Boot dependencies
    )

    customProvidedRuntime('org.springframework.boot:spring-boot-starter-tomcat')
}

war {
    classpath = files(configurations.runtime.minus(configurations.customProvidedRuntime))
}

springBoot {
    providedConfiguration = "customProvidedRuntime"
}

MongoDB or CouchDB - fit for production?

We are using MongoDB in production in our mobile backend service namely Netmera. We are using it to store all user and content data.

Comparing two dictionaries and checking how many (key, value) pairs are equal

The function is fine IMO, clear and intuitive. But just to give you (another) answer, here is my go:

def compare_dict(dict1, dict2):
    for x1 in dict1.keys():
        z = dict1.get(x1) == dict2.get(x1)
        if not z:
            print('key', x1)
            print('value A', dict1.get(x1), '\nvalue B', dict2.get(x1))
            print('-----\n')

Can be useful for you or for anyone else..

EDIT:

I have created a recursive version of the one above.. Have not seen that in the other answers

def compare_dict(a, b):
    # Compared two dictionaries..
    # Posts things that are not equal..
    res_compare = []
    for k in set(list(a.keys()) + list(b.keys())):
        if isinstance(a[k], dict):
            z0 = compare_dict(a[k], b[k])
        else:
            z0 = a[k] == b[k]

        z0_bool = np.all(z0)
        res_compare.append(z0_bool)
        if not z0_bool:
            print(k, a[k], b[k])
    return np.all(res_compare)

How to get the current time in Python

If you just want the current timestamp in ms (for example, to measure execution time), you can also use the "timeit" module:

import timeit
start_time = timeit.default_timer()
do_stuff_you_want_to_measure()
end_time = timeit.default_timer()
print("Elapsed time: {}".format(end_time - start_time))

Naming Classes - How to avoid calling everything a "<WhatEver>Manager"?

You can take a look at source-code-wordle.de, I have analyzed there the most frequently used suffixes of class names of the .NET framework and some other libraries.

The top 20 are:

  • attribute
  • type
  • helper
  • collection
  • converter
  • handler
  • info
  • provider
  • exception
  • service
  • element
  • manager
  • node
  • option
  • factory
  • context
  • item
  • designer
  • base
  • editor

Call PowerShell script PS1 from another PS1 script inside Powershell ISE

To execute easily a script file in the same folder (or subfolder of) as the caller you can use this:

# Get full path to the script:
$ScriptRoute = [System.IO.Path]::GetFullPath([System.IO.Path]::Combine($PSScriptRoot, "Scriptname.ps1"))

# Execute script at location:
&"$ScriptRoute"

how to add picasso library in android studio

Add this to your dependencies in build.gradle:

enter image description here

dependencies {
 implementation 'com.squareup.picasso:picasso:2.71828'
  ...

The latest version can be found here

Make sure you are connected to the Internet. When you sync Gradle, all related files will be added to your project

Take a look at your libraries folder, the library you just added should be in there.

enter image description here

Linq to Sql: Multiple left outer joins

I am using this linq query for my application. if this match your requirement you can refer this. here i have joined(Left outer join) with 3 tables.

 Dim result = (From csL In contractEntity.CSLogin.Where(Function(cs) cs.Login = login AndAlso cs.Password = password).DefaultIfEmpty
                   From usrT In contractEntity.UserType.Where(Function(uTyp) uTyp.UserTypeID = csL.UserTyp).DefaultIfEmpty ' <== makes join left join
                   From kunD In contractEntity.EmployeeMaster.Where(Function(kunDat) kunDat.CSLoginID = csL.CSLoginID).DefaultIfEmpty
                   Select New With {
                  .CSLoginID = csL.CSLoginID,
                  .UserType = csL.UserTyp}).ToList()

Send parameter to Bootstrap modal window?

I have found this better way , no need to remove data , just call the source of the remote content each time

$(document).ready(function() {
    $('.class').click(function() {
        var id = this.id;
        //alert(id);checking that have correct id
        $("#iframe").attr("src","url?id=" + id);
        $('#Modal').modal({ 
            show: true 
        });
    });
});

How to remove underline from a name on hover

try this:

legend.green-color a:hover{
    text-decoration: none;
}

How to loop through a HashMap in JSP?

Depending on what you want to accomplish within the loop, iterate over one of these instead:

  • countries.keySet()
  • countries.entrySet()
  • countries.values()

Installing MySQL in Docker fails with error message "Can't connect to local MySQL server through socket"

Remember that you will need to connect to running docker container. So you probably want to use tcp instead of unix socket. Check output of docker ps command and look for running mysql containers. If you find one then use mysql command like this: mysql -h 127.0.0.1 -P <mysql_port> (you will find port in docker ps output). If you can't find any running mysql container in docker ps output then try docker images to find mysql image name and try something like this to run it: docker run -d -p 3306:3306 tutum/mysql where "tutum/mysql" is image name found in docker images.

In SQL, how can you "group by" in ranges?

Perhaps you're asking about keeping such things going...

Of course you'll invoke a full table scan for the queries and if the table containing the scores that need to be tallied (aggregations) is large you might want a better performing solution, you can create a secondary table and use rules, such as on insert - you might look into it.

Not all RDBMS engines have rules, though!

Socket send and receive byte array

There is a JDK socket tutorial here, which covers both the server and client end. That looks exactly like what you want.

(from that tutorial) This sets up to read from an echo server:

    echoSocket = new Socket("taranis", 7);
    out = new PrintWriter(echoSocket.getOutputStream(), true);
    in = new BufferedReader(new InputStreamReader(
                                echoSocket.getInputStream()));

taking a stream of bytes and converts to strings via the reader and using a default encoding (not advisable, normally).

Error handling and closing sockets/streams omitted from the above, but check the tutorial.

Coloring Buttons in Android with Material Design and AppCompat

if you want below style

enter image description here

add this style your button

style="@style/Widget.AppCompat.Button.Borderless.Colored"

if you want this style

enter image description here

add below code

style="@style/Widget.AppCompat.Button.Colored"

Move the most recent commit(s) to a new branch with Git

You can do this is just 3 simple step that i used.

1) make new branch where you want to commit you recent update.

git branch <branch name>

2) Find Recent Commit Id for commit on new branch.

git log

3) Copy that commit id note that Most Recent commit list take place on top. so you can find your commit. you also find this via message.

git cherry-pick d34bcef232f6c...

you can also provide some rang of commit id.

git cherry-pick d34bcef...86d2aec

Now your job done. If you picked correct id and correct branch then you will success. So before do this be careful. else another problem can occur.

Now you can push your code

git push

How to find tags with only certain attributes - BeautifulSoup

find using an attribute in any tag

<th class="team" data-sort="team">Team</th>    
soup.find_all(attrs={"class": "team"}) 

<th data-sort="team">Team</th>  
soup.find_all(attrs={"data-sort": "team"}) 
 

Can't Autowire @Repository annotated interface in Spring Boot

It could be to do with the package you have it in. I had a similar problem:

Description:
Field userRepo in com.App.AppApplication required a bean of type 'repository.UserRepository' that could not be found.

The injection point has the following annotations:
    - @org.springframework.beans.factory.annotation.Autowired(required=true)

Action:

Consider defining a bean of type 'repository.UserRepository' in your configuration. "

Solved it by put the repository files into a package with standardised naming convention:

e.g. com.app.Todo (for main domain files)

and

com.app.Todo.repository (for repository files)

That way, spring knows where to go looking for the repositories, else things get confusing really fast. :)

Hope this helps.

What is the right way to POST multipart/form-data using curl?

to upload a file using curl in Windows I found that the path requires escaped double quotes

e.g.

curl -v -F 'upload=@\"C:/myfile.txt\"' URL

Spring CORS No 'Access-Control-Allow-Origin' header is present

We had the same issue and we resolved it using Spring's XML configuration as below:

Add this in your context xml file

<mvc:cors>
    <mvc:mapping path="/**"
        allowed-origins="*"
        allowed-headers="Content-Type, Access-Control-Allow-Origin, Access-Control-Allow-Headers, Authorization, X-Requested-With, requestId, Correlation-Id"
        allowed-methods="GET, PUT, POST, DELETE"/>
</mvc:cors>

Calling Python in PHP

Depending on what you are doing, system() or popen() may be perfect. Use system() if the Python script has no output, or if you want the Python script's output to go directly to the browser. Use popen() if you want to write data to the Python script's standard input, or read data from the Python script's standard output in php. popen() will only let you read or write, but not both. If you want both, check out proc_open(), but with two way communication between programs you need to be careful to avoid deadlocks, where each program is waiting for the other to do something.

If you want to pass user supplied data to the Python script, then the big thing to be careful about is command injection. If you aren't careful, your user could send you data like "; evilcommand ;" and make your program execute arbitrary commands against your will.

escapeshellarg() and escapeshellcmd() can help with this, but personally I like to remove everything that isn't a known good character, using something like

preg_replace('/[^a-zA-Z0-9]/', '', $str)

How does RewriteBase work in .htaccess

AFAIK, RewriteBase is only used to fix cases where mod_rewrite is running in a .htaccess file not at the root of a site and it guesses the wrong web path (as opposed to filesystem path) for the folder it is running in. So if you have a RewriteRule in a .htaccess in a folder that maps to http://example.com/myfolder you can use:

RewriteBase myfolder

If mod_rewrite isn't working correctly.

Trying to use it to achieve something unusual, rather than to fix this problem sounds like a recipe to getting very confused.

How to convert "Mon Jun 18 00:00:00 IST 2012" to 18/06/2012?

I hope following program will solve your problem

String dateStr = "Mon Jun 18 00:00:00 IST 2012";
DateFormat formatter = new SimpleDateFormat("E MMM dd HH:mm:ss Z yyyy");
Date date = (Date)formatter.parse(dateStr);
System.out.println(date);        

Calendar cal = Calendar.getInstance();
cal.setTime(date);
String formatedDate = cal.get(Calendar.DATE) + "/" + (cal.get(Calendar.MONTH) + 1) + "/" +         cal.get(Calendar.YEAR);
System.out.println("formatedDate : " + formatedDate);    

curl: (35) SSL connect error

If updating cURL doesn't fix it, updating NSS should do the trick.

How to force delete a file?

You have to close that application first. There is no way to delete it, if it's used by some application.

UnLock IT is a neat utility that helps you to take control of any file or folder when it is locked by some application or system. For every locked resource, you get a list of locking processes and can unlock it by terminating those processes. EMCO Unlock IT offers Windows Explorer integration that allows unlocking files and folders by one click in the context menu.

There's also Unlocker (not recommended, see Warning below), which is a free tool which helps locate any file locking handles running, and give you the option to turn it off. Then you can go ahead and do anything you want with those files.

Warning: The installer includes a lot of undesirable stuff. You're almost certainly better off with UnLock IT.

Can a class member function template be virtual?

While an older question that has been answered by many I believe a succinct method, not so different from the others posted, is to use a minor macro to help ease the duplication of class declarations.

// abstract.h

// Simply define the types that each concrete class will use
#define IMPL_RENDER() \
    void render(int a, char *b) override { render_internal<char>(a, b); }   \
    void render(int a, short *b) override { render_internal<short>(a, b); } \
    // ...

class Renderable
{
public:
    // Then, once for each on the abstract
    virtual void render(int a, char *a) = 0;
    virtual void render(int a, short *b) = 0;
    // ...
};

So now, to implement our subclass:

class Box : public Renderable
{
public:
    IMPL_RENDER() // Builds the functions we want

private:
    template<typename T>
    void render_internal(int a, T *b); // One spot for our logic
};

The benefit here is that, when adding a newly supported type, it can all be done from the abstract header and forego possibly rectifying it in multiple source/header files.

Submit form and stay on same page?

Use XMLHttpRequest

var xhr = new XMLHttpRequest();
xhr.open("POST", '/server', true);

//Send the proper header information along with the request
xhr.setRequestHeader("Content-Type", "application/x-www-form-urlencoded");

xhr.onreadystatechange = function() { // Call a function when the state changes.
    if (this.readyState === XMLHttpRequest.DONE && this.status === 200) {
        // Request finished. Do processing here.
    }
}
xhr.send("foo=bar&lorem=ipsum");
// xhr.send(new Int8Array()); 
// xhr.send(document);

Is it safe to shallow clone with --depth 1, create commits, and pull updates again?

See some of the answers to my similar question why-cant-i-push-from-a-shallow-clone and the link to the recent thread on the git list.

Ultimately, the 'depth' measurement isn't consistent between repos, because they measure from their individual HEADs, rather than (a) your Head, or (b) the commit(s) you cloned/fetched, or (c) something else you had in mind.

The hard bit is getting one's Use Case right (i.e. self-consistent), so that distributed, and therefore probably divergent repos will still work happily together.

It does look like the checkout --orphan is the right 'set-up' stage, but still lacks clean (i.e. a simple understandable one line command) guidance on the "clone" step. Rather it looks like you have to init a repo, set up a remote tracking branch (you do want the one branch only?), and then fetch that single branch, which feels long winded with more opportunity for mistakes.

Edit: For the 'clone' step see this answer

Best way to remove an event handler in jQuery?

If you use $(document).on() to add a listener to a dynamically created element then you may have to use the following to remove it:

// add the listener
$(document).on('click','.element',function(){
    // stuff
});

// remove the listener
$(document).off("click", ".element");

How do I show/hide a UIBarButtonItem?

For Swift 3 and Swift 4 you can do this to hide the UIBarButtomItem:

self.deleteButton.isEnabled = false
self.deleteButton.tintColor = UIColor.clear

And to show the UIBarButtonItem:

self.deleteButton.isEnabled = true
self.deleteButton.tintColor = UIColor.blue

On the tintColor you must have to specify the origin color you are using for the UIBarButtomItem

Default passwords of Oracle 11g?

Once installed in windows Followed the instructions starting from Run SQL Command Line (command prompt)

then... v. SQL> connect /as sysdba

Connected. [SQL prompt response]

vi. SQL> alter user SYS identified by "newpassword";

User altered. [SQL prompt response]

Thank you. This minimized a headache

Pandas Split Dataframe into two Dataframes at a specific row

use np.split(..., axis=1):

Demo:

In [255]: df = pd.DataFrame(np.random.rand(5, 6), columns=list('abcdef'))

In [256]: df
Out[256]:
          a         b         c         d         e         f
0  0.823638  0.767999  0.460358  0.034578  0.592420  0.776803
1  0.344320  0.754412  0.274944  0.545039  0.031752  0.784564
2  0.238826  0.610893  0.861127  0.189441  0.294646  0.557034
3  0.478562  0.571750  0.116209  0.534039  0.869545  0.855520
4  0.130601  0.678583  0.157052  0.899672  0.093976  0.268974

In [257]: dfs = np.split(df, [4], axis=1)

In [258]: dfs[0]
Out[258]:
          a         b         c         d
0  0.823638  0.767999  0.460358  0.034578
1  0.344320  0.754412  0.274944  0.545039
2  0.238826  0.610893  0.861127  0.189441
3  0.478562  0.571750  0.116209  0.534039
4  0.130601  0.678583  0.157052  0.899672

In [259]: dfs[1]
Out[259]:
          e         f
0  0.592420  0.776803
1  0.031752  0.784564
2  0.294646  0.557034
3  0.869545  0.855520
4  0.093976  0.268974

np.split() is pretty flexible - let's split an original DF into 3 DFs at columns with indexes [2,3]:

In [260]: dfs = np.split(df, [2,3], axis=1)

In [261]: dfs[0]
Out[261]:
          a         b
0  0.823638  0.767999
1  0.344320  0.754412
2  0.238826  0.610893
3  0.478562  0.571750
4  0.130601  0.678583

In [262]: dfs[1]
Out[262]:
          c
0  0.460358
1  0.274944
2  0.861127
3  0.116209
4  0.157052

In [263]: dfs[2]
Out[263]:
          d         e         f
0  0.034578  0.592420  0.776803
1  0.545039  0.031752  0.784564
2  0.189441  0.294646  0.557034
3  0.534039  0.869545  0.855520
4  0.899672  0.093976  0.268974

XAMPP keeps showing Dashboard/Welcome Page instead of the Configuration Page

This works in Windows; didn't check Linux but don't see why it wouldn't work. Download the zip files for 5.6.8 portable. Unzip the files and copy the xampp/htdocs to the xampp/htdocs in your install directory.

AngularJS $watch window resize inside directive

// Following is angular 2.0 directive for window re size that adjust scroll bar for give element as per your tag

---- angular 2.0 window resize directive.
import { Directive, ElementRef} from 'angular2/core';

@Directive({
       selector: '[resize]',
       host: { '(window:resize)': 'onResize()' } // Window resize listener
})

export class AutoResize {

element: ElementRef; // Element that associated to attribute.
$window: any;
       constructor(_element: ElementRef) {

         this.element = _element;
         // Get instance of DOM window.
         this.$window = angular.element(window);

         this.onResize();

    }

    // Adjust height of element.
    onResize() {
         $(this.element.nativeElement).css('height', (this.$window.height() - 163) + 'px');
   }
}

JOptionPane Input to int

// sample code for addition using JOptionPane

import javax.swing.JOptionPane;

public class Addition {

    public static void main(String[] args) {

        String firstNumber = JOptionPane.showInputDialog("Input <First Integer>");

        String secondNumber = JOptionPane.showInputDialog("Input <Second Integer>");

        int num1 = Integer.parseInt(firstNumber);
        int num2 = Integer.parseInt(secondNumber);
        int sum = num1 + num2;
        JOptionPane.showMessageDialog(null, "Sum is" + sum, "Sum of two Integers", JOptionPane.PLAIN_MESSAGE);
    }
}

Calling the base constructor in C#

You can also do a conditional check with parameters in the constructor, which allows some flexibility.

public MyClass(object myObject=null): base(myObject ?? new myOtherObject())
{
}

or

public MyClass(object myObject=null): base(myObject==null ? new myOtherObject(): myObject)
{
}

Maven: How to run a .java file from command line passing arguments

You could run: mvn exec:exec -Dexec.args="arg1".

This will pass the argument arg1 to your program.

You should specify the main class fully qualified, for example, a Main.java that is in a package test would need

mvn exec:java  -Dexec.mainClass=test.Main

By using the -f parameter, as decribed here, you can also run it from other directories.

mvn exec:java -Dexec.mainClass=test.Main -f folder/pom.xm

For multiple arguments, simply separate them with a space as you would at the command line.

mvn exec:java -Dexec.mainClass=test.Main -Dexec.args="arg1 arg2 arg3"

For arguments separated with a space, you can group using 'argument separated with space' inside the quotation marks.

mvn exec:java -Dexec.mainClass=test.Main -Dexec.args="'argument separated with space' 'another one'"

socket.shutdown vs socket.close

Here's one explanation:

Once a socket is no longer required, the calling program can discard the socket by applying a close subroutine to the socket descriptor. If a reliable delivery socket has data associated with it when a close takes place, the system continues to attempt data transfer. However, if the data is still undelivered, the system discards the data. Should the application program have no use for any pending data, it can use the shutdown subroutine on the socket prior to closing it.

Can't pickle <type 'instancemethod'> when using multiprocessing Pool.map()

Some limitations though to Steven Bethard's solution :

When you register your class method as a function, the destructor of your class is surprisingly called every time your method processing is finished. So if you have 1 instance of your class that calls n times its method, members may disappear between 2 runs and you may get a message malloc: *** error for object 0x...: pointer being freed was not allocated (e.g. open member file) or pure virtual method called, terminate called without an active exception (which means than the lifetime of a member object I used was shorter than what I thought). I got this when dealing with n greater than the pool size. Here is a short example :

from multiprocessing import Pool, cpu_count
from multiprocessing.pool import ApplyResult

# --------- see Stenven's solution above -------------
from copy_reg import pickle
from types import MethodType

def _pickle_method(method):
    func_name = method.im_func.__name__
    obj = method.im_self
    cls = method.im_class
    return _unpickle_method, (func_name, obj, cls)

def _unpickle_method(func_name, obj, cls):
    for cls in cls.mro():
        try:
            func = cls.__dict__[func_name]
        except KeyError:
            pass
        else:
            break
    return func.__get__(obj, cls)


class Myclass(object):

    def __init__(self, nobj, workers=cpu_count()):

        print "Constructor ..."
        # multi-processing
        pool = Pool(processes=workers)
        async_results = [ pool.apply_async(self.process_obj, (i,)) for i in range(nobj) ]
        pool.close()
        # waiting for all results
        map(ApplyResult.wait, async_results)
        lst_results=[r.get() for r in async_results]
        print lst_results

    def __del__(self):
        print "... Destructor"

    def process_obj(self, index):
        print "object %d" % index
        return "results"

pickle(MethodType, _pickle_method, _unpickle_method)
Myclass(nobj=8, workers=3)
# problem !!! the destructor is called nobj times (instead of once)

Output:

Constructor ...
object 0
object 1
object 2
... Destructor
object 3
... Destructor
object 4
... Destructor
object 5
... Destructor
object 6
... Destructor
object 7
... Destructor
... Destructor
... Destructor
['results', 'results', 'results', 'results', 'results', 'results', 'results', 'results']
... Destructor

The __call__ method is not so equivalent, because [None,...] are read from the results :

from multiprocessing import Pool, cpu_count
from multiprocessing.pool import ApplyResult

class Myclass(object):

    def __init__(self, nobj, workers=cpu_count()):

        print "Constructor ..."
        # multiprocessing
        pool = Pool(processes=workers)
        async_results = [ pool.apply_async(self, (i,)) for i in range(nobj) ]
        pool.close()
        # waiting for all results
        map(ApplyResult.wait, async_results)
        lst_results=[r.get() for r in async_results]
        print lst_results

    def __call__(self, i):
        self.process_obj(i)

    def __del__(self):
        print "... Destructor"

    def process_obj(self, i):
        print "obj %d" % i
        return "result"

Myclass(nobj=8, workers=3)
# problem !!! the destructor is called nobj times (instead of once), 
# **and** results are empty !

So none of both methods is satisfying...

Android View shadow

This is may be late but for those who are still looking for answer for this I found a project on git hub and this is the only one that actually fit my needs. android-materialshadowninepatch

Just add this line on your build.gradle dependency

compile 'com.h6ah4i.android.materialshadowninepatch:materialshadowninepatch:0.6.3'

cheers. thumbs up for the creator ! happycodings

adb command not found in linux environment

NOTE: while using adb on Linux you'll need to type ./adb to execute adb commands unless you create a path in ~/.bashrc. In a terminal write:

sudo gedit ~/.bashrc

Add the following line at the end of the file. Once you're done, save and exit.

Android tools

export PATH=~/Development/adt-bundle-linux/sdk/platform-tools:~/Development/adt-bundle-linux/sdk/tools:$PATH

Then in a Terminal run this command to reload your .bashrc: Code:

source ~/.bashrc

Now you can just run adb without put ./ before every command.

React js onClick can't pass value to method

class TableHeader extends Component {
  handleClick = (parameter,event) => {
console.log(parameter)
console.log(event)

  }

  render() {
    return (
      <button type="button" 
onClick={this.handleClick.bind(this,"dataOne")}>Send</button>
    );
  }
}

Count all occurrences of a string in lots of files with grep

Instead of using -c, just pipe it to wc -l.

grep string * | wc -l

This will list each occurrence on a single line and then count the number of lines.

This will miss instances where the string occurs 2+ times on one line, though.

VBA to copy a file from one directory to another

One thing that caused me a massive headache when using this code (might affect others and I wish that somebody had left a comment like this one here for me to read):

  • My aim is to create a dynamic access dashboard, which requires that its linked tables be updated.
  • I use the copy methods described above to replace the existing linked CSVs with an updated version of them.
  • Running the above code manually from a module worked fine.
  • Running identical code from a form linked to the CSV data had runtime error 70 (Permission denied), even tho the first step of my code was to close that form (which should have unlocked the CSV file so that it could be overwritten).
  • I now believe that despite the form being closed, it keeps the outdated CSV file locked while it executes VBA associated with that form.

My solution will be to run the code (On timer event) from another hidden form that opens with the database.

VBA - Select columns using numbers?

In this way, you can start to select data even behind column "Z" and select a lot of columns.

Sub SelectColumNums()
    Dim xCol1 As Integer, xNumOfCols as integer
    xCol1 = 26
    xNumOfCols = 17
    Range(Columns(xCol1), Columns(xCol1 + xNumOfCols)).Select
End Sub

JavaScript displaying a float to 2 decimal places

You could do it with the toFixed function, but it's buggy in IE. If you want a reliable solution, look at my answer here.

What is a typedef enum in Objective-C?

Three things are being declared here: an anonymous enumerated type is declared, ShapeType is being declared a typedef for that anonymous enumeration, and the three names kCircle, kRectangle, and kOblateSpheroid are being declared as integral constants.

Let's break that down. In the simplest case, an enumeration can be declared as

enum tagname { ... };

This declares an enumeration with the tag tagname. In C and Objective-C (but not C++), any references to this must be preceded with the enum keyword. For example:

enum tagname x;  // declare x of type 'enum tagname'
tagname x;  // ERROR in C/Objective-C, OK in C++

In order to avoid having to use the enum keyword everywhere, a typedef can be created:

enum tagname { ... };
typedef enum tagname tagname;  // declare 'tagname' as a typedef for 'enum tagname'

This can be simplified into one line:

typedef enum tagname { ... } tagname;  // declare both 'enum tagname' and 'tagname'

And finally, if we don't need to be able to use enum tagname with the enum keyword, we can make the enum anonymous and only declare it with the typedef name:

typedef enum { ... } tagname;

Now, in this case, we're declaring ShapeType to be a typedef'ed name of an anonymous enumeration. ShapeType is really just an integral type, and should only be used to declare variables which hold one of the values listed in the declaration (that is, one of kCircle, kRectangle, and kOblateSpheroid). You can assign a ShapeType variable another value by casting, though, so you have to be careful when reading enum values.

Finally, kCircle, kRectangle, and kOblateSpheroid are declared as integral constants in the global namespace. Since no specific values were specified, they get assigned to consecutive integers starting with 0, so kCircle is 0, kRectangle is 1, and kOblateSpheroid is 2.

React Native TextInput that only accepts numeric characters

<TextInput autoCapitalize={'none'} maxLength={10} placeholder='Mobile Number'  value={this.state.mobile} onChangeText={(mobile) => this.onChanged(mobile)}/>

and onChanged method :

onChanged(text){
   var newText = '';
   var numbers = '0123456789';
   if(text.length < 1){
     this.setState({ mobile: '' });
   }
   for (var i=0; i < text.length; i++) {
        if(numbers.indexOf(text[i]) > -1 ) {
             newText = newText + text[i];
        }
        this.setState({ mobile: newText });
    }
}

Inserting values into tables Oracle SQL

INSERT
INTO    Employee 
        (emp_id, emp_name, emp_address, emp_state, emp_position, emp_manager)
SELECT  '001', 'John Doe', '1 River Walk, Green Street', state_id, position_id, manager_id
FROM    dual
JOIN    state s
ON      s.state_name = 'New York'
JOIN    positions p
ON      p.position_name = 'Sales Executive'
JOIN    manager m
ON      m.manager_name = 'Barry Green'

Note that but a single spelling mistake (or an extra space) will result in a non-match and nothing will be inserted.

Image re-size to 50% of original size in HTML

You did not do anything wrong here, it will any other thing that is overriding the image size.

You can check this working fiddle.

And in this fiddle I have alter the image size using %, and it is working.

Also try using this code:

<img src="image.jpg" style="width: 50%; height: 50%"/>?

Here is the example fiddle.

How do I delete everything in Redis?

you can use following approach in python

def redis_clear_cache(self):

    try:
        redis_keys = self.redis_client.keys('*')
    except Exception as e:
        # print('redis_client.keys() raised exception => ' + str(e))
        return 1

    try:
        if len(redis_keys) != 0:
            self.redis_client.delete(*redis_keys)
    except Exception as e:
        # print('redis_client.delete() raised exception => ' + str(e))
        return 1

    # print("cleared cache")
    return 0

Creating a file name as a timestamp in a batch job

Because the idea of tearing %DATE% and %TIME% apart and mashing them back together seems fragile at best, here's an alternative that uses a powershell oneliner:

for /f %i in ('powershell -c "get-date -format yyyy-MM-dd--HH-mm-ss"') do @set DATETIME=%i
set LOGFILE=my-script-%DATETIME%.txt

Reference for get-date is here, with format options for both .NET-style and UNIX-style.

What should a Multipart HTTP request with multiple files look like?

Well, note that the request contains binary data, so I'm not posting the request as such - instead, I've converted every non-printable-ascii character into a dot (".").

POST /cgi-bin/qtest HTTP/1.1
Host: aram
User-Agent: Mozilla/5.0 Gecko/2009042316 Firefox/3.0.10
Accept: text/html,application/xhtml+xml,application/xml;q=0.9,*/*;q=0.8
Accept-Language: en-us,en;q=0.5
Accept-Encoding: gzip,deflate
Accept-Charset: ISO-8859-1,utf-8;q=0.7,*;q=0.7
Keep-Alive: 300
Connection: keep-alive
Referer: http://aram/~martind/banner.htm
Content-Type: multipart/form-data; boundary=2a8ae6ad-f4ad-4d9a-a92c-6d217011fe0f
Content-Length: 514

--2a8ae6ad-f4ad-4d9a-a92c-6d217011fe0f
Content-Disposition: form-data; name="datafile1"; filename="r.gif"
Content-Type: image/gif

GIF87a.............,...........D..;
--2a8ae6ad-f4ad-4d9a-a92c-6d217011fe0f
Content-Disposition: form-data; name="datafile2"; filename="g.gif"
Content-Type: image/gif

GIF87a.............,...........D..;
--2a8ae6ad-f4ad-4d9a-a92c-6d217011fe0f
Content-Disposition: form-data; name="datafile3"; filename="b.gif"
Content-Type: image/gif

GIF87a.............,...........D..;
--2a8ae6ad-f4ad-4d9a-a92c-6d217011fe0f--

Note that every line (including the last one) is terminated by a \r\n sequence.

Getting data from Yahoo Finance

To your first question, you can't really do any query through YQL to get data for all companies. It's more oriented towards obtaining data for a smaller query. (I.e., it's not going to give you a full data dump of the whole Yahoo! Finance database.)

To your second question, here's how you can get started exploring the Yahoo! Finance tables in YQL:

  1. Start at the YQL Console
  2. In the upper left corner, make sure Show Community Tables is checked
  3. Type finance in the search field
  4. You'll see all the Yahoo Finance tables (about 15)

Then you can try some example queries like the following:

select * from yahoo.finance.quote where symbol in ("YHOO","AAPL","GOOG","MSFT")

Update 2016-04-04: Here's a current screenshot showing the location of the Show Community Tables checkbox which must be clicked to see these finance tables: enter image description here

Cannot send a content-body with this verb-type

I had the similar issue using Flurl.Http:

Flurl.Http.FlurlHttpException: Call failed. Cannot send a content-body with this verb-type. GET http://******:8301/api/v1/agents/**** ---> System.Net.ProtocolViolationException: Cannot send a content-body with this verb-type.

The problem was I used .WithHeader("Content-Type", "application/json") when creating IFlurlRequest.

Flutter plugin not installed error;. When running flutter doctor

You can just install the Flutter and Dart plugin in the android studio by following these steps:

  1. Start the Android Studio application
  2. Open plugin preferences (Preferences>Plugins on macOS, File>Settings>Plugins on Windows & Linux).
  3. Select Marketplace…, search the Flutter plugin, and click install.
  4. Click Yes when prompted to install the Dart plugin.
  5. Click on Apply and OK.
  6. Click "Restart" on the popup.

The below image indicates where you should do it

enter image description here

What is the curl error 52 "empty reply from server"?

I ran into this error sporadically and could not understand. Googling did not help.

I finally found out. I run a couple of docker containers, among them NGINX and Apache. The command at hand addresses a specific container, running Apache. As it turned out, I also have a cron job doing some heavy lifting at times running on the same container. Depending on the load this cron job puts on this container, it was not able to answer my command in a timely manner, resulting in error 52 empty reply from server or even 502 Bad Gateway.

I discovered and verified this by plain curl when I noticed that the process I investigated took less than 2 seconds and all of a sudden I got a 52 error and then a 502 error and then again less than 2 seconds - so it was definitely not my code which was unchanged. Using ps aux within the container I saw the other process running and understood.

Actually, I was bothered by 502 Bad Gateway from NGINX with long running jobs and could not fix it with the appropriate parameters, so I finally gave up and switched these things to Apache. That's why I was puzzled even more about these errors.

The remedy is simple. I just fired up some more instances of this container with docker service scale and that was it. docker load balances on its own.


Well, there is more to this as another example showed. This time I did some repetitious jobs.

I found out that after some time I ran out of memory used by PHP which cannot be reclaimed, so the process died.

Why? Having more than a dozen containers on a 8GB RAM machine, I initially thought it would be a good idea to limit RAM usage on PHP containers to 50MB.

Stupid! I forgot about it, but swarmpit gave me a hint. I call ini_set("memory_limit",-1); in the constructor of my class, but that only went as far as those 50MB.

So I removed those restrictions from my compose file. Now those containers may use up to 8GB. The process runs with Apache for hours now and it looks like the problem is solved, memory usage rising to well beyond 100MB.


Another caveat: To easily get and read debug messages, I started said process in Opera under Windows. That is fine with errors appearing soon.

However, if the last one is cared for, quite naturally the process runs and runs and memory usage in the browser builds up, eventually making my local machine unusable. So if that happens, kill this tab and the process keeps running fine.

Execute a command in command prompt using excel VBA

The S parameter does not do anything on its own.

/S      Modifies the treatment of string after /C or /K (see below) 
/C      Carries out the command specified by string and then terminates  
/K      Carries out the command specified by string but remains  

Try something like this instead

Call Shell("cmd.exe /S /K" & "perl a.pl c:\temp", vbNormalFocus)

You may not even need to add "cmd.exe" to this command unless you want a command window to open up when this is run. Shell should execute the command on its own.

Shell("perl a.pl c:\temp")



-Edit-
To wait for the command to finish you will have to do something like @Nate Hekman shows in his answer here

Dim wsh As Object
Set wsh = VBA.CreateObject("WScript.Shell")
Dim waitOnReturn As Boolean: waitOnReturn = True
Dim windowStyle As Integer: windowStyle = 1

wsh.Run "cmd.exe /S /C perl a.pl c:\temp", windowStyle, waitOnReturn

How to cd into a directory with space in the name?

$ cd "$DOCS"

You need to quote "$DOCS" to prevent spaces from being parsed as word separators. More often than not, variable references should be quoted.

Note that $HOME would have the same problem. The issue is coming from when the shell evaluates variable references; it's nothing to do with what variables you use or how you assign to them. It's the expansion that needs to be quoted.

$ echo $HOME
/home/my dir

This is deceptive. echo is actually echoing the two strings /home/my and dir. If you use cd or ls you'll see how it's actually working.

$ ls $HOME
ls: cannot access /home/my: No such file or directory
ls: cannot access dir: No such file or directory
$ cd $HOME
bash: cd: /home/my: No such file or directory
$ cd "$HOME"
<success!>

Can I ask why it works when I manually type it in but not in a variable?

Great question! Let's examine the commands you typed:

$ DOCS="\"/cygdrive/c/Users/my dir/Documents\""
$ echo $DOCS
"/cygdrive/c/Users/my dir/Documents"
$ cd $DOCS
-bash: cd: "/cygdrive/c/Users/my: No such file or directory

The reason this doesn't work is because Bash doesn't parse quotes inside variable expansions. It does perform word splitting, so whitespace in unquoted variable expansions is taken as word separators. It doesn't parse quotes in any way, meaning you can't put double quotes inside a variable to override word splitting.

$ cd $DOCS

Because of this, cd is passed two parameters. As far as cd knows it looks like you wrote:

$ cd '"/cygdrive/c/Users/my' 'dir/Documents"'

Two parameters, with double quotes intact.

Embedding DLLs in a compiled executable

I highly recommend to use Costura.Fody - by far the best and easiest way to embed resources in your assembly. It's available as NuGet package.

Install-Package Costura.Fody

After adding it to the project, it will automatically embed all references that are copied to the output directory into your main assembly. You might want to clean the embedded files by adding a target to your project:

Install-CleanReferencesTarget

You'll also be able to specify whether to include the pdb's, exclude certain assemblies, or extracting the assemblies on the fly. As far as I know, also unmanaged assemblies are supported.

Update

Currently, some people are trying to add support for DNX.

Update 2

For the lastest Fody version, you will need to have MSBuild 16 (so Visual Studio 2019). Fody version 4.2.1 will do MSBuild 15. (reference: Fody is only supported on MSBuild 16 and above. Current version: 15)

Number of days between past date and current date in Google spreadsheet

DAYS360 does not calculate what you want, i.e. the number of days passed between the two dates. Use simple subtraction (-) or MINUS(). I made an updated copy of @DrCord’s sample spreadsheet to illustrate this.

Are you SURE you want DAYS360? That is a specialized function used in the financial sector to simplify calculations for bonds. It assumes a 360 day year, with 12 months of 30 days each. If you really want actual days, you'll lose 6 days each year. [source]

How to purge tomcat's cache when deploying a new .war file? Is there a config setting?

You can delete the "work" directory.

Are you sure it's not a browser caching issue?

java.lang.NoSuchMethodError: javax.servlet.ServletContext.getContextPath()Ljava/lang/String;

java.lang.NoSuchMethodError: javax.servlet.ServletContext.getContextPath()Ljava/lang/String;

That method was added in Servlet 2.5.

So this problem can have at least 3 causes:

  1. The servlet container does not support Servlet 2.5.
  2. The web.xml is not declared conform Servlet 2.5 or newer.
  3. The webapp's runtime classpath is littered with servlet container specific JAR files of a different servlet container make/version which does not support Servlet 2.5.

To solve it,

  1. Make sure that your servlet container supports at least Servlet 2.5. That are at least Tomcat 6, Glassfish 2, JBoss AS 4.1, etcetera. Tomcat 5.5 for example supports at highest Servlet 2.4. If you can't upgrade Tomcat, then you'd need to downgrade Spring to a Servlet 2.4 compatible version.
  2. Make sure that the root declaration of web.xml complies Servlet 2.5 (or newer, at least the highest whatever your target runtime supports). For an example, see also somewhere halfway our servlets wiki page.
  3. Make sure that you don't have any servlet container specific libraries like servlet-api.jar or j2ee.jar in /WEB-INF/lib or even worse, the JRE/lib or JRE/lib/ext. They do not belong there. This is a pretty common beginner's mistake in an attempt to circumvent compilation errors in an IDE, see also How do I import the javax.servlet API in my Eclipse project?.

Export HTML page to PDF on user click using JavaScript

This is because you define your "doc" variable outside of your click event. The first time you click the button the doc variable contains a new jsPDF object. But when you click for a second time, this variable can't be used in the same way anymore. As it is already defined and used the previous time.

change it to:

$(function () {

    var specialElementHandlers = {
        '#editor': function (element,renderer) {
            return true;
        }
    };
 $('#cmd').click(function () {
        var doc = new jsPDF();
        doc.fromHTML(
            $('#target').html(), 15, 15, 
            { 'width': 170, 'elementHandlers': specialElementHandlers }, 
            function(){ doc.save('sample-file.pdf'); }
        );

    });  
});

and it will work.

Why are static variables considered evil?

If you are using the ‘static’ keyword without the ‘final’ keyword, this should be a signal to carefully consider your design. Even the presence of a ‘final’ is not a free pass, since a mutable static final object can be just as dangerous.

I would estimate somewhere around 85% of the time I see a ‘static’ without a ‘final’, it is WRONG. Often, I will find strange workarounds to mask or hide these problems.

Please don’t create static mutables. Especially Collections. In general, Collections should be initialized when their containing object is initialized and should be designed so that they are reset or forgotten about when their containing object is forgotten.

Using statics can create very subtle bugs which will cause sustaining engineers days of pain. I know, because I’ve both created and hunted these bugs.

If you would like more details, please read on…

Why Not Use Statics?

There are many issues with statics, including writing and executing tests, as well as subtle bugs that are not immediately obvious.

Code that relies on static objects can’t be easily unit tested, and statics can’t be easily mocked (usually).

If you use statics, it is not possible to swap the implementation of the class out in order to test higher level components. For example, imagine a static CustomerDAO that returns Customer objects it loads from the database. Now I have a class CustomerFilter, that needs to access some Customer objects. If CustomerDAO is static, I can’t write a test for CustomerFilter without first initializing my database and populating useful information.

And database population and initialization takes a long time. And in my experience, your DB initialization framework will change over time, meaning data will morph, and tests may break. IE, imagine Customer 1 used to be a VIP, but the DB initialization framework changed, and now Customer 1 is no longer VIP, but your test was hard-coded to load Customer 1…

A better approach is to instantiate a CustomerDAO, and pass it into the CustomerFilter when it is constructed. (An even better approach would be to use Spring or another Inversion of Control framework.

Once you do this, you can quickly mock or stub out an alternate DAO in your CustomerFilterTest, allowing you to have more control over the test,

Without the static DAO, the test will be faster (no db initialization) and more reliable (because it won’t fail when the db initialization code changes). For example, in this case ensuring Customer 1 is and always will be a VIP, as far as the test is concerned.

Executing Tests

Statics cause a real problem when running suites of unit tests together (for example, with your Continuous Integration server). Imagine a static map of network Socket objects that remains open from one test to another. The first test might open a Socket on port 8080, but you forgot to clear out the Map when the test gets torn down. Now when a second test launches, it is likely to crash when it tries to create a new Socket for port 8080, since the port is still occupied. Imagine also that Socket references in your static Collection are not removed, and (with the exception of WeakHashMap) are never eligible to be garbage collected, causing a memory leak.

This is an over-generalized example, but in large systems, this problem happens ALL THE TIME. People don’t think of unit tests starting and stopping their software repeatedly in the same JVM, but it is a good test of your software design, and if you have aspirations towards high availability, it is something you need to be aware of.

These problems often arise with framework objects, for example, your DB access, caching, messaging, and logging layers. If you are using Java EE or some best of breed frameworks, they probably manage a lot of this for you, but if like me you are dealing with a legacy system, you might have a lot of custom frameworks to access these layers.

If the system configuration that applies to these framework components changes between unit tests, and the unit test framework doesn’t tear down and rebuild the components, these changes can’t take effect, and when a test relies on those changes, they will fail.

Even non-framework components are subject to this problem. Imagine a static map called OpenOrders. You write one test that creates a few open orders, and checks to make sure they are all in the right state, then the test ends. Another developer writes a second test which puts the orders it needs into the OpenOrders map, then asserts the number of orders is accurate. Run individually, these tests would both pass, but when run together in a suite, they will fail.

Worse, failure might be based on the order in which the tests were run.

In this case, by avoiding statics, you avoid the risk of persisting data across test instances, ensuring better test reliability.

Subtle Bugs

If you work in high availability environment, or anywhere that threads might be started and stopped, the same concern mentioned above with unit test suites can apply when your code is running on production as well.

When dealing with threads, rather than using a static object to store data, it is better to use an object initialized during the thread’s startup phase. This way, each time the thread is started, a new instance of the object (with a potentially new configuration) is created, and you avoid data from one instance of the thread bleeding through to the next instance.

When a thread dies, a static object doesn’t get reset or garbage collected. Imagine you have a thread called “EmailCustomers”, and when it starts it populates a static String collection with a list of email addresses, then begins emailing each of the addresses. Lets say the thread is interrupted or canceled somehow, so your high availability framework restarts the thread. Then when the thread starts up, it reloads the list of customers. But because the collection is static, it might retain the list of email addresses from the previous collection. Now some customers might get duplicate emails.

An Aside: Static Final

The use of “static final” is effectively the Java equivalent of a C #define, although there are technical implementation differences. A C/C++ #define is swapped out of the code by the pre-processor, before compilation. A Java “static final” will end up memory resident on the stack. In that way, it is more similar to a “static const” variable in C++ than it is to a #define.

Summary

I hope this helps explain a few basic reasons why statics are problematic up. If you are using a modern Java framework like Java EE or Spring, etc, you may not encounter many of these situations, but if you are working with a large body of legacy code, they can become much more frequent.

milliseconds to days

In case you solve a more complex task of logging execution statistics in your code:

public void logExecutionMillis(LocalDateTime start, String callerMethodName) {

  LocalDateTime end = getNow();
  long difference = Duration.between(start, end).toMillis();

  Logger logger = LoggerFactory.getLogger(ProfilerInterceptor.class);

  long millisInDay = 1000 * 60 * 60 * 24;
  long millisInHour = 1000 * 60 * 60;
  long millisInMinute = 1000 * 60;
  long millisInSecond = 1000;

  long days = difference / millisInDay;
  long daysDivisionResidueMillis = difference - days * millisInDay;

  long hours = daysDivisionResidueMillis / millisInHour;
  long hoursDivisionResidueMillis = daysDivisionResidueMillis - hours * millisInHour;

  long minutes = hoursDivisionResidueMillis / millisInMinute;
  long minutesDivisionResidueMillis = hoursDivisionResidueMillis - minutes * millisInMinute;

  long seconds = minutesDivisionResidueMillis / millisInSecond;
  long secondsDivisionResidueMillis = minutesDivisionResidueMillis - seconds * millisInSecond;

  logger.info(
      "\n************************************************************************\n"
          + callerMethodName
          + "() - "
          + difference
          + " millis ("
          + days
          + " d. "
          + hours
          + " h. "
          + minutes
          + " min. "
          + seconds
          + " sec."
          + secondsDivisionResidueMillis
          + " millis).");
}

P.S. Logger can be replaced with simple System.out.println() if you like.

multiple classes on single element html

It's a good practice if you need them. It's also a good practice is they make sense, so future coders can understand what you're doing.

But generally, no it's not a good practice to attach 10 class names to an object because most likely whatever you're using them for, you could accomplish the same thing with far fewer classes. Probably just 1 or 2.

To qualify that statement, javascript plugins and scripts may append far more classnames to do whatever it is they're going to do. Modernizr for example appends anywhere from 5 - 25 classes to your body tag, and there's a very good reason for it. jQuery UI appends lots of classnames when you use one of the widgets in that library.

Using boolean values in C

C has a boolean type: bool (at least for the last 10(!) years)

Include stdbool.h and true/false will work as expected.

Convert date formats in bash

If you would like a bash function that works both on Mac OS X and Linux:

#
# Convert one date format to another
# 
# Usage: convert_date_format <input_format> <date> <output_format>
#
# Example: convert_date_format '%b %d %T %Y %Z' 'Dec 10 17:30:05 2017 GMT' '%Y-%m-%d'
convert_date_format() {
  local INPUT_FORMAT="$1"
  local INPUT_DATE="$2"
  local OUTPUT_FORMAT="$3"
  local UNAME=$(uname)

  if [[ "$UNAME" == "Darwin" ]]; then
    # Mac OS X
    date -j -f "$INPUT_FORMAT" "$INPUT_DATE" +"$OUTPUT_FORMAT"
  elif [[ "$UNAME" == "Linux" ]]; then
    # Linux
    date -d "$INPUT_DATE" +"$OUTPUT_FORMAT"
  else
    # Unsupported system
    echo "Unsupported system"
  fi
}

# Example: 'Dec 10 17:30:05 2017 GMT' => '2017-12-10'
convert_date_format '%b %d %T %Y %Z' 'Dec 10 17:30:05 2017 GMT' '%Y-%m-%d'

SQL Server Profiler - How to filter trace to only display events from one database?

Create a new template and check DBname. Use that template for your tracefile.

What are the differences between Abstract Factory and Factory design patterns?

Consider this example for easy understanding.

What does telecommunication companies provide? Broadband, phone line and mobile for instance and you're asked to create an application to offer their products to their customers.

Generally what you'd do here is, creating the products i.e broadband, phone line and mobile are through your Factory Method where you know what properties you have for those products and it's pretty straightforward.

Now, the company wants to offer their customer a bundle of their products i.e broadband, phone line, and mobile altogether, and here comes the Abstract Factory to play.

Abstract Factory is, in other words, are the composition of other factories who are responsible for creating their own products and Abstract Factory knows how to place these products in more meaningful in respect of its own responsibilities.

In this case, the BundleFactory is the Abstract Factory, BroadbandFactory, PhonelineFactory and MobileFactory are the Factory. To simplify more, these Factories will have Factory Method to initialise the individual products.

Se the code sample below:

public class BroadbandFactory : IFactory {
    public static Broadband CreateStandardInstance() {
        // broadband product creation logic goes here
    }
}

public class PhonelineFactory : IFactory {
    public static Phoneline CreateStandardInstance() {
        // phoneline product creation logic goes here
    }
}

public class MobileFactory : IFactory {
    public static Mobile CreateStandardInstance() {
        // mobile product creation logic goes here
    }
}

public class BundleFactory : IAbstractFactory {

    public static Bundle CreateBundle() {
        broadband = BroadbandFactory.CreateStandardInstance();
        phoneline = PhonelineFactory.CreateStandardInstance();
        mobile = MobileFactory.CreateStandardInstance();

        applySomeDiscountOrWhatever(broadband, phoneline, mobile);
    }

    private static void applySomeDiscountOrWhatever(Broadband bb, Phoneline pl, Mobile m) {
        // some logic here
        // maybe manange some variables and invoke some other methods/services/etc.
    }
}

Hope this helps.

what is the difference between uint16_t and unsigned short int incase of 64 bit processor?

uint16_t is unsigned 16-bit integer.

unsigned short int is unsigned short integer, but the size is implementation dependent. The standard only says it's at least 16-bit (i.e, minimum value of UINT_MAX is 65535). In practice, it usually is 16-bit, but you can't take that as guaranteed.

Note:

  1. If you want a portable unsigned 16-bit integer, use uint16_t.
  2. inttypes.h and stdint.h are both introduced in C99. If you are using C89, define your own type.
  3. uint16_t may not be provided in certain implementation(See reference below), but unsigned short int is always available.

Reference: C11(ISO/IEC 9899:201x) §7.20 Integer types

For each type described herein that the implementation provides) shall declare that typedef name and define the associated macros. Conversely, for each type described herein that the implementation does not provide, shall not declare that typedef name nor shall it define the associated macros. An implementation shall provide those types described as ‘‘required’’, but need not provide any of the others (described as ‘optional’’).

Image convert to Base64

Function convert image to base64 using jquery (you can convert to vanila js). Hope it help to you!

Usage: input is your nameId input has file image

<input type="file" id="asd"/>
<button onclick="proccessData()">Submit</button>

<script src="https://cdnjs.cloudflare.com/ajax/libs/jquery/3.5.1/jquery.min.js"></script>
<script>

async function converImageToBase64(inputId) {
  let image = $('#'+inputId)[0]['files']

  if (image && image[0]) {
    const reader = new FileReader();

    return new Promise(resolve => {
      reader.onload = ev => {
        resolve(ev.target.result)
      }
      reader.readAsDataURL(image[0])
    })
  }
}

async function proccessData() {
  const image = await converImageToBase64('asd')
  console.log(image)
}

</script>

Example: converImageToBase64('yourFileInputId')

https://codepen.io/mariohandsome/pen/yLadmVb

Replace first occurrence of string in Python

string replace() function perfectly solves this problem:

string.replace(s, old, new[, maxreplace])

Return a copy of string s with all occurrences of substring old replaced by new. If the optional argument maxreplace is given, the first maxreplace occurrences are replaced.

>>> u'longlongTESTstringTEST'.replace('TEST', '?', 1)
u'longlong?stringTEST'

Get JSON object from URL

You could use PHP's json_decode function:

$url = "http://urlToYourJsonFile.com";
$json = file_get_contents($url);
$json_data = json_decode($json, true);
echo "My token: ". $json_data["access_token"];

Javascript-Setting background image of a DIV via a function and function parameter

You need to concatenate your string.

document.getElementById(tabName).style.backgroundImage = 'url(buttons/' + imagePrefix + '.png)';

The way you had it, it's just making 1 long string and not actually interpreting imagePrefix.

I would even suggest creating the string separate:

function ChangeBackgroungImageOfTab(tabName, imagePrefix)
{
    var urlString = 'url(buttons/' + imagePrefix + '.png)';
    document.getElementById(tabName).style.backgroundImage =  urlString;
}

As mentioned by David Thomas below, you can ditch the double quotes in your string. Here is a little article to get a better idea of how strings and quotes/double quotes are related: http://www.quirksmode.org/js/strings.html

How do you fadeIn and animate at the same time?

Another way to do simultaneous animations if you want to call them separately (eg. from different code) is to use queue. Again, as with Tinister's answer you would have to use animate for this and not fadeIn:

$('.tooltip').css('opacity', 0);
$('.tooltip').show();
...

$('.tooltip').animate({opacity: 1}, {queue: false, duration: 'slow'});
$('.tooltip').animate({ top: "-10px" }, 'slow');

Java regex capturing groups indexes

For The Rest Of Us

Here is a simple and clear example of how this works

Regex: ([a-zA-Z0-9]+)([\s]+)([a-zA-Z ]+)([\s]+)([0-9]+)

String: "!* UserName10 John Smith 01123 *!"

group(0): UserName10 John Smith 01123
group(1): UserName10
group(2):  
group(3): John Smith
group(4):  
group(5): 01123

As you can see, I have created FIVE groups which are each enclosed in parentheses.

I included the !* and *! on either side to make it clearer. Note that none of those characters are in the RegEx and therefore will not be produced in the results. Group(0) merely gives you the entire matched string (all of my search criteria in one single line). Group 1 stops right before the first space because the space character was not included in the search criteria. Groups 2 and 4 are simply the white space, which in this case is literally a space character, but could also be a tab or a line feed etc. Group 3 includes the space because I put it in the search criteria ... etc.

Hope this makes sense.

Sending HTTP POST Request In Java

The first answer was great, but I had to add try/catch to avoid Java compiler errors.
Also, I had troubles to figure how to read the HttpResponse with Java libraries.

Here is the more complete code :

/*
 * Create the POST request
 */
HttpClient httpClient = new DefaultHttpClient();
HttpPost httpPost = new HttpPost("http://example.com/");
// Request parameters and other properties.
List<NameValuePair> params = new ArrayList<NameValuePair>();
params.add(new BasicNameValuePair("user", "Bob"));
try {
    httpPost.setEntity(new UrlEncodedFormEntity(params, "UTF-8"));
} catch (UnsupportedEncodingException e) {
    // writing error to Log
    e.printStackTrace();
}
/*
 * Execute the HTTP Request
 */
try {
    HttpResponse response = httpClient.execute(httpPost);
    HttpEntity respEntity = response.getEntity();

    if (respEntity != null) {
        // EntityUtils to get the response content
        String content =  EntityUtils.toString(respEntity);
    }
} catch (ClientProtocolException e) {
    // writing exception to log
    e.printStackTrace();
} catch (IOException e) {
    // writing exception to log
    e.printStackTrace();
}

Return generated pdf using spring MVC

You were on the right track with response.getOutputStream(), but you're not using its output anywhere in your code. Essentially what you need to do is to stream the PDF file's bytes directly to the output stream and flush the response. In Spring you can do it like this:

@RequestMapping(value="/getpdf", method=RequestMethod.POST)
public ResponseEntity<byte[]> getPDF(@RequestBody String json) {
    // convert JSON to Employee 
    Employee emp = convertSomehow(json);

    // generate the file
    PdfUtil.showHelp(emp);

    // retrieve contents of "C:/tmp/report.pdf" that were written in showHelp
    byte[] contents = (...);

    HttpHeaders headers = new HttpHeaders();
    headers.setContentType(MediaType.APPLICATION_PDF);
    // Here you have to set the actual filename of your pdf
    String filename = "output.pdf";
    headers.setContentDispositionFormData(filename, filename);
    headers.setCacheControl("must-revalidate, post-check=0, pre-check=0");
    ResponseEntity<byte[]> response = new ResponseEntity<>(contents, headers, HttpStatus.OK);
    return response;
}

Notes:

  • use meaningful names for your methods: naming a method that writes a PDF document showHelp is not a good idea
  • reading a file into a byte[]: example here
  • I'd suggest adding a random string to the temporary PDF file name inside showHelp() to avoid overwriting the file if two users send a request at the same time

How do I get console input in javascript?

In plain JavaScript, simply use response = readline() after printing a prompt.

In Node.js, you'll need to use the readline module: const readline = require('readline')

Return JSON response from Flask view

jsonify serializes the data you pass it to JSON. If you want to serialize the data yourself, do what jsonify does by building a response with status=200 and mimetype='application/json'.

from flask import json

@app.route('/summary')
def summary():
    data = make_summary()
    response = app.response_class(
        response=json.dumps(data),
        status=200,
        mimetype='application/json'
    )
    return response

Vector of structs initialization

If you want to use the new current standard, you can do so:

sub.emplace_back ("Math", 70, 0);

or

sub.push_back ({"Math", 70, 0});

These don't require default construction of subject.

Trigger change event of dropdown

Try this:

$(document).ready(function(event) {
    $('#countrylist').change(function(e){
         // put code here
     }).change();
});

Define the change event, and trigger it immediately. This ensures the event handler is defined before calling it.

Might be late to answer the original poster, but someone else might benefit from the shorthand notation, and this follows jQuery's chaining, etc

jquery chaining

How can I remove a button or make it invisible in Android?

This view is visible.

button.setVisibility(View.VISIBLE);

This view is invisible, and it doesn't take any space for layout purposes.

button.setVisibility(View.GONE); 

But if you just want to make it invisible:

button.setVisibility(View.INVISIBLE);

Google Maps API: open url by clicking on marker

the previous answers didn't work out for me well. I had persisting problems by setting the marker. So i changed the code slightly.

   <!DOCTYPE html>
   <html>
   <head>
     <meta http-equiv="content-type" content="text/html; charset=ANSI" />
     <title>Google Maps Multiple Markers</title>
     <script src="http://maps.google.com/maps/api/js?sensor=false"
      type="text/javascript"></script>
   </head>
   <body>
     <div id="map" style="width: 1500px; height: 1000px;"></div>

     <script type="text/javascript">
       var locations = [
         ['Goettingen',  51.54128040000001,  9.915803500000038, 'http://www.google.de'],
         ['Kassel', 51.31271139999999,  9.479746100000057,0, 'http://www.stackoverflow.com'],
         ['Witzenhausen', 51.33996819999999,  9.855564299999969,0, 'www.http://developer.mozilla.org.de']

 ];

var map = new google.maps.Map(document.getElementById('map'), {
  zoom: 10,
 center: new google.maps.LatLng(51.54376, 9.910419999999931),
 mapTypeId: google.maps.MapTypeId.ROADMAP
});

var infowindow = new google.maps.InfoWindow();

var marker, i;

for (i = 0; i < locations.length; i++) {
  marker = new google.maps.Marker({
   position: new google.maps.LatLng(locations[i][1], locations[i][2]),
   map: map,
   url: locations[i][4]
  });

 google.maps.event.addListener(marker, 'mouseover', (function(marker, i) {
   return function() {
     infowindow.setContent(locations[i][0]);
     infowindow.open(map, marker);
   }
 })(marker, i));

      google.maps.event.addListener(marker, 'click', (function(marker, i) {
   return function() {
     infowindow.setContent(locations[i][0]);
     infowindow.open(map, marker);
     window.location.href = this.url;
   }
 })(marker, i));

    }

     </script>
   </body>
   </html>

This way worked out for me! You can create Google Maps routing links from your Datebase to to use it as an interactive routing map.

AttributeError: 'module' object has no attribute 'urlopen'

import urllib.request as ur
s = ur.urlopen("http://www.google.com")
sl = s.read()
print(sl)

In Python v3 the "urllib.request" is a module by itself, therefore "urllib" cannot be used here.

How do I set up cron to run a file just once at a specific time?

Try this out to execute a command on 30th March 2011 at midnight:

0 0 30 3 ? 2011  /command

WARNING: As noted in comments, the year column is not supported in standard/default implementations of cron. Please refer to TomOnTime answer below, for a proper way to run a script at a specific time in the future in standard implementations of cron.

How generate unique Integers based on GUIDs

Eric Lippert did a very interesting (as always) post about the probability of hash collisions.

You should read it all but he concluded with this very illustrative graphic:

Probability of hash collisions

Related to your specific question, I would also go with GetHashCode since collisions will be unavoidable either way.

How to make fixed header table inside scrollable div?

A Fiddle would have been more helpful nevertheless from what I understand, I guess what you need is persistent headers, look into this

http://css-tricks.com/persistent-headers/

How can I format a number into a string with leading zeros?

For interpolated strings:

$"Int value: {someInt:D4} or {someInt:0000}. Float: {someFloat: 00.00}"

Fast query runs slow in SSRS

Thanks for the suggestions provided here. We have found a solution and it did turn out to be related to the parameters. SQL Server was producing a convoluted execution plan when executed from the SSRS report due to 'parameter sniffing'. The workaround was to declare variables inside of the stored procedure and assign the incoming parameters to the variables. Then the query used the variables rather than the parameters. This caused the query to perform consistently whether called from SQL Server Manager or through the SSRS report.

How to grep for contents after pattern?

Modern BASH has support for regular expressions:

while read -r line; do
  if [[ $line =~ ^potato:\ ([0-9]+) ]]; then
    echo "${BASH_REMATCH[1]}"
  fi
done

CSS: fixed to bottom and centered

Based on the comment from @Michael:

There is a better way to do this. Simply create the body with position:relative and a padding the size of the footer + the space between content and footer you want. Then just make a footer div with an absolute and bottom:0.

I went digging for the explanation and it boils down to this:

  • By default, absolute position of bottom:0px sets it to the bottom of the window...not the bottom of the page.
  • Relative positioning an element resets the scope of its children's absolute position...so by setting the body to relative positioning, the absolute position of bottom:0px now truly reflects the bottom of the page.

More details at http://css-tricks.com/absolute-positioning-inside-relative-positioning/

Difference between jar and war in Java

Basicly both compressed archives. war is used for web application with a specific directory structure.

GitHub: invalid username or password

There is a issue on Windows using cmd-Greetings

There is a issue on Windows using cmd-Greetings who will not let you clone private repositories. Remove that cmd-greeting described in this documentation (keyword Command Processor):

Known-Issues

I can confirm that other clients like SourceTree, GitKraken, Tower and TortoiseGit affected to this issue too.

How to convert string into float in JavaScript?

If they're meant to be separate values, try this:

var values = "554,20".split(",")
var v1 = parseFloat(values[0])
var v2 = parseFloat(values[1])

If they're meant to be a single value (like in French, where one-half is written 0,5)

var value = parseFloat("554,20".replace(",", "."));

PHP CURL CURLOPT_SSL_VERIFYPEER ignored

According to documentation: to verify host or peer certificate you need to specify alternate certificates with the CURLOPT_CAINFO option or a certificate directory can be specified with the CURLOPT_CAPATH option.

Also look at CURLOPT_SSL_VERIFYHOST:

  • 1 to check the existence of a common name in the SSL peer certificate.
  • 2 to check the existence of a common name and also verify that it matches the hostname provided.

curl_setopt($ch, CURLOPT_SSL_VERIFYHOST, 0);
curl_setopt($ch, CURLOPT_SSL_VERIFYPEER, 0);

Send POST parameters with MultipartFormData using Alamofire, in iOS Swift

for alamofire 4 use this ..

        Alamofire.upload(multipartFormData: { (multipartFormData) in

            multipartFormData.append(fileUrl, withName: "video")
       //fileUrl is your file path in iOS device and withName is parameter name

        }, to:"http://to_your_url_path")
        { (result) in
            switch result {
            case .success(let upload, _ , _):

                upload.uploadProgress(closure: { (progress) in

                    print("uploding")
                })

                upload.responseJSON { response in

                   print("done")

                }

            case .failure(let encodingError):
                print("failed")
                print(encodingError)

            }
        }

What is the difference between precision and scale?

Precision is the total number of digits, can be between 1 and 38.
Scale is the number of digits after the decimal point, may also be set as negative for rounding.

Example:
NUMBER(7,5): 12.12345
NUMBER(5,0): 12345

More details on the ORACLE website:
https://docs.oracle.com/cd/B28359_01/server.111/b28318/datatype.htm#CNCPT1832

A simple algorithm for polygon intersection

If you use C++, and don't want to create the algorithm yourself, you can use Boost.Geometry. It uses an adapted version of the Weiler-Atherton algorithm mentioned above.

CSS : center form in page horizontally and vertically

I suggest you using bootstrap which works perfectly:

_x000D_
_x000D_
@import url('http://getbootstrap.com/dist/css/bootstrap.css');_x000D_
 html, body, .container-table {_x000D_
    height: 100%;_x000D_
}_x000D_
.container-table {_x000D_
    display: table;_x000D_
}_x000D_
.vertical-center-row {_x000D_
    display: table-cell;_x000D_
    vertical-align: middle;_x000D_
}
_x000D_
<!DOCTYPE html PUBLIC "-//W3C//DTD XHTML 1.0 Transitional//EN" "http://www.w3.org/TR/xhtml1/DTD/xhtml1-transitional.dtd">_x000D_
<html xmlns="http://www.w3.org/1999/xhtml">_x000D_
<head>_x000D_
<meta http-equiv="Content-Type" content="text/html; charset=utf-8" />_x000D_
<meta name="viewport" content="width=device-width, initial-scale=1.0" />_x000D_
<title>Login Page | ... </title>_x000D_
_x000D_
<script src="http://cdnjs.cloudflare.com/ajax/libs/twitter-bootstrap/2.1.0/bootstrap.min.js"></script>_x000D_
</head>_x000D_
_x000D_
<body>_x000D_
_x000D_
 <div class="container container-table">_x000D_
  <div class="row vertical-center-row">_x000D_
   <div class="text-center col-md-4 col-md-offset-4" style="">_x000D_
      <form id="login" action="dashboard.html" method="post">_x000D_
     _x000D_
     <div class="username">_x000D_
      <div class="usernameinner">_x000D_
       <input type="text" name="username" id="username" placeholder="Login" />_x000D_
      </div>_x000D_
     </div>_x000D_
     _x000D_
     <div class="password">_x000D_
      <div class="passwordinner">_x000D_
       <input type="password" name="password" id="password" placeholder="Mot de passe" />_x000D_
      </div>_x000D_
     </div>_x000D_
     _x000D_
     <button id="login-button">Connexion</button>_x000D_
     _x000D_
     <div class="keep"><input type="checkbox" /> Gardez moi connecté</div>_x000D_
    _x000D_
    </form>_x000D_
   </div>_x000D_
  </div>_x000D_
 </div>_x000D_
</body>_x000D_
</html>
_x000D_
_x000D_
_x000D_

How to take character input in java

I had the same struggle and I this is what I used:

} public static void main(String[] args) {

Scanner scan = new Scanner(System.in);
System.out.print("Please enter the string: ");
String input = scan.next();
System.out.print("Please enter the required symbol: ");
String symbol = scan.next();        
char symbolChar = symbol.charAt(0);

This works just fine. The idea is to get from the string the only char in it.

Convert time span value to format "hh:mm Am/Pm" using C#

You can try this:

   string timeexample= string.Format("{0:hh:mm:ss tt}", DateTime.Now);

you can remove hh or mm or ss or tt according your need where hh is hour in 12 hr formate, mm is minutes,ss is seconds,and tt is AM/PM.

Homebrew: Could not symlink, /usr/local/bin is not writable

For those running into this issue (granted 4 years after this post was made) while running Mac OS High Sierra - the steps outlined here solved the problem for me. Essentially just outlines uninstalling and reinstalling brew.

https://medium.com/@mrkdsgn/brew-error-on-macos-high-sierra-check-you-have-permission-to-write-to-usr-local-e8bd1c6a22d4

After running those steps, brew link worked like a charm!

Disable PHP in directory (including all sub-directories) with .htaccess

None of those answers are working for me (either generating a 500 error or doing nothing). That is probably due to the fact that I'm working on a hosted server where I can't have access to Apache configuration.

But this worked for me :

RewriteRule ^.*\.php$ - [F,L]

This line will generate a 403 Forbidden error for any URL that ends with .php and ends up in this subdirectory.

@Oussama lead me to the right direction here, thanks to him.

Excel function to get first word from sentence in other cell

Generic solution extracting the first "n" words of refcell string into a new string of "x" number of characters

=LEFT(SUBSTITUTE(***refcell***&" "," ",REPT(" ",***x***),***n***),***x***)

Assuming A1 has text string to extract, the 1st word extracted to a 15 character result

=LEFT(SUBSTITUTE(A1&" "," ",REPT(" ",15),1),15)

This would result in "Toronto" being returned to a 15 character string. 1st 2 words extracted to a 30 character result

=LEFT(SUBSTITUTE(A1&" "," ",REPT(" ",30),2),30)

would result in "Toronto is" being returned to a 30 character string

How to kill a process in MacOS?

I just now searched for this as I'm in a similar situation, and instead of kill -9 698 I tried sudo kill 428 where 428 was the pid of the process I'm trying to kill. It worked cleanly for me, in the absence of the hyphen '-' character. I hope it helps!

"Could not find or load main class" Error while running java program using cmd prompt

I was facing similar issue but it was due to space character in my file directory where I kept my java class.

Scenario given below along with solution:

   public class Sample{
      public static void main(String[] args) {
        System.out.println("Hello world, Java");
      }
}
  • My Sample.java class was kept at Dir "D:\Java Programs\Sample.java"[NOTE: Package statement not present in java class].
  • In command prompt, changed directory to "D:\Java Programs\", my programmed compiled but failed to run with error "Could not find or load main class"
  • After all the possible solutions over SOF(nothing worked), I realized may b space causing me this issue.
  • Surprisingly removal of folder name space char['Java Programs' -> 'JavaPrograms'], my program executed successfully.

    Hope it helps

jQuery replace one class with another

Sometimes when you have multiple classes and you really need to overwrite all of them, it's easiest to use jQuery's .attr() to overwrite the class attribute:

$('#myElement').attr('class', 'new-class1 new-class2 new-class3');

scp copy directory to another server with private key auth

The command looks quite fine. Could you try to run -v (verbose mode) and then we can figure out what it is wrong on the authentication?

Also as mention in the other answer, maybe could be this issue - that you need to convert the keys (answered already here): How to convert SSH keypairs generated using PuttyGen(Windows) into key-pairs used by ssh-agent and KeyChain(Linux) OR http://winscp.net/eng/docs/ui_puttygen (depending what you need)

How do I hide a menu item in the actionbar?

I think a better approach would be to use a member variable for the menu, initialize it in onCreateOptionsMenu() and just use setVisible() afterwards, without invalidating the options menu.

How to add an auto-incrementing primary key to an existing table, in PostgreSQL?

ALTER TABLE test1 ADD COLUMN id SERIAL PRIMARY KEY;

This is all you need to:

  1. Add the id column
  2. Populate it with a sequence from 1 to count(*).
  3. Set it as primary key / not null.

Credit is given to @resnyanskiy who gave this answer in a comment.

Twitter Bootstrap 3, vertically center content

You can use display:inline-block instead of float and vertical-align:middle with this CSS:

.col-lg-4, .col-lg-8 {
    float:none;
    display:inline-block;
    vertical-align:middle;
    margin-right:-4px;
}

The demo http://bootply.com/94402

How do I remove diacritics (accents) from a string in .NET?

Try HelperSharp package.

There is a method RemoveAccents:

 public static string RemoveAccents(this string source)
 {
     //8 bit characters 
     byte[] b = Encoding.GetEncoding(1251).GetBytes(source);

     // 7 bit characters
     string t = Encoding.ASCII.GetString(b);
     Regex re = new Regex("[^a-zA-Z0-9]=-_/");
     string c = re.Replace(t, " ");
     return c;
 }

java.lang.NoClassDefFoundError: org.slf4j.LoggerFactory

Add a SLF4J implementation (as you only have its API):

<dependency>
    <groupId>org.slf4j</groupId>
    <artifactId>slf4j-log4j12</artifactId>
    <version>1.7.26</version>
</dependency>

angularjs make a simple countdown

Please take a look at this example here. It is a simple example of a count up! Which I think you could easily modify to create a count down.

http://jsfiddle.net/ganarajpr/LQGE2/

JavaScript code:

function AlbumCtrl($scope,$timeout) {
    $scope.counter = 0;
    $scope.onTimeout = function(){
        $scope.counter++;
        mytimeout = $timeout($scope.onTimeout,1000);
    }
    var mytimeout = $timeout($scope.onTimeout,1000);

    $scope.stop = function(){
        $timeout.cancel(mytimeout);
    }
}

HTML markup:

<!doctype html>
<html ng-app>
<head>
    <script src="http://code.angularjs.org/angular-1.0.0rc11.min.js"></script>
    <script src="http://documentcloud.github.com/underscore/underscore-min.js"></script>
</head>
<body>
<div ng-controller="AlbumCtrl">
    {{counter}}
    <button ng-click="stop()">Stop</button>    
</div>
</body>
</html>

PHP is_numeric or preg_match 0-9 validation

According to http://www.php.net/manual/en/function.is-numeric.php, is_numeric alows something like "+0123.45e6" or "0xFF". I think this not what you expect.

preg_match can be slow, and you can have something like 0000 or 0051.

I prefer using ctype_digit (works only with strings, it's ok with $_GET).

<?php
  $id = $_GET['id'];
  if (ctype_digit($id)) {
      echo 'ok';
  } else {
      echo 'nok';
  }
?>

Sass and combined child selector

Without the combined child selector you would probably do something similar to this:

foo {
  bar {
    baz {
      color: red;
    }
  }
}

If you want to reproduce the same syntax with >, you could to this:

foo {
  > bar {
    > baz {
      color: red;
    }
  }
}

This compiles to this:

foo > bar > baz {
  color: red;
}

Or in sass:

foo
  > bar
    > baz
      color: red

How to "comment-out" (add comment) in a batch/cmd?

Use :: or REM

::   commenttttttttttt
REM  commenttttttttttt

BUT (as people noted):

  • :: doesn't work inline; add & character:
    your commands here & :: commenttttttttttt
  • Inside nested parts (IF/ELSE, FOR loops, etc...) :: should be followed with normal line, otherwise it gives error (use REM there).
  • :: may also fail within setlocal ENABLEDELAYEDEXPANSION

Git commit in terminal opens VIM, but can't get back to terminal

not really the answer to the VIM problem but you could use the command line to also enter the commit message:

git commit -m "This is the first commit"

How to URL encode in Python 3?

You misread the documentation. You need to do two things:

  1. Quote each key and value from your dictionary, and
  2. Encode those into a URL

Luckily urllib.parse.urlencode does both those things in a single step, and that's the function you should be using.

from urllib.parse import urlencode, quote_plus

payload = {'username':'administrator', 'password':'xyz'}
result = urlencode(payload, quote_via=quote_plus)
# 'password=xyz&username=administrator'

Dropdown select with images

Seems like a straightforward html menu would be simpler. Use html5 data attributes for values or whatever method you want to store them and css to handle images as backgrounds or put them in the html itself.

Edit: If you are forced to convert from an existing select that you can't get rid of, there are some good plugins as well to modify a select to html. Wijmo and Chosen are a couple that come to mind

How to shift a column in Pandas DataFrame

I suppose imports

import pandas as pd
import numpy as np

First append new row with NaN, NaN,... at the end of DataFrame (df).

s1 = df.iloc[0]    # copy 1st row to a new Series s1
s1[:] = np.NaN     # set all values to NaN
df2 = df.append(s1, ignore_index=True)  # add s1 to the end of df

It will create new DF df2. Maybe there is more elegant way but this works.

Now you can shift it:

df2.x2 = df2.x2.shift(1)  # shift what you want

Getting the docstring from a function

You can also use inspect.getdoc. It cleans up the __doc__ by normalizing tabs to spaces and left shifting the doc body to remove common leading spaces.

how to use php DateTime() function in Laravel 5

I didn't mean to copy the same answer, that is why I didn't accept my own answer.

Actually when I add use DateTime in top of the controller solves this problem.

Comparing HTTP and FTP for transferring files

Many firewalls drop outbound connections which are not to ports 80 or 443 (http & https); some even drop connections to those ports that are not HTTP(S). FTP may or may not be allowed, not to speak of the active/PASV modes.

Also, HTTP/1.1 allows for much better partial requests ("only send from byte 123456 to the end of file"), conditional requests and caching ("only send if content changed/if last-modified-date changed") and content compression (gzip).

HTTP is much easier to use through a proxy.

From my anecdotal evidence, HTTP is easier to make work with dropped/slow/flaky connections; e.g. it is not needed to (re)establish a login session before (re)initiating transfer.

OTOH, HTTP is stateless, so you'd have to do authentication and building a trail of "who did what when" yourself.

The only difference in speed I've noticed is transferring lots of small files: HTTP with pipelining is faster (reduces round-trips, esp. noticeable on high-latency networks).

Note that HTTP/2 offers even more optimizations, whereas the FTP protocol has not seen any updates for decades (and even extensions to FTP have insignificant uptake by users). So, unless you are transferring files through a time machine, HTTP seems to have won.

(Tangentially: there are protocols that are better suited for file transfer, such as rsync or BitTorrent, but those don't have as much mindshare, whereas HTTP is Everywhere™)

How do I delete specific characters from a particular String in Java?

To remove the last character do as Mark Byers said

s = s.substring(0, s.length() - 1);

Additionally, another way to remove the characters you don't want would be to use the .replace(oldCharacter, newCharacter) method.

as in:

s = s.replace(",","");

and

s = s.replace(".","");

How to rearrange Pandas column sequence?

You can do the following:

df =DataFrame({'a':[1,2,3,4],'b':[2,4,6,8]})

df['x']=df.a + df.b
df['y']=df.a - df.b

create column title whatever order you want in this way:

column_titles = ['x','y','a','b']

df.reindex(columns=column_titles)

This will give you desired output

Concat strings by & and + in VB.Net

You can write '&' to add string and integer :

processDetails=objProcess.ProcessId & ":" & objProcess.name
message = msgbox(processDetails,16,"Details")

output will be:

5577:wscript.exe

Forgot Oracle username and password, how to retrieve?

Go to SQL command line:- type:

sql>connect / as sysdba;

then type:

sql>desc dba_users;

then type:

sql>select username,password from dba_users;

If sysdba doesn't work then try connecting with username:scott and password: Tiger

You will be able to see all users with passwords. Probably you might find your's. Hope this helps

Printing long int value in C

To take input " long int " and output " long int " in C is :

long int n;
scanf("%ld", &n);
printf("%ld", n);

To take input " long long int " and output " long long int " in C is :

long long int n;
scanf("%lld", &n);
printf("%lld", n);

Hope you've cleared..

How to send multiple data fields via Ajax?

Try to use :

$.ajax({
    type: "GET",
    url: "something.php",
    data: { "b": data1, "c": data2 },   
    dataType: "html",
    beforeSend: function() {},
    error: function() {
        alert("Error");
    },
    success: function(data) {                                                    
        $("#result").empty();
        $("#result").append(data);
    }
});

Python Loop: List Index Out of Range

Try reducing the range of the for loop to range(len(a)-1):

a = [0,1,2,3]
b = []

for i in range(len(a)-1):
    b.append(a[i]+a[i+1])

print(b)

This can also be written as a list comprehension:

b = [a[i] + a[i+1] for i in range(len(a)-1)]
print(b)

How to have PHP display errors? (I've added ini_set and error_reporting, but just gives 500 on errors)

You need to set the error_reporting value in a .htaccess file. Since there is a parse error, it never runs the error_reporting() function in your PHP code.

Try this in a .htaccess file (assuming you can use one):

php_flag display_errors 1
php_value error_reporting 30719

I think 30719 corresponds to E_ALL but I may be wrong.

Edit Update: http://php.net/manual/en/errorfunc.constants.php

int error_reporting ([ int $level ] )
---
32767   E_ALL (integer)     
All errors and warnings, as supported, except of   level E_STRICT prior to PHP 5.4.0.   32767 in PHP 5.4.x, 30719 in PHP 5.3.x, 6143 in PHP   5.2.x, 2047 previously

SQL Error: 0, SQLState: 08S01 Communications link failure

Check your server config file /etc/mysql/my.cnf - verify bind_address is not set to 127.0.0.1. Set it to 0.0.0.0 or comment it out then restart server with:

sudo service mysql restart

Adding items to a JComboBox

Method call setSelectedIndex("item_value"); doesn't work because setSelectedIndex use sequential index.

Check, using jQuery, if an element is 'display:none' or block on click

Yes, you can use the cssfunction. The below will search all divs, but you can modify it for whatever elements you need

$('div').each(function(){

    if ( $(this).css('display') == 'none')
    {
       //do something
    }
});

MVC 4 Razor adding input type date

The input date value format needs the date specified as per http://tools.ietf.org/html/rfc3339#section-5.6 full-date.

So I've ended up doing:

<input type="date" id="last-start-date" value="@string.Format("{0:yyyy-MM-dd}", Model.LastStartDate)" />

I did try doing it "properly" using:

[DataType(DataType.Date)]
[DisplayFormat(ApplyFormatInEditMode = true, DataFormatString = "{0:yyyy-MM-dd}")]
public DateTime LastStartDate
{
    get { return lastStartDate; }
    set { lastStartDate = value; }
}

with

@Html.TextBoxFor(model => model.LastStartDate, 
    new { type = "date" })

Unfortunately that always seemed to set the value attribute of the input to a standard date time so I've ended up applying the formatting directly as above.

Edit:

According to Jorn if you use

@Html.EditorFor(model => model.LastStartDate)

instead of TextBoxFor it all works fine.

Convert HTML string to image

Thanks all for your responses. I used HtmlRenderer external dll (library) to achieve the same and found below code for the same.

Here is the code for this

public void ConvertHtmlToImage()
{
   Bitmap m_Bitmap = new Bitmap(400, 600);
   PointF point = new PointF(0, 0);
   SizeF maxSize = new System.Drawing.SizeF(500, 500);
   HtmlRenderer.HtmlRender.Render(Graphics.FromImage(m_Bitmap),
                                           "<html><body><p>This is some html code</p>"
                                           + "<p>This is another html line</p></body>",
                                            point, maxSize);

   m_Bitmap.Save(@"C:\Test.png", ImageFormat.Png);
}

Create list of object from another using Java 8 Streams

What you are possibly looking for is map(). You can "convert" the objects in a stream to another by mapping this way:

...
 .map(userMeal -> new UserMealExceed(...))
...

How to check if a class inherits another class without instantiating it?

Try this

typeof(IFoo).IsAssignableFrom(typeof(BarClass));

This will tell you whether BarClass(Derived) implements IFoo(SomeType) or not

How to format a number 0..9 to display with 2 digits (it's NOT a date)

In android resources it's rather simple

<string name="smth">%1$02d</string>