Programs & Examples On #Selectors api

The Selectors API provides methods that make it quick and easy to retrieve Element nodes from the DOM by matching against a set of selectors.

Why does JS code "var a = document.querySelector('a[data-a=1]');" cause error?

Yes strings must be quoted and in some cases like in applescript, quotes must be escaped

do JavaScript "document.querySelector('span[" & attrName & "=\"" & attrValue & "\"]').click();"

How to use querySelectorAll only for elements that have a specific attribute set?

With your example:

<input type="checkbox" id="c2" name="c2" value="DE039230952"/>

Replace $$ with document.querySelectorAll in the examples:

$$('input') //Every input
$$('[id]') //Every element with id
$$('[id="c2"]') //Every element with id="c2"
$$('input,[id]') //Every input + every element with id
$$('input[id]') //Every input including id
$$('input[id="c2"]') //Every input including id="c2"
$$('input#c2') //Every input including id="c2" (same as above)
$$('input#c2[value="DE039230952"]') //Every input including id="c2" and value="DE039230952"
$$('input#c2[value^="DE039"]') //Every input including id="c2" and value has content starting with DE039
$$('input#c2[value$="0952"]') //Every input including id="c2" and value has content ending with 0952
$$('input#c2[value*="39230"]') //Every input including id="c2" and value has content including 39230

Use the examples directly with:

const $$ = document.querySelectorAll.bind(document);

Some additions:

$$(.) //The same as $([class])
$$(div > input) //div is parent tag to input
document.querySelector() //equals to $$()[0] or $()

Javascript .querySelector find <div> by innerTEXT

Since you have asked it in javascript so you can have something like this

function contains(selector, text) {
  var elements = document.querySelectorAll(selector);
  return Array.prototype.filter.call(elements, function(element){
    return RegExp(text).test(element.textContent);
  });
}

And then call it like this

contains('div', 'sometext'); // find "div" that contain "sometext"
contains('div', /^sometext/); // find "div" that start with "sometext"
contains('div', /sometext$/i); // find "div" that end with "sometext", case-insensitive

querySelector, wildcard element match?

Set the tagName as an explicit attribute:

for(var i=0,els=document.querySelectorAll('*'); i<els.length;
          els[i].setAttribute('tagName',els[i++].tagName) );

I needed this myself, for an XML Document, with Nested Tags ending in _Sequence. See JaredMcAteer answer for more details.

document.querySelectorAll('[tagName$="_Sequence"]')

I didn't say it would be pretty :) PS: I would recommend to use tag_name over tagName, so you do not run into interferences when reading 'computer generated', implicit DOM attributes.

Linq to Sql: Multiple left outer joins

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

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

Disable cross domain web security in Firefox

Best Firefox Addon to disable CORS as of September 2016: https://github.com/fredericlb/Force-CORS/releases

You can even configure it by Referrers (Website).

#1214 - The used table type doesn't support FULLTEXT indexes

Only MyISAM allows for FULLTEXT, as seen here.

Try this:

CREATE TABLE gamemech_chat (
  id bigint(20) unsigned NOT NULL auto_increment,
  from_userid varchar(50) NOT NULL default '0',
  to_userid varchar(50) NOT NULL default '0',
  text text NOT NULL,
  systemtext text NOT NULL,
  timestamp datetime NOT NULL default '0000-00-00 00:00:00',
  chatroom bigint(20) NOT NULL default '0',
  PRIMARY KEY  (id),
  KEY from_userid (from_userid),
  FULLTEXT KEY from_userid_2 (from_userid),
  KEY chatroom (chatroom),
  KEY timestamp (timestamp)
) ENGINE=MyISAM;

Using jQuery to build table rows from AJAX response(json)

You could do it something like this:

<!-- Latest compiled and minified CSS -->
<link rel="stylesheet" href="https://maxcdn.bootstrapcdn.com/bootstrap/3.3.7/css/bootstrap.min.css">

<!-- jQuery library -->
<script src="https://ajax.googleapis.com/ajax/libs/jquery/3.2.1/jquery.min.js"></script>

<!-- Latest compiled JavaScript -->
<script src="https://maxcdn.bootstrapcdn.com/bootstrap/3.3.7/js/bootstrap.min.js"></script>


    <script>
    $(function(){

    $.ajax({
    url: '<Insert your REST API which you want GET/POST/PUT/DELETE>',
    data: '<any parameters you want to send as the Request body or query string>',
    dataType: json,
    async: true,
    method: "GET"
    success: function(data){

    //If the REST API returned a successful response it'll be stored in data, 
    //just parse that field using jQuery and you're all set

    var tblSomething = '<thead> <tr> <td> Heading Col 1 </td> <td> Heading Col 2 </td> <td> Col 3 </td> </tr> </thead> <tbody>';

    $.each(data, function(idx, obj){

    //Outer .each loop is for traversing the JSON rows
    tblSomething += '<tr>';

    //Inner .each loop is for traversing JSON columns
    $.each(obj, function(key, value){
    tblSomething += '<td>' + value + '</td>';
    });
    tblSomething += '</tr>';
    });

    tblSomething += '</tbody>';

    $('#tblSomething').html(tblSomething);
    },
    error: function(jqXHR, textStatus, errorThrown){
    alert('Hey, something went wrong because: ' + errorThrown);
    }
    });


    });
    </script>


    <table id = "tblSomething" class = "table table-hover"></table>

rejected master -> master (non-fast-forward)

My Remote was not in sync with the local so this worked for me

git pull --rebase

and make sure when you do git pull again it should say Already up to date and now you are ready to push to origin

assuming you have already git remote add origin remote repository URL

do

`git push origin master`  

The Screenshot says it all enter image description here

Alternatively you can do this

  1. git stash (stores uncommited work temporarily)
  2. git pull (make your local and remote in sync)
  3. git stash pop (get back you uncommited changes )
  4. git push

Convert a object into JSON in REST service by Spring MVC


The Json conversion should work out-of-the box. In order this to happen you need add some simple configurations:
First add a contentNegotiationManager into your spring config file. It is responsible for negotiating the response type:

<bean id="contentNegotiationManager"
      class="org.springframework.web.accept.ContentNegotiationManagerFactoryBean">
    <property name="favorPathExtension" value="false" />
    <property name="favorParameter" value="true" />
    <property name="ignoreAcceptHeader" value="true" />
    <property name="useJaf" value="false" />
     <property name="defaultContentType" value="application/json" />

      <property name="mediaTypes">
         <map>
            <entry key="json" value="application/json" />
            <entry key="xml" value="application/xml" />
         </map>
      </property>
   </bean>

   <mvc:annotation-driven
      content-negotiation-manager="contentNegotiationManager" />

   <context:annotation-config />

Then add Jackson2 jars (jackson-databind and jackson-core) in the service's class path. Jackson is responsible for the data serialization to JSON. Spring will detect these and initialize the MappingJackson2HttpMessageConverter automatically for you. Having only this configured I have my automatic conversion to JSON working. The described config has an additional benefit of giving you the possibility to serialize to XML if you set accept:application/xml header.

Running a script inside a docker container using shell script

You could also mount a local directory into your docker image and source the script in your .bashrc. Don't forget the script has to consist of functions unless you want it to execute on every new shell. (This is outdated see the update notice.)

I'm using this solution to be able to update the script outside of the docker instance. This way I don't have to rerun the image if changes occur, I just open a new shell. (Got rid of reopening a shell - see the update notice)

Here is how you bind your current directory:

docker run -it -v $PWD:/scripts $my_docker_build /bin/bash

Now your current directory is bound to /scripts of your docker instance.

(Outdated) To save your .bashrc changes commit your working image with this command:

docker commit $container_id $my_docker_build

Update

To solve the issue to open up a new shell for every change I now do the following:

In the dockerfile itself I add RUN echo "/scripts/bashrc" > /root/.bashrc". Inside zshrc I export the scripts directory to the path. The scripts directory now contains multiple files instead of one. Now I can directly call all scripts without having open a sub shell on every change.

BTW you can define the history file outside of your container too. This way it's not necessary to commit on a bash change anymore.

How many socket connections can a web server handle?

It looks like the answer is at least 12 million if you have a beefy server, your server software is optimized for it, you have enough clients. If you test from one client to one server, the number of port numbers on the client will be one of the obvious resource limits (Each TCP connection is defined by the unique combination of IP and port number at the source and destination).

(You need to run multiple clients as otherwise you hit the 64K limit on port numbers first)

When it comes down to it, this is a classic example of the witticism that "the difference between theory and practise is much larger in practise than in theory" - in practise achieving the higher numbers seems to be a cycle of a. propose specific configuration/architecture/code changes, b. test it till you hit a limit, c. Have I finished? If not then d. work out what was the limiting factor, e. go back to step a (rinse and repeat).

Here is an example with 2 million TCP connections onto a beefy box (128GB RAM and 40 cores) running Phoenix http://www.phoenixframework.org/blog/the-road-to-2-million-websocket-connections - they ended up needing 50 or so reasonably significant servers just to provide the client load (their initial smaller clients maxed out to early, eg "maxed our 4core/15gb box @ 450k clients").

Here is another reference for go this time at 10 million: http://goroutines.com/10m.

This appears to be java based and 12 million connections: https://mrotaru.wordpress.com/2013/06/20/12-million-concurrent-connections-with-migratorydata-websocket-server/

Run cmd commands through Java

Once you get the reference to Process, you can call getOutpuStream on it to get the standard input of the cmd prompt. Then you can send any command over the stream using write method as with any other stream.

Note that it is process.getOutputStream() which is connected to the stdin on the spawned process. Similarly, to get the output of any command, you will need to call getInputStream and then read over this as any other input stream.

How to create a GUID / UUID

Here you can find a very small function that generates uuids https://gist.github.com/jed/982883

One of the final versions is:

function b(
  a                  // placeholder
){
  var cryptoObj = window.crypto || window.msCrypto; // for IE 11
  return a           // if the placeholder was passed, return
    ? (              // a random number from 0 to 15
      a ^            // unless b is 8,
      cryptoObj.getRandomValues(new Uint8Array(1))[0]  // in which case
      % 16           // a random number from
      >> a/4         // 8 to 11
      ).toString(16) // in hexadecimal
    : (              // or otherwise a concatenated string:
      [1e7] +        // 10000000 +
      -1e3 +         // -1000 +
      -4e3 +         // -4000 +
      -8e3 +         // -80000000 +
      -1e11          // -100000000000,
      ).replace(     // replacing
        /[018]/g,    // zeroes, ones, and eights with
        b            // random hex digits
      )
}

Exception in thread "main" java.util.NoSuchElementException

You close the second Scanner which closes the underlying InputStream, therefore the first Scanner can no longer read from the same InputStream and a NoSuchElementException results.

The solution: For console apps, use a single Scanner to read from System.in.

Aside: As stated already, be aware that Scanner#nextInt does not consume newline characters. Ensure that these are consumed before attempting to call nextLine again by using Scanner#newLine().

See: Do not create multiple buffered wrappers on a single InputStream

QR Code encoding and decoding using zxing

I tried using ISO-8859-1 as said in the first answer. All went ok on encoding, but when I tried to get the byte[] using result string on decoding, all negative bytes became the character 63 (question mark). The following code does not work:

// Encoding works great
byte[] contents = new byte[]{-1};
QRCodeWriter codeWriter = new QRCodeWriter();
BitMatrix bitMatrix = codeWriter.encode(new String(contents, Charset.forName("ISO-8859-1")), BarcodeFormat.QR_CODE, w, h);

// Decodes like this fails
LuminanceSource ls = new BufferedImageLuminanceSource(encodedBufferedImage);
Result result = new QRCodeReader().decode(new BinaryBitmap( new HybridBinarizer(ls)));
byte[] resultBytes = result.getText().getBytes(Charset.forName("ISO-8859-1")); // a byte[] with byte 63 is given
return resultBytes;

It looks so strange because the API in a very old version (don't know exactly) had a method thar works well:

Vector byteSegments = result.getByteSegments();

So I tried to search why this method was removed and realized that there is a way to get ByteSegments, through metadata. So my decode method looks like:

// Decodes like this works perfectly
LuminanceSource ls = new BufferedImageLuminanceSource(encodedBufferedImage);
Result result = new QRCodeReader().decode(new BinaryBitmap( new HybridBinarizer(ls)));
Vector byteSegments = (Vector) result.getResultMetadata().get(ResultMetadataType.BYTE_SEGMENTS);  
int i = 0;
int tam = 0;
for (Object o : byteSegments) {
    byte[] bs = (byte[])o;
    tam += bs.length;
}
byte[] resultBytes = new byte[tam];
i = 0;
for (Object o : byteSegments) {
    byte[] bs = (byte[])o;
    for (byte b : bs) {
        resultBytes[i++] = b;
    }
}
return resultBytes;

Error sending json in POST to web API service

Please check if you are were passing method as POST instead as GET. if so you will get same error as a you posted above.

$http({               
 method: 'GET',

The request entity's media type 'text/plain' is not supported for this resource.

window.onload vs document.onload

In Chrome, window.onload is different from <body onload="">, whereas they are the same in both Firefox(version 35.0) and IE (version 11).

You could explore that by the following snippet:

<!DOCTYPE html>
<html xmlns="http://www.w3.org/1999/xhtml">
    <head>
        <meta http-equiv="Content-Type" content="text/html; charset=utf-8" />
        <!--import css here-->
        <!--import js scripts here-->

        <script language="javascript">

            function bodyOnloadHandler() {
                console.log("body onload");
            }

            window.onload = function(e) {
                console.log("window loaded");
            };
        </script>
    </head>

    <body onload="bodyOnloadHandler()">

        Page contents go here.

    </body>
</html>

And you will see both "window loaded"(which comes firstly) and "body onload" in Chrome console. However, you will see just "body onload" in Firefox and IE. If you run "window.onload.toString()" in the consoles of IE & FF, you will see:

"function onload(event) { bodyOnloadHandler() }"

which means that the assignment "window.onload = function(e)..." is overwritten.

Query error with ambiguous column name in SQL

if you join 2 or more tables and they have similar names for their columns sql server wants you to qualify columns which they belong.

SELECT  ev.[ID]
    ,[Description]
    FROM   [Events] as ev 
    LEFT JOIN  [Units] as un ON ev.UnitID = un.UnitId  

if Events and Units tables has same column name (ID) SQL server wants you to use aliases.

How do I compare if a string is not equal to?

Either != or ne will work, but you need to get the accessor syntax and nested quotes sorted out.

<c:if test="${content.contentType.name ne 'MCE'}">
    <%-- snip --%>
</c:if>

Center a button in a Linear layout

You also can Try this Code:

<LinearLayout
            android:id="@+id/linear_layout"
            android:layout_width="fill_parent"
            android:layout_height="0dp"
            android:layout_gravity="center"
            android:orientation="horizontal"
            android:weightSum="2.0"
            android:background="@drawable/anyBackground" >

        <LinearLayout
            android:layout_width="match_parent"
            android:layout_height="wrap_content"
            android:layout_gravity="center"
            android:orientation="vertical"
            android:layout_weight="1" >

            <ImageView
                android:id="@+id/img_mail"
                android:layout_width="wrap_content"
                android:layout_height="wrap_content"
                android:layout_gravity="center"
                android:background="@drawable/yourImage" />
        </LinearLayout>

        <LinearLayout
            android:layout_width="match_parent"
            android:layout_height="wrap_content"
            android:layout_gravity="center"
            android:orientation="vertical"
            android:layout_weight="1" >



<ImageView
            android:id="@+id/img_save"
            android:layout_width="wrap_content"
            android:layout_height="match_parent"
            android:layout_gravity="center"
            android:background="@drawable/yourImage" />
        </LinearLayout>
        </LinearLayout>

Get GPS location via a service in Android

Here is my solution

Step1 Register Serice in manifest

<receiver
    android:name=".MySMSBroadcastReceiver"
    android:exported="true">
    <intent-filter>
        <action android:name="com.google.android.gms.auth.api.phone.SMS_RETRIEVED" />
    </intent-filter>
</receiver>

Step2 Code Of Service

public class FusedLocationService extends Service {

    private String mLastUpdateTime = null;

    // bunch of location related apis
    private FusedLocationProviderClient mFusedLocationClient;
    private SettingsClient mSettingsClient;
    private LocationRequest mLocationRequest;
    private LocationSettingsRequest mLocationSettingsRequest;
    private LocationCallback mLocationCallback;
    private Location lastLocation;

    // location updates interval - 10sec
    private static final long UPDATE_INTERVAL_IN_MILLISECONDS = 5000;

    // fastest updates interval - 5 sec
    // location updates will be received if another app is requesting the locations
    // than your app can handle
    private static final long FASTEST_UPDATE_INTERVAL_IN_MILLISECONDS = 500;
    private DatabaseReference locationRef;
    private int notificationBuilder = 0;
    private boolean isInitRef;

    @Override
    public int onStartCommand(Intent intent, int flags, int startId) {
        Log.log("LOCATION GET DURATION", "start in service");
        init();
        return START_STICKY;
    }

    /**
     * Initilize Location Apis
     * Create Builder if Share location true
     */
    private void init() {
        mFusedLocationClient = LocationServices.getFusedLocationProviderClient(this);
        mSettingsClient = LocationServices.getSettingsClient(this);
        mLocationCallback = new LocationCallback() {
            @Override
            public void onLocationResult(LocationResult locationResult) {
                super.onLocationResult(locationResult);
                receiveLocation(locationResult);
            }
        };

        mLocationRequest = new LocationRequest();
        mLocationRequest.setInterval(UPDATE_INTERVAL_IN_MILLISECONDS);
        mLocationRequest.setFastestInterval(FASTEST_UPDATE_INTERVAL_IN_MILLISECONDS);
        mLocationRequest.setPriority(LocationRequest.PRIORITY_HIGH_ACCURACY);

        LocationSettingsRequest.Builder builder = new LocationSettingsRequest.Builder();
        builder.addLocationRequest(mLocationRequest);
        mLocationSettingsRequest = builder.build();
        startLocationUpdates();
    }

    /**
     * Request Location Update
     */
    @SuppressLint("MissingPermission")
    private void startLocationUpdates() {
        mSettingsClient
                .checkLocationSettings(mLocationSettingsRequest)
                .addOnSuccessListener(locationSettingsResponse -> {
                    Log.log(TAG, "All location settings are satisfied. No MissingPermission");

                    //noinspection MissingPermission
                    mFusedLocationClient.requestLocationUpdates(mLocationRequest, mLocationCallback, Looper.myLooper());
                })
                .addOnFailureListener(e -> {
                    int statusCode = ((ApiException) e).getStatusCode();
                    switch (statusCode) {
                        case LocationSettingsStatusCodes.RESOLUTION_REQUIRED:
                            Log.loge("Location settings are not satisfied. Attempting to upgrade " + "location settings ");
                            break;
                        case LocationSettingsStatusCodes.SETTINGS_CHANGE_UNAVAILABLE:
                            Log.loge("Location settings are inadequate, and cannot be " + "fixed here. Fix in Settings.");
                    }
                });
    }

    /**
     * onLocationResult
     * on Receive Location  share to other activity and save if save true
     *
     * @param locationResult
     */
    private void receiveLocation(LocationResult locationResult) {
        lastLocation = locationResult.getLastLocation();

        LocationInstance.getInstance().changeState(lastLocation);

        saveLocation();
    }

    private void saveLocation() {
        String saveLocation = getsaveLocationStatus(this);

        if (saveLocation.equalsIgnoreCase("true") && notificationBuilder == 0) {
            notificationBuilder();
            notificationBuilder = 1;
        } else if (saveLocation.equalsIgnoreCase("false") && notificationBuilder == 1) {
            ((NotificationManager) getSystemService(Context.NOTIFICATION_SERVICE)).cancel(1);
            notificationBuilder = 0;
        }

        Log.logd("receiveLocation : Share :- " + saveLocation + ", [Lat " + lastLocation.getLatitude() + ", Lng" + lastLocation.getLongitude() + "], Time :- " + mLastUpdateTime);

        if (saveLocation.equalsIgnoreCase("true") || getPreviousMin() < getCurrentMin()) {
            setLatLng(this, lastLocation);

            mLastUpdateTime = DateFormat.getTimeInstance().format(new Date());

            if (isOnline(this) && !getUserId(this).equalsIgnoreCase("")) {
                if (!isInitRef) {
                    locationRef = getFirebaseInstance().child(getUserId(this)).child("location");
                    isInitRef = true;
                }
                if (isInitRef) {
                    locationRef.setValue(new LocationModel(lastLocation.getLatitude(), lastLocation.getLongitude(), mLastUpdateTime));
                }
            }
        }
    }

    private int getPreviousMin() {
        int previous_min = 0;
        if (mLastUpdateTime != null) {
            String[] pretime = mLastUpdateTime.split(":");
            previous_min = Integer.parseInt(pretime[1].trim()) + 1;

            if (previous_min > 59) {
                previous_min = 0;
            }
        }
        return previous_min;
    }

    @Override
    public void onDestroy() {
        super.onDestroy();
        stopLocationUpdates();
    }

    /**
     * Remove Location Update
     */
    public void stopLocationUpdates() {
        mFusedLocationClient
                .removeLocationUpdates(mLocationCallback)
                .addOnCompleteListener(task -> Log.logd("stopLocationUpdates : "));
    }

    private void notificationBuilder() {
        if (Build.VERSION.SDK_INT >= 26) {
            String CHANNEL_ID = "my_channel_01";
            NotificationChannel channel = new NotificationChannel(CHANNEL_ID, "Channel human readable title",
                    NotificationManager.IMPORTANCE_DEFAULT);

            ((NotificationManager) getSystemService(Context.NOTIFICATION_SERVICE)).createNotificationChannel(channel);

            Notification notification = new NotificationCompat.Builder(this, CHANNEL_ID)
                    .setContentTitle("")
                    .setContentText("").build();

            startForeground(1, notification);
        }
    }

    @Override
    public IBinder onBind(Intent intent) {
        return null;
    }
}

Step 3

<uses-permission android:name="android.permission.ACCESS_COARSE_LOCATION" />
<uses-permission android:name="android.permission.ACCESS_FINE_LOCATION" />
<uses-permission android:name="android.permission.FOREGROUND_SERVICE" />

Step 4

implementation 'com.google.android.gms:play-services-location:16.0.0'

Static variables in C++

Static variable in a header file:

say 'common.h' has

static int zzz;

This variable 'zzz' has internal linkage (This same variable can not be accessed in other translation units). Each translation unit which includes 'common.h' has it's own unique object of name 'zzz'.

Static variable in a class:

Static variable in a class is not a part of the subobject of the class. There is only one copy of a static data member shared by all the objects of the class.

$9.4.2/6 - "Static data members of a class in namespace scope have external linkage (3.5).A local class shall not have static data members."

So let's say 'myclass.h' has

struct myclass{
   static int zzz;        // this is only a declaration
};

and myclass.cpp has

#include "myclass.h"

int myclass::zzz = 0           // this is a definition, 
                               // should be done once and only once

and "hisclass.cpp" has

#include "myclass.h"

void f(){myclass::zzz = 2;}    // myclass::zzz is always the same in any 
                               // translation unit

and "ourclass.cpp" has

#include "myclass.h"
void g(){myclass::zzz = 2;}    // myclass::zzz is always the same in any 
                               // translation unit

So, class static members are not limited to only 2 translation units. They need to be defined only once in any one of the translation units.

Note: usage of 'static' to declare file scope variable is deprecated and unnamed namespace is a superior alternate

How to create a WPF Window without a border that can be resized via a grip only?

While the accepted answer is very true, just want to point out that AllowTransparency has some downfalls. It does not allow child window controls to show up, ie WebBrowser, and it usually forces software rendering which can have negative performance effects.

There is a better work around though.

When you want to create a window with no border that is resizeable and is able to host a WebBrowser control or a Frame control pointed to a URL you simply couldn't, the contents of said control would show empty.

I found a workaround though; in the Window, if you set the WindowStyle to None, ResizeMode to NoResize (bear with me, you will still be able to resize once done) then make sure you have UNCHECKED AllowsTransparency you will have a static sized window with no border and will show the browser control.

Now, you probably still want to be able to resize right? Well we can to that with a interop call:

    [DllImport("user32.dll", CharSet = CharSet.Auto)]
    private static extern IntPtr SendMessage(IntPtr hWnd, uint Msg, IntPtr wParam, IntPtr lParam);

    [DllImportAttribute("user32.dll")]
    public static extern bool ReleaseCapture();

    //Attach this to the MouseDown event of your drag control to move the window in place of the title bar
    private void WindowDrag(object sender, MouseButtonEventArgs e) // MouseDown
    {
        ReleaseCapture();
        SendMessage(new WindowInteropHelper(this).Handle,
            0xA1, (IntPtr)0x2, (IntPtr)0);
    }

    //Attach this to the PreviewMousLeftButtonDown event of the grip control in the lower right corner of the form to resize the window
    private void WindowResize(object sender, MouseButtonEventArgs e) //PreviewMousLeftButtonDown
    {
        HwndSource hwndSource = PresentationSource.FromVisual((Visual)sender) as HwndSource;
        SendMessage(hwndSource.Handle, 0x112, (IntPtr)61448, IntPtr.Zero);
    }

And voila, A WPF window with no border and still movable and resizable without losing compatibility with with controls like WebBrowser

Does uninstalling a package with "pip" also remove the dependent packages?

I have found the solution even though it might be a little difficult for some to carry out.

1st step (for python3 and linux):
pip3 install pip-autoremove
2nd step:
cd /home/usernamegoeshere/.local/bin/
3rd step:
gedit /home/usernamegoeshere/.local/lib/python3.8/site-packages/pip_autoremove.py
and change all pip(s) to pip3 4th step: ./pip-autoremove packagenamegoeshere

At least, this was what worked for me ...

Source file not compiled Dev C++

This maybe because the c compiler is designed to work in linux.I had this problem too and to fix it go to tools and select compiler options.In the box click on programs

Now you will see a tab with gcc and make and the respective path to it.Edit the gcc and make path to use mingw32-c++.exe and mingw32-make.exe respectively.Now it will work.

The Answer

The reason was that you were using compilers built for linux.

Mysql service is missing

I also face the same problem. do the simple steps

  1. Go to bin directory copy the path and set it as a environment variable.
  2. Run the command prompt as admin and cd to bin directory:
  3. Run command : mysqld –install
  4. Now the services are successfully installed
  5. Start the service in service windows of os
  6. Type mysql and go

Output data from all columns in a dataframe in pandas

you can also use DataFrame.head(x) / .tail(x) to display the first / last x rows of the DataFrame.

Java generics - ArrayList initialization

The key lies in the differences between references and instances and what the reference can promise and what the instance can really do.

ArrayList<A> a = new ArrayList<A>();

Here a is a reference to an instance of a specific type - exactly an array list of As. More explicitly, a is a reference to an array list that will accept As and will produce As. new ArrayList<A>() is an instance of an array list of As, that is, an array list that will accept As and will produce As.

ArrayList<Integer> a = new ArrayList<Number>(); 

Here, a is a reference to exactly an array list of Integers, i.e. exactly an array list that can accept Integers and will produce Integers. It cannot point to an array list of Numbers. That array list of Numbers can not meet all the promises of ArrayList<Integer> a (i.e. an array list of Numbers may produce objects that are not Integers, even though its empty right then).

ArrayList<Number> a = new ArrayList<Integer>(); 

Here, declaration of a says that a will refer to exactly an array list of Numbers, that is, exactly an array list that will accept Numbers and will produce Numbers. It cannot point to an array list of Integers, because the type declaration of a says that a can accept any Number, but that array list of Integers cannot accept just any Number, it can only accept Integers.

ArrayList<? extends Object> a= new ArrayList<Object>();

Here a is a (generic) reference to a family of types rather than a reference to a specific type. It can point to any list that is member of that family. However, the trade-off for this nice flexible reference is that they cannot promise all of the functionality that it could if it were a type-specific reference (e.g. non-generic). In this case, a is a reference to an array list that will produce Objects. But, unlike a type-specific list reference, this a reference cannot accept any Object. (i.e. not every member of the family of types that a can point to can accept any Object, e.g. an array list of Integers can only accept Integers.)

ArrayList<? super Integer> a = new ArrayList<Number>();

Again, a is a reference to a family of types (rather than a single specific type). Since the wildcard uses super, this list reference can accept Integers, but it cannot produce Integers. Said another way, we know that any and every member of the family of types that a can point to can accept an Integer. However, not every member of that family can produce Integers.

PECS - Producer extends, Consumer super - This mnemonic helps you remember that using extends means the generic type can produce the specific type (but cannot accept it). Using super means the generic type can consume (accept) the specific type (but cannot produce it).

ArrayList<ArrayList<?>> a

An array list that holds references to any list that is a member of a family of array lists types.

= new ArrayList<ArrayList<?>>(); // correct

An instance of an array list that holds references to any list that is a member of a family of array lists types.

ArrayList<?> a

An reference to any array list (a member of the family of array list types).

= new ArrayList<?>()

ArrayList<?> refers to any type from a family of array list types, but you can only instantiate a specific type.


See also How can I add to List<? extends Number> data structures?

How do I get Fiddler to stop ignoring traffic to localhost?

make sure Monitor all connections is ticked. it does not work for me maybe port is diffren i need yo see httprequest to my site from gmail my site is on win xp and iis5(my own machine)

Get the current time in C

Easy way:

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

int main(void)
{
    time_t mytime = time(NULL);
    char * time_str = ctime(&mytime);
    time_str[strlen(time_str)-1] = '\0';
    printf("Current Time : %s\n", time_str);

    return 0;
}

Count how many files in directory PHP

Since I needed this too, I was curious as to which alternative was the fastest.

I found that -- if all you want is a file count -- Baba's solution is a lot faster than the others. I was quite surprised.

Try it out for yourself:

<?php
define('MYDIR', '...');

foreach (array(1, 2, 3) as $i)
{
    $t = microtime(true);
    $count = run($i);
    echo "$i: $count (".(microtime(true) - $t)." s)\n";
}

function run ($n)
{
    $func = "countFiles$n";
    $x = 0;
    for ($f = 0; $f < 5000; $f++)
        $x = $func();
    return $x;
}

function countFiles1 ()
{
    $dir = opendir(MYDIR);
    $c = 0;
    while (($file = readdir($dir)) !== false)
        if (!in_array($file, array('.', '..')))
            $c++;
    closedir($dir);
    return $c;
}

function countFiles2 ()
{
    chdir(MYDIR);
    return count(glob("*"));
}

function countFiles3 () // Fastest method
{
    $f = new FilesystemIterator(MYDIR, FilesystemIterator::SKIP_DOTS);
    return iterator_count($f);
}
?>

Test run: (obviously, glob() doesn't count dot-files)

1: 99 (0.4815571308136 s)
2: 98 (0.96104407310486 s)
3: 99 (0.26513481140137 s)

AttributeError: 'numpy.ndarray' object has no attribute 'append'

I got this error after change a loop in my program, let`s see:

for ...
  for ... 
     x_batch.append(one_hot(int_word, vocab_size))
     y_batch.append(one_hot(int_nb, vocab_size, value))
  ...
  ...
  if ...
        x_batch = np.asarray(x_batch)
        y_batch = np.asarray(y_batch)
...

In fact, I was reusing the variable and forgot to reset them inside the external loop, like the comment of John Lyon:

for ...
  x_batch = []
  y_batch = []
  for ... 
     x_batch.append(one_hot(int_word, vocab_size))
     y_batch.append(one_hot(int_nb, vocab_size, value))
  ...
  ...
  if ...
        x_batch = np.asarray(x_batch)
        y_batch = np.asarray(y_batch)
...

Then, check if you are using np.asarray() or something like that.

Get integer value from string in swift

A more general solution could be a extension

extension String {
    var toFloat:Float {
        return Float(self.bridgeToObjectiveC().floatValue)
    }
    var toDouble:Double {
        ....
    }
    ....
}

this for example extends the swift native String object by toFloat

What should be in my .gitignore for an Android Studio project?

.gitignore from AndroidRate library

# Copyright 2017 - 2018 Vorlonsoft LLC
#
# Licensed under The MIT License (MIT)

# Built application files
*.ap_
*.apk

# Built library files
*.aar
*.jar

# Built native files
*.o
*.so

# Files for the Dalvik/Android Runtime (ART)
*.dex
*.odex

# Java class files
*.class

# Generated files
bin/
gen/
out/

# Gradle files
.gradle/
build/

# Local configuration file (sdk/ndk path, etc)
local.properties

# Windows thumbnail cache
Thumbs.db

# macOS
.DS_Store/

# Log Files
*.log

# Android Studio
.navigation/
captures/
output.json

# NDK
.externalNativeBuild/
obj/

# IntelliJ
## User-specific stuff
.idea/**/tasks.xml
.idea/**/workspace.xml
.idea/dictionaries
## Sensitive or high-churn files
.idea/**/dataSources/
.idea/**/dataSources.ids
.idea/**/dataSources.local.xml
.idea/**/dynamic.xml
.idea/**/sqlDataSources.xml
.idea/**/uiDesigner.xml
## Gradle
.idea/**/gradle.xml
.idea/**/libraries
## VCS
.idea/vcs.xml
## Module files
*.iml
## File-based project format
*.iws

What is the purpose of XSD files?

Also questions is: What is the purpose of giving the relationships in xsd.

Suppose you want to generate some XML for an external party's tool, or similar - how would you know what structure it is allowed to follow to be used correctly for their tool? you write to a schema. Likewise if you want other people to use your tool, you would write a schema for them to follow. It may also be useful for validating your own XML.

PHP Fatal error: Uncaught exception 'Exception'

For

throw new Exception('test exception');

I got 500 (but didn't see anything in the browser), until I put

php_flag display_errors on

in my .htaccess (just for a subfolder). There are also more detailed settings, see Enabling error display in php via htaccess only

Limiting the number of characters in a JTextField

Since the introduction of the DocumentFilter in Java 1.4, the need to override Document has been lessoned.

DocumentFilter provides the means for filtering content been passed to the Document before it actually reaches it.

These allows the field to continue to maintain what ever document it needs, while providing the means to filter the input from the user.

import java.awt.EventQueue;
import java.awt.GridBagLayout;
import javax.swing.JFrame;
import javax.swing.JPasswordField;
import javax.swing.JTextField;
import javax.swing.UIManager;
import javax.swing.UnsupportedLookAndFeelException;
import javax.swing.text.AbstractDocument;
import javax.swing.text.AttributeSet;
import javax.swing.text.BadLocationException;
import javax.swing.text.DocumentFilter;

public class LimitTextField {

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

    public LimitTextField() {
        EventQueue.invokeLater(new Runnable() {
            @Override
            public void run() {
                try {
                    UIManager.setLookAndFeel(UIManager.getSystemLookAndFeelClassName());
                } catch (ClassNotFoundException | InstantiationException | IllegalAccessException | UnsupportedLookAndFeelException ex) {
                    ex.printStackTrace();
                }

                JTextField pfPassword = new JTextField(20);
                ((AbstractDocument)pfPassword.getDocument()).setDocumentFilter(new LimitDocumentFilter(15));

                JFrame frame = new JFrame("Testing");
                frame.setDefaultCloseOperation(JFrame.EXIT_ON_CLOSE);
                frame.setLayout(new GridBagLayout());
                frame.add(pfPassword);
                frame.pack();
                frame.setLocationRelativeTo(null);
                frame.setVisible(true);
            }
        });
    }

    public class LimitDocumentFilter extends DocumentFilter {

        private int limit;

        public LimitDocumentFilter(int limit) {
            if (limit <= 0) {
                throw new IllegalArgumentException("Limit can not be <= 0");
            }
            this.limit = limit;
        }

        @Override
        public void replace(FilterBypass fb, int offset, int length, String text, AttributeSet attrs) throws BadLocationException {
            int currentLength = fb.getDocument().getLength();
            int overLimit = (currentLength + text.length()) - limit - length;
            if (overLimit > 0) {
                text = text.substring(0, text.length() - overLimit);
            }
            if (text.length() > 0) {
                super.replace(fb, offset, length, text, attrs); 
            }
        }

    }

}

Reset textbox value in javascript

To set value

 $('#searchField').val('your_value');

to retrieve value

$('#searchField').val();

Write bytes to file

If I understand you correctly, this should do the trick. You'll need add using System.IO at the top of your file if you don't already have it.

public bool ByteArrayToFile(string fileName, byte[] byteArray)
{
    try
    {
        using (var fs = new FileStream(fileName, FileMode.Create, FileAccess.Write))
        {
            fs.Write(byteArray, 0, byteArray.Length);
            return true;
        }
    }
    catch (Exception ex)
    {
        Console.WriteLine("Exception caught in process: {0}", ex);
        return false;
    }
}

How can I get javascript to read from a .json file?

NOTICE: AS OF JULY 12TH, 2018, THE OTHER ANSWERS ARE ALL OUTDATED. JSONP IS NOW CONSIDERED A TERRIBLE IDEA

If you have your JSON as a string, JSON.parse() will work fine. Since you are loading the json from a file, you will need to do a XMLHttpRequest to it. For example (This is w3schools.com example):

_x000D_
_x000D_
var xmlhttp = new XMLHttpRequest();_x000D_
xmlhttp.onreadystatechange = function() {_x000D_
    if (this.readyState == 4 && this.status == 200) {_x000D_
        var myObj = JSON.parse(this.responseText);_x000D_
        document.getElementById("demo").innerHTML = myObj.name;_x000D_
    }_x000D_
};_x000D_
xmlhttp.open("GET", "json_demo.txt", true);_x000D_
xmlhttp.send();
_x000D_
<!DOCTYPE html>_x000D_
<html>_x000D_
<body>_x000D_
_x000D_
<h2>Use the XMLHttpRequest to get the content of a file.</h2>_x000D_
<p>The content is written in JSON format, and can easily be converted into a JavaScript object.</p>_x000D_
_x000D_
<p id="demo"></p>_x000D_
_x000D_
_x000D_
<p>Take a look at <a href="json_demo.txt" target="_blank">json_demo.txt</a></p>_x000D_
_x000D_
</body>_x000D_
</html>
_x000D_
_x000D_
_x000D_

It will not work here as that file isn't located here. Go to this w3schools example though: https://www.w3schools.com/js/tryit.asp?filename=tryjson_ajax

Here is the documentation for JSON.parse(): https://developer.mozilla.org/en/docs/Web/JavaScript/Reference/Global_Objects/JSON/parse

Here's a summary:

The JSON.parse() method parses a JSON string, constructing the JavaScript value or object described by the string. An optional reviver function can be provided to perform a transformation on the resulting object before it is returned.

Here's the example used:

_x000D_
_x000D_
var json = '{"result":true, "count":42}';_x000D_
obj = JSON.parse(json);_x000D_
_x000D_
console.log(obj.count);_x000D_
// expected output: 42_x000D_
_x000D_
console.log(obj.result);_x000D_
// expected output: true
_x000D_
_x000D_
_x000D_

Here is a summary on XMLHttpRequests from https://developer.mozilla.org/en-US/docs/Web/API/XMLHttpRequest:

Use XMLHttpRequest (XHR) objects to interact with servers. You can retrieve data from a URL without having to do a full page refresh. This enables a Web page to update just part of a page without disrupting what the user is doing. XMLHttpRequest is used heavily in Ajax programming.

If you don't want to use XMLHttpRequests, then a JQUERY way (which I'm not sure why it isn't working for you) is http://api.jquery.com/jQuery.getJSON/

Since it isn't working, I'd try using XMLHttpRequests

You could also try AJAX requests:

$.ajax({
    'async': false,
    'global': false,
    'url': "/jsonfile.json",
    'dataType': "json",
    'success': function (data) {
        // do stuff with data
    }
});

Documentation: http://api.jquery.com/jquery.ajax/

How to retry image pull in a kubernetes Pods?

Usually in case of "ImagePullBackOff" it's retried after few seconds/minutes. In case you want to try again manually you can delete the old pod and recreate the pod. The one line command to delete and recreate the pod would be:

kubectl replace --force -f <yml_file_describing_pod>

How to make sure you don't get WCF Faulted state exception?

Similar to Ryan Rodemoyer's answer, I found that when the UriTemplate on the Contract is not valid you can get this error. In my case, I was using the same parameter twice. For example:

/Root/{Name}/{Name}

ISO C90 forbids mixed declarations and code in C

Just use a compiler (or provide it with the arguments it needs) such that it compiles for a more recent version of the C standard, C99 or C11. E.g for the GCC family of compilers that would be -std=c99.

fetch gives an empty response body

fetch("http://localhost:8988/api", {
    method: "GET",
    headers: {
       "Content-Type": "application/json"
    }
})
.then((response) =>response.json());
.then((data) => {
    console.log(data);
})
.catch(error => {
    return error;
});

How to build & install GLFW 3 and use it in a Linux project

Great guide, thank you. Given most instructions here, it almost built for me but I did have one remaining error.

/usr/bin/ld: //usr/local/lib/libglfw3.a(glx_context.c.o): undefined reference to symbol 'dlclose@@GLIBC_2.2.5'
//lib/x86_64-linux-gnu/libdl.so.2: error adding symbols: DSO missing from command line
collect2: error: ld returned 1 exit status

After searching for this error, I had to add -ldl to the command line.

g++ main.cpp -lglfw3 -lX11 -lXrandr -lXinerama -lXi -lXxf86vm -lXcursor -lGL -lpthread -ldl

Then the "hello GLFW" sample app compiled and linked.

I am pretty new to linux so I am not completely certain what exactly this extra library does... other than fix my linking error. I do see that cmd line switch in the post above, however.

How to implement authenticated routes in React Router 4?

It seems your hesitation is in creating your own component and then dispatching in the render method? Well you can avoid both by just using the render method of the <Route> component. No need to create a <AuthenticatedRoute> component unless you really want to. It can be as simple as below. Note the {...routeProps} spread making sure you continue to send the properties of the <Route> component down to the child component (<MyComponent> in this case).

<Route path='/someprivatepath' render={routeProps => {

   if (!this.props.isLoggedIn) {
      this.props.redirectToLogin()
      return null
    }
    return <MyComponent {...routeProps} anotherProp={somevalue} />

} />

See the React Router V4 render documentation

If you did want to create a dedicated component, then it looks like you are on the right track. Since React Router V4 is purely declarative routing (it says so right in the description) I do not think you will get away with putting your redirect code outside of the normal component lifecycle. Looking at the code for React Router itself, they perform the redirect in either componentWillMount or componentDidMount depending on whether or not it is server side rendering. Here is the code below, which is pretty simple and might help you feel more comfortable with where to put your redirect logic.

import React, { PropTypes } from 'react'

/**
 * The public API for updating the location programatically
 * with a component.
 */
class Redirect extends React.Component {
  static propTypes = {
    push: PropTypes.bool,
    from: PropTypes.string,
    to: PropTypes.oneOfType([
      PropTypes.string,
      PropTypes.object
    ])
  }

  static defaultProps = {
    push: false
  }

  static contextTypes = {
    router: PropTypes.shape({
      history: PropTypes.shape({
        push: PropTypes.func.isRequired,
        replace: PropTypes.func.isRequired
      }).isRequired,
      staticContext: PropTypes.object
    }).isRequired
  }

  isStatic() {
    return this.context.router && this.context.router.staticContext
  }

  componentWillMount() {
    if (this.isStatic())
      this.perform()
  }

  componentDidMount() {
    if (!this.isStatic())
      this.perform()
  }

  perform() {
    const { history } = this.context.router
    const { push, to } = this.props

    if (push) {
      history.push(to)
    } else {
      history.replace(to)
    }
  }

  render() {
    return null
  }
}

export default Redirect

C pointers and arrays: [Warning] assignment makes pointer from integer without a cast

int[] and int* are represented the same way, except int[] allocates (IIRC).

ap is a pointer, therefore giving it the value of an integer is dangerous, as you have no idea what's at address 45.

when you try to access it (x = *ap), you try to access address 45, which causes the crash, as it probably is not a part of the memory you can access.

How can I detect the touch event of an UIImageView?

For those of you looking for a Swift 4 solution to this answer, you can use the following to detect a touch event on a UIImageView.

let gestureRecognizer: UITapGestureRecognizer = UITapGestureRecognizer(target: self, action: #selector(imageViewTapped))
imageView.addGestureRecognizer(gestureRecognizer)
imageView.isUserInteractionEnabled = true

You will then need to define your selector as follows:

@objc func imageViewTapped() {
    // Image has been tapped
}

Aren't promises just callbacks?

In addition to the other answers, the ES2015 syntax blends seamlessly with promises, reducing even more boilerplate code:

// Sequentially:
api1()
  .then(r1 => api2(r1))
  .then(r2 => api3(r2))
  .then(r3 => {
      // Done
  });

// Parallel:
Promise.all([
    api1(),
    api2(),
    api3()
]).then(([r1, r2, r3]) => {
    // Done
});

How to step through Python code to help debug issues?

Starting in Python 3.7, you can use the breakpoint() built-in function to enter the debugger:

foo()
breakpoint()  # drop into the debugger at this point
bar()

By default, breakpoint() will import pdb and call pdb.set_trace(). However, you can control debugging behavior via sys.breakpointhook() and use of the environment variable PYTHONBREAKPOINT.

See PEP 553 for more information.

Can you have if-then-else logic in SQL?

Please check whether this helps:

select TOP 1
    product, 
    price 
from 
    table1 
where 
    (project=1 OR Customer=2 OR company=3) AND
    price IS NOT NULL
ORDER BY company 

Nginx Different Domains on Same IP

Your "listen" directives are wrong. See this page: http://nginx.org/en/docs/http/server_names.html.

They should be

server {
    listen      80;
    server_name www.domain1.com;
    root /var/www/domain1;
}

server {
    listen       80;
    server_name www.domain2.com;
    root /var/www/domain2;
}

Note, I have only included the relevant lines. Everything else looked okay but I just deleted it for clarity. To test it you might want to try serving a text file from each server first before actually serving php. That's why I left the 'root' directive in there.

How to create a sleep/delay in nodejs that is Blocking?

Node is asynchronous by nature, and that's what's great about it, so you really shouldn't be blocking the thread, but as this seems to be for a project controlling LED's, I'll post a workaraound anyway, even if it's not a very good one and shouldn't be used (seriously).

A while loop will block the thread, so you can create your own sleep function

function sleep(time, callback) {
    var stop = new Date().getTime();
    while(new Date().getTime() < stop + time) {
        ;
    }
    callback();
}

to be used as

sleep(1000, function() {
   // executes after one second, and blocks the thread
});

I think this is the only way to block the thread (in principle), keeping it busy in a loop, as Node doesn't have any blocking functionality built in, as it would sorta defeat the purpose of the async behaviour.

How to put labels over geom_bar for each bar in R with ggplot2

Try this:

ggplot(data=dat, aes(x=Types, y=Number, fill=sample)) + 
     geom_bar(position = 'dodge', stat='identity') +
     geom_text(aes(label=Number), position=position_dodge(width=0.9), vjust=-0.25)

ggplot output

How do I select child elements of any depth using XPath?

You're almost there. Simply use:

//form[@id='myform']//input[@type='submit']

The // shortcut can also be used inside an expression.

Python: slicing a multi-dimensional array

If you use numpy, this is easy:

slice = arr[:2,:2]

or if you want the 0's,

slice = arr[0:2,0:2]

You'll get the same result.

*note that slice is actually the name of a builtin-type. Generally, I would advise giving your object a different "name".


Another way, if you're working with lists of lists*:

slice = [arr[i][0:2] for i in range(0,2)]

(Note that the 0's here are unnecessary: [arr[i][:2] for i in range(2)] would also work.).

What I did here is that I take each desired row 1 at a time (arr[i]). I then slice the columns I want out of that row and add it to the list that I'm building.

If you naively try: arr[0:2] You get the first 2 rows which if you then slice again arr[0:2][0:2], you're just slicing the first two rows over again.

*This actually works for numpy arrays too, but it will be slow compared to the "native" solution I posted above.

How to play CSS3 transitions in a loop?

If you want to take advantage of the 60FPS smoothness that the "transform" property offers, you can combine the two:

@keyframes changewidth {
  from {
    transform: scaleX(1);
  }

  to {
    transform: scaleX(2);
  }
}

div {
  animation-duration: 0.1s;
  animation-name: changewidth;
  animation-iteration-count: infinite;
  animation-direction: alternate;
}

More explanation on why transform offers smoother transitions here: https://medium.com/outsystems-experts/how-to-achieve-60-fps-animations-with-css3-db7b98610108

How to install Anaconda on RaspBerry Pi 3 Model B

On Raspberry Pi 3 Model B - Installation of Miniconda (bundled with Python 3)

Go and get the latest version of miniconda for Raspberry Pi - made for armv7l processor and bundled with Python 3 (eg.: uname -m)

wget http://repo.continuum.io/miniconda/Miniconda3-latest-Linux-armv7l.sh
md5sum Miniconda3-latest-Linux-armv7l.sh
bash Miniconda3-latest-Linux-armv7l.sh

After installation, source your updated .bashrc file with source ~/.bashrc. Then enter the command python --version, which should give you:

Python 3.4.3 :: Continuum Analytics, Inc.

pandas: to_numeric for multiple columns

You can use:

print df.columns[5:]
Index([u'2004', u'2005', u'2006', u'2007', u'2008', u'2009', u'2010', u'2011',
       u'2012', u'2013', u'2014'],
      dtype='object')

for col in  df.columns[5:]:
    df[col] = pd.to_numeric(df[col], errors='coerce')

print df
       GeoName      ComponentName  IndustryId  IndustryClassification  \
37926  Alabama  Real GDP by state           9                     213   
37951  Alabama  Real GDP by state          34                      42   
37932  Alabama  Real GDP by state          15                     327   

                                      Description  2004   2005   2006   2007  \
37926               Support activities for mining    99     98    117    117   
37951                            Wholesale  trade  9898  10613  10952  11034   
37932  Nonmetallic mineral products manufacturing   980    968    940   1084   

        2008  2009  2010  2011  2012  2013     2014  
37926    115    87    96    95   103   102      NaN  
37951  11075  9722  9765  9703  9600  9884  10199.0  
37932    861   724   714   701   589   641      NaN  

Another solution with filter:

print df.filter(like='20')
       2004   2005   2006   2007   2008  2009  2010  2011  2012  2013   2014
37926    99     98    117    117    115    87    96    95   103   102   (NA)
37951  9898  10613  10952  11034  11075  9722  9765  9703  9600  9884  10199
37932   980    968    940   1084    861   724   714   701   589   641   (NA)

for col in  df.filter(like='20').columns:
    df[col] = pd.to_numeric(df[col], errors='coerce')
print df
       GeoName      ComponentName  IndustryId  IndustryClassification  \
37926  Alabama  Real GDP by state           9                     213   
37951  Alabama  Real GDP by state          34                      42   
37932  Alabama  Real GDP by state          15                     327   

                                      Description  2004   2005   2006   2007  \
37926               Support activities for mining    99     98    117    117   
37951                            Wholesale  trade  9898  10613  10952  11034   
37932  Nonmetallic mineral products manufacturing   980    968    940   1084   

        2008  2009  2010  2011  2012  2013     2014  
37926    115    87    96    95   103   102      NaN  
37951  11075  9722  9765  9703  9600  9884  10199.0  
37932    861   724   714   701   589   641      NaN  

fill an array in C#

You could try something like this:

I have initialzed the array for having value 5, you could put your number similarly.

int[] arr = new int[10]; // your initial array

arr = arr.Select(i => 5).ToArray(); // array initialized to 5.

What is the HTML tabindex attribute?

The HTML tabindex atribute is responsible for indicating if an element is reachable by keyboard navigation. When the user presses the Tab key the focus is shifted from one element to another. By using the tabindex atribute, the tab order flow is shifted.

Getting a better understanding of callback functions in JavaScript

You can just say

callback();

Alternately you can use the call method if you want to adjust the value of this within the callback.

callback.call( newValueForThis);

Inside the function this would be whatever newValueForThis is.

Use jquery click to handle anchor onClick()

The first time you click the link, the openSolution function is executed. That function binds the click event handler to the link, but it won't execute it. The second time you click the link, the click event handler will be executed.

What you are doing seems to kind of defeat the point of using jQuery in the first place. Why not just bind the click event to the elements in the first place:

$(document).ready(function() {
    $("#solTitle a").click(function() {
        //Do stuff when clicked
    });
});

This way you don't need onClick attributes on your elements.

It also looks like you have multiple elements with the same id value ("solTitle"), which is invalid. You would need to find some other common characteristic (class is usually a good option). If you change all occurrences of id="solTitle" to class="solTitle", you can then use a class selector:

$(".solTitle a")

Since duplicate id values is invalid, the code will not work as expected when facing multiple copies of the same id. What tends to happen is that the first occurrence of the element with that id is used, and all others are ignored.

How to hide scrollbar in Firefox?

This is something of a generic solution:

<div class="outer">
 <div class="inner">
    Some content...
 </div>
</div>

<style>
 .outer {
 overflow: hidden;
}
 .inner {
 margin-right: -16px;
 overflow-y: scroll;
 overflow-x: hidden;
}
</style>

The scroll bar is hidden by the parent div.

This requires you to use overflow:hidden in the parent div.

Attach Authorization header for all axios requests

Sometimes you get a case where some of the requests made with axios are pointed to endpoints that do not accept authorization headers. Thus, alternative way to set authorization header only on allowed domain is as in the example below. Place the following function in any file that gets executed each time React application runs such as in routes file.

export default () => {
    axios.interceptors.request.use(function (requestConfig) {
        if (requestConfig.url.indexOf(<ALLOWED_DOMAIN>) > -1) {
            const token = localStorage.token;
            requestConfig.headers['Authorization'] = `Bearer ${token}`;
        }

        return requestConfig;
    }, function (error) {
        return Promise.reject(error);
    });

}

Easiest way to read/write a file's content in Python

contents = open(filename)

This gives you generator so you must save somewhere the values though, or

contents = [line for line in open(filename)]

This does the saving to list explicit close is not then possible (at least with my knowledge of Python).

Could not find any resources appropriate for the specified culture or the neutral culture

Just another case. I copied a solution with two projects and renamed them partially in the Windows explorer (folder names, .sln and .csproj file names) and partially with a massive Find & Replace action in Visual Studio (namespaces etc.). Nevertheless the exception stated by the OP still occurred. I found out that the Assembly and Namespace names were still old.

Although the project and everything else was already named OfficeStyle the Assembly name and Default namespace were still named Linckus.

Old situation

After this correction everything worked fine again, compile and run time :)

New situation

Fail to create Android virtual Device, "No system image installed for this Target"

In order to create an Android Wear emulator you need to follow the instructions below:

  1. If your version of Android SDK Tools is lower than 22.6, you must update

  2. Under Android 4.4.2, select Android Wear ARM EABI v7a System Image and install it.

  3. Under Extras, ensure that you have the latest version of the Android Support Library. If an update is available, select Android Support Library. If you're using Android Studio, also select Android Support Repository.

Below is the snapshot of what it should look like:

Screenshot1

Then you must check the following in order to create a Wearable AVD:

  1. For the Device, select Android Wear Square or Android Wear Round.

  2. For the Target, select Android 4.4.2 - API Level 19 (or higher, otherwise corresponding system image will not show up.).

  3. For the CPU/ABI, select Android Wear ARM (armeabi-v7a).

  4. For the Skin, select AndroidWearSquare or AndroidWearRound.

  5. Leave all other options set to their defaults and click OK.

Screenshot2

Then you are good to go. For more information you can always refer to the developer site.

How to install node.js as windows service?

The process manager + task scheduler approach I posted a year ago works well with some one-off service installations. But recently I started to design system in a micro-service fashion, with many small services talking to each other via IPC. So manually configuring each service has become unbearable.

Towards the goal of installing services without manual configuration, I created serman, a command line tool (install with npm i -g serman) to install an executable as a service. All you need to write (and only write once) is a simple service configuration file along with your executable. Run

serman install <path_to_config_file>

will install the service. stdout and stderr are all logged. For more info, take a look at the project website.

A working configuration file is very simple, as demonstrated below. But it also has many useful features such as <env> and <persistent_env> below.

<service>
  <id>hello</id>
  <name>hello</name>
  <description>This service runs the hello application</description>

  <executable>node.exe</executable>

  <!-- 
       {{dir}} will be expanded to the containing directory of your 
       config file, which is normally where your executable locates 
   -->
  <arguments>"{{dir}}\hello.js"</arguments>

  <logmode>rotate</logmode>

  <!-- OPTIONAL FEATURE:
       NODE_ENV=production will be an environment variable 
       available to your application, but not visible outside 
       of your application
   -->
  <env name="NODE_ENV" value="production"/>

  <!-- OPTIONAL FEATURE:
       FOO_SERVICE_PORT=8989 will be persisted as an environment
       variable machine-wide.
   -->
  <persistent_env name="FOO_SERVICE_PORT" value="8989" />
</service>

Checking on a thread / remove from list

you need to call thread.isAlive()to find out if the thread is still running

Selecting last element in JavaScript array

So, a lot of people are answering with pop(), but most of them don't seem to realize that's a destructive method.

var a = [1,2,3]
a.pop()
//3
//a is now [1,2]

So, for a really silly, nondestructive method:

var a = [1,2,3]
a[a.push(a.pop())-1]
//3

a push pop, like in the 90s :)

push appends a value to the end of an array, and returns the length of the result. so

d=[]
d.push('life') 
//=> 1
d 
//=>['life']

pop returns the value of the last item of an array, prior to it removing that value at that index. so

c = [1,2,1]
c.pop() 
//=> 1
c 
//=> [1,2]

arrays are 0 indexed, so c.length => 3, c[c.length] => undefined (because you're looking for the 4th value if you do that(this level of depth is for any hapless newbs that end up here)).

Probably not the best, or even a good method for your application, what with traffic, churn, blah. but for traversing down an array, streaming it onto another, just being silly with inefficient methods, this. Totally this.

Cannot find module '@angular/compiler'

Try to delete that "angular/cli": "1.0.0-beta.28.3", in the devDependencies it is useless , and add instead of it "@angular/compiler-cli": "^2.3.1", (since it is the current version, else add it by npm i --save-dev @angular/compiler-cli ), then in your root app folder run those commands:

  1. rm -r node_modules (or delete your node_modules folder manually)
  2. npm cache clean (npm > v5 add --force so: npm cache clean --force)
  3. npm install

Substitute a comma with a line break in a cell

For some reason, none of the above worked for me. This DID however:

  1. Selected the range of cells I needed to replace.
  2. Go to Home > Find & Select > Replace or Ctrl + H
  3. Find what: ,
  4. Replace with: CTRL + SHIFT + J
  5. Click Replace All

Somehow CTRL + SHIFT + J is registered as a linebreak.

Difference between logger.info and logger.debug

What is the difference between logger.debug and logger.info?

These are only some default level already defined. You can define your own levels if you like. The purpose of those levels is to enable/disable one or more of them, without making any change in your code.

When logger.debug will be printed ??

When you have enabled the debug or any higher level in your configuration.

Reading Excel file using node.js

install exceljs and use the following code,

var Excel = require('exceljs');

var wb = new Excel.Workbook();
var path = require('path');
var filePath = path.resolve(__dirname,'sample.xlsx');

wb.xlsx.readFile(filePath).then(function(){

    var sh = wb.getWorksheet("Sheet1");

    sh.getRow(1).getCell(2).value = 32;
    wb.xlsx.writeFile("sample2.xlsx");
    console.log("Row-3 | Cell-2 - "+sh.getRow(3).getCell(2).value);

    console.log(sh.rowCount);
    //Get all the rows data [1st and 2nd column]
    for (i = 1; i <= sh.rowCount; i++) {
        console.log(sh.getRow(i).getCell(1).value);
        console.log(sh.getRow(i).getCell(2).value);
    }
});

Vue component event after render

updated might be what you're looking for. https://vuejs.org/v2/api/#updated

Spring MVC: How to return image in @ResponseBody?

In spring 4 it's very easy you don't need to make any changes in beans. Only mark your return type to @ResponseBody.

Example:-

@RequestMapping(value = "/image/{id}")
    public @ResponseBody
    byte[] showImage(@PathVariable Integer id) {
                 byte[] b;
        /* Do your logic and return 
               */
        return b;
    }

Counting Number of Letters in a string variable

You can simply use

int numberOfLetters = yourWord.Length;

or to be cool and trendy, use LINQ like this :

int numberOfLetters = yourWord.ToCharArray().Count();

and if you hate both Properties and LINQ, you can go old school with a loop :

int numberOfLetters = 0;
foreach (char letter in yourWord)
{
    numberOfLetters++;
}

Debugging JavaScript in IE7

Running your code through a Javascript static analysis tool like JSLint can catch some common IE7 errors, such as trailing commas in object definitions.

How to check if a string contains an element from a list in Python

extensionsToCheck = ('.pdf', '.doc', '.xls')

'test.doc'.endswith(extensionsToCheck)   # returns True

'test.jpg'.endswith(extensionsToCheck)   # returns False

Data structure for maintaining tabular data in memory?

First, given that you have a complex data retrieval scenario, are you sure even SQLite is overkill?

You'll end up having an ad hoc, informally-specified, bug-ridden, slow implementation of half of SQLite, paraphrasing Greenspun's Tenth Rule.

That said, you are very right in saying that choosing a single data structure will impact one or more of searching, sorting or counting, so if performance is paramount and your data is constant, you could consider having more than one structure for different purposes.

Above all, measure what operations will be more common and decide which structure will end up costing less.

How to check if one of the following items is in a list?

I have to say that my situation might not be what you are looking for, but it may provide an alternative to your thinking.

I have tried both the set() and any() method but still have problems with speed. So I remembered Raymond Hettinger said everything in python is a dictionary and use dict whenever you can. So that's what I tried.

I used a defaultdict with int to indicate negative results and used the item in the first list as the key for the second list (converted to defaultdict). Because you have instant lookup with dict, you know immediately whether that item exist in the defaultdict. I know you don't always get to change data structure for your second list, but if you are able to from the start, then it's much faster. You may have to convert list2 (larger list) to a defaultdict, where key is the potential value you want to check from small list, and value is either 1 (hit) or 0 (no hit, default).

from collections import defaultdict
already_indexed = defaultdict(int)

def check_exist(small_list, default_list):
    for item in small_list:
        if default_list[item] == 1:
            return True
    return False

if check_exist(small_list, already_indexed):
    continue
else:
    for x in small_list:
        already_indexed[x] = 1

Description Box using "onmouseover"

Assuming popup is the ID of your "description box":

HTML

<div id="parent"> <!-- This is the main container, to mouse over -->
<div id="popup" style="display: none">description text here</div>
</div>

JavaScript

var e = document.getElementById('parent');
e.onmouseover = function() {
  document.getElementById('popup').style.display = 'block';
}
e.onmouseout = function() {
  document.getElementById('popup').style.display = 'none';
}

Alternatively you can get rid of JavaScript entirely and do it just with CSS:

CSS

#parent #popup {
  display: none;
}

#parent:hover #popup {
  display: block;
}

How can I scroll to a specific location on the page using jquery?

Using jquery.easing.min.js, With fixed IE console Errors

Html

<a class="page-scroll" href="#features">Features</a>
<section id="features" class="features-section">Features Section</section>


        <!-- jQuery (necessary for Bootstrap's JavaScript plugins) -->
        <script src="js/jquery.js"></script>
        <!-- Include all compiled plugins (below), or include individual files as needed -->
        <script src="js/bootstrap.min.js"></script>

        <!-- Scrolling Nav JavaScript -->
        <script src="js/jquery.easing.min.js"></script>

Jquery

//jQuery to collapse the navbar on scroll, you can use this code with in external file with name scrolling-nav.js
        $(window).scroll(function () {
            if ($(".navbar").offset().top > 50) {
                $(".navbar-fixed-top").addClass("top-nav-collapse");
            } else {
                $(".navbar-fixed-top").removeClass("top-nav-collapse");
            }
        });
        //jQuery for page scrolling feature - requires jQuery Easing plugin
        $(function () {
            $('a.page-scroll').bind('click', function (event) {
                var anchor = $(this);
                if ($(anchor).length > 0) {
                    var href = $(anchor).attr('href');
                    if ($(href.substring(href.indexOf('#'))).length > 0) {
                        $('html, body').stop().animate({
                            scrollTop: $(href.substring(href.indexOf('#'))).offset().top
                        }, 1500, 'easeInOutExpo');
                    }
                    else {
                        window.location = href;
                    }
                }
                event.preventDefault();
            });
        });

Curl to return http status code along with the response

For programmatic usage, I use the following :

curlwithcode() {
    code=0
    # Run curl in a separate command, capturing output of -w "%{http_code}" into statuscode
    # and sending the content to a file with -o >(cat >/tmp/curl_body)
    statuscode=$(curl -w "%{http_code}" \
        -o >(cat >/tmp/curl_body) \
        "$@"
    ) || code="$?"

    body="$(cat /tmp/curl_body)"
    echo "statuscode : $statuscode"
    echo "exitcode : $code"
    echo "body : $body"
}

curlwithcode https://api.github.com/users/tj

It shows following output :

statuscode : 200
exitcode : 0
body : {
  "login": "tj",
  "id": 25254,
  ...
}

ModuleNotFoundError: What does it mean __main__ is not a package?

Remove the dot and import absolute_import in the beginning of your file

from __future__ import absolute_import

from p_02_paying_debt_off_in_a_year import compute_balance_after

Delete topic in Kafka 0.8.1.1

This steps will delete all topics and data

  • Stop Kafka-server and Zookeeper-server
  • Remove the tmp data directories of both services, by default they are C:/tmp/kafka-logs and C:/tmp/zookeeper.
  • then start Zookeeper-server and Kafka-server

Restart android machine

I think the only way to do this is to run another machine in parallel and use that machine to issue commands to your android box similar to how you would with a phone. If you have issues with the IP changing you can reserve an ip on your router and have the machine grab that one instead of asking the routers DHCP for one. This way you can ping the machine and figure out if it's done rebooting to continue the script.

C# Iterate through Class properties

You could possibly use Reflection to do this. As far as I understand it, you could enumerate the properties of your class and set the values. You would have to try this out and make sure you understand the order of the properties though. Refer to this MSDN Documentation for more information on this approach.

For a hint, you could possibly do something like:

Record record = new Record();

PropertyInfo[] properties = typeof(Record).GetProperties();
foreach (PropertyInfo property in properties)
{
    property.SetValue(record, value);
}

Where value is the value you're wanting to write in (so from your resultItems array).

Javadoc link to method in other class

For the Javadoc tag @see, you don't need to use @link; Javadoc will create a link for you. Try

@see com.my.package.Class#method()

Here's more info about @see.

How to handle authentication popup with Selenium WebDriver using Java

I faced this issue a number of times in my application.

We can generally handle this with the below 2 approaches.

  1. Pass the username and password in url itself

  2. You can create an AutoIT Script and call script before opening the url.

Please check the below article in which I have mentioned both ways:
Handle Authentication/Login window in Selenium Webdriver

Does the Java &= operator apply & or &&?

i came across a similar situation using booleans where I wanted to avoid calling b() if a was already false.

This worked for me:

a &= a && b()

Is False == 0 and True == 1 an implementation detail or is it guaranteed by the language?

In Python 2.x this is not guaranteed as it is possible for True and False to be reassigned. However, even if this happens, boolean True and boolean False are still properly returned for comparisons.

In Python 3.x True and False are keywords and will always be equal to 1 and 0.

Under normal circumstances in Python 2, and always in Python 3:

False object is of type bool which is a subclass of int:

object
   |
 int
   |
 bool

It is the only reason why in your example, ['zero', 'one'][False] does work. It would not work with an object which is not a subclass of integer, because list indexing only works with integers, or objects that define a __index__ method (thanks mark-dickinson).

Edit:

It is true of the current python version, and of that of Python 3. The docs for python 2 and the docs for Python 3 both say:

There are two types of integers: [...] Integers (int) [...] Booleans (bool)

and in the boolean subsection:

Booleans: These represent the truth values False and True [...] Boolean values behave like the values 0 and 1, respectively, in almost all contexts, the exception being that when converted to a string, the strings "False" or "True" are returned, respectively.

There is also, for Python 2:

In numeric contexts (for example when used as the argument to an arithmetic operator), they [False and True] behave like the integers 0 and 1, respectively.

So booleans are explicitly considered as integers in Python 2 and 3.

So you're safe until Python 4 comes along. ;-)

Python Selenium accessing HTML source

from bs4 import BeautifulSoup
from selenium import webdriver

driver = webdriver.Chrome()
html_source_code = driver.execute_script("return document.body.innerHTML;")
html_soup: BeautifulSoup = BeautifulSoup(html_source_code, 'html.parser')

Now you can apply BeautifulSoup function to extract data...

What is inf and nan?

nan means "not a number", a float value that you get if you perform a calculation whose result can't be expressed as a number. Any calculations you perform with NaN will also result in NaN.

inf means infinity.

For example:

>>> 2*float("inf")
inf
>>> -2*float("inf")
-inf
>>> float("inf")-float("inf")
nan

How to present popover properly in iOS 8

Okay, A housemate took a look at it and figured it out:

 func addCategory() {

    var popoverContent = self.storyboard?.instantiateViewControllerWithIdentifier("NewCategory") as UIViewController
    var nav = UINavigationController(rootViewController: popoverContent)
    nav.modalPresentationStyle = UIModalPresentationStyle.Popover
    var popover = nav.popoverPresentationController
    popoverContent.preferredContentSize = CGSizeMake(500,600)
    popover.delegate = self
    popover.sourceView = self.view
    popover.sourceRect = CGRectMake(100,100,0,0)

    self.presentViewController(nav, animated: true, completion: nil)

}

That's the way.

You don't talk to the popover itself anymore, you talk to the view controller inside of it to set the content size, by calling the property preferredContentSize

How to pretty print XML from Java?

Here's an answer to my own question. I combined the answers from the various results to write a class that pretty prints XML.

No guarantees on how it responds with invalid XML or large documents.

package ecb.sdw.pretty;

import org.apache.xml.serialize.OutputFormat;
import org.apache.xml.serialize.XMLSerializer;
import org.w3c.dom.Document;
import org.xml.sax.InputSource;
import org.xml.sax.SAXException;

import javax.xml.parsers.DocumentBuilder;
import javax.xml.parsers.DocumentBuilderFactory;
import javax.xml.parsers.ParserConfigurationException;
import java.io.IOException;
import java.io.StringReader;
import java.io.StringWriter;
import java.io.Writer;

/**
 * Pretty-prints xml, supplied as a string.
 * <p/>
 * eg.
 * <code>
 * String formattedXml = new XmlFormatter().format("<tag><nested>hello</nested></tag>");
 * </code>
 */
public class XmlFormatter {

    public XmlFormatter() {
    }

    public String format(String unformattedXml) {
        try {
            final Document document = parseXmlFile(unformattedXml);

            OutputFormat format = new OutputFormat(document);
            format.setLineWidth(65);
            format.setIndenting(true);
            format.setIndent(2);
            Writer out = new StringWriter();
            XMLSerializer serializer = new XMLSerializer(out, format);
            serializer.serialize(document);

            return out.toString();
        } catch (IOException e) {
            throw new RuntimeException(e);
        }
    }

    private Document parseXmlFile(String in) {
        try {
            DocumentBuilderFactory dbf = DocumentBuilderFactory.newInstance();
            DocumentBuilder db = dbf.newDocumentBuilder();
            InputSource is = new InputSource(new StringReader(in));
            return db.parse(is);
        } catch (ParserConfigurationException e) {
            throw new RuntimeException(e);
        } catch (SAXException e) {
            throw new RuntimeException(e);
        } catch (IOException e) {
            throw new RuntimeException(e);
        }
    }

    public static void main(String[] args) {
        String unformattedXml =
                "<?xml version=\"1.0\" encoding=\"UTF-8\"?><QueryMessage\n" +
                        "        xmlns=\"http://www.SDMX.org/resources/SDMXML/schemas/v2_0/message\"\n" +
                        "        xmlns:query=\"http://www.SDMX.org/resources/SDMXML/schemas/v2_0/query\">\n" +
                        "    <Query>\n" +
                        "        <query:CategorySchemeWhere>\n" +
                        "   \t\t\t\t\t         <query:AgencyID>ECB\n\n\n\n</query:AgencyID>\n" +
                        "        </query:CategorySchemeWhere>\n" +
                        "    </Query>\n\n\n\n\n" +
                        "</QueryMessage>";

        System.out.println(new XmlFormatter().format(unformattedXml));
    }

}

How do you get the logical xor of two variables in Python?

  • Python logical or: A or B: returns A if bool(A) is True, otherwise returns B
  • Python logical and: A and B: returns A if bool(A) is False, otherwise returns B

To keep most of that way of thinking, my logical xor definintion would be:

def logical_xor(a, b):
    if bool(a) == bool(b):
        return False
    else:
        return a or b

That way it can return a, b, or False:

>>> logical_xor('this', 'that')
False
>>> logical_xor('', '')
False
>>> logical_xor('this', '')
'this'
>>> logical_xor('', 'that')
'that'

GCC: array type has incomplete element type

It's the array that's causing trouble in:

void print_graph(g_node graph_node[], double weight[][], int nodes);

The second and subsequent dimensions must be given:

void print_graph(g_node graph_node[], double weight[][32], int nodes);

Or you can just give a pointer to pointer:

void print_graph(g_node graph_node[], double **weight, int nodes);

However, although they look similar, those are very different internally.

If you're using C99, you can use variably-qualified arrays. Quoting an example from the C99 standard (section §6.7.5.2 Array Declarators):

void fvla(int m, int C[m][m]); // valid: VLA with prototype scope

void fvla(int m, int C[m][m])  // valid: adjusted to auto pointer to VLA
{
    typedef int VLA[m][m];     // valid: block scope typedef VLA
    struct tag {
        int (*y)[n];           // invalid: y not ordinary identifier
        int z[n];              // invalid: z not ordinary identifier
    };
    int D[m];                  // valid: auto VLA
    static int E[m];           // invalid: static block scope VLA
    extern int F[m];           // invalid: F has linkage and is VLA
    int (*s)[m];               // valid: auto pointer to VLA
    extern int (*r)[m];        // invalid: r has linkage and points to VLA
    static int (*q)[m] = &B;   // valid: q is a static block pointer to VLA
}

Question in comments

[...] In my main(), the variable I am trying to pass into the function is a double array[][], so how would I pass that into the function? Passing array[0][0] into it gives me incompatible argument type, as does &array and &array[0][0].

In your main(), the variable should be:

double array[10][20];

or something faintly similar; maybe

double array[][20] = { { 1.0, 0.0, ... }, ... };

You should be able to pass that with code like this:

typedef struct graph_node
{
    int X;
    int Y;
    int active;
} g_node;

void print_graph(g_node graph_node[], double weight[][20], int nodes);

int main(void)
{
    g_node g[10];
    double array[10][20];
    int n = 10;

    print_graph(g, array, n);
    return 0;
}

That compiles (to object code) cleanly with GCC 4.2 (i686-apple-darwin11-llvm-gcc-4.2 (GCC) 4.2.1 (Based on Apple Inc. build 5658) (LLVM build 2336.9.00)) and also with GCC 4.7.0 on Mac OS X 10.7.3 using the command line:

/usr/bin/gcc -O3 -g -std=c99 -Wall -Wextra -c zzz.c

convert from Color to brush

It's often sufficient to use sibling's or parent's brush for the purpose, and that's easily available in wpf via retrieving their Foreground or Background property.

ref: Control.Background

Get month name from number

This Is What I Would Do:

from datetime import *

months = ["Unknown",
          "January",
          "Febuary",
          "March",
          "April",
          "May",
          "June",
          "July",
          "August",
          "September",
          "October",
          "November",
          "December"]

now = (datetime.now())
year = (now.year)
month = (months[now.month])
print(month)

It Outputs:

>>> September

(This Was The Real Date When I Wrote This)

How to remove element from array in forEach loop?

Although Xotic750's answer provides several good points and possible solutions, sometimes simple is better.

You know the array being iterated on is being mutated in the iteration itself (i.e. removing an item => index changes), thus the simplest logic is to go backwards in an old fashioned for (à la C language):

_x000D_
_x000D_
let arr = ['a', 'a', 'b', 'c', 'b', 'a', 'a'];_x000D_
_x000D_
for (let i = arr.length - 1; i >= 0; i--) {_x000D_
  if (arr[i] === 'a') {_x000D_
    arr.splice(i, 1);_x000D_
  }_x000D_
}_x000D_
_x000D_
document.body.append(arr.join());
_x000D_
_x000D_
_x000D_

If you really think about it, a forEach is just syntactic sugar for a for loop... So if it's not helping you, just please stop breaking your head against it.

How to set timeout for a line of c# code

You can use the IAsyncResult and Action class/interface to achieve this.

public void TimeoutExample()
{
    IAsyncResult result;
    Action action = () =>
    {
        // Your code here
    };

    result = action.BeginInvoke(null, null);

    if (result.AsyncWaitHandle.WaitOne(10000))
         Console.WriteLine("Method successful.");
    else
         Console.WriteLine("Method timed out.");
}

Vim for Windows - What do I type to save and exit from a file?

Use:

:wq!

The exclamation mark is used for overriding read-only mode.

AngularJS ng-click stopPropagation

In case that you're using a directive like me this is how it works when you need the two data way binding for example after updating an attribute in any model or collection:

angular.module('yourApp').directive('setSurveyInEditionMode', setSurveyInEditionMode)

function setSurveyInEditionMode() {
  return {
    restrict: 'A',
    link: function(scope, element, $attributes) {
      element.on('click', function(event){
        event.stopPropagation();
        // In order to work with stopPropagation and two data way binding
        // if you don't use scope.$apply in my case the model is not updated in the view when I click on the element that has my directive
        scope.$apply(function () {
          scope.mySurvey.inEditionMode = true;
          console.log('inside the directive')
        });
      });
    }
  }
}

Now, you can easily use it in any button, link, div, etc. like so:

<button set-survey-in-edition-mode >Edit survey</button>

How to load external webpage in WebView

activity_main.xml:

<?xml version="1.0" encoding="utf-8"?>
<androidx.constraintlayout.widget.ConstraintLayout xmlns:android="http://schemas.android.com/apk/res/android"
    xmlns:app="http://schemas.android.com/apk/res-auto"
    xmlns:tools="http://schemas.android.com/tools"
    android:layout_width="match_parent"
    android:layout_height="match_parent"
    tools:context=".MainActivity">
    <WebView
        android:id="@+id/webView"
        android:layout_width="0dp"
        android:layout_height="0dp"
        app:layout_constraintBottom_toBottomOf="parent"
        app:layout_constraintEnd_toEndOf="parent"
        app:layout_constraintStart_toStartOf="parent"
        app:layout_constraintTop_toTopOf="parent" />

</androidx.constraintlayout.widget.ConstraintLayout>

MainActivity.java:

package com.example.myapplication;

import androidx.appcompat.app.AppCompatActivity;

import android.os.Bundle;
import android.webkit.WebView;
import android.webkit.WebViewClient;

public class MainActivity extends AppCompatActivity {
    private class MyWebViewClient extends WebViewClient {
        @Override
        public boolean shouldOverrideUrlLoading(WebView view, String url) {
            view.loadUrl(url);
            return true;
        }
    }
    WebView webView;
    @Override
    protected void onCreate(Bundle savedInstanceState) {
        super.onCreate(savedInstanceState);
        setContentView(R.layout.activity_main);

        webView = findViewById(R.id.webView);
        webView .loadUrl("http://www.google.com");
        webView.setWebViewClient(new MyWebViewClient());
    }
}

AndroidManifest.xml: (add uses-permission and android:usesCleartextTraffic)

<?xml version="1.0" encoding="utf-8"?>
<manifest xmlns:android="http://schemas.android.com/apk/res/android"
    package="com.example.myapplication">

    <uses-permission android:name="android.permission.INTERNET" />

    <application
        android:usesCleartextTraffic="true"
        android:allowBackup="true"
        android:icon="@mipmap/ic_launcher"
        android:label="@string/app_name"
        android:roundIcon="@mipmap/ic_launcher_round"
        android:supportsRtl="true"
        android:theme="@style/Theme.MyApplication">
        <activity android:name=".MainActivity">
            <intent-filter>
                <action android:name="android.intent.action.MAIN" />
                <category android:name="android.intent.category.LAUNCHER" />
            </intent-filter>
        </activity>
    </application>

</manifest>

How can I create an Asynchronous function in Javascript?

Here is a function that takes in another function and outputs a version that runs async.

var async = function (func) {
  return function () {
    var args = arguments;
    setTimeout(function () {
      func.apply(this, args);
    }, 0);
  };
};

It is used as a simple way to make an async function:

var anyncFunction = async(function (callback) {
    doSomething();
    callback();
});

This is different from @fider's answer because the function itself has its own structure (no callback added on, it's already in the function) and also because it creates a new function that can be used.

How to view query error in PDO PHP

I'm guessing that your complaint is that the exception is not firing. PDO is most likely configured to not throw exceptions. Enable them with this:

$db->setAttribute(PDO::ATTR_ERRMODE, PDO::ERRMODE_EXCEPTION); 

Tomcat manager/html is not available?

My problem/solution is very embarrassing but who knows... perhaps it happened to someone else:

My solution: Turn off proxy

For the past two hours I've been wondering why my manager would not load. (the root was cached so it loaded). I had set the browser's proxy to proxy traffic to my house. :/

How to get index of an item in java.util.Set

A small static custom method in a Util class would help:

 public static int getIndex(Set<? extends Object> set, Object value) {
   int result = 0;
   for (Object entry:set) {
     if (entry.equals(value)) return result;
     result++;
   }
   return -1;
 }

If you need/want one class that is a Set and offers a getIndex() method, I strongly suggest to implement a new Set and use the decorator pattern:

 public class IndexAwareSet<T> implements Set {
   private Set<T> set;
   public IndexAwareSet(Set<T> set) {
     this.set = set;
   }

   // ... implement all methods from Set and delegate to the internal Set

   public int getIndex(T entry) {
     int result = 0;
     for (T entry:set) {
       if (entry.equals(value)) return result;
       result++;
     }
     return -1;
   }
 }

Recommended way to insert elements into map

Use insert if you want to insert a new element. insert will not overwrite an existing element, and you can verify that there was no previously exising element:

if ( !myMap.insert( std::make_pair( key, value ) ).second ) {
    //  Element already present...
}

Use [] if you want to overwrite a possibly existing element:

myMap[ key ] = value;
assert( myMap.find( key )->second == value ); // post-condition

This form will overwrite any existing entry.

WARNING in budgets, maximum exceeded for initial

Open angular.json file and find budgets keyword.

It should look like:

    "budgets": [
       {
          "type": "initial",
          "maximumWarning": "2mb",
          "maximumError": "5mb"
       }
    ]

As you’ve probably guessed you can increase the maximumWarning value to prevent this warning, i.e.:

    "budgets": [
       {
          "type": "initial",
          "maximumWarning": "4mb", <===
          "maximumError": "5mb"
       }
    ]

What does budgets mean?

A performance budget is a group of limits to certain values that affect site performance, that may not be exceeded in the design and development of any web project.

In our case budget is the limit for bundle sizes.

See also:

Access Tomcat Manager App from different host

For Tomcat v8.5.4 and above, the file <tomcat>/webapps/manager/META-INF/context.xml has been adjusted:

<Context antiResourceLocking="false" privileged="true" >
    <Valve className="org.apache.catalina.valves.RemoteAddrValve"
         allow="127\.\d+\.\d+\.\d+|::1|0:0:0:0:0:0:0:1" />
</Context>

Change this file to comment the Valve:

<Context antiResourceLocking="false" privileged="true" >
    <!--
    <Valve className="org.apache.catalina.valves.RemoteAddrValve"
         allow="127\.\d+\.\d+\.\d+|::1|0:0:0:0:0:0:0:1" />
    -->
</Context>

After that, refresh your browser (not need to restart Tomcat), you can see the manager page.

Fatal error: Call to a member function prepare() on null

You can try/catch PDOExceptions (your configs could differ but the important part is the try/catch):

try {
        $dbh = new PDO(
            DB_TYPE . ':host=' . DB_HOST . ';dbname=' . DB_NAME . ';charset=' . DB_CHARSET,
            DB_USER,
            DB_PASS,
            [
                PDO::ATTR_PERSISTENT            => true,
                PDO::ATTR_ERRMODE               => PDO::ERRMODE_EXCEPTION,
                PDO::MYSQL_ATTR_INIT_COMMAND    => 'SET NAMES ' . DB_CHARSET . ' COLLATE ' . DB_COLLATE

            ]
        );
    } catch ( PDOException $e ) {
        echo 'ERROR!';
        print_r( $e );
    }

The print_r( $e ); line will show you everything you need, for example I had a recent case where the error message was like unknown database 'my_db'.

How to force a checkbox and text on the same line?

It wont break if you wrap each item in a div. Check out my fiddle with the link below. I made the width of the fieldset 125px and made each item 50px wide. You'll see the label and checkbox remain side by side on a new line and don't break.

<fieldset>
<div class="item">
    <input type="checkbox" id="a">
    <label for="a">a</label>
</div>
<div class="item">
   <input type="checkbox" id="b">
<!-- depending on width, a linebreak can occur here. -->
    <label for="b">bgf bh fhg fdg hg dg gfh dfgh</label>
</div>
<div class="item">
    <input type="checkbox" id="c">
    <label for="c">c</label>
</div>
</fieldset>

http://jsfiddle.net/t5dwp7pg/1/

What is aria-label and how should I use it?

If you wants to know how aria-label helps you practically .. then follow the steps ... you will get it by your own ..

Create a html page having below code

<!DOCTYPE html>
<html lang="en">
<head>
    <title></title>
</head>
<body>
    <button title="Close"> X </button>
    <br />
    <br />
    <br />
    <br />
    <button aria-label="Back to the page" title="Close" > X </button>
</body>
</html>

Now, you need a virtual screen reader emulator which will run on browser to observe the difference. So, chrome browser users can install chromevox extension and mozilla users can go with fangs screen reader addin

Once done with installation, put headphones in your ears, open the html page and make focus on both button(by pressing tab) one-by-one .. and you can hear .. focusing on first x button .. will tell you only x button .. but in case of second x button .. you will hear back to the page button only..

i hope you got it well now!!

How to add class active on specific li on user click with jQuery

Slightly off topic but having arrived here while developing an Angular2 app I would like to share that Angular2 automatically adds the class "router-link-active" to active router links such as this one:

<li><a [routerLink]="['Dashboard']">Dashboard</a></li>

You can therefore easily style such links using CSS:

.router-link-active {
    color: red;
}

How do I create a SQL table under a different schema?

                           create a database schema in SQL Server 2008
1. Navigate to Security > Schemas
2. Right click on Schemas and select New Schema
3. Complete the details in the General tab for the new schema. Like, the schema name is "MySchema" and the schema owner is "Admin".
4. Add users to the schema as required and set their permissions:
5. Add any extended properties (via the Extended Properties tab)
6. Click OK.
                           Add a Table to the New Schema "MySchema"
1. In Object Explorer, right click on the table name and select "Design":
2. Changing database schema for a table in SQL Server Management Studio
3. From Design view, press F4 to display the Properties window.
4. From the Properties window, change the schema to the desired schema:
5. Close Design View by right clicking the tab and selecting "Close":
6. Closing Design View
7. Click "OK" when prompted to save
8. Your table has now been transferred to the "MySchema" schema.

Refresh the Object Browser view To confirm the changes
Done

Python + Regex: AttributeError: 'NoneType' object has no attribute 'groups'

You are getting AttributeError because you're calling groups on None, which hasn't any methods.

regex.search returning None means the regex couldn't find anything matching the pattern from supplied string.

when using regex, it is nice to check whether a match has been made:

Result = re.search(SearchStr, htmlString)

if Result:
    print Result.groups()

Adding timestamp to a filename with mv in BASH

mv server.log logs/$(date -d "today" +"%Y%m%d%H%M").log

How do I edit SSIS package files?

I prefer to use :

(from SSDT visual studio just opened) file> open > file > locate dtsx file > open

then you can edit work and save

SQL Client for Mac OS X that works with MS SQL Server

Squirrel SQL is a Java based SQL client, that I've had good experience with on Windows and Linux. Since it's Java, it should do the trick.

It's open source. You can run multiple sessions with multiple databases concurrently.

How to remove constraints from my MySQL table?

I had the same problem and I got to solve with this code:

ALTER TABLE `table_name` DROP FOREIGN KEY `id_name_fk`;
ALTER TABLE `table_name` DROP INDEX  `id_name_fk`;

Passing multiple variables to another page in url

Pretty simple but another said you dont pass session variables through the url bar 1.You dont need to because a session is passed throughout the whole website from header when you put in header file 2.security risks
Here is first page code

$url = "http://localhost/main.php?email=" . urlencode($email_address) . "&eventid=" . urlencode($event_id);

2nd page when getting the variables from the url bar is:

if(isset($_GET['email']) && !empty($_GET['email']) AND isset($_GET['eventid']) && !empty($_GET['eventid'])){ ////do whatever here }

Now if you want to do it the proper way of using the session you created then ignore my above code and call the session variables on the second page for instance create a session on the first page lets say for example:

 $_SESSION['WEB_SES'] = $email_address . "^" . $event_id;

obvious that you would have already assigned values to the session variables in the code above, you can call the session name whatever you want to i just used the example web_ses , the second page all you need to do is start a session and see if the session is there and check the variables and do whatever with them, example:

 session_start();
 if (isset($_SESSION['WEB_SES'])){
 $Array = explode("^", $_SESSION['WEB_SES']);
 $email = $Array[0];
 $event_id = $Array[1]
 echo "$email";
 echo "$event_id";
 }

Like I said before the good thing about sessions are they can be carried throughout the entire website if this type of code in put in the header file that gets called upon on all pages that load, you can simple use the variable wherever and whenever. Hope this helps :)

How is AngularJS different from jQuery

  1. While Angular 1 was a framework, Angular 2 is a platform. (ref)

To developers, Angular2 provides some features beyond showing data on screen. For example, using angular2 cli tool can help you "pre-compile" your code and generate necessary javascript code (tree-shaking) to shrink the download size down to 35Kish.

  1. Angular2 emulated Shadow DOM. (ref)

This opens a door for server rendering that can address SEO issue and work with Nativescript etc that don't work on browsers.

AngularJS is a framework. It has following features

  1. Two way data binding
  2. MVW pattern (MVC-ish)
  3. Template
  4. Custom-directive (reusable components, custom markup)
  5. REST-friendly
  6. Deep Linking (set up a link for any dynamic page)
  7. Form Validation
  8. Server Communication
  9. Localization
  10. Dependency injection
  11. Full testing environment (both unit, e2e)

check this presentation and this great introduction

Don't forget to read the official developer guide

Or learn it from these awesome video tutorials

If you want to watch more tutorial video, check out this post, Collection of best 60+ AngularJS tutorials.

You can use jQuery with AngularJS without any issue.

In fact, AngularJS uses jQuery lite in it, which is a great tool.

From FAQ

Does Angular use the jQuery library?

Yes, Angular can use jQuery if it's present in your app when the application is being bootstrapped. If jQuery is not present in your script path, Angular falls back to its own implementation of the subset of jQuery that we call jQLite.

However, don't try to use jQuery to modify the DOM in AngularJS controllers, do it in your directives.

Update:

Angular2 is released. Here is a great list of resource for starters

How to get a value inside an ArrayList java

main class

public class Test {
    public static void main (String [] args){
        Car thisCar= new Car ("Toyota", "$10000", "2003");  
        ArrayList<Car> car= new ArrayList<Car> ();
        car.add(thisCar); 
        processCar(car);
    } 

    public static void processCar(ArrayList<Car> car){
        for(Car c : car){
            System.out.println (c.getPrice());
        }
    }
}

car class

public class Car {
    private String vehicle;
    private String price;
    private String model;

    public Car(String vehicle, String price, String model){
        this.vehicle = vehicle;
        this.model = model;
        this.price = price;
    }

    public String getVehicle() {
        return vehicle;
    }

    public String getPrice() {
        return price;
    }

    public String getModel() {
        return model;
    }  
}

MySQL JOIN ON vs USING?

Database tables

To demonstrate how the USING and ON clauses work, let's assume we have the following post and post_comment database tables, which form a one-to-many table relationship via the post_id Foreign Key column in the post_comment table referencing the post_id Primary Key column in the post table:

SQL USING vs ON clauses table relationship

The parent post table has 3 rows:

| post_id | title     |
|---------|-----------|
| 1       | Java      |
| 2       | Hibernate |
| 3       | JPA       |

and the post_comment child table has the 3 records:

| post_comment_id | review    | post_id |
|-----------------|-----------|---------|
| 1               | Good      | 1       |
| 2               | Excellent | 1       |
| 3               | Awesome   | 2       |

The JOIN ON clause using a custom projection

Traditionally, when writing an INNER JOIN or LEFT JOIN query, we happen to use the ON clause to define the join condition.

For example, to get the comments along with their associated post title and identifier, we can use the following SQL projection query:

SELECT
   post.post_id,
   title,
   review
FROM post
INNER JOIN post_comment ON post.post_id = post_comment.post_id
ORDER BY post.post_id, post_comment_id

And, we get back the following result set:

| post_id | title     | review    |
|---------|-----------|-----------|
| 1       | Java      | Good      |
| 1       | Java      | Excellent |
| 2       | Hibernate | Awesome   |

The JOIN USING clause using a custom projection

When the Foreign Key column and the column it references have the same name, we can use the USING clause, like in the following example:

SELECT
  post_id,
  title,
  review
FROM post
INNER JOIN post_comment USING(post_id)
ORDER BY post_id, post_comment_id

And, the result set for this particular query is identical to the previous SQL query that used the ON clause:

| post_id | title     | review    |
|---------|-----------|-----------|
| 1       | Java      | Good      |
| 1       | Java      | Excellent |
| 2       | Hibernate | Awesome   |

The USING clause works for Oracle, PostgreSQL, MySQL, and MariaDB. SQL Server doesn't support the USING clause, so you need to use the ON clause instead.

The USING clause can be used with INNER, LEFT, RIGHT, and FULL JOIN statements.

SQL JOIN ON clause with SELECT *

Now, if we change the previous ON clause query to select all columns using SELECT *:

SELECT *
FROM post
INNER JOIN post_comment ON post.post_id = post_comment.post_id
ORDER BY post.post_id, post_comment_id

We are going to get the following result set:

| post_id | title     | post_comment_id | review    | post_id |
|---------|-----------|-----------------|-----------|---------|
| 1       | Java      | 1               | Good      | 1       |
| 1       | Java      | 2               | Excellent | 1       |
| 2       | Hibernate | 3               | Awesome   | 2       |

As you can see, the post_id is duplicated because both the post and post_comment tables contain a post_id column.

SQL JOIN USING clause with SELECT *

On the other hand, if we run a SELECT * query that features the USING clause for the JOIN condition:

SELECT *
FROM post
INNER JOIN post_comment USING(post_id)
ORDER BY post_id, post_comment_id

We will get the following result set:

| post_id | title     | post_comment_id | review    |
|---------|-----------|-----------------|-----------|
| 1       | Java      | 1               | Good      |
| 1       | Java      | 2               | Excellent |
| 2       | Hibernate | 3               | Awesome   |

You can see that this time, the post_id column is deduplicated, so there is a single post_id column being included in the result set.

Conclusion

If the database schema is designed so that Foreign Key column names match the columns they reference, and the JOIN conditions only check if the Foreign Key column value is equal to the value of its mirroring column in the other table, then you can employ the USING clause.

Otherwise, if the Foreign Key column name differs from the referencing column or you want to include a more complex join condition, then you should use the ON clause instead.

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.

Read and write a text file in typescript

import * as fs from 'fs';
import * as path from 'path';

fs.readFile(path.join(__dirname, "filename.txt"), (err, data) => {
    if (err) throw err;
    console.log(data);
})

EDIT:

consider the project structure:

../readfile/
+-- filename.txt
+-- src
    +-- index.js
    +-- index.ts

consider the index.ts:

import * as fs from 'fs';
import * as path from 'path';

function lookFilesInDirectory(path_directory) {
    fs.stat(path_directory, (err, stat) => {
        if (!err) {
            if (stat.isDirectory()) {
                console.log(path_directory)
                fs.readdirSync(path_directory).forEach(file => {
                    console.log(`\t${file}`);
                });
                console.log();
            }
        }
    });
}

let path_view = './';
lookFilesInDirectory(path_view);
lookFilesInDirectory(path.join(__dirname, path_view));

if you have in the readfile folder and run tsc src/index.ts && node src/index.js, the output will be:

./
        filename.txt
        src

/home/andrei/scripts/readfile/src/
        index.js
        index.ts

that is, it depends on where you run the node.

the __dirname is directory name of the current module.

Loading state button in Bootstrap 3

You need to detect the click from js side, your HTML remaining same. Note: this method is deprecated since v3.5.5 and removed in v4.

$("button").click(function() {
    var $btn = $(this);
    $btn.button('loading');
    // simulating a timeout
    setTimeout(function () {
        $btn.button('reset');
    }, 1000);
});

Also, don't forget to load jQuery and Bootstrap js (based on jQuery) file in your page.

JSFIDDLE

Official Documentation

Rename all files in a folder with a prefix in a single command

If your filenames contain no whitepace and you don't have any subdirectories, you can use a simple for loop:

$ for FILENAME in *; do mv $FILENAME Unix_$FILENAME; done 

Otherwise use the convenient rename command (which is a perl script) - although it might not be available out of the box on every Unix (e.g. OS X doesn't come with rename).

A short overview at debian-administration.org:

If your filenames contain whitespace it's easier to use find, on Linux the following should work:

$ find . -type f -name '*' -printf "echo mv '%h/%f' '%h/Unix_%f\n'" | sh

On BSD systems, there is no -printf option, unfortunately. But GNU findutils should be installable (on e.g. Mac OS X with brew install findutils).

$ gfind . -type f -name '*' -printf "mv \"%h/%f\" \"%h/Unix_%f\"\n" | sh

node and Error: EMFILE, too many open files

You're reading too many files. Node reads files asynchronously, it'll be reading all files at once. So you're probably reading the 10240 limit.

See if this works:

var fs = require('fs')
var events = require('events')
var util = require('util')
var path = require('path')

var FsPool = module.exports = function(dir) {
    events.EventEmitter.call(this)
    this.dir = dir;
    this.files = [];
    this.active = [];
    this.threads = 1;
    this.on('run', this.runQuta.bind(this))
};
// So will act like an event emitter
util.inherits(FsPool, events.EventEmitter);

FsPool.prototype.runQuta = function() {
    if(this.files.length === 0 && this.active.length === 0) {
        return this.emit('done');
    }
    if(this.active.length < this.threads) {
        var name = this.files.shift()

        this.active.push(name)
        var fileName = path.join(this.dir, name);
        var self = this;
        fs.stat(fileName, function(err, stats) {
            if(err)
                throw err;
            if(stats.isFile()) {
                fs.readFile(fileName, function(err, data) {
                    if(err)
                        throw err;
                    self.active.splice(self.active.indexOf(name), 1)
                    self.emit('file', name, data);
                    self.emit('run');

                });
            } else {
                self.active.splice(self.active.indexOf(name), 1)
                self.emit('dir', name);
                self.emit('run');
            }
        });
    }
    return this
};
FsPool.prototype.init = function() {
    var dir = this.dir;
    var self = this;
    fs.readdir(dir, function(err, files) {
        if(err)
            throw err;
        self.files = files
        self.emit('run');
    })
    return this
};
var fsPool = new FsPool(__dirname)

fsPool.on('file', function(fileName, fileData) {
    console.log('file name: ' + fileName)
    console.log('file data: ', fileData.toString('utf8'))

})
fsPool.on('dir', function(dirName) {
    console.log('dir name: ' + dirName)

})
fsPool.on('done', function() {
    console.log('done')
});
fsPool.init()

Force download a pdf link using javascript/ajax/jquery

Here is the perfect example of downloading a file using javaScript.

Usage: download_file(fileURL, fileName);

Scrollbar without fixed height/Dynamic height with scrollbar

A quick, clean approach using very little JS and CSS padding: http://jsfiddle.net/benjamincharity/ZcTsT/14/

var headerHeight = $('#header').height(),
    footerHeight = $('#footer').height();

$('#content').css({
  'padding-top': headerHeight,
  'padding-bottom': footerHeight
});

How to get device make and model on iOS?

EITHER try this library: http://github.com/erica/uidevice-extension/ (by Erica Sadun). (The library is 7-8 years old, and hence is obsolete)

(Sample Code):

    [[UIDevice currentDevice] platformType]   // ex: UIDevice4GiPhone
    [[UIDevice currentDevice] platformString] // ex: @"iPhone 4G"

OR You can use this method:

You can get the device model number using uname from sys/utsname.h. For example:

Objective-C

    #import <sys/utsname.h> // import it in your header or implementation file.

    NSString* deviceName()
    {
        struct utsname systemInfo;
        uname(&systemInfo);
    
        return [NSString stringWithCString:systemInfo.machine
                                  encoding:NSUTF8StringEncoding];
    }

Swift 3

    extension UIDevice {
        var modelName: String {
            var systemInfo = utsname()
            uname(&systemInfo)
            let machineMirror = Mirror(reflecting: systemInfo.machine)
            let identifier = machineMirror.children.reduce("") { identifier, element in
                guard let value = element.value as? Int8, value != 0 else { return identifier }
                return identifier + String(UnicodeScalar(UInt8(value)))
            }
            return identifier
        }
    }

    print(UIDevice.current.modelName)

The result should be:

// Output on a simulator
@"i386"      on 32-bit Simulator
@"x86_64"    on 64-bit Simulator

// Output on an iPhone
@"iPhone1,1" on iPhone
@"iPhone1,2" on iPhone 3G
@"iPhone2,1" on iPhone 3GS
@"iPhone3,1" on iPhone 4 (GSM)
@"iPhone3,2" on iPhone 4 (GSM Rev A)
@"iPhone3,3" on iPhone 4 (CDMA/Verizon/Sprint)
@"iPhone4,1" on iPhone 4S
@"iPhone5,1" on iPhone 5 (model A1428, AT&T/Canada)
@"iPhone5,2" on iPhone 5 (model A1429, everything else)
@"iPhone5,3" on iPhone 5c (model A1456, A1532 | GSM)
@"iPhone5,4" on iPhone 5c (model A1507, A1516, A1526 (China), A1529 | Global)
@"iPhone6,1" on iPhone 5s (model A1433, A1533 | GSM)
@"iPhone6,2" on iPhone 5s (model A1457, A1518, A1528 (China), A1530 | Global)
@"iPhone7,1" on iPhone 6 Plus
@"iPhone7,2" on iPhone 6
@"iPhone8,1" on iPhone 6S
@"iPhone8,2" on iPhone 6S Plus
@"iPhone8,4" on iPhone SE
@"iPhone9,1" on iPhone 7 (CDMA)
@"iPhone9,3" on iPhone 7 (GSM)
@"iPhone9,2" on iPhone 7 Plus (CDMA)
@"iPhone9,4" on iPhone 7 Plus (GSM)
@"iPhone10,1" on iPhone 8 (CDMA)
@"iPhone10,4" on iPhone 8 (GSM)
@"iPhone10,2" on iPhone 8 Plus (CDMA)
@"iPhone10,5" on iPhone 8 Plus (GSM)
@"iPhone10,3" on iPhone X (CDMA)
@"iPhone10,6" on iPhone X (GSM)
@"iPhone11,2" on iPhone XS
@"iPhone11,4" on iPhone XS Max
@"iPhone11,6" on iPhone XS Max China
@"iPhone11,8" on iPhone XR
@"iPhone12,1" on iPhone 11
@"iPhone12,3" on iPhone 11 Pro
@"iPhone12,5" on iPhone 11 Pro Max
@"iPhone12,8" on iPhone SE (2nd Gen)
@"iPhone13,1" on iPhone 12 Mini
@"iPhone13,2" on iPhone 12
@"iPhone13,3" on iPhone 12 Pro
@"iPhone13,4" on iPhone 12 Pro Max

//iPad 1
@"iPad1,1" on iPad - Wifi (model A1219)
@"iPad1,2" on iPad - Wifi + Cellular (model A1337)

//iPad 2
@"iPad2,1" - Wifi (model A1395)
@"iPad2,2" - GSM (model A1396)
@"iPad2,3" - 3G (model A1397)
@"iPad2,4" - Wifi (model A1395)

// iPad Mini
@"iPad2,5" - Wifi (model A1432)
@"iPad2,6" - Wifi + Cellular (model  A1454)
@"iPad2,7" - Wifi + Cellular (model  A1455)

//iPad 3
@"iPad3,1" - Wifi (model A1416)
@"iPad3,2" - Wifi + Cellular (model  A1403)
@"iPad3,3" - Wifi + Cellular (model  A1430)

//iPad 4
@"iPad3,4" - Wifi (model A1458)
@"iPad3,5" - Wifi + Cellular (model  A1459)
@"iPad3,6" - Wifi + Cellular (model  A1460)

//iPad AIR
@"iPad4,1" - Wifi (model A1474)
@"iPad4,2" - Wifi + Cellular (model A1475)
@"iPad4,3" - Wifi + Cellular (model A1476)

// iPad Mini 2
@"iPad4,4" - Wifi (model A1489)
@"iPad4,5" - Wifi + Cellular (model A1490)
@"iPad4,6" - Wifi + Cellular (model A1491)

// iPad Mini 3
@"iPad4,7" - Wifi (model A1599)
@"iPad4,8" - Wifi + Cellular (model A1600)
@"iPad4,9" - Wifi + Cellular (model A1601)

// iPad Mini 4
@"iPad5,1" - Wifi (model A1538)
@"iPad5,2" - Wifi + Cellular (model A1550)

//iPad AIR 2
@"iPad5,3" - Wifi (model A1566)
@"iPad5,4" - Wifi + Cellular (model A1567)

// iPad PRO 9.7"
@"iPad6,3" - Wifi (model A1673)
@"iPad6,4" - Wifi + Cellular (model A1674)
@"iPad6,4" - Wifi + Cellular (model A1675)

//iPad PRO 12.9"
@"iPad6,7" - Wifi (model A1584)
@"iPad6,8" - Wifi + Cellular (model A1652)

//iPad (5th generation)
@"iPad6,11" - Wifi (model A1822)
@"iPad6,12" - Wifi + Cellular (model A1823)
         
//iPad PRO 12.9" (2nd Gen)
@"iPad7,1" - Wifi (model A1670)
@"iPad7,2" - Wifi + Cellular (model A1671)
@"iPad7,2" - Wifi + Cellular (model A1821)
         
//iPad PRO 10.5"
@"iPad7,3" - Wifi (model A1701)
@"iPad7,4" - Wifi + Cellular (model A1709)

// iPad (6th Gen)
@"iPad7,5" - WiFi
@"iPad7,6" - WiFi + Cellular

// iPad (7th Gen)
@"iPad7,11" - WiFi
@"iPad7,12" - WiFi + Cellular

//iPad PRO 11"
@"iPad8,1" - WiFi
@"iPad8,2" - 1TB, WiFi
@"iPad8,3" - WiFi + Cellular
@"iPad8,4" - 1TB, WiFi + Cellular

//iPad PRO 12.9" (3rd Gen)
@"iPad8,5" - WiFi
@"iPad8,6" - 1TB, WiFi
@"iPad8,7" - WiFi + Cellular
@"iPad8,8" - 1TB, WiFi + Cellular

//iPad PRO 11" (2nd Gen)
@"iPad8,9" - WiFi
@"iPad8,10" - 1TB, WiFi

//iPad PRO 12.9" (4th Gen)
@"iPad8,11" - (WiFi)
@"iPad8,12" - (WiFi+Cellular)

// iPad mini 5th Gen
@"iPad11,1" - WiFi
@"iPad11,2" - Wifi  + Cellular

// iPad Air 3rd Gen
@"iPad11,3" - Wifi 
@"iPad11,4" - Wifi  + Cellular

// iPad (8th Gen)
@"iPad11,6" - iPad 8th Gen (WiFi)
@"iPad11,7" - iPad 8th Gen (WiFi+Cellular)

// iPad Air 4th Gen
@"iPad13,1" - iPad air 4th Gen (WiFi)
@"iPad13,2" - iPad air 4th Gen (WiFi+Cellular)

//iPod Touch
@"iPod1,1"   on iPod Touch
@"iPod2,1"   on iPod Touch Second Generation
@"iPod3,1"   on iPod Touch Third Generation
@"iPod4,1"   on iPod Touch Fourth Generation
@"iPod5,1"   on iPod Touch 5th Generation
@"iPod7,1"   on iPod Touch 6th Generation
@"iPod9,1"   on iPod Touch 7th Generation

// Apple Watch
@"Watch1,1" on Apple Watch 38mm case
@"Watch1,2" on Apple Watch 38mm case
@"Watch2,6" on Apple Watch Series 1 38mm case
@"Watch2,7" on Apple Watch Series 1 42mm case
@"Watch2,3" on Apple Watch Series 2 38mm case
@"Watch2,4" on Apple Watch Series 2 42mm case
@"Watch3,1" on Apple Watch Series 3 38mm case (GPS+Cellular)
@"Watch3,2" on Apple Watch Series 3 42mm case (GPS+Cellular)
@"Watch3,3" on Apple Watch Series 3 38mm case (GPS)
@"Watch3,4" on Apple Watch Series 3 42mm case (GPS)
@"Watch4,1" on Apple Watch Series 4 40mm case (GPS)
@"Watch4,2" on Apple Watch Series 4 44mm case (GPS)
@"Watch4,3" on Apple Watch Series 4 40mm case (GPS+Cellular)
@"Watch4,4" on Apple Watch Series 4 44mm case (GPS+Cellular)
@"Watch5,1" on Apple Watch Series 5 40mm case (GPS)
@"Watch5,2" on Apple Watch Series 5 44mm case (GPS)
@"Watch5,3" on Apple Watch Series 5 40mm case (GPS+Cellular)
@"Watch5,4" on Apple Watch Series 5 44mm case (GPS+Cellular)
@"Watch5,9" on Apple Watch SE 40mm case (GPS)
@"Watch5,10" on Apple Watch SE 44mm case (GPS)
@"Watch5,11" on Apple Watch SE 40mm case (GPS+Cellular)
@"Watch5,12" on Apple Watch SE 44mm case (GPS+Cellular)
@"Watch6,1" on Apple Watch Series 6 40mm case (GPS)
@"Watch6,2" on Apple Watch Series 6 44mm case (GPS)
@"Watch6,3" on Apple Watch Series 6 40mm case (GPS+Cellular)
@"Watch6,4" on Apple Watch Series 6 44mm case (GPS+Cellular)

2D arrays in Python

If you want to do some serious work with arrays then you should use the numpy library. This will allow you for example to do vector addition and matrix multiplication, and for large arrays it is much faster than Python lists.

However, numpy requires that the size is predefined. Of course you can also store numpy arrays in a list, like:

import numpy as np
vec_list = [np.zeros((3,)) for _ in range(10)]
vec_list.append(np.array([1,2,3]))
vec_sum = vec_list[0] + vec_list[1]  # possible because we use numpy
print vec_list[10][2]  # prints 3

But since your numpy arrays are pretty small I guess there is some overhead compared to using a tuple. It all depends on your priorities.

See also this other question, which is pretty similar (apart from the variable size).

How do I negate a condition in PowerShell?

if you don't like the double brackets or you don't want to write a function, you can just use a variable.

$path = Test-Path C:\Code
if (!$path) {
    write "it doesn't exist!"
}

Angularjs -> ng-click and ng-show to show a div

<html>
<head>
    <title></title>
</head>
<body>
    <script type="text/javascript" src="https://ajax.googleapis.com/ajax/libs/angularjs/1.3.9/angular.min.js"></script>
    <script type="text/javascript">
        var app = angular.module('MyApp', [])
        app.controller('MyController', function ($scope) {
            //This will hide the DIV by default.
            $scope.IsVisible = false;
            $scope.ShowHide = function () {
                //If DIV is visible it will be hidden and vice versa.
                $scope.IsVisible = $scope.IsVisible ? false : true;
            }
        });
    </script>
    <div ng-app="MyApp" ng-controller="MyController">
        <input type="button" value="Show Hide DIV" ng-click="ShowHide()" />
        <br />
        <br />
        <div ng-show = "IsVisible">My DIV</div>
    </div>
</body>
</html>

EXAMPLE : - http://jsfiddle.net/mafais/4WK7R/380/

How to Delete a directory from Hadoop cluster which is having comma(,) in its name?

Have you tried :

hadoop dfs -rmr hdfs://host:port/Navi/MyDir\,\ Name?

Errors in pom.xml with dependencies (Missing artifact...)

SIMPLE..

First check with the closing tag of project. It should be placed after all the dependency tags are closed.This way I solved my error. --Sush happy coding :)

Convert double to string

a = 0.000006;
b = 6;
c = a/b;

textbox.Text = c.ToString("0.000000");

As you requested:

textbox.Text = c.ToString("0.######");

This will only display out to the 6th decimal place if there are 6 decimals to display.

Use cases for the 'setdefault' dict method

defaultdict is great when the default value is static, like a new list, but not so much if it's dynamic.

For example, I need a dictionary to map strings to unique ints. defaultdict(int) will always use 0 for the default value. Likewise, defaultdict(intGen()) always produces 1.

Instead, I used a regular dict:

nextID = intGen()
myDict = {}
for lots of complicated stuff:
    #stuff that generates unpredictable, possibly already seen str
    strID = myDict.setdefault(myStr, nextID())

Note that dict.get(key, nextID()) is insufficient because I need to be able to refer to these values later as well.

intGen is a tiny class I build that automatically increments an int and returns its value:

class intGen:
    def __init__(self):
        self.i = 0

    def __call__(self):
        self.i += 1
    return self.i

If someone has a way to do this with defaultdict I'd love to see it.

Angular 2 Dropdown Options Default Value

You Can approach this way:

<option *ngFor="let workout of workouts" [value]="workout.name">{{workout.name}}</option>

or this way:

  <option *ngFor="let workout of workouts" [attr.value]="workout.name" [attr.selected]="workout.name == 'leg' ? true : null">{{workout.name}}</option>

or you can set default value this way:

<option [value]="null">Please Select</option>
<option *ngFor="let workout of workouts" [value]="workout.name">{{workout.name}}</option>

or

<option [value]="0">Please Select</option>
<option *ngFor="let workout of workouts" [value]="workout.name">{{workout.name}}</option>

pass JSON to HTTP POST Request

I think the following should work:

// fire request
request({
    url: url,
    method: "POST",
    json: requestData
}, ...

In this case, the Content-type: application/json header is automatically added.

Reading value from console, interactively

I believe this deserves a modern async-await answer, assuming node >= 7.x is used.

The answer still uses ReadLine::question but wraps it so that the while (done) {} is possible, which is something the OP asks about explicitely.

var cl = readln.createInterface( process.stdin, process.stdout );
var question = function(q) {
    return new Promise( (res, rej) => {
        cl.question( q, answer => {
            res(answer);
        })
    });
};

and then an example usage

(async function main() {
    var answer;
    while ( answer != 'yes' ) {
        answer = await question('Are you sure? ');
    }
    console.log( 'finally you are sure!');
})();

leads to following conversation

Are you sure? no
Are you sure? no
Are you sure? yes
finally you are sure!

Edit. In order to properly end the input, call

cl.close();

at the end of the script.

How to make an Android Spinner with initial text "Select One"?

here's a simple one

    private boolean isFirst = true;
private void setAdapter() {
    final ArrayList<String> spinnerArray = new ArrayList<String>();     
    spinnerArray.add("Select your option");
    spinnerArray.add("Option 1");
    spinnerArray.add("Option 2");
    spin.setOnItemSelectedListener(new AdapterView.OnItemSelectedListener() {
        @Override
        public void onItemSelected(AdapterView<?> parentView, View selectedItemView, int position, long id) {
            TextView tv = (TextView)selectedItemView;
            String res = tv.getText().toString().trim();
            if (res.equals("Option 1")) {
            //do Something
        } else if (res.equals("Option 2")) {
            //do Something else
        }
        }

        @Override
        public void onNothingSelected(AdapterView<?> parentView) { }

    });

    ArrayAdapter<String> adapter = new ArrayAdapter<String>(this, R.layout.my_spinner_style,spinnerArray) {
         public View getView(int position, View convertView, ViewGroup parent) {
             View v = super.getView(position, convertView, parent);
             int height = (int) TypedValue.applyDimension(TypedValue.COMPLEX_UNIT_DIP, 25, getResources().getDisplayMetrics());                  
             ((TextView) v).setTypeface(tf2);
             ((TextView) v).getLayoutParams().height = height;
             ((TextView) v).setGravity(Gravity.CENTER);
             ((TextView) v).setTextSize(TypedValue.COMPLEX_UNIT_SP, 19);
             ((TextView) v).setTextColor(Color.WHITE);
             return v;
         }

         public View getDropDownView(int position, View convertView,
                 ViewGroup parent) {
             if (isFirst) {
                 isFirst = false;
                 spinnerArray.remove(0);
             }
             View v = super.getDropDownView(position, convertView, parent);                  
             ((TextView) v).setTextColor(Color.argb(255, 70, 70, 70));
             ((TextView) v).setTypeface(tf2);
             ((TextView) v).setGravity(Gravity.CENTER);
             return v;
         }
     };
     spin.setAdapter(adapter);
}

What is SOA "in plain english"?

Only one suggestion:-

Read SOA Concepts, Technology and Design by Thomas Erl.

It has very beautifully given the details about SOA in plain English and with case studies.

Angular cli generate a service and include the provider in one step

Angular 6+ Singleton Services

The recommended approach for a singleton service for Angular 6 and beyond is :

import { Injectable } from '@angular/core';

@Injectable({
  providedIn: 'root',
})
export class UserService {
}

In fact the CLI --module switch doesn't even exist any more for registering a service at the app level because it doesn't need to modify app.module.ts anymore.

This will create the above code, without needing to specify a module.

ng g s services/user

So if you don't want your service to be a singleton you must remove the providedIn code yourself - and then add it manually to providers for a component or lazy loaded module. Doesn't look like there is currently a switch to not generate the providedIn: 'root' part so you need to manually remove it.

Going through a text file line by line in C

So many problems in so few lines. I probably forget some:

  • argv[0] is the program name, not the first argument;
  • if you want to read in a variable, you have to allocate its memory
  • one never loops on feof, one loops on an IO function until it fails, feof then serves to determinate the reason of failure,
  • sscanf is there to parse a line, if you want to parse a file, use fscanf,
  • "%s" will stop at the first space as a format for the ?scanf family
  • to read a line, the standard function is fgets,
  • returning 1 from main means failure

So

#include <stdio.h>

int main(int argc, char* argv[])
{
    char const* const fileName = argv[1]; /* should check that argc > 1 */
    FILE* file = fopen(fileName, "r"); /* should check the result */
    char line[256];

    while (fgets(line, sizeof(line), file)) {
        /* note that fgets don't strip the terminating \n, checking its
           presence would allow to handle lines longer that sizeof(line) */
        printf("%s", line); 
    }
    /* may check feof here to make a difference between eof and io failure -- network
       timeout for instance */

    fclose(file);

    return 0;
}

What does .class mean in Java?

It's a generics literal. It means that you don't know the type of class this Class instance is representing, but you are still using the generic version.

  • if you knew the class, you'd use Class<Foo>. That way you can create a new instance, for example, without casting: Foo foo = clazz.newInstance();
  • if you don't use generics at all, you'll get a warning at least (and not using generics is generally discouraged as it may lead to hard-to-detect side effects)

How do I code my submit button go to an email address

You might use Form tag with action attribute to submit the mailto.

Here is an example:

<form method="post" action="mailto:[email protected]" >
<input type="submit" value="Send Email" /> 
</form>

How to create a remote Git repository from a local one?

I think you make a bare repository on the remote side, git init --bare, add the remote side as the push/pull tracker for your local repository (git remote add origin URL), and then locally you just say git push origin master. Now any other repository can pull from the remote repository.

Is it possible to read from a InputStream with a timeout?

If your InputStream is backed by a Socket, you can set a Socket timeout (in milliseconds) using setSoTimeout. If the read() call doesn't unblock within the timeout specified, it will throw a SocketTimeoutException.

Just make sure that you call setSoTimeout on the Socket before making the read() call.

How can I search an array in VB.NET?

This would do the trick, returning the values at indeces 0, 2 and 3.

Array.FindAll(arr, Function(s) s.ToLower().StartsWith("ra"))

PHP Date Format to Month Name and Year

You could use:

echo date('F Y', strtotime('20130814'));

which should do the trick.

Edit: You have a date which is in a string format. To be able to format it nicelt, you first need to change it into a date itself - which is where strtotime comes in. It is a fantastic feature that converts almost any plausible expression of a date into a date itself. Then we can actually use the date() function to format the output into what you want.

Easy way to dismiss keyboard?

Add A Tap Gesture Recognizer to your view.And define it ibaction

your .m file will be like

    - (IBAction)hideKeyboardGesture:(id)sender {
    NSArray *windows = [UIApplication sharedApplication].windows;
    for(UIWindow *window in windows) [window endEditing:true];
    [[UIApplication sharedApplication].keyWindow endEditing:true];
}

It's worked for me

change directory in batch file using variable

The set statement doesn't treat spaces the way you expect; your variable is really named Pathname[space] and is equal to [space]C:\Program Files.

Remove the spaces from both sides of the = sign, and put the value in double quotes:

set Pathname="C:\Program Files"

Also, if your command prompt is not open to C:\, then using cd alone can't change drives.

Use

cd /d %Pathname%

or

pushd %Pathname%

instead.

How to use sed to remove the last n lines of a file

With the answers here you'd have already learnt that sed is not the best tool for this application.

However I do think there is a way to do this in using sed; the idea is to append N lines to hold space untill you are able read without hitting EOF. When EOF is hit, print the contents of hold space and quit.

sed -e '$!{N;N;N;N;N;N;H;}' -e x

The sed command above will omit last 5 lines.

Detect the Enter key in a text input field

Try this to detect the Enter key pressed in a textbox.

$(function(){

$(".input1").keyup(function (e) {
    if (e.which == 13) {
        // Enter key pressed
    }
 });

});

Split string into array of character strings

If the original string contains supplementary Unicode characters, then split() would not work, as it splits these characters into surrogate pairs. To correctly handle these special characters, a code like this works:

String[] chars = new String[stringToSplit.codePointCount(0, stringToSplit.length())];
for (int i = 0, j = 0; i < stringToSplit.length(); j++) {
    int cp = stringToSplit.codePointAt(i);
    char c[] = Character.toChars(cp);
    chars[j] = new String(c);
    i += Character.charCount(cp);
}

How to reload current page?

I believe Angular 6 has the BehaviorSubject object. My sample below is done using Angular 8 and will hopefully work for Angular 6 as well.

This method is a more "reactive" approach to the problem, and assumes you are using and are well versed in rxjs.

Assuming you are using an Observable in your parent component, the component that is used in your routing definition, then you should be able to just pulse the data stream pretty easily.

My example also assumes you are using a view model in your component like so...

vm$: Observable<IViewModel>;

And in the HTML like so...

<div *ngIf="(vm$ | async) as vm">

In your component file, add a BehaviorSubject instance...

private refreshBs: BehaviorSubject<number> = new BehaviorSubject<number>(0);

Then also add an action that can be invoked by a UI element...

  refresh() {
    this.refreshBs.next(1);
  }

Here's the UI snippet, a Material Bootstrap button...

<button mdbBtn color="primary" class="ml-1 waves-dark" type="button" outline="true"
                    (click)="refresh()" mdbWavesEffect>Refresh</button>

Then, in your ngOnIt function do something like this, keep in mind that my example is simplified a bit so that I don't have to provide a lot of code...

  ngOnInit() {

    this.vm$ = this.refreshBs.asObservable().pipe(
      switchMap(v => this.route.queryParamMap),
      map(qpm => qpm.get("value")),
      tap(v => console.log(`query param value: "${v}"`)),

      // simulate data load
      switchMap(v => of(v).pipe(
        delay(500),
        map(v => ({ items: [] }))
      )),
      
      catchError(e => of({ items: [], error: e }))
    );
    
  }

How can I move all the files from one folder to another using the command line?

You can use move for this. The documentation from help move states:

Moves files and renames files and directories.

To move one or more files:
MOVE [/Y | /-Y] [drive:][path]filename1[,...] destination

To rename a directory:
MOVE [/Y | /-Y] [drive:][path]dirname1 dirname2

  [drive:][path]filename1 Specifies the location and name of the file
                          or files you want to move.
  destination             Specifies the new location of the file. Destination
                          can consist of a drive letter and colon, a
                          directory name, or a combination. If you are moving
                          only one file, you can also include a filename if
                          you want to rename the file when you move it.
  [drive:][path]dirname1  Specifies the directory you want to rename.
  dirname2                Specifies the new name of the directory.

  /Y                      Suppresses prompting to confirm you want to
                          overwrite an existing destination file.
  /-Y                     Causes prompting to confirm you want to overwrite
                          an existing destination file.

The switch /Y may be present in the COPYCMD environment variable.
This may be overridden with /-Y on the command line.  Default is
to prompt on overwrites unless MOVE command is being executed from
within a batch script.

See the following transcript for an example where it initially shows the qq1 and qq2 directories as having three and no files respectively. Then, we do the move and we find that the three files have been moved from qq1 to qq2 as expected.

C:\Documents and Settings\Pax\My Documents>dir qq1
 Volume in drive C is Primary
 Volume Serial Number is 04F7-0E7B

 Directory of C:\Documents and Settings\Pax\My Documents\qq1

20/01/2011  11:36 AM    <DIR>          .
20/01/2011  11:36 AM    <DIR>          ..
20/01/2011  11:36 AM                13 xx1
20/01/2011  11:36 AM                13 xx2
20/01/2011  11:36 AM                13 xx3
               3 File(s)             39 bytes
               2 Dir(s)  20,092,547,072 bytes free

C:\Documents and Settings\Pax\My Documents>dir qq2
 Volume in drive C is Primary
 Volume Serial Number is 04F7-0E7B

 Directory of C:\Documents and Settings\Pax\My Documents\qq2

20/01/2011  11:36 AM    <DIR>          .
20/01/2011  11:36 AM    <DIR>          ..
               0 File(s)              0 bytes
               2 Dir(s)  20,092,547,072 bytes free

 

C:\Documents and Settings\Pax\My Documents>move qq1\* qq2
C:\Documents and Settings\Pax\My Documents\qq1\xx1
C:\Documents and Settings\Pax\My Documents\qq1\xx2
C:\Documents and Settings\Pax\My Documents\qq1\xx3

 

C:\Documents and Settings\Pax\My Documents>dir qq1
 Volume in drive C is Primary
 Volume Serial Number is 04F7-0E7B

 Directory of C:\Documents and Settings\Pax\My Documents\qq1

20/01/2011  11:37 AM    <DIR>          .
20/01/2011  11:37 AM    <DIR>          ..
               0 File(s)              0 bytes
               2 Dir(s)  20,092,547,072 bytes free

C:\Documents and Settings\Pax\My Documents>dir qq2
 Volume in drive C is Primary
 Volume Serial Number is 04F7-0E7B

 Directory of C:\Documents and Settings\Pax\My Documents\qq2

20/01/2011  11:37 AM    <DIR>          .
20/01/2011  11:37 AM    <DIR>          ..
20/01/2011  11:36 AM                13 xx1
20/01/2011  11:36 AM                13 xx2
20/01/2011  11:36 AM                13 xx3
               3 File(s)             39 bytes
               2 Dir(s)  20,092,547,072 bytes free

How do I keep track of pip-installed packages in an Anaconda (Conda) environment?

You can start by installing the below given command in the conda environment:

conda install pip

Followed by installing all pip packages you need in the environment.

After installing all the conda and pip packages to export the environment use:

conda env export -n <env-name> > environment.yml

This will create the required file in the folder

git cherry-pick says "...38c74d is a merge but no -m option was given"

The way a cherry-pick works is by taking the diff a changeset represents (the difference between the working tree at that point and the working tree of its parent), and applying it to your current branch.

So, if a commit has two or more parents, it also represents two or more diffs - which one should be applied?

You're trying to cherry pick fd9f578, which was a merge with two parents. So you need to tell the cherry-pick command which one against which the diff should be calculated, by using the -m option. For example, git cherry-pick -m 1 fd9f578 to use parent 1 as the base.

I can't say for sure for your particular situation, but using git merge instead of git cherry-pick is generally advisable. When you cherry-pick a merge commit, it collapses all the changes made in the parent you didn't specify to -m into that one commit. You lose all their history, and glom together all their diffs. Your call.

Is there a way to take a screenshot using Java and save it to some sort of image?

import java.awt.Color;
import java.awt.Dimension;
import java.awt.Rectangle;
import java.awt.Robot;
import java.awt.Toolkit;
import java.awt.event.ActionEvent;
import java.awt.event.ActionListener;
import java.awt.image.BufferedImage;
import java.io.File; 
import javax.imageio.ImageIO;
import javax.swing.*;  

public class HelloWorldFrame extends JFrame implements ActionListener {

JButton b;
public HelloWorldFrame() {
    this.setVisible(true);
    this.setLayout(null);
    b = new JButton("Click Here");
    b.setBounds(380, 290, 120, 60);
    b.setBackground(Color.red);
    b.setVisible(true);
    b.addActionListener(this);
    add(b);
    setSize(1000, 700);
}
public void actionPerformed(ActionEvent e)
{
    if (e.getSource() == b) 
    {
        this.dispose();
        try {
            Thread.sleep(1000);
            Toolkit tk = Toolkit.getDefaultToolkit(); 
            Dimension d = tk.getScreenSize();
            Rectangle rec = new Rectangle(0, 0, d.width, d.height);  
            Robot ro = new Robot();
            BufferedImage img = ro.createScreenCapture(rec);
            File f = new File("myimage.jpg");//set appropriate path
            ImageIO.write(img, "jpg", f);
        } catch (Exception ex) {
            System.out.println(ex.getMessage());
        }
    }
}

public static void main(String[] args) {
    HelloWorldFrame obj = new HelloWorldFrame();
}
}

How do I find the maximum of 2 numbers?

Use the builtin function max.

Example: max(2, 4) returns 4.

Just for giggles, there's a min as well...should you need it. :P

Difference between a SOAP message and a WSDL?

In a simple terms if you have a web service of calculator. WSDL tells about the functions that you can implement or exposed to the client. For example: add, delete, subtract and so on. Where as using SOAP you actually perform actions like doDelete(), doSubtract(), doAdd(). So SOAP and WSDL are apples and oranges. We should not compare them. They both have their own different functionality.

iOS: Convert UTC NSDate to local Timezone

Convert the date from the UTC calendar to one with the appropriate local NSTimeZone.

Extract and delete all .gz in a directory- Linux

for foo in *.gz
do
  tar xf "$foo"
  rm "$foo"
done

Why is using a wild card with a Java import statement bad?

  • There is no runtime impact, as compiler automatically replaces the * with concrete class names. If you decompile the .class file, you would never see import ...*.

  • C# always uses * (implicitly) as you can only using package name. You can never specify the class name at all. Java introduces the feature after c#. (Java is so tricky in many aspects but it's beyond this topic).

  • In Intellij Idea when you do "organize imports", it automatically replaces multiple imports of the same package with *. This is a mandantory feature as you can not turn it off (though you can increase the threshold).

  • The case listed by the accepted reply is not valid. Without * you still got the same issue. You need specify the pakcage name in your code no matter you use * or not.

Convert NSNumber to int in Objective-C

You should stick to the NSInteger data types when possible. So you'd create the number like that:

NSInteger myValue = 1;
NSNumber *number = [NSNumber numberWithInteger: myValue];

Decoding works with the integerValue method then:

NSInteger value = [number integerValue];

How do I use a C# Class Library in a project?

You need to add a reference to your class library from your project. Right click on the references folder and click add reference. You can either browse for the DLL or, if your class libaray is a project in your solution you can add a project reference.

How to put a symbol above another in LaTeX?

Use \overset{above}{main} in math mode. In your case, \overset{a}{\#}.

How to make an HTTP get request with parameters

You can also pass value directly via URL.

If you want to call method public static void calling(string name){....}

then you should call usingHttpWebRequest webrequest = (HttpWebRequest)WebRequest.Create("http://localhost:****/Report/calling?name=Priya); webrequest.Method = "GET"; webrequest.ContentType = "application/text";

Just make sure you are using ?Object = value in URL

Valid values for android:fontFamily and what they map to?

Where do these values come from? The documentation for android:fontFamily does not list this information in any place

These are indeed not listed in the documentation. But they are mentioned here under the section 'Font families'. The document lists every new public API for Android Jelly Bean 4.1.

In the styles.xml file in the application I'm working on somebody listed this as the font family, and I'm pretty sure it's wrong:

Yes, that's wrong. You don't reference the font file, you have to use the font name mentioned in the linked document above. In this case it should have been this:

<item name="android:fontFamily">sans-serif</item>

Like the linked answer already stated, 12 variants are possible:

Added in Android Jelly Bean (4.1) - API 16 :

Regular (default):

<item name="android:fontFamily">sans-serif</item>
<item name="android:textStyle">normal</item> 

Italic:

<item name="android:fontFamily">sans-serif</item>
<item name="android:textStyle">italic</item>

Bold:

<item name="android:fontFamily">sans-serif</item>
<item name="android:textStyle">bold</item>

Bold-italic:

<item name="android:fontFamily">sans-serif</item>
<item name="android:textStyle">bold|italic</item>

Light:

<item name="android:fontFamily">sans-serif-light</item>
<item name="android:textStyle">normal</item>

Light-italic:

<item name="android:fontFamily">sans-serif-light</item>
<item name="android:textStyle">italic</item>

Thin :

<item name="android:fontFamily">sans-serif-thin</item>
<item name="android:textStyle">normal</item>

Thin-italic :

<item name="android:fontFamily">sans-serif-thin</item>
<item name="android:textStyle">italic</item>

Condensed regular:

<item name="android:fontFamily">sans-serif-condensed</item>
<item name="android:textStyle">normal</item>

Condensed italic:

<item name="android:fontFamily">sans-serif-condensed</item>
<item name="android:textStyle">italic</item>

Condensed bold:

<item name="android:fontFamily">sans-serif-condensed</item>
<item name="android:textStyle">bold</item>

Condensed bold-italic:

<item name="android:fontFamily">sans-serif-condensed</item>
<item name="android:textStyle">bold|italic</item>

Added in Android Lollipop (v5.0) - API 21 :

Medium:

<item name="android:fontFamily">sans-serif-medium</item>
<item name="android:textStyle">normal</item>

Medium-italic:

<item name="android:fontFamily">sans-serif-medium</item>
<item name="android:textStyle">italic</item>

Black:

<item name="android:fontFamily">sans-serif-black</item>
<item name="android:textStyle">italic</item>

For quick reference, this is how they all look like:

Multiple lines of input in <input type="text" />

Check this:

The TEXTAREA element creates a multi-line text input control

Is it possible to make a Tree View with Angular?

So many great solutions, but I feel they all in one way or another over-complicate things a bit.

I wanted to create something that recreated the simplicity of @Mark Lagendijk's awnser, but without it defining a template in the directive, but rather would let the "user" create the template in HTML...

With ideas taken from https://github.com/stackfull/angular-tree-repeat etc... I ended up with creating the project: https://github.com/dotJEM/angular-tree

Which allows you to build your tree like:

<ul dx-start-with="rootNode">
  <li ng-repeat="node in $dxPrior.nodes">
    {{ node.name }}
    <ul dx-connect="node"/>
  </li>
</ul>

Which to me is cleaner than having to create multiple directives for differently structured trees.... In essence calling the above a tree is a bit false, it picks much more off from @ganaraj's awnser of "recursive templates", but allows us to define the template where we need the tree.

(you could do that with a script tag based template, but it still has to sit right outside the actual tree node, and it still just feels a bit yuk...)

Left here for just another choice...

How to detect when a UIScrollView has finished scrolling

An alternative would be to use scrollViewWillEndDragging:withVelocity:targetContentOffset which is called whenever the user lifts the finger and contains the target content offset where the scroll will stop. Using this content offset in scrollViewDidScroll: correctly identifies when the scroll view has stopped scrolling.

private var targetY: CGFloat?
public func scrollViewWillEndDragging(_ scrollView: UIScrollView,
                                      withVelocity velocity: CGPoint,
                                      targetContentOffset: UnsafeMutablePointer<CGPoint>) {
       targetY = targetContentOffset.pointee.y
}
public func scrollViewDidScroll(_ scrollView: UIScrollView) {
    if (scrollView.contentOffset.y == targetY) {
        print("finished scrolling")
    }

Batch files: How to read a file?

The FOR-LOOP generally works, but there are some issues. The FOR doesn't accept empty lines and lines with more than ~8190 are problematic. The expansion works only reliable, if the delayed expansion is disabled.

Detection of CR/LF versus single LF seems also a little bit complicated.
Also NUL characters are problematic, as a FOR-Loop immediatly cancels the reading.

Direct binary reading seems therefore nearly impossible.

The problem with empty lines can be solved with a trick. Prefix each line with a line number, using the findstr command, and after reading, remove the prefix.

@echo off
SETLOCAL DisableDelayedExpansion
FOR /F "usebackq delims=" %%a in (`"findstr /n ^^ t.txt"`) do (
    set "var=%%a"
    SETLOCAL EnableDelayedExpansion
    set "var=!var:*:=!"
    echo(!var!
    ENDLOCAL
)

Toggling between enable and disabled delayed expansion is neccessary for the safe working with strings, like ! or ^^^xy!z.
That's because the line set "var=%%a" is only safe with DisabledDelayedExpansion, else exclamation marks are removed and the carets are used as (secondary) escape characters and they are removed too.
But using the variable var is only safe with EnabledDelayedExpansion, as even a call %%var%% will fail with content like "&"&.

EDIT: Added set/p variant
There is a second way of reading a file with set /p, the only disadvantages are that it is limited to ~1024 characters per line and it removes control characters at the line end.
But the advantage is, you didn't need the delayed toggling and it's easier to store values in variables

@echo off
setlocal EnableDelayedExpansion
set "file=%~1"

for /f "delims=" %%n in ('find /c /v "" %file%') do set "len=%%n"
set "len=!len:*: =!"

<%file% (
  for /l %%l in (1 1 !len!) do (
    set "line="
    set /p "line="
    echo(!line!
  )
)

For reading it "binary" into a hex-representation
You could look at SO: converting a binary file to HEX representation using batch file

How do I fix a .NET windows application crashing at startup with Exception code: 0xE0434352?

It looks like this error 0xe0434352 applies to a number of different errors.

In case it helps anyone, I ran into this error when I was trying to install my application on a new Windows 10 installation. It worked on other machines, and looked like the app momentarily would start before dying. After much trial and error the problem turned out to be that the app required DirectX9. Though a later version of DirectX was present it had to have version 9. Hope that saves someone some frustration.

Multiple Python versions on the same machine?

Update 2019: Using asdf

These days I suggest using asdf to install various versions of Python interpreters next to each other.

Note1: asdf works not only for Python but for all major languages.

Note2: asdf works fine in combination with popular package-managers such as pipenv and poetry.

If you have asdf installed you can easily download/install new Python interpreters:

# Install Python plugin for asdf:
asdf plugin-add python

# List all available Python interpreters:
asdf list-all python

# Install the Python interpreters that you need:
asdf install python 3.7.4
asdf install python 3.6.9
# etc...

# If you want to define the global version:
asdf global python 3.7.4

# If you want to define the local (project) version:
# (this creates a file .tool-versions in the current directory.)
asdf local python 3.7.4

Old Answer: Install Python from source

If you need to install multiple versions of Python (next to the main one) on Ubuntu / Mint: (should work similar on other Unixs'.)

1) Install Required Packages for source compilation

$ sudo apt-get install build-essential checkinstall
$ sudo apt-get install libreadline-gplv2-dev libncursesw5-dev libssl-dev libsqlite3-dev tk-dev libgdbm-dev libc6-dev libbz2-dev

2) Download and extract desired Python version

Download Python Source for Linux as tarball and move it to /usr/src.

Extract the downloaded package in place. (replace the 'x's with your downloaded version)

$ sudo tar xzf Python-x.x.x.tgz

3) Compile and Install Python Source

$ cd Python-x.x.x
$ sudo ./configure
$ sudo make altinstall

Your new Python bin is now located in /usr/local/bin. You can test the new version:

$ pythonX.X -V
Python x.x.x
$ which pythonX.X
/usr/local/bin/pythonX.X

# Pip is now available for this version as well:
$ pipX.X -V
pip X.X.X from /usr/local/lib/pythonX.X/site-packages (python X.X)

How can I map True/False to 1/0 in a Pandas DataFrame?

Use Series.view for convert boolean to integers:

df["somecolumn"] = df["somecolumn"].view('i1')

How to copy a row from one SQL Server table to another

Jarrett's answer creates a new table.

Scott's answer inserts into an existing table with the same structure.

You can also insert into a table with different structure:

INSERT Table2
(columnX, columnY)
SELECT column1, column2 FROM Table1
WHERE [Conditions]

Aligning two divs side-by-side

The HTML code is for three div align side by side and can be used for two also by some changes

<div id="wrapper">
  <div id="first">first</div>
  <div id="second">second</div>
  <div id="third">third</div>
</div>

The CSS will be

#wrapper {
  display:table;
  width:100%;
}
#row {
  display:table-row;
}
#first {
  display:table-cell;
  background-color:red;
  width:33%;
}
#second {
  display:table-cell;
  background-color:blue;
  width:33%;
}
#third {
  display:table-cell;
  background-color:#bada55;
  width:34%;
}

This code will workup towards responsive layout as it will resize the

<div> 

according to device width. Even one can silent anyone

<div>

as

<!--<div id="third">third</div> --> 

and can use rest two for two

<div> 

side by side.

How to generate a HTML page dynamically using PHP?

As per your requirement you dont have to generate a html page dynamicaly. It can be done by .htaccess file .

Still this is sample code to generate HTML Page

<?php

 $filename = 'test.html';
 header("Cache-Control: public");
 header("Content-Description: File Transfer");
 header("Content-Disposition: attachment; filename=$filename");
 header("Content-Type: application/octet-stream; ");
 header("Content-Transfer-Encoding: binary");
?>

you can create any .html , .php file just change extention in file name

jQuery’s .bind() vs. .on()

As of Jquery 3.0 and above .bind has been deprecated and they prefer using .on instead. As @Blazemonger answered earlier that it may be removed and its for sure that it will be removed. For the older versions .bind would also call .on internally and there is no difference between them. Please also see the api for more detail.

jQuery API documentation for .bind()

How to implement zoom effect for image view in android?

Very simple way (Tested) :-

PhotoViewAttacher pAttacher;
pAttacher = new PhotoViewAttacher(Your_Image_View);
pAttacher.update();

Add bellow line in build.gradle :-

compile 'com.commit451:PhotoView:1.2.4'

jQuery .scrollTop(); + animation

you can use both CSS class or HTML id, for keeping it symmetric I always use CSS class for example

<a class="btn btn-full js--scroll-to-plans" href="#">I’m hungry</a> 
|
|
|
<section class="section-plans js--section-plans clearfix">

$(document).ready(function () {
    $('.js--scroll-to-plans').click(function () {
        $('body,html').animate({
            scrollTop: $('.js--section-plans').offset().top
        }, 1000);
        return false;})
});

TypeError: a bytes-like object is required, not 'str'

This code is probably good for Python 2. But in Python 3, this will cause an issue, something related to bit encoding. I was trying to make a simple TCP server and encountered the same problem. Encoding worked for me. Try this with sendto command.

clientSocket.sendto(message.encode(),(serverName, serverPort))

Similarly you would use .decode() to receive the data on the UDP server side, if you want to print it exactly as it was sent.

How to parse a CSV file in Bash?

We can parse csv files with quoted strings and delimited by say | with following code

while read -r line
do
    field1=$(echo "$line" | awk -F'|' '{printf "%s", $1}' | tr -d '"')
    field2=$(echo "$line" | awk -F'|' '{printf "%s", $2}' | tr -d '"')

    echo "$field1 $field2"
done < "$csvFile"

awk parses the string fields to variables and tr removes the quote.

Slightly slower as awk is executed for each field.

What is the correct XPath for choosing attributes that contain "foo"?

John C is the closest, but XPath is case sensitive, so the correct XPath would be:

/bla/a[contains(@prop, 'Foo')]

HashMap(key: String, value: ArrayList) returns an Object instead of ArrayList?

Using generics (as in the above answers) is your best bet here. I've just double checked and:

test.put("test", arraylistone); 
ArrayList current = new ArrayList();
current = (ArrayList) test.get("test");

will work as well, through I wouldn't recommend it as the generics ensure that only the correct data is added, rather than trying to do the handling at retrieval time.

What is the difference between char * const and const char *?

const always modifies the thing that comes before it (to the left of it), EXCEPT when it's the first thing in a type declaration, where it modifies the thing that comes after it (to the right of it).

So these two are the same:

int const *i1;
const int *i2;

they define pointers to a const int. You can change where i1 and i2 points, but you can't change the value they point at.

This:

int *const i3 = (int*) 0x12345678;

defines a const pointer to an integer and initializes it to point at memory location 12345678. You can change the int value at address 12345678, but you can't change the address that i3 points to.

DateTime format to SQL format using C#

The correct answer was already given "use parameters". Formatting a date and passing it as a string to SQL-Server can lead to errors as it depends on the settings how the date is interpreted on the server side. In europe, we write '1.12.2012' to indicate december 1st 2012, whereas in other countries this might be treated as january 12th.

When issuing statements directly in SSMS I use the format yyyymmdd which seem to be quite general. I did not encounter any problems on the various installations I worked on so far.

There is another seldom used format, which is a bit weird but works for all versions:

select { d '2013-10-01' }

will return the first of october 2013.

select { ts '2013-10-01 13:45:01' }

will return october 1st, 1:45:01 PM

I strongly advice to use parameters and never format your own SQL code by pasting together homegrown formatted statement fragments. It is an entry for SQL injection and strange errors (formatting a float value is another potential issue)

How do I change selected value of select2 dropdown with JqGrid?

For select2 version >= 4.0.0

The other solutions might not work, however the following examples should work.

Solution 1: Causes all attached change events to trigger, including select2

$('select').val('1').trigger('change');

Solution 2: Causes JUST select2 change event to trigger

$('select').val('1').trigger('change.select2');

See this jsfiddle for examples of these. Thanks to @minlare for Solution 2.

Explanation:

Say I have a best friend select with people's names. So Bob, Bill and John (in this example I assume the Value is the same as the name). First I initialize select2 on my select:

$('#my-best-friend').select2();

Now I manually select Bob in the browser. Next Bob does something naughty and I don't like him anymore. So the system unselects Bob for me:

$('#my-best-friend').val('').trigger('change');

Or say I make the system select the next in the list instead of Bob:

// I have assume you can write code to select the next guy in the list
$('#my-best-friend').val('Bill').trigger('change');  

Notes on Select 2 website (see Deprecated and removed methods) that might be useful for others:

.select2('val') The "val" method has been deprecated and will be removed in Select2 4.1. The deprecated method no longer includes the triggerChange parameter.

You should directly call .val on the underlying element instead. If you needed the second parameter (triggerChange), you should also call .trigger("change") on the element.

$('select').val('1').trigger('change'); // instead of $('select').select2('val', '1');

Python and pip, list all versions of a package that's available?

You don't need a third party package to get this information. pypi provides simple JSON feeds for all packages under

https://pypi.org/pypi/{PKG_NAME}/json

Here's some Python code using only the standard library which gets all versions.

import json
import urllib2
from distutils.version import StrictVersion

def versions(package_name):
    url = "https://pypi.org/pypi/%s/json" % (package_name,)
    data = json.load(urllib2.urlopen(urllib2.Request(url)))
    versions = data["releases"].keys()
    versions.sort(key=StrictVersion)
    return versions

print "\n".join(versions("scikit-image"))

That code prints (as of Feb 23rd, 2015):

0.7.2
0.8.0
0.8.1
0.8.2
0.9.0
0.9.1
0.9.2
0.9.3
0.10.0
0.10.1

Changing the color of a clicked table row using jQuery

in your css:

.selected{
    background: #F00;
}

in the jquery:

$("#data tr").click(function(){
   $(this).toggleClass('selected');
});

Basically you create a class and adds/removes it from the selected row.

Btw you could have shown more effort, there's no css or jquery/js at all in your code xD

Using scanner.nextLine()

Rather than placing an extra scanner.nextLine() each time you want to read something, since it seems you want to accept each input on a new line, you might want to instead changing the delimiter to actually match only newlines (instead of any whitespace, as is the default)

import java.util.Scanner;

class ScannerTest {
    public static void main(String[] args) {
        Scanner scanner = new Scanner(System.in);
        scanner.useDelimiter("\\n");

        System.out.print("Enter an index: ");
        int index = scanner.nextInt();

        System.out.print("Enter a sentence: ");
        String sentence = scanner.next();

        System.out.println("\nYour sentence: " + sentence);
        System.out.println("Your index: " + index);
    }
}

Thus, to read a line of input, you only need scanner.next() that has the same behavior delimiter-wise of next{Int, Double, ...}

The difference with the "nextLine() every time" approach, is that the latter will accept, as an index also <space>3, 3<space> and 3<space>whatever while the former only accepts 3 on a line on its own

java - path to trustStore - set property doesn't work?

You have a typo - it is trustStore.

Apart from setting the variables with System.setProperty(..), you can also use

-Djavax.net.ssl.keyStore=path/to/keystore.jks

Reset input value in angular 2

  1. check the @viewchild in your .ts

    @ViewChild('ngOtpInput') ngOtpInput:any;
    
  2. set the below code in your method were you want the fields to be clear.

    yourMethod(){
        this.ngOtpInput.setValue(yourValue);
    }
    

Slick.js: Get current and total slides (ie. 3/5)

The slider object contains the slide count as property.

Slick < 1.5

$('.slideshow').slick({
    slide: 'img',
    autoplay: true,
    dots: true,
    dotsClass: 'custom_paging',
    customPaging: function (slider, i) {
        //FYI just have a look at the object to find available information
        //press f12 to access the console in most browsers
        //you could also debug or look in the source
        console.log(slider);
        return  (i + 1) + '/' + slider.slideCount;
    }
});

DEMO

Update for Slick 1.5+ (tested until 1.8.1)

var $status = $('.pagingInfo');
var $slickElement = $('.slideshow');

$slickElement.on('init reInit afterChange', function(event, slick, currentSlide, nextSlide){
    //currentSlide is undefined on init -- set it to 0 in this case (currentSlide is 0 based)
    var i = (currentSlide ? currentSlide : 0) + 1;
    $status.text(i + '/' + slick.slideCount);
});

$slickElement.slick({
    slide: 'img',
    autoplay: true,
    dots: true
});

DEMO

Update for Slick 1.9+

var $status = $('.pagingInfo');
var $slickElement = $('.slideshow');

$slickElement.on('init reInit afterChange', function(event, slick, currentSlide, nextSlide){
    //currentSlide is undefined on init -- set it to 0 in this case (currentSlide is 0 based)
    var i = (currentSlide ? currentSlide : 0) + 1;
    $status.text(i + '/' + slick.slideCount);
});

$slickElement.slick({
    autoplay: true,
    dots: true
});

DEMO

Example when using slidesToShow

var $status = $('.pagingInfo');
var $slickElement = $('.slideshow');

$slickElement.on('init reInit afterChange', function (event, slick, currentSlide, nextSlide) {
  // no dots -> no slides
  if(!slick.$dots){
    return;
  }

  //currentSlide is undefined on init -- set it to 0 in this case (currentSlide is 0 based)
  var i = (currentSlide ? currentSlide : 0) + 1;
  // use dots to get some count information
  $status.text(i + '/' + (slick.$dots[0].children.length));
});

$slickElement.slick({
  infinite: false,
  slidesToShow: 4,
  autoplay: true,
  dots: true
});

DEMO