Programs & Examples On #Role base authorization

How to get "wc -l" to print just the number of lines without file name?

Obviously, there are a lot of solutions to this. Here is another one though:

wc -l somefile | tr -d "[:alpha:][:blank:][:punct:]"

This only outputs the number of lines, but the trailing newline character (\n) is present, if you don't want that either, replace [:blank:] with [:space:].

Get Folder Size from Windows Command Line

Here comes a powershell code I write to list size and file count for all folders under current directory. Feel free to re-use or modify per your need.

$FolderList = Get-ChildItem -Directory
foreach ($folder in $FolderList)
{
    set-location $folder.FullName
    $size = Get-ChildItem -Recurse | Measure-Object -Sum Length
    $info = $folder.FullName + "    FileCount: " + $size.Count.ToString() + "   Size: " + [math]::Round(($size.Sum / 1GB),4).ToString() + " GB"
    write-host $info
}

Incorrect syntax near ''

Panagiotis Kanavos is right, sometimes copy and paste T-SQL can make appear unwanted characters...

I finally found a simple and fast way (only Notepad++ needed) to detect which character is wrong, without having to manually rewrite the whole statement: there is no need to save any file to disk.

It's pretty quick, in Notepad++:

  • Click "New file"
  • Check under the menu "Encoding": the value should be "Encode in UTF-8"; set it if it's not
  • Paste your text enter image description here
  • From Encoding menu, now click "Encode in ANSI" and check again your text enter image description here

You should easily find the wrong character(s)

SQL Server r2 installation error .. update Visual Studio 2008 to SP1

Finally, I solved it. Even though the solution is a bit lengthy, I think its the simplest. The solution is as follows:

  1. Install Visual Studio 2008
  2. Install the service Package 1 (SP1)
  3. Install SQL Server 2008 r2

How to convert date to string and to date again?

tl;dr

How to convert date to string and to date again?

LocalDate.now().toString()

2017-01-23

…and…

LocalDate.parse( "2017-01-23" )

java.time

The Question uses troublesome old date-time classes bundled with the earliest versions of Java. Those classes are now legacy, supplanted by the java.time classes built into Java 8, Java 9, and later.

Determining today’s date requires a time zone. For any given moment the date varies around the globe by zone.

If not supplied by you, your JVM’s current default time zone is applied. That default can change at any moment during runtime, and so is unreliable. I suggest you always specify your desired/expected time zone.

ZoneId z = ZoneId.of( "America/Montreal" ) ;
LocalDate ld = LocalDate.now( z ) ;

ISO 8601

Your desired format of YYYY-MM-DD happens to comply with the ISO 8601 standard.

That standard happens to be used by default by the java.time classes when parsing/generating strings. So you can simply call LocalDate::parse and LocalDate::toString without specifying a formatting pattern.

String s = ld.toString() ;

To parse:

LocalDate ld = LocalDate.parse( s ) ;

About java.time

The java.time framework is built into Java 8 and later. These classes supplant the troublesome old legacy date-time classes such as java.util.Date, Calendar, & SimpleDateFormat.

The Joda-Time project, now in maintenance mode, advises migration to the java.time classes.

To learn more, see the Oracle Tutorial. And search Stack Overflow for many examples and explanations. Specification is JSR 310.

Where to obtain the java.time classes?

The ThreeTen-Extra project extends java.time with additional classes. This project is a proving ground for possible future additions to java.time. You may find some useful classes here such as Interval, YearWeek, YearQuarter, and more.

Virtualenv Command Not Found

Personally. I did the same steps you did on a fresh Ubuntu 20 installation (except that I used pip3). I got the same problem, and I remember I solved it this way:

python3 -m virtualenv venv 

Link to understand the -m <module-name> notation.

Function not defined javascript

important: in this kind of error you should look for simple mistakes in most cases

besides syntax error, I should say once I had same problem and it was because of bad name I have chosen for function. I have never searched for the reason but I remember that I copied another function and change it to use. I add "1" after the name to changed the function name and I got this error.

Colspan all columns

If you're using jQuery (or don't mind adding it), this will get the job done better than any of these hacks.

function getMaxColCount($table) {
    var maxCol = 0;

    $table.find('tr').each(function(i,o) {
        var colCount = 0;
        $(o).find('td:not(.maxcols),th:not(.maxcols)').each(function(i,oo) {
            var cc = Number($(oo).attr('colspan'));
            if (cc) {
                colCount += cc;
            } else {
                colCount += 1;
            }
        });
        if(colCount > maxCol) { maxCol = colCount };
    });

    return maxCol;

}

To ease the implementation, I decorate any td/th I need adjusted with a class such as "maxCol" then I can do the following:

$('td.maxcols, th.maxcols').each(function(i,o) {
    $t = $($(o).parents('table')[0]); $(o).attr('colspan',  getMaxColCount($t));
});

If you find an implementation this won't work for, don't slam the answer, explain in comments and I'll update if it can be covered.

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

Maven is a build tool. Along with Ant or Gradle are Javas tools for building.
If you are a newbie in Java though just build using your IDE since Maven has a steep learning curve.

How to remove all elements in String array in java?

example = new String[example.length];

If you need dynamic collection, you should consider using one of java.util.Collection implementations that fits your problem. E.g. java.util.List.

Twitter Bootstrap 3 Sticky Footer

Here is a method that will add a sticky footer that doesn't require any additional CSS or Javascript other than what's already in Bootstrap and won't interfere with your current footer.

Example here: Easy Sticky Footer

Just copy and paste this directly into your code. No fuss no muss.

<div class="navbar navbar-default navbar-fixed-bottom">
    <div class="container">
      <p class="navbar-text pull-left">© 2014 - Site Built By Mr. M.
           <a href="http://tinyurl.com/tbvalid" target="_blank" >HTML 5 Validation</a>
      </p>

      <a href="http://youtu.be/zJahlKPCL9g" class="navbar-btn btn-danger btn pull-right">
      <span class="glyphicon glyphicon-star"></span>  Subscribe on YouTube</a>
    </div>
</div>

How to view/delete local storage in Firefox?

Try this, it works for me:

var storage = null;
setLocalStorage();

function setLocalStorage() {
    storage = (localStorage ? localStorage : (window.content.localStorage ? window.content.localStorage : null));

    try {
        storage.setItem('test_key', 'test_value');//verify if posible saving in the current storage
    }
    catch (e) {
        if (e.name == "NS_ERROR_FILE_CORRUPTED") {
            storage = sessionStorage ? sessionStorage : null;//set the new storage if fails
        }
    }
}

How to get names of classes inside a jar file?

Use this bash script:

#!/bin/bash

for VARIABLE in *.jar
do
   jar -tf $VARIABLE |grep "\.class"|awk -v arch=$VARIABLE '{print arch ":" $4}'|sed 's/\//./g'|sed 's/\.\.//g'|sed 's/\.class//g'
done

this will list the classes inside jars in your directory in the form:

file1.jar:fullyqualifiedclassName
file1.jar:fullyqualifiedclassName
file1.jar:fullyqualifiedclassName
file1.jar:fullyqualifiedclassName
file2.jar:fullyqualifiedclassName
file2.jar:fullyqualifiedclassName
file2.jar:fullyqualifiedclassName

Sample output:

commons-io.jar:org.apache.commons.io.ByteOrderMark
commons-io.jar:org.apache.commons.io.Charsets
commons-io.jar:org.apache.commons.io.comparator.AbstractFileComparator
commons-io.jar:org.apache.commons.io.comparator.CompositeFileComparator
commons-io.jar:org.apache.commons.io.comparator.DefaultFileComparator
commons-io.jar:org.apache.commons.io.comparator.DirectoryFileComparator
commons-io.jar:org.apache.commons.io.comparator.ExtensionFileComparator
commons-io.jar:org.apache.commons.io.comparator.LastModifiedFileComparator

In windows you can use powershell:

Get-ChildItem -File -Filter *.jar |
ForEach-Object{
    $filename = $_.Name
    Write-Host $filename
    $classes = jar -tf $_.Name |Select-String -Pattern '.class' -CaseSensitive -SimpleMatch
    ForEach($line in $classes) {
       write-host $filename":"(($line -replace "\.class", "") -replace "/", ".")
    }
}

ERROR 1067 (42000): Invalid default value for 'created_at'

As mentioned in @Bernd Buffen's answer. This is issue with MariaDB 5.5, I simple upgrade MariaDB 5.5 to MariaDB 10.1 and issue resolved.

Here Steps to upgrade MariaDB 5.5 into MariaDB 10.1 at CentOS 7 (64-Bit)

  1. Add following lines to MariaDB repo.

    nano /etc/yum.repos.d/mariadb.repo and paste the following lines.

[mariadb]
name = MariaDB
baseurl = http://yum.mariadb.org/10.1/centos7-amd64
gpgkey=https://yum.mariadb.org/RPM-GPG-KEY-MariaDB
gpgcheck=1

  1. Stop MariaDB, if already running service mariadb stop
  2. Perform update

    yum update

  3. Starting MariaDB & Performing Upgrade

    service mariadb start

    mysql_upgrade

Everything Done.

Check MariaDB version: mysql -V


NOTE: Please always take backup of Database(s) before performing upgrades. Data can be lost if upgrade failed or something went wrong.

Twitter Bootstrap - full width navbar

Put your <nav>element out from the <div class='container-fluid'>. Ex :-

_x000D_
_x000D_
<nav>_x000D_
 ......nav content goes here_x000D_
<nav>_x000D_
_x000D_
<div class="container-fluid">_x000D_
  <div>_x000D_
   ........ other content goes here_x000D_
  </div>_x000D_
</div>
_x000D_
_x000D_
_x000D_

Program does not contain a static 'Main' method suitable for an entry point

Project Properties \ Output file -> Select Class Library :)

Using helpers in model: how do I include helper dependencies?

I wouldn't recommend any of these methods. Instead, put it within its own namespace.

class Post < ActiveRecord::Base
  def clean_input
    self.input = Helpers.sanitize(self.input, :tags => %w(b i u))
  end

  module Helpers
    extend ActionView::Helpers::SanitizeHelper
  end
end

Make Https call using HttpClient

I was also getting the error:

The underlying connection was closed: Could not establish trust relationship for the SSL/TLS secure channel.

... with a Xamarin Forms Android-targeting application attempting to request resources from an API provider that required TLS 1.3.

The solution was to update the project configuration to swap out the Xamarin "managed" (.NET) http client (that doesn't support TLS 1.3 as of Xamarin Forms v2.5), and instead use the android native client.

It's a simple project toggle in visual studio. See screenshot below.

  • Project Properties
  • Android Options
  • Advanced
  • List item
  • Change "HttpClient implementation" to "Android"
  • Change SSL/TLS implementation to "Native TLS 1.2+"

enter image description here

Submitting HTML form using Jquery AJAX

If you add:

jquery.form.min.js

You can simply do this:

<script>
$('#myform').ajaxForm(function(response) {
  alert(response);
});

// this will register the AJAX for <form id="myform" action="some_url">
// and when you submit the form using <button type="submit"> or $('myform').submit(), then it will send your request and alert response
</script>

NOTE:

You could use simple $('FORM').serialize() as suggested in post above, but that will not work for FILE INPUTS... ajaxForm() will.

change Oracle user account status from EXPIRE(GRACE) to OPEN

Step-1 Need to find user details by using below query

SQL> select username, account_status from dba_users where username='BOB';

USERNAME                       ACCOUNT_STATUS
------------------------------ --------------------------------
BOB                            EXPIRED

Step-2 Get users password by using below query.

SQL>SELECT 'ALTER USER '|| name ||' IDENTIFIED BY VALUES '''|| spare4 ||';'|| password ||''';' FROM sys.user$ WHERE name='BOB';

ALTER USER BOB IDENTIFIED BY VALUES 'S:9BDD17811E21EFEDFB1403AAB1DD86AB481E;T:602E36430C0D8DF7E1E453;2F9933095143F432';

Step -3 Run Above alter query

SQL> ALTER USER BOB IDENTIFIED BY VALUES 'S:9BDD17811E21EFEDFB1403AAB1DD86AB481E;T:602E36430C0D8DF7E1E453;2F9933095143F432';
User altered.

Step-4 :Check users account status

SQL> select username, account_status from dba_users where username='BOB';
USERNAME                       ACCOUNT_STATUS
------------------------------ --------------------------------
BOB                            OPEN

How to get a variable from a file to another file in Node.js

File FileOne.js:

module.exports = { ClientIDUnsplash : 'SuperSecretKey' };

File FileTwo.js:

var { ClientIDUnsplash } = require('./FileOne');

This example works best for React.

Print range of numbers on same line

n = int(input())
for i in range(1,n+1):
    print(i,end='')

Convert .class to .java

Invoking javap to read the bytecode

The javap command takes class-names without the .class extension. Try

javap -c ClassName

Converting .class files back to .java files

javap will however not give you the implementations of the methods in java-syntax. It will at most give it to you in JVM bytecode format.

To actually decompile (i.e., do the reverse of javac) you will have to use proper decompiler. See for instance the following related question:

Use space as a delimiter with cut command

You can't do it easily with cut if the data has for example multiple spaces. I have found it useful to normalize input for easier processing. One trick is to use sed for normalization as below.

echo -e "foor\t \t bar" | sed 's:\s\+:\t:g' | cut -f2  #bar

java.lang.ClassNotFoundException: org.springframework.web.context.ContextLoaderListener

In my case the problem was that the class was located in test package. Moving it to main package has solved the problem.

"Error 404 Not Found" in Magento Admin Login Page

I have just copied and moved a Magento site to a local area so I could work on it offline and had the same problem.

But in the end I found out Magento was forcing a redirect from http to https and I didn't have a SSL setup. So this solved my problem http://www.magentocommerce.com/wiki/recover/ssl_access_with_phpmyadmin

It pretty much says set web/secure/use_in_adminhtml value from 1 to 0 in the core_config_data to allow non-secure access to the admin area

justify-content property isn't working

I had a further issue that foxed me for a while when theming existing code from a CMS. I wanted to use flexbox with justify-content:space-between but the left and right elements weren't flush.

In that system the items were floated and the container had a :before and/or an :after to clear floats at beginning or end. So setting those sneaky :before and :after elements to display:none did the trick.

Python Pandas counting and summing specific conditions

You can first make a conditional selection, and sum up the results of the selection using the sum function.

>> df = pd.DataFrame({'a': [1, 2, 3]})
>> df[df.a > 1].sum()   
a    5
dtype: int64

Having more than one condition:

>> df[(df.a > 1) & (df.a < 3)].sum()
a    2
dtype: int64

xcode library not found

If your library file is called libGoogleAnalytics.a you need to put -lGoogleAnalytics so make sure the .a file is named as you'd expect

How to execute mongo commands through shell scripts?

The shell script below also worked nicely for me... definite had to use the redirect that Antonin mentioned at first... that gave me the idea to test the here document.

function testMongoScript {
    mongo <<EOF
    use mydb
    db.leads.findOne()
    db.leads.find().count()
EOF
}

Excel VBA For Each Worksheet Loop

You need to put the worksheet identifier in your range statements as shown below ...

 Option Explicit
 Dim ws As Worksheet, a As Range

Sub forEachWs()

For Each ws In ActiveWorkbook.Worksheets
Call resizingColumns
Next

End Sub

Sub resizingColumns()
ws.Range("A:A").ColumnWidth = 20.14
ws.Range("B:B").ColumnWidth = 9.71
ws.Range("C:C").ColumnWidth = 35.86
ws.Range("D:D").ColumnWidth = 30.57
ws.Range("E:E").ColumnWidth = 23.57
ws.Range("F:F").ColumnWidth = 21.43
ws.Range("G:G").ColumnWidth = 18.43
ws.Range("H:H").ColumnWidth = 23.86
ws.Range("i:I").ColumnWidth = 27.43
ws.Range("J:J").ColumnWidth = 36.71
ws.Range("K:K").ColumnWidth = 30.29
ws.Range("L:L").ColumnWidth = 31.14
ws.Range("M:M").ColumnWidth = 31
ws.Range("N:N").ColumnWidth = 41.14
ws.Range("O:O").ColumnWidth = 33.86
End Sub

System.Collections.Generic.IEnumerable' does not contain any definition for 'ToList'

An alternative to adding LINQ would be to use this code instead:

List<Pax_Detail> paxList = new List<Pax_Detail>(pax);

How to drop a unique constraint from table column?

If you know the name of your constraint then you can directly use the command like

alter table users drop constraint constraint_name;

If you don't know the constraint name, you can get the constraint by using this command

select constraint_name,constraint_type from user_constraints where table_name = 'YOUR TABLE NAME';

SVN commit command

Step1. $ cd [your working path of code]

Step2. $ svn commit [your server path ] -m 'Add commit message'

For help use $ svn help commit

How to recover corrupted Eclipse workspace?

I have some experience at recovering from eclipse when it becomes unstartable for whatever reason, could these blog entries help you?

link (archived)

also search for "cannot start eclipse" (I am a new user, I can only post a single hyperlink, so I have to just ask that you search for the second :( sorry)

perhaps those allow you to recover your workspace as well, I hope it helps.

Array.push() if does not exist?

In case you need something simple without wanting to extend the Array prototype:

// Example array
var array = [{id: 1}, {id: 2}, {id: 3}];

function pushIfNew(obj) {
  for (var i = 0; i < array.length; i++) {
    if (array[i].id === obj.id) { // modify whatever property you need
      return;
    }
  }
  array.push(obj);
}

How to use double or single brackets, parentheses, curly braces

Parentheses in function definition

Parentheses () are being used in function definition:

function_name () { command1 ; command2 ; }

That is the reason you have to escape parentheses even in command parameters:

$ echo (
bash: syntax error near unexpected token `newline'

$ echo \(
(

$ echo () { command echo The command echo was redefined. ; }
$ echo anything
The command echo was redefined.

How do I show the number keyboard on an EditText in android?

Define this in your xml code

android:inputType="number"

ASP.NET MVC - Extract parameter of an URL

In order to get the values of your parameters, you can use RouteData.

More context would be nice. Why do you need to "extract" them in the first place? You should have an Action like:

public ActionResult Edit(int id, bool allowed) {}

How to create a circular ImageView in Android?

I too needed a rounded ImageView, I used the below code, you can modify it accordingly:

import android.content.Context;
import android.graphics.Bitmap;
import android.graphics.Bitmap.Config;
import android.graphics.Canvas;
import android.graphics.Color;
import android.graphics.Paint;
import android.graphics.PorterDuff.Mode;
import android.graphics.PorterDuffXfermode;
import android.graphics.Rect;
import android.graphics.drawable.BitmapDrawable;
import android.graphics.drawable.Drawable;
import android.util.AttributeSet;
import android.widget.ImageView;

public class RoundedImageView extends ImageView {

    public RoundedImageView(Context context) {
        super(context);
    }

    public RoundedImageView(Context context, AttributeSet attrs) {
        super(context, attrs);
    }

    public RoundedImageView(Context context, AttributeSet attrs, int defStyle) {
        super(context, attrs, defStyle);
    }

    @Override
    protected void onDraw(Canvas canvas) {

        Drawable drawable = getDrawable();

        if (drawable == null) {
            return;
        }

        if (getWidth() == 0 || getHeight() == 0) {
            return;
        }
        Bitmap b = ((BitmapDrawable) drawable).getBitmap();
        Bitmap bitmap = b.copy(Bitmap.Config.ARGB_8888, true);

        int w = getWidth();
        @SuppressWarnings("unused")
        int h = getHeight();

        Bitmap roundBitmap = getCroppedBitmap(bitmap, w);
        canvas.drawBitmap(roundBitmap, 0, 0, null);

    }

    public static Bitmap getCroppedBitmap(Bitmap bmp, int radius) {
        Bitmap sbmp;

        if (bmp.getWidth() != radius || bmp.getHeight() != radius) {
            float smallest = Math.min(bmp.getWidth(), bmp.getHeight());
            float factor = smallest / radius;
            sbmp = Bitmap.createScaledBitmap(bmp,
                    (int) (bmp.getWidth() / factor),
                    (int) (bmp.getHeight() / factor), false);
        } else {
            sbmp = bmp;
        }

        Bitmap output = Bitmap.createBitmap(radius, radius, Config.ARGB_8888);
        Canvas canvas = new Canvas(output);

        final String color = "#BAB399";
        final Paint paint = new Paint();
        final Rect rect = new Rect(0, 0, radius, radius);

        paint.setAntiAlias(true);
        paint.setFilterBitmap(true);
        paint.setDither(true);
        canvas.drawARGB(0, 0, 0, 0);
        paint.setColor(Color.parseColor(color));
        canvas.drawCircle(radius / 2 + 0.7f, radius / 2 + 0.7f,
                radius / 2 + 0.1f, paint);
        paint.setXfermode(new PorterDuffXfermode(Mode.SRC_IN));
        canvas.drawBitmap(sbmp, rect, rect, paint);

        return output;
    }

}

Create a .txt file if doesn't exist, and if it does append a new line

Try this.

string path = @"E:\AppServ\Example.txt";
if (!File.Exists(path))
{
    using (var txtFile = File.AppendText(path))
    {
        txtFile.WriteLine("The very first line!");
    }
}
else if (File.Exists(path))
{     
    using (var txtFile = File.AppendText(path))
    {
        txtFile.WriteLine("The next line!");
    }
}

Caused by: org.flywaydb.core.api.FlywayException: Validate failed. Migration Checksum mismatch for migration 2

The best solution would be to do these steps :

  1. Delete the file called - V2__create_shipwreck.sql, clean and build the project again.
  2. Run the project again, login into h2 and delete the table called "schema_version".

    drop table schema_version;

  3. Now make V2__create_shipwreck.sql file with ddl and rerun the project again.

  4. Do remember this, add version 4.1.2 for flyway-core in pom.xml like

    <dependency>
        <groupId>org.flywaydb</groupId>
        <artifactId>flyway-core</artifactId>
        <version>4.1.2</version>
    </dependency>
    

It should work now. Hope this will help.

MySQL & Java - Get id of the last inserted value (JDBC)

Alternatively you can do:

Statement stmt = db.prepareStatement(query, Statement.RETURN_GENERATED_KEYS);
numero = stmt.executeUpdate();

ResultSet rs = stmt.getGeneratedKeys();
if (rs.next()){
    risultato=rs.getString(1);
}

But use Sean Bright's answer instead for your scenario.

Visual Studio 2017 errors on standard headers

I upgraded VS2017 from version 15.2 to 15.8. With version 15.8 here's what happened:

Project -> Properties -> General -> Windows SDK Version -> select 10.0.15063.0 no longer worked for me! I had to change it to 10.0.17134.0 and then everything built again. After the upgrade and without making this change, I was getting the same header file errors.

I would have submitted this as a comment on one of the other answers but I don't have enough reputation yet.

Java and HTTPS url connection without downloading certificate

Use the latest X509ExtendedTrustManager instead of X509Certificate as advised here: java.security.cert.CertificateException: Certificates does not conform to algorithm constraints

    package javaapplication8;

    import java.io.InputStream;
    import java.net.Socket;
    import java.net.URL;
    import java.net.URLConnection;
    import java.security.cert.CertificateException;
    import java.security.cert.X509Certificate;
    import javax.net.ssl.HostnameVerifier;
    import javax.net.ssl.HttpsURLConnection;
    import javax.net.ssl.SSLContext;
    import javax.net.ssl.SSLEngine;
    import javax.net.ssl.SSLSession;
    import javax.net.ssl.TrustManager;
    import javax.net.ssl.X509ExtendedTrustManager;

    /**
     *
     * @author hoshantm
     */
    public class JavaApplication8 {

        /**
         * @param args the command line arguments
         * @throws java.lang.Exception
         */
        public static void main(String[] args) throws Exception {
            /*
             *  fix for
             *    Exception in thread "main" javax.net.ssl.SSLHandshakeException:
             *       sun.security.validator.ValidatorException:
             *           PKIX path building failed: sun.security.provider.certpath.SunCertPathBuilderException:
             *               unable to find valid certification path to requested target
             */
            TrustManager[] trustAllCerts = new TrustManager[]{
                new X509ExtendedTrustManager() {
                    @Override
                    public java.security.cert.X509Certificate[] getAcceptedIssuers() {
                        return null;
                    }

                    @Override
                    public void checkClientTrusted(X509Certificate[] certs, String authType) {
                    }

                    @Override
                    public void checkServerTrusted(X509Certificate[] certs, String authType) {
                    }

                    @Override
                    public void checkClientTrusted(X509Certificate[] xcs, String string, Socket socket) throws CertificateException {

                    }

                    @Override
                    public void checkServerTrusted(X509Certificate[] xcs, String string, Socket socket) throws CertificateException {

                    }

                    @Override
                    public void checkClientTrusted(X509Certificate[] xcs, String string, SSLEngine ssle) throws CertificateException {

                    }

                    @Override
                    public void checkServerTrusted(X509Certificate[] xcs, String string, SSLEngine ssle) throws CertificateException {

                    }

                }
            };

            SSLContext sc = SSLContext.getInstance("SSL");
            sc.init(null, trustAllCerts, new java.security.SecureRandom());
            HttpsURLConnection.setDefaultSSLSocketFactory(sc.getSocketFactory());

            // Create all-trusting host name verifier
            HostnameVerifier allHostsValid = new HostnameVerifier() {
                @Override
                public boolean verify(String hostname, SSLSession session) {
                    return true;
                }
            };
            // Install the all-trusting host verifier
            HttpsURLConnection.setDefaultHostnameVerifier(allHostsValid);
            /*
             * end of the fix
             */

            URL url = new URL("https://10.52.182.224/cgi-bin/dynamic/config/panel.bmp");
            URLConnection con = url.openConnection();
            //Reader reader = new ImageStreamReader(con.getInputStream());

            InputStream is = new URL(url.toString()).openStream();

            // Whatever you may want to do next

        }

    }

Good examples using java.util.logging

Should declare logger like this:

private final static Logger LOGGER = Logger.getLogger(MyClass.class.getName());

so if you refactor your class name it follows.

I wrote an article about java logger with examples here.

Creating SolidColorBrush from hex color value

Try this instead:

(SolidColorBrush)(new BrushConverter().ConvertFrom("#ffaacc"));

How to fix ReferenceError: primordials is not defined in node

Gulp 3.9.1 doesn't work with Node v12.x.x, and if you upgrade to Gulp 4.0.2, you have to completely change gulpfile.js with the new Syntax (Series & Parallels). So your best bet is to downgrade to Node V 11.x.x, the 11.15.0 worked fine for me. By simply using the following code in terminal:

nvm install 11.15.0
nvm use 11.15.0 #just in case it didn't automatically select the 11.15.0 as the main node.
nvm uninstall 13.1.0
npm rebuild node-sass

I want to declare an empty array in java and then I want do update it but the code is not working

Your code compiles just fine. However, your array initialization line is wrong:

int array[]={};

What this does is declare an array with a size equal to the number of elements in the brackets. Since there is nothing in the brackets, you're saying the size of the array is 0 - this renders the array completely useless, since now it can't store anything.

Instead, you can either initialize the array right in your original line:

int array[] = { 5, 5, 5, 5 };

Or you can declare the size and then populate it:

int array[] = new int[4];
// ...while loop

If you don't know the size of the array ahead of time (for example, if you're reading a file and storing the contents), you should use an ArrayList instead, because that's an array that grows in size dynamically as more elements are added to it (in layman's terms).

Print second last column/field in awk

Perl solution similar to Chris Kannon's awk solution:

perl -lane 'print $F[$#F-1]' file

These command-line options are used:

  • n loop around every line of the input file, do not automatically print every line

  • l removes newlines before processing, and adds them back in afterwards

  • a autosplit mode – split input lines into the @F array. Defaults to splitting on whitespace

  • e execute the perl code

The @F autosplit array starts at index [0] while awk fields start with $1.
$#F is the number of elements in @F

Show DialogFragment with animation growing from a point

DialogFragment has a public getTheme() method that you can over ride for this exact reason. This solution uses less lines of code:

public class MyCustomDialogFragment extends DialogFragment{
    ...
    @Override
    public int getTheme() {
        return R.style.MyThemeWithCustomAnimation;
    }
}

How to find first element of array matching a boolean condition in JavaScript?

As of ES 2015, Array.prototype.find() provides for this exact functionality.

For browsers that do not support this feature, the Mozilla Developer Network has provided a polyfill (pasted below):

if (!Array.prototype.find) {
  Array.prototype.find = function(predicate) {
    if (this === null) {
      throw new TypeError('Array.prototype.find called on null or undefined');
    }
    if (typeof predicate !== 'function') {
      throw new TypeError('predicate must be a function');
    }
    var list = Object(this);
    var length = list.length >>> 0;
    var thisArg = arguments[1];
    var value;

    for (var i = 0; i < length; i++) {
      value = list[i];
      if (predicate.call(thisArg, value, i, list)) {
        return value;
      }
    }
    return undefined;
  };
}

CSS hide scroll bar if not needed

You can use overflow:auto;

You can also control the x or y axis individually with the overflow-x and overflow-y properties.

Example:

.content {overflow:auto;}
.content {overflow-y:auto;}
.content {overflow-x:auto;}

C# Regex for Guid

This one is quite simple and does not require a delegate as you say.

resultString = Regex.Replace(subjectString, 
     @"(?im)^[{(]?[0-9A-F]{8}[-]?(?:[0-9A-F]{4}[-]?){3}[0-9A-F]{12}[)}]?$", 
     "'$0'");

This matches the following styles, which are all equivalent and acceptable formats for a GUID.

ca761232ed4211cebacd00aa0057b223
CA761232-ED42-11CE-BACD-00AA0057B223
{CA761232-ED42-11CE-BACD-00AA0057B223}
(CA761232-ED42-11CE-BACD-00AA0057B223)

Update 1

@NonStatic makes the point in the comments that the above regex will match false positives which have a wrong closing delimiter.

This can be avoided by regex conditionals which are broadly supported.

Conditionals are supported by the JGsoft engine, Perl, PCRE, Python, and the .NET framework. Ruby supports them starting with version 2.0. Languages such as Delphi, PHP, and R that have regex features based on PCRE also support conditionals. (source http://www.regular-expressions.info/conditional.html)

The regex that follows Will match

{123}
(123)
123

And will not match

{123)
(123}
{123
(123
123}
123)

Regex:

^({)?(\()?\d+(?(1)})(?(2)\))$

The solutions is simplified to match only numbers to show in a more clear way what is required if needed.

How do I use Bash on Windows from the Visual Studio Code integrated terminal?

I followed this tutorial from Paul DeCarlo to use the Bash from the Windows Subsystem for Linux (WSL) instead of what comes with Git Bash for Windows. They are the same steps as above in the answer, but use the below in your User Settings instead.

"terminal.integrated.shell.windows": "C:\\Windows\\sysnative\\bash.exe",

This worked for me the first time... which is rare for this stuff.

How should I remove all the leading spaces from a string? - swift

extension String {

    var removingWhitespaceAndNewLines: String {
        return removing(.whitespacesAndNewlines)
    }

    func removing(_ forbiddenCharacters: CharacterSet) -> String {
        return String(unicodeScalars.filter({ !forbiddenCharacters.contains($0) }))
    }
}

What is the full path to the Packages folder for Sublime text 2 on Mac OS Lion

According to the documentation, in Sublime 2, the data directory should be on these locations:

  • Windows: %APPDATA%\Sublime Text 2
  • OS X: ~/Library/Application Support/Sublime Text 2
  • Linux: ~/.config/sublime-text-2

This information is available here: http://docs.sublimetext.info/en/sublime-text-2/basic_concepts.html#the-data-directory

For Sublime 3, the locations are the following:

  • Windows: %APPDATA%\Sublime Text 3
  • OS X: ~/Library/Application Support/Sublime Text 3
  • Linux: ~/.config/sublime-text-3

This information is available here:http://docs.sublimetext.info/en/sublime-text-3/basic_concepts.html#the-data-directory

What are the differences between B trees and B+ trees?

The image below helps show the differences between B+ trees and B trees.

Advantages of B+ trees:

  • Because B+ trees don't have data associated with interior nodes, more keys can fit on a page of memory. Therefore, it will require fewer cache misses in order to access data that is on a leaf node.
  • The leaf nodes of B+ trees are linked, so doing a full scan of all objects in a tree requires just one linear pass through all the leaf nodes. A B tree, on the other hand, would require a traversal of every level in the tree. This full-tree traversal will likely involve more cache misses than the linear traversal of B+ leaves.

Advantage of B trees:

  • Because B trees contain data with each key, frequently accessed nodes can lie closer to the root, and therefore can be accessed more quickly.

B and B+ tree

How to move Docker containers between different hosts?

Use this script: https://github.com/ricardobranco777/docker-volumes.sh

This does preserve data in volumes.

Example usage:

# Stop the container   
docker stop $CONTAINER

# Create a new image   
docker commit $CONTAINER $CONTAINER

# Save image
docker save -o $CONTAINER.tar $CONTAINER

# Save the volumes (use ".tar.gz" if you want compression)
docker-volumes.sh $CONTAINER save $CONTAINER-volumes.tar

# Copy image and volumes to another host
scp $CONTAINER.tar $CONTAINER-volumes.tar $USER@$HOST:

# On the other host:
docker load -i $CONTAINER.tar
docker create --name $CONTAINER [<PREVIOUS CONTAINER OPTIONS>] $CONTAINER

# Load the volumes
docker-volumes.sh $CONTAINER load $CONTAINER-volumes.tar

# Start container
docker start $CONTAINER

PadLeft function in T-SQL

SQL Server now supports the FORMAT function starting from version 2012, so:

SELECT FORMAT(id, '0000') FROM TableA

will do the trick.

If your id or column is in a varchar and represents a number you convert first:

SELECT FORMAT(CONVERT(INT,id), '0000') FROM TableA

Disable webkit's spin buttons on input type="number"?

You can also hide spinner with following trick :

input[type=number]::-webkit-inner-spin-button,
input[type=number]::-webkit-outer-spin-button {
  opacity:0;
  pointer-events:none;
}

Error: Jump to case label

Declaration of new variables in case statements is what causing problems. Enclosing all case statements in {} will limit the scope of newly declared variables to the currently executing case which solves the problem.

switch(choice)
{
    case 1: {
       // .......
    }break;
    case 2: {
       // .......
    }break;
    case 3: {
       // .......
    }break;
}    

Test if something is not undefined in JavaScript

You must first check whether response[0] is undefined, and only if it's not, check for the rest. That means that in your case, response[0] is undefined.

How do I base64 encode a string efficiently using Excel VBA?

This code works very fast. It comes from here

Option Explicit

Private Const clOneMask = 16515072          '000000 111111 111111 111111
Private Const clTwoMask = 258048            '111111 000000 111111 111111
Private Const clThreeMask = 4032            '111111 111111 000000 111111
Private Const clFourMask = 63               '111111 111111 111111 000000

Private Const clHighMask = 16711680         '11111111 00000000 00000000
Private Const clMidMask = 65280             '00000000 11111111 00000000
Private Const clLowMask = 255               '00000000 00000000 11111111

Private Const cl2Exp18 = 262144             '2 to the 18th power
Private Const cl2Exp12 = 4096               '2 to the 12th
Private Const cl2Exp6 = 64                  '2 to the 6th
Private Const cl2Exp8 = 256                 '2 to the 8th
Private Const cl2Exp16 = 65536              '2 to the 16th

Public Function Encode64(sString As String) As String

    Dim bTrans(63) As Byte, lPowers8(255) As Long, lPowers16(255) As Long, bOut() As Byte, bIn() As Byte
    Dim lChar As Long, lTrip As Long, iPad As Integer, lLen As Long, lTemp As Long, lPos As Long, lOutSize As Long

    For lTemp = 0 To 63                                 'Fill the translation table.
        Select Case lTemp
            Case 0 To 25
                bTrans(lTemp) = 65 + lTemp              'A - Z
            Case 26 To 51
                bTrans(lTemp) = 71 + lTemp              'a - z
            Case 52 To 61
                bTrans(lTemp) = lTemp - 4               '1 - 0
            Case 62
                bTrans(lTemp) = 43                      'Chr(43) = "+"
            Case 63
                bTrans(lTemp) = 47                      'Chr(47) = "/"
        End Select
    Next lTemp

    For lTemp = 0 To 255                                'Fill the 2^8 and 2^16 lookup tables.
        lPowers8(lTemp) = lTemp * cl2Exp8
        lPowers16(lTemp) = lTemp * cl2Exp16
    Next lTemp

    iPad = Len(sString) Mod 3                           'See if the length is divisible by 3
    If iPad Then                                        'If not, figure out the end pad and resize the input.
        iPad = 3 - iPad
        sString = sString & String(iPad, Chr(0))
    End If

    bIn = StrConv(sString, vbFromUnicode)               'Load the input string.
    lLen = ((UBound(bIn) + 1) \ 3) * 4                  'Length of resulting string.
    lTemp = lLen \ 72                                   'Added space for vbCrLfs.
    lOutSize = ((lTemp * 2) + lLen) - 1                 'Calculate the size of the output buffer.
    ReDim bOut(lOutSize)                                'Make the output buffer.

    lLen = 0                                            'Reusing this one, so reset it.

    For lChar = LBound(bIn) To UBound(bIn) Step 3
        lTrip = lPowers16(bIn(lChar)) + lPowers8(bIn(lChar + 1)) + bIn(lChar + 2)    'Combine the 3 bytes
        lTemp = lTrip And clOneMask                     'Mask for the first 6 bits
        bOut(lPos) = bTrans(lTemp \ cl2Exp18)           'Shift it down to the low 6 bits and get the value
        lTemp = lTrip And clTwoMask                     'Mask for the second set.
        bOut(lPos + 1) = bTrans(lTemp \ cl2Exp12)       'Shift it down and translate.
        lTemp = lTrip And clThreeMask                   'Mask for the third set.
        bOut(lPos + 2) = bTrans(lTemp \ cl2Exp6)        'Shift it down and translate.
        bOut(lPos + 3) = bTrans(lTrip And clFourMask)   'Mask for the low set.
        If lLen = 68 Then                               'Ready for a newline
            bOut(lPos + 4) = 13                         'Chr(13) = vbCr
            bOut(lPos + 5) = 10                         'Chr(10) = vbLf
            lLen = 0                                    'Reset the counter
            lPos = lPos + 6
        Else
            lLen = lLen + 4
            lPos = lPos + 4
        End If
    Next lChar

    If bOut(lOutSize) = 10 Then lOutSize = lOutSize - 2 'Shift the padding chars down if it ends with CrLf.

    If iPad = 1 Then                                    'Add the padding chars if any.
        bOut(lOutSize) = 61                             'Chr(61) = "="
    ElseIf iPad = 2 Then
        bOut(lOutSize) = 61
        bOut(lOutSize - 1) = 61
    End If

    Encode64 = StrConv(bOut, vbUnicode)                 'Convert back to a string and return it.

End Function

Public Function Decode64(sString As String) As String

    Dim bOut() As Byte, bIn() As Byte, bTrans(255) As Byte, lPowers6(63) As Long, lPowers12(63) As Long
    Dim lPowers18(63) As Long, lQuad As Long, iPad As Integer, lChar As Long, lPos As Long, sOut As String
    Dim lTemp As Long

    sString = Replace(sString, vbCr, vbNullString)      'Get rid of the vbCrLfs.  These could be in...
    sString = Replace(sString, vbLf, vbNullString)      'either order.

    lTemp = Len(sString) Mod 4                          'Test for valid input.
    If lTemp Then
        Call Err.Raise(vbObjectError, "MyDecode", "Input string is not valid Base64.")
    End If

    If InStrRev(sString, "==") Then                     'InStrRev is faster when you know it's at the end.
        iPad = 2                                        'Note:  These translate to 0, so you can leave them...
    ElseIf InStrRev(sString, "=") Then                  'in the string and just resize the output.
        iPad = 1
    End If

    For lTemp = 0 To 255                                'Fill the translation table.
        Select Case lTemp
            Case 65 To 90
                bTrans(lTemp) = lTemp - 65              'A - Z
            Case 97 To 122
                bTrans(lTemp) = lTemp - 71              'a - z
            Case 48 To 57
                bTrans(lTemp) = lTemp + 4               '1 - 0
            Case 43
                bTrans(lTemp) = 62                      'Chr(43) = "+"
            Case 47
                bTrans(lTemp) = 63                      'Chr(47) = "/"
        End Select
    Next lTemp

    For lTemp = 0 To 63                                 'Fill the 2^6, 2^12, and 2^18 lookup tables.
        lPowers6(lTemp) = lTemp * cl2Exp6
        lPowers12(lTemp) = lTemp * cl2Exp12
        lPowers18(lTemp) = lTemp * cl2Exp18
    Next lTemp

    bIn = StrConv(sString, vbFromUnicode)               'Load the input byte array.
    ReDim bOut((((UBound(bIn) + 1) \ 4) * 3) - 1)       'Prepare the output buffer.

    For lChar = 0 To UBound(bIn) Step 4
        lQuad = lPowers18(bTrans(bIn(lChar))) + lPowers12(bTrans(bIn(lChar + 1))) + _
                lPowers6(bTrans(bIn(lChar + 2))) + bTrans(bIn(lChar + 3))           'Rebuild the bits.
        lTemp = lQuad And clHighMask                    'Mask for the first byte
        bOut(lPos) = lTemp \ cl2Exp16                   'Shift it down
        lTemp = lQuad And clMidMask                     'Mask for the second byte
        bOut(lPos + 1) = lTemp \ cl2Exp8                'Shift it down
        bOut(lPos + 2) = lQuad And clLowMask            'Mask for the third byte
        lPos = lPos + 3
    Next lChar

    sOut = StrConv(bOut, vbUnicode)                     'Convert back to a string.
    If iPad Then sOut = Left$(sOut, Len(sOut) - iPad)   'Chop off any extra bytes.
    Decode64 = sOut

End Function

How to set up gradle and android studio to do release build?

No need to update gradle for making release application in Android studio.If you were eclipse user then it will be so easy for you. If you are new then follow the steps

1: Go to the "Build" at the toolbar section. 2: Choose "Generate Signed APK..." option. enter image description here

3:fill opened form and go next 4 :if you already have .keystore or .jks then choose that file enter your password and alias name and respective password. 5: Or don't have .keystore or .jks file then click on Create new... button as shown on pic 1 then fill the form.enter image description here

Above process was to make build manually. If You want android studio to automatically Signing Your App

In Android Studio, you can configure your project to sign your release APK automatically during the build process:

On the project browser, right click on your app and select Open Module Settings. On the Project Structure window, select your app's module under Modules. Click on the Signing tab. Select your keystore file, enter a name for this signing configuration (as you may create more than one), and enter the required information. enter image description here Figure 4. Create a signing configuration in Android Studio.

Click on the Build Types tab. Select the release build. Under Signing Config, select the signing configuration you just created. enter image description here Figure 5. Select a signing configuration in Android Studio.

4:Most Important thing that make debuggable=false at gradle.

    buildTypes {
        release {
           minifyEnabled false
          proguardFiles getDefaultProguardFile('proguard-  android.txt'), 'proguard-rules.txt'
        debuggable false
        jniDebuggable false
        renderscriptDebuggable false
        zipAlignEnabled true
       }
     }

visit for more in info developer.android.com

Convert string to Time

"16:23:01" doesn't match the pattern of "hh:mm:ss tt" - it doesn't have an am/pm designator, and 16 clearly isn't in a 12-hour clock. You're specifying that format in the parsing part, so you need to match the format of the existing data. You want:

DateTime dateTime = DateTime.ParseExact(time, "HH:mm:ss",
                                        CultureInfo.InvariantCulture);

(Note the invariant culture, not the current culture - assuming your input genuinely always uses colons.)

If you want to format it to hh:mm:ss tt, then you need to put that part in the ToString call:

lblClock.Text = date.ToString("hh:mm:ss tt", CultureInfo.CurrentCulture);

Or better yet (IMO) use "whatever the long time pattern is for the culture":

lblClock.Text = date.ToString("T", CultureInfo.CurrentCulture);

Also note that hh is unusual; typically you don't want to 0-left-pad the number for numbers less than 10.

(Also consider using my Noda Time API, which has a LocalTime type - a more appropriate match for just a "time of day".)

What is a blob URL and why it is used?

I have modified working solution to handle both the case.. when video is uploaded and when image is uploaded .. hope it will help some.

HTML

<input type="file" id="fileInput">
<div> duration: <span id='sp'></span><div>

Javascript

var fileEl = document.querySelector("input");

fileEl.onchange = function(e) {


    var file = e.target.files[0]; // selected file

    if (!file) {
        console.log("nothing here");
        return;
    }

    console.log(file);
    console.log('file.size-' + file.size);
    console.log('file.type-' + file.type);
    console.log('file.acutalName-' + file.name);

    let start = performance.now();

    var mime = file.type, // store mime for later
        rd = new FileReader(); // create a FileReader

    if (/video/.test(mime)) {

        rd.onload = function(e) { // when file has read:


            var blob = new Blob([e.target.result], {
                    type: mime
                }), // create a blob of buffer
                url = (URL || webkitURL).createObjectURL(blob), // create o-URL of blob
                video = document.createElement("video"); // create video element
            //console.log(blob);
            video.preload = "metadata"; // preload setting

            video.addEventListener("loadedmetadata", function() { // when enough data loads
                console.log('video.duration-' + video.duration);
                console.log('video.videoHeight-' + video.videoHeight);
                console.log('video.videoWidth-' + video.videoWidth);
                //document.querySelector("div")
                //  .innerHTML = "Duration: " + video.duration + "s" + " <br>Height: " + video.videoHeight; // show duration
                (URL || webkitURL).revokeObjectURL(url); // clean up

                console.log(start - performance.now());
                // ... continue from here ...

            });
            video.src = url; // start video load
        };
    } else if (/image/.test(mime)) {
        rd.onload = function(e) {

            var blob = new Blob([e.target.result], {
                    type: mime
                }),
                url = URL.createObjectURL(blob),
                img = new Image();

            img.onload = function() {
                console.log('iamge');
                console.dir('this.height-' + this.height);
                console.dir('this.width-' + this.width);
                URL.revokeObjectURL(this.src); // clean-up memory
                console.log(start - performance.now()); // add image to DOM
            }

            img.src = url;

        };
    }

    var chunk = file.slice(0, 1024 * 1024 * 10); // .5MB
    rd.readAsArrayBuffer(chunk); // read file object

};

jsFiddle Url

https://jsfiddle.net/PratapDessai/0sp3b159/

How to Decode Json object in laravel and apply foreach loop on that in laravel

you can use json_decode function

foreach (json_decode($response) as $area)
{
 print_r($area); // this is your area from json response
}

See this fiddle

Check if a string is a valid Windows directory (folder) path

A simpler OS-independent solution:

Go ahead and attempt to create the actual directory; if there is an issue or the name is invalid, the OS will automatically complain and the code will throw.

public static class PathHelper
{
    public static void ValidatePath(string path)
    {
        if (!Directory.Exists(path))
            Directory.CreateDirectory(path).Delete();
    }
}

Usage:

try
{
    PathHelper.ValidatePath(path);
}
catch(Exception e)
{
    // handle exception
}

Directory.CreateDirectory() will automatically throw in all of the following situations:

System.IO.IOException:
The directory specified by path is a file. -or- The network name is not known.

System.UnauthorizedAccessException:
The caller does not have the required permission.

System.ArgumentException:
path is a zero-length string, contains only white space, or contains one or more invalid characters. You can query for invalid characters by using the System.IO.Path.GetInvalidPathChars method. -or- path is prefixed with, or contains, only a colon character (:).

System.ArgumentNullException:
path is null.

System.IO.PathTooLongException:
The specified path, file name, or both exceed the system-defined maximum length.

System.IO.DirectoryNotFoundException:
The specified path is invalid (for example, it is on an unmapped drive).

System.NotSupportedException:
path contains a colon character (:) that is not part of a drive label ("C:").

JPA: How to get entity based on field value other than ID?

It is not a "problem" as you stated it.

Hibernate has the built-in find(), but you have to build your own query in order to get a particular object. I recommend using Hibernate's Criteria :

Criteria criteria = session.createCriteria(YourClass.class);
YourObject yourObject = criteria.add(Restrictions.eq("yourField", yourFieldValue))
                             .uniqueResult();

This will create a criteria on your current class, adding the restriction that the column "yourField" is equal to the value yourFieldValue. uniqueResult() tells it to bring a unique result. If more objects match, you should retrive a list.

List<YourObject> list = criteria.add(Restrictions.eq("yourField", yourFieldValue)).list();

If you have any further questions, please feel free to ask. Hope this helps.

Converting std::__cxx11::string to std::string

Answers here mostly focus on short way to fix it, but if that does not help, I'll give some steps to check, that helped me (Linux only):

  • If the linker errors happen when linking other libraries, build those libs with debug symbols ("-g" GCC flag)
  • List the symbols in the library and grep the symbols that linker complains about (enter the commands in command line):

    nm lib_your_problem_library.a | grep functionNameLinkerComplainsAbout

  • If you got the method signature, proceed to the next step, if you got no symbols instead, mostlikely you stripped off all the symbols from the library and that is why linker can't find them when linking the library. Rebuild the library without stripping ALL the symbols, you can strip debug (strip -S option) symbols if you need.

  • Use a c++ demangler to understand the method signature, for example, this one

  • Compare the method signature in the library that you just got with the one you are using in code (check header file as well), if they are different, use the proper header or the proper library or whatever other way you now know to fix it

In an array of objects, fastest way to find the index of an object whose attributes match a search

var test = [
  {id:1, test: 1},
  {id:2, test: 2},
  {id:2, test: 2}
];

var result = test.findIndex(findIndex, '2');

console.log(result);

function findIndex(object) {
  return object.id == this;
}

will return index 1 (Works only in ES 2016)

How to change color and font on ListView

use them in Java code like this:

 color = getResources().getColor(R.color.mycolor);

The getResources() method returns the ResourceManager class for the current activity, and getColor() asks the manager to look up a color given a resource ID

Where can I find documentation on formatting a date in JavaScript?

I was unable to find any definitive documentation on valid date formats so I wrote my own test to see what is supported in various browsers.

http://blarg.co.uk/blog/javascript-date-formats

My results concluded the following formats are valid in all browsers that I tested (examples use the date "9th August 2013"):

[Full Year]/[Month]/[Date number] - Month can be either the number with or without a leading zero or the month name in short or long format, and date number can be with or without a leading zero.

  • 2013/08/09
  • 2013/08/9
  • 2013/8/09
  • 2013/8/9
  • 2013/August/09
  • 2013/August/9
  • 2013/Aug/09
  • 2013/Aug/9

[Month]/[Full Year]/[Date Number] - Month can be either the number with or without a leading zero or the month name in short or long format, and date number can be with or without a leading zero.

  • 08/2013/09
  • 08/2013/9
  • 8/2013/09
  • 8/2013/9
  • August/2013/09
  • August/2013/9
  • Aug/2013/09
  • Aug/2013/9

Any combination of [Full Year], [Month Name] and [Date Number] separated by spaces - Month name can be in either short or long format, and date number can be with or without a leading zero.

  • 2013 August 09
  • August 2013 09
  • 09 August 2013
  • 2013 Aug 09
  • Aug 9 2013
  • 2013 9 Aug
  • etc...

Also valid in "modern browsers" (or in other words all browsers except IE9 and below)

[Full Year]-[Month Number]-[Date Number] - Month and Date Number must include leading zeros (this is the format that the MySQL Date type uses)

  • 2013-08-09

Using month names:
Interestingly, when using month names I discovered that only the first 3 characters of the month name are ever used so all the of the following are perfectly valid:

new Date('9 August 2013');
new Date('9 Aug 2013');
new Date('9 Augu 2013');
new Date('9 Augustagfsdgsd 2013');

NPM doesn't install module dependencies

It looks like you hit a bug that has existed for quite a while and doesn't have solution yet. There are several open issues for this case in the npm repository:

In the first one people list several workarounds that you may try.

An alternative solution may be (a little hackish) to explicitly list the dependencies as first level dependents. This requires you to maintain the list but practically it has to be done very infrequently.

C# HttpWebRequest The underlying connection was closed: An unexpected error occurred on a send

I experienced this exception, and it was also related to ServicePointManager.SecurityProtocol.

For me, this was because ServicePointManager.SecurityProtocol had been set to Tls | Tls11 (because of certain websites the application visits with broken TLS 1.2) and upon visiting a TLS 1.2-only website (tested with SSLLabs' SSL Report), it failed.

An option for .NET 4.5 and higher is to enable all TLS versions:

ServicePointManager.SecurityProtocol = SecurityProtocolType.Tls
                                     | SecurityProtocolType.Tls11
                                     | SecurityProtocolType.Tls12;

Adding external resources (CSS/JavaScript/images etc) in JSP

Using Following Code You Solve thisQuestion.... If you run a file using localhost server than this problem solve by following Jsp Page Code.This Code put Between Head Tag in jsp file

<style type="text/css">
    <%@include file="css/style.css" %>
</style>
<script type="text/javascript">
    <%@include file="js/script.js" %>
</script>

How do I convert a TimeSpan to a formatted string?

I know this question is older but .Net 4 now has support for Custom TimeSpan formats.

Also I know it's been mentioned but it caught me out, converting Ticks to DateTime works but doesn't properly handle more than a 24 hour span.

new DateTime((DateTime.Now - DateTime.Now.AddHours(-25)).Ticks).ToString("HH:mm")

That will get you 01:00 not 25:00 as you might expect.

How to test android apps in a real device with Android Studio?

To test an android apps in a real device with Android Studio, You must keep two things in mind

  1. You should enable USB debugging option on your android phone.
  2. You must have driver installed on your computer.

Now , let me tell you how you can enable USB debugging on your android phone:

  1. Go to Settings on your android phone
  2. Scroll down to the bottom and click on About phone
  3. On this menu also scroll down to the bottom, you should see something Build number
  4. Click on Build number 7 times
  5. Now your Developer Option enables, once you done click on back button and you should see a new option on your android screen i.e. Developer Options
  6. Click On Developer Options
  7. Scroll down until you see USB Debugging
  8. Go ahead and click the check box next to the USB debugging
  9. Now your USB Debugging option enables.
  10. Connect your android device to your computer with the help of USB connector.

Now let me tell you how you can download the driver on your Windows PC:

  1. Your windows machine need a software called driver to communicate with your phone.
  2. Go To OEM USB Driver Website to install your appropriate driver
  3. Scroll down and select the driver appropriate for your device. Check the screen shoot
  4. Once you download it , you have to unzip your file
  5. After Installing Google USB Driver, close SDK Manager window, Connect your phone or tablet through USB cable to your laptop or PC.
  6. Now click on My Computer (Windows 7) (or) This PC(Windows 8.1).Select Manage.
  7. Select Device Manager –> Portable Devices –> Your Device Name
  8. Right Click on Your Device Name and Select Browse My Computer For Driver Software.
  9. Point it to C:\Users\YourUserName\AppData\Local\Android\sdk\extras\google\usb_driver. Hit Next and Finish.
  10. Now Hit Run Button after selecting Your Project in Project Explorer in Android studio. Choose your device and press OK.

java.lang.NoClassDefFoundError: com/fasterxml/jackson/core/JsonFactory

Solved the problem by upgrading the dependency to below version

<dependency>
    <groupId>com.fasterxml.jackson.core</groupId>
    <artifactId>jackson-core</artifactId>
    <version>2.9.8</version>
</dependency>

Why do I need to configure the SQL dialect of a data source?

The SQL dialect converts the HQL query which we write in our java or any other object oriented program to the specific database SQL.

For example in the java suppose I write List employees = session.createQuery("FROM Employee").list();

but when my dialect is <property name="hibernate.dialect"> org.hibernate.dialect.MySQLDialect

The HQL ("FROM Employee") gets converted to "SELECT * FROM EMPLOYEE" before hitting the MySQL database

Fastest way to convert JavaScript NodeList to Array?

Here are charts updated as of the date of this posting ("unknown platform" chart is Internet Explorer 11.15.16299.0):

Safari 11.1.2 Firefox 61.0 Chrome 68.0.3440.75 Internet Explorer 11.15.16299.0

From these results, it seems that the preallocate 1 method is the safest cross-browser bet.

Iterating through list of list in Python

Create a method to recursively iterate through nested lists. If the current element is an instance of list, then call the same method again. If not, print the current element. Here's an example:

data = [1,2,3,[4,[5,6,7,[8,9]]]]

def print_list(the_list):

    for each_item in the_list:
        if isinstance(each_item, list):
            print_list(each_item)
        else:
            print(each_item)

print_list(data)

Java, How to add values to Array List used as value in HashMap

First, you have to lookup the correct ArrayList in the HashMap:

ArrayList<String> myAList = theHashMap.get(courseID)

Then, add the new grade to the ArrayList:

myAList.add(newGrade)

enabling cross-origin resource sharing on IIS7

I can't post comments so I have to put this in a separate answer, but it's related to the accepted answer by Shah.

I initially followed Shahs answer (thank you!) by re configuring the OPTIONSVerbHandler in IIS, but my settings were restored when I redeployed my application.

I ended up removing the OPTIONSVerbHandler in my Web.config instead.

<handlers>
    <remove name="OPTIONSVerbHandler"/>
</handlers>

Basic Python client socket example

You might be confusing compilation from execution. Python has no compilation step! :) As soon as you type python myprogram.py the program runs and, in your case, tries to connect to an open port 5000, giving an error if no server program is listening there. It sounds like you are familiar with two-step languages, that require compilation to produce an executable — and thus you are confusing Python's runtime compilaint that “I can't find anyone listening on port 5000!” with a compile-time error. But, in fact, your Python code is fine; you just need to bring up a listener before running it!

Extract Month and Year From Date in R

The data.table package introduced the IDate class some time ago and zoo-package-like functions to retrieve months, days, etc (Check ?IDate). so, you can extract the desired info now in the following ways:

require(data.table)
df <- data.frame(id = 1:3,
                 date = c("2004-02-06" , "2006-03-14" , "2007-07-16"))
setDT(df)
df[ , date := as.IDate(date) ] # instead of as.Date()
df[ , yrmn := paste0(year(date), '-', month(date)) ]
df[ , yrmn2 := format(date, '%Y-%m') ]

Reading a UTF8 CSV file with Python

Using codecs.open as Alex Martelli suggested proved to be useful to me.

import codecs

delimiter = ';'
reader = codecs.open("your_filename.csv", 'r', encoding='utf-8')
for line in reader:
    row = line.split(delimiter)
    # do something with your row ...

Delete a row in Excel VBA

Chris Nielsen's solution is simple and will work well. A slightly shorter option would be...

ws.Rows(Rand).Delete

...note there is no need to specify a Shift when deleting a row as, by definition, it's not possible to shift left

Incidentally, my preferred method for deleting rows is to use...

ws.Rows(Rand) = ""

...in the initial loop. I then use a Sort function to push these rows to the bottom of the data. The main reason for this is because deleting single rows can be a very slow procedure (if you are deleting >100). It also ensures nothing gets missed as per Robert Ilbrink's comment

You can learn the code for sorting by recording a macro and reducing the code as demonstrated in this expert Excel video. I have a suspicion that the neatest method (Range("A1:Z10").Sort Key1:=Range("A1"), Order1:=xlSortAscending/Descending, Header:=xlYes/No) can only be discovered on pre-2007 versions of Excel...but you can always reduce the 2007/2010 equivalent code

Couple more points...if your list is not already sorted by a column and you wish to retain the order, you can stick the row number 'Rand' in a spare column to the right of each row as you loop through. You would then sort by that comment and eliminate it

If your data rows contain formatting, you may wish to find the end of the new data range and delete the rows that you cleared earlier. That's to keep the file size down. Note that a single large delete at the end of the procedure will not impair your code's performance in the same way that deleting single rows does

Changing :hover to touch/click for mobile devices

On most devices, the other answers work. For me, to ensure it worked on every device (in react) I had to wrap it in an anchor tag <a> and add the following: :hover, :focus, :active (in that order), as well as role="button" and tabIndex="0".

Responding with a JSON object in Node.js (converting object/array to JSON string)

Using res.json with Express:

function random(response) {
  console.log("response.json sets the appropriate header and performs JSON.stringify");
  response.json({ 
    anObject: { item1: "item1val", item2: "item2val" }, 
    anArray: ["item1", "item2"], 
    another: "item"
  });
}

Alternatively:

function random(response) {
  console.log("Request handler random was called.");
  response.writeHead(200, {"Content-Type": "application/json"});
  var otherArray = ["item1", "item2"];
  var otherObject = { item1: "item1val", item2: "item2val" };
  var json = JSON.stringify({ 
    anObject: otherObject, 
    anArray: otherArray, 
    another: "item"
  });
  response.end(json);
}

Create a BufferedImage from file and make it TYPE_INT_ARGB

Create a BufferedImage from file and make it TYPE_INT_RGB

import java.io.*;
import java.awt.image.*;
import javax.imageio.*;
public class Main{
    public static void main(String args[]){
        try{
            BufferedImage img = new BufferedImage( 
                500, 500, BufferedImage.TYPE_INT_RGB );
            File f = new File("MyFile.png");
            int r = 5;
            int g = 25; 
            int b = 255;
            int col = (r << 16) | (g << 8) | b;
            for(int x = 0; x < 500; x++){
                for(int y = 20; y < 300; y++){
                    img.setRGB(x, y, col);
                }
            }
            ImageIO.write(img, "PNG", f); 
        }
        catch(Exception e){ 
            e.printStackTrace();
        }
    }
}

This paints a big blue streak across the top.

If you want it ARGB, do it like this:

    try{
        BufferedImage img = new BufferedImage( 
            500, 500, BufferedImage.TYPE_INT_ARGB );
        File f = new File("MyFile.png");
        int r = 255;
        int g = 10;
        int b = 57;
        int alpha = 255;
        int col = (alpha << 24) | (r << 16) | (g << 8) | b;
        for(int x = 0; x < 500; x++){
            for(int y = 20; y < 30; y++){
                img.setRGB(x, y, col);
            }
        }
        ImageIO.write(img, "PNG", f);
    }
    catch(Exception e){
        e.printStackTrace();
    }

Open up MyFile.png, it has a red streak across the top.

WebAPI Multiple Put/Post parameters

[HttpPost]
public string MyMethod([FromBody]JObject data)
{
    Customer customer = data["customerData"].ToObject<Customer>();
    Product product = data["productData"].ToObject<Product>();
    Employee employee = data["employeeData"].ToObject<Employee>();
    //... other class....
}

using referance

using Newtonsoft.Json.Linq;

Use Request for JQuery Ajax

var customer = {
    "Name": "jhon",
    "Id": 1,
};
var product = {
    "Name": "table",
    "CategoryId": 5,
    "Count": 100
};
var employee = {
    "Name": "Fatih",
    "Id": 4,
};

var myData = {};
myData.customerData = customer;
myData.productData = product;
myData.employeeData = employee;

$.ajax({
    type: 'POST',
    async: true,
    dataType: "json",
    url: "Your Url",
    data: myData,
    success: function (data) {
        console.log("Response Data ?");
        console.log(data);
    },
    error: function (err) {
        console.log(err);
    }
});

Convert a string to datetime in PowerShell

$invoice = "Jul-16"
[datetime]$newInvoice = "01-" + $invoice

$newInvoice.ToString("yyyy-MM-dd")

There you go, use a type accelerator, but also into a new var, if you want to use it elsewhere, use it like so: $newInvoice.ToString("yyyy-MM-dd")as $newInvoice will always be in the datetime format, unless you cast it as a string afterwards, but will lose the ability to perform datetime functions - adding days etc...

How to add a WiX custom action that happens only on uninstall (via MSI)?

Here's a set of properties i made that feel more intuitive to use than the built in stuff. The conditions are based off of the truth table supplied above by ahmd0.

<!-- truth table for installer varables (install vs uninstall vs repair vs upgrade) https://stackoverflow.com/a/17608049/1721136 -->
 <SetProperty Id="_INSTALL"   After="FindRelatedProducts" Value="1"><![CDATA[Installed="" AND PREVIOUSVERSIONSINSTALLED=""]]></SetProperty>
 <SetProperty Id="_UNINSTALL" After="FindRelatedProducts" Value="1"><![CDATA[PREVIOUSVERSIONSINSTALLED="" AND REMOVE="ALL"]]></SetProperty>
 <SetProperty Id="_CHANGE"    After="FindRelatedProducts" Value="1"><![CDATA[Installed<>"" AND REINSTALL="" AND PREVIOUSVERSIONSINSTALLED<>"" AND REMOVE=""]]></SetProperty>
 <SetProperty Id="_REPAIR"    After="FindRelatedProducts" Value="1"><![CDATA[REINSTALL<>""]]></SetProperty>
 <SetProperty Id="_UPGRADE"   After="FindRelatedProducts" Value="1"><![CDATA[PREVIOUSVERSIONSINSTALLED<>"" ]]></SetProperty>

Here's some sample usage:

  <Custom Action="CaptureExistingLocalSettingsValues" After="InstallInitialize">NOT _UNINSTALL</Custom>
  <Custom Action="GetConfigXmlToPersistFromCmdLineArgs" After="InstallInitialize">_INSTALL OR _UPGRADE</Custom>
  <Custom Action="ForgetProperties" Before="InstallFinalize">_UNINSTALL OR _UPGRADE</Custom>
  <Custom Action="SetInstallCustomConfigSettingsArgs" Before="InstallCustomConfigSettings">NOT _UNINSTALL</Custom>
  <Custom Action="InstallCustomConfigSettings" Before="InstallFinalize">NOT _UNINSTALL</Custom>

Issues:

Sending Arguments To Background Worker?

you can try this out if you want to pass more than one type of arguments, first add them all to an array of type Object and pass that object to RunWorkerAsync() here is an example :

   some_Method(){
   List<string> excludeList = new List<string>(); // list of strings
   string newPath ="some path";  // normal string
   Object[] args = {newPath,excludeList };
            backgroundAnalyzer.RunWorkerAsync(args);
      }

Now in the doWork method of background worker

backgroundAnalyzer_DoWork(object sender, DoWorkEventArgs e)
      {
        backgroundAnalyzer.ReportProgress(50);
        Object[] arg = e.Argument as Object[];
        string path= (string)arg[0];
        List<string> lst = (List<string>) arg[1];
        .......
        // do something......
        //.....
       }

Can't install nuget package because of "Failed to initialize the PowerShell host"

After trying various suggested fixes, it was finally solved by updating the NuGet Package Manager extension in Visual Studio.

This is done under Tools -> Extensions And Updates, then in the Extensions and Updates dialog Updated -> Visual Studio Gallery. A restart of Visual Studio may be required.

How to extract svg as file from web page

Based on a web search, I just found a Chrome plugin called SVG Export.

Regex Match all characters between two strings

You can simply use this: \This is .*? \sentence

Converting integer to binary in python

Just use the format function

format(6, "08b")

The general form is

format(<the_integer>, "<0><width_of_string><format_specifier>")

fastest way to export blobs from table into individual files

I tried using a CLR function and it was more than twice as fast as BCP. Here's my code.

Original Method:

SET @bcpCommand = 'bcp "SELECT blobcolumn FROM blobtable WHERE ID = ' + CAST(@FileID AS VARCHAR(20)) + '" queryout "' + @FileName + '" -T -c'
EXEC master..xp_cmdshell @bcpCommand

CLR Method:

declare @file varbinary(max) = (select blobcolumn from blobtable WHERE ID = @fileid)
declare @filepath nvarchar(4000) = N'c:\temp\' + @FileName
SELECT Master.dbo.WriteToFile(@file, @filepath, 0)

C# Code for the CLR function

using System;
using System.Data;
using System.Data.SqlTypes;
using System.IO;
using Microsoft.SqlServer.Server;

namespace BlobExport
{
    public class Functions
    {
      [SqlFunction]
      public static SqlString WriteToFile(SqlBytes binary, SqlString path, SqlBoolean append)
      {        
        try
        {
          if (!binary.IsNull && !path.IsNull && !append.IsNull)
          {         
            var dir = Path.GetDirectoryName(path.Value);           
            if (!Directory.Exists(dir))              
              Directory.CreateDirectory(dir);            
              using (var fs = new FileStream(path.Value, append ? FileMode.Append : FileMode.OpenOrCreate))
            {
                byte[] byteArr = binary.Value;
                for (int i = 0; i < byteArr.Length; i++)
                {
                    fs.WriteByte(byteArr[i]);
                };
            }
            return "SUCCESS";
          }
          else
             "NULL INPUT";
        }
        catch (Exception ex)
        {          
          return ex.Message;
        }
      }
    }
}

Difference between id and name attributes in HTML

name is deprecated for link targets, and invalid in HTML5. It no longer works at least in latest Firefox (v13). Change <a name="hello"> to<a id="hello">

The target does not need to be an <a> tag, it can be <p id="hello"> or <h2 id="hello"> etc. which is often cleaner code.

As other posts say clearly, name is still used (needed) in forms. It is also still used in META tags.

Flatten List in LINQ

iList.SelectMany(x => x).ToArray()

enable/disable zoom in Android WebView

hey there for anyone who might be looking for solution like this.. i had issue with scaling inside WebView so best way to do is in your java.class where you set all for webView put this two line of code: (webViewSearch is name of my webView -->webViewSearch = (WebView) findViewById(R.id.id_webview_search);)

// force WebView to show content not zoomed---------------------------------------------------------
    webViewSearch.getSettings().setLoadWithOverviewMode(true);
    webViewSearch.getSettings().setUseWideViewPort(true);

How do I write a SQL query for a specific date range and date time using SQL Server 2008?

use DBName

select * from TABLE_NAME A

where A.date >= '2018-06-26 21:24' and A.date <= '2018-06-26 21:28';

CSS selector for "foo that contains bar"?

Only thing that comes even close is the :contains pseudo class in CSS3, but that only selects textual content, not tags or elements, so you're out of luck.

A simpler way to select a parent with specific children in jQuery can be written as (with :has()):

$('#parent:has(#child)');

jQuery Selector: Id Ends With?

It's safer to add the underscore or $ to the term you're searching for so it's less likely to match other elements which end in the same ID:

$("element[id$=_txtTitle]")

(where element is the type of element you're trying to find - eg div, input etc.

(Note, you're suggesting your IDs tend to have $ signs in them, but I think .NET 2 now tends to use underscores in the ID instead, so my example uses an underscore).

C++: How to round a double to an int?

Casting is not a mathematical operation and doesn't behave as such. Try

int y = (int)round(x);

How can I set / change DNS using the command-prompt at windows 8

Now you can change the primary dns (index=1), assuming that your interface is static (not using dhcp)

You can set your DNS servers statically even if you use DHCP to obtain your IP address.

Example under Windows 7 to add two DN servers, the command is as follows:

netsh interface ipv4 add dns "Local Area Connection" address=192.168.x.x index=1 netsh interface ipv4 add dns "Local Area Connection" address=192.168.x.x index=2

iOS app 'The application could not be verified' only on one device

I faced this issue a lot. I am not sure if this is the issue, but I think, when xCode saw that there is an app with the same bundle identifier as of the app, I am trying to install, it didn't allow me. So, I had to delete the older one and attempted to install and it worked. However sometimes for testing purpose, I needed multiple version of the same app and in that case, I would change the bundle identifier and try to install. It only works if, I am using an wildcard provisioning profile.

How to make a div fill a remaining horizontal space?

The easiest solution is to use margin. This will also be responsive!

<div style="margin-right: auto">left</div>
<div style="margin-left: auto; margin-right:auto">center</div>
<div style="margin-left: auto">right</div>

Build and Install unsigned apk on device without the development server?

There are two extensions you can use for this. This is added to react-native for setting these:

  1. disableDevInDebug: true: Disables dev server in debug buildType
  2. bundleInDebug: true: Adds jsbundle to debug buildType.

So, your final project.ext.react in android/app/build.gradle should look like below

project.ext.react = [
    enableHermes: false,  // clean and rebuild if changing
    devDisabledInDev: true, // Disable dev server in dev release
    bundleInDev: true, // add bundle to dev apk
]

Why there is no ConcurrentHashSet against ConcurrentHashMap

Like Ray Toal mentioned it is as easy as:

Set<String> myConcurrentSet = ConcurrentHashMap.newKeySet();

What is recursion and when should I use it?

A great many problems can be thought of in two types of pieces:

  1. Base cases, which are elementary things that you can solve by just looking at them, and
  2. Recursive cases, which build a bigger problem out of smaller pieces (elementary or otherwise).

So what's a recursive function? Well, that's where you have a function that is defined in terms of itself, directly or indirectly. OK, that sounds ridiculous until you realize that it is sensible for the problems of the kind described above: you solve the base cases directly and deal with the recursive cases by using recursive calls to solve the smaller pieces of the problem embedded within.

The truly classic example of where you need recursion (or something that smells very much like it) is when you're dealing with a tree. The leaves of the tree are the base case, and the branches are the recursive case. (In pseudo-C.)

struct Tree {
    int leaf;
    Tree *leftBranch;
    Tree *rightBranch;
};

The simplest way of printing this out in order is to use recursion:

function printTreeInOrder(Tree *tree) {
    if (tree->leftBranch) {
        printTreeInOrder(tree->leftBranch);
    }
    print(tree->leaf);
    if (tree->rightBranch) {
        printTreeInOrder(tree->rightBranch);
    }
}

It's dead easy to see that that's going to work, since it's crystal clear. (The non-recursive equivalent is quite a lot more complex, requiring a stack structure internally to manage the list of things to process.) Well, assuming that nobody's done a circular connection of course.

Mathematically, the trick to showing that recursion is tamed is to focus on finding a metric for the size of the arguments. For our tree example, the easiest metric is the maximum depth of the tree below the current node. At leaves, it's zero. At a branch with only leaves below it, it's one, etc. Then you can simply show that there's strictly ordered sequence on the size of the arguments that the function is invoked on in order to process the tree; the arguments to the recursive calls are always "lesser" in the sense of the metric than the argument to the overall call. With a strictly decreasing cardinal metric, you're sorted.

It's also possible to have infinite recursion. That's messy and in many languages won't work because the stack blows up. (Where it does work, the language engine must be determining that the function somehow doesn't return and is able therefore to optimize away the keeping of the stack. Tricky stuff in general; tail-recursion is just the most trivial way of doing this.)

Angular 2 - How to navigate to another route using this.router.parent.navigate('/about')?

import { Router } from '@angular/router';
//in your constructor
constructor(public router: Router){}

//navigation 
link.this.router.navigateByUrl('/home');

How do I convert strings in a Pandas data frame to a 'date' data type?

Another way to do this and this works well if you have multiple columns to convert to datetime.

cols = ['date1','date2']
df[cols] = df[cols].apply(pd.to_datetime)

How to set up Spark on Windows?

Here's the fixes to get it to run in Windows without rebuilding everything - such as if you do not have a recent version of MS-VS. (You will need a Win32 C++ compiler, but you can install MS VS Community Edition free.)

I've tried this with Spark 1.2.2 and mahout 0.10.2 as well as with the latest versions in November 2015. There are a number of problems including the fact that the Scala code tries to run a bash script (mahout/bin/mahout) which does not work of course, the sbin scripts have not been ported to windows, and the winutils are missing if hadoop is not installed.

(1) Install scala, then unzip spark/hadoop/mahout into the root of C: under their respective product names.

(2) Rename \mahout\bin\mahout to mahout.sh.was (we will not need it)

(3) Compile the following Win32 C++ program and copy the executable to a file named C:\mahout\bin\mahout (that's right - no .exe suffix, like a Linux executable)

#include "stdafx.h"
#define BUFSIZE 4096
#define VARNAME TEXT("MAHOUT_CP")
int _tmain(int argc, _TCHAR* argv[]) {
    DWORD dwLength;     LPTSTR pszBuffer;
    pszBuffer = (LPTSTR)malloc(BUFSIZE*sizeof(TCHAR));
    dwLength = GetEnvironmentVariable(VARNAME, pszBuffer, BUFSIZE);
    if (dwLength > 0) { _tprintf(TEXT("%s\n"), pszBuffer); return 0; }
    return 1;
}

(4) Create the script \mahout\bin\mahout.bat and paste in the content below, although the exact names of the jars in the _CP class paths will depend on the versions of spark and mahout. Update any paths per your installation. Use 8.3 path names without spaces in them. Note that you cannot use wildcards/asterisks in the classpaths here.

set SCALA_HOME=C:\Progra~2\scala
set SPARK_HOME=C:\spark
set HADOOP_HOME=C:\hadoop
set MAHOUT_HOME=C:\mahout
set SPARK_SCALA_VERSION=2.10
set MASTER=local[2]
set MAHOUT_LOCAL=true
set path=%SCALA_HOME%\bin;%SPARK_HOME%\bin;%PATH%
cd /D %SPARK_HOME%
set SPARK_CP=%SPARK_HOME%\conf\;%SPARK_HOME%\lib\xxx.jar;...other jars...
set MAHOUT_CP=%MAHOUT_HOME%\lib\xxx.jar;...other jars...;%MAHOUT_HOME%\xxx.jar;...other jars...;%SPARK_CP%;%MAHOUT_HOME%\lib\spark\xxx.jar;%MAHOUT_HOME%\lib\hadoop\xxx.jar;%MAHOUT_HOME%\src\conf;%JAVA_HOME%\lib\tools.jar
start "master0" "%JAVA_HOME%\bin\java" -cp "%SPARK_CP%" -Xms1g -Xmx1g org.apache.spark.deploy.master.Master --ip localhost --port 7077 --webui-port 8082 >>out-master0.log 2>>out-master0.err
start "worker1" "%JAVA_HOME%\bin\java" -cp "%SPARK_CP%" -Xms1g -Xmx1g org.apache.spark.deploy.worker.Worker spark://localhost:7077 --webui-port 8083 >>out-worker1.log 2>>out-worker1.err
...you may add more workers here...
cd /D %MAHOUT_HOME%
"%JAVA_HOME%\bin\java" -Xmx4g -classpath "%MAHOUT_CP%" "org.apache.mahout.sparkbindings.shell.Main"

The name of the variable MAHOUT_CP should not be changed, as it is referenced in the C++ code.

Of course you can comment-out the code that launches the Spark master and worker because Mahout will run Spark as-needed; I just put it in the batch job to show you how to launch it if you wanted to use Spark without Mahout.

(5) The following tutorial is a good place to begin:

https://mahout.apache.org/users/sparkbindings/play-with-shell.html

You can bring up the Mahout Spark instance at:

"C:\Program Files (x86)\Google\Chrome\Application\chrome" --disable-web-security http://localhost:4040

Is it possible to run .APK/Android apps on iPad/iPhone devices?

There is another option not mentioned previously:

  • Pieceable Viewer has unfortunately stopped its service at December 31, 2012 but open-sourced its software. You need to compile your iOS application for the emulator and Pieceable's software will embed it in a webpage which hosts the application. This webpage can be used to run the iOS application. See Pieceable's for more details.

How do I add the Java API documentation to Eclipse?

if you are using maven:

mvn eclipse:eclipse -DdownloadSources=true  -DdownloadJavadocs=true

Load vs. Stress testing

The terms "stress testing" and "load testing" are often used interchangeably by software test engineers but they are really quite different.

Stress testing

In Stress testing we tries to break the system under test by overwhelming its resources or by taking resources away from it (in which case it is sometimes called negative testing). The main purpose behind this madness is to make sure that the system fails and recovers gracefully -- this quality is known as recoverability. OR Stress testing is the process of subjecting your program/system under test (SUT) to reduced resources and then examining the SUT’s behavior by running standard functional tests. The idea of this is to expose problems that do not appear under normal conditions.For example, a multi-threaded program may work fine under normal conditions but under conditions of reduced CPU availability, timing issues will be different and the SUT will crash. The most common types of system resources reduced in stress testing are CPU, internal memory, and external disk space. When performing stress testing, it is common to call the tools which reduce these three resources EatCPU, EatMem, and EatDisk respectively.

While on the other hand Load Testing

In case of Load testing Load testing is the process of subjecting your SUT to heavy loads, typically by simulating multiple users( Using Load runner), where "users" can mean human users or virtual/programmatic users. The most common example of load testing involves subjecting a Web-based or network-based application to simultaneous hits by thousands of users. This is generally accomplished by a program which simulates the users. There are two main purposes of load testing: to determine performance characteristics of the SUT, and to determine if the SUT "breaks" gracefully or not.

In the case of a Web site, you would use load testing to determine how many users your system can handle and still have adequate performance, and to determine what happens with an extreme load — will the Web site generate a "too busy" message for users, or will the Web server crash in flames?

How to convert Nonetype to int or string?

In one of the comments, you say:

Somehow I got an Nonetype value, it supposed to be an int, but it's now a Nonetype object

If it's your code, figure out how you're getting None when you expect a number and stop that from happening.

If it's someone else's code, find out the conditions under which it gives None and determine a sensible value to use for that, with the usual conditional code:

result = could_return_none(x)

if result is None:
    result = DEFAULT_VALUE

...or even...

if x == THING_THAT_RESULTS_IN_NONE:
    result = DEFAULT_VALUE
else:
    result = could_return_none(x) # But it won't return None, because we've restricted the domain.

There's no reason to automatically use 0 here — solutions that depend on the "false"-ness of None assume you will want this. The DEFAULT_VALUE (if it even exists) completely depends on your code's purpose.

How do I execute external program within C code in linux with arguments?

You can use fork() and system() so that your program doesn't have to wait until system() returns.

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

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

    int status;

    // By calling fork(), a child process will be created as a exact duplicate of the calling process.
    // Search for fork() (maybe "man fork" on Linux) for more information.
    if(fork() == 0){ 
        // Child process will return 0 from fork()
        printf("I'm the child process.\n");
        status = system("my_app");
        exit(0);
    }else{
        // Parent process will return a non-zero value from fork()
        printf("I'm the parent.\n");
    }

    printf("This is my main program and it will continue running and doing anything i want to...\n");

    return 0;
}

Getting A File's Mime Type In Java

Apache Tika offers in tika-core a mime type detection based based on magic markers in the stream prefix. tika-core does not fetch other dependencies, which makes it as lightweight as the currently unmaintained Mime Type Detection Utility.

Simple code example (Java 7), using the variables theInputStream and theFileName

try (InputStream is = theInputStream;
        BufferedInputStream bis = new BufferedInputStream(is);) {
    AutoDetectParser parser = new AutoDetectParser();
    Detector detector = parser.getDetector();
    Metadata md = new Metadata();
    md.add(Metadata.RESOURCE_NAME_KEY, theFileName);
    MediaType mediaType = detector.detect(bis, md);
    return mediaType.toString();
}

Please note that MediaType.detect(...) cannot be used directly (TIKA-1120). More hints are provided at https://tika.apache.org/1.24/detection.html.

Convert array of indices to 1-hot encoded numpy array

You can use sklearn.preprocessing.LabelBinarizer:

Example:

import sklearn.preprocessing
a = [1,0,3]
label_binarizer = sklearn.preprocessing.LabelBinarizer()
label_binarizer.fit(range(max(a)+1))
b = label_binarizer.transform(a)
print('{0}'.format(b))

output:

[[0 1 0 0]
 [1 0 0 0]
 [0 0 0 1]]

Amongst other things, you may initialize sklearn.preprocessing.LabelBinarizer() so that the output of transform is sparse.

Java Mouse Event Right Click

I've seen

anEvent.isPopupTrigger() 

be used before. I'm fairly new to Java so I'm happy to hear thoughts about this approach :)

Bootstrap-select - how to fire event on change

This is what I did.

$('.selectpicker').on('changed.bs.select', function (e, clickedIndex, newValue, oldValue) {
    var selected = $(e.currentTarget).val();
});

Return index of highest value in an array

$newarr=arsort($arr);
$max_key=array_shift(array_keys($new_arr));

SQL Server - transactions roll back on error?

Here the code with getting the error message working with MSSQL Server 2016:

BEGIN TRY
    BEGIN TRANSACTION 
        -- Do your stuff that might fail here
    COMMIT
END TRY
BEGIN CATCH
    IF @@TRANCOUNT > 0
        ROLLBACK TRAN

        DECLARE @ErrorMessage NVARCHAR(4000) = ERROR_MESSAGE()
        DECLARE @ErrorSeverity INT = ERROR_SEVERITY()
        DECLARE @ErrorState INT = ERROR_STATE()

    -- Use RAISERROR inside the CATCH block to return error  
    -- information about the original error that caused  
    -- execution to jump to the CATCH block.  
    RAISERROR (@ErrorMessage, @ErrorSeverity, @ErrorState);
END CATCH

Difference between 2 dates in seconds

$timeFirst  = strtotime('2011-05-12 18:20:20');
$timeSecond = strtotime('2011-05-13 18:20:20');
$differenceInSeconds = $timeSecond - $timeFirst;

You will then be able to use the seconds to find minutes, hours, days, etc.

Amazon S3 exception: "The specified key does not exist"

Step 1: Get the latest aws-java-sdk

<!-- https://mvnrepository.com/artifact/org.apache.hadoop/hadoop-aws -->
<dependency>
<groupId>com.amazonaws</groupId>
<artifactId>aws-java-sdk</artifactId>
<version>1.11.660</version>
</dependency>

Step 2: The correct imports

import com.amazonaws.auth.AWSCredentials;
import com.amazonaws.auth.BasicAWSCredentials;
import com.amazonaws.regions.Region;
import com.amazonaws.regions.Regions;
import com.amazonaws.services.s3.AmazonS3;
import com.amazonaws.services.s3.AmazonS3Client;
import com.amazonaws.services.s3.AmazonS3ClientBuilder;
import com.amazonaws.services.s3.model.ListObjectsRequest;
import com.amazonaws.services.s3.model.ObjectListing;

If you are sure the bucket exists, Specified key does not exists error would mean the bucketname is not spelled correctly ( contains slash or special characters). Refer the documentation for naming convention.

The document quotes:

If the requested object is available in the bucket and users are still getting the 404 NoSuchKey error from Amazon S3, check the following:

Confirm that the request matches the object name exactly, including the capitalization of the object name. Requests for S3 objects are case sensitive. For example, if an object is named myimage.jpg, but Myimage.jpg is requested, then requester receives a 404 NoSuchKey error. Confirm that the requested path matches the path to the object. For example, if the path to an object is awsexamplebucket/Downloads/February/Images/image.jpg, but the requested path is awsexamplebucket/Downloads/February/image.jpg, then the requester receives a 404 NoSuchKey error. If the path to the object contains any spaces, be sure that the request uses the correct syntax to recognize the path. For example, if you're using the AWS CLI to download an object to your Windows machine, you must use quotation marks around the object path, similar to: aws s3 cp "s3://awsexamplebucket/Backup Copy Job 4/3T000000.vbk". Optionally, you can enable server access logging to review request records in further detail for issues that might be causing the 404 error.

AWSCredentials credentials = new BasicAWSCredentials(AWS_ACCESS_KEY_ID, AWS_SECRET_KEY);
AmazonS3 s3Client = AmazonS3ClientBuilder.standard().withRegion(Regions.US_EAST_1).build();
ObjectListing objects = s3Client.listObjects("bigdataanalytics");
System.out.println(objects.getObjectSummaries());

How to make a radio button unchecked by clicking it?

Unfortunately it does not work in Chrome or Edge, but it does work in FireFox:

$(document)
// uncheck it when clicked
.on("click","input[type='radio']", function(){ $(this).prop("checked",false); })
// re-check it if value is changed to this input
.on("change","input[type='radio']", function(){ $(this).prop("checked",true); });

Generate random numbers uniformly over an entire range

If you want numbers to be uniformly distributed over the range, you should break your range up into a number of equal sections that represent the number of points you need. Then get a random number with a min/max for each section.

As another note, you should probably not use rand() as it's not very good at actually generating random numbers. I don't know what platform you're running on, but there is probably a better function you can call like random().

Simple JavaScript login form validation

Add a property to the form method="post".

Like this:

<form name="loginform" method="post">

How do you use youtube-dl to download live streams (that are live)?

I have Written a small script to download the live youtube video, you may use as single command as well. script it can be invoked simply as,

~/ytdl_lv.sh <URL> <output file name>

e.g.

~/ytdl_lv.sh https://www.youtube.com/watch?v=BLIGxsYLyjc myfile.mp4

script is as simple as below,

#!/bin/bash 

# ytdl_lv.sh
# Author Prashant
# 

URL=$1 
OUTNAME=$2
streamlink --hls-live-restart -o ${OUTNAME} ${URL} best

here the best is the stream quality, it also can be 144p (worst), 240p, 360p, 480p, 720p (best)

Web colors in an Android color xml resource file

I specifically was looking for the XML representation for Android.Graphics.Color. I didn't find these, so here you are. More details are in the help document.

<?xml version="1.0" encoding="utf-8"?>
<resources>
    <color name="sysBlack">#FF000000</color>
    <color name="sysBlue">#FF0000FF</color>
    <color name="sysCyan">#FF00FFFF</color>
    <color name="sysDkGray">#FF444444</color>
    <color name="sysGray">#FF888888</color>
    <color name="sysGreen">#FF00FF00</color>
    <color name="sysLtGray">#FFCCCCCC</color>
    <color name="sysMagenta">#FFFF00FF</color>
    <color name="sysRed">#FFFF0000</color>
    <color name="sysTransparent">#00000000</color>
    <color name="sysWhite">#FFFFFFFF</color>
    <color name="sysYellow">#FFFFFF00</color>
</resources>

Of course, this is used like this:

android:textColor="@color/sysGray"

C# DateTime to UTC Time without changing the time

You can use the overloaded constructor of DateTime:

DateTime utcDateTime = new DateTime(dateTime.Year, dateTime.Month, dateTime.Day, dateTime.Hour, dateTime.Minute, dateTime.Second, DateTimeKind.Utc);

What's the most concise way to read query parameters in AngularJS?

You can inject $routeParams (requires ngRoute) into your controller. Here's an example from the docs:

// Given:
// URL: http://server.com/index.html#/Chapter/1/Section/2?search=moby
// Route: /Chapter/:chapterId/Section/:sectionId
//
// Then
$routeParams ==> {chapterId:1, sectionId:2, search:'moby'}

EDIT: You can also get and set query parameters with the $location service (available in ng), particularly its search method: $location.search().

$routeParams are less useful after the controller's initial load; $location.search() can be called anytime.

global variable for all controller and views

In Laravel 5+, to set a variable just once and access it 'globally', I find it easiest to just add it as an attribute to the Request:

$request->attributes->add(['myVar' => $myVar]);

Then you can access it from any of your controllers using:

$myVar = $request->get('myVar');

and from any of your blades using:

{{ Request::get('myVar') }}

How to create duplicate table with new name in SQL Server 2008

To create a new table from an existing table: (copying all rows from Old_Table into de New_Table):

SELECT * INTO New_table FROM  Old_Table

To copy the data from one table to another (when you have already created them):

Insert into Table_Name2 select top 1 * from Table_Name1

Remember to remove the top 1 argument and apply a relevant where clause if needed on the Select

How to remove leading zeros using C#

This Regex let you avoid wrong result with digits which consits only from zeroes "0000" and work on digits of any length:

using System.Text.RegularExpressions;

/*
00123 => 123
00000 => 0
00000a => 0a
00001a => 1a
00001a => 1a
0000132423423424565443546546356546454654633333a => 132423423424565443546546356546454654633333a
*/

Regex removeLeadingZeroesReg = new Regex(@"^0+(?=\d)");
var strs = new string[]
{
    "00123",
    "00000",
    "00000a",
    "00001a",
    "00001a",
    "0000132423423424565443546546356546454654633333a",
};
foreach (string str in strs)
{
    Debug.Print(string.Format("{0} => {1}", str, removeLeadingZeroesReg.Replace(str, "")));
}

And this regex will remove leading zeroes anywhere inside string:

new Regex(@"(?<!\d)0+(?=\d)");
//  "0000123432 d=0 p=002 3?0574 m=600"
//     => "123432 d=0 p=2 3?574 m=600"

How can I remove Nan from list Python/NumPy

I like to remove missing values from a list like this:

list_no_nan = [x for x in list_with_nan if pd.notnull(x)]

How to use particular CSS styles based on screen size / device

Use @media queries. They serve this exact purpose. Here's an example how they work:

@media (max-width: 800px) {
  /* CSS that should be displayed if width is equal to or less than 800px goes here */
}

This would work only on devices whose width is equal to or less than 800px.

Read up more about media queries on the Mozilla Developer Network.

Android: How to get a custom View's height and width?

Don't try to get them inside its constructor. Try Call them in onDraw() method.

How to break out from foreach loop in javascript

Use a for loop instead of .forEach()

var myObj = [{"a": "1","b": null},{"a": "2","b": 5}]
var result = false

for(var call of myObj) {
    console.log(call)
    
    var a = call['a'], b = call['b']
     
    if(a == null || b == null) {
        result = false
        break
    }
}

SSRS Expression for IF, THEN ELSE

You should be able to use

IIF(Fields!ExitReason.Value = 7, 1, 0)

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

Check if a Class Object is subclass of another Class Object in Java

In addition to @To-kra's answer. If someone doesn't like recurrence:

    public static boolean isSubClassOf(Class<?> clazz, Class<?> superClass) {
        if(Object.class.equals(superClass)) {
            return true;
        }

        for(; !Object.class.equals(clazz); clazz = clazz.getSuperclass()) {
            if(clazz.getSuperclass().equals(superClass)) {
                return true;
            }
        }

        return false;
    }

NOTE: no null checking for clarity.

Use of REPLACE in SQL Query for newline/ carriage return characters

There are probably embedded tabs (CHAR(9)) etc. as well. You can find out what other characters you need to replace (we have no idea what your goal is) with something like this:

DECLARE @var NVARCHAR(255), @i INT;

SET @i = 1;

SELECT @var = AccountType FROM dbo.Account
  WHERE AccountNumber = 200
  AND AccountType LIKE '%Daily%';

CREATE TABLE #x(i INT PRIMARY KEY, c NCHAR(1), a NCHAR(1));

WHILE @i <= LEN(@var)
BEGIN
  INSERT #x 
    SELECT SUBSTRING(@var, @i, 1), ASCII(SUBSTRING(@var, @i, 1));

  SET @i = @i + 1;
END

SELECT i,c,a FROM #x ORDER BY i;

You might also consider doing better cleansing of this data before it gets into your database. Cleaning it every time you need to search or display is not the best approach.

Where is array's length property defined?

Arrays are special objects in java, they have a simple attribute named length which is final.

There is no "class definition" of an array (you can't find it in any .class file), they're a part of the language itself.

10.7. Array Members

The members of an array type are all of the following:

  • The public final field length, which contains the number of components of the array. length may be positive or zero.
  • The public method clone, which overrides the method of the same name in class Object and throws no checked exceptions. The return type of the clone method of an array type T[] is T[].

    A clone of a multidimensional array is shallow, which is to say that it creates only a single new array. Subarrays are shared.

  • All the members inherited from class Object; the only method of Object that is not inherited is its clone method.

Resources:

How do I replace all line breaks in a string with <br /> elements?

Not answering the specific question, but I am sure this will help someone...

If you have output from PHP that you want to render on a web page using JavaScript (perhaps the result of an Ajax request), and you just want to retain white space and line breaks, consider just enclosing the text inside a <pre></pre> block:

var text_with_line_breaks = retrieve_some_text_from_php();
var element = document.querySelectorAll('#output');
element.innerHTML = '<pre>' + text_with_line_breaks + '</pre>';

How do I write a RGB color value in JavaScript?

I am showing with an example of adding random color. You can write this way

var r = Math.floor(Math.random() * 255);
var g = Math.floor(Math.random() * 255);
var b = Math.floor(Math.random() * 255);
var col = "rgb(" + r + "," + g + "," + b + ")";
parent.childNodes[1].style.color = col;

The property is expected as a string

Getting a list of values from a list of dicts

Follow the example --

songs = [
{"title": "happy birthday", "playcount": 4},
{"title": "AC/DC", "playcount": 2},
{"title": "Billie Jean", "playcount": 6},
{"title": "Human Touch", "playcount": 3}
]

print("===========================")
print(f'Songs --> {songs} \n')
title = list(map(lambda x : x['title'], songs))
print(f'Print Title --> {title}')

playcount = list(map(lambda x : x['playcount'], songs))
print(f'Print Playcount --> {playcount}')
print (f'Print Sorted playcount --> {sorted(playcount)}')

# Aliter -
print(sorted(list(map(lambda x: x['playcount'],songs))))

How to make promises work in IE11

If you want this type of code to run in IE11 (which does not support much of ES6 at all), then you need to get a 3rd party promise library (like Bluebird), include that library and change your coding to use ES5 coding structures (no arrow functions, no let, etc...) so you can live within the limits of what older browsers support.

Or, you can use a transpiler (like Babel) to convert your ES6 code to ES5 code that will work in older browsers.

Here's a version of your code written in ES5 syntax with the Bluebird promise library:

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

<script>

'use strict';

var promise = new Promise(function(resolve) {
    setTimeout(function() {
        resolve("result");
    }, 1000);
});

promise.then(function(result) {
    alert("Fulfilled: " + result);
}, function(error) {
    alert("Rejected: " + error);
});

</script>

get current page from url

Path.GetFileName( Request.Url.AbsolutePath )

MySQL vs MySQLi when using PHP

If you have a look at MySQL Improved Extension Overview, it should tell you everything you need to know about the differences between the two.

The main useful features are:

  • an Object-oriented interface
  • support for prepared statements
  • support for multiple statements
  • support for transactions
  • enhanced debugging capabilities
  • embedded server support.

How to change font size in html?

If you're just interested in increasing the font size of just the first paragraph of any document, an effect used by online publications, then you can use the first-child pseudo-class to achieve the desired effect.

p:first-child
{
   font-size:   115%; // Will set the font size to be 115% of the original font-size for the p element.
}

However, this will change the font size of every p element that is the first-child of any other element. If you're interested in setting the size of the first p element of the body element, then use the following:

body > p:first-child
{
   font-size:   115%;
}

The above code will only work with the p element that is a child of the body element.

Pyspark: display a spark data frame in a table format

As mentioned by @Brent in the comment of @maxymoo's answer, you can try

df.limit(10).toPandas()

to get a prettier table in Jupyter. But this can take some time to run if you are not caching the spark dataframe. Also, .limit() will not keep the order of original spark dataframe.

How do I find which program is using port 80 in Windows?

Use this nifty freeware utility:

CurrPorts is network monitoring software that displays the list of all currently opened TCP/IP and UDP ports on your local computer.

Enter image description here

Iterate through dictionary values?

You can just look for the value that corresponds with the key and then check if the input is equal to the key.

for key in PIX0:
    NUM = input("Which standard has a resolution of %s " % PIX0[key])
    if NUM == key:

Also, you will have to change the last line to fit in, so it will print the key instead of the value if you get the wrong answer.

print("I'm sorry but thats wrong. The correct answer was: %s." % key )

Also, I would recommend using str.format for string formatting instead of the % syntax.

Your full code should look like this (after adding in string formatting)

PIX0 = {"QVGA":"320x240", "VGA":"640x480", "SVGA":"800x600"}

for key in PIX0:
    NUM = input("Which standard has a resolution of {}".format(PIX0[key]))
    if NUM == key:
        print ("Nice Job!")
        count = count + 1
    else:
        print("I'm sorry but that's wrong. The correct answer was: {}.".format(key))

What does `unsigned` in MySQL mean and when to use it?

MySQL says:

All integer types can have an optional (nonstandard) attribute UNSIGNED. Unsigned type can be used to permit only nonnegative numbers in a column or when you need a larger upper numeric range for the column. For example, if an INT column is UNSIGNED, the size of the column's range is the same but its endpoints shift from -2147483648 and 2147483647 up to 0 and 4294967295.

When do I use it ?

Ask yourself this question: Will this field ever contain a negative value?
If the answer is no, then you want an UNSIGNED data type.

A common mistake is to use a primary key that is an auto-increment INT starting at zero, yet the type is SIGNED, in that case you’ll never touch any of the negative numbers and you are reducing the range of possible id's to half.

MySQL Event Scheduler on a specific time everyday

The documentation on CREATE EVENT is quite good, but it takes a while to get it right.

You have two problems, first, making the event recur, second, making it run at 13:00 daily.

This example creates a recurring event.

CREATE EVENT e_hourly
    ON SCHEDULE
      EVERY 1 HOUR
    COMMENT 'Clears out sessions table each hour.'
    DO
      DELETE FROM site_activity.sessions;

When in the command-line MySQL client, you can:

SHOW EVENTS;

This lists each event with its metadata, like if it should run once only, or be recurring.

The second problem: pointing the recurring event to a specific schedule item.

By trying out different kinds of expression, we can come up with something like:

CREATE EVENT IF NOT EXISTS `session_cleaner_event`
ON SCHEDULE
  EVERY 13 DAY_HOUR
  COMMENT 'Clean up sessions at 13:00 daily!'
  DO
    DELETE FROM site_activity.sessions;

How do I find all the files that were created today in Unix/Linux?

This worked for me. Lists the files created on May 30 in the current directory.

ls -lt | grep 'May 30'

How to revert a merge commit that's already pushed to remote branch?

Here's a complete example in the hope that it helps someone:

git revert -m 1 <commit-hash> 
git push -u origin master

Where <commit-hash> is the commit hash of the merge that you would like to revert, and as stated in the explanation of this answer, -m 1 indicates that you'd like to revert to the tree of the first parent prior to the merge.

The git revert ... line essentially commits your changes while the second line makes your changes public by pushing them to the remote branch.

Python string to unicode

Decode it with the unicode-escape codec:

>>> a="Hello\u2026"
>>> a.decode('unicode-escape')
u'Hello\u2026'
>>> print _
Hello…

This is because for a non-unicode string the \u2026 is not recognised but is instead treated as a literal series of characters (to put it more clearly, 'Hello\\u2026'). You need to decode the escapes, and the unicode-escape codec can do that for you.

Note that you can get unicode to recognise it in the same way by specifying the codec argument:

>>> unicode(a, 'unicode-escape')
u'Hello\u2026'

But the a.decode() way is nicer.

How to insert a value that contains an apostrophe (single quote)?

Because a single quote is used for indicating the start and end of a string; you need to escape it.

The short answer is to use two single quotes - '' - in order for an SQL database to store the value as '.

Look at using REPLACE to sanitize incoming values:

You want to check for '''', and replace them if they exist in the string with '''''' in order to escape the lone single quote.

Why is Python running my module when I import it, and how do I stop it?

You may write your "main.py" like this:

#!/usr/bin/env python

__all__=["somevar", "do_something"]

somevar=""

def do_something():
    pass #blahblah

if __name__=="__main__":
    do_something()

How to do a less than or equal to filter in Django queryset?

Less than or equal:

User.objects.filter(userprofile__level__lte=0)

Greater than or equal:

User.objects.filter(userprofile__level__gte=0)

Likewise, lt for less than and gt for greater than. You can find them all in the documentation.

A server is already running. Check …/tmp/pids/server.pid. Exiting - rails

Run this command -

_x000D_
_x000D_
lsof -wni tcp:3000
_x000D_
_x000D_
_x000D_

then you will get the following table -

_x000D_
_x000D_
COMMAND  PID  USER   FD   TYPE DEVICE SIZE/OFF NODE NAME
ruby    2552 shyam   17u  IPv4  44599      0t0  TCP 127.0.0.1:3000 (LISTEN)
ruby    2552 shyam   18u  IPv6  44600      0t0  TCP [::1]:3000 (LISTEN)
_x000D_
_x000D_
_x000D_

Run this command and replace PID from the Above table

_x000D_
_x000D_
kill -9 PID
_x000D_
_x000D_
_x000D_

example:

_x000D_
_x000D_
kill -9 2552
_x000D_
_x000D_
_x000D_

Setting device orientation in Swift iOS

// Swift 2

override func supportedInterfaceOrientations() -> UIInterfaceOrientationMask {
    let orientation: UIInterfaceOrientationMask =
    [UIInterfaceOrientationMask.Portrait, UIInterfaceOrientationMask.PortraitUpsideDown]
    return orientation
}

docker cannot start on windows

I got the same error for Docker version 19.03.12 and Windows 10. Resolved it by going through the below steps. Hope it helps others.

  1. Go to Windows Start -> Search Box (Type here to search). There enter 'Services'. Among the listed items, click Services app.
  2. Now search 'Docker Desktop Service' in the Services window opened. Right click on it and Start the service. Its status should be changed to 'Running'.
  3. If step 2 gives error like 'the dependency service failed to start', then start all dependency services. For me, I had to start a service called 'Server'.
  4. Double click 'Docker Desktop' icon in desktop. Now you will see 'Docker Desktop is running' in system tray.
  5. Now run the command 'docker version' from Command Prompt or PowerShell. It should give clean output.
  6. If any issue in step 5, run Command Prompt or PowerShell as administrator.

Above resolution assumes Docker is already installed and Hyper-V / Virtualization is enabled in your system.

How can I selectively escape percent (%) in Python strings?

If the formatting template was read from a file, and you cannot ensure the content doubles the percent sign, then you probably have to detect the percent character and decide programmatically whether it is the start of a placeholder or not. Then the parser should also recognize sequences like %d (and other letters that can be used), but also %(xxx)s etc.

Similar problem can be observed with the new formats -- the text can contain curly braces.

How to set image width to be 100% and height to be auto in react native?

use aspectRatio property in style

Aspect ratio control the size of the undefined dimension of a node. Aspect ratio is a non-standard property only available in react native and not CSS.

  • On a node with a set width/height aspect ratio control the size of the unset dimension
  • On a node with a set flex basis aspect ratio controls the size of the node in the cross axis if unset
  • On a node with a measure function aspect ratio works as though the measure function measures the flex basis
  • On a node with flex grow/shrink aspect ratio controls the size of the node in the cross axis if unset
  • Aspect ratio takes min/max dimensions into account

docs: https://reactnative.dev/docs/layout-props#aspectratio

try like this:

import {Image, Dimensions} from 'react-native';

var width = Dimensions.get('window').width; 

<Image
    source={{
        uri: '<IMAGE_URI>'
    }}
    style={{
        width: width * .2,  //its same to '20%' of device width
        aspectRatio: 1, // <-- this
        resizeMode: 'contain', //optional
    }}
/>

How to change the remote repository for a git submodule?

git config --file=.gitmodules -e opens the default editor in which you can update the path

How to use sudo inside a docker container?

When neither sudo nor apt-get is available in container, you can also jump into running container as root user using command

docker exec -u root -t -i container_id /bin/bash

Javascript/jQuery detect if input is focused

Using jQuery's .is( ":focus" )

$(".status").on("click","textarea",function(){
        if ($(this).is( ":focus" )) {
            // fire this step
        }else{
                    $(this).focus();
            // fire this step
    }

javascript window.location in new tab

I don't think there's a way to do this, unless you're writing a browser extension. You could try using window.open and hoping that the user has their browser set to open new windows in new tabs.

How can I call the 'base implementation' of an overridden virtual method?

You can do it, but not at the point you've specified. Within the context of B, you may invoke A.X() by calling base.X().

java.util.Date format conversion yyyy-mm-dd to mm-dd-yyyy

'M' (Capital) represent month & 'm' (Simple) represent minutes

Some example for months

'M' -> 7  (without prefix 0 if it is single digit)
'M' -> 12

'MM' -> 07 (with prefix 0 if it is single digit)
'MM' -> 12

'MMM' -> Jul (display with 3 character)

'MMMM' -> December (display with full name)

Some example for minutes

'm' -> 3  (without prefix 0 if it is single digit)
'm' -> 19
'mm' -> 03 (with prefix 0 if it is single digit)
'mm' -> 19

Filter Java Stream to 1 and only 1 element

Update

Nice suggestion in comment from @Holger:

Optional<User> match = users.stream()
              .filter((user) -> user.getId() > 1)
              .reduce((u, v) -> { throw new IllegalStateException("More than one ID found") });

Original answer

The exception is thrown by Optional#get, but if you have more than one element that won't help. You could collect the users in a collection that only accepts one item, for example:

User match = users.stream().filter((user) -> user.getId() > 1)
                  .collect(toCollection(() -> new ArrayBlockingQueue<User>(1)))
                  .poll();

which throws a java.lang.IllegalStateException: Queue full, but that feels too hacky.

Or you could use a reduction combined with an optional:

User match = Optional.ofNullable(users.stream().filter((user) -> user.getId() > 1)
                .reduce(null, (u, v) -> {
                    if (u != null && v != null)
                        throw new IllegalStateException("More than one ID found");
                    else return u == null ? v : u;
                })).get();

The reduction essentially returns:

  • null if no user is found
  • the user if only one is found
  • throws an exception if more than one is found

The result is then wrapped in an optional.

But the simplest solution would probably be to just collect to a collection, check that its size is 1 and get the only element.

Spring Boot Rest Controller how to return different HTTP status codes?

A nice way is to use Spring's ResponseStatusException

Rather than returning a ResponseEntityor similar you simply throw the ResponseStatusException from the controller with an HttpStatus and cause, for example:

throw new ResponseStatusException(HttpStatus.BAD_REQUEST, "Cause description here");

or:

throw new ResponseStatusException(HttpStatus.INTERNAL_SERVER_ERROR, "Cause description here");

This results in a response to the client containing the HTTP status (e.g. 400 Bad request) with a body like:

{
  "timestamp": "2020-07-09T04:43:04.695+0000",
  "status": 400,
  "error": "Bad Request",
  "message": "Cause description here",
  "path": "/test-api/v1/search"
}

Select All as default value for Multivalue parameter

It works better

CREATE TABLE [dbo].[T_Status](
   [Status] [nvarchar](20) NULL
) ON [PRIMARY]

GO
INSERT [dbo].[T_Status] ([Status]) VALUES (N'Active')
GO
INSERT [dbo].[T_Status] ([Status]) VALUES (N'notActive')
GO
INSERT [dbo].[T_Status] ([Status]) VALUES (N'Active')
GO

DECLARE @GetStatus nvarchar(20) = null
--DECLARE @GetStatus nvarchar(20) = 'Active'
SELECT [Status]
FROM [T_Status]
WHERE  [Status] = CASE WHEN (isnull(@GetStatus, '')='') THEN [Status]
ELSE @GetStatus END

Convert javascript object or array to json for ajax data

You can use JSON.stringify(object) with an object and I just wrote a function that'll recursively convert an array to an object, like this JSON.stringify(convArrToObj(array)), which is the following code (more detail can be found on this answer):

// Convert array to object
var convArrToObj = function(array){
    var thisEleObj = new Object();
    if(typeof array == "object"){
        for(var i in array){
            var thisEle = convArrToObj(array[i]);
            thisEleObj[i] = thisEle;
        }
    }else {
        thisEleObj = array;
    }
    return thisEleObj;
}

To make it more generic, you can override the JSON.stringify function and you won't have to worry about it again, to do this, just paste this at the top of your page:

// Modify JSON.stringify to allow recursive and single-level arrays
(function(){
    // Convert array to object
    var convArrToObj = function(array){
        var thisEleObj = new Object();
        if(typeof array == "object"){
            for(var i in array){
                var thisEle = convArrToObj(array[i]);
                thisEleObj[i] = thisEle;
            }
        }else {
            thisEleObj = array;
        }
        return thisEleObj;
    };
    var oldJSONStringify = JSON.stringify;
    JSON.stringify = function(input){
        return oldJSONStringify(convArrToObj(input));
    };
})();

And now JSON.stringify will accept arrays or objects! (link to jsFiddle with example)


Edit:

Here's another version that's a tad bit more efficient, although it may or may not be less reliable (not sure -- it depends on if JSON.stringify(array) always returns [], which I don't see much reason why it wouldn't, so this function should be better as it does a little less work when you use JSON.stringify with an object):

(function(){
    // Convert array to object
    var convArrToObj = function(array){
        var thisEleObj = new Object();
        if(typeof array == "object"){
            for(var i in array){
                var thisEle = convArrToObj(array[i]);
                thisEleObj[i] = thisEle;
            }
        }else {
            thisEleObj = array;
        }
        return thisEleObj;
    };
    var oldJSONStringify = JSON.stringify;
    JSON.stringify = function(input){
        if(oldJSONStringify(input) == '[]')
            return oldJSONStringify(convArrToObj(input));
        else
            return oldJSONStringify(input);
    };
})();

jsFiddle with example here

js Performance test here, via jsPerf

Making button go full-width?

I would have thought this would be the most bootstrap-esque way of doing things:

<button type='button' class='btn btn-success col-xs-12'> First buttton baby </button>

All I'm doing is adding the class col-xs-12 to the button.

IIS7: A process serving application pool 'YYYYY' suffered a fatal communication error with the Windows Process Activation Service

Make sure that each Application Pool in IIS, under Advanced Settings has Enable 32 bit Applications set to True

IIS screenshot

grid controls for ASP.NET MVC?

Try: http://mvcjqgridcontrol.codeplex.com/ It's basically a MVC-compliant jQuery Grid wrapper with full .Net support

Getting a list of all subdirectories in the current directory

Listing Out only directories

print("\nWe are listing out only the directories in current directory -")
directories_in_curdir = filter(os.path.isdir, os.listdir(os.curdir))
print(directories_in_curdir)

Listing Out only files in current directory

files = filter(os.path.isfile, os.listdir(os.curdir))
print("\nThe following are the list of all files in the current directory -")
print(files)

BigDecimal setScale and round

There is indeed a big difference, which you should keep in mind. setScale really set the scale of your number whereas round does round your number to the specified digits BUT it "starts from the leftmost digit of exact result" as mentioned within the jdk. So regarding your sample the results are the same, but try 0.0034 instead. Here's my note about that on my blog:

http://araklefeistel.blogspot.com/2011/06/javamathbigdecimal-difference-between.html

How to convert a char array to a string?

Another solution might look like this,

char arr[] = "mom";
std::cout << "hi " << std::string(arr);

which avoids using an extra variable.

Access properties file programmatically with Spring?

This post also explatis howto access properties: http://maciej-miklas.blogspot.de/2013/07/spring-31-programmatic-access-to.html

You can access properties loaded by spring property-placeholder over such spring bean:

@Named
public class PropertiesAccessor {

    private final AbstractBeanFactory beanFactory;

    private final Map<String,String> cache = new ConcurrentHashMap<>();

    @Inject
    protected PropertiesAccessor(AbstractBeanFactory beanFactory) {
        this.beanFactory = beanFactory;
    }

    public  String getProperty(String key) {
        if(cache.containsKey(key)){
            return cache.get(key);
        }

        String foundProp = null;
        try {
            foundProp = beanFactory.resolveEmbeddedValue("${" + key.trim() + "}");
            cache.put(key,foundProp);
        } catch (IllegalArgumentException ex) {
           // ok - property was not found
        }

        return foundProp;
    }
}

StringIO in Python3

In my case I have used:

from io import StringIO

How to view the dependency tree of a given npm module?

View All the metadata about npm module

npm view mongoose(module name)

View All Dependencies of module

npm view mongoose dependencies

View All Version or Versions module

npm view mongoose version
npm view mongoose versions

View All the keywords

npm view mongoose keywords

How to remove the first and the last character of a string

if you need to remove the first leter of string

string.slice(1, 0)

and for remove last letter

string.slice(0, -1)

This Row already belongs to another table error when trying to add rows?

This isn't the cleanest/quickest/easiest/most elegant solution, but it is a brute force one that I created to get the job done in a similar scenario:

DataTable dt = (DataTable)Session["dtAllOrders"];
DataTable dtSpecificOrders = new DataTable();

// Create new DataColumns for dtSpecificOrders that are the same as in "dt"
DataColumn dcID = new DataColumn("ID", typeof(int));
DataColumn dcName = new DataColumn("Name", typeof(string));
dtSpecificOrders.Columns.Add(dtID);
dtSpecificOrders.Columns.Add(dcName);

DataRow[] orderRows = dt.Select("CustomerID = 2");

foreach (DataRow dr in orderRows)
{
    DataRow myRow = dtSpecificOrders.NewRow();  // <-- create a brand-new row
    myRow[dcID] = int.Parse(dr["ID"]);
    myRow[dcName] = dr["Name"].ToString();
    dtSpecificOrders.Rows.Add(myRow);   // <-- this will add the new row
}

The names in the DataColumns must match those in your original table for it to work. I just used "ID" and "Name" as examples.

MVC3 DropDownListFor - a simple example?

For binding Dynamic Data in a DropDownList you can do the following:

Create ViewBag in Controller like below

ViewBag.ContribTypeOptions = yourFunctionValue();

now use this value in view like below:

@Html.DropDownListFor(m => m.ContribType, 
    new SelectList(@ViewBag.ContribTypeOptions, "ContribId", 
                   "Value", Model.ContribTypeOptions.First().ContribId), 
    "Select, please")

Concat a string to SELECT * MySql

You simply can't do that in SQL. You have to explicitly list the fields and concat each one:

SELECT CONCAT(field1, '/'), CONCAT(field2, '/'), ... FROM `socials` WHERE 1

If you are using an app, you can use SQL to read the column names, and then use your app to construct a query like above. See this stackoverflow question to find the column names: Get table column names in mysql?

Gson: Directly convert String to JsonObject (no POJO)

Try to use getAsJsonObject() instead of a straight cast used in the accepted answer:

JsonObject o = new JsonParser().parse("{\"a\": \"A\"}").getAsJsonObject();

Export specific rows from a PostgreSQL table as INSERT SQL script

For my use-case I was able to simply pipe to grep.

pg_dump -U user_name --data-only --column-inserts -t nyummy.cimory | grep "tokyo" > tokyo.sql

Binding a list in @RequestParam

Or you could just do it that way:

public String controllerMethod(@RequestParam(value="myParam[]") String[] myParams){
    ....
}

That works for example for forms like this:

<input type="checkbox" name="myParam[]" value="myVal1" />
<input type="checkbox" name="myParam[]" value="myVal2" />

This is the simplest solution :)