Programs & Examples On #Pcap

pcap (packet capture) consists of an application programming interface (API) for capturing network traffic

Parsing a pcap file in python

You might want to start with scapy.

How do you store Java objects in HttpSession?

You are not adding the object to the session, instead you are adding it to the request.
What you need is:

HttpSession session = request.getSession();
session.setAttribute("MySessionVariable", param);

In Servlets you have 4 scopes where you can store data.

  1. Application
  2. Session
  3. Request
  4. Page

Make sure you understand these. For more look here

NOW() function in PHP

Or you can use DateTime constants:

echo date(DateTime::W3C); // 2005-08-15T15:52:01+00:00

Here's the list of them:

ATOM = "Y-m-d\TH:i:sP" ;               // -> 2005-08-15T15:52:01+00:00
COOKIE = "l, d-M-Y H:i:s T" ;          // -> Monday, 15-Aug-2005 15:52:01 UTC
ISO8601 = "Y-m-d\TH:i:sO" ;            // -> 2005-08-15T15:52:01+0000
RFC822 = "D, d M y H:i:s O" ;          // -> Mon, 15 Aug 05 15:52:01 +0000
RFC850 = "l, d-M-y H:i:s T" ;          // -> Monday, 15-Aug-05 15:52:01 UTC
RFC1036 = "D, d M y H:i:s O" ;         // -> Mon, 15 Aug 05 15:52:01 +0000
RFC1123 = "D, d M Y H:i:s O" ;         // -> Mon, 15 Aug 2005 15:52:01 +0000
RFC2822 = "D, d M Y H:i:s O" ;         // -> Mon, 15 Aug 2005 15:52:01 +0000
RFC3339 = "Y-m-d\TH:i:sP" ;            // -> 2005-08-15T15:52:01+00:00 ( == ATOM)
RFC3339_EXTENDED = "Y-m-d\TH:i:s.vP" ; // -> 2005-08-15T15:52:01.000+00:00
RSS = "D, d M Y H:i:s O" ;             // -> Mon, 15 Aug 2005 15:52:01 +0000
W3C = "Y-m-d\TH:i:sP" ;                // -> 2005-08-15T15:52:01+00:00

For debugging I prefer a shorter one though (3v4l.org):

echo date('ymd\THisP'); // 180614T120708+02:00

NLTK and Stopwords Fail #lookuperror

import nltk
nltk.download()

