Programs & Examples On #Localserver

Connect Device to Mac localhost Server?

Try enabling Internet Sharing:
Open System Preferences -> Sharing. Check Internet Sharing to turn it on, it will prompt you to confirm your action, select ok. If your iPhone is connected using USB, the iPhone USB is checked at the "sharing your connection" list on the right side.
After this, try accessing your local server using your macs ip on wifi.

How often should Oracle database statistics be run?

What Oracle version are you using? Check this page which refers to Oracle 10:

http://www.acs.ilstu.edu/docs/Oracle/server.101/b10752/stats.htm

It says:

The recommended approach to gathering statistics is to allow Oracle to automatically gather the statistics. Oracle gathers statistics on all database objects automatically and maintains those statistics in a regularly-scheduled maintenance job.

Aborting a shell script if any command returns a non-zero value

To add to the accepted answer:

Bear in mind that set -e sometimes is not enough, specially if you have pipes.

For example, suppose you have this script

#!/bin/bash
set -e 
./configure  > configure.log
make

... which works as expected: an error in configure aborts the execution.

Tomorrow you make a seemingly trivial change:

#!/bin/bash
set -e 
./configure  | tee configure.log
make

... and now it does not work. This is explained here, and a workaround (Bash only) is provided:

#!/bin/bash
set -e 
set -o pipefail

./configure  | tee configure.log
make

DataTables: Cannot read property 'length' of undefined

In my case, i had to assign my json to an attribute called aaData just like in Datatables ajax example which data looked like this.

How to read until end of file (EOF) using BufferedReader in Java?

You are consuming a line at, which is discarded

while((str=input.readLine())!=null && str.length()!=0)

and reading a bigint at

BigInteger n = new BigInteger(input.readLine());

so try getting the bigint from string which is read as

BigInteger n = new BigInteger(str);

   Constructor used: BigInteger(String val)

Aslo change while((str=input.readLine())!=null && str.length()!=0) to

while((str=input.readLine())!=null)

see related post string to bigint

readLine()
Returns:
    A String containing the contents of the line, not including any line-termination characters, or null if the end of the stream has been reached 

see javadocs

Max size of URL parameters in _GET

Ok, it seems that some versions of PHP have a limitation of length of GET params:

Please note that PHP setups with the suhosin patch installed will have a default limit of 512 characters for get parameters. Although bad practice, most browsers (including IE) supports URLs up to around 2000 characters, while Apache has a default of 8000.

To add support for long parameters with suhosin, add suhosin.get.max_value_length = <limit> in php.ini

Source: http://www.php.net/manual/en/reserved.variables.get.php#101469

How to test Spring Data repositories?

I solved this by using this way -

    @RunWith(SpringRunner.class)
    @EnableJpaRepositories(basePackages={"com.path.repositories"})
    @EntityScan(basePackages={"com.model"})
    @TestPropertySource("classpath:application.properties")
    @ContextConfiguration(classes = {ApiTestConfig.class,SaveActionsServiceImpl.class})
    public class SaveCriticalProcedureTest {

        @Autowired
        private SaveActionsService saveActionsService;
        .......
        .......
}

Php multiple delimiters in explode

I do it this way...

public static function multiExplode($delims, $string, $special = '|||') {

    if (is_array($delims) == false) {
        $delims = array($delims);
    }

    if (empty($delims) == false) {
        foreach ($delims as $d) {
            $string = str_replace($d, $special, $string);
        }
    }

    return explode($special, $string);
}

Correct syntax to compare values in JSTL <c:if test="${values.type}=='object'">

The comparison needs to be evaluated fully inside EL ${ ... }, not outside.

<c:if test="${values.type eq 'object'}">

As to the docs, those ${} things are not JSTL, but EL (Expression Language) which is a whole subject at its own. JSTL (as every other JSP taglib) is just utilizing it. You can find some more EL examples here.

<c:if test="#{bean.booleanValue}" />
<c:if test="#{bean.intValue gt 10}" />
<c:if test="#{bean.objectValue eq null}" />
<c:if test="#{bean.stringValue ne 'someValue'}" />
<c:if test="#{not empty bean.collectionValue}" />
<c:if test="#{not bean.booleanValue and bean.intValue ne 0}" />
<c:if test="#{bean.enumValue eq 'ONE' or bean.enumValue eq 'TWO'}" />

See also:


By the way, unrelated to the concrete problem, if I guess your intent right, you could also just call Object#getClass() and then Class#getSimpleName() instead of adding a custom getter.

<c:forEach items="${list}" var="value">
    <c:if test="${value['class'].simpleName eq 'Object'}">
        <!-- code here -->
    </c:if>
</c:forEeach>

See also:

C# event with custom arguments

Example with no parameters:

delegate void NewEventHandler();
public event NewEventHandler OnEventHappens;

And from another class, you can subscribe to

otherClass.OnEventHappens += ExecuteThisFunctionWhenEventHappens;

And declare that function with no parameters.

The import javax.persistence cannot be resolved

I ran into this same issue and realized that, since I am using spring boot, all I needed to do to resolve the issue was to add the following dependency:

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

Open window in JavaScript with HTML inserted

You can use window.open to open a new window/tab(according to browser setting) in javascript.

By using document.write you can write HTML content to the opened window.

CSS force image resize and keep aspect ratio

I would suggest for a responsive approach the best practice would be using the Viewport units and min/max attributes as follows:

img{
  display: block;
  width: 12vw;
  height:12vw;
  max-width:100%;
  min-width:100px;
  min-height:100px;
  object-fit:contain;
}

How to set a default row for a query that returns no rows?

I figured it out, and it should also work for other systems too. It's a variation of WW's answer.

select rate 
from d_payment_index
where fy = 2007
  and payment_year = 2008
  and program_id = 18
union
select 0 as rate 
from d_payment_index 
where not exists( select rate 
                  from d_payment_index
                  where fy = 2007
                    and payment_year = 2008
                    and program_id = 18 )

what is the basic difference between stack and queue?

Imagine a stack of paper. The last piece put into the stack is on the top, so it is the first one to come out. This is LIFO. Adding a piece of paper is called "pushing", and removing a piece of paper is called "popping".

Imagine a queue at the store. The first person in line is the first person to get out of line. This is FIFO. A person getting into line is "enqueued", and a person getting out of line is "dequeued".

How do I draw a circle in iOS Swift?

Make a class UIView and assign it this code for a simple circle

import UIKit
@IBDesignable
class DRAW: UIView {

    override func draw(_ rect: CGRect) {

        var path = UIBezierPath()
        path = UIBezierPath(ovalIn: CGRect(x: 50, y: 50, width: 100, height: 100))
        UIColor.yellow.setStroke()
        UIColor.red.setFill()
        path.lineWidth = 5
        path.stroke()
        path.fill()


    }


}

how to extract only the year from the date in sql server 2008?

the year function dose, like this:

select year(date_column) from table_name

mysql count group by having

Maybe

SELECT count(*) FROM (
    SELECT COUNT(*) FROM Movies GROUP BY ID HAVING count(Genre) = 4
) AS the_count_total

although that would not be the sum of all the movies, just how many have 4 genre's.

So maybe you want

SELECT sum(
    SELECT COUNT(*) FROM Movies GROUP BY ID having Count(Genre) = 4
) as the_sum_total

What is the best comment in source code you have ever encountered?

// The freshest corpse at the back please.
m_DeadCharacters.push_back( std::make_pair(character, 0.0f) );
// Get rid of the rotting surplus
while( m_DeadCharacters.size() > 3 )
    m_DeadCharacters.pop_front();

Is HTML considered a programming language?

In the advanced programming languages class I took in college, we had what I think is a pretty good definition of "programming language": a programming language is any (formal) language capable of expressing all computable functions, which the Church-Turing thesis implies is the set of all Turing-computable functions.

By that definition, no, HTML is not a programming language, even a declarative one. It is, as others have explained, a markup language.

But the people reviewing your resume may very well not care about such a formal distinction. I'd follow the good advice given by others and list it under a "Technologies" type of section.

Using Excel VBA to run SQL query

