Programs & Examples On #Filecompare

How to declare and initialize a static const array as a class member?

// in foo.h
class Foo {
    static const unsigned char* Msg;
};

// in foo.cpp
static const unsigned char Foo_Msg_data[] = {0x00,0x01};
const unsigned char* Foo::Msg = Foo_Msg_data;

Argument Exception "Item with Same Key has already been added"

If you want "insert or replace" semantics, use this syntax:

A[key] = value;     // <-- insert or replace semantics

It's more efficient and readable than calls involving "ContainsKey()" or "Remove()" prior to "Add()".

So in your case:

rct3Features[items[0]] = items[1];

How to search if dictionary value contains certain string with Python

def search(myDict, lookup):
    a=[]
    for key, value in myDict.items():
        for v in value:
            if lookup in v:
                 a.append(key)
    a=list(set(a))
    return a

if the research involves more keys maybe you should create a list with all the keys

Check if a property exists in a class

If you are binding like I was:

<%# Container.DataItem.GetType().GetProperty("Property1") != null ? DataBinder.Eval(Container.DataItem, "Property1") : DataBinder.Eval(Container.DataItem, "Property2")  %>

Is it possible to output a SELECT statement from a PL/SQL block?

From an anonymous block? I'd like to now more about the situation where you think that to be required, because with subquery factoring clauses and inline views it's pretty rare that you need to resort to PL/SQL for anything other than the most complex situations.

If you can use a named procedure then use pipelined functions. Here's an example pulled from the documentation:

CREATE PACKAGE pkg1 AS
  TYPE numset_t IS TABLE OF NUMBER;
  FUNCTION f1(x NUMBER) RETURN numset_t PIPELINED;
END pkg1;
/

CREATE PACKAGE BODY pkg1 AS
-- FUNCTION f1 returns a collection of elements (1,2,3,... x)
FUNCTION f1(x NUMBER) RETURN numset_t PIPELINED IS
  BEGIN
    FOR i IN 1..x LOOP
      PIPE ROW(i);
    END LOOP;
    RETURN;
  END;
END pkg1;
/

-- pipelined function is used in FROM clause of SELECT statement
SELECT * FROM TABLE(pkg1.f1(5));

ASP.NET Web API application gives 404 when deployed at IIS 7

While the marked answer gets it working, all you really need to add to the webconfig is:

    <handlers>
      <!-- Your other remove tags-->
      <remove name="UrlRoutingModule-4.0"/>
      <!-- Your other add tags-->
      <add name="UrlRoutingModule-4.0" path="*" verb="*" type="System.Web.Routing.UrlRoutingModule" preCondition=""/>
    </handlers>

Note that none of those have a particular order, though you want your removes before your adds.

The reason that we end up getting a 404 is because the Url Routing Module only kicks in for the root of the website in IIS. By adding the module to this application's config, we're having the module to run under this application's path (your subdirectory path), and the routing module kicks in.

Center a DIV horizontally and vertically

After trying a lot of things I find a way that works. I share it here if it is useful to anyone. You can see it here working: http://jsbin.com/iquviq/30/edit

.content {
        width: 200px;
        height: 600px;
        background-color: blue;
        position: absolute; /*Can also be `fixed`*/
        left: 0;
        right: 0;
        top: 0;
        bottom: 0;
        margin: auto;
        /*Solves a problem in which the content is being cut when the div is smaller than its' wrapper:*/
        max-width: 100%;
        max-height: 100%;
        overflow: auto;
}

Configuring so that pip install can work from github

Clone target repository same way like you cloning any other project:

git clone [email protected]:myuser/foo.git

Then install it in develop mode:

cd foo
pip install -e .

You can change anything you wan't and every code using foo package will use modified code.

There 2 benefits ot this solution:

  1. You can install package in your home projects directory.
  2. Package includes .git dir, so it's regular Git repository. You can push to your fork right away.

Should I mix AngularJS with a PHP framework?

It seems you may be more comfortable with developing in PHP you let this hold you back from utilizing the full potential with web applications.

It is indeed possible to have PHP render partials and whole views, but I would not recommend it.

To fully utilize the possibilities of HTML and javascript to make a web application, that is, a web page that acts more like an application and relies heavily on client side rendering, you should consider letting the client maintain all responsibility of managing state and presentation. This will be easier to maintain, and will be more user friendly.

I would recommend you to get more comfortable thinking in a more API centric approach. Rather than having PHP output a pre-rendered view, and use angular for mere DOM manipulation, you should consider having the PHP backend output the data that should be acted upon RESTFully, and have Angular present it.

Using PHP to render the view:

/user/account

if($loggedIn)
{
    echo "<p>Logged in as ".$user."</p>";
}
else
{
    echo "Please log in.";
}

How the same problem can be solved with an API centric approach by outputting JSON like this:

api/auth/

{
  authorized:true,
  user: {
      username: 'Joe', 
      securityToken: 'secret'
  }
}

and in Angular you could do a get, and handle the response client side.

$http.post("http://example.com/api/auth", {})
.success(function(data) {
    $scope.isLoggedIn = data.authorized;
});

To blend both client side and server side the way you proposed may be fit for smaller projects where maintainance is not important and you are the single author, but I lean more towards the API centric way as this will be more correct separation of conserns and will be easier to maintain.

How to get the position of a character in Python?

Just for completion, in the case I want to find the extension in a file name in order to check it, I need to find the last '.', in this case use rfind:

path = 'toto.titi.tata..xls'
path.find('.')
4
path.rfind('.')
15

in my case, I use the following, which works whatever the complete file name is:

filename_without_extension = complete_name[:complete_name.rfind('.')]

Could not load NIB in bundle

Had this same issue nothing worked, so I figured something weird with derived data.

In xcode 6.3.2 I had to:

In XCode Menu --> Preferences --> Locations Tab --> In Locations Change Derived Data to Relative and then toggle back to Default

Then the nib loaded fine.

Char array to hex string C++

Here is something:

char const hex_chars[16] = { '0', '1', '2', '3', '4', '5', '6', '7', '8', '9', 'A', 'B', 'C', 'D', 'E', 'F' };

for( int i = data; i < data_length; ++i )
{
    char const byte = data[i];

    string += hex_chars[ ( byte & 0xF0 ) >> 4 ];
    string += hex_chars[ ( byte & 0x0F ) >> 0 ];
}

How do I best silence a warning about unused variables?

You can put it in "(void)var;" expression (does nothing) so that a compiler sees it is used. This is portable between compilers.

E.g.

void foo(int param1, int param2)
{
    (void)param2;
    bar(param1);
}

Or,

#define UNUSED(expr) do { (void)(expr); } while (0)
...

void foo(int param1, int param2)
{
    UNUSED(param2);
    bar(param1);
}

Regex matching in a Bash if statement

Or you might be looking at this question because you happened to make a silly typo like I did and have the =~ reversed to ~=

start/play embedded (iframe) youtube-video on click of an image

To start video

var videoURL = $('#playerID').prop('src');
videoURL += "&autoplay=1";
$('#playerID').prop('src',videoURL);

To stop video

var videoURL = $('#playerID').prop('src');
videoURL = videoURL.replace("&autoplay=1", "");
$('#playerID').prop('src','');
$('#playerID').prop('src',videoURL);

You may want to replace "&autoplay=1" with "?autoplay=1" incase there are no additional parameters

works for both vimeo and youtube on FF & Chrome

Best way to convert text files between character sets?

Use this Python script: https://github.com/goerz/convert_encoding.py Works on any platform. Requires Python 2.7.

Format date and time in a Windows batch script

For a very simple solution for numeric date for use in filenames use the following code:

set month=%date:~4,2%
set day=%date:~7,2%
set curTimestamp=%month%%day%%year%

rem then the you can add a prefix and a file extension easily like this
echo updates%curTimestamp%.txt

Kotlin's List missing "add", "remove", Map missing "put", etc?

In Kotlin you must use MutableList or ArrayList.

Let's see how the methods of MutableList work:

var listNumbers: MutableList<Int> = mutableListOf(10, 15, 20)
// Result: 10, 15, 20

listNumbers.add(1000)
// Result: 10, 15, 20, 1000

listNumbers.add(1, 250)
// Result: 10, 250, 15, 20, 1000

listNumbers.removeAt(0)
// Result: 250, 15, 20, 1000

listNumbers.remove(20)
// Result: 250, 15, 1000

for (i in listNumbers) { 
    println(i) 
}

Let's see how the methods of ArrayList work:

var arrayNumbers: ArrayList<Int> = arrayListOf(1, 2, 3, 4, 5)
// Result: 1, 2, 3, 4, 5

arrayNumbers.add(20)
// Result: 1, 2, 3, 4, 5, 20

arrayNumbers.remove(1)
// Result: 2, 3, 4, 5, 20

arrayNumbers.clear()
// Result: Empty

for (j in arrayNumbers) { 
    println(j) 
}

'Missing contentDescription attribute on image' in XML

Add android:contentDescription="@string/description" (static or dynamic) to your ImageView. Please do not ignore nor filter the message, because it is helpfull for people using alternative input methods because of their disability (Like TalkBack, Tecla Access Shield etc etc).

Escape string for use in Javascript regex

Short 'n Sweet

function escapeRegExp(string) {
  return string.replace(/[.*+?^${}()|[\]\\]/g, '\\$&'); // $& means the whole matched string
}

Example

escapeRegExp("All of these should be escaped: \ ^ $ * + ? . ( ) | { } [ ]");

>>> "All of these should be escaped: \\ \^ \$ \* \+ \? \. \( \) \| \{ \} \[ \] "

(NOTE: the above is not the original answer; it was edited to show the one from MDN. This means it does not match what you will find in the code in the below npm, and does not match what is shown in the below long answer. The comments are also now confusing. My recommendation: use the above, or get it from MDN, and ignore the rest of this answer. -Darren,Nov 2019)

Install

Available on npm as escape-string-regexp

npm install --save escape-string-regexp

Note

See MDN: Javascript Guide: Regular Expressions

Other symbols (~`!@# ...) MAY be escaped without consequence, but are not required to be.

.

.

.

.

Test Case: A typical url

escapeRegExp("/path/to/resource.html?search=query");

>>> "\/path\/to\/resource\.html\?search=query"

The Long Answer

If you're going to use the function above at least link to this stack overflow post in your code's documentation so that it doesn't look like crazy hard-to-test voodoo.

var escapeRegExp;

(function () {
  // Referring to the table here:
  // https://developer.mozilla.org/en/JavaScript/Reference/Global_Objects/regexp
  // these characters should be escaped
  // \ ^ $ * + ? . ( ) | { } [ ]
  // These characters only have special meaning inside of brackets
  // they do not need to be escaped, but they MAY be escaped
  // without any adverse effects (to the best of my knowledge and casual testing)
  // : ! , = 
  // my test "~!@#$%^&*(){}[]`/=?+\|-_;:'\",<.>".match(/[\#]/g)

  var specials = [
        // order matters for these
          "-"
        , "["
        , "]"
        // order doesn't matter for any of these
        , "/"
        , "{"
        , "}"
        , "("
        , ")"
        , "*"
        , "+"
        , "?"
        , "."
        , "\\"
        , "^"
        , "$"
        , "|"
      ]

      // I choose to escape every character with '\'
      // even though only some strictly require it when inside of []
    , regex = RegExp('[' + specials.join('\\') + ']', 'g')
    ;

  escapeRegExp = function (str) {
    return str.replace(regex, "\\$&");
  };

  // test escapeRegExp("/path/to/res?search=this.that")
}());

phpMyAdmin is throwing a #2002 cannot log in to the mysql server phpmyadmin

my problem is solved by this step

  1. apt-get install mysql-server phpmy admin
  2. /etc/init.d/mysql restart
  3. done.

detect key press in python?

I would suggest you use PyGame and add an event handle.

http://www.pygame.org/docs/ref/event.html

Good way of getting the user's location in Android

This is my solution which works fairly well:

private Location bestLocation = null;
private Looper looper;
private boolean networkEnabled = false, gpsEnabled = false;

private synchronized void setLooper(Looper looper) {
    this.looper = looper;
}

private synchronized void stopLooper() {
    if (looper == null) return;
    looper.quit();
}

@Override
protected void runTask() {
    final LocationManager locationManager = (LocationManager) service
            .getSystemService(Context.LOCATION_SERVICE);
    final SharedPreferences prefs = getPreferences();
    final int maxPollingTime = Integer.parseInt(prefs.getString(
            POLLING_KEY, "0"));
    final int desiredAccuracy = Integer.parseInt(prefs.getString(
            DESIRED_KEY, "0"));
    final int acceptedAccuracy = Integer.parseInt(prefs.getString(
            ACCEPTED_KEY, "0"));
    final int maxAge = Integer.parseInt(prefs.getString(AGE_KEY, "0"));
    final String whichProvider = prefs.getString(PROVIDER_KEY, "any");
    final boolean canUseGps = whichProvider.equals("gps")
            || whichProvider.equals("any");
    final boolean canUseNetwork = whichProvider.equals("network")
            || whichProvider.equals("any");
    if (canUseNetwork)
        networkEnabled = locationManager
                .isProviderEnabled(LocationManager.NETWORK_PROVIDER);
    if (canUseGps)
        gpsEnabled = locationManager
                .isProviderEnabled(LocationManager.GPS_PROVIDER);
    // If any provider is enabled now and we displayed a notification clear it.
    if (gpsEnabled || networkEnabled) removeErrorNotification();
    if (gpsEnabled)
        updateBestLocation(locationManager
                .getLastKnownLocation(LocationManager.GPS_PROVIDER));
    if (networkEnabled)
        updateBestLocation(locationManager
                .getLastKnownLocation(LocationManager.NETWORK_PROVIDER));
    if (desiredAccuracy == 0
            || getLocationQuality(desiredAccuracy, acceptedAccuracy,
                    maxAge, bestLocation) != LocationQuality.GOOD) {
        // Define a listener that responds to location updates
        LocationListener locationListener = new LocationListener() {

            public void onLocationChanged(Location location) {
                updateBestLocation(location);
                if (desiredAccuracy != 0
                        && getLocationQuality(desiredAccuracy,
                                acceptedAccuracy, maxAge, bestLocation)
                                == LocationQuality.GOOD)
                    stopLooper();
            }

            public void onProviderEnabled(String provider) {
                if (isSameProvider(provider,
                        LocationManager.NETWORK_PROVIDER))networkEnabled =true;
                else if (isSameProvider(provider,
                        LocationManager.GPS_PROVIDER)) gpsEnabled = true;
                // The user has enabled a location, remove any error
                // notification
                if (canUseGps && gpsEnabled || canUseNetwork
                        && networkEnabled) removeErrorNotification();
            }

            public void onProviderDisabled(String provider) {
                if (isSameProvider(provider,
                        LocationManager.NETWORK_PROVIDER))networkEnabled=false;
                else if (isSameProvider(provider,
                        LocationManager.GPS_PROVIDER)) gpsEnabled = false;
                if (!gpsEnabled && !networkEnabled) {
                    showErrorNotification();
                    stopLooper();
                }
            }

            public void onStatusChanged(String provider, int status,
                    Bundle extras) {
                Log.i(LOG_TAG, "Provider " + provider + " statusChanged");
                if (isSameProvider(provider,
                        LocationManager.NETWORK_PROVIDER)) networkEnabled = 
                        status == LocationProvider.AVAILABLE
                        || status == LocationProvider.TEMPORARILY_UNAVAILABLE;
                else if (isSameProvider(provider,
                        LocationManager.GPS_PROVIDER))
                    gpsEnabled = status == LocationProvider.AVAILABLE
                      || status == LocationProvider.TEMPORARILY_UNAVAILABLE;
                // None of them are available, stop listening
                if (!networkEnabled && !gpsEnabled) {
                    showErrorNotification();
                    stopLooper();
                }
                // The user has enabled a location, remove any error
                // notification
                else if (canUseGps && gpsEnabled || canUseNetwork
                        && networkEnabled) removeErrorNotification();
            }
        };
        if (networkEnabled || gpsEnabled) {
            Looper.prepare();
            setLooper(Looper.myLooper());
            // Register the listener with the Location Manager to receive
            // location updates
            if (canUseGps)
                locationManager.requestLocationUpdates(
                        LocationManager.GPS_PROVIDER, 1000, 1,
                        locationListener, Looper.myLooper());
            if (canUseNetwork)
                locationManager.requestLocationUpdates(
                        LocationManager.NETWORK_PROVIDER, 1000, 1,
                        locationListener, Looper.myLooper());
            Timer t = new Timer();
            t.schedule(new TimerTask() {

                @Override
                public void run() {
                    stopLooper();
                }
            }, maxPollingTime * 1000);
            Looper.loop();
            t.cancel();
            setLooper(null);
            locationManager.removeUpdates(locationListener);
        } else // No provider is enabled, show a notification
        showErrorNotification();
    }
    if (getLocationQuality(desiredAccuracy, acceptedAccuracy, maxAge,
            bestLocation) != LocationQuality.BAD) {
        sendUpdate(new Event(EVENT_TYPE, locationToString(desiredAccuracy,
                acceptedAccuracy, maxAge, bestLocation)));
    } else Log.w(LOG_TAG, "LocationCollector failed to get a location");
}

private synchronized void showErrorNotification() {
    if (notifId != 0) return;
    ServiceHandler handler = service.getHandler();
    NotificationInfo ni = NotificationInfo.createSingleNotification(
            R.string.locationcollector_notif_ticker,
            R.string.locationcollector_notif_title,
            R.string.locationcollector_notif_text,
            android.R.drawable.stat_notify_error);
    Intent intent = new Intent(
            android.provider.Settings.ACTION_LOCATION_SOURCE_SETTINGS);
    ni.pendingIntent = PendingIntent.getActivity(service, 0, intent,
            PendingIntent.FLAG_UPDATE_CURRENT);
    Message msg = handler.obtainMessage(ServiceHandler.SHOW_NOTIFICATION);
    msg.obj = ni;
    handler.sendMessage(msg);
    notifId = ni.id;
}

private void removeErrorNotification() {
    if (notifId == 0) return;
    ServiceHandler handler = service.getHandler();
    if (handler != null) {
        Message msg = handler.obtainMessage(
                ServiceHandler.CLEAR_NOTIFICATION, notifId, 0);
        handler.sendMessage(msg);
        notifId = 0;
    }
}

@Override
public void interrupt() {
    stopLooper();
    super.interrupt();
}

private String locationToString(int desiredAccuracy, int acceptedAccuracy,
        int maxAge, Location location) {
    StringBuilder sb = new StringBuilder();
    sb.append(String.format(
            "qual=%s time=%d prov=%s acc=%.1f lat=%f long=%f",
            getLocationQuality(desiredAccuracy, acceptedAccuracy, maxAge,
                    location), location.getTime() / 1000, // Millis to
                                                            // seconds
            location.getProvider(), location.getAccuracy(), location
                    .getLatitude(), location.getLongitude()));
    if (location.hasAltitude())
        sb.append(String.format(" alt=%.1f", location.getAltitude()));
    if (location.hasBearing())
        sb.append(String.format(" bearing=%.2f", location.getBearing()));
    return sb.toString();
}

private enum LocationQuality {
    BAD, ACCEPTED, GOOD;

    public String toString() {
        if (this == GOOD) return "Good";
        else if (this == ACCEPTED) return "Accepted";
        else return "Bad";
    }
}

