Programs & Examples On #Eventaggregator

pandas DataFrame: replace nan values with average of columns

Pandas: How to replace NaN (nan) values with the average (mean), median or other statistics of one column

Say your DataFrame is df and you have one column called nr_items. This is: df['nr_items']

If you want to replace the NaN values of your column df['nr_items'] with the mean of the column:

Use method .fillna():

mean_value=df['nr_items'].mean()
df['nr_item_ave']=df['nr_items'].fillna(mean_value)

I have created a new df column called nr_item_ave to store the new column with the NaN values replaced by the mean value of the column.

You should be careful when using the mean. If you have outliers is more recommendable to use the median

How to set default font family in React Native?

With React-Native 0.56, the above method of changing Text.prototype.render does not work anymore, so you have to use your own component, which can be done in one line!

MyText.js

export default props => <Text {...props} style={[{fontFamily: 'Helvetica'}, props.style]}>{props.children}</Text>

AnotherComponent.js

import Text from './MyText';

...
<Text>This will show in default font.</Text>
...

How to convert std::string to LPCSTR?

str.c_str() gives you a const char *, which is an LPCSTR (Long Pointer to Constant STRing) -- means that it's a pointer to a 0 terminated string of characters. W means wide string (composed of wchar_t instead of char).

How to navigate to to different directories in the terminal (mac)?

To check that the file you're trying to open actually exists, you can change directories in terminal using cd. To change to ~/Desktop/sass/css: cd ~/Desktop/sass/css. To see what files are in the directory: ls.

If you want information about either of those commands, use the man page: man cd or man ls, for example.

Google for "basic unix command line commands" or similar; that will give you numerous examples of moving around, viewing files, etc in the command line.

On Mac OS X, you can also use open to open a finder window: open . will open the current directory in finder. (open ~/Desktop/sass/css will open the ~/Desktop/sass/css).

Why shouldn't I use PyPy over CPython if PyPy is 6.3 times faster?

For a lot of projects, there is actually 0% difference between the different pythons in terms of speed. That is those that are dominated by engineering time and where all pythons have the same amount of library support.

.m2 , settings.xml in Ubuntu

As per Where is Maven Installed on Ubuntu it will first create your settings.xml on /usr/share/maven2/, then you can copy to your home folder as jens mentioned

$ cp /usr/share/maven3/conf/settings.xml ~/.m2/settings.xml

pythonw.exe or python.exe?

If you don't want a terminal window to pop up when you run your program, use pythonw.exe;
Otherwise, use python.exe

Regarding the syntax error: print is now a function in 3.x
So use instead:

print("a")

React JS get current date

OPTION 1: if you want to make a common utility function then you can use this

export function getCurrentDate(separator=''){

let newDate = new Date()
let date = newDate.getDate();
let month = newDate.getMonth() + 1;
let year = newDate.getFullYear();

return `${year}${separator}${month<10?`0${month}`:`${month}`}${separator}${date}`
}

and use it by just importing it as

import {getCurrentDate} from './utils'
console.log(getCurrentDate())

OPTION 2: or define and use in a class directly

getCurrentDate(separator=''){

let newDate = new Date()
let date = newDate.getDate();
let month = newDate.getMonth() + 1;
let year = newDate.getFullYear();

return `${year}${separator}${month<10?`0${month}`:`${month}`}${separator}${date}`
}

How to uninstall a Windows Service when there is no executable for it left on the system?

found here

I just tried on windows XP, it worked

local computer: sc \\. delete [service-name]

  Deleting services in Windows Server 2003

  We can use sc.exe in the Windows Server 2003 to control services, create services and delete services. Since some people thought they must directly modify the registry to delete a service, I would like to share how to use sc.exe to delete a service without directly modifying the registry so that decreased the possibility for system failures.

  To delete a service: 

  Click “start“ - “run“, and then enter “cmd“ to open Microsoft Command Console.

  Enter command:

  sc servername delete servicename

  For instance, sc \\dc delete myservice

  (Note: In this example, dc is my Domain Controller Server name, which is not the local machine, myservice is the name of the service I want to delete on the DC server.)

  Below is the official help of all sc functions:

  DESCRIPTION:
    SC is a command line program used for communicating with the
    NT Service Controller and services. 
  USAGE:
          sc

Error :- java runtime environment JRE or java development kit must be available in order to run eclipse

Check the eclipse.ini file and make sure there is no -vm option there that is pointing to a non existing java install now. You can delete the option to let Eclipse figure out what java install to use or change it so it's pointing to the new install.

What's the best way to calculate the size of a directory in .NET?

No, this looks like the recommended way to calculate directory size, the relevent method included below:

public static long DirSize(DirectoryInfo d) 
{    
    long size = 0;    
    // Add file sizes.
    FileInfo[] fis = d.GetFiles();
    foreach (FileInfo fi in fis) 
    {      
        size += fi.Length;    
    }
    // Add subdirectory sizes.
    DirectoryInfo[] dis = d.GetDirectories();
    foreach (DirectoryInfo di in dis) 
    {
        size += DirSize(di);   
    }
    return size;  
}

You would call with the root as:

Console.WriteLine("The size is {0} bytes.", DirSize(new DirectoryInfo(targetFolder));

...where targetFolder is the folder-size to calculate.

How can I cast int to enum?

Take the following example:

int one = 1;
MyEnum e = (MyEnum)one;

#define in Java

Manifold Preprocessor implemented as a javac compiler plugin is designed exclusively for conditional compilation of Java source code. It uses familiar C/C++ style of directives: #define, #undef, #if, #elif, #else, #endif, #error. and #warning.

It has Maven and Gradle plugins.

"The operation is not valid for the state of the transaction" error and transaction scope

After doing some research, it seems I cannot have two connections opened to the same database with the TransactionScope block. I needed to modify my code to look like this:

public void MyAddUpdateMethod()
{
    using (TransactionScope Scope = new TransactionScope(TransactionScopeOption.RequiresNew))
    {
        using(SQLServer Sql = new SQLServer(this.m_connstring))
        {
            //do my first add update statement            
        }

        //removed the method call from the first sql server using statement
        bool DoesRecordExist = this.SelectStatementCall(id)
    }
}

public bool SelectStatementCall(System.Guid id)
{
    using(SQLServer Sql = new SQLServer(this.m_connstring))
    {
        //create parameters
    }
}

Calculating time difference between 2 dates in minutes

I think you could use TIMESTAMPDIFF(unit,datetime_expr1,datetime_expr2) something like

select * from MyTab T where
TIMESTAMPDIFF(MINUTE,T.runTime,NOW()) > 20

Best way to get user GPS location in background in Android

Use : GCM Network Manager

Run this to start a periodic task that will be ran even after re-boot:

PeriodicTask task = new PeriodicTask.Builder()
    .setService(MyLocationService.class)
    .setTag("periodic")
    .setPeriod(30L)
    .setPersisted(true)
    .build();
mGcmNetworkManager.schedule(task);

then in onRunTask() get current location and use it (in this example, event is submitted at the end to let UI know that location was found):

    public void getLastKnownLocation() {
    Location lastKnownGPSLocation;
    Location lastKnownNetworkLocation;
    String gpsLocationProvider = LocationManager.GPS_PROVIDER;
    String networkLocationProvider = LocationManager.NETWORK_PROVIDER;

    try {
        locationManager = (LocationManager) App.get().getSystemService(Context.LOCATION_SERVICE);

        lastKnownNetworkLocation = locationManager.getLastKnownLocation(networkLocationProvider);
        lastKnownGPSLocation = locationManager.getLastKnownLocation(gpsLocationProvider);

        if (lastKnownGPSLocation != null) {
            Log.i(TAG, "lastKnownGPSLocation is used.");
            this.mCurrentLocation = lastKnownGPSLocation;
        } else if (lastKnownNetworkLocation != null) {
            Log.i(TAG, "lastKnownNetworkLocation is used.");
            this.mCurrentLocation = lastKnownNetworkLocation;
        } else {
            Log.e(TAG, "lastLocation is not known.");
            return;
        }

        LocationChangedEvent event = new LocationChangedEvent();
        event.setLocation(mCurrentLocation);
        EventHelper.publishEvent(event);

    } catch (SecurityException sex) {
        Log.e(TAG, "Location permission is not granted!");
    }

    return;
}

The MyLocationService in whole:

public class MyLocationService extends GcmTaskService {
private static final String TAG = MyLocationService.class.getSimpleName();

private LocationManager locationManager;
private Location mCurrentLocation;

public static final String TASK_GET_LOCATION_ONCE="location_oneoff_task";
public static final String TASK_GET_LOCATION_PERIODIC="location_periodic_task";


private static final int RC_PLAY_SERVICES = 123;

@Override
public void onInitializeTasks() {
    // When your package is removed or updated, all of its network tasks are cleared by
    // the GcmNetworkManager. You can override this method to reschedule them in the case of
    // an updated package. This is not called when your application is first installed.
    //
    // This is called on your application's main thread.
    startPeriodicLocationTask(TASK_GET_LOCATION_PERIODIC,
            30L, null);
}

@Override
public int onRunTask(TaskParams taskParams) {
    Log.d(TAG, "onRunTask: " + taskParams.getTag());

    String tag = taskParams.getTag();
    Bundle extras = taskParams.getExtras();
    // Default result is success.
    int result = GcmNetworkManager.RESULT_SUCCESS;

    switch (tag) {
        case TASK_GET_LOCATION_ONCE:
            getLastKnownLocation();
            break;

        case TASK_GET_LOCATION_PERIODIC:
            getLastKnownLocation();
            break;

    }

    return result;
}


public void getLastKnownLocation() {
    Location lastKnownGPSLocation;
    Location lastKnownNetworkLocation;
    String gpsLocationProvider = LocationManager.GPS_PROVIDER;
    String networkLocationProvider = LocationManager.NETWORK_PROVIDER;

    try {
        locationManager = (LocationManager) App.get().getSystemService(Context.LOCATION_SERVICE);

        lastKnownNetworkLocation = locationManager.getLastKnownLocation(networkLocationProvider);
        lastKnownGPSLocation = locationManager.getLastKnownLocation(gpsLocationProvider);

        if (lastKnownGPSLocation != null) {
            Log.i(TAG, "lastKnownGPSLocation is used.");
            this.mCurrentLocation = lastKnownGPSLocation;
        } else if (lastKnownNetworkLocation != null) {
            Log.i(TAG, "lastKnownNetworkLocation is used.");
            this.mCurrentLocation = lastKnownNetworkLocation;
        } else {
            Log.e(TAG, "lastLocation is not known.");
            return;
        }

        LocationChangedEvent event = new LocationChangedEvent();
        event.setLocation(mCurrentLocation);
        EventHelper.publishEvent(event);

    } catch (SecurityException sex) {
        Log.e(TAG, "Location permission is not granted!");
    }

    return;
}

public static void startOneOffLocationTask(String tag, Bundle extras) {
    Log.d(TAG, "startOneOffLocationTask");

    GcmNetworkManager mGcmNetworkManager = GcmNetworkManager.getInstance(App.get());
    OneoffTask.Builder taskBuilder = new OneoffTask.Builder()
            .setService(MyLocationService.class)
            .setTag(tag);

    if (extras != null) taskBuilder.setExtras(extras);

    OneoffTask task = taskBuilder.build();
    mGcmNetworkManager.schedule(task);
}

public static void startPeriodicLocationTask(String tag, Long period, Bundle extras) {
    Log.d(TAG, "startPeriodicLocationTask");

    GcmNetworkManager mGcmNetworkManager = GcmNetworkManager.getInstance(App.get());
    PeriodicTask.Builder taskBuilder = new PeriodicTask.Builder()
            .setService(MyLocationService.class)
            .setTag(tag)
            .setPeriod(period)
            .setPersisted(true)
            .setRequiredNetwork(Task.NETWORK_STATE_CONNECTED);

    if (extras != null) taskBuilder.setExtras(extras);

    PeriodicTask task = taskBuilder.build();
    mGcmNetworkManager.schedule(task);
}




public static boolean checkPlayServicesAvailable(Activity activity) {
    GoogleApiAvailability availability = GoogleApiAvailability.getInstance();
    int resultCode = availability.isGooglePlayServicesAvailable(App.get());

    if (resultCode != ConnectionResult.SUCCESS) {
        if (availability.isUserResolvableError(resultCode)) {
            // Show dialog to resolve the error.
            availability.getErrorDialog(activity, resultCode, RC_PLAY_SERVICES).show();
        }
        return false;
    } else {
        return true;
    }
}

Also add these 2 to the AndroidManifest.xml:

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

 <application...
 <service
        android:name=".api.location.MyLocationService"
        android:exported="true"
        android:permission="com.google.android.gms.permission.BIND_NETWORK_TASK_SERVICE">
        <intent-filter>
            <action android:name="com.google.android.gms.gcm.ACTION_TASK_READY" />
        </intent-filter>
    </service>

how to change color of TextinputLayout's label and edittext underline android

Add this attribute in Edittext tag and enjoy:

 android:backgroundTint="@color/colorWhite"

Send PHP variable to javascript function

A great option is to use jQuery/AJAX. Look at these examples and try them out on your server. In this example, in FILE1.php, note that it is passing a blank value. You can pass a value if you wish, which might look something like this (assuming javascript vars called username and password:

data: 'username='+username+'&password='+password,

In the FILE2.php example, you would retrieve those values like this:

$uname = $_POST['username'];
$pword = $_POST['password'];

Then do your MySQL lookup and return the values thus:

echo 'You are logged in';

This would deliver the message You are logged in to the success function in FILE1.php, and the message string would be stored in the variable called "data". Therefore, the alert(data); line in the success function would alert that message. Of course, you can echo anything that you like, even large amounts of HTML, such as entire table structures.

Here is another good example to review.

The approach is to create your form, and then use jQuery to detect the button press and submit the data to a secondary PHP file via AJAX. The above examples show how to do that.

The secondary PHP file receives the variables (if any are sent) and returns a response (whatever you choose to send). That response then appears in the Success: section of your AJAX call as "data" (in these examples).

The jQuery/AJAX code is javascript, so you have two options: you can place it within <script type="text/javascript"></script> tags within your main PHP document, or you can <?php include "my_javascript_stuff.js"; ?> at the bottom of your PHP document. If you are using jQuery, don't forget to include the jQuery library as in the examples given.

In your case, it sounds like you can pretty much mirror the first example I suggested, sending no data and receiving the response in the AJAX success function. Whatever you need to do with that data, though, you must do inside the success function. Seems a bit weird at first, but it works.

How do I force "git pull" to overwrite local files?

Warning, doing this will permanently delete your files if you have any directory/* entries in your gitignore file.

Some answers seem to be terrible. Terrible in the sense of what happened to @Lauri by following David Avsajanishvili suggestion.

Rather (git > v1.7.6):

git stash --include-untracked
git pull

Later you can clean the stash history.

Manually, one-by-one:

$ git stash list
stash@{0}: WIP on <branch>: ...
stash@{1}: WIP on <branch>: ...

$ git stash drop stash@{0}
$ git stash drop stash@{1}

Brutally, all-at-once:

$ git stash clear

Of course if you want to go back to what you stashed:

$ git stash list
...
$ git stash apply stash@{5}

Looking for simple Java in-memory cache

Another option for an in-memory java cache is cache2k. The in-memory performance is superior to EHCache and google guava, see the cache2k benchmarks page.

The usage pattern is similar to other caches. Here is an example:

Cache<String,String> cache = new Cache2kBuilder<String, String>() {}
  .expireAfterWrite(5, TimeUnit.MINUTES)    // expire/refresh after 5 minutes
  .resilienceDuration(30, TimeUnit.SECONDS) // cope with at most 30 seconds
                                          // outage before propagating 
                                          // exceptions
  .refreshAhead(true)                       // keep fresh when expiring
  .loader(new CacheLoader<String, String>() {
    @Override
    public String load(final String key) throws Exception {
      return ....;
    }
  })
  .build();
String val = cache.peek("something");
cache.put("something", "hello");
val = cache.get("something");

If you have google guava as dependency then trying out guava cache, may be a good alternative.

Removing the fragment identifier from AngularJS urls (# symbol)

Be sure to check browser support for the html5 history API:

  if(window.history && window.history.pushState){
    $locationProvider.html5Mode(true);
  }

Why is volatile needed in C?

Another use for volatile is signal handlers. If you have code like this:

int quit = 0;
while (!quit)
{
    /* very small loop which is completely visible to the compiler */
}

The compiler is allowed to notice the loop body does not touch the quit variable and convert the loop to a while (true) loop. Even if the quit variable is set on the signal handler for SIGINT and SIGTERM; the compiler has no way to know that.

However, if the quit variable is declared volatile, the compiler is forced to load it every time, because it can be modified elsewhere. This is exactly what you want in this situation.

Skip first line(field) in loop using CSV file?

There are many ways to skip the first line. In addition to those said by Bakuriu, I would add:

with open(filename, 'r') as f:
    next(f)
    for line in f:

and:

with open(filename,'r') as f:
    lines = f.readlines()[1:]

Count textarea characters

This code gets the maximum value from the maxlength attribute of the textarea and decreases the value as the user types.

<DEMO>

_x000D_
_x000D_
var el_t = document.getElementById('textarea');_x000D_
var length = el_t.getAttribute("maxlength");_x000D_
var el_c = document.getElementById('count');_x000D_
el_c.innerHTML = length;_x000D_
el_t.onkeyup = function () {_x000D_
  document.getElementById('count').innerHTML = (length - this.value.length);_x000D_
};
_x000D_
<textarea id="textarea" name="text"_x000D_
 maxlength="500"></textarea>_x000D_
<span id="count"></span>
_x000D_
_x000D_
_x000D_

Submitting a multidimensional array via POST with php

On submitting, you would get an array as if created like this:

$_POST['topdiameter'] = array( 'first value', 'second value' );
$_POST['bottomdiameter'] = array( 'first value', 'second value' );

However, I would suggest changing your form names to this format instead:

name="diameters[0][top]"
name="diameters[0][bottom]"
name="diameters[1][top]"
name="diameters[1][bottom]"
...

Using that format, it's much easier to loop through the values.

if ( isset( $_POST['diameters'] ) )
{
    echo '<table>';
    foreach ( $_POST['diameters'] as $diam )
    {
        // here you have access to $diam['top'] and $diam['bottom']
        echo '<tr>';
        echo '  <td>', $diam['top'], '</td>';
        echo '  <td>', $diam['bottom'], '</td>';
        echo '</tr>';
    }
    echo '</table>';
}

Add event handler for body.onload by javascript within <body> part

As we were already using jQuery for a graphical eye-candy feature we ended up using this. A code like

$(document).ready(function() {
    // any code goes here
    init();
});

did everything we wanted and cares about browser incompatibilities at its own.

How to open port in Linux

First, you should disable selinux, edit file /etc/sysconfig/selinux so it looks like this:

SELINUX=disabled
SELINUXTYPE=targeted

Save file and restart system.

Then you can add the new rule to iptables:

iptables -A INPUT -m state --state NEW -p tcp --dport 8080 -j ACCEPT

and restart iptables with /etc/init.d/iptables restart

If it doesn't work you should check other network settings.

How to change the version of the 'default gradle wrapper' in IntelliJ IDEA?

The easiest way is to execute the following command from the command line (see Upgrading the Gradle Wrapper in documentation):

./gradlew wrapper --gradle-version 5.5

Moreover, you can use --distribution-type parameter with either bin or all value to choose a distribution type. Use all distribution type to avoid a hint from IntelliJ IDEA or Android Studio that will offer you to download Gradle with sources:

./gradlew wrapper --gradle-version 5.5 --distribution-type all

Or you can create a custom wrapper task

task wrapper(type: Wrapper) {
    gradleVersion = '5.5'
}

and run ./gradlew wrapper.

How to print the current time in a Batch-File?

set time1=%time%
call timeout 10
set time2=%time%
echo. time1
echo. time2
echo.
pause

Removing leading zeroes from a field in a SQL statement

I had the same need and used this:

select 
    case 
        when left(column,1) = '0' 
        then right(column, (len(column)-1)) 
        else column 
      end

How to connect to a MS Access file (mdb) using C#?

What Access File extension or you using? The Jet OLEDB or the Ace OLEDB. If your Access DB is .mdb (aka Jet Oledb)

using System;
using System.Collections.Generic;
using System.Linq;
using System.Text;
using System.Data.Oledb

namespace MembershipInformationSystem.Helpers
{
    public class dbs
    {
        private String connectionString;
        private String OleDBProvider = "Microsoft.JET.OLEDB.4.0"; \\if ACE Microsoft.ACE.OLEDB.12.0
        private String OleDBDataSource = "C:\\yourdb.mdb";
        private String OleDBPassword = "infosys";
        private String PersistSecurityInfo = "False";

        public dbs()
        {

        }

        public dbs(String connectionString)
        {
            this.connectionString = connectionString;
        }

        public String konek()
        {
            connectionString = "Provider=" + OleDBProvider + ";Data Source=" + OleDBDataSource + ";JET OLEDB:Database Password=" + OleDBPassword + ";Persist Security Info=" + PersistSecurityInfo + "";
            return connectionString;
        }
    }
}

Connect to Oracle DB using sqlplus

As David Aldridge explained, your parentheses should start right after the sqlplus command, so it should be:

sqlplus 'test/test@(DESCRIPTION=(ADDRESS_LIST=(ADDRESS=(PROTOCOL=TCP)(HOST=hostname.com )(PORT=1521)))(CONNECT_DATA=(SID=mysid))'

How to serialize an object into a string

How about writing the data to a ByteArrayOutputStream instead of a FileOutputStream?

Otherwise, you could serialize the object using XMLEncoder, persist the XML, then deserialize via XMLDecoder.

How to compare two dates to find time difference in SQL Server 2005, date manipulation

I think you need the time gap between job_start & job_end.

Try this...

select SUBSTRING(CONVERT(VARCHAR(20),(job_end - job_start),120),12,8) from tableA

I ended up with this.

01:14:37

Python regex for integer?

Regexp work on the character base, and \d means a single digit 0...9 and not a decimal number.

A regular expression that matches only integers with a sign could be for example

^[-+]?[0-9]+$

meaning

  1. ^ - start of string
  2. [-+]? - an optional (this is what ? means) minus or plus sign
  3. [0-9]+ - one or more digits (the plus means "one or more" and [0-9] is another way to say \d)
  4. $ - end of string

Note: having the sign considered part of the number is ok only if you need to parse just the number. For more general parsers handling expressions it's better to leave the sign out of the number: source streams like 3-2 could otherwise end up being parsed as a sequence of two integers instead of an integer, an operator and another integer. My experience is that negative numbers are better handled by constant folding of the unary negation operator at an higher level.

Node JS Error: ENOENT

You can include a different jade file into your template, that to from a different directory

views/
     layout.jade
static/
     page.jade

To include the layout file from views dir to static/page.jade

page.jade

extends ../views/layout

How to redirect cin and cout to files?

Try this to redirect cout to file.

#include <iostream>
#include <fstream>

int main()
{
    /** backup cout buffer and redirect to out.txt **/
    std::ofstream out("out.txt");

    auto *coutbuf = std::cout.rdbuf();
    std::cout.rdbuf(out.rdbuf());

    std::cout << "This will be redirected to file out.txt" << std::endl;

    /** reset cout buffer **/
    std::cout.rdbuf(coutbuf);

    std::cout << "This will be printed on console" << std::endl;

    return 0;
}

Read full article Use std::rdbuf to Redirect cin and cout

CHECK constraint in MySQL is not working

Check constraints are supported as of version 8.0.15 (yet to be released)

https://bugs.mysql.com/bug.php?id=3464

[23 Jan 16:24] Paul Dubois

Posted by developer: Fixed in 8.0.15.

Previously, MySQL permitted a limited form of CHECK constraint syntax, but parsed and ignored it. MySQL now implements the core features of table and column CHECK constraints, for all storage engines. Constraints are defined using CREATE TABLE and ALTER TABLE statements.

How to Disable GUI Button in Java

You should put the statement btnConvertDocuments.setEnabled(false); in the actionPerformed(ActionEvent event) method. Your conditional above only get call once in the constructor when IPGUI object is being instantiated.

if (command.equals("w")) {
    FileConverter fc = new FileConverter();
    btn1Clicked = true;
    btnConvertDocuments.setEnabled(false);
}

What should I do when 'svn cleanup' fails?

After going through most of the solutions that are cited here, I still was getting the error.

The issue was case insensitive OS X. Checking out a directory that has two files with the same name, but different capitalization causes an issue. For example, ApproximationTest.java and Approximationtest.java should not be in the same directory. As soon as we get rid of one of the file, the issue goes away.

JSON.Net Self referencing loop detected

If using ASP.NET Core MVC, add this to the ConfigureServices method of your startup.cs file:

services.AddMvc()
    .AddJsonOptions(
        options => options.SerializerSettings.ReferenceLoopHandling =            
        Newtonsoft.Json.ReferenceLoopHandling.Ignore
    );

nvm is not compatible with the npm config "prefix" option:

I had this issue after moving my home folder to a new drive on linux. It was fixed by removing .nvm folder and reinstalling nvm

Fatal error: Allowed memory size of 268435456 bytes exhausted (tried to allocate 71 bytes)

I changed the memory limit from .htaccess and this problem got resolved.

I was trying to scan my website from one of the antivirus plugin and there I was getting this problem. I increased memory by pasting this in my .htaccess file in Wordpress folder:

php_value memory_limit 512M

After scan was over, I removed this line to make the size as it was before.

ASP.NET MVC Razor: How to render a Razor Partial View's HTML inside the controller action

Although adequate answers have already been given, I'd like to propose a less verbose solution, that can be used without the helper methods available in an MVC controller class. Using a third party library called "RazorEngine" you can use .Net file IO to get the contents of the razor file and call

string html = Razor.Parse(razorViewContentString, modelObject);

Get the third party library here.

SQL: Return "true" if list of records exists?

You can use a SELECT CASE statement like so:

select case when EXISTS (
 select 1 
 from <table>
 where <condition>
 ) then TRUE else FALSE end

It returns TRUE when your query in the parents exists.

PL/SQL, how to escape single quote in a string?

In addition to DCookie's answer above, you can also use chr(39) for a single quote.

I find this particularly useful when I have to create a number of insert/update statements based on a large amount of existing data.

Here's a very quick example:

Lets say we have a very simple table, Customers, that has 2 columns, FirstName and LastName. We need to move the data into Customers2, so we need to generate a bunch of INSERT statements.

Select 'INSERT INTO Customers2 (FirstName, LastName) ' ||
       'VALUES (' || chr(39) || FirstName || chr(39) ',' || 
       chr(39) || LastName || chr(39) || ');' From Customers;

I've found this to be very useful when moving data from one environment to another, or when rebuilding an environment quickly.

How to add manifest permission to an application?

That may be also interesting in context of adding INTERNET permission to your application:

Google has also given each app Internet access, effectively removing the Internet access permission. Oh, sure, Android developers still have to declare they want Internet access when putting together the app. But users can no longer see the Internet access permission when installing an app and current apps that don’t have Internet access can now gain Internet access with an automatic update without prompting you.

Source: http://www.howtogeek.com/190863/androids-app-permissions-were-just-simplified-now-theyre-much-less-secure/

Bottom line is that you still have to add INTERNET permission in manifest file but application will be updated on user's devices without asking them for new permission.

Find unused npm packages in package.json

if you want to choose upon which giant's shoulders you will stand

here is a link to generate a short list of options available to npm; it filters on the keywords unused packages

https://www.npmjs.com/search?q=unused%20packages

How to submit an HTML form on loading the page?

using javascript

 <form id="frm1" action="file.php"></form>
    <script>document.getElementById('frm1').submit();</script>

What is a raw type and why shouldn't we use it?

Avoid raw types

Raw types refer to using a generic type without specifying a type parameter.

For example,

A list is a raw type, while List<String> is a parameterized type.

When generics were introduced in JDK 1.5, raw types were retained only to maintain backwards compatibility with older versions of Java. Although using raw types is still possible,

They should be avoided:

  • They usually require casts
  • They aren't type safe, and some important kinds of errors will only appear at runtime
  • They are less expressive, and don't self-document in the same way as parameterized types Example

    import java.util.*;
    
    public final class AvoidRawTypes {
    
    void withRawType() {
    
        //Raw List doesn't self-document, 
        //doesn't state explicitly what it can contain
    
        List stars = Arrays.asList("Arcturus", "Vega", "Altair");
    
        Iterator iter = stars.iterator();
    
        while (iter.hasNext()) {
    
            String star = (String) iter.next(); //cast needed
    
            log(star);
        }
    
    }
    
    void withParameterizedType() {
    
        List < String > stars = Arrays.asList("Spica", "Regulus", "Antares");
    
        for (String star: stars) {
    
            log(star);
        }
    
    }
    
    private void log(Object message) {
    
        System.out.println(Objects.toString(message));
    
    }
    
    }
    

For reference: https://docs.oracle.com/javase/tutorial/java/generics/rawTypes.html

#ifdef replacement in the Swift language

In many situations, you don't really need conditional compilation; you just need conditional behavior that you can switch on and off. For that, you can use an environment variable. This has the huge advantage that you don't actually have to recompile.

You can set the environment variable, and easily switch it on or off, in the scheme editor:

enter image description here

You can retrieve the environment variable with NSProcessInfo:

    let dic = NSProcessInfo.processInfo().environment
    if dic["TRIPLE"] != nil {
        // ... do secret stuff here ...
    }

Here's a real-life example. My app runs only on the device, because it uses the music library, which doesn't exist on the Simulator. How, then, to take screen shots on the Simulator for devices I don't own? Without those screen shots, I can't submit to the AppStore.

I need fake data and a different way of processing it. I have two environment variables: one which, when switched on, tells the app to generate the fake data from the real data while running on my device; the other which, when switched on, uses the fake data (not the missing music library) while running on the Simulator. Switching each of those special modes on / off is easy thanks to environment variable checkboxes in the Scheme editor. And the bonus is that I can't accidentally use them in my App Store build, because archiving has no environment variables.

iPhone app signing: A valid signing identity matching this profile could not be found in your keychain

If you have new mac you can go to IOS developer center --> Provisioning Portal --> Certificates --> Development --> Revoke and create new certificate. My problem solved. My error is "Code Sign error: The identity 'iPhone Developer' doesn't match any valid, non-expired certificate/private key pair in your keychains"

Significance of ios_base::sync_with_stdio(false); cin.tie(NULL);

This is to synchronize IOs from C and C++ world. If you synchronize, then you have a guaranty that the orders of all IOs is exactly what you expect. In general, the problem is the buffering of IOs that causes the problem, synchronizing let both worlds to share the same buffers. For example cout << "Hello"; printf("World"); cout << "Ciao";; without synchronization you'll never know if you'll get HelloCiaoWorld or HelloWorldCiao or WorldHelloCiao...

tie lets you have the guaranty that IOs channels in C++ world are tied one to each other, which means for example that every output have been flushed before inputs occurs (think about cout << "What's your name ?"; cin >> name;).

You can always mix C or C++ IOs, but if you want some reasonable behavior you must synchronize both worlds. Beware that in general it is not recommended to mix them, if you program in C use C stdio, and if you program in C++ use streams. But you may want to mix existing C libraries into C++ code, and in such a case it is needed to synchronize both.

Remove the last line from a file in Bash

You can try this method also : example of removing last n number of lines.

a=0 ; while [ $a -lt 4 ];do sed -i '$ d' output.txt; a=expr $a + 1;done

Removing last 4 lines from file(output.txt).

PATH issue with pytest 'ImportError: No module named YadaYadaYada'

Also if you run pytest within your virtual environment make sure pytest module is installed within your virtual environment. Activate your virtual env and run pip install pytest.

How to tell when UITableView has completed ReloadData?

You can use performBatchUpdates function of uitableview

Here is how you can achieve

self.tableView.performBatchUpdates({

      //Perform reload
        self.tableView.reloadData()
    }) { (completed) in

        //Reload Completed Use your code here
    }

Do I need to explicitly call the base virtual destructor?

No you don't need to call the base destructor, a base destructor is always called for you by the derived destructor. Please see my related answer here for order of destruction.

To understand why you want a virtual destructor in the base class, please see the code below:

class B
{
public:
    virtual ~B()
    {
        cout<<"B destructor"<<endl;
    }
};


class D : public B
{
public:
    virtual ~D()
    {
        cout<<"D destructor"<<endl;
    }
};

When you do:

B *pD = new D();
delete pD;

Then if you did not have a virtual destructor in B, only ~B() would be called. But since you have a virtual destructor, first ~D() will be called, then ~B().

google console error `OR-IEH-01`

Recently I was also having this issue, then I contacted Google Support and they gave me this link to provide required info, I posted and within 24 hours my problem was fixed.

Link: https://support.google.com/payments/contact/alt_account_verification

Hosting ASP.NET in IIS7 gives Access is denied?

After some thinking and a lot of of trial and error I found out that this error occurred because part of my web.config was encrypted and for some reason the key was no longer valid.

Re-encrypting the config section solved the issue.

How to post SOAP Request from PHP

PHP has SOAP support. Just call

$client = new SoapClient($url);

to connect to the SoapServer and then you can get list of functions and call functions simply by doing...

$client->__getTypes();      
$client->__getFunctions();  

$result = $client->functionName();  

for more http://www.php.net/manual/en/soapclient.soapclient.php

How to show imageView full screen on imageView click?

It's easy to achieve this is to just use an Intent like this: (I put the method in a custom class that takes in an Activity as a parameter so it can be called from any Fragment or Activity)

    public class UIutils {

private Activity mActivity;

    public UIutils(Activity activity){
        mActivity = activity;
    }

public void showPhoto(Uri photoUri){
        Intent intent = new Intent();
        intent.setAction(Intent.ACTION_VIEW);
        intent.setDataAndType(photoUri, "image/*");
        mActivity.startActivity(intent);
    }
}

Then to use it just do this:

imageView.setOnClickListener(v1 -> new UIutils(getActivity()).showPhoto(Uri.parse(imageURI)));

I use this with an Image URL but it can be used with stored files as well. If you are accessing images form the phones memory you should use a content provider.

Java Command line arguments

Try to pass value a and compare using the equals method like this:

public static void main(String str[]) {

    boolean b = str[0].equals("a");

    System.out.println(b);

}

Follow this link to know more about Command line argument in Java

Opening a .ipynb.txt File

What you have on your hands is an IPython Notebook file. (Now renamed to Jupyter Notebook

you can open it using the command ipython notebook filename.ipynb from the directory it is downloaded on to.

If you are on a newer machine, open the file as jupyter notebook filename.ipynb.

do not forget to remove the .txt extension.

the file has a series of python code/statements and markdown text that you can run/inspect/save/share. read more about ipython notebook from the website.

if you do not have IPython installed, you can do

pip install ipython

or check out installation instructions at the ipython website

JavaScript - Get minutes between two dates

This problem is solved easily with moment.js, like this example:

var difference = mostDate.diff(minorDate, "minutes");

The second parameter can be changed for another parameters, see the moment.js documentation.

e.g.: "days", "hours", "minutes", etc.

http://momentjs.com/docs/

The CDN for moment.js is available here:

https://cdnjs.com/libraries/moment.js

Thanks.

EDIT:

mostDate and minorDate should be a moment type.

EDIT 2:

For those who are reading my answer in 2020+, momentjs is now a legacy project.

If you are still looking for a well-known library to do this job, I would recommend date-fns.

// How many minutes are between 2 July 2014 12:07:59 and 2 July 2014 12:20:00?
var result = differenceInMinutes(
  new Date(2014, 6, 2, 12, 20, 0),
  new Date(2014, 6, 2, 12, 7, 59)
)
//=> 12

Genymotion, "Unable to load VirtualBox engine." on Mavericks. VBox is setup correctly

Update: Genymotion's 2.5.1 release (https://www.genymotion.com/#!/release-notes/251#251) seems to have fixed this issue. (thanks for the heads up @Roger!)


For those that may be stumbling upon this a bit later, I resolved this by installing VirtualBox 4.3.28 (https://www.virtualbox.org/wiki/Download_Old_Builds_4_3). The new 5.0.0 and 4.3.30 versions didn't work for me with Genymotion 2.5. None of the above solutions worked :(

It's also worth noting that at the time of writing, Genymotion's FAQ states the following:

However, for performance reasons, we recommend using version 4.3.12

Inserting HTML elements with JavaScript

To my knowledge, which, to be fair, is fairly new and limited, the only potential issue with this technique is the fact that you are prevented from dynamically creating some table elements.

I use a form to templating by adding "template" elements to a hidden DIV and then using cloneNode(true) to create a clone and appending it as required. Bear in ind that you do need to ensure you re-assign id's as required to prevent duplication.

How to clear the canvas for redrawing

Context.clearRect(starting width, starting height, ending width, ending height);

Example: context.clearRect(0, 0, canvas.width, canvas.height);

SSH to Elastic Beanstalk instance

I came here looking for a way to add a key to an instance Beanstalk creates during provisioning (we're using Terraform). You can do the following in Terraform:

resource "aws_elastic_beanstalk_environment" "your-beanstalk" {
   ... 
   setting {
      namespace = "aws:autoscaling:launchconfiguration"
      name      = "EC2KeyName"
      value     = "${aws_key_pair.your-ssh-key.key_name}"
   }
   ...
}

You can then use that key to SSH into the box.

Last segment of URL in jquery

// https://x.com/boo/?q=foo&s=bar = boo
// https://x.com/boo?q=foo&s=bar = boo
// https://x.com/boo/ = boo
// https://x.com/boo = boo

const segment = new 
URL(window.location.href).pathname.split('/').filter(Boolean).pop();
console.log(segment);

Works for me.

Changing EditText bottom line color with appcompat v7

I use this method to change the color of the line with PorterDuff, with no other drawable.

public void changeBottomColorSearchView(int color) {
    int searchPlateId = mSearchView.getContext().getResources().getIdentifier("android:id/search_plate", null, null);
    View searchPlate = mSearchView.findViewById(searchPlateId);
    searchPlate.getBackground().setColorFilter(color, PorterDuff.Mode.SRC_IN);
}

Difference between AutoPostBack=True and AutoPostBack=False?

hai sir

There is one event which is default associate with any webcontrol. For example, in case of Button click event, in case of Check box CheckChangedEvent is there. So in case of AutoPostBack true these events are called by default and event handle at server sid

Changing fonts in ggplot2

A simple answer if you don't want to install anything new

To change all the fonts in your plot plot + theme(text=element_text(family="mono")) Where mono is your chosen font.

List of default font options:

  • mono
  • sans
  • serif
  • Courier
  • Helvetica
  • Times
  • AvantGarde
  • Bookman
  • Helvetica-Narrow
  • NewCenturySchoolbook
  • Palatino
  • URWGothic
  • URWBookman
  • NimbusMon
  • URWHelvetica
  • NimbusSan
  • NimbusSanCond
  • CenturySch
  • URWPalladio
  • URWTimes
  • NimbusRom

R doesn't have great font coverage and, as Mike Wise points out, R uses different names for common fonts.

This page goes through the default fonts in detail.

Xcode 9 Swift Language Version (SWIFT_VERSION)

I just click on latest swift convert button and set App target build setting-> Swift language version: swift 4.0,

Hope this will help.

.ssh directory not being created

As a slight improvement over the other answers, you can do the mkdir and chmod as a single operation using mkdir's -m switch.

$ mkdir -m 700 ${HOME}/.ssh

Usage

From a Linux system

$ mkdir --help
Usage: mkdir [OPTION]... DIRECTORY...
Create the DIRECTORY(ies), if they do not already exist.

Mandatory arguments to long options are mandatory for short options too.
  -m, --mode=MODE   set file mode (as in chmod), not a=rwx - umask
...
...

Is it safe to delete a NULL pointer?

delete performs the check anyway, so checking it on your side adds overhead and looks uglier. A very good practice is setting the pointer to NULL after delete (helps avoiding double deletion and other similar memory corruption problems).

I'd also love if delete by default was setting the parameter to NULL like in

#define my_delete(x) {delete x; x = NULL;}

(I know about R and L values, but wouldn't it be nice?)

File uploading with Express 4.0: req.files undefined

Just to add to answers above, you can streamline the use of express-fileupload to just a single route that needs it, instead of adding it to the every route.

let fileupload = require("express-fileupload");

...

app.post("/upload", fileupload, function(req, res){

...

});

change values in array when doing foreach

Array: [1, 2, 3, 4]
Result: ["foo1", "foo2", "foo3", "foo4"]

Array.prototype.map() Keep original array

_x000D_
_x000D_
const originalArr = ["Iron", "Super", "Ant", "Aqua"];
const modifiedArr = originalArr.map(name => `${name}man`);

console.log( "Original: %s", originalArr );
console.log( "Modified: %s", modifiedArr );
_x000D_
_x000D_
_x000D_

Array.prototype.forEach() Override original array

_x000D_
_x000D_
const originalArr = ["Iron", "Super", "Ant", "Aqua"];
originalArr.forEach((name, index) => originalArr[index] = `${name}man`);

console.log( "Overridden: %s", originalArr );
_x000D_
_x000D_
_x000D_

Most efficient way to find smallest of 3 numbers Java?

double smallest = a;
if (smallest > b) smallest = b;
if (smallest > c) smallest = c;

Not necessarily faster than your code.

How to save a spark DataFrame as csv on disk?

Writing dataframe to disk as csv is similar read from csv. If you want your result as one file, you can use coalesce.

df.coalesce(1)
      .write
      .option("header","true")
      .option("sep",",")
      .mode("overwrite")
      .csv("output/path")

If your result is an array you should use language specific solution, not spark dataframe api. Because all these kind of results return driver machine.

MYSQL query between two timestamps

Try below code. Worked in my case. Hope this helps!

    select id,total_Hour,
    (coalesce(weekday_1,0)+coalesce(weekday_2,0)+coalesce(weekday_3,0)) as weekday_Listing_Hrs,
    (coalesce(weekend_1,0)+coalesce(weekend_2,0)+coalesce(weekend_3,0)) as weekend_Listing_Hrs
    from
    select *,
    listing_duration_Hour-(coalesce(weekday_1,0)+coalesce(weekday_2,0)+coalesce(weekday_3,0)+coalesce(weekend_1,0)+coalesce(weekend_2,0)) as weekend_3 
    from 
    (
    select * , 
    case when date(Start_Date) = date(End_Date) and weekday(Start_Date) in (0,1,2,3,4) 
         then timestampdiff(hour,Start_Date,End_Date)
         when date(Start_Date) != date(End_Date) and weekday(Start_Date) in (0,1,2,3,4) 
         then 24-timestampdiff(hour,date(Start_Date),Start_Date)
         end as weekday_1,  
    case when date(Start_Date) != date(End_Date) and weekday(End_Date) in (0,1,2,3,4) 
         then timestampdiff(hour,date(End_Date),End_Date)
         end as weekday_2,
    case when date(Start_Date) != date(End_Date) then    
    (5*(DATEDIFF(date(End_Date),adddate(date(Start_Date),+1)) DIV 7) + 
    MID('0123455501234445012333450122234501101234000123450',7 * WEEKDAY(adddate(date(Start_Date),+1))
    + WEEKDAY(date(End_Date)) + 1, 1))* 24 end as  weekday_3,
    case when date(Start_Date) = date(End_Date) and weekday(Start_Date) in (5,6) 
         then timestampdiff(hour,Start_Date,End_Date)
         when date(Start_Date) != date(End_Date) and weekday(Start_Date) in (5,6) 
         then 24-timestampdiff(hour,date(Start_Date),Start_Date)
         end as weekend_1,  
    case when date(Start_Date) != date(End_Date) and weekday(End_Date) in (5,6) 
         then timestampdiff(hour,date(End_Date),End_Date)
         end as weekend_2
    from 
    TABLE_1
    )

Why do I get a SyntaxError for a Unicode escape in my file path?

You need to use a raw string, double your slashes or use forward slashes instead:

r'C:\Users\expoperialed\Desktop\Python'
'C:\\Users\\expoperialed\\Desktop\\Python'
'C:/Users/expoperialed/Desktop/Python'

In regular python strings, the \U character combination signals a extended Unicode codepoint escape.

You can hit any number of other issues, for any of the recognised escape sequences, such as \a or \t or \x, etc.

How to remove an iOS app from the App Store

I just changed availability date to a future date. After doing that, I received following message -

You have selected an Available Date in the future. This will remove your currently live version from the App Store until the new date. Changing Available Date affects all versions of the application, both Ready For Sale and In Review.

Which means that the app is removed and no longer available.

Regular expression to match exact number of characters?

What you have is correct, but this is more consice:

^[A-Z]{3}$

MySQL Workbench Edit Table Data is read only

In MySQL Workbench you need an INDEX to edit, no need it to be PK (although adding a PK is a solution as well).

You can make a regular INDEX or compound INDEX. That's all MySQL WB needs to fix the Read only thing (I have v. 6.2 with MariaDB v. 10.1.4):

Just right click table, select "Alter table..." then go to "Indexes" tab. In the left pane put a custom name for your index, and in the middle pane checkmark one (make sure the vale will be unique) or more fields (just make sure the combination is unique)

Is there a way to add a gif to a Markdown file?

just upload the .gif file into your base folder of GitHub and edit README.md just use this code

![](name-of-giphy.gif)

How to increase the vertical split window size in Vim

I am using the below commands for this:

set lines=50     " For increasing the height to 50 lines (vertical)
set columns=200  " For increasing the width to 200 columns (horizontal)

Python: How do I make a subclass from a superclass?

class MySubClass(MySuperClass):
    def __init__(self):
        MySuperClass.__init__(self)

        # <the rest of your custom initialization code goes here>

The section on inheritance in the python documentation explains it in more detail

Truth value of a Series is ambiguous. Use a.empty, a.bool(), a.item(), a.any() or a.all()

One minor thing, which wasted my time.

Put the conditions(if comparing using " = ", " != ") in parenthesis, failing to do so also raises this exception. This will work

df[(some condition) conditional operator (some conditions)]

This will not

df[some condition conditional-operator some condition]

How do I detect a page refresh using jquery?

$('body').bind('beforeunload',function(){
   //do something
});

But this wont save any info for later, unless you were planning on saving that in a cookie somewhere (or local storage) and the unload event does not always fire in all browsers.


Example: http://jsfiddle.net/maniator/qpK7Y/

Code:

$(window).bind('beforeunload',function(){

     //save info somewhere

    return 'are you sure you want to leave?';

});

Load a HTML page within another HTML page

Load a page within a page using an iframe. The following should serve as a good starting point.

<body>
  <div>
    <iframe src="page1.html" name="targetframe" allowTransparency="true" scrolling="no" frameborder="0" >
    </iframe>
  </div>

  <br/>

  <div>
    <a href="page2.html" target="targetframe">Link to Page 2</a><br />
    <a href="page3.html" target="targetframe">Link to Page 3</a>
  </div>
</body>

When to choose mouseover() and hover() function?

From the official jQuery documentation

  • .mouseover()
    Bind an event handler to the "mouseover" JavaScript event, or trigger that event on an element.

  • .hover() Bind one or two handlers to the matched elements, to be executed when the mouse pointer enters and leaves the elements.

    Calling $(selector).hover(handlerIn, handlerOut) is shorthand for: $(selector).mouseenter(handlerIn).mouseleave(handlerOut);


  • .mouseenter()

    Bind an event handler to be fired when the mouse enters an element, or trigger that handler on an element.

    mouseover fires when the pointer moves into the child element as well, while mouseenter fires only when the pointer moves into the bound element.


What this means

Because of this, .mouseover() is not the same as .hover(), for the same reason .mouseover() is not the same as .mouseenter().

$('selector').mouseover(over_function) // may fire multiple times

// enter and exit functions only called once per element per entry and exit
$('selector').hover(enter_function, exit_function) 

How to enable directory listing in apache web server

I had to disable selinux to make this work. Note. The system needs to be rebooted for selinux to take effect.

Better way to represent array in java properties file

As user 'Skip Head' already pointed out, csv or a any table file format would be a better fitt in your case.

If it is an option for you, maybe this Table implementation might interest you.

What happens when a duplicate key is put into a HashMap?

You may find your answer in the javadoc of Map#put(K, V) (which actually returns something):

public V put(K key,
             V value)

Associates the specified value with the specified key in this map (optional operation). If the map previously contained a mapping for this key, the old value is replaced by the specified value. (A map m is said to contain a mapping for a key k if and only if m.containsKey(k) would return true.)

Parameters:
key - key with which the specified value is to be associated.
value - value to be associated with the specified key.

Returns:
previous value associated with specified key, or null if there was no mapping for key. (A null return can also indicate that the map previously associated null with the specified key, if the implementation supports null values.)

So if you don't assign the returned value when calling mymap.put("1", "a string"), it just becomes unreferenced and thus eligible for garbage collection.

MySQL Install: ERROR: Failed to build gem native extension

on OSX mountain Lion: If you have brew installed, then brew install mysql and follow the instructions on creating a test database with mysql on your machine. You don't have to go all the way through, I didn't need to After I did that I was able to bundle install and rake.

Error - trustAnchors parameter must be non-empty

On Red Hat Linux I got this issue resolved by importing the certificates to /etc/pki/java/cacerts.

warning: control reaches end of non-void function [-Wreturn-type]

You just need to return from the main function at some point. The error message says that the function is defined to return a value but you are not returning anything.

  /* .... */
  if (Date1 == Date2)  
     fprintf (stderr , "Indicating that the first date is equal to second date.\n"); 

  return 0;
}

How can I clear console

For Windows, via Console API:

void clear() {
    COORD topLeft  = { 0, 0 };
    HANDLE console = GetStdHandle(STD_OUTPUT_HANDLE);
    CONSOLE_SCREEN_BUFFER_INFO screen;
    DWORD written;

    GetConsoleScreenBufferInfo(console, &screen);
    FillConsoleOutputCharacterA(
        console, ' ', screen.dwSize.X * screen.dwSize.Y, topLeft, &written
    );
    FillConsoleOutputAttribute(
        console, FOREGROUND_GREEN | FOREGROUND_RED | FOREGROUND_BLUE,
        screen.dwSize.X * screen.dwSize.Y, topLeft, &written
    );
    SetConsoleCursorPosition(console, topLeft);
}

It happily ignores all possible errors, but hey, it's console clearing. Not like system("cls") handles errors any better.

For *nixes, you usually can go with ANSI escape codes, so it'd be:

void clear() {
    // CSI[2J clears screen, CSI[H moves the cursor to top-left corner
    std::cout << "\x1B[2J\x1B[H";
}

Using system for this is just ugly.

How to reference a .css file on a razor view?

I tried adding a block like so:

@section styles{
    <link rel="Stylesheet" href="@Href("~/Content/MyStyles.css")" />
}

And a corresponding block in the _Layout.cshtml file:

<head>
<title>@ViewBag.Title</title>
@RenderSection("styles", false);
</head>

Which works! But I can't help but think there's a better way. UPDATE: Added "false" in the @RenderSection statement so your view won't 'splode when you neglect to add a @section called head.

Reset select value to default

A simple way that runs is

 var myselect = $("select.SimpleAddAClass");
 myselect[0].selectedIndex = 0;
 myselect.selectmenu("refresh");

Removing Conda environment

This worked for me:

conda env remove --name tensorflow

Git pushing to remote branch

You can push your local branch to a new remote branch like so:

git push origin master:test

(Assuming origin is your remote, master is your local branch name and test is the name of the new remote branch, you wish to create.)

If at the same time you want to set up your local branch to track the newly created remote branch, you can do so with -u (on newer versions of Git) or --set-upstream, so:

git push -u origin master:test

or

git push --set-upstream origin master:test

...will create a new remote branch, named test, in remote repository origin, based on your local master, and setup your local master to track it.

Writing unit tests in Python: How do I start?

nosetests is brilliant solution for unit-testing in python. It supports both unittest based testcases and doctests, and gets you started with it with just simple config file.

Core dumped, but core file is not in the current directory?

I could think of two following possibilities:

  1. As others have already pointed out, the program might chdir(). Is the user running the program allowed to write into the directory it chdir()'ed to? If not, it cannot create the core dump.

  2. For some weird reason the core dump isn't named core.* You can check /proc/sys/kernel/core_pattern for that. Also, the find command you named wouldn't find a typical core dump. You should use find / -name "*core.*", as the typical name of the coredump is core.$PID

JavaScript Chart.js - Custom data formatting to display on tooltip

You can give tooltipTemplate a function, and format the tooltip as you wish:

tooltipTemplate: function(v) {return someFunction(v.value);}
multiTooltipTemplate: function(v) {return someOtherFunction(v.value);}

Those given 'v' arguments contain lots of information besides the 'value' property. You can put a 'debugger' inside that function and inspect those yourself.

How to delete from select in MySQL?

DELETE 
  p1
  FROM posts AS p1 
CROSS JOIN (
  SELECT ID FROM posts GROUP BY id HAVING COUNT(id) > 1
) AS p2
USING (id)

Plotting time-series with Date labels on x-axis

I like ggplot too.

Here's one example:

df1 = data.frame(
date_id = c('2017-08-01', '2017-08-02', '2017-08-03', '2017-08-04'),          
nation = c('China', 'USA', 'China', 'USA'), 
value = c(4.0, 5.0, 6.0, 5.5))

ggplot(df1, aes(date_id, value, group=nation, colour=nation))+geom_line()+xlab(label='dates')+ylab(label='value')

enter image description here

Creating table variable in SQL server 2008 R2

@tableName Table variables are alive for duration of the script running only i.e. they are only session level objects.

To test this, open two query editor windows under sql server management studio, and create table variables with same name but different structures. You will get an idea. The @tableName object is thus temporary and used for our internal processing of data, and it doesn't contribute to the actual database structure.

There is another type of table object which can be created for temporary use. They are #tableName objects declared like similar create statement for physical tables:

Create table #test (Id int, Name varchar(50))

This table object is created and stored in temp database. Unlike the first one, this object is more useful, can store large data and takes part in transactions etc. These tables are alive till the connection is open. You have to drop the created object by following script before re-creating it.

IF OBJECT_ID('tempdb..#test') IS NOT NULL
  DROP TABLE #test 

Hope this makes sense !

How to style the menu items on an Android action bar

BottomNavigationView navigation = (BottomNavigationView) findViewById(R.id.navigation);

    TextView textView = (TextView) navigation.findViewById(R.id.navigation_home).findViewById(R.id.smallLabel);
    textView.setTypeface(Typeface.DEFAULT_BOLD);
    textView = (TextView) navigation.findViewById(R.id.navigation_home).findViewById(R.id.largeLabel);
    textView.setTypeface(Typeface.DEFAULT_BOLD);

PDF Editing in PHP?

The PDF/pdflib extension documentation in PHP is sparse (something that has been noted in bugs.php.net) - I reccommend you use the Zend library.

Using two values for one switch case statement

The fallthrough answers by others are good ones.

However another approach would be extract methods out of the contents of your case statements and then just call the appropriate method from each case.

In the example below, both case 'text1' and case 'text4' behave the same:

switch (name) {
        case text1: {
            method1();
            break;
        }
        case text2: {
            method2();
            break;
        }
        case text3: {
            method3();
            break;
        }
        case text4: {
            method1();
            break;
        }

I personally find this style of writing case statements more maintainable and slightly more readable, especially when the methods you call have good descriptive names.

Better way to check variable for null or empty string?

I'll humbly accept if I'm wrong, but I tested on my own end and found that the following works for testing both string(0) "" and NULL valued variables:

if ( $question ) {
  // Handle success here
}

Which could also be reversed to test for success as such:

if ( !$question ) {
  // Handle error here
}

Generate insert script for selected records?

SELECT 'INSERT SomeOtherDB.dbo.table(column1,column2,etc.)
  SELECT ' + CONVERT(VARCHAR(12), Pk_Id) + ','
       + '''' + REPLACE(ProductName, '''', '''''') + ''','
       + CONVERT(VARCHAR(12), Fk_CompanyId) + ','
       + CONVERT(VARCHAR(12), Price) + ';'
FROM dbo.unspecified_table_name
WHERE Fk_CompanyId = 1;

Why do we need C Unions?

It's difficult to think of a specific occasion when you'd need this type of flexible structure, perhaps in a message protocol where you would be sending different sizes of messages, but even then there are probably better and more programmer friendly alternatives.

Unions are a bit like variant types in other languages - they can only hold one thing at a time, but that thing could be an int, a float etc. depending on how you declare it.

For example:

typedef union MyUnion MYUNION;
union MyUnion
{
   int MyInt;
   float MyFloat;
};

MyUnion will only contain an int OR a float, depending on which you most recently set. So doing this:

MYUNION u;
u.MyInt = 10;

u now holds an int equal to 10;

u.MyFloat = 1.0;

u now holds a float equal to 1.0. It no longer holds an int. Obviously now if you try and do printf("MyInt=%d", u.MyInt); then you're probably going to get an error, though I'm unsure of the specific behaviour.

The size of the union is dictated by the size of its largest field, in this case the float.

Windows cannot find 'http:/.127.0.0.1:%HTTPPORT%/apex/f?p=4950'. Make sure you typed the name correctly, and then try again

You can directly go to http://127.0.0.1:8080/apex/f?p=4950 and you will get Home Page Of your Oracle Database.

Right click on the shortcut > choose properties > go to security tab > Choose Authenticated Users > and give permission to do everything

and now try to change the URL you will be able to do it.

Hope this help

How copy data from Excel to a table using Oracle SQL Developer

You may directly right-click on the table name - that also shows the "Import Data.." option.Then you can follow few simple steps & succeed.

Do anyone know how to import a new table with data from excel?

How may I reference the script tag that loaded the currently-executing script?

I've got this, which is working in FF3, IE6 & 7. The methods in the on-demand loaded scripts aren't available until page load is complete, but this is still very useful.

//handle on-demand loading of javascripts
makescript = function(url){
    var v = document.createElement('script');
    v.src=url;
    v.type='text/javascript';

    //insertAfter. Get last <script> tag in DOM
    d=document.getElementsByTagName('script')[(document.getElementsByTagName('script').length-1)];
    d.parentNode.insertBefore( v, d.nextSibling );
}

Solution for "Fatal error: Maximum function nesting level of '100' reached, aborting!" in PHP

php.ini:

xdebug.max_nesting_level = -1

I'm not entirely sure if the value will ever overflow and reach -1, but it'll either never reach -1, or it'll set the max_nesting_level pretty high.

Python: most idiomatic way to convert None to empty string?

We can always avoid type casting in scenarios explained below.

customer = "John"
name = str(customer)
if name is None
   print "Name is blank"
else: 
   print "Customer name : " + name

In the example above in case variable customer's value is None the it further gets casting while getting assigned to 'name'. The comparison in 'if' clause will always fail.

customer = "John" # even though its None still it will work properly.
name = customer
if name is None
   print "Name is blank"
else: 
   print "Customer name : " + str(name)

Above example will work properly. Such scenarios are very common when values are being fetched from URL, JSON or XML or even values need further type casting for any manipulation.

TABLOCK vs TABLOCKX

Quite an old article on mssqlcity attempts to explain the types of locks:

Shared locks are used for operations that do not change or update data, such as a SELECT statement.

Update locks are used when SQL Server intends to modify a page, and later promotes the update page lock to an exclusive page lock before actually making the changes.

Exclusive locks are used for the data modification operations, such as UPDATE, INSERT, or DELETE.

What it doesn't discuss are Intent (which basically is a modifier for these lock types). Intent (Shared/Exclusive) locks are locks held at a higher level than the real lock. So, for instance, if your transaction has an X lock on a row, it will also have an IX lock at the table level (which stops other transactions from attempting to obtain an incompatible lock at a higher level on the table (e.g. a schema modification lock) until your transaction completes or rolls back).


The concept of "sharing" a lock is quite straightforward - multiple transactions can have a Shared lock for the same resource, whereas only a single transaction may have an Exclusive lock, and an Exclusive lock precludes any transaction from obtaining or holding a Shared lock.

Display more Text in fullcalendar

as a possible solution: Add some extra more content to the title. Overwrite this css style:

 .fc-day-grid-event .fc-content {
   white-space: normal; 
}

"No X11 DISPLAY variable" - what does it mean?

Don't forget to execute "host +" on your "home" display machine, and when you ssh to the machine you're doing "ssh -x hostname"

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

Easiest way is probably to convert from a VARCHAR to a DATE; then format it back to a VARCHAR again in the format you want;

SELECT TO_CHAR(TO_DATE(DOJ,'MM/DD/YYYY'), 'MM/DD/YYYY') FROM EmpTable;

An SQLfiddle to test with.

Compile to a stand-alone executable (.exe) in Visual Studio

I agree with @Marlon. When you compile your C# project with the Release configuration, you will find into the "bin/Release" folder of your project the executable of your application. This SHOULD work for a simple application.

But, if your application have any dependencies on some external dll, I suggest you to create a SetupProject with VisualStudio. Doing so, the project wizard will find all dependencies of your application and add them (the librairies) to the installation folder. Finally, all you will have to do is run the setup on the users computer and install your software.

String replacement in java, similar to a velocity template

Take a look at the java.text.MessageFormat class, MessageFormat takes a set of objects, formats them, then inserts the formatted strings into the pattern at the appropriate places.

Object[] params = new Object[]{"hello", "!"};
String msg = MessageFormat.format("{0} world {1}", params);

What is the best way to use a HashMap in C++?

The standard library includes the ordered and the unordered map (std::map and std::unordered_map) containers. In an ordered map the elements are sorted by the key, insert and access is in O(log n). Usually the standard library internally uses red black trees for ordered maps. But this is just an implementation detail. In an unordered map insert and access is in O(1). It is just another name for a hashtable.

An example with (ordered) std::map:

#include <map>
#include <iostream>
#include <cassert>

int main(int argc, char **argv)
{
  std::map<std::string, int> m;
  m["hello"] = 23;
  // check if key is present
  if (m.find("world") != m.end())
    std::cout << "map contains key world!\n";
  // retrieve
  std::cout << m["hello"] << '\n';
  std::map<std::string, int>::iterator i = m.find("hello");
  assert(i != m.end());
  std::cout << "Key: " << i->first << " Value: " << i->second << '\n';
  return 0;
}

Output:

23
Key: hello Value: 23

If you need ordering in your container and are fine with the O(log n) runtime then just use std::map.

Otherwise, if you really need a hash-table (O(1) insert/access), check out std::unordered_map, which has a similar to std::map API (e.g. in the above example you just have to search and replace map with unordered_map).

The unordered_map container was introduced with the C++11 standard revision. Thus, depending on your compiler, you have to enable C++11 features (e.g. when using GCC 4.8 you have to add -std=c++11 to the CXXFLAGS).

Even before the C++11 release GCC supported unordered_map - in the namespace std::tr1. Thus, for old GCC compilers you can try to use it like this:

#include <tr1/unordered_map>

std::tr1::unordered_map<std::string, int> m;

It is also part of boost, i.e. you can use the corresponding boost-header for better portability.

open link of google play store in mobile version android

You can check if the Google Play Store app is installed and, if this is the case, you can use the "market://" protocol.

final String my_package_name = "........."  // <- HERE YOUR PACKAGE NAME!!
String url = "";

try {
    //Check whether Google Play store is installed or not:
    this.getPackageManager().getPackageInfo("com.android.vending", 0);

    url = "market://details?id=" + my_package_name;
} catch ( final Exception e ) {
    url = "https://play.google.com/store/apps/details?id=" + my_package_name;
}


//Open the app page in Google Play store:
final Intent intent = new Intent(Intent.ACTION_VIEW, Uri.parse(url));
intent.addFlags(Intent.FLAG_ACTIVITY_NEW_TASK | Intent.FLAG_ACTIVITY_CLEAR_WHEN_TASK_RESET);
startActivity(intent);

remove inner shadow of text input

This is the solution for mobile safari:

-webkit-appearance: none;

as suggested here: Remove textarea inner shadow on Mobile Safari (iPhone)

how to run vibrate continuously in iphone?

Thankfully, it's not possible to change the duration of the vibration. The only way to trigger the vibration is to play the kSystemSoundID_Vibrate as you have. If you really want to though, what you can do is to repeat the vibration indefinitely, resulting in a pulsing vibration effect instead of a long continuous one. To do this, you need to register a callback function that will get called when the vibration sound that you play is complete:

 AudioServicesAddSystemSoundCompletion (
        kSystemSoundID_Vibrate,
        NULL,
        NULL,
        MyAudioServicesSystemSoundCompletionProc,
        NULL
    );
    AudioServicesPlaySystemSound(kSystemSoundID_Vibrate);

Then you define your callback function to replay the vibrate sound again:

#pragma mark AudioService callback function prototypes
void MyAudioServicesSystemSoundCompletionProc (
   SystemSoundID  ssID,
   void           *clientData
);

#pragma mark AudioService callback function implementation

// Callback that gets called after we finish buzzing, so we 
// can buzz a second time.
void MyAudioServicesSystemSoundCompletionProc (
   SystemSoundID  ssID,
   void           *clientData
) {
  if (iShouldKeepBuzzing) { // Your logic here...
      AudioServicesPlaySystemSound(kSystemSoundID_Vibrate); 
  } else {
      //Unregister, so we don't get called again...
      AudioServicesRemoveSystemSoundCompletion(kSystemSoundID_Vibrate);
  }  
}

Difference between Java SE/EE/ME?

As I come across this question, I found the information provided on the Oracle's tutorial very complete and worth to share:

The Java Programming Language Platforms

There are four platforms of the Java programming language:

  • Java Platform, Standard Edition (Java SE)

  • Java Platform, Enterprise Edition (Java EE)

  • Java Platform, Micro Edition (Java ME)

  • JavaFX

All Java platforms consist of a Java Virtual Machine (VM) and an application programming interface (API). The Java Virtual Machine is a program, for a particular hardware and software platform, that runs Java technology applications. An API is a collection of software components that you can use to create other software components or applications. Each Java platform provides a virtual machine and an API, and this allows applications written for that platform to run on any compatible system with all the advantages of the Java programming language: platform-independence, power, stability, ease-of-development, and security.

Java SE

When most people think of the Java programming language, they think of the Java SE API. Java SE's API provides the core functionality of the Java programming language. It defines everything from the basic types and objects of the Java programming language to high-level classes that are used for networking, security, database access, graphical user interface (GUI) development, and XML parsing.

In addition to the core API, the Java SE platform consists of a virtual machine, development tools, deployment technologies, and other class libraries and toolkits commonly used in Java technology applications.

Java EE

The Java EE platform is built on top of the Java SE platform. The Java EE platform provides an API and runtime environment for developing and running large-scale, multi-tiered, scalable, reliable, and secure network applications.

Java ME

The Java ME platform provides an API and a small-footprint virtual machine for running Java programming language applications on small devices, like mobile phones. The API is a subset of the Java SE API, along with special class libraries useful for small device application development. Java ME applications are often clients of Java EE platform services.

JavaFX

JavaFX is a platform for creating rich internet applications using a lightweight user-interface API. JavaFX applications use hardware-accelerated graphics and media engines to take advantage of higher-performance clients and a modern look-and-feel as well as high-level APIs for connecting to networked data sources. JavaFX applications may be clients of Java EE platform services.

How do you get a directory listing in C?

There is no standard C (or C++) way to enumerate files in a directory.

Under Windows you can use the FindFirstFile/FindNextFile functions to enumerate all entries in a directory. Under Linux/OSX use the opendir/readdir/closedir functions.

Creating a list/array in excel using VBA to get a list of unique names in a column

You can try my suggestion for a work around in Doug's approach.
But if you want to stick with your logic though, you can try this:

Option Explicit

Sub GetUnique()

Dim rng As Range
Dim myarray, myunique
Dim i As Integer

ReDim myunique(1)

With ThisWorkbook.Sheets("Sheet1")
    Set rng = .Range(.Range("A1"), .Range("A" & .Rows.Count).End(xlUp))
    myarray = Application.Transpose(rng)
    For i = LBound(myarray) To UBound(myarray)
        If IsError(Application.Match(myarray(i), myunique, 0)) Then
            myunique(UBound(myunique)) = myarray(i)
            ReDim Preserve myunique(UBound(myunique) + 1)
        End If
    Next
End With

For i = LBound(myunique) To UBound(myunique)
    Debug.Print myunique(i)
Next

End Sub

This uses array instead of range.
It also uses Match function instead of a nested For Loop.
I didn't have the time to check the time difference though.
So I leave the testing to you.

How can I pop-up a print dialog box using Javascript?

if problem:

 mywindow.print();

altenative using:

'<scr'+'ipt>print()</scr'+'ipt>'

Full:

 $('.print-ticket').click(function(){

        var body = $('body').html();
        var ticket_area = '<aside class="widget tickets">' + $('.widget.tickets').html() + '</aside>';

        $('body').html(ticket_area);
        var print_html = '<html lang="tr">' + $('html').html() + '<scr'+'ipt>print()</scr'+'ipt>' + '</html>'; 
        $('body').html(body);

        var mywindow = window.open('', 'my div', 'height=600,width=800');
        mywindow.document.write(print_html);
        mywindow.document.close(); // necessary for IE >= 10'</html>'
        mywindow.focus(); // necessary for IE >= 10
        //mywindow.print();
        mywindow.close();

        return true;
    });

npm ERR! network getaddrinfo ENOTFOUND

I was setting proxy as

npm config set http_proxy=http://domain:8080

instead of using the correct way

npm config set proxy http://domain:8080

How to convert a python numpy array to an RGB image with Opencv 2.4?

You don't need to convert NumPy array to Mat because OpenCV cv2 module can accept NumPyarray. The only thing you need to care for is that {0,1} is mapped to {0,255} and any value bigger than 1 in NumPy array is equal to 255. So you should divide by 255 in your code, as shown below.

img = numpy.zeros([5,5,3])

img[:,:,0] = numpy.ones([5,5])*64/255.0
img[:,:,1] = numpy.ones([5,5])*128/255.0
img[:,:,2] = numpy.ones([5,5])*192/255.0

cv2.imwrite('color_img.jpg', img)
cv2.imshow("image", img)
cv2.waitKey()

Standard concise way to copy a file in Java?

Three possible problems with the above code:

  1. If getChannel throws an exception, you might leak an open stream.
  2. For large files, you might be trying to transfer more at once than the OS can handle.
  3. You are ignoring the return value of transferFrom, so it might be copying just part of the file.

This is why org.apache.tools.ant.util.ResourceUtils.copyResource is so complicated. Also note that while transferFrom is OK, transferTo breaks on JDK 1.4 on Linux (see Bug ID:5056395) – Jesse Glick Jan

What is the purpose of "pip install --user ..."?

Without Virtual Environments

pip <command> --user changes the scope of the current pip command to work on the current user account's local python package install location, rather than the system-wide package install location, which is the default.

This only really matters on a multi-user machine. Anything installed to the system location will be visible to all users, so installing to the user location will keep that package installation separate from other users (they will not see it, and would have to install it themselves separately to use it). Because there can be version conflicts, installing a package with dependencies needed by other packages can cause problems, so it's best not to push all packages a given user uses to the system install location.

  • If it is a single-user machine, there is little or no difference to installing to the --user location. It will be installed to a different folder, that may or may not need to be added to the path, depending on the package and how it's used (many packages install command-line tools that must be on the path to run from a shell).
  • If it is a multi-user machine, --user is preferred to using root/sudo or requiring administrator installation and affecting the Python environment of every user, except in cases of general packages that the administrator wants to make available to all users by default.
    • Note: Per comments, on most Unix/Linux installs it has been pointed out that system installs should use the general package manager, such as apt, rather than pip.

With Virtual Environments

The --user option in an active venv/virtualenv environment will install to the local user python location (same as without a virtual environment).

Packages are installed to the virtual environment by default, but if you use --user it will force it to install outside the virtual environments, in the users python script directory (in Windows, this currently is c:\users\<username>\appdata\roaming\python\python37\scripts for me with Python 3.7).

However, you won't be able to access a system or user install from within virtual environment (even if you used --user while in a virtual environment).

If you install a virtual environment with the --system-site-packages argument, you will have access to the system script folder for python. I believe this included the user python script folder as well, but I'm unsure. However, there may be unintended consequences for this and it is not the intended way to use virtual environments.


Location of the Python System and Local User Install Folders

You can find the location of the user install folder for python with python -m site --user-base. I'm finding conflicting information in Q&A's, the documentation and actually using this command on my PC as to what the defaults are, but they are underneath the user home directory (~ shortcut in *nix, and c:\users\<username> typically for Windows).


Other Details

The --user option is not a valid for every command. For example pip uninstall will find and uninstall packages wherever they were installed (in the user folder, virtual environment folder, etc.) and the --user option is not valid.

Things installed with pip install --user will be installed in a local location that will only be seen by the current user account, and will not require root access (on *nix) or administrator access (on Windows).

The --user option modifies all pip commands that accept it to see/operate on the user install folder, so if you use pip list --user it will only show you packages installed with pip install --user.

PHP: Best way to check if input is a valid number?

return ctype_digit($num) && (int) $num > 0

How to align a <div> to the middle (horizontally/width) of the page

Some other pre-existing setups from older code that will prevent div page centering L&R are:

  1. Other classes hidden in external stylesheet links.
  2. Other classes embedded in something like an img (like for older external CSS print format controls).
  3. Legend code with IDs and/or CLASSES will conflict with a named div class.

Cause of No suitable driver found for

Not sure if it's worth anything, but I had a similar problem where I was getting a "java.sql.SQLException: No suitable driver found" error. I found this thread while researching a solution.

The way I ended up solving my problem was to forgo using java.sql.DriverManager to get a connection and instead built up an instance of org.hsqldb.jdbc.jdbcDataSource and used that.

The root cause of my problem (I believe) had to do with the classloader hierarchy and the fact that the JRE was running Java 5. Even though I could successfully load the jdbcDriver class, the classloader behind java.sql.DriverManager was higher up, to the point that it couldn't see the hsqldb.jar I needed.

Anyway, just putting this note here in case someone else stumbles by with a similar problem.

Getting value GET OR POST variable using JavaScript?

_x000D_
_x000D_
/**_x000D_
* getGET: [Funcion que captura las variables pasados por GET]_x000D_
* @Implementacion [pagina.html?id=10&pos=3]_x000D_
* @param  {[const ]} loc           [capturamos la url]_x000D_
* @return {[array]} get [Devuelve un array de clave=>valor]_x000D_
*/_x000D_
const getGET = () => {_x000D_
    const loc = document.location.href;_x000D_
_x000D_
            // si existe el interrogante_x000D_
            if(loc.indexOf('?')>0){_x000D_
            // cogemos la parte de la url que hay despues del interrogante_x000D_
            const getString = loc.split('?')[1];_x000D_
            // obtenemos un array con cada clave=valor_x000D_
            const GET = getString.split('&');_x000D_
            const get = {};_x000D_
_x000D_
            // recorremos todo el array de valores_x000D_
            for(let i = 0, l = GET.length; i < l; i++){_x000D_
                const tmp = GET[i].split('=');_x000D_
                get[tmp[0]] = unescape(decodeURI(tmp[1]));_x000D_
            }//::END for_x000D_
            return get;_x000D_
        }//::END if _x000D_
}//::END getGET_x000D_
_x000D_
/**_x000D_
* [DOMContentLoaded]_x000D_
* @param  {[const]} valores  [Cogemos los valores pasados por get]_x000D_
* @return {[document.write]}       _x000D_
*/_x000D_
document.addEventListener('DOMContentLoaded', () => {_x000D_
    const valores=getGET();_x000D_
_x000D_
    if(valores){_x000D_
            // hacemos un bucle para pasar por cada indice del array de valores_x000D_
            for(const index in valores){_x000D_
                document.write(`<br>clave: ${index} - valor: ${valores[index]}`);_x000D_
            }//::END for_x000D_
        }else{_x000D_
            // no se ha recibido ningun parametro por GET_x000D_
            document.write("<br>No se ha recibido ningún parámetro");_x000D_
        }//::END if_x000D_
});//::END DOMContentLoaded
_x000D_
_x000D_
_x000D_

Using custom fonts using CSS?

You have to download the font file and load it in your CSS.

F.e. I'm using the Yanone Kaffeesatz font in my Web Application.

I load and use it via

@font-face {
    font-family: "Yanone Kaffeesatz";
    src: url("../fonts/YanoneKaffeesatz-Regular.ttf");
}

in my stylesheet.

'node' is not recognized as an internal or external command

I set the NODEJS variable in the system control panel but the only thing that worked to set the path was to do it from command line as administrator.

SET PATH=%NODEJS%;%PATH%

Another trick is that once you set the path you must close the console and open a new one for the new path to be taken into account.

However for the regular user to be able to use node I had to run set path again not as admin and restart the computer

How to prevent page from reloading after form submit - JQuery

The <button> element, when placed in a form, will submit the form automatically unless otherwise specified. You can use the following 2 strategies:

  1. Use <button type="button"> to override default submission behavior
  2. Use event.preventDefault() in the onSubmit event to prevent form submission

Solution 1:

  • Advantage: simple change to markup
  • Disadvantage: subverts default form behavior, especially when JS is disabled. What if the user wants to hit "enter" to submit?

Insert extra type attribute to your button markup:

<button id="button" type="button" value="send" class="btn btn-primary">Submit</button>

Solution 2:

  • Advantage: form will work even when JS is disabled, and respects standard form UI/UX such that at least one button is used for submission

Prevent default form submission when button is clicked. Note that this is not the ideal solution because you should be in fact listening to the submit event, not the button click event:

$(document).ready(function () {
  // Listen to click event on the submit button
  $('#button').click(function (e) {

    e.preventDefault();

    var name = $("#name").val();
    var email = $("#email").val();

    $.post("process.php", {
      name: name,
      email: email
    }).complete(function() {
        console.log("Success");
      });
  });
});

Better variant:

In this improvement, we listen to the submit event emitted from the <form> element:

$(document).ready(function () {
  // Listen to submit event on the <form> itself!
  $('#main').submit(function (e) {

    e.preventDefault();

    var name = $("#name").val();
    var email = $("#email").val();

    $.post("process.php", {
      name: name,
      email: email
    }).complete(function() {
        console.log("Success");
      });
  });
});

Even better variant: use .serialize() to serialize your form, but remember to add name attributes to your input:

The name attribute is required for .serialize() to work, as per jQuery's documentation:

For a form element's value to be included in the serialized string, the element must have a name attribute.

<input type="text" id="name" name="name" class="form-control mb-2 mr-sm-2 mb-sm-0" id="inlineFormInput" placeholder="Jane Doe">
<input type="text" id="email" name="email" class="form-control" id="inlineFormInputGroup" placeholder="[email protected]">

And then in your JS:

$(document).ready(function () {
  // Listen to submit event on the <form> itself!
  $('#main').submit(function (e) {

    // Prevent form submission which refreshes page
    e.preventDefault();

    // Serialize data
    var formData = $(this).serialize();

    // Make AJAX request
    $.post("process.php", formData).complete(function() {
      console.log("Success");
    });
  });
});

Get connection string from App.config

Can't you just do the following:

var connection = 
    System.Configuration.ConfigurationManager.
    ConnectionStrings["Test"].ConnectionString;

Your assembly also needs a reference to System.Configuration.dll

Parsing JSON giving "unexpected token o" error

Using JSON.stringify(data);:

$.ajax({
    url: ...
    success:function(data){
        JSON.stringify(data); //to string
        alert(data.you_value); //to view you pop up
    }
});

SQL query for extracting year from a date

This worked for me:

SELECT EXTRACT(YEAR FROM ASOFDATE) FROM PSASOFDATE;

How to get current date & time in MySQL?

In database design, iIhighly recommend using Unixtime for consistency and indexing / search / comparison performance.

UNIX_TIMESTAMP() 

One can always convert to human readable formats afterwards, internationalizing as is individually most convenient.

FROM_ UNIXTIME (unix_timestamp, [format ])

Make view 80% width of parent in React Native

I have an updated solution (late 2019) , to get 80% width of parent Responsively with Hooks it work's even if the device rotate.

You can use Dimensions.get('window').width to get Device Width in this example you can see how you can do it Responsively

import React, { useEffect, useState } from 'react';
import { Dimensions , View , Text , StyleSheet  } from 'react-native';

export default const AwesomeProject() => {
   const [screenData, setScreenData] = useState(Dimensions.get('window').width);

    useEffect(() => {
     const onChange = () => {
     setScreenData(Dimensions.get('window').width);
     };
     Dimensions.addEventListener('change', onChange);

     return () => {Dimensions.removeEventListener('change', onChange);};
    });

   return (  
          <View style={[styles.container, { width: screenData * 0.8 }]}>
             <Text> I'mAwesome </Text>
           </View>
    );
}

const styles = StyleSheet.create({
container: {
     flex: 1,
     alignItems: 'center',
     justifyContent: 'center',
     backgroundColor: '#eee',
     },
});

jQuery - hashchange event

I just ran into the same problem (lack of hashchange event in IE7). A workaround that suited for my purposes was to bind the click event of the hash-changing links.

<a class='hash-changer' href='#foo'>Foo</a>

<script type='text/javascript'>

if (("onhashchange" in window) && !($.browser.msie)) { 

    //modern browsers 
    $(window).bind('hashchange', function() {
        var hash = window.location.hash.replace(/^#/,'');
        //do whatever you need with the hash
    });

} else {

    //IE and browsers that don't support hashchange
    $('a.hash-changer').bind('click', function() {
        var hash = $(this).attr('href').replace(/^#/,'');
        //do whatever you need with the hash
    });

}

</script>

How can we store into an NSDictionary? What is the difference between NSDictionary and NSMutableDictionary?

The key difference: NSMutableDictionary can be modified in place, NSDictionary cannot. This is true for all the other NSMutable* classes in Cocoa. NSMutableDictionary is a subclass of NSDictionary, so everything you can do with NSDictionary you can do with both. However, NSMutableDictionary also adds complementary methods to modify things in place, such as the method setObject:forKey:.

You can convert between the two like this:

NSMutableDictionary *mutable = [[dict mutableCopy] autorelease];
NSDictionary *dict = [[mutable copy] autorelease]; 

Presumably you want to store data by writing it to a file. NSDictionary has a method to do this (which also works with NSMutableDictionary):

BOOL success = [dict writeToFile:@"/file/path" atomically:YES];

To read a dictionary from a file, there's a corresponding method:

NSDictionary *dict = [NSDictionary dictionaryWithContentsOfFile:@"/file/path"];

If you want to read the file as an NSMutableDictionary, simply use:

NSMutableDictionary *dict = [NSMutableDictionary dictionaryWithContentsOfFile:@"/file/path"];

Laravel 5: Retrieve JSON array from $request

You need to change your Ajax call to

$.ajax({
    type: "POST",
    url: "/people",
    data: '[{ "name": "John", "location": "Boston" }, { "name": "Dave", "location": "Lancaster" }]',
    contentType: "json",
    processData: false,
    success:function(data) {
        $('#save_message').html(data.message);
    } 
});

change the dataType to contentType and add the processData option.

To retrieve the JSON payload from your controller, use:

dd(json_decode($request->getContent(), true));

instead of

dd($request->all());

Disable PHP in directory (including all sub-directories) with .htaccess

This will display the source code instead of executing it:

<VirtualHost *>
    ServerName sourcecode.testserver.me
    DocumentRoot /var/www/example
    AddType text/plain php
</VirtualHost>

I used it once to enable other co-worker to have read access to the source code from the local network (just a quick and dirty alternative).

WARNING !:

As Dan pointed it out sometime ago, this method should never be used in production. Please follow the accepted answer as it blocks any attempt to execute or display php files.

If you want users to share php files (and let others to display the source code), there are better ways to do it, like git, wiki, etc.

This method should be avoided! (you have been warned. Left it here for educational purposes)

Create Generic method constraining T to an Enum

Since Enum Type implements IConvertible interface, a better implementation should be something like this:

public T GetEnumFromString<T>(string value) where T : struct, IConvertible
{
   if (!typeof(T).IsEnum) 
   {
      throw new ArgumentException("T must be an enumerated type");
   }

   //...
}

This will still permit passing of value types implementing IConvertible. The chances are rare though.

Spring .properties file: get element as an Array

If you need to pass the asterisk symbol, you have to wrap it with quotes.

In my case, I need to configure cors for websockets. So, I decided to put cors urls into application.yml. For prod env I'll use specific urls, but for dev it's ok to use just *.

In yml file I have:

websocket:
  cors: "*"

In Config class I have:

@Value("${websocket.cors}")
private String[] cors;

@JsonProperty annotation on field as well as getter/setter

My observations based on a few tests has been that whichever name differs from the property name is one which takes effect:

For eg. consider a slight modification of your case:

@JsonProperty("fileName")
private String fileName;

@JsonProperty("fileName")
public String getFileName()
{
    return fileName;
}

@JsonProperty("fileName1")
public void setFileName(String fileName)
{
    this.fileName = fileName;
}

Both fileName field, and method getFileName, have the correct property name of fileName and setFileName has a different one fileName1, in this case Jackson will look for a fileName1 attribute in json at the point of deserialization and will create a attribute called fileName1 at the point of serialization.

Now, coming to your case, where all the three @JsonProperty differ from the default propertyname of fileName, it would just pick one of them as the attribute(FILENAME), and had any on of the three differed, it would have thrown an exception:

java.lang.IllegalStateException: Conflicting property name definitions

Accessing elements by type in javascript

If you are lucky and need to care only for recent browsers, you can use:

document.querySelectorAll('input[type=text]')

"recent" means not IE6 and IE7

AngularJS accessing DOM elements inside directive template

You could write a directive for this, which simply assigns the (jqLite) element to the scope using an attribute-given name.

Here is the directive:

app.directive("ngScopeElement", function () {
  var directiveDefinitionObject = {

    restrict: "A",

    compile: function compile(tElement, tAttrs, transclude) {
      return {
          pre: function preLink(scope, iElement, iAttrs, controller) {
            scope[iAttrs.ngScopeElement] = iElement;
          }
        };
    }
  };

  return directiveDefinitionObject;
});

Usage:

app.directive("myDirective", function() {
    return {
        template: '<div><ul ng-scope-element="list"><li ng-repeat="item in items"></ul></div>',
        link: function(scope, element, attrs) {
            scope.list[0] // scope.list is the jqlite element, 
                          // scope.list[0] is the native dom element
        }
    }
});

Some remarks:

  • Due to the compile and link order for nested directives you can only access scope.list from myDirectives postLink-Function, which you are very likely using anyway
  • ngScopeElement uses a preLink-function, so that directives nested within the element having ng-scope-element can already access scope.list
  • not sure how this behaves performance-wise

Remove sensitive files and their commits from Git history

So, It looks something like this:

git rm --cached /config/deploy.rb
echo /config/deploy.rb >> .gitignore

Remove cache for tracked file from git and add that file to .gitignore list

How can I return pivot table output in MySQL?

There is a tool called MySQL Pivot table generator, it can help you create web based pivot table that you can later export to excel(if you like). it can work if your data is in a single table or in several tables .

All you need to do is to specify the data source of the columns (it supports dynamic columns), rows , the values in the body of the table and table relationship (if there are any) MySQL Pivot Table

The home page of this tool is http://mysqlpivottable.net

PHP multidimensional array search by value

You can use array_column for that.

$search_value = '5465';
$search_key   = 'uid';
$user = array_search($search_value, array_column($userdb, $search_key));

print_r($userdb[$user]);

5465 is the user ID you want to search, uid is the key that contains user ID and $userdb is the array that is defined in the question.

How to get data from Magento System Configuration

$configValue = Mage::getStoreConfig('sectionName/groupName/fieldName');

sectionName, groupName and fieldName are present in etc/system.xml file of your module.

The above code will automatically fetch config value of currently viewed store.

If you want to fetch config value of any other store than the currently viewed store then you can specify store ID as the second parameter to the getStoreConfig function as below:

$store = Mage::app()->getStore(); // store info
$configValue = Mage::getStoreConfig('sectionName/groupName/fieldName', $store);

Install gitk on Mac

As of macOS Catalina 10.15.6, I run:

brew install git
brew install git-gui

and it worked for me.

How to: Create trigger for auto update modified date with SQL Server 2008

My approach:

  • define a default constraint on the ModDate column with a value of GETDATE() - this handles the INSERT case

  • have a AFTER UPDATE trigger to update the ModDate column

Something like:

CREATE TRIGGER trg_UpdateTimeEntry
ON dbo.TimeEntry
AFTER UPDATE
AS
    UPDATE dbo.TimeEntry
    SET ModDate = GETDATE()
    WHERE ID IN (SELECT DISTINCT ID FROM Inserted)

How to clear Facebook Sharer cache?

This answer is intended for developers.

Clearing the cache means that new shares of this webpage will show the new content which is provided in the OG tags. But only if the URL that you are working on has less than 50 interactions (likes + shares). It will also not affect old links to this webpage which have already been posted on Facebook. Only when sharing the URL on Facebook again will the way that Facebook shows the link be updated.

catandmouse's answer is correct but you can also make Facebook clear the OG (OpenGraph) cache by sending a post request to graph.facebook.com (works for both http and https as of the writing of this answer). You do not need an access token.

A post request to graph.facebook.com may look as follows:

POST / HTTP/1.1
Content-Type: application/x-www-form-urlencoded
Host: graph.facebook.com
Content-Length: 63
Accept-Encoding: gzip
User-Agent: Mojolicious (Perl)

id=<url_encoded_url>&scrape=true

In Perl, you can use the following code where the library Mojo::UserAgent is used to send and receive HTTP requests:

sub _clear_og_cache_on_facebook {
    my $fburl     = "http://graph.facebook.com";
    my $ua        = Mojo::UserAgent->new;
    my $clearurl  = <the url you want Facebook to forget>;
    my $post_body = {id => $clearurl, scrape => 'true'};
    my $res       = $ua->post($fburl => form => $post_body)->res;
    my $code      = $res->code;
    unless ($code eq '200') {
        Log->warn("Clearing cached OG data for $clearurl failed with code $code.");
        }
    }
}

Sending this post request through the terminal can be done with the following command:

curl -F id="<URL>" -F scrape=true graph.facebook.com

Could not find a version that satisfies the requirement tensorflow

Tensorflow 2.2.0 supports Python3.8

First, make sure to install Python 3.8 64bit. For some reason, the official site defaults to 32bit. Verify this using python -VV (two capital V, not W). Then continue as usual:

python -m pip install --upgrade pip
python -m pip install wheel  # not necessary
python -m pip install tensorflow

As usual, make sure you have CUDA 10.1 and CuDNN installed.

How to view an HTML file in the browser with Visual Studio Code

If you're just on Mac this tasks.json file:

{
    "version": "0.1.0",
    "command": "open",
    "args": ["${file}"],
}

...is all you need to open the current file in Safari, assuming its extension is ".html".

Create tasks.json as described above and invoke it with ?+shift+b.

If you want it to open in Chrome then:

{
    "version": "0.1.0",
    "command": "open",
    "args": ["-a", "Chrome.app", "${file}"],
}

This will do what you want, as in opening in a new tab if the app is already open.

What does <T> denote in C#

This feature is known as generics. http://msdn.microsoft.com/en-us/library/512aeb7t(v=vs.100).aspx

An example of this is to make a collection of items of a specific type.

class MyArray<T>
{
    T[] array = new T[10];

    public T GetItem(int index)
    {
        return array[index];
    }
}

In your code, you could then do something like this:

MyArray<int> = new MyArray<int>();

In this case, T[] array would work like int[] array, and public T GetItem would work like public int GetItem.

OpenCV - Saving images to a particular folder of choice

Answer given by Jeru Luke is working only on Windows systems, if we try on another operating system (Ubuntu) then it runs without error but the image is saved on target location or path.

Not working in Ubuntu and working in Windows

  import cv2
  img = cv2.imread('1.jpg', 1)
  path = '/tmp'
  cv2.imwrite(str(path) + 'waka.jpg',img)
  cv2.waitKey(0)

I run above code but the image does not save the image on target path. Then I found that the way of adding path is wrong for the general purpose we using OS module to add the path.

Example:

 import os
 final_path = os.path.join(path_1,path_2,path_3......)

working in Ubuntu and Windows

 import cv2
 import os
 img = cv2.imread('1.jpg', 1)
 path = 'D:/OpenCV/Scripts/Images'
 cv2.imwrite(os.path.join(path , 'waka.jpg'),img)
 cv2.waitKey(0)

that code works fine on both Windows and Ubuntu :)

Replace part of a string in Python?

You can easily use .replace() as also previously described. But it is also important to keep in mind that strings are immutable. Hence if you do not assign the change you are making to a variable, then you will not see any change. Let me explain by;

    >>stuff = "bin and small"
    >>stuff.replace('and', ',')
    >>print(stuff)
    "big and small" #no change

To observe the change you want to apply, you can assign same or another variable;

    >>stuff = "big and small"
    >>stuff = stuff.replace("and", ",")   
    >>print(stuff)
    'big, small'

Creating folders inside a GitHub repository without using Git

Another thing you can do is just drag a folder from your computer into the GitHub repository page. This folder does have to have at least 1 item in it, though.

Get current URL path in PHP

<?php
function current_url()
{
    $url      = "http://" . $_SERVER['HTTP_HOST'] . $_SERVER['REQUEST_URI'];
    $validURL = str_replace("&", "&amp", $url);
    return $validURL;
}
//echo "page URL is : ".current_url();

$offer_url = current_url();

?>



<?php

if ($offer_url == "checking url name") {
?> <p> hi this is manip5595 </p>

<?php
}
?>

What is the difference between an annotated and unannotated tag?

Push annotated tags, keep lightweight local

man git-tag says:

Annotated tags are meant for release while lightweight tags are meant for private or temporary object labels.

And certain behaviors do differentiate between them in ways that this recommendation is useful e.g.:

  • annotated tags can contain a message, creator, and date different than the commit they point to. So you could use them to describe a release without making a release commit.

    Lightweight tags don't have that extra information, and don't need it, since you are only going to use it yourself to develop.

  • git push --follow-tags will only push annotated tags
  • git describe without command line options only sees annotated tags

Internals differences

  • both lightweight and annotated tags are a file under .git/refs/tags that contains a SHA-1

  • for lightweight tags, the SHA-1 points directly to a commit:

    git tag light
    cat .git/refs/tags/light
    

    prints the same as the HEAD's SHA-1.

    So no wonder they cannot contain any other metadata.

  • annotated tags point to a tag object in the object database.

    git tag -as -m msg annot
    cat .git/refs/tags/annot
    

    contains the SHA of the annotated tag object:

    c1d7720e99f9dd1d1c8aee625fd6ce09b3a81fef
    

    and then we can get its content with:

    git cat-file -p c1d7720e99f9dd1d1c8aee625fd6ce09b3a81fef
    

    sample output:

    object 4284c41353e51a07e4ed4192ad2e9eaada9c059f
    type commit
    tag annot
    tagger Ciro Santilli <[email protected]> 1411478848 +0200
    
    msg
    -----BEGIN PGP SIGNATURE-----
    Version: GnuPG v1.4.11 (GNU/Linux)
    
    <YOUR PGP SIGNATURE>
    -----END PGP SIGNAT
    

    And this is how it contains extra metadata. As we can see from the output, the metadata fields are:

    A more detailed analysis of the format is present at: What is the format of a git tag object and how to calculate its SHA?

Bonuses

  • Determine if a tag is annotated:

    git cat-file -t tag
    

    Outputs

    • commit for lightweight, since there is no tag object, it points directly to the commit
    • tag for annotated, since there is a tag object in that case
  • List only lightweight tags: How can I list all lightweight tags?

Get the selected option id with jQuery

You can get it using the :selected selector, like this:

$("#my_select").change(function() {
  var id = $(this).children(":selected").attr("id");
});

Getting list of files in documents folder

Swift 5

// Get the document directory url
let documentsUrl =  FileManager.default.urls(for: .documentDirectory, in: .userDomainMask).first!

do {
    // Get the directory contents urls (including subfolders urls)
    let directoryContents = try FileManager.default.contentsOfDirectory(at: documentsUrl, includingPropertiesForKeys: nil)
    print(directoryContents)

    // if you want to filter the directory contents you can do like this:
    let mp3Files = directoryContents.filter{ $0.pathExtension == "mp3" }
    print("mp3 urls:",mp3Files)
    let mp3FileNames = mp3Files.map{ $0.deletingPathExtension().lastPathComponent }
    print("mp3 list:", mp3FileNames)

} catch {
    print(error)
}

Disable scrolling on `<input type=number>`

@Semyon Perepelitsa

There is a better solution for this. Blur removes the focus from the input and that is a side affect that you do not want. You should use evt.preventDefault instead. This prevents the default behavior of the input when the user scrolls. Here is the code:

input = document.getElementById("the_number_input")
input.addEventListener("mousewheel", function(evt){ evt.preventDefault(); })

Repeat command automatically in Linux

A concise solution, which is particularly useful if you want to run the command repeatedly until it fails, and lets you see all output.

while ls -l; do
    sleep 5
done

How to specify in crontab by what user to run script?

Since you're running Ubuntu, your system crontab is located at /etc/crontab.

As the root user (or using sudo), you can simply edit this file and specify the user that should run this command. Here is the format of entries in the system crontab and how you should enter your command:

# m h dom mon dow user  command
*/1 * * * * www-data php5 /var/www/web/includes/crontab/queue_process.php >> /var/www/web/includes/crontab/queue.log 2>&1

Of course the permissions for your php script and your log file should be set so that the www-data user has access to them.

Pass a list to a function to act as multiple arguments

Since Python 3.5 you can unpack unlimited amount of lists.

PEP 448 - Additional Unpacking Generalizations

So this will work:

a = ['1', '2', '3', '4']
b = ['5', '6']
function_that_needs_strings(*a, *b)

Merge Two Lists in R

Here's some code that I ended up writing, based upon @Andrei's answer but without the elegancy/simplicity. The advantage is that it allows a more complex recursive merge and also differs between elements that should be connected with rbind and those that are just connected with c:

# Decided to move this outside the mapply, not sure this is 
# that important for speed but I imagine redefining the function
# might be somewhat time-consuming
mergeLists_internal <- function(o_element, n_element){
  if (is.list(n_element)){
    # Fill in non-existant element with NA elements
    if (length(n_element) != length(o_element)){
      n_unique <- names(n_element)[! names(n_element) %in% names(o_element)]
      if (length(n_unique) > 0){
        for (n in n_unique){
          if (is.matrix(n_element[[n]])){
            o_element[[n]] <- matrix(NA, 
                                     nrow=nrow(n_element[[n]]), 
                                     ncol=ncol(n_element[[n]]))
          }else{
            o_element[[n]] <- rep(NA, 
                                  times=length(n_element[[n]]))
          }
        }
      }

      o_unique <- names(o_element)[! names(o_element) %in% names(n_element)]
      if (length(o_unique) > 0){
        for (n in o_unique){
          if (is.matrix(n_element[[n]])){
            n_element[[n]] <- matrix(NA, 
                                     nrow=nrow(o_element[[n]]), 
                                     ncol=ncol(o_element[[n]]))
          }else{
            n_element[[n]] <- rep(NA, 
                                  times=length(o_element[[n]]))
          }
        }
      }
    }  

    # Now merge the two lists
    return(mergeLists(o_element, 
                      n_element))

  }
  if(length(n_element)>1){
    new_cols <- ifelse(is.matrix(n_element), ncol(n_element), length(n_element))
    old_cols <- ifelse(is.matrix(o_element), ncol(o_element), length(o_element))
    if (new_cols != old_cols)
      stop("Your length doesn't match on the elements,",
           " new element (", new_cols , ") !=",
           " old element (", old_cols , ")")
  }

  return(rbind(o_element, 
               n_element, 
               deparse.level=0))
  return(c(o_element, 
           n_element))
}
mergeLists <- function(old, new){
  if (is.null(old))
    return (new)

  m <- mapply(mergeLists_internal, old, new, SIMPLIFY=FALSE)
  return(m)
}

Here's my example:

v1 <- list("a"=c(1,2), b="test 1", sublist=list(one=20:21, two=21:22))
v2 <- list("a"=c(3,4), b="test 2", sublist=list(one=10:11, two=11:12, three=1:2))
mergeLists(v1, v2)

This results in:

$a
     [,1] [,2]
[1,]    1    2
[2,]    3    4

$b
[1] "test 1" "test 2"

$sublist
$sublist$one
     [,1] [,2]
[1,]   20   21
[2,]   10   11

$sublist$two
     [,1] [,2]
[1,]   21   22
[2,]   11   12

$sublist$three
     [,1] [,2]
[1,]   NA   NA
[2,]    1    2

Yeah, I know - perhaps not the most logical merge but I have a complex parallel loop that I had to generate a more customized .combine function for, and therefore I wrote this monster :-)

jquery - Click event not working for dynamically created button

My guess is that the buttons you created are not yet on the page by the time you bind the button. Either bind each button in the $.getJSON function, or use a dynamic binding method like:

$('body').on('click', 'button', function() {
    ...
});

Note you probably don't want to do this on the 'body' tag, but instead wrap the buttons in another div or something and call on on it.

jQuery On Method

Java - Including variables within strings?

you can use String format to include variables within strings

i use this code to include 2 variable in string:

String myString = String.format("this is my string %s %2d", variable1Name, variable2Name);

Good NumericUpDown equivalent in WPF?

A control that is missing from the original set of WPF controls, but much used, is the NumericUpDown control. It is a neat way to get users to select a number from a fixed range, in a small area. A slider could be used, but for compact forms with little horizontal real-estate, the NumericUpDown is essential.

Solution A (via WindowsFormsHost)

You can use the Windows Forms NumericUpDown control in WPF by hosting it in a WindowsFormsHost. Pay attention that you have to include a reference to System.Windows.Forms.dll assembly.

<Window x:Class="WpfApplication61.MainWindow"
        xmlns="http://schemas.microsoft.com/winfx/2006/xaml/presentation"
        xmlns:x="http://schemas.microsoft.com/winfx/2006/xaml"
        xmlns:wf="clr-namespace:System.Windows.Forms;assembly=System.Windows.Forms" 
        Title="MainWindow" Height="350" Width="525">
    <StackPanel>    
        <WindowsFormsHost>
            <wf:NumericUpDown/>
        </WindowsFormsHost>
...

Solution B (custom)

There are several commercial and codeplex versions around, but both involve installing 3rd party dlls and overheads to your project. Far simpler to build your own, and a aimple way to do that is with the ScrollBar.

A vertical ScrollBar with no Thumb (just the repeater buttons) is in fact just what we want. It inherits rom RangeBase, so it has all the properties we need, like Min, Max, and SmallChange (set to 1, to restrict it to Integer values)

So we change the ScrollBar ControlTemplate. First we remove the Thumb and Horizontal trigger actions. Then we group the remains into a grid and add a TextBlock for the number:

<Grid Margin="2">
    <Grid.ColumnDefinitions>
        <ColumnDefinition/>
        <ColumnDefinition />
    </Grid.ColumnDefinitions>
    <TextBlock VerticalAlignment="Center" FontSize="20" MinWidth="25" Text="{Binding Value, RelativeSource={RelativeSource TemplatedParent}}"/>
    <Grid Grid.Column="1" x:Name="GridRoot" Width="{DynamicResource {x:Static SystemParameters.VerticalScrollBarWidthKey}}" Background="{TemplateBinding Background}">
        <Grid.RowDefinitions>
            <RowDefinition MaxHeight="18"/>
            <RowDefinition Height="0.00001*"/>
            <RowDefinition MaxHeight="18"/>
        </Grid.RowDefinitions>
        <RepeatButton x:Name="DecreaseRepeat" Command="ScrollBar.LineDownCommand" Focusable="False">
            <Grid>
                <Path x:Name="DecreaseArrow" Stroke="{TemplateBinding Foreground}" StrokeThickness="1" Data="M 0 4 L 8 4 L 4 0 Z"/>
            </Grid>
        </RepeatButton>
        <RepeatButton Grid.Row="2" x:Name="IncreaseRepeat" Command="ScrollBar.LineUpCommand" Focusable="False">
            <Grid>
                <Path x:Name="IncreaseArrow" Stroke="{TemplateBinding Foreground}" StrokeThickness="1" Data="M 0 0 L 4 4 L 8 0 Z"/>
            </Grid>
        </RepeatButton>
    </Grid>
</Grid>

Sources:

Check if a string contains another string

There is also the InStrRev function which does the same type of thing, but starts searching from the end of the text to the beginning.

Per @rene's answer...

Dim pos As Integer
pos = InStrRev("find the comma, in the string", ",")

...would still return 15 to pos, but if the string has more than one of the search string, like the word "the", then:

Dim pos As Integer
pos = InStrRev("find the comma, in the string", "the")

...would return 20 to pos, instead of 6.

ES6 modules implementation, how to load a json file

With json-loader installed, now you can simply use:

import suburbs from '../suburbs.json';

or, even more simply:

import suburbs from '../suburbs';

Using port number in Windows host file

If what is happening is that you have another server running on localhost and you want to give this new server a different local hostname like http://teamviewer/

I think that what you are actually looking for is Virtual Hosts functionality. I use Apache so I do not know how other web daemons support this. Maybe it is called Alias. Here is the Apache documentation:

Apache Virtual Hosts examples

How do I add a newline to a windows-forms TextBox?

First you have to set the MultiLine property of the TextBox to true so that it supports multiple lines.

Then you just use Environment.NewLine to get the newline character combination.

How to bind a List<string> to a DataGridView control?

you can also use linq and anonymous types to achieve the same result with much less code as described here.

UPDATE: blog is down, here's the content:

(..) The values shown in the table represent the length of strings instead of string values (!) It may seem strange, but that’s how binding mechanism works by default – given an object it will try to bind to the first property of that object (the first property it can find). When passed an instance the String class the property it binds to is String.Length since there’s no other property that would provide the actual string itself.

That means that to get our binding right we need a wrapper object that will expose the actual value of a string as a property:

public class StringWrapper
    {
     string stringValue;
     public string StringValue { get { return stringValue; } set { stringValue = value; } }

     public StringWrapper(string s)
     {
     StringValue = s;
     }
  }   

   List<StringWrapper> testData = new List<StringWrapper>();

   // add data to the list / convert list of strings to list of string wrappers

  Table1.SetDataBinding(testdata);

While this solution works as expected it requires quite a few lines of code (mostly to convert list of strings to the list of string wrappers).

We can improve this solution by using LINQ and anonymous types- we’ll use LINQ query to create a new list of string wrappers (string wrapper will be an anonymous type in our case).

 var values = from data in testData select new { Value = data };

 Table1.SetDataBinding(values.ToList());

The last change we’re going to make is to move the LINQ code to an extension method:

public static class StringExtensions
  {
     public static IEnumerable CreateStringWrapperForBinding(this IEnumerable<string> strings)
     {
     var values = from data in strings
     select new { Value = data };

     return values.ToList();
     }

This way we can reuse the code by calling single method on any collection of strings:

Table1.SetDataBinding(testData.CreateStringWrapperForBinding());

Redirect after Login on WordPress

The accepted answer is clearly not a good answer! It may solve your problem for a while, but what will happen next time you update your WordPress installation? Your core files may get overridden and you will loose all your modifications.

As already stated by others (Dan and Travis answers), the correct answer is to use the login_redirect filter.

Center a DIV horizontally and vertically

You want to set style

margin: auto;

And remove the positioning styles (top, left, position)

I know this will center horrizontaly but I'm not sure about vertical!

When should you use 'friend' in C++?

You control the access rights for members and functions using Private/Protected/Public right? so assuming the idea of each and every one of those 3 levels is clear, then it should be clear that we are missing something...

The declaration of a member/function as protected for example is pretty generic. You are saying that this function is out of reach for everyone (except for an inherited child of course). But what about exceptions? every security system lets you have some type of 'white list" right?

So friend lets you have the flexibility of having rock solid object isolation, but allows for a "loophole" to be created for things that you feel are justified.

I guess people say it is not needed because there is always a design that will do without it. I think it is similar to the discussion of global variables: You should never use them, There is always a way to do without them... but in reality, you see cases where that ends up being the (almost) most elegant way... I think this is the same case with friends.

It doesn't really do any good, other than let you access a member variable without using a setting function

well that is not exactly the way to look at it. The idea is to control WHO can access what, having or not a setting function has little to do with it.

python location on mac osx

On High Sierra

which python

shows the default python but if you downloaded and installed the latest version from python.org you can find it by:

which python3.6

which on my machine shows

/Library/Frameworks/Python.framework/Versions/3.6/bin/python3.6

undefined reference to 'vtable for class' constructor

You're declaring a virtual function and not defining it:

virtual void calculateCredits();

Either define it or declare it as:

virtual void calculateCredits() = 0;

Or simply:

virtual void calculateCredits() { };

Read more about vftable: http://en.wikipedia.org/wiki/Virtual_method_table

How to use split?

Documentation can be found e.g. at MDN. Note that .split() is not a jQuery method, but a native string method.

If you use .split() on a string, then you get an array back with the substrings:

var str = 'something -- something_else';
var substr = str.split(' -- ');
// substr[0] contains "something"
// substr[1] contains "something_else"

If this value is in some field you could also do:

tRow.append($('<td>').text($('[id$=txtEntry2]').val().split(' -- ')[0])));

Regular expression that matches valid IPv6 addresses

I'd have to strongly second the answer from Frank Krueger.

Whilst you say you need a regular expression to match an IPv6 address, I'm assuming what you really need is to be able to check if a given string is a valid IPv6 address. There is a subtle but important distinction here.

There is more than one way to check if a given string is a valid IPv6 address and regular expression matching is only one solution.

Use an existing library if you can. The library will have fewer bugs and its use will result in less code for you to maintain.

The regular expression suggested by Factor Mystic is long and complex. It most likely works, but you should also consider how you'd cope if it unexpectedly fails. The point I'm trying to make here is that if you can't form a required regular expression yourself you won't be able to easily debug it.

If you have no suitable library it may be better to write your own IPv6 validation routine that doesn't depend on regular expressions. If you write it you understand it and if you understand it you can add comments to explain it so that others can also understand and subsequently maintain it.

Act with caution when using a regular expression whose functionality you can't explain to someone else.

SQL Server : SUM() of multiple rows including where clauses

This will bring back totals per property and type

SELECT  PropertyID,
        TYPE,
        SUM(Amount)
FROM    yourTable
GROUP BY    PropertyID,
            TYPE

This will bring back only active values

SELECT  PropertyID,
        TYPE,
        SUM(Amount)
FROM    yourTable
WHERE   EndDate IS NULL
GROUP BY    PropertyID,
            TYPE

and this will bring back totals for properties

SELECT  PropertyID,
        SUM(Amount)
FROM    yourTable
WHERE   EndDate IS NULL
GROUP BY    PropertyID

......