Programs & Examples On #Rakefile

Rakefile: configuration file for Rake build language (equivalent build.xml in Ant). Rakefiles are Rake's version of Makefiles.

execJs: 'Could not find a JavaScript runtime' but execjs AND therubyracer are in Gemfile

I had the same problem on a staging server. I had no issues running rake tasks on my local development machine, but deploying to the staging server failed with the "Could not find a JavaScript runtime" error message while trying to run the assets:precompile rake task.

Of course, therubyracer and execjs were in my Gemfile, and I was using the latest versions. My Gemfile.lock files matched, and I further verified versions by running bundle show.

After searching around on Google, I ended up deleting all of my gems and reinstalling them which fixed the problem. I still don't know what the root cause was, but maybe this will help you.

Here's what my environment looks like, BTW:

Ubuntu 10.04.3 LTS
rbenv
Ruby 1.9.2-p290
bundler-1.0.21
execjs-1.3.0
therubyracer-0.9.9

How to start rails server?

I believe this is what happens if "rails new [project]" has not actually executed correctly. If you are doing this on windows and "rails server" just returns the help screen, you may need to restart your command prompt window and likely repeat your setup instructions. This is more likely true if this is your first time setting up the environment.

How to run Rake tasks from within Rake tasks?

I would suggest not to create general debug and release tasks if the project is really something that gets compiled and so results in files. You should go with file-tasks which is quite doable in your example, as you state, that your output goes into different directories. Say your project just compiles a test.c file to out/debug/test.out and out/release/test.out with gcc you could setup your project like this:

WAYS = ['debug', 'release']
FLAGS = {}
FLAGS['debug'] = '-g'
FLAGS['release'] = '-O'
def out_dir(way)
  File.join('out', way)
end
def out_file(way)
  File.join(out_dir(way), 'test.out')
end
WAYS.each do |way|
  desc "create output directory for #{way}"
  directory out_dir(way)

  desc "build in the #{way}-way"
  file out_file(way) => [out_dir(way), 'test.c'] do |t|
    sh "gcc #{FLAGS[way]} -c test.c -o #{t.name}"
  end
end
desc 'build all ways'
task :all => WAYS.map{|way|out_file(way)}

task :default => [:all]

This setup can be used like:

rake all # (builds debug and release)
rake debug # (builds only debug)
rake release # (builds only release)

This does a little more as asked for, but shows my points:

  1. output directories are created, as necessary.
  2. the files are only recompiled if needed (this example is only correct for the simplest of test.c files).
  3. you have all tasks readily at hand if you want to trigger the release build or the debug build.
  4. this example includes a way to also define small differences between debug and release-builds.
  5. no need to reenable a build-task that is parametrized with a global variable, because now the different builds have different tasks. the codereuse of the build-task is done by reusing the code to define the build-tasks. see how the loop does not execute the same task twice, but instead created tasks, that can later be triggered (either by the all-task or be choosing one of them on the rake commandline).

How do you run a single test/spec file in RSpec?

http://github.com/grosser/single_test lets you do stuff like..

rake spec:user          #run spec/model/user_spec.rb (searches for user*_spec.rb)
rake test:users_c       #run test/functional/users_controller_test.rb
rake spec:user:token    #run the first spec in user_spec.rb that matches /token/
rake test:user:token    #run all tests in user_test.rb that match /token/
rake test:last
rake spec:last

How can I insert into a BLOB column from an insert statement in sqldeveloper?

  1. insert into mytable(id, myblob) values (1,EMPTY_BLOB);
  2. SELECT * FROM mytable mt where mt.id=1 for update
  3. Click on the Lock icon to unlock for editing
  4. Click on the ... next to the BLOB to edit
  5. Select the appropriate tab and click open on the top left.
  6. Click OK and commit the changes.

Message Queue vs. Web Services?

I think in general, you'd want a web service for a blocking task (this tasks needs to be completed before we execute more code), and a message queue for a non-blocking task (could take quite a while, but we don't need to wait for it).

How to set Grid row and column positions programmatically

for (int i = 0; i < 6; i++)
{
    test.ColumnDefinitions.Add(new ColumnDefinition());

    Label t1 = new Label();
    t1.Content = "Test" + i;

    Grid.SetColumn(t1, i);
    Grid.SetRow(t1, 0);
    test.Children.Add(t1);
}

How to convert a String to CharSequence?

CharSequence is an interface and String is its one of the implementations other than StringBuilder, StringBuffer and many other.

So, just as you use InterfaceName i = new ItsImplementation(), you can use CharSequence cs = new String("string") or simply CharSequence cs = "string";

Creating Duplicate Table From Existing Table

Use this query to create the new table with the values from existing table

CREATE TABLE New_Table_name AS SELECT * FROM Existing_table_Name; 

Now you can get all the values from existing table into newly created table.

What are carriage return, linefeed, and form feed?

As a supplement,

1, Carriage return: It's a printer terminology meaning changing the print location to the beginning of current line. In computer world, it means return to the beginning of current line in most cases but stands for new line rarely.

2, Line feed: It's a printer terminology meaning advancing the paper one line. So Carriage return and Line feed are used together to start to print at the beginning of a new line. In computer world, it generally has the same meaning as newline.

3, Form feed: It's a printer terminology, I like the explanation in this thread.

If you were programming for a 1980s-style printer, it would eject the paper and start a new page. You are virtually certain to never need it.

http://en.wikipedia.org/wiki/Form_feed

It's almost obsolete and you can refer to Escape sequence \f - form feed - what exactly is it? for detailed explanation.

Note, we can use CR or LF or CRLF to stand for newline in some platforms but newline can't be stood by them in some other platforms. Refer to wiki Newline for details.

LF: Multics, Unix and Unix-like systems (Linux, OS X, FreeBSD, AIX, Xenix, etc.), BeOS, Amiga, RISC OS, and others

CR: Commodore 8-bit machines, Acorn BBC, ZX Spectrum, TRS-80, Apple II family, Oberon, the classic Mac OS up to version 9, MIT Lisp Machine and OS-9

RS: QNX pre-POSIX implementation

0x9B: Atari 8-bit machines using ATASCII variant of ASCII (155 in decimal)

CR+LF: Microsoft Windows, DOS (MS-DOS, PC DOS, etc.), DEC TOPS-10, RT-11, CP/M, MP/M, Atari TOS, OS/2, Symbian OS, Palm OS, Amstrad CPC, and most other early non-Unix and non-IBM OSes

LF+CR: Acorn BBC and RISC OS spooled text output.

How to copy directories in OS X 10.7.3?

Is there something special with that directory or are you really just asking how to copy directories?

Copy recursively via CLI:

cp -R <sourcedir> <destdir>

If you're only seeing the files under the sourcedir being copied (instead of sourcedir as well), that's happening because you kept the trailing slash for sourcedir:

cp -R <sourcedir>/ <destdir>

The above only copies the files and their directories inside of sourcedir. Typically, you want to include the directory you're copying, so drop the trailing slash:

cp -R <sourcedir> <destdir>

Copy files to network computers on windows command line

check Robocopy:

ROBOCOPY \\server-source\c$\VMExports\ C:\VMExports\ /E /COPY:DAT

make sure you check what robocopy parameter you want. this is just an example. type robocopy /? in a comandline/powershell on your windows system.

What is the Java equivalent of PHP var_dump?

I like to use GSON because it's often already a dependency of the type of projects I'm working on:

public static String getDump(Object o) {
    return new GsonBuilder().setPrettyPrinting().create().toJson(o);
}

Or substitute GSON for any other JSON library you use.

Using union and order by clause in mysql

Try:

SELECT result.* 
FROM (
 [QUERY 1]
 UNION
 [QUERY 2]
) result
ORDER BY result.id

Where [QUERY 1] and [QUERY 2] are your two queries that you want to merge.

Import and Export Excel - What is the best library?

I've been using ClosedXML and it works great!

ClosedXML makes it easier for developers to create Excel 2007/2010 files. It provides a nice object oriented way to manipulate the files (similar to VBA) without dealing with the hassles of XML Documents. It can be used by any .NET language like C# and Visual Basic (VB).

How can I find the product GUID of an installed MSI setup?

If you have too many installers to find what you are looking for easily, here is some powershell to provide a filter and narrow it down a little by display name.

$filter = "*core*sdk*"; (Get-ChildItem HKLM:\SOFTWARE\Microsoft\Windows\CurrentVersion\Uninstall).Name | % { $path = "Registry::$_"; Get-ItemProperty $path } | Where-Object { $_.DisplayName -like $filter } | Select-Object -Property DisplayName, PsChildName

How to find all occurrences of an element in a list

Using a for-loop:

  • Answers with enumerate and a list comprehension are more pythonic, not necessarily faster, however, this answer is aimed at students who may not be allowed to use some of those built-in functions.
  • create an empty list, indices
  • create the loop with for i in range(len(x)):, which essentially iterates through a list of index locations [0, 1, 2, 3, ..., len(x)-1]
  • in the loop, add any i, where x[i] is a match to value, to indices
def get_indices(x: list, value: int) -> list:
    indices = list()
    for i in range(len(x)):
        if x[i] == value:
            indices.append(i)
    return indices

n = [1, 2, 3, -50, -60, 0, 6, 9, -60, -60]
print(get_indices(n, -60))

>>> [4, 8, 9]
  • The functions, get_indices, are implemented with type hints. In this case, the list, n, is a bunch of ints, therefore we search for value, also defined as an int.

Using a while-loop and .index:

  • With .index, use try-except for error handling, because a ValueError will occur if value is not in the list.
def get_indices(x: list, value: int) -> list:
    indices = list()
    i = 0
    while True:
        try:
            # find an occurrence of value and update i to that index
            i = x.index(value, i)
            # add i to the list
            indices.append(i)
            # advance i by 1
            i += 1
        except ValueError as e:
            break
    return indices

print(get_indices(n, -60))
>>> [4, 8, 9]

Align button at the bottom of div using CSS

Goes to the right and can be used the same way for the left

.yourComponent
{
   float: right;
   bottom: 0;
}

C++ - Hold the console window open?

How about std::cin.get(); ?

Also, if you're using Visual Studio, you can run without debugging (CTRL-F5 by default) and it won't close the console at the end. If you run it with debugging, you could always put a breakpoint at the closing brace of main().

How to deal with ModalDialog using selenium webdriver?

Assuming the expectation is just going to be two windows popping up (one of the parent and one for the popup) then just wait for two windows to come up, find the other window handle and switch to it.

WebElement link = // element that will showModalDialog()

// Click on the link, but don't wait for the document to finish
final JavascriptExecutor executor = (JavascriptExecutor) driver;
executor.executeScript(
    "var el=arguments[0]; setTimeout(function() { el.click(); }, 100);",
  link);

// wait for there to be two windows and choose the one that is 
// not the original window
final String parentWindowHandle = driver.getWindowHandle();
new WebDriverWait(driver, 60, 1000)
    .until(new Function<WebDriver, Boolean>() {
    @Override
    public Boolean apply(final WebDriver driver) {
        final String[] windowHandles =
            driver.getWindowHandles().toArray(new String[0]);
        if (windowHandles.length != 2) {
            return false;
        }
        if (windowHandles[0].equals(parentWindowHandle)) {
            driver.switchTo().window(windowHandles[1]);
        } else {
            driver.switchTo().window(windowHandles[0]);
        }
        return true;
    }
});

UIButton: set image for selected-highlighted state

Swift 3+

button.setImage(UIImage(named: "selected_image"), for: [.selected, .highlighted])

OR

button.setImage(UIImage(named: "selected_image"), for: UIControlState.selected.union(.highlighted))

It means that the button current in selected state, then you touch it, show the highlight state.

What can MATLAB do that R cannot do?

As a user of both MATLAB and R, I think they are very different applications. I myself have a background in computer science, etc. and I can't help thinking that R is by statisticians for statisticians whereas MATLAB is by programmers for programmers.

R makes it very easy to visualize and compute all sorts of statistical stuff but I wouldn't use it to implement anything signal processing related if it was up to me.

To sum up, if you want to do statistics, use R. If you want to program, use MATLAB or some programming language.

Add a custom attribute to a Laravel / Eloquent model on load?

you can use setAttribute function in Model to add a custom attribute

Py_Initialize fails - unable to load the file system codec

Ran into the same thing trying to install brew's python3 under Mac OS! The issue here is that in Mac OS, homebrew puts the "real" python a whole layer deeper than you think. You would think from the homebrew output that

$ echo $PYTHONHOME
/usr/local/Cellar/python3/3.6.2/
$ echo $PYTHONPATH
/usr/local/Cellar/python3/3.6.2/bin

would be correct, but invoking $PYTHONPATH/python3 immediately crashes with the abort 6 "can't find encodings." This is because although that $PYTHONHOME looks like a complete installation, having a bin, lib etc, it is NOT the actual Python, which is in a Mac OS "Framework". Do this:

PYTHONHOME=/usr/local/Cellar/python3/3.x.y/Frameworks/Python.framework/Versions/3.x
PYTHONPATH=$PYTHONHOME/bin

(substituting version numbers as appropriate) and it will work fine.

What does the return keyword do in a void method in Java?

The Java language specification says you can have return with no expression if your method returns void.

How to find controls in a repeater header or footer

private T GetHeaderControl<T>(Repeater rp, string id) where T : Control
{
    T returnValue = null;
    if (rp != null && !String.IsNullOrWhiteSpace(id))
    {
        returnValue = rp.Controls.Cast<RepeaterItem>().Where(i => i.ItemType == ListItemType.Header).Select(h => h.FindControl(id) as T).Where(c => c != null).FirstOrDefault();
    }
    return returnValue;
}