Below is code that I currently use to pull data from a MS SQL Server 2008 into VBA. You need to make sure you have the proper ADODB reference [VBA Editor->Tools->References] and make sure you have Microsoft ActiveX Data Objects 2.8 Library checked, which is the second from the bottom row that is checked (I'm using Excel 2010 on Windows 7; you might have a slightly different ActiveX version, but it will still begin with Microsoft ActiveX):

References required for SQL

Sub Module for Connecting to MS SQL with Remote Host & Username/Password

Sub Download_Standard_BOM()
'Initializes variables
Dim cnn As New ADODB.Connection
Dim rst As New ADODB.Recordset
Dim ConnectionString As String
Dim StrQuery As String

'Setup the connection string for accessing MS SQL database
   'Make sure to change:
       '1: PASSWORD
       '2: USERNAME
       '3: REMOTE_IP_ADDRESS
       '4: DATABASE
    ConnectionString = "Provider=SQLOLEDB.1;Password=PASSWORD;Persist Security Info=True;User ID=USERNAME;Data Source=REMOTE_IP_ADDRESS;Use Procedure for Prepare=1;Auto Translate=True;Packet Size=4096;Use Encryption for Data=False;Tag with column collation when possible=False;Initial Catalog=DATABASE"

    'Opens connection to the database
    cnn.Open ConnectionString
    'Timeout error in seconds for executing the entire query; this will run for 15 minutes before VBA timesout, but your database might timeout before this value
    cnn.CommandTimeout = 900

    'This is your actual MS SQL query that you need to run; you should check this query first using a more robust SQL editor (such as HeidiSQL) to ensure your query is valid
    StrQuery = "SELECT TOP 10 * FROM tbl_table"

    'Performs the actual query
    rst.Open StrQuery, cnn
    'Dumps all the results from the StrQuery into cell A2 of the first sheet in the active workbook
    Sheets(1).Range("A2").CopyFromRecordset rst
End Sub

How do I remove the top margin in a web page?

I had same problem. It was resolved by following css line;

h1{margin-top:0px}

My main div contained h1 tag in the beginning.

High Quality Image Scaling Library

I have some improve for Doctor Jones's answer.

It works for who wanted to how to proportional resize the image. It tested and worked for me.

The methods of class I added:

public static System.Drawing.Bitmap ResizeImage(System.Drawing.Image image, Size size)
{
    return ResizeImage(image, size.Width, size.Height);
}


public static Size GetProportionedSize(Image image, int maxWidth, int maxHeight, bool withProportion)
{
    if (withProportion)
    {
        double sourceWidth = image.Width;
        double sourceHeight = image.Height;

        if (sourceWidth < maxWidth && sourceHeight < maxHeight)
        {
            maxWidth = (int)sourceWidth;
            maxHeight = (int)sourceHeight;
        }
        else
        {
            double aspect = sourceHeight / sourceWidth;

            if (sourceWidth < sourceHeight)
            {
                maxWidth = Convert.ToInt32(Math.Round((maxHeight / aspect), 0));
            }
            else
            {
                maxHeight = Convert.ToInt32(Math.Round((maxWidth * aspect), 0));
            }
        }
    }

    return new Size(maxWidth, maxHeight);
}

and new available using according to this codes:

using (var resized = ImageUtilities.ResizeImage(image, ImageUtilities.GetProportionedSize(image, 50, 100)))
{
    ImageUtilities.SaveJpeg(@"C:\myimage.jpeg", resized, 90);
}

Can't connect to MySQL server on '127.0.0.1' (10061) (2003)

Slightly different case, but it may help someone.

I followed the instructions to create a secondary database instance, and I had to clone the ini file as part of that. It was failing to start the service, with the same error. Turns out notepad.exe had re-encoded the cloned ini file as UTF8-BOM, and MySQL (version 8) refused to work with it. Removing the BOM fixed the problem.

Get column index from column name in python pandas

In case you want the column name from the column location (the other way around to the OP question), you can use:

>>> df.columns.get_values()[location]

Using @DSM Example:

>>> df = DataFrame({"pear": [1,2,3], "apple": [2,3,4], "orange": [3,4,5]})

>>> df.columns

Index(['apple', 'orange', 'pear'], dtype='object')

>>> df.columns.get_values()[1]

'orange'

Other ways:

df.iloc[:,1].name

df.columns[location] #(thanks to @roobie-nuby for pointing that out in comments.) 

Non-static method requires a target

All the answers are pointing to a Lambda expression with an NRE (Null Reference Exception). I have found that it also occurs when using Linq to Entities. I thought it would be helpful to point out that this exception is not limited to just an NRE inside a Lambda expression.

php random x digit number

Well you can use as simple php function mt_rand(2000,9000) which can generate a 4 digit random number

mt_rand(2000,9000) 

Excel 2013 horizontal secondary axis

You should follow the guidelines on Add a secondary horizontal axis:

Add a secondary horizontal axis

To complete this procedure, you must have a chart that displays a secondary vertical axis. To add a secondary vertical axis, see Add a secondary vertical axis.

  1. Click a chart that displays a secondary vertical axis. This displays the Chart Tools, adding the Design, Layout, and Format tabs.

  2. On the Layout tab, in the Axes group, click Axes.

    enter image description here

  3. Click Secondary Horizontal Axis, and then click the display option that you want.

enter image description here


Add a secondary vertical axis

You can plot data on a secondary vertical axis one data series at a time. To plot more than one data series on the secondary vertical axis, repeat this procedure for each data series that you want to display on the secondary vertical axis.

  1. In a chart, click the data series that you want to plot on a secondary vertical axis, or do the following to select the data series from a list of chart elements:

    • Click the chart.

      This displays the Chart Tools, adding the Design, Layout, and Format tabs.

    • On the Format tab, in the Current Selection group, click the arrow in the Chart Elements box, and then click the data series that you want to plot along a secondary vertical axis.

      enter image description here

  2. On the Format tab, in the Current Selection group, click Format Selection. The Format Data Series dialog box is displayed.

    Note: If a different dialog box is displayed, repeat step 1 and make sure that you select a data series in the chart.

  3. On the Series Options tab, under Plot Series On, click Secondary Axis and then click Close.

    A secondary vertical axis is displayed in the chart.

  4. To change the display of the secondary vertical axis, do the following:

    • On the Layout tab, in the Axes group, click Axes.

    • Click Secondary Vertical Axis, and then click the display option that you want.

  5. To change the axis options of the secondary vertical axis, do the following:

    • Right-click the secondary vertical axis, and then click Format Axis.

    • Under Axis Options, select the options that you want to use.

When do you use the "this" keyword?

I use it only when required, except for symmetric operations which due to single argument polymorphism have to be put into methods of one side:

boolean sameValue (SomeNum other) {
   return this.importantValue == other.importantValue;
} 

What version of javac built my jar?

you can find Java compiler version from .class files using a Hex Editor.

Step 1: Extract .class files from jar file using a zip extractor

step 2: open .class file with a hex editor.(I have used notepad++ hex editor plugin. This plugin reads file as binary and shows it in hex) You can see below. enter image description here

Index 6 and 7 gives major version number of the class file format being used. https://en.wikipedia.org/wiki/Java_class_file

Java SE 11 = 55 (0x37 hex)

Java SE 10 = 54 (0x36 hex)

Java SE 9 = 53 (0x35 hex)

Java SE 8 = 52 (0x34 hex),

Java SE 7 = 51 (0x33 hex),

Java SE 6.0 = 50 (0x32 hex),

Java SE 5.0 = 49 (0x31 hex),

JDK 1.4 = 48 (0x30 hex),

JDK 1.3 = 47 (0x2F hex),

JDK 1.2 = 46 (0x2E hex),

JDK 1.1 = 45 (0x2D hex).

How to set enum to null

would it not be better to explicitly assign value 0 to None constant? Why?

Because default enum value is equal to 0, if You would call default(Color) it would print None.

Because it is at first position, assigning literal value 0 to any other constant would change that behaviour, also changing order of occurrence would change output of default(Color) (https://stackoverflow.com/a/4967673/8611327)

Proper way to renew distribution certificate for iOS

When your certificate expires, it simply disappears from the ‘Certificates, Identifier & Profiles’ section of Member Center. There is no ‘Renew’ button that allows you to renew your certificate. You can revoke a certificate and generate a new one before it expires. Or you can wait for it to expire and disappear, then generate a new certificate. In Apple's App Distribution Guide:

Replacing Expired Certificates

When your development or distribution certificate expires, remove it and request a new certificate in Xcode.

When your certificate expires or is revoked, any provisioning profile that made use of the expired/revoked certificate will be reflected as ‘Invalid’. You cannot build and sign any app using these invalid provisioning profiles. As you can imagine, I'd rather revoke and regenerate a certificate before it expires.

Q: If I do that then will all my live apps be taken down?

Apps that are already on the App Store continue to function fine. Again, in Apple's App Distribution Guide:

Important: Re-creating your development or distribution certificates doesn’t affect apps that you’ve submitted to the store nor does it affect your ability to update them.

So…

Q: How to I properly renew it?

As mentioned above, there is no renewing of certificates. Follow the steps below to revoke and regenerate a new certificate, along with the affected provisioning profiles. The instructions have been updated for Xcode 8.3 and Xcode 9.

Step 1: Revoke the expiring certificate

Login to Member Center > Certificates, Identifiers & Profiles, select the expiring certificate. Take note of the expiry date of the certificate, and click the ‘Revoke’ button.

Select the expiring certificate and click the Revoke button

Step 2: (Optional) Remove the revoked certificate from your Keychain

Optionally, if you don't want to have the revoked certificate lying around in your system, you can delete them from your system. Unfortunately, the ‘Delete Certificate’ function in Xcode > Preferences > Accounts > [Apple ID] > Manage Certificates… seems to be always disabled, so we have to delete them manually using Keychain Access.app (/Applications/Utilities/Keychain Access.app).

Optionally remove the revoked certificate using Keychain Access.app

Filter by ‘login’ Keychains and ‘Certificates’ Category. Locate the certificate that you've just revoked in Step 1.

Depending on the certificate that you've just revoked, search for either ‘Mac’ or ‘iPhone’. Mac App Store distribution certificates begin with “3rd Party Mac Developer”, and iOS App Store distribution certificates begin with “iPhone Distribution”.

You can locate the revoked certificate based on the team name, the type of certificate (Mac or iOS) and the expiry date of the certificate you've noted down in Step 1.

Step 3: Request a new certificate using Xcode

Under Xcode > Preferences > Accounts > [Apple ID] > Manage Certificates…, click on the ‘+’ button on the lower left, and select the same type of certificate that you've just revoked to let Xcode request a new one for you.

Let Xcode request a new certificate for you in Xcode > Preferences > Accounts > Apple ID > Manage Certificates…

Step 4: Update your provisioning profiles to use the new certificate

After which, head back to Member Center > Certificates, Identifiers & Profiles > Provisioning Profiles > All. You'll notice that any provisioning profile that made use of the revoked certificate is now reflected as ‘Invalid’.

Notice that any provisioning profile that made use of the revoked certificate is now reflected as ‘Invalid’

Click on any profile that are now ‘Invalid’, click ‘Edit’, then choose the newly created certificate, then click on ‘Generate’. Repeat this until all provisioning profiles are regenerated with the new certificate.

Choose the newly created certificate, and click on Generate

Step 5: Use Xcode to download the new provisioning profiles

Tip: Before you download the new profiles using Xcode, you may want to clear any existing and possibly invalid provisioning profiles from your Mac. You can do so by removing all the profiles from ~/Library/MobileDevice/Provisioning Profiles

Back in Xcode > Preferences > Accounts > [Apple ID], click on the ‘Download All Profiles’ button to ask Xcode to download all the provisioning profiles from your developer account.

Click Download All Profiles for Xcode to download all the newly generated profiles

Is there an opposite of include? for Ruby Arrays?

Try this, it's pure Ruby so there's no need to add any peripheral frameworks

if @players.include?(p.name) == false do 
  ...
end

I was struggling with a similar logic for a few days, and after checking several forums and Q&A boards to little avail it turns out the solution was actually pretty simple.

Reloading a ViewController

If you want to reload a ViewController initially loaded from a XIB, you can use the next UIViewController extension:

extension UIViewController {
    func reloadViewFromNib() {
        let parent = view.superview
        view.removeFromSuperview()
        view = nil
        parent?.addSubview(view) // This line causes the view to be reloaded 
    }
}

Polynomial time and exponential time

Check this out.

Exponential is worse than polynomial.

O(n^2) falls into the quadratic category, which is a type of polynomial (the special case of the exponent being equal to 2) and better than exponential.

Exponential is much worse than polynomial. Look at how the functions grow

n    = 10    |     100   |      1000

n^2  = 100   |   10000   |   1000000 

k^n  = k^10  |   k^100   |    k^1000

k^1000 is exceptionally huge unless k is smaller than something like 1.1. Like, something like every particle in the universe would have to do 100 billion billion billion operations per second for trillions of billions of billions of years to get that done.

I didn't calculate it out, but ITS THAT BIG.

Tool to generate JSON schema from JSON data

For the offline tools that support multiple inputs, the best I've seen so far is https://github.com/wolverdude/GenSON/ I'd like to see a tool that takes filenames on standard input because I have thousands of files. However, I run out of open file descriptors, so make sure the files are closed. I'd also like to see JSON Schema generators that handle recursion. I am now working on generating Java classes from JSON objects in hopes of going to JSON Schema from my Java classes. Here is my GenSON script if you are curious or want to identify bugs in it.

#!/bin/sh
ulimit -n 4096
rm x3d*json
cat /dev/null > x3d.json
find ~/Downloads/www.web3d.org/x3d/content/examples -name '*json' -      print| xargs node goodJSON.js | xargs python bin/genson.py -i 2 -s     x3d.json >> x3d.json
split -p '^{' x3d.json x3d.json
python bin/genson.py -i 2 -s x3d.jsonaa -s x3d.jsonab /Users/johncarlson/Downloads/www.web3d.org/x3d/content/examples/X3dForWebAuthors/Chapter02-GeometryPrimitives/Box.json > x3dmerge.json 

Detect whether there is an Internet connection available on Android

The getActiveNetworkInfo() method of ConnectivityManager returns a NetworkInfo instance representing the first connected network interface it can find or null if none if the interfaces are connected. Checking if this method returns null should be enough to tell if an internet connection is available.

private boolean isNetworkAvailable() {
     ConnectivityManager connectivityManager = (ConnectivityManager) getSystemService(Context.CONNECTIVITY_SERVICE);
     NetworkInfo activeNetworkInfo = connectivityManager.getActiveNetworkInfo();
     return activeNetworkInfo != null; 
}

You will also need:

in your android manifest.

Edit:

Note that having an active network interface doesn't guarantee that a particular networked service is available. Networks issues, server downtime, low signal, captive portals, content filters and the like can all prevent your app from reaching a server. For instance you can't tell for sure if your app can reach Twitter until you receive a valid response from the Twitter service.

getActiveNetworkInfo() shouldn't never give null. I don't know what they were thinking when they came up with that. It should give you an object always.

How do I get a Date without time in Java?

Do you absolutely have to use java.util.Date? I would thoroughly recommend that you use Joda Time or the java.time package from Java 8 instead. In particular, while Date and Calendar always represent a particular instant in time, with no such concept as "just a date", Joda Time does have a type representing this (LocalDate). Your code will be much clearer if you're able to use types which represent what you're actually trying to do.

There are many, many other reasons to use Joda Time or java.time instead of the built-in java.util types - they're generally far better APIs. You can always convert to/from a java.util.Date at the boundaries of your own code if you need to, e.g. for database interaction.

Failed to connect to mailserver at "localhost" port 25

PHP mail function can send email in 2 scenarios:

a. Try to send email via unix sendmail program At linux it will exec program "sendmail", put all params to sendmail and that all.

OR

b. Connect to mail server (using smtp protocol and host/port/username/pass from php.ini) and try to send email.

If php unable to connect to email server it will give warning (and you see such workning in your logs) To solve it, install smtp server on your local machine or use any available server. How to setup / configure smtp you can find on php.net

How to ignore a particular directory or file for tslint?

Can confirm that on version tslint 5.11.0 it works by modifying lint script in package.json by defining exclude argument:

"lint": "ng lint --exclude src/models/** --exclude package.json"

Cheers!!

Set Background color programmatically

The previous answers are now deprecated, you need to use ContextCompat.getColor to retrieve the color properly:

root.setBackgroundColor(ContextCompat.getColor(getActivity(), R.color.white));

How do I create a branch?

Normally you'd copy it to svn+ssh://host.example.com/repos/project/branches/mybranch so that you can keep several branches in the repository, but your syntax is valid.

Here's some advice on how to set up your repository layout.

How to create User/Database in script for Docker Postgres

You can use this commands:

docker exec -it yournamecontainer psql -U postgres -c "CREATE DATABASE mydatabase ENCODING 'LATIN1' TEMPLATE template0 LC_COLLATE 'C' LC_CTYPE 'C';"

docker exec -it yournamecontainer psql -U postgres -c "GRANT ALL PRIVILEGES ON DATABASE postgres TO postgres;"

Format telephone and credit card numbers in AngularJS

Try using phoneformat.js (http://www.phoneformat.com/), you can not only format phone number based on user locales (en-US, ja-JP, fr-FR, de-DE etc) but it also validates the phone number. Its very robust library based on googles libphonenumber project.

How to check if array element is null to avoid NullPointerException in Java

You have more going on than you said. I ran the following expanded test from your example:

public class test {

    public static void main(String[] args) {
        Object[][] someArray = new Object[5][];
        someArray[0] = new Object[10];
        someArray[1] = null;
        someArray[2] = new Object[1];
        someArray[3] = null;
        someArray[4] = new Object[5];

        for (int i=0; i<=someArray.length-1; i++) {
            if (someArray[i] != null) {
                System.out.println("not null");
            } else {
                System.out.println("null");
            }
        }
    }
}

and got the expected output:

$ /cygdrive/c/Program\ Files/Java/jdk1.6.0_03/bin/java -cp . test
not null
null
not null
null
not null

Are you possibly trying to check the lengths of someArray[index]?

Easiest way to convert a List to a Set in Java

Set<E> alphaSet  = new HashSet<E>(<your List>);

or complete example

import java.util.ArrayList;
import java.util.HashSet;
import java.util.List;
import java.util.Set;

public class ListToSet
{
    public static void main(String[] args)
    {
        List<String> alphaList = new ArrayList<String>();
        alphaList.add("A");
        alphaList.add("B");
        alphaList.add("C");
        alphaList.add("A");
        alphaList.add("B");
        System.out.println("List values .....");
        for (String alpha : alphaList)
        {
            System.out.println(alpha);
        }
        Set<String> alphaSet = new HashSet<String>(alphaList);
        System.out.println("\nSet values .....");
        for (String alpha : alphaSet)
        {
            System.out.println(alpha);
        }
    }
}

how to run two commands in sudo?

For your command you also could refer to the following example:

sudo sh -c 'whoami; whoami'

assign function return value to some variable using javascript

You could simply return a value from the function:

var response = 0;

function doSomething() {
    // some code
    return 10;
}
response = doSomething();

Hide options in a select list using jQuery

You cannot do this x-browser. If I recall ie has issues. The easiest thing to do is keep a cloned copy of the select before you remove items, this allows you to easily remove and then append the missing items back.

How to resolve the "ADB server didn't ACK" error?

if you are using any mobile suit like mobogenie or something that might also will make this issue. try killing that too from the task manager.

Note : i faced the same issue, tried the above solution. That didn't work, finally found out this solution.May useful for someone else!..

Angular 2: 404 error occur when I refresh through the browser

In fact, it's normal that you have a 404 error when refreshing your application since the actual address within the browser is updating (and without # / hashbang approach). By default, HTML5 history is used for reusing in Angular2.

To fix the 404 error, you need to update your server to serve the index.html file for each route path you defined.

If you want to switch to the HashBang approach, you need to use this configuration:

import {bootstrap} from 'angular2/platform/browser';
import {provide} from 'angular2/core';
import {ROUTER_PROVIDERS} from 'angular2/router';
import {LocationStrategy, HashLocationStrategy} from '@angular/common';

import {MyApp} from './myapp';

bootstrap(MyApp, [
  ROUTER_PROVIDERS,
  {provide: LocationStrategy, useClass: HashLocationStrategy}
]);

In this case, when you refresh the page, it will be displayed again (but you will have a # in your address).

This link could help you as well: When I refresh my website I get a 404. This is with Angular2 and firebase.

Hope it helps you, Thierry

Get Android .apk file VersionName or VersionCode WITHOUT installing apk

Using apkanalyzer that is now part of cmdline-tools:

$ apkanalyzer manifest version-code my_app.apk
1
$ apkanalyzer manifest version-name my_app.apk
1.2.3.4

Maven in Eclipse: step by step installation

First install maven in your system and set Maven environment variables

  1. M2_HOME: ....\apache-maven-3.0.5 \ maven installed path
  2. M2_Repo: D:\maven_repo \If change maven repo location
  3. M2: %M2_HOME%\bin

Steps to Configures maven on Eclipse IDE:

  • Select Window -> Preferences Note: If Maven option is not present, then add maven 3 to eclipse or install it.
  • Add the Maven location of your system

To check maven is configured properly:

  • Open Eclipse and click on Windows -> Preferences

  • Choose Maven from left panel, and select installations.

  • Click on Maven -> "User Settings" option form left panel, to check local repository location.

Radio/checkbox alignment in HTML/CSS

The following works in Firefox and Opera (sorry, I do not have access to other browsers at the moment):

<div class="form-field">
    <input id="option1" type="radio" name="opt"/>
    <label for="option1">Option 1</label>
</div>

The CSS:

.form-field * {
    vertical-align: middle;
}

Java generating Strings with placeholders

If you can change the format of your placeholder, you could use String.format(). If not, you could also replace it as pre-processing.

String.format("hello %s!", "world");

More information in this other thread.

Back to previous page with header( "Location: " ); in PHP

try:

header('Location: ' . $_SERVER['HTTP_REFERER']);

Note that this may not work with secure pages (HTTPS) and it's a pretty bad idea overall as the header can be hijacked, sending the user to some other destination. The header may not even be sent by the browser.

Ideally, you will want to either:

  • Append the return address to the request as a query variable (eg. ?back=/list)
  • Define a return page in your code (ie. all successful form submissions redirect to the listing page)
  • Provide the user the option of where they want to go next (eg. Save and continue editing or just Save)

Does "\d" in regex mean a digit?

This is just a guess, but I think your editor actually matches every single digit — 1 2 3 — but only odd matches are highlighted, to distinguish it from the case when the whole 123 string is matched.

Most regex consoles highlight contiguous matches with different colors, but due to the plugin settings, terminal limitations or for some other reason, only every other group might be highlighted in your case.

SQL Server Output Clause into a scalar variable

Way later but still worth mentioning is that you can also use variables to output values in the SET clause of an UPDATE or in the fields of a SELECT;

DECLARE @val1 int;
DECLARE @val2 int;
UPDATE [dbo].[PortalCounters_TEST]
SET @val1 = NextNum, @val2 = NextNum = NextNum + 1
WHERE [Condition] = 'unique value'
SELECT @val1, @val2

In the example above @val1 has the before value and @val2 has the after value although I suspect any changes from a trigger would not be in val2 so you'd have to go with the output table in that case. For anything but the simplest case, I think the output table will be more readable in your code as well.

One place this is very helpful is if you want to turn a column into a comma-separated list;

DECLARE @list varchar(max) = '';
DECLARE @comma varchar(2) = '';
SELECT @list = @list + @comma + County, @comma = ', ' FROM County
print @list

Find JavaScript function definition in Chrome

This landed in Chrome on 2012-08-26 Not sure about the exact version, I noticed it in Chrome 24.

A screenshot is worth a million words:

 Chrome Dev Tools > Console > Show Function Definition

I am inspecting an object with methods in the Console. Clicking on the "Show function definition" takes me to the place in the source code where the function is defined. Or I can just hover over the function () { word to see function body in a tooltip. You can easily inspect the whole prototype chain like this! CDT definitely rock!!!

Hope you all find it helpful!

Append to the end of a file in C

Open with append:

pFile2 = fopen("myfile2.txt", "a");

then just write to pFile2, no need to fseek().

Writing binary number system in C code

Standard C doesn't define binary constants. There's a GNU (I believe) extension though (among popular compilers, clang adapts it as well): the 0b prefix:

int foo = 0b1010;

If you want to stick with standard C, then there's an option: you can combine a macro and a function to create an almost readable "binary constant" feature:

#define B(x) S_to_binary_(#x)

static inline unsigned long long S_to_binary_(const char *s)
{
        unsigned long long i = 0;
        while (*s) {
                i <<= 1;
                i += *s++ - '0';
        }
        return i;
}

And then you can use it like this:

int foo = B(1010);

If you turn on heavy compiler optimizations, the compiler will most likely eliminate the function call completely (constant folding) or will at least inline it, so this won't even be a performance issue.

Proof:

The following code:

#include <stdio.h>
#include <stdlib.h>
#include <limits.h>
#include <string.h>


#define B(x) S_to_binary_(#x)

static inline unsigned long long S_to_binary_(const char *s)
{
    unsigned long long i = 0;
    while (*s) {
        i <<= 1;
        i += *s++ - '0';
    }
    return i;
}

int main()
{
    int foo = B(001100101);

    printf("%d\n", foo);

    return 0;
}

has been compiled using clang -o baz.S baz.c -Wall -O3 -S, and it produced the following assembly:

    .section    __TEXT,__text,regular,pure_instructions
    .globl  _main
    .align  4, 0x90
_main:                                  ## @main
    .cfi_startproc
## BB#0:
    pushq   %rbp
Ltmp2:
    .cfi_def_cfa_offset 16
Ltmp3:
    .cfi_offset %rbp, -16
    movq    %rsp, %rbp
Ltmp4:
    .cfi_def_cfa_register %rbp
    leaq    L_.str1(%rip), %rdi
    movl    $101, %esi               ## <= This line!
    xorb    %al, %al
    callq   _printf
    xorl    %eax, %eax
    popq    %rbp
    ret
    .cfi_endproc

    .section    __TEXT,__cstring,cstring_literals
L_.str1:                                ## @.str1
    .asciz   "%d\n"


.subsections_via_symbols

So clang completely eliminated the call to the function, and replaced its return value with 101. Neat, huh?

An Authentication object was not found in the SecurityContext - Spring 3.2.2

I encountered the same error while using SpringBoot 2.1.4, along with Spring Security 5 (I believe). After one day of trying everything that Google had to offer, I discovered the cause of error in my case. I had a setup of micro-services, with the Auth server being different from the Resource Server. I had the following lines in my application.yml which prevented 'auto-configuration' despite of having included dependencies spring-boot-starter-security, spring-security-oauth2 and spring-security-jwt. I had included the following in the properties (during development) which caused the error.

spring:
  autoconfigure:
    exclude: org.springframework.boot.autoconfigure.security.servlet.SecurityAutoConfiguration

Commenting it out solved it for me.

#spring:
#  autoconfigure:
#    exclude: org.springframework.boot.autoconfigure.security.servlet.SecurityAutoConfiguration

Hope, it helps someone.

IPython/Jupyter Problems saving notebook as PDF

What I found was that the nbconvert/utils/pandoc.py had a code bug that resulted in the error for my machine. The code checks if pandoc is in your environmental variables path. For my machine the answer is no. However pandoc.exe is!

Solution was to add '.exe' to the code on line 69

if __version is None:
    if not which('pandoc.exe'):
        raise PandocMissing()

The same goes for 'xelatex' is not installed. Add to the file nbconvert/exporters/pdf.py on line 94

    cmd = which(command_list[0]+'.exe')

error code 1292 incorrect date value mysql

An update. Dates of the form '2019-08-00' will trigger the same error. Adding the lines:

[mysqld]

sql_mode="NO_ZERO_IN_DATE,NO_ZERO_DATE,ERROR_FOR_DIVISION_BY_ZERO,NO_AUTO_CREATE_USER,NO_ENGINE_SUBSTITUTION" 

to mysql.cnf fixes this too. Inserting malformed dates now generates warnings for values out of range but does insert the data.

How do I cancel an HTTP fetch() request?

Let's polyfill:

if(!AbortController){
  class AbortController {
    constructor() {
      this.aborted = false;
      this.signal = this.signal.bind(this);
    }
    signal(abortFn, scope) {
      if (this.aborted) {
        abortFn.apply(scope, { name: 'AbortError' });
        this.aborted = false;
      } else {
        this.abortFn = abortFn.bind(scope);
      }
    }
    abort() {
      if (this.abortFn) {
        this.abortFn({ reason: 'canceled' });
        this.aborted = false;
      } else {
        this.aborted = true;
      }
    }
  }

  const originalFetch = window.fetch;

  const customFetch = (url, options) => {
    const { signal } = options || {};

    return new Promise((resolve, reject) => {
      if (signal) {
        signal(reject, this);
      }
      originalFetch(url, options)
        .then(resolve)
        .catch(reject);
    });
  };

  window.fetch = customFetch;
}

Please have in mind that the code is not tested! Let me know if you have tested it and something didn't work. It may give you warnings that you try to overwrite the 'fetch' function from the JavaScript official library.

"Cannot send session cache limiter - headers already sent"

"Headers already sent" means that your PHP script already sent the HTTP headers, and as such it can't make modifications to them now.

Check that you don't send ANY content before calling session_start. Better yet, just make session_start the first thing you do in your PHP file (so put it at the absolute beginning, before all HTML etc).

Listen to port via a Java socket

What do you actually want to achieve? What your code does is it tries to connect to a server located at 192.168.1.104:4000. Is this the address of a server that sends the messages (because this looks like a client-side code)? If I run fake server locally:

$ nc -l 4000

...and change socket address to localhost:4000, it will work and try to read something from nc-created server.

What you probably want is to create a ServerSocket and listen on it:

ServerSocket serverSocket = new ServerSocket(4000);
Socket socket = serverSocket.accept();

The second line will block until some other piece of software connects to your machine on port 4000. Then you can read from the returned socket. Look at this tutorial, this is actually a very broad topic (threading, protocols...)

How can I convert a zero-terminated byte array to string?

Only use for performance tuning.

package main

import (
    "fmt"
    "reflect"
    "unsafe"
)

func BytesToString(b []byte) string {
    return *(*string)(unsafe.Pointer(&b))
}

func StringToBytes(s string) []byte {
    return *(*[]byte)(unsafe.Pointer(&s))
}

func main() {
    b := []byte{'b', 'y', 't', 'e'}
    s := BytesToString(b)
    fmt.Println(s)
    b = StringToBytes(s)
    fmt.Println(string(b))
}

In C# check that filename is *possibly* valid (not that it exists)

There are several methods you could use that exist in the System.IO namespace:

Directory.GetLogicalDrives() // Returns an array of strings like "c:\"
Path.GetInvalidFileNameChars() // Returns an array of characters that cannot be used in a file name
Path.GetInvalidPathChars() // Returns an array of characters that cannot be used in a path.

As suggested you could then do this:

bool IsValidFilename(string testName) {
    string regexString = "[" + Regex.Escape(Path.GetInvalidPathChars()) + "]";
    Regex containsABadCharacter = new Regex(regexString);
    if (containsABadCharacter.IsMatch(testName)) {
        return false;
    }

    // Check for drive
    string pathRoot = Path.GetPathRoot(testName);
    if (Directory.GetLogicalDrives().Contains(pathRoot)) {
        // etc
    }

    // other checks for UNC, drive-path format, etc

    return true;
}

How do I localize the jQuery UI Datepicker?

I figured out the demo and implemented it the following way:

$.datepicker.setDefaults(
  $.extend(
    {'dateFormat':'dd-mm-yy'},
    $.datepicker.regional['nl']
  )
);

I needed to set the default for the dateformat too ...

Display Animated GIF

Glide

Image Loader Library for Android, recommended by Google.

  • Glide is quite similar to Picasso but this is much faster than Picasso.
  • Glide consumes less memory than Picasso.

What that Glide has but Picasso doesn't

An ability to load GIF Animation to a simple ImageView might be the most interesting feature of Glide. And yes, you can't do that with Picasso. enter image description here Some important links-

  1. https://github.com/bumptech/glide
  2. http://inthecheesefactory.com/blog/get-to-know-glide-recommended-by-google/en

How to increase dbms_output buffer?

Here you go:

DECLARE
BEGIN
  dbms_output.enable(NULL); -- Disables the limit of DBMS
  -- Your print here !
END;

C++: Where to initialize variables in constructor

In short, always prefer initialization lists when possible. 2 reasons:

  • If you do not mention a variable in a class's initialization list, the constructor will default initialize it before entering the body of the constructor you've written. This means that option 2 will lead to each variable being written to twice, once for the default initialization and once for the assignment in the constructor body.

  • Also, as mentioned by mwigdahl and avada in other answers, const members and reference members can only be initialized in an initialization list.

Also note that variables are always initialized on the order they are declared in the class declaration, not in the order they are listed in an initialization list (with proper warnings enabled a compiler will warn you if a list is written out of order). Similarly, destructors will call member destructors in the opposite order, last to first in the class declaration, after the code in your class's destructor has executed.

String strip() for JavaScript?

If you're already using jQuery, then you may want to have a look at jQuery.trim() which is already provided with jQuery.

Zabbix server is not running: the information displayed may not be current

i had similar problem and my gui reported problem with cache, i change it zabbix-server.conf to 32M and now is ok, zabbix is an intelligent tool, please if it possible check problems in gui first. I had to much hosts ... for default cache.

Add back button to action bar

this one worked for me:

@Override
protected void onCreate(Bundle savedInstanceState) {
    super.onCreate(savedInstanceState);
    setContentView(R.layout.activity_your_activity);
    getSupportActionBar().setDisplayHomeAsUpEnabled(true);
    // ... other stuff
}

@Override
public boolean onSupportNavigateUp(){
    finish();
    return true;
}

The method onSupportNavigateUp() is called when you use the back button in the SupportActionBar.

Setting a PHP $_SESSION['var'] using jQuery

Whats you are looking for is jQuery Ajax. And then just setup a php page to process the request.

How can I print out C++ map values?

If your compiler supports (at least part of) C++11 you could do something like:

for (auto& t : myMap)
    std::cout << t.first << " " 
              << t.second.first << " " 
              << t.second.second << "\n";

For C++03 I'd use std::copy with an insertion operator instead:

typedef std::pair<string, std::pair<string, string> > T;

std::ostream &operator<<(std::ostream &os, T const &t) { 
    return os << t.first << " " << t.second.first << " " << t.second.second;
}

// ...
std:copy(myMap.begin(), myMap.end(), std::ostream_iterator<T>(std::cout, "\n"));

ActivityCompat.requestPermissions not showing dialog box

This just happened to me. It turned out I was requesting ALL permissions, when I needed to filter to just DANGEROUS permissions, and it suddenly started working.

fun requestPermissions() {
    val missingDangerPermissions = PERMISSIONS
            .filter { ContextCompat.checkSelfPermission(this, it) != PackageManager.PERMISSION_GRANTED }
            .filter { this.getPackageManager().getPermissionInfo(it, PackageManager.GET_META_DATA).protectionLevel == PermissionInfo.PROTECTION_DANGEROUS } // THIS FILTER HERE!

    if (missingDangerPermissions.isNotEmpty()) {
        Log.i(TAG, "Requesting dangerous permission to $missingDangerPermissions.")
        ActivityCompat.requestPermissions(this,
                missingDangerPermissions.toTypedArray(),
                REQUEST_CODE_REQUIRED_PERMISSIONS);
        return
    } else {
        Log.i(TAG, "We had all the permissions we needed (yay!)")
    }
}

Rails: Address already in use - bind(2) (Errno::EADDRINUSE)

If the above solutions don't work on ubuntu/linux then you can try this

sudo fuser -k -n tcp port

Run it several times to kill processes on your port of choosing. port could be 3000 for example. You would have killed all the processes if you see no output after running the command

How to get response using cURL in PHP

am using this simple one

´´´´ class Connect {

public $url;
public $path;
public $username;
public $password;

    $ch = curl_init();

    curl_setopt($ch, CURLOPT_URL, $this->url);
    curl_setopt($ch, CURLOPT_RETURNTRANSFER, 1);

    curl_setopt($ch, CURLOPT_USERPWD, "$this->username:$this->password");

    //PROPFIND request that lists all requested properties.
    curl_setopt($ch, CURLOPT_CUSTOMREQUEST, "PROPFIND");
    $response = curl_exec($ch);

    curl_close($ch);

Given URL is not allowed by the Application configuration

This can be caused by incorrect app-ID

In my ionic sample I had the same issue because I had inserted a different "app-ID" in my ionic app other than the app-ID I received from Facebook developer account.

so we have to carefully insert the relavent appID

git stash apply version

Just making simple to understand for beginners.

Check your git stash list with below command :

git stash list

And then apply with below command:

git stash apply stash@{n}

For example: I am applying my latest stash(latest is always index {0} on top of the stash list).

 git stash apply stash@{0}

How can I insert data into Database Laravel?

make sure you use the POST to insert the data. Actually you were using GET.

Exception from HRESULT: 0x800A03EC Error

Got this error also....

it occurs when save to filepath contains invalid characters, in my case:

path = "C:/somefolder/anotherfolder\file.xls";

Note the existence of both \ and /

*Also may occur if trying to save to directory which doesn't already exist.

VBA Copy Sheet to End of Workbook (with Hidden Worksheets)

Try this

Sub Sample()
    Dim test As Worksheet
    Sheets(1).Copy After:=Sheets(Sheets.Count)
    Set test = ActiveSheet
    test.Name = "copied sheet!"
End Sub

How to start an Android application from the command line?

Example here.

Pasted below:

This is about how to launch android application from the adb shell.

Command: am

Look for invoking path in AndroidManifest.xml

Browser app::

# am start -a android.intent.action.MAIN -n com.android.browser/.BrowserActivity
Starting: Intent { action=android.intent.action.MAIN comp={com.android.browser/com.android.browser.BrowserActivity} }
Warning: Activity not started, its current task has been brought to the front

Settings app::

# am start -a android.intent.action.MAIN -n com.android.settings/.Settings
Starting: Intent { action=android.intent.action.MAIN comp={com.android.settings/com.android.settings.Settings} }

Check if element exists in jQuery

If you have a class on your element, then you can try the following:

if( $('.exists_content').hasClass('exists_content') ){
 //element available
}

Ruby max integer

In ruby Fixnums are automatically converted to Bignums.

To find the highest possible Fixnum you could do something like this:

class Fixnum
 N_BYTES = [42].pack('i').size
 N_BITS = N_BYTES * 8
 MAX = 2 ** (N_BITS - 2) - 1
 MIN = -MAX - 1
end
p(Fixnum::MAX)

Shamelessly ripped from a ruby-talk discussion. Look there for more details.

Functions that return a function

Returning the function name without () returns a reference to the function, which can be assigned as you've done with var s = a(). s now contains a reference to the function b(), and calling s() is functionally equivalent to calling b().

// Return a reference to the function b().
// In your example, the reference is assigned to var s
return b;

Calling the function with () in a return statement executes the function, and returns whatever value was returned by the function. It is similar to calling var x = b();, but instead of assigning the return value of b() you are returning it from the calling function a(). If the function b() itself does not return a value, the call returns undefined after whatever other work is done by b().

// Execute function b() and return its value
return b();
// If b() has no return value, this is equivalent to calling b(), followed by
// return undefined;

How to navigate a few folders up?

public static string AppRootDirectory()
        {
            string _BaseDirectory = AppDomain.CurrentDomain.BaseDirectory;
            return Path.GetFullPath(Path.Combine(_BaseDirectory, @"..\..\"));
        }

Where is the web server root directory in WAMP?

In WAMP the files are served by the Apache component (the A in WAMP).

In Apache, by default the files served are located in the subdirectory htdocs of the installation directory. But this can be changed, and is actually changed when WAMP installs Apache.

The location from where the files are served is named the DocumentRoot, and is defined using a variable in Apache configuration file. The default value is the subdirectory htdocs relative to what is named the ServerRoot directory.

By default the ServerRoot is the installation directory of Apache. However this can also be redefined into the configuration file, or using the -d option of the command httpd which is used to launch Apache. The value in the configuration file overrides the -d option.

The configuration file is by default conf/httpd.conf relative to ServerRoot. But this can be changed using the -f option of command httpd.

When WAMP installs itself, it modify the default configuration file with DocumentRoot c:/wamp/www/. The files to be served need to be located here and not in the htdocs default directory.

You may change this location set by WAMP, either by modifying DocumentRoot in the default configuration file, or by using one of the two command line options -f or -d which point explicitly or implicity to a new configuration file which may hold a different value for DocumentRoot (in that case the new file needs to contain this definition, but also the rest of the configuration found in the default configuration file).

Python try-else

The statements in the else block are executed if execution falls off the bottom of the try - if there was no exception. Honestly, I've never found a need.

However, Handling Exceptions notes:

The use of the else clause is better than adding additional code to the try clause because it avoids accidentally catching an exception that wasn’t raised by the code being protected by the try ... except statement.

So, if you have a method that could, for example, throw an IOError, and you want to catch exceptions it raises, but there's something else you want to do if the first operation succeeds, and you don't want to catch an IOError from that operation, you might write something like this:

try:
    operation_that_can_throw_ioerror()
except IOError:
    handle_the_exception_somehow()
else:
    # we don't want to catch the IOError if it's raised
    another_operation_that_can_throw_ioerror()
finally:
    something_we_always_need_to_do()

If you just put another_operation_that_can_throw_ioerror() after operation_that_can_throw_ioerror, the except would catch the second call's errors. And if you put it after the whole try block, it'll always be run, and not until after the finally. The else lets you make sure

  1. the second operation's only run if there's no exception,
  2. it's run before the finally block, and
  3. any IOErrors it raises aren't caught here

Accessing all items in the JToken

If you know the structure of the json that you're receiving then I'd suggest having a class structure that mirrors what you're receiving in json.

Then you can call its something like this...

AddressMap addressMap = JsonConvert.DeserializeObject<AddressMap>(json);

(Where json is a string containing the json in question)

If you don't know the format of the json you've receiving then it gets a bit more complicated and you'd probably need to manually parse it.

check out http://www.hanselman.com/blog/NuGetPackageOfTheWeek4DeserializingJSONWithJsonNET.aspx for more info

Bootstrap center heading

Per your comments, to center all headings all you have to do is add text-align:center to all of them at the same time, like so:

CSS

    h1, h2, h3, h4, h5, h6 {
        text-align: center;
    }

Why is textarea filled with mysterious white spaces?

Open (and close!) your PHP tags right after, and before, your textarea tags:

<textarea style="width:350px; height:80px;" cols="42" rows="5" name="sitelink"><?php
  if($siteLink_val) echo $siteLink_val;
?></textarea>

How to add image background to btn-default twitter-bootstrap button?

Have you tried using a icon font like http://fortawesome.github.io/Font-Awesome/

Bootstrap comes with their own library, but it doesn't have as many icons as Font Awesome.

http://getbootstrap.com/components/#glyphicons

Python Tkinter clearing a frame

https://anzeljg.github.io/rin2/book2/2405/docs/tkinter/universal.html

w.winfo_children()
Returns a list of all w's children, in their stacking order from lowest (bottom) to highest (top).

for widget in frame.winfo_children():
    widget.destroy()

Will destroy all the widget in your frame. No need for a second frame.

Generating random numbers with normal distribution in Excel

IF you have excel 2007, you can use

=NORMSINV(RAND())*SD+MEAN

Because there was a big change in 2010 about excel's function

What does "The APR based Apache Tomcat Native library was not found" mean?

Unless you're running a production server, don't worry about this message. This is a library which is used to improve performance (on production systems). From Apache Portable Runtime (APR) based Native library for Tomcat:

Tomcat can use the Apache Portable Runtime to provide superior scalability, performance, and better integration with native server technologies. The Apache Portable Runtime is a highly portable library that is at the heart of Apache HTTP Server 2.x. APR has many uses, including access to advanced IO functionality (such as sendfile, epoll and OpenSSL), OS level functionality (random number generation, system status, etc), and native process handling (shared memory, NT pipes and Unix sockets).

Byte[] to InputStream or OutputStream

You create and use byte array I/O streams as follows:

byte[] source = ...;
ByteArrayInputStream bis = new ByteArrayInputStream(source);
// read bytes from bis ...

ByteArrayOutputStream bos = new ByteArrayOutputStream();
// write bytes to bos ...
byte[] sink = bos.toByteArray();

Assuming that you are using a JDBC driver that implements the standard JDBC Blob interface (not all do), you can also connect a InputStream or OutputStream to a blob using the getBinaryStream and setBinaryStream methods1, and you can also get and set the bytes directly.

(In general, you should take appropriate steps to handle any exceptions, and close streams. However, closing bis and bos in the example above is unnecessary, since they aren't associated with any external resources; e.g. file descriptors, sockets, database connections.)

1 - The setBinaryStream method is really a getter. Go figure.

Android Service Stops When App Is Closed

try this, it will keep the service running in the background.

BackServices.class

public class BackServices extends Service{

    @Override
    public IBinder onBind(Intent arg0) {
        // TODO Auto-generated method stub
        return null;
    }

    @Override
   public int onStartCommand(Intent intent, int flags, int startId) {
      // Let it continue running until it is stopped.
      Toast.makeText(this, "Service Started", Toast.LENGTH_LONG).show();
      return START_STICKY;
   }
   @Override
   public void onDestroy() {
      super.onDestroy();
      Toast.makeText(this, "Service Destroyed", Toast.LENGTH_LONG).show();
   }
}

in your MainActivity onCreate drop this line of code

startService(new Intent(getBaseContext(), BackServices.class));

Now the service will stay running in background.

jQuery Ajax POST example with PHP

Please check this. It is the complete Ajax request code.

$('#foo').submit(function(event) {
    // Get the form data
    // There are many ways to get this data using jQuery (you
    // can use the class or id also)
    var formData = $('#foo').serialize();
    var url = 'URL of the request';

    // Process the form.
    $.ajax({
        type        : 'POST',   // Define the type of HTTP verb we want to use
        url         : 'url/',   // The URL where we want to POST
        data        : formData, // Our data object
        dataType    : 'json',   // What type of data do we expect back.
        beforeSend : function() {

            // This will run before sending an Ajax request.
            // Do whatever activity you want, like show loaded.
        },
        success:function(response){
            var obj = eval(response);
            if(obj)
            {
                if(obj.error==0){
                    alert('success');
                }
                else{
                    alert('error');
                }
            }
        },
        complete : function() {
            // This will run after sending an Ajax complete
        },
        error:function (xhr, ajaxOptions, thrownError){
            alert('error occured');
            // If any error occurs in request
        }
    });

    // Stop the form from submitting the normal way
    // and refreshing the page
    event.preventDefault();
});

XPath test if node value is number

There's an amazing type test operator in XPath 2.0 you can use:

<xsl:if test="$number castable as xs:double">
    <!-- implementation -->
</xsl:if>

How do I render a shadow?

    viewStyle : {
    backgroundColor: '#F8F8F8',
    justifyContent: 'center',
    alignItems: 'center',
    height: 60,
    paddingTop: 15,
    shadowColor: '#000',
    shadowOffset: { width: 0, height: 2 },
    shadowOpacity: 0.2,
    marginBottom: 10,
    elevation: 2,
    position: 'relative'
},

Use marginBottom: 10

SecurityException during executing jnlp file (Missing required Permissions manifest attribute in main jar)

JAR File Manifest Attributes for Security

The JAR file manifest contains information about the contents of the JAR file, including security and configuration information.

Add the attributes to the manifest before the JAR file is signed.
See Modifying a Manifest File in the Java Tutorial for information on adding attributes to the JAR manifest file.

Permissions Attribute

The Permissions attribute is used to verify that the permissions level requested by the RIA when it runs matches the permissions level that was set when the JAR file was created.

Use this attribute to help prevent someone from re-deploying an application that is signed with your certificate and running it at a different privilege level. Set this attribute to one of the following values:

  • sandbox - runs in the security sandbox and does not require additional permissions.

  • all-permissions - requires access to the user's system resources.

Changes to Security Slider:

The following changes to Security Slider were included in this release(7u51):

  • Block Self-Signed and Unsigned applets on High Security Setting
  • Require Permissions Attribute for High Security Setting
  • Warn users of missing Permissions Attributes for Medium Security Setting

For more information, see Java Control Panel documentation.

enter image description here

sample MANIFEST.MF

Manifest-Version: 1.0
Ant-Version: Apache Ant 1.8.3
Created-By: 1.7.0_51-b13 (Oracle Corporation)
Trusted-Only: true
Class-Path: lib/plugin.jar
Permissions: sandbox
Codebase: http://myweb.de http://www.myweb.de
Application-Name: summary-applet

Javascript date regex DD/MM/YYYY

Do the following change to the jquery.validationengine-en.js file and update the dd/mm/yyyy inline validation by including leap year:

"date": {
    // Check if date is valid by leap year
    "func": function (field) {
    //var pattern = new RegExp(/^(\d{4})[\/\-\.](0?[1-9]|1[012])[\/\-\.](0?[1-9]|[12][0-9]|3[01])$/);
    var pattern = new RegExp(/^(0?[1-9]|[12][0-9]|3[01])[\/\-\.](0?[1-9]|1[012])[\/\-\.](\d{4})$/);
    var match = pattern.exec(field.val());
    if (match == null)
    return false;

    //var year = match[1];
    //var month = match[2]*1;
    //var day = match[3]*1;
    var year = match[3];
    var month = match[2]*1;
    var day = match[1]*1;
    var date = new Date(year, month - 1, day); // because months starts from 0.

    return (date.getFullYear() == year && date.getMonth() == (month - 1) && date.getDate() == day);
},
"alertText": "* Invalid date, must be in DD-MM-YYYY format"

T-SQL stored procedure that accepts multiple Id values

Try This One:

@list_of_params varchar(20) -- value 1, 2, 5, 7, 20 

SELECT d.[Name]
FROM Department d
where @list_of_params like ('%'+ CONVERT(VARCHAR(10),d.Id)  +'%')

very simple.

disable editing default value of text input

You can either use the readonly or the disabled attribute. Note that when disabled, the input's value will not be submitted when submitting the form.

<input id="price_to" value="price to" readonly="readonly">
<input id="price_to" value="price to" disabled="disabled">

How to fill a datatable with List<T>

Try this

static DataTable ConvertToDatatable(List<Item> list)
{
    DataTable dt = new DataTable();

    dt.Columns.Add("Name");
    dt.Columns.Add("Price");
    dt.Columns.Add("URL");
    foreach (var item in list)
    {
        var row = dt.NewRow();

        row["Name"] = item.Name;
        row["Price"] = Convert.ToString(item.Price);
        row["URL"] = item.URL;

        dt.Rows.Add(row);
    }

    return dt;
}

Replace NA with 0 in a data frame column

Since nobody so far felt fit to point out why what you're trying doesn't work:

  1. NA == NA doesn't return TRUE, it returns NA (since comparing to undefined values should yield an undefined result).
  2. You're trying to call apply on an atomic vector. You can't use apply to loop over the elements in a column.
  3. Your subscripts are off - you're trying to give two indices into a$x, which is just the column (an atomic vector).

I'd fix up 3. to get to a$x[is.na(a$x)] <- 0

How much does it cost to develop an iPhone application?

I'm one of the developers for Twitterrific and to be honest, I can't tell you how many hours have gone into the product. I can tell you everyone who upvoted the estimate of 160 hours for development and 40 hours for design is fricken' high. (I'd use another phrase, but this is my first post on Stack Overflow, so I'm being good.)

Twitterrific has had 4 major releases beginning with the iOS 1.0 (Jailbreak.) That's a lot of code, much of which is in the bit bucket (we refactor a lot with each major release.)

One thing that would be interesting to look at is the amount of time that we had to work on the iPad version. Apple set a product release date that gave us 60 days to do the development. (That was later extended by a week.)

We started the iPad development from scratch, but a lot of our underlying code (mostly models) was re-used. The development was done by two experienced iOS developers. One of them has even written a book: http://appdevmanual.com :-)

With such a short schedule, we worked some pretty long hours. Let's be conservative and say it's 10 hours per day for 6 days a week. That 60 hours for 9 weeks gives us 540 hours. With two developers, that's pretty close to 1,100 hours. Our rate for clients is $150 per hour giving $165,000 just for new code. Remember also that we were reusing a bunch existing code: I'm going to lowball the value of that code at $35,000 giving a total development cost of $200,000.

Anyone who's done serious iPhone development can tell you there's a lot of design work involved with any project. We had two designers working on that aspect of the product. They worked their asses off dealing with completely new interaction mechanics. Don't forget they didn't have any hardware to touch, either (LOTS of printouts!) Combined they spent at least 25 hours per week on the project. So 225 hours at $150/hr is about $34,000.

There are also other costs that many developer neglect to take into account: project management, testing, equipment. Again, if we lowball that figure at $16,000 we're at $250,000. This number falls in line with Jonathan Wight's (@schwa) $50-150K estimate with the 22 day Obama app.

Take another hit, dude.

Now if you want to build backend services for your app, that number's going to go up even more. Everyone seems surprised that Instagram chewed through $500K in venture funding to build a new frontend and backend. I'm not.

Python error: "IndexError: string index out of range"

It looks like you indented so_far = new too much. Try this:

if guess in word:
    print("\nYes!", guess, "is in the word!")

    # Create a new variable (so_far) to contain the guess
    new = ""
    i = 0
    for i in range(len(word)):
        if guess == word[i]:
            new += guess
        else:
            new += so_far[i]
    so_far = new # unindented this

Python __call__ special method practical example

IMHO __call__ method and closures give us a natural way to create STRATEGY design pattern in Python. We define a family of algorithms, encapsulate each one, make them interchangeable and in the end we can execute a common set of steps and, for example, calculate a hash for a file.

Resolve Javascript Promise outside function scope

How about creating a function to hijack the reject and return it ?

function createRejectablePromise(handler) {
  let _reject;

  const promise = new Promise((resolve, reject) => {
    _reject = reject;

    handler(resolve, reject);
  })

  promise.reject = _reject;
  return promise;
}

// Usage
const { reject } = createRejectablePromise((resolve) => {
  setTimeout(() => {
    console.log('resolved')
    resolve();
  }, 2000)

});

reject();

How do I set a program to launch at startup

Add an app to run automatically at startup in Windows 10

Step 1: Select the Windows Start button and scroll to find the app you want to run at startup.

Step 2: Right-click the app, select More, and then select Open file location. This opens the location where the shortcut to the app is saved. If there isn't an option for Open file location, it means the app can't run at startup.

Step 3: With the file location open, press the Windows logo key + R, type shell:startup, then select OK. This opens the Startup folder.

Step 4: Copy and paste the shortcut to the app from the file location to the Startup folder.

How do I install cURL on Windows?

I agree with Erroid, you must add PHP directory into PATH environment.

PATH=%PATH%;<Your_PHP_Path>

Example

PATH=%PATH%;C:\php

It worked for me. Thank you.

Is there a limit on an Excel worksheet's name length?

I just tested a couple paths using Excel 2013 on on Windows 7. I found the overall pathname limit to be 213 and the basename length to be 186. At least the error dialog for exceeding basename length is clear: basename error

And trying to move a not-too-long basename to a too-long-pathname is also very clear:enter image description here

The pathname error is deceptive, though. Quite unhelpful:enter image description here

This is a lazy Microsoft restriction. There's no good reason for these arbitrary length limits, but in the end, it’s a real bug in the error dialog.

jquery toggle slide from left to right and back

Use this...

$('#cat_icon').click(function () {
    $('#categories').toggle("slow");
    //$('#cat_icon').hide();
});
$('.panel_title').click(function () {
    $('#categories').toggle("slow");
    //$('#cat_icon').show();
});

See this Example

Greetings.

<SELECT multiple> - how to allow only one item selected?

I am coming here after searching google and change thing at my-end.

So I just change this sample and it will work with jquery at run-time.

$('select[name*="homepage_select"]').removeAttr('multiple')

http://jsfiddle.net/ajayendra2707/ejkxgy1p/5/

How to play ringtone/alarm sound in Android

This works fine:

AudioManager audioManager = (AudioManager) getSystemService(Context.AUDIO_SERVICE);
MediaPlayer thePlayer = MediaPlayer.create(getApplicationContext(), RingtoneManager.getDefaultUri(RingtoneManager.TYPE_NOTIFICATION));

try {
    thePlayer.setVolume((float) (audioManager.getStreamVolume(AudioManager.STREAM_NOTIFICATION) / 7.0)),
                        (float) (audioManager.getStreamVolume(AudioManager.STREAM_NOTIFICATION) / 7.0)));
} catch (Exception e) {
    e.printStackTrace();
}

thePlayer.start();

how to add or embed CKEditor in php page

Easy steps to Integrate ckeditor with php pages

step 1 : download the ckeditor.zip file

step 2 : paste ckeditor.zip file on root directory of the site or you can paste it where the files are (i did this one )

step 3 : extract the ckeditor.zip file

step 4 : open the desired php page you want to integrate with here page1.php

step 5 : add some javascript first below, this is to call elements of ckeditor and styling and css without this you will only a blank textarea

<script type="text/javascript" src="ckeditor/ckeditor.js"></script>

And if you are using in other sites, then use relative links for that here is one below

<script type="text/javascript" src="somedirectory/ckeditor/ckeditor.js"></script>

step 6 : now!, you need to call the work code of ckeditor on your page page1.php below is how you call it

<?php

// Make sure you are using a correct path here.
include_once 'ckeditor/ckeditor.php';

$ckeditor = new CKEditor();
$ckeditor->basePath = '/ckeditor/';
$ckeditor->config['filebrowserBrowseUrl'] = '/ckfinder/ckfinder.html';
$ckeditor->config['filebrowserImageBrowseUrl'] = '/ckfinder/ckfinder.html?type=Images';
$ckeditor->config['filebrowserFlashBrowseUrl'] = '/ckfinder/ckfinder.html?type=Flash';
$ckeditor->config['filebrowserUploadUrl'] = '/ckfinder/core/connector/php/connector.php?command=QuickUpload&type=Files';
$ckeditor->config['filebrowserImageUploadUrl'] = '/ckfinder/core/connector/php/connector.php?command=QuickUpload&type=Images';
$ckeditor->config['filebrowserFlashUploadUrl'] = '/ckfinder/core/connector/php/connector.php?command=QuickUpload&type=Flash';
$ckeditor->editor('CKEditor1');

?>

step 7 : what ever you name you want, you can name to it ckeditor by changing the step 6 code last line

$ckeditor->editor('mycustomname');

step 8 : Open-up the page1.php, see it, use it, share it and Enjoy because we all love Open Source.

Thanks

CSS animation delay in repeating

I know this is old but I was looking for the answer in this post and with jquery you can do it easily and without too much hassle. Just declare your animation keyframe in the css and set the class with the atributes you would like. I my case I used the tada animation from css animate:

.tada {
    -webkit-animation-name: tada;
    animation-name: tada;
    -webkit-animation-duration: 1.25s;
    animation-duration: 1.25s;
    -webkit-animation-fill-mode: both;
    animation-fill-mode: both;
}

I wanted the animation to run every 10 seconds so jquery just adds the class, after 6000ms (enough time for the animation to finish) it removes the class and 4 seconds later it adds the class again and so the animation starts again.

$(document).ready(function() {
  setInterval(function() {

    $(".bottom h2").addClass("tada");//adds the class

    setTimeout(function() {//waits 6 seconds to remove the class
      $(".bottom h2").removeClass("tada");
    }, 6000);

  }, 10000)//repeats the process every 10 seconds
});

Not at all difficult like one guy posted.

How to set a Fragment tag by code?

Nowadays there's a simpler way to achieve this if you are using a DialogFragment (not a Fragment):

val yourDialogFragment = YourDialogFragment()
yourDialogFragment.show(
    activity.supportFragmentManager,
    "YOUR_TAG_FRAGMENT"
)

Under the hood, the show() method does create a FragmentTransaction and adds the tag by using the add() method. But it's much more convenient to use the show() method in my opinion.

You could shorten it for Fragment too, by using a Kotlin Extension :)

SQL Stored Procedure: If variable is not null, update statement

Use a T-SQL IF:

IF @ABC IS NOT NULL AND @ABC != -1
    UPDATE [TABLE_NAME] SET XYZ=@ABC

Take a look at the MSDN docs.

An unhandled exception occurred during the execution of the current web request. ASP.NET

I had the same problem and found out that I had forgotten to include the script in the file which I want to include in the live site.

Also, you should try this:

bundles.Add(new ScriptBundle("~/bundles/jquery").Include(
"~/Scripts/jquery-{version}.js"));

What's the difference between lists enclosed by square brackets and parentheses in Python?

One interesting difference :

lst=[1]
print lst          // prints [1]
print type(lst)    // prints <type 'list'>

notATuple=(1)
print notATuple        // prints 1
print type(notATuple)  // prints <type 'int'>
                                         ^^ instead of tuple(expected)

A comma must be included in a tuple even if it contains only a single value. e.g. (1,) instead of (1).

Namespace not recognized (even though it is there)

Crazy. I know.

Tried all options here. Restarting, cleaning, manually checking in generated DLLs (this is invaluable to understanding if it's actually yourself that messed up).

I got it to work by setting the Verbosity of MSBuild to "Detailed" in Options.

Better solution without exluding fields from Binding

You should not use your domain models in your views. ViewModels are the correct way to do it.

You need to map your domain model's necessary fields to viewmodel and then use this viewmodel in your controllers. This way you will have the necessery abstraction in your application.

If you never heard of viewmodels, take a look at this.

Concatenating null strings in Java

See section 5.4 and 15.18 of the Java Language specification:

String conversion applies only to the operands of the binary + operator when one of the arguments is a String. In this single special case, the other argument to the + is converted to a String, and a new String which is the concatenation of the two strings is the result of the +. String conversion is specified in detail within the description of the string concatenation + operator.

and

If only one operand expression is of type String, then string conversion is performed on the other operand to produce a string at run time. The result is a reference to a String object (newly created, unless the expression is a compile-time constant expression (§15.28))that is the concatenation of the two operand strings. The characters of the left-hand operand precede the characters of the right-hand operand in the newly created string. If an operand of type String is null, then the string "null" is used instead of that operand.

Naming conventions for Java methods that return boolean

Standard is use is or has as a prefix. For example isValid, hasChildren.

Viewing contents of a .jar file

Extending Tom Hawtin answer, you can pipe the listing to filter out desired class or files:

jar tf my-fat-jar-file.jar | grep filename

This should work on bash/zsh and similars, or emacs' eshell.

Additional information: https://docs.oracle.com/javase/tutorial/deployment/jar/view.html

Capture key press without placing an input element on the page?

For non-printable keys such as arrow keys and shortcut keys such as Ctrl-z, Ctrl-x, Ctrl-c that may trigger some action in the browser (for instance, inside editable documents or elements), you may not get a keypress event in all browsers. For this reason you have to use keydown instead, if you're interested in suppressing the browser's default action. If not, keyup will do just as well.

Attaching a keydown event to document works in all the major browsers:

document.onkeydown = function(evt) {
    evt = evt || window.event;
    if (evt.ctrlKey && evt.keyCode == 90) {
        alert("Ctrl-Z");
    }
};

For a complete reference, I strongly recommend Jan Wolter's article on JavaScript key handling.

Simple Pivot Table to Count Unique Values

Siddharth's answer is terrific.

However, this technique can hit trouble when working with a large set of data (my computer froze up on 50,000 rows). Some less processor-intensive methods:

Single uniqueness check

  1. Sort by the two columns (A, B in this example)
  2. Use a formula that looks at less data

    =IF(SUMPRODUCT(($A2:$A3=A2)*($B2:$B3=B2))>1,0,1) 
    

Multiple uniqueness checks

If you need to check uniqueness in different columns, you can't rely on two sorts.

Instead,

  1. Sort single column (A)
  2. Add formula covering the maximum number of records for each grouping. If ABC might have 50 rows, the formula will be

    =IF(SUMPRODUCT(($A2:$A49=A2)*($B2:$B49=B2))>1,0,1)
    

How do I change the IntelliJ IDEA default JDK?

Change JDK version to 1.8

  1. Language level File -> project Structure -> Modules -> Sources -> Language level -> 8-Lambdas, type annotations etc. enter image description here
  2. Project SDk File -> project Structure -> Project 1.8 enter image description here

  3. Java compiler File -> Settings -> Build, Executions, Deployment -> Compiler -> Java compiler enter image description here

Do we need to execute Commit statement after Update in SQL Server

The SQL Server Management Studio has implicit commit turned on, so all statements that are executed are implicitly commited.

This might be a scary thing if you come from an Oracle background where the default is to not have commands commited automatically, but it's not that much of a problem.

If you still want to use ad-hoc transactions, you can always execute

BEGIN TRANSACTION

within SSMS, and than the system waits for you to commit the data.

If you want to replicate the Oracle behaviour, and start an implicit transaction, whenever some DML/DDL is issued, you can set the SET IMPLICIT_TRANSACTIONS checkbox in

Tools -> Options -> Query Execution -> SQL Server -> ANSI

What does '<?=' mean in PHP?

It's a shorthand for <?php echo $a; ?>.

It's enabled by default since 5.4 regardless of php.ini settings.

Compiling/Executing a C# Source File in Command Prompt

In Windows systems, use the command csc <filname>.cs in the command prompt while the current directory is in Microsoft Visual Studio\<Year>\<Version>

There are two ways:

Using the command prompt:

  1. Start --> Command Prompt
  2. Change the directory to Visual Studio folder, using the command: cd C:\Program Files (x86)\Microsoft Visual Studio\2017\ <Version>
  3. Use the command: csc /.cs

Using Developer Command Prompt :

  1. Start --> Developer Command Prompt for VS 2017 (Here the directory is already set to Visual Studio folder)

  2. Use the command: csc /.cs

Hope it helps!

MySQL 8.0 - Client does not support authentication protocol requested by server; consider upgrading MySQL client

I have MYSQL on server and nodejs application on another server

Execute the following query in MYSQL Workbench

ALTER USER 'root'@'%' IDENTIFIED WITH mysql_native_password BY 'password'

Replace Div Content onclick

Try This:

I think that you want something like this.

HTML:

<div id="1">
    My Content 1
</div>

<div id="2" style="display:none;">
    My Dynamic Content
</div>
<button id="btnClick">Click me!</button>

jQuery:

$('#btnClick').on('click',function(){
if($('#1').css('display')!='none'){
$('#2').show().siblings('div').hide();
}else if($('#2').css('display')!='none'){
    $('#1').show().siblings('div').hide();
}
});


JsFiddle:
http://jsfiddle.net/ha6qp7w4/1113/ <--- see this I hope You want something like this.

List View Filter Android

Implement your adapter Filterable:

public class vJournalAdapter extends ArrayAdapter<JournalModel> implements Filterable{
private ArrayList<JournalModel> items;
private Context mContext;
....

then create your Filter class:

private class JournalFilter extends Filter{

    @Override
    protected FilterResults performFiltering(CharSequence constraint) {
        FilterResults result = new FilterResults();
        List<JournalModel> allJournals = getAllJournals();
        if(constraint == null || constraint.length() == 0){

            result.values = allJournals;
            result.count = allJournals.size();
        }else{
            ArrayList<JournalModel> filteredList = new ArrayList<JournalModel>();
            for(JournalModel j: allJournals){
                if(j.source.title.contains(constraint))
                    filteredList.add(j);
            }
            result.values = filteredList;
            result.count = filteredList.size();
        }

        return result;
    }
    @SuppressWarnings("unchecked")
    @Override
    protected void publishResults(CharSequence constraint, FilterResults results) {
        if (results.count == 0) {
            notifyDataSetInvalidated();
        } else {
            items = (ArrayList<JournalModel>) results.values;
            notifyDataSetChanged();
        }
    }

}

this way, your adapter is Filterable, you can pass filter item to adapter's filter and do the work. I hope this will be helpful.

How to deal with SettingWithCopyWarning in Pandas

Here I answer the question directly. How to deal with it?

Make a .copy(deep=False) after you slice. See pandas.DataFrame.copy.

Wait, doesn't a slice return a copy? After all, this is what the warning message is attempting to say? Read the long answer:

import pandas as pd
df = pd.DataFrame({'x':[1,2,3]})

This gives a warning:

df0 = df[df.x>2]
df0['foo'] = 'bar'

This does not:

df1 = df[df.x>2].copy(deep=False)
df1['foo'] = 'bar'

Both df0 and df1 are DataFrame objects, but something about them is different that enables pandas to print the warning. Let's find out what it is.

import inspect
slice= df[df.x>2]
slice_copy = df[df.x>2].copy(deep=False)
inspect.getmembers(slice)
inspect.getmembers(slice_copy)

Using your diff tool of choice, you will see that beyond a couple of addresses, the only material difference is this:

|          | slice   | slice_copy |
| _is_copy | weakref | None       |

The method that decides whether to warn is DataFrame._check_setitem_copy which checks _is_copy. So here you go. Make a copy so that your DataFrame is not _is_copy.

The warning is suggesting to use .loc, but if you use .loc on a frame that _is_copy, you will still get the same warning. Misleading? Yes. Annoying? You bet. Helpful? Potentially, when chained assignment is used. But it cannot correctly detect chain assignment and prints the warning indiscriminately.

The name 'controlname' does not exist in the current context

I had the same issue since i was tring to re produce the aspx file from a visual studio 2010 project so the controls had clientidmode="Static" property. When this is removed it was resolved.

Remove columns from DataTable in C#

The question has already been marked as answered, But I guess the question states that the person wants to remove multiple columns from a DataTable.

So for that, here is what I did, when I came across the same problem.

string[] ColumnsToBeDeleted = { "col1", "col2", "col3", "col4" };

foreach (string ColName in ColumnsToBeDeleted)
{
    if (dt.Columns.Contains(ColName))
        dt.Columns.Remove(ColName);
}

The source was not found, but some or all event logs could not be searched

Didnt work for me.

I created a new key and string value and managed to get it working

Key= HKEY_LOCAL_MACHINE\SYSTEM\CurrentControlSet\services\eventlog\Application\<Your app name>\
String EventMessageFile value=C:\Windows\Microsoft.NET\Framework\v2.0.50727\EventLogMessages.dll

Use of True, False, and None as return values in Python functions

Use if foo or if not foo. There isn't any need for either == or is for that.

For checking against None, is None and is not None are recommended. This allows you to distinguish it from False (or things that evaluate to False, like "" and []).

Whether get_attr should return None would depend on the context. You might have an attribute where the value is None, and you wouldn't be able to do that. I would interpret None as meaning "unset", and a KeyError would mean the key does not exist in the file.

toBe(true) vs toBeTruthy() vs toBeTrue()

As you read through the examples below, just keep in mind this difference

true === true // true
"string" === true // false
1 === true // false
{} === true // false

But

Boolean("string") === true // true
Boolean(1) === true // true
Boolean({}) === true // true

1. expect(statement).toBe(true)

Assertion passes when the statement passed to expect() evaluates to true

expect(true).toBe(true) // pass
expect("123" === "123").toBe(true) // pass

In all other cases cases it would fail

expect("string").toBe(true) // fail
expect(1).toBe(true); // fail
expect({}).toBe(true) // fail

Even though all of these statements would evaluate to true when doing Boolean():

So you can think of it as 'strict' comparison

2. expect(statement).toBeTrue()

This one does exactly the same type of comparison as .toBe(true), but was introduced in Jasmine recently in version 3.5.0 on Sep 20, 2019

3. expect(statement).toBeTruthy()

toBeTruthy on the other hand, evaluates the output of the statement into boolean first and then does comparison

expect(false).toBeTruthy() // fail
expect(null).toBeTruthy() // fail
expect(undefined).toBeTruthy() // fail
expect(NaN).toBeTruthy() // fail
expect("").toBeTruthy() // fail
expect(0).toBeTruthy() // fail

And IN ALL OTHER CASES it would pass, for example

expect("string").toBeTruthy() // pass
expect(1).toBeTruthy() // pass
expect({}).toBeTruthy() // pass

How to change the data type of a column without dropping the column with query?

ALTER tablename MODIFY columnName newColumnType

I'm not sure how it will handle the change from datetime to varchar though, so you may need to rename the column, add a new one with the old name and the correct data type (varchar) and then write an update query to populate the new column from the old.

http://www.1keydata.com/sql/sql-alter-table.html

How to support different screen size in android

It sounds lofty,when it comes to supporting multiple screen Sizes.The following gves better results .

res/layout/layout-w120dp
res/layout/layout-w160dp
res/layout/layout-w240dp
res/layout/layout-w160dp
res/layout/layout-w320dp
res/layout/layout-w480dp
res/layout/layout-w600dp
res/layout/layout-w720dp

Chek the Device Width and Height using Display Metrics

Place/figure out which layout suits for the resulted width of the Device .

let smallestScreenWidthDp="assume some value(Which will be derived from Display metrics)"

All should be checked before setContentView().Otherwise you put yourself in trouble

     Configuration config = getResources().getConfiguration();


        if (config.smallestScreenWidthDp >= 600) {
            setContentView(R.layout.layout-w600dp);
        } else {
            setContentView(R.layout.main_activity);
        }

In the top,i have created so many layouts to fit multiple screens,it is all depends on you ,you may or not.You can see the play store reviews from Which API ,The Downloads are High..form that you have to proceed.

I hope it helps you lot.Few were using some third party libraries,It may be reduce your work ,but that is not best practice. Get Used to Android Best Practices.

Check This Out

Binding an Image in WPF MVVM

If you have a process that already generates and returns an Image type, you can alter the bind and not have to modify any additional image creation code.

Refer to the ".Source" of the image in the binding statement.

XAML

<Image Name="imgOpenClose" Source="{Binding ImageOpenClose.Source}"/>

View Model Field

private Image _imageOpenClose;
public Image ImageOpenClose
{
    get
    {
        return _imageOpenClose;
    }
    set
    {
        _imageOpenClose = value;
        OnPropertyChanged();
    }
}

how to get the selected index of a drop down

<select name="CCards" id="ccards">
    <option value="0">Select Saved Payment Method:</option>
    <option value="1846">test  xxxx1234</option>
    <option value="1962">test2  xxxx3456</option>
</select>

<script type="text/javascript">

    /** Jquery **/
    var selectedValue = $('#ccards').val();

    //** Regular Javascript **/
    var selectedValue2 = document.getElementById('ccards').value;


</script>

How to specify table's height such that a vertical scroll bar appears?

You need to wrap the table inside another element and set the height of that element. Example with inline css:

<div style="height: 500px; overflow: auto;">
 <table>
 </table>
</div>

Assertion failure in dequeueReusableCellWithIdentifier:forIndexPath:

I think this error is about registering your nib or class for the identifier.

So that you may keep what you are doing in your tableView:cellForRowAtIndexPath function and just add code below into your viewDidLoad:

[self.tableView registerClass:[UITableViewCell class] forCellReuseIdentifier:@"Cell"];

It's worked for me. Hope it may help.

WPF Data Binding and Validation Rules Best Practices

I think the new preferred way might be to use IDataErrorInfo

Read more here

React Native Border Radius with background color

You should add overflow: hidden to your styles:

Js:

<Button style={styles.submit}>Submit</Button>

Styles:

submit {
   backgroundColor: '#68a0cf';
   overflow: 'hidden';
}

Constants in Objective-C

// Prefs.h
extern NSString * const RAHUL;

// Prefs.m
NSString * const RAHUL = @"rahul";

How to upload and parse a CSV file in php

Hi I feel str_getcsv — Parse a CSV string into an array is the best option for you.

  1. You need to upload the file to sever

  2. parse the file using str_getcsv.

  3. run through the array and align as per u need in your website.

Why is processing a sorted array faster than processing an unsorted array?

This question is rooted in branch prediction models on CPUs. I'd recommend reading this paper:

Increasing the Instruction Fetch Rate via Multiple Branch Prediction and a Branch Address Cache

When you have sorted elements, the IR can not be bothered to fetch all CPU instructions, again and again. It fetches them from the cache.

The RPC server is unavailable. (Exception from HRESULT: 0x800706BA)

My problem turned out to be blank spaces in the txt file that I was using to feed the WMI Powershell script.

jQuery vs. javascript?

It's all about performance and development speed. Of course, if you are a good programmer and design something that is really tailored to your needs, you might achieve better performance than if you had used a Javascript framework. But do you have the time to do it all by yourself?

My personal opinion is that Javascript is incredibly useful and overused, but that if you really need it, a framework is the way to go.

Now comes the choice of the framework. For what benchmarks are worth, you can find one at http://ejohn.org/files/142/ . It also depends on which plugins are available and what you intend to do with them. I started using jQuery because it seemed to be maintained and well featured, even though it wasn't the fastest at that moment. I do not regret it but I didn't test anything else since then.

Can we write our own iterator in Java?

Sure. An iterator is just an implementation of the java.util.Iterator interface. If you're using an existing iterable object (say, a LinkedList) from java.util, you'll need to either subclass it and override its iterator function so that you return your own, or provide a means of wrapping a standard iterator in your special Iterator instance (which has the advantage of being more broadly used), etc.

JAXB :Need Namespace Prefix to all the elements

Another way is to tell the marshaller to always use a certain prefix

marshaller.setProperty("com.sun.xml.bind.namespacePrefixMapper", new NamespacePrefixMapper() {
             @Override
            public String getPreferredPrefix(String arg0, String arg1, boolean arg2) {
                return "ns1";
            }
        });'

How to debug apk signed for release?

I know this is old question, but future references. In Android Studio with Gradle:

buildTypes {
    release {
        debuggable true
        runProguard true
        proguardFiles getDefaultProguardFile('proguard-android.txt'), 'proguard-rules.txt'
    }
}

The line debuggable true was the trick for me.

Update:

Since gradle 1.0 it's minifyEnabled instead of runProguard. Look at here

Chrome disable SSL checking for sites?

In my case I was developing an ASP.Net MVC5 web app and the certificate errors on my local dev machine (IISExpress certificate) started becoming a practical concern once I started working with service workers. Chrome simply wouldn't register my service worker because of the certificate error.

I did, however, notice that during my automated Selenium browser tests, Chrome seem to just "ignore" all these kinds of problems (e.g. the warning page about an insecure site), so I asked myself the question: How is Selenium starting Chrome for running its tests, and might it also solve the service worker problem?

Using Process Explorer on Windows, I was able to find out the command-line arguments with which Selenium is starting Chrome:

"C:\Program Files (x86)\Google\Chrome\Application\chrome.exe" --disable-background-networking --disable-client-side-phishing-detection --disable-default-apps --disable-hang-monitor --disable-popup-blocking --disable-prompt-on-repost --disable-sync --disable-web-resources --enable-automation --enable-logging --force-fieldtrials=SiteIsolationExtensions/Control --ignore-certificate-errors --log-level=0 --metrics-recording-only --no-first-run --password-store=basic --remote-debugging-port=12207 --safebrowsing-disable-auto-update --test-type=webdriver --use-mock-keychain --user-data-dir="C:\Users\Sam\AppData\Local\Temp\some-non-existent-directory" data:,

There are a bunch of parameters here that I didn't end up doing necessity-testing for, but if I run Chrome this way, my service worker registers and works as expected.

The only one that does seem to make a difference is the --user-data-dir parameter, which to make things work can be set to a non-existent directory (things won't work if you don't provide the parameter).

Hope that helps someone else with a similar problem. I'm using Chrome 60.0.3112.90.

Hibernate JPA Sequence (non-Id)

I was struggling with this today, was able to solve using this

@Generated(GenerationTime.INSERT)
@Column(name = "internal_id", columnDefinition = "serial", updatable = false)
private int internalId;

Hex to ascii string conversion

strtol() is your friend here. The third parameter is the numerical base that you are converting.

Example:

#include <stdio.h>      /* printf */
#include <stdlib.h>     /* strtol */

int main(int argc, char **argv)
{
    long int num  = 0;
    long int num2 =0;
    char * str. = "f00d";
    char * str2 = "0xf00d";

    num = strtol( str, 0, 16);  //converts hexadecimal string to long.
    num2 = strtol( str2, 0, 0); //conversion depends on the string passed in, 0x... Is hex, 0... Is octal and everything else is decimal.

    printf( "%ld\n", num);
    printf( "%ld\n", num);
}

MySQL ON DUPLICATE KEY UPDATE for multiple rows insert in single query

INSERT INTO ... ON DUPLICATE KEY UPDATE will only work for MYSQL, not for SQL Server.

for SQL server, the way to work around this is to first declare a temp table, insert value to that temp table, and then use MERGE

Like this:

declare @Source table
(
name varchar(30),
age decimal(23,0)
)

insert into @Source VALUES
('Helen', 24),
('Katrina', 21),
('Samia', 22),
('Hui Ling', 25),
('Yumie', 29);


MERGE beautiful  AS Tg
using  @source as Sc
on tg.namet=sc.name 

when matched then update 
set tg.age=sc.age

when not matched then 
insert (name, age) VALUES
(SC.name, sc.age);

How can I find and run the keytool

keytool is part of the JDK.

Try to prepend %{JAVA_HOME}\ to the exec statement or c:\{path to jdk}\bin.

Align <div> elements side by side

keep it simple

<div align="center">
<div style="display: inline-block"> <img src="img1.png"> </div>
<div style="display: inline-block"> <img src="img2.png"> </div>
</div>

Convert UTC datetime string to local datetime

If you want to get the correct result even for the time that corresponds to an ambiguous local time (e.g., during a DST transition) and/or the local utc offset is different at different times in your local time zone then use pytz timezones:

#!/usr/bin/env python
from datetime import datetime
import pytz    # $ pip install pytz
import tzlocal # $ pip install tzlocal

local_timezone = tzlocal.get_localzone() # get pytz tzinfo
utc_time = datetime.strptime("2011-01-21 02:37:21", "%Y-%m-%d %H:%M:%S")
local_time = utc_time.replace(tzinfo=pytz.utc).astimezone(local_timezone)

how to install apk application from my pc to my mobile android

To install an APK on your mobile, you can either:

  1. Use ADB from the Android SDK, and do the following command: adb install filename.apk. Note, you'll need to enable USB debugging for this to work.
  2. Transfer the file to your device, then open it with a file manager, such as Linda File Manager.

Note, that you'll have to enable installing packages from Unknown Sources in your Applications settings.

As for getting USB to work, I suggest consulting the Android StackExchange for advice.

Composer update memory limit

I am facing problems with composer because it consumes all the available memory, and then, the process get killed ( actualy, the output message is "Killed")

So, I was looking for a solution to limit composer memory usage.

I tried ( from @Sven answers )

$ php -d memory_limit=512M /usr/local/bin/composer update

But it didn't work because

"Composer internally increases the memory_limit to 1.5G."

-> Thats from composer oficial website.

Then I found a command that works :

$ COMPOSER_MEMORY_LIMIT=512M php composer.phar update

Althought, in my case 512mb is not enough !

Source : https://www.agileana.com/blog/composer-memory-limit-troubleshooting/

Convert object array to hash map, indexed by an attribute value of the Object

Using simple Javascript

var createMapFromList = function(objectList, property) {
    var objMap = {};
    objectList.forEach(function(obj) {
      objMap[obj[property]] = obj;
    });
    return objMap;
  };
// objectList - the array  ;  property - property as the key

How to Make A Chevron Arrow Using CSS?

An other approach using borders and no CSS3 properties :

_x000D_
_x000D_
div, div:after{_x000D_
    border-width: 80px 0 80px 80px;_x000D_
    border-color: transparent transparent transparent #000;_x000D_
    border-style:solid;_x000D_
    position:relative;_x000D_
}_x000D_
div:after{_x000D_
    content:'';_x000D_
    position:absolute;_x000D_
    left:-115px; top:-80px;_x000D_
    border-left-color:#fff;_x000D_
}
_x000D_
<div></div>
_x000D_
_x000D_
_x000D_

Suppress/ print without b' prefix for bytes in Python 3

Use decode:

print(curses.version.decode())
# 2.2

Bootstrap Collapse not Collapsing

bootstrap.js is using jquery library so you need to add jquery library before bootstrap js.

so please add it jquery library like

Note : Please maintain order of js file. html page use top to bottom approach for compilation

<head>
    <link rel="stylesheet" href="http://netdna.bootstrapcdn.com/bootstrap/3.1.1/css/bootstrap.min.css">
    <script src="http://code.jquery.com/jquery-1.11.0.min.js"></script>
    <script src="http://netdna.bootstrapcdn.com/bootstrap/3.1.1/js/bootstrap.min.js"></script>
</head>

React: trigger onChange if input value is changing by state?

you must do 4 following step :

  1. create event

    var event = new Event("change",{
        detail: {
            oldValue:yourValueVariable,
            newValue:!yourValueVariable
        },
        bubbles: true,
        cancelable: true
    });
    event.simulated = true;
    let tracker = this.yourComponentDomRef._valueTracker;
    if (tracker) {
        tracker.setValue(!yourValueVariable);
    }
    
  2. bind value to component dom

    this.yourComponentDomRef.value = !yourValueVariable;
    
  3. bind element onchange to react onChange function

     this.yourComponentDomRef.onchange = (e)=>this.props.onChange(e);
    
  4. dispatch event

    this.yourComponentDomRef.dispatchEvent(event);
    

in above code yourComponentDomRef refer to master dom of your React component for example <div className="component-root-dom" ref={(dom)=>{this.yourComponentDomRef= dom}}>

Root password inside a Docker container

try the following command to get the root access

$ sudo -i 

Output a NULL cell value in Excel

As you've indicated, you can't output NULL in an excel formula. I think this has to do with the fact that the formula itself causes the cell to not be able to be NULL. "" is the next best thing, but sometimes it's useful to use 0.

--EDIT--

Based on your comment, you might want to check out this link. http://peltiertech.com/WordPress/mind-the-gap-charting-empty-cells/

It goes in depth on the graphing issues and what the various values represent, and how to manipulate their output on a chart.

I'm not familiar with VSTO I'm afraid. So I won't be much help there. But if you are really placing formulas in the cell, then there really is no way. ISBLANK() only tests to see if a cell is blank or not, it doesn't have a way to make it blank. It's possible to write code in VBA (and VSTO I imagine) that would run on a worksheet_change event and update the various values instead of using formulas. But that would be cumbersome and performance would take a hit.

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

autoResetEvent.WaitOne()

is similar to

try
{
   manualResetEvent.WaitOne();
}
finally
{
   manualResetEvent.Reset();
}

as an atomic operation

showDialog deprecated. What's the alternative?

This code worked for me. Easy fix but probably not a preferred way.

public void onClick (View v) {
    createdDialog(0).show(); // Instead of showDialog(0);
}

protected Dialog createdDialog(int id) {
    // Your code
}

ASP.NET IIS Web.config [Internal Server Error]

I had the same problem.

Solution:

  1. Click the right button in your site folder in "iis"
  2. "Convert to Application".

List of ANSI color escape sequences

It's related absolutely to your terminal. VTE doesn't support blink, If you use gnome-terminal, tilda, guake, terminator, xfce4-terminal and so on according to VTE, you won't have blink.
If you use or want to use blink on VTE, you have to use xterm.
You can use infocmp command with terminal name:

#infocmp vt100
#infocmp xterm
#infocmp vte

For example :

# infocmp vte
#   Reconstructed via infocmp from file: /usr/share/terminfo/v/vte
vte|VTE aka GNOME Terminal,
    am, bce, mir, msgr, xenl,
    colors#8, cols#80, it#8, lines#24, ncv#16, pairs#64,
    acsc=``aaffggiijjkkllmmnnooppqqrrssttuuvvwwxxyyzz{{||}}~~,
    bel=^G, bold=\E[1m, civis=\E[?25l, clear=\E[H\E[2J,
    cnorm=\E[?25h, cr=^M, csr=\E[%i%p1%d;%p2%dr,
    cub=\E[%p1%dD, cub1=^H, cud=\E[%p1%dB, cud1=^J,
    cuf=\E[%p1%dC, cuf1=\E[C, cup=\E[%i%p1%d;%p2%dH,
    cuu=\E[%p1%dA, cuu1=\E[A, dch=\E[%p1%dP, dch1=\E[P,
    dim=\E[2m, dl=\E[%p1%dM, dl1=\E[M, ech=\E[%p1%dX, ed=\E[J,
    el=\E[K, enacs=\E)0, home=\E[H, hpa=\E[%i%p1%dG, ht=^I,
    hts=\EH, il=\E[%p1%dL, il1=\E[L, ind=^J, invis=\E[8m,
    is2=\E[m\E[?7h\E[4l\E>\E7\E[r\E[?1;3;4;6l\E8,
    kDC=\E[3;2~, kEND=\E[1;2F, kHOM=\E[1;2H, kIC=\E[2;2~,
    kLFT=\E[1;2D, kNXT=\E[6;2~, kPRV=\E[5;2~, kRIT=\E[1;2C,
    kb2=\E[E, kbs=\177, kcbt=\E[Z, kcub1=\EOD, kcud1=\EOB,
    kcuf1=\EOC, kcuu1=\EOA, kdch1=\E[3~, kend=\EOF, kf1=\EOP,
    kf10=\E[21~, kf11=\E[23~, kf12=\E[24~, kf13=\E[1;2P,
    kf14=\E[1;2Q, kf15=\E[1;2R, kf16=\E[1;2S, kf17=\E[15;2~,
    kf18=\E[17;2~, kf19=\E[18;2~, kf2=\EOQ, kf20=\E[19;2~,
    kf21=\E[20;2~, kf22=\E[21;2~, kf23=\E[23;2~,
    kf24=\E[24;2~, kf25=\E[1;5P, kf26=\E[1;5Q, kf27=\E[1;5R,
    kf28=\E[1;5S, kf29=\E[15;5~, kf3=\EOR, kf30=\E[17;5~,
    kf31=\E[18;5~, kf32=\E[19;5~, kf33=\E[20;5~,
    kf34=\E[21;5~, kf35=\E[23;5~, kf36=\E[24;5~,
    kf37=\E[1;6P, kf38=\E[1;6Q, kf39=\E[1;6R, kf4=\EOS,
    kf40=\E[1;6S, kf41=\E[15;6~, kf42=\E[17;6~,
    kf43=\E[18;6~, kf44=\E[19;6~, kf45=\E[20;6~,
    kf46=\E[21;6~, kf47=\E[23;6~, kf48=\E[24;6~,
    kf49=\E[1;3P, kf5=\E[15~, kf50=\E[1;3Q, kf51=\E[1;3R,
    kf52=\E[1;3S, kf53=\E[15;3~, kf54=\E[17;3~,
    kf55=\E[18;3~, kf56=\E[19;3~, kf57=\E[20;3~,
    kf58=\E[21;3~, kf59=\E[23;3~, kf6=\E[17~, kf60=\E[24;3~,
    kf61=\E[1;4P, kf62=\E[1;4Q, kf63=\E[1;4R, kf7=\E[18~,
    kf8=\E[19~, kf9=\E[20~, kfnd=\E[1~, khome=\EOH,
    kich1=\E[2~, kind=\E[1;2B, kmous=\E[M, knp=\E[6~,
    kpp=\E[5~, kri=\E[1;2A, kslt=\E[4~, meml=\El, memu=\Em,
    op=\E[39;49m, rc=\E8, rev=\E[7m, ri=\EM, ritm=\E[23m,
    rmacs=^O, rmam=\E[?7l, rmcup=\E[2J\E[?47l\E8, rmir=\E[4l,
    rmkx=\E[?1l\E>, rmso=\E[m, rmul=\E[m, rs1=\Ec,
    rs2=\E7\E[r\E8\E[m\E[?7h\E[!p\E[?1;3;4;6l\E[4l\E>\E[?1000l\E[?25h,
    sc=\E7, setab=\E[4%p1%dm, setaf=\E[3%p1%dm,
    sgr=\E[0%?%p6%t;1%;%?%p2%t;4%;%?%p5%t;2%;%?%p7%t;8%;%?%p1%p3%|%t;7%;m%?%p9%t\016%e\017%;,
    sgr0=\E[0m\017, sitm=\E[3m, smacs=^N, smam=\E[?7h,
    smcup=\E7\E[?47h, smir=\E[4h, smkx=\E[?1h\E=, smso=\E[7m,
    smul=\E[4m, tbc=\E[3g, u6=\E[%i%d;%dR, u7=\E[6n,
    u8=\E[?%[;0123456789]c, u9=\E[c, vpa=\E[%i%p1%dd,

How do I jump out of a foreach loop in C#?

foreach (var item in listOfItems) {
  if (condition_is_met)
    // Any processing you may need to complete here...
    break; // return true; also works if you're looking to
           // completely exit this function.
}

Should do the trick. The break statement will just end the execution of the loop, while the return statement will obviously terminate the entire function. Judging from your question you may want to use the return true; statement.

How to open a web server port on EC2 instance

You need to open TCP port 8787 in the ec2 Security Group. Also need to open the same port on the EC2 instance's firewall.

How to split a String by space

Here is a method to trim a String that has a "," or white space

private String shorterName(String s){
        String[] sArr = s.split("\\,|\\s+");
        String output = sArr[0];

        return output;
    }

Cannot deserialize the current JSON array (e.g. [1,2,3]) into type

For array type Please try this one.

 List<MyStok> myDeserializedObjList = (List<MyStok>)Newtonsoft.Json.JsonConvert.DeserializeObject(sc), typeof(List<MyStok>));

Please See here for details to deserialise Json

Promise Error: Objects are not valid as a React child

You can't just return an array of objects because there's nothing telling React how to render that. You'll need to return an array of components or elements like:

render: function() {
  return (
    <span>
      // This will go through all the elements in arrayFromJson and
      // render each one as a <SomeComponent /> with data from the object
      {this.state.arrayFromJson.map(function(object) {
        return (
          <SomeComponent key={object.id} data={object} />
        );
      })}
    </span>
  );
}

How to modify existing, unpushed commit messages?

Update your last wrong commit message with the new commit message in one line:

git commit --amend -m "your new commit message"

Or, try Git reset like below:

# You can reset your head to n number of commit
# NOT a good idea for changing last commit message,
# but you can get an idea to split commit into multiple commits
git reset --soft HEAD^

# It will reset you last commit. Now, you
# can re-commit it with new commit message.

Using reset to split commits into smaller commits

git reset can help you to break one commit into multiple commits too:

# Reset your head. I am resetting to last commits:
git reset --soft HEAD^
# (You can reset multiple commit by doing HEAD~2(no. of commits)

# Now, reset your head for splitting it to multiple commits
git reset HEAD

# Add and commit your files separately to make multiple commits: e.g
git add app/
git commit -m "add all files in app directory"

git add config/
git commit -m "add all files in config directory"

Here you have successfully broken your last commit into two commits.

Visual Studio Code how to resolve merge conflicts with git?

  1. Click "Source Control" button on left.
  2. See MERGE CHANGES in sidebar.
  3. Those files have merge conflicts.

VS Code > Source Control > Merge Changes (Example)

Daylight saving time and time zone best practices

Crossing the boundary of "computer time" and "people time" is a nightmare. The main one being that there is no sort of standard for the rules governing timezones and daylight saving times. Countries are free to change their timezone and DST rules at any time, and they do.

Some countries e.g. Israel, Brazil, decide each year when to have their daylight saving times, so it is impossible to know in advance when (if) DST will be in effect. Others have fixed(ish) rules as to when DST is in effect. Other countries do not use DST as all.

Timezones do not have to be full hour differences from GMT. Nepal is +5.45. There are even timezones that are +13. That means that:

SUN 23:00 in Howland Island (-12)
MON 11:00 GMT 
TUE 00:00 in Tonga (+13)

are all the same time, yet 3 different days!

There is also no clear standard on the abbreviations for timezones, and how they change when in DST so you end up with things like this:

AST Arab Standard Time     UTC+03
AST Arabian Standard Time  UTC+04
AST Arabic Standard Time   UTC+03

The best advice is to stay away from local times as much as possible and stick to UTC where you can. Only convert to local times at the last possible moment.

When testing make sure you test countries in the Western and Eastern hemispheres, with both DST in progress and not and a country that does not use DST (6 in total).

error LNK2038: mismatch detected for '_ITERATOR_DEBUG_LEVEL': value '0' doesn't match value '2' in main.obj

I also had this issue and it arose because I re-made the project and then forgot to re-link it by reference in a dependent project.

Thus it was linking by reference to the old project instead of the new one.

It is important to know that there is a bug in re-adding a previously linked project by reference. You've got to manually delete the reference in the vcxproj and only then can you re-add it. This is a known issue in Visual studio according to msdn.

How to Convert an int to a String?

Did you try:

text_Rate.setText(String.valueOf(sdRate));

What is the meaning of ToString("X2")?

ToString("X2") prints the input in Hexadecimal

Removing items from a list

//first find out the removed ones

List removedList = new ArrayList();
for(Object a: list){
    if(a.getXXX().equalsIgnoreCase("AAA")){
        logger.info("this is AAA........should be removed from the list ");
        removedList.add(a);

    }
}

list.removeAll(removedList);

Intro to GPU programming

Another easy way to get into GPU programming, without getting into CUDA or OpenCL, is to do it via OpenACC.

OpenACC works like OpenMP, with compiler directives (like #pragma acc kernels) to send work to the GPU. For example, if you have a big loop (only larger ones really benefit):

int i;
float a = 2.0;
float b[10000];
#pragma acc kernels
for (i = 0; i < 10000; ++i) b[i] = 1.0f;
#pragma acc kernels
for (i = 0; i < 10000; ++i) {
  b[i] = b[i] * a;
}

Edit: unfortunately, only the PGI compiler really supports OpenACC right now, for NVIDIA GPU cards.

Recommended SQL database design for tags or tagging

Normally I would agree with Yaakov Ellis but in this special case there is another viable solution:

Use two tables:

Table: Item
Columns: ItemID, Title, Content
Indexes: ItemID

Table: Tag
Columns: ItemID, Title
Indexes: ItemId, Title

This has some major advantages:

First it makes development much simpler: in the three-table solution for insert and update of item you have to lookup the Tag table to see if there are already entries. Then you have to join them with new ones. This is no trivial task.

Then it makes queries simpler (and perhaps faster). There are three major database queries which you will do: Output all Tags for one Item, draw a Tag-Cloud and select all items for one Tag Title.

All Tags for one Item:

3-Table:

SELECT Tag.Title 
  FROM Tag 
  JOIN ItemTag ON Tag.TagID = ItemTag.TagID
 WHERE ItemTag.ItemID = :id

2-Table:

SELECT Tag.Title
FROM Tag
WHERE Tag.ItemID = :id

Tag-Cloud:

3-Table:

SELECT Tag.Title, count(*)
  FROM Tag
  JOIN ItemTag ON Tag.TagID = ItemTag.TagID
 GROUP BY Tag.Title

2-Table:

SELECT Tag.Title, count(*)
  FROM Tag
 GROUP BY Tag.Title

Items for one Tag:

3-Table:

SELECT Item.*
  FROM Item
  JOIN ItemTag ON Item.ItemID = ItemTag.ItemID
  JOIN Tag ON ItemTag.TagID = Tag.TagID
 WHERE Tag.Title = :title

2-Table:

SELECT Item.*
  FROM Item
  JOIN Tag ON Item.ItemID = Tag.ItemID
 WHERE Tag.Title = :title

But there are some drawbacks, too: It could take more space in the database (which could lead to more disk operations which is slower) and it's not normalized which could lead to inconsistencies.

The size argument is not that strong because the very nature of tags is that they are normally pretty small so the size increase is not a large one. One could argue that the query for the tag title is much faster in a small table which contains each tag only once and this certainly is true. But taking in regard the savings for not having to join and the fact that you can build a good index on them could easily compensate for this. This of course depends heavily on the size of the database you are using.

The inconsistency argument is a little moot too. Tags are free text fields and there is no expected operation like 'rename all tags "foo" to "bar"'.

So tldr: I would go for the two-table solution. (In fact I'm going to. I found this article to see if there are valid arguments against it.)