Click on download button when gui prompted. It worked for me.(nltk.download('stopwords') doesn't work for me)

Reload chart data via JSON with Highcharts

You need to clear the old array out before you push the new data in. There are many ways to accomplish this but I used this one:

options.series[0].data.length = 0;

So your code should look like this:

options.series[0].data.length = 0;
$.each(lines, function(lineNo, line) {
                    var items = line.split(',');
                    var data = {};
                    $.each(items, function(itemNo, item) {
                        if (itemNo === 0) {
                            data.name = item;
                        } else {
                            data.y = parseFloat(item);
                        }
                    });
                    options.series[0].data.push(data);
                });

Now when the button is clicked the old data is purged and only the new data should show up. Hope that helps.

Java 8 Lambda function that throws exception?

If you don't mind using a third party library, with cyclops-react, a library I contribute to, you can use the FluentFunctions API to write

 Function<String, Integer> standardFn = FluentFunctions.ofChecked(this::myMethod);

ofChecked takes a jOO? CheckedFunction and returns the reference softened back to a standard (unchecked) JDK java.util.function.Function.

Alternatively you can keep working with the captured function via the FluentFunctions api!

For example to execute your method, retrying it up to 5 times and logging it's status you can write

  FluentFunctions.ofChecked(this::myMethod)
                 .log(s->log.debug(s),e->log.error(e,e.getMessage())
                 .try(5,1000)
                 .apply("my param");

What is the difference between ManualResetEvent and AutoResetEvent in .NET?

Taken from C# 3.0 Nutshell book, by Joseph Albahari

Threading in C# - Free E-Book

A ManualResetEvent is a variation on AutoResetEvent. It differs in that it doesn't automatically reset after a thread is let through on a WaitOne call, and so functions like a gate: calling Set opens the gate, allowing any number of threads that WaitOne at the gate through; calling Reset closes the gate, causing, potentially, a queue of waiters to accumulate until its next opened.

One could simulate this functionality with a boolean "gateOpen" field (declared with the volatile keyword) in combination with "spin-sleeping" – repeatedly checking the flag, and then sleeping for a short period of time.

ManualResetEvents are sometimes used to signal that a particular operation is complete, or that a thread's completed initialization and is ready to perform work.

How to check if an element exists in the xml using xpath?

Use:

boolean(/*/*[@subjectIdentifier="Primary"]/*/*/*/*
                           [name()='AttachedXml' 
                          and 
                            namespace-uri()='http://xml.mycompany.com/XMLSchema'
                           ]
       )

How do I extend a class with c# extension methods?

The closest I can get to the answer is by adding an extension method into a System.Type object. Not pretty, but still interesting.

public static class Foo
{
    public static void Bar()
    {
        var now = DateTime.Now;
        var tomorrow = typeof(DateTime).Tomorrow();
    }

    public static DateTime Tomorrow(this System.Type type)
    {
        if (type == typeof(DateTime)) {
            return DateTime.Now.AddDays(1);
        } else {
            throw new InvalidOperationException();
        }
    }
}

Otherwise, IMO Andrew and ShuggyCoUk has a better implementation.

Using ResourceManager

This SO answer might help in this case.
If the main project already references the resource project, then you could just explicitly work with your generated-resource class in your code, and access its ResourceManager from that. Hence, something along the lines of:

ResourceManager resMan = YeagerTechResources.Resources.ResourceManager;

// then, you could go on working with that
ResourceSet resourceSet = resMan.GetResourceSet(CultureInfo.CurrentUICulture, true, true);
// ...

JSP : JSTL's <c:out> tag

c:out also has an attribute for assigning a default value if the value of person.name happens to be null.

Source: out (TLDDoc Generated Documentation)

How to implement Rate It feature in Android App

Java & Kotlin solution (In-app review API by Google in 2020):

enter image description here

First, in your build.gradle(app) file, add following dependencies (full setup here)

dependencies {
    // This dependency is downloaded from the Google’s Maven repository.
    // So, make sure you also include that repository in your project's build.gradle file.
    implementation 'com.google.android.play:core:1.8.0'
}

Add this method to your Activity:

void askRatings() {
    ReviewManager manager = ReviewManagerFactory.create(this);
    Task<ReviewInfo> request = manager.requestReviewFlow();
    request.addOnCompleteListener(task -> {
        if (task.isSuccessful()) {
            // We can get the ReviewInfo object
            ReviewInfo reviewInfo = task.getResult();
            Task<Void> flow = manager.launchReviewFlow(this, reviewInfo);
            flow.addOnCompleteListener(task2 -> {
                // The flow has finished. The API does not indicate whether the user
                // reviewed or not, or even whether the review dialog was shown. Thus, no
                // matter the result, we continue our app flow.
            });
        } else {
            // There was some problem, continue regardless of the result.
        }
    });
}

Call it like any other method:

askRatings();

Kotlin code can be found here

C++ error 'Undefined reference to Class::Function()'

What are you using to compile this? If there's an undefined reference error, usually it's because the .o file (which gets created from the .cpp file) doesn't exist and your compiler/build system is not able to link it.

Also, in your card.cpp, the function should be Card::Card() instead of void Card. The Card:: is scoping; it means that your Card() function is a member of the Card class (which it obviously is, since it's the constructor for that class). Without this, void Card is just a free function. Similarly,

void Card(Card::Rank rank, Card::Suit suit)

should be

Card::Card(Card::Rank rank, Card::Suit suit)

Also, in deck.cpp, you are saying #include "Deck.h" even though you referred to it as deck.h. The includes are case sensitive.

How can I check the extension of a file?

one easy way could be:

import os

if os.path.splitext(file)[1] == ".mp3":
    # do something

os.path.splitext(file) will return a tuple with two values (the filename without extension + just the extension). The second index ([1]) will therefor give you just the extension. The cool thing is, that this way you can also access the filename pretty easily, if needed!

Correct way of looping through C++ arrays

If you have a very short list of elements you would like to handle, you could use the std::initializer_list introduced in C++11 together with auto:

#include <iostream>

int main(int, char*[])
{
    for(const auto& ext : { ".slice", ".socket", ".service", ".target" })
        std::cout << "Handling *" << ext << " systemd files" << std::endl;

    return 0;
}

How to embed fonts in HTML?

Things have changed since this question was originally asked and answered. There's been a large amount of work done on getting cross-browser font embedding for body text to work using @font-face embedding.

Paul Irish put together Bulletproof @font-face syntax combining attempts from multiple other people. If you actually go through the entire article (not just the top) it allows a single @font-face statement to cover IE, Firefox, Safari, Opera, Chrome and possibly others. Basically this can feed out OTF, EOT, SVG and WOFF in ways that don't break anything.

Snipped from his article:

@font-face {
  font-family: 'Graublau Web';
  src: url('GraublauWeb.eot');
  src: local('Graublau Web Regular'), local('Graublau Web'),
    url("GraublauWeb.woff") format("woff"),
    url("GraublauWeb.otf") format("opentype"),
    url("GraublauWeb.svg#grablau") format("svg");
}

Working from that base, Font Squirrel put together a variety of useful tools including the @font-face Generator which allows you to upload a TTF or OTF file and get auto-converted font files for the other types, along with pre-built CSS and a demo HTML page. Font Squirrel also has Hundreds of @font-face kits.

Soma Design also put together the FontFriend Bookmarklet, which redefines fonts on a page on the fly so you can try things out. It includes drag-and-drop @font-face support in FireFox 3.6+.

More recently, Google has started to provide the Google Web Fonts, an assortment of fonts available under an Open Source license and served from Google's servers.

License Restrictions

Finally, WebFonts.info has put together a nice wiki'd list of Fonts available for @font-face embedding based on licenses. It doesn't claim to be an exhaustive list, but fonts on it should be available (possibly with conditions such as an attribution in the CSS file) for embedding/linking. It's important to read the licenses, because there are some limitations that aren't pushed forward obviously on the font downloads.

How to convert a file into a dictionary?

d = {}
with open("file.txt") as f:
    for line in f:
       (key, val) = line.split()
       d[int(key)] = val

How to set time to a date object in java

Calendar cal = Calendar.getInstance();
cal.set(Calendar.HOUR_OF_DAY,17);
cal.set(Calendar.MINUTE,30);
cal.set(Calendar.SECOND,0);
cal.set(Calendar.MILLISECOND,0);

Date d = cal.getTime();

Also See

Gradient of n colors ranging from color 1 and color 2

Just to expand on the previous answer colorRampPalettecan handle more than two colors.

So for a more expanded "heat map" type look you can....

colfunc<-colorRampPalette(c("red","yellow","springgreen","royalblue"))
plot(rep(1,50),col=(colfunc(50)), pch=19,cex=2)

The resulting image:

enter image description here

python - if not in list

if I got it right, you can try

for item in [x for x in checklist if x not in mylist]:
    print (item)

Android Studio Gradle DSL method not found: 'android()' -- Error(17,0)

Change to root build.gradle file

to

// Top-level build file where you can add configuration options common to all sub-projects/modules.

buildscript {
    repositories {
        jcenter()
    }
    dependencies {
        classpath 'com.android.tools.build:gradle:1.5.0'

        // NOTE: Do not place your application dependencies here; they belong
        // in the individual module build.gradle files
    }
}

allprojects {
    repositories {
        jcenter()
    }
}

task clean(type: Delete) {
    delete rootProject.buildDir
}

jQuery ajax request with json response, how to?

Connect your javascript clientside controller and php serverside controller using sending and receiving opcodes with binded data. So your php code can send as response functional delta for js recepient/listener

see https://github.com/ArtNazarov/LazyJs

Sorry for my bad English

Get first row of dataframe in Python Pandas based on criteria

For existing matches, use query:

df.query(' A > 3' ).head(1)
Out[33]: 
   A  B  C
2  4  6  3

df.query(' A > 4 and B > 3' ).head(1)
Out[34]: 
   A  B  C
4  5  4  5

df.query(' A > 3 and (B > 3 or C > 2)' ).head(1)
Out[35]: 
   A  B  C
2  4  6  3

ios simulator: how to close an app

You can also kill the app by process id

ps -cx -o pid,command | awk '$2 == "YourAppNameCaseSensitive" { print $1 }' | xargs kill -9

Simulating a click in jQuery/JavaScript on a link

You can use the the click function to trigger the click event on the selected element.

Example:

$( 'selector for your link' ).click ();

You can learn about various selectors in jQuery's documentation.

EDIT: like the commenters below have said; this only works on events attached with jQuery, inline or in the style of "element.onclick". It does not work with addEventListener, and it will not follow the link if no event handlers are defined. You could solve this with something like this:

var linkEl = $( 'link selector' );
if ( linkEl.attr ( 'onclick' ) === undefined ) {
    document.location = linkEl.attr ( 'href' );
} else {
    linkEl.click ();
}

Don't know about addEventListener though.

How do I properly force a Git push?

I would really recommend to:

  • push only to the main repo

  • make sure that main repo is a bare repo, in order to never have any problem with the main repo working tree being not in sync with its .git base. See "How to push a local git repository to another computer?"

  • If you do have to make modification in the main (bare) repo, clone it (on the main server), do your modification and push back to it

In other words, keep a bare repo accessible both from the main server and the local computer, in order to have a single upstream repo from/to which to pull/pull.

RabbitMQ / AMQP: single queue, multiple consumers for same message?

I think you should check sending your messages using the fan-out exchanger. That way you willl receiving the same message for differents consumers, under the table RabbitMQ is creating differents queues for each one of this new consumers/subscribers.

This is the link for see the tutorial example in javascript https://www.rabbitmq.com/tutorials/tutorial-one-javascript.html

Ant task to run an Ant target only if a file exists?

Check Using Filename filters like DB_*/**/*.sql

Here is a variation to perform an action if one or more files exist corresponding to a wildcard filter. That is, you don't know the exact name of the file.

Here, we are looking for "*.sql" files in any sub-directories called "DB_*", recursively. You can adjust the filter to your needs.

NB: Apache Ant 1.7 and higher!

Here is the target to set a property if matching files exist:

<target name="check_for_sql_files">
    <condition property="sql_to_deploy">
        <resourcecount when="greater" count="0">
            <fileset dir="." includes="DB_*/**/*.sql"/>
        </resourcecount>
    </condition>
</target>

Here is a "conditional" target that only runs if files exist:

<target name="do_stuff" depends="check_for_sql_files" if="sql_to_deploy">
    <!-- Do stuff here -->
</target>

Using Jquery Ajax to retrieve data from Mysql


You can't return ajax return value. You stored global variable store your return values after return.
Or Change ur code like this one.

AjaxGet = function (url) {
    var result = $.ajax({
        type: "POST",
        url: url,
       param: '{}',
        contentType: "application/json; charset=utf-8",
        dataType: "json",
       async: false,
        success: function (data) {
            // nothing needed here
      }
    }) .responseText ;
    return  result;
}

how to delete all commit history in github?

If you are sure you want to remove all commit history, simply delete the .git directory in your project root (note that it's hidden). Then initialize a new repository in the same folder and link it to the GitHub repository:

git init
git remote add origin [email protected]:user/repo

now commit your current version of code

git add *
git commit -am 'message'

and finally force the update to GitHub:

git push -f origin master

However, I suggest backing up the history (the .git folder in the repository) before taking these steps!

How to return only 1 row if multiple duplicate rows and still return rows that are not duplicates?

If this is a SQL question, and I understand what you are asking, (it's not entirely clear), just add distinct to the query

   Select Distinct * From TempTable

Location for session files in Apache/PHP

The only surefire option to find the current session.save_path value is always to check with phpinfo() in exactly the environment where you want to find out the session storage directory.

Reason: there can be all sorts of things that change session.save_path, either by overriding the php.ini value or by setting it at runtime with ini_set('session.save_path','/path/to/folder');. For example, web server management panels like ISPConfig, Plesk etc. often adapt this to give each website its own directory with session files.

How can a Jenkins user authentication details be "passed" to a script which uses Jenkins API to create jobs?

I needed to explicitly add POST in the CURL command:

curl -X POST http://<user>:<token>@<server>/safeRestart

I also have the SafeRestart Plugin installed, in case that makes a difference.

Django values_list vs values

The best place to understand the difference is at the official documentation on values / values_list. It has many useful examples and explains it very clearly. The django docs are very user freindly.

Here's a short snippet to keep SO reviewers happy:

values

Returns a QuerySet that returns dictionaries, rather than model instances, when used as an iterable.

And read the section which follows it:

value_list

This is similar to values() except that instead of returning dictionaries, it returns tuples when iterated over.

What does the servlet <load-on-startup> value signify

As stated on other answer and this load-on-startup article zero is acceptable and in the absent of any other servlet this will take priority on loading and loaded during deployment. Best use of load-on statup is to load servlets which takes longer time to initialize well before first request come like servlets which creates connection pool or make network call or hold bulky resource, this will significantly reduce response time for first few request.

Use Device Login on Smart TV / Console

Facebook login for smarttv/devices without facebook sdk is possible throught code , check the documentation here :

https://developers.facebook.com/docs/facebook-login/for-devices

How to Import Excel file into mysql Database from PHP

You are probably having a problem with the sort of CSV file that you have.

Open the CSV file with a text editor, check that all the separations are done with the comma, and not semicolon and try the script again. It should work fine.

BadImageFormatException. This will occur when running in 64 bit mode with the 32 bit Oracle client components installed

I had the same problem in SSIS 2008. I tried to connect to an Oracle 11g using ODAC 12c 32 bit. Tried to install ODAC 12c 64 bit as well. SSIS was actually able to preview the table but when trying to run the package it was giving this error message. Nothing helped. Switched to VS 2013, now it was running in debug mode but got the same error when the running the package using dtexec /f filename. Then I found this page: http://sqlmag.com/comment/reply/17881.

To make it short it says: (if the page is still there just go to the page and follow the instrucrtions...) 1) Download and install the latest version of odac 64 bit xcopy from oracle site. 2) Download and install the latest version of odac 32 bit xcopy from oracle site. How? open a cmd shell AS AN ADMINSTARTOR and run: c:\64bitODACLocation> install.bat oledb c:\odac\odac64. the first parameter is the component you want to install. The second param is where to install to. install the 32 version as well like this: c:\32bitODACLocation> install.bat oledb c:\odac\odac32. 3) Change the path of the system to include c:\odac\odac32; c:\odac\odac32\bin; c:\odac\odac64;c:\odac\odac64\bin IN THIS ORDER. 4) Restart the machine. 5) make sure you have the same tnsnames.ora in both odac32\admin\network and odac64\admin\network folders (or at least the same entry for your connection). 6) Now open up SSIS in visual studio (I used the free 2013 version with the ssis package) - Use OLEDB and then select the Oracle Provider for OLE DB provider as your connection type. Set the name of the entry in your tnsnames.ora as the "server or file name". Username is your schema name (db name) and password is the password for schema. you are done!

Again, you can find the very detailed solution and much more in the original site.

This was the only thing which worked for me and did not mess up my environment.

Cheers! gcr

What is the difference between Eclipse for Java (EE) Developers and Eclipse Classic?

If you want to build Java EE applications, it's best to use Eclipse IDE for Java EE. It has editors from HTML to JSP/JSF, Javascript. It's rich for webapps development, and provide plugins and tools to develop Java EE applications easily (all bundled).

Eclipse Classic is basically the full featured Eclipse without the Java EE part.

Debugging in Maven?

Why not use the JPDA and attach to the launched process from a separate debugger process ? You should be able to specify the appropriate options in Maven to launch your process with the debugging hooks enabled. This article has more information.

What is the Auto-Alignment Shortcut Key in Eclipse?

Want to format it automatically when you save the file???

then Goto Window > Preferences > Java > Editor > Save Actions

and configure your save actions.

Along with saving, you can format, Organize imports,add modifier ‘final’ where possible etc

Why does my favicon not show up?

Try adding the profile attribute to your head tag and use "image/x-icon" for the type attribute:

<head profile="http://www.w3.org/2005/10/profile">
<link rel="icon" type="image/x-icon" href="img/favicon.ico">

If the above code doesn't work, try using the full icon path for the href attribute:

<head profile="http://www.w3.org/2005/10/profile">
<link rel="icon" type="image/x-icon" href="http://example.com/img/favicon.ico">

Check that a input to UITextField is numeric only

For integer test it'll be:

- (BOOL) isIntegerNumber: (NSString*)input
{
    return [input integerValue] != 0 || [input isEqualToString:@"0"];
}

How can I show and hide elements based on selected option with jQuery?

<script>  
$(document).ready(function(){
    $('#colorselector').on('change', function() {
      if ( this.value == 'red')
      {
        $("#divid").show();
      }
      else
      {
        $("#divid").hide();
      }
    });
});
</script>

Do like this for every value

How to compare only Date without Time in DateTime types in Linq to SQL with Entity Framework?

try using the Date property on the DateTime Object...

if(dtOne.Date == dtTwo.Date)
    ....

How to load image (and other assets) in Angular an project?

I fixed it. My actual image file name had spaces in it, and for whatever reason Angular did not like that. When I removed the spaces from my file name, assets/images/myimage.png worked.

How do I use a custom Serializer with Jackson?

Use @JsonValue:

public class User {
    int id;
    String name;

    @JsonValue
    public int getId() {
        return id;
    }
}

@JsonValue only works on methods so you must add the getId method. You should be able to skip your custom serializer altogether.

What is HTTP "Host" header?

The Host Header tells the webserver which virtual host to use (if set up). You can even have the same virtual host using several aliases (= domains and wildcard-domains). In this case, you still have the possibility to read that header manually in your web app if you want to provide different behavior based on different domains addressed. This is possible because in your webserver you can (and if I'm not mistaken you must) set up one vhost to be the default host. This default vhost is used whenever the host header does not match any of the configured virtual hosts.

That means: You get it right, although saying "multiple hosts" may be somewhat misleading: The host (the addressed machine) is the same, what really gets resolved to the IP address are different domain names (including subdomains) that are also referred to as hostnames (but not hosts!).


Although not part of the question, a fun fact: This specification led to problems with SSL in early days because the web server has to deliver the certificate that corresponds to the domain the client has addressed. However, in order to know what certificate to use, the webserver should have known the addressed hostname in advance. But because the client sends that information only over the encrypted channel (which means: after the certificate has already been sent), the server had to assume you browsed the default host. That meant one ssl-secured domain per IP address / port-combination.

This has been overcome with Server Name Indication; however, that again breaks some privacy, as the server name is now transferred in plain text again, so every man-in-the-middle would see which hostname you are trying to connect to.

Although the webserver would know the hostname from Server Name Indication, the Host header is not obsolete, because the Server Name Indication information is only used within the TLS handshake. With an unsecured connection, there is no Server Name Indication at all, so the Host header is still valid (and necessary).

Another fun fact: Most webservers (if not all) reject your HTTP request if it does not contain exactly one Host header, even if it could be omitted because there is only the default vhost configured. That means the minimum required information in an http-(get-)request is the first line containing METHOD RESOURCE and PROTOCOL VERSION and at least the Host header, like this:

GET /someresource.html HTTP/1.1
Host: www.example.com

In the MDN Documentation on the "Host" header they actually phrase it like this:

A Host header field must be sent in all HTTP/1.1 request messages. A 400 (Bad Request) status code will be sent to any HTTP/1.1 request message that lacks a Host header field or contains more than one.

As mentioned by Darrel Miller, the complete specs can be found in RFC7230.

SQL Server 2012 Install or add Full-text search

You can add full text to an existing instance by changing the SQL Server program in Programs and Features. Follow the steps below. You might need the original disk or ISO for the installation to complete. (Per HotN's comment: If you have SQL Server Express, make sure it is SQL Server Express With Advanced Services.)

Directions:

  1. Open the Programs and Features control panel.
  2. Select Microsoft SQL Server 2012 and click Change.
  3. When prompted to Add/Repair/Remove, select Add.
  4. Advance through the wizard until the Feature Selection screen. Then select Full-Text Search.

Step 1 Step 2

enter image description here

  1. On the Installation Type screen, select the appropriate SQL Server instance.

  2. Advance through the rest of the wizard.

Source (with screenshots): http://www.techrepublic.com/blog/networking/adding-sql-full-text-search-to-an-existing-sql-server/5546

phpMyAdmin access denied for user 'root'@'localhost' (using password: NO)

Please run and re reconfigure your phpmyadmin

sudo dpkg-reconfigure phpmyadmin

Can't connect to Postgresql on port 5432

You have to edit postgresql.conf file and change line with 'listen_addresses'.

This file you can find in the /etc/postgresql/9.3/main directory.

Default Ubuntu config have allowed only localhost (or 127.0.0.1) interface, which is sufficient for using, when every PostgreSQL client work on the same computer, as PostgreSQL server. If you want connect PostgreSQL server from other computers, you have change this config line in this way:

listen_addresses = '*'

Then you have edit pg_hba.conf file, too. In this file you have set, from which computers you can connect to this server and what method of authentication you can use. Usually you will need similar line:

host    all         all         192.168.1.0/24        md5

Please, read comments in this file...

EDIT:

After the editing postgresql.conf and pg_hba.conf you have to restart postgresql server.

EDIT2: Highlited configuration files.

Get screen width and height in Android

As an android official document said for the default display use Context#getDisplay() because this method was deprecated in API level 30.

getWindowManager().getDefaultDisplay().getMetrics(displayMetrics);

This code given below is in kotlin and is written accodring to the latest version of Android help you determine width and height:

fun getWidth(context: Context): Int {
    var width:Int = 0
    if (Build.VERSION.SDK_INT >= Build.VERSION_CODES.R) {
        val displayMetrics = DisplayMetrics()
        val display: Display? = context.getDisplay()
        display!!.getRealMetrics(displayMetrics)
        return displayMetrics.widthPixels
    }else{
        val displayMetrics = DisplayMetrics()
        this.windowManager.defaultDisplay.getMetrics(displayMetrics)
        width = displayMetrics.widthPixels
        return width
    }
}

fun getHeight(context: Context): Int {
    var height: Int = 0
    if (Build.VERSION.SDK_INT >= Build.VERSION_CODES.R) {
        val displayMetrics = DisplayMetrics()
        val display = context.display
        display!!.getRealMetrics(displayMetrics)
        return displayMetrics.heightPixels
    }else {
        val displayMetrics = DisplayMetrics()
        this.windowManager.defaultDisplay.getMetrics(displayMetrics)
        height = displayMetrics.heightPixels
        return height
    }
}

Set element width or height in Standards Mode

Try declaring the unit of width:

e1.style.width = "400px"; // width in PIXELS

Bootstrap 3 Horizontal and Vertical Divider

Do you have to use Bootstrap for this? Here's a basic HTML/CSS example for obtaining this look that doesn't use any Bootstrap:

HTML:

<div class="bottom">
    <div class="box-content right">Rich Media Ad Production</div>
    <div class="box-content right">Web Design & Development</div>
    <div class="box-content right">Mobile Apps Development</div>
    <div class="box-content">Creative Design</div>
</div>
<div>
    <div class="box-content right">Web Analytics</div>
    <div class="box-content right">Search Engine Marketing</div>
    <div class="box-content right">Social Media</div>
    <div class="box-content">Quality Assurance</div>
</div>

CSS:

.box-content {
    display: inline-block;
    width: 200px;
    padding: 10px;
}

.bottom {
    border-bottom: 1px solid #ccc;
}

.right {
    border-right: 1px solid #ccc;
}

Here is the working Fiddle.


UPDATE

If you must use Bootstrap, here is a semi-responsive example that achieves the same effect, although you may need to write a few additional media queries.

HTML:

<div class="row">
    <div class="col-xs-3">Rich Media Ad Production</div>
    <div class="col-xs-3">Web Design & Development</div>
    <div class="col-xs-3">Mobile Apps Development</div>
    <div class="col-xs-3">Creative Design</div>
</div>
<div class="row">
    <div class="col-xs-3">Web Analytics</div>
    <div class="col-xs-3">Search Engine Marketing</div>
    <div class="col-xs-3">Social Media</div>
    <div class="col-xs-3">Quality Assurance</div>
</div>

CSS:

.row:not(:last-child) {
    border-bottom: 1px solid #ccc;
}

.col-xs-3:not(:last-child) {
    border-right: 1px solid #ccc;
}

Here is another working Fiddle.

Note:

Note that you may also use the <hr> element to insert a horizontal divider in Bootstrap as well if you'd like.

Install windows service without InstallUtil.exe

I know it is a very old question, but better update it with new information.

You can install service by using sc command:

InstallService.bat:

@echo OFF
echo Stopping old service version...
net stop "[YOUR SERVICE NAME]"
echo Uninstalling old service version...
sc delete "[YOUR SERVICE NAME]"

echo Installing service...
rem DO NOT remove the space after "binpath="!
sc create "[YOUR SERVICE NAME]" binpath= "[PATH_TO_YOUR_SERVICE_EXE]" start= auto
echo Starting server complete
pause

With SC, you can do a lot more things as well: uninstalling the old service (if you already installed it before), checking if service with same name exists... even set your service to autostart.

One of many references: creating a service with sc.exe; how to pass in context parameters

I have done by both this way & InstallUtil. Personally I feel that using SC is cleaner and better for your health.

How do you install Google frameworks (Play, Accounts, etc.) on a Genymotion virtual device?

Google Apps KitKat for Genymotion.

Download the Google Apps ZIP file from the link which contain the essential Google Apps such as Play Store, Gmail, YouTube, etc.

https://www.mediafire.com/?qbbt4lhyu9q10ix

After finishing booting, drag and drop the ZIP file we downloaded named update-gapps-4-4-2-signed.zip to the Genymotion Window. It starts installing the Google Apps, and it asks for your confirmation. Confirm it.

how to query for a list<String> in jdbctemplate

To populate a List of String, you need not use custom row mapper. Implement it using queryForList.

List<String>data=jdbcTemplate.queryForList(query,String.class)

When is JavaScript synchronous?

To someone who really understands how JS works this question might seem off, however most people who use JS do not have such a deep level of insight (and don't necessarily need it) and to them this is a fairly confusing point, I will try to answer from that perspective.

JS is synchronous in the way its code is executed. each line only runs after the line before it has completed and if that line calls a function after that is complete etc...

The main point of confusion arises from the fact that your browser is able to tell JS to execute more code at anytime (similar to how you can execute more JS code on a page from the console). As an example JS has Callback functions who's purpose is to allow JS to BEHAVE asynchronously so further parts of JS can run while waiting for a JS function that has been executed (I.E. a GET call) to return back an answer, JS will continue to run until the browser has an answer at that point the event loop (browser) will execute the JS code that calls the callback function.

Since the event loop (browser) can input more JS to be executed at any point in that sense JS is asynchronous (the primary things that will cause a browser to input JS code are timeouts, callbacks and events)

I hope this is clear enough to be helpful to somebody.

Raw_Input() Is Not Defined

For Python 3.x, use input(). For Python 2.x, use raw_input(). Don't forget you can add a prompt string in your input() call to create one less print statement. input("GUESS THAT NUMBER!").

How to turn off word wrapping in HTML?

You need to use the CSS white-space attribute.

In particular, white-space: nowrap and white-space: pre are the most commonly used values. The first one seems to be what you 're after.

Remove all multiple spaces in Javascript and replace with single space

You could use a regular expression replace:

str = str.replace(/ +(?= )/g,'');

Credit: The above regex was taken from Regex to replace multiple spaces with a single space

Split comma separated column data into additional columns

If the number of fields in the CSV is constant then you could do something like this:

select a[1], a[2], a[3], a[4]
from (
    select regexp_split_to_array('a,b,c,d', ',')
) as dt(a)

For example:

=> select a[1], a[2], a[3], a[4] from (select regexp_split_to_array('a,b,c,d', ',')) as dt(a);
 a | a | a | a 
---+---+---+---
 a | b | c | d
(1 row)

If the number of fields in the CSV is not constant then you could get the maximum number of fields with something like this:

select max(array_length(regexp_split_to_array(csv, ','), 1))
from your_table

and then build the appropriate a[1], a[2], ..., a[M] column list for your query. So if the above gave you a max of 6, you'd use this:

select a[1], a[2], a[3], a[4], a[5], a[6]
from (
    select regexp_split_to_array(csv, ',')
    from your_table
) as dt(a)

You could combine those two queries into a function if you wanted.

For example, give this data (that's a NULL in the last row):

=> select * from csvs;
     csv     
-------------
 1,2,3
 1,2,3,4
 1,2,3,4,5,6

(4 rows)

=> select max(array_length(regexp_split_to_array(csv, ','), 1)) from csvs;
 max 
-----
   6
(1 row)

=> select a[1], a[2], a[3], a[4], a[5], a[6] from (select regexp_split_to_array(csv, ',') from csvs) as dt(a);
 a | a | a | a | a | a 
---+---+---+---+---+---
 1 | 2 | 3 |   |   | 
 1 | 2 | 3 | 4 |   | 
 1 | 2 | 3 | 4 | 5 | 6
   |   |   |   |   | 
(4 rows)

Since your delimiter is a simple fixed string, you could also use string_to_array instead of regexp_split_to_array:

select ...
from (
    select string_to_array(csv, ',')
    from csvs
) as dt(a);

Thanks to Michael for the reminder about this function.

You really should redesign your database schema to avoid the CSV column if at all possible. You should be using an array column or a separate table instead.

UILabel is not auto-shrinking text to fit label size

This is for Swift 3 running Xcode 8.2.1 ( 8C1002 )

The best solution that I've found is to set a fixed width in your Storyboard or IB on the label. Set your constraints with constrain to margins. In your viewDidLoad add the following lines of code:

override func viewDidLoad() {
            super.viewDidLoad()

            label.numberOfLines = 1
            label.adjustsFontSizeToFitWidth = true
            label.minimumScaleFactor = 0.5
        }

label constraints to margin

fixed width label constraints to margin

attributes inspector

This worked like a charm and it doesn't overflow to a new line and shrinks the text to fit the width of the label without any weird issues and works in Swift 3.

How do I compile a .c file on my Mac?

In 2017, this will do it:

cc myfile.c

Get skin path in Magento?

To get current skin URL use this Mage::getDesign()->getSkinUrl()

Determine if map contains a value for a key?

Check the return value of find against end.

map<int, Bar>::iterator it = m.find('2');
if ( m.end() != it ) { 
  // contains
  ...
}

get string from right hand side

I just found out that regexp_substr() is perfect for this purpose :)

My challenge is picking the right-hand 16 chars from a reference string which theoretically can be everything from 7ish to 250ish chars long. It annoys me that substr( OurReference , -16 ) returns null when length( OurReference ) < 16. (On the other hand, it's kind of logical, too, that Oracle consequently returns null whenever a call to substr() goes beyond a string's boundaries.) However, I can set a regular expression to recognise everything between 1 and 16 of any char right before the end of the string:

regexp_substr( OurReference , '.{1,16}$' )

When it comes to performance issues regarding regular expressions, I can't say which of the GREATER() solution and this one performs best. Anyone test this? Generally I've experienced that regular expressions are quite fast if they're written neat and well (as this one).

Good luck! :)

How to make a div with no content have a width?

Either use padding , height or &nbsp for width to take effect with empty div

EDIT:

Non zero min-height also works great

Comparison of C++ unit test frameworks

API Sanity Checker — test framework for C/C++ libraries:

An automatic generator of basic unit tests for a shared C/C++ library. It is able to generate reasonable (in most, but unfortunately not all, cases) input data for parameters and compose simple ("sanity" or "shallow"-quality) test cases for every function in the API through the analysis of declarations in header files.

The quality of generated tests allows to check absence of critical errors in simple use cases. The tool is able to build and execute generated tests and detect crashes (segfaults), aborts, all kinds of emitted signals, non-zero program return code and program hanging.

Unique features in comparison with CppUnit, Boost and Google Test:

  • Automatic generation of test data and input arguments (even for complex data types)
  • Modern and highly reusable specialized types instead of fixtures and templates

How do I copy items from list to list without foreach?

You could try this:

List<Int32> copy = new List<Int32>(original);

or if you're using C# 3 and .NET 3.5, with Linq, you can do this:

List<Int32> copy = original.ToList();

What is the proper way to test if a parameter is empty in a batch file?

I test with below code and it is fine.

@echo off

set varEmpty=
if not "%varEmpty%"=="" (
    echo varEmpty is not empty
) else (
    echo varEmpty is empty
)
set varNotEmpty=hasValue
if not "%varNotEmpty%"=="" (
    echo varNotEmpty is not empty
) else (
    echo varNotEmpty is empty
)

PHP Constants Containing Arrays?

if you're using PHP 7 & 7+, you can use fetch like this as well

define('TEAM', ['guy', 'development team']);
echo TEAM[0]; 
// output from system will be "guy"

Laravel - Pass more than one variable to view

This Answer seems to be

bit helpful while declaring the large numbe of variable in the function

Laravel 5.7.*

For Example

public function index()
{
    $activePost = Post::where('status','=','active')->get()->count();

    $inActivePost = Post::where('status','=','inactive')->get()->count();

    $yesterdayPostActive = Post::whereDate('created_at', Carbon::now()->addDay(-1))->get()->count();

    $todayPostActive = Post::whereDate('created_at', Carbon::now()->addDay(0))->get()->count();

    return view('dashboard.index')->with('activePost',$activePost)->with('inActivePost',$inActivePost )->with('yesterdayPostActive',$yesterdayPostActive )->with('todayPostActive',$todayPostActive );
}

When you see the last line of the returns it not looking good

When You Project is Getting Larger its not good

So

public function index()
    {
        $activePost = Post::where('status','=','active')->get()->count();

        $inActivePost = Post::where('status','=','inactive')->get()->count();

        $yesterdayPostActive = Post::whereDate('created_at', Carbon::now()->addDay(-1))->get()->count();

        $todayPostActive = Post::whereDate('created_at', Carbon::now()->addDay(0))->get()->count();

        $viewShareVars = ['activePost','inActivePost','yesterdayPostActive','todayPostActive'];

        return view('dashboard.index',compact($viewShareVars));
    }

As You see all the variables as declared as array of $viewShareVars and Accessed in View

But My Function Becomes very Larger so i have decided to make the line as very simple

public function index()
    {
        $activePost = Post::where('status','=','active')->get()->count();

        $inActivePost = Post::where('status','=','inactive')->get()->count();

        $yesterdayPostActive = Post::whereDate('created_at', Carbon::now()->addDay(-1))->get()->count();

        $todayPostActive = Post::whereDate('created_at', Carbon::now()->addDay(0))->get()->count();

        $viewShareVars = array_keys(get_defined_vars());

        return view('dashboard.index',compact($viewShareVars));
    }

the native php function get_defined_vars() get all the defined variables from the function

and array_keys will grab the variable names

so in your view you can access all the declared variable inside the function

as {{$todayPostActive}}

How to respond with HTTP 400 error in a Spring MVC @ResponseBody method returning String?

I would change the implementation slightly:

First, I create a UnknownMatchException:

@ResponseStatus(HttpStatus.NOT_FOUND)
public class UnknownMatchException extends RuntimeException {
    public UnknownMatchException(String matchId) {
        super("Unknown match: " + matchId);
    }
}

Note the use of @ResponseStatus, which will be recognized by Spring's ResponseStatusExceptionResolver. If the exception is thrown, it will create a response with the corresponding response status. (I also took the liberty of changing the status code to 404 - Not Found which I find more appropriate for this use case, but you can stick to HttpStatus.BAD_REQUEST if you like.)


Next, I would change the MatchService to have the following signature:

interface MatchService {
    public Match findMatch(String matchId);
}

Finally, I would update the controller and delegate to Spring's MappingJackson2HttpMessageConverter to handle the JSON serialization automatically (it is added by default if you add Jackson to the classpath and add either @EnableWebMvc or <mvc:annotation-driven /> to your config, see the reference docs):

@RequestMapping(value = "/matches/{matchId}", produces = MediaType.APPLICATION_JSON_VALUE)
@ResponseBody
public Match match(@PathVariable String matchId) {
    // throws an UnknownMatchException if the matchId is not known 
    return matchService.findMatch(matchId);
}

Note, it is very common to separate the domain objects from the view objects or DTO objects. This can easily be achieved by adding a small DTO factory that returns the serializable JSON object:

@RequestMapping(value = "/matches/{matchId}", produces = MediaType.APPLICATION_JSON_VALUE)
@ResponseBody
public MatchDTO match(@PathVariable String matchId) {
    Match match = matchService.findMatch(matchId);
    return MatchDtoFactory.createDTO(match);
}

Python Remove last char from string and return it

The precise wording of the question makes me think it's impossible.

return to me means you have a function, which you have passed a string as a parameter.

You cannot change this parameter. Assigning to it will only change the value of the parameter within the function, not the passed in string. E.g.

>>> def removeAndReturnLastCharacter(a):
        c = a[-1]
        a = a[:-1]
        return c

>>> b = "Hello, Gaukler!"
>>> removeAndReturnLastCharacter(b)
!

>>> b    # b has not been changed
Hello, Gaukler!

Evaluate expression given as a string

Sorry but I don't understand why too many people even think a string was something that could be evaluated. You must change your mindset, really. Forget all connections between strings on one side and expressions, calls, evaluation on the other side.

The (possibly) only connection is via parse(text = ....) and all good R programmers should know that this is rarely an efficient or safe means to construct expressions (or calls). Rather learn more about substitute(), quote(), and possibly the power of using do.call(substitute, ......).

fortunes::fortune("answer is parse")
# If the answer is parse() you should usually rethink the question.
#    -- Thomas Lumley
#       R-help (February 2005)

Dec.2017: Ok, here is an example (in comments, there's no nice formatting):

q5 <- quote(5+5)
str(q5)
# language 5 + 5

e5 <- expression(5+5)
str(e5)
# expression(5 + 5)

and if you get more experienced you'll learn that q5 is a "call" whereas e5 is an "expression", and even that e5[[1]] is identical to q5:

identical(q5, e5[[1]])
# [1] TRUE

ORA-12514 TNS:listener does not currently know of service requested in connect descriptor

I had this issue and the fix was to make sure in tnsnames.ora the SERVICE_NAME is a valid service name in your database. To find out valid service names, you can use the following query in oracle:

select value from v$parameter where name='service_names'

Once I updated tnsnames.ora to:

TEST =
   (DESCRIPTION =
    (ADDRESS_LIST =
      (ADDRESS = (PROTOCOL = TCP)(HOST = *<validhost>*)(PORT = *<validport>*))
    )
    (CONNECT_DATA =
      (SERVER = DEDICATED)
      (SERVICE_NAME = *<servicenamefromDB>*)
    )
)

then I ran:

sqlplus user@TEST

Success! The listener is basically telling you that whatever service_name you are using isn't a valid service according to the DB.

(*I was running sqlplus from Win7 client workstation to remote DB and blame the DBAs ;) *)

Sending a JSON HTTP POST request from Android

try some thing like blow:

SString otherParametersUrServiceNeed =  "Company=acompany&Lng=test&MainPeriod=test&UserID=123&CourseDate=8:10:10";
String request = "http://android.schoolportal.gr/Service.svc/SaveValues";

URL url = new URL(request); 
HttpURLConnection connection = (HttpURLConnection) url.openConnection();   
connection.setDoOutput(true);
connection.setDoInput(true);
connection.setInstanceFollowRedirects(false); 
connection.setRequestMethod("POST"); 
connection.setRequestProperty("Content-Type", "application/x-www-form-urlencoded"); 
connection.setRequestProperty("charset", "utf-8");
connection.setRequestProperty("Content-Length", "" + Integer.toString(otherParametersUrServiceNeed.getBytes().length));
connection.setUseCaches (false);

DataOutputStream wr = new DataOutputStream(connection.getOutputStream ());
wr.writeBytes(otherParametersUrServiceNeed);

   JSONObject jsonParam = new JSONObject();
jsonParam.put("ID", "25");
jsonParam.put("description", "Real");
jsonParam.put("enable", "true");

wr.writeBytes(jsonParam.toString());

wr.flush();
wr.close();

References :

  1. http://www.xyzws.com/Javafaq/how-to-use-httpurlconnection-post-data-to-web-server/139
  2. Java - sending HTTP parameters via POST method easily

Angular 2 optional route parameter

It's recommended to use a query parameter when the information is optional.

Route Parameters or Query Parameters?

There is no hard-and-fast rule. In general,

prefer a route parameter when

  • the value is required.
  • the value is necessary to distinguish one route path from another.

prefer a query parameter when

  • the value is optional.
  • the value is complex and/or multi-variate.

from https://angular.io/guide/router#optional-route-parameters

You just need to take out the parameter from the route path.

@RouteConfig([
{
    path: '/user/',
    component: User,
    as: 'User'
}])

How to remove focus without setting focus to another control?

Try the following (calling clearAllEditTextFocuses();)

private final boolean clearAllEditTextFocuses() {
    View v = getCurrentFocus();
    if(v instanceof EditText) {
        final FocusedEditTextItems list = new FocusedEditTextItems();
        list.addAndClearFocus((EditText) v);

        //Focus von allen EditTexten entfernen
        boolean repeat = true;
        do {
            v = getCurrentFocus();
            if(v instanceof EditText) {
                if(list.containsView(v))
                    repeat = false;
                else list.addAndClearFocus((EditText) v);
            } else repeat = false;
        } while(repeat);

        final boolean result = !(v instanceof EditText);
        //Focus wieder setzen
        list.reset();
        return result;
    } else return false;
}

private final static class FocusedEditTextItem {

    private final boolean focusable;

    private final boolean focusableInTouchMode;

    @NonNull
    private final EditText editText;

    private FocusedEditTextItem(final @NonNull EditText v) {
        editText = v;
        focusable = v.isFocusable();
        focusableInTouchMode = v.isFocusableInTouchMode();
    }

    private final void clearFocus() {
        if(focusable)
            editText.setFocusable(false);
        if(focusableInTouchMode)
            editText.setFocusableInTouchMode(false);
        editText.clearFocus();
    }

    private final void reset() {
        if(focusable)
            editText.setFocusable(true);
        if(focusableInTouchMode)
            editText.setFocusableInTouchMode(true);
    }

}

private final static class FocusedEditTextItems extends ArrayList<FocusedEditTextItem> {

    private final void addAndClearFocus(final @NonNull EditText v) {
        final FocusedEditTextItem item = new FocusedEditTextItem(v);
        add(item);
        item.clearFocus();
    }

    private final boolean containsView(final @NonNull View v) {
        boolean result = false;
        for(FocusedEditTextItem item: this) {
            if(item.editText == v) {
                result = true;
                break;
            }
        }
        return result;
    }

    private final void reset() {
        for(FocusedEditTextItem item: this)
            item.reset();
    }

}

How to get the name of a class without the package?

If using a StackTraceElement, use:

String fullClassName = stackTraceElement.getClassName();
String simpleClassName = fullClassName.substring(fullClassName.lastIndexOf('.') + 1);

System.out.println(simpleClassName);

iPhone is not available. Please reconnect the device

Whenever this error occurs, either your Xcode version or iPhone version isn't working together. You will have to update one or the either or both.

2020 Update: Xcode: 12 Beta for iOS 14

Convert long/lat to pixel x/y on a given picture

my approach works without a library and with cropped maps. Means it works with just parts from a Mercator image. Maybe it helps somebody: https://stackoverflow.com/a/10401734/730823

How to get scrollbar position with Javascript?

document.getScroll = function() {
    if (window.pageYOffset != undefined) {
        return [pageXOffset, pageYOffset];
    } else {
        var sx, sy, d = document,
            r = d.documentElement,
            b = d.body;
        sx = r.scrollLeft || b.scrollLeft || 0;
        sy = r.scrollTop || b.scrollTop || 0;
        return [sx, sy];
    }
}

returns an array with two integers- [scrollLeft, scrollTop]

How to force a SQL Server 2008 database to go Offline

Go offline

USE master
GO
ALTER DATABASE YourDatabaseName
SET OFFLINE WITH ROLLBACK IMMEDIATE
GO

Go online

USE master
GO
ALTER DATABASE YourDatabaseName
SET ONLINE
GO

How to do SELECT MAX in Django?

See this. Your code would be something like the following:

from django.db.models import Max
# Generates a "SELECT MAX..." query
Argument.objects.aggregate(Max('rating')) # {'rating__max': 5}

You can also use this on existing querysets:

from django.db.models import Max
args = Argument.objects.filter(name='foo') # or whatever arbitrary queryset
args.aggregate(Max('rating')) # {'rating__max': 5}

If you need the model instance that contains this max value, then the code you posted is probably the best way to do it:

arg = args.order_by('-rating')[0]

Note that this will error if the queryset is empty, i.e. if no arguments match the query (because the [0] part will raise an IndexError). If you want to avoid that behavior and instead simply return None in that case, use .first():

arg = args.order_by('-rating').first() # may return None

How do I stretch a background image to cover the entire HTML element?

Not sure that stretching a background image is possible. If you find that it's not possible, or not reliable in all of your target browsers, you could try using a stretched img tag with z-index set lower, and position set to absolute so that other content appears on top of it.

Let us know what you end up doing.

Edit: What I suggested is basically what's in gabriel's link. So try that :)

img src SVG changing the styles with CSS

If you are just switching the image between the real color and the black-and-white, you can set one selector as:

{filter:none;}

and another as:

{filter:grayscale(100%);}

java.lang.RuntimeException: Unable to start activity ComponentInfo

I had the same issue, I cleaned and rebuilt the project and it worked.

MVC 5 Access Claims Identity User Data

Remember that in order to query the IEnumerable you need to reference system.linq.
It will give you the extension object needed to do:

CaimsList.FirstOrDefault(x=>x.Type =="variableName").toString();

What's the best way to determine the location of the current PowerShell script?

PowerShell 3+

# This is an automatic variable set to the current file's/module's directory
$PSScriptRoot

PowerShell 2

Prior to PowerShell 3, there was not a better way than querying the MyInvocation.MyCommand.Definition property for general scripts. I had the following line at the top of essentially every PowerShell script I had:

$scriptPath = split-path -parent $MyInvocation.MyCommand.Definition

Parsing jQuery AJAX response

Use parseJSON. Look at the doc

var obj = $.parseJSON(data);

Something like this:

$.ajax({     
    type: "POST",
    url: '/admin/systemgoalssystemgoalupdate?format=html',
    data: formdata,
    success: function (data) {

        console.log($.parseJSON(data)); //will log Object

    }
});

Do HTTP POST methods send data as a QueryString?

If your post try to reach the following URL

mypage.php?id=1

you will have the POST data but also GET data.

Multiple types were found that match the controller named 'Home'

If it could help other, I've also face this error. The problem was cause by on incorrect reference in me web site. For unknown reason my web site was referring another web site, in the same solution. And once I remove that bad reference, thing began to work properly.

RuntimeError: module compiled against API version a but this version of numpy is 9

Check the path

import numpy
print numpy.__path__

For me this was /System/Library/Frameworks/Python.framework/Versions/2.7/Extras/lib/python/numpy So I moved it to a temporary place

sudo mv /System/Library/Frameworks/Python.framework/Versions/2.7/Extras/lib/python/numpy \
/System/Library/Frameworks/Python.framework/Versions/2.7/Extras/lib/python/numpy_old

and then the next time I imported numpy the path was /Library/Python/2.7/site-packages/numpy/init.pyc and all was well.

Fatal error: Can't open and lock privilege tables: Table 'mysql.host' doesn't exist

My case on Ubuntu 14.04.2 LTS was similar to others with my.cnf, but for me the cause was a ~/.my.cnf that was leftover from a previous installation. After deleting that file and purging/re-installing mysql-server, it worked fine.

How to filter for multiple criteria in Excel?

You can pass an array as the first AutoFilter argument and use the xlFilterValues operator.

This will display PDF, DOC and DOCX filetypes.

Criteria1:=Array(".pdf", ".doc", ".docx"), Operator:=xlFilterValues

CSS: how to add white space before element's content?

Since you are looking for adding space between elements you may need something as simple as a margin-left or padding-left. Here are examples of both http://jsfiddle.net/BGHqn/3/

This will add 10 pixels to the left of the paragraph element

p {
    margin-left: 10px;
 }

or if you just want some padding within your paragraph element

p {
    padding-left: 10px;
}

Any tools to generate an XSD schema from an XML instance document?

the Microsoft XSD inference tool is a good, free solution. Many XML editing tools, such as XmlSpy (mentioned by @Garth Gilmour) or OxygenXML Editor also have that feature. They're rather expensive, though. BizTalk Server also has an XSD inferring tool as well.

edit: I just discovered the .net XmlSchemaInference class, so if you're using .net you should consider that

Moment.js - tomorrow, today and yesterday

In Moment.js, the from() method has the daily precision you're looking for:

var today = new Date();
var tomorrow = new Date();
var yesterday = new Date();
tomorrow.setDate(today.getDate()+1);
yesterday.setDate(today.getDate()-1);

moment(today).from(moment(yesterday)); // "in a day"
moment(today).from(moment(tomorrow)); // "a day ago" 

moment(yesterday).from(moment(tomorrow)); // "2 days ago" 
moment(tomorrow).from(moment(yesterday)); // "in 2 days"

How to modify a CSS display property from JavaScript?

I found the solution.

As said in the EDIT of my answer, a <div> is misfunctioning in a <table>. So I wrote this code instead :

<tr id="hidden" style="display:none;">
    <td class="depot_table_left">
        <label for="sexe">Sexe</label>
    </td>
    <td>
        <select type="text" name="sexe">
            <option value="1">Sexe</option>
            <option value="2">Joueur</option>
            <option value="3">Joueuse</option>
        </select>
    </td>
</tr>

And this is working fine.

Thanks everybody ;)

Node / Express: EADDRINUSE, Address already in use - Kill server

delete undefined file in your project root directory (which created on app crash)

Do Swift-based applications work on OS X 10.9/iOS 7 and lower?

Try the following code:

It's working without StoryBoard:

func application(application: UIApplication, didFinishLaunchingWithOptions launchOptions: NSDictionary?) -> Bool {
    self.window = UIWindow(frame: UIScreen.mainScreen().bounds)
    self.window!.backgroundColor = UIColor.whiteColor()

    // Create a nav/vc pair using the custom ViewController class

    let nav = UINavigationController()
    let vc = ViewController(nibName: "ViewController", bundle: nil)

    // Push the vc onto the nav
    nav.pushViewController(vc, animated: false)

    // Set the window’s root view controller
    self.window!.rootViewController = nav

    // Present the window
    self.window!.makeKeyAndVisible()
    return true
}

Visual Studio error "Object reference not set to an instance of an object" after install of ASP.NET and Web Tools 2015

The solution to the issue when i had this earlier today was that there was an additional set of tags bolted on the end of my Web.config. Once removed the functionality returned.

How do we download a blob url video

  1. Find the playlist/manifest with the developer tools network tab. There is always one, as that's how it works. It might have a m3u8 extension that you can type into the Filter. (The youtube-dl tool can also find the m3u8 tool automatically some time give it direct link to the webpage where the video is being displayed.)

  2. Give it to the youtube-dl tool (Download) . It can download much more than just YouTube. It'll auto-download each segment then combine everything with FFmpeg then discard the parts. There is a good chance it supports the site you want to download from natively, and you don't even need to do step #1.

  3. If you find a site that is stubborn and you run into 403 errors... Telerik Fiddler to the rescue. It can catch and save anything transmitted (such as the video file) as it acts as a local proxy. Everything you see/hear can be downloaded, unless it's DRM content like Spotify.

Note: in windows, you can use youtube-dl.exe using "Command Prompt" or creating a batch file. i.e

d:\youtube-dl.exe https://www.youtube.com/watch?v=gbdFOwKHil0

Thanks

How can I disable editing cells in a WPF Datagrid?

The WPF DataGrid has an IsReadOnly property that you can set to True to ensure that users cannot edit your DataGrid's cells.

You can also set this value for individual columns in your DataGrid as needed.

File.Move Does Not Work - File Already Exists

If you don't have the option to delete the already existing file in the new location, but still need to move and delete from the original location, this renaming trick might work:

string newFileLocation = @"c:\test\Test\SomeFile.txt";

while (File.Exists(newFileLocation)) {
    newFileLocation = newFileLocation.Split('.')[0] + "_copy." + newFileLocation.Split('.')[1];
}
File.Move(@"c:\test\SomeFile.txt", newFileLocation);

This assumes the only '.' in the file name is before the extension. It splits the file in two before the extension, attaches "_copy." in between. This lets you move the file, but creates a copy if the file already exists or a copy of the copy already exists, or a copy of the copy of the copy exists... ;)

Git diff --name-only and copy that list

No-one has mentioned cpio which is easy to type, creates hard links and handles spaces in filenames:

git diff --name-only $from..$to  | cpio -pld outdir

Convenient way to parse incoming multipart/form-data parameters in a Servlet

Not always there's a servlet before of an upload (I could use a filter for example). Or could be that the same controller ( again a filter or also a servelt ) can serve many actions, so I think that rely on that servlet configuration to use the getPart method (only for Servlet API >= 3.0), I don't know, I don't like.

In general, I prefer independent solutions, able to live alone, and in this case http://commons.apache.org/proper/commons-fileupload/ is one of that.

List<FileItem> multiparts = new ServletFileUpload(new DiskFileItemFactory()).parseRequest(request);
    for (FileItem item : multiparts) {
        if (!item.isFormField()) {
            //your operations on file
        } else {
            String name = item.getFieldName();
            String value = item.getString();
            //you operations on paramters
        }
}

Find current directory and file's directory

If you are trying to find the current directory of the file you are currently in:

OS agnostic way:

dirname, filename = os.path.split(os.path.abspath(__file__))

Width of input type=text element

input width is 10 + 2 times 1 px for border

executing a function in sql plus

One option would be:

SET SERVEROUTPUT ON

EXEC DBMS_OUTPUT.PUT_LINE(your_fn_name(your_fn_arguments));

How To: Best way to draw table in console app (C#)

Edit: thanks to @superlogical, you can now find and improve the following code in github!


I wrote this class based on some ideas here. The columns width is optimal, an it can handle object arrays with this simple API:

static void Main(string[] args)
{
  IEnumerable<Tuple<int, string, string>> authors =
    new[]
    {
      Tuple.Create(1, "Isaac", "Asimov"),
      Tuple.Create(2, "Robert", "Heinlein"),
      Tuple.Create(3, "Frank", "Herbert"),
      Tuple.Create(4, "Aldous", "Huxley"),
    };

  Console.WriteLine(authors.ToStringTable(
    new[] {"Id", "First Name", "Surname"},
    a => a.Item1, a => a.Item2, a => a.Item3));

  /* Result:        
  | Id | First Name | Surname  |
  |----------------------------|
  | 1  | Isaac      | Asimov   |
  | 2  | Robert     | Heinlein |
  | 3  | Frank      | Herbert  |
  | 4  | Aldous     | Huxley   |
  */
}

Here is the class:

public static class TableParser
{
  public static string ToStringTable<T>(
    this IEnumerable<T> values,
    string[] columnHeaders,
    params Func<T, object>[] valueSelectors)
  {
    return ToStringTable(values.ToArray(), columnHeaders, valueSelectors);
  }

  public static string ToStringTable<T>(
    this T[] values,
    string[] columnHeaders,
    params Func<T, object>[] valueSelectors)
  {
    Debug.Assert(columnHeaders.Length == valueSelectors.Length);

    var arrValues = new string[values.Length + 1, valueSelectors.Length];

    // Fill headers
    for (int colIndex = 0; colIndex < arrValues.GetLength(1); colIndex++)
    {
      arrValues[0, colIndex] = columnHeaders[colIndex];
    }

    // Fill table rows
    for (int rowIndex = 1; rowIndex < arrValues.GetLength(0); rowIndex++)
    {
      for (int colIndex = 0; colIndex < arrValues.GetLength(1); colIndex++)
      {
        arrValues[rowIndex, colIndex] = valueSelectors[colIndex]
          .Invoke(values[rowIndex - 1]).ToString();
      }
    }

    return ToStringTable(arrValues);
  }

  public static string ToStringTable(this string[,] arrValues)
  {
    int[] maxColumnsWidth = GetMaxColumnsWidth(arrValues);
    var headerSpliter = new string('-', maxColumnsWidth.Sum(i => i + 3) - 1);

    var sb = new StringBuilder();
    for (int rowIndex = 0; rowIndex < arrValues.GetLength(0); rowIndex++)
    {
      for (int colIndex = 0; colIndex < arrValues.GetLength(1); colIndex++)
      {
        // Print cell
        string cell = arrValues[rowIndex, colIndex];
        cell = cell.PadRight(maxColumnsWidth[colIndex]);
        sb.Append(" | ");
        sb.Append(cell);
      }

      // Print end of line
      sb.Append(" | ");
      sb.AppendLine();

      // Print splitter
      if (rowIndex == 0)
      {
        sb.AppendFormat(" |{0}| ", headerSpliter);
        sb.AppendLine();
      }
    }

    return sb.ToString();
  }

  private static int[] GetMaxColumnsWidth(string[,] arrValues)
  {
    var maxColumnsWidth = new int[arrValues.GetLength(1)];
    for (int colIndex = 0; colIndex < arrValues.GetLength(1); colIndex++)
    {
      for (int rowIndex = 0; rowIndex < arrValues.GetLength(0); rowIndex++)
      {
        int newLength = arrValues[rowIndex, colIndex].Length;
        int oldLength = maxColumnsWidth[colIndex];

        if (newLength > oldLength)
        {
          maxColumnsWidth[colIndex] = newLength;
        }
      }
    }

    return maxColumnsWidth;
  }
}

Edit: I added a minor improvement - if you want the column headers to be the property name, add the following method to TableParser (note that it will be a bit slower due to reflection):

public static string ToStringTable<T>(
    this IEnumerable<T> values,
    params Expression<Func<T, object>>[] valueSelectors)
{
  var headers = valueSelectors.Select(func => GetProperty(func).Name).ToArray();
  var selectors = valueSelectors.Select(exp => exp.Compile()).ToArray();
  return ToStringTable(values, headers, selectors);
}

private static PropertyInfo GetProperty<T>(Expression<Func<T, object>> expresstion)
{
  if (expresstion.Body is UnaryExpression)
  {
    if ((expresstion.Body as UnaryExpression).Operand is MemberExpression)
    {
      return ((expresstion.Body as UnaryExpression).Operand as MemberExpression).Member as PropertyInfo;
    }
  }

  if ((expresstion.Body is MemberExpression))
  {
    return (expresstion.Body as MemberExpression).Member as PropertyInfo;
  }
  return null;
}

jQuery Dialog Box

If you need to use multiple dialog boxes on one page and open, close and reopen them the following works well:

 JS CODE:
    $(".sectionHelp").click(function(){
        $("#dialog_"+$(this).attr('id')).dialog({autoOpen: false});
        $("#dialog_"+$(this).attr('id')).dialog("open");
    });

 HTML: 
    <div class="dialog" id="dialog_help1" title="Dialog Title 1">
        <p>Dialog 1</p>
    </div>
    <div class="dialog" id="dialog_help2" title="Dialog Title 2">
        <p>Dialog 2 </p>
    </div>

    <a href="#" id="help1" class="sectionHelp"></a>
    <a href="#" id="help2" class="sectionHelp"></a>

 CSS:
    div.dialog{
      display:none;
    }

Oracle's default date format is YYYY-MM-DD, WHY?

If you are using this query to generate an input file for your Data Warehouse, then you need to format the data appropriately. Essentially in that case you are converting the date (which does have a time component) to a string. You need to explicitly format your string or change your nls_date_format to set the default. In your query you could simply do:

select to_char(some_date, 'yyyy-mm-dd hh24:mi:ss') my_date
  from some_table;

warning: incompatible implicit declaration of built-in function ‘xyz’

Here is some C code that produces the above mentioned error:

int main(int argc, char **argv) {
  exit(1);
}

Compiled like this on Fedora 17 Linux 64 bit with gcc:

el@defiant ~/foo2 $ gcc -o n n2.c                                                               
n2.c: In function ‘main’:
n2.c:2:3: warning: incompatible implicit declaration of built-in 
function ‘exit’ [enabled by default]
el@defiant ~/foo2 $ ./n 
el@defiant ~/foo2 $ 

To make the warning go away, add this declaration to the top of the file:

#include <stdlib.h>

Which is fastest? SELECT SQL_CALC_FOUND_ROWS FROM `table`, or SELECT COUNT(*)

MySQL has started deprecating SQL_CALC_FOUND_ROWS functionality with version 8.0.17 onwards.

So, it is always preferred to consider executing your query with LIMIT, and then a second query with COUNT(*) and without LIMIT to determine whether there are additional rows.

From docs:

The SQL_CALC_FOUND_ROWS query modifier and accompanying FOUND_ROWS() function are deprecated as of MySQL 8.0.17 and will be removed in a future MySQL version.

COUNT(*) is subject to certain optimizations. SQL_CALC_FOUND_ROWS causes some optimizations to be disabled.

Use these queries instead:

SELECT * FROM tbl_name WHERE id > 100 LIMIT 10;
SELECT COUNT(*) WHERE id > 100;

Also, SQL_CALC_FOUND_ROWS has been observed to having more issues generally, as explained in the MySQL WL# 12615 :

SQL_CALC_FOUND_ROWS has a number of problems. First of all, it's slow. Frequently, it would be cheaper to run the query with LIMIT and then a separate SELECT COUNT() for the same query, since COUNT() can make use of optimizations that can't be done when searching for the entire result set (e.g. filesort can be skipped for COUNT(*), whereas with CALC_FOUND_ROWS, we must disable some filesort optimizations to guarantee the right result)

More importantly, it has very unclear semantics in a number of situations. In particular, when a query has multiple query blocks (e.g. with UNION), there's simply no way to calculate the number of “would-have-been” rows at the same time as producing a valid query. As the iterator executor is progressing towards these kinds of queries, it is genuinely difficult to try to retain the same semantics. Furthermore, if there are multiple LIMITs in the query (e.g. for derived tables), it's not necessarily clear to which of them SQL_CALC_FOUND_ROWS should refer to. Thus, such nontrivial queries will necessarily get different semantics in the iterator executor compared to what they had before.

Finally, most of the use cases where SQL_CALC_FOUND_ROWS would seem useful should simply be solved by other mechanisms than LIMIT/OFFSET. E.g., a phone book should be paginated by letter (both in terms of UX and in terms of index use), not by record number. Discussions are increasingly infinite-scroll ordered by date (again allowing index use), not by paginated by post number. And so on.

Compiling with g++ using multiple cores

You can do this with make - with gnu make it is the -j flag (this will also help on a uniprocessor machine).

For example if you want 4 parallel jobs from make:

make -j 4

You can also run gcc in a pipe with

gcc -pipe

This will pipeline the compile stages, which will also help keep the cores busy.

If you have additional machines available too, you might check out distcc, which will farm compiles out to those as well.

std::string formatting like sprintf

I wrote my own using vsnprintf so it returns string instead of having to create my own buffer.

#include <string>
#include <cstdarg>

//missing string printf
//this is safe and convenient but not exactly efficient
inline std::string format(const char* fmt, ...){
    int size = 512;
    char* buffer = 0;
    buffer = new char[size];
    va_list vl;
    va_start(vl, fmt);
    int nsize = vsnprintf(buffer, size, fmt, vl);
    if(size<=nsize){ //fail delete buffer and try again
        delete[] buffer;
        buffer = 0;
        buffer = new char[nsize+1]; //+1 for /0
        nsize = vsnprintf(buffer, size, fmt, vl);
    }
    std::string ret(buffer);
    va_end(vl);
    delete[] buffer;
    return ret;
}

So you can use it like

std::string mystr = format("%s %d %10.5f", "omg", 1, 10.5);

#pragma mark in Swift?

Official Documentation

Apple's official document about Xcode Jump Bar: Add code annotations to the jump bar

Jump Bar Screenshots for Sample Code

Sample Code

Behavior in Xcode 10.1 and macOS 10.14.3 (Mojave)

Xcode 10.1 and macOS 10.14.3

Behavior in Xcode 10.0 and macOS 10.13.4 (High Sierra)

Xcode 10.0 and macOS 10.13.4

Behavior in Xcode 9.4.1 and macOS 10.13.0

Xcode 9.4.1 and macOS 10.13.0

Discussion

!!!: and ???: sometimes are not able to be displayed.

Extract directory path and filename

You can simply do:

base=$(basename "$fspec")

How to configure robots.txt to allow everything?

That file will allow all crawlers access

User-agent: *
Allow: /

This basically allows all user agents (the *) to all parts of the site (the /).

Data binding in React

This could be achieved with a hook. However, I would not recommend it, as it strictly couples state and layout.

November 2019 Data Bind with Hooks

const useInput = (placeholder, initial) => {
    const [value, setVal] = useState(initial)
    const onChange = (e) => setVal(e.target.value)
    const element = <input value={value} onChange={onChange} placeholder={placeholder}/>
    return {element, value}
}

Use it in any functional component

const BensPlayGround = () => {
    const name = useInput("Enter name here")
    return (
        <>
            {name.element}
            <h1>Hello {name.value}</h1>
        </>
    )
}

Basic version - bind value and onChange

const useDataBind = () => {
    const [value, setVal] = useState("")
    const onChange = (e) => setVal(e.target.value)
    return {value, onChange}
}

const Demo = (props) => {
    const nameProps = useDataBind()
    return (
        <>
            <input {...nameProps} placeholder="Enter name here" />
            <h1>Hello {nameProps.value}</h1>
        </>
    )
}

How do I get the directory that a program is running from?

Maybe concatenate the current working directory with argv[0]? I'm not sure if that would work in Windows but it works in linux.

For example:

#include <stdio.h>
#include <unistd.h>
#include <string.h>

int main(int argc, char **argv) {
    char the_path[256];

    getcwd(the_path, 255);
    strcat(the_path, "/");
    strcat(the_path, argv[0]);

    printf("%s\n", the_path);

    return 0;
}

When run, it outputs:

jeremy@jeremy-desktop:~/Desktop$ ./test
/home/jeremy/Desktop/./test

Pagination response payload from a RESTful API

just add in your backend API new property's into response body. from example .net core:

[Authorize]
[HttpGet]
public async Task<IActionResult> GetUsers([FromQuery]UserParams userParams)
{
  var users = await _repo.GetUsers(userParams);
  var usersToReturn = _mapper.Map<IEnumerable<UserForListDto>>(users);


  // create new object and add into it total count param etc
  var UsersListResult = new
  {
    usersToReturn,
    currentPage = users.CurrentPage,
    pageSize = users.PageSize,
    totalCount = users.TotalCount,
    totalPages = users.TotalPages
  };

  return Ok(UsersListResult);
}

In body response it look like this

{
"usersToReturn": [
    {
        "userId": 1,
        "username": "[email protected]",
        "firstName": "Joann",
        "lastName": "Wilson",
        "city": "Armstrong",
        "phoneNumber": "+1 (893) 515-2172"
    },
    {
        "userId": 2,
        "username": "[email protected]",
        "firstName": "Booth",
        "lastName": "Drake",
        "city": "Franks",
        "phoneNumber": "+1 (800) 493-2168"
    }
],
// metadata to pars in client side
"currentPage": 1,
"pageSize": 2,
"totalCount": 87,
"totalPages": 44

}

Encrypting & Decrypting a String in C#

If you need to store a password in memory and would like to have it encrypted you should use SecureString:

http://msdn.microsoft.com/en-us/library/system.security.securestring.aspx

For more general uses I would use a FIPS approved algorithm such as Advanced Encryption Standard, formerly known as Rijndael. See this page for an implementation example:

http://msdn.microsoft.com/en-us/library/system.security.cryptography.rijndael.aspx

How to sort multidimensional array by column?

Yes. The sorted built-in accepts a key argument:

sorted(li,key=lambda x: x[1])
Out[31]: [['Jason', 1], ['John', 2], ['Jim', 9]]

note that sorted returns a new list. If you want to sort in-place, use the .sort method of your list (which also, conveniently, accepts a key argument).

or alternatively,

from operator import itemgetter
sorted(li,key=itemgetter(1))
Out[33]: [['Jason', 1], ['John', 2], ['Jim', 9]]

Read more on the python wiki.

Thymeleaf using path variables to th:href

I think you can try this:

<a th:href="${'/category/edit/' + {category.id}}">view</a>

Or if you have "idCategory" this:

<a th:href="${'/category/edit/' + {category.idCategory}}">view</a>

MySQL Sum() multiple columns

You could change the database structure such that all subject rows become a column variable (like spreadsheet). This makes such analysis much easier

Creating a thumbnail from an uploaded image

function getExtension($str) 
    {

          $i = strrpos($str,".");
         if (!$i) { return ""; } 

         $l = strlen($str) - $i;
         $ext = substr($str,$i+1,$l);
         return $ext;
    }

$valid_formats = array("jpg", "png", "gif", "bmp","jpeg","PNG","JPG","JPEG","GIF","BMP");
if(isset($_POST) and $_SERVER['REQUEST_METHOD'] == "POST")
    {
        $name = $_FILES['photoimg']['name'];
        $size = $_FILES['photoimg']['size'];

        if(strlen($name))
            {
                 $ext = getExtension($name);
                if(in_array($ext,$valid_formats))
                {
                if($size<(1024*1024))
                    {
                        $actual_image_name = time().substr(str_replace(" ", "_", $txt), 5).".".$ext;
                        $tmp = $_FILES['photoimg']['tmp_name'];
                        if(move_uploaded_file($tmp, $path.$actual_image_name))
                            {


                            mysql_query("INSERT INTO users (uid, profile_image) VALUES ('$session_id' , '$actual_image_name')");

                                echo "<img src='uploads/".$actual_image_name."'  class='preview'>";
                            }
                        else
                            echo "Fail upload folder with read access.";
                    }
                    else
                    echo "Image file size max 1 MB";                    
                    }
                    else
                    echo "Invalid file format..";   
            }

        else
            echo "Please select image..!";

        exit;
    }

Referenced Project gets "lost" at Compile Time

Make sure that both projects have same target framework version here: right click on project -> properties -> application (tab) -> target framework

Also, make sure that the project "logger" (which you want to include in the main project) has the output type "Class Library" in: right click on project -> properties -> application (tab) -> output type

Finally, Rebuild the solution.

Regular expression to match standard 10 digit phone number

How about this?

^(\+?[01])?[-.\s]?\(?[1-9]\d{2}\)?[-.\s]?\d{3}[-.\s]?\d{4}

EDIT: I forgot about the () one. EDIT 2: Got the first 3 digit part wrong.

How to disable Compatibility View in IE

<meta http-equiv="X-UA-Compatible" content="IE=8" /> 

should force your page to render in IE8 standards. The user may add the site to compatibility list but this tag will take precedence.

A quick way to check would be to load the page and type the following the address bar :

javascript:alert(navigator.userAgent) 

If you see IE7 in the string, it is loading in compatibility mode, otherwise not.

CSS Background Image Not Displaying

I know this doesn't address the exact case of the OP, but for others coming from Google don't forget to try display: block; based on the element type. I had the image in an <i>, but it wasn't appearing...

Tar archiving that takes input from a list of files

For me on AIX, it worked as follows:

tar -L List.txt -cvf BKP.tar

How to prevent ENTER keypress to submit a web form?

Simply return false from the onsubmit handler

<form onsubmit="return false;">

or if you want a handler in the middle

<script>
var submitHandler = function() {
  // do stuff
  return false;
}
</script>
<form onsubmit="return submitHandler()">

Best way to format multiple 'or' conditions in an if statement (Java)

You could look for the presence of a map key or see if it's in a set.

Depending on what you're actually doing, though, you might be trying to solve the problem wrong :)

How to select the row with the maximum value in each group

Another base solution

group_sorted <- group[order(group$Subject, -group$pt),]
group_sorted[!duplicated(group_sorted$Subject),]

# Subject pt Event
#       1  5     2
#       2 17     2
#       3  5     2

Order the data frame by pt (descending) and then remove rows duplicated in Subject

How to Save Console.WriteLine Output to Text File

For the question:

How to save Console.Writeline Outputs to text file?

I would use Console.SetOut as others have mentioned.


However, it looks more like you are keeping track of your program flow. I would consider using Debug or Trace for keeping track of the program state.

It works similar the console except you have more control over your input such as WriteLineIf.

Debug will only operate when in debug mode where as Trace will operate in both debug or release mode.

They both allow for listeners such as output files or the console.

TextWriterTraceListener tr1 = new TextWriterTraceListener(System.Console.Out);
Debug.Listeners.Add(tr1);

TextWriterTraceListener tr2 = new TextWriterTraceListener(System.IO.File.CreateText("Output.txt"));
Debug.Listeners.Add(tr2);

-http://support.microsoft.com/kb/815788

Content Type text/xml; charset=utf-8 was not supported by service

I've seen this behavior today when the

   <service name="A.B.C.D" behaviorConfiguration="returnFaults">
        <endpoint contract="A.B.C.ID" binding="basicHttpBinding" address=""/>
    </service>

was missing from the web.config. The service.svc file was there and got served. It took a while to realize that the problem was not in the binding configuration it self...

Java Security: Illegal key size or default parameters?

The JRE/JDK/Java 8 jurisdiction files can be found here:

Java Cryptography Extension (JCE) Unlimited Strength Jurisdiction Policy Files 8 Download

Like James said above:
Install the files in ${java.home}/jre/lib/security/.

NSArray + remove item from array

As others suggested, NSMutableArray has methods to do so but sometimes you are forced to use NSArray, I'd use:

NSArray* newArray = [oldArray subarrayWithRange:NSMakeRange(1, [oldArray count] - 1)];

This way, the oldArray stays as it was but a newArray will be created with the first item removed.

What could cause an error related to npm not being able to find a file? No contents in my node_modules subfolder. Why is that?

In my case, this error happened with a new project.

none of the proposed solutions here worked, so I simply reinstalled all the packages and started working correctly.

Update an outdated branch against master in a Git repo

Update the master branch, which you need to do regardless.

Then, one of:

  1. Rebase the old branch against the master branch. Solve the merge conflicts during rebase, and the result will be an up-to-date branch that merges cleanly against master.

  2. Merge your branch into master, and resolve the merge conflicts.

  3. Merge master into your branch, and resolve the merge conflicts. Then, merging from your branch into master should be clean.

None of these is better than the other, they just have different trade-off patterns.

I would use the rebase approach, which gives cleaner overall results to later readers, in my opinion, but that is nothing aside from personal taste.

To rebase and keep the branch you would:

git checkout <branch> && git rebase <target>

In your case, check out the old branch, then

git rebase master 

to get it rebuilt against master.

How to read a config file using python

Since your config file is a normal text file, just read it using the open function:

file = open("abc.txt", 'r')
content = file.read()
paths = content.split("\n") #split it into lines
for path in paths:
    print path.split(" = ")[1]

This will print your paths. You can also store them using dictionaries or lists.

path_list = []
path_dict = {}
for path in paths:
    p = path.split(" = ")
    path_list.append(p)[1]
    path_dict[p[0]] = p[1]

More on reading/writing file here. Hope this helps!

How to check if an email address exists without sending an email?

The general answer is that you can not check if an email address exists event if you send an email to it: it could just go into a black hole.

That being said the method described there is quite effective. It is used in production code in ZoneCheck except that it uses RSET instead of QUIT.

Where user interaction with his mailbox is not overcostly many sites actually test that the mail arrive somewhere by sending a secret number that must be sent back to the emitter (either by going to a secret URL or sending back this secret number by email). Most mailing lists work like that.

Set variable in jinja

Nice shorthand for Multiple variable assignments

{% set label_cls, field_cls = "col-md-7", "col-md-3" %}

How do I catch a numpy warning like it's an exception (not just for testing)?

To elaborate on @Bakuriu's answer above, I've found that this enables me to catch a runtime warning in a similar fashion to how I would catch an error warning, printing out the warning nicely:

import warnings

with warnings.catch_warnings():
    warnings.filterwarnings('error')
    try:
        answer = 1 / 0
    except Warning as e:
        print('error found:', e)

You will probably be able to play around with placing of the warnings.catch_warnings() placement depending on how big of an umbrella you want to cast with catching errors this way.

foreach vs someList.ForEach(){}

As they say, the devil is in the details...

The biggest difference between the two methods of collection enumeration is that foreach carries state, whereas ForEach(x => { }) does not.

But lets dig a little deeper, because there are some things you should be aware of that can influence your decision, and there are some caveats you should be aware of when coding for either case.

Lets use List<T> in our little experiment to observe behavior. For this experiment, I am using .NET 4.7.2:

var names = new List<string>
{
    "Henry",
    "Shirley",
    "Ann",
    "Peter",
    "Nancy"
};

Lets iterate over this with foreach first:

foreach (var name in names)
{
    Console.WriteLine(name);
}

We could expand this into:

using (var enumerator = names.GetEnumerator())
{

}

With the enumerator in hand, looking under the covers we get:

public List<T>.Enumerator GetEnumerator()
{
  return new List<T>.Enumerator(this);
}
    internal Enumerator(List<T> list)
{
  this.list = list;
  this.index = 0;
  this.version = list._version;
  this.current = default (T);
}

public bool MoveNext()
{
  List<T> list = this.list;
  if (this.version != list._version || (uint) this.index >= (uint) list._size)
    return this.MoveNextRare();
  this.current = list._items[this.index];
  ++this.index;
  return true;
}

object IEnumerator.Current
{
  {
    if (this.index == 0 || this.index == this.list._size + 1)
      ThrowHelper.ThrowInvalidOperationException(ExceptionResource.InvalidOperation_EnumOpCantHappen);
    return (object) this.Current;
  }
}

Two things become immediate evident:

  1. We are returned a stateful object with intimate knowledge of the underlying collection.
  2. The copy of the collection is a shallow copy.

This is of course in no way thread safe. As was pointed out above, changing the collection while iterating is just bad mojo.

But what about the problem of the collection becoming invalid during iteration by means outside of us mucking with the collection during iteration? Best practices suggests versioning the collection during operations and iteration, and checking versions to detect when the underlying collection changes.

Here's where things get really murky. According to the Microsoft documentation:

If changes are made to the collection, such as adding, modifying, or deleting elements, the behavior of the enumerator is undefined.

Well, what does that mean? By way of example, just because List<T> implements exception handling does not mean that all collections that implement IList<T> will do the same. That seems to be a clear violation of the Liskov Substitution Principle:

Objects of a superclass shall be replaceable with objects of its subclasses without breaking the application.

Another problem is that the enumerator must implement IDisposable -- that means another source of potential memory leaks, not only if the caller gets it wrong, but if the author does not implement the Dispose pattern correctly.

Lastly, we have a lifetime issue... what happens if the iterator is valid, but the underlying collection is gone? We now a snapshot of what was... when you separate the lifetime of a collection and its iterators, you are asking for trouble.

Lets now examine ForEach(x => { }):

names.ForEach(name =>
{

});

This expands to:

public void ForEach(Action<T> action)
{
  if (action == null)
    ThrowHelper.ThrowArgumentNullException(ExceptionArgument.match);
  int version = this._version;
  for (int index = 0; index < this._size && (version == this._version || !BinaryCompatibility.TargetsAtLeast_Desktop_V4_5); ++index)
    action(this._items[index]);
  if (version == this._version || !BinaryCompatibility.TargetsAtLeast_Desktop_V4_5)
    return;
  ThrowHelper.ThrowInvalidOperationException(ExceptionResource.InvalidOperation_EnumFailedVersion);
}

Of important note is the following:

for (int index = 0; index < this._size && ... ; ++index) action(this._items[index]);

This code does not allocate any enumerators (nothing to Dispose), and does not pause while iterating.

Note that this also performs a shallow copy of the underlying collection, but the collection is now a snapshot in time. If the author does not correctly implement a check for the collection changing or going 'stale', the snapshot is still valid.

This doesn't in any way protect you from the problem of the lifetime issues... if the underlying collection disappears, you now have a shallow copy that points to what was... but at least you don't have a Dispose problem to deal with on orphaned iterators...

Yes, I said iterators... sometimes its advantageous to have state. Suppose you want to maintain something akin to a database cursor... maybe multiple foreach style Iterator<T>'s is the way to go. I personally dislike this style of design as there are too many lifetime issues, and you rely on the good graces of the authors of the collections you are relying on (unless you literally write everything yourself from scratch).

There is always a third option...

for (var i = 0; i < names.Count; i++)
{
    Console.WriteLine(names[i]);
}

It ain't sexy, but its got teeth (apologies to Tom Cruise and the movie The Firm)

Its your choice, but now you know and it can be an informed one.

A Windows equivalent of the Unix tail command

DOS has no tail command; you can download a Windows binary for GNU tail and other GNU tools here.

How to sort the files according to the time stamp in unix?

File modification:

ls -t

Inode change:

ls -tc

File access:

ls -tu

"Newest" one at the bottom:

ls -tr

None of this is a creation time. Most Unix filesystems don't support creation timestamps.

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

The :: instead of REM was preferably used in the days that computers weren't very fast. REM'ed line are read and then ingnored. ::'ed line are ignored all the way. This could speed up your code in "the old days". Further more after a REM you need a space, after :: you don't.

And as said in the first comment: you can add info to any line you feel the need to

SET DATETIME=%DTS:~0,8%-%DTS:~8,6% ::Makes YYYYMMDD-HHMMSS

As for the skipping of parts. Putting REM in front of every line can be rather time consuming. As mentioned using GOTO to skip parts is an easy way to skip large pieces of code. Be sure to set a :LABEL at the point you want the code to continue.

SOME CODE

GOTO LABEL  ::REM OUT THIS LINE TO EXECUTE THE CODE BETWEEN THIS GOTO AND :LABEL

SOME CODE TO SKIP
.
LAST LINE OF CODE TO SKIP

:LABEL
CODE TO EXECUTE

Maximum length of the textual representation of an IPv6 address?

On Linux, see constant INET6_ADDRSTRLEN (include <arpa/inet.h>, see man inet_ntop). On my system (header "in.h"):

#define INET6_ADDRSTRLEN 46

The last character is for terminating NULL, as I belive, so the max length is 45, as other answers.

Get the current cell in Excel VB

I realize this doesn't directly apply from the title of the question, However some ways to deal with a variable range could be to select the range each time the code runs -- especially if you are interested in a user-selected range. If you are interested in that option, you can use the Application.InputBox (official documentation page here). One of the optional variables is 'type'. If the type is set equal to 8, the InputBox also has an excel-style range selection option. An example of how to use it in code would be:

Dim rng as Range
Set rng = Application.InputBox(Prompt:= "Please select a range", Type:=8)

Note:

If you assign the InputBox value to a none-range variable (without the Set keyword), instead of the ranges, the values from the ranges will be assigned, as in the code below (although selecting multiple ranges in this situation may require the values to be assigned to a variant):

Dim str as String
str = Application.InputBox(Prompt:= "Please select a range", Type:=8)

Returning a boolean from a Bash function

It might work if you rewrite this function myfun(){ ... return 0; else return 1; fi;} as this function myfun(){ ... return; else false; fi;}. That is if false is the last instruction in the function you get false result for whole function but return interrupts function with true result anyway. I believe it's true for my bash interpreter at least.

Tomcat 7.0.43 "INFO: Error parsing HTTP request header"

I had this issue when working on a Java Project in Debian 10 with Tomcat as the application server.

The issue was that the application already had https defined as it's default protocol while I was using http to call the application in the browser. So when I try running the application I get this error in my log file:

org.apache.coyote.http11.AbstractHttp11Processor process
INFO: Error parsing HTTP request header
 Note: further occurrences of HTTP header parsing errors will be logged at DEBUG level.

I however tried using the https protocol in the browser but it didn't connect throwing the error:

Here's how I solved it:

You need a certificate to setup the https protocol for the application. I first had to create a keystore file for the application, more like a self-signed certificate for the https protocol:

sudo keytool -genkey -keyalg RSA -alias tomcat -keystore /usr/share/tomcat.keystore

Note: You need to have Java installed on the server to be able to do this. Java can be installed using sudo apt install default-jdk.

Next, I added a https Tomcat server connector for the application in the Tomcat server configuration file (/opt/tomcat/conf/server.xml):

sudo nano /opt/tomcat/conf/server.xml

Add the following to the configuration of the application. Notice that the keystore file location and password are specified. Also a port for the https protocol is defined, which is different from the port for the http protocol:

<Connector protocol="org.apache.coyote.http11.Http11Protocol"
           port="8443" maxThreads="200" scheme="https"
           secure="true" SSLEnabled="true"
           keystoreFile="/usr/share/tomcat.keystore"
           keystorePass="my-password"
           clientAuth="false" sslProtocol="TLS"
           URIEncoding="UTF-8"
           compression="force"
           compressableMimeType="text/html,text/xml,text/plain,text/javascript,text/css"/>

So the full server configuration for the application looked liked this in the Tomcat server configuration file (/opt/tomcat/conf/server.xml):

<Service name="my-application">
  <Connector protocol="org.apache.coyote.http11.Http11Protocol"
             port="8443" maxThreads="200" scheme="https"
             secure="true" SSLEnabled="true"
             keystoreFile="/usr/share/tomcat.keystore"
             keystorePass="my-password"
             clientAuth="false" sslProtocol="TLS"
             URIEncoding="UTF-8"
             compression="force"
             compressableMimeType="text/html,text/xml,text/plain,text/javascript,text/css"/>

  <Connector port="8009" protocol="HTTP/1.1"
             connectionTimeout="20000"
             redirectPort="8443" />

  <Engine name="my-application" defaultHost="localhost">
     <Realm className="org.apache.catalina.realm.LockOutRealm">
        <Realm className="org.apache.catalina.realm.UserDatabaseRealm"
             resourceName="UserDatabase"/>
    </Realm>

    <Host name="localhost"  appBase="webapps"
          unpackWARs="true" autoDeploy="true">

        <Valve className="org.apache.catalina.valves.AccessLogValve" directory="logs"
             prefix="localhost_access_log" suffix=".txt"
             pattern="%h %l %u %t &quot;%r&quot; %s %b" />

    </Host>
  </Engine>
</Service>

This time when I tried accessing the application from the browser using:

https://my-server-ip-address:https-port

In my case it was:

https:35.123.45.6:8443

it worked fine. Although, I had to accept a warning which added a security exception for the website since the certificate used is a self-signed one.

That's all.

I hope this helps

Android: converting String to int

barcode often consist of large number so i think your app crashes because of the size of the string that you are trying to convert to int. you can use BigInteger

BigInteger reallyBig = new BigInteger(myString);

Single Line Nested For Loops

The best source of information is the official Python tutorial on list comprehensions. List comprehensions are nearly the same as for loops (certainly any list comprehension can be written as a for-loop) but they are often faster than using a for loop.

Look at this longer list comprehension from the tutorial (the if part filters the comprehension, only parts that pass the if statement are passed into the final part of the list comprehension (here (x,y)):

>>> [(x, y) for x in [1,2,3] for y in [3,1,4] if x != y]
[(1, 3), (1, 4), (2, 3), (2, 1), (2, 4), (3, 1), (3, 4)]

It's exactly the same as this nested for loop (and, as the tutorial says, note how the order of for and if are the same).

>>> combs = []
>>> for x in [1,2,3]:
...     for y in [3,1,4]:
...         if x != y:
...             combs.append((x, y))
...
>>> combs
[(1, 3), (1, 4), (2, 3), (2, 1), (2, 4), (3, 1), (3, 4)]

The major difference between a list comprehension and a for loop is that the final part of the for loop (where you do something) comes at the beginning rather than at the end.

On to your questions:

What type must object be in order to use this for loop structure?

An iterable. Any object that can generate a (finite) set of elements. These include any container, lists, sets, generators, etc.

What is the order in which i and j are assigned to elements in object?

They are assigned in exactly the same order as they are generated from each list, as if they were in a nested for loop (for your first comprehension you'd get 1 element for i, then every value from j, 2nd element into i, then every value from j, etc.)

Can it be simulated by a different for loop structure?

Yes, already shown above.

Can this for loop be nested with a similar or different structure for loop? And how would it look?

Sure, but it's not a great idea. Here, for example, gives you a list of lists of characters:

[[ch for ch in word] for word in ("apple", "banana", "pear", "the", "hello")]

In Python, how do you convert seconds since epoch to a `datetime` object?

Note that datetime.datetime.fromtimestamp(timestamp) and .utcfromtimestamp(timestamp) fail on windows for dates before Jan. 1, 1970 while negative unix timestamps seem to work on unix-based platforms. The docs say this:

"This may raise ValueError, if the timestamp is out of the range of values supported by the platform C gmtime() function. It’s common for this to be restricted to years in 1970 through 2038"

See also Issue1646728

How can I close a browser window without receiving the "Do you want to close this window" prompt?

Because of the security enhancements in IE, you can't close a window unless it is opened by a script. So the way around this will be to let the browser think that this page is opened using a script, and then to close the window. Below is the implementation.

Try this, it works like a charm!
javascript close current window without prompt IE

<script type="text/javascript">
function closeWP() {
 var Browser = navigator.appName;
 var indexB = Browser.indexOf('Explorer');

 if (indexB > 0) {
    var indexV = navigator.userAgent.indexOf('MSIE') + 5;
    var Version = navigator.userAgent.substring(indexV, indexV + 1);

    if (Version >= 7) {
        window.open('', '_self', '');
        window.close();
    }
    else if (Version == 6) {
        window.opener = null;
        window.close();
    }
    else {
        window.opener = '';
        window.close();
    }

 }
else {
    window.close();
 }
}
</script>

javascript close current window without prompt IE

How can I create an error 404 in PHP?

try this once.

$wp_query->set_404();
status_header(404);
get_template_part('404'); 

Get selected row item in DataGrid WPF

if I select the second row -

 Dim jason As DataRowView


    jason = dg1.SelectedItem

    noteText.Text = jason.Item(0).ToString()

noteText will be 646. This is VB, but you get it.

How do you import a large MS SQL .sql file?

Your question is quite similar to this one

You can save your file/script as .txt or .sql and run it from Sql Server Management Studio (I think the menu is Open/Query, then just run the query in the SSMS interface). You migh have to update the first line, indicating the database to be created or selected on your local machine.

If you have to do this data transfer very often, you could then go for replication. Depending on your needs, snapshot replication could be ok. If you have to synch the data between your two servers, you could go for a more complex model such as merge replication.

EDIT: I didn't notice that you had problems with SSMS linked to file size. Then you can go for command-line, as proposed by others, snapshot replication (publish on your main server, subscribe on your local one, replicate, then unsubscribe) or even backup/restore

Vertically aligning text next to a radio button

You may try something like;

<p><input type="radio" id="oddsPref" name="oddsPref" value="decimal" /><span>Decimal</span></p>

and give the span a margin top like;

span{
    margin-top: 4px;
    position:absolute;
}

here is the fiddle http://jsfiddle.net/UnA6j/11/

Implement specialization in ER diagram

So I assume your permissions table has a foreign key reference to admin_accounts table. If so because of referential integrity you will only be able to add permissions for account ids exsiting in the admin accounts table. Which also means that you wont be able to enter a user_account_id [assuming there are no duplicates!]

MySQL - sum column value(s) based on row from the same table

SUM CASE using example:

    SELECT 
  DISTINCT(p.`ProductID`) AS ProductID,
  SUM(IF(p.`PaymentMethod`='Cash',Amount,0)) AS Cash_,
  SUM(IF(p.`PaymentMethod`='Check',Amount,0)) AS Check_,
  SUM(IF(p.`PaymentMethod`='Credit Card',Amount,0)) AS Credit_Card_,
  SUM( CASE PaymentMethod 
      WHEN 'Cash' THEN Amount
      WHEN 'Check' THEN Amount
      WHEN 'Credit Card' THEN Amount
     END) AS Total
FROM
  `payments` AS p 
GROUP BY p.`ProductID`;

SQL FIDDLE: http://www.sqlfiddle.com/#!9/23d07d/18

Result and Table view

PHP: Split string

explode('.', $string)

If you know your string has a fixed number of components you could use something like

list($a, $b) = explode('.', 'object.attribute');
echo $a;
echo $b;

Prints:

object
attribute

HTML5 pattern for formatting input box to take date mm/dd/yyyy?

I've converted the http://html5pattern.com/Dates Full Date Validation (YYYY-MM-DD) to DD/MM/YYYY Brazilian format:

pattern='(?:((?:0[1-9]|1[0-9]|2[0-9])\/(?:0[1-9]|1[0-2])|(?:30)\/(?!02)(?:0[1-9]|1[0-2])|31\/(?:0[13578]|1[02]))\/(?:19|20)[0-9]{2})'

android : Error converting byte to dex

Just clean and retry solved for me.

How to copy a file along with directory structure/path using python?

take a look at shutil. shutil.copyfile(src, dst) will copy a file to another file.

Note that shutil.copyfile will not create directories that do not already exist. for that, use os.makedirs

How to create threads in nodejs

The nodejs 10.5.0 release has announced multithreading in Node.js. The feature is still experimental. There is a new worker_threads module available now.

You can start using worker threads if you run Node.js v10.5.0 or higher, but this is an experimental API. It is not available by default: you need to enable it by using --experimental-worker when invoking Node.js.

Here is an example with ES6 and worker_threads enabled, tested on version 12.3.1

//package.json

  "scripts": {
  "start": "node  --experimental-modules --experimental- worker index.mjs"
  },

Now, you need to import Worker from worker_threads. Note: You need to declare you js files with '.mjs' extension for ES6 support.

//index.mjs
import { Worker } from 'worker_threads';

const spawnWorker = workerData => {
    return new Promise((resolve, reject) => {
        const worker = new Worker('./workerService.mjs', { workerData });
        worker.on('message', resolve);
        worker.on('error', reject);
        worker.on('exit', code => code !== 0 && reject(new Error(`Worker stopped with 
        exit code ${code}`)));
    })
}

const spawnWorkers = () => {
    for (let t = 1; t <= 5; t++)
        spawnWorker('Hello').then(data => console.log(data));
}

spawnWorkers();

Finally, we create a workerService.mjs

//workerService.mjs
import { workerData, parentPort, threadId } from 'worker_threads';

// You can do any cpu intensive tasks here, in a synchronous way
// without blocking the "main thread"
parentPort.postMessage(`${workerData} from worker ${threadId}`);

Output:

npm run start

Hello from worker 4
Hello from worker 3
Hello from worker 1
Hello from worker 2
Hello from worker 5

Running Selenium WebDriver python bindings in chrome

You need to make sure the standalone ChromeDriver binary (which is different than the Chrome browser binary) is either in your path or available in the webdriver.chrome.driver environment variable.

see http://code.google.com/p/selenium/wiki/ChromeDriver for full information on how wire things up.

Edit:

Right, seems to be a bug in the Python bindings wrt reading the chromedriver binary from the path or the environment variable. Seems if chromedriver is not in your path you have to pass it in as an argument to the constructor.

import os
from selenium import webdriver

chromedriver = "/Users/adam/Downloads/chromedriver"
os.environ["webdriver.chrome.driver"] = chromedriver
driver = webdriver.Chrome(chromedriver)
driver.get("http://stackoverflow.com")
driver.quit()

Passing parameters from jsp to Spring Controller method

Use the @RequestParam to pass a parameter to the controller handler method. In the jsp your form should have an input field with name = "id" like the following:

<input type="text" name="id" />
<input type="submit" />

Then in your controller, your handler method should be like the following:

@RequestMapping("listNotes")
public String listNotes(@RequestParam("id") int id) {
    Person person = personService.getCurrentlyAuthenticatedUser();
    model.addAttribute("person", new Person());
    model.addAttribute("listPersons", this.personService.listPersons());
    model.addAttribute("listNotes", this.notesService.listNotesBySectionId(id, person));
    return "note";
}

Please also refer to these answers and tutorial:

Populating spinner directly in the layout xml

Define this in your String.xml file and name the array what you want, such as "Weight"

<string-array name="Weight">
<item>Kg</item>
<item>Gram</item>
<item>Tons</item>
</string-array>

and this code in your layout.xml

<Spinner 
        android:id="@+id/fromspin"
        android:layout_width="fill_parent"
        android:layout_height="wrap_content"
        android:entries="@array/Weight"
 />

In your java file, getActivity is used in fragment; if you write that code in activity, then remove getActivity.

a = (Spinner) findViewById(R.id.fromspin);

 ArrayAdapter<CharSequence> adapter = ArrayAdapter.createFromResource(this.getActivity(),
                R.array.weight, android.R.layout.simple_spinner_item);
        adapter.setDropDownViewResource(android.R.layout.simple_spinner_dropdown_item);

        a.setAdapter(adapter);
        a.setOnItemSelectedListener(new AdapterView.OnItemSelectedListener() {
            public void onItemSelected(AdapterView<?> parent, View view, int pos, long id) {
                if (a.getSelectedItem().toString().trim().equals("Kilogram")) {
                    if (!b.getText().toString().isEmpty()) {
                        float value1 = Float.parseFloat(b.getText().toString());
                        float kg = value1;
                        c.setText(Float.toString(kg));
                        float gram = value1 * 1000;
                        d.setText(Float.toString(gram));
                        float carat = value1 * 5000;
                        e.setText(Float.toString(carat));
                        float ton = value1 / 908;
                        f.setText(Float.toString(ton));
                    }

                }



            public void onNothingSelected(AdapterView<?> parent) {
                // Another interface callback
            }
        });
        // Inflate the layout for this fragment
        return v;
    }

What is the difference between compileSdkVersion and targetSdkVersion?

The compileSdkVersion should be newest stable version. The targetSdkVersion should be fully tested and less or equal to compileSdkVersion.

Create a mocked list by mockito

We can mock list properly for foreach loop. Please find below code snippet and explanation.

This is my actual class method where I want to create test case by mocking list. this.nameList is a list object.

public void setOptions(){
    // ....
    for (String str : this.nameList) {
        str = "-"+str;
    }
    // ....
}

The foreach loop internally works on iterator, so here we crated mock of iterator. Mockito framework has facility to return pair of values on particular method call by using Mockito.when().thenReturn(), i.e. on hasNext() we pass 1st true and on second call false, so that our loop will continue only two times. On next() we just return actual return value.

@Test
public void testSetOptions(){
    // ...
    Iterator<SampleFilter> itr = Mockito.mock(Iterator.class);
    Mockito.when(itr.hasNext()).thenReturn(true, false);
    Mockito.when(itr.next()).thenReturn(Mockito.any(String.class);  

    List mockNameList = Mockito.mock(List.class);
    Mockito.when(mockNameList.iterator()).thenReturn(itr);
    // ...
}

In this way we can avoid sending actual list to test by using mock of list.

How can I test a Windows DLL file to determine if it is 32 bit or 64 bit?

Dependency Walker tells all(well almost). http://www.dependencywalker.com/

It does not "install" -just get it, extract it and run the exec. It works for any x32 or x64 windows module|application.

As I recall it is fairly straightforward to see all dependencies, i.e. the dll modules, and since the appl. is a sum of the dependencies one can ascertain if it is full x64, x32(x86) or a bit of each.

Type of CPU that the module was built for is in the "CPU" column. Most 64-bit aps are still a bit of each but 32-bit ap w/b all x86.

Beautiful program for geeks/programmers and it is free...

Search and get a line in Python

If you prefer a one-liner:

matched_lines = [line for line in my_string.split('\n') if "substring" in line]

Good NumericUpDown equivalent in WPF?

The Extended WPF Toolkit has one: NumericUpDown enter image description here

PHP compare time

$ThatTime ="14:08:10";
if (time() >= strtotime($ThatTime)) {
  echo "ok";
}

A solution using DateTime (that also regards the timezone).

$dateTime = new DateTime($ThatTime);
if ($dateTime->diff(new DateTime)->format('%R') == '+') {
  echo "OK";
}

http://php.net/datetime.diff

PHP - SSL certificate error: unable to get local issuer certificate

When you view the http://curl.haxx.se/docs/caextract.html page, you will notice in big letters a section called:

RSA-1024 removed

Read it, then download the version of the certificates that includes the 'RSA-1024' certificates. https://github.com/bagder/ca-bundle/blob/e9175fec5d0c4d42de24ed6d84a06d504d5e5a09/ca-bundle.crt

Those will work with Mandrill.

Disabling SSL is a bad idea.

Make copy of an array

All solution that call length from array, add your code redundant null checkersconsider example:

int[] a = {1,2,3,4,5};
int[] b = Arrays.copyOf(a, a.length);
int[] c = a.clone();

//What if array a comes as local parameter? You need to use null check:

public void someMethod(int[] a) {
    if (a!=null) {
        int[] b = Arrays.copyOf(a, a.length);
        int[] c = a.clone();
    }
}

I recommend you not inventing the wheel and use utility class where all necessary checks have already performed. Consider ArrayUtils from apache commons. You code become shorter:

public void someMethod(int[] a) {
    int[] b = ArrayUtils.clone(a);
}

Apache commons you can find there

How to add extension methods to Enums

Of course you can, say for example, you want to use the DescriptionAttribue on your enum values:

using System.ComponentModel.DataAnnotations;

public enum Duration 
{ 
    [Description("Eight hours")]
    Day,

    [Description("Five days")]
    Week,

    [Description("Twenty-one days")] 
    Month 
}

Now you want to be able to do something like:

Duration duration = Duration.Week;
var description = duration.GetDescription(); // will return "Five days"

Your extension method GetDescription() can be written as follows:

using System.ComponentModel;
using System.Reflection;

public static string GetDescription(this Enum value)
{
    FieldInfo fieldInfo = value.GetType().GetField(value.ToString());
    if (fieldInfo == null) return null;
    var attribute = (DescriptionAttribute)fieldInfo.GetCustomAttribute(typeof(DescriptionAttribute));
    return attribute.Description;
}

Convert DateTime to TimeSpan

To convert a DateTime to a TimeSpan you should choose a base date/time - e.g. midnight of January 1st, 2000, and subtract it from your DateTime value (and add it when you want to convert back to DateTime).

If you simply want to convert a DateTime to a number you can use the Ticks property.

How to generate UML diagrams (especially sequence diagrams) from Java code?

I am one of the authors, so the answer can be biased. It is open-source (Apache 2.0), but the plugin is not free. You don't have to pay (obviously) if you clone and build it locally.

On Intellij IDEA, ZenUML can generate sequence diagram from Java code. enter image description here

Check it out at https://plugins.jetbrains.com/plugin/12437-zenuml-support

Source code: https://github.com/ZenUml/jetbrains-zenuml

Can we create an instance of an interface in Java?

Normaly, you can create a reference for an interface. But you cant create an instance for interface.

Jump to function definition in vim

Use gd or gD while placing the cursor on any variable in your program.

  1. gd will take you to the local declaration.
  2. gD will take you to the global declaration.

more navigation options can be found in here.

Use cscope for cross referencing large project such as the linux kernel.

How to change 1 char in the string?

Strings are immutable. You can use the string builder class to help!:

string str = "valta is the best place in the World";

StringBuilder strB = new StringBuilder(str);

strB[0] = 'M';

AngularJS - Multiple ng-view in single template

I believe you can accomplish it by just having single ng-view. In the main template you can have ng-include sections for sub views, then in the main controller define model properties for each sub template. So that they will bind automatically to ng-include sections. This is same as having multiple ng-view

You can check the example given in ng-include documentation

in the example when you change the template from dropdown list it changes the content. Here assume you have one main ng-view and instead of manually selecting sub content by selecting drop down, you do it as when main view is loaded.

ASP.NET Core Web API exception handling

Firstly, thanks to Andrei as I've based my solution on his example.

I'm including mine as it's a more complete sample and might save readers some time.

The limitation of Andrei's approach is that doesn't handle logging, capturing potentially useful request variables and content negotiation (it will always return JSON no matter what the client has requested - XML / plain text etc).

My approach is to use an ObjectResult which allows us to use the functionality baked into MVC.

This code also prevents caching of the response.

The error response has been decorated in such a way that it can be serialized by the XML serializer.

public class ExceptionHandlerMiddleware
{
    private readonly RequestDelegate next;
    private readonly IActionResultExecutor<ObjectResult> executor;
    private readonly ILogger logger;
    private static readonly ActionDescriptor EmptyActionDescriptor = new ActionDescriptor();

    public ExceptionHandlerMiddleware(RequestDelegate next, IActionResultExecutor<ObjectResult> executor, ILoggerFactory loggerFactory)
    {
        this.next = next;
        this.executor = executor;
        logger = loggerFactory.CreateLogger<ExceptionHandlerMiddleware>();
    }

    public async Task Invoke(HttpContext context)
    {
        try
        {
            await next(context);
        }
        catch (Exception ex)
        {
            logger.LogError(ex, $"An unhandled exception has occurred while executing the request. Url: {context.Request.GetDisplayUrl()}. Request Data: " + GetRequestData(context));

            if (context.Response.HasStarted)
            {
                throw;
            }

            var routeData = context.GetRouteData() ?? new RouteData();

            ClearCacheHeaders(context.Response);

            var actionContext = new ActionContext(context, routeData, EmptyActionDescriptor);

            var result = new ObjectResult(new ErrorResponse("Error processing request. Server error."))
            {
                StatusCode = (int) HttpStatusCode.InternalServerError,
            };

            await executor.ExecuteAsync(actionContext, result);
        }
    }

    private static string GetRequestData(HttpContext context)
    {
        var sb = new StringBuilder();

        if (context.Request.HasFormContentType && context.Request.Form.Any())
        {
            sb.Append("Form variables:");
            foreach (var x in context.Request.Form)
            {
                sb.AppendFormat("Key={0}, Value={1}<br/>", x.Key, x.Value);
            }
        }

        sb.AppendLine("Method: " + context.Request.Method);

        return sb.ToString();
    }

    private static void ClearCacheHeaders(HttpResponse response)
    {
        response.Headers[HeaderNames.CacheControl] = "no-cache";
        response.Headers[HeaderNames.Pragma] = "no-cache";
        response.Headers[HeaderNames.Expires] = "-1";
        response.Headers.Remove(HeaderNames.ETag);
    }

    [DataContract(Name= "ErrorResponse")]
    public class ErrorResponse
    {
        [DataMember(Name = "Message")]
        public string Message { get; set; }

        public ErrorResponse(string message)
        {
            Message = message;
        }
    }
}

How to install Boost on Ubuntu

You can use apt-get command (requires sudo)

sudo apt-get install libboost-all-dev

Or you can call

aptitude search boost

find packages you need and install them using the apt-get command.

How to define a two-dimensional array?

You're technically trying to index an uninitialized array. You have to first initialize the outer list with lists before adding items; Python calls this "list comprehension".

# Creates a list containing 5 lists, each of 8 items, all set to 0
w, h = 8, 5;
Matrix = [[0 for x in range(w)] for y in range(h)] 

You can now add items to the list:

Matrix[0][0] = 1
Matrix[6][0] = 3 # error! range... 
Matrix[0][6] = 3 # valid

Note that the matrix is "y" address major, in other words, the "y index" comes before the "x index".

print Matrix[0][0] # prints 1
x, y = 0, 6 
print Matrix[x][y] # prints 3; be careful with indexing! 

Although you can name them as you wish, I look at it this way to avoid some confusion that could arise with the indexing, if you use "x" for both the inner and outer lists, and want a non-square Matrix.

How to detect a USB drive has been plugged in?

Microsoft API Code Pack. ShellObjectWatcher class.

SQL Server Error : String or binary data would be truncated

This error is usually encountered when inserting a record in a table where one of the columns is a VARCHAR or CHAR data type and the length of the value being inserted is longer than the length of the column.

I am not satisfied how Microsoft decided to inform with this "dry" response message, without any point of where to look for the answer.

Simple parse JSON from URL on Android and display in listview

HttpClient client = new DefaultHttpClient();
HttpGet request = new HttpGet();
request.setURI(new URI(url));
HttpResponse response = client.execute(request);
BufferedReader in = new BufferedReader(new InputStreamReader(response
        .getEntity().getContent()));
String line = "";

while ((line = in.readLine()) != null) {

    JSONObject jObject = new JSONObject(line);

    if (jObject.has("name")) {

        String temp = jObject.getString("name");
        Log.e("name",temp);

    }

}

What is the regex for "Any positive integer, excluding 0"

Any positive integer, excluding 0: ^\+?[1-9]\d*$
Any positive integer, including 0: ^(0|\+?[1-9]\d*)$

WPF popup window

You need to create a new Window class. You can design that then any way you want. You can create and show a window modally like this:

MyWindow popup = new MyWindow();
popup.ShowDialog();

You can add a custom property for your result value, or if you only have two possible results ( + possibly undeterminate, which would be null), you can set the window's DialogResult property before closing it and then check for it (it is the value returned by ShowDialog()).

Android: how to refresh ListView contents?

I'm doing the same thing using invalidateViews() and that works for me. If you want it to invalidate immediately you could try calling postInvalidate after calling invalidateViews.