Finds and casts the control. (Based on Piyey's VB answer)

Actual meaning of 'shell=True' in subprocess

The benefit of not calling via the shell is that you are not invoking a 'mystery program.' On POSIX, the environment variable SHELL controls which binary is invoked as the "shell." On Windows, there is no bourne shell descendent, only cmd.exe.

So invoking the shell invokes a program of the user's choosing and is platform-dependent. Generally speaking, avoid invocations via the shell.

Invoking via the shell does allow you to expand environment variables and file globs according to the shell's usual mechanism. On POSIX systems, the shell expands file globs to a list of files. On Windows, a file glob (e.g., "*.*") is not expanded by the shell, anyway (but environment variables on a command line are expanded by cmd.exe).

If you think you want environment variable expansions and file globs, research the ILS attacks of 1992-ish on network services which performed subprogram invocations via the shell. Examples include the various sendmail backdoors involving ILS.

In summary, use shell=False.

How to use a App.config file in WPF applications?

In my case, I followed the steps below.

App.config

<configuration>  
   <startup> 
       <supportedRuntime version="v4.0" sku=".NETFramework,Version=v4.5" />
  </startup>

 <appSettings>
   <add key="POCPublishSubscribeQueueName" value="FormatName:Direct=OS:localhost\Private$\POCPublishSubscribe"/>
 </appSettings>

</configuration>

Added System.Configuartion to my project.

Added using System.Configuration statement in file at top.

Then used this statement:

string queuePath = ConfigurationManager.AppSettings["POCPublishSubscribeQueueName"].ToString();

How to view .img files?

As you did not mention which OS you are running, here a solution for linux: use losetup

losetup /dev/loop0 /path/to/your/file.img

Then you can mount it.

How to skip "are you sure Y/N" when deleting files in batch files

You have the following options on Windows command line:

net use [DeviceName [/home[{Password | *}] [/delete:{yes | no}]]

Try like:

net use H: /delete /y

Default parameters with C++ constructors

One thing bothering me with default parameters is that you can't specify the last parameters but use the default values for the first ones. For example, in your code, you can't create a Foo with no name but a given age (however, if I remember correctly, this will be possible in C++0x, with the unified constructing syntax). Sometimes, this makes sense, but it can also be really awkward.

In my opinion, there is no rule of thumb. Personnaly, I tend to use multiple overloaded constructors (or methods), except if only the last argument needs a default value.

ssh: Could not resolve hostname [hostname]: nodename nor servname provided, or not known

If you're on Mac, restarting the DNS responder fixed the issue for me.

sudo killall -HUP mDNSResponder

What are the differences between a clustered and a non-clustered index?

Clustered indexes physically order the data on the disk. This means no extra data is needed for the index, but there can be only one clustered index (obviously). Accessing data using a clustered index is fastest.

All other indexes must be non-clustered. A non-clustered index has a duplicate of the data from the indexed columns kept ordered together with pointers to the actual data rows (pointers to the clustered index if there is one). This means that accessing data through a non-clustered index has to go through an extra layer of indirection. However if you select only the data that's available in the indexed columns you can get the data back directly from the duplicated index data (that's why it's a good idea to SELECT only the columns that you need and not use *)

importing pyspark in python shell

For a Spark execution in pyspark two components are required to work together:

  • pyspark python package
  • Spark instance in a JVM

When launching things with spark-submit or pyspark, these scripts will take care of both, i.e. they set up your PYTHONPATH, PATH, etc, so that your script can find pyspark, and they also start the spark instance, configuring according to your params, e.g. --master X

Alternatively, it is possible to bypass these scripts and run your spark application directly in the python interpreter likepython myscript.py. This is especially interesting when spark scripts start to become more complex and eventually receive their own args.

  1. Ensure the pyspark package can be found by the Python interpreter. As already discussed either add the spark/python dir to PYTHONPATH or directly install pyspark using pip install.
  2. Set the parameters of spark instance from your script (those that used to be passed to pyspark).
    • For spark configurations as you'd normally set with --conf they are defined with a config object (or string configs) in SparkSession.builder.config
    • For main options (like --master, or --driver-mem) for the moment you can set them by writing to the PYSPARK_SUBMIT_ARGS environment variable. To make things cleaner and safer you can set it from within Python itself, and spark will read it when starting.
  3. Start the instance, which just requires you to call getOrCreate() from the builder object.

Your script can therefore have something like this:

from pyspark.sql import SparkSession

if __name__ == "__main__":
    if spark_main_opts:
        # Set main options, e.g. "--master local[4]"
        os.environ['PYSPARK_SUBMIT_ARGS'] = spark_main_opts + " pyspark-shell"

    # Set spark config
    spark = (SparkSession.builder
             .config("spark.checkpoint.compress", True)
             .config("spark.jars.packages", "graphframes:graphframes:0.5.0-spark2.1-s_2.11")
             .getOrCreate())

how can I Update top 100 records in sql server

for those like me still stuck with SQL Server 2000, SET ROWCOUNT {number}; can be used before the UPDATE query

SET ROWCOUNT 100;
UPDATE Table SET ..;
SET ROWCOUNT 0;

will limit the update to 100 rows

It has been deprecated at least since SQL 2005, but as of SQL 2017 it still works. https://docs.microsoft.com/en-us/sql/t-sql/statements/set-rowcount-transact-sql?view=sql-server-2017

Read all worksheets in an Excel workbook into an R list with data.frames

I stumbled across this old question and I think the easiest approach is still missing.

You can use rio to import all excel sheets with just one line of code.

library(rio)
data_list <- import_list("test.xls")

If you're a fan of the tidyverse, you can easily import them as tibbles by adding the setclass argument to the function call.

data_list <- import_list("test.xls", setclass = "tbl")

Suppose they have the same format, you could easily row bind them by setting the rbind argument to TRUE.

data_list <- import_list("test.xls", setclass = "tbl", rbind = TRUE)

merge one local branch into another local branch

First, checkout to your Branch3:

git checkout Branch3

Then merge the Branch1:

git merge Branch1

And if you want the updated commits of Branch1 on Branch2, you are probaly looking for git rebase

git checkout Branch2
git rebase Branch1

This will update your Branch2 with the latest updates of Branch1.

Using Colormaps to set color of line in matplotlib

U may do as I have written from my deleted account (ban for new posts :( there was). Its rather simple and nice looking.

Im using 3-rd one of these 3 ones usually, also I wasny checking 1 and 2 version.

from matplotlib.pyplot import cm
import numpy as np

#variable n should be number of curves to plot (I skipped this earlier thinking that it is obvious when looking at picture - sorry my bad mistake xD): n=len(array_of_curves_to_plot)
#version 1:

color=cm.rainbow(np.linspace(0,1,n))
for i,c in zip(range(n),color):
   ax1.plot(x, y,c=c)

#or version 2: - faster and better:

color=iter(cm.rainbow(np.linspace(0,1,n)))
c=next(color)
plt.plot(x,y,c=c)

#or version 3:

color=iter(cm.rainbow(np.linspace(0,1,n)))
for i in range(n):
   c=next(color)
   ax1.plot(x, y,c=c)

example of 3:

Ship RAO of Roll vs Ikeda damping in function of Roll amplitude A44

JSON.Net Self referencing loop detected

Add "[JsonIgnore]" to your model class

{
  public Customer()
  {
    Orders = new Collection<Order>();
  }

public int Id { get; set; }
public string Name { get; set; }
public string Surname { get; set; }

[JsonIgnore]
public ICollection<Order> Orders { get; set; }
}

How do you embed binary data in XML?

I had this problem just last week. I had to serialize a PDF file and send it, inside an XML file, to a server.

If you're using .NET, you can convert a binary file directly to a base64 string and stick it inside an XML element.

string base64 = Convert.ToBase64String(File.ReadAllBytes(fileName));

Or, there is a method built right into the XmlWriter object. In my particular case, I had to include Microsoft's datatype namespace:

StringBuilder sb = new StringBuilder();
System.Xml.XmlWriter xw = XmlWriter.Create(sb);
xw.WriteStartElement("doc");
xw.WriteStartElement("serialized_binary");
xw.WriteAttributeString("types", "dt", "urn:schemas-microsoft-com:datatypes", "bin.base64");
byte[] b = File.ReadAllBytes(fileName);
xw.WriteBase64(b, 0, b.Length);
xw.WriteEndElement();
xw.WriteEndElement();
string abc = sb.ToString();

The string abc looks something that looks like this:

<?xml version="1.0" encoding="utf-16"?>
<doc>
    <serialized_binary types:dt="bin.base64" xmlns:types="urn:schemas-microsoft-com:datatypes">
        JVBERi0xLjMKJaqrrK0KNCAwIG9iago8PCAvVHlwZSAvSW5mbw...(plus lots more)
    </serialized_binary>
</doc>

open new tab(window) by clicking a link in jquery

Try this:

window.open(url, '_blank');

This will open in new tab (if your code is synchronous and in this case it is. in other case it would open a window)

ApplicationContextException: Unable to start ServletWebServerApplicationContext due to missing ServletWebServerFactory bean

In my case, I was using an TOMCAT 8 and updating to TOMCAT 9 fixed it:

  <modelVersion>4.0.0</modelVersion>
  <groupId>spring-boot-app</groupId>
  <artifactId>spring-boot-app</artifactId>
  <version>0.0.1-SNAPSHOT</version>
  <packaging>war</packaging>

  <parent>
    <groupId>org.springframework.boot</groupId>
    <artifactId>spring-boot-starter-parent</artifactId>
    <version>2.3.1.RELEASE</version>
    <relativePath/> <!-- lookup parent from repository -->
  </parent>

  <dependencies>
    <dependency>
      <groupId>org.springframework.boot</groupId>
      <artifactId>spring-boot-starter-web</artifactId>
    </dependency>
    <dependency>
      <groupId>org.springframework.boot</groupId>
      <artifactId>spring-boot-starter-data-jpa</artifactId>
    </dependency>
    <dependency>
      <groupId>com.h2database</groupId>
      <artifactId>h2</artifactId>
    </dependency>
    <dependency>
      <groupId>org.springframework.boot</groupId>
      <artifactId>spring-boot-starter-test</artifactId>
    </dependency>
  </dependencies>

  <build>
    <plugins>
      <plugin>
        <groupId>org.codehaus.mojo</groupId>
        <artifactId>exec-maven-plugin</artifactId>
        <version>1.2.1</version>
        <executions>
          <execution>
            <goals>
              <goal>java</goal>
            </goals>
          </execution>
        </executions>
        <configuration>
          <mainClass>com.example.Application</mainClass>
        </configuration>
      </plugin>
    </plugins>
  </build>

  <properties>
    <tomcat.version>9.0.37</tomcat.version>
  </properties>

Related issues:

  1. https://github.com/spring-projects/spring-boot/issues?q=missing+ServletWebServerFactory+bean
  2. https://github.com/spring-projects/spring-boot/issues/22013 - Spring Boot app as a module
  3. https://github.com/spring-projects/spring-boot/issues/19141 - Application fails to load when main class extends a base class annotated with @SpringBootApplication when spring-boot-starter-web is included as a dependency

How to count the number of set bits in a 32-bit integer?

Simple algorithm to count the number of set bits:

int countbits(n){
     int count = 0;
     while(n != 0){
        n = n & (n-1);
        count++;
   }
   return count;
}

Take the example of 11 (1011) and try manually running through the algorithm. Should help you a lot!

Error: Can't set headers after they are sent to the client

If you din't get help from above : for noobs The reason behind this error is sending request multiple times let us understand from some cases:- 1. `

module.exports = (req,res,next)=>{
        try{
           const decoded  = jwt.verify(req.body.token,"secret");
           req.userData = decoded;
           next();
        }catch(error){
            return res.status(401).json({message:'Auth failed'});
        }
        next();   
        }

` in the above calling next() twice will raise an error

  1. router.delete('/:orderId', (req, res, next) => { Order.remove({_id:req.params.orderId},(err,data)=>{ if(err){ **res.status(500).json(err);** }else{ res.status(200).json(data); } *res.status(200).json(data);* }) })

here respond is send twice check whether you already sent a response

Date minus 1 year?

On my website, to check if registering people is 18 years old, I simply used the following :

$legalAge = date('Y-m-d', strtotime('-18 year'));

After, only compare the the two dates.

Hope it could help someone.

How to edit hosts file via CMD?

Use Hosts Commander. It's simple and powerful. Translated description (from russian) here.

Examples of using

hosts add another.dev 192.168.1.1 # Remote host
hosts add test.local # 127.0.0.1 used by default
hosts set myhost.dev # new comment
hosts rem *.local
hosts enable local*
hosts disable localhost

...and many others...

Help

Usage:
    hosts - run hosts command interpreter
    hosts <command> <params> - execute hosts command

Commands:
    add  <host> <aliases> <addr> # <comment>   - add new host
    set  <host|mask> <addr> # <comment>        - set ip and comment for host
    rem  <host|mask>   - remove host
    on   <host|mask>   - enable host
    off  <host|mask>   - disable host
    view [all] <mask>  - display enabled and visible, or all hosts
    hide <host|mask>   - hide host from 'hosts view'
    show <host|mask>   - show host in 'hosts view'
    print      - display raw hosts file
    format     - format host rows
    clean      - format and remove all comments
    rollback   - rollback last operation
    backup     - backup hosts file
    restore    - restore hosts file from backup
    recreate   - empty hosts file
    open       - open hosts file in notepad

Download

https://code.google.com/p/hostscmd/downloads/list

How to check if a file is empty in Bash?

Misspellings are irritating, aren't they? Check your spelling of empty, but then also try this:

#!/bin/bash -e

if [ -s diff.txt ]
then
        rm -f empty.txt
        touch full.txt
else
        rm -f full.txt
        touch empty.txt
fi

I like shell scripting a lot, but one disadvantage of it is that the shell cannot help you when you misspell, whereas a compiler like your C++ compiler can help you.

Notice incidentally that I have swapped the roles of empty.txt and full.txt, as @Matthias suggests.

Hash function for a string

Java's String implements hashCode like this:

public int hashCode()

Returns a hash code for this string. The hash code for a String object is computed as

     s[0]*31^(n-1) + s[1]*31^(n-2) + ... + s[n-1]

using int arithmetic, where s[i] is the ith character of the string, n is the length of the string, and ^ indicates exponentiation. (The hash value of the empty string is zero.) 

So something like this:

int HashTable::hash (string word) {
    int result = 0;
    for(size_t i = 0; i < word.length(); ++i) {
        result += word[i] * pow(31, i);
    }
    return result;
}

What is the height of iPhone's onscreen keyboard?

I used the following approach for determining the frame of the keyboard in iOS 7.1.

In the init method of my view controller, I registered for the UIKeyboardDidShowNotification:

NSNotificationCenter *center = [NSNotificationCenter defaultCenter];
[center addObserver:self selector:@selector(keyboardOnScreen:) name:UIKeyboardDidShowNotification object:nil];

Then, I used the following code in keyboardOnScreen: to gain access to the frame of the keyboard. This code gets the userInfo dictionary from the notification and then accesses the NSValue associated with UIKeyboardFrameEndUserInfoKey. You can then access the CGRect and convert it to the coordinates of the view of your view controller. From there, you can perform any calculations you need based on that frame.

-(void)keyboardOnScreen:(NSNotification *)notification 
 {
        NSDictionary *info  = notification.userInfo;
        NSValue      *value = info[UIKeyboardFrameEndUserInfoKey];

        CGRect rawFrame      = [value CGRectValue];
        CGRect keyboardFrame = [self.view convertRect:rawFrame fromView:nil];

        NSLog(@"keyboardFrame: %@", NSStringFromCGRect(keyboardFrame));
 }

Swift

And the equivalent implementation with Swift:

NotificationCenter.default.addObserver(self, selector: #selector(keyboardDidShow), name: UIResponder.keyboardDidShowNotification, object: nil)


@objc
func keyboardDidShow(notification: Notification) {
    guard let info = notification.userInfo else { return }
    guard let frameInfo = info[UIResponder.keyboardFrameEndUserInfoKey] as? NSValue else { return }
    let keyboardFrame = frameInfo.cgRectValue
    print("keyboardFrame: \(keyboardFrame)")
}

How do I resolve a path relative to an ASP.NET MVC 4 application root?

To get the absolute path use this:

String path = HttpContext.Current.Server.MapPath("~/Data/data.html");

EDIT:

To get the Controller's Context remove .Current from the above line. By using HttpContext by itself it's easier to Test because it's based on the Controller's Context therefore more localized.

I realize now that I dislike how Server.MapPath works (internally eventually calls HostingEnvironment.MapPath) So I now recommend to always use HostingEnvironment.MapPath because its static and not dependent on the context unless of course you want that...

How can foreign key constraints be temporarily disabled using T-SQL?

http://www.sqljunkies.com/WebLog/roman/archive/2005/01/30/7037.aspx

-- Disable all table constraints

ALTER TABLE MyTable NOCHECK CONSTRAINT ALL

-- Enable all table constraints

ALTER TABLE MyTable WITH CHECK CHECK CONSTRAINT ALL

-- Disable single constraint

ALTER TABLE MyTable NOCHECK CONSTRAINT MyConstraint

-- Enable single constraint

ALTER TABLE MyTable WITH CHECK CHECK CONSTRAINT MyConstraint

What is the difference between PUT, POST and PATCH?

Think of it this way...

POST - create

PUT - replace

PATCH - update

GET - read

DELETE - delete

How to correctly dismiss a DialogFragment?

I think a better way to close a DialogFragment is this:

Fragment prev = getSupportFragmentManager().findFragmentByTag("fragment_dialog");
if (prev != null) {
    DialogFragment df = (DialogFragment) prev;
    df.dismiss();
}

This way you dont have to hold a reference to the DialogFragment and can close it from everywhere.

Radio button checked event handling

Update in 2017: Hey. This is a terrible answer. Don't use it. Back in the old days this type of jQuery use was common. And it probably worked back then. Just read it, realize it's terrible, then move on (or downvote or, whatever) to one of the other answers that are better for today's jQuery.


$("input[type=radio]").change(function(){
    alert( $("input[type=radio][name="+ this.name + "]").val() );
});

How to find common elements from multiple vectors?

intersect_all <- function(a,b,...){
  all_data <- c(a,b,...)
  require(plyr)
  count_data<- length(list(a,b,...))
  freq_dist <- count(all_data)
  intersect_data <- freq_dist[which(freq_dist$freq==count_data),"x"]
  intersect_data
}


intersect_all(a,b,c)

UPDATE EDIT A simpler code

intersect_all <- function(a,b,...){
  Reduce(intersect, list(a,b,...))
}

intersect_all(a,b,c)

mysql query result into php array

What about this:

while ($row = mysql_fetch_array($result)) 
{
    $new_array[$row['id']]['id'] = $row['id'];
    $new_array[$row['id']]['link'] = $row['link'];
}

To retrieve link and id:

foreach($new_array as $array)
{       
   echo $array['id'].'<br />';
   echo $array['link'].'<br />';
}

Android EditText Hint

You can use the concept of selector. onFocus removes the hint.

android:hint="Email"

So when TextView has focus, or has user input (i.e. not empty) the hint will not display.

SQL server ignore case in a where expression

What database are you on? With MS SQL Server, it's a database-wide setting, or you can over-ride it per-query with the COLLATE keyword.

collapse cell in jupyter notebook

JupyterLab supports cell collapsing. Clicking on the blue cell bar on the left will fold the cell. enter image description here

Linux command to print directory structure in the form of a tree

This command works to display both folders and files.

find . | sed -e "s/[^-][^\/]*\// |/g" -e "s/|\([^ ]\)/|-\1/"

Example output:

.
 |-trace.pcap
 |-parent
 | |-chdir1
 | | |-file1.txt
 | |-chdir2
 | | |-file2.txt
 | | |-file3.sh
 |-tmp
 | |-json-c-0.11-4.el7_0.x86_64.rpm

Source: Comment from @javasheriff here. Its submerged as a comment and posting it as answer helps users spot it easily.

How to search images from private 1.0 registry in docker?

Was able to get everything in my private registry back by searching just for 'library':

docker search [my.registry.host]:[port]/library

Returns (e.g.):

NAME                    DESCRIPTION   STARS     OFFICIAL   AUTOMATED
library/custom-image                  0                    
library/another-image                 0                    
library/hello-world                   0

How to sort with lambda in Python

You're trying to use key functions with lambda functions.

Python and other languages like C# or F# use lambda functions.

Also, when it comes to key functions and according to the documentation

Both list.sort() and sorted() have a key parameter to specify a function to be called on each list element prior to making comparisons.

...

The value of the key parameter should be a function that takes a single argument and returns a key to use for sorting purposes. This technique is fast because the key function is called exactly once for each input record.

So, key functions have a parameter key and it can indeed receive a lambda function.

In Real Python there's a nice example of its usage. Let's say you have the following list

ids = ['id1', 'id100', 'id2', 'id22', 'id3', 'id30']

and want to sort through its "integers". Then, you'd do something like

sorted_ids = sorted(ids, key=lambda x: int(x[2:])) # Integer sort

and printing it would give

['id1', 'id2', 'id3', 'id22', 'id30', 'id100']

In your particular case, you're only missing to write key= before lambda. So, you'd want to use the following

a = sorted(a, key=lambda x: x.modified, reverse=True)

CSS Background Image Not Displaying

background : url (/img.. )

NOTE: If you have your css in a different folder, ensure that you start the image path with THE FORWARD SLASH.

It worked for me. !

Error when trying vagrant up

This happened due to having a vagrant file without a defined box name. this happen when you running vagrant init with out a box name parameter.

So you have to delete the Vagrant file then

vagrant init box-title
vagrant up

I hope this could help!

Resolve conflicts using remote changes when pulling from Git remote

If you truly want to discard the commits you've made locally, i.e. never have them in the history again, you're not asking how to pull - pull means merge, and you don't need to merge. All you need do is this:

# fetch from the default remote, origin
git fetch
# reset your current branch (master) to origin's master
git reset --hard origin/master

I'd personally recommend creating a backup branch at your current HEAD first, so that if you realize this was a bad idea, you haven't lost track of it.

If on the other hand, you want to keep those commits and make it look as though you merged with origin, and cause the merge to keep the versions from origin only, you can use the ours merge strategy:

# fetch from the default remote, origin
git fetch
# create a branch at your current master
git branch old-master
# reset to origin's master
git reset --hard origin/master
# merge your old master, keeping "our" (origin/master's) content
git merge -s ours old-master

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

You can use this js code:

<input type="date" id="dateDefault" />

JS

function setInputDate(_id){
    var _dat = document.querySelector(_id);
    var hoy = new Date(),
        d = hoy.getDate(),
        m = hoy.getMonth()+1, 
        y = hoy.getFullYear(),
        data;

    if(d < 10){
        d = "0"+d;
    };
    if(m < 10){
        m = "0"+m;
    };

    data = y+"-"+m+"-"+d;
    console.log(data);
    _dat.value = data;
};

setInputDate("#dateDefault");

Creating pdf files at runtime in c#

Have a look at PDFSharp

It is open source and it is written in .NET, I use it myself for some PDF invoice generation.

Host 'xxx.xx.xxx.xxx' is not allowed to connect to this MySQL server

if you are trying to execute mysql query withouth defining connectionstring, you will get this error.

Probably you forgat to define connection string before execution. have you check this out? (sorry for bad english)

Table fixed header and scrollable body

Used this link, stackoverflow.com/a/17380697/1725764, by Hashem Qolami at the original posts' comments and used display:inline-blocks instead of floats. Fixes borders if the table has the class 'table-bordered' also.

table.scroll {
  width: 100%;  
  &.table-bordered {
    td, th {
      border-top: 0;
      border-right: 0;
    }    
    th {
      border-bottom-width: 1px;
    }
    td:first-child,
    th:first-child {
      border-right: 0;
      border-left: 0;
    }
  }
  tbody {
    height: 200px;
    overflow-y: auto;
    overflow-x: hidden;  
  }
  tbody, thead {
    display: block;
  }
  tr {
    width: 100%;
    display: block;
  }
  th, td {
    display: inline-block;

  }
  td {
    height: 46px; //depends on your site
  }
}

Then just add the widths of the td and th

table.table-prep {
  tr > td.type,
  tr > th.type{
    width: 10%;
  }
  tr > td.name,
  tr > th.name,
  tr > td.notes,
  tr > th.notes,
  tr > td.quantity,
  tr > th.quantity{
    width: 30%;
  }
}

SELECT INTO Variable in MySQL DECLARE causes syntax error?

You can also use SET instead of DECLARE

SET @myvar := (SELECT somevalue INTO myvar FROM mytable WHERE uid=1);

SELECT myvar;

How to increment variable under DOS?

Indeed, set in DOS has no option to allow for arithmetic. You could do a giant lookup table, though:

if %COUNTER%==249 set COUNTER=250
...
if %COUNTER%==3 set COUNTER=4
if %COUNTER%==2 set COUNTER=3
if %COUNTER%==1 set COUNTER=2
if %COUNTER%==0 set COUNTER=1

Check if a given time lies between two times regardless of date

As with the help of @kocko, the complete working code is as below:

try{
Date time11 = new SimpleDateFormat("HH:mm:ss").parse("20:11:13");
Calendar calendar1 = Calendar.getInstance();
calendar1.setTime(time11);

Date time22 = new SimpleDateFormat("HH:mm:ss").parse("14:49:00");
Calendar calendar2 = Calendar.getInstance();
calendar2.setTime(time22);

Date currentTime = new SimpleDateFormat("HH:mm:ss").parse("00:00:00");
Calendar startingCalendar = Calendar.getInstance();
startingCalendar.setTime(currentTime);
startingCalendar.add(Calendar.DATE, 1);



//let's say we have to check about 01:00:00
String someRandomTime = time1;
Date d = new SimpleDateFormat("HH:mm:ss").parse(someRandomTime);
Calendar calendar3 = Calendar.getInstance();
calendar3.setTime(d);

if(startingCalendar.getTime().after(calendar1.getTime()))
{
calendar2.add(Calendar.DATE, 1);

    calendar3.add(Calendar.DATE, 1);
}

Date x = calendar3.getTime();

if (x.after(calendar1.getTime()) && x.before(calendar2.getTime())) 
{
System.out.println("Time is in between..");
}
else
{
System.out.println("Time is not in between..");
}

} catch (ParseException e) 
{
e.printStackTrace();
}

How to call any method asynchronously in c#

Starting with .Net 4.5 you can use Task.Run to simply start an action:

void Foo(string args){}
...
Task.Run(() => Foo("bar"));

Task.Run vs Task.Factory.StartNew

php, mysql - Too many connections to database error

There are a bunch of different reasons for the "Too Many Connections" error.

Check out this FAQ page on MySQL.com: http://dev.mysql.com/doc/refman/5.5/en/too-many-connections.html

Check your my.cnf file for "max_connections". If none exist try:

[mysqld]
set-variable=max_connections=250

However the default is 151, so you should be okay.

If you are on a shared host, it might be that other users are taking up too many connections.

Other problems to look out for is the use of persistent connections and running out of diskspace.

Get only records created today in laravel

for Laravel 5.6+ users, you can just do

    $posts = Post::whereDate('created_at', Carbon::today())->get();

Happy coding

How to set base url for rest in spring boot?

I might be a bit late, BUT... I believe it is the best solution. Set it up in your application.yml (or analogical config file):

spring:
    data:
        rest:
            basePath: /api

As I can remember that's it - all of your repositories will be exposed beneath this URI.

Restoring MySQL database from physical files

I ran into this trying to revive an accidentally deleted Docker Container (oraclelinux's MySQL) from a luckily-not-removed docker volume that had the DB data in physical files.

So, all I wanted to do was to turn the data from physical files into a .sql importable file to recreate the container with the DB and the data.

I tried biolin's solution, but ran into some [InnoDB] Multiple files found for the same tablespace ID errors, after restart. I realized that doing open hurt surgery on certain folders/files there is quite trickey.

The solution that worked for me was temporarily changing the datadir= in my.cnf to the available folder and restarting the MySQL server. It did the job perfectly!

summing two columns in a pandas dataframe

I think you've misunderstood some python syntax, the following does two assignments:

In [11]: a = b = 1

In [12]: a
Out[12]: 1

In [13]: b
Out[13]: 1

So in your code it was as if you were doing:

sum = df['budget'] + df['actual']  # a Series
# and
df['variance'] = df['budget'] + df['actual']  # assigned to a column

The latter creates a new column for df:

In [21]: df
Out[21]:
  cluster                 date  budget  actual
0       a  2014-01-01 00:00:00   11000   10000
1       a  2014-02-01 00:00:00    1200    1000
2       a  2014-03-01 00:00:00     200     100
3       b  2014-04-01 00:00:00     200     300
4       b  2014-05-01 00:00:00     400     450
5       c  2014-06-01 00:00:00     700    1000
6       c  2014-07-01 00:00:00    1200    1000
7       c  2014-08-01 00:00:00     200     100
8       c  2014-09-01 00:00:00     200     300

In [22]: df['variance'] = df['budget'] + df['actual']

In [23]: df
Out[23]:
  cluster                 date  budget  actual  variance
0       a  2014-01-01 00:00:00   11000   10000     21000
1       a  2014-02-01 00:00:00    1200    1000      2200
2       a  2014-03-01 00:00:00     200     100       300
3       b  2014-04-01 00:00:00     200     300       500
4       b  2014-05-01 00:00:00     400     450       850
5       c  2014-06-01 00:00:00     700    1000      1700
6       c  2014-07-01 00:00:00    1200    1000      2200
7       c  2014-08-01 00:00:00     200     100       300
8       c  2014-09-01 00:00:00     200     300       500

As an aside, you shouldn't use sum as a variable name as the overrides the built-in sum function.

What does Maven do, in theory and in practice? When is it worth to use it?

What it does

Maven is a "build management tool", it is for defining how your .java files get compiled to .class, packaged into .jar (or .war or .ear) files, (pre/post)processed with tools, managing your CLASSPATH, and all others sorts of tasks that are required to build your project. It is similar to Apache Ant or Gradle or Makefiles in C/C++, but it attempts to be completely self-contained in it that you shouldn't need any additional tools or scripts by incorporating other common tasks like downloading & installing necessary libraries etc.

It is also designed around the "build portability" theme, so that you don't get issues as having the same code with the same buildscript working on one computer but not on another one (this is a known issue, we have VMs of Windows 98 machines since we couldn't get some of our Delphi applications compiling anywhere else). Because of this, it is also the best way to work on a project between people who use different IDEs since IDE-generated Ant scripts are hard to import into other IDEs, but all IDEs nowadays understand and support Maven (IntelliJ, Eclipse, and NetBeans). Even if you don't end up liking Maven, it ends up being the point of reference for all other modern builds tools.

Why you should use it

There are three things about Maven that are very nice.

  1. Maven will (after you declare which ones you are using) download all the libraries that you use and the libraries that they use for you automatically. This is very nice, and makes dealing with lots of libraries ridiculously easy. This lets you avoid "dependency hell". It is similar to Apache Ant's Ivy.

  2. It uses "Convention over Configuration" so that by default you don't need to define the tasks you want to do. You don't need to write a "compile", "test", "package", or "clean" step like you would have to do in Ant or a Makefile. Just put the files in the places in which Maven expects them and it should work off of the bat.

  3. Maven also has lots of nice plug-ins that you can install that will handle many routine tasks from generating Java classes from an XSD schema using JAXB to measuring test coverage with Cobertura. Just add them to your pom.xml and they will integrate with everything else you want to do.

The initial learning curve is steep, but (nearly) every professional Java developer uses Maven or wishes they did. You should use Maven on every project although don't be surprised if it takes you a while to get used to it and that sometimes you wish you could just do things manually, since learning something new sometimes hurts. However, once you truly get used to Maven you will find that build management takes almost no time at all.

How to Start

The best place to start is "Maven in 5 Minutes". It will get you start with a project ready for you to code in with all the necessary files and folders set-up (yes, I recommend using the quickstart archetype, at least at first).

After you get started you'll want a better understanding over how the tool is intended to be used. For that "Better Builds with Maven" is the most thorough place to understand the guts of how it works, however, "Maven: The Complete Reference" is more up-to-date. Read the first one for understanding, but then use the second one for reference.

How do I close an open port from the terminal on the Mac?

  1. Find out the process ID (PID) which is occupying the port number (e.g., 5955) you would like to free

    sudo lsof -i :5955
    
  2. Kill the process which is currently using the port using its PID

    sudo kill -9 PID
    

What's the best way to build a string of delimited items in Java?

And a minimal one (if you don't want to include Apache Commons or Gauva into project dependencies just for the sake of joining strings)

/**
 *
 * @param delim : String that should be kept in between the parts
 * @param parts : parts that needs to be joined
 * @return  a String that's formed by joining the parts
 */
private static final String join(String delim, String... parts) {
    StringBuilder builder = new StringBuilder();
    for (int i = 0; i < parts.length - 1; i++) {
        builder.append(parts[i]).append(delim);
    }
    if(parts.length > 0){
        builder.append(parts[parts.length - 1]);
    }
    return builder.toString();
}

How to set the allowed url length for a nginx request (error code: 414, uri too large)

From: http://nginx.org/r/large_client_header_buffers

Syntax: large_client_header_buffers number size ;
Default: large_client_header_buffers 4 8k;
Context: http, server

Sets the maximum number and size of buffers used for reading large client request header. A request line cannot exceed the size of one buffer, or the 414 (Request-URI Too Large) error is returned to the client. A request header field cannot exceed the size of one buffer as well, or the 400 (Bad Request) error is returned to the client. Buffers are allocated only on demand. By default, the buffer size is equal to 8K bytes. If after the end of request processing a connection is transitioned into the keep-alive state, these buffers are released.

so you need to change the size parameter at the end of that line to something bigger for your needs.

log4j logging hierarchy order

Use the force, read the source (excerpt from the Priority and Level class compiled, TRACE level was introduced in version 1.2.12):

public final static int OFF_INT = Integer.MAX_VALUE;
public final static int FATAL_INT = 50000;
public final static int ERROR_INT = 40000;
public final static int WARN_INT  = 30000;
public final static int INFO_INT  = 20000;
public final static int DEBUG_INT = 10000;
public static final int TRACE_INT = 5000; 
public final static int ALL_INT = Integer.MIN_VALUE; 

or the log4j API for the Level class, which makes it quite clear.

When the library decides whether to print a certain statement or not, it computes the effective level of the responsible Logger object (based on configuration) and compares it with the LogEvent's level (depends on which method was used in the code – trace/debug/.../fatal). If LogEvent's level is greater or equal to the Logger's level, the LogEvent is sent to appender(s) – "printed". At the core, it all boils down to an integer comparison and this is where these constants come to action.

System.Runtime.InteropServices.COMException (0x800A03EC)

In my case, the problem was styling header as "Header 1" but that style was not exist in the Word that I get the error because it was not an Office in English Language.

data type not understood

Try:

mmatrix = np.zeros((nrows, ncols))

Since the shape parameter has to be an int or sequence of ints

http://docs.scipy.org/doc/numpy/reference/generated/numpy.zeros.html

Otherwise you are passing ncols to np.zeros as the dtype.

How to create a hash or dictionary object in JavaScript

if( a['desiredKey'] !== undefined )
{
   // it exists
}

Tree data structure in C#

Here's mine, which is very similar to Aaron Gage's, just a little more conventional, in my opinion. For my purposes, I haven't ran into any performance issues with List<T>. It would be easy enough to switch to a LinkedList if needed.


namespace Overby.Collections
{
    public class TreeNode<T>
    {
        private readonly T _value;
        private readonly List<TreeNode<T>> _children = new List<TreeNode<T>>();

        public TreeNode(T value)
        {
            _value = value;
        }

        public TreeNode<T> this[int i]
        {
            get { return _children[i]; }
        }

        public TreeNode<T> Parent { get; private set; }

        public T Value { get { return _value; } }

        public ReadOnlyCollection<TreeNode<T>> Children
        {
            get { return _children.AsReadOnly(); }
        }

        public TreeNode<T> AddChild(T value)
        {
            var node = new TreeNode<T>(value) {Parent = this};
            _children.Add(node);
            return node;
        }

        public TreeNode<T>[] AddChildren(params T[] values)
        {
            return values.Select(AddChild).ToArray();
        }

        public bool RemoveChild(TreeNode<T> node)
        {
            return _children.Remove(node);
        }

        public void Traverse(Action<T> action)
        {
            action(Value);
            foreach (var child in _children)
                child.Traverse(action);
        }

        public IEnumerable<T> Flatten()
        {
            return new[] {Value}.Concat(_children.SelectMany(x => x.Flatten()));
        }
    }
}

Hiding a button in Javascript

when you press the button so it should call function that will alert message. so after alert put style visible property . you can achieve it using

_x000D_
_x000D_
function OpenAlert(){_x000D_
        alert("Getting the message");_x000D_
        document.getElementById("getMessage").style.visibility="hidden";_x000D_
        _x000D_
    }
_x000D_
 <input type="button" id="getMessage" name="GetMessage" value="GetMessage" onclick="OpenAlert()"/>
_x000D_
_x000D_
_x000D_

Hope this will help . Happy to help

Abstract methods in Java

The error message tells the exact reason: "abstract methods cannot have a body".

They can only be defined in abstract classes and interfaces (interface methods are implicitly abstract!) and the idea is, that the subclass implements the method.

Example:

 public abstract class AbstractGreeter {
   public abstract String getHelloMessage();

   public void sayHello() {
     System.out.println(getHelloMessage());
   }
 }

 public class FrenchGreeter extends AbstractGreeter{

   // we must implement the abstract method
   @Override
   public String getHelloMessage() {
     return "bonjour";
   }
 }

Laravel 5 Clear Views Cache

To get all the artisan command, type...

php artisan

If you want to clear view cache, just use:

php artisan view:clear

If you don't know how to use specific artisan command, just add "help" (see below)

php artisan help view:clear

Is the MIME type 'image/jpg' the same as 'image/jpeg'?

tl;dr the "standards" are a hodge-podge mess; it depends who you ask!

Overall, there appears to be no MIME type image/jpg. Yet, in practice, nearly all software handles image files named "*.jpg" just fine.
This particular topic is confusing because the varying association of file name extension associated to a MIME type depends which organization created the table of file name extensions to MIME types. In other words, file name extension .jpg could be many different things.

For example, here are three "complete lists" and one RFC that with varying JPEG Image format file name extensions and the associated MIME types.

These "complete lists" and RFC do not have MIME type image/jpg! But for MIME type image/jpeg some lists do have varying file name extensions (.jpeg, .jpg, …). Other lists do not mention image/jpeg.

Also, there are different types of JPEG Image formats (e.g. Progressive JPEG Image format, JPEG 2000, etcetera) and "JPEG Extensions" that may or may not overlap in file name extension and declared MIME type.

Another confusing thing is RFC 3745 does not appear to match IANA Media Types yet the same RFC is supposed to inform the IANA Media Types document. For example, in RFC 3745 .jpf is preferred file extension for image/jpx but in IANA Media Types the name jpf is not present (and that IANA document references RFC 3745!).

Another confusing thing is IANA Media Types lists "names" but does not list "file name extensions". This is on purpose, but confuses the endeavor of mapping file name extensions to MIME types.

Another confusing thing: is it "mime", or "MIME", or "MIME type", or "mime type", or "mime/type", or "media type"?


The most official seeming document by IANA is surprisingly inadequate. No MIME type is registered for file extension .jpg yet there exists the odd vnd.sealedmedia.softseal.jpg. File extension.JPEG is only known as a video type while file extension .jpeg is an image type (when did lowercase and uppercase letters start mattering!?). At the same time, jpeg2000 is type video yet RFC 3745 considers JPEG 2000 an image type! The IANA list seems to cater to company-specific jpeg formats (e.g. vnd.sealedmedia.softseal.jpg).


In summary...

Because of the prior confusions, it is difficult to find an industry-accepted canonical document that maps file name extensions to MIME types, particularly for the JPEG Image File Format.



Related question "List of ALL MimeTypes on the Planet, mapped to File Extensions?".

Unix shell script find out which directory the script file resides?

The best answer for this question was answered here:
Getting the source directory of a Bash script from within

And it is:

DIR="$( cd "$( dirname "${BASH_SOURCE[0]}" )" && pwd )"

One-liner which will give you the full directory name of the script no matter where it is being called from.

To understand how it works you can execute the following script:

#!/bin/bash

SOURCE="${BASH_SOURCE[0]}"
while [ -h "$SOURCE" ]; do # resolve $SOURCE until the file is no longer a symlink
  TARGET="$(readlink "$SOURCE")"
  if [[ $TARGET == /* ]]; then
    echo "SOURCE '$SOURCE' is an absolute symlink to '$TARGET'"
    SOURCE="$TARGET"
  else
    DIR="$( dirname "$SOURCE" )"
    echo "SOURCE '$SOURCE' is a relative symlink to '$TARGET' (relative to '$DIR')"
    SOURCE="$DIR/$TARGET" # if $SOURCE was a relative symlink, we need to resolve it relative to the path where the symlink file was located
  fi
done
echo "SOURCE is '$SOURCE'"
RDIR="$( dirname "$SOURCE" )"
DIR="$( cd -P "$( dirname "$SOURCE" )" && pwd )"
if [ "$DIR" != "$RDIR" ]; then
  echo "DIR '$RDIR' resolves to '$DIR'"
fi
echo "DIR is '$DIR'"

CS0120: An object reference is required for the nonstatic field, method, or property 'foo'

You start a thread which runs the static method SumData. However, SumData calls SetTextboxText which isn't static. Thus you need an instance of your form to call SetTextboxText.

How to create an installer for a .net Windows Service using Visual Studio

Nor Kelsey, nor Brendan solutions does not works for me in Visual Studio 2015 Community.

Here is my brief steps how to create service with installer:

  1. Run Visual Studio, Go to File->New->Project
  2. Select .NET Framework 4, in 'Search Installed Templates' type 'Service'
  3. Select 'Windows Service'. Type Name and Location. Press OK.
  4. Double click Service1.cs, right click in designer and select 'Add Installer'
  5. Double click ProjectInstaller.cs. For serviceProcessInstaller1 open Properties tab and change 'Account' property value to 'LocalService'. For serviceInstaller1 change 'ServiceName' and set 'StartType' to 'Automatic'.
  6. Double click serviceInstaller1. Visual Studio creates serviceInstaller1_AfterInstall event. Write code:

    private void serviceInstaller1_AfterInstall(object sender, InstallEventArgs e)
    {
        using (System.ServiceProcess.ServiceController sc = new 
        System.ServiceProcess.ServiceController(serviceInstaller1.ServiceName))
        {
            sc.Start();
        }
    }
    
  7. Build solution. Right click on project and select 'Open Folder in File Explorer'. Go to bin\Debug.

  8. Create install.bat with below script:

    :::::::::::::::::::::::::::::::::::::::::
    :: Automatically check & get admin rights
    :::::::::::::::::::::::::::::::::::::::::
    @echo off
    CLS 
    ECHO.
    ECHO =============================
    ECHO Running Admin shell
    ECHO =============================
    
    :checkPrivileges 
    NET FILE 1>NUL 2>NUL
    if '%errorlevel%' == '0' ( goto gotPrivileges ) else ( goto getPrivileges ) 
    
    :getPrivileges 
    if '%1'=='ELEV' (shift & goto gotPrivileges)  
    ECHO. 
    ECHO **************************************
    ECHO Invoking UAC for Privilege Escalation 
    ECHO **************************************
    
    setlocal DisableDelayedExpansion
    set "batchPath=%~0"
    setlocal EnableDelayedExpansion
    ECHO Set UAC = CreateObject^("Shell.Application"^) > "%temp%\OEgetPrivileges.vbs" 
    ECHO UAC.ShellExecute "!batchPath!", "ELEV", "", "runas", 1 >> "%temp%\OEgetPrivileges.vbs" 
    "%temp%\OEgetPrivileges.vbs" 
    exit /B 
    
    :gotPrivileges 
    ::::::::::::::::::::::::::::
    :START
    ::::::::::::::::::::::::::::
    setlocal & pushd .
    
    cd /d %~dp0
    %windir%\Microsoft.NET\Framework\v4.0.30319\InstallUtil /i "WindowsService1.exe"
    pause
    
  9. Create uninstall.bat file (change in pen-ult line /i to /u)
  10. To install and start service run install.bat, to stop and uninstall run uninstall.bat

Vue.js getting an element within a component

The answers are not making it clear:

Use this.$refs.someName, but, in order to use it, you must add ref="someName" in the parent.

See demo below.

_x000D_
_x000D_
new Vue({_x000D_
  el: '#app',_x000D_
  mounted: function() {_x000D_
    var childSpanClassAttr = this.$refs.someName.getAttribute('class');_x000D_
    _x000D_
    console.log('<span> was declared with "class" attr -->', childSpanClassAttr);_x000D_
  }_x000D_
})
_x000D_
<script src="https://unpkg.com/[email protected]/dist/vue.min.js"></script>_x000D_
_x000D_
<div id="app">_x000D_
  Parent._x000D_
  <span ref="someName" class="abc jkl xyz">Child Span</span>_x000D_
</div>
_x000D_
_x000D_
_x000D_

$refs and v-for

Notice that when used in conjunction with v-for, the this.$refs.someName will be an array:

_x000D_
_x000D_
new Vue({_x000D_
  el: '#app',_x000D_
  data: {_x000D_
    ages: [11, 22, 33]_x000D_
  },_x000D_
  mounted: function() {_x000D_
    console.log("<span> one's text....:", this.$refs.mySpan[0].innerText);_x000D_
    console.log("<span> two's text....:", this.$refs.mySpan[1].innerText);_x000D_
    console.log("<span> three's text..:", this.$refs.mySpan[2].innerText);_x000D_
  }_x000D_
})
_x000D_
span { display: inline-block; border: 1px solid red; }
_x000D_
<script src="https://unpkg.com/[email protected]/dist/vue.min.js"></script>_x000D_
_x000D_
<div id="app">_x000D_
  Parent._x000D_
  <div v-for="age in ages">_x000D_
    <span ref="mySpan">Age is {{ age }}</span>_x000D_
  </div>_x000D_
</div>
_x000D_
_x000D_
_x000D_

The type List is not generic; it cannot be parameterized with arguments [HTTPClient]

Adding java.util.list will resolve your problem because List interface which you are trying to use is part of java.util.list package.

Difference between <span> and <div> with text-align:center;?

Spans are inline, divs are block elements. i.e. spans are only as wide as their respective content. You can align the span inside the surrounding container (if it's a block container), but you can't align the content.

Span is primarily used for formatting purposes. If you want to arrange or position the contents, use div, p or some other block element.

Access denied for user 'root'@'localhost' (using password: YES) (Mysql::Error)

I was running UTs and I started receiving error messages. I am not sure what was the problem. But when I changed my encoding style in INTELLIJ to UTF8 it started working again.

access denied for user 'root'@'localhost' (using password yes) hibernate

this is my URL db.url=jdbc:mysql://localhost:3306/somedb?useUnicode=true&connectionCollation=utf8_general_ci&characterSetResults=utf8&characterEncoding=utf8

Can anyone explain me StandardScaler?

Following is a simple working example to explain how standarization calculation works. The theory part is already well explained in other answers.

>>>import numpy as np
>>>data = [[6, 2], [4, 2], [6, 4], [8, 2]]
>>>a = np.array(data)

>>>np.std(a, axis=0)
array([1.41421356, 0.8660254 ])

>>>np.mean(a, axis=0)
array([6. , 2.5])

>>>from sklearn.preprocessing import StandardScaler
>>>scaler = StandardScaler()
>>>scaler.fit(data)
>>>print(scaler.mean_)

#Xchanged = (X-µ)/s  WHERE s is Standard Deviation and µ is mean
>>>z=scaler.transform(data)
>>>z

Calculation

As you can see in the output, mean is [6. , 2.5] and std deviation is [1.41421356, 0.8660254 ]

Data is (0,1) position is 2 Standardization = (2 - 2.5)/0.8660254 = -0.57735027

Data in (1,0) position is 4 Standardization = (4-6)/1.41421356 = -1.414

Result After Standardization

enter image description here

Check Mean and Std Deviation After Standardization

enter image description here

Note: -2.77555756e-17 is very close to 0.

References

  1. Compare the effect of different scalers on data with outliers

  2. What's the difference between Normalization and Standardization?

  3. Mean of data scaled with sklearn StandardScaler is not zero

Interface or an Abstract Class: which one to use?

Also, just would like to add here that just because any other OO language has some kind of interfaces and abstraction too doesn't mean they have the same meaning and purpose as in PHP. The use of abstraction/interfaces is slightly different while interfaces in PHP actually don't have a real function. They merely are used for semantic and scheme-related reasons. The point is to have a project as much flexible as possible, expandable and safe for future extensions regardless whether the developer later on has a totally different plan of use or not.

If your English is not native you might lookup what Abstraction and Interfaces actually are. And look for synonyms too.

And this might help you as a metaphor:

INTERFACE

Let's say, you bake a new sort of cake with strawberries and you made up a recipe describing the ingredients and steps. Only you know why it's tasting so well and your guests like it. Then you decide to publish your recipe so other people can try that cake as well.

The point here is

- to make it right
- to be careful
- to prevent things which could go bad (like too much strawberries or something)
- to keep it easy for the people who try it out
- to tell you how long is what to do (like stiring)
- to tell which things you CAN do but don't HAVE to

Exactly THIS is what describes interfaces. It is a guide, a set of instructions which observe the content of the recipe. Same as if you would create a project in PHP and you want to provide the code on GitHub or with your mates or whatever. An interface is what people can do and what you should not. Rules that hold it - if you disobey one, the entire construct will be broken.


ABSTRACTION

To continue with this metaphor here... imagine, you are the guest this time eating that cake. Then you are trying that cake using the recipe now. But you want to add new ingredients or change/skip the steps described in the recipe. So what comes next? Plan a different version of that cake. This time with black berries and not straw berries and more vanilla cream...yummy.

This is what you could consider an extension of the original cake. You basically do an abstraction of it by creating a new recipe because it's a lil different. It has a few new steps and other ingredients. However, the black berry version has some parts you took over from the original - these are the base steps that every kind of that cake must have. Like ingredients just as milk - That is what every derived class has.

Now you want to exchange ingredients and steps and these MUST be defined in the new version of that cake. These are abstract methods which have to be defined for the new cake, because there should be a fruit in the cake but which? So you take the black berries this time. Done.

There you go, you have extended the cake, followed the interface and abstracted steps and ingredients from it.

Adding Multiple Values in ArrayList at a single index

Use two dimensional array instead. For instance, int values[][] = new int[2][5]; Arrays are faster, when you are not manipulating much.

How to parseInt in Angular.js

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

app.controller('MainCtrl', ['$scope', function($scope){
   $scope.num1 = 1;
   $scope.num2 = 1;
   $scope.total = parseInt($scope.num1 + $scope.num2);

}]);

Demo: parseInt with AngularJS

Read file line by line in PowerShell

I was able to read a 4GB log file in about 50 seconds with the following. You may be able to make it faster by loading it as a C# assembly dynamically using PowerShell.

[System.IO.StreamReader]$sr = [System.IO.File]::Open($file, [System.IO.FileMode]::Open)
while (-not $sr.EndOfStream){
    $line = $sr.ReadLine()
}
$sr.Close() 

How to pass a parameter to Vue @click event handler

I had the same issue and here is how I manage to pass through:

In your case you have addToCount() which is called. now to pass down a param when user clicks, you can say @click="addToCount(item.contactID)"

in your function implementation you can receive the params like:

addToCount(paramContactID){
 // the paramContactID contains the value you passed into the function when you called it
 // you can do what you want to do with the paramContactID in here!

}

How to set background color of HTML element using css properties in JavaScript

$("body").css("background","green"); //jQuery

document.body.style.backgroundColor = "green"; //javascript

so many ways are there I think it is very easy and simple

Demo On Plunker

Does a VPN Hide my Location on Android?

Your question can be conveniently divided into several parts:

Does a VPN hide location? Yes, he is capable of this. This is not about GPS determining your location. If you try to change the region via VPN in an application that requires GPS access, nothing will work. However, sites define your region differently. They get an IP address and see what country or region it belongs to. If you can change your IP address, you can change your region. This is exactly what VPNs can do.

How to hide location on Android? There is nothing difficult in figuring out how to set up a VPN on Android, but a couple of nuances still need to be highlighted. Let's start with the fact that not all Android VPNs are created equal. For example, VeePN outperforms many other services in terms of efficiency in circumventing restrictions. It has 2500+ VPN servers and a powerful IP and DNS leak protection system.

You can easily change the location of your Android device by using a VPN. Follow these steps for any device model (Samsung, Sony, Huawei, etc.):

  1. Download and install a trusted VPN.

  2. Install the VPN on your Android device.

  3. Open the application and connect to a server in a different country.

  4. Your Android location will now be successfully changed!

Is it legal? Yes, changing your location on Android is legal. Likewise, you can change VPN settings in Microsoft Edge on your PC, and all this is within the law. VPN allows you to change your IP address, safeguarding your privacy and protecting your actual location from being exposed. However, VPN laws may vary from country to country. There are restrictions in some regions.

Brief summary: Yes, you can change your region on Android and a VPN is a necessary assistant for this. It's simple, safe and legal. Today, VPN is the best way to change the region and unblock sites with regional restrictions.

getaddrinfo: nodename nor servname provided, or not known

I was seeing this error unrelated to rails. It turned out my test was trying to use a port that was too high (greater than 65535).

This code will produce the error in question

require 'socket'
Socket.getaddrinfo("127.0.0.1", "65536")

How do I "Add Existing Item" an entire directory structure in Visual Studio?

Drag the files / folders from Windows Explorer into the Solution Explorer. It will add them all. Note this doesn't work if Visual Studio is in Administrator Mode, because Windows Explorer is a User Mode process.

Can you hide the controls of a YouTube embed without enabling autoplay?

Autoplay works only with /v/ instead of /embed/, so change the src to:

src="//www.youtube.com/v/qUJYqhKZrwA?autoplay=1&showinfo=0&controls=0"

How to declare a local variable in Razor?

Not a direct answer to OP's problem, but it may help you too. You can declare a local variable next to some html inside a scope without trouble.

@foreach (var item in Model.Stuff)
{
    var file = item.MoreStuff.FirstOrDefault();

    <li><a href="@item.Source">@file.Name</a></li>
}

How to embed a SWF file in an HTML page?

I know this is an old question. But this answer will be good for the present.

<!DOCTYPE html>
<html>
    <head>
        <meta charset="UTF-8">
        <title>histo2</title>
        <style type="text/css" media="screen">
        html, body { height:100%; background-color: #ffff99;}
        body { margin:0; padding:0; overflow:hidden; }
        #flashContent { width:100%; height:100%; }
        </style>
    </head>
    <body>
        <div id="flashContent">
            <object type="application/x-shockwave-flash" data="histo2.swf" width="822" height="550" id="histo2" style="float: none; vertical-align:middle">
                <param name="movie" value="histo2.swf" />
                <param name="quality" value="high" />
                <param name="bgcolor" value="#ffff99" />
                <param name="play" value="true" />
                <param name="loop" value="true" />
                <param name="wmode" value="window" />
                <param name="scale" value="showall" />
                <param name="menu" value="true" />
                <param name="devicefont" value="false" />
                <param name="salign" value="" />
                <param name="allowScriptAccess" value="sameDomain" />
                <a href="http://www.adobe.com/go/getflash">
                    <img src="http://www.adobe.com/images/shared/download_buttons/get_flash_player.gif" alt="Get Adobe Flash player" />
                </a>
            </object>
        </div>
    </body>
</html>

C# - Making a Process.Start wait until the process has start-up

Like others have already said, it's not immediately obvious what you're asking. I'm going to assume that you want to start a process and then perform another action when the process "is ready".

Of course, the "is ready" is the tricky bit. Depending on what you're needs are, you may find that simply waiting is sufficient. However, if you need a more robust solution, you can consider using a named Mutex to control the control flow between your two processes.

For example, in your main process, you might create a named mutex and start a thread or task which will wait. Then, you can start the 2nd process. When that process decides that "it is ready", it can open the named mutex (you have to use the same name, of course) and signal to the first process.

Convert string date to timestamp in Python

I use ciso8601, which is 62x faster than datetime's strptime.

t = "01/12/2011"
ts = ciso8601.parse_datetime(t)
# to get time in seconds:
time.mktime(ts.timetuple())

You can learn more here.

What is the effect of encoding an image in base64?

It will be bigger in base64.

Base64 uses 6 bits per byte to encode data, whereas binary uses 8 bits per byte. Also, there is a little padding overhead with Base64. Not all bits are used with Base64 because it was developed in the first place to encode binary data on systems that can only correctly process non-binary data.

That means that the encoded image will be around 33%-36% larger (33% from not using 2 of the bits per byte, plus possible padding accounting for the remaining 3%).

Where can I view Tomcat log files in Eclipse?

Another forum provided this answer:

Ahh, figured this out. The following system properties need to be set, so that the "logging.properties" file can be picked up.

Assuming that the tomcat is located under an Eclipse project, add the following under the "Arguments" tab of its launch configuration:

-Dcatalina.base="${project_loc}\<apache-tomcat-5.5.23_loc>" 
-Dcatalina.home="${project_loc}\<apache-tomcat-5.5.23_loc>" 
-Djava.util.logging.config.file="${project_loc}\<apache-tomcat-5.5.23_loc>\conf\logging.properties" 
-Djava.util.logging.manager=org.apache.juli.ClassLoaderLogManager 

http://www.coderanch.com/t/442412/Tomcat/Tweaking-tomcat-logging-properties-file

Email address validation in C# MVC 4 application: with or without using Regex

Why not just use the EmailAttribute?

[Email(ErrorMessage = "Bad email")]
public string Email { get; set; }

Access Session attribute on jstl

You should definitely avoid using <jsp:...> tags. They're relics from the past and should always be avoided now.

Use the JSTL.

Now, wether you use the JSTL or any other tag library, accessing to a bean property needs your bean to have this property. A property is not a private instance variable. It's an information accessible via a public getter (and setter, if the property is writable). To access the questionPaperID property, you thus need to have a

public SomeType getQuestionPaperID() {
    //...
}

method in your bean.

Once you have that, you can display the value of this property using this code :

<c:out value="${Questions.questionPaperID}" />

or, to specifically target the session scoped attributes (in case of conflicts between scopes) :

<c:out value="${sessionScope.Questions.questionPaperID}" />

Finally, I encourage you to name scope attributes as Java variables : starting with a lowercase letter.

How to access a preexisting collection with Mongoose?

Are you sure you've connected to the db? (I ask because I don't see a port specified)

try:

mongoose.connection.on("open", function(){
  console.log("mongodb is connected!!");
});

Also, you can do a "show collections" in mongo shell to see the collections within your db - maybe try adding a record via mongoose and see where it ends up?

From the look of your connection string, you should see the record in the "test" db.

Hope it helps!

Resizing Images in VB.NET

Don't know much VB.NET syntax but here's and idea

Dim source As New Bitmap("C:\image.png") 
Dim target As New Bitmap(size.Width, size.Height, PixelFormat.Format24bppRgb)

Using graphics As Graphics = Graphics.FromImage(target)
    graphics.DrawImage(source, new Size(48, 48)) 
End Using

Chrome doesn't delete session cookies

This maybe because Chrome is still running in background after you close the browser. Try to disable this feature by doing following:

  1. Open chrome://settings/
  2. Click "Show advanced settings ..."
  3. Navigate down to System section and disable "Continue running background apps when Google Chrome is closed". This will force Chrome to close completely and then it will delete session cookies.

However, I think Chrome should check and delete previous session cookies at it starting instead of closing.

ESLint - "window" is not defined. How to allow global variables in package.json

There is a builtin environment: browser that includes window.

Example .eslintrc.json:

"env": {
    "browser": true,
    "node": true,
    "jasmine": true
  },

More information: http://eslint.org/docs/user-guide/configuring.html#specifying-environments

Also see the package.json answer by chevin99 below.

Java using enum with switch statement

This should work in the way that you describe. What error are you getting? If you could pastebin your code that would help.

http://download.oracle.com/javase/tutorial/java/javaOO/enum.html

EDIT: Are you sure you want to define a static enum? That doesn't sound right to me. An enum is much like any other object. If your code compiles and runs but gives incorrect results, this would probably be why.

How to watch for array changes?

I fiddled around and came up with this. The idea is that the object has all the Array.prototype methods defined, but executes them on a separate array object. This gives the ability to observe methods like shift(), pop() etc. Although some methods like concat() won't return the OArray object. Overloading those methods won't make the object observable if accessors are used. To achieve the latter, the accessors are defined for each index within given capacity.

Performance wise... OArray is around 10-25 times slower compared to the plain Array object. For the capasity in a range 1 - 100 the difference is 1x-3x.

class OArray {
    constructor(capacity, observer) {

        var Obj = {};
        var Ref = []; // reference object to hold values and apply array methods

        if (!observer) observer = function noop() {};

        var propertyDescriptors = Object.getOwnPropertyDescriptors(Array.prototype);

        Object.keys(propertyDescriptors).forEach(function(property) {
            // the property will be binded to Obj, but applied on Ref!

            var descriptor = propertyDescriptors[property];
            var attributes = {
                configurable: descriptor.configurable,
                enumerable: descriptor.enumerable,
                writable: descriptor.writable,
                value: function() {
                    observer.call({});
                    return descriptor.value.apply(Ref, arguments);
                }
            };
            // exception to length
            if (property === 'length') {
                delete attributes.value;
                delete attributes.writable;
                attributes.get = function() {
                    return Ref.length
                };
                attributes.set = function(length) {
                    Ref.length = length;
                };
            }

            Object.defineProperty(Obj, property, attributes);
        });

        var indexerProperties = {};
        for (var k = 0; k < capacity; k++) {

            indexerProperties[k] = {
                configurable: true,
                get: (function() {
                    var _i = k;
                    return function() {
                        return Ref[_i];
                    }
                })(),
                set: (function() {
                    var _i = k;
                    return function(value) {
                        Ref[_i] = value;
                        observer.call({});
                        return true;
                    }
                })()
            };
        }
        Object.defineProperties(Obj, indexerProperties);

        return Obj;
    }
}

Entity Framework Provider type could not be loaded?

I see similar problem, and using the method from this post: (http://entityframework.codeplex.com/workitem/1590), which solves my problem.

To work around the issue you can make your test assembly directly reference the provider assembly by adding some line like this anywhere in the test assembly: var _ = System.Data.Entity.SqlServer.SqlProviderServices.Instance;

Get hours difference between two dates in Moment Js

Or you can do simply:

var a = moment('2016-06-06T21:03:55');//now
var b = moment('2016-05-06T20:03:55');

console.log(a.diff(b, 'minutes')) // 44700
console.log(a.diff(b, 'hours')) // 745
console.log(a.diff(b, 'days')) // 31
console.log(a.diff(b, 'weeks')) // 4

docs: here

How do I get the first element from an IEnumerable<T> in .net?

Well, you didn't specify which version of .Net you're using.

Assuming you have 3.5, another way is the ElementAt method:

var e = enumerable.ElementAt(0);

How to fetch data from local JSON file on react native?

maybe you could use AsyncStorage setItem and getItem...and store the data as string, then use the json parser for convert it again to json...

What is the use of a private static variable in Java?

Another perspective :

  1. A class and its instance are two different things at the runtime. A class info is "shared" by all the instances of that class.
  2. The non-static class variables belong to instances and the static variable belongs to class.
  3. Just like an instance variables can be private or public, static variables can also be private or public.

Spring RestTemplate timeout

  1. RestTemplate timeout with SimpleClientHttpRequestFactory To programmatically override the timeout properties, we can customize the SimpleClientHttpRequestFactory class as below.

Override timeout with SimpleClientHttpRequestFactory

//Create resttemplate
RestTemplate restTemplate = new RestTemplate(getClientHttpRequestFactory());

//Override timeouts in request factory
private SimpleClientHttpRequestFactory getClientHttpRequestFactory() 
{
    SimpleClientHttpRequestFactory clientHttpRequestFactory
                      = new SimpleClientHttpRequestFactory();
    //Connect timeout
    clientHttpRequestFactory.setConnectTimeout(10_000);

    //Read timeout
    clientHttpRequestFactory.setReadTimeout(10_000);
    return clientHttpRequestFactory;
}
  1. RestTemplate timeout with HttpComponentsClientHttpRequestFactory SimpleClientHttpRequestFactory helps in setting timeout but it is very limited in functionality and may not prove sufficient in realtime applications. In production code, we may want to use HttpComponentsClientHttpRequestFactory which support HTTP Client library along with resttemplate.

HTTPClient provides other useful features such as connection pool, idle connection management etc.

Read More : Spring RestTemplate + HttpClient configuration example

Override timeout with HttpComponentsClientHttpRequestFactory

//Create resttemplate
RestTemplate restTemplate = new RestTemplate(getClientHttpRequestFactory());

//Override timeouts in request factory
private SimpleClientHttpRequestFactory getClientHttpRequestFactory() 
{
    HttpComponentsClientHttpRequestFactory clientHttpRequestFactory
                      = new HttpComponentsClientHttpRequestFactory();
    //Connect timeout
    clientHttpRequestFactory.setConnectTimeout(10_000);

    //Read timeout
    clientHttpRequestFactory.setReadTimeout(10_000);
    return clientHttpRequestFactory;
}

reference: Spring RestTemplate timeout configuration example

Installing J2EE into existing eclipse IDE

Step 1 Go to Help ---> Install New Software...

Step 2 Try to find "http://download.eclipse.org/webtools/updates" under work with drop down. If you find then select and install all the available updates.

If you can not find then click on Add -> Add Repository. Name: Eclipse Webtools Location: http://download.eclipse.org/webtools/updates Select all available updates and Install them.

Visit http://download.eclipse.org/webtools/updates/ for more details.

TypeError: Can't convert 'int' object to str implicitly

You cannot concatenate a string with an int. You would need to convert your int to a string using the str function, or use formatting to format your output.

Change: -

print("Ok. Your balance is now at " + balanceAfterStrength + " skill points.")

to: -

print("Ok. Your balance is now at {} skill points.".format(balanceAfterStrength))

or: -

print("Ok. Your balance is now at " + str(balanceAfterStrength) + " skill points.")

or as per the comment, use , to pass different strings to your print function, rather than concatenating using +: -

print("Ok. Your balance is now at ", balanceAfterStrength, " skill points.")

How to search a Git repository by commit message?

This:

git log --oneline --grep='Searched phrase'

or this:

git log --oneline --name-status --grep='Searched phrase'

commands work best for me.

mysql error 2005 - Unknown MySQL server host 'localhost'(11001)

I have passed through that error today and did everything described above but didn't work for me. So I decided to view the core problem and logged onto the MySQL root folder in Windows 7 and did this solution:

  1. Go to folder:

    C:\AppServ\MySQL
    
  2. Right click and Run as Administrator these files:

    mysql_servicefix.bat
    
    mysql_serviceinstall.bat
    
    mysql_servicestart.bat
    

Then close the entire explorer window and reopen it or clear cache then login to phpMyAdmin again.

Bash scripting missing ']'

I got this error while trying to use the && operator inside single brackets like [ ... && ... ]. I had to switch to [[ ... && ... ]].

Find the similarity metric between two strings

BLEUscore

BLEU, or the Bilingual Evaluation Understudy, is a score for comparing a candidate translation of text to one or more reference translations.

A perfect match results in a score of 1.0, whereas a perfect mismatch results in a score of 0.0.

Although developed for translation, it can be used to evaluate text generated for a suite of natural language processing tasks.

Code:

import nltk
from nltk.translate import bleu
from nltk.translate.bleu_score import SmoothingFunction
smoothie = SmoothingFunction().method4

C1='Text'
C2='Best'

print('BLEUscore:',bleu([C1], C2, smoothing_function=smoothie))

Examples: By updating C1 and C2.

C1='Test' C2='Test'

BLEUscore: 1.0

C1='Test' C2='Best'

BLEUscore: 0.2326589746035907

C1='Test' C2='Text'

BLEUscore: 0.2866227639866161

You can also compare sentence similarity:

C1='It is tough.' C2='It is rough.'

BLEUscore: 0.7348889200874658

C1='It is tough.' C2='It is tough.'

BLEUscore: 1.0

How do I detect "shift+enter" and generate a new line in Textarea?

using ng-keyup directive in angularJS, only send a message on pressing Enter key and Shift+Enter will just take a new line.

ng-keyup="($event.keyCode == 13&&!$event.shiftKey) ? sendMessage() : null"

select2 changing items dynamically

I fix the lack of example's library here:

<link href="https://cdnjs.cloudflare.com/ajax/libs/select2/3.5.2/select2.css" rel="stylesheet"/>
<script src="https://cdnjs.cloudflare.com/ajax/libs/select2/3.5.2/select2.js">

http://jsfiddle.net/bbAU9/328/

Right align and left align text in same HTML table cell

It is possible but how depends on what you are trying to accomplish. If it's this:

| Left-aligned       Right-aligned | in one cell then you can use floating divs inside the td tag:

<td>
<div style='float: left; text-align: left'>Left-aligned</div>
<div style='float: right; text-align: right'>Right-aligned</div>
</td>

If it's | Left-aligned
                                           Right Aligned |

Then Balon's solution is correct.

If it's: | Left-aligned    |   Right-Aligned |

Then it's:

<td align="left">Left-aligned</td>
<td align="right">Right-Aligned</td>

What is the difference between a Docker image and a container?

I couldn't understand the concept of image and layer in spite of reading all the questions here and then eventually stumbled upon this excellent documentation from Docker (duh!).

The example there is really the key to understand the whole concept. It is a lengthy post, so I am summarising the key points that need to be really grasped to get clarity.

  • Image: A Docker image is built up from a series of read-only layers

  • Layer: Each layer represents an instruction in the image’s Dockerfile.

Example: The below Dockerfile contains four commands, each of which creates a layer.

FROM ubuntu:15.04

COPY . /app

RUN make /app

CMD python /app/app.py

Importantly, each layer is only a set of differences from the layer before it.

  • Container. When you create a new container, you add a new writable layer on top of the underlying layers. This layer is often called the “container layer”. All changes made to the running container, such as writing new files, modifying existing files, and deleting files, are written to this thin writable container layer.

Hence, the major difference between a container and an image is the top writable layer. All writes to the container that add new or modify existing data are stored in this writable layer. When the container is deleted, the writable layer is also deleted. The underlying image remains unchanged.

Understanding images cnd Containers from a size-on-disk perspective

To view the approximate size of a running container, you can use the docker ps -s command. You get size and virtual size as two of the outputs:

  • Size: the amount of data (on disk) that is used for the writable layer of each container

  • Virtual Size: the amount of data used for the read-only image data used by the container. Multiple containers may share some or all read-only image data. Hence these are not additive. I.e. you can't add all the virtual sizes to calculate how much size on disk is used by the image

Another important concept is the copy-on-write strategy

If a file or directory exists in a lower layer within the image, and another layer (including the writable layer) needs read access to it, it just uses the existing file. The first time another layer needs to modify the file (when building the image or running the container), the file is copied into that layer and modified.

I hope that helps someone else like me.

How can I put CSS and HTML code in the same file?

You can include CSS styles in an html document with <style></style> tags.

Example:

<style>
  .myClass { background: #f00; }

  .myOtherClass { font-size: 12px; }
</style>

How to deploy a war file in JBoss AS 7?

open up console and navigate to bin folder and run

JBOSS_HOME/bin > stanalone.sh

Once it is up and running just copy past your war file in

standalone/deployments folder

Thats probably it for jboss 7.1

JavaScript for detecting browser language preference

Javascript way:

var language = window.navigator.userLanguage || window.navigator.language;//returns value like 'en-us'

If you are using jQuery.i18n plugin, you can use:

jQuery.i18n.browserLang();//returns value like '"en-US"'

Facebook Oauth Logout

A note for Christoph's answer: Facebook Oauth Logout The logout function requires a callback function to be specified and will fail without it, at least on Firefox. Chrome works without the callback.

FB.logout(function(response) {});

Accessing Websites through a Different Port?

You can use ssh to forward ports onto somewhere else.

If you have two computers, one you browse from, and one which is free to access websites, and is not logged (ie. you own it and it's sitting at home), then you can set up a tunnel between them to forward http traffic over.

For example, I connect to my home computer from work using ssh, with port forwarding, like this:

ssh -L 22222:<target_website>:80 <home_computer>

Then I can point my browser to

http://localhost:22222/

And this request will be forwarded over ssh. Since the work computer is first contacting the home computer, and then contacting the target website, it will be hard to log.

However, this is all getting into 'how to bypass web proxies' and the like, and I suggest you create a new question asking what exactly you want to do.

Ie. "How do I bypass web proxies to avoid my traffic being logged?"

Can you recommend a free light-weight MySQL GUI for Linux?

i suggest using phpmyadmin

it’s definitely the best free tool out there and it works on every system with php+mysql

How do I find all of the symlinks in a directory tree?

What I do is create a script in my bin directory that is like an alias. For example I have a script named lsd ls -l | grep ^d

you could make one lsl ls -lR | grep ^l

Just chmod them +x and you are good to go.

How to set cursor to input box in Javascript?

In my experience

document.getElementById(frmObj.id).focus();

is good on a browser running on a PC. But on mobile if you want the keyboard to show up so the user can input directly then you also need:

document.getElementById(frmObj.id).select();

Postgres: SQL to list table foreign keys

This query works correct with composite keys also:

select c.constraint_name
    , x.table_schema as schema_name
    , x.table_name
    , x.column_name
    , y.table_schema as foreign_schema_name
    , y.table_name as foreign_table_name
    , y.column_name as foreign_column_name
from information_schema.referential_constraints c
join information_schema.key_column_usage x
    on x.constraint_name = c.constraint_name
join information_schema.key_column_usage y
    on y.ordinal_position = x.position_in_unique_constraint
    and y.constraint_name = c.unique_constraint_name
order by c.constraint_name, x.ordinal_position

FFmpeg on Android

I had the same issue, I found most of the answers here out dated. I ended up writing a wrapper on FFMPEG to access from Android with a single line of code.

https://github.com/madhavanmalolan/ffmpegandroidlibrary

What is monkey patching?

First: monkey patching is an evil hack (in my opinion).

It is often used to replace a method on the module or class level with a custom implementation.

The most common usecase is adding a workaround for a bug in a module or class when you can't replace the original code. In this case you replace the "wrong" code through monkey patching with an implementation inside your own module/package.

How to implement a Boolean search with multiple columns in pandas

the query() method can do that very intuitively. Express your condition in a string to be evaluated like the following example :

df = df.query("columnNameA <= @x or columnNameB == @y")

with x and y are declared variables which you can refer to with @

How to publish a website made by Node.js to Github Pages?

It's very simple steps to push your node js application from local to GitHub.

Steps:

  1. First create a new repository on GitHub
  2. Open Git CMD installed to your system (Install GitHub Desktop)
  3. Clone the repository to your system with the command: git clone repo-url
  4. Now copy all your application files to this cloned library if it's not there
  5. Get everything ready to commit: git add -A
  6. Commit the tracked changes and prepares them to be pushed to a remote repository: git commit -a -m "First Commit"
  7. Push the changes in your local repository to GitHub: git push origin master

Parameterize an SQL IN clause

I would pass a table type parameter (since it's SQL Server 2008), and do a where exists, or inner join. You may also use XML, using sp_xml_preparedocument, and then even index that temporary table.

AngularJS: Can't I set a variable value on ng-click?

You can use some thing like this

_x000D_
_x000D_
<!DOCTYPE html>_x000D_
<html>_x000D_
_x000D_
<head>_x000D_
  <script src="http://ajax.googleapis.com/ajax/libs/angularjs/1.2.26/angular.min.js"></script>_x000D_
</head>_x000D_
_x000D_
<body>_x000D_
  <div ng-app="" ng-init="btn1=false" ng-init="btn2=false">_x000D_
    <p>_x000D_
      <input type="submit" ng-disabled="btn1||btn2" ng-click="btn1=true" ng-model="btn1" />_x000D_
    </p>_x000D_
    <p>_x000D_
      <button ng-disabled="btn1||btn2" ng-model="btn2" ng-click="btn2=true">Click Me!</button>_x000D_
    </p>_x000D_
  </div>_x000D_
</body>_x000D_
_x000D_
</html>
_x000D_
_x000D_
_x000D_

Java - Convert image to Base64

new String(byteArray, 0, bytesRead); does not modify the array. You need to use System.arrayCopy to trim the array to the actual data size. Otherwise you are processing all 102400 bytes most of which are zeros.

Installing ADB on macOS

Note that if you use Android Studio and download through its SDK Manager, the SDK is downloaded to ~/Library/Android/sdk by default, not ~/.android-sdk-macosx.

I would rather add this as a comment to @brismuth's excellent answer, but it seems I don't have enough reputation points yet.

Convert text to columns in Excel using VBA

If someone is facing issue using texttocolumns function in UFT. Please try using below function.

myxl.Workbooks.Open myexcel.xls
myxl.Application.Visible = false `enter code here`
set mysheet = myxl.ActiveWorkbook.Worksheets(1)
Set objRange = myxl.Range("A1").EntireColumn
Set objRange2 = mysheet.Range("A1")
objRange.TextToColumns objRange2,1,1, , , , true

Here we are using coma(,) as delimiter.

Print to standard printer from Python?

This has only been tested on Windows:

You can do the following:

import os

os.startfile("C:/Users/TestFile.txt", "print")

This will start the file, in its default opener, with the verb 'print', which will print to your default printer.Only requires the os module which comes with the standard library

What is the SSIS package and what does it do?

For Latest Info About SSIS > https://docs.microsoft.com/en-us/sql/integration-services/sql-server-integration-services

From the above referenced site:

Microsoft Integration Services is a platform for building enterprise-level data integration and data transformations solutions. Use Integration Services to solve complex business problems by copying or downloading files, loading data warehouses, cleansing and mining data, and managing SQL Server objects and data.

Integration Services can extract and transform data from a wide variety of sources such as XML data files, flat files, and relational data sources, and then load the data into one or more destinations.

Integration Services includes a rich set of built-in tasks and transformations, graphical tools for building packages, and the Integration Services Catalog database, where you store, run, and manage packages.

You can use the graphical Integration Services tools to create solutions without writing a single line of code. You can also program the extensive Integration Services object model to create packages programmatically and code custom tasks and other package objects.

Getting Started with SSIS - http://msdn.microsoft.com/en-us/sqlserver/bb671393.aspx

If you are Integration Services Information Worker - http://msdn.microsoft.com/en-us/library/ms141667.aspx

If you are Integration Services Administrator - http://msdn.microsoft.com/en-us/library/ms137815.aspx

If you are Integration Services Developer - http://msdn.microsoft.com/en-us/library/ms137709.aspx

If you are Integration Services Architect - http://msdn.microsoft.com/en-us/library/ms142161.aspx

Overview of SSIS - http://msdn.microsoft.com/en-us/library/ms141263.aspx

Integration Services How-to Topics - http://msdn.microsoft.com/en-us/library/ms141767.aspx

intellij idea - Error: java: invalid source release 1.9

For anyone struggling with this issue who tried DeanM's solution but to no avail, there's something else worth checking, which is the version of the JDK you have configured for your project. What I'm trying to say is that if you have configured JDK 8u191 (for example) for your project, but have the language level set to anything higher than 8, you're gonna get this error.

In this case, it's probably better to ask whoever's in charge of the project, which version of the JDK would be preferable to compile the sources.

How to replace multiple patterns at once with sed?

echo "C:\Users\San.Tan\My Folder\project1" | sed -e 's/C:\\/mnt\/c\//;s/\\/\//g'

replaces

C:\Users\San.Tan\My Folder\project1

to

mnt/c/Users/San.Tan/My Folder/project1

in case someone needs to replace windows paths to Windows Subsystem for Linux(WSL) paths

TypeError: unsupported operand type(s) for -: 'list' and 'list'

The operations needed to be performed, require numpy arrays either created via

np.array()

or can be converted from list to an array via

np.stack()

As in the above mentioned case, 2 lists are inputted as operands it triggers the error.

Efficient way to Handle ResultSet in Java

Here is the code little modified that i got it from google -

 List data_table = new ArrayList<>();
    Class.forName("oracle.jdbc.driver.OracleDriver");
            con = DriverManager.getConnection(conn_url, user_id, password);
            Statement stmt = con.createStatement();
            System.out.println("query_string: "+query_string);
            ResultSet rs = stmt.executeQuery(query_string);
            ResultSetMetaData rsmd = rs.getMetaData();


            int row_count = 0;
            while (rs.next()) {
                HashMap<String, String> data_map = new HashMap<>();
                if (row_count == 240001) {
                    break;
                }
                for (int i = 1; i <= rsmd.getColumnCount(); i++) {
                    data_map.put(rsmd.getColumnName(i), rs.getString(i));
                }
                data_table.add(data_map);
                row_count = row_count + 1;
            }
            rs.close();
            stmt.close();
            con.close();

Create directory if it does not exist

I had the exact same problem. You can use something like this:

$local = Get-Location;
$final_local = "C:\Processing";

if(!$local.Equals("C:\"))
{
    cd "C:\";
    if((Test-Path $final_local) -eq 0)
    {
        mkdir $final_local;
        cd $final_local;
        liga;
    }

    ## If path already exists
    ## DB Connect
    elseif ((Test-Path $final_local) -eq 1)
    {
        cd $final_local;
        echo $final_local;
        liga;  (function created by you TODO something)
    }
}

Responsive design with media query : screen size?

i will provide mine because @muni s solution was a bit overkill for me

note: if you want to add custom definitions for several resolutions together, say something like this:

//mobile generally   
 @media screen and (max-width: 1199)  {

      .irns-desktop{
        display: none;
      }

      .irns-mobile{
        display: initial;
      }

    }

Be sure to add those definitions on top of the accurate definitions, so it cascades correctly (e.g. 'smartphone portrait' must win versus 'mobile generally')

//here all definitions to apply globally


//desktop
@media only screen
and (min-width : 1200) {


}

//tablet landscape
@media screen and (min-width: 1024px) and (max-width: 1600px)  {

} // end media query

//tablet portrait
@media screen and (min-width: 768px) and (max-width: 1023px)  {

}//end media definition


//smartphone landscape
@media screen and (min-width: 480px) and (max-width: 767px)  {

}//end media query



//smartphone portrait
@media screen /*and (min-width: 320px)*/
and (max-width: 479px) {

}

//end media query

Creating a Pandas DataFrame from a Numpy array: How do I specify the index column and column headers?

This can be done simply by using from_records of pandas DataFrame

import numpy as np
import pandas as pd
# Creating a numpy array
x = np.arange(1,10,1).reshape(-1,1)
dataframe = pd.DataFrame.from_records(x)

Python __call__ special method practical example

Specify a __metaclass__ and override the __call__ method, and have the specified meta classes' __new__ method return an instance of the class, viola you have a "function" with methods.

Spring Boot - Error creating bean with name 'dataSource' defined in class path resource

Created database in MySQL

create database springboot2;

application.properties

spring.datasource.driver-class-name=com.mysql.cj.jdbc.Driver
spring.datasource.url = jdbc:mysql://localhost:3306/springboot2
spring.datasource.username = root
spring.datasource.password = root
spring.jpa.show-sql = true
spring.jpa.hibernate.ddl-auto = update
spring.jpa.properties.hibernate.dialect = org.hibernate.dialect.MySQL5Dialect
server.port=9192

pom.xml

<dependencies>
        <dependency>
            <groupId>org.springframework.boot</groupId>
            <artifactId>spring-boot-starter-data-jpa</artifactId>
        </dependency>
        <dependency>
            <groupId>org.springframework.boot</groupId>
            <artifactId>spring-boot-starter-web</artifactId>
        </dependency>

        <dependency>
            <groupId>mysql</groupId>
            <artifactId>mysql-connector-java</artifactId>
            <scope>runtime</scope>
        </dependency>
        <dependency>
            <groupId>org.projectlombok</groupId>
            <artifactId>lombok</artifactId>
            <optional>true</optional>
        </dependency>
        <dependency>
            <groupId>org.springframework.boot</groupId>
            <artifactId>spring-boot-starter-test</artifactId>
            <scope>test</scope>
            <exclusions>
                <exclusion>
                    <groupId>org.junit.vintage</groupId>
                    <artifactId>junit-vintage-engine</artifactId>
                </exclusion>
            </exclusions>
        </dependency>
    </dependencies>

main class

import org.springframework.boot.SpringApplication;
import org.springframework.boot.autoconfigure.SpringBootApplication;

@SpringBootApplication
public class Application {

    public static void main(String[] args) {
        SpringApplication.run(Application.class, args);
    }

}

model class

package com.First.Try.springboot.entity;
    
import javax.persistence.Entity;
import javax.persistence.GeneratedValue;
import javax.persistence.Id;
import javax.persistence.Table;

import lombok.AllArgsConstructor;
import lombok.Data;
import lombok.NoArgsConstructor;
@Data
@AllArgsConstructor 
@NoArgsConstructor
@Entity
@Table(name="PRODUCT_TBL1")
public class Product {
    @Id
    @GeneratedValue
    private int id;
    private String name;
    private int quantity;
    private double price;
    ....
    ....
    ....
 }

How to use "not" in xpath?

None of these answers worked for me for python. I solved by this

a[not(@id='XX')]

Also you can use or condition in your xpath by | operator. Such as

a[not(@id='XX')]|a[not(@class='YY')]

Sometimes we want element which has no class. So you can do like

a[not(@class)]

In Ruby, how do I skip a loop in a .each loop, similar to 'continue'

Use next:

(1..10).each do |a|
  next if a.even?
  puts a
end

prints:

1
3   
5
7
9

For additional coolness check out also redo and retry.

Works also for friends like times, upto, downto, each_with_index, select, map and other iterators (and more generally blocks).

For more info see http://ruby-doc.org/docs/ProgrammingRuby/html/tut_expressions.html#UL.

ng-if, not equal to?

It is better to use ng-switch

<div ng-switch on="details.Payment[0].Status">
    <div ng-switch-when="1">
        <!-- code to render a large video block-->
    </div>
    <div ng-switch-default>
        <!-- code to render the regular video block -->
    </div>
</div>

How to store .pdf files into MySQL as BLOBs using PHP?

In regards to Gordon M's answer above, the 1st and 2nd parameter in mysqli_real_escape_string () call should be swapped for the newer php versions, according to: http://php.net/manual/en/mysqli.real-escape-string.php

Android Facebook integration with invalid key hash

The generated hash key is wrong. You may get the hash key using two steps.

One is through a command prompt. Another one is through coding. The hash key through a command prompt is working on the first time only. I don't know the reason. I have also got the same problem. So I tried it through programmatically.

Follow these steps:

Paste the following code in oncreate().

try {
    PackageInfo info = getPackageManager().getPackageInfo(
                           "com.example.packagename",
                           PackageManager.GET_SIGNATURES);
    for (Signature signature : info.signatures) {
        MessageDigest md = MessageDigest.getInstance("SHA");
        md.update(signature.toByteArray());
        Log.d("KeyHash:", Base64.encodeToString(md.digest(), Base64.DEFAULT));
    }
}
catch (NameNotFoundException e) {
}
catch (NoSuchAlgorithmException e) {
}

Modify "com.example.packagename" with your package name in the above coding without fail (you may find your package name in the Android manifest file).

Run your application. Go to the activity where you pasted the above code. In the LogCat file, search for "KeyHash". You may find a key hash. Copy the key hash and go to Facebook application dashboard page. Go to settings and enter the details like in the below image.

Enter image description here

Once you finished the above step, relaunch the app again. You may now log into Facebook. For more details about key hash, check the link.

If you add wrong information in the settings page, it means it will give some error. So use the correct information there. And also if the public (other than you) need to use your application means you need to enable the permission (change "yes" in the "Status & Review" next to the setting).

How to check if spark dataframe is empty?

I found that on some cases:

>>>print(type(df))
<class 'pyspark.sql.dataframe.DataFrame'>

>>>df.take(1).isEmpty
'list' object has no attribute 'isEmpty'

this is same for "length" or replace take() by head()

[Solution] for the issue we can use.

>>>df.limit(2).count() > 1
False

setTimeout / clearTimeout problems

Not sure if this violates some good practice coding rule but I usually come out with this one:

if(typeof __t == 'undefined')
        __t = 0;
clearTimeout(__t);
__t = setTimeout(callback, 1000);

This prevent the need to declare the timer out of the function.

EDIT: this also don't declare a new variable at each invocation, but always recycle the same.

Hope this helps.

Is it possible to force row level locking in SQL Server?

You can use the ROWLOCK hint, but AFAIK SQL may decide to escalate it if it runs low on resources

From the doco:

ROWLOCK Specifies that row locks are taken when page or table locks are ordinarily taken. When specified in transactions operating at the SNAPSHOT isolation level, row locks are not taken unless ROWLOCK is combined with other table hints that require locks, such as UPDLOCK and HOLDLOCK.

and

Lock hints ROWLOCK, UPDLOCK, AND XLOCK that acquire row-level locks may place locks on index keys rather than the actual data rows. For example, if a table has a nonclustered index, and a SELECT statement using a lock hint is handled by a covering index, a lock is acquired on the index key in the covering index rather than on the data row in the base table.

And finally this gives a pretty in-depth explanation about lock escalation in SQL Server 2005 which was changed in SQL Server 2008.

There is also, the very in depth: Locking in The Database Engine (in books online)

So, in general

UPDATE
Employees WITH (ROWLOCK)
SET Name='Mr Bean'
WHERE Age>93

Should be ok, but depending on the indexes and load on the server it may end up escalating to a page lock.

How can I close a Twitter Bootstrap popover with a click from anywhere (else) on the page?

Here is the solution which worked very fine for me, if it can help :

/**
* Add the equals method to the jquery objects
*/
$.fn.equals = function(compareTo) {
  if (!compareTo || this.length !== compareTo.length) {
    return false;
  }
  for (var i = 0; i < this.length; ++i) {
    if (this[i] !== compareTo[i]) {
      return false;
    }
  }
  return true;
};

/**
 * Activate popover message for all concerned fields
 */
var popoverOpened = null;
$(function() { 
    $('span.btn').popover();
    $('span.btn').unbind("click");
    $('span.btn').bind("click", function(e) {
        e.stopPropagation();
        if($(this).equals(popoverOpened)) return;
        if(popoverOpened !== null) {
            popoverOpened.popover("hide");            
        }
        $(this).popover('show');
        popoverOpened = $(this);
        e.preventDefault();
    });

    $(document).click(function(e) {
        if(popoverOpened !== null) {
            popoverOpened.popover("hide");   
            popoverOpened = null;
        }        
    });
});

Convert RGB values to Integer

if r, g, b = 3 integer values from 0 to 255 for each color

then

rgb = 65536 * r + 256 * g + b;

the single rgb value is the composite value of r,g,b combined for a total of 16777216 possible shades.

Calculate logarithm in python

The math.log function is to the base e, i.e. natural logarithm. If you want to the base 10 use math.log10.

ReactJS - .JS vs .JSX

In most of the cases it’s only a need for the transpiler/bundler, which might not be configured to work with JSX files, but with JS! So you are forced to use JS files instead of JSX.

And since react is just a library for javascript, it makes no difference for you to choose between JSX or JS. They’re completely interchangeable!

In some cases users/developers might also choose JSX over JS, because of code highlighting, but the most of the newer editors are also viewing the react syntax correctly in JS files.

Limit length of characters in a regular expression?

Is there a way to limit a regex to 100 characters WITH regex?

Your example suggests that you'd like to grab a number from inside the regex and then use this number to place a maximum length on another part that is matched later in the regex. This usually isn't possible in a single pass. Your best bet is to have two separate regular expressions:

  • one to match the maximum length you'd like to use
  • one which uses the previously extracted value to verify that its own match does not exceed the specified length

If you just want to limit the number of characters matched by an expression, most regular expressions support bounds by using braces. For instance,

\d{3}-\d{3}-\d{4}

will match (US) phone numbers: exactly three digits, then a hyphen, then exactly three digits, then another hyphen, then exactly four digits.

Likewise, you can set upper or lower limits:

\d{5,10}

means "at least 5, but not more than 10 digits".


Update: The OP clarified that he's trying to limit the value, not the length. My new answer is don't use regular expressions for that. Extract the value, then compare it against the maximum you extracted from the size parameter. It's much less error-prone.

Best way to create an empty map in Java

1) If the Map can be immutable:

Collections.emptyMap()

// or, in some cases:
Collections.<String, String>emptyMap()

You'll have to use the latter sometimes when the compiler cannot automatically figure out what kind of Map is needed (this is called type inference). For example, consider a method declared like this:

public void foobar(Map<String, String> map){ ... }

When passing the empty Map directly to it, you have to be explicit about the type:

foobar(Collections.emptyMap());                 // doesn't compile
foobar(Collections.<String, String>emptyMap()); // works fine

2) If you need to be able to modify the Map, then for example:

new HashMap<String, String>()

(as tehblanx pointed out)


Addendum: If your project uses Guava, you have the following alternatives:

1) Immutable map:

ImmutableMap.of()
// or:
ImmutableMap.<String, String>of()

Granted, no big benefits here compared to Collections.emptyMap(). From the Javadoc:

This map behaves and performs comparably to Collections.emptyMap(), and is preferable mainly for consistency and maintainability of your code.

2) Map that you can modify:

Maps.newHashMap()
// or:
Maps.<String, String>newHashMap()

Maps contains similar factory methods for instantiating other types of maps as well, such as TreeMap or LinkedHashMap.


Update (2018): On Java 9 or newer, the shortest code for creating an immutable empty map is:

Map.of()

...using the new convenience factory methods from JEP 269.

Eclipse hangs on loading workbench

The best solution I found is to delete this file: workspace/.metadata/.plugins/org.eclipse.e4.workbench/workbench

HTML image not showing in Gmail

Try to add title and alt properties to your image.... Gmail and some others blocks images without some attributes.. and it is also a logic to include your email to be read as spam.

Set the text in a span

This is because you have wrong selector. According to your markup, .ui-icon and .ui-icon-circle-triangle-w" should point to the same <span> element. So you should use:

$(".ui-icon.ui-icon-circle-triangle-w").html("<<");

or

$(".ui-datepicker-prev .ui-icon").html("<<");

or

$(".ui-datepicker-prev span").html("<<");

"document.getElementByClass is not a function"

It should be getElementsByClassName, and not getElementByClass. See this - https://developer.mozilla.org/en/DOM/document.getElementsByClassName.

Note that some browsers/versions may not support this.

How to declare or mark a Java method as deprecated?

Use the annotation @Deprecated for your method, and you should also mention it in your javadocs.

SoapUI "failed to load url" error when loading WSDL

I have had similar problems and worked around them by saving the WSDL locally. Don't forget to save any XSD files as well. You may need to edit the WSDL to specify an appropriate location for XSDs.

Toggle button using two image on different state

Do this:

<ToggleButton 
        android:id="@+id/toggle"
        android:layout_width="wrap_content"
        android:layout_height="wrap_content"
        android:background="@drawable/check"   <!--check.xml-->
        android:layout_margin="10dp"
        android:textOn=""
        android:textOff=""
        android:focusable="false"
        android:focusableInTouchMode="false"
        android:layout_centerVertical="true"/>

create check.xml in drawable folder

<?xml version="1.0" encoding="utf-8"?>
<selector xmlns:android="http://schemas.android.com/apk/res/android">
    <!-- When selected, use grey -->
    <item android:drawable="@drawable/selected_image"
          android:state_checked="true" />
    <!-- When not selected, use white-->
    <item android:drawable="@drawable/unselected_image"
        android:state_checked="false"/>

 </selector>

Calculate age based on date of birth

 $dob = $this->dateOfBirth; //Datetime 
        $currentDate = new \DateTime();
        $dateDiff = $dob->diff($currentDate);
        $years = $dateDiff->y;
        $months = $dateDiff->m;
        $days = $dateDiff->d;
        $age = $years .' Year(s)';

        if($years === 0) {
            $age = $months .' Month(s)';
            if($months === 0) {
                $age = $days .' Day(s)';
            }
        }
        return $age;

Getting value from a cell from a gridview on RowDataBound event

why not pull the data directly out of the data source.

DataBinder.Eval(e.Row.DataItem, "ColumnName")

How to find the Vagrant IP?

By default, a vagrant box doesn't have any ip address. In order to find the IP address, you simply assign the IP address in your Vagrantfile then call vagrant reload

If you just need to access a vagrant machine from only the host machine, setting up a "private network" is all you need. Either uncomment the appropriate line in a default Vagrantfile, or add this snippet. If you want your VM to appear at 172.30.1.5 it would be the following:

config.vm.network "private_network", ip: "172.30.1.5"

Learn more about private networks. https://www.vagrantup.com/docs/networking/private_network.html

If you need vagrant to be accessible outside your host machine, for instance for developing against a mobile device such as iOS or Android, you have to enable a public network you can use either static IP, such as 192.168.1.10, or DHCP.

config.vm.network "public_network", ip: "192.168.1.10"

Learn more about configuring a public network https://www.vagrantup.com/docs/networking/public_network.html

Using ListView : How to add a header view?

I found out that inflating the header view as:

inflater.inflate(R.layout.listheader, container, false);

being container the Fragment's ViewGroup, inflates the headerview with a LayoutParam that extends from FragmentLayout but ListView expect it to be a AbsListView.LayoutParams instead.

So, my problem was solved solved by inflating the header view passing the list as container:

ListView list = fragmentview.findViewById(R.id.listview);
View headerView = inflater.inflate(R.layout.listheader, list, false);

then

list.addHeaderView(headerView, null, false);

Kinda late answer but I hope this can help someone

POST request via RestTemplate in JSON

If you are using Spring 3.0, an easy way to avoid the org.springframework.web.client.HttpClientErrorException: 415 Unsupported Media Type exception, is to include the jackson jar files in your classpath, and use mvc:annotation-driven config element. As specified here.

I was pulling my hair out trying to figure out why the mvc-ajax app worked without any special config for the MappingJacksonHttpMessageConverter. If you read the article I linked above closely:

Underneath the covers, Spring MVC delegates to a HttpMessageConverter to perform the serialization. In this case, Spring MVC invokes a MappingJacksonHttpMessageConverter built on the Jackson JSON processor. This implementation is enabled automatically when you use the mvc:annotation-driven configuration element with Jackson present in your classpath.

nano error: Error opening terminal: xterm-256color

I, too, have this problem on an older Mac that I upgraded to Lion.

Before reading the terminfo tip, I was able to get vi and less working by doing "export TERM=xterm".

After reading the tip, I grabbed /usr/share/terminfo from a newer Mac that has fresh install of Lion and does not exhibit this problem.

Now, even though echo $TERM still yields xterm-256color, vi and less now work fine.

How do I specify different layouts for portrait and landscape orientations?

Or use this:

<ScrollView xmlns:android="http://schemas.android.com/apk/res/android"
            android:scrollbars="vertical" 
            android:layout_height="wrap_content" 
            android:layout_width="fill_parent">

  <LinearLayout android:orientation="vertical"
                android:layout_width="fill_parent"
                android:layout_height="fill_parent">

     <!-- Add your UI elements inside the inner most linear layout -->

  </LinearLayout>
</ScrollView>

What is the difference between HTTP_HOST and SERVER_NAME in PHP?

If you want to check through a server.php or whatever, you want to call it with the following:

<?php
    phpinfo(INFO_VARIABLES);
?>

or

<?php
    header("Content-type: text/plain");

    print_r($_SERVER);
?>

Then access it with all the valid URLs for your site and check out the difference.

How to check if a column exists in Pandas

To check if one or more columns all exist, you can use set.issubset, as in:

if set(['A','C']).issubset(df.columns):
   df['sum'] = df['A'] + df['C']                

As @brianpck points out in a comment, set([]) can alternatively be constructed with curly braces,

if {'A', 'C'}.issubset(df.columns):

See this question for a discussion of the curly-braces syntax.

Or, you can use a list comprehension, as in:

if all([item in df.columns for item in ['A','C']]):

Read only the first line of a file?

first_line = next(open(filename))

What is the difference between spark.sql.shuffle.partitions and spark.default.parallelism?

From the answer here, spark.sql.shuffle.partitions configures the number of partitions that are used when shuffling data for joins or aggregations.

spark.default.parallelism is the default number of partitions in RDDs returned by transformations like join, reduceByKey, and parallelize when not set explicitly by the user. Note that spark.default.parallelism seems to only be working for raw RDD and is ignored when working with dataframes.

If the task you are performing is not a join or aggregation and you are working with dataframes then setting these will not have any effect. You could, however, set the number of partitions yourself by calling df.repartition(numOfPartitions) (don't forget to assign it to a new val) in your code.


To change the settings in your code you can simply do:

sqlContext.setConf("spark.sql.shuffle.partitions", "300")
sqlContext.setConf("spark.default.parallelism", "300")

Alternatively, you can make the change when submitting the job to a cluster with spark-submit:

./bin/spark-submit --conf spark.sql.shuffle.partitions=300 --conf spark.default.parallelism=300

How to catch a click event on a button?

Change your onCreate to

@Override
protected void onCreate(Bundle savedInstanceState) {
    super.onCreate(savedInstanceState);

for me this update worked

Get environment variable value in Dockerfile

If you just want to find and replace all environment variables ($ExampleEnvVar) in a Dockerfile then build it this would work:

envsubst < /path/to/Dockerfile | docker build -t myDockerImage . -f -