private LocationQuality getLocationQuality(int desiredAccuracy,
        int acceptedAccuracy, int maxAge, Location location) {
    if (location == null) return LocationQuality.BAD;
    if (!location.hasAccuracy()) return LocationQuality.BAD;
    long currentTime = System.currentTimeMillis();
    if (currentTime - location.getTime() < maxAge * 1000
            && location.getAccuracy() <= desiredAccuracy)
        return LocationQuality.GOOD;
    if (acceptedAccuracy == -1
            || location.getAccuracy() <= acceptedAccuracy)
        return LocationQuality.ACCEPTED;
    return LocationQuality.BAD;
}

private synchronized void updateBestLocation(Location location) {
    bestLocation = getBestLocation(location, bestLocation);
}

protected Location getBestLocation(Location location,
        Location currentBestLocation) {
    if (currentBestLocation == null) {
        // A new location is always better than no location
        return location;
    }
    if (location == null) return currentBestLocation;
    // Check whether the new location fix is newer or older
    long timeDelta = location.getTime() - currentBestLocation.getTime();
    boolean isSignificantlyNewer = timeDelta > TWO_MINUTES;
    boolean isSignificantlyOlder = timeDelta < -TWO_MINUTES;
    boolean isNewer = timeDelta > 0;
    // If it's been more than two minutes since the current location, use
    // the new location
    // because the user has likely moved
    if (isSignificantlyNewer) {
        return location;
        // If the new location is more than two minutes older, it must be
        // worse
    } else if (isSignificantlyOlder) {
        return currentBestLocation;
    }
    // Check whether the new location fix is more or less accurate
    int accuracyDelta = (int) (location.getAccuracy() - currentBestLocation
            .getAccuracy());
    boolean isLessAccurate = accuracyDelta > 0;
    boolean isMoreAccurate = accuracyDelta < 0;
    boolean isSignificantlyLessAccurate = accuracyDelta > 200;
    // Check if the old and new location are from the same provider
    boolean isFromSameProvider = isSameProvider(location.getProvider(),
            currentBestLocation.getProvider());
    // Determine location quality using a combination of timeliness and
    // accuracy
    if (isMoreAccurate) {
        return location;
    } else if (isNewer && !isLessAccurate) {
        return location;
    } else if (isNewer && !isSignificantlyLessAccurate
            && isFromSameProvider) {
        return location;
    }
    return bestLocation;
}

/** Checks whether two providers are the same */
private boolean isSameProvider(String provider1, String provider2) {
    if (provider1 == null) return provider2 == null;
    return provider1.equals(provider2);
}

How to display multiple images in one figure correctly?

You could try the following:

import matplotlib.pyplot as plt
import numpy as np

def plot_figures(figures, nrows = 1, ncols=1):
    """Plot a dictionary of figures.

    Parameters
    ----------
    figures : <title, figure> dictionary
    ncols : number of columns of subplots wanted in the display
    nrows : number of rows of subplots wanted in the figure
    """

    fig, axeslist = plt.subplots(ncols=ncols, nrows=nrows)
    for ind,title in zip(range(len(figures)), figures):
        axeslist.ravel()[ind].imshow(figures[title], cmap=plt.jet())
        axeslist.ravel()[ind].set_title(title)
        axeslist.ravel()[ind].set_axis_off()
    plt.tight_layout() # optional



# generation of a dictionary of (title, images)
number_of_im = 20
w=10
h=10
figures = {'im'+str(i): np.random.randint(10, size=(h,w)) for i in range(number_of_im)}

# plot of the images in a figure, with 5 rows and 4 columns
plot_figures(figures, 5, 4)

plt.show()

However, this is basically just copy and paste from here: Multiple figures in a single window for which reason this post should be considered to be a duplicate.

I hope this helps.

Converting a string to a date in a cell

To accomodate both data scenarios you have, you will want to use this:

datevalue(text(a2,"mm/dd/yyyy"))

That will give you the date number representation for a cell that Excel has in date, or in text datatype.

Is there a way to get a collection of all the Models in your Rails app?

I can't comment yet, but I think sj26 answer should be the top answer. Just a hint:

Rails.application.eager_load! unless Rails.configuration.cache_classes
ActiveRecord::Base.descendants

How to put text in the upper right, or lower right corner of a "box" using css

_x000D_
_x000D_
<div style="position: relative; width: 250px;">_x000D_
  <div style="position: absolute; top: 0; right: 0; width: 100px; text-align:right;">_x000D_
    here_x000D_
  </div>_x000D_
  <div style="position: absolute; bottom: 0; right: 0; width: 100px; text-align:right;">_x000D_
    and here_x000D_
  </div>_x000D_
  Lorem Ipsum etc <br />_x000D_
  blah <br />_x000D_
  blah blah <br />_x000D_
  blah <br />_x000D_
  lorem ipsums_x000D_
</div>
_x000D_
_x000D_
_x000D_

Gets you pretty close, although you may need to tweak the "top" and "bottom" values.

SOAP Action WSDL

the service have 4 operations: 1. GetServiceDetails 2. GetArrivalBoard 3. GetDepartureBoard 4. GetArrivalDepartureBoard

Implementation of web service

How to enter ssh password using bash?

Create a new keypair: (go with the defaults)

ssh-keygen

Copy the public key to the server: (password for the last time)

ssh-copy-id [email protected]

From now on the server should recognize your key and not ask you for the password anymore:

ssh [email protected]

Cannot convert lambda expression to type 'string' because it is not a delegate type

For people just stumbling upon this now, I resolved an error of this type that was thrown with all the references and using statements placed properly. There's evidently some confusion with substituting in a function that returns DataTable instead of calling it on a declared DataTable. For example:

This worked for me:

DataTable dt = SomeObject.ReturnsDataTable();

List<string> ls = dt.AsEnumerable().Select(dr => dr["name"].ToString()).ToList<string>();

But this didn't:

List<string> ls = SomeObject.ReturnsDataTable().AsEnumerable().Select(dr => dr["name"].ToString()).ToList<string>();

I'm still not 100% sure why, but if anyone is frustrated by an error of this type, give this a try.

Map enum in JPA with fixed values?

For versions earlier than JPA 2.1, JPA provides only two ways to deal with enums, by their name or by their ordinal. And the standard JPA doesn't support custom types. So:

  • If you want to do custom type conversions, you'll have to use a provider extension (with Hibernate UserType, EclipseLink Converter, etc). (the second solution). ~or~
  • You'll have to use the @PrePersist and @PostLoad trick (the first solution). ~or~
  • Annotate getter and setter taking and returning the int value ~or~
  • Use an integer attribute at the entity level and perform a translation in getters and setters.

I'll illustrate the latest option (this is a basic implementation, tweak it as required):

@Entity
@Table(name = "AUTHORITY_")
public class Authority implements Serializable {

    public enum Right {
        READ(100), WRITE(200), EDITOR (300);

        private int value;

        Right(int value) { this.value = value; }    

        public int getValue() { return value; }

        public static Right parse(int id) {
            Right right = null; // Default
            for (Right item : Right.values()) {
                if (item.getValue()==id) {
                    right = item;
                    break;
                }
            }
            return right;
        }

    };

    @Id
    @GeneratedValue(strategy = GenerationType.AUTO)
    @Column(name = "AUTHORITY_ID")
    private Long id;

    @Column(name = "RIGHT_ID")
    private int rightId;

    public Right getRight () {
        return Right.parse(this.rightId);
    }

    public void setRight(Right right) {
        this.rightId = right.getValue();
    }

}

Including another class in SCSS

Looks like @mixin and @include are not needed for a simple case like this.

One can just do:

.myclass {
  font-weight: bold;
  font-size: 90px;
}

.myotherclass {
  @extend .myclass;
  color: #000000;
}

'cannot open git-upload-pack' error in Eclipse when cloning or pushing git repository

I just got this same error, "cannot open git-upload-pack", in Eclipse with a BitBucket repo trying to do a pull or a push. I resolved it by switching local branches (Team/Switch To) to the master branch and doing a pull, and then switching back to the branch I was working on and pulling again.

convert from Color to brush

This is for Color to Brush....

you can't convert it, you have to make a new brush....

SolidColorBrush brush = new SolidColorBrush( myColor );

now, if you need it in XAML, you COULD make a custom value converter and use that in a binding

Open Form2 from Form1, close Form1 from Form2

I did this once for my project, to close one application and open another application.

    System.Threading.Thread newThread;
    Form1 frmNewForm = new Form1;

   newThread = new System.Threading.Thread(new System.Threading.ThreadStart(frmNewFormThread));
this.Close();
        newThread.SetApartmentState(System.Threading.ApartmentState.STA);
        newThread.Start();

And add the following Method. Your newThread.Start will call this method.

    public void frmNewFormThread)()
    {

        Application.Run(frmNewForm);

    }

How to embed images in email

Here is how to get the code for an embedded image without worrying about any files or base64 statements or mimes (it's still base64, but you don't have to do anything to get it). I originally posted this same answer in this thread, but it may be valuable to repeat it in this one, too.

To do this, you need Mozilla Thunderbird, you can fetch the html code for an image like this:

  1. Copy a bitmap to clipboard.
  2. Start a new email message.
  3. Paste the image. (don't save it as a draft!!!)
  4. Double-click on it to get to the image settings dialogue.
  5. Look for the "image location" property.
  6. Fetch the code and wrap it in an image tag, like this:

You should end up with a string of text something like this:

<img src="data:image/png;base64,iVBORw0KGgoAAAANSUhEUgAAAaIAAAGcCAIAAAAUGTPlAAAACXBIWXMAAA7DAAAOwwHHb6hkAAAPbklEQVR4nO3d2ZbixhJAUeku//8vcx/oxphBaMgpIvd+c7uqmqakQ6QkxHq73RaA3tZ13fNlJ5K1yhzQy860fbS/XTIHtHOla9/8jJjMARXV6No332omc0BhLdP27r1pMgeU0bduz16yJnPAVeME7uG5bDIHxTzv7bn3rAG79u7xK/in7+OArNY14QwRom7v/tf7AUASQROw07qu4f6Bjwcsc1BLuC58FDFwD/dHbtEKtWwvWl/aMeAKN27dXpjmoIyLnRqtKaM9ntPWdTXNQRWHRrmhjPzYzjHNQXnnJrsR+jLCYyjONAej6Ht4LmXg7kxzUMahTAx1wiH0udQ9ZA6G0Ct8uQN3Z9EKBeyPxThvCJshcHcJ348CFx29ou1jLz7cDmikC+Xmadxi0Qo/XS/C+8EvjWvJohX+42gCtr9+56DX0myNW0xzsMeJNHw7falx7Znm4Lyj1ThxmK9gFuds3GKagxdfPzblr+c/afWgCoj1aMtyphVevZ8uKNKIc2ds93zjTzM3brFohXc1Xvs7zhOTN24xzcFOvWKR7P5OXTg2ByRnmoO9ak9GxXdGo9yyLLfbzTQHQ9C4ekxzcECNdtTYBzXu7v7cmubggOJJMmc0IHPQTaXGGeXuHk+v6+agg3pDnMa9M83BAW3eDsF1z0+yzMFe4zfOKPeRzEFT9UqkcQ8vryUyB7sUjEiNHmncBqcg4LfiEbn/wPd7nzhsd937c2iagx9aLjPP/V1GuW2mOdhSqiCPEaPSYMjdx3FY5uCr6wV53+ue/+Tjz19Xb8EsTObgsyuNu9KpQ99rlHv27amTOfjgXD6O1q3U7dfZJnPwqvjndVX6URL5bOOpkzn4j0PtuB44h+GK2H4aXVACf3z7AOlvNj7qsNAj2mKU2880B8tybaG6ffmbea22358M6XcAZRv381uuM8o97HliTXNpeRfRTlcWqvu/t8jVcOp2jszNwkWnH51uXMviqNs3OzdpmcvJjrHH4G8g9UssReYmYqB7diIiTqEOZf/GLHNhXD/WpnEPA6ZkwIc0skMbs+vmYjh6xx5F2zBUUNa/ej+QSI5u3qa5WQjf3ThBGeeRpCdzgW0fa7v/r8ddats9rIGNUJYRHkNoJzZmmQtMvA7p3pfuDyCBc9u8zGVmv7rzPORw+nXdKYgYTvyC7dt3ngdMc2FcuQR/5xVzyd4fJnCZXNkaTXOBbezGRa59DZ2J0A+eFxdfcWUuNjvzR56WTK6vKmQuocl38sn/+ckUOXIic+HZq595NjIpdXRY5kLauOvZuaNyH78r3CkIjcuk4ObnTOu83qMQrmtkVXZTNM0lcW/WnnOvWd8rnu9fNK3iL7emuTx+7uduasL4amyHpjmWReMYQ6XtUObQOJKTudlpHIOotyk6NjeiZO8thW21t3CZG87H95ZW2g72/1jlpZIG25JFa1TXN47Tjfv4J3BCm9dLmYuheFaMY/R1u92abYQyF4MqkUnj7VnmZpQymin/Ufm0HOIeZG44tTeCIp9jPWBTHC4cXJfA3dU6hUcpz3vvxo1Jdkr56xa4wXXf6mQugG+lO7p7p/ld61ogI2x1rpsLpt41dCGujBO4EEbbeGQuntOl21j/FvxbKhG42h6/7tNP9VAbzLOxNmW++XYLzCI7/+12G/PuwdLWTPffdVUyF0OvHb7bqTGBa2WGArighK80Lr0ZGrfIXBT1NsfbX5V+/lEa18w4v/TanIKY1M9NvP0+IHAtzdO4xbG5cC62YMxft8C1NOY2UJVpbgrDbtkC19iwW0JVjs3lN+yWrXGNDbsl1GaaowOBa2/axi0yl96hjbvBRcIC197MgbuzaGVZlmVd128BKhgmjWtP4xbTXG7bm/j+6Ny/8soOI3BdaNydzM2oZXQErguBe+a6uUgOJePjb7bxZXca14Wd+oVjc7PYOPp26IdU+mJK0bh3MpfT9dupX6RxXWjcR47NZdalNQLXhcBtkLmEvt0ms4jtuwprXBfNGhfiTvrvZC6Mo9d/NCZwvexszaFb5P/8CbE4NkcBcXeA6E407v0/T4vyezfNxTDy9jTyY0ts/0TmF2Sa4xK7UBfXD4qV+rCk6z+kAZnjpCIX4nHO9Wf+RKGiRO2dd0EEoCZs2LMLf/sAzP0ePyFiMUxzENueV8GXNk3VuEXmxmeU46eql0lGb9ziTCvwUabXV9Mc5Hf0urnrx/KGYpobWqZXVEJocKP89kxzEN6JDH3MWdaXVdPcuLJuczS2Z0Pa+Jroo9wiczC57QgmaNwic8MyylHExoY0zzbm2BzEVm/gyjHKLaa5Mc3zMstFVUuU4MLgO5mDqH7Wp/h95d7/xut362zAW/eHY5RjfPduRLmK2DQHHBbrxdgpiLHE2nrgxZgbsGkOKPY+ijEXraa5gYz5SsgMTmx7YxbtI5kDluXUXe8v3q2zGWdaR2GUYxzJsmCaA14le9E1zQ0h2VZFGjn6YJoDvsrxAixzwJYEH8jrujngt3Vd39/gFWVJ69jcEKK/WhLIx13+9BYYIiAy15/G0dLpz6Iu9QPbs2iFuTyWnzs9f3HQl2SnIGA6QWt1msxBErfbrfb68f3nj79iXWQOcnjkZmfsigx0IRq3OAUxgtlWEJS1vQvP8PmEPzkFAVHtidTja2Z+NTXN9Tfz9sc5p3fbOYc7metP5tiv1A77batLGQSZG4LSsa3GfhroLucXOdMKQ2twmcizlK+4TkEM4Xa7pdy8OK3XVGWao6KUmxcnNBvf5tnkHJsbi5kuqCvzeN99MOKNlY6SuXFJXiDv92Lb+S00IHMxSN7I7ESDk7nY5K87e9D4nIIITOO607gQZC4qjYOdXDcXksZ1Z44LxDQXj8Z1p3GxyBwco3HhyFwwRrm+NC4imYO9NC4omYNdNC4umYvEirUXjQtN5sLQuF40LjrXzcFXApeDaS4Go1x7GpeGzMEHGpeJRSv8h8DlI3Pwh8BlJXMBODBXm8Dl5tgcs9O49GRudEa5qjRuBhatTErg5iFzTEfgZiNzQ7NiLUvg5iRzTEHgZiZzJCdwONM6LivW6zSOxTRHVgLHg2mOhDSOZ6a5QVmxnqBufCRzZCBwbLBoJTyNY9tqExmQFes5NmY+Ms2Rx7quXiF4J3Nko3S8kDkSUjqeydxw7KJFeBp5kDkgOZkjLQMddzIHJCdzYzGAQHEyByQnc0ByMkda3vvFncwNxIE5qEHmgORkjpysWHmQOSA5mSMhoxzPZA5ITubIxijHC5kjFY3jncwBycncKFwbfJ1Rjo9kjiQ0jm9kjgw0jg0yByT3T+8HAFf9HOVejnsa/WZjmhuC8w+nHW0cE5I5Ajs3lwnfbGSOqKw92UnmCOlK4/RxNk5BkNztdju3Sn3+LmUMzTRHPKejc7vddn7vSxkdzgtN5vqzCx1isOIomSOSE40r9Sri1SgumSOMjo0797czCJkjhsaNE7VMnGklgJaN+/iNqheazDG6Nol5r5u0pSFzjK7qsf9vP1zjMpE5ZrSdTo1LRuaYyJ7BUOPycaYV/qVxKckc/KFxWckcLIvGpSZzoHHJyRws67p6y2pizrTCH4/SvQx3PjEnOtMcvFr/+vZ/Gz8eLjLNwVeKloPM8cd9LTbVjr1n+fnxCVnX1dI1EItWluVph7f37uFZikXmOhtweppnH/ber0lYtPJhTz79aVilbJ/r7Ev4wnGIobPuO/DGBtDmsbn1ObXJXGcjZ+6h7IMsvsldfHh2gfQsWqe2cw+/eBK2dkcmPEfMIaa5zoY6BBbdxpO5ncJkzwMvTHPk8XOs+/YFz38iefm4oIRsPp44fvnP7ideaEnm5pV4bNnzT9uOHZnIHPkdHdAMdMnIXE92p2YOPdWmvGRkblK59+T9Ucv9PHAnc8xiZ/uELx8XlDCLb/3StfRMcySkXDyTuRlNWIEJ/8k8WLSSk67xYJoDkpO56RhzmI3MAcnJ3FyMckxI5oDkZG4iRjnmJHNAcjIHJCdzQHIyByQnc7Nw/oFpyRyQnMwByclcNz4IAtqQuSk4MMfMZA5ITuaA5GQuPytWJidzQHIyByQnc8lZsYLMAcnJHJCczGVmxQqLzPXinV7QjMylZZSDO5kDkpO5nIxy8CBzQHIyByQnc0ByMgckJ3MJOf8Az2SuA9cGQ0syByQnc9lYscILmQOSkzkgOZkDkpO51qqeZnVgDt7JHJCczAHJyVweVqzwkcwByclcU/XOPxjl4BuZA5KTOSA5mcvAihU2yByQnMy1U+n8g1EOtskckJzMAcnJXGxWrPCTzAHJyVwjNc4/GOVgD5kDkpM5IDmZi8qKFXaSOSA5mQvJKAf7yVwLVT/mBtgmc0ByMhePFSscInNAcjIXjFEOjpK56px/gL5kDkhO5uoqO8pZscIJMgckJ3NhGOXgHJmryMkHGIHMAcnJXAxWrHCazNVixQqDkLkAjHJwhcwByclcFQVXrEY5uEjmgORkbmhGObhO5oDkZG5cRjkoQubKc8UcDEXmBmWUg1JkrjCjHIxG5kZklIOCZA5ITuZKsmKFAclcMaUaZ8UKZcncWDQOipO5MixXYVgyNxCjHNQgcwUY5WBkMjcKoxxUInNXFRnlNA7qkTkgOZnrzygHVcncJU4+wPhk7jxH5SAEmQOSk7mTjHIQhcwBycncGc48QCAy140VK7Qhc4c5KgexyFwHGgctydwx10c5jYPGZA5ITuYOMMpBRDK3l8ZBUDK3i8ZBXDIHJCdzvxnlIDSZ+0HjIDqZ2+K9q5CAzH3lTV2Qg8wBycncZ0Y5SEPmPtA4yETmXmkcJCNz5WkcDEXm/sNVcpCPzP1L4yAlmftD4yArmVsWjYPUZM47uiC52TPn8hFIb+rMaRzMYN7MaRxMYtLMaRzMY8bMaRxMZbrMaRzMZq7MaRxM6J/eD6CRUhfHaRyEM8U0p3Ews/yZ0ziYXOZFa8F3cWkcxJV2mtM44C7nNGehCjxky5whDniRJ3Nl76ekcZBGhswJHLAhduaK3xFT4yCfwGdaNQ7YI+Q0J3DAfsEyV+NzGzQOcguTuUofTKNxkF6AzAkccMW4mav3uYICB1MZMXNVPzhV42A2Y2VO4IDiRsmcwAGV9Mxc1bTdCRzQJ3MCBzTTOnO1A6duwIsWmWswuy0CB3xRJXNtuvYgcMCGYplrnLY7gQN+upq5LnVbBA7Y7VjmekXtmcABh+zKXPe6SRtw2mvmuhftQdqAIv5kbpC6SRtQXP+6SRtQ1XqvjCvdgKzW9+L42FMgk/8DDsgw4HlIEQ0AAAAASUVORK5CYII=" alt="" height="211" width="213">

You can wrap this up into a string variable and place this absolutely anywhere that you would present an html email message - even in your email signatures. The advantage is that there are no attachments, and there are no links. (this code will display a lizard)

A picture is worth a thousand words: enter image description here

Incidentally, I did write a program to do all of this for you. It's called BaseImage, and it will create the image code as well as the html for you. Please don't consider this self-promotion; I'm just sharing a solution.

Error : No resource found that matches the given name (at 'icon' with value '@drawable/icon')

This happens when you have previously changed your icon or the ic_launcher; and when that ic_launcher no longer exists in your base folder.

Try adding a png image and giving the same name and then copy it to your drawable folder.Now re build the project.

How to simulate target="_blank" in JavaScript

This might help

var link = document.createElementNS("http://www.w3.org/1999/xhtml", "a");
    link.href = 'http://www.google.com';
    link.target = '_blank';
    var event = new MouseEvent('click', {
        'view': window,
        'bubbles': false,
        'cancelable': true
    });
    link.dispatchEvent(event);

How to add a local repo and treat it as a remote repo

If your goal is to keep a local copy of the repository for easy backup or for sticking onto an external drive or sharing via cloud storage (Dropbox, etc) you may want to use a bare repository. This allows you to create a copy of the repository without a working directory, optimized for sharing.

For example:

$ git init --bare ~/repos/myproject.git
$ cd /path/to/existing/repo
$ git remote add origin ~/repos/myproject.git
$ git push origin master

Similarly you can clone as if this were a remote repo:

$ git clone ~/repos/myproject.git

how to set font size based on container size?

I've given a more detailed answer of using vw with respect to specific container sizing in this answer, so I won't just repeat my answer here.

In summary, however, it is essentially a matter of factoring (or controlling) what the container size is going to be with respect to viewport, and then working out the proper vw sizing based on that for the container, taking mind of what needs to happen if something is dynamically resized.

So if you wanted a 5vw size at a container at 100% of the viewport width, then one at 75% of the viewport width you would probably want to be (5vw * .75) = 3.75vw.

C++ How do I convert a std::chrono::time_point to long and back

I would also note there are two ways to get the number of ms in the time point. I'm not sure which one is better, I've benchmarked them and they both have the same performance, so I guess it's a matter of preference. Perhaps Howard could chime in:

auto now = system_clock::now();

//Cast the time point to ms, then get its duration, then get the duration's count.
auto ms = time_point_cast<milliseconds>(now).time_since_epoch().count();

//Get the time point's duration, then cast to ms, then get its count.
auto ms = duration_cast<milliseconds>(tpBid.time_since_epoch()).count();

The first one reads more clearly in my mind going from left to right.

Simple JavaScript Checkbox Validation

For now no jquery or php needed. Use just "required" HTML5 input attrbute like here

 <form>
        <p>
            <input class="form-control" type="text" name="email" />
            <input type="submit" value="ok" class="btn btn-success" name="submit" />
            <input type="hidden" name="action" value="0" />
        </p>
        <p><input type="checkbox" required name="terms">I have read and accept <a href="#">SOMETHING Terms and Conditions</a></p>
 </form>

This will validate and prevent any submit before checkbox is opt in. Language independent solution because its generated by users web browser.

How to get ip address of a server on Centos 7 in bash

You can run simple commands like

curl ifconfig.co

curl ifconfig.me

wget -qO - icanhazip.com

Get selected item value from Bootstrap DropDown with specific ID

The selector would be #demolist.dropdown-menu li a note no space between id and class. However i would suggest a more generic approach:

<div class="input-group">                                            
    <input type="TextBox" Class="form-control datebox"></input>
    <div class="input-group-btn">
    <button type="button" class="btn dropdown-toggle" data-toggle="dropdown">
        <span class="caret"></span>
    </button>
    <ul class="dropdown-menu">
        <li><a href="#">A</a></li>
        <li><a href="#">B</a></li>
        <li><a href="#">C</a></li>
    </ul>
</div>


$(document).on('click', '.dropdown-menu li a', function() {
    $(this).parent().parent().parent().find('.datebox').val($(this).html());
}); 

by using a class rather than id, and using parent().find(), you can have as many of these on a page as you like, with no duplicated js

How to Read and Write from the Serial Port

SerialPort (RS-232 Serial COM Port) in C# .NET
This article explains how to use the SerialPort class in .NET to read and write data, determine what serial ports are available on your machine, and how to send files. It even covers the pin assignments on the port itself.

Example Code:

using System;
using System.IO.Ports;
using System.Windows.Forms;

namespace SerialPortExample
{
  class SerialPortProgram
  {
    // Create the serial port with basic settings
    private SerialPort port = new SerialPort("COM1",
      9600, Parity.None, 8, StopBits.One);

    [STAThread]
    static void Main(string[] args)
    { 
      // Instatiate this class
      new SerialPortProgram();
    }

    private SerialPortProgram()
    {
      Console.WriteLine("Incoming Data:");

      // Attach a method to be called when there
      // is data waiting in the port's buffer
      port.DataReceived += new 
        SerialDataReceivedEventHandler(port_DataReceived);

      // Begin communications
      port.Open();

      // Enter an application loop to keep this thread alive
      Application.Run();
    }

    private void port_DataReceived(object sender,
      SerialDataReceivedEventArgs e)
    {
      // Show all the incoming data in the port's buffer
      Console.WriteLine(port.ReadExisting());
    }
  }
}

I want to multiply two columns in a pandas DataFrame and add the result into a new column

If we're willing to sacrifice the succinctness of Hayden's solution, one could also do something like this:

In [22]: orders_df['C'] = orders_df.Action.apply(
               lambda x: (1 if x == 'Sell' else -1))

In [23]: orders_df   # New column C represents the sign of the transaction
Out[23]:
   Prices  Amount Action  C
0       3      57   Sell  1
1      89      42   Sell  1
2      45      70    Buy -1
3       6      43   Sell  1
4      60      47   Sell  1
5      19      16    Buy -1
6      56      89   Sell  1
7       3      28    Buy -1
8      56      69   Sell  1
9      90      49    Buy -1

Now we have eliminated the need for the if statement. Using DataFrame.apply(), we also do away with the for loop. As Hayden noted, vectorized operations are always faster.

In [24]: orders_df['Value'] = orders_df.Prices * orders_df.Amount * orders_df.C

In [25]: orders_df   # The resulting dataframe
Out[25]:
   Prices  Amount Action  C  Value
0       3      57   Sell  1    171
1      89      42   Sell  1   3738
2      45      70    Buy -1  -3150
3       6      43   Sell  1    258
4      60      47   Sell  1   2820
5      19      16    Buy -1   -304
6      56      89   Sell  1   4984
7       3      28    Buy -1    -84
8      56      69   Sell  1   3864
9      90      49    Buy -1  -4410

This solution takes two lines of code instead of one, but is a bit easier to read. I suspect that the computational costs are similar as well.

Convert varchar2 to Date ('MM/DD/YYYY') in PL/SQL

Example query: SELECT TO_CHAR(TO_DATE('2017-08-23','YYYY-MM-DD'), 'MM/DD/YYYY') FROM dual;

Can I use Objective-C blocks as properties?

Hello, Swift

Complementing what @Francescu answered.

Adding extra parameters:

func test(function:String -> String, param1:String, param2:String) -> String
{
    return function("test"+param1 + param2)
}

func funcStyle(s:String) -> String
{
    return "FUNC__" + s + "__FUNC"
}
let resultFunc = test(funcStyle, "parameter 1", "parameter 2")

let blockStyle:(String) -> String = {s in return "BLOCK__" + s + "__BLOCK"}
let resultBlock = test(blockStyle, "parameter 1", "parameter 2")

let resultAnon = test({(s:String) -> String in return "ANON_" + s + "__ANON" }, "parameter 1", "parameter 2")


println(resultFunc)
println(resultBlock)
println(resultAnon)

I get conflicting provisioning settings error when I try to archive to submit an iOS app

If you are from Ionic world. You might get a "conflict code signing" error when you in the "archive" stage, as below:

... is automatically signed for development, but a conflicting code signing identity iPhone Distribution has been manually specified. Set the code signing identity value to "iPhone Developer" in the build settings editor, or switch to manual signing in the project editor. Code signing is required for product type 'Application' in SDK 'iOS 10.x'

In this case, please go to Build Settings/under signing, code signing identity, and select both as iOS Developer, not Distribution.

Go to the menu: Product/Archive again, then the issue will be fixed.

what is Array.any? for javascript

If you really want to got nuts, add a new method to the prototype:

if (!('empty' in Array.prototype)) {
  Array.prototype.empty = function () {
    return this.length === 0;
  };
}

[1, 2].empty() // false
[].empty() // true

DEMO

How to encrypt a large file in openssl using public key

Solution for safe and high secured encode anyone file in OpenSSL and command-line:

You should have ready some X.509 certificate for encrypt files in PEM format.

Encrypt file:

openssl smime -encrypt -binary -aes-256-cbc -in plainfile.zip -out encrypted.zip.enc -outform DER yourSslCertificate.pem

What is what:

  • smime - ssl command for S/MIME utility (smime(1))
  • -encrypt - chosen method for file process
  • -binary - use safe file process. Normally the input message is converted to "canonical" format as required by the S/MIME specification, this switch disable it. It is necessary for all binary files (like a images, sounds, ZIP archives).
  • -aes-256-cbc - chosen cipher AES in 256 bit for encryption (strong). If not specified 40 bit RC2 is used (very weak). (Supported ciphers)
  • -in plainfile.zip - input file name
  • -out encrypted.zip.enc - output file name
  • -outform DER - encode output file as binary. If is not specified, file is encoded by base64 and file size will be increased by 30%.
  • yourSslCertificate.pem - file name of your certificate's. That should be in PEM format.

That command can very effectively a strongly encrypt big files regardless of its format.
Known issue: Something wrong happens when you try encrypt huge file (>600MB). No error thrown, but encrypted file will be corrupted. Always verify each file! (or use PGP - that has bigger support for files encryption with public key)

Decrypt file:

openssl smime -decrypt -binary -in encrypted.zip.enc -inform DER -out decrypted.zip -inkey private.key -passin pass:your_password

What is what:

  • -inform DER - same as -outform above
  • -inkey private.key - file name of your private key. That should be in PEM format and can be encrypted by password.
  • -passin pass:your_password - your password for private key encrypt. (passphrase arguments)

How can I add spaces between two <input> lines using CSS?

Try to minimize the use of <br> as much as you possibly can. HTML is supposed to carry content and structure, <br> is neither. A simple workaround is to wrap your input elements in <p> elements, like so:

<form name="publish" id="publish" action="publishprocess.php" method="post">

    <p><input type="text" id="title" name="title" size="60" maxlength="110" value="<?php echo $title ?>" /> - Title</p>
    <p><input type="text" id="contact" name="contact" size="24" maxlength="30" value="<?php echo $contact ?>" /> - Contact</p>

    <p>Task description (you may include task description, requirements on bidders, time requirements, etc):</p>
    <p><textarea name="detail" id="detail" rows="7" cols="60" style="font-family:Arial, Helvetica, sans-serif"><?php echo $detail ?></textarea></p>

    <p><input type="text" id="price" name="price" size="10" maxlength="20" value="<?php echo $price ?>" /> - Price</p>

    <p><input class="tagvalidate" type="text" id="tag" name="tag" size="40" maxlength="60" value="<?php echo $tag ?>" /> - Skill or Knowledge Tags</p>
    <p>Combine multiple words into single-words, space to separate up to 3 tags (example:photoshop quantum-physics computer-programming)</p>

    <p>District Restriction:<?php echo $locationtext.$cityname; ?></p>

    <p><input type="submit" id="submit" value="Submit" /></p>
</form>

How to get CSS to select ID that begins with a string (not in Javascript)?

[id^=product]

^= indicates "starts with". Conversely, $= indicates "ends with".

The symbols are actually borrowed from Regex syntax, where ^ and $ mean "start of string" and "end of string" respectively.

See the specs for full information.

canvas.toDataURL() SecurityError

In my case I was using the WebBrowser control (forcing IE 11) and I could not get past the error. Switching to CefSharp which uses Chrome solved it for me.

sub and gsub function?

That won't work if the string contains more than one match... try this:

echo "/x/y/z/x" | awk '{ gsub("/", "_") ; system( "echo "  $0) }'

or better (if the echo isn't a placeholder for something else):

echo "/x/y/z/x" | awk '{ gsub("/", "_") ; print $0 }'

In your case you want to make a copy of the value before changing it:

echo "/x/y/z/x" | awk '{ c=$0; gsub("/", "_", c) ; system( "echo " $0 " " c )}'

Streaming video from Android camera to server

This is hardly a full answer, but webRTC may be what you're looking for. Here's some quick examples of webRTC in action: http://www.webrtc.org/reference-apps

If you want Android specific code, it exists! http://www.webrtc.org/native-code/android

Excel VBA If cell.Value =... then

You can use the Like operator with a wildcard to determine whether a given substring exists in a string, for example:

If cell.Value Like "*Word1*" Then
'...
ElseIf cell.Value Like "*Word2*" Then
'...
End If

In this example the * character in "*Word1*" is a wildcard character which matches zero or more characters.

NOTE: The Like operator is case-sensitive, so "Word1" Like "word1" is false, more information can be found on this MSDN page.

Why is 2 * (i * i) faster than 2 * i * i in Java?

More of an addendum. I did repro the experiment using the latest Java 8 JVM from IBM:

java version "1.8.0_191"
Java(TM) 2 Runtime Environment, Standard Edition (IBM build 1.8.0_191-b12 26_Oct_2018_18_45 Mac OS X x64(SR5 FP25))
Java HotSpot(TM) 64-Bit Server VM (build 25.191-b12, mixed mode)

And this shows very similar results:

0.374653912 s
n = 119860736
0.447778698 s
n = 119860736

(second results using 2 * i * i).

Interestingly enough, when running on the same machine, but using Oracle Java:

Java version "1.8.0_181"
Java(TM) SE Runtime Environment (build 1.8.0_181-b13)
Java HotSpot(TM) 64-Bit Server VM (build 25.181-b13, mixed mode)

results are on average a bit slower:

0.414331815 s
n = 119860736
0.491430656 s
n = 119860736

Long story short: even the minor version number of HotSpot matter here, as subtle differences within the JIT implementation can have notable effects.

jQuery: How can I create a simple overlay?

By overlay do you mean content that overlaps/covers the rest of the page? In HTML, you could do this by using a div that uses absolute or fixed positioning. If it needed to be generated dynamically, jQuery could simply generate a div with the position style set appropriately.

Google Authenticator available as a public service?

The project is open source. I have not used it. But it's using a documented algorithm (noted in the RFC listed on the open source project page), and the authenticator implementations support multiple accounts.

The actual process is straightforward. The one time code is, essentially, a pseudo random number generator. A random number generator is a formula that once given a seed, or starting number, continues to create a stream of random numbers. Given a seed, while the numbers may be random to each other, the sequence itself is deterministic. So, once you have your device and the server "in sync" then the random numbers that the device creates, each time you hit the "next number button", will be the same, random, numbers the server expects.

A secure one time password system is more sophisticated than a random number generator, but the concept is similar. There are also other details to help keep the device and server in sync.

So, there's no need for someone else to host the authentication, like, say OAuth. Instead you need to implement that algorithm that is compatible with the apps that Google provides for the mobile devices. That software is (should be) available on the open source project.

Depending on your sophistication, you should have all you need to implement the server side of this process give the OSS project and the RFC. I do not know if there is a specific implementation for your server software (PHP, Java, .NET, etc.)

But, specifically, you don't need an offsite service to handle this.

Get key by value in dictionary

we can get the Key of dict by :

def getKey(dct,value):
     return [key for key in dct if (dct[key] == value)]

How to programmatically set the ForeColor of a label to its default?

You can also use below format:

Label1.ForeColor = System.Drawing.ColorTranslator.FromHtml("#22FF99");

and

HyperLink1.ForeColor = System.Drawing.ColorTranslator.FromHtml("#22FF99");

What is PECS (Producer Extends Consumer Super)?

[Covariance and contravariance]

Lets take a look at example

public class A { }
//B is A
public class B extends A { }
//C is A
public class C extends A { }

Generics allows you to work with Types dynamically in a safe way

//ListA
List<A> listA = new ArrayList<A>();

//add
listA.add(new A());
listA.add(new B());
listA.add(new C());

//get
A a0 = listA.get(0);
A a1 = listA.get(1);
A a2 = listA.get(2);
//ListB
List<B> listB = new ArrayList<B>();

//add
listB.add(new B());

//get
B b0 = listB.get(0);

Problem

Since Java's Collection is a reference type as a result we have next issues:

Problem #1

//not compiled
//danger of **adding** non-B objects using listA reference
listA = listB;

*Swift's generic does not have such problem because Collection is Value type[About] therefore a new collection is created

Problem #2

//not compiled
//danger of **getting** non-B objects using listB reference
listB = listA;

The solution - Generic Wildcards

Wildcard is a reference type feature and it can not be instantiated directly

Solution #1 <? super A> aka lower bound aka contravariance aka consumers guarantees that it is operates by A and all superclasses, that is why it is safe to add

List<? super A> listSuperA;
listSuperA = listA;
listSuperA = new ArrayList<Object>();

//add
listSuperA.add(new A());
listSuperA.add(new B());

//get
Object o0 = listSuperA.get(0);

Solution #2

<? extends A> aka upper bound aka covariance aka producers guarantees that it is operates by A and all subclasses, that is why it is safe to get and cast

List<? extends A> listExtendsA;
listExtendsA = listA;
listExtendsA = listB;

//get
A a0 = listExtendsA.get(0);

Should I use .done() and .fail() for new jQuery AJAX code instead of success and error

When we are going to migrate JQuery from 1.x to 2x or 3.x in our old existing application , then we will use .done,.fail instead of success,error as JQuery up gradation is going to be deprecated these methods.For example when we make a call to server web methods then server returns promise objects to the calling methods(Ajax methods) and this promise objects contains .done,.fail..etc methods.Hence we will the same for success and failure response. Below is the example(it is for POST request same way we can construct for request type like GET...)

 $.ajax({
            type: "POST",
            url: url,
            data: '{"name" :"sheo"}',
            contentType: "application/json; charset=utf-8",
            async: false,
            cache: false
            }).done(function (Response) {
                  //do something when get response            })
           .fail(function (Response) {
                    //do something when any error occurs.
                });

Javascript seconds to minutes and seconds

I was thinking of a faster way to get this done and this is what i came up with

var sec = parseInt(time);
var min=0;
while(sec>59){ sec-=60; min++;}

If we want to convert "time" to minutes and seconds, for example:

// time = 75,3 sec
var sec = parseInt(time); //sec = 75
var min=0;
while(sec>59){ sec-=60; min++;} //sec = 15; min = 1

Simple int to char[] conversion

You can't truly do it in "standard" C, because the size of an int and of a char aren't fixed. Let's say you are using a compiler under Windows or Linux on an intel PC...

int i = 5;
char a = ((char*)&i)[0];
char b = ((char*)&i)[1];

Remember of endianness of your machine! And that int are "normally" 32 bits, so 4 chars!

But you probably meant "i want to stringify a number", so ignore this response :-)

Get nodes where child node contains an attribute

I would think your own suggestion is correct, however the xml is not quite valid. If you are running the //book[title[@lang='it']] on <root>[Your"XML"Here]</root> then the free online xPath testers such as one here will find the expected result.

Ruby 2.0.0p0 IRB warning: "DL is deprecated, please use Fiddle"

I got this resolution at openshift.com.

Resolution:

This error occurs only on Windows machine with Ruby 2.0.0 version. Until we officially support Ruby 2.0 please downgrade to Ruby 1.9.

On Windows, you can install Ruby 1.9.3 alongside 2.0. Change your %PATH% to c:\ruby193\ or whatever directory you installed to prior to installing the gem.

Making TextView scrollable on Android

Put maxLines and scrollbars inside TextView in xml.

<TextView android:layout_width="wrap_content"
    android:layout_height="wrap_content"
    android:scrollbars="vertical"
    android:maxLines="5" // any number of max line here.
    />

Then in java code.

textView.setMovementMethod(new ScrollingMovementMethod());

Java error - "invalid method declaration; return type required"

Every method (other than a constructor) must have a return type.

public double diameter(){...

A JRE or JDK must be available in order to run Eclipse. No JVM was found after searching the following locations

I had this issue; I fixed it by going to

Computer-->Properties-->Advanced Settings-->Environmental Variables

In the System Variables find the variable named PATH.
-->Select Edit -->At the very end of the Path Variable, put a ";" then add your path of your JDK and put \bin\ at the end

Should be fixed.

Example:

System Variable-

C:\Program Files (x86)\Common Files.......HP\LeanFT\bin

JDK path-

C:\Programs Files\Java\jre1.8.0_121

Final Path -

C:\Program Files (x86)\Common Files.......HP\LeanFT\bin;C:\Programs Files\Java\jre1.8.0_121\bin\

Sources: https://www.java.com/en/download/help/path.xml

Using DataContractSerializer to serialize, but can't deserialize back

I ended up doing the following and it works.

public static string Serialize(object obj)
{
    using (MemoryStream memoryStream = new MemoryStream())
    {
        DataContractSerializer serializer = new DataContractSerializer(obj.GetType());
        serializer.WriteObject(memoryStream, obj);
        return Encoding.UTF8.GetString(memoryStream.ToArray());
    }
}

public static object Deserialize(string xml, Type toType)
{
    using (MemoryStream memoryStream = new MemoryStream(Encoding.UTF8.GetBytes(xml)))
    {
        XmlDictionaryReader reader = XmlDictionaryReader.CreateTextReader(memoryStream, Encoding.UTF8, new XmlDictionaryReaderQuotas(), null);
        DataContractSerializer serializer = new DataContractSerializer(toType);
        return serializer.ReadObject(reader);
    }
}

It seems that the major problem was in the Serialize function when calling stream.GetBuffer(). Calling stream.ToArray() appears to work.

:first-child not working as expected

For that particular case you can use:

.detail_container > ul + h1{ 
    color: blue; 
}

But if you need that same selector on many cases, you should have a class for those, like BoltClock said.

Getting a timestamp for today at midnight?

Today at midnight. Easy.

$stamp = mktime(0, 0, 0);

jQuery return ajax result into outside variable

You are missing a comma after

'data': { 'request': "", 'target': 'arrange_url', 'method': 'method_target' }

Also, if you want return_first to hold the result of your anonymous function, you need to make a function call:

var return_first = function () {
    var tmp = null;
    $.ajax({
        'async': false,
        'type': "POST",
        'global': false,
        'dataType': 'html',
        'url': "ajax.php?first",
        'data': { 'request': "", 'target': 'arrange_url', 'method': 'method_target' },
        'success': function (data) {
            tmp = data;
        }
    });
    return tmp;
}();

Note () at the end.

How to play .wav files with java

The snippet here works fine, tested with windows sound:

public static void main(String[] args) {
        AePlayWave aw = new AePlayWave( "C:\\WINDOWS\\Media\\tada.wav" );
        aw.start();     
}

How to convert string to Date in Angular2 \ Typescript?

You can use date filter to convert in date and display in specific format.

In .ts file (typescript):

let dateString = '1968-11-16T00:00:00' 
let newDate = new Date(dateString);

In HTML:

{{dateString |  date:'MM/dd/yyyy'}}

Below are some formats which you can implement :

Backend:

public todayDate = new Date();

HTML :

<select>
<option value=""></option>
<option value="MM/dd/yyyy">[{{todayDate | date:'MM/dd/yyyy'}}]</option>
<option value="EEEE, MMMM d, yyyy">[{{todayDate | date:'EEEE, MMMM d, yyyy'}}]</option>
<option value="EEEE, MMMM d, yyyy h:mm a">[{{todayDate | date:'EEEE, MMMM d, yyyy h:mm a'}}]</option>
<option value="EEEE, MMMM d, yyyy h:mm:ss a">[{{todayDate | date:'EEEE, MMMM d, yyyy h:mm:ss a'}}]</option>
<option value="MM/dd/yyyy h:mm a">[{{todayDate | date:'MM/dd/yyyy h:mm a'}}]</option>
<option value="MM/dd/yyyy h:mm:ss a">[{{todayDate | date:'MM/dd/yyyy h:mm:ss a'}}]</option>
<option value="MMMM d">[{{todayDate | date:'MMMM d'}}]</option>   
<option value="yyyy-MM-ddTHH:mm:ss">[{{todayDate | date:'yyyy-MM-ddTHH:mm:ss'}}]</option>
<option value="h:mm a">[{{todayDate | date:'h:mm a'}}]</option>
<option value="h:mm:ss a">[{{todayDate | date:'h:mm:ss a'}}]</option>      
<option value="EEEE, MMMM d, yyyy hh:mm:ss a">[{{todayDate | date:'EEEE, MMMM d, yyyy hh:mm:ss a'}}]</option>
<option value="MMMM yyyy">[{{todayDate | date:'MMMM yyyy'}}]</option> 
</select>

Reading a column from CSV file using JAVA

If you are using Java 7+, you may want to use NIO.2, e.g.:

Code:

public static void main(String[] args) throws Exception {

    File file = new File("test.csv");

    List<String> lines = Files.readAllLines(file.toPath(), 
            StandardCharsets.UTF_8);

    for (String line : lines) {
        String[] array = line.split(",", -1);
        System.out.println(array[0]);
    }

}

Output:

a
1RW
1RW
1RW
1RW
1RW
1RW
1R1W
1R1W
1R1W

"Incorrect string value" when trying to insert UTF-8 into MySQL via JDBC?

I had this problem with my PLAY Java application. This is my stack trace for that exception:

javax.persistence.PersistenceException: Error[Incorrect string value: '\xE0\xA6\xAC\xE0\xA6\xBE...' for column 'product_name' at row 1]
  at io.ebean.config.dbplatform.SqlCodeTranslator.translate(SqlCodeTranslator.java:52)
  at io.ebean.config.dbplatform.DatabasePlatform.translate(DatabasePlatform.java:192)
  at io.ebeaninternal.server.persist.dml.DmlBeanPersister.execute(DmlBeanPersister.java:83)
  at io.ebeaninternal.server.persist.dml.DmlBeanPersister.insert(DmlBeanPersister.java:49)
  at io.ebeaninternal.server.core.PersistRequestBean.executeInsert(PersistRequestBean.java:1136)
  at io.ebeaninternal.server.core.PersistRequestBean.executeNow(PersistRequestBean.java:723)
  at io.ebeaninternal.server.core.PersistRequestBean.executeNoBatch(PersistRequestBean.java:778)
  at io.ebeaninternal.server.core.PersistRequestBean.executeOrQueue(PersistRequestBean.java:769)
  at io.ebeaninternal.server.persist.DefaultPersister.insert(DefaultPersister.java:456)
  at io.ebeaninternal.server.persist.DefaultPersister.insert(DefaultPersister.java:406)
  at io.ebeaninternal.server.persist.DefaultPersister.save(DefaultPersister.java:393)
  at io.ebeaninternal.server.core.DefaultServer.save(DefaultServer.java:1602)
  at io.ebeaninternal.server.core.DefaultServer.save(DefaultServer.java:1594)
  at io.ebean.Model.save(Model.java:190)
  at models.Product.create(Product.java:147)
  at controllers.PushData.xlsupload(PushData.java:67)
  at router.Routes$$anonfun$routes$1.$anonfun$applyOrElse$40(Routes.scala:690)
  at play.core.routing.HandlerInvokerFactory$$anon$3.resultCall(HandlerInvoker.scala:134)
  at play.core.routing.HandlerInvokerFactory$$anon$3.resultCall(HandlerInvoker.scala:133)
  at play.core.routing.HandlerInvokerFactory$JavaActionInvokerFactory$$anon$8$$anon$2$$anon$1.invocation(HandlerInvoker.scala:108)
  at play.core.j.JavaAction$$anon$1.call(JavaAction.scala:88)
  at play.http.DefaultActionCreator$1.call(DefaultActionCreator.java:31)
  at play.core.j.JavaAction.$anonfun$apply$8(JavaAction.scala:138)
  at scala.concurrent.Future$.$anonfun$apply$1(Future.scala:655)
  at scala.util.Success.$anonfun$map$1(Try.scala:251)
  at scala.util.Success.map(Try.scala:209)
  at scala.concurrent.Future.$anonfun$map$1(Future.scala:289)
  at scala.concurrent.impl.Promise.liftedTree1$1(Promise.scala:29)
  at scala.concurrent.impl.Promise.$anonfun$transform$1(Promise.scala:29)
  at scala.concurrent.impl.CallbackRunnable.run$$$capture(Promise.scala:60)
  at scala.concurrent.impl.CallbackRunnable.run(Promise.scala)
  at play.core.j.HttpExecutionContext$$anon$2.run(HttpExecutionContext.scala:56)
  at play.api.libs.streams.Execution$trampoline$.execute(Execution.scala:70)
  at play.core.j.HttpExecutionContext.execute(HttpExecutionContext.scala:48)
  at scala.concurrent.impl.CallbackRunnable.executeWithValue(Promise.scala:68)
  at scala.concurrent.impl.Promise$KeptPromise$Kept.onComplete(Promise.scala:368)
  at scala.concurrent.impl.Promise$KeptPromise$Kept.onComplete$(Promise.scala:367)
  at scala.concurrent.impl.Promise$KeptPromise$Successful.onComplete(Promise.scala:375)
  at scala.concurrent.impl.Promise.transform(Promise.scala:29)
  at scala.concurrent.impl.Promise.transform$(Promise.scala:27)
  at scala.concurrent.impl.Promise$KeptPromise$Successful.transform(Promise.scala:375)
  at scala.concurrent.Future.map(Future.scala:289)
  at scala.concurrent.Future.map$(Future.scala:289)
  at scala.concurrent.impl.Promise$KeptPromise$Successful.map(Promise.scala:375)
  at scala.concurrent.Future$.apply(Future.scala:655)
  at play.core.j.JavaAction.apply(JavaAction.scala:138)
  at play.api.mvc.Action.$anonfun$apply$2(Action.scala:96)
  at scala.concurrent.Future.$anonfun$flatMap$1(Future.scala:304)
  at scala.concurrent.impl.Promise.$anonfun$transformWith$1(Promise.scala:37)
  at scala.concurrent.impl.CallbackRunnable.run$$$capture(Promise.scala:60)
  at scala.concurrent.impl.CallbackRunnable.run(Promise.scala)
  at akka.dispatch.BatchingExecutor$AbstractBatch.processBatch(BatchingExecutor.scala:55)
  at akka.dispatch.BatchingExecutor$BlockableBatch.$anonfun$run$1(BatchingExecutor.scala:91)
  at scala.runtime.java8.JFunction0$mcV$sp.apply(JFunction0$mcV$sp.java:12)
  at scala.concurrent.BlockContext$.withBlockContext(BlockContext.scala:81)
  at akka.dispatch.BatchingExecutor$BlockableBatch.run(BatchingExecutor.scala:91)
  at akka.dispatch.TaskInvocation.run(AbstractDispatcher.scala:40)
  at akka.dispatch.ForkJoinExecutorConfigurator$AkkaForkJoinTask.exec(ForkJoinExecutorConfigurator.scala:43)
  at akka.dispatch.forkjoin.ForkJoinTask.doExec(ForkJoinTask.java:260)
  at akka.dispatch.forkjoin.ForkJoinPool$WorkQueue.runTask(ForkJoinPool.java:1339)
  at akka.dispatch.forkjoin.ForkJoinPool.runWorker(ForkJoinPool.java:1979)
  at akka.dispatch.forkjoin.ForkJoinWorkerThread.run(ForkJoinWorkerThread.java:107)
Caused by: java.sql.SQLException: Incorrect string value: '\xE0\xA6\xAC\xE0\xA6\xBE...' for column 'product_name' at row 1
  at com.mysql.jdbc.SQLError.createSQLException(SQLError.java:1074)
  at com.mysql.jdbc.MysqlIO.checkErrorPacket(MysqlIO.java:4096)
  at com.mysql.jdbc.MysqlIO.checkErrorPacket(MysqlIO.java:4028)
  at com.mysql.jdbc.MysqlIO.sendCommand(MysqlIO.java:2490)
  at com.mysql.jdbc.MysqlIO.sqlQueryDirect(MysqlIO.java:2651)
  at com.mysql.jdbc.ConnectionImpl.execSQL(ConnectionImpl.java:2734)
  at com.mysql.jdbc.PreparedStatement.executeInternal(PreparedStatement.java:2155)
  at com.mysql.jdbc.PreparedStatement.executeUpdate(PreparedStatement.java:2458)
  at com.mysql.jdbc.PreparedStatement.executeUpdate(PreparedStatement.java:2375)
  at com.mysql.jdbc.PreparedStatement.executeUpdate(PreparedStatement.java:2359)
  at com.zaxxer.hikari.pool.ProxyPreparedStatement.executeUpdate(ProxyPreparedStatement.java:61)
  at com.zaxxer.hikari.pool.HikariProxyPreparedStatement.executeUpdate(HikariProxyPreparedStatement.java)
  at io.ebeaninternal.server.type.DataBind.executeUpdate(DataBind.java:82)
  at io.ebeaninternal.server.persist.dml.InsertHandler.execute(InsertHandler.java:122)
  at io.ebeaninternal.server.persist.dml.DmlBeanPersister.execute(DmlBeanPersister.java:73)
  ... 59 more

I was trying to save a record using io.Ebean. I fixed it by re creating my database with utf8mb4 collation, and applied play evolution to re create all tables so that all tables should be recreated with utf-8 collation.

CREATE DATABASE inventory CHARACTER SET utf8mb4 COLLATE utf8mb4_unicode_ci;

Loop through array of values with Arrow Function

In short:

someValues.forEach((element) => {
    console.log(element);
});

If you care about index, then second parameter can be passed to receive the index of current element:

someValues.forEach((element, index) => {
    console.log(`Current index: ${index}`);
    console.log(element);
});

Refer here to know more about Array of ES6: https://developer.mozilla.org/en-US/docs/Web/JavaScript/Reference/Global_Objects/Array

Convert Unicode to ASCII without errors in Python

>>> u'a?ä'.encode('ascii', 'ignore')
'a'

Decode the string you get back, using either the charset in the the appropriate meta tag in the response or in the Content-Type header, then encode.

The method encode(encoding, errors) accepts custom handlers for errors. The default values, besides ignore, are:

>>> u'a?ä'.encode('ascii', 'replace')
b'a??'
>>> u'a?ä'.encode('ascii', 'xmlcharrefreplace')
b'a&#12354;&#228;'
>>> u'a?ä'.encode('ascii', 'backslashreplace')
b'a\\u3042\\xe4'

See https://docs.python.org/3/library/stdtypes.html#str.encode

How to create a QR code reader in a HTML5 website?

Reader they show at http://www.webqr.com/index.html works like a charm, but literaly, you need the one on the webpage, the github version it's really hard to make it work, however, it is possible. The best way to go is reverse-engineer the example shown at the webpage.

However, to edit and get the full potential out of it, it's not so easy. At some point I may post the stripped-down reverse-engineered QR reader, but in the meantime have some fun hacking the code.

Happy coding.

Error: EACCES: permission denied

First install without -g (global) on root. After try using -g (global) It worked for me.

how to inherit Constructor from super class to sub class

You inherit class attributes, not class constructors .This is how it goes :

If no constructor is added in the super class, if no then the compiler adds a no argument contructor. This default constructor is invoked implicitly whenever a new instance of the sub class is created . Here the sub class may or may not have constructor, all is ok .

if a constructor is provided in the super class, the compiler will see if it is a no arg constructor or a constructor with parameters.

if no args, then the compiler will invoke it for any sub class instanciation . Here also the sub class may or may not have constructor, all is ok .

if 1 or more contructors in the parent class have parameters and no args constructor is absent, then the subclass has to have at least 1 constructor where an implicit call for the parent class construct is made via super (parent_contractor params) .

this way you are sure that the inherited class attributes are always instanciated .

How do I get the project basepath in CodeIgniter

Change your default controller which is in config file.

i.e : config/routes.php

$route['default_controller'] = "Your controller name";

Hope this will help.

Kill a postgresql session/connection

Remote scenario. But if you're trying to run tests in a rails app, and you get something like

"ActiveRecord::StatementInvalid: PG::ObjectInUse: ERROR: database "myapp_test" is being accessed by other users DETAIL: There is 1 other session using the database."

Make sure you close pgAdmin or any other postgres GUI tools before running tests.

Android Studio - Failed to apply plugin [id 'com.android.application']

I found the simplest answer to this.

Just go gradle.properties file and change the enableUnitTestBinaryResources from true to false

android.enableUnitTestBinaryResources=false

The snapshot is shown below

enter image description here

OpenCV Error: (-215)size.width>0 && size.height>0 in function imshow

I was facing the same problem while trying to open images containing spaces and special characters like the following ´

So, after modifying the images names removing their spaces and special characters, everything worked perfectly.

Native query with named parameter fails with "Not all named parameters have been set"

I use EclipseLink. This JPA allows the following way for the native queries:

Query q = em.createNativeQuery("SELECT * FROM mytable where username = ?username");
q.setParameter("username", "test");
q.getResultList();

round() doesn't seem to be rounding properly

If you use the Decimal module you can approximate without the use of the 'round' function. Here is what I've been using for rounding especially when writing monetary applications:

Decimal(str(16.2)).quantize(Decimal('.01'), rounding=ROUND_UP)

This will return a Decimal Number which is 16.20.

How to I say Is Not Null in VBA

you can do like follows. Remember, IsNull is a function which returns TRUE if the parameter passed to it is null, and false otherwise.

Not IsNull(Fields!W_O_Count.Value)

Writing to an Excel spreadsheet

Try taking a look at the following libraries too:

xlwings - for getting data into and out of a spreadsheet from Python, as well as manipulating workbooks and charts

ExcelPython - an Excel add-in for writing user-defined functions (UDFs) and macros in Python instead of VBA

what's data-reactid attribute in html?

The data-reactid attribute is a custom attribute used so that React can uniquely identify its components within the DOM.

This is important because React applications can be rendered at the server as well as the client. Internally React builds up a representation of references to the DOM nodes that make up your application (simplified version is below).

{
  id: '.1oqi7occu80',
  node: DivRef,
  children: [
    {
      id: '.1oqi7occu80.0',
      node: SpanRef,
      children: [
        {
          id: '.1oqi7occu80.0.0',
          node: InputRef,
          children: []
        }
      ]
    }
  ]
}

There's no way to share the actual object references between the server and the client and sending a serialized version of the entire component tree is potentially expensive. When the application is rendered at the server and React is loaded at the client, the only data it has are the data-reactid attributes.

<div data-reactid='.loqi70ccu80'>
  <span data-reactid='.loqi70ccu80.0'>
    <input data-reactid='.loqi70ccu80.0' />
  </span>
</div>

It needs to be able to convert that back into the data structure above. The way it does that is with the unique data-reactid attributes. This is called inflating the component tree.

You might also notice that if React renders at the client-side, it uses the data-reactid attribute, even though it doesn't need to lose its references. In some browsers, it inserts your application into the DOM using .innerHTML then it inflates the component tree straight away, as a performance boost.

The other interesting difference is that client-side rendered React ids will have an incremental integer format (like .0.1.4.3), whereas server-rendered ones will be prefixed with a random string (such as .loqi70ccu80.1.4.3). This is because the application might be rendered across multiple servers and it's important that there are no collisions. At the client-side, there is only one rendering process, which means counters can be used to ensure unique ids.

React 15 uses document.createElement instead, so client rendered markup won't include these attributes anymore.

How to use ConcurrentLinkedQueue?

No, the methods don't need to be synchronized, and you don't need to define any methods; they are already in ConcurrentLinkedQueue, just use them. ConcurrentLinkedQueue does all the locking and other operations you need internally; your producer(s) adds data into the queue, and your consumers poll for it.

First, create your queue:

Queue<YourObject> queue = new ConcurrentLinkedQueue<YourObject>();

Now, wherever you are creating your producer/consumer objects, pass in the queue so they have somewhere to put their objects (you could use a setter for this, instead, but I prefer to do this kind of thing in a constructor):

YourProducer producer = new YourProducer(queue);

and:

YourConsumer consumer = new YourConsumer(queue);

and add stuff to it in your producer:

queue.offer(myObject);

and take stuff out in your consumer (if the queue is empty, poll() will return null, so check it):

YourObject myObject = queue.poll();

For more info see the Javadoc

EDIT:

If you need to block waiting for the queue to not be empty, you probably want to use a LinkedBlockingQueue, and use the take() method. However, LinkedBlockingQueue has a maximum capacity (defaults to Integer.MAX_VALUE, which is over two billion) and thus may or may not be appropriate depending on your circumstances.

If you only have one thread putting stuff into the queue, and another thread taking stuff out of the queue, ConcurrentLinkedQueue is probably overkill. It's more for when you may have hundreds or even thousands of threads accessing the queue at the same time. Your needs will probably be met by using:

Queue<YourObject> queue = Collections.synchronizedList(new LinkedList<YourObject>());

A plus of this is that it locks on the instance (queue), so you can synchronize on queue to ensure atomicity of composite operations (as explained by Jared). You CANNOT do this with a ConcurrentLinkedQueue, as all operations are done WITHOUT locking on the instance (using java.util.concurrent.atomic variables). You will NOT need to do this if you want to block while the queue is empty, because poll() will simply return null while the queue is empty, and poll() is atomic. Check to see if poll() returns null. If it does, wait(), then try again. No need to lock.

Finally:

Honestly, I'd just use a LinkedBlockingQueue. It is still overkill for your application, but odds are it will work fine. If it isn't performant enough (PROFILE!), you can always try something else, and it means you don't have to deal with ANY synchronized stuff:

BlockingQueue<YourObject> queue = new LinkedBlockingQueue<YourObject>();

queue.put(myObject); // Blocks until queue isn't full.

YourObject myObject = queue.take(); // Blocks until queue isn't empty.

Everything else is the same. Put probably won't block, because you aren't likely to put two billion objects into the queue.

How do servlets work? Instantiation, sessions, shared variables and multithreading

When the servlet container (like Apache Tomcat) starts up, it will read from the web.xml file (only one per application) if anything goes wrong or shows up an error at container side console, otherwise, it will deploy and load all web applications by using web.xml (so named it as deployment descriptor).

During instantiation phase of the servlet, servlet instance is ready but it cannot serve the client request because it is missing with two pieces of information:
1: context information
2: initial configuration information

Servlet engine creates servletConfig interface object encapsulating the above missing information into it servlet engine calls init() of the servlet by supplying servletConfig object references as an argument. Once init() is completely executed servlet is ready to serve the client request.

Q) In the lifetime of servlet how many times instantiation and initialization happens ??

A)only once (for every client request a new thread is created) only one instance of the servlet serves any number of the client request ie, after serving one client request server does not die. It waits for other client requests ie what CGI (for every client request a new process is created) limitation is overcome with the servlet (internally servlet engine creates the thread).

Q)How session concept works?

A)whenever getSession() is called on HttpServletRequest object

Step 1: request object is evaluated for incoming session ID.

Step 2: if ID not available a brand new HttpSession object is created and its corresponding session ID is generated (ie of HashTable) session ID is stored into httpservlet response object and the reference of HttpSession object is returned to the servlet (doGet/doPost).

Step 3: if ID available brand new session object is not created session ID is picked up from the request object search is made in the collection of sessions by using session ID as the key.

Once the search is successful session ID is stored into HttpServletResponse and the existing session object references are returned to the doGet() or doPost() of UserDefineservlet.

Note:

1)when control leaves from servlet code to client don't forget that session object is being held by servlet container ie, the servlet engine

2)multithreading is left to servlet developers people for implementing ie., handle the multiple requests of client nothing to bother about multithread code

Inshort form:

A servlet is created when the application starts (it is deployed on the servlet container) or when it is first accessed (depending on the load-on-startup setting) when the servlet is instantiated, the init() method of the servlet is called then the servlet (its one and only instance) handles all requests (its service() method being called by multiple threads). That's why it is not advisable to have any synchronization in it, and you should avoid instance variables of the servlet when the application is undeployed (the servlet container stops), the destroy() method is called.

Fatal error: Call to undefined function mb_detect_encoding()

There's a much easier way than recompiling PHP. Just yum install the required mbstring library:

Example: How to install PHP mbstring on CentOS 6.2

yum --enablerepo=remi install php-mbstring

Oh, and don't forget to restart apache afterward.

What is the purpose of using WHERE 1=1 in SQL statements?

It's also a common practice when people are building the sql query programmatically, it's just easier to start with 'where 1=1 ' and then appending ' and customer.id=:custId' depending if a customer id is provided. So you can always append the next part of the query starting with 'and ...'.

How to iterate over each string in a list of strings and operate on it's elements

You are iterating trough items in words but you have to iterate through item's length:

words = ['aba', 'xyz', 'xgx', 'dssd', 'sdjh']
c = 0
for i in range(len(words)):
    w1 = words[i]
    if w1[0] == w1[len(w1) - 1]:
      c += 1
    print (c)

In your case i[0] is 'aba' because i is calculated from items in words:

words = ['aba', 'xyz', 'xgx', 'dssd', 'sdjh']
c = 0
for i in words:
print(i)

the output is:

aba

How to execute an .SQL script file using c#

This Works on Framework 4.0 or Higher. Supports "GO". Also show the error message, line, and sql command.

using System.Data.SqlClient;

        private bool runSqlScriptFile(string pathStoreProceduresFile, string connectionString)
    {
        try
        {
            string script = File.ReadAllText(pathStoreProceduresFile);

            // split script on GO command
            System.Collections.Generic.IEnumerable<string> commandStrings = Regex.Split(script, @"^\s*GO\s*$",
                                     RegexOptions.Multiline | RegexOptions.IgnoreCase);
            using (SqlConnection connection = new SqlConnection(connectionString))
            {
                connection.Open();
                foreach (string commandString in commandStrings)
                {
                    if (commandString.Trim() != "")
                    {
                        using (var command = new SqlCommand(commandString, connection))
                        {
                        try
                        {
                            command.ExecuteNonQuery();
                        }
                        catch (SqlException ex)
                        {
                            string spError = commandString.Length > 100 ? commandString.Substring(0, 100) + " ...\n..." : commandString;
                            MessageBox.Show(string.Format("Please check the SqlServer script.\nFile: {0} \nLine: {1} \nError: {2} \nSQL Command: \n{3}", pathStoreProceduresFile, ex.LineNumber, ex.Message, spError), "Warning", MessageBoxButtons.OK, MessageBoxIcon.Warning);
                            return false;
                        }
                    }
                    }
                }
                connection.Close();
            }
        return true;
        }
        catch (Exception ex)
        {
            MessageBox.Show(ex.Message, "Warning", MessageBoxButtons.OK, MessageBoxIcon.Warning);
            return false;
        }
    }

How to find out which JavaScript events fired?

Regarding Chrome, checkout the monitorEvents() via the command line API.

  • Open the console via Menu > Tools > JavaScript Console.

  • Enter monitorEvents(window);

  • View the console flooded with events

     ...
     mousemove MouseEvent {dataTransfer: ...}
     mouseout MouseEvent {dataTransfer: ...}
     mouseover MouseEvent {dataTransfer: ...}
     change Event {clipboardData: ...}
     ...
    

There are other examples in the documentation. I'm guessing this feature was added after the previous answer.

How do I set log4j level on the command line?

Based on Thorbjørn Ravn Andersens suggestion I wrote some code that makes this work

Add the following early in the main method and it is now possible to set the log level from the comand line. This have been tested in a project of mine but I'm new to log4j and might have made some mistake. If so please correct me.

    Logger.getRootLogger().setLevel(Level.WARN);
    HashMap<String,Level> logLevels=new HashMap<String,Level>();
    logLevels.put("ALL",Level.ALL);
    logLevels.put("TRACE",Level.TRACE);
    logLevels.put("DEBUG",Level.DEBUG);
    logLevels.put("INFO",Level.INFO);
    logLevels.put("WARN",Level.WARN);
    logLevels.put("ERROR",Level.ERROR);
    logLevels.put("FATAL",Level.FATAL);
    logLevels.put("OFF",Level.OFF);
    for(String name:System.getProperties().stringPropertyNames()){
        String logger="log4j.logger.";
        if(name.startsWith(logger)){
            String loggerName=name.substring(logger.length());
            String loggerValue=System.getProperty(name);
            if(logLevels.containsKey(loggerValue))
                Logger.getLogger(loggerName).setLevel(logLevels.get(loggerValue));
            else
                Logger.getRootLogger().warn("unknown log4j logg level on comand line: "+loggerValue);
        }
    }

Only using @JsonIgnore during serialization, but not deserialization

You can also do like:

@JsonIgnore
@JsonProperty(access = Access.WRITE_ONLY)
private String password;

It's worked for me

Row was updated or deleted by another transaction (or unsaved-value mapping was incorrect)

check if the object exists or not in DB, if it exists get the object and refresh it:

if (getEntityManager().contains(instance)) {
    getEntityManager().refresh(instance);
    return instance;
}

if it fails the above if condition... find the Object with Id in DB, do the operation which you need, in this case exactly changes will reflects.

if (....) {
    } else if (null != identity) {
        E dbInstance = (E) getEntityManager().find(instance.getClass(), identity);
        return dbInstance;
    }

Check if multiple strings exist in another string

I would use this kind of function for speed:

def check_string(string, substring_list):
    for substring in substring_list:
        if substring in string:
            return True
    return False

configure: error: C compiler cannot create executables

You have an old set of developer tools. gcc is reporting its version as 4.0.1. This may be left over from migrating from an older version of the OS. If you've installed Xcode 4.3.x, you need to launch it, go into its preferences, select the Downloads tab, and click "Install" next to the Command Line Tools package.

How to setup virtual environment for Python in VS Code?

P.S:

  • I have been using vs code for a while now and found an another way to show virtual environments in vs code.

  • Go to the parent folder in which venv is there through command prompt.

  • Type code . and Enter. [Working on both windows and linux for me.]

  • That should also show the virtual environments present in that folder.

Original Answer

I almost run into same problem everytime I am working on VS-Code using venv. I follow below steps, hope it helps:

  1. Go to File > preferences > Settings.

  2. Click on Workspace settings.

  3. Under Files:Association, in the JSON: Schemas section, you will find Edit in settings.json , click on that.

  4. Update "python.pythonPath": "Your_venv_path/bin/python" under workspace settings. (For Windows): Update "python.pythonPath": "Your_venv_path/Scripts/python.exe" under workspace settings.

  5. Restart VSCode incase if it still doesn't show your venv.

Java Replace Character At Specific Position Of String?

To replace a character at a specified position :

public static String replaceCharAt(String s, int pos, char c) {
   return s.substring(0,pos) + c + s.substring(pos+1);
}

Lint: How to ignore "<key> is not translated in <language>" errors?

add the lines in your /res/values.xml file in resource root tab like this:

<resources
xmlns:tools="http://schemas.android.com/tools" 
    tools:locale="en" tools:ignore="MissingTranslation">

tools:locale set the local language to English, no need of language translation later on that for all resource strings and tools:ignore let Lint to isnore the missing translations of the resource string values.

How do I use two submit buttons, and differentiate between which one was used to submit the form?

If you can't put value on buttons. I have just a rough solution. Put a hidden field. And when one of the buttons are clicked before submitting, populate the value of hidden field with like say 1 when first button clicked and 2 if second one is clicked. and in submit page check for the value of this hidden field to determine which one is clicked.

What's the difference between process.cwd() vs __dirname?

As per node js doc process.cwd()

cwd is a method of global object process, returns a string value which is the current working directory of the Node.js process.

As per node js doc __dirname

The directory name of current script as a string value. __dirname is not actually a global but rather local to each module.

Let me explain with example,

suppose we have a main.js file resides inside C:/Project/main.js and running node main.js both these values return same file

or simply with following folder structure

Project 
+-- main.js
+--lib
   +-- script.js

main.js

console.log(process.cwd())
// C:\Project
console.log(__dirname)
// C:\Project
console.log(__dirname===process.cwd())
// true

suppose we have another file script.js files inside a sub directory of project ie C:/Project/lib/script.js and running node main.js which require script.js

main.js

require('./lib/script.js')
console.log(process.cwd())
// C:\Project
console.log(__dirname)
// C:\Project
console.log(__dirname===process.cwd())
// true

script.js

console.log(process.cwd())
// C:\Project
console.log(__dirname)
// C:\Project\lib
console.log(__dirname===process.cwd())
// false

Why does 'git commit' not save my changes?

The reason why this is happening is because you have a folder that is already being tracked by Git inside another folder that is also tracked by Git. For example, I had a project and I added a subfolder to it. Both of them were being tracked by Git before I put one inside the other. In order to stop tracking the one inside, find it and remove the Git file with:

rm -rf .git

In my case I had a WordPress application and the folder I added inside was a theme. So I had to go to the theme root, and remove the Git file, so that the whole project would now be tracked by the parent, the WordPress application.

Check if value exists in dataTable?

You can use LINQ-to-DataSet with Enumerable.Any:

String author = "John Grisham";
bool contains = tbl.AsEnumerable().Any(row => author == row.Field<String>("Author"));

Another approach is to use DataTable.Select:

DataRow[] foundAuthors = tbl.Select("Author = '" + searchAuthor + "'");
if(foundAuthors.Length != 0)
{
    // do something...
}

Q: what if we do not know the columns Headers and we want to find if any cell value PEPSI exist in any rows'c columns? I can loop it all to find out but is there a better way? –

Yes, you can use this query:

DataColumn[] columns = tbl.Columns.Cast<DataColumn>().ToArray();
bool anyFieldContainsPepsi = tbl.AsEnumerable()
    .Any(row => columns.Any(col => row[col].ToString() == "PEPSI"));

How to get all of the IDs with jQuery?

It's a late answer but now there is an easy way. Current version of jquery lets you search if attribute exists. For example

$('[id]')

will give you all the elements if they have id. If you want all spans with id starting with span you can use

$('span[id^="span"]')

matplotlib get ylim values

I put above-mentioned methods together using ax instead of plt

import numpy as np
import matplotlib.pyplot as plt

x = range(100)
y = x

fig, ax = plt.subplots(1, 1, figsize=(7.2, 7.2))
ax.plot(x, y);

# method 1
print(ax.get_xlim())
print(ax.get_xlim())
# method 2
print(ax.axis())

enter image description here

How to change the interval time on bootstrap carousel?

       <div class="carousel-inner text-right">
                  <div class="carousel-item active text-center" id="first"  data-interval="1000" >
                    <img src="images/slide-1.gif" alt="slide-1">
                  </div>
                  <div class="carousel-item  text-center" id="second"  data-interval="2000" >
                    <img src="images/slide-2.gif" alt="slide-2">
                  </div>
                  <div class="carousel-item  text-center" id="third"  data-interval="3000" >
                    <img src="images/slide-3.gif" alt="slide-3">
                  </div>
                  <div class="carousel-item text-center" id="four"  data-interval="5000" >
                    <img src="images/slide-4.gif" alt="slide-4">
                  </div>
                </div>

You can also change different slides.

How to Call a JS function using OnClick event

Inline code takes higher precedence than the other ones. To call your other function func () call it from the f1 ().

Inside your function, add a line,

function fun () {
// Your code here
}

function f1()
    {
       alert("f1 called");
       //form validation that recalls the page showing with supplied inputs.    

fun ();

    }

Rewriting your whole code,

 <!DOCTYPE html>
    <html>
      <head>

      <script>

       function fun()
        {
         alert("hello");
         //validation code to see State field is mandatory.  
        }   

        function f1()
        {
           alert("f1 called");
           //form validation that recalls the page showing with supplied inputs.   
           fun (); 
        }

      </script>
      </head>
      <body>
       <form name="form1" id="form1" method="post">

         State: <select id="state ID">
                   <option></option>
                   <option value="ap">ap</option>
                   <option value="bp">bp</option>
                </select>
       </form>
       <table><tr><td id="Save" onclick="f1()">click</td></tr></table>

      </body>
</html>

wget/curl large file from google drive

After messing around with this garbage. I've found a way to download my sweet file by using chrome - developer tools.

  1. At your google docs tab, Ctr+Shift+J (Setting --> Developer tools)
  2. Switch to Network tabs
  3. At your docs file, click "Download" --> Download as CSV, xlsx,....
  4. It will show you the request in the "Network" console enter image description here

  5. Right click -> Copy -> Copy as Curl

  6. Your Curl command will be like this, and add -o to create a exported file. curl 'https://docs.google.com/spreadsheets/d/1Cjsryejgn29BDiInOrGZWvg/export?format=xlsx&id=1Cjsryejgn29BDiInOrGZWvg' -H 'authority: docs.google.com' -H 'upgrade-insecure-requests: 1' -H 'user-agent: Mozilla/5.0 (X..... -o server.xlsx

Solved!

Best way to store a key=>value array in JavaScript?

If I understood you correctly:

var hash = {};
hash['bob'] = 123;
hash['joe'] = 456;

var sum = 0;
for (var name in hash) {
    sum += hash[name];
}
alert(sum); // 579

How can I add some small utility functions to my AngularJS application?

Here is a simple, compact and easy to understand method I use.
First, add a service in your js.

app.factory('Helpers', [ function() {
      // Helper service body

        var o = {
        Helpers: []

        };

        // Dummy function with parameter being passed
        o.getFooBar = function(para) {

            var valueIneed = para + " " + "World!";

            return valueIneed;

          };

        // Other helper functions can be added here ...

        // And we return the helper object ...
        return o;

    }]);

Then, in your controller, inject your helper object and use any available function with something like the following:

app.controller('MainCtrl', [

'$scope',
'Helpers',

function($scope, Helpers){

    $scope.sayIt = Helpers.getFooBar("Hello");
    console.log($scope.sayIt);

}]);

Concatenate text files with Windows command line, dropping leading lines

This takes Test.txt with headers and appends Test1.txt and Test2.txt and writes results to Testresult.txt file after stripping headers from second and third files respectively:

type C:\Test.txt > C:\Testresult.txt && more +1 C:\Test1.txt >> C:\Testresult.txt && more +1 C:\Test2.txt >> C:\Testresult.txt

How to use BufferedReader in Java

Try this to read a file:

BufferedReader reader = null;

try {
    File file = new File("sample-file.dat");
    reader = new BufferedReader(new FileReader(file));

    String line;
    while ((line = reader.readLine()) != null) {
        System.out.println(line);
    }

} catch (IOException e) {
    e.printStackTrace();
} finally {
    try {
        reader.close();
    } catch (IOException e) {
        e.printStackTrace();
    }
}

MySQL Error #1133 - Can't find any matching row in the user table

I encountered this issue, but in my case the password for the 'phpmyadmin' user did not match the contents of /etc/phpmyadmin/config-db.php

Once I updated the password for the 'phpmyadmin' user the error went away.

These are the steps I took:

  1. Log in to mysql as root: mysql -uroot -pYOUR_ROOT_PASS
  2. Change to the 'mysql' db: use mysql;
  3. Update the password for the 'phpmyadmin' user: UPDATE mysql.user SET Password=PASSWORD('YOUR_PASS_HERE') WHERE User='phpmyadmin' AND Host='localhost';
  4. Flush privileges: FLUSH PRIVILEGES;

DONE!! It worked for me.

set environment variable in python script

bash:

LD_LIBRARY_PATH=my_path
sqsub -np $1 /path/to/executable

Similar, in Python:

import os
import subprocess
import sys

os.environ['LD_LIBRARY_PATH'] = "my_path" # visible in this process + all children
subprocess.check_call(['sqsub', '-np', sys.argv[1], '/path/to/executable'],
                      env=dict(os.environ, SQSUB_VAR="visible in this subprocess"))

Python print statement “Syntax Error: invalid syntax”

In Python 3, print is a function, you need to call it like print("hello world").

Using multiple parameters in URL in express

For what you want I would've used

    app.get('/fruit/:fruitName&:fruitColor', function(request, response) {
       const name = request.params.fruitName 
       const color = request.params.fruitColor 
    });

or better yet

    app.get('/fruit/:fruit', function(request, response) {
       const fruit = request.params.fruit
       console.log(fruit)
    });

where fruit is a object. So in the client app you just call

https://mydomain.dm/fruit/{"name":"My fruit name", "color":"The color of the fruit"}

and as a response you should see:

    //  client side response
    // { name: My fruit name, color:The color of the fruit}

iOS 7: UITableView shows under status bar

Adding to the top answer:

after the 2nd method did not initially seem to work I did some additional tinkering and have found the solution.

TLDR; the top answer's 2nd solution almost works, but for some versions of xCode ctrl+dragging to "Top Layout Guide" and selecting Vertical Spacing does nothing. However, by first adjusting the size of the Table View and then selecting "Top Space to Top Layout Guide" works


  1. Drag a blank ViewController onto the storyboard. View Controller

  2. Drag a UITableView object into the View. (Not UITableViewController). Position it in the very center using the blue layout guides.

Table View Center Image

  1. Drag a UITableViewCell into the TableView. This will be your prototype reuse cell, so don't forget to set it's Reuse Identifier under the Attributes tab or you'll get a crash.

Add Table View Cell Reuse Identifier

  1. Create your custom subclass of UIViewController, and add the <UITableViewDataSource, UITableViewDelegate> protocols. Don't forget to set your storyboard's ViewController to this class in the Identity Inspector.

  2. Create an outlet for your TableView in your implementation file, and name it "tableView"

Create Outlet tableView

  1. Right click the TableView and drag both the dataSource and the delegate to your ViewController.

dataSource delegate

Now for the part of not clipping into the status bar.

  1. Grab the top edge of your Table View and move it down to one of the dashed blue auto-layout guides that are near the top

resize

  1. Now, you can control drag from the Table View to the top and select Top Space to Top Layout Guide

Top Space to Top Layout Guide

  1. It will give you an error about ambiguous layout of TableView, just Add Missing Constraints and your done.

Add Missing Constraints

Now you can set up your table view like normal, and it won't clip the status bar!

How can I return the sum and average of an int array?

customerssalary.Average();
customerssalary.Sum();

What is the 'override' keyword in C++ used for?

The override keyword serves two purposes:

  1. It shows the reader of the code that "this is a virtual method, that is overriding a virtual method of the base class."
  2. The compiler also knows that it's an override, so it can "check" that you are not altering/adding new methods that you think are overrides.

To explain the latter:

class base
{
  public:
    virtual int foo(float x) = 0; 
};


class derived: public base
{
   public:
     int foo(float x) override { ... } // OK
}

class derived2: public base
{
   public:
     int foo(int x) override { ... } // ERROR
};

In derived2 the compiler will issue an error for "changing the type". Without override, at most the compiler would give a warning for "you are hiding virtual method by same name".

What does the C++ standard state the size of int, long type to be?

Nope, there is no standard for type sizes. Standard only requires that:

sizeof(short int) <= sizeof(int) <= sizeof(long int)

The best thing you can do if you want variables of a fixed sizes is to use macros like this:

#ifdef SYSTEM_X
  #define WORD int
#else
  #define WORD long int
#endif

Then you can use WORD to define your variables. It's not that I like this but it's the most portable way.

How to secure an ASP.NET Web API

If you want to secure your API in a server to server fashion (no redirection to website for 2 legged authentication). You can look at OAuth2 Client Credentials Grant protocol.

https://dev.twitter.com/docs/auth/application-only-auth

I have developed a library that can help you easily add this kind of support to your WebAPI. You can install it as a NuGet package:

https://nuget.org/packages/OAuth2ClientCredentialsGrant/1.0.0.0

The library targets .NET Framework 4.5.

Once you add the package to your project, it will create a readme file in the root of your project. You can look at that readme file to see how to configure/use this package.

Cheers!

Git: Pull from other remote

upstream in the github example is just the name they've chosen to refer to that repository. You may choose any that you like when using git remote add. Depending on what you select for this name, your git pull usage will change. For example, if you use:

git remote add upstream git://github.com/somename/original-project.git

then you would use this to pull changes:

git pull upstream master

But, if you choose origin for the name of the remote repo, your commands would be:

To name the remote repo in your local config: git remote add origin git://github.com/somename/original-project.git

And to pull: git pull origin master

Excel VBA Macro: User Defined Type Not Defined

Sub DeleteEmptyRows()  

    Worksheets("YourSheetName").Activate
    On Error Resume Next
    Columns("A").SpecialCells(xlCellTypeBlanks).EntireRow.Delete

End Sub

The following code will delete all rows on a sheet(YourSheetName) where the content of Column A is blank.

EDIT: User Defined Type Not Defined is caused by "oTable As Table" and "oRow As Row". Replace Table and Row with Object to resolve the error and make it compile.

Browser/HTML Force download of image from src="data:image/jpeg;base64..."

you can use the download attribute on an a tag ...

<a href="data:image/jpeg;base64,/9j/4AAQSkZ..." download="filename.jpg"></a>

see more: https://developer.mozilla.org/en/HTML/element/a#attr-download

Moment.js transform to date object

Since momentjs has no control over javascript date object I found a work around to this.

_x000D_
_x000D_
const currentTime = new Date();    _x000D_
const convertTime = moment(currentTime).tz(timezone).format("YYYY-MM-DD HH:mm:ss");_x000D_
const convertTimeObject = new Date(convertTime);
_x000D_
_x000D_
_x000D_

This will give you a javascript date object with the converted time

How can I determine the direction of a jQuery scroll event?

Scroll Event

The scroll event behaves oddly in FF (it is fired a lot of times because of the smoothness scrolling) but it works.

Note: The scroll event actually is fired when dragging the scroll bar, using cursor keys or mousewheel.

//creates an element to print the scroll position
$("<p id='test'>").appendTo("body").css({
    padding: "5px 7px",
    background: "#e9e9e9",
    position: "fixed",
    bottom: "15px",
    left: "35px"
});

//binds the "scroll" event
$(window).scroll(function (e) {
    var target = e.currentTarget,
        self = $(target),
        scrollTop = window.pageYOffset || target.scrollTop,
        lastScrollTop = self.data("lastScrollTop") || 0,
        scrollHeight = target.scrollHeight || document.body.scrollHeight,
        scrollText = "";

    if (scrollTop > lastScrollTop) {
        scrollText = "<b>scroll down</b>";
    } else {
        scrollText = "<b>scroll up</b>";
    }

    $("#test").html(scrollText +
      "<br>innerHeight: " + self.innerHeight() +
      "<br>scrollHeight: " + scrollHeight +
      "<br>scrollTop: " + scrollTop +
      "<br>lastScrollTop: " + lastScrollTop);

    if (scrollHeight - scrollTop === self.innerHeight()) {
      console.log("? End of scroll");
    }

    //saves the current scrollTop
    self.data("lastScrollTop", scrollTop);
});

Wheel Event

You also may take a look at MDN, it exposes a great information about the Wheel Event.

Note: The wheel event is fired only when using the mousewheel; cursor keys and dragging the scroll bar does not fire the event.

I read the document and the example: Listening to this event across browser
and after some tests with FF, IE, chrome, safari, I ended up with this snippet:

//creates an element to print the scroll position
$("<p id='test'>").appendTo("body").css({
    padding: "5px 7px",
    background: "#e9e9e9",
    position: "fixed",
    bottom: "15px",
    left: "15px"
});

//attach the "wheel" event if it is supported, otherwise "mousewheel" event is used
$("html").on(("onwheel" in document.createElement("div") ? "wheel" : "mousewheel"), function (e) {
    var evt = e.originalEvent || e;

    //this is what really matters
    var deltaY = evt.deltaY || (-1 / 40 * evt.wheelDelta), //wheel || mousewheel
        scrollTop = $(this).scrollTop() || $("body").scrollTop(), //fix safari
        scrollText = "";

    if (deltaY > 0) {
        scrollText = "<b>scroll down</b>";
    } else {
        scrollText = "<b>scroll up</b>";
    }

    //console.log("Event: ", evt);
    $("#test").html(scrollText +
      "<br>clientHeight: " + this.clientHeight +
      "<br>scrollHeight: " + this.scrollHeight +
      "<br>scrollTop: " + scrollTop +
      "<br>deltaY: " + deltaY);
});

LaTex left arrow over letter in math mode

Use \overleftarrow to create a long arrow to the left.

\overleftarrow{blahblahblah}

LaTeX output

React onClick and preventDefault() link refresh/redirect?

If you are using React Router, I'd suggest looking into the react-router-bootstrap library which has a handy component LinkContainer. This component prevents default page reload so you don't have to deal with the event.

In your case it could look something like:

import { LinkContainer } from 'react-router-bootstrap';

<LinkContainer to={givePathHere}>
    <span className="upvotes" onClick={this.upvote}>upvote</span>
</LinkContainer>

How do I insert datetime value into a SQLite database?

The format you need is:

'2007-01-01 10:00:00'

i.e. yyyy-MM-dd HH:mm:ss

If possible, however, use a parameterised query as this frees you from worrying about the formatting details.

AngularJS ng-if with multiple conditions

JavaScript Code

function ctrl($scope){
$scope.call={state:['second','first','nothing','Never', 'Gonna', 'Give', 'You', 'Up']}


$scope.whatClassIsIt= function(someValue){
     if(someValue=="first")
            return "ClassA"
     else if(someValue=="second")
         return "ClassB";
    else
         return "ClassC";
}
}

How to check if string contains Latin characters only?

Ahh, found the answer myself:

if (/[a-zA-Z]/.test(num)) {
  alert('Letter Found')
}

Most efficient way to find mode in numpy array

Expanding on this method, applied to finding the mode of the data where you may need the index of the actual array to see how far away the value is from the center of the distribution.

(_, idx, counts) = np.unique(a, return_index=True, return_counts=True)
index = idx[np.argmax(counts)]
mode = a[index]

Remember to discard the mode when len(np.argmax(counts)) > 1, also to validate if it is actually representative of the central distribution of your data you may check whether it falls inside your standard deviation interval.

Find max and second max salary for a employee table MySQL

Try below Query, was working for me to find Nth highest number salary. Just replace your number with nth_No

Select DISTINCT TOP 1 salary
from 
(Select DISTINCT TOP *nth_No* salary
from Employee
ORDER BY Salary DESC)
Result
ORDER BY Salary

Why are there two ways to unstage a file in Git?

These 2 commands have several subtle differences if the file in question is already in the repo and under version control (previously committed etc.):

  • git reset HEAD <file> unstages the file in the current commit.
  • git rm --cached <file> will unstage the file for future commits also. It's unstaged untill it gets added again with git add <file>.

And there's one more important difference:

  • After running git rm --cached <file> and push your branch to the remote, anyone pulling your branch from the remote will get the file ACTUALLY deleted from their folder, even though in your local working set the file just becomes untracked (i.e. not physically deleted from the folder).

This last difference is important for projects which include a config file where each developer on the team has a different config (i.e. different base url, ip or port setting) so if you're using git rm --cached <file> anyone who pulls your branch will have to manually re-create the config, or you can send them yours and they can re-edit it back to their ip settings (etc.), because the delete only effects people pulling your branch from the remote.

How to make div follow scrolling smoothly with jQuery?

Here is mine solution (hope it is plug-n-play enough too):

  1. Copy JS code part
  2. Add 'slide-along-scroll' class to element you want
  3. Make pixel-perfect corrections in JS-code
  4. Hope you will enjoy it!

_x000D_
_x000D_
// SlideAlongScroll_x000D_
var SlideAlongScroll = function(el) {_x000D_
  var _this = this;_x000D_
  this.el = el;_x000D_
  // elements original position_x000D_
  this.elpos_original = el.parent().offset().top;  _x000D_
  // scroller timeout_x000D_
  this.scroller_timeout;_x000D_
  // scroller calculate function_x000D_
  this.scroll = function() {_x000D_
    // 20px gap for beauty_x000D_
    var windowpos = $(window).scrollTop() + 20;_x000D_
    // targeted destination_x000D_
    var finaldestination = windowpos - this.elpos_original;_x000D_
    // define stopper object and correction amount_x000D_
    var stopper = ($('.footer').offset().top); // $(window).height() if you dont need it_x000D_
    var stophere = stopper - el.outerHeight() - this.elpos_original - 20;_x000D_
    // decide what to do_x000D_
    var realdestination = 0;_x000D_
    if(windowpos > this.elpos_original) {_x000D_
      if(finaldestination >= stophere) {_x000D_
        realdestination = stophere;_x000D_
      } else {_x000D_
        realdestination = finaldestination;_x000D_
      }_x000D_
    }_x000D_
    el.css({'top': realdestination });_x000D_
  };_x000D_
  // scroll listener_x000D_
  $(window).on('scroll', function() {_x000D_
    // debounce it_x000D_
    clearTimeout(_this.scroller_timeout);_x000D_
    // set scroll calculation timeout_x000D_
    _this.scroller_timeout = setTimeout(function() { _this.scroll(); }, 300);_x000D_
  });_x000D_
  // initial position (in case page is pre-scrolled by browser after load)_x000D_
  this.scroll();_x000D_
};_x000D_
// init action, little timeout for smoothness_x000D_
$(document).ready(function() {_x000D_
  $('.slide-along-scroll').each(function(i, el) {_x000D_
    setTimeout(function(el) { new SlideAlongScroll(el); }, 300, $(el));_x000D_
  });_x000D_
});
_x000D_
/* part you need */_x000D_
.slide-along-scroll {_x000D_
  padding: 20px;_x000D_
  background-color: #CCCCCC;_x000D_
 transition: top 300ms ease-out;_x000D_
 position: relative;_x000D_
}_x000D_
/* just demo */_x000D_
div {  _x000D_
  box-sizing: border-box;_x000D_
}_x000D_
.side-column {_x000D_
  float: left;_x000D_
  width: 20%;    _x000D_
}_x000D_
.main-column {_x000D_
  padding: 20px;_x000D_
  float: right;_x000D_
  width: 75%;_x000D_
  min-height: 1200px;_x000D_
  background-color: #EEEEEE;_x000D_
}_x000D_
.body {  _x000D_
  padding: 20px 0;  _x000D_
}_x000D_
.body:after {_x000D_
  content: ' ';_x000D_
  clear: both;_x000D_
  display: table;_x000D_
}_x000D_
.header {_x000D_
  padding: 20px;_x000D_
  text-align: center;_x000D_
  border-bottom: 2px solid #CCCCCC;  _x000D_
}_x000D_
.footer {_x000D_
  padding: 20px;_x000D_
  border-top: 2px solid #CCCCCC;_x000D_
  min-height: 300px;_x000D_
}
_x000D_
<script src="https://ajax.googleapis.com/ajax/libs/jquery/2.1.1/jquery.min.js"></script>_x000D_
<div>_x000D_
  <div class="header">_x000D_
      <h1>Your super-duper website</h1>_x000D_
  </div>_x000D_
  <div class="body">  _x000D_
    <div class="side-column">_x000D_
        <!-- part you need -->_x000D_
        <div class="slide-along-scroll">_x000D_
            Side menu content_x000D_
            <ul>_x000D_
               <li>Lorem ipsum dolor sit amet, consectetuer adipiscing elit.</li>_x000D_
               <li>Aliquam tincidunt mauris eu risus.</li>_x000D_
               <li>Vestibulum auctor dapibus neque.</li>_x000D_
            </ul>         _x000D_
        </div>_x000D_
    </div>_x000D_
    <div class="main-column">_x000D_
        Main content area (1200px)_x000D_
    </div>_x000D_
  </div>_x000D_
  <div class="footer">_x000D_
      Footer (slide along is limited by it)_x000D_
  </div>_x000D_
</div>
_x000D_
_x000D_
_x000D_

How to find foreign key dependencies in SQL Server?

USE information_schema;

SELECT COLUMN_NAME, REFERENCED_TABLE_NAME, REFERENCED_COLUMN_NAME
FROM KEY_COLUMN_USAGE
WHERE (table_name = *tablename*) AND NOT (REFERENCED_TABLE_NAME IS NULL)

How can I profile C++ code running on Linux?

If your goal is to use a profiler, use one of the suggested ones.

However, if you're in a hurry and you can manually interrupt your program under the debugger while it's being subjectively slow, there's a simple way to find performance problems.

Just halt it several times, and each time look at the call stack. If there is some code that is wasting some percentage of the time, 20% or 50% or whatever, that is the probability that you will catch it in the act on each sample. So, that is roughly the percentage of samples on which you will see it. There is no educated guesswork required. If you do have a guess as to what the problem is, this will prove or disprove it.

You may have multiple performance problems of different sizes. If you clean out any one of them, the remaining ones will take a larger percentage, and be easier to spot, on subsequent passes. This magnification effect, when compounded over multiple problems, can lead to truly massive speedup factors.

Caveat: Programmers tend to be skeptical of this technique unless they've used it themselves. They will say that profilers give you this information, but that is only true if they sample the entire call stack, and then let you examine a random set of samples. (The summaries are where the insight is lost.) Call graphs don't give you the same information, because

  1. They don't summarize at the instruction level, and
  2. They give confusing summaries in the presence of recursion.

They will also say it only works on toy programs, when actually it works on any program, and it seems to work better on bigger programs, because they tend to have more problems to find. They will say it sometimes finds things that aren't problems, but that is only true if you see something once. If you see a problem on more than one sample, it is real.

P.S. This can also be done on multi-thread programs if there is a way to collect call-stack samples of the thread pool at a point in time, as there is in Java.

P.P.S As a rough generality, the more layers of abstraction you have in your software, the more likely you are to find that that is the cause of performance problems (and the opportunity to get speedup).

Added: It might not be obvious, but the stack sampling technique works equally well in the presence of recursion. The reason is that the time that would be saved by removal of an instruction is approximated by the fraction of samples containing it, regardless of the number of times it may occur within a sample.

Another objection I often hear is: "It will stop someplace random, and it will miss the real problem". This comes from having a prior concept of what the real problem is. A key property of performance problems is that they defy expectations. Sampling tells you something is a problem, and your first reaction is disbelief. That is natural, but you can be sure if it finds a problem it is real, and vice-versa.

Added: Let me make a Bayesian explanation of how it works. Suppose there is some instruction I (call or otherwise) which is on the call stack some fraction f of the time (and thus costs that much). For simplicity, suppose we don't know what f is, but assume it is either 0.1, 0.2, 0.3, ... 0.9, 1.0, and the prior probability of each of these possibilities is 0.1, so all of these costs are equally likely a-priori.

Then suppose we take just 2 stack samples, and we see instruction I on both samples, designated observation o=2/2. This gives us new estimates of the frequency f of I, according to this:

Prior                                    
P(f=x) x  P(o=2/2|f=x) P(o=2/2&&f=x)  P(o=2/2&&f >= x)  P(f >= x | o=2/2)

0.1    1     1             0.1          0.1            0.25974026
0.1    0.9   0.81          0.081        0.181          0.47012987
0.1    0.8   0.64          0.064        0.245          0.636363636
0.1    0.7   0.49          0.049        0.294          0.763636364
0.1    0.6   0.36          0.036        0.33           0.857142857
0.1    0.5   0.25          0.025        0.355          0.922077922
0.1    0.4   0.16          0.016        0.371          0.963636364
0.1    0.3   0.09          0.009        0.38           0.987012987
0.1    0.2   0.04          0.004        0.384          0.997402597
0.1    0.1   0.01          0.001        0.385          1

                  P(o=2/2) 0.385                

The last column says that, for example, the probability that f >= 0.5 is 92%, up from the prior assumption of 60%.

Suppose the prior assumptions are different. Suppose we assume P(f=0.1) is .991 (nearly certain), and all the other possibilities are almost impossible (0.001). In other words, our prior certainty is that I is cheap. Then we get:

Prior                                    
P(f=x) x  P(o=2/2|f=x) P(o=2/2&& f=x)  P(o=2/2&&f >= x)  P(f >= x | o=2/2)

0.001  1    1              0.001        0.001          0.072727273
0.001  0.9  0.81           0.00081      0.00181        0.131636364
0.001  0.8  0.64           0.00064      0.00245        0.178181818
0.001  0.7  0.49           0.00049      0.00294        0.213818182
0.001  0.6  0.36           0.00036      0.0033         0.24
0.001  0.5  0.25           0.00025      0.00355        0.258181818
0.001  0.4  0.16           0.00016      0.00371        0.269818182
0.001  0.3  0.09           0.00009      0.0038         0.276363636
0.001  0.2  0.04           0.00004      0.00384        0.279272727
0.991  0.1  0.01           0.00991      0.01375        1

                  P(o=2/2) 0.01375                

Now it says P(f >= 0.5) is 26%, up from the prior assumption of 0.6%. So Bayes allows us to update our estimate of the probable cost of I. If the amount of data is small, it doesn't tell us accurately what the cost is, only that it is big enough to be worth fixing.

Yet another way to look at it is called the Rule Of Succession. If you flip a coin 2 times, and it comes up heads both times, what does that tell you about the probable weighting of the coin? The respected way to answer is to say that it's a Beta distribution, with average value (number of hits + 1) / (number of tries + 2) = (2+1)/(2+2) = 75%.

(The key is that we see I more than once. If we only see it once, that doesn't tell us much except that f > 0.)

So, even a very small number of samples can tell us a lot about the cost of instructions that it sees. (And it will see them with a frequency, on average, proportional to their cost. If n samples are taken, and f is the cost, then I will appear on nf+/-sqrt(nf(1-f)) samples. Example, n=10, f=0.3, that is 3+/-1.4 samples.)


Added: To give an intuitive feel for the difference between measuring and random stack sampling:
There are profilers now that sample the stack, even on wall-clock time, but what comes out is measurements (or hot path, or hot spot, from which a "bottleneck" can easily hide). What they don't show you (and they easily could) is the actual samples themselves. And if your goal is to find the bottleneck, the number of them you need to see is, on average, 2 divided by the fraction of time it takes. So if it takes 30% of time, 2/.3 = 6.7 samples, on average, will show it, and the chance that 20 samples will show it is 99.2%.

Here is an off-the-cuff illustration of the difference between examining measurements and examining stack samples. The bottleneck could be one big blob like this, or numerous small ones, it makes no difference.

enter image description here

Measurement is horizontal; it tells you what fraction of time specific routines take. Sampling is vertical. If there is any way to avoid what the whole program is doing at that moment, and if you see it on a second sample, you've found the bottleneck. That's what makes the difference - seeing the whole reason for the time being spent, not just how much.

How do I parse a HTML page with Node.js

jsdom is too strict to do any real screen scraping sort of things, but beautifulsoup doesn't choke on bad markup.

node-soupselect is a port of python's beautifulsoup into nodejs, and it works beautifully

What's the difference between "app.render" and "res.render" in express.js?

Here are some differences:

  1. You can call app.render on root level and res.render only inside a route/middleware.

  2. app.render always returns the html in the callback function, whereas res.render does so only when you've specified the callback function as your third parameter. If you call res.render without the third parameter/callback function the rendered html is sent to the client with a status code of 200.

    Take a look at the following examples.

    • app.render

      app.render('index', {title: 'res vs app render'}, function(err, html) {
          console.log(html)
      });
      
      // logs the following string (from default index.jade)
      <!DOCTYPE html><html><head><title>res vs app render</title><link rel="stylesheet" href="/stylesheets/style.css"></head><body><h1>res vs app render</h1><p>Welcome to res vs app render</p></body></html>
      
    • res.render without third parameter

      app.get('/render', function(req, res) {
          res.render('index', {title: 'res vs app render'})
      })
      
      // also renders index.jade but sends it to the client 
      // with status 200 and content-type text/html on GET /render
      
    • res.render with third parameter

      app.get('/render', function(req, res) {
          res.render('index', {title: 'res vs app render'}, function(err, html) {
              console.log(html);
              res.send('done');
          })
      })
      
      // logs the same as app.render and sends "done" to the client instead 
      // of the content of index.jade
      
  3. res.render uses app.render internally to render template files.

  4. You can use the render functions to create html emails. Depending on your structure of your app, you might not always have acces to the app object.

    For example inside an external route:

    app.js

    var routes = require('routes');
    
    app.get('/mail', function(req, res) {
        // app object is available -> app.render
    })
    
    app.get('/sendmail', routes.sendmail);
    

    routes.js

    exports.sendmail = function(req, res) {
        // can't use app.render -> therefore res.render
    }
    

How to clear an EditText on click?

Code for clearing up the text field when clicked

<EditText android:onClick="TextFieldClicked"/>

public void TextFieldClicked(View view){      
      if(view.getId()==R.id.editText1);
           text.setText("");    
}

How to increase the clickable area of a <a> tag button?

Big thanks to the contributors to the answers here, it pointed me in the right direction.

For the Bootstrap4 users out there, this worked for me. Sets the a link (tap target) to correct size to pass the Lighthouse Site Audit on mobiles.

    <span class="small">
         <a class="d-inline position-relative p-3 m-n3" style="z-index: 1;" href="/AdvancedSearch" title="Advanced Site Search using extra optional filters">Advanced Site Search</a>
    </span>

How to map an array of objects in React

@FurkanO has provided the right approach. Though to go for a more cleaner approach (es6 way) you can do something like this

[{
    name: 'Sam',
    email: '[email protected]'
 },
 {
    name: 'Ash',
    email: '[email protected]'
 }
].map( ( {name, email} ) => {
    return <p key={email}>{name} - {email}</p>
})

Cheers!

Difference between x86, x32, and x64 architectures?

x86 refers to the Intel processor architecture that was used in PCs. Model numbers were 8088 (8 bit bus version of 8086 and used in the first IBM PC), 8086, 286, 386, 486. After which they switched to names instead of numbers to stop AMD from copying the processor names. Pentium etc, never a Hexium :).

x64 is the architecture name for the extensions to the x86 instruction set that enable 64-bit code. Invented by AMD and later copied by Intel when they couldn't get their own 64-bit arch to be competitive, Itanium didn't fare well. Other names for it are x86_64, AMD's original name and commonly used in open source tools. And amd64, AMD's next name and commonly used in Microsoft tools. Intel's own names for it (EM64T and "Intel 64") never caught on.

x32 is a fuzzy term that's not associated with hardware. It tends to be used to mean "32-bit" or "32-bit pointer architecture", Linux has an ABI by that name.

link button property to open in new tab?

Here is your Tag.

<asp:LinkButton ID="LinkButton1" runat="server">Open Test Page</asp:LinkButton>

Here is your code on the code behind.

LinkButton1.Attributes.Add("href","../Test.aspx")
LinkButton1.Attributes.Add("target","_blank")

Hope this will be helpful for someone.

Edit To do the same with a link button inside a template field, use the following code.

Use GridView_RowDataBound event to find Link button.

Dim LB as LinkButton = e.Row.FindControl("LinkButton1")         
LB.Attributes.Add("href","../Test.aspx")  
LB.Attributes.Add("target","_blank")

Configure active profile in SpringBoot via Maven

You can run using the following command. Here I want to run using spring profile local:

spring-boot:run -Drun.jvmArguments="-Dspring.profiles.active=local"

Why is it important to override GetHashCode when Equals method is overridden?

Just to add on above answers:

If you don't override Equals then the default behavior is that references of the objects are compared. The same applies to hashcode - the default implmentation is typically based on a memory address of the reference. Because you did override Equals it means the correct behavior is to compare whatever you implemented on Equals and not the references, so you should do the same for the hashcode.

Clients of your class will expect the hashcode to have similar logic to the equals method, for example linq methods which use a IEqualityComparer first compare the hashcodes and only if they're equal they'll compare the Equals() method which might be more expensive to run, if we didn't implement hashcode, equal object will probably have different hashcodes (because they have different memory address) and will be determined wrongly as not equal (Equals() won't even hit).

In addition, except the problem that you might not be able to find your object if you used it in a dictionary (because it was inserted by one hashcode and when you look for it the default hashcode will probably be different and again the Equals() won't even be called, like Marc Gravell explains in his answer, you also introduce a violation of the dictionary or hashset concept which should not allow identical keys - you already declared that those objects are essentially the same when you overrode Equals so you don't want both of them as different keys on a data structure which suppose to have a unique key. But because they have a different hashcode the "same" key will be inserted as different one.

Printing integer variable and string on same line in SQL

Numbers have higher precedence than strings so of course the + operators want to convert your strings into numbers before adding.

You could do:

print 'There are ' + CONVERT(varchar(10),@Number) +
      ' alias combinations did not match a record'

or use the (rather limited) formatting facilities of RAISERROR:

RAISERROR('There are %i alias combinations did not match a record',10,1,@Number)
WITH NOWAIT

Make an existing Git branch track a remote branch?

Use '--track' Option

  • After a git pull :

    git checkout --track <remote-branch-name>

  • Or:

    git fetch && git checkout <branch-name>

How to get week number in Python?

datetime.date has a isocalendar() method, which returns a tuple containing the calendar week:

>>> import datetime
>>> datetime.date(2010, 6, 16).isocalendar()[1]
24

datetime.date.isocalendar() is an instance-method returning a tuple containing year, weeknumber and weekday in respective order for the given date instance.

Choose Git merge strategy for specific files ("ours", "mine", "theirs")

Even though this question is answered, providing an example as to what "theirs" and "ours" means in the case of git rebase vs merge. See this link

Git Rebase
theirs is actually the current branch in the case of rebase. So the below set of commands are actually accepting your current branch changes over the remote branch.

# see current branch
$ git branch
... 
* branch-a
# rebase preferring current branch changes during conflicts
$ git rebase -X theirs branch-b

Git Merge
For merge, the meaning of theirs and ours is reversed. So, to get the same effect during a merge, i.e., keep your current branch changes (ours) over the remote branch being merged (theirs).

# assuming branch-a is our current version
$ git merge -X ours branch-b  # <- ours: branch-a, theirs: branch-b

CreateProcess: No such file or directory

This problem might arise if you have different versions of programs.

For instance, you have 1-year old gcc and you want to compile a C++ source code. If you use mingw-get to install g++, gcc and g++ will suddenly have different versions and you ware likely to find yourself in this situation.

Running mingw-get update and mingw-get upgrade has solved this issue for me.

Reactjs: Unexpected token '<' Error

If you're like me and prone to silly mistakes, also check your package.json if it contains your babel preset:

  "babel": {
    "presets": [
      "env",
      "react",
      "stage-2"
    ]
  },

How to render an ASP.NET MVC view as a string?

you are get the view in string using this way

protected string RenderPartialViewToString(string viewName, object model)
{
    if (string.IsNullOrEmpty(viewName))
        viewName = ControllerContext.RouteData.GetRequiredString("action");

    if (model != null)
        ViewData.Model = model;

    using (StringWriter sw = new StringWriter())
    {
        ViewEngineResult viewResult = ViewEngines.Engines.FindPartialView(ControllerContext, viewName);
        ViewContext viewContext = new ViewContext(ControllerContext, viewResult.View, ViewData, TempData, sw);
        viewResult.View.Render(viewContext, sw);

        return sw.GetStringBuilder().ToString();
    }
}

We are call this method in two way

string strView = RenderPartialViewToString("~/Views/Shared/_Header.cshtml", null)

OR

var model = new Person()
string strView = RenderPartialViewToString("~/Views/Shared/_Header.cshtml", model)

What are good grep tools for Windows?

UnxUtils is the one I use, works perfectly for me...

How to print pthread_t

This will print out a hexadecimal representation of a pthread_t, no matter what that actually is:

void fprintPt(FILE *f, pthread_t pt) {
  unsigned char *ptc = (unsigned char*)(void*)(&pt);
  fprintf(f, "0x");
  for (size_t i=0; i<sizeof(pt); i++) {
    fprintf(f, "%02x", (unsigned)(ptc[i]));
  }
}

To just print a small id for a each pthread_t something like this could be used (this time using iostreams):

void printPt(std::ostream &strm, pthread_t pt) {
  static int nextindex = 0;
  static std::map<pthread_t, int> ids;
  if (ids.find(pt) == ids.end()) {
    ids[pt] = nextindex++;
  }
  strm << ids[pt];
}

Depending on the platform and the actual representation of pthread_t it might here be necessary to define an operator< for pthread_t, because std::map needs an ordering on the elements:

bool operator<(const pthread_t &left, const pthread_t &right) {
  ...
}

Data access object (DAO) in Java

Spring JPA DAO

For example we have some entity Group.

For this entity we create the repository GroupRepository.

public interface GroupRepository extends JpaRepository<Group, Long> {   
}

Then we need to create a service layer with which we will use this repository.

public interface Service<T, ID> {

    T save(T entity);

    void deleteById(ID id);

    List<T> findAll();

    T getOne(ID id);

    T editEntity(T entity);

    Optional<T> findById(ID id);
}

public abstract class AbstractService<T, ID, R extends JpaRepository<T, ID>> implements Service<T, ID> {

    private final R repository;

    protected AbstractService(R repository) {
        this.repository = repository;
    }

    @Override
    public T save(T entity) {
        return repository.save(entity);
    }

    @Override
    public void deleteById(ID id) {
        repository.deleteById(id);
    }

    @Override
    public List<T> findAll() {
        return repository.findAll();
    }

    @Override
    public T getOne(ID id) {
        return repository.getOne(id);
    }

    @Override
    public Optional<T> findById(ID id) {
        return repository.findById(id);
    }

    @Override
    public T editEntity(T entity) {
        return repository.saveAndFlush(entity);
    }
}

@org.springframework.stereotype.Service
public class GroupServiceImpl extends AbstractService<Group, Long, GroupRepository> {

    private final GroupRepository groupRepository;

    @Autowired
    protected GroupServiceImpl(GroupRepository repository) {
        super(repository);
        this.groupRepository = repository;
    }
}

And in the controller we use this service.

@RestController
@RequestMapping("/api")
class GroupController {

    private final Logger log = LoggerFactory.getLogger(GroupController.class);

    private final GroupServiceImpl groupService;

    @Autowired
    public GroupController(GroupServiceImpl groupService) {
        this.groupService = groupService;
    }

    @GetMapping("/groups")
    Collection<Group> groups() {
        return groupService.findAll();
    }

    @GetMapping("/group/{id}")
    ResponseEntity<?> getGroup(@PathVariable Long id) {
        Optional<Group> group = groupService.findById(id);
        return group.map(response -> ResponseEntity.ok().body(response))
                .orElse(new ResponseEntity<>(HttpStatus.NOT_FOUND));
    }

    @PostMapping("/group")
    ResponseEntity<Group> createGroup(@Valid @RequestBody Group group) throws URISyntaxException {
        log.info("Request to create group: {}", group);
        Group result = groupService.save(group);
        return ResponseEntity.created(new URI("/api/group/" + result.getId()))
                .body(result);
    }

    @PutMapping("/group")
    ResponseEntity<Group> updateGroup(@Valid @RequestBody Group group) {
        log.info("Request to update group: {}", group);
        Group result = groupService.save(group);
        return ResponseEntity.ok().body(result);
    }

    @DeleteMapping("/group/{id}")
    public ResponseEntity<?> deleteGroup(@PathVariable Long id) {
        log.info("Request to delete group: {}", id);
        groupService.deleteById(id);
        return ResponseEntity.ok().build();
    }    
}

iReport not starting using JRE 8

There's another way if you don't want to have older Java versions installed you can do the following:

1) Download the iReport-5.6.0.zip from https://sourceforge.net/projects/ireport/files/iReport/iReport-5.6.0/

2) Download jre-7u67-windows-x64.tar.gz (the one packed in a tar) from https://www.oracle.com/technetwork/java/javase/downloads/java-archive-downloads-javase7-521261.html

3) Extract the iReport and in the extracted folder that contains the bin and etc folders throw in the jre. For example if you unpack twice the jre-7u67-windows-x64.tar.gz you end up with a folder named jre1.7.0_67. Put that folder in the iReport-5.6.0 directory:

enter image description here

and then go into the etc folder and edit the file ireport.conf and add the following line into it:

For Windows jdkhome=".\jre1.7.0_67"

For Linux jdkhome="./jre1.7.0_67"

Note : jre version may change! according to your download of 1.7

enter image description here

now if you run the ireport_w.exe from the bin folder in the iReport directory it should load just fine.

Print array elements on separate lines in Bash?

Just quote the argument to echo:

( IFS=$'\n'; echo "${my_array[*]}" )

the sub shell helps restoring the IFS after use

How do I get column datatype in Oracle with PL-SQL with low privileges?

The best solution that I've found for such case is

select column_name, data_type||
case
when data_precision is not null and nvl(data_scale,0)>0 then '('||data_precision||','||data_scale||')'
when data_precision is not null and nvl(data_scale,0)=0 then '('||data_precision||')'
when data_precision is null and data_scale is not null then '(*,'||data_scale||')'
when char_length>0 then '('||char_length|| case char_used 
                                                         when 'B' then ' Byte'
                                                         when 'C' then ' Char'
                                                         else null 
                                           end||')'
end||decode(nullable, 'N', ' NOT NULL')
from user_tab_columns
where table_name = 'TABLE_NAME'
and column_name = 'COLUMN_NAME';

@Aaron Stainback, thank you for correction!

Starting with Zend Tutorial - Zend_DB_Adapter throws Exception: "SQLSTATE[HY000] [2002] No such file or directory"

i had this problem when running the magento indexer in osx. and yes its related to php problem when connecting to mysql through pdo

in mac osx xampp, to fix this you have create symbolic link to directory /var/mysql, here is how

cd /var/mysql && sudo ln -s /Applications/XAMPP/xamppfiles/var/mysql/mysql.sock

if the directory /var/mysql doesnt exist, we must create it with

sudo mkdir /var/mysql

Python if-else short-hand

Try this:

x = a > b and 10 or 11

This is a sample of execution:

>>> a,b=5,7
>>> x = a > b and 10 or 11
>>> print x
11

PHP UML Generator

I strongly recommend BOUML which:

  • is extremely fast (fastest UML tool ever created, check out benchmarks),
  • has rock solid PHP import and export support (also supports C++, Java, Python)
  • is multiplatform (Linux, Windows, other OSes),
  • is full featured, impressively intensively developed (look at development history, it's hard to believe that such fast progress is possible).
  • supports plugins, has modular architecture (this allows user contributions, looks like BOUML community is forming up)

Missing include "bits/c++config.h" when cross compiling 64 bit program on 32 bit in Ubuntu

While compiling in RHEL 6.2 (x86_64), I installed both 32bit and 64bit libstdc++-dev packages, but I had the "c++config.h no such file or directory" problem.

Resolution:

The directory /usr/include/c++/4.4.6/x86_64-redhat-linux was missing.

I did the following:

cd /usr/include/c++/4.4.6/
mkdir x86_64-redhat-linux
cd x86_64-redhat-linux
ln -s ../i686-redhat-linux 32

I'm now able to compile 32bit binaries on a 64bit OS.

rails simple_form - hidden field - create?

Shortest Yet !!!

=f.hidden_field :title, :value => "some value"

Shorter, DRYer and perhaps more obvious.

Of course with ruby 1.9 and the new hash format we can go 3 characters shorter with...

=f.hidden_field :title, value: "some value"

Facebook Architecture

Facebook is using LAMP structure. Facebook’s back-end services are written in a variety of different programming languages including C++, Java, Python, and Erlang and they are used according to requirement. With LAMP Facebook uses some technologies ,to support large number of requests, like

  1. Memcache - It is a memory caching system that is used to speed up dynamic database-driven websites (like Facebook) by caching data and objects in RAM to reduce reading time. Memcache is Facebook’s primary form of caching and helps alleviate the database load. Having a caching system allows Facebook to be as fast as it is at recalling your data.

  2. Thrift (protocol) - It is a lightweight remote procedure call framework for scalable cross-language services development. Thrift supports C++, PHP, Python, Perl, Java, Ruby, Erlang, and others.

  3. Cassandra (database) - It is a database management system designed to handle large amounts of data spread out across many servers.

  4. HipHop for PHP - It is a source code transformer for PHP script code and was created to save server resources. HipHop transforms PHP source code into optimized C++. After doing this, it uses g++ to compile it to machine code.

If we go into more detail, then answer to this question go longer. We can understand more from following posts:

  1. How Does Facebook Work?
  2. Data Management, Facebook-style
  3. Facebook database design?
  4. Facebook wall's database structure
  5. Facebook "like" data structure

Parse large JSON file in Nodejs

To process a file line-by-line, you simply need to decouple the reading of the file and the code that acts upon that input. You can accomplish this by buffering your input until you hit a newline. Assuming we have one JSON object per line (basically, format B):

var stream = fs.createReadStream(filePath, {flags: 'r', encoding: 'utf-8'});
var buf = '';

stream.on('data', function(d) {
    buf += d.toString(); // when data is read, stash it in a string buffer
    pump(); // then process the buffer
});

function pump() {
    var pos;

    while ((pos = buf.indexOf('\n')) >= 0) { // keep going while there's a newline somewhere in the buffer
        if (pos == 0) { // if there's more than one newline in a row, the buffer will now start with a newline
            buf = buf.slice(1); // discard it
            continue; // so that the next iteration will start with data
        }
        processLine(buf.slice(0,pos)); // hand off the line
        buf = buf.slice(pos+1); // and slice the processed data off the buffer
    }
}

function processLine(line) { // here's where we do something with a line

    if (line[line.length-1] == '\r') line=line.substr(0,line.length-1); // discard CR (0x0D)

    if (line.length > 0) { // ignore empty lines
        var obj = JSON.parse(line); // parse the JSON
        console.log(obj); // do something with the data here!
    }
}

Each time the file stream receives data from the file system, it's stashed in a buffer, and then pump is called.

If there's no newline in the buffer, pump simply returns without doing anything. More data (and potentially a newline) will be added to the buffer the next time the stream gets data, and then we'll have a complete object.

If there is a newline, pump slices off the buffer from the beginning to the newline and hands it off to process. It then checks again if there's another newline in the buffer (the while loop). In this way, we can process all of the lines that were read in the current chunk.

Finally, process is called once per input line. If present, it strips off the carriage return character (to avoid issues with line endings – LF vs CRLF), and then calls JSON.parse one the line. At this point, you can do whatever you need to with your object.

Note that JSON.parse is strict about what it accepts as input; you must quote your identifiers and string values with double quotes. In other words, {name:'thing1'} will throw an error; you must use {"name":"thing1"}.

Because no more than a chunk of data will ever be in memory at a time, this will be extremely memory efficient. It will also be extremely fast. A quick test showed I processed 10,000 rows in under 15ms.

Error occurred during initialization of boot layer FindException: Module not found

You say that your module-info.java contains

module myModule {}

That means it declares a module called myModule, not com.pantech.myModule. Pointing this from the command format:

 -m <module-name>/<main-class>

How to convert Varchar to Int in sql server 2008?

That is the correct way to convert it to an INT as long as you don't have any alpha characters or NULL values.

If you have any NULL values, use

ISNULL(column1, 0)

Why does configure say no C compiler found when GCC is installed?

Sometime gcc had created as /usr/bin/gcc32. so please create a ln -s /usr/bin/gcc32 /usr/bin/gcc and then compile that ./configure.

What does a bitwise shift (left or right) do and what is it used for?

Here is an applet where you can exercise some bit-operations, including shifting.

You have a collection of bits, and you move some of them beyond their bounds:

1111 1110 << 2
1111 1000

It is filled from the right with fresh zeros. :)

0001 1111 >> 3
0000 0011

Filled from the left. A special case is the leading 1. It often indicates a negative value - depending on the language and datatype. So often it is wanted, that if you shift right, the first bit stays as it is.

1100 1100 >> 1
1110 0110

And it is conserved over multiple shifts:

1100 1100 >> 2
1111 0011

If you don't want the first bit to be preserved, you use (in Java, Scala, C++, C as far as I know, and maybe more) a triple-sign-operator:

1100 1100 >>> 1
0110 0110

There isn't any equivalent in the other direction, because it doesn't make any sense - maybe in your very special context, but not in general.

Mathematically, a left-shift is a *=2, 2 left-shifts is a *=4 and so on. A right-shift is a /= 2 and so on.

Filename too long in Git for Windows

Move repository to root of your drive (temporary fix)

You can try to temporarily move the local repository (the entire folder) to the root of your drive or as close to the root as possible.

Since the path is smaller at the root of the drive, it sometimes fixes the issues.

On Windows, I'd move this to C:\ or another drive's root.

How to get JQuery.trigger('click'); to initiate a mouse click

This is JQuery behavior. I'm not sure why it works this way, it only triggers the onClick function on the link.

Try:

jQuery(document).ready(function() {
    jQuery('#foo').on('click', function() {
        jQuery('#bar')[0].click();
    });
});

Entity Framework Code First - two Foreign Keys from same table

InverseProperty in EF Core makes the solution easy and clean.

InverseProperty

So the desired solution would be:

public class Team
{
    [Key]
    public int TeamId { get; set;} 
    public string Name { get; set; }

    [InverseProperty(nameof(Match.HomeTeam))]
    public ICollection<Match> HomeMatches{ get; set; }

    [InverseProperty(nameof(Match.GuestTeam))]
    public ICollection<Match> AwayMatches{ get; set; }
}


public class Match
{
    [Key]
    public int MatchId { get; set; }

    [ForeignKey(nameof(HomeTeam)), Column(Order = 0)]
    public int HomeTeamId { get; set; }
    [ForeignKey(nameof(GuestTeam)), Column(Order = 1)]
    public int GuestTeamId { get; set; }

    public float HomePoints { get; set; }
    public float GuestPoints { get; set; }
    public DateTime Date { get; set; }

    public Team HomeTeam { get; set; }
    public Team GuestTeam { get; set; }
}

Shortcut key for commenting out lines of Python code in Spyder

  • Unblock multi-line comment

    Ctrl+5

  • Multi-line comment

    Ctrl+4

NOTE: For my version of Spyder (3.1.4) if I highlighted the entire multi-line comment and used Ctrl+5 the block remained commented out. Only after highlighting a small portion of the multi-line comment did Ctrl+5 work.

Capturing URL parameters in request.GET

Using GET

request.GET["id"]

Using POST

request.POST["id"]

How can I extract audio from video with ffmpeg?

Here's what I just used:

ffmpeg -i my.mkv -map 0:3 -vn -b:a 320k my.mp3

Options explanation:

  • my.mkv is a source video file, you can use other formats as well
  • -map 0:3 means I want 3rd stream from video file. Put your N there - video files often has multiple audio streams; you can omit it or use -map 0:a to take the default audio stream. Run ffprobe my.mkv to see what streams does the video file have.
  • my.mp3 is a target audio filename, and ffmpeg figures out I want an MP3 from its extension. In my case the source audio stream is ac3 DTS and just copying wasn't what I wanted
  • 320k is a desired target bitrate
  • -vn means I don't want video in target file

How to stop flask application without using ctrl-c

If you're outside the request-response handling, you can still:

import os
import signal

sig = getattr(signal, "SIGKILL", signal.SIGTERM)
os.kill(os.getpid(), sig)

How to copy a folder via cmd?

xcopy  "C:\Documents and Settings\user\Desktop\?????????" "D:\Backup" /s /e /y /i

Probably the problem is the space.Try with quotes.

How to create multiple class objects with a loop in python?

This question is asked every day in some variation. The answer is: keep your data out of your variable names, and this is the obligatory blog post.

In this case, why not make a list of objs?

objs = [MyClass() for i in range(10)]
for obj in objs:
    other_object.add(obj)

objs[0].do_sth()

How to use ADB in Android Studio to view an SQLite DB

You can use a very nice tool called Stetho by adding this to build.gradle file:

compile 'com.facebook.stetho:stetho:1.4.1'

And initialized it inside your Application or Activity onCreate() method:

@Override
protected void onCreate(Bundle savedInstanceState) {
    super.onCreate(savedInstanceState);
    Stetho.initializeWithDefaults(this);
    setContentView(R.layout.activity_main);
}

Then you can view the db records in chrome in the address:

chrome://inspect/#devices

For more details you can read my post: How to view easily your db records

Python TypeError: not enough arguments for format string

Note that the % syntax for formatting strings is becoming outdated. If your version of Python supports it, you should write:

instr = "'{0}', '{1}', '{2}', '{3}', '{4}', '{5}', '{6}'".format(softname, procversion, int(percent), exe, description, company, procurl)

This also fixes the error that you happened to have.

Node.js res.setHeader('content-type', 'text/javascript'); pushing the response javascript as file download

Use application/javascript as content type instead of text/javascript

text/javascript is mentioned obsolete. See reference docs.

http://www.iana.org/assignments/media-types/application

Also see this question on SO.

UPDATE:

I have tried executing the code you have given and the below didn't work.

res.setHeader('content-type', 'text/javascript');
res.send(JS_Script);

This is what worked for me.

res.setHeader('content-type', 'text/javascript');
res.end(JS_Script);

As robertklep has suggested, please refer to the node http docs, there is no response.send() there.

Android WebView Cookie Problem

Note that it may be better use subdomains instead of usual URL. So, set .example.com instead of https://example.com/.

Thanks to Jody Jacobus Geers and others I wrote so:

if (savedInstanceState == null) {
    val cookieManager = CookieManager.getInstance()
    cookieManager.acceptCookie()
    val domain = ".example.com"
    if (Build.VERSION.SDK_INT >= Build.VERSION_CODES.LOLLIPOP) {
        cookieManager.setCookie(domain, "token=$token") {
            view.webView.loadUrl(url)
        }
        cookieManager.setAcceptThirdPartyCookies(view.webView, true)
    } else {
        cookieManager.setCookie(domain, "token=$token")
        view.webView.loadUrl(url)
    }
} else {
    // Check whether we're recreating a previously destroyed instance.
    view.webView.restoreState(savedInstanceState)
}

How can I drop a "not null" constraint in Oracle when I don't know the name of the constraint?

Just remember, if the field you want to make nullable is part of a primary key, you can't. Primary Keys cannot have null fields.

C++ display stack trace on exception

Since the stack is already unwound when entering the catch block, the solution in my case was to not catch certain exceptions which then lead to a SIGABRT. In the signal handler for SIGABRT I then fork() and execl() either gdb (in debug builds) or Google breakpads stackwalk (in release builds). Also I try to only use signal handler safe functions.

GDB:

static const char BACKTRACE_START[] = "<2>--- backtrace of entire stack ---\n";
static const char BACKTRACE_STOP[] = "<2>--- backtrace finished ---\n";

static char *ltrim(char *s)
{
    while (' ' == *s) {
        s++;
    }
    return s;
}

void Backtracer::print()
{
    int child_pid = ::fork();
    if (child_pid == 0) {
        // redirect stdout to stderr
        ::dup2(2, 1);

        // create buffer for parent pid (2+16+1 spaces to allow up to a 64 bit hex parent pid)
        char pid_buf[32];
        const char* stem = "                   ";
        const char* s = stem;
        char* d = &pid_buf[0];
        while (static_cast<bool>(*s))
        {
            *d++ = *s++;
        }
        *d-- = '\0';
        char* hexppid = d;

        // write parent pid to buffer and prefix with 0x
        int ppid = getppid();
        while (ppid != 0) {
            *hexppid = ((ppid & 0xF) + '0');
            if(*hexppid > '9') {
                *hexppid += 'a' - '0' - 10;
            }
            --hexppid;
            ppid >>= 4;
        }
        *hexppid-- = 'x';
        *hexppid = '0';

        // invoke GDB
        char name_buf[512];
        name_buf[::readlink("/proc/self/exe", &name_buf[0], 511)] = 0;
        ssize_t r = ::write(STDERR_FILENO, &BACKTRACE_START[0], sizeof(BACKTRACE_START));
        (void)r;
        ::execl("/usr/bin/gdb",
                "/usr/bin/gdb", "--batch", "-n", "-ex", "thread apply all bt full", "-ex", "quit",
                &name_buf[0], ltrim(&pid_buf[0]), nullptr);
        ::exit(1); // if GDB failed to start
    } else if (child_pid == -1) {
        ::exit(1); // if forking failed
    } else {
        // make it work for non root users
        if (0 != getuid()) {
            ::prctl(PR_SET_PTRACER, PR_SET_PTRACER_ANY, 0, 0, 0);
        }
        ::waitpid(child_pid, nullptr, 0);
        ssize_t r = ::write(STDERR_FILENO, &BACKTRACE_STOP[0], sizeof(BACKTRACE_STOP));
        (void)r;
    }
}

minidump_stackwalk:

static bool dumpCallback(const google_breakpad::MinidumpDescriptor& descriptor, void* context, bool succeeded)
{
    int child_pid = ::fork();
    if (child_pid == 0) {
        ::dup2(open("/dev/null", O_WRONLY), 2); // ignore verbose output on stderr
        ssize_t r = ::write(STDOUT_FILENO, &MINIDUMP_STACKWALK_START[0], sizeof(MINIDUMP_STACKWALK_START));
        (void)r;
        ::execl("/usr/bin/minidump_stackwalk", "/usr/bin/minidump_stackwalk", descriptor.path(), "/usr/share/breakpad-syms", nullptr);
        ::exit(1); // if minidump_stackwalk failed to start
    } else if (child_pid == -1) {
        ::exit(1); // if forking failed
    } else {
        ::waitpid(child_pid, nullptr, 0);
        ssize_t r = ::write(STDOUT_FILENO, &MINIDUMP_STACKWALK_STOP[0], sizeof(MINIDUMP_STACKWALK_STOP));
        (void)r;
    }
    ::remove(descriptor.path()); // this is not signal safe anymore but should still work
    return succeeded;
}

Edit: To make it work for breakpad I also had to add this:

std::set_terminate([]()
{
    ssize_t r = ::write(STDERR_FILENO, EXCEPTION, sizeof(EXCEPTION));
    (void)r;
    google_breakpad::ExceptionHandler::WriteMinidump(std::string("/tmp"), dumpCallback, NULL);
    exit(1); // avoid creating a second dump by not calling std::abort
});

Source: How to get a stack trace for C++ using gcc with line number information? and Is it possible to attach gdb to a crashed process (a.k.a "just-in-time" debugging)

HTML5 iFrame Seamless Attribute

It is possible to use the semless attribute right now, here i found a german article http://www.solife.cc/blog/html5-iframe-attribut-seamless-beispiele.html

and here are another presentation about this topic: http://benvinegar.github.com/seamless-talk/

You have to use the window.postMessage method to communicate between the parent and the iframe.

When to use setAttribute vs .attribute= in JavaScript?

From Javascript: The Definitive Guide, it clarifies things. It notes that HTMLElement objects of a HTML doc define JS properties that correspond to all standard HTML attributes.

So you only need to use setAttribute for non-standard attributes.

Example:

node.className = 'test'; // works
node.frameborder = '0'; // doesn't work - non standard attribute
node.setAttribute('frameborder', '0'); // works

Haskell: Converting Int to String

The opposite of read is show.

Prelude> show 3
"3"

Prelude> read $ show 3 :: Int
3