Programs & Examples On #Native

An application designed to run in the computer environment (machine language and OS) being referenced. The term is used to contrast a native application with an interpreted one such as a Java application that is not native to a single platform.

`React/RCTBridgeModule.h` file not found

This error appeared for me after I ran pod install command for the new dependencies. Along with those, React had also been installed. Therefore probably Xcode was confused for path. I removed these lines from PodFile and error was gone. Please note that those removed from here were already linked in Xcode.

target 'app' do

  pod 'GoogleMaps'
  pod 'Firebase/Auth', '~> 6.3.0'
  pod 'Firebase/Database', '~> 6.3.0'

  # Removed four pods below and it worked.

  pod 'react-native-image-picker', :path => '../node_modules/react-native-image-picker'

  pod 'ReactNativePermissions', :path => '../node_modules/react-native-permissions'

  pod 'react-native-image-resizer', :path => '../node_modules/react-native-image-resizer'

  pod 'RNFS', :path => '../node_modules/react-native-fs'

  end

What is the native keyword in Java for?

The native keyword is applied to a method to indicate that the method is implemented in native code using JNI (Java Native Interface).

Is there any native DLL export functions viewer?

If you don't have the source code and API documentation, the machine code is all there is, you need to disassemble the dll library using something like IDA Pro , another option is use the trial version of PE Explorer.

PE Explorer provides a Disassembler. There is only one way to figure out the parameters: run the disassembler and read the disassembly output. Unfortunately, this task of reverse engineering the interface cannot be automated.

PE Explorer comes bundled with descriptions for 39 various libraries, including the core Windows® operating system libraries (eg. KERNEL32, GDI32, USER32, SHELL32, WSOCK32), key graphics libraries (DDRAW, OPENGL32) and more.

alt text
(source: heaventools.com)

What are native methods in Java and where should they be used?

I like to know where does we use Native Methods

Ideally, not at all. In reality some functionality is not available in Java and you have to call some C code.

The methods are implemented in C code.

What do these operators mean (** , ^ , %, //)?

You are correct that ** is the power function.

^ is bitwise XOR.

% is indeed the modulus operation, but note that for positive numbers, x % m = x whenever m > x. This follows from the definition of modulus. (Additionally, Python specifies x % m to have the sign of m.)

// is a division operation that returns an integer by discarding the remainder. This is the standard form of division using the / in most programming languages. However, Python 3 changed the behavior of / to perform floating-point division even if the arguments are integers. The // operator was introduced in Python 2.6 and Python 3 to provide an integer-division operator that would behave consistently between Python 2 and Python 3. This means:

| context                                | `/` behavior   | `//` behavior |
---------------------------------------------------------------------------
| floating-point arguments, Python 2 & 3 | float division | int divison   |
---------------------------------------------------------------------------
| integer arguments, python 2            | int division   | int division  |
---------------------------------------------------------------------------
| integer arguments, python 3            | float division | int division  |

For more details, see this question: Division in Python 2.7. and 3.3

How to check visibility of software keyboard in Android?

NEW ANSWER added Jan 25th 2012

Since writing the below answer, someone clued me in to the existence of ViewTreeObserver and friends, APIs which have been lurking in the SDK since version 1.

Rather than requiring a custom Layout type, a much simpler solution is to give your activity's root view a known ID, say @+id/activityRoot, hook a GlobalLayoutListener into the ViewTreeObserver, and from there calculate the size diff between your activity's view root and the window size:

final View activityRootView = findViewById(R.id.activityRoot);
activityRootView.getViewTreeObserver().addOnGlobalLayoutListener(new OnGlobalLayoutListener() {
    @Override
    public void onGlobalLayout() {
        int heightDiff = activityRootView.getRootView().getHeight() - activityRootView.getHeight();
        if (heightDiff > dpToPx(this, 200)) { // if more than 200 dp, it's probably a keyboard...
            // ... do something here
        }
     }
});

Using a utility such as:

public static float dpToPx(Context context, float valueInDp) {
    DisplayMetrics metrics = context.getResources().getDisplayMetrics();
    return TypedValue.applyDimension(TypedValue.COMPLEX_UNIT_DIP, valueInDp, metrics);
}

Easy!

Note: Your application must set this flag in Android Manifest android:windowSoftInputMode="adjustResize" otherwise above solution will not work.

ORIGINAL ANSWER

Yes it's possible, but it's far harder than it ought to be.

If I need to care about when the keyboard appears and disappears (which is quite often) then what I do is customize my top-level layout class into one which overrides onMeasure(). The basic logic is that if the layout finds itself filling significantly less than the total area of the window, then a soft keyboard is probably showing.

import android.app.Activity;
import android.content.Context;
import android.graphics.Rect;
import android.util.AttributeSet;
import android.widget.LinearLayout;

/*
 * LinearLayoutThatDetectsSoftKeyboard - a variant of LinearLayout that can detect when 
 * the soft keyboard is shown and hidden (something Android can't tell you, weirdly). 
 */

public class LinearLayoutThatDetectsSoftKeyboard extends LinearLayout {

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

    public interface Listener {
        public void onSoftKeyboardShown(boolean isShowing);
    }
    private Listener listener;
    public void setListener(Listener listener) {
        this.listener = listener;
    }

    @Override
    protected void onMeasure(int widthMeasureSpec, int heightMeasureSpec) {
        int height = MeasureSpec.getSize(heightMeasureSpec);
        Activity activity = (Activity)getContext();
        Rect rect = new Rect();
        activity.getWindow().getDecorView().getWindowVisibleDisplayFrame(rect);
        int statusBarHeight = rect.top;
        int screenHeight = activity.getWindowManager().getDefaultDisplay().getHeight();
        int diff = (screenHeight - statusBarHeight) - height;
        if (listener != null) {
            listener.onSoftKeyboardShown(diff>128); // assume all soft keyboards are at least 128 pixels high
        }
        super.onMeasure(widthMeasureSpec, heightMeasureSpec);       
    }

    }

Then in your Activity class...

public class MyActivity extends Activity implements LinearLayoutThatDetectsSoftKeyboard.Listener {

    @Override
    public void onCreate(Bundle savedInstanceState) {
        super.onCreate(savedInstanceState);
        ...
        LinearLayoutThatDetectsSoftKeyboard mainLayout = (LinearLayoutThatDetectsSoftKeyboard)findViewById(R.id.main);
        mainLayout.setListener(this);
        ...
    }


    @Override
    public void onSoftKeyboardShown(boolean isShowing) {
        // do whatever you need to do here
    }

    ...
}

Cursor adapter and sqlite example

CursorAdapter Example with Sqlite

...
DatabaseHelper helper = new DatabaseHelper(this);
aListView = (ListView) findViewById(R.id.aListView);
Cursor c = helper.getAllContacts();
CustomAdapter adapter = new CustomAdapter(this, c);
aListView.setAdapter(adapter);
...

class CustomAdapter extends CursorAdapter {
    // CursorAdapter will handle all the moveToFirst(), getCount() logic for you :)

    public CustomAdapter(Context context, Cursor c) {
        super(context, c);
    }

    public void bindView(View view, Context context, Cursor cursor) {
        String id = cursor.getString(0);
        String name = cursor.getString(1);
        // Get all the values
        // Use it however you need to
        TextView textView = (TextView) view;
        textView.setText(name);
    }

    public View newView(Context context, Cursor cursor, ViewGroup parent) {
        // Inflate your view here.
        TextView view = new TextView(context);
        return view;
    }
}

private final class DatabaseHelper extends SQLiteOpenHelper {

    private static final String DATABASE_NAME = "db_name";
    private static final int DATABASE_VERSION = 1;
    private static final String CREATE_TABLE_TIMELINE = "CREATE TABLE IF NOT EXISTS table_name (_id INTEGER PRIMARY KEY AUTOINCREMENT, name varchar);";

    public DatabaseHelper(Context context) {
        super(context, DATABASE_NAME, null, DATABASE_VERSION);
    }

    @Override
    public void onCreate(SQLiteDatabase db) {
        db.execSQL(CREATE_TABLE_TIMELINE);
        db.execSQL("INSERT INTO ddd (name) VALUES ('One')");
        db.execSQL("INSERT INTO ddd (name) VALUES ('Two')");
        db.execSQL("INSERT INTO ddd (name) VALUES ('Three')");
    }

    @Override
    public void onUpgrade(SQLiteDatabase db, int oldVersion, int newVersion) {
    }

    public Cursor getAllContacts() {
        String selectQuery = "SELECT  * FROM table_name;
        SQLiteDatabase db = this.getReadableDatabase();
        Cursor cursor = db.rawQuery(selectQuery, null);
        return cursor;
    }
}

jquery remove "selected" attribute of option?

It's something in the way jQuery translates to IE8, not necessarily the browser itself.

I was able to work around by going old school and breaking out of jQuery for one line:

document.getElementById('myselect').selectedIndex = -1;

How to use a Java8 lambda to sort a stream in reverse order?

This can easily be done using Java 8 and the use of a reversed Comparator.

I have created a list of files from a directory, which I display unsorted, sorted and reverse sorted using a simple Comparator for the sort and then calling reversed() on it to get the reversed version of that Comparator.

See code below:

package test;

import java.io.File;
import java.util.Arrays;
import java.util.Comparator;
import java.util.Date;
import java.util.List;
import java.util.stream.Collectors;

public class SortTest {
    public static void main(String... args) {
        File directory = new File("C:/Media");
        File[] files = directory.listFiles();
        List<File> filesList = Arrays.asList(files);

        Comparator<File> comparator = Comparator.comparingLong(File::lastModified);
        Comparator<File> reverseComparator = comparator.reversed();

        List<File> forwardOrder = filesList.stream().sorted(comparator).collect(Collectors.toList());
        List<File> reverseOrder = filesList.stream().sorted(reverseComparator).collect(Collectors.toList());

        System.out.println("*** Unsorted ***");
        filesList.forEach(SortTest::processFile);

        System.out.println("*** Sort ***");
        forwardOrder.forEach(SortTest::processFile);

        System.out.println("*** Reverse Sort ***");
        reverseOrder.forEach(SortTest::processFile);
    }

    private static void processFile(File file) {
        try {
            if (file.isFile()) {
                System.out.println(file.getCanonicalPath() + " - " + new Date(file.lastModified()));
            }
        } catch (Exception e) {
            System.out.println(e.getMessage());
        }
    }
}

Convert base64 string to ArrayBuffer

Try this:

function _base64ToArrayBuffer(base64) {
    var binary_string = window.atob(base64);
    var len = binary_string.length;
    var bytes = new Uint8Array(len);
    for (var i = 0; i < len; i++) {
        bytes[i] = binary_string.charCodeAt(i);
    }
    return bytes.buffer;
}

Is String.Contains() faster than String.IndexOf()?

Tried it today on a 1.3 GB text file. Amongst others every line is checked for existence of a '@' char. 17.000.000 calls to Contains/IndexOf are made. Result: 12.5 sec for all Contains('@') calls, 2.5 sec for all IndexOf('@') calls. => IndexOf performs 5 times faster!! (.Net 4.8)

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

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

How to rename uploaded file before saving it into a directory?

The move_uploaded_file will return false if the file was not successfully moved you can put something into your code to alert you in a log if that happens, that should help you figure out why your having trouble renaming the file

How to round an average to 2 decimal places in PostgreSQL?

you can use the function below

 SELECT TRUNC(14.568,2);

the result will show :

14.56

you can also cast your variable to the desire type :

 SELECT TRUNC(YOUR_VAR::numeric,2)

How to make a div with no content have a width?

If you set display: to inline-block, block, flex, ..., on the element with no content, then

For min-width to take effect on a tag with no content, you only need to apply padding for either top or bot.

For min-height to take effect on a tag with no content, you only need to apply padding for left or right.

This example showcases it; here I only sat the padding-left for the min-width to take effect on an empty span tag

Capitalize first letter. MySQL

This should work nicely:

UPDATE tb_Company SET CompanyIndustry = 
CONCAT(UPPER(LEFT(CompanyIndustry, 1)), SUBSTRING(CompanyIndustry, 2))

How to cache data in a MVC application

I use two classes. First one the cache core object:

public class Cacher<TValue>
    where TValue : class
{
    #region Properties
    private Func<TValue> _init;
    public string Key { get; private set; }
    public TValue Value
    {
        get
        {
            var item = HttpRuntime.Cache.Get(Key) as TValue;
            if (item == null)
            {
                item = _init();
                HttpContext.Current.Cache.Insert(Key, item);
            }
            return item;
        }
    }
    #endregion

    #region Constructor
    public Cacher(string key, Func<TValue> init)
    {
        Key = key;
        _init = init;
    }
    #endregion

    #region Methods
    public void Refresh()
    {
        HttpRuntime.Cache.Remove(Key);
    }
    #endregion
}

Second one is list of cache objects:

public static class Caches
{
    static Caches()
    {
        Languages = new Cacher<IEnumerable<Language>>("Languages", () =>
                                                          {
                                                              using (var context = new WordsContext())
                                                              {
                                                                  return context.Languages.ToList();
                                                              }
                                                          });
    }
    public static Cacher<IEnumerable<Language>> Languages { get; private set; }
}

Unexpected end of file error

You did forget to include stdafx.h in your source (as I cannot see it your code). If you didn't, then make sure #include "stdafx.h" is the first line in your .cpp file, otherwise you will see the same error even if you've included "stdafx.h" in your source file (but not in the very beginning of the file).

How to make the tab character 4 spaces instead of 8 spaces in nano?

In nano 2.2.6 the line in ~/.nanorc to do this seems to be

set tabsize 4

Setting tabspace gave me the error: 'Unknown flag "tabspace"'

Storage permission error in Marshmallow

Unless there is a definite requirement of writing on external storage, you can always choose to save files in app directory. In my case I had to save files and after wasting 2 to 3 days I found out if I change the storage path from

Environment.getExternalStorageDirectory()

to

getApplicationContext().getFilesDir().getPath() //which returns the internal app files directory path

it works like charm on all the devices. This is because for writing on External storage you need extra permissions but writing in internal app directory is simple.

java comparator, how to sort by integer?

public class DogAgeComparator implements Comparator<Dog> {
    public int compare(Dog o1, Dog o2) {
        return Integer.compare(o1.getAge(), o2.getId());
    }
}

No tests found for given includes Error, when running Parameterized Unit test in Android Studio

I made the mistake of defining my test like this

class MyTest {
    @Test
    fun `test name`() = runBlocking {


        // something here that isn't Unit
    }
}

That resulted in runBlocking returning something, which meant that the method wasn't void and junit didn't recognize it as a test. That was pretty lame. I explicitly supply a type parameter now to run blocking. It won't stop the pain or get me my two hours back but it will make sure this doesn't happen again.

class MyTest {
    @Test
    fun `test name`() = runBlocking<Unit> { // Specify Unit


        // something here that isn't Unit
    }
}

C++ obtaining milliseconds time on Linux -- clock() doesn't seem to work properly

This should work...tested on a mac...

#include <stdio.h>
#include <sys/time.h>

int main() {
        struct timeval tv;
        struct timezone tz;
        struct tm *tm;
        gettimeofday(&tv,&tz);
        tm=localtime(&tv.tv_sec);
        printf("StartTime: %d:%02d:%02d %d \n", tm->tm_hour, tm->tm_min, tm->tm_sec, tv.tv_usec);
}

Yeah...run it twice and subtract...

PreparedStatement with Statement.RETURN_GENERATED_KEYS

private void alarmEventInsert(DriveDetail driveDetail, String vehicleRegNo, int organizationId) {

    final String ALARM_EVENT_INS_SQL = "INSERT INTO alarm_event (event_code,param1,param2,org_id,created_time) VALUES (?,?,?,?,?)";
    CachedConnection conn = JDatabaseManager.getConnection();
    PreparedStatement ps = null;
    ResultSet generatedKeys = null;
    try {
        ps = conn.prepareStatement(ALARM_EVENT_INS_SQL, ps.RETURN_GENERATED_KEYS);
        ps.setInt(1, driveDetail.getEventCode());
        ps.setString(2, vehicleRegNo);
        ps.setString(3, null);
        ps.setInt(4, organizationId);
        ps.setString(5, driveDetail.getCreateTime());
        ps.execute();
        generatedKeys = ps.getGeneratedKeys();
        if (generatedKeys.next()) {
            driveDetail.setStopDuration(generatedKeys.getInt(1));
        }
    } catch (SQLException e) {
        e.printStackTrace();
        logger.error("Error inserting into alarm_event : {}", e
                .getMessage());
        logger.info(ps.toString());
    } finally {
        if (ps != null) {
            try {

                if (ps != null)
                    ps.close();
            } catch (SQLException e) {
                logger.error("Error closing prepared statements : {}", e
                        .getMessage());
            }
        }
    }
    JDatabaseManager.freeConnection(conn);
}

add elements to object array

I know this is old, but came across it looking for a simpler way, and this is how i do it, just create a new list of the same object and add it to the one you want to use e.g.

Subject[] subjectsList = {new Subject1{....}, new Subject2{....}, new Subject3{....}} 
univStudent.subjects = subjectsList ;

Add one day to date in javascript

Just for the sake of adding functions to the Date prototype:

In a mutable fashion / style:

Date.prototype.addDays = function(n) {
   this.setDate(this.getDate() + n);
};

// Can call it tomorrow if you want
Date.prototype.nextDay = function() {
   this.addDays(1);
};

Date.prototype.addMonths = function(n) {
   this.setMonth(this.getMonth() + n);
};

Date.prototype.addYears = function(n) {
   this.setFullYear(this.getFullYear() + n);
}

// etc...

var currentDate = new Date();
currentDate.nextDay();

Git blame -- prior commits?

You might want to check out:

git gui blame <filename>

Gives you a nice graphical display of changes like "git blame" but with clickable links per line, to move into earlier commits. Hover over the links to get a popup with commit details. Not my credits... found it here:

http://zsoltfabok.com/blog/2012/02/git-blame-line-history/

git gui is a graphical Tcl/Tc interface to git. Without any other params it starts a pretty simple but useful graphical app for committing files, hunks or even single lines and other similar commands like amend, revert, push... It's part of the git stock suite. On windows it is included in the installer. On debian - I don't know about other *nix systems - it has to be installed separately:

apt-get install git-gui

From the docs:

https://git-scm.com/docs/git-gui

DESCRIPTION

A Tcl/Tk based graphical user interface to Git. git gui focuses on allowing users to make changes to their repository by making new commits, amending existing ones, creating branches, performing local merges, and fetching/pushing to remote repositories.

Unlike gitk, git gui focuses on commit generation and single file annotation and does not show project history. It does however supply menu actions to start a gitk session from within git gui.

git gui is known to work on all popular UNIX systems, Mac OS X, and Windows (under both Cygwin and MSYS). To the extent possible OS specific user interface guidelines are followed, making git gui a fairly native interface for users.

COMMANDS

blame

Start a blame viewer on the specified file on the given version (or working directory if not specified).

browser

Start a tree browser showing all files in the specified commit. Files selected through the browser are opened in the blame viewer.

citool

Start git gui and arrange to make exactly one commit before exiting and returning to the shell. The interface is limited to only commit actions, slightly reducing the application’s startup time and simplifying the menubar.

version

Display the currently running version of git gui.

ERROR in The Angular Compiler requires TypeScript >=3.1.1 and <3.2.0 but 3.2.1 was found instead

I also faced similar issues when tried to do ng serve. I was able to resolve it as below.
Note:

C:\Windows\system32> is on windows command prompt
C:\apps\workspace\testProj>  is on VS code Terminal (can also be doable in another command prompt)

Following are the steps which I used to resolve this.

Step1. Verify the cli version installed on command prompt (will be Angular CLI global version)

C:\Windows\system32>ng --version

Angular CLI: 8.3.13

If cli was installed earlier, it shows the global cli version.

If cli was not installed, we may get the error
ng is not recognized as an internal or external command

a. (Optional Step) Install Angular CLI global version

C:\Windows\system32>npm install -g @angular/cli
C:\Windows\system32>npm install -g @angular-cli/latest

b. Check version again

C:\Windows\system32>ng --version
Angular CLI: 8.3.13

Step2. Verify the local cli version installed on your angular project(VS code ide or command prompt cd'd to your project project)

C:\apps\workspace\testProj>ng --version
Angular CLI: 7.3.8

Note: Clearly versions are not in sync. Do the following in your angular project

C:\apps\workspace\testProj>ng update @angular/cli        -> important to sync with global cli version

Note: If upgrade donot work using above command (ref: How to upgrade Angular CLI to the latest version) On command prompt, uninstall global angular cli, clean the cache and reinstall the cli

C:\Windows\system32>npm uninstall -g angular-cli
C:\Windows\system32>npm cache clean or npm cache verify #(if npm > 5)
C:\Windows\system32>npm install -g @angular/cli@latest

Now update your local project version, because cli version of your local project is having higher priority than global one when you try to execute your project.

C:\apps\workspace\testProj>rm -rf node_modules
C:\apps\workspace\testProj>npm uninstall --save-dev angular-cli
C:\apps\workspace\testProj>npm install --save-dev @angular/cli@latest
C:\apps\workspace\testProj>npm install
C:\apps\workspace\testProj>ng update @angular/cli

Step3. Verify if local project cli version now in sync with global one

C:\Windows\system32>ng --version
Angular CLI: 8.3.13

C:\apps\workspace\testProj>ng --version
Angular CLI: 8.3.13

Step4.. Revalidate on the project

C:\apps\workspace\testProj>ng serve

Should work now

Using a bitmask in C#

Easy Way:

[Flags]
public enum MyFlags {
    None = 0,
    Susan = 1,
    Alice = 2,
    Bob = 4,
    Eve = 8
}

To set the flags use logical "or" operator |:

MyFlags f = new MyFlags();
f = MyFlags.Alice | MyFlags.Bob;

And to check if a flag is included use HasFlag:

if(f.HasFlag(MyFlags.Alice)) { /* true */}
if(f.HasFlag(MyFlags.Eve)) { /* false */}

CSS: how do I create a gap between rows in a table?

Simply you can use padding-top and padding-bottom on a td element.

Unit can anything from this list:

enter image description here

Demo Code:

_x000D_
_x000D_
td_x000D_
{_x000D_
  padding-top: 10px;_x000D_
  padding-bottom: 10px;_x000D_
}
_x000D_
<table>_x000D_
  <tr>_x000D_
    <th>Firstname</th>_x000D_
    <th>Lastname</th>_x000D_
  </tr>_x000D_
  <tr>_x000D_
    <td>Peter</td>_x000D_
    <td>Griffin</td>_x000D_
  </tr>_x000D_
  <tr>_x000D_
    <td>Lois</td>_x000D_
    <td>Griffin</td>_x000D_
  </tr>_x000D_
</table>
_x000D_
_x000D_
_x000D_

How to trigger SIGUSR1 and SIGUSR2?

They are signals that application developers use. The kernel shouldn't ever send these to a process. You can send them using kill(2) or using the utility kill(1).

If you intend to use signals for synchronization you might want to check real-time signals (there's more of them, they are queued, their delivery order is guaranteed etc).

Sum values from an array of key-value pairs in JavaScript

I would use reduce

var myData = new Array(['2013-01-22', 0], ['2013-01-29', 0], ['2013-02-05', 0], ['2013-02-12', 0], ['2013-02-19', 0], ['2013-02-26', 0], ['2013-03-05', 0], ['2013-03-12', 0], ['2013-03-19', 0], ['2013-03-26', 0], ['2013-04-02', 21], ['2013-04-09', 2]);

var sum = myData.reduce(function(a, b) {
    return a + b[1];
}, 0);

$("#result").text(sum);

Available on jsfiddle

Convert a 1D array to a 2D array in numpy

some_array.shape = (1,)+some_array.shape

or get a new one

another_array = numpy.reshape(some_array, (1,)+some_array.shape)

This will make dimensions +1, equals to adding a bracket on the outermost

Configure cron job to run every 15 minutes on Jenkins

Your syntax is slightly wrong. Say:

*/15 * * * * command
  |
  |--> `*/15` would imply every 15 minutes.

* indicates that the cron expression matches for all values of the field.

/ describes increments of ranges.

How to open local file on Jupyter?

I do not know if it's what you were looking for, but it sounds to me something like this.

This is for linux (ubuntu) but maybe it also works on mac:

If the file is a pdf called 'book.pdf' and is located in your downloads, then

import subprocess

path='/home/user/Downloads/book.pdf'
subprocess.call(['evince', path])

where evince is the program that open pdfs in ubuntu

Insert data to MySql DB and display if insertion is success or failure

if (mysql_query("INSERT INTO PEOPLE (NAME ) VALUES ('COLE')")or die(mysql_error())) {
  echo 'Success';
} else {
  echo 'Fail';
} 

Although since you have or die(mysql_error()) it will show the mysql_error() on the screen when it fails. You should probably remove that if it isnt the desired result

Implementing a Custom Error page on an ASP.Net website

There are 2 ways to configure custom error pages for ASP.NET sites:

  1. Internet Information Services (IIS) Manager (the GUI)
  2. web.config file

This article explains how to do each:

The reason your error.aspx page is not displaying might be because you have an error in your web.config. Try this instead:

<configuration>
   <system.web>
      <customErrors defaultRedirect="error.aspx" mode="RemoteOnly">
         <error statusCode="404" redirect="error.aspx"/>
      </customErrors>
   </system.web>
</configuration>

You might need to make sure that Error Pages in IIS Manager - Feature Delegation is set to Read/Write:

IIS Manager: Feature Delegation panel

Also, this answer may help you configure the web.config file:

Java getting the Enum name given the Enum Value

You should replace your getEnumNameForValue by a call to the name() method.

What is the equivalent of Java static methods in Kotlin?

There is no static keyword in kotlin. kotlin docs recommends to use package-level functions if u want to follow DRY. Create a file with .kt extension and put your method in it.

package p
    fun m(){
    //fun body
    }

after compilation m will have a signature of public static final void

and

import p.m

?

Double precision - decimal places

An IEEE double has 53 significant bits (that's the value of DBL_MANT_DIG in <cfloat>). That's approximately 15.95 decimal digits (log10(253)); the implementation sets DBL_DIG to 15, not 16, because it has to round down. So you have nearly an extra decimal digit of precision (beyond what's implied by DBL_DIG==15) because of that.

The nextafter() function computes the nearest representable number to a given number; it can be used to show just how precise a given number is.

This program:

#include <cstdio>
#include <cfloat>
#include <cmath>

int main() {
    double x = 1.0/7.0;
    printf("FLT_RADIX = %d\n", FLT_RADIX);
    printf("DBL_DIG = %d\n", DBL_DIG);
    printf("DBL_MANT_DIG = %d\n", DBL_MANT_DIG);
    printf("%.17g\n%.17g\n%.17g\n", nextafter(x, 0.0), x, nextafter(x, 1.0));
}

gives me this output on my system:

FLT_RADIX = 2
DBL_DIG = 15
DBL_MANT_DIG = 53
0.14285714285714282
0.14285714285714285
0.14285714285714288

(You can replace %.17g by, say, %.64g to see more digits, none of which are significant.)

As you can see, the last displayed decimal digit changes by 3 with each consecutive value. The fact that the last displayed digit of 1.0/7.0 (5) happens to match the mathematical value is largely coincidental; it was a lucky guess. And the correct rounded digit is 6, not 5. Replacing 1.0/7.0 by 1.0/3.0 gives this output:

FLT_RADIX = 2
DBL_DIG = 15
DBL_MANT_DIG = 53
0.33333333333333326
0.33333333333333331
0.33333333333333337

which shows about 16 decimal digits of precision, as you'd expect.

How do I find the difference between two values without knowing which is larger?

use this function.

its the same convention you wanted. using the simple abs feature of python.

also - sometimes the answers are so simple we miss them, its okay :)

>>> def distance(x,y):
    return abs(x-y)

How do I print the key-value pairs of a dictionary in python

A little intro to dictionary

d={'a':'apple','b':'ball'}
d.keys()  # displays all keys in list
['a','b']
d.values() # displays your values in list
['apple','ball']
d.items() # displays your pair tuple of key and value
[('a','apple'),('b','ball')

Print keys,values method one

for x in d.keys():
    print x +" => " + d[x]

Another method

for key,value in d.items():
    print key + " => " + value

You can get keys using iter

>>> list(iter(d))
['a', 'b']

You can get value of key of dictionary using get(key, [value]):

d.get('a')
'apple'

If key is not present in dictionary,when default value given, will return value.

d.get('c', 'Cat')
'Cat'

What is Android keystore file, and what is it used for?

The whole idea of a keytool is to sign your apk with a unique identifier indicating the source of that apk. A keystore file (from what I understand) is used for debuging so your apk has the functionality of a keytool without signing your apk for production. So yes, for debugging purposes you should be able to sign multiple apk's with a single keystore. But understand that, upon pushing to production you'll need unique keytools as identifiers for each apk you create.

What is your favorite C programming trick?

Using a stupid macro trick to make record definitions easier to maintain.

#define COLUMNS(S,E) [(E) - (S) + 1]

typedef struct
{
    char studentNumber COLUMNS( 1,  9);
    char firstName     COLUMNS(10, 30);
    char lastName      COLUMNS(31, 51);

} StudentRecord;

Passing a variable from one php include file to another: global vs. not

Here is a pitfall to avoid. In case you need to access your variable $name within a function, you need to say "global $name;" at the beginning of that function. You need to repeat this for each function in the same file.

include('front.inc');
global $name;

function foo() {
  echo $name;
}

function bar() {
  echo $name;
}

foo();
bar();

will only show errors. The correct way to do that would be:

include('front.inc');

function foo() {
  global $name;
  echo $name;
}

function bar() {
  global $name;
  echo $name;
}

foo();
bar();

How to hide element using Twitter Bootstrap and show it using jQuery?

Initiate the element with as such:

<div id='foo' style="display: none"></div>

And then, use the event you want to show it, as such:

$('#foo').show();

The simplest way to go I believe.

How do I remove all HTML tags from a string without knowing which tags are in it?

You can parse the string using Html Agility pack and get the InnerText.

    HtmlDocument htmlDoc = new HtmlDocument();
    htmlDoc.LoadHtml(@"<b> Hulk Hogan's Celebrity Championship Wrestling &nbsp;&nbsp;&nbsp;<font color=\"#228b22\">[Proj # 206010]</font></b>&nbsp;&nbsp;&nbsp; (Reality Series, &nbsp;)");
    string result = htmlDoc.DocumentNode.InnerText;

how to use Spring Boot profiles

You can specify properties according profiles in one application.properties(yml) like here. Then mvn clean spring-boot:run -Dspring.profiles.active=dev should run it correct. It works for me

Move UIView up when the keyboard appears in iOS

Based on theDunc's answer but written in Swift with Autolayout.

@IBOutlet weak var bottomConstraint: NSLayoutConstraint! // connect the bottom of the view you want to move to the bottom layout guide

override func viewWillAppear(animated: Bool) {
    super.viewWillAppear(animated)
    NSNotificationCenter.defaultCenter().addObserver(self,
                                                     selector: #selector(ConversationViewController.keyboardWillShow(_:)),
                                                     name: UIKeyboardWillShowNotification,
                                                     object: nil)

    NSNotificationCenter.defaultCenter().addObserver(self,
                                                     selector: #selector(ConversationViewController.keyboardWillHide(_:)),
                                                     name: UIKeyboardWillHideNotification,
                                                     object: nil)
}

override func viewWillDisappear(animated: Bool) {
    NSNotificationCenter.defaultCenter().removeObserver(self, name: UIKeyboardWillShowNotification, object: nil)
    NSNotificationCenter.defaultCenter().removeObserver(self, name: UIKeyboardWillHideNotification, object: nil)
    super.viewWillDisappear(animated)
}

// MARK: - Keyboard events

func keyboardWillShow(notification: NSNotification) {
    if let userInfo = notification.userInfo,
        keyboardFrame = userInfo[UIKeyboardFrameBeginUserInfoKey]
    {
        let keyboardSize = keyboardFrame.CGRectValue().size
        self.bottomConstraint.constant = keyboardSize.height
        UIView.animateWithDuration(0.3) {
            self.view.layoutIfNeeded()
        }
    }
}

func keyboardWillHide(notification: NSNotification) {
    self.bottomConstraint.constant = 0
    UIView.animateWithDuration(0.3) {
        self.view.layoutIfNeeded()
    }
}

Why does Google prepend while(1); to their JSON responses?

That would be to make it difficult for a third-party to insert the JSON response into an HTML document with the <script> tag. Remember that the <script> tag is exempt from the Same Origin Policy.

iOS Remote Debugging

I am using remotedebug-ios-webkit-adapter, works well for me with IOS and debugger open in Chrome on Windows 10.

Will be glad if it helps some one Link

How to drop a unique constraint from table column?

You can use following script :

Declare @Cons_Name NVARCHAR(100)
Declare @Str NVARCHAR(500)

SELECT @Cons_Name=name
FROM sys.objects
WHERE type='UQ' AND OBJECT_NAME(parent_object_id) = N'TableName';

---- Delete the unique constraint.
SET @Str='ALTER TABLE TableName DROP CONSTRAINT ' + @Cons_Name;
Exec (@Str)
GO

C pointer to array/array of pointers disambiguation

int* arr[8]; // An array of int pointers.
int (*arr)[8]; // A pointer to an array of integers

The third one is same as the first.

The general rule is operator precedence. It can get even much more complex as function pointers come into the picture.

Creating multiple log files of different content with log4j

Perhaps something like this?

<!DOCTYPE log4j:configuration SYSTEM "log4j.dtd">
<log4j:configuration xmlns:log4j="http://jakarta.apache.org/log4j/">
 <!-- general application log -->
 <appender name="MainLogFile" class="org.apache.log4j.FileAppender">
  <param name="File" value="server.log" />
  <param name="Threshold" value="INFO" />
  <layout class="org.apache.log4j.PatternLayout">
   <param name="ConversionPattern" value="%-5p %t [%-40.40c] %x - %m%n"/>
  </layout>
 </appender> 
 <!-- additional fooSystem logging -->
 <appender name="FooLogFile" class="org.apache.log4j.FileAppender">
  <param name="File" value="foo.log" />
  <layout class="org.apache.log4j.PatternLayout">
   <param name="ConversionPattern" value="%-5p %t [%-40.40c] %x - %m%n"/>
  </layout>
 </appender>
 <!-- foo logging -->
 <logger name="com.example.foo">
  <level value="DEBUG"/>
  <appender-ref ref="FooLogFile"/>
 </logger>
 <!-- default logging -->
 <root>
  <level value="INFO"/>
  <appender-ref ref="MainLogFile"/>
 </root>
</log4j:configuration>

Thus, all info messages are written to server.log; by contrast, foo.log contains only com.example.foo messages, including debug-level messages.

Position absolute and overflow hidden

You just make divs like this:

<div style="width:100px; height: 100px; border:1px solid; overflow:hidden; ">
    <br/>
    <div style="position:inherit; width: 200px; height:200px; background:yellow;">
        <br/>
        <div style="position:absolute; width: 500px; height:50px; background:Pink; z-index: 99;">
            <br/>
        </div>
    </div>
</div>

I hope this code will help you :)

Error 1920 service failed to start. Verify that you have sufficient privileges to start system services

I had this issue while testing software. Drivers were not signed.

Tip for me was: in cmd line: (administrator) bcdedit /set TESTSIGNING ON and reboot the machine (shutdown -r -t 5)

How can I restart a Java application?

Windows

public void restartApp(){

    // This launches a new instance of application dirctly, 
    // remember to add some sleep to the start of the cmd file to make sure current instance is
    // completely terminated, otherwise 2 instances of the application can overlap causing strange
    // things:)

    new ProcessBuilder("cmd","/c start /min c:/path/to/script/that/launches/my/application.cmd ^& exit").start();
    System.exit(0);
}

/min to start script in minimized window

^& exit to close cmd window after finish

a sample cmd script could be

@echo off
rem add some sleep (e.g. 10 seconds) to allow the preceding application instance to release any open resources (like ports) and exit gracefully, otherwise the new instance could fail to start
sleep 10   
set path=C:\someFolder\application_lib\libs;%path%
java -jar application.jar

sleep 10 sleep for 10 seconds

Installing OpenCV on Windows 7 for Python 2.7

I have posted a very simple method to install OpenCV 2.4 for Python in Windows here : Install OpenCV in Windows for Python

It is just as simple as copy and paste. Hope it will be useful for future viewers.

  1. Download Python, Numpy, OpenCV from their official sites.

  2. Extract OpenCV (will be extracted to a folder opencv)

  3. Copy ..\opencv\build\python\x86\2.7\cv2.pyd

  4. Paste it in C:\Python27\Lib\site-packages

  5. Open Python IDLE or terminal, and type

    >>> import cv2
    

If no errors shown, it is OK.

UPDATE (Thanks to dana for this info):

If you are using the VideoCapture feature, you must copy opencv_ffmpeg.dll into your path as well. See: https://stackoverflow.com/a/11703998/1134940

How to use a calculated column to calculate another column in the same view

If you want to refer to calculated column on the "same query level" then you could use CROSS APPLY(Oracle 12c):

--Sample data:
CREATE TABLE tab(ColumnA NUMBER(10,2),ColumnB NUMBER(10,2),ColumnC NUMBER(10,2));

INSERT INTO tab(ColumnA, ColumnB, ColumnC) VALUES (2, 10, 2);
INSERT INTO tab(ColumnA, ColumnB, ColumnC) VALUES (3, 15, 6);
INSERT INTO tab(ColumnA, ColumnB, ColumnC) VALUES (7, 14, 3);
COMMIT;

Query:

SELECT
  ColumnA,
  ColumnB,
  sub.calccolumn1,
  sub.calccolumn1 / ColumnC AS calccolumn2
FROM tab t
CROSS APPLY (SELECT t.ColumnA + t.ColumnB AS calccolumn1 FROM dual) sub;

DBFiddle Demo


Please note that expression from CROSS APPLY/OUTER APPLY is available in other clauses too:

SELECT
  ColumnA,
  ColumnB,
  sub.calccolumn1,
  sub.calccolumn1 / ColumnC AS calccolumn2
FROM tab t
CROSS APPLY (SELECT t.ColumnA + t.ColumnB AS calccolumn1 FROM dual) sub
WHERE sub.calccolumn1 = 12;
-- GROUP BY ...
-- ORDER BY ...;

This approach allows to avoid wrapping entire query with outerquery or copy/paste same expression in multiple places(with complex one it could be hard to maintain).

Related article: The SQL Language’s Most Missing Feature

Remove trailing zeros from decimal in SQL Server

Try this :

SELECT REPLACE(TRIM(REPLACE(20.5500, "0", " ")), " ", "0")

Gives 20.55

Bash script to run php script

#!/usr/bin/env bash
PHP=`which php`
$PHP /path/to/php/file.php

How to remove a character at the end of each line in unix

This Perl code removes commas at the end of the line:

perl -pe 's/,$//' file > file.nocomma

This variation still works if there is whitespace after the comma:

perl -lpe 's/,\s*$//' file > file.nocomma

This variation edits the file in-place:

perl -i -lpe 's/,\s*$//' file

This variation edits the file in-place, and makes a backup file.bak:

perl -i.bak -lpe 's/,\s*$//' file

How to make a vertical line in HTML

I used a combination of the "hr" code suggested, and here's what my code looks like:

<hr style="width:0.5px; height:500px; position: absolute; left: 315px;"/>

I simply changed the value of the "left" pixel value to position it. (I used the vertical line to line-up content on my webpage, and then I removed it.)

LPCSTR, LPCTSTR and LPTSTR

Quick and dirty:

LP == Long Pointer. Just think pointer or char*

C = Const, in this case, I think they mean the character string is a const, not the pointer being const.

STR is string

the T is for a wide character or char (TCHAR) depending on compile options.

optional parameters in SQL Server stored proc?

You can declare like this

CREATE PROCEDURE MyProcName
    @Parameter1 INT = 1,
    @Parameter2 VARCHAR (100) = 'StringValue',
    @Parameter3 VARCHAR (100) = NULL
AS

/* check for the NULL / default value (indicating nothing was passed */
if (@Parameter3 IS NULL)
BEGIN
    /* whatever code you desire for a missing parameter*/
    INSERT INTO ........
END

/* and use it in the query as so*/
SELECT *
FROM Table
WHERE Column = @Parameter

Apache is downloading php files instead of displaying them

If Your .htaccess have anything like this

AddType application/x-httpd-ea-php56 .php .php5 .phtm .html .htm

Run JavaScript code on window close or page refresh?

Ok, I found a working solution for this, it consists of using the beforeunload event and then making the handler return null. This executes the wanted code without a confirmation box popping-up. It goes something like this:

window.onbeforeunload = closingCode;
function closingCode(){
   // do something...
   return null;
}

Is it possible to view RabbitMQ message contents directly from the command line?

I wrote rabbitmq-dump-queue which allows dumping messages from a RabbitMQ queue to local files and requeuing the messages in their original order.

Example usage (to dump the first 50 messages of queue incoming_1):

rabbitmq-dump-queue -url="amqp://user:[email protected]:5672/" -queue=incoming_1 -max-messages=50 -output-dir=/tmp

Jupyter notebook not running code. Stuck on In [*]

If you have ad block installed in your browser, just switch it off and then stop the kernel and start again. now the code will execute

Java random number with given length

Generate a number in the range from 100000 to 999999.

// pseudo code
int n = 100000 + random_float() * 900000;

For more details see the documentation for Random

Using sudo with Python script

I know it is always preferred not to hardcode the sudo password in the script. However, for some reason, if you have no permission to modify /etc/sudoers or change file owner, Pexpect is a feasible alternative.

Here is a Python function sudo_exec for your reference:

import platform, os, logging
import subprocess, pexpect

log = logging.getLogger(__name__)

def sudo_exec(cmdline, passwd):
    osname = platform.system()
    if osname == 'Linux':
        prompt = r'\[sudo\] password for %s: ' % os.environ['USER']
    elif osname == 'Darwin':
        prompt = 'Password:'
    else:
        assert False, osname

    child = pexpect.spawn(cmdline)
    idx = child.expect([prompt, pexpect.EOF], 3)
    if idx == 0: # if prompted for the sudo password
        log.debug('sudo password was asked.')
        child.sendline(passwd)
        child.expect(pexpect.EOF)
return child.before

Shell Script Syntax Error: Unexpected End of File

Unrelated to the OP's problem, but my issue was that I'm a noob shell scripter. All the other languages I've used require parentheses to invoke methods, whereas shell doesn't seem to like that.

function do_something() {
  # do stuff here
}

# bad
do_something()

# works
do_something

@Autowired and static method

Use AppContext. Make sure you create a bean in your context file.

private final static Foo foo = AppContext.getApplicationContext().getBean(Foo.class);

public static void randomMethod() {
     foo.doStuff();
}

What's the meaning of System.out.println in Java?

Check following link:

http://download.oracle.com/javase/1.5.0/docs/api/java/lang/System.html

You will clearly see that:

System is a class in the java.lang package.

out is a static member of the System class, and is an instance of java.io.PrintStream.

println is a method of java.io.PrintStream. This method is overloaded to print message to output destination, which is typically a console or file.

Pass C# ASP.NET array to Javascript array

Simple

The array of integers is quite simple to pass. However this solution works for more complex data as well. In your model:

public int[] Numbers => new int[5];

In your view:

numbers = @(new HtmlString(JsonSerializer.Serialize(Model.Numbers)))

Optional

A tip for passing strings. You may want JSON encoder to not escape some symbols in your strings. In this example I want raw unescaped cyrillic letters. In your view:

strings = @(
new HtmlString(
    JsonSerializer.Serialize(Model.Strings, new JsonSerializerOptions
    {
        Encoder = JavaScriptEncoder.Create(
            UnicodeRanges.BasicLatin,
            UnicodeRanges.Cyrillic)
    })))

Visual Studio Code how to resolve merge conflicts with git?

With VSCode you can find the merge conflicts easily with the following UI. enter image description here

(if you do not have the topbar, set "editor.codeLens": true in User Preferences)

It indicates the current change that you have and incoming change from the server. This makes it easy to resolve the conflicts - just press the buttons above <<<< HEAD.

If you have multiple changes and want to apply all of them at once - open command palette (View -> Command Palette) and start typing merge - multiple options will appear including Merge Conflict: Accept Incoming, etc.

Android Saving created bitmap to directory on sd card

You can also try this.

File file = new File(strDirectoy,imgname);
OutputStream fOut = new FileOutputStream(file);
bitmap.compress(Bitmap.CompressFormat.JPEG, 85, fOut);
fOut.flush();
fOut.close();
MediaStore.Images.Media.insertImage(getContentResolver(),file.getAbsolutePath(),file.getName(),file.getName());

Python: tf-idf-cosine: to find document similarity

I know its an old post. but I tried the http://scikit-learn.sourceforge.net/stable/ package. here is my code to find the cosine similarity. The question was how will you calculate the cosine similarity with this package and here is my code for that

from sklearn.feature_extraction.text import CountVectorizer
from sklearn.metrics.pairwise import cosine_similarity
from sklearn.feature_extraction.text import TfidfVectorizer

f = open("/root/Myfolder/scoringDocuments/doc1")
doc1 = str.decode(f.read(), "UTF-8", "ignore")
f = open("/root/Myfolder/scoringDocuments/doc2")
doc2 = str.decode(f.read(), "UTF-8", "ignore")
f = open("/root/Myfolder/scoringDocuments/doc3")
doc3 = str.decode(f.read(), "UTF-8", "ignore")

train_set = ["president of India",doc1, doc2, doc3]

tfidf_vectorizer = TfidfVectorizer()
tfidf_matrix_train = tfidf_vectorizer.fit_transform(train_set)  #finds the tfidf score with normalization
print "cosine scores ==> ",cosine_similarity(tfidf_matrix_train[0:1], tfidf_matrix_train)  #here the first element of tfidf_matrix_train is matched with other three elements

Here suppose the query is the first element of train_set and doc1,doc2 and doc3 are the documents which I want to rank with the help of cosine similarity. then I can use this code.

Also the tutorials provided in the question was very useful. Here are all the parts for it part-I,part-II,part-III

the output will be as follows :

[[ 1.          0.07102631  0.02731343  0.06348799]]

here 1 represents that query is matched with itself and the other three are the scores for matching the query with the respective documents.

SQL Server - find nth occurrence in a string

Try this

CREATE FUNCTION [dbo].[CHARINDEX2] (
    @expressionToFind VARCHAR(MAX),
    @expressionToSearch VARCHAR(MAX),
    @occurrenceIndex INT,
    @startLocation INT = 0
)
RETURNS INT
AS BEGIN

IF @occurrenceIndex < 1 BEGIN
    RETURN CAST('The argument @occurrenceIndex must be a positive integer.' AS INT)
END

IF @startLocation < 0 BEGIN
    RETURN CAST('The argument @startLocation must be a non negative integer.' AS INT)
END

DECLARE @returnIndex INT

SET @returnIndex = CHARINDEX(@expressionToFind, @expressionToSearch, @startLocation)

IF (@occurrenceIndex = 1) BEGIN
    RETURN @returnIndex
END

DECLARE @target_length INT
SET @target_length = LEN(@expressionToFind)
SET @occurrenceIndex += -1

WHILE (@occurrenceIndex > 0 AND @returnIndex > 0) BEGIN
    SET @returnIndex = CHARINDEX(@expressionToFind, @expressionToSearch, @returnIndex + @target_length);
    SET @occurrenceIndex += -1
END

RETURN @returnIndex

END
GO

Tool for sending multipart/form-data request

The usual error is one tries to put Content-Type: {multipart/form-data} into the header of the post request. That will fail, it is best to let Postman do it for you. For example:

Suggestion To Load Via Postman Body Part

Fails If In Header Common Error

Works should remove content type from the Header

How can I make a CSS table fit the screen width?

CSS:

table { 
    table-layout:fixed;
}

Update with CSS from the comments:

td { 
    overflow: hidden; 
    text-overflow: ellipsis; 
    word-wrap: break-word;
}

For mobile phones I leave the table width but assign an additional CSS class to the table to enable horizontal scrolling (table will not go over the mobile screen anymore):

@media only screen and (max-width: 480px) {
    /* horizontal scrollbar for tables if mobile screen */
    .tablemobile {
        overflow-x: auto;
        display: block;
    }
}

Sufficient enough.

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

You can use the iprof library:

https://gitlab.com/Neurochrom/iprof

https://github.com/Neurochrom/iprof

It's cross-platform and allows you not to measure performance of your application also in real-time. You can even couple it with a live graph. Full disclaimer: I am the author.

jQuery object equality

It is, generally speaking, a bad idea to compare $(foo) with $(foo) as that is functionally equivalent to the following comparison:

<html>
<head>
<script language='javascript'>
    function foo(bar) {
        return ({ "object": bar });
    }

    $ = foo;

    if ( $("a") == $("a") ) {
        alert ("JS engine screw-up");
    }
    else {
        alert ("Expected result");
    }

</script>

</head>
</html>

Of course you would never expect "JS engine screw-up". I use "$" just to make it clear what jQuery is doing.

Whenever you call $("#foo") you are actually doing a jQuery("#foo") which returns a new object. So comparing them and expecting same object is not correct.

However what you CAN do may be is something like:

<html>
<head>
<script language='javascript'>
    function foo(bar) {
        return ({ "object": bar });
    }

    $ = foo;

    if ( $("a").object == $("a").object ) {
        alert ("Yep! Now it works");
    }
    else {
        alert ("This should not happen");
    }

</script>

</head>
</html>

So really you should perhaps compare the ID elements of the jQuery objects in your real program so something like

... 
$(someIdSelector).attr("id") == $(someOtherIdSelector).attr("id")

is more appropriate.

why does DateTime.ToString("dd/MM/yyyy") give me dd-MM-yyyy?

Dumb question/answer perhaps, but have you tried dd/MM/yyyy? Note the capitalization.

mm is for minutes with a leading zero. So I doubt that's what you want.

This may be helpful: http://www.geekzilla.co.uk/View00FF7904-B510-468C-A2C8-F859AA20581F.htm

Python: Converting string into decimal number

You will need to use strip() because of the extra bits in the strings.

A2 = [float(x.strip('"')) for x in A1]

how to make negative numbers into positive

Use float fabsf (float n) for float values.

Use double fabs (double n) for double values.

Use long double fabsl(long double) for long double values.

Use abs(int) for int values.

How to use Morgan logger?

Using morgan is pretty much straightforward. As the documentation suggests, there are different ways to get your desired output with morgan. It comes with preconfigured logging methods or you can define one yourself. Eg.

const morgan = require('morgan')

app.use(morgan('tiny')

This will give you the preconfiguration called tiny. You will notice in your terminal what it does. In case you are not satisfied with this and you want deeper e.g. lets say the request url, then this is where tokens come in.

morgan.token('url', function (req, res){ return '/api/myendpoint' })

then use it like so:

app.use(morgan(' :url ')

Check the documentation its all highlighted there.

change cursor from block or rectangle to line?

please Press fn +ins key together

How to get SQL from Hibernate Criteria API (*not* for logging)

This answer is based on user3715338's answer (with a small spelling error corrected) and mixed with Michael's answer for Hibernate 3.6 - based on the accepted answer from Brian Deterling. I then extended it (for PostgreSQL) with a couple more types replacing the questionmarks:

public static String toSql(Criteria criteria)
{
    String sql = "";
    Object[] parameters = null;
    try
    {
        CriteriaImpl criteriaImpl = (CriteriaImpl) criteria;
        SessionImpl sessionImpl = (SessionImpl) criteriaImpl.getSession();
        SessionFactoryImplementor factory = sessionImpl.getSessionFactory();
        String[] implementors = factory.getImplementors(criteriaImpl.getEntityOrClassName());
        OuterJoinLoadable persister = (OuterJoinLoadable) factory.getEntityPersister(implementors[0]);
        LoadQueryInfluencers loadQueryInfluencers = new LoadQueryInfluencers();
        CriteriaLoader loader = new CriteriaLoader(persister, factory,
            criteriaImpl, implementors[0].toString(), loadQueryInfluencers);
        Field f = OuterJoinLoader.class.getDeclaredField("sql");
        f.setAccessible(true);
        sql = (String) f.get(loader);
        Field fp = CriteriaLoader.class.getDeclaredField("translator");
        fp.setAccessible(true);
        CriteriaQueryTranslator translator = (CriteriaQueryTranslator) fp.get(loader);
        parameters = translator.getQueryParameters().getPositionalParameterValues();
    }
    catch (Exception e)
    {
        throw new RuntimeException(e);
    }
    if (sql != null)
    {
        int fromPosition = sql.indexOf(" from ");
        sql = "\nSELECT * " + sql.substring(fromPosition);

        if (parameters != null && parameters.length > 0)
        {
            for (Object val : parameters)
            {
                String value = "%";
                if (val instanceof Boolean)
                {
                    value = ((Boolean) val) ? "1" : "0";
                }
                else if (val instanceof String)
                {
                    value = "'" + val + "'";
                }
                else if (val instanceof Number)
                {
                    value = val.toString();
                }
                else if (val instanceof Class)
                {
                    value = "'" + ((Class) val).getCanonicalName() + "'";
                }
                else if (val instanceof Date)
                {
                    SimpleDateFormat sdf = new SimpleDateFormat(
                        "yyyy-MM-dd HH:mm:ss.SSS");
                    value = "'" + sdf.format((Date) val) + "'";
                }
                else if (val instanceof Enum)
                {
                    value = "" + ((Enum) val).ordinal();
                }
                else
                {
                    value = val.toString();
                }
                sql = sql.replaceFirst("\\?", value);
            }
        }
    }
    return sql.replaceAll("left outer join", "\nleft outer join").replaceAll(
        " and ", "\nand ").replaceAll(" on ", "\non ").replaceAll("<>",
        "!=").replaceAll("<", " < ").replaceAll(">", " > ");
}

What is the difference between children and childNodes in JavaScript?

Pick one depends on the method you are looking for!?

I will go with ParentNode.children:

As it provides namedItem method that allows me directly to get one of the children elements without looping through all children or avoiding to use getElementById etc.

e.g.

ParentNode.children.namedItem('ChildElement-ID'); // JS
ref.current.children.namedItem('ChildElement-ID'); // React
this.$refs.ref.children.namedItem('ChildElement-ID'); // Vue

I will go with Node.childNodes:

As it provides forEach method when I work with window.IntersectionObserver e.g.

nodeList.forEach((node) => { observer.observe(node) })
// IE11 does not support forEach on nodeList, but easy to be polyfilled.

On Chrome 83

Node.childNodes provides entries, forEach, item, keys, length and values

ParentNode.children provides item, length and namedItem

MySQL ORDER BY rand(), name ASC

SELECT  *
FROM    (
        SELECT  *
        FROM    users
        WHERE   1
        ORDER BY
                rand()
        LIMIT 20
        ) q
ORDER BY
        name

Convert object of any type to JObject with Json.NET

This will work:

var cycles = cycleSource.AllCycles();

var settings = new JsonSerializerSettings
{
    ContractResolver = new CamelCasePropertyNamesContractResolver()
};

var vm = new JArray();

foreach (var cycle in cycles)
{
    var cycleJson = JObject.FromObject(cycle);
    // extend cycleJson ......
    vm.Add(cycleJson);
}

return vm;

how to make div click-able?

The simplest of them all:

<div onclick="location.href='where.you.want.to.go'" style="cursor:pointer"></div>

Execute function after Ajax call is complete

Append .done() to your ajax request.

$.ajax({
  url: "test.html",
  context: document.body
}).done(function() { //use this
  alert("DONE!");
});

See the JQuery Doc for .done()

Finding multiple occurrences of a string within a string in Python

You can split to get relative positions then sum consecutive numbers in a list and add (string length * occurence order) at the same time to get the wanted string indexes.

>>> key = 'll'
>>> text = "Allowed Hello Hollow"
>>> x = [len(i) for i in text.split(key)[:-1]]
>>> [sum(x[:i+1]) + i*len(key) for i in range(len(x))]
[1, 10, 16]
>>> 

ASP.Net MVC: Calling a method from a view

Building on Amine's answer, create a helper like:

public static class HtmlHelperExtensions
{
    public static MvcHtmlString CurrencyFormat(this HtmlHelper helper, string value)
    {
        var result = string.Format("{0:C2}", value);
        return new MvcHtmlString(result);
    }
}

in your view: use @Html.CurrencyFormat(model.value)

If you are doing simple formating like Standard Numeric Formats, then simple use string.Format() in your view like in the helper example above:

@string.Format("{0:C2}", model.value)

jQuery "blinking highlight" effect on div?

jQuery UI Highlight Effect is what you're looking for.

$("div").click(function () {
      $(this).effect("highlight", {}, 3000);
});

The documentation and demo can be found here


Edit:
Maybe the jQuery UI Pulsate Effect is more appropriate, see here


Edit #2:
To adjust the opacity you could do this:

$("div").click(function() {
  // do fading 3 times
  for(i=0;i<3;i++) {
    $(this).fadeTo('slow', 0.5).fadeTo('slow', 1.0);
  }
});

...so it won't go any lower than 50% opacity.

Cannot deserialize the JSON array (e.g. [1,2,3]) into type ' ' because type requires JSON object (e.g. {"name":"value"}) to deserialize correctly

Use this, FrontData is JSON string:

var objResponse1 = JsonConvert.DeserializeObject<List<DataTransfer>>(FrontData);  

and extract list:

var a = objResponse1[0];
var b = a.CustomerData;

How to align the checkbox and label in same line in html?

Wrap the checkbox with the label and check this

HTML:

<li>
     <label for="checkid"  style="word-wrap:break-word">
        <input id="checkid"  type="checkbox" value="test" />testdata
     </label>
</li>

CSS:

[type="checkbox"]
{
    vertical-align:middle;
}

http://jsfiddle.net/pKD9K/1/

Javascript return number of days,hours,minutes,seconds between two dates

MomentJS has a function to do that:

const start = moment(j.timings.start);
const end = moment(j.timings.end);
const elapsedMinutes = end.diff(start, "minutes");

"Keep Me Logged In" - the best approach

I read all the answers and still found it difficult to extract what I was supposed to do. If a picture is worth 1k words I hope this helps others implement a secure persistent storage based on Barry Jaspan's Improved Persistent Login Cookie Best Practice

enter image description here

If you have questions, feedback, or suggestions, I will try to update the diagram to reflect for the newbie trying to implement a secure persistent login.

Error: EACCES: permission denied

node recommends executing following:

 sudo chown -R $USER:$(id -gn $USER) /home/venkatesh/.config

If you execute

npm config

You will see something like this

¦                   npm update check failed                   ¦
¦             Try running with sudo or get access             ¦
¦            to the local update config store via             ¦
¦ sudo chown -R $USER:$(id -gn $USER) /home/venkatesh/.config ¦

It worked for me.

Installing PIL (Python Imaging Library) in Win7 64 bits, Python 2.6.4

http://www.lfd.uci.edu/~gohlke/pythonlibs/

press contrl F type Pillow-2.4.0.win-amd64-py3.3.exe

then click and downloadd the 64 bit version

Pillow is a replacement for PIL, the Python Image Library, which provides image processing functionality and supports many file formats. Note: use from PIL import Image instead of import Image. PIL-1.1.7.win-amd64-py2.5.exe PIL-1.1.7.win32-py2.5.exe Pillow-2.4.0.win-amd64-py2.6.exe Pillow-2.4.0.win-amd64-py2.7.exe Pillow-2.4.0.win-amd64-py3.2.exe Pillow-2.4.0.win-amd64-py3.3.exe Pillow-2.4.0.win-amd64-py3.4.exe Pillow-2.4.0.win32-py2.6.exe Pillow-2.4.0.win32-py2.7.exe Pillow-2.4.0.win32-py3.2.exe Pillow-2.4.0.win32-py3.3.exe Pillow-2.4.0.win32-py3.4.exe

Check if a string contains a string in C++

#include <algorithm>        // std::search
#include <string>
using std::search; using std::count; using std::string;

int main() {
    string mystring = "The needle in the haystack";
    string str = "needle";
    string::const_iterator it;
    it = search(mystring.begin(), mystring.end(), 
                str.begin(), str.end()) != mystring.end();

    // if string is found... returns iterator to str's first element in mystring
    // if string is not found... returns iterator to mystring.end()

if (it != mystring.end())
    // string is found
else
    // not found

return 0;
}

How to find a Java Memory Leak

As most of us use Eclipse already for writing code, Why not use the Memory Analyser Tool(MAT) in Eclipse. It works great.

The Eclipse MAT is a set of plug-ins for the Eclipse IDE which provides tools to analyze heap dumps from Java application and to identify memory problems in the application.

This helps the developer to find memory leaks with the following features

  1. Acquiring a memory snapshot (Heap Dump)
  2. Histogram
  3. Retained Heap
  4. Dominator Tree
  5. Exploring Paths to the GC Roots
  6. Inspector
  7. Common Memory Anti-Patterns
  8. Object Query Language

enter image description here

How do I get rid of the b-prefix in a string in python?

It is just letting you know that the object you are printing is not a string, rather a byte object as a byte literal. People explain this in incomplete ways, so here is my take.

Consider creating a byte object by typing a byte literal (literally defining a byte object without actually using a byte object e.g. by typing b'') and converting it into a string object encoded in utf-8. (Note that converting here means decoding)

byte_object= b"test" # byte object by literally typing characters
print(byte_object) # Prints b'test'
print(byte_object.decode('utf8')) # Prints "test" without quotations

You see that we simply apply the .decode(utf8) function.

Bytes in Python

https://docs.python.org/3.3/library/stdtypes.html#bytes

String literals are described by the following lexical definitions:

https://docs.python.org/3.3/reference/lexical_analysis.html#string-and-bytes-literals

stringliteral   ::=  [stringprefix](shortstring | longstring)
stringprefix    ::=  "r" | "u" | "R" | "U"
shortstring     ::=  "'" shortstringitem* "'" | '"' shortstringitem* '"'
longstring      ::=  "'''" longstringitem* "'''" | '"""' longstringitem* '"""'
shortstringitem ::=  shortstringchar | stringescapeseq
longstringitem  ::=  longstringchar | stringescapeseq
shortstringchar ::=  <any source character except "\" or newline or the quote>
longstringchar  ::=  <any source character except "\">
stringescapeseq ::=  "\" <any source character>

bytesliteral   ::=  bytesprefix(shortbytes | longbytes)
bytesprefix    ::=  "b" | "B" | "br" | "Br" | "bR" | "BR" | "rb" | "rB" | "Rb" | "RB"
shortbytes     ::=  "'" shortbytesitem* "'" | '"' shortbytesitem* '"'
longbytes      ::=  "'''" longbytesitem* "'''" | '"""' longbytesitem* '"""'
shortbytesitem ::=  shortbyteschar | bytesescapeseq
longbytesitem  ::=  longbyteschar | bytesescapeseq
shortbyteschar ::=  <any ASCII character except "\" or newline or the quote>
longbyteschar  ::=  <any ASCII character except "\">
bytesescapeseq ::=  "\" <any ASCII character>

How to represent the double quotes character (") in regex?

Firstly, double quote character is nothing special in regex - it's just another character, so it doesn't need escaping from the perspective of regex.

However, because java uses double quotes to delimit String constants, if you want to create a string in java with a double quote in it, you must escape them.

This code will test if your String matches:

if (str.matches("\".*\"")) {
    // this string starts and end with a double quote
}

Note that you don't need to add start and end of input markers (^ and $) in the regex, because matches() requires that the whole input be matched to return true - ^ and $ are implied.

Printing integer variable and string on same line in SQL

declare @x INT = 1 /* Declares an integer variable named "x" with the value of 1 */
    
PRINT 'There are ' + CAST(@x AS VARCHAR) + ' alias combinations did not match a record' /* Prints a string concatenated with x casted as a varchar */

How to get text box value in JavaScript

If you are using ASP.NET, the server-side code tags in these examples below will provide the exact control ID, even if you are using Master pages.

Javascript:

document.getElementById("<%=MyControlName.ClientID%>").value;

JQuery:

$("#<%= MyControlName.ClientID %>").val();

bootstrap jquery show.bs.modal event won't fire

Try this

$('#myModal').on('shown.bs.modal', function () {
   alert('hi');
});

Using shown instead of show also make sure you have your semi colons at the end of your function and alert.

Primefaces valueChangeListener or <p:ajax listener not firing for p:selectOneMenu

this works for me:

It can be used inside the dialog, but the dialog can´t be inside any componet such as panels, accordion, etc.

Classes residing in App_Code is not accessible

Go to the page from where you want to access the App_code class, and then add the namespace of the app_code class. You need to provide a using statement, as follows:

using WebApplication3.App_Code;

After that, you will need to go to the app_code class property and set the 'Build Action' to 'Compile'.

What is the best way to implement "remember me" for a website?

Store their UserId and a RememberMeToken. When they login with remember me checked generate a new RememberMeToken (which invalidate any other machines which are marked are remember me).

When they return look them up by the remember me token and make sure the UserId matches.

How can I initialize C++ object member variables in the constructor?

I know this is 5 years later, but the replies above don't address what was wrong with your software. (Well, Yuushi's does, but I didn't realise until I had typed this - doh!). They answer the question in the title How can I initialize C++ object member variables in the constructor? This is about the other questions: Am I using the right approach but the wrong syntax? Or should I be coming at this from a different direction?

Programming style is largely a matter of opinion, but an alternative view to doing as much as possible in a constructor is to keep constructors down to a bare minimum, often having a separate initialization function. There is no need to try to cram all initialization into a constructor, never mind trying to force things at times into the constructors initialization list.

So, to the point, what was wrong with your software?

private:
    ThingOne* ThingOne;
    ThingTwo* ThingTwo;

Note that after these lines, ThingOne (and ThingTwo) now have two meanings, depending on context.

Outside of BigMommaClass, ThingOne is the class you created with #include "ThingOne.h"

Inside BigMommaClass, ThingOne is a pointer.

That is assuming the compiler can even make sense of the lines and doesn't get stuck in a loop thinking that ThingOne is a pointer to something which is itself a pointer to something which is a pointer to ...

Later, when you write

this->ThingOne = ThingOne(100);
this->ThingTwo = ThingTwo(numba1, numba2);

bear in mind that inside of BigMommaClass your ThingOne is a pointer.

If you change the declarations of the pointers to include a prefix (p)

private:
    ThingOne* pThingOne;
    ThingTwo* pThingTwo;

Then ThingOne will always refer to the class and pThingOne to the pointer.

It is then possible to rewrite

this->ThingOne = ThingOne(100);
this->ThingTwo = ThingTwo(numba1, numba2);

as

pThingOne = new ThingOne(100);
pThingTwo = new ThingTwo(numba1, numba2);

which corrects two problems: the double meaning problem, and the missing new. (You can leave this-> if you like!)

With that in place, I can add the following lines to a C++ program of mine and it compiles nicely.

class ThingOne{public:ThingOne(int n){};};
class ThingTwo{public:ThingTwo(int x, int y){};};

class BigMommaClass {

    public:
            BigMommaClass(int numba1, int numba2);

    private:
            ThingOne* pThingOne;
            ThingTwo* pThingTwo;
};

BigMommaClass::BigMommaClass(int numba1, int numba2)
{
    pThingOne = new ThingOne(numba1 + numba2);
    pThingTwo = new ThingTwo(numba1, numba2);
};

When you wrote

this->ThingOne = ThingOne(100);
this->ThingTwo = ThingTwo(numba1, numba2);

the use of this-> tells the compiler that the left hand side ThingOne is intended to mean the pointer. However we are inside BigMommaClass at the time and it's not necessary.

The problem is with the right hand side of the equals where ThingOne is intended to mean the class. So another way to rectify your problems would have been to write

this->ThingOne = new ::ThingOne(100);
this->ThingTwo = new ::ThingTwo(numba1, numba2);

or simply

ThingOne = new ::ThingOne(100);
ThingTwo = new ::ThingTwo(numba1, numba2);

using :: to change the compiler's interpretation of the identifier.

PHP Fatal Error Failed opening required File

Just in case this helps anybody else out there, I stumbled on an obscure case for this error triggering last night. Specifically, I was using the require_once method and specifying only a filename and no path, since the file being required was present in the same directory.

I started to get the 'Failed opening required file' error at one point. After tearing my hair out for a while, I finally noticed a PHP Warning message immediately above the fatal error output, indicating 'failed to open stream: Permission denied', but more importantly, informing me of the path to the file it was trying to open. I then twigged to the fact I had created a copy of the file (with ownership not accessible to Apache) elsewhere that happened to also be in the PHP 'include' search path, and ahead of the folder where I wanted it to be picked up. D'oh!

Reading all files in a directory, store them in objects, and send the object

For all example below you need to import fs and path modules:

const fs = require('fs');
const path = require('path');

Read files asynchronously

function readFiles(dir, processFile) {
  // read directory
  fs.readdir(dir, (error, fileNames) => {
    if (error) throw error;

    fileNames.forEach(filename => {
      // get current file name
      const name = path.parse(filename).name;
      // get current file extension
      const ext = path.parse(filename).ext;
      // get current file path
      const filepath = path.resolve(dir, filename);

      // get information about the file
      fs.stat(filepath, function(error, stat) {
        if (error) throw error;

        // check if the current path is a file or a folder
        const isFile = stat.isFile();

        // exclude folders
        if (isFile) {
          // callback, do something with the file
          processFile(filepath, name, ext, stat);
        }
      });
    });
  });
}

Usage:

// use an absolute path to the folder where files are located
readFiles('absolute/path/to/directory/', (filepath, name, ext, stat) => {
  console.log('file path:', filepath);
  console.log('file name:', name);
  console.log('file extension:', ext);
  console.log('file information:', stat);
});

Read files synchronously, store in array, natural sorting

/**
 * @description Read files synchronously from a folder, with natural sorting
 * @param {String} dir Absolute path to directory
 * @returns {Object[]} List of object, each object represent a file
 * structured like so: `{ filepath, name, ext, stat }`
 */
function readFilesSync(dir) {
  const files = [];

  fs.readdirSync(dir).forEach(filename => {
    const name = path.parse(filename).name;
    const ext = path.parse(filename).ext;
    const filepath = path.resolve(dir, filename);
    const stat = fs.statSync(filepath);
    const isFile = stat.isFile();

    if (isFile) files.push({ filepath, name, ext, stat });
  });

  files.sort((a, b) => {
    // natural sort alphanumeric strings
    // https://stackoverflow.com/a/38641281
    return a.name.localeCompare(b.name, undefined, { numeric: true, sensitivity: 'base' });
  });

  return files;
}

Usage:

// return an array list of objects
// each object represent a file
const files = readFilesSync('absolute/path/to/directory/');

Read files async using promise

More info on promisify in this article.

const { promisify } = require('util');

const readdir_promise = promisify(fs.readdir);
const stat_promise = promisify(fs.stat);

function readFilesAsync(dir) {
  return readdir_promise(dir, { encoding: 'utf8' })
    .then(filenames => {
      const files = getFiles(dir, filenames);

      return Promise.all(files);
    })
    .catch(err => console.error(err));
}

function getFiles(dir, filenames) {
  return filenames.map(filename => {
    const name = path.parse(filename).name;
    const ext = path.parse(filename).ext;
    const filepath = path.resolve(dir, filename);

    return stat({ name, ext, filepath });
  });
}

function stat({ name, ext, filepath }) {
  return stat_promise(filepath)
    .then(stat => {
      const isFile = stat.isFile();

      if (isFile) return { name, ext, filepath, stat };
    })
    .catch(err => console.error(err));
}

Usage:

readFiles('absolute/path/to/directory/')
  // return an array list of objects
  // each object is a file
  // with those properties: { name, ext, filepath, stat }
  .then(files => console.log(files))
  .catch(err => console.log(err));

Note: return undefined for folders, if you want you can filter them out:

readFiles('absolute/path/to/directory/')
  .then(files => files.filter(file => file !== undefined))
  .catch(err => console.log(err));

Replace substring with another substring C++

    string & replace(string & subj, string old, string neu)
    {
        size_t uiui = subj.find(old);
        if (uiui != string::npos)
        {
           subj.erase(uiui, old.size());
           subj.insert(uiui, neu);
        }
        return subj;
    }

I think this fits your requirement with few code!

Get value from SimpleXMLElement Object

$codeZero = null;
foreach ($xml->code->children() as $child) {
   $codeZero = $child;
}

$lat = null;
foreach ($codeZero->children() as $child) {
   if (isset($child->lat)) {
      $lat = $child->lat;
   }
}

Difference between int32, int, int32_t, int8 and int8_t

Between int32 and int32_t, (and likewise between int8 and int8_t) the difference is pretty simple: the C standard defines int8_t and int32_t, but does not define anything named int8 or int32 -- the latter (if they exist at all) is probably from some other header or library (most likely predates the addition of int8_t and int32_t in C99).

Plain int is quite a bit different from the others. Where int8_t and int32_t each have a specified size, int can be any size >= 16 bits. At different times, both 16 bits and 32 bits have been reasonably common (and for a 64-bit implementation, it should probably be 64 bits).

On the other hand, int is guaranteed to be present in every implementation of C, where int8_t and int32_t are not. It's probably open to question whether this matters to you though. If you use C on small embedded systems and/or older compilers, it may be a problem. If you use it primarily with a modern compiler on desktop/server machines, it probably won't be.

Oops -- missed the part about char. You'd use int8_t instead of char if (and only if) you want an integer type guaranteed to be exactly 8 bits in size. If you want to store characters, you probably want to use char instead. Its size can vary (in terms of number of bits) but it's guaranteed to be exactly one byte. One slight oddity though: there's no guarantee about whether a plain char is signed or unsigned (and many compilers can make it either one, depending on a compile-time flag). If you need to ensure its being either signed or unsigned, you need to specify that explicitly.

How to get the current time in milliseconds from C in Linux?

Use gettimeofday() to get the time in seconds and microseconds. Combining and rounding to milliseconds is left as an exercise.

How to jump to top of browser page

you're using jQuery UI dialog, you could just style the modal to appear with the position fixed in the window so it doesn't pop-up out of view, negating the need to scroll. Other

Best way to create a simple python web service

If you mean "web service" in SOAP/WSDL sense, you might want to look at Generating a WSDL using Python and SOAPpy

How to ignore conflicts in rpm installs

The --force option will reinstall already installed packages or overwrite already installed files from other packages. You don't want this normally.

If you tell rpm to install all RPMs from some directory, then it does exactly this. rpm will not ignore RPMs listed for installation. You must manually remove the unneeded RPMs from the list (or directory). It will always overwrite the files with the "latest RPM installed" whichever order you do it in.

You can remove the old RPM and rpm will resolve the dependency with the newer version of the installed RPM. But this will only work, if none of the to be installed RPMs depends exactly on the old version.

If you really need different versions of the same RPM, then the RPM must be relocatable. You can then tell rpm to install the specific RPM to a different directory. If the files are not conflicting, then you can just install different versions with rpm -i (zypper in can not install different versions of the same RPM). I am packaging for example ruby gems as relocatable RPMs at work. So I can have different versions of the same gem installed.

I don't know on which files your RPMs are conflicting, but if all of them are "just" man pages, then you probably can simply overwrite the new ones with the old ones with rpm -i --replacefiles. The only problem with this would be, that it could confuse somebody who is reading the old man page and thinks it is for the actual version. Another problem would be the rpm --verify command. It will complain for the new package if the old one has overwritten some files.

Is this possibly a duplicate of https://serverfault.com/questions/522525/rpm-ignore-conflicts?

How can I remove an entry in global configuration with git config?

Open config file to edit :

git config --global --edit

Press Insert and remove the setting

and finally type :wq and Enter to save.

How do I create/edit a Manifest file?

In Visual Studio 2010 (until 2019 and possibly future versions) you can add the manifest file to your project.

Right click your project file on the Solution Explorer, select Add, then New item (or CTRL+SHIFT+A). There you can find Application Manifest File.

The file name is app.manifest.

The role of #ifdef and #ifndef

The code looks strange because the printf are not in any function blocks.

how to get the first and last days of a given month

cal_days_in_month() should give you the total number of days in the month, and therefore, the last one.

How to empty a Heroku database

Check your heroku version. I just updated mine to 2.29.0, as follows:

heroku --version
#=> heroku-gem/2.29.0 (x86_64-linux) ruby/1.9.3

Now you can run:

heroku pg:reset DATABASE --confirm YOUR_APP_NAME

Then create your database and seed it in a single command:

heroku run rake db:setup

Now restart and try your app:

heroku restart
heroku open

How to debug stored procedures with print statements?

try using:

RAISERROR('your message here!!!',0,1) WITH NOWAIT

you could also try switching to "Results to Text" it is just a few icons to the right of "Execute" on the default tool bar.

With both of the above in place, and you still you do not see the messages, make sure you are running the same server/database/owner version of the procedure that you are editing. Make sure you are hitting the RAISERROR command, make it the first command inside the procedure.

If all else fails, you could create a table:

create table temp_log (RowID int identity(1,1) primary key not null
                      , MessageValue varchar(255))

then:

INSERT INTO temp_log VALUES ('Your message here')

then after running the procedure (provided no rollbacks) just select the table.

Fast Linux file count for a large number of files

I came here when trying to count the files in a data set of approximately 10,000 folders with approximately 10,000 files each. The problem with many of the approaches is that they implicitly stat 100 million files, which takes ages.

I took the liberty to extend the approach by Christopher Schultz so it supports passing directories via arguments (his recursive approach uses stat as well).

Put the following into file dircnt_args.c:

#include <stdio.h>
#include <dirent.h>

int main(int argc, char *argv[]) {
    DIR *dir;
    struct dirent *ent;
    long count;
    long countsum = 0;
    int i;

    for(i=1; i < argc; i++) {
        dir = opendir(argv[i]);
        count = 0;
        while((ent = readdir(dir)))
            ++count;

        closedir(dir);

        printf("%s contains %ld files\n", argv[i], count);
        countsum += count;
    }
    printf("sum: %ld\n", countsum);

    return 0;
}

After a gcc -o dircnt_args dircnt_args.c you can invoke it like this:

dircnt_args /your/directory/*

On 100 million files in 10,000 folders, the above completes quite quickly (approximately 5 minutes for the first run, and followup on cache: approximately 23 seconds).

The only other approach that finished in less than an hour was ls with about 1 min on cache: ls -f /your/directory/* | wc -l. The count is off by a couple of newlines per directory though...

Other than expected, none of my attempts with find returned within an hour :-/

How to blur background images in Android

The simplest way to achieve this is given below,

I)

Glide.with(context.getApplicationContext())
                        .load(Your Path)   
                        .override(15, 15) // (change according to your wish)
                        .error(R.drawable.placeholder)
                        .into(image.score);

else you can follow the code below..

II)

1.Create a class.(Code is given below)

public class BlurTransformation extends BitmapTransformation {

    private RenderScript rs;

    public BlurTransformation(Context context) {
        super( context );

        rs = RenderScript.create( context );
    }

    @Override
    protected Bitmap transform(BitmapPool pool, Bitmap toTransform, int outWidth, int outHeight) {
        Bitmap blurredBitmap = toTransform.copy( Bitmap.Config.ARGB_8888, true );

        // Allocate memory for Renderscript to work with
        Allocation input = Allocation.createFromBitmap(
            rs, 
            blurredBitmap, 
            Allocation.MipmapControl.MIPMAP_FULL, 
            Allocation.USAGE_SHARED
        );
        Allocation output = Allocation.createTyped(rs, input.getType());

        // Load up an instance of the specific script that we want to use.
        ScriptIntrinsicBlur script = ScriptIntrinsicBlur.create(rs, Element.U8_4(rs));
        script.setInput(input);

        // Set the blur radius
        script.setRadius(10);

        // Start the ScriptIntrinisicBlur
        script.forEach(output);

        // Copy the output to the blurred bitmap
        output.copyTo(blurredBitmap);

        toTransform.recycle();

        return blurredBitmap;
    }

    @Override
    public String getId() {
        return "blur";
    }
}

2.Set image to ImageView using Glide.

eg:

Glide.with(this)
     .load(expertViewDetailsModel.expert.image)
     .asBitmap()
     .transform(new BlurTransformation(this))
     .into(ivBackground);

Reading a date using DataReader

In my case I changed the datetime field in the SQL database to not allow null. SqlDataReader then allowed me to cast the value directly to a DateTime.

Drawing an image from a data URL to a canvas

function drawDataURIOnCanvas(strDataURI, canvas) {
    "use strict";
    var img = new window.Image();
    img.addEventListener("load", function () {
        canvas.getContext("2d").drawImage(img, 0, 0);
    });
    img.setAttribute("src", strDataURI);
}

Email address validation using ASP.NET MVC data type attributes

Used the above code in MVC5 project and it works completely fine with the validation error. Just try this code:

   [Required]
   [Display(Name = "Email")]
   [EmailAddress]

   [RegularExpression(@"^([A-Za-z0-9][^'!&\\#*$%^?<>()+=:;`~\[\]{}|/,?€@ ][a-zA-z0- 
    9-._][^!&\\#*$%^?<>()+=:;`~\[\]{}|/,?€@ ]*\@[a-zA-Z0-9][^!&@\\#*$%^?<> 
        ()+=':;~`.\[\]{}|/,?€ ]*\.[a-zA-Z]{2,6})$", ErrorMessage = "Please enter a 
   valid Email")]


   public string ReceiverMail { get; set; }

Bash script plugin for Eclipse?

ShellEd is a good plugin for Eclipse.

This link helped me to install it: http://mattnorris.me/blog/install-eclipse-shelled-plugin/

Steps:

  1. Download ShellEd: http://sourceforge.net/projects/shelled/files/latest/download - The file is a zipped archive named something like net.sourceforge.shelled-site-2.0.x.zip.

  2. Then click Help > Install New Software...

  3. Click Add... in the upper right.
  4. Click Archive...
  5. Navigate to where you saved the zipped archive net.sourceforge.shelled-site-2.0.x.zip and select it.
  6. Click OK. (Don't worry about the optional Name field. Eclipse will name it automatically.)
  7. Select the new Shell Script checkbox.
  8. Click Next.
  9. Click Next again.
  10. Select "I accept the terms of the license agreement."
  11. Click Finish.
  12. Restart Eclipse.

How do I get rid of an element's offset using CSS?

That offset is basically the x,y position that the browser has calculated for the element based on it's position css attribute. So if you put a <br> before it or any other element, it would change the offset. For example, you could set it to 0 by:

#inputBox{position:absolute;top:0px;left:0px;}

or

#inputBox{position:relative;top:-12px;left:-2px;}

Therefore, whatever positioning issue you have, is not necessarily an issue with offset, though you could always fix it by playing with the top,left,right and bottom attributes.

Is your problem browser incompatibility?

Using Python's os.path, how do I go up one directory?

From the current file path you could use:

os.path.join(os.path.dirname(__file__),'..','img','banner.png')

open_basedir restriction in effect. File(/) is not within the allowed path(s):

For me the problem was bad/missing config values for the Plesk server running the whole thing. I just followed the directions here: http://davidseah.com/blog/2007/04/separate-php-error-logs-for-multiple-domains-with-plesk/

You can configure PHP to have a separate error log file for each VirtualHost definition. The trick is knowing exactly how to set it up, because you can’t touch the configuration directly without breaking Plesk. Every domain name on your (dv) has its own directory in /var/www/vhosts. A typical directory has the following top level directories:

cgi-bin/
conf/
error_docs/
httpdocs/
httpsdocs/
...and so on

You’ll want to create a vhost.conf file in the domain directory’s conf/ folder with the following lines:

php_value error_log /path/to/error_log
php_flag display_errors off
php_value error_reporting 6143
php_flag log_errors on

Change the first value to match your actual installation (I used /tmp/phperrors.log). After you’re done editing the vhost.conf file, test the configuration from the console with:

apachectl configtest
…or if you don’t have apachectl (as Plesk 8.6 doesn’t seem to)…

/etc/init.d/httpd configtest

And finally tell Plesk that you’ve made this change.

/usr/local/psa/admin/bin/websrvmng -a

auto create database in Entity Framework Core

For EF Core 2.0+ I had to take a different approach because they changed the API. As of March 2019 Microsoft recommends you put your database migration code in your application entry class but outside of the WebHost build code.

public class Program
{
    public static void Main(string[] args)
    {
        var host = CreateWebHostBuilder(args).Build();
        using (var serviceScope = host.Services.CreateScope())
        {
            var context = serviceScope.ServiceProvider.GetRequiredService<PersonContext>();
            context.Database.Migrate();
        }
        host.Run();
    }

    public static IWebHostBuilder CreateWebHostBuilder(string[] args) =>
        WebHost.CreateDefaultBuilder(args)
            .UseStartup<Startup>();
}

Call a PHP function after onClick HTML event

You don't need javascript for doing so. Just delete the onClick and write the php Admin.php file like this:

<!-- HTML STARTS-->
<?php
//If all the required fields are filled
if (!empty($GET_['fullname'])&&!empty($GET_['email'])&&!empty($GET_['name']))
{
function addNewContact()
    {
    $new = '{';
    $new .= '"fullname":"' . $_GET['fullname'] . '",';
    $new .= '"email":"' . $_GET['email'] . '",';
    $new .= '"phone":"' . $_GET['phone'] . '",';
    $new .= '}';
    return $new;
    }

function saveContact()
    {
    $datafile = fopen ("data/data.json", "a+");
    if(!$datafile){
        echo "<script>alert('Data not existed!')</script>";
        } 
    else{
        $contact_list = $contact_list . addNewContact();
        file_put_contents("data/data.json", $contact_list);
        }
    fclose($datafile);
    }

// Call the function saveContact()
saveContact();
echo "Thank you for joining us";
}
else //If the form is not submited or not all the required fields are filled

{ ?>

<form>
    <fieldset>
        <legend>Add New Contact</legend>
        <input type="text" name="fullname" placeholder="First name and last name" required /> <br />
        <input type="email" name="email" placeholder="[email protected]" required /> <br />
        <input type="text" name="phone" placeholder="Personal phone number: mobile, home phone etc." required /> <br />
        <input type="submit" name="submit" class="button" value="Add Contact"/>
        <input type="button" name="cancel" class="button" value="Reset" />
    </fieldset>
</form>
<?php }
?>
<!-- HTML ENDS -->

Thought I don't like the PHP bit. Do you REALLY want to create a file for contacts? It'd be MUCH better to use a mysql database. Also, adding some breaks to that file would be nice too...

Other thought, IE doesn't support placeholder.

How to set width to 100% in WPF

You could use HorizontalContentAlignment="Stretch" as follows:

<ListBox HorizontalContentAlignment="Stretch"/>

How to display raw JSON data on a HTML page

I think all you need to display the data on an HTML page is JSON.stringify.

For example, if your JSON is stored like this:

var jsonVar = {
        text: "example",
        number: 1
    };

Then you need only do this to convert it to a string:

var jsonStr = JSON.stringify(jsonVar);

And then you can insert into your HTML directly, for example:

document.body.innerHTML = jsonStr;

Of course you will probably want to replace body with some other element via getElementById.

As for the CSS part of your question, you could use RegExp to manipulate the stringified object before you put it into the DOM. For example, this code (also on JSFiddle for demonstration purposes) should take care of indenting of curly braces.

var jsonVar = {
        text: "example",
        number: 1,
        obj: {
            "more text": "another example"
        },
        obj2: {
             "yet more text": "yet another example"
        }
    }, // THE RAW OBJECT
    jsonStr = JSON.stringify(jsonVar),  // THE OBJECT STRINGIFIED
    regeStr = '', // A EMPTY STRING TO EVENTUALLY HOLD THE FORMATTED STRINGIFIED OBJECT
    f = {
            brace: 0
        }; // AN OBJECT FOR TRACKING INCREMENTS/DECREMENTS,
           // IN PARTICULAR CURLY BRACES (OTHER PROPERTIES COULD BE ADDED)

regeStr = jsonStr.replace(/({|}[,]*|[^{}:]+:[^{}:,]*[,{]*)/g, function (m, p1) {
var rtnFn = function() {
        return '<div style="text-indent: ' + (f['brace'] * 20) + 'px;">' + p1 + '</div>';
    },
    rtnStr = 0;
    if (p1.lastIndexOf('{') === (p1.length - 1)) {
        rtnStr = rtnFn();
        f['brace'] += 1;
    } else if (p1.indexOf('}') === 0) {
         f['brace'] -= 1;
        rtnStr = rtnFn();
    } else {
        rtnStr = rtnFn();
    }
    return rtnStr;
});

document.body.innerHTML += regeStr; // appends the result to the body of the HTML document

This code simply looks for sections of the object within the string and separates them into divs (though you could change the HTML part of that). Every time it encounters a curly brace, however, it increments or decrements the indentation depending on whether it's an opening brace or a closing (behaviour similar to the space argument of 'JSON.stringify'). But you could this as a basis for different types of formatting.

Why is exception.printStackTrace() considered bad practice?

printStackTrace() prints to a console. In production settings, nobody is ever watching at that. Suraj is correct, should pass this information to a logger.

Good PHP ORM Library?

Look at http://code.google.com/p/lworm/ . It is a really simple, but powerful, lightweight ORM system for PHP. You can also easily extend it, if you want.

How to return data from PHP to a jQuery ajax call

Yes, the way you are doing it is perfectly legitimate. To access that data on the client side, edit your success function to accept a parameter: data.

$.ajax({
    type: "POST",
    url: "somescript.php",
    datatype: "html",
    data: dataString,
    success: function(data) {
        doSomething(data);
    }
});

How to draw interactive Polyline on route google maps v2 android

Using the google maps projection api to draw the polylines on an overlay view enables us to do a lot of things. Check this repo that has an example.

enter image description here

In Java, can you modify a List while iterating through it?

There is nothing wrong with the idea of modifying an element inside a list while traversing it (don't modify the list itself, that's not recommended), but it can be better expressed like this:

for (int i = 0; i < letters.size(); i++) {
    letters.set(i, "D");
}

At the end the whole list will have the letter "D" as its content. It's not a good idea to use an enhanced for loop in this case, you're not using the iteration variable for anything, and besides you can't modify the list's contents using the iteration variable.

Notice that the above snippet is not modifying the list's structure - meaning: no elements are added or removed and the lists' size remains constant. Simply replacing one element by another doesn't count as a structural modification. Here's the link to the documentation quoted by @ZouZou in the comments, it states that:

A structural modification is any operation that adds or deletes one or more elements, or explicitly resizes the backing array; merely setting the value of an element is not a structural modification

NSURLErrorDomain error codes description

IN SWIFT 3. Here are the NSURLErrorDomain error codes description in a Swift 3 enum: (copied from answer above and converted what i can).

enum NSURLError: Int {
    case unknown = -1
    case cancelled = -999
    case badURL = -1000
    case timedOut = -1001
    case unsupportedURL = -1002
    case cannotFindHost = -1003
    case cannotConnectToHost = -1004
    case connectionLost = -1005
    case lookupFailed = -1006
    case HTTPTooManyRedirects = -1007
    case resourceUnavailable = -1008
    case notConnectedToInternet = -1009
    case redirectToNonExistentLocation = -1010
    case badServerResponse = -1011
    case userCancelledAuthentication = -1012
    case userAuthenticationRequired = -1013
    case zeroByteResource = -1014
    case cannotDecodeRawData = -1015
    case cannotDecodeContentData = -1016
    case cannotParseResponse = -1017
    //case NSURLErrorAppTransportSecurityRequiresSecureConnection NS_ENUM_AVAILABLE(10_11, 9_0) = -1022
    case fileDoesNotExist = -1100
    case fileIsDirectory = -1101
    case noPermissionsToReadFile = -1102
    //case NSURLErrorDataLengthExceedsMaximum NS_ENUM_AVAILABLE(10_5, 2_0) =   -1103

    // SSL errors
    case secureConnectionFailed = -1200
    case serverCertificateHasBadDate = -1201
    case serverCertificateUntrusted = -1202
    case serverCertificateHasUnknownRoot = -1203
    case serverCertificateNotYetValid = -1204
    case clientCertificateRejected = -1205
    case clientCertificateRequired = -1206
    case cannotLoadFromNetwork = -2000

    // Download and file I/O errors
    case cannotCreateFile = -3000
    case cannotOpenFile = -3001
    case cannotCloseFile = -3002
    case cannotWriteToFile = -3003
    case cannotRemoveFile = -3004
    case cannotMoveFile = -3005
    case downloadDecodingFailedMidStream = -3006
    case downloadDecodingFailedToComplete = -3007

    /*
     case NSURLErrorInternationalRoamingOff NS_ENUM_AVAILABLE(10_7, 3_0) =         -1018
     case NSURLErrorCallIsActive NS_ENUM_AVAILABLE(10_7, 3_0) =                    -1019
     case NSURLErrorDataNotAllowed NS_ENUM_AVAILABLE(10_7, 3_0) =                  -1020
     case NSURLErrorRequestBodyStreamExhausted NS_ENUM_AVAILABLE(10_7, 3_0) =      -1021

     case NSURLErrorBackgroundSessionRequiresSharedContainer NS_ENUM_AVAILABLE(10_10, 8_0) = -995
     case NSURLErrorBackgroundSessionInUseByAnotherProcess NS_ENUM_AVAILABLE(10_10, 8_0) = -996
     case NSURLErrorBackgroundSessionWasDisconnected NS_ENUM_AVAILABLE(10_10, 8_0)= -997
     */
}

Direct link to URLError.Code in the Swift github repository, which contains the up to date list of error codes being used (github link).

Can I display the value of an enum with printf()?

The correct answer to this has already been given: no, you can't give the name of an enum, only it's value.

Nevertheless, just for fun, this will give you an enum and a lookup-table all in one and give you a means of printing it by name:

main.c:

#include "Enum.h"

CreateEnum(
        EnumerationName,
        ENUMValue1,
        ENUMValue2,
        ENUMValue3);

int main(void)
{
    int i;
    EnumerationName EnumInstance = ENUMValue1;

    /* Prints "ENUMValue1" */
    PrintEnumValue(EnumerationName, EnumInstance);

    /* Prints:
     * ENUMValue1
     * ENUMValue2
     * ENUMValue3
     */
    for (i=0;i<3;i++)
    {
        PrintEnumValue(EnumerationName, i);
    }
    return 0;
}

Enum.h:

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

#ifdef NDEBUG
#define CreateEnum(name,...) \
    typedef enum \
    { \
        __VA_ARGS__ \
    } name;
#define PrintEnumValue(name,value)
#else
#define CreateEnum(name,...) \
    typedef enum \
    { \
        __VA_ARGS__ \
    } name; \
    const char Lookup##name[] = \
        #__VA_ARGS__;
#define PrintEnumValue(name, value) print_enum_value(Lookup##name, value)
void print_enum_value(const char *lookup, int value);
#endif

Enum.c

#include "Enum.h"

#ifndef NDEBUG
void print_enum_value(const char *lookup, int value)
{
    char *lookup_copy;
    int lookup_length;
    char *pch;

    lookup_length = strlen(lookup);
    lookup_copy = malloc((1+lookup_length)*sizeof(char));
    strcpy(lookup_copy, lookup);

    pch = strtok(lookup_copy," ,");
    while (pch != NULL)
    {
        if (value == 0)
        {
            printf("%s\n",pch);
            break;
        }
        else
        {
            pch = strtok(NULL, " ,.-");
            value--;
        }
    }

    free(lookup_copy);
}
#endif

Disclaimer: don't do this.

swift How to remove optional String Character

Try this,

var check:String?="optional String"
print(check!) //optional string. This will result in nil while unwrapping an optional value if value is not initialized or if initialized to nil.
print(check) //Optional("optional string") //nil values are handled in this statement

Go with first if you are confident to have no nil in your variable. Also, you can use if let or Guard let statement to unwrap optionals without any crash.

 if let unwrapperStr = check
 {
    print(unwrapperStr) //optional String
 }

Guard let,

 guard let gUnwrap = check else
 {
    //handle failed unwrap case here
 }
 print(gUnwrap) //optional String

LINQ Where with AND OR condition

from item in db.vw_Dropship_OrderItems
    where (listStatus != null ? listStatus.Contains(item.StatusCode) : true) &&
    (listMerchants != null ? listMerchants.Contains(item.MerchantId) : true)
    select item;

Might give strange behavior if both listMerchants and listStatus are both null.

Why doesn't indexOf work on an array IE8?

Please careful with $.inArray if you want to use it. I just found out that the $.inArray is only works with "Array", not with String. That's why this function will not working in IE8!

The jQuery API make confusion

The $.inArray() method is similar to JavaScript's native .indexOf() method in that it returns -1 when it doesn't find a match. If the first element within the array matches value, $.inArray() returns 0

--> They shouldn't say it "Similar". Since indexOf support "String" also!

How can I close a Twitter Bootstrap popover with a click from anywhere (else) on the page?

Add btn-popover class to your popover button/link that opens the popover. This code will close the popovers when clicking outside of it.

$('body').on('click', function(event) {
  if (!$(event.target).closest('.btn-popover, .popover').length) {
    $('.popover').popover('hide');
  }
});

How can I pass a Bitmap object from one activity to another

Because Intent has size limit . I use public static object to do pass bitmap from service to broadcast ....

public class ImageBox {
    public static Queue<Bitmap> mQ = new LinkedBlockingQueue<Bitmap>(); 
}

pass in my service

private void downloadFile(final String url){
        mExecutorService.submit(new Runnable() {
            @Override
            public void run() {
                Bitmap b = BitmapFromURL.getBitmapFromURL(url);
                synchronized (this){
                    TaskCount--;
                }
                Intent i = new Intent(ACTION_ON_GET_IMAGE);
                ImageBox.mQ.offer(b);
                sendBroadcast(i);
                if(TaskCount<=0)stopSelf();
            }
        });
    }

My BroadcastReceiver

private final BroadcastReceiver mReceiver = new BroadcastReceiver() {
        public void onReceive(Context context, Intent intent) {
            LOG.d(TAG, "BroadcastReceiver get broadcast");

            String action = intent.getAction();
            if (DownLoadImageService.ACTION_ON_GET_IMAGE.equals(action)) {
                Bitmap b = ImageBox.mQ.poll();
                if(b==null)return;
                if(mListener!=null)mListener.OnGetImage(b);
            }
        }
    };

Getting a list of files in a directory with a glob

You need to roll your own method to eliminate the files you don't want.

This isn't easy with the built in tools, but you could use RegExKit Lite to assist with finding the elements in the returned array you are interested in. According to the release notes this should work in both Cocoa and Cocoa-Touch applications.

Here's the demo code I wrote up in about 10 minutes. I changed the < and > to " because they weren't showing up inside the pre block, but it still works with the quotes. Maybe somebody who knows more about formatting code here on StackOverflow will correct this (Chris?).

This is a "Foundation Tool" Command Line Utility template project. If I get my git daemon up and running on my home server I'll edit this post to add the URL for the project.

#import "Foundation/Foundation.h"
#import "RegexKit/RegexKit.h"

@interface MTFileMatcher : NSObject 
{
}
- (void)getFilesMatchingRegEx:(NSString*)inRegex forPath:(NSString*)inPath;
@end

int main (int argc, const char * argv[])
{
    NSAutoreleasePool * pool = [[NSAutoreleasePool alloc] init];

    // insert code here...
    MTFileMatcher* matcher = [[[MTFileMatcher alloc] init] autorelease];
    [matcher getFilesMatchingRegEx:@"^.+\\.[Jj][Pp][Ee]?[Gg]$" forPath:[@"~/Pictures" stringByExpandingTildeInPath]];

    [pool drain];
    return 0;
}

@implementation MTFileMatcher
- (void)getFilesMatchingRegEx:(NSString*)inRegex forPath:(NSString*)inPath;
{
    NSArray* filesAtPath = [[[NSFileManager defaultManager] directoryContentsAtPath:inPath] arrayByMatchingObjectsWithRegex:inRegex];
    NSEnumerator* itr = [filesAtPath objectEnumerator];
    NSString* obj;
    while (obj = [itr nextObject])
    {
        NSLog(obj);
    }
}
@end

Turning multiple lines into one comma separated line

file

aaa
bbb
ccc
ddd

xargs

cat file | xargs

result

aaa bbb ccc ddd 

xargs improoved

cat file | xargs | sed -e 's/ /,/g'

result

aaa,bbb,ccc,ddd 

how do I initialize a float to its max/min value?

To manually find the minimum of an array you don't need to know the minimum value of float:

float myFloats[];
...
float minimum = myFloats[0];
for (int i = 0; i < myFloatsSize; ++i)
{
  if (myFloats[i] < minimum)
  {
    minimum = myFloats[i];
  }
}

And similar code for the maximum value.

JQuery add class to parent element

$(this.parentNode).addClass('newClass');

How to sort List of objects by some property

Since Java8 this can be done even cleaner using a combination of Comparator and Lambda expressions

For Example:

class Student{

    private String name;
    private List<Score> scores;

    // +accessor methods
}

class Score {

    private int grade;
    // +accessor methods
}

    Collections.sort(student.getScores(), Comparator.comparing(Score::getGrade);

What is the difference between localStorage, sessionStorage, session and cookies?

LocalStorage:

  • Web storage can be viewed simplistically as an improvement on cookies, providing much greater storage capacity. Available size is 5MB which considerably more space to work with than a typical 4KB cookie.

  • The data is not sent back to the server for every HTTP request (HTML, images, JavaScript, CSS, etc) - reducing the amount of traffic between client and server.

  • The data stored in localStorage persists until explicitly deleted. Changes made are saved and available for all current and future visits to the site.

  • It works on same-origin policy. So, data stored will only be available on the same origin.

Cookies:

  • We can set the expiration time for each cookie

  • The 4K limit is for the entire cookie, including name, value, expiry date etc. To support most browsers, keep the name under 4000 bytes, and the overall cookie size under 4093 bytes.

  • The data is sent back to the server for every HTTP request (HTML, images, JavaScript, CSS, etc) - increasing the amount of traffic between client and server.

sessionStorage:

  • It is similar to localStorage.
  • Changes are only available per window (or tab in browsers like Chrome and Firefox). Changes made are saved and available for the current page, as well as future visits to the site on the same window. Once the window is closed, the storage is deleted The data is available only inside the window/tab in which it was set.

  • The data is not persistent i.e. it will be lost once the window/tab is closed. Like localStorage, it works on same-origin policy. So, data stored will only be available on the same origin.

Angular2 multiple router-outlet in the same template

There seems to be another (rather hacky) way to reuse the router-outlet in one template. This answer is intendend for informational purposes only and the techniques used here should probably not be used in production.

https://stackblitz.com/edit/router-outlet-twice-with-events

The router-outlet is wrapped by an ng-template. The template is updated by listening to events of the router. On every event the template is swapped and re-swapped with an empty placeholder. Without this "swapping" the template would not be updated.

This most definetly is not a recommended approach though, since the whole swapping of two templates seems a bit hacky.

in the controller:

  ngOnInit() {
    this.router.events.subscribe((routerEvent: Event) => {
      console.log(routerEvent);
      this.myTemplateRef = this.trigger;
      setTimeout(() => {
        this.myTemplateRef = this.template;
      }, 0);
    });
  }

in the template:

<div class="would-be-visible-on-mobile-only">
  This would be the mobile-layout with a router-outlet (inside a template): 
  <br>
  <ng-container *ngTemplateOutlet="myTemplateRef"></ng-container>
</div>

<hr>

<div class="would-be-visible-on-desktop-only">
  This would be the desktop-layout with a router-outlet (inside a template): 
  <br>
  <ng-container *ngTemplateOutlet="myTemplateRef"></ng-container>
</div>

<ng-template #template>
    <br>
    This is my counter: {{counter}}
    inside the template, the router-outlet should follow
    <router-outlet>
    </router-outlet>
</ng-template>

<ng-template #trigger>
  template to trigger changes...
</ng-template>

Add/remove HTML inside div using JavaScript

To remove node you can try this solution it helped me.

var rslt = (nodee=document.getElementById(id)).parentNode.removeChild(nodee);

Define preprocessor macro through CMake?

To do this for a specific target, you can do the following:

target_compile_definitions(my_target PRIVATE FOO=1 BAR=1)

You should do this if you have more than one target that you're building and you don't want them all to use the same flags. Also see the official documentation on target_compile_definitions.

How can I capitalize the first letter of each word in a string using JavaScript?

I usually prefer not to use regexp because of readability and also I try to stay away from loops. I think this is kind of readable.

function capitalizeFirstLetter(string) {
    return string && string.charAt(0).toUpperCase() + string.substring(1);
};

Get file path of image on Android

use this function to get the capture image path

protected void onActivityResult(int requestCode, int resultCode, Intent data) {  
        if (requestCode == CAMERA_REQUEST && resultCode == RESULT_OK) {  
            Uri mImageCaptureUri = intent.getData();
            Bitmap photo = (Bitmap) data.getExtras().get("data"); 
            imageView.setImageBitmap(photo);
            knop.setVisibility(Button.VISIBLE);
            System.out.println(mImageCaptureUri);
           //getImgPath(mImageCaptureUri);// it will return the Capture image path
        }  
    }

public String getImgPath(Uri uri) {
        String[] largeFileProjection = { MediaStore.Images.ImageColumns._ID,
                MediaStore.Images.ImageColumns.DATA };
        String largeFileSort = MediaStore.Images.ImageColumns._ID + " DESC";
        Cursor myCursor = this.managedQuery(
                MediaStore.Images.Media.EXTERNAL_CONTENT_URI,
                largeFileProjection, null, null, largeFileSort);
        String largeImagePath = "";
        try {
            myCursor.moveToFirst();
            largeImagePath = myCursor
                    .getString(myCursor
                            .getColumnIndexOrThrow(MediaStore.Images.ImageColumns.DATA));
        } finally {
            myCursor.close();
        }
        return largeImagePath;
    }

Join String list elements with a delimiter in one step

You can use : org.springframework.util.StringUtils;

String stringDelimitedByComma = StringUtils.collectionToCommaDelimitedString(myList);

Is there a limit on number of tcp/ip connections between machines on linux?

When looking for the max performance you run into a lot of issue and potential bottlenecks. Running a simple hello world test is not necessarily going to find them all.

Possible limitations include:

  • Kernel socket limitations: look in /proc/sys/net for lots of kernel tuning..
  • process limits: check out ulimit as others have stated here
  • as your application grows in complexity, it may not have enough CPU power to keep up with the number of connections coming in. Use top to see if your CPU is maxed
  • number of threads? I'm not experienced with threading, but this may come into play in conjunction with the previous items.

Time stamp in the C programming language

Standard C99:

#include <time.h>

time_t t0 = time(0);
// ...
time_t t1 = time(0);
double datetime_diff_ms = difftime(t1, t0) * 1000.;

clock_t c0 = clock();
// ...
clock_t c1 = clock();
double runtime_diff_ms = (c1 - c0) * 1000. / CLOCKS_PER_SEC;

The precision of the types is implementation-defined, ie the datetime difference might only return full seconds.

Setting an HTML text input box's "default" value. Revert the value when clicking ESC

If the question is: "Is it possible to add value on ESC" than the answer is yes. You can do something like that. For example with use of jQuery it would look like below.

HTML

<script src="//ajax.googleapis.com/ajax/libs/jquery/1.7.1/jquery.min.js" type="text/javascript"></script>

<input type="text" value="default!" id="myInput" />

JavaScript

$(document).ready(function (){
    $('#myInput').keyup(function(event) {
        // 27 is key code of ESC
        if (event.keyCode == 27) {
            $('#myInput').val('default!');
            // Loose focus on input field
            $('#myInput').blur();
        }
    });
});

Working source can be found here: http://jsfiddle.net/S3N5H/1/

Please let me know if you meant something different, I can adjust the code later.

Div 100% height works on Firefox but not in IE

I've been successful in getting this to work when I set the margins of the container to 0:

#container
{
   margin: 0 px;
}

in addition to all your other styles

Difference between Inheritance and Composition

Inheritence means reusing the complete functionality of a class, Here my class have to use all the methods of the super class and my class will be titely coupled with the super class and code will be duplicated in both the classes in case of inheritence.

But we can overcome from all these problem when we use composition to talk with another class . composition is declaring an attribute of another class into my class to which we want to talk. and what functionality we want from that class we can get by using that attribute.

NotificationCenter issue on Swift 3

Swift 3 & 4

Swift 3, and now Swift 4, have replaced many "stringly-typed" APIs with struct "wrapper types", as is the case with NotificationCenter. Notifications are now identified by a struct Notfication.Name rather than by String. For more details see the now legacy Migrating to Swift 3 guide

Swift 2.2 usage:

// Define identifier
let notificationIdentifier: String = "NotificationIdentifier"

// Register to receive notification
NSNotificationCenter.defaultCenter().addObserver(self, selector: #selector(YourClassName.methodOfReceivedNotification(_:)), name: notificationIdentifier, object: nil)

// Post a notification
NSNotificationCenter.defaultCenter().postNotificationName(notificationIdentifier, object: nil)

Swift 3 & 4 usage:

// Define identifier
let notificationName = Notification.Name("NotificationIdentifier")

// Register to receive notification
NotificationCenter.default.addObserver(self, selector: #selector(YourClassName.methodOfReceivedNotification), name: notificationName, object: nil)

// Post notification
NotificationCenter.default.post(name: notificationName, object: nil)

// Stop listening notification
NotificationCenter.default.removeObserver(self, name: notificationName, object: nil)

All of the system notification types are now defined as static constants on Notification.Name; i.e. .UIApplicationDidFinishLaunching, .UITextFieldTextDidChange, etc.

You can extend Notification.Name with your own custom notifications in order to stay consistent with the system notifications:

// Definition:
extension Notification.Name {
    static let yourCustomNotificationName = Notification.Name("yourCustomNotificationName")
}

// Usage:
NotificationCenter.default.post(name: .yourCustomNotificationName, object: nil)

Swift 4.2 usage:

Same as Swift 4, except now system notifications names are part of UIApplication. So in order to stay consistent with the system notifications you can extend UIApplication with your own custom notifications instead of Notification.Name :

// Definition:
UIApplication {
    public static let yourCustomNotificationName = Notification.Name("yourCustomNotificationName")
}

// Usage:
NotificationCenter.default.post(name: UIApplication.yourCustomNotificationName, object: nil)

curl: (60) SSL certificate problem: unable to get local issuer certificate

I have solved this problem by adding one line code in cURL script:

curl_setopt($ch, CURLOPT_SSL_VERIFYPEER, false);

Warning: This makes the request absolute insecure (see answer by @YSU)!

Variable number of arguments in C++?

Using variadic templates, example to reproduce console.log as seen in JavaScript:

Console console;
console.log("bunch", "of", "arguments");
console.warn("or some numbers:", 1, 2, 3);
console.error("just a prank", "bro");

Filename e.g. js_console.h:

#include <iostream>
#include <utility>

class Console {
protected:
    template <typename T>
    void log_argument(T t) {
        std::cout << t << " ";
    }
public:
    template <typename... Args>
    void log(Args&&... args) {
        int dummy[] = { 0, ((void) log_argument(std::forward<Args>(args)),0)... };
        cout << endl;
    }

    template <typename... Args>
    void warn(Args&&... args) {
        cout << "WARNING: ";
        int dummy[] = { 0, ((void) log_argument(std::forward<Args>(args)),0)... };
        cout << endl;
    }

    template <typename... Args>
    void error(Args&&... args) {
        cout << "ERROR: ";
        int dummy[] = { 0, ((void) log_argument(std::forward<Args>(args)),0)... };
        cout << endl;
    }
};

WELD-001408: Unsatisfied dependencies for type Customer with qualifiers @Default

Your Customer class has to be discovered by CDI as a bean. For that you have two options:

  1. Put a bean defining annotation on it. As @Model is a stereotype it's why it does the trick. A qualifier like @Named is not a bean defining annotation, reason why it doesn't work

  2. Change the bean discovery mode in your bean archive from the default "annotated" to "all" by adding a beans.xml file in your jar.

Keep in mind that @Named has only one usage : expose your bean to the UI. Other usages are for bad practice or compatibility with legacy framework.

Web.Config Debug/Release

To make the transform work in development (using F5 or CTRL + F5) I drop ctt.exe (https://ctt.codeplex.com/) in the packages folder (packages\ConfigTransform\ctt.exe).

Then I register a pre- or post-build event in Visual Studio...

$(SolutionDir)packages\ConfigTransform\ctt.exe source:"$(ProjectDir)connectionStrings.config" transform:"$(ProjectDir)connectionStrings.$(ConfigurationName).config" destination:"$(ProjectDir)connectionStrings.config"
$(SolutionDir)packages\ConfigTransform\ctt.exe source:"$(ProjectDir)web.config" transform:"$(ProjectDir)web.$(ConfigurationName).config" destination:"$(ProjectDir)web.config"

For the transforms I use SlowCheeta VS extension (https://visualstudiogallery.msdn.microsoft.com/69023d00-a4f9-4a34-a6cd-7e854ba318b5).

Using Linq select list inside list

After my previous answer disaster, I'm going to try something else.

List<Model> usrList  = 
(list.Where(n => n.application == "applicationame").ToList());
usrList.ForEach(n => n.users.RemoveAll(n => n.surname != "surname"));

How to fetch the row count for all tables in a SQL SERVER database

SELECT 
    sc.name +'.'+ ta.name TableName, SUM(pa.rows) RowCnt
FROM 
    sys.tables ta
INNER JOIN sys.partitions pa
    ON pa.OBJECT_ID = ta.OBJECT_ID
INNER JOIN sys.schemas sc
    ON ta.schema_id = sc.schema_id
WHERE ta.is_ms_shipped = 0 AND pa.index_id IN (1,0)
GROUP BY sc.name,ta.name
ORDER BY SUM(pa.rows) DESC

C: printf a float value

printf("%.<number>f", myFloat) //where <number> - digit after comma

http://www.cplusplus.com/reference/clibrary/cstdio/printf/

How can I calculate divide and modulo for integers in C#?

There is also Math.DivRem

quotient = Math.DivRem(dividend, divisor, out remainder);

SQL Network Interfaces, error: 26 - Error Locating Server/Instance Specified

i had this issue, and fixed it. the problem seemed to be this:

wrong:

<add key="aaa" value="server=[abc\SQL2K8];database=bbb;uid=ccc;password=ddd;" />

right

<add key="aaa" value="server=abc\SQL2K8;database=bbb;uid=ccc;password=ddd;" />

Rails: How do I create a default value for attributes in Rails activerecord's model?

I found a better way to do it now:

def status=(value) 
  self[:status] = 'P' 
end 

In Ruby a method call is allowed to have no parentheses, therefore I should name the local variable into something else, otherwise Ruby will recognize it as a method call.

Why check both isset() and !empty()

It is not necessary.

No warning is generated if the variable does not exist. That means empty() is essentially the concise equivalent to !isset($var) || $var == false.

php.net

blur() vs. onblur()

Contrary to what pointy says, the blur() method does exist and is a part of the w3c standard. The following exaple will work in every modern browser (including IE):

<!DOCTYPE HTML PUBLIC "-//W3C//DTD HTML 4.01//EN" "http://www.w3.org/TR/html4/strict.dtd">
<html>
    <head>
        <title>Javascript test</title>
        <script type="text/javascript" language="javascript">
            window.onload = function()
            {
                var field = document.getElementById("field");
                var link = document.getElementById("link");
                var output = document.getElementById("output");

                field.onfocus = function() { output.innerHTML += "<br/>field.onfocus()"; };
                field.onblur = function() { output.innerHTML += "<br/>field.onblur()"; };
                link.onmouseover = function() { field.blur(); };
            };
        </script>
    </head>
    <body>
        <form name="MyForm">
            <input type="text" name="field" id="field" />
            <a href="javascript:void(0);" id="link">Blur field on hover</a>
            <div id="output"></div>
        </form>
    </body>
</html>

Note that I used link.onmouseover instead of link.onclick, because otherwise the click itself would have removed the focus.

What is console.log in jQuery?

It has nothing to do with jQuery, it's just a handy js method built into modern browsers.

Think of it as a handy alternative to debugging via window.alert()

cin and getline skipping input

Here, the '\n' left by cin, is creating issues.

do {
    system("cls");
    manageCustomerMenu();
    cin >> choice;               #This cin is leaving a trailing \n
    system("cls");

    switch (choice) {
        case '1':
            createNewCustomer();
            break;

This \n is being consumed by next getline in createNewCustomer(). You should use getline instead -

do {
    system("cls");
    manageCustomerMenu();
    getline(cin, choice)               
    system("cls");

    switch (choice) {
        case '1':
            createNewCustomer();
            break;

I think this would resolve the issue.

How to run bootRun with spring profile via gradle task

Configuration for 4 different task with different profiles and gradle tasks dependencies:

  • bootRunLocal and bootRunDev - run with specific profile
  • bootPostgresRunLocal and bootPostgresRunDev same as prev, but executing custom task runPostgresDocker and killPostgresDocker before/after bootRun

build.gradle:

final LOCAL='local'
final DEV='dev'

void configBootTask(Task bootTask, String profile) {
    bootTask.main = bootJar.mainClassName
    bootTask.classpath = sourceSets.main.runtimeClasspath

    bootTask.args = [ "--spring.profiles.active=$profile" ]
//    systemProperty 'spring.profiles.active', profile // this approach also may be used
    bootTask.environment = postgresLocalEnvironment
}

bootRun {
    description "Run Spring boot application with \"$LOCAL\" profile"
    doFirst() {
        configBootTask(it, LOCAL)
    }
}

task bootRunLocal(type: BootRun, dependsOn: 'classes') {
    description "Alias to \":${bootRun.name}\" task: ${bootRun.description}"
    doFirst() {
        configBootTask(it, LOCAL)
    }
}

task bootRunDev(type: BootRun, dependsOn: 'classes') {
    description "Run Spring boot application with \"$DEV\" profile"
    doFirst() {
        configBootTask(it, DEV)
    }
}

task bootPostgresRunLocal(type: BootRun) {
    description "Run Spring boot application with \"$LOCAL\" profile and re-creating DB Postgres container"
    dependsOn runPostgresDocker
    finalizedBy killPostgresDocker
    doFirst() {
        configBootTask(it, LOCAL)
    }
}

task bootPostgresRunDev(type: BootRun) {
    description "Run Spring boot application with \"$DEV\" profile and re-creating DB Postgres container"
    dependsOn runPostgresDocker
    finalizedBy killPostgresDocker
    doFirst() {
        configBootTask(it, DEV)
    }
}

/usr/bin/ld: cannot find

@Alwin Doss You should provide the -L option before -l. You would have done the other way round probably. Try this :)

Check if a string is a palindrome

Shortest technique to find Palindrome using conventional way

public string IsPalindrome(string Word)
{
    int i = 0, j = Word.Length - 1;
    for (; i < Word.Length - 1 && j >= 0 && Word[i] == Word[j]; i++, j--) ;
    return j == 0 ? "Palindrome" : "Not Palindrome";
}

Gradle - Could not find or load main class

  1. verify if gradle.properties define right one JAVA_HOVE

    org.gradle.java.home=C:\Program Files (x86)\Java\jdk1.8.0_181

or

  1. if it's not defined be sure if Eclipse know JDK and not JRE

enter image description here

JavaScript backslash (\) in variables is causing an error

The backslash \ is reserved for use as an escape character in Javascript.

To use a backslash literally you need to use two backslashes

\\

String to decimal conversion: dot separation instead of comma

    usCulture = new CultureInfo("vi-VN");
Thread.CurrentThread.CurrentCulture = usCulture;
Thread.CurrentThread.CurrentUICulture = usCulture;
usCulture = Thread.CurrentThread.CurrentCulture;
dbNumberFormat = usCulture.NumberFormat;
number = decimal.Parse("1.332,23", dbNumberFormat); //123.456.789,00

usCulture = new CultureInfo("en-GB");
Thread.CurrentThread.CurrentCulture = usCulture;
Thread.CurrentThread.CurrentUICulture = usCulture;
usCulture = Thread.CurrentThread.CurrentCulture;
dbNumberFormat = usCulture.NumberFormat;
number = decimal.Parse("1,332.23", dbNumberFormat); //123.456.789,00

/*Decision*/
var usCulture = Thread.CurrentThread.CurrentCulture;
var dbNumberFormat = usCulture.NumberFormat;
decimal number;
decimal.TryParse("1,332.23", dbNumberFormat, out number); //123.456.789,00

SQL Insert Multiple Rows

For MSSQL, there are two ways:(Consider you have a 'users' table,below both examples are using this table for example)

1) In case, you need to insert different values in users table. Then you can write statement like:

    INSERT INTO USERS VALUES
(2, 'Michael', 'Blythe'),
(3, 'Linda', 'Mitchell'),
(4, 'Jillian', 'Carson'),
(5, 'Garrett', 'Vargas');

2) Another case, if you need to insert same value for all rows(for example, 10 rows you need to insert here). Then you can use below sample statement:

    INSERT INTO USERS VALUES
(2, 'Michael', 'Blythe')
GO 10

Hope this helps.

How to convert a String to long in javascript?

JavaScript has a Number type which is a 64 bit floating point number*.

If you're looking to convert a string to a number, use

  1. either parseInt or parseFloat. If using parseInt, I'd recommend always passing the radix too.
  2. use the Unary + operator e.g. +"123456"
  3. use the Number constructor e.g. var n = Number("12343")

*there are situations where the number will internally be held as an integer.

How do you echo a 4-digit Unicode character in Bash?

In Bash:

UnicodePointToUtf8()
{
    local x="$1"               # ok if '0x2620'
    x=${x/\\u/0x}              # '\u2620' -> '0x2620'
    x=${x/U+/0x}; x=${x/u+/0x} # 'U-2620' -> '0x2620'
    x=$((x)) # from hex to decimal
    local y=$x n=0
    [ $x -ge 0 ] || return 1
    while [ $y -gt 0 ]; do y=$((y>>1)); n=$((n+1)); done
    if [ $n -le 7 ]; then       # 7
        y=$x
    elif [ $n -le 11 ]; then    # 5+6
        y=" $(( ((x>> 6)&0x1F)+0xC0 )) \
            $(( (x&0x3F)+0x80 ))" 
    elif [ $n -le 16 ]; then    # 4+6+6
        y=" $(( ((x>>12)&0x0F)+0xE0 )) \
            $(( ((x>> 6)&0x3F)+0x80 )) \
            $(( (x&0x3F)+0x80 ))"
    else                        # 3+6+6+6
        y=" $(( ((x>>18)&0x07)+0xF0 )) \
            $(( ((x>>12)&0x3F)+0x80 )) \
            $(( ((x>> 6)&0x3F)+0x80 )) \
            $(( (x&0x3F)+0x80 ))"
    fi
    printf -v y '\\x%x' $y
    echo -n -e $y
}

# test
for (( i=0x2500; i<0x2600; i++ )); do
    UnicodePointToUtf8 $i
    [ "$(( i+1 & 0x1f ))" != 0 ] || echo ""
done
x='U+2620'
echo "$x -> $(UnicodePointToUtf8 $x)"

Output:

-?¦?????????+???+???+???+???+???
????¦???????-???????-???????+???
????????????????-¦++++++++++++¦¦
¦¦¦¦------+++???????????????????
¯???_???¦???¦???¦¦¦¦????????????
¦???????????????????????????????
????????????????????????????????
????????????????????????????????
U+2620 -> ?

Using Google Text-To-Speech in Javascript

You can use the SpeechSynthesisUtterance with a function like say:

function say(m) {
  var msg = new SpeechSynthesisUtterance();
  var voices = window.speechSynthesis.getVoices();
  msg.voice = voices[10];
  msg.voiceURI = "native";
  msg.volume = 1;
  msg.rate = 1;
  msg.pitch = 0.8;
  msg.text = m;
  msg.lang = 'en-US';
  speechSynthesis.speak(msg);
}

Then you only need to call say(msg) when using it.

Update: Look at Google's Developer Blog that is about Voice Driven Web Apps Introduction to the Web Speech API.

Intellisense and code suggestion not working in Visual Studio 2012 Ultimate RC

Sometime your code syntax has error, like you use " in ", it must be " ...'...." For help you quickly detect problems, you click Design button, vs try to render, and it will show the line of error

How do I rename the extension for a bunch of files?

Nice & simple!

find . -iname *.html  -exec mv {} "$(basename {} .html).text"  \;

Can not get a simple bootstrap modal to work

A simple way to use modals is with eModal!

Ex from github:

  1. Link to eModal.js <script src="//rawgit.com/saribe/eModal/master/dist/eModal.min.js"></script>
  2. use eModal to display a modal for alert, ajax, prompt or confirm

    // Display an alert modal with default title (Attention)
    eModal.alert('You shall not pass!');