Programs & Examples On #Sdo

Service Data Objects is a technology that allows heterogeneous data to be accessed in a uniform way.

Message "Async callback was not invoked within the 5000 ms timeout specified by jest.setTimeout"

You can also get timeout errors based on silly typos. e.g This seemingly innocuous mistake:

describe('Something', () => {
  it('Should do something', () => {
    expect(1).toEqual(1)
  })

  it('Should do nothing', something_that_does_not_exist => {
    expect(1).toEqual(1)
  })
})

Produces the following error:

FAIL src/TestNothing.spec.js (5.427s)
  ? Something › Should do nothing

    Timeout - Async callback was not invoked within the 5000ms timeout specified by jest.setTimeout.
      
      at node_modules/jest-jasmine2/build/queue_runner.js:68:21
      at Timeout.callback [as _onTimeout] (node_modules/jsdom/lib/jsdom/browser/Window.js:678:19)

Whilst the code sample posted doesn't suffer from this it might be a cause of failures elsewhere. Also note that I'm not setting a timeout for anything anywhere - either here or in the config. The 5000ms is just the default setting.

'react-scripts' is not recognized as an internal or external command

In my situation, some problems happened with my node package. So I run npm audit fix and it fixed all problems

How to solve npm install throwing fsevents warning on non-MAC OS?

If you want to hide this warn, you just need to install fsevents as a optional dependency. Just execute:

npm i fsevents@latest -f --save-optional

..And the warn will no longer be a bother.

Get Path from another app (WhatsApp)

It works for me for opening small text file... I didn't try in other file

protected void viewhelper(Intent intent) {
    Uri a = intent.getData();
    if (!a.toString().startsWith("content:")) {
        return;
    }
    //Ok Let's do it
    String content = readUri(a);
    //do something with this content
}

here is the readUri(Uri uri) method

private String readUri(Uri uri) {
    InputStream inputStream = null;
    try {
        inputStream = getContentResolver().openInputStream(uri);
        if (inputStream != null) {
            byte[] buffer = new byte[1024];
            int result;
            String content = "";
            while ((result = inputStream.read(buffer)) != -1) {
                content = content.concat(new String(buffer, 0, result));
            }
            return content;
        }
    } catch (IOException e) {
        Log.e("receiver", "IOException when reading uri", e);
    } finally {
        if (inputStream != null) {
            try {
                inputStream.close();
            } catch (IOException e) {
                Log.e("receiver", "IOException when closing stream", e);
            }
        }
    }
    return null;
}

I got it from this repository https://github.com/zhutq/android-file-provider-demo/blob/master/FileReceiver/app/src/main/java/com/demo/filereceiver/MainActivity.java
I modified some code so that it work.

Manifest file:

    <activity android:name=".MainActivity">
        <intent-filter >
            <action android:name="android.intent.action.VIEW" />
            <category android:name="android.intent.category.DEFAULT" />
            <data android:mimeType="*/*" />
        </intent-filter>
    </activity>

You need to add

@Override
protected void onCreate(Bundle savedInstanceState) {
    /*
     *    Your OnCreate
     */
    Intent intent = getIntent();
    String action = intent.getAction();
    String type = intent.getType();

    //VIEW"
    if (Intent.ACTION_VIEW.equals(action) && type != null) {
        viewhelper(intent); // Handle text being sent
    }
  }

react router v^4.0.0 Uncaught TypeError: Cannot read property 'location' of undefined

Replace

import { Router, Route, Link, browserHistory } from 'react-router';

With

import { BrowserRouter as Router, Route } from 'react-router-dom';

It will start working. It is because react-router-dom exports BrowserRouter

Disable eslint rules for folder

The previous answers were in the right track, but the complete answer for this is going to Disabling rules only for a group of files, there you'll find the documentation needed to disable/enable rules for certain folders (Because in some cases you don't want to ignore the whole thing, only disable certain rules). Example:

{
    "env": {},
    "extends": [],
    "parser": "",
    "plugins": [],
    "rules": {},
    "overrides": [
      {
        "files": ["test/*.spec.js"], // Or *.test.js
        "rules": {
          "require-jsdoc": "off"
        }
      }
    ],
    "settings": {}
}

Why does C++ code for testing the Collatz conjecture run faster than hand-written assembly?

Claiming that the C++ compiler can produce more optimal code than a competent assembly language programmer is a very bad mistake. And especially in this case. The human always can make the code better than the compiler can, and this particular situation is a good illustration of this claim.

The timing difference you're seeing is because the assembly code in the question is very far from optimal in the inner loops.

(The below code is 32-bit, but can be easily converted to 64-bit)

For example, the sequence function can be optimized to only 5 instructions:

    .seq:
        inc     esi                 ; counter
        lea     edx, [3*eax+1]      ; edx = 3*n+1
        shr     eax, 1              ; eax = n/2
        cmovc   eax, edx            ; if CF eax = edx
        jnz     .seq                ; jmp if n<>1

The whole code looks like:

include "%lib%/freshlib.inc"
@BinaryType console, compact
options.DebugMode = 1
include "%lib%/freshlib.asm"

start:
        InitializeAll
        mov ecx, 999999
        xor edi, edi        ; max
        xor ebx, ebx        ; max i

    .main_loop:

        xor     esi, esi
        mov     eax, ecx

    .seq:
        inc     esi                 ; counter
        lea     edx, [3*eax+1]      ; edx = 3*n+1
        shr     eax, 1              ; eax = n/2
        cmovc   eax, edx            ; if CF eax = edx
        jnz     .seq                ; jmp if n<>1

        cmp     edi, esi
        cmovb   edi, esi
        cmovb   ebx, ecx

        dec     ecx
        jnz     .main_loop

        OutputValue "Max sequence: ", edi, 10, -1
        OutputValue "Max index: ", ebx, 10, -1

        FinalizeAll
        stdcall TerminateAll, 0

In order to compile this code, FreshLib is needed.

In my tests, (1 GHz AMD A4-1200 processor), the above code is approximately four times faster than the C++ code from the question (when compiled with -O0: 430 ms vs. 1900 ms), and more than two times faster (430 ms vs. 830 ms) when the C++ code is compiled with -O3.

The output of both programs is the same: max sequence = 525 on i = 837799.

npm start error with create-react-app

I solve this issue by running following command

echo fs.inotify.max_user_watches=524288 | sudo tee -a /etc/sysctl.conf && sudo sysctl -p

hope it helps

Uncaught TypeError: $(...).datepicker is not a function(anonymous function)

if you are using ASP.NET MVC

Open the layout file "_Layout.cshtml" or your custom one

At the part of the code you see, as below:

@Scripts.Render("~/bundles/bootstrap")
@RenderSection("scripts", required: false)
@Scripts.Render("~/bundles/jquery")

Remove the line "@Scripts.Render("~/bundles/jquery")"

(at the part of the code you see) past as the latest line, as below:

@Styles.Render("~/Content/css")
@Scripts.Render("~/bundles/modernizr")
@Scripts.Render("~/bundles/jquery")

This help me and hope helps you as well.

How to add a recyclerView inside another recyclerView

I would like to suggest to use a single RecyclerView and populate your list items dynamically. I've added a github project to describe how this can be done. You might have a look. While the other solutions will work just fine, I would like to suggest, this is a much faster and efficient way of showing multiple lists in a RecyclerView.

The idea is to add logic in your onCreateViewHolder and onBindViewHolder method so that you can inflate proper view for the exact positions in your RecyclerView.

I've added a sample project along with that wiki too. You might clone and check what it does. For convenience, I am posting the adapter that I have used.

public class DynamicListAdapter extends RecyclerView.Adapter<RecyclerView.ViewHolder> {

    private static final int FOOTER_VIEW = 1;
    private static final int FIRST_LIST_ITEM_VIEW = 2;
    private static final int FIRST_LIST_HEADER_VIEW = 3;
    private static final int SECOND_LIST_ITEM_VIEW = 4;
    private static final int SECOND_LIST_HEADER_VIEW = 5;

    private ArrayList<ListObject> firstList = new ArrayList<ListObject>();
    private ArrayList<ListObject> secondList = new ArrayList<ListObject>();

    public DynamicListAdapter() {
    }

    public void setFirstList(ArrayList<ListObject> firstList) {
        this.firstList = firstList;
    }

    public void setSecondList(ArrayList<ListObject> secondList) {
        this.secondList = secondList;
    }

    public class ViewHolder extends RecyclerView.ViewHolder {
        // List items of first list
        private TextView mTextDescription1;
        private TextView mListItemTitle1;

        // List items of second list
        private TextView mTextDescription2;
        private TextView mListItemTitle2;

        // Element of footer view
        private TextView footerTextView;

        public ViewHolder(final View itemView) {
            super(itemView);

            // Get the view of the elements of first list
            mTextDescription1 = (TextView) itemView.findViewById(R.id.description1);
            mListItemTitle1 = (TextView) itemView.findViewById(R.id.title1);

            // Get the view of the elements of second list
            mTextDescription2 = (TextView) itemView.findViewById(R.id.description2);
            mListItemTitle2 = (TextView) itemView.findViewById(R.id.title2);

            // Get the view of the footer elements
            footerTextView = (TextView) itemView.findViewById(R.id.footer);
        }

        public void bindViewSecondList(int pos) {

            if (firstList == null) pos = pos - 1;
            else {
                if (firstList.size() == 0) pos = pos - 1;
                else pos = pos - firstList.size() - 2;
            }

            final String description = secondList.get(pos).getDescription();
            final String title = secondList.get(pos).getTitle();

            mTextDescription2.setText(description);
            mListItemTitle2.setText(title);
        }

        public void bindViewFirstList(int pos) {

            // Decrease pos by 1 as there is a header view now.
            pos = pos - 1;

            final String description = firstList.get(pos).getDescription();
            final String title = firstList.get(pos).getTitle();

            mTextDescription1.setText(description);
            mListItemTitle1.setText(title);
        }

        public void bindViewFooter(int pos) {
            footerTextView.setText("This is footer");
        }
    }

    public class FooterViewHolder extends ViewHolder {
        public FooterViewHolder(View itemView) {
            super(itemView);
        }
    }

    private class FirstListHeaderViewHolder extends ViewHolder {
        public FirstListHeaderViewHolder(View itemView) {
            super(itemView);
        }
    }

    private class FirstListItemViewHolder extends ViewHolder {
        public FirstListItemViewHolder(View itemView) {
            super(itemView);
        }
    }

    private class SecondListHeaderViewHolder extends ViewHolder {
        public SecondListHeaderViewHolder(View itemView) {
            super(itemView);
        }
    }

    private class SecondListItemViewHolder extends ViewHolder {
        public SecondListItemViewHolder(View itemView) {
            super(itemView);
        }
    }

    @Override
    public RecyclerView.ViewHolder onCreateViewHolder(ViewGroup parent, int viewType) {

        View v;

        if (viewType == FOOTER_VIEW) {
            v = LayoutInflater.from(parent.getContext()).inflate(R.layout.list_item_footer, parent, false);
            FooterViewHolder vh = new FooterViewHolder(v);
            return vh;

        } else if (viewType == FIRST_LIST_ITEM_VIEW) {
            v = LayoutInflater.from(parent.getContext()).inflate(R.layout.list_item_first_list, parent, false);
            FirstListItemViewHolder vh = new FirstListItemViewHolder(v);
            return vh;

        } else if (viewType == FIRST_LIST_HEADER_VIEW) {
            v = LayoutInflater.from(parent.getContext()).inflate(R.layout.list_item_first_list_header, parent, false);
            FirstListHeaderViewHolder vh = new FirstListHeaderViewHolder(v);
            return vh;

        } else if (viewType == SECOND_LIST_HEADER_VIEW) {
            v = LayoutInflater.from(parent.getContext()).inflate(R.layout.list_item_second_list_header, parent, false);
            SecondListHeaderViewHolder vh = new SecondListHeaderViewHolder(v);
            return vh;

        } else {
            // SECOND_LIST_ITEM_VIEW
            v = LayoutInflater.from(parent.getContext()).inflate(R.layout.list_item_second_list, parent, false);
            SecondListItemViewHolder vh = new SecondListItemViewHolder(v);
            return vh;
        }
    }

    @Override
    public void onBindViewHolder(RecyclerView.ViewHolder holder, int position) {

        try {
            if (holder instanceof SecondListItemViewHolder) {
                SecondListItemViewHolder vh = (SecondListItemViewHolder) holder;
                vh.bindViewSecondList(position);

            } else if (holder instanceof FirstListHeaderViewHolder) {
                FirstListHeaderViewHolder vh = (FirstListHeaderViewHolder) holder;

            } else if (holder instanceof FirstListItemViewHolder) {
                FirstListItemViewHolder vh = (FirstListItemViewHolder) holder;
                vh.bindViewFirstList(position);

            } else if (holder instanceof SecondListHeaderViewHolder) {
                SecondListHeaderViewHolder vh = (SecondListHeaderViewHolder) holder;

            } else if (holder instanceof FooterViewHolder) {
                FooterViewHolder vh = (FooterViewHolder) holder;
                vh.bindViewFooter(position);
            }
        } catch (Exception e) {
            e.printStackTrace();
        }
    }

    @Override
    public int getItemCount() {

        int firstListSize = 0;
        int secondListSize = 0;

        if (secondList == null && firstList == null) return 0;

        if (secondList != null)
            secondListSize = secondList.size();
        if (firstList != null)
            firstListSize = firstList.size();

        if (secondListSize > 0 && firstListSize > 0)
            return 1 + firstListSize + 1 + secondListSize + 1;   // first list header, first list size, second list header , second list size, footer
        else if (secondListSize > 0 && firstListSize == 0)
            return 1 + secondListSize + 1;                       // second list header, second list size, footer
        else if (secondListSize == 0 && firstListSize > 0)
            return 1 + firstListSize;                            // first list header , first list size
        else return 0;
    }

    @Override
    public int getItemViewType(int position) {

        int firstListSize = 0;
        int secondListSize = 0;

        if (secondList == null && firstList == null)
            return super.getItemViewType(position);

        if (secondList != null)
            secondListSize = secondList.size();
        if (firstList != null)
            firstListSize = firstList.size();

        if (secondListSize > 0 && firstListSize > 0) {
            if (position == 0) return FIRST_LIST_HEADER_VIEW;
            else if (position == firstListSize + 1)
                return SECOND_LIST_HEADER_VIEW;
            else if (position == secondListSize + 1 + firstListSize + 1)
                return FOOTER_VIEW;
            else if (position > firstListSize + 1)
                return SECOND_LIST_ITEM_VIEW;
            else return FIRST_LIST_ITEM_VIEW;

        } else if (secondListSize > 0 && firstListSize == 0) {
            if (position == 0) return SECOND_LIST_HEADER_VIEW;
            else if (position == secondListSize + 1) return FOOTER_VIEW;
            else return SECOND_LIST_ITEM_VIEW;

        } else if (secondListSize == 0 && firstListSize > 0) {
            if (position == 0) return FIRST_LIST_HEADER_VIEW;
            else return FIRST_LIST_ITEM_VIEW;
        }

        return super.getItemViewType(position);
    }
}

There is another way of keeping your items in a single ArrayList of objects so that you can set an attribute tagging the items to indicate which item is from first list and which one belongs to second list. Then pass that ArrayList into your RecyclerView and then implement the logic inside adapter to populate them dynamically.

Hope that helps.

jQuery ajax request being block because Cross-Origin

Try to use JSONP in your Ajax call. It will bypass the Same Origin Policy.

http://learn.jquery.com/ajax/working-with-jsonp/

Try example

$.ajax({
    url: "https://api.dailymotion.com/video/x28j5hv?fields=title",

    dataType: "jsonp",
    success: function( response ) {
        console.log( response ); // server response
    }

});

Unknown URL content://downloads/my_downloads

The exception is caused by disabled Download Manager. And there is no way to activate/deactivate Download Manager directly, since it's system application and we don't have access to it.

Only alternative way is redirect user to settings of Download Manager Application.

try {
     //Open the specific App Info page:
     Intent intent = new Intent(android.provider.Settings.ACTION_APPLICATION_DETAILS_SETTINGS);
     intent.setData(Uri.parse("package:" + "com.android.providers.downloads"));
     startActivity(intent);

} catch ( ActivityNotFoundException e ) {
     e.printStackTrace();

     //Open the generic Apps page:
     Intent intent = new Intent(android.provider.Settings.ACTION_MANAGE_APPLICATIONS_SETTINGS);
     startActivity(intent);
}

java.lang.NullPointerException: Attempt to invoke virtual method 'int android.view.View.getImportantForAccessibility()' on a null object reference

it sometimes occurs when we use a custom adapter in any activity of fragment . and we return null object i.e null view so the activity gets confused which view to load , so that is why this exception occurs

shows the position where to change the view

Solve Cross Origin Resource Sharing with Flask

Well, I faced the same issue. For new users who may land at this page. Just follow their official documentation.

Install flask-cors

pip install -U flask-cors

then after app initialization, initialize flask-cors with default arguments:

from flask import Flask
from flask_cors import CORS

app = Flask(__name__)
CORS(app)

@app.route("/")
def helloWorld():
   return "Hello, cross-origin-world!"

There is already an object named in the database

I had same problem and after three hour struggling I find out what's going on

In my case, when I wanted to migrate for the first time in up() method, the default code wants to create the tables that already existed so I got same error as you

To solve it, just delete those code and write want you want. For example, I wanted to add a column so i just write

migrationBuilder.AddColumn<string>(
            name: "fieldName",
            table: "tableName",
            nullable: true);

How to enable CORS in flask

Improving the solution described here: https://stackoverflow.com/a/52875875/10299604

With after_request we can handle the CORS response headers avoiding to add extra code to our endpoints:

    ### CORS section
    @app.after_request
    def after_request_func(response):
        origin = request.headers.get('Origin')
        if request.method == 'OPTIONS':
            response = make_response()
            response.headers.add('Access-Control-Allow-Credentials', 'true')
            response.headers.add('Access-Control-Allow-Headers', 'Content-Type')
            response.headers.add('Access-Control-Allow-Headers', 'x-csrf-token')
            response.headers.add('Access-Control-Allow-Methods',
                                'GET, POST, OPTIONS, PUT, PATCH, DELETE')
            if origin:
                response.headers.add('Access-Control-Allow-Origin', origin)
        else:
            response.headers.add('Access-Control-Allow-Credentials', 'true')
            if origin:
                response.headers.add('Access-Control-Allow-Origin', origin)

        return response
    ### end CORS section

How to make Bootstrap Panel body with fixed height

HTML :

<div class="span4">
  <div class="panel panel-primary">
    <div class="panel-heading">jhdsahfjhdfhs</div>
    <div class="panel-body panel-height">fdoinfds sdofjohisdfj</div>
  </div>
</div>

CSS :

.panel-height {
  height: 100px; / change according to your requirement/
}

Validate date in dd/mm/yyyy format using JQuery Validate

I encountered a similar problem in my project. After struggling a lot, I found this solution:

if ($.datepicker.parseDate("dd/mm/yy","17/06/2015") > $.datepicker.parseDate("dd/mm/yy","20/06/2015"))
    // do something

You DO NOT NEED plugins like jQuery Validate or Moment.js for this issue. Hope this solution helps.

How to find NSDocumentDirectory in Swift?

Usually I prefer to use this extension:

Swift 3.x and Swift 4.0:

extension FileManager {
    class func documentsDir() -> String {
        var paths = NSSearchPathForDirectoriesInDomains(.documentDirectory, .userDomainMask, true) as [String]
        return paths[0]
    }
    
    class func cachesDir() -> String {
        var paths = NSSearchPathForDirectoriesInDomains(.cachesDirectory, .userDomainMask, true) as [String]
        return paths[0]
    }
}

Swift 2.x:

extension NSFileManager {
    class func documentsDir() -> String {
        var paths = NSSearchPathForDirectoriesInDomains(.DocumentDirectory, .UserDomainMask, true) as [String]
        return paths[0]
    }
    
    class func cachesDir() -> String {
        var paths = NSSearchPathForDirectoriesInDomains(.CachesDirectory, .UserDomainMask, true) as [String]
        return paths[0]
    }
}

Ajax Cross-Origin Request Blocked: The Same Origin Policy disallows reading the remote resource

I used the header("Access-Control-Allow-Origin: *"); method but still received the CORS error. It turns out that the PHP script that was being requested had an error in it (I had forgotten to add a period (.) when concatenating two variables). Once I fixed that typo, it worked!

So, It seems that the remote script being called cannot have errors within it.

Proper way of checking if row exists in table in PL/SQL block

You can do EXISTS in Oracle PL/SQL.

You can do the following:

DECLARE
    n_rowExist NUMBER := 0;
BEGIN
    SELECT CASE WHEN EXISTS (
      SELECT 1
      FROM person
      WHERE ID = 10
    ) THEN 1 ELSE 0 INTO n_rowExist END FROM DUAL;
    
    IF n_rowExist = 1 THEN
       -- do things when it exists
    ELSE
       -- do things when it doesn't exist
    END IF;

END;
/

Explanation:

In the query nested where it starts with SELECT CASE WHEN EXISTS and after the parenthesis (SELECT 1 FROM person WHERE ID = 10) it will return a result if it finds a person of ID of 10. If the there's a result on the query then it will assign the value of 1 otherwise it will assign the value of 0 to n_rowExist variable. Afterwards, the if statement checks if the value returned equals to 1 then is true otherwise it will be 0 = 1 and that is false.

Object variable or With block variable not set (Error 91)

As I wrote in my comment, the solution to your problem is to write the following:

Set hyperLinkText = hprlink.Range

Set is needed because TextRange is a class, so hyperLinkText is an object; as such, if you want to assign it, you need to make it point to the actual object that you need.

javax.xml.bind.UnmarshalException: unexpected element. Expected elements are (none)

Alternatively if you want to persist in using the DocumentType class. Then you could just add the following annotation on top of your DocumentType class.

    @XmlRootElement(name="document")

Note: the String value "document" refers to the name of the root tag of the xml message.

Why does my JavaScript code receive a "No 'Access-Control-Allow-Origin' header is present on the requested resource" error, while Postman does not?

If I understood it right you are doing an XMLHttpRequest to a different domain than your page is on. So the browser is blocking it as it usually allows a request in the same origin for security reasons. You need to do something different when you want to do a cross-domain request. A tutorial about how to achieve that is Using CORS.

When you are using postman they are not restricted by this policy. Quoted from Cross-Origin XMLHttpRequest:

Regular web pages can use the XMLHttpRequest object to send and receive data from remote servers, but they're limited by the same origin policy. Extensions aren't so limited. An extension can talk to remote servers outside of its origin, as long as it first requests cross-origin permissions.

CORS: Cannot use wildcard in Access-Control-Allow-Origin when credentials flag is true

This is a part of security, you cannot do that. If you want to allow credentials then your Access-Control-Allow-Origin must not use *. You will have to specify the exact protocol + domain + port. For reference see these questions :

  1. Access-Control-Allow-Origin wildcard subdomains, ports and protocols
  2. Cross Origin Resource Sharing with Credentials

Besides * is too permissive and would defeat use of credentials. So set http://localhost:3000 or http://localhost:8000 as the allow origin header.

Waiting on a list of Future

 /**
     * execute suppliers as future tasks then wait / join for getting results
     * @param functors a supplier(s) to execute
     * @return a list of results
     */
    private List getResultsInFuture(Supplier<?>... functors) {
        CompletableFuture[] futures = stream(functors)
                .map(CompletableFuture::supplyAsync)
                .collect(Collectors.toList())
                .toArray(new CompletableFuture[functors.length]);
        CompletableFuture.allOf(futures).join();
        return stream(futures).map(a-> {
            try {
                return a.get();
            } catch (InterruptedException | ExecutionException e) {
                //logger.error("an error occurred during runtime execution a function",e);
                return null;
            }
        }).collect(Collectors.toList());
    };

403 Forbidden error when making an ajax Post request in Django framework

Another approach is to add X-CSRFTOKEN header with the "{{ csrf_token }}" value like in the following example:

$.ajax({
            url: "{% url 'register_lowresistancetyres' %}",
            type: "POST",
            headers: {//<==
                        "X-CSRFTOKEN": "{{ csrf_token }}"//<==
                },
            data: $(example_form).serialize(),
            success: function(data) {
                //Success code
            },
            error: function () {
                //Error code
            }
        });

JSONP call showing "Uncaught SyntaxError: Unexpected token : "

Working fiddle:

http://jsfiddle.net/repjt/

$.ajax({
    url: 'https://api.flightstats.com/flex/schedules/rest/v1/jsonp/flight/AA/100/departing/2013/10/4?appId=19d57e69&appKey=e0ea60854c1205af43fd7b1203005d59',
    dataType: 'JSONP',
    jsonpCallback: 'callback',
    type: 'GET',
    success: function (data) {
        console.log(data);
    }
});

I had to manually set the callback to callback, since that's all the remote service seems to support. I also changed the url to specify that I wanted jsonp.

jquery.ajax Access-Control-Allow-Origin

At my work we have our restful services on a different port number and the data resides in db2 on a pair of AS400s. We typically use the $.getJSON AJAX method because it easily returns JSONP using the ?callback=? without having any issues with CORS.

data ='USER=<?echo trim($USER)?>' +
         '&QRYTYPE=' + $("input[name=QRYTYPE]:checked").val();

        //Call the REST program/method returns: JSONP 
        $.getJSON( "http://www.stackoverflow.com/rest/resttest?callback=?",data)
        .done(function( json ) {        

              //  loading...
                if ($.trim(json.ERROR) != '') {
                    $("#error-msg").text(message).show();
                }
                else{
                    $(".error").hide();
                    $("#jsonp").text(json.whatever);

                }

        })  
        .fail(function( jqXHR, textStatus, error ) {
        var err = textStatus + ", " + error;
        alert('Unable to Connect to Server.\n Try again Later.\n Request Failed: ' + err);
        });     

Arduino error: does not name a type?

More recently, I have found that other factors will also cause this error. I had an AES.h, AES.cpp containing a AES class and it gave this same unhelpful error. Only when I renamed to Encryption.h, Encryption.cpp and Encryption as the class name did it suddenly start working. There were no other code changes.

How to send a correct authorization header for basic authentication

You can include the user and password as part of the URL:

http://user:[email protected]/index.html

see this URL, for more

HTTP Basic Authentication credentials passed in URL and encryption

of course, you'll need the username password, it's not 'Basic hashstring.

hope this helps...

How to use Tomcat 8 in Eclipse?

Downloaded Eclipse Luna and installed WTP using http://download.eclipse.org/webtools/repository/luna

Downloaded Tomcat 8 and configured new server in Eclipse. I am able to setup tomcat 8 now in Eclipse luna

datatable jquery - table header width not aligned with body width

I was facing the same issue. I added the scrollX: true property for the dataTable and it worked. There is no need to change the CSS for datatable

jQuery('#myTable').DataTable({
                            "fixedHeader":true,
                            "scrollY":"450px",
                            "scrollX":true,
                            "paging":   false,
                            "ordering": false,
                            "info":     false,
                            "searching": false,
                            "scrollCollapse": true
                            });

jQuery Cross Domain Ajax

Unfortunately it seems that this web service returns JSON which contains another JSON - parsing contents of the inner JSON is successful. The solution is ugly but works for me. JSON.parse(...) tries to convert the entire string and fails. Assuming that you always get the answer starting with {"AuthenticateUserResult": and interesting data is after this, try:

$.ajax({
    type: 'GET',
    dataType: "text",
    crossDomain: true,
    url: "http://someotherdomain.com/service.svc",
    success: function (responseData, textStatus, jqXHR) {
        var authResult = JSON.parse(
            responseData.replace(
                '{"AuthenticateUserResult":"', ''
            ).replace('}"}', '}')
        );
        console.log("in");
    },
    error: function (responseData, textStatus, errorThrown) {
        alert('POST failed.');
    }
});

It is very important that dataType must be text to prevent auto-parsing of malformed JSON you are receiving from web service.

Basically, I'm wiping out the outer JSON by removing topmost braces and key AuthenticateUserResult along with leading and trailing quotation marks. The result is a well formed JSON, ready for parsing.

error_reporting(E_ALL) does not produce error

That error is a parse error. The parser is throwing it while going through the code, trying to understand it. No code is being executed yet in the parsing stage. Because of that it hasn't yet executed the error_reporting line, therefore the error reporting settings aren't changed yet.

You cannot change error reporting settings (or really, do anything) in a file with syntax errors.

How to set cookie value with AJAX request?

Basically, ajax request as well as synchronous request sends your document cookies automatically. So, you need to set your cookie to document, not to request. However, your request is cross-domain, and things became more complicated. Basing on this answer, additionally to set document cookie, you should allow its sending to cross-domain environment:

type: "GET",    
url: "http://example.com",
cache: false,
// NO setCookies option available, set cookie to document
//setCookies: "lkfh89asdhjahska7al446dfg5kgfbfgdhfdbfgcvbcbc dfskljvdfhpl",
crossDomain: true,
dataType: 'json',
xhrFields: {
    withCredentials: true
},
success: function (data) {
    alert(data);
});

Origin http://localhost is not allowed by Access-Control-Allow-Origin

There are 2 calls that need to set the correct headers. Initially there is a preflight check so you need something like...

app.get('/item', item.list);
app.options('/item', item.preflight);

and then have the following functions...

exports.list = function (req, res) {
Items.allItems(function (err, items) {
    ...
        res.header('Access-Control-Allow-Origin', "*");     // TODO - Make this more secure!!
        res.header('Access-Control-Allow-Methods', 'GET,PUT,POST');
        res.header('Access-Control-Allow-Headers', 'Access-Control-Allow-Headers", "Origin, X-Requested-With, Content-Type, Accept');
        res.send(items);
      }
   );
};

and for the pre-flight checks

exports.preflight = function (req, res) {
Items.allItems(function (err, items) {
        res.header('Access-Control-Allow-Origin', "*");     // TODO - Make this more secure!!
        res.header('Access-Control-Allow-Methods', 'GET,PUT,POST');
        res.header('Access-Control-Allow-Headers', 'Access-Control-Allow-Headers", "Origin, X-Requested-With, Content-Type, Accept');
        res.send(200);
    }
  );
};

You can consolidate the res.header() code into a single function if you want.

Also as stated above, be careful of using res.header('Access-Control-Allow-Origin', "*") this means anyone can access your site!

Need to ZIP an entire directory using Node.js

This is another library which zips the folder in one line : zip-local

var zipper = require('zip-local');

zipper.sync.zip("./hello/world/").compress().save("pack.zip");

Passing data between different controller action methods

If you need to pass data from one controller to another you must pass data by route values.Because both are different request.if you send data from one page to another then you have to user query string(same as route values).

But you can do one trick :

In your calling action call the called action as a simple method :

public class ServerController : Controller
{
 [HttpPost]
 public ActionResult ApplicationPoolsUpdate(ServiceViewModel viewModel)
 {
      XDocument updatedResultsDocument = myService.UpdateApplicationPools();
      ApplicationPoolController pool=new ApplicationPoolController(); //make an object of ApplicationPoolController class.

      return pool.UpdateConfirmation(updatedResultsDocument); // call the ActionMethod you want as a simple method and pass the model as an argument.
      // Redirect to ApplicationPool controller and pass
      // updatedResultsDocument to be used in UpdateConfirmation action method
 }
}

Running Python on Windows for Node.js dependencies

Here is a guide that resolved a lot of these issues for me.

http://www.steveworkman.com/node-js/2012/installing-jsdom-on-windows/

I remember in particular the python version as important. Make sure you install 2.7.3 instead of 3's.

Delete specified file from document directory

Swift 3.0:

func removeImage(itemName:String, fileExtension: String) {
  let fileManager = FileManager.default
  let nsDocumentDirectory = FileManager.SearchPathDirectory.documentDirectory
  let nsUserDomainMask = FileManager.SearchPathDomainMask.userDomainMask
  let paths = NSSearchPathForDirectoriesInDomains(nsDocumentDirectory, nsUserDomainMask, true)
  guard let dirPath = paths.first else {
      return
  }  
  let filePath = "\(dirPath)/\(itemName).\(fileExtension)"
  do {
    try fileManager.removeItem(atPath: filePath)
  } catch let error as NSError {
    print(error.debugDescription)
  }}

Thanks to @Anil Varghese, I wrote very similiar code in swift 2.0:

static func removeImage(itemName:String, fileExtension: String) {
  let fileManager = NSFileManager.defaultManager()
  let nsDocumentDirectory = NSSearchPathDirectory.DocumentDirectory
  let nsUserDomainMask = NSSearchPathDomainMask.UserDomainMask
  let paths = NSSearchPathForDirectoriesInDomains(nsDocumentDirectory, nsUserDomainMask, true)
  guard let dirPath = paths.first else {
    return
  }
  let filePath = "\(dirPath)/\(itemName).\(fileExtension)"
  do {
    try fileManager.removeItemAtPath(filePath)
  } catch let error as NSError {
    print(error.debugDescription)
  }
}

Loading cross-domain endpoint with AJAX

You can use Ajax-cross-origin a jQuery plugin. With this plugin you use jQuery.ajax() cross domain. It uses Google services to achieve this:

The AJAX Cross Origin plugin use Google Apps Script as a proxy jSON getter where jSONP is not implemented. When you set the crossOrigin option to true, the plugin replace the original url with the Google Apps Script address and send it as encoded url parameter. The Google Apps Script use Google Servers resources to get the remote data, and return it back to the client as JSONP.

It is very simple to use:

    $.ajax({
        crossOrigin: true,
        url: url,
        success: function(data) {
            console.log(data);
        }
    });

You can read more here: http://www.ajax-cross-origin.com/

Cross domain POST request is not sending cookie Ajax Jquery

Please note this doesn't solve the cookie sharing process, as in general this is bad practice.

You need to be using JSONP as your type:

From $.ajax documentation: Cross-domain requests and dataType: "jsonp" requests do not support synchronous operation.

$.ajax(
    { 
      type: "POST",
      url: "http://example.com/api/getlist.json",
      dataType: 'jsonp',
      xhrFields: {
           withCredentials: true
      },
      crossDomain: true,
      beforeSend: function(xhr) {
            xhr.setRequestHeader("Cookie", "session=xxxyyyzzz");
      },
      success: function(){
           alert('success');
      },
      error: function (xhr) {
             alert(xhr.responseText);
      }
    }
);

Swift_TransportException Connection could not be established with host smtp.gmail.com

Fatal error: Uncaught exception 'Swift_TransportException' with message 'Connection could not be established with host smtp.gmail.com [Connection refused #111]

Connection refused is a very explicit and clear error message. It means that the socket connection could not be established because the remote end actively refused to connect.

It's very unlikely that Google is blocking the connection.

It's very likely that your web hosting provider has firewall settings that block outgoing connections on port 465, or that they are blocking SMTP to Gmail. 465 is the "wrong" port for secure SMTP, though it is often used, and Gmail does listen there. Try port 587 instead. If the connection is still refused, call your host and ask them what's up.

Cannot find the declaration of element 'beans'

Found it on another thread that solved my problem... was using an internet connection less network.

In that case copy the xsd files from the url and place it next to the beans.xml file and change the xsi:schemaLocation as under:

 <beans xmlns="http://www.springframework.org/schema/beans" 
   xmlns:xsi="http://www.w3.org/2001/XMLSchema-instance"
  xsi:schemaLocation="http://www.springframework.org/schema/beans 
spring-beans-3.1.xsd">

Change select box option background color

My selects would not color the background until I added !important to the style.

    input, select, select option{background-color:#FFE !important}

Disable automatic sorting on the first column when using jQuery DataTables

If any of other solution doesn't fix it, try to override the styles to hide the sort togglers:

.sorting_asc:after, .sorting_desc:after {
  content: "";
}

Disable sorting on last column when using jQuery DataTables

This is work perfect for me if you don't allow sorting the first column then use

<script>
    $(document).ready(function () {
        $('#example2').DataTable({               
            'order':[],
            'columnDefs': [{
                "targets": 0,
                "orderable": false
            }]
        });
    });
</script>

here index row starts with 0, so put 0 in targets.
And if you disable sorting for one or more column then use,

<script>
    $(document).ready(function () {
        $('#example2').DataTable({               
            'order':[],
            'columnDefs': [{
                "targets": [0,3],
                "orderable": false
            }]
        });
    });
</script>

Here you can see , disable sorting in datatable js

Above my checkbox column at 0 positions and Action column at 3rd position so sorting disable in both table.

Implement a loading indicator for a jQuery AJAX call

I'm guessing you're using jQuery.get or some other jQuery ajax function to load the modal. You can show the indicator before the ajax call, and hide it when the ajax completes. Something like

$('#indicator').show();
$('#someModal').get(anUrl, someData, function() { $('#indicator').hide(); });

How do I convert a org.w3c.dom.Document object to a String?

This worked for me, as documented on this page:

TransformerFactory tf = TransformerFactory.newInstance();
Transformer trans = tf.newTransformer();
StringWriter sw = new StringWriter();
trans.transform(new DOMSource(document), new StreamResult(sw));
return sw.toString();

Jetty: HTTP ERROR: 503/ Service Unavailable

Remove/Delete the project from workspace. and Reimport the project to the workspace. This method worked for me.

IE9 jQuery AJAX with CORS returns "Access is denied"

I was testing a CORS web service on my dev machine and was getting the "Access is denied" error message in only IE. Firefox and Chrome worked fine. It turns out this was caused by my use of localhost in the ajax call! So my browser URL was something like:

http://my_computer.my_domain.local/CORS_Service/test.html

and my ajax call inside of test.html was something like:

//fails in IE 
$.ajax({
  url: "http://localhost/CORS_Service/api/Controller",
  ...
});

Everything worked once I changed the ajax call to use my computer IP instead of localhost.

//Works in IE
$.ajax({
  url: "http://192.168.0.1/CORS_Service/api/Controller",
  ...
});

The IE dev tools window "Network" tab also shows CORS Preflight OPTIONS request followed by the XMLHttpRequest GET, which is exactly what I expected to see.

Stop form from submitting , Using Jquery

use this too :

if(e.preventDefault) 
   e.preventDefault(); 
else 
   e.returnValue = false;

Becoz e.preventDefault() is not supported in IE( some versions ). In IE it is e.returnValue = false

xls to csv converter

Maybe someone find this ready-to-use piece of code useful. It allows to create CSVs from all spreadsheets in Excel's workbook.

enter image description here

# -*- coding: utf-8 -*-
import xlrd
import csv
from os import sys

def csv_from_excel(excel_file):
    workbook = xlrd.open_workbook(excel_file)
    all_worksheets = workbook.sheet_names()
    for worksheet_name in all_worksheets:
        worksheet = workbook.sheet_by_name(worksheet_name)
        with open(u'{}.csv'.format(worksheet_name), 'wb') as your_csv_file:
            wr = csv.writer(your_csv_file, quoting=csv.QUOTE_ALL)
            for rownum in xrange(worksheet.nrows):
                wr.writerow([unicode(entry).encode("utf-8") for entry in worksheet.row_values(rownum)])

if __name__ == "__main__":
    csv_from_excel(sys.argv[1])

How to execute 16-bit installer on 64-bit Win7?

You can't run 16-bit applications (or components) on 64-bit versions of Windows. That emulation layer no longer exists. The 64-bit versions already have to provide a compatibility layer for 32-bit applications.

Support for 16-bit had to be dropped eventually, even in a culture where backwards-compatibility is of sacred import. The transition to 64-bit seemed like as good a time as any. It's hard to imagine anyone out there in the wild that is still using 16-bit applications and seeking to upgrade to 64-bit OSes.

What would be the best way to get round this problem?

If the component itself is 16-bit, then using a virtual machine running a 32-bit version of Windows is your only real choice. Oracle's VirtualBox is free, and a perennial favorite.

If only the installer is 16-bit (and it installs a 32-bit component), then you might be able to use a program like 7-Zip to extract the contents of the installer and install them manually. Let's just say this "solution" is high-risk and you should have few, if any, expectations.

It's high time to upgrade away from 16-bit stuff, like Turbo C++ and Sheridan controls. I've yet to come across anything that the Sheridan controls can do that the built-in controls can't do and haven't been able to do since Windows 95.

How to beautify JSON in Python?

From the command-line:

echo '{"one":1,"two":2}' | python -mjson.tool

which outputs:

{
    "one": 1, 
    "two": 2
}

Programmtically, the Python manual describes pretty-printing JSON:

>>> import json
>>> print json.dumps({'4': 5, '6': 7}, sort_keys=True, indent=4)
{
    "4": 5,
    "6": 7
}

Add MIME mapping in web.config for IIS Express

If anybody encounters this with errors like Error: cannot add duplicate collection entry of type ‘mimeMap’ with unique key attribute and/or other scripts stop working when doing this fix, it might help to remove it first like this:

<staticContent>
  <remove fileExtension=".woff" />
  <mimeMap fileExtension=".woff" mimeType="application/font-woff" />
</staticContent>

At least that solved my problem

Jquery Ajax Loading image

Its a bit late but if you don't want to use a div specifically, I usually do it like this...

var ajax_image = "<img src='/images/Loading.gif' alt='Loading...' />";
$('#ReplaceDiv').html(ajax_image);

ReplaceDiv is the div that the Ajax inserts too. So when it arrives, the image is replaced.

Remove a specific character using awk or sed

Use sed's substitution: sed 's/"//g'

s/X/Y/ replaces X with Y.

g means all occurrences should be replaced, not just the first one.

Redraw datatables after using ajax to refresh the table content?

check fnAddData: https://legacy.datatables.net/ref

$(document).ready(function () {
  var table = $('#example').dataTable();
  var url = '/RESTApplicationTest/webresources/entity.person';
  $.get(url, function (data) {
    for (var i = 0; i < data.length; i++) {
      table.fnAddData([data[i].idPerson, data[i].firstname, data[i].lastname, data[i].email, data[i].phone])
    }
  });
});

The 'packages' element is not declared

You can also find a copy of the nuspec.xsd here as it seems to no longer be available:

https://gist.github.com/sharwell/6131243

JsonMappingException: No suitable constructor found for type [simple type, class ]: can not instantiate from JSON object

If you start annotating constructor, you must annotate all fields.

Notice, my Staff.name field is mapped to "ANOTHER_NAME" in JSON string.

     String jsonInString="{\"ANOTHER_NAME\":\"John\",\"age\":\"17\"}";
     ObjectMapper mapper = new ObjectMapper();
     Staff obj = mapper.readValue(jsonInString, Staff.class);
     // print to screen

     public static class Staff {
       public String name;
       public Integer age;
       public Staff() {         
       }        

       //@JsonCreator - don't need this
       public Staff(@JsonProperty("ANOTHER_NAME") String   n,@JsonProperty("age") Integer a) {
        name=n;age=a;
       }        
    }

Callback function for JSONP with jQuery AJAX

This is what I do on mine

$(document).ready(function() {
  if ($('#userForm').valid()) {
    var formData = $("#userForm").serializeArray();
    $.ajax({
      url: 'http://www.example.com/user/' + $('#Id').val() + '?callback=?',
      type: "GET",
      data: formData,
      dataType: "jsonp",
      jsonpCallback: "localJsonpCallback"
    });
  });

function localJsonpCallback(json) {
  if (!json.Error) {
    $('#resultForm').submit();
  } else {
    $('#loading').hide();
    $('#userForm').show();
    alert(json.Message);
  }
}

jQuery Ajax requests are getting cancelled without being sent

If anyone else runs into this, the issue we had was that we were making the ajax request from a link, and not preventing the link from being followed. So if you are doing this in an onclick attribute, make sure to return false; as well.

iOS start Background Thread

The default sqlite library that comes with iOS is not compiled using the SQLITE_THREADSAFE macro on. This could be a reason why your code crashes.

What is the documents directory (NSDocumentDirectory)?

You can access documents directory using this code it is basically used for storing file in plist format:

NSArray *paths = NSSearchPathForDirectoriesInDomains(NSDocumentDirectory, NSUserDomainMask, YES);
NSString *documentsDirectory = [paths firstObject];
return documentsDirectory;

Install dependencies globally and locally using package.json

Due to the disadvantages described below, I would recommend following the accepted answer:

Use npm install --save-dev [package_name] then execute scripts with:

$ npm run lint
$ npm run build
$ npm test

My original but not recommended answer follows.


Instead of using a global install, you could add the package to your devDependencies (--save-dev) and then run the binary from anywhere inside your project:

"$(npm bin)/<executable_name>" <arguments>...

In your case:

"$(npm bin)"/node.io --help

This engineer provided an npm-exec alias as a shortcut. This engineer uses a shellscript called env.sh. But I prefer to use $(npm bin) directly, to avoid any extra file or setup.

Although it makes each call a little larger, it should just work, preventing:

  • potential dependency conflicts with global packages (@nalply)
  • the need for sudo
  • the need to set up an npm prefix (although I recommend using one anyway)

Disadvantages:

  • $(npm bin) won't work on Windows.
  • Tools deeper in your dev tree will not appear in the npm bin folder. (Install npm-run or npm-which to find them.)

It seems a better solution is to place common tasks (such as building and minifying) in the "scripts" section of your package.json, as Jason demonstrates above.

How to describe "object" arguments in jsdoc?

From the @param wiki page:


Parameters With Properties

If a parameter is expected to have a particular property, you can document that immediately after the @param tag for that parameter, like so:

 /**
  * @param userInfo Information about the user.
  * @param userInfo.name The name of the user.
  * @param userInfo.email The email of the user.
  */
 function logIn(userInfo) {
        doLogIn(userInfo.name, userInfo.email);
 }

There used to be a @config tag which immediately followed the corresponding @param, but it appears to have been deprecated (example here).

SQL 'like' vs '=' performance

If value is unindexed, both result in a table-scan. The performance difference in this scenario will be negligible.

If value is indexed, as Daniel points out in his comment, the = will result in an index lookup which is O(log N) performance. The LIKE will (most likely - depending on how selective it is) result in a partial scan of the index >= 'abc' and < 'abd' which will require more effort than the =.

Note that I'm talking SQL Server here - not all DBMSs will be nice with LIKE.

How to make remote REST call inside Node.js? any CURL?

Look at http.request

var options = {
  host: url,
  port: 80,
  path: '/resource?id=foo&bar=baz',
  method: 'POST'
};

http.request(options, function(res) {
  console.log('STATUS: ' + res.statusCode);
  console.log('HEADERS: ' + JSON.stringify(res.headers));
  res.setEncoding('utf8');
  res.on('data', function (chunk) {
    console.log('BODY: ' + chunk);
  });
}).end();

Write a file on iOS

May be this is useful to you.

//Method writes a string to a text file
-(void) writeToTextFile{
        //get the documents directory:
        NSArray *paths = NSSearchPathForDirectoriesInDomains
            (NSDocumentDirectory, NSUserDomainMask, YES);
        NSString *documentsDirectory = [paths objectAtIndex:0];

        //make a file name to write the data to using the documents directory:
        NSString *fileName = [NSString stringWithFormat:@"%@/textfile.txt", 
                                                      documentsDirectory];
        //create content - four lines of text
        NSString *content = @"One\nTwo\nThree\nFour\nFive";
        //save content to the documents directory
        [content writeToFile:fileName 
                         atomically:NO 
                               encoding:NSUTF8StringEncoding 
                                      error:nil];

}


//Method retrieves content from documents directory and
//displays it in an alert
-(void) displayContent{
        //get the documents directory:
        NSArray *paths = NSSearchPathForDirectoriesInDomains
                        (NSDocumentDirectory, NSUserDomainMask, YES);
        NSString *documentsDirectory = [paths objectAtIndex:0];

        //make a file name to write the data to using the documents directory:
        NSString *fileName = [NSString stringWithFormat:@"%@/textfile.txt", 
                                                      documentsDirectory];
        NSString *content = [[NSString alloc] initWithContentsOfFile:fileName
                                                      usedEncoding:nil
                                                             error:nil];
        //use simple alert from my library (see previous post for details)
        [ASFunctions alert:content];
        [content release];

}

Get child Node of another Node, given node name

If the Node is not just any node, but actually an Element (it could also be e.g. an attribute or a text node), you can cast it to Element and use getElementsByTagName.

org.xml.sax.SAXParseException: Content is not allowed in prolog

Just an additional thought on this one for the future. Getting this bug could be the case that one simply hits the delete key or some other key randomly when they have an XML window as the active display and are not paying attention. This has happened to me before with the struts.xml file in my web application. Clumsy elbows ...

jQuery Ajax calls and the Html.AntiForgeryToken()

Slight improvement to 360Airwalk solution. This imbeds the Anti Forgery Token within the javascript function, so @Html.AntiForgeryToken() no longer needs to be included on every view.

$(document).ready(function () {
    var securityToken = $('@Html.AntiForgeryToken()').attr('value');
    $('body').bind('ajaxSend', function (elm, xhr, s) {
        if (s.type == 'POST' && typeof securityToken != 'undefined') {
            if (s.data.length > 0) {
                s.data += "&__RequestVerificationToken=" + encodeURIComponent(securityToken);
            }
            else {
                s.data = "__RequestVerificationToken=" + encodeURIComponent(securityToken);
            }
        }
    });
});

Spring schemaLocation fails when there is no internet connection

The problem lies in the JAR files that you use in your application.

What I did, which worked, was to get inside the JARs for SPRING-CORE, SPRING-BEANS, SPRING-CONTEXT, SPRING-TX that match the version I am using. Within the META-INF folder, I concatenated all the spring.handlers and spring.schemas that come in those JARs.

I killed two birds with one stone, I solved the problem of the schemas so this also works correctly in offline mode.

P.S. I tried the maven plugin for SHADE and the transformers but that did not work.

How can I make the browser wait to display the page until it's fully loaded?

This is a very bad idea for all of the reasons given, and more. That said, here's how you do it using jQuery:

<body>
<div id="msg" style="font-size:largest;">
<!-- you can set whatever style you want on this -->
Loading, please wait...
</div>
<div id="body" style="display:none;">
<!-- everything else -->
</div>
<script type="text/javascript">
$(document).ready(function() {
    $('#body').show();
    $('#msg').hide();
});
</script>
</body>

If the user has JavaScript disabled, they never see the page. If the page never finishes loading, they never see the page. If the page takes too long to load, they may assume something went wrong and just go elsewhere instead of *please wait...*ing.

How to wait for all threads to finish, using ExecutorService?

ExecutorService.invokeAll() does it for you.

ExecutorService taskExecutor = Executors.newFixedThreadPool(4);
List<Callable<?>> tasks; // your tasks
// invokeAll() returns when all tasks are complete
List<Future<?>> futures = taskExecutor.invokeAll(tasks);

Getting list of pixel values from PIL

Python shouldn't crash when you call getdata(). The image might be corrupted or there is something wrong with your PIL installation. Try it with another image or post the image you are using.

This should break down the image the way you want:

from PIL import Image
im = Image.open('um_000000.png')

pixels = list(im.getdata())
width, height = im.size
pixels = [pixels[i * width:(i + 1) * width] for i in xrange(height)]

How do you check if a JavaScript Object is a DOM Object?

This is what I figured out:

var isHTMLElement = (function () {
    if ("HTMLElement" in window) {
        // Voilà. Quick and easy. And reliable.
        return function (el) {return el instanceof HTMLElement;};
    } else if ((document.createElement("a")).constructor) {
        // We can access an element's constructor. So, this is not IE7
        var ElementConstructors = {}, nodeName;
        return function (el) {
            return el && typeof el.nodeName === "string" &&
                 (el instanceof ((nodeName = el.nodeName.toLowerCase()) in ElementConstructors 
                    ? ElementConstructors[nodeName] 
                    : (ElementConstructors[nodeName] = (document.createElement(nodeName)).constructor)))
        }
    } else {
        // Not that reliable, but we don't seem to have another choice. Probably IE7
        return function (el) {
            return typeof el === "object" && el.nodeType === 1 && typeof el.nodeName === "string";
        }
    }
})();

To improve performance I created a self-invoking function that tests the browser's capabilities only once and assigns the appropriate function accordingly.

The first test should work in most modern browsers and was already discussed here. It just tests if the element is an instance of HTMLElement. Very straightforward.

The second one is the most interesting one. This is its core-functionality:

return el instanceof (document.createElement(el.nodeName)).constructor

It tests whether el is an instance of the construcor it pretends to be. To do that, we need access to an element's contructor. That's why we're testing this in the if-Statement. IE7 for example fails this, because (document.createElement("a")).constructor is undefined in IE7.

The problem with this approach is that document.createElement is really not the fastest function and could easily slow down your application if you're testing a lot of elements with it. To solve this, I decided to cache the constructors. The object ElementConstructors has nodeNames as keys with its corresponding constructors as values. If a constructor is already cached, it uses it from the cache, otherwise it creates the Element, caches its constructor for future access and then tests against it.

The third test is the unpleasant fallback. It tests whether el is an object, has a nodeType property set to 1 and a string as nodeName. This is not very reliable of course, yet the vast majority of users shouldn't even fall back so far.

This is the most reliable approach I came up with while still keeping performance as high as possible.

Can someone post a well formed crossdomain.xml sample?

This is what I've been using for development:

<?xml version="1.0" ?>
<cross-domain-policy>
<allow-access-from domain="*" />
</cross-domain-policy>

This is a very liberal approach, but is fine for my application.

As others have pointed out below, beware the risks of this.

How to create empty text file from a batch file?

type NUL > EmptyFile.txt

After reading the previous two posts, this blend of the two is what I came up with. It seems a little cleaner. There is no need to worry about redirecting the "1 file(s) copied." message to NUL, like the previous post does, and it looks nice next to the ECHO OutputLineFromLoop >> Emptyfile.txt that will usually follow in a batch file.

Language Books/Tutorials for popular languages

C++

The first one is good for beginners and the second one requires more advanced level in C++.

How to skip the OPTIONS preflight request?

I think best way is check if request is of type "OPTIONS" return 200 from middle ware. It worked for me.

express.use('*',(req,res,next) =>{
      if (req.method == "OPTIONS") {
        res.status(200);
        res.send();
      }else{
        next();
      }
    });

Check if Key Exists in NameValueCollection

You could use the Get method and check for null as the method will return null if the NameValueCollection does not contain the specified key.

See MSDN.

Add Legend to Seaborn point plot

I would suggest not to use seaborn pointplot for plotting. This makes things unnecessarily complicated.
Instead use matplotlib plot_date. This allows to set labels to the plots and have them automatically put into a legend with ax.legend().

import matplotlib.pyplot as plt
import pandas as pd
import seaborn as sns
import numpy as np

date = pd.date_range("2017-03", freq="M", periods=15)
count = np.random.rand(15,4)
df1 = pd.DataFrame({"date":date, "count" : count[:,0]})
df2 = pd.DataFrame({"date":date, "count" : count[:,1]+0.7})
df3 = pd.DataFrame({"date":date, "count" : count[:,2]+2})

f, ax = plt.subplots(1, 1)
x_col='date'
y_col = 'count'

ax.plot_date(df1.date, df1["count"], color="blue", label="A", linestyle="-")
ax.plot_date(df2.date, df2["count"], color="red", label="B", linestyle="-")
ax.plot_date(df3.date, df3["count"], color="green", label="C", linestyle="-")

ax.legend()

plt.gcf().autofmt_xdate()
plt.show()

enter image description here


In case one is still interested in obtaining the legend for pointplots, here a way to go:

sns.pointplot(ax=ax,x=x_col,y=y_col,data=df1,color='blue')
sns.pointplot(ax=ax,x=x_col,y=y_col,data=df2,color='green')
sns.pointplot(ax=ax,x=x_col,y=y_col,data=df3,color='red')

ax.legend(handles=ax.lines[::len(df1)+1], labels=["A","B","C"])

ax.set_xticklabels([t.get_text().split("T")[0] for t in ax.get_xticklabels()])
plt.gcf().autofmt_xdate()

plt.show()

How to use regex in file find

Use -regex:

From the man page:

-regex pattern
       File name matches regular expression pattern.  This is a match on the whole path, not a search.  For example, to match a file named './fubar3',  you  can  use  the
       regular expression '.*bar.' or '.*b.*3', but not 'b.*r3'.

Also, I don't believe find supports regex extensions such as \d. You need to use [0-9].

find . -regex '.*test\.log\.[0-9][0-9][0-9][0-9]-[0-9][0-9]-[0-9][0-9]\.zip'

An invalid form control with name='' is not focusable

In my case the problem was with the input type="radio" required being hidden with:

visibility: hidden;

This error message will also show if the required input type radio or checkbox has a display: none; CSS property.

If you want to create custom radio/checkbox inputs where they must be hidden from the UI and still keep the required attribute, you should instead use the:

opacity: 0; CSS property

css transition opacity fade background

It's not fading to "black transparent" or "white transparent". It's just showing whatever color is "behind" the image, which is not the image's background color - that color is completely hidden by the image.

If you want to fade to black(ish), you'll need a black container around the image. Something like:

.ctr {
    margin: 0; 
    padding: 0;
    background-color: black;
    display: inline-block;
}

and

<div class="ctr"><img ... /></div>

Fluid or fixed grid system, in responsive design, based on Twitter Bootstrap

Fluid layout in Bootstrap 3.

Unlike Boostrap 2, Bootstrap 3 doesn't have a .container-fluid mixin to make a fluid container. The .container is a fixed width responsive grid layout. In a large screen, there are excessive white spaces in both sides of one's Web page content.

container-fluid is added back in Bootstrap 3.1

A fluid grid layout uses all screen width and works better in large screen. It turns out that it is easy to create a fluid grid layout using Bootstrap 3 mixins. The following line makes a fluid responsive grid layout:

.container-fixed;

The .container-fixed mixin sets the content to the center of the screen and add paddings. It doesn't specifies a fixed page width.

Another approach is to use Eric Flowers' CSS style

.my-fluid-container {
    padding-left: 15px;
    padding-right: 15px;
    margin-left: auto;
    margin-right: auto;
}

List files in local git repo?

git ls-tree --full-tree -r HEAD and git ls-files return all files at once. For a large project with hundreds or thousands of files, and if you are interested in a particular file/directory, you may find more convenient to explore specific directories. You can do it by obtaining the ID/SHA-1 of the directory that you want to explore and then use git cat-file -p [ID/SHA-1 of directory]. For example:

git cat-file -p 14032aabd85b43a058cfc7025dd4fa9dd325ea97
100644 blob b93a4953fff68df523aa7656497ee339d6026d64    glyphicons-halflings-regular.eot
100644 blob 94fb5490a2ed10b2c69a4a567a4fd2e4f706d841    glyphicons-halflings-regular.svg
100644 blob 1413fc609ab6f21774de0cb7e01360095584f65b    glyphicons-halflings-regular.ttf
100644 blob 9e612858f802245ddcbf59788a0db942224bab35    glyphicons-halflings-regular.woff
100644 blob 64539b54c3751a6d9adb44c8e3a45ba5a73b77f0    glyphicons-halflings-regular.woff2

In the example above, 14032aabd85b43a058cfc7025dd4fa9dd325ea97 is the ID/SHA-1 of the directory that I wanted to explore. In this case, the result was that four files within that directory were being tracked by my Git repo. If the directory had additional files, it would mean those extra files were not being tracked. You can add files using git add <file>... of course.

“Unable to find manifest signing certificate in the certificate store” - even when add new key

I've finally found the solution and really hope this helps someone else too.

  1. Edit the .csproj file for the project in question.
  2. Delete the following lines of code:

    <PropertyGroup>
       <ManifestCertificateThumbprint>...........</ManifestCertificateThumbprint>
    </PropertyGroup>
    <PropertyGroup>
       <ManifestKeyFile>xxxxxxxx.pfx</ManifestKeyFile>
    </PropertyGroup>
    <PropertyGroup>
       <GenerateManifests>true</GenerateManifests>
    </PropertyGroup>
    <PropertyGroup>
       <SignManifests>false</SignManifests>
    </PropertyGroup>
    

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

You can find all of those operators in the Python language reference, though you'll have to scroll around a bit to find them all. As other answers have said:

  • The ** operator does exponentiation. a ** b is a raised to the b power. The same ** symbol is also used in function argument and calling notations, with a different meaning (passing and receiving arbitrary keyword arguments).
  • The ^ operator does a binary xor. a ^ b will return a value with only the bits set in a or in b but not both. This one is simple!
  • The % operator is mostly to find the modulus of two integers. a % b returns the remainder after dividing a by b. Unlike the modulus operators in some other programming languages (such as C), in Python a modulus it will have the same sign as b, rather than the same sign as a. The same operator is also used for the "old" style of string formatting, so a % b can return a string if a is a format string and b is a value (or tuple of values) which can be inserted into a.
  • The // operator does Python's version of integer division. Python's integer division is not exactly the same as the integer division offered by some other languages (like C), since it rounds towards negative infinity, rather than towards zero. Together with the modulus operator, you can say that a == (a // b)*b + (a % b). In Python 2, floor division is the default behavior when you divide two integers (using the normal division operator /). Since this can be unexpected (especially when you're not picky about what types of numbers you get as arguments to a function), Python 3 has changed to make "true" (floating point) division the norm for division that would be rounded off otherwise, and it will do "floor" division only when explicitly requested. (You can also get the new behavior in Python 2 by putting from __future__ import division at the top of your files. I strongly recommend it!)

Android Bitmap to Base64 String

use following method to convert bitmap to byte array:

ByteArrayOutputStream byteArrayOutputStream = new ByteArrayOutputStream();  
bitmap.compress(Bitmap.CompressFormat.PNG, 100, byteArrayOutputStream);
byte[] byteArray = byteArrayOutputStream .toByteArray();

to encode base64 from byte array use following method

String encoded = Base64.encodeToString(byteArray, Base64.DEFAULT);

Pure JavaScript equivalent of jQuery's $.ready() - how to call a function when the page/DOM is ready for it

I'm not quite sure what you're asking, but maybe this can help:

window.onload = function(){
    // Code. . .

}

Or:

window.onload = main;

function main(){
    // Code. . .

}

Use of def, val, and var in scala

With

def person = new Person("Kumar", 12) 

you are defining a function/lazy variable which always returns a new Person instance with name "Kumar" and age 12. This is totally valid and the compiler has no reason to complain. Calling person.age will return the age of this newly created Person instance, which is always 12.

When writing

person.age = 45

you assign a new value to the age property in class Person, which is valid since age is declared as var. The compiler will complain if you try to reassign person with a new Person object like

person = new Person("Steve", 13)  // Error

Get the filePath from Filename using Java

Look at the methods in the java.io.File class:

File file = new File("yourfileName");
String path = file.getAbsolutePath();

How to show Alert Message like "successfully Inserted" after inserting to DB using ASp.net MVC3

Personally I'd go with AJAX.

If you cannot switch to @Ajax... helpers, I suggest you to add a couple of properties in your model

public bool TriggerOnLoad { get; set; }
public string TriggerOnLoadMessage { get; set: }

Change your view to a strongly typed Model via

@using MyModel

Before returning the View, in case of successfull creation do something like

MyModel model = new MyModel();
model.TriggerOnLoad = true;
model.TriggerOnLoadMessage = "Object successfully created!";
return View ("Add", model);

then in your view, add this

@{
   if (model.TriggerOnLoad) {
   <text>
   <script type="text/javascript">
     alert('@Model.TriggerOnLoadMessage');
   </script>
   </text>
   }
}

Of course inside the tag you can choose to do anything you want, event declare a jQuery ready function:

$(document).ready(function () {
   alert('@Model.TriggerOnLoadMessage');
});

Please remember to reset the Model properties upon successfully alert emission.

Another nice thing about MVC is that you can actually define an EditorTemplate for all this, and then use it in your view via:

@Html.EditorFor (m => m.TriggerOnLoadMessage)

But in case you want to build up such a thing, maybe it's better to define your own C# class:

class ClientMessageNotification {
    public bool TriggerOnLoad { get; set; }
    public string TriggerOnLoadMessage { get; set: }
}

and add a ClientMessageNotification property in your model. Then write EditorTemplate / DisplayTemplate for the ClientMessageNotification class and you're done. Nice, clean, and reusable.

How to access accelerometer/gyroscope data from Javascript?

Can't add a comment to the excellent explanation in the other post but wanted to mention that a great documentation source can be found here.

It is enough to register an event function for accelerometer like so:

if(window.DeviceMotionEvent){
  window.addEventListener("devicemotion", motion, false);
}else{
  console.log("DeviceMotionEvent is not supported");
}

with the handler:

function motion(event){
  console.log("Accelerometer: "
    + event.accelerationIncludingGravity.x + ", "
    + event.accelerationIncludingGravity.y + ", "
    + event.accelerationIncludingGravity.z
  );
}

And for magnetometer a following event handler has to be registered:

if(window.DeviceOrientationEvent){
  window.addEventListener("deviceorientation", orientation, false);
}else{
  console.log("DeviceOrientationEvent is not supported");
}

with a handler:

function orientation(event){
  console.log("Magnetometer: "
    + event.alpha + ", "
    + event.beta + ", "
    + event.gamma
  );
}

There are also fields specified in the motion event for a gyroscope but that does not seem to be universally supported (e.g. it didn't work on a Samsung Galaxy Note).

There is a simple working code on GitHub

Batch file to delete folders older than 10 days in Windows 7

FORFILES /S /D -10 /C "cmd /c IF @isdir == TRUE rd /S /Q @path"

I could not get Blorgbeard's suggestion to work, but I was able to get it to work with RMDIR instead of RD:

FORFILES /p N:\test /S /D -10 /C "cmd /c IF @isdir == TRUE RMDIR /S /Q @path"

Since RMDIR won't delete folders that aren't empty so I also ended up using this code to delete the files that were over 10 days and then the folders that were over 10 days old.

FOR /d %%K in ("n:\test*") DO (

FOR /d %%J in ("%%K*") DO (

FORFILES /P %%J /S /M . /D -10 /C "cmd /c del @file"

)

)

FORFILES /p N:\test /S /D -10 /C "cmd /c IF @isdir == TRUE RMDIR /S /Q @path"

I used this code to purge out the sub folders in the folders within test (example n:\test\abc\123 would get purged when empty, but n:\test\abc would not get purged

Make element fixed on scroll

You can go to LESS CSS website http://lesscss.org/

Their dockable menu is light and performs well. The only caveat is that the effect takes place after the scroll is complete. Just do a view source to see the js.

I am getting Failed to load resource: net::ERR_BLOCKED_BY_CLIENT with Google chrome

Don't use keyworks like "ad", "ads", "advertise", etc. in image url or image class. Adblock block them automatically.

How can I change the color of AlertDialog title and the color of the line under it

Unfortunately, this is not a particularly simple task to accomplish. In my answer here, I detail how to adjust the color of a ListSeparator by just checking out the parent style used by Android, creating a new image, and creating a new style based on the original. Unfortunately, unlike with the ListSeparator's style, AlertDialog themes are internal, and therefore cannot be referenced as parent styles. There is no easy way to change that little blue line! Thus you need to resort to making custom dialogs.

If that just isn't your cup of tea... don't give up! I was very disturbed that there was no easy way to do this so I set up a little project on github for making quickly customized holo-style dialogs (assuming that the phone supports the Holo style). You can find the project here: https://github.com/danoz73/QustomDialog

It should easily enable going from boring blue to exciting orange!

enter image description here

The project is basically an example of using a custom dialog builder, and in the example I created a custom view that seemed to cater to the IP Address example you give in your original question.

With QustomDialog, in order to create a basic dialog (title, message) with a desired different color for the title or divider, you use the following code:

private String HALLOWEEN_ORANGE = "#FF7F27";

QustomDialogBuilder qustomDialogBuilder = new QustomDialogBuilder(v.getContext()).
    setTitle("Set IP Address").
    setTitleColor(HALLOWEEN_ORANGE).
    setDividerColor(HALLOWEEN_ORANGE).
    setMessage("You are now entering the 10th dimension.");

qustomDialogBuilder.show();

And in order to add a custom layout (say, to add the little IP address EditText), you add

setCustomView(R.layout.example_ip_address_layout, v.getContext())

to the builder with a layout that you have designed (the IP example can be found in the github). I hope this helps. Many thanks to Joseph Earl and his answer here.

Why should I use var instead of a type?

It's really just a coding style. The compiler generates the exact same for both variants.

See also here for the performance question:

Where does PostgreSQL store the database?

Open pgAdmin and go to Properties for specific database. Find OID and then open directory

<POSTGRESQL_DIRECTORY>/data/base/<OID>

There should be your DB files.

What is 'PermSize' in Java?

A quick definition of the "permanent generation":

"The permanent generation is used to hold reflective data of the VM itself such as class objects and method objects. These reflective objects are allocated directly into the permanent generation, and it is sized independently from the other generations." [ref]

In other words, this is where class definitions go (and this explains why you may get the message OutOfMemoryError: PermGen space if an application loads a large number of classes and/or on redeployment).

Note that PermSize is additional to the -Xmx value set by the user on the JVM options. But MaxPermSize allows for the JVM to be able to grow the PermSize to the amount specified. Initially when the VM is loaded, the MaxPermSize will still be the default value (32mb for -client and 64mb for -server) but will not actually take up that amount until it is needed. On the other hand, if you were to set BOTH PermSize and MaxPermSize to 256mb, you would notice that the overall heap has increased by 256mb additional to the -Xmx setting.

Set an empty DateTime variable

There's no such thing as an empty date per se, do you mean something like:

DateTime? myDateTime = null;

Cannot kill Python script with Ctrl-C

KeyboardInterrupt and signals are only seen by the process (ie the main thread)... Have a look at Ctrl-c i.e. KeyboardInterrupt to kill threads in python

Something like 'contains any' for Java set?

A good way to implement containsAny for sets is using the Guava Sets.intersection().

containsAny would return a boolean, so the call looks like:

Sets.intersection(set1, set2).isEmpty()

This returns true iff the sets are disjoint, otherwise false. The time complexity of this is likely slightly better than retainAll because you dont have to do any cloning to avoid modifying your original set.

Failed to build gem native extension (installing Compass)

Try brew install coreutils.

I've hit this problem while rebuilding an aging sass/compass project that was recently updated to ruby 2.2.5 by a colleague. The project uses rvm and bundler. These were my commands

$ rvm install ruby-2.2.5
$ rvm use ruby-2.2.5
$ gem install bundler
$ bundle install

This caused me to hit the famed ffi installation errors, that are reported around the StackOverflow environment:

An error occurred while installing ffi (1.9.14), and Bundler cannot continue.

Most of the suggestions to solve this problem are to install Xcode command line tools. However this was already installed in my environment:

$ xcode-select -p
/Library/Developer/CommandLineTools

Other suggestions said to install gcc... so I tried:

$ brew install gcc46

But this also failed due to a segmentation fault... ¯\_(?)_/¯.

So, I then tried installing compass by hand, just to see if it would give the same ffi error:

$ gem install compass

But to my surprise, I got a totally different error:

make: /usr/local/bin/gmkdir: No such file or directory

So I searched for that issue, and found this ancient blog post that said to install coreutils:

$ brew install coreutils

After installing coreutils with Homebrew, bundler was able to finish and installed compass and dependencies successfully.

The End.

update to python 3.7 using anaconda

To see just the Python releases, do conda search --full-name python.

Regex using javascript to return just numbers

If you want only digits:

var value = '675-805-714';
var numberPattern = /\d+/g;
value = value.match( numberPattern ).join([]);
alert(value);
//Show: 675805714

Now you get the digits joined

How to make a countdown timer in Android?

Just Call below function by passing seconds and textview object

public void reverseTimer(int Seconds,final TextView tv){

    new CountDownTimer(Seconds* 1000+1000, 1000) {

        public void onTick(long millisUntilFinished) {
            int seconds = (int) (millisUntilFinished / 1000);
            int minutes = seconds / 60;
            seconds = seconds % 60;
            tv.setText("TIME : " + String.format("%02d", minutes)
                    + ":" + String.format("%02d", seconds));
        }

        public void onFinish() {
            tv.setText("Completed");
        }
    }.start();
}

Unix ls command: show full path when using options

optimized from spacedrop answer ...

ls $(pwd)/*

and you can use ls options

ls -alrt $(pwd)/*

What is the bower (and npm) version syntax?

Bower uses semver syntax, but here are a few quick examples:

You can install a specific version:

$ bower install jquery#1.11.1

You can use ~ to specify 'any version that starts with this':

$ bower install jquery#~1.11

You can specify multiple version requirements together:

$ bower install "jquery#<2.0 >1.10"

Email & Phone Validation in Swift

File-New-File.Make a Swift class named AppExtension.Add the following.

        extension UIViewController{
            func validateEmailAndGetBoolValue(candidate: String) -> Bool {
                let emailRegex = "[A-Z0-9a-z._%+-]+@[A-Za-z0-9.-]+\\.[A-Za-z]{2,6}"
                return NSPredicate(format: "SELF MATCHES %@", emailRegex).evaluateWithObject(candidate)
            }
        }

        Use: 
        var emailValidator:Bool?
        self.emailValidator =  self.validateEmailAndGetBoolValue(resetEmail!)
                        print("emailValidator : "+String(self.emailValidator?.boolValue))

        Use a loop to alternate desired results.


    OR
        extension String
        {
        //Validate Email
            var isEmail: Bool {
                do {
                    let regex = try NSRegularExpression(pattern: "^[a-zA-Z0-9.!#$%&'*+/=?^_`{|}~-]+@[a-zA-Z0-9](?:[a-zA-Z0-9-]{0,61}[a-zA-Z0-9])?(?:\\.[a-zA-Z0-9](?:[a-zA-Z0-9-]{0,61}[a-zA-Z0-9])?)*$", options: .CaseInsensitive)
                    return regex.firstMatchInString(self, options: NSMatchingOptions(rawValue: 0), range: NSMakeRange(0, self.characters.count)) != nil
                } catch {
                    return false
                }

            }
        }

        Use:
        if(resetEmail!.isEmail)
                        {
                        AppController().requestResetPassword(resetEmail!)
                        self.view.makeToast(message: "Sending OTP")
                        }
                        else
                        {
                            self.view.makeToast(message: "Please enter a valid email")
                        }

How to scan a folder in Java?

Not sure how you want to represent the tree? Anyway here's an example which scans the entire subtree using recursion. Files and directories are treated alike. Note that File.listFiles() returns null for non-directories.

public static void main(String[] args) {
    Collection<File> all = new ArrayList<File>();
    addTree(new File("."), all);
    System.out.println(all);
}

static void addTree(File file, Collection<File> all) {
    File[] children = file.listFiles();
    if (children != null) {
        for (File child : children) {
            all.add(child);
            addTree(child, all);
        }
    }
}

Java 7 offers a couple of improvements. For example, DirectoryStream provides one result at a time - the caller no longer has to wait for all I/O operations to complete before acting. This allows incremental GUI updates, early cancellation, etc.

static void addTree(Path directory, Collection<Path> all)
        throws IOException {
    try (DirectoryStream<Path> ds = Files.newDirectoryStream(directory)) {
        for (Path child : ds) {
            all.add(child);
            if (Files.isDirectory(child)) {
                addTree(child, all);
            }
        }
    }
}

Note that the dreaded null return value has been replaced by IOException.

Java 7 also offers a tree walker:

static void addTree(Path directory, final Collection<Path> all)
        throws IOException {
    Files.walkFileTree(directory, new SimpleFileVisitor<Path>() {
        @Override
        public FileVisitResult visitFile(Path file, BasicFileAttributes attrs)
                throws IOException {
            all.add(file);
            return FileVisitResult.CONTINUE;
        }
    });
}

How to use componentWillMount() in React Hooks?

This is the way how I simulate constructor in functional components using the useRef hook:

function Component(props) {
    const willMount = useRef(true);
    if (willMount.current) {
        console.log('This runs only once before rendering the component.');
        willMount.current = false;        
    }

    return (<h1>Meow world!</h1>);
}

Here is the lifecycle example:

function RenderLog(props) {
    console.log('Render log: ' + props.children);
    return (<>{props.children}</>);
}

function Component(props) {

    console.log('Body');
    const [count, setCount] = useState(0);
    const willMount = useRef(true);

    if (willMount.current) {
        console.log('First time load (it runs only once)');
        setCount(2);
        willMount.current = false;
    } else {
        console.log('Repeated load');
    }

    useEffect(() => {
        console.log('Component did mount (it runs only once)');
        return () => console.log('Component will unmount');
    }, []);

    useEffect(() => {
        console.log('Component did update');
    });

    useEffect(() => {
        console.log('Component will receive props');
    }, [count]);


    return (
        <>
        <h1>{count}</h1>
        <RenderLog>{count}</RenderLog>
        </>
    );
}
[Log] Body
[Log] First time load (it runs only once)
[Log] Body
[Log] Repeated load
[Log] Render log: 2
[Log] Component did mount (it runs only once)
[Log] Component did update
[Log] Component will receive props

Of course Class components don't have Body steps, it's not possible to make 1:1 simulation due to different concepts of functions and classes.

What does `return` keyword mean inside `forEach` function?

The return exits the current function, but the iterations keeps on, so you get the "next" item that skips the if and alerts the 4...

If you need to stop the looping, you should just use a plain for loop like so:

$('button').click(function () {
   var arr = [1, 2, 3, 4, 5];
   for(var i = 0; i < arr.length; i++) {
     var n = arr[i]; 
     if (n == 3) {
         break;
      }
      alert(n);
   })
})

You can read more about js break & continue here: http://www.w3schools.com/js/js_break.asp

check the null terminating character in char*

To make this complete: while others now solved your problem :) I would like to give you a piece of good advice: don't reinvent the wheel.

size_t forward_length = strlen(forward);

Crop image in PHP

$image = imagecreatefromjpeg($_GET['src']);

Needs to be replaced with this:

$image = imagecreatefromjpeg('images/thumbnails/myimage.jpg');

Because imagecreatefromjpeg() is expecting a string.
This worked for me.

ref:
http://php.net/manual/en/function.imagecreatefromjpeg.php

How to unbind a listener that is calling event.preventDefault() (using jQuery)?

Disable:

document.ontouchstart = function(e){ e.preventDefault(); }

Enable:

document.ontouchstart = function(e){ return true; }

What is the Swift equivalent of isEqualToString in Objective-C?

Actually, it feels like swift is trying to promote strings to be treated less like objects and more like values. However this doesn't mean under the hood swift doesn't treat strings as objects, as am sure you all noticed that you can still invoke methods on strings and use their properties.

For example:-

//example of calling method (String to Int conversion)
let intValue = ("12".toInt())
println("This is a intValue now \(intValue)")


//example of using properties (fetching uppercase value of string)
let caUpperValue = "ca".uppercaseString
println("This is the uppercase of ca \(caUpperValue)")

In objectC you could pass the reference to a string object through a variable, on top of calling methods on it, which pretty much establishes the fact that strings are pure objects.

Here is the catch when you try to look at String as objects, in swift you cannot pass a string object by reference through a variable. Swift will always pass a brand new copy of the string. Hence, strings are more commonly known as value types in swift. In fact, two string literals will not be identical (===). They are treated as two different copies.

let curious = ("ca" === "ca")
println("This will be false.. and the answer is..\(curious)")

As you can see we are starting to break aways from the conventional way of thinking of strings as objects and treating them more like values. Hence .isEqualToString which was treated as an identity operator for string objects is no more a valid as you can never get two identical string objects in Swift. You can only compare its value, or in other words check for equality(==).

 let NotSoCuriousAnyMore = ("ca" == "ca")
 println("This will be true.. and the answer is..\(NotSoCuriousAnyMore)")

This gets more interesting when you look at the mutability of string objects in swift. But thats for another question, another day. Something you should probably look into, cause its really interesting. :) Hope that clears up some confusion. Cheers!

How to deal with persistent storage (e.g. databases) in Docker

When using Docker Compose, simply attach a named volume, for example:

version: '2'
services:
  db:
    image: mysql:5.6
    volumes:
      - db_data:/var/lib/mysql:rw
    environment:
      MYSQL_ROOT_PASSWORD: root
volumes:
  db_data:

What are Runtime.getRuntime().totalMemory() and freeMemory()?

According to the API

totalMemory()

Returns the total amount of memory in the Java virtual machine. The value returned by this method may vary over time, depending on the host environment. Note that the amount of memory required to hold an object of any given type may be implementation-dependent.

maxMemory()

Returns the maximum amount of memory that the Java virtual machine will attempt to use. If there is no inherent limit then the value Long.MAX_VALUE will be returned.

freeMemory()

Returns the amount of free memory in the Java Virtual Machine. Calling the gc method may result in increasing the value returned by freeMemory.

In reference to your question, maxMemory() returns the -Xmx value.

You may be wondering why there is a totalMemory() AND a maxMemory(). The answer is that the JVM allocates memory lazily. Lets say you start your Java process as such:

java -Xms64m -Xmx1024m Foo

Your process starts with 64mb of memory, and if and when it needs more (up to 1024m), it will allocate memory. totalMemory() corresponds to the amount of memory currently available to the JVM for Foo. If the JVM needs more memory, it will lazily allocate it up to the maximum memory. If you run with -Xms1024m -Xmx1024m, the value you get from totalMemory() and maxMemory() will be equal.

Also, if you want to accurately calculate the amount of used memory, you do so with the following calculation :

final long usedMem = totalMemory() - freeMemory();

What's the difference between ISO 8601 and RFC 3339 Date Formats?

Is one just an extension?

Pretty much, yes - RFC 3339 is listed as a profile of ISO 8601. Most notably RFC 3339 specifies a complete representation of date and time (only fractional seconds are optional). The RFC also has some small, subtle differences. For example truncated representations of years with only two digits are not allowed -- RFC 3339 requires 4-digit years, and the RFC only allows a period character to be used as the decimal point for fractional seconds. The RFC also allows the "T" to be replaced by a space (or other character), while the standard only allows it to be omitted (and only when there is agreement between all parties using the representation).

I wouldn't worry too much about the differences between the two, but on the off-chance your use case runs in to them, it'd be worth your while taking a glance at:

Text size of android design TabLayout tabs

TabLayout  tab_layout = (TabLayout)findViewById(R.id.tab_Layout_);

private void changeTabsFont() {
    Typeface font = Typeface.createFromAsset(getActivity().getAssets(), "fonts/"+ Constants.FontStyle);
    ViewGroup vg = (ViewGroup) tab_layout.getChildAt(0);
    int tabsCount = vg.getChildCount();
    for (int j = 0; j < tabsCount; j++) {
        ViewGroup vgTab = (ViewGroup) vg.getChildAt(j);
        int tabChildsCount = vgTab.getChildCount();
        for (int i = 0; i < tabChildsCount; i++) {
            View tabViewChild = vgTab.getChildAt(i);
            if (tabViewChild instanceof TextView) {
                ((TextView) tabViewChild).setTypeface(font);
                ((TextView) tabViewChild).setTextSize(15);

            }
        }
    }
}

This code is works for me using tablayout. It will change size of fonts and also change font style.

This will also help you guys please check this link

https://stackoverflow.com/a/43156384/5973946

This code works for Tablayout change text color,type face (font style) and also text size.

How to read a file into a variable in shell?

You can access 1 line at a time by for loop

#!/bin/bash -eu

#This script prints contents of /etc/passwd line by line

FILENAME='/etc/passwd'
I=0
for LN in $(cat $FILENAME)
do
    echo "Line number $((I++)) -->  $LN"
done

Copy the entire content to File (say line.sh ) ; Execute

chmod +x line.sh
./line.sh

Alter table to modify default value of column

Your belief about what will happen is not correct. Setting a default value for a column will not affect the existing data in the table.

I create a table with a column col2 that has no default value

SQL> create table foo(
  2    col1 number primary key,
  3    col2 varchar2(10)
  4  );

Table created.

SQL> insert into foo( col1 ) values (1);

1 row created.

SQL> insert into foo( col1 ) values (2);

1 row created.

SQL> insert into foo( col1 ) values (3);

1 row created.

SQL> select * from foo;

      COL1 COL2
---------- ----------
         1
         2
         3

If I then alter the table to set a default value, nothing about the existing rows will change

SQL> alter table foo
  2    modify( col2 varchar2(10) default 'foo' );

Table altered.

SQL> select * from foo;

      COL1 COL2
---------- ----------
         1
         2
         3

SQL> insert into foo( col1 ) values (4);

1 row created.

SQL> select * from foo;

      COL1 COL2
---------- ----------
         1
         2
         3
         4 foo

Even if I subsequently change the default again, there will still be no change to the existing rows

SQL> alter table foo
  2    modify( col2 varchar2(10) default 'bar' );

Table altered.

SQL> select * from foo;

      COL1 COL2
---------- ----------
         1
         2
         3
         4 foo

SQL> insert into foo( col1 ) values (5);

1 row created.

SQL> select * from foo;

      COL1 COL2
---------- ----------
         1
         2
         3
         4 foo
         5 bar

How to escape JSON string?

Yep, just add the following function to your Utils class or something:

    public static string cleanForJSON(string s)
    {
        if (s == null || s.Length == 0) {
            return "";
        }

        char         c = '\0';
        int          i;
        int          len = s.Length;
        StringBuilder sb = new StringBuilder(len + 4);
        String       t;

        for (i = 0; i < len; i += 1) {
            c = s[i];
            switch (c) {
                case '\\':
                case '"':
                    sb.Append('\\');
                    sb.Append(c);
                    break;
                case '/':
                    sb.Append('\\');
                    sb.Append(c);
                    break;
                case '\b':
                    sb.Append("\\b");
                    break;
                case '\t':
                    sb.Append("\\t");
                    break;
                case '\n':
                    sb.Append("\\n");
                    break;
                case '\f':
                    sb.Append("\\f");
                    break;
                case '\r':
                    sb.Append("\\r");
                    break;
                default:
                    if (c < ' ') {
                        t = "000" + String.Format("X", c);
                        sb.Append("\\u" + t.Substring(t.Length - 4));
                    } else {
                        sb.Append(c);
                    }
                    break;
            }
        }
        return sb.ToString();
    }

How Spring Security Filter Chain works

The Spring security filter chain is a very complex and flexible engine.

Key filters in the chain are (in the order)

  • SecurityContextPersistenceFilter (restores Authentication from JSESSIONID)
  • UsernamePasswordAuthenticationFilter (performs authentication)
  • ExceptionTranslationFilter (catch security exceptions from FilterSecurityInterceptor)
  • FilterSecurityInterceptor (may throw authentication and authorization exceptions)

Looking at the current stable release 4.2.1 documentation, section 13.3 Filter Ordering you could see the whole filter chain's filter organization:

13.3 Filter Ordering

The order that filters are defined in the chain is very important. Irrespective of which filters you are actually using, the order should be as follows:

  1. ChannelProcessingFilter, because it might need to redirect to a different protocol

  2. SecurityContextPersistenceFilter, so a SecurityContext can be set up in the SecurityContextHolder at the beginning of a web request, and any changes to the SecurityContext can be copied to the HttpSession when the web request ends (ready for use with the next web request)

  3. ConcurrentSessionFilter, because it uses the SecurityContextHolder functionality and needs to update the SessionRegistry to reflect ongoing requests from the principal

  4. Authentication processing mechanisms - UsernamePasswordAuthenticationFilter, CasAuthenticationFilter, BasicAuthenticationFilter etc - so that the SecurityContextHolder can be modified to contain a valid Authentication request token

  5. The SecurityContextHolderAwareRequestFilter, if you are using it to install a Spring Security aware HttpServletRequestWrapper into your servlet container

  6. The JaasApiIntegrationFilter, if a JaasAuthenticationToken is in the SecurityContextHolder this will process the FilterChain as the Subject in the JaasAuthenticationToken

  7. RememberMeAuthenticationFilter, so that if no earlier authentication processing mechanism updated the SecurityContextHolder, and the request presents a cookie that enables remember-me services to take place, a suitable remembered Authentication object will be put there

  8. AnonymousAuthenticationFilter, so that if no earlier authentication processing mechanism updated the SecurityContextHolder, an anonymous Authentication object will be put there

  9. ExceptionTranslationFilter, to catch any Spring Security exceptions so that either an HTTP error response can be returned or an appropriate AuthenticationEntryPoint can be launched

  10. FilterSecurityInterceptor, to protect web URIs and raise exceptions when access is denied

Now, I'll try to go on by your questions one by one:

I'm confused how these filters are used. Is it that for the spring provided form-login, UsernamePasswordAuthenticationFilter is only used for /login, and latter filters are not? Does the form-login namespace element auto-configure these filters? Does every request (authenticated or not) reach FilterSecurityInterceptor for non-login url?

Once you are configuring a <security-http> section, for each one you must at least provide one authentication mechanism. This must be one of the filters which match group 4 in the 13.3 Filter Ordering section from the Spring Security documentation I've just referenced.

This is the minimum valid security:http element which can be configured:

<security:http authentication-manager-ref="mainAuthenticationManager" 
               entry-point-ref="serviceAccessDeniedHandler">
    <security:intercept-url pattern="/sectest/zone1/**" access="hasRole('ROLE_ADMIN')"/>
</security:http>

Just doing it, these filters are configured in the filter chain proxy:

{
        "1": "org.springframework.security.web.context.SecurityContextPersistenceFilter",
        "2": "org.springframework.security.web.context.request.async.WebAsyncManagerIntegrationFilter",
        "3": "org.springframework.security.web.header.HeaderWriterFilter",
        "4": "org.springframework.security.web.csrf.CsrfFilter",
        "5": "org.springframework.security.web.savedrequest.RequestCacheAwareFilter",
        "6": "org.springframework.security.web.servletapi.SecurityContextHolderAwareRequestFilter",
        "7": "org.springframework.security.web.authentication.AnonymousAuthenticationFilter",
        "8": "org.springframework.security.web.session.SessionManagementFilter",
        "9": "org.springframework.security.web.access.ExceptionTranslationFilter",
        "10": "org.springframework.security.web.access.intercept.FilterSecurityInterceptor"
    }

Note: I get them by creating a simple RestController which @Autowires the FilterChainProxy and returns it's contents:

    @Autowired
    private FilterChainProxy filterChainProxy;

    @Override
    @RequestMapping("/filterChain")
    public @ResponseBody Map<Integer, Map<Integer, String>> getSecurityFilterChainProxy(){
        return this.getSecurityFilterChainProxy();
    }

    public Map<Integer, Map<Integer, String>> getSecurityFilterChainProxy(){
        Map<Integer, Map<Integer, String>> filterChains= new HashMap<Integer, Map<Integer, String>>();
        int i = 1;
        for(SecurityFilterChain secfc :  this.filterChainProxy.getFilterChains()){
            //filters.put(i++, secfc.getClass().getName());
            Map<Integer, String> filters = new HashMap<Integer, String>();
            int j = 1;
            for(Filter filter : secfc.getFilters()){
                filters.put(j++, filter.getClass().getName());
            }
            filterChains.put(i++, filters);
        }
        return filterChains;
    }

Here we could see that just by declaring the <security:http> element with one minimum configuration, all the default filters are included, but none of them is of a Authentication type (4th group in 13.3 Filter Ordering section). So it actually means that just by declaring the security:http element, the SecurityContextPersistenceFilter, the ExceptionTranslationFilter and the FilterSecurityInterceptor are auto-configured.

In fact, one authentication processing mechanism should be configured, and even security namespace beans processing claims for that, throwing an error during startup, but it can be bypassed adding an entry-point-ref attribute in <http:security>

If I add a basic <form-login> to the configuration, this way:

<security:http authentication-manager-ref="mainAuthenticationManager">
    <security:intercept-url pattern="/sectest/zone1/**" access="hasRole('ROLE_ADMIN')"/>
    <security:form-login />
</security:http>

Now, the filterChain will be like this:

{
        "1": "org.springframework.security.web.context.SecurityContextPersistenceFilter",
        "2": "org.springframework.security.web.context.request.async.WebAsyncManagerIntegrationFilter",
        "3": "org.springframework.security.web.header.HeaderWriterFilter",
        "4": "org.springframework.security.web.csrf.CsrfFilter",
        "5": "org.springframework.security.web.authentication.UsernamePasswordAuthenticationFilter",
        "6": "org.springframework.security.web.authentication.ui.DefaultLoginPageGeneratingFilter",
        "7": "org.springframework.security.web.savedrequest.RequestCacheAwareFilter",
        "8": "org.springframework.security.web.servletapi.SecurityContextHolderAwareRequestFilter",
        "9": "org.springframework.security.web.authentication.AnonymousAuthenticationFilter",
        "10": "org.springframework.security.web.session.SessionManagementFilter",
        "11": "org.springframework.security.web.access.ExceptionTranslationFilter",
        "12": "org.springframework.security.web.access.intercept.FilterSecurityInterceptor"
    }

Now, this two filters org.springframework.security.web.authentication.UsernamePasswordAuthenticationFilter and org.springframework.security.web.authentication.ui.DefaultLoginPageGeneratingFilter are created and configured in the FilterChainProxy.

So, now, the questions:

Is it that for the spring provided form-login, UsernamePasswordAuthenticationFilter is only used for /login, and latter filters are not?

Yes, it is used to try to complete a login processing mechanism in case the request matches the UsernamePasswordAuthenticationFilter url. This url can be configured or even changed it's behaviour to match every request.

You could too have more than one Authentication processing mechanisms configured in the same FilterchainProxy (such as HttpBasic, CAS, etc).

Does the form-login namespace element auto-configure these filters?

No, the form-login element configures the UsernamePasswordAUthenticationFilter, and in case you don't provide a login-page url, it also configures the org.springframework.security.web.authentication.ui.DefaultLoginPageGeneratingFilter, which ends in a simple autogenerated login page.

The other filters are auto-configured by default just by creating a <security:http> element with no security:"none" attribute.

Does every request (authenticated or not) reach FilterSecurityInterceptor for non-login url?

Every request should reach it, as it is the element which takes care of whether the request has the rights to reach the requested url. But some of the filters processed before might stop the filter chain processing just not calling FilterChain.doFilter(request, response);. For example, a CSRF filter might stop the filter chain processing if the request has not the csrf parameter.

What if I want to secure my REST API with JWT-token, which is retrieved from login? I must configure two namespace configuration http tags, rights? Other one for /login with UsernamePasswordAuthenticationFilter, and another one for REST url's, with custom JwtAuthenticationFilter.

No, you are not forced to do this way. You could declare both UsernamePasswordAuthenticationFilter and the JwtAuthenticationFilter in the same http element, but it depends on the concrete behaviour of each of this filters. Both approaches are possible, and which one to choose finnally depends on own preferences.

Does configuring two http elements create two springSecurityFitlerChains?

Yes, that's true

Is UsernamePasswordAuthenticationFilter turned off by default, until I declare form-login?

Yes, you could see it in the filters raised in each one of the configs I posted

How do I replace SecurityContextPersistenceFilter with one, which will obtain Authentication from existing JWT-token rather than JSESSIONID?

You could avoid SecurityContextPersistenceFilter, just configuring session strategy in <http:element>. Just configure like this:

<security:http create-session="stateless" >

Or, In this case you could overwrite it with another filter, this way inside the <security:http> element:

<security:http ...>  
   <security:custom-filter ref="myCustomFilter" position="SECURITY_CONTEXT_FILTER"/>    
</security:http>
<beans:bean id="myCustomFilter" class="com.xyz.myFilter" />

EDIT:

One question about "You could too have more than one Authentication processing mechanisms configured in the same FilterchainProxy". Will the latter overwrite the authentication performed by first one, if declaring multiple (Spring implementation) authentication filters? How this relates to having multiple authentication providers?

This finally depends on the implementation of each filter itself, but it's true the fact that the latter authentication filters at least are able to overwrite any prior authentication eventually made by preceding filters.

But this won't necesarily happen. I have some production cases in secured REST services where I use a kind of authorization token which can be provided both as a Http header or inside the request body. So I configure two filters which recover that token, in one case from the Http Header and the other from the request body of the own rest request. It's true the fact that if one http request provides that authentication token both as Http header and inside the request body, both filters will try to execute the authentication mechanism delegating it to the manager, but it could be easily avoided simply checking if the request is already authenticated just at the begining of the doFilter() method of each filter.

Having more than one authentication filter is related to having more than one authentication providers, but don't force it. In the case I exposed before, I have two authentication filter but I only have one authentication provider, as both of the filters create the same type of Authentication object so in both cases the authentication manager delegates it to the same provider.

And opposite to this, I too have a scenario where I publish just one UsernamePasswordAuthenticationFilter but the user credentials both can be contained in DB or LDAP, so I have two UsernamePasswordAuthenticationToken supporting providers, and the AuthenticationManager delegates any authentication attempt from the filter to the providers secuentially to validate the credentials.

So, I think it's clear that neither the amount of authentication filters determine the amount of authentication providers nor the amount of provider determine the amount of filters.

Also, documentation states SecurityContextPersistenceFilter is responsible of cleaning the SecurityContext, which is important due thread pooling. If I omit it or provide custom implementation, I have to implement the cleaning manually, right? Are there more similar gotcha's when customizing the chain?

I did not look carefully into this filter before, but after your last question I've been checking it's implementation, and as usually in Spring, nearly everything could be configured, extended or overwrited.

The SecurityContextPersistenceFilter delegates in a SecurityContextRepository implementation the search for the SecurityContext. By default, a HttpSessionSecurityContextRepository is used, but this could be changed using one of the constructors of the filter. So it may be better to write an SecurityContextRepository which fits your needs and just configure it in the SecurityContextPersistenceFilter, trusting in it's proved behaviour rather than start making all from scratch.

How can I discard remote changes and mark a file as "resolved"?

Make sure of the conflict origin: if it is the result of a git merge, see Brian Campbell's answer.

But if is the result of a git rebase, in order to discard remote (their) changes and use local changes, you would have to do a:

git checkout --theirs -- .

See "Why is the meaning of “ours” and “theirs” reversed"" to see how ours and theirs are swapped during a rebase (because the upstream branch is checked out).

React - Component Full Screen (with height 100%)

I managed this with a css class in my app.css

.fill-window {
    height: 100%;
    position: absolute;
    left: 0;
    width: 100%;
    overflow: hidden;
}

Apply it to your root element in your render() method

render() {
   return ( <div className="fill-window">{content}</div> );
}

Or inline

render() {
   return (
      <div style={{ height: '100%', position: 'absolute', left: '0px', width: '100%', overflow: 'hidden'}}>
          {content}
      </div>
   );
}

JavaScript moving element in the DOM

jQuery.fn.swap = function(b){ 
    b = jQuery(b)[0]; 
    var a = this[0]; 
    var t = a.parentNode.insertBefore(document.createTextNode(''), a); 
    b.parentNode.insertBefore(a, b); 
    t.parentNode.insertBefore(b, t); 
    t.parentNode.removeChild(t); 
    return this; 
};

and use it like this:

$('#div1').swap('#div2');

if you don't want to use jQuery you could easily adapt the function.

How to install cron

Do you have a Windows machine or a Linux machine?

Under Windows cron is called 'Scheduled Tasks'. It's located in the Control Panel. You can set several scripts to run at specified times in the control panel. Use the wizard to define the scheduled times. Be sure that PHP is callable in your PATH.

Under Linux you can create a crontab for your current user by typing:

crontab -e [username]

If this command fails, it's likely that cron is not installed. If you use a Debian based system (Debian, Ubuntu), try the following commands first:

sudo apt-get update
sudo apt-get install cron

If the command runs properly, a text editor will appear. Now you can add command lines to the crontab file. To run something every five minutes:

*/5 * * * *  /home/user/test.pl

The syntax is basically this:

.---------------- minute (0 - 59) 
|  .------------- hour (0 - 23)
|  |  .---------- day of month (1 - 31)
|  |  |  .------- month (1 - 12) OR jan,feb,mar,apr ... 
|  |  |  |  .---- day of week (0 - 6) (Sunday=0 or 7)  OR sun,mon,tue,wed,thu,fri,sat 
|  |  |  |  |
*  *  *  *  *  command to be executed

Read more about it on the following pages: Wikipedia: crontab

C# - Create SQL Server table programmatically

using System;
using System.Data;
using System.Data.SqlClient;

namespace SqlCommend
{
    class sqlcreateapp
    {
        static void Main(string[] args)
        {
            try
            {
                SqlConnection conn = new SqlConnection("Data source=USER-PC; Database=Emp123;User Id=sa;Password=sa123");
                SqlCommand cmd = new SqlCommand("create table <Table Name>(empno int,empname varchar(50),salary money);", conn);
                conn.Open();
                cmd.ExecuteNonQuery();
                Console.WriteLine("Table Created Successfully...");
                conn.Close();
            }
            catch(Exception e)
            {
                Console.WriteLine("exception occured while creating table:" + e.Message + "\t" + e.GetType());
            }
            Console.ReadKey();
        }
    }
}

Java: how to convert HashMap<String, Object> to array

If you are using Java 8+ and need a 2 dimensional Array, perhaps for TestNG data providers, you can try:

map.entrySet()
    .stream()
    .map(e -> new Object[]{e.getKey(), e.getValue()})
    .toArray(Object[][]::new);

If your Objects are Strings and you need a String[][], try:

map.entrySet()
    .stream()
    .map(e -> new String[]{e.getKey(), e.getValue().toString()})
    .toArray(String[][]::new);

How can I use iptables on centos 7?

And to add, you should also be able to do the same for ip6tables after running the systemctl mask firewalld command:

    systemctl start ip6tables.service
    systemctl enable ip6tables.service

PostgreSQL how to see which queries have run

PostgreSql is very advanced when related to logging techniques

Logs are stored in Installationfolder/data/pg_log folder. While log settings are placed in postgresql.conf file.

Log format is usually set as stderr. But CSV log format is recommended. In order to enable CSV format change in

log_destination = 'stderr,csvlog'   
logging_collector = on

In order to log all queries, very usefull for new installations, set min. execution time for a query

log_min_duration_statement = 0

In order to view active Queries on your database, use

SELECT * FROM pg_stat_activity

To log specific queries set query type

log_statement = 'all'           # none, ddl, mod, all

For more information on Logging queries see PostgreSql Log.

Automatically resize jQuery UI dialog to the width of the content loaded by ajax

I had this problem as well.

I got it working with this:

.ui-dialog{
    display:inline-block;
}

No 'Access-Control-Allow-Origin' - Node / Apache Port Issue

app.all('*', function(req, res,next) {
    /**
     * Response settings
     * @type {Object}
     */
    var responseSettings = {
        "AccessControlAllowOrigin": req.headers.origin,
        "AccessControlAllowHeaders": "Content-Type,X-CSRF-Token, X-Requested-With, Accept, Accept-Version, Content-Length, Content-MD5,  Date, X-Api-Version, X-File-Name",
        "AccessControlAllowMethods": "POST, GET, PUT, DELETE, OPTIONS",
        "AccessControlAllowCredentials": true
    };

    /**
     * Headers
     */
    res.header("Access-Control-Allow-Credentials", responseSettings.AccessControlAllowCredentials);
    res.header("Access-Control-Allow-Origin",  responseSettings.AccessControlAllowOrigin);
    res.header("Access-Control-Allow-Headers", (req.headers['access-control-request-headers']) ? req.headers['access-control-request-headers'] : "x-requested-with");
    res.header("Access-Control-Allow-Methods", (req.headers['access-control-request-method']) ? req.headers['access-control-request-method'] : responseSettings.AccessControlAllowMethods);

    if ('OPTIONS' == req.method) {
        res.send(200);
    }
    else {
        next();
    }


});

React Native Responsive Font Size

Take a look at the library I wrote: https://github.com/tachyons-css/react-native-style-tachyons

It allows you to specify a root-fontSize (rem) upon start, which you can make dependent of your PixelRatio or other device-characteristics.

Then you get styles relative to your rem, not only fontSize, but paddings etc. as well:

<Text style={[s.f5, s.pa2, s.tc]}>
     Something
</Text>

Expanation:

  • f5is always your base-fontsize
  • pa2 gives you padding relative to your base-fontsize.

Batch File; List files in directory, only filenames?

The full command is:

dir /b /a-d

Let me break it up;

Basically the /b is what you look for.

/a-d will exclude the directory names.


For more information see dir /? for other arguments that you can use with the dir command.

How to read a file in Groovy into a string?

String fileContents = new File('/path/to/file').text

If you need to specify the character encoding, use the following instead:

String fileContents = new File('/path/to/file').getText('UTF-8')

Using the GET parameter of a URL in JavaScript

If you're already running a php page then

php bit:

    $json   =   json_encode($_REQUEST, JSON_FORCE_OBJECT);
    print "<script>var getVars = $json;</script>";

js bit:

    var param1var = getVars.param1var;

But for Html pages Jose Basilio's solution looks good to me.

Good luck!

How to view file diff in git before commit

If you want to see what you haven't git added yet:

git diff myfile.txt

or if you want to see already added changes

git diff --cached myfile.txt

PHP function to make slug (URL string)

Since I've Seen a lot of methods here but I've found a simplest method for myself.Maybe it will help someone.

$slug = strtolower(preg_replace('/[^a-zA-Z0-9\-]/', '',preg_replace('/\s+/', '-', $string) ));

PHP: get the value of TEXTBOX then pass it to a VARIABLE

You are posting the data, so it should be $_POST. But 'name' is not the best name to use.

name = "name"

will only cause confusion IMO.

How can I transform string to UTF-8 in C#?

@anothershrubery answer worked for me. I've made an enhancement using StringEntensions Class so I can easily convert any string at all in my program.

Method:

public static class StringExtensions
{
    public static string ToUTF8(this string text)
    {
        return Encoding.UTF8.GetString(Encoding.Default.GetBytes(text));
    }
}

Usage:

string myString = "Acción";
string strConverted = myString.ToUTF8();

Or simply:

string strConverted = "Acción".ToUTF8();

Is there a "do ... while" loop in Ruby?

This works correctly now:

begin
    # statment
end until <condition>

But, it may be remove in the future, because the begin statement is counterintuitive. See: http://blade.nagaokaut.ac.jp/cgi-bin/scat.rb/ruby/ruby-core/6745

Matz (Ruby’s Creator) recommended doing it this way:

loop do
    # ...
    break if <condition>
end

Can enums be subclassed to add new elements?

Enums represent a complete enumeration of possible values. So the (unhelpful) answer is no.

As an example of a real problem take weekdays, weekend days and, the union, days of week. We could define all days within days-of-week but then we would not be able to represent properties special to either weekdays and weekend-days.

What we could do, is have three enum types with a mapping between weekdays/weekend-days and days-of-week.

public enum Weekday {
    MON, TUE, WED, THU, FRI;
    public DayOfWeek toDayOfWeek() { ... }
}
public enum WeekendDay {
    SAT, SUN;
    public DayOfWeek toDayOfWeek() { ... }
}
public enum DayOfWeek {
    MON, TUE, WED, THU, FRI, SAT, SUN;
}

Alternatively, we could have an open-ended interface for day-of-week:

interface Day {
    ...
}
public enum Weekday implements Day {
    MON, TUE, WED, THU, FRI;
}
public enum WeekendDay implements Day {
    SAT, SUN;
}

Or we could combine the two approaches:

interface Day {
    ...
}
public enum Weekday implements Day {
    MON, TUE, WED, THU, FRI;
    public DayOfWeek toDayOfWeek() { ... }
}
public enum WeekendDay implements Day {
    SAT, SUN;
    public DayOfWeek toDayOfWeek() { ... }
}
public enum DayOfWeek {
    MON, TUE, WED, THU, FRI, SAT, SUN;
    public Day toDay() { ... }
}

How can I remove 3 characters at the end of a string in php?

<?php echo substr($string, 0, strlen($string) - 3); ?>

receiving json and deserializing as List of object at spring mvc controller

@RequestMapping(
         value="person", 
         method=RequestMethod.POST,
         consumes="application/json",
         produces="application/json")
@ResponseBody
public List<String> savePerson(@RequestBody Person[] personArray) {
    List<String> response = new ArrayList<String>();
    for (Person person: personArray) {
        personService.save(person);
        response.add("Saved person: " + person.toString());
    }
    return response;
}

We can use Array as shown above.

How to find all tables that have foreign keys that reference particular table.column and have values for those foreign keys?

Here you go:

USE information_schema;
SELECT *
FROM
  KEY_COLUMN_USAGE
WHERE
  REFERENCED_TABLE_NAME = 'X'
  AND REFERENCED_COLUMN_NAME = 'X_id';

If you have multiple databases with similar tables/column names you may also wish to limit your query to a particular database:

SELECT *
FROM
  KEY_COLUMN_USAGE
WHERE
  REFERENCED_TABLE_NAME = 'X'
  AND REFERENCED_COLUMN_NAME = 'X_id'
  AND TABLE_SCHEMA = 'your_database_name';

How do I get the value of a textbox using jQuery?

You can access the value of Texbox control either by its ID or by its Class name.

Here is the example code:

<input type="text" id="txtEmail" class="textbox" value="1">

$(document).ready(function(){
   alert($("#txtEmail").val());
   alert($(".textbox").val());//Not recommended 
});

Using class name for getting any text-box control value can return other or wrong value as same class name can also be defined for any other control. So getting value of a specific textbox can be fetch by its id.

No Activity found to handle Intent : android.intent.action.VIEW

If you have these error in your logcat then use these code it help me

 Intent intent = new Intent(Intent.ACTION_VIEW);
            intent.setDataAndType(Uri.fromFile(new File(data.getLocation())), "audio/*");
            try {
                context.startActivity(intent);
            } catch (ActivityNotFoundException e) {
                Log.d("error", e.getMessage());
            }

also

   Intent intent = new Intent(MediaStore.INTENT_ACTION_MUSIC_PLAYER);
            intent.setDataAndType(Uri.fromFile(new File(data.getLocation())), "audio/*");
            try {
                context.startActivity(intent);
            } catch (ActivityNotFoundException e) {
                Log.d("error", e.getMessage());
            }

How to show live preview in a small popup of linked page on mouse over on link?

You could do the following:

  1. Create (or find) a service that renders URLs as preview images
  2. Load that image on mouse over and show it
  3. If you are obsessive about being live, then use a Timer plug-in for jQuery to reload the image after some time

Of course this isn't actually live.

What would be more sensible is that you could generate preview images for certain URLs e.g. every day or every week and use them. I image that you don't want to do this manually and you don't want to show the users of your service a preview that looks completely different than what the site currently looks like.

Only numbers. Input number in React

 <input
        className="input-Flied2"
        type="TEXT"
        name="userMobileNo"
        placeholder="Moble No"
        value={phonNumber}
        maxLength="10"
        onChange={handleChangeInput}
        required
      />

  const handleChangeInput = (e) => {
const re = /^[0-9\b]+$/; //rules
if (e.target.value === "" || re.test(e.target.value)) {
  setPhoneNumber(e.target.value);
}

};

Extracting Ajax return data in jQuery

on success: function (response) { alert(response.d); }

How do I iterate through each element in an n-dimensional matrix in MATLAB?

The idea of a linear index for arrays in matlab is an important one. An array in MATLAB is really just a vector of elements, strung out in memory. MATLAB allows you to use either a row and column index, or a single linear index. For example,

A = magic(3)
A =
     8     1     6
     3     5     7
     4     9     2

A(2,3)
ans =
     7

A(8)
ans =
     7

We can see the order the elements are stored in memory by unrolling the array into a vector.

A(:)
ans =
     8
     3
     4
     1
     5
     9
     6
     7
     2

As you can see, the 8th element is the number 7. In fact, the function find returns its results as a linear index.

find(A>6)
ans =
     1
     6
     8

The result is, we can access each element in turn of a general n-d array using a single loop. For example, if we wanted to square the elements of A (yes, I know there are better ways to do this), one might do this:

B = zeros(size(A));
for i = 1:numel(A)
  B(i) = A(i).^2;
end

B
B =
    64     1    36
     9    25    49
    16    81     4

There are many circumstances where the linear index is more useful. Conversion between the linear index and two (or higher) dimensional subscripts is accomplished with the sub2ind and ind2sub functions.

The linear index applies in general to any array in matlab. So you can use it on structures, cell arrays, etc. The only problem with the linear index is when they get too large. MATLAB uses a 32 bit integer to store these indexes. So if your array has more then a total of 2^32 elements in it, the linear index will fail. It is really only an issue if you use sparse matrices often, when occasionally this will cause a problem. (Though I don't use a 64 bit MATLAB release, I believe that problem has been resolved for those lucky individuals who do.)

File Upload with Angular Material

I find a way to avoid styling my own choose file button.

Because I'm using flowjs for resumable upload, I'm able to use the "flow-btn" directive from ng-flow, which gives a choose file button with material design style.

Note that wrapping the input element inside a md-button won't work.

React Native fixed footer

You get the Dimension first and then manipulate it through flex style

var Dimensions = require('Dimensions')
var {width, height} = Dimensions.get('window')

In render

<View style={{flex: 1}}>
    <View style={{width: width, height: height - 200}}>main</View>
    <View style={{width: width, height: 200}}>footer</View>
</View>

The other method is to use flex

<View style={{flex: 1}}>
    <View style={{flex: .8}}>main</View>
    <View style={{flex: .2}}>footer</View>
</View>

HTML5 Pre-resize images before uploading

I tackled this problem a few years ago and uploaded my solution to github as https://github.com/rossturner/HTML5-ImageUploader

robertc's answer uses the solution proposed in the Mozilla Hacks blog post, however I found this gave really poor image quality when resizing to a scale that was not 2:1 (or a multiple thereof). I started experimenting with different image resizing algorithms, although most ended up being quite slow or else were not great in quality either.

Finally I came up with a solution which I believe executes quickly and has pretty good performance too - as the Mozilla solution of copying from 1 canvas to another works quickly and without loss of image quality at a 2:1 ratio, given a target of x pixels wide and y pixels tall, I use this canvas resizing method until the image is between x and 2 x, and y and 2 y. At this point I then turn to algorithmic image resizing for the final "step" of resizing down to the target size. After trying several different algorithms I settled on bilinear interpolation taken from a blog which is not online anymore but accessible via the Internet Archive, which gives good results, here's the applicable code:

ImageUploader.prototype.scaleImage = function(img, completionCallback) {
    var canvas = document.createElement('canvas');
    canvas.width = img.width;
    canvas.height = img.height;
    canvas.getContext('2d').drawImage(img, 0, 0, canvas.width, canvas.height);

    while (canvas.width >= (2 * this.config.maxWidth)) {
        canvas = this.getHalfScaleCanvas(canvas);
    }

    if (canvas.width > this.config.maxWidth) {
        canvas = this.scaleCanvasWithAlgorithm(canvas);
    }

    var imageData = canvas.toDataURL('image/jpeg', this.config.quality);
    this.performUpload(imageData, completionCallback);
};

ImageUploader.prototype.scaleCanvasWithAlgorithm = function(canvas) {
    var scaledCanvas = document.createElement('canvas');

    var scale = this.config.maxWidth / canvas.width;

    scaledCanvas.width = canvas.width * scale;
    scaledCanvas.height = canvas.height * scale;

    var srcImgData = canvas.getContext('2d').getImageData(0, 0, canvas.width, canvas.height);
    var destImgData = scaledCanvas.getContext('2d').createImageData(scaledCanvas.width, scaledCanvas.height);

    this.applyBilinearInterpolation(srcImgData, destImgData, scale);

    scaledCanvas.getContext('2d').putImageData(destImgData, 0, 0);

    return scaledCanvas;
};

ImageUploader.prototype.getHalfScaleCanvas = function(canvas) {
    var halfCanvas = document.createElement('canvas');
    halfCanvas.width = canvas.width / 2;
    halfCanvas.height = canvas.height / 2;

    halfCanvas.getContext('2d').drawImage(canvas, 0, 0, halfCanvas.width, halfCanvas.height);

    return halfCanvas;
};

ImageUploader.prototype.applyBilinearInterpolation = function(srcCanvasData, destCanvasData, scale) {
    function inner(f00, f10, f01, f11, x, y) {
        var un_x = 1.0 - x;
        var un_y = 1.0 - y;
        return (f00 * un_x * un_y + f10 * x * un_y + f01 * un_x * y + f11 * x * y);
    }
    var i, j;
    var iyv, iy0, iy1, ixv, ix0, ix1;
    var idxD, idxS00, idxS10, idxS01, idxS11;
    var dx, dy;
    var r, g, b, a;
    for (i = 0; i < destCanvasData.height; ++i) {
        iyv = i / scale;
        iy0 = Math.floor(iyv);
        // Math.ceil can go over bounds
        iy1 = (Math.ceil(iyv) > (srcCanvasData.height - 1) ? (srcCanvasData.height - 1) : Math.ceil(iyv));
        for (j = 0; j < destCanvasData.width; ++j) {
            ixv = j / scale;
            ix0 = Math.floor(ixv);
            // Math.ceil can go over bounds
            ix1 = (Math.ceil(ixv) > (srcCanvasData.width - 1) ? (srcCanvasData.width - 1) : Math.ceil(ixv));
            idxD = (j + destCanvasData.width * i) * 4;
            // matrix to vector indices
            idxS00 = (ix0 + srcCanvasData.width * iy0) * 4;
            idxS10 = (ix1 + srcCanvasData.width * iy0) * 4;
            idxS01 = (ix0 + srcCanvasData.width * iy1) * 4;
            idxS11 = (ix1 + srcCanvasData.width * iy1) * 4;
            // overall coordinates to unit square
            dx = ixv - ix0;
            dy = iyv - iy0;
            // I let the r, g, b, a on purpose for debugging
            r = inner(srcCanvasData.data[idxS00], srcCanvasData.data[idxS10], srcCanvasData.data[idxS01], srcCanvasData.data[idxS11], dx, dy);
            destCanvasData.data[idxD] = r;

            g = inner(srcCanvasData.data[idxS00 + 1], srcCanvasData.data[idxS10 + 1], srcCanvasData.data[idxS01 + 1], srcCanvasData.data[idxS11 + 1], dx, dy);
            destCanvasData.data[idxD + 1] = g;

            b = inner(srcCanvasData.data[idxS00 + 2], srcCanvasData.data[idxS10 + 2], srcCanvasData.data[idxS01 + 2], srcCanvasData.data[idxS11 + 2], dx, dy);
            destCanvasData.data[idxD + 2] = b;

            a = inner(srcCanvasData.data[idxS00 + 3], srcCanvasData.data[idxS10 + 3], srcCanvasData.data[idxS01 + 3], srcCanvasData.data[idxS11 + 3], dx, dy);
            destCanvasData.data[idxD + 3] = a;
        }
    }
};

This scales an image down to a width of config.maxWidth, maintaining the original aspect ratio. At the time of development this worked on iPad/iPhone Safari in addition to major desktop browsers (IE9+, Firefox, Chrome) so I expect it will still be compatible given the broader uptake of HTML5 today. Note that the canvas.toDataURL() call takes a mime type and image quality which will allow you to control the quality and output file format (potentially different to input if you wish).

The only point this doesn't cover is maintaining the orientation information, without knowledge of this metadata the image is resized and saved as-is, losing any metadata within the image for orientation meaning that images taken on a tablet device "upside down" were rendered as such, although they would have been flipped in the device's camera viewfinder. If this is a concern, this blog post has a good guide and code examples on how to accomplish this, which I'm sure could be integrated to the above code.

Error on line 2 at column 1: Extra content at the end of the document

The problem is database connection string, one of your MySQL database connection function parameter is not correct ,so there is an error message in the browser output, Just right click output webpage and view html source code you will see error line followed by correct XML output data(file). I had same problem and the above solution worked perfectly.

Convert php array to Javascript

Dumb and simple :

var js_array = [<?php echo '"'.implode('","', $php_array).'"' ?>];

How to redirect 404 errors to a page in ExpressJS?

I found this example quite helpful:

https://github.com/visionmedia/express/blob/master/examples/error-pages/index.js

So it is actually this part:

// "app.router" positions our routes
// above the middleware defined below,
// this means that Express will attempt
// to match & call routes _before_ continuing
// on, at which point we assume it's a 404 because
// no route has handled the request.

app.use(app.router);

// Since this is the last non-error-handling
// middleware use()d, we assume 404, as nothing else
// responded.

// $ curl http://localhost:3000/notfound
// $ curl http://localhost:3000/notfound -H "Accept: application/json"
// $ curl http://localhost:3000/notfound -H "Accept: text/plain"

app.use(function(req, res, next){
  res.status(404);

  // respond with html page
  if (req.accepts('html')) {
    res.render('404', { url: req.url });
    return;
  }

  // respond with json
  if (req.accepts('json')) {
    res.send({ error: 'Not found' });
    return;
  }

  // default to plain-text. send()
  res.type('txt').send('Not found');
});

AngularJS: How to set a variable inside of a template?

Use ngInit: https://docs.angularjs.org/api/ng/directive/ngInit

<div ng-repeat="day in forecast_days" ng-init="f = forecast[day.iso]">
  {{$index}} - {{day.iso}} - {{day.name}}
  Temperature: {{f.temperature}}<br>
  Humidity: {{f.humidity}}<br>
  ...
</div>

Example: http://jsfiddle.net/coma/UV4qF/

Descending order by date filter in AngularJs

You can prefix the argument in orderBy with a '-' to have descending order instead of ascending. I would write it like this:

<div class="recent" 
   ng-repeat="reader in book.reader | orderBy: '-created_at' | limitTo: 1">
</div>

This is also stated in the documentation for the filter orderBy.

How do I render a shadow?

You have to give elevation prop to View

<View elevation={5} style={styles.container}>
   <Text>Hello World !</Text>
 </View>

styles can be added like this:

 const styles = StyleSheet.create({

     container:{
        padding:20,
        backgroundColor:'#d9d9d9',
        shadowColor: "#000000",
        shadowOpacity: 0.8,
        shadowRadius: 2,
        shadowOffset: {
          height: 1,
          width: 1
        }
       },
   })

Change color when hover a font awesome icon?

use - !important - to override default black

_x000D_
_x000D_
.fa-heart:hover{_x000D_
   color:red !important;_x000D_
}_x000D_
.fa-heart-o:hover{_x000D_
   color:red !important;_x000D_
}
_x000D_
<link rel="stylesheet" href="https://maxcdn.bootstrapcdn.com/font-awesome/4.7.0/css/font-awesome.min.css">_x000D_
_x000D_
<i class="fa fa-heart fa-2x"></i>_x000D_
<i class="fa fa-heart-o fa-2x"></i>
_x000D_
_x000D_
_x000D_

How do you easily horizontally center a <div> using CSS?

.center {
   margin-left: auto;
   margin-right: auto;
}

Minimum width is not globally supported, but can be implemented using

.divclass {
   min-width: 200px;
}

Then you can set your div to be

<div class="center divclass">stuff in here</div>

mysql query order by multiple items

Sort by picture and then by activity:

SELECT some_cols
FROM `prefix_users`
WHERE (some conditions)
ORDER BY pic_set, last_activity DESC;

Integration Testing POSTing an entire object to Spring MVC controller

I had the same question and it turned out the solution was fairly simple, by using JSON marshaller.
Having your controller just change the signature by changing @ModelAttribute("newObject") to @RequestBody. Like this:

@Controller
@RequestMapping(value = "/somewhere/new")
public class SomewhereController {

    @RequestMapping(method = RequestMethod.POST)
    public String post(@RequestBody NewObject newObject) {
        // ...
    }
}

Then in your tests you can simply say:

NewObject newObjectInstance = new NewObject();
// setting fields for the NewObject  

mockMvc.perform(MockMvcRequestBuilders.post(uri)
  .content(asJsonString(newObjectInstance))
  .contentType(MediaType.APPLICATION_JSON)
  .accept(MediaType.APPLICATION_JSON));

Where the asJsonString method is just:

public static String asJsonString(final Object obj) {
    try {
        final ObjectMapper mapper = new ObjectMapper();
        final String jsonContent = mapper.writeValueAsString(obj);
        return jsonContent;
    } catch (Exception e) {
        throw new RuntimeException(e);
    }
}  

How can I make a list of lists in R?

If you are trying to keep a list of lists (similar to python's list.append()) then this might work:

a <- list(1,2,3)
b <- list(4,5,6)
c <- append(list(a), list(b))

> c
[[1]]
[[1]][[1]]
[1] 1

[[1]][[2]]
[1] 2

[[1]][[3]]
[1] 3


[[2]]
[[2]][[1]]
[1] 4

[[2]][[2]]
[1] 5

[[2]][[3]]
[1] 6

In-place edits with sed on OS X

You can use the -i flag correctly by providing it with a suffix to add to the backed-up file. Extending your example:

sed -i.bu 's/oldword/newword/' file1.txt

Will give you two files: one with the name file1.txt that contains the substitution, and one with the name file1.txt.bu that has the original content.

Mildly dangerous

If you want to destructively overwrite the original file, use something like:

sed -i '' 's/oldword/newword/' file1.txt
      ^ note the space

Because of the way the line gets parsed, a space is required between the option flag and its argument because the argument is zero-length.

Other than possibly trashing your original, I’m not aware of any further dangers of tricking sed this way. It should be noted, however, that if this invocation of sed is part of a script, The Unix Way™ would (IMHO) be to use sed non-destructively, test that it exited cleanly, and only then remove the extraneous file.

What is JAVA_HOME? How does the JVM find the javac path stored in JAVA_HOME?

JAVA_HOME and JRE_HOME are not used by Java itself. Some third-party programs (for example Apache Tomcat) expect one of these environment variables to be set to the installation directory of the JDK or JRE. If you are not using software that requires them, you do not need to set JAVA_HOME and JRE_HOME. PATH is an environment variable used by the operating system (Windows, Mac OS X, Linux) where it will look for native executable programs to run. You should add the bin subdirectory of your JDK installation directory to the PATH, so that you can use the javac and java commands and other JDK tools in a command prompt window. Courtesy: coderanch

mySQL convert varchar to date

select date_format(str_to_date('31/12/2010', '%d/%m/%Y'), '%Y%m'); 

or

select date_format(str_to_date('12/31/2011', '%m/%d/%Y'), '%Y%m'); 

hard to tell from your example

How can I tell if a Java integer is null?

I don't think you can use "exists" on an integer in Perl, only on collections. Can you give an example of what you mean in Perl which matches your example in Java.

Given an expression that specifies a hash element or array element, returns true if the specified element in the hash or array has ever been initialized, even if the corresponding value is undefined.

This indicates it only applies to hash or array elements!

How to see which flags -march=native will activate?

To see command-line flags, use:

gcc -march=native -E -v - </dev/null 2>&1 | grep cc1

If you want to see the compiler/precompiler defines set by certain parameters, do this:

echo | gcc -dM -E - -march=native

How to resize the jQuery DatePicker control

This code will work on Calender buttons. size of numbers will increase by using "line-height".

/* Change Size */
<style>
    .ui-datepicker{
        font-size:16px;
        line-height: 1.3;
    }
</style>

Ruby on Rails. How do I use the Active Record .build method in a :belongs to relationship?

@article = user.articles.build(:title => "MainTitle")
@article.save

how to change listen port from default 7001 to something different?

You can change the listen port as per your requirement. This task can be accomplished in two diffrent ways. By changing config.xml file By changing in admin console Change the listen port in config.xml as per your requirement and bounce the domain. Admin Console Login to AdminConsole->Server->Configuration->ListenPort (Change it) Note: It is a bad practice to edit config.xml and try to edit in admin console(It's a good practise as well)

What is SELF JOIN and when would you use it?

You use a self join when a table references data in itself.

E.g., an Employee table may have a SupervisorID column that points to the employee that is the boss of the current employee.

To query the data and get information for both people in one row, you could self join like this:

select e1.EmployeeID, 
    e1.FirstName, 
    e1.LastName,
    e1.SupervisorID, 
    e2.FirstName as SupervisorFirstName, 
    e2.LastName as SupervisorLastName
from Employee e1
left outer join Employee e2 on e1.SupervisorID = e2.EmployeeID

Static link of shared library function in gcc

If you have the .a file of your shared library (.so) you can simply include it with its full path as if it was an object file, like this:

This generates main.o by just compiling:

gcc -c main.c

This links that object file with the corresponding static library and creates the executable (named "main"):

gcc main.o mylibrary.a -o main

Or in a single command:

gcc main.c mylibrary.a -o main

It could also be an absolute or relative path:

gcc main.c /usr/local/mylibs/mylibrary.a -o main

startsWith() and endsWith() functions in PHP

PHP 8 update

PHP 8 includes new str_starts_with and str_ends_with functions that finally provide a performant and convenient solution to this problem:

$str = "beginningMiddleEnd";
if (str_starts_with($str, "beg")) echo "printed\n";
if (str_starts_with($str, "Beg")) echo "not printed\n";
if (str_ends_with($str, "End")) echo "printed\n";
if (str_ends_with($str, "end")) echo "not printed\n";

The RFC for this feature provides more information, and also a discussion of the merits and problems of obvious (and not-so-obvious) userland implementations.

Javascript : get <img> src and set as variable?

Use JQuery, its easy.

Include the JQuery library into your html file in the head as such:

<head>
  <script src="https://ajax.googleapis.com/ajax/libs/jquery/3.2.1/jquery.min.js"></script>
</head>

(Make sure that this script tag goes before your other script tags in your html file)

Target your id in your JavaScript file as such:

<script>
var youtubeimcsrc = $('#youtubeimg').attr('src');

//your var will be the src string that you're looking for

</script>

Calculate a Running Total in SQL Server

While Sam Saffron did great work on it, he still didn't provide recursive common table expression code for this problem. And for us who working with SQL Server 2008 R2 and not Denali, it's still fastest way to get running total, it's about 10 times faster than cursor on my work computer for 100000 rows, and it's also inline query.
So, here it is (I'm supposing that there's an ord column in the table and it's sequential number without gaps, for fast processing there also should be unique constraint on this number):

;with 
CTE_RunningTotal
as
(
    select T.ord, T.total, T.total as running_total
    from #t as T
    where T.ord = 0
    union all
    select T.ord, T.total, T.total + C.running_total as running_total
    from CTE_RunningTotal as C
        inner join #t as T on T.ord = C.ord + 1
)
select C.ord, C.total, C.running_total
from CTE_RunningTotal as C
option (maxrecursion 0)

-- CPU 140, Reads 110014, Duration 132

sql fiddle demo

update I also was curious about this update with variable or quirky update. So usually it works ok, but how we can be sure that it works every time? well, here's a little trick (found it here - http://www.sqlservercentral.com/Forums/Topic802558-203-21.aspx#bm981258) - you just check current and previous ord and use 1/0 assignment in case they are different from what you expecting:

declare @total int, @ord int

select @total = 0, @ord = -1

update #t set
    @total = @total + total,
    @ord = case when ord <> @ord + 1 then 1/0 else ord end,
    ------------------------
    running_total = @total

select * from #t

-- CPU 0, Reads 58, Duration 139

From what I've seen if you have proper clustered index/primary key on your table (in our case it would be index by ord_id) update will proceed in a linear way all the time (never encountered divide by zero). That said, it's up to you to decide if you want to use it in production code :)

update 2 I'm linking this answer, cause it includes some useful info about unreliability of the quirky update - nvarchar concatenation / index / nvarchar(max) inexplicable behavior.

How can I exclude $(this) from a jQuery selector?

You should use the "siblings()" method, and prevent from running the ".content a" selector over and over again just for applying that effect:

HTML

<div class="content">
    <a href="#">A</a>
</div>
<div class="content">
    <a href="#">B</a>
</div>
<div class="content">
    <a href="#">C</a>
</div>

CSS

.content {
    background-color:red;
    margin:10px;
}
.content.other {
    background-color:yellow;
}

Javascript

$(".content a").click(function() {
  var current = $(this).parent();
  current.removeClass('other')
    .siblings()
    .addClass('other');
});

See here: http://jsfiddle.net/3bzLV/1/

Accept function as parameter in PHP

Tested for PHP 5.3

As i see here, Anonymous Function could help you: http://php.net/manual/en/functions.anonymous.php

What you'll probably need and it's not said before it's how to pass a function without wrapping it inside a on-the-fly-created function. As you'll see later, you'll need to pass the function's name written in a string as a parameter, check its "callability" and then call it.

The function to do check:

if( is_callable( $string_function_name ) ){
    /*perform the call*/
}

Then, to call it, use this piece of code (if you need parameters also, put them on an array), seen at : http://php.net/manual/en/function.call-user-func.php

call_user_func_array( "string_holding_the_name_of_your_function", $arrayOfParameters );

as it follows (in a similar, parameterless, way):

    function funToBeCalled(){
        print("----------------------i'm here");
    }
    function wrapCaller($fun){
        if( is_callable($fun)){
            print("called");
            call_user_func($fun);
        }else{
            print($fun." not called");
        }
    }

    wrapCaller("funToBeCalled");
    wrapCaller("cannot call me");

Here's a class explaining how to do something similar :

<?php
class HolderValuesOrFunctionsAsString{
    private $functions = array();
    private $vars = array();

    function __set($name,$data){
        if(is_callable($data))
            $this->functions[$name] = $data;
        else
            $this->vars[$name] = $data;
    }

    function __get($name){
        $t = $this->vars[$name];
        if(isset($t))
            return $t;
        else{
            $t = $this->$functions[$name];
            if( isset($t))
                return $t;
        }
    }

    function __call($method,$args=null){
        $fun = $this->functions[$method];
        if(isset($fun)){
            call_user_func_array($fun,$args);
        } else {
            // error out
            print("ERROR: Funciton not found: ". $method);
        }
    }
}
?>

and an example of usage

<?php
    /*create a sample function*/
    function sayHello($some = "all"){
    ?>
         <br>hello to <?=$some?><br>
    <?php
    }

    $obj = new HolderValuesOrFunctionsAsString;

    /*do the assignement*/
    $obj->justPrintSomething = 'sayHello'; /*note that the given
        "sayHello" it's a string ! */

    /*now call it*/
    $obj->justPrintSomething(); /*will print: "hello to all" and
        a break-line, for html purpose*/

    /*if the string assigned is not denoting a defined method
         , it's treat as a simple value*/
    $obj->justPrintSomething = 'thisFunctionJustNotExistsLOL';

    echo $obj->justPrintSomething; /*what do you expect to print?
        just that string*/
    /*N.B.: "justPrintSomething" is treated as a variable now!
        as the __set 's override specify"*/

    /*after the assignement, the what is the function's destiny assigned before ? It still works, because it's held on a different array*/
     $obj->justPrintSomething("Jack Sparrow");


     /*You can use that "variable", ie "justPrintSomething", in both ways !! so you can call "justPrintSomething" passing itself as a parameter*/

     $obj->justPrintSomething( $obj->justPrintSomething );
         /*prints: "hello to thisFunctionJustNotExistsLOL" and a break-line*/

    /*in fact, "justPrintSomething" it's a name used to identify both
         a value (into the dictionary of values) or a function-name
         (into the dictionary of functions)*/
?>

Creating CSS Global Variables : Stylesheet theme management

I do it this way:

The html:

<head>
    <style type="text/css"> <? require_once('xCss.php'); ?> </style>
</head>

The xCss.php:

<? // place here your vars
$fntBtn = 'bold 14px  Arial'
$colBorder  = '#556677' ;
$colBG0     = '#dddddd' ;
$colBG1     = '#44dddd' ;
$colBtn     = '#aadddd' ;

// here goes your css after the php-close tag: 
?>
button { border: solid 1px <?= $colBorder; ?>; border-radius:4px; font: <?= $fntBtn; ?>; background-color:<?= $colBtn; ?>; } 

How do I use MySQL through XAMPP?

XAMPP only offers MySQL (Database Server) & Apache (Webserver) in one setup and you can manage them with the xampp starter.

After the successful installation navigate to your xampp folder and execute the xampp-control.exe

Press the start Button at the mysql row.

enter image description here

Now you've successfully started mysql. Now there are 2 different ways to administrate your mysql server and its databases.

But at first you have to set/change the MySQL Root password. Start the Apache server and type localhost or 127.0.0.1 in your browser's address bar. If you haven't deleted anything from the htdocs folder the xampp status page appears. Navigate to security settings and change your mysql root password.

Now, you can browse to your phpmyadmin under http://localhost/phpmyadmin or download a windows mysql client for example navicat lite or mysql workbench. Install it and log in to your mysql server with your new root password.

enter image description here

Running Java gives "Error: could not open `C:\Program Files\Java\jre6\lib\amd64\jvm.cfg'"

  • I had a similar problem (trying to start a Jenkins slave agent on Windows) on Windows 2008R2, Java 1.7.0_15

  • I had two situations that contributed to the problem and that changing both of them fixed it:

    1) Installing Java in a unix-compatible path (changing from c:\Program Files\... to c:\Software\...); I don't think this directly affected the problem described in this thread, but noting the change;

    2) Running Java not through a shortcut. It originally failed with a shortcut, but re-running from the direct executable (C:\Software\Java...\bin\java) worked.

How do I remove a submodule?

You can use an alias to automate the solutions provided by others:

[alias]
  rms = "!f(){ git rm --cached \"$1\";rm -r \"$1\";git config -f .gitmodules --remove-section \"submodule.$1\";git config -f .git/config --remove-section \"submodule.$1\";git add .gitmodules; }; f"

Put that in your git config, and then you can do: git rms path/to/submodule

How to get WooCommerce order details

WOOCOMMERCE ORDERS IN VERSION 3.0+

Since Woocommerce mega major Update 3.0+ things have changed quite a lot:

Related:
How to get Customer details from Order in WooCommerce?
Get Order items and WC_Order_Item_Product in WooCommerce 3

So the Order items properties will not be accessible as before in a foreach loop and you will have to use these specific getter and setter methods instead.

Using some WC_Order and WC_Abstract_Order methods (example):

// Get an instance of the WC_Order object (same as before)
$order = wc_get_order( $order_id );

$order_id  = $order->get_id(); // Get the order ID
$parent_id = $order->get_parent_id(); // Get the parent order ID (for subscriptions…)

$user_id   = $order->get_user_id(); // Get the costumer ID
$user      = $order->get_user(); // Get the WP_User object

$order_status  = $order->get_status(); // Get the order status (see the conditional method has_status() below)
$currency      = $order->get_currency(); // Get the currency used  
$payment_method = $order->get_payment_method(); // Get the payment method ID
$payment_title = $order->get_payment_method_title(); // Get the payment method title
$date_created  = $order->get_date_created(); // Get date created (WC_DateTime object)
$date_modified = $order->get_date_modified(); // Get date modified (WC_DateTime object)

$billing_country = $order->get_billing_country(); // Customer billing country

// ... and so on ...

For order status as a conditional method (where "the_targeted_status" need to be defined and replaced by an order status to target a specific order status):

if ( $order->has_status('completed') ) {
    // Do something
}

Get and access to the order data properties (in an array of values):

// Get an instance of the WC_Order object
$order = wc_get_order( $order_id );

$order_data = $order->get_data(); // The Order data

$order_id = $order_data['id'];
$order_parent_id = $order_data['parent_id'];
$order_status = $order_data['status'];
$order_currency = $order_data['currency'];
$order_version = $order_data['version'];
$order_payment_method = $order_data['payment_method'];
$order_payment_method_title = $order_data['payment_method_title'];
$order_payment_method = $order_data['payment_method'];
$order_payment_method = $order_data['payment_method'];

## Creation and modified WC_DateTime Object date string ##

// Using a formated date ( with php date() function as method)
$order_date_created = $order_data['date_created']->date('Y-m-d H:i:s');
$order_date_modified = $order_data['date_modified']->date('Y-m-d H:i:s');

// Using a timestamp ( with php getTimestamp() function as method)
$order_timestamp_created = $order_data['date_created']->getTimestamp();
$order_timestamp_modified = $order_data['date_modified']->getTimestamp();

$order_discount_total = $order_data['discount_total'];
$order_discount_tax = $order_data['discount_tax'];
$order_shipping_total = $order_data['shipping_total'];
$order_shipping_tax = $order_data['shipping_tax'];
$order_total = $order_data['total'];
$order_total_tax = $order_data['total_tax'];
$order_customer_id = $order_data['customer_id']; // ... and so on

## BILLING INFORMATION:

$order_billing_first_name = $order_data['billing']['first_name'];
$order_billing_last_name = $order_data['billing']['last_name'];
$order_billing_company = $order_data['billing']['company'];
$order_billing_address_1 = $order_data['billing']['address_1'];
$order_billing_address_2 = $order_data['billing']['address_2'];
$order_billing_city = $order_data['billing']['city'];
$order_billing_state = $order_data['billing']['state'];
$order_billing_postcode = $order_data['billing']['postcode'];
$order_billing_country = $order_data['billing']['country'];
$order_billing_email = $order_data['billing']['email'];
$order_billing_phone = $order_data['billing']['phone'];

## SHIPPING INFORMATION:

$order_shipping_first_name = $order_data['shipping']['first_name'];
$order_shipping_last_name = $order_data['shipping']['last_name'];
$order_shipping_company = $order_data['shipping']['company'];
$order_shipping_address_1 = $order_data['shipping']['address_1'];
$order_shipping_address_2 = $order_data['shipping']['address_2'];
$order_shipping_city = $order_data['shipping']['city'];
$order_shipping_state = $order_data['shipping']['state'];
$order_shipping_postcode = $order_data['shipping']['postcode'];
$order_shipping_country = $order_data['shipping']['country'];

Get the order items and access the data with WC_Order_Item_Product and WC_Order_Item methods:

// Get an instance of the WC_Order object
$order = wc_get_order($order_id);

// Iterating through each WC_Order_Item_Product objects
foreach ($order->get_items() as $item_key => $item ):

    ## Using WC_Order_Item methods ##

    // Item ID is directly accessible from the $item_key in the foreach loop or
    $item_id = $item->get_id();

    ## Using WC_Order_Item_Product methods ##

    $product      = $item->get_product(); // Get the WC_Product object

    $product_id   = $item->get_product_id(); // the Product id
    $variation_id = $item->get_variation_id(); // the Variation id

    $item_type    = $item->get_type(); // Type of the order item ("line_item")

    $item_name    = $item->get_name(); // Name of the product
    $quantity     = $item->get_quantity();  
    $tax_class    = $item->get_tax_class();
    $line_subtotal     = $item->get_subtotal(); // Line subtotal (non discounted)
    $line_subtotal_tax = $item->get_subtotal_tax(); // Line subtotal tax (non discounted)
    $line_total        = $item->get_total(); // Line total (discounted)
    $line_total_tax    = $item->get_total_tax(); // Line total tax (discounted)

    ## Access Order Items data properties (in an array of values) ##
    $item_data    = $item->get_data();

    $product_name = $item_data['name'];
    $product_id   = $item_data['product_id'];
    $variation_id = $item_data['variation_id'];
    $quantity     = $item_data['quantity'];
    $tax_class    = $item_data['tax_class'];
    $line_subtotal     = $item_data['subtotal'];
    $line_subtotal_tax = $item_data['subtotal_tax'];
    $line_total        = $item_data['total'];
    $line_total_tax    = $item_data['total_tax'];

    // Get data from The WC_product object using methods (examples)
    $product        = $item->get_product(); // Get the WC_Product object

    $product_type   = $product->get_type();
    $product_sku    = $product->get_sku();
    $product_price  = $product->get_price();
    $stock_quantity = $product->get_stock_quantity();

endforeach;

So using get_data() method allow us to access to the protected data (associative array mode) …

How to vertically align label and input in Bootstrap 3?

This works perfectly for me in Bootstrap 4.

<div class="form-row align-items-center">
   <div class="col-md-2">
     <label for="FirstName" style="margin-bottom:0rem !important;">First Name</label>
 </div>
 <div class="col-md-10">
    <input type="text" id="FirstName" name="FirstName" class="form-control" val=""/>
  /div>
</div>

How to get certain commit from GitHub project

If you want to go with any certain commit or want to code of any certain commit then you can use below command:

git checkout <BRANCH_NAME>
git reset --hard  <commit ID which code you want>
git push --force

Example:

 git reset --hard fbee9dd 
 git push --force

What is a unix command for deleting the first N characters of a line?

sed 's/^.\{5\}//' logfile 

and you replace 5 by the number you want...it should do the trick...

EDIT if for each line sed 's/^.\{5\}//g' logfile

R apply function with multiple parameters

Just pass var2 as an extra argument to one of the apply functions.

mylist <- list(a=1,b=2,c=3)
myfxn <- function(var1,var2){
  var1*var2
}
var2 <- 2

sapply(mylist,myfxn,var2=var2)

This passes the same var2 to every call of myfxn. If instead you want each call of myfxn to get the 1st/2nd/3rd/etc. element of both mylist and var2, then you're in mapply's domain.

Override intranet compatibility mode IE8

There is a certain amount of confusion in the answers to this this question.

The top answer is currently a server-side solution which sets a flag in the http header and some comments are indicating that a solution using a meta tag just doesn't work.

I think this blog entry gives a nice overview of how to use compatibility meta information and in my experience works as described: http://blogs.msdn.com/b/cjacks/archive/2012/02/29/using-x-ua-compatible-to-create-durable-enterprise-web-applications.aspx

The main points:

  • setting the information using a meta tag and in the header both works
  • The meta tag takes precedence over the header
  • The meta tag has to be the first tag, to make sure that the browser does not determine the rendering engine before based on heuristics

One important point (and I think lots of confusion comes from this point) is that IE has two "classes" of modes:

  1. The document mode
  2. The browser mode

The document mode determines the rendering engine (how is the web page rendered).

The Browser Mode determines what User-Agent (UA) string IE sends to servers, what Document Mode IE defaults to, and how IE evaluates Conditional Comments.

More on the information on document mode vs. browser mode can be found in this article: http://blogs.msdn.com/b/ie/archive/2010/06/16/ie-s-compatibility-features-for-site-developers.aspx?Redirected=true

In my experience the compatibility meta data will only influence the document mode. So if you are relying on browser detection this won't help you. But if you are using feature detection this should be the way to go.

So I would recommend using the meta tag (in the html page) using this syntax:

<meta http-equiv="X-UA-Compatible" content="IE=9,10" ></meta>

Notice: give a list of browser modes you have tested for.

The blog post also advices against the use of EmulateIEX. Here a quote:

That being said, one thing I do find strange is when an application requests EmulateIE7, or EmulateIE8. These emulate modes are themselves decisions. So, instead of being specific about what you want, you’re asking for one of two things and then determining which of those two things by looking elsewhere in the code for a DOCTYPE (and then attempting to understand whether that DOCTYPE will give you standards or quirks depending on its contents – another sometimes confusing task). Rather than do that, I think it makes significantly more sense to directly specify what you want, rather than giving a response that is itself a question. If you want IE7 standards, then use IE=7, rather than IE=EmulateIE7. (Note that this doesn’t mean you shouldn’t use a DOCTYPE – you should.)

R solve:system is exactly singular

Using solve with a single parameter is a request to invert a matrix. The error message is telling you that your matrix is singular and cannot be inverted.

"A referral was returned from the server" exception when accessing AD from C#

This is the answer for the question.Reason for the cause is my LDAP string was wrong.

    try
    {
        string adServer = ConfigurationManager.AppSettings["Server"];
        string adDomain = ConfigurationManager.AppSettings["Domain"];
        string adUsername = ConfigurationManager.AppSettings["AdiminUsername"];
        string password = ConfigurationManager.AppSettings["Password"];
        string[] dc = adDomain.Split('.');
        string dcAdDomain = string.Empty;

        foreach (string item in dc)
        {
            if (dc[dc.Length - 1].Equals(item))
                dcAdDomain = dcAdDomain + "DC=" + item;
            else
                dcAdDomain = dcAdDomain + "DC=" + item + ",";
        }

        DirectoryEntry de = new DirectoryEntry("LDAP://" + adServer + "/CN=Users," + dcAdDomain, adUsername, password);

        DirectorySearcher ds = new DirectorySearcher(de);

        ds.SearchScope = SearchScope.Subtree;

        ds.Filter = "(&(objectClass=User)(sAMAccountName=" + username + "))";

        if (ds.FindOne() != null)
            return true;
    }
    catch (Exception ex)
    {
        ExLog(ex);
    }
    return false;

Import data.sql MySQL Docker Container

Import using docker-compose

cat dump.sql | docker-compose exec -T <mysql_container> mysql -u <db-username> -p<db-password> <db-name>

Is there any way to show a countdown on the lockscreen of iphone?

Or you could figure out the exacting amount of hours and minutes and have that displayed by puttin it into the timer app that already exist in every iphone :)

ssh connection refused on Raspberry Pi

I think pi has ssh server enabled by default. Mine have always worked out of the box. Depends which operating system version maybe.

Most of the time when it fails for me it is because the ip address has been changed. Perhaps you are pinging something else now? Also sometimes they just refuse to connect and need a restart.

Regular Expressions- Match Anything

Use .*, and make sure you are using your implementations' equivalent of single-line so you will match on line endings.

There is a great explanation here -> http://www.regular-expressions.info/dot.html

JavaScript: Passing parameters to a callback function

Your question is unclear. If you're asking how you can do this in a simpler way, you should take a look at the ECMAScript 5th edition method .bind(), which is a member of Function.prototype. Using it, you can do something like this:

function tryMe (param1, param2) {
    alert (param1 + " and " + param2);
}

function callbackTester (callback) {
    callback();
}

callbackTester(tryMe.bind(null, "hello", "goodbye"));

You can also use the following code, which adds the method if it isn't available in the current browser:

// From Prototype.js
if (!Function.prototype.bind) { // check if native implementation available
  Function.prototype.bind = function(){ 
    var fn = this, args = Array.prototype.slice.call(arguments),
        object = args.shift(); 
    return function(){ 
      return fn.apply(object, 
        args.concat(Array.prototype.slice.call(arguments))); 
    }; 
  };
}

Example

bind() - PrototypeJS Documentation

onclick or inline script isn't working in extension

I decide to publish my example that I used in my case. I tried to replace content in div using a script. My problem was that Chrome did not recognized / did not run that script.

In more detail What I wanted to do: To click on a link, and that link to "read" an external html file, that it will be loaded in a div section.

  • I found out that by placing the script before the DIV with ID that was called, the script did not work.
  • If the script was in another DIV, also it does not work
  • The script must be coded using document.addEventListener('DOMContentLoaded', function() as it was told

        <body>
        <a id=id_page href ="#loving"   onclick="load_services()"> loving   </a>
    
            <script>
                    // This script MUST BE under the "ID" that is calling
                    // Do not transfer it to a differ DIV than the caller "ID"
                    document.getElementById("id_page").addEventListener("click", function(){
                    document.getElementById("mainbody").innerHTML = '<object data="Services.html" class="loving_css_edit"; ></object>'; });
                </script>
        </body>
    
      <div id="mainbody" class="main_body">
            "here is loaded the external html file when the loving link will 
             be  clicked. "
      </div>
    

How do I round to the nearest 0.5?

The Correct way to do this is:

  public static Decimal GetPrice(Decimal price)
            {
                var DecPrice = price / 50;
                var roundedPrice = Math.Round(DecPrice, MidpointRounding.AwayFromZero);
                var finalPrice = roundedPrice * 50;

                return finalPrice;

            }

How to add element in Python to the end of list using list.insert?

You'll have to pass the new ordinal position to insert using len in this case:

In [62]:

a=[1,2,3,4]
a.insert(len(a),5)
a
Out[62]:
[1, 2, 3, 4, 5]

add a temporary column with a value

select field1, field2, NewField = 'example' from table1 

How to use SharedPreferences in Android to store, fetch and edit values

Store in SharedPreferences

SharedPreferences preferences = getSharedPreferences("temp", getApplicationContext().MODE_PRIVATE);
Editor editor = preferences.edit();
editor.putString("name", name);
editor.commit();

Fetch in SharedPreferences

SharedPreferences preferences=getSharedPreferences("temp", getApplicationContext().MODE_PRIVATE);
String name=preferences.getString("name",null);

Note: "temp" is sharedpreferences name and "name" is input value. if value does't exit then return null

When to use window.opener / window.parent / window.top

top, parent, opener (as well as window, self, and iframe) are all window objects.

  1. window.opener -> returns the window that opens or launches the current popup window.
  2. window.top -> returns the topmost window, if you're using frames, this is the frameset window, if not using frames, this is the same as window or self.
  3. window.parent -> returns the parent frame of the current frame or iframe. The parent frame may be the frameset window or another frame if you have nested frames. If not using frames, parent is the same as the current window or self

document.createElement("script") synchronously

I had the following problem(s) with the existing answers to this question (and variations of this question on other stackoverflow threads):

  • None of the loaded code was debuggable
  • Many of the solutions required callbacks to know when loading was finished instead of truly blocking, meaning I would get execution errors from immediately calling loaded (ie loading) code.

Or, slightly more accurately:

  • None of the loaded code was debuggable (except from the HTML script tag block, if and only if the solution added a script elements to the dom, and never ever as individual viewable scripts.) => Given how many scripts I have to load (and debug), this was unacceptable.
  • Solutions using 'onreadystatechange' or 'onload' events failed to block, which was a big problem since the code originally loaded dynamic scripts synchronously using 'require([filename, 'dojo/domReady']);' and I was stripping out dojo.

My final solution, which loads the script before returning, AND has all scripts properly accessible in the debugger (for Chrome at least) is as follows:

WARNING: The following code should PROBABLY be used only in 'development' mode. (For 'release' mode I recommend prepackaging and minification WITHOUT dynamic script loading, or at least without eval).

//Code User TODO: you must create and set your own 'noEval' variable

require = function require(inFileName)
{
    var aRequest
        ,aScript
        ,aScriptSource
        ;

    //setup the full relative filename
    inFileName = 
        window.location.protocol + '//'
        + window.location.host + '/'
        + inFileName;

    //synchronously get the code
    aRequest = new XMLHttpRequest();
    aRequest.open('GET', inFileName, false);
    aRequest.send();

    //set the returned script text while adding special comment to auto include in debugger source listing:
    aScriptSource = aRequest.responseText + '\n////# sourceURL=' + inFileName + '\n';

    if(noEval)//<== **TODO: Provide + set condition variable yourself!!!!**
    {
        //create a dom element to hold the code
        aScript = document.createElement('script');
        aScript.type = 'text/javascript';

        //set the script tag text, including the debugger id at the end!!
        aScript.text = aScriptSource;

        //append the code to the dom
        document.getElementsByTagName('body')[0].appendChild(aScript);
    }
    else
    {
        eval(aScriptSource);
    }
};

How exactly do you configure httpOnlyCookies in ASP.NET?

Interestingly putting <httpCookies httpOnlyCookies="false"/> doesn't seem to disable httpOnlyCookies in ASP.NET 2.0. Check this article about SessionID and Login Problems With ASP .NET 2.0.

Looks like Microsoft took the decision to not allow you to disable it from the web.config. Check this post on forums.asp.net

Minimum and maximum date

As you can see, 01/01/1970 returns 0, which means it is the lowest possible date.

new Date('1970-01-01Z00:00:00:000') //returns Thu Jan 01 1970 01:00:00 GMT+0100 (Central European Standard Time)
new Date('1970-01-01Z00:00:00:000').getTime() //returns 0
new Date('1970-01-01Z00:00:00:001').getTime() //returns 1

What's the difference between deadlock and livelock?

Livelock

A thread often acts in response to the action of another thread. If the other thread's action is also a response to the action of another thread, then livelock may result.

As with deadlock, livelocked threads are unable to make further progress. However, the threads are not blocked — they are simply too busy responding to each other to resume work. This is comparable to two people attempting to pass each other in a corridor: Alphonse moves to his left to let Gaston pass, while Gaston moves to his right to let Alphonse pass. Seeing that they are still blocking each other, Alphonse moves to his right, while Gaston moves to his left. They're still blocking each other, and so on...

The main difference between livelock and deadlock is that threads are not going to be blocked, instead they will try to respond to each other continuously.

In this image, both circles (threads or processes) will try to give space to the other by moving left and right. But they can't move any further.

enter image description here

Set keyboard caret position in html textbox

The link in the answer is broken, this one should work (all credits go to blog.vishalon.net):

http://snipplr.com/view/5144/getset-cursor-in-html-textarea/

In case the code gets lost again, here are the two main functions:

function doGetCaretPosition(ctrl)
{
 var CaretPos = 0;

 if (ctrl.selectionStart || ctrl.selectionStart == 0)
 {// Standard.
  CaretPos = ctrl.selectionStart;
 }
 else if (document.selection)
 {// Legacy IE
  ctrl.focus ();
  var Sel = document.selection.createRange ();
  Sel.moveStart ('character', -ctrl.value.length);
  CaretPos = Sel.text.length;
 }

 return (CaretPos);
}


function setCaretPosition(ctrl,pos)
{
 if (ctrl.setSelectionRange)
 {
  ctrl.focus();
  ctrl.setSelectionRange(pos,pos);
 }
 else if (ctrl.createTextRange)
 {
  var range = ctrl.createTextRange();
  range.collapse(true);
  range.moveEnd('character', pos);
  range.moveStart('character', pos);
  range.select();
 }
}

Python: Pandas Dataframe how to multiply entire column with a scalar

You can use the index of the column you want to apply the multiplication for

df.loc[:,6] *= -1

This will multiply the column with index 6 with -1.

Shell Script: Execute a python program from within a shell script

I use this and it works fine

#/bin/bash
/usr/bin/python python python_script.py

ReactJS - Call One Component Method From Another Component

Well, actually, React is not suitable for calling child methods from the parent. Some frameworks, like Cycle.js, allow easily access data both from parent and child, and react to it.

Also, there is a good chance you don't really need it. Consider calling it into existing component, it is much more independent solution. But sometimes you still need it, and then you have few choices:

  • Pass method down, if it is a child (the easiest one, and it is one of the passed properties)
  • add events library; in React ecosystem Flux approach is the most known, with Redux library. You separate all events into separated state and actions, and dispatch them from components
  • if you need to use function from the child in a parent component, you can wrap in a third component, and clone parent with augmented props.

UPD: if you need to share some functionality which doesn't involve any state (like static functions in OOP), then there is no need to contain it inside components. Just declare it separately and invoke when need:

let counter = 0;
function handleInstantiate() {
   counter++;
}

constructor(props) {
   super(props);
   handleInstantiate();
}

Reading a json file in Android

Put that file in assets.

For project created in Android Studio project you need to create assets folder under the main folder.

Read that file as:

public String loadJSONFromAsset(Context context) {
        String json = null;
        try {
            InputStream is = context.getAssets().open("file_name.json");

            int size = is.available();

            byte[] buffer = new byte[size];

            is.read(buffer);

            is.close();

            json = new String(buffer, "UTF-8");


        } catch (IOException ex) {
            ex.printStackTrace();
            return null;
        }
        return json;

    }

and then you can simply read this string return by this function as

JSONObject obj = new JSONObject(json_return_by_the_function);

For further details regarding JSON see http://www.vogella.com/articles/AndroidJSON/article.html

Hope you will get what you want.

fatal: The current branch master has no upstream branch

First use git pull origin your_branch_name Then use git push origin your_branch_name

Issue with adding common code as git submodule: "already exists in the index"

Don't know if this is any useful, though I had the same problem when trying to commit my files from within IntelliJ 15. In the end, I opened SourceTree and in there I could simply commit the file. Problem solved. No need to issue any fancy git commands. Just mentioning it in case anyone has the same issue.

Spring Resttemplate exception handling

A very simple solution can be:

try {
     requestEntity = RequestEntity
     .get(new URI("user String"));
    
    return restTemplate.exchange(requestEntity, String.class);
} catch (RestClientResponseException e) {
        return ResponseEntity.status(e.getRawStatusCode()).body(e.getResponseBodyAsString());
}

How do you use math.random to generate random ints?

you are importing java.util package. That's why its giving error. there is a random() in java.util package too. Please remove the import statement importing java.util package. then your program will use random() method for java.lang by default and then your program will work. remember to cast it i.e

int x = (int)(Math.random()*100);

Why Does OAuth v2 Have Both Access and Refresh Tokens?

To clear up some confusion you have to understand the roles of the client secret and the user password, which are very different.

The client is an app/website/program/..., backed by a server, that wants to authenticate a user by using a third-party authentication service. The client secret is a (random) string that is known to both this client and the authentication server. Using this secret the client can identify itself with the authentication server, receiving authorization to request access tokens.

To get the initial access token and refresh token, what is required is:

  • The user ID
  • The user password
  • The client ID
  • The client secret

To get a refreshed access token however the client uses the following information:

  • The client ID
  • The client secret
  • The refresh token

This clearly shows the difference: when refreshing, the client receives authorization to refresh access tokens by using its client secret, and can thus re-authenticate the user using the refresh token instead of the user ID + password. This effectively prevents the user from having to re-enter his/her password.

This also shows that losing a refresh token is no problem because the client ID and secret are not known. It also shows that keeping the client ID and client secret secret is vital.

How do I script a "yes" response for installing programs?

The 'yes' command will echo 'y' (or whatever you ask it to) indefinitely. Use it as:

yes | command-that-asks-for-input

or, if a capital 'Y' is required:

yes Y | command-that-asks-for-input

DateTime group by date and hour

SQL Server :

SELECT [activity_dt], count(*)
FROM table1
GROUP BY DATEPART(day, [activity_dt]), DATEPART(hour, [activity_dt]);

Oracle :

SELECT [activity_dt], count(*)
FROM table1
GROUP BY TO_CHAR(activity_dt, 'DD'), TO_CHAR(activity_dt, 'hh');

MySQL :

SELECT [activity_dt], count(*)
FROM table1
GROUP BY hour( activity_dt ) , day( activity_dt )

How do I set the classpath in NetBeans?

  1. Right-click your Project.
  2. Select Properties.
  3. On the left-hand side click Libraries.
  4. Under Compile tab - click Add Jar/Folder button.

Or

  1. Expand your Project.
  2. Right-click Libraries.
  3. Select Add Jar/Folder.

Powershell import-module doesn't find modules

My finding with PS 5.0 on Windows 7: $ENV:PsModulePath has to end with a . This normally means it will load all modules in that path.

I'm not able to add a single module to $env:PsModulePath and get it to load with Import-Module ExampleModule. I have to use the full path to the module. e.g. C:\MyModules\ExampleModule. I am sure it used to work.

For example: Say I have the modules:

C:\MyModules\ExampleModule
C:\MyModules\FishingModule

I need to add C:\MyModules\ to $env:PsModulePath, which will allow me to do

Import-Module ExampleModule
Import-Module FishingModule

If for some reason, I didn't want FishingModule, I thought I could add C:\MyModules\ExampleModule only (no trailing \), but this doesn't seem to work now. To load it, I have to Import-Module C:\MyModules\ExampleModule

Interestingly, in both cases, doing Get-Module -ListAvailable, shows the modules, but it won't import. Although, the module's cmdlets seem to work anyway.

AFAIK, to get the automatic import to work, one has to add the name of the function to FunctionsToExport in the manifest (.psd1) file. Adding FunctionsToExport = '*', breaks the auto load. You can still have Export-ModuleMember -Function * in the module file (.psm1).

These are my findings. Whether there's been a change or my computer is broken, remains to be seen. HTH

Show loading gif after clicking form submit using jQuery

The show() method only affects the display CSS setting. If you want to set the visibility you need to do it directly. Also, the .load_button element is a button and does not raise a submit event. You would need to change your selector to the form for that to work:

$('#login_form').submit(function() {
    $('#gif').css('visibility', 'visible');
});

Also note that return true; is redundant in your logic, so it can be removed.

Trying to read cell 1,1 in spreadsheet using Google Script API

You have to first obtain the Range object. Also, getCell() will not return the value of the cell but instead will return a Range object of the cell. So, use something on the lines of

function email() {

// Opens SS by its ID

var ss = SpreadsheetApp.openById("0AgJjDgtUl5KddE5rR01NSFcxYTRnUHBCQ0stTXNMenc");

// Get the name of this SS

var name = ss.getName();  // Not necessary 

// Read cell 1,1 * Line below does't work *

// var data = Range.getCell(0, 0);
var sheet = ss.getSheetByName('Sheet1'); // or whatever is the name of the sheet 
var range = sheet.getRange(1,1); 
var data = range.getValue();

}

The hierarchy is Spreadsheet --> Sheet --> Range --> Cell.

How to connect to SQL Server from command prompt with Windows authentication

type sqlplus/"as sysdba" in cmd for connection in cmd prompt

Is the NOLOCK (Sql Server hint) bad practice?

I believe that it is virtually never correct to use nolock.

If you are reading a single row, then the correct index means that you won't need NOLOCK as individual row actions are completed quickly.

If you are reading many rows for anything other than temporary display, and care about being able repeat the result, or defend by the number produced, then NOLOCK is not appropriate.

NOLOCK is a surrogate tag for "i don't care if this answer contains duplicate rows, rows which are deleted, or rows which were never inserted to begin with because of rollback"

Errors which are possible under NOLOCK:

  • Rows which match are not returned at all.
  • single rows are returned multiple times (including multiple instances of the same primary key)
  • Rows which do not match are returned.

Any action which can cause a page split while the noLock select is running can cause these things to occur. Almost any action (even a delete) can cause a page split.

Therefore: if you "know" that the row won't be changed while you are running, don't use nolock, as an index will allow efficient retrieval.

If you suspect the row can change while the query is running, and you care about accuracy, don't use nolock.

If you are considering NOLOCK because of deadlocks, examine the query plan structure for unexpected table scans, trace the deadlocks and see why they occur. NOLOCK around writes can mean that queries which previously deadlocked will potentially both write the wrong answer.

How to check if a windows form is already open, and close it if it is?

* Hope This will work for u

System.Windows.Forms.Form f1 = System.Windows.Forms.Application.OpenForms["Order"];
if(((Order)f1)!=null)
{
//open Form
}
else
{
//not open
}

How to get a substring of text?

If you want a string, then the other answers are fine, but if what you're looking for is the first few letters as characters you can access them as a list:

your_text.chars.take(30)

Psexec "run as (remote) admin"

Simply add a -h after adding your credentials using a -u -p, and it will run with elevated privileges.

What's the best way to build a string of delimited items in Java?

In the case of Android, the StringUtils class from commons isn't available, so for this I used

android.text.TextUtils.join(CharSequence delimiter, Iterable tokens)

http://developer.android.com/reference/android/text/TextUtils.html

What steps are needed to stream RTSP from FFmpeg?

FWIW, I was able to setup a local RTSP server for testing purposes using simple-rtsp-server and ffmpeg following these steps:

  1. Create a configuration file for the RTSP server called rtsp-simple-server.yml with this single line:
    protocols: [tcp]
    
  2. Start the RTSP server as a Docker container:
    $ docker run --rm -it -v $PWD/rtsp-simple-server.yml:/rtsp-simple-server.yml -p 8554:8554 aler9/rtsp-simple-server
    
  3. Use ffmpeg to stream a video file (looping forever) to the server:
    $ ffmpeg -re -stream_loop -1 -i test.mp4 -f rtsp -rtsp_transport tcp rtsp://localhost:8554/live.stream
    

Once you have that running you can use ffplay to view the stream:

$ ffplay -rtsp_transport tcp rtsp://localhost:8554/live.stream

Note that simple-rtsp-server can also handle UDP streams (i.s.o. TCP) but that's tricky running the server as a Docker container.

How to add anything in <head> through jquery/javascript?

With jquery you have other option:

$('head').html($('head').html() + '...');

anyway it is working. JavaScript option others said, thats correct too.

Converting string to double in C#

private double ConvertToDouble(string s)
    {
        char systemSeparator = Thread.CurrentThread.CurrentCulture.NumberFormat.CurrencyDecimalSeparator[0];
        double result = 0;
        try
        {
            if (s != null)
                if (!s.Contains(","))
                    result = double.Parse(s, CultureInfo.InvariantCulture);
                else
                    result = Convert.ToDouble(s.Replace(".", systemSeparator.ToString()).Replace(",", systemSeparator.ToString()));
        }
        catch (Exception e)
        {
            try
            {
                result = Convert.ToDouble(s);
            }
            catch
            {
                try
                {
                    result = Convert.ToDouble(s.Replace(",", ";").Replace(".", ",").Replace(";", "."));
                }
                catch {
                    throw new Exception("Wrong string-to-double format");
                }
            }
        }
        return result;
    }

and successfully passed tests are:

        Debug.Assert(ConvertToDouble("1.000.007") == 1000007.00);
        Debug.Assert(ConvertToDouble("1.000.007,00") == 1000007.00);
        Debug.Assert(ConvertToDouble("1.000,07") == 1000.07);
        Debug.Assert(ConvertToDouble("1,000,007") == 1000007.00);
        Debug.Assert(ConvertToDouble("1,000,000.07") == 1000000.07);
        Debug.Assert(ConvertToDouble("1,007") == 1.007);
        Debug.Assert(ConvertToDouble("1.07") == 1.07);
        Debug.Assert(ConvertToDouble("1.007") == 1007.00);
        Debug.Assert(ConvertToDouble("1.000.007E-08") == 0.07);
        Debug.Assert(ConvertToDouble("1,000,007E-08") == 0.07);

Cannot deserialize the current JSON object (e.g. {"name":"value"}) into type 'System.Collections.Generic.List`1

The real problem is that you are using dynamic return type in the FacebookClient Get method. And although you use a method for serializing, the JSON converter cannot deserialize this Object after that.

Use insted of:

dynamic result = client.Get("fql", new { q = "select target_id,target_type from connection where source_id = me()"}); 
string jsonstring = JsonConvert.SerializeObject(result);

something like that:

string result = client.Get("fql", new { q = "select target_id,target_type from connection where source_id = me()"}).ToString();

Then you can use DeserializeObject method:

var datalist = JsonConvert.DeserializeObject<List<RootObject>>(result);

Hope this helps.

Get the client IP address using PHP

It also works fine for internal IP addresses:

 function get_client_ip()
 {
      $ipaddress = '';
      if (getenv('HTTP_CLIENT_IP'))
          $ipaddress = getenv('HTTP_CLIENT_IP');
      else if(getenv('HTTP_X_FORWARDED_FOR'))
          $ipaddress = getenv('HTTP_X_FORWARDED_FOR');
      else if(getenv('HTTP_X_FORWARDED'))
          $ipaddress = getenv('HTTP_X_FORWARDED');
      else if(getenv('HTTP_FORWARDED_FOR'))
          $ipaddress = getenv('HTTP_FORWARDED_FOR');
      else if(getenv('HTTP_FORWARDED'))
          $ipaddress = getenv('HTTP_FORWARDED');
      else if(getenv('REMOTE_ADDR'))
          $ipaddress = getenv('REMOTE_ADDR');
      else
          $ipaddress = 'UNKNOWN';

      return $ipaddress;
 }

jQuery callback on image load (even when the image is cached)

You can also use this code with support for loading error:

$("img").on('load', function() {
  // do stuff on success
})
.on('error', function() {
  // do stuff on smth wrong (error 404, etc.)
})
.each(function() {
    if(this.complete) {
      $(this).load();
    } else if(this.error) {
      $(this).error();
    }
});

How to export all data from table to an insertable sql format?

Quick and Easy way:

  1. Right click database
  2. Point to tasks In SSMS 2017 you need to ignore step 2 - the generate scripts options is at the top level of the context menu Thanks to Daniel for the comment to update.
  3. Select generate scripts
  4. Click next
  5. Choose tables
  6. Click next
  7. Click advanced
  8. Scroll to Types of data to script - Called types of data to script in SMSS 2014 Thanks to Ellesedil for commenting
  9. Select data only
  10. Click on 'Ok' to close the advanced script options window
  11. Click next and generate your script

I usually in cases like this generate to a new query editor window and then just do any modifications where needed.

Remove ListView items in Android

Remove it from the adapter and then notify the arrayadapter that data set has changed.

m_adapter.remove(o);
m_adapter.notifyDataSetChanged();

Exit from app when click button in android phonegap?

navigator.app.exitApp();

add this line where you want you exit the application.

What EXACTLY is meant by "de-referencing a NULL pointer"?

A NULL pointer points to memory that doesn't exist, and will raise Segmentation fault. There's an easier way to de-reference a NULL pointer, take a look.

int main(int argc, char const *argv[])
{
    *(int *)0 = 0; // Segmentation fault (core dumped)
    return 0;
}

Since 0 is never a valid pointer value, a fault occurs.

SIGSEGV {si_signo=SIGSEGV, si_code=SEGV_MAPERR, si_addr=NULL}

Access Tomcat Manager App from different host

To access the tomcat manager from different machine you have to follow bellow steps:

1. Update conf/tomcat-users.xml file with user and some roles:

<role rolename="manager-gui"/>
 <role rolename="manager-script"/>
 <role rolename="manager-jmx"/>
 <role rolename="manager-status"/>
 <user username="admin" password="admin" roles="manager-gui,manager-script,manager-jmx,manager-status"/>

Here admin user is assigning roles="manager-gui,manager-script,manager-jmx,manager-status".

Here tomcat user and password is : admin

2. Update webapps/manager/META-INF/context.xml file (Allowing IP address):

Default configuration:

<Context antiResourceLocking="false" privileged="true" >
  
  <Valve className="org.apache.catalina.valves.RemoteAddrValve"
         allow="127\.\d+\.\d+\.\d+|::1|0:0:0:0:0:0:0:1" />
  
  <Manager sessionAttributeValueClassNameFilter="java\.lang\.(?:Boolean|Integer|Long|Number|String)|org\.apache\.catalina\.filters\.CsrfPreventionFilter\$LruCache(?:\$1)?|java\.util\.(?:Linked)?HashMap"/>
</Context>

Here in Valve it is allowing only local machine IP start with 127.\d+.\d+.\d+ .

2.a : Allow specefic IP:

<Valve className="org.apache.catalina.valves.RemoteAddrValve"
         allow="127\.\d+\.\d+\.\d+|::1|0:0:0:0:0:0:0:1|YOUR.IP.ADDRESS.HERE" />

Here you just replace |YOUR.IP.ADDRESS.HERE with your IP address

2.b : Allow all IP:

<Valve className="org.apache.catalina.valves.RemoteAddrValve"
         allow=".*" />

Here using allow=".*" you are allowing all IP.

Thanks :)

Can't connect to Postgresql on port 5432

I had the same problem after a MacOS system upgrade. Solved it by upgrading the postgres with brew. Details: it looks like the system was trying to access Postgres 11 using older Postgres 10 settings. I'm sure it was my mistake somewhere in the past, but luckily it all got sorted out with the upgrade above.

Naming threads and thread-pools of ExecutorService

Guava almost always has what you need.

ThreadFactory namedThreadFactory = 
  new ThreadFactoryBuilder().setNameFormat("my-sad-thread-%d").build()

and pass it off to your ExecutorService.

Restore DB — Error RESTORE HEADERONLY is terminating abnormally.

This type of error will come when you try to upload backup data from a higher version to lower version. Like you have backup of SQL server 2008 and you trying to upload data into SQL server 2005 then you will get this kind of error. Please try to upload in a higher version.

CSS "and" and "or"

AND (&&):

.registration_form_right input:not([type="radio"]):not([type="checkbox"])

OR (||):

.registration_form_right input:not([type="radio"]), 
   .registration_form_right input:not([type="checkbox"])

How can I force gradle to redownload dependencies?

For Android Studio 3.4.1

Simply open the gradle tab (can be located on the right) and right-click on the parent in the list (should be called "Android"), then select "Refresh dependencies".

This should resolve your issue.

Passing parameters in Javascript onClick event

onclick vs addEventListener. A matter of preference perhaps (where IE>9).

// Using closures
function onClickLink(e, index) {   
    alert(index);
    return false;
}

var div = document.getElementById('div');

for (var i = 0; i < 10; i++) {
    var link = document.createElement('a');

    link.setAttribute('href', '#');
    link.innerHTML = i + '';
    link.addEventListener('click', (function(e) {
        var index = i;
        return function(e) {
            return onClickLink(e, index);
        }
    })(), false);
    div.appendChild(link);
    div.appendChild(document.createElement('BR'));
}

How abut just using a plain data-* attribute, not as cool as a closure, but..

function onClickLink(e) {       
    alert(e.target.getAttribute('data-index'));
    return false;
}

var div = document.getElementById('div');

for (var i = 0; i < 10; i++) {
    var link = document.createElement('a');

    link.setAttribute('href', '#');
    link.setAttribute('data-index', i);
    link.innerHTML = i + ' Hello';        
    link.addEventListener('click', onClickLink, false);
    div.appendChild(link);
    div.appendChild(document.createElement('BR'));
}

MongoDB: exception in initAndListen: 20 Attempted to create a lock file on a read-only directory: /data/db, terminating

If your system is using SELinux, make sure that you use the right context for the directory you created:

ls -dZ /data/db/
ls -dZ /var/lib/mongo/

and clone the context with:

chcon -R --reference=/var/lib/mongo /data/db

What is the 'instanceof' operator used for in Java?

It's an operator that returns true if the left side of the expression is an instance of the class name on the right side.

Think about it this way. Say all the houses on your block were built from the same blueprints. Ten houses (objects), one set of blueprints (class definition).

instanceof is a useful tool when you've got a collection of objects and you're not sure what they are. Let's say you've got a collection of controls on a form. You want to read the checked state of whatever checkboxes are there, but you can't ask a plain old object for its checked state. Instead, you'd see if each object is a checkbox, and if it is, cast it to a checkbox and check its properties.

if (obj instanceof Checkbox)
{
    Checkbox cb = (Checkbox)obj;
    boolean state = cb.getState();
}

JavaScript before leaving the page

Normally you want to show this message, when the user has made changes in a form, but they are not saved.

Take this approach to show a message, only when the user has changed something

var form = $('#your-form'),
  original = form.serialize()

form.submit(function(){
  window.onbeforeunload = null
})

window.onbeforeunload = function(){
  if (form.serialize() != original)
    return 'Are you sure you want to leave?'
}

Jquery Ajax Call, doesn't call Success or Error

Try to encapsulate the ajax call into a function and set the async option to false. Note that this option is deprecated since jQuery 1.8.

function foo() {
    var myajax = $.ajax({
        type: "POST",
        url: "CHService.asmx/SavePurpose",
        dataType: "text",
        data: JSON.stringify({ Vid: Vid, PurpId: PurId }),
        contentType: "application/json; charset=utf-8",
        async: false, //add this
    });
    return myajax.responseText;
}

You can do this also:

$.ajax({
    type: "POST",
    url: "CHService.asmx/SavePurpose",
    dataType: "text",
    data: JSON.stringify({ Vid: Vid, PurpId: PurId }),
    contentType: "application/json; charset=utf-8",
    async: false, //add this
}).done(function ( data ) {
        Success = true;
}).fail(function ( data ) {
       Success = false;
});

You can read more about the jqXHR jQuery Object

Javascript loop through object array?

Iterations

Method 1: forEach method

messages.forEach(function(message) {
   console.log(message);
}

Method 2: for..of method

for(let message of messages){
   console.log(message);
}

Note: This method might not work with objects, such as:

let obj = { a: 'foo', b: { c: 'bar', d: 'daz' }, e: 'qux' }

Method 2: for..in method

for(let key in messages){
       console.log(messages[key]);
 }

How to view the committed files you have not pushed yet?

Here you'll find your answer:

Using Git how do I find changes between local and remote

For the lazy:

  1. Use "git log origin..HEAD"
  2. Use "git fetch" followed by "git log HEAD..origin". You can cherry-pick individual commits using the listed commit ids.

The above assumes, of course, that "origin" is the name of your remote tracking branch (which it is if you've used clone with default options).

Retrieve all values from HashMap keys in an ArrayList Java

List constructor accepts any data structure that implements Collection interface to be used to build a list.

To get all the keys from a hash map to a list:

Map<String, Integer> map = new HashMap<String, Integer>();
List<String> keys = new ArrayList<>(map.keySet());

To get all the values from a hash map to a list:

Map<String, Integer> map = new HashMap<String, Integer>();
List<Integer> values = new ArrayList<>(map.values());

How to count down in for loop?

First I recommand you can try use print and observe the action:

for i in range(0, 5, 1):
    print i

the result:

0
1
2
3
4

You can understand the function principle. In fact, range scan range is from 0 to 5-1. It equals 0 <= i < 5

When you really understand for-loop in python, I think its time we get back to business. Let's focus your problem.

You want to use a DECREMENT for-loop in python. I suggest a for-loop tutorial for example.

for i in range(5, 0, -1):
    print i

the result:

5
4
3
2
1

Thus it can be seen, it equals 5 >= i > 0

You want to implement your java code in python:

for (int index = last-1; index >= posn; index--)

It should code this:

for i in range(last-1, posn-1, -1)

error: the details of the application error from being viewed remotely

Dear olga is clear what the message says. Turn off the custom errors to see the details about this error for fix it, and then you close them back. So add mode="off" as:

<configuration>
    <system.web>
        <customErrors mode="Off"/>
    </system.web>
</configuration>

Relative answer: Deploying website: 500 - Internal server error

By the way: The error message declare that the web.config is not the one you type it here. Maybe you have forget to upload your web.config ? And remember to close the debug flag on the web.config that you use for online pages.

AngularJs: How to set radio button checked based on model

Ended up just using the built-in angular attribute ng-checked="model"

Call-time pass-by-reference has been removed

Only call time pass-by-reference is removed. So change:

call_user_func($func, &$this, &$client ...

To this:

call_user_func($func, $this, $client ...

&$this should never be needed after PHP4 anyway period.

If you absolutely need $client to be passed by reference, update the function ($func) signature instead (function func(&$client) {)

Put a Delay in Javascript

This thread has a good discussion and a useful solution:

function pause( iMilliseconds )
{
    var sDialogScript = 'window.setTimeout( function () { window.close(); }, ' + iMilliseconds + ');';
    window.showModalDialog('javascript:document.writeln ("<script>' + sDialogScript + '<' + '/script>")');
}

Unfortunately it appears that this doesn't work in some versions of IE, but the thread has many other worthy proposals if that proves to be a problem for you.

In python, what is the difference between random.uniform() and random.random()?

Apart from what is being mentioned above, .uniform() can also be used for generating multiple random numbers that too with the desired shape which is not possible with .random()

np.random.seed(99)
np.random.random()

#generates 0.6722785586307918

while the following code

np.random.seed(99)
np.random.uniform(0.0, 1.0, size = (5,2))

#generates this 
array([[0.67227856, 0.4880784 ],
       [0.82549517, 0.03144639],
       [0.80804996, 0.56561742],
       [0.2976225 , 0.04669572],
       [0.9906274 , 0.00682573]])

This can't be done with random(...), and if you're generating the random(...) numbers for ML related things, most of the time, you'll end up using .uniform(...)

Convert datetime object to a String of date only in Python

You can convert datetime to string.

published_at = "{}".format(self.published_at)

how to make UITextView height dynamic according to text length?

Followed by DeyaEldeen's answer.
In my case. I grow the textview height automatically by adding

swift 3

textView.translatesAutoresizingMaskIntoConstraints = false textView.isScrollEnabled = false

Python OpenCV2 (cv2) wrapper to get image size?

cv2 uses numpy for manipulating images, so the proper and best way to get the size of an image is using numpy.shape. Assuming you are working with BGR images, here is an example:

>>> import numpy as np
>>> import cv2
>>> img = cv2.imread('foo.jpg')
>>> height, width, channels = img.shape
>>> print height, width, channels
  600 800 3

In case you were working with binary images, img will have two dimensions, and therefore you must change the code to: height, width = img.shape

Renaming column names of a DataFrame in Spark Scala

def aliasAllColumns(t: DataFrame, p: String = "", s: String = ""): DataFrame =
{
  t.select( t.columns.map { c => t.col(c).as( p + c + s) } : _* )
}

In case is isn't obvious, this adds a prefix and a suffix to each of the current column names. This can be useful when you have two tables with one or more columns having the same name, and you wish to join them but still be able to disambiguate the columns in the resultant table. It sure would be nice if there were a similar way to do this in "normal" SQL.

json: cannot unmarshal object into Go value of type

Here's a fixed version of it: http://play.golang.org/p/w2ZcOzGHKR

The biggest fix that was needed is when Unmarshalling an array, that property needs to be an array/slice in the struct as well.

For example:

{ "things": ["a", "b", "c"] }

Would Unmarshal into a:

type Item struct {
    Things []string
}

And not into:

type Item struct {
    Things string
}

The other thing to watch out for when Unmarshaling is that the types line up exactly. It will fail when Unmarshalling a JSON string representation of a number into an int or float field -- "1" needs to Unmarshal into a string, not into an int like we saw with ShippingAdditionalCost int

Is it worth using Python's re.compile?

I really respect all the above answers. From my opinion Yes! For sure it is worth to use re.compile instead of compiling the regex, again and again, every time.

Using re.compile makes your code more dynamic, as you can call the already compiled regex, instead of compiling again and aagain. This thing benefits you in cases:

  1. Processor Efforts
  2. Time Complexity.
  3. Makes regex Universal.(can be used in findall, search, match)
  4. And makes your program looks cool.

Example :

  example_string = "The room number of her room is 26A7B."
  find_alpha_numeric_string = re.compile(r"\b\w+\b")

Using in Findall

 find_alpha_numeric_string.findall(example_string)

Using in search

  find_alpha_numeric_string.search(example_string)

Similarly you can use it for: Match and Substitute

getting JRE system library unbound error in build path

Go to project then

Right click on project---> Build Path-->Configure build path

Now there are 4 tabs Source, Projects, Libraries, Order and Export

Go to

Libraries tab -->  Click on Add Library (shown at the right side) -->
select JRE System Library --> Next-->click Alternate JRE --> select
Installed JRE--> Finish --> Apply--> OK.

What does the arrow operator, '->', do in Java?

This one is useful as well when you want to implement a functional interface

Runnable r = ()-> System.out.print("Run method");

is equivalent to

Runnable r = new Runnable() {
        @Override
        public void run() {
            System.out.print("Run method");
        }
};

Write code to convert given number into words (eg 1234 as input should output one thousand two hundred and thirty four)

#include<iostream>
using namespace std;
void expand(int);
int main()
{
    int num;
    cout<<"Enter a number : ";
    cin>>num;
    expand(num);
}
void expand(int value)
{
    const char * const ones[20] = {"zero", "one", "two", "three","four","five","six","seven",
    "eight","nine","ten","eleven","twelve","thirteen","fourteen","fifteen","sixteen","seventeen",
    "eighteen","nineteen"};
    const char * const tens[10] = {"", "ten", "twenty", "thirty","forty","fifty","sixty","seventy",
    "eighty","ninety"};

    if(value<0)
    {
        cout<<"minus ";
        expand(-value);
    }
    else if(value>=1000)
    {
        expand(value/1000);
        cout<<" thousand";
        if(value % 1000)
        {
            if(value % 1000 < 100)
            {
                cout << " and";
            }
            cout << " " ;
            expand(value % 1000);
        }
    }
    else if(value >= 100)
    {
        expand(value / 100);
        cout<<" hundred";
        if(value % 100)
        {
            cout << " and ";
            expand (value % 100);
        }
    }
    else if(value >= 20)
    {
        cout << tens[value / 10];
        if(value % 10)
        {
            cout << " ";
            expand(value % 10);
        }
    }
    else
    {
        cout<<ones[value];
    }
    return;
}

Set color of text in a Textbox/Label to Red and make it bold in asp.net C#

Try using the property ForeColor. Like this :

TextBox1.ForeColor = Color.Red;

Remove menubar from Electron app

The menu can be hidden or auto-hidden (like in Slack or VS Code - you can press Alt to show/hide the menu).

Relevant methods:

---- win.setMenu(menu) - Sets the menu as the window’s menu bar, setting it to null will remove the menu bar. (This will remove the menu completly)

mainWindow.setMenu(null)


---- win.setAutoHideMenuBar(hide) - Sets whether the window menu bar should hide itself automatically. Once set the menu bar will only
show
when users press the single Alt key.

mainWindow.setAutoHideMenuBar(true)

Source: https://github.com/Automattic/simplenote-electron/issues/293

There is also the method for making a frameless window as shown bellow:

(no close button no anything. Can be what we want (better design))

const { BrowserWindow } = require('electron')
let win = new BrowserWindow({ width: 800, height: 600, frame: false })
win.show()

https://electronjs.org/docs/api/browser-window#winremovemenu-linux-windows

doc: https://electronjs.org/docs/api/frameless-window

Edit: (new)

win.removeMenu() Linux Windows Remove the window's menu bar.

https://electronjs.org/docs/api/browser-window#winremovemenu-linux-windows

Added win.removeMenu() to remove application menus instead of using win.setMenu(null)

That is added from v5 as per:

https://github.com/electron/electron/pull/16570

https://github.com/electron/electron/pull/16657

Electron v7 bug

For Electron 7.1.1 use Menu.setApplicationMenu instead of win.removeMenu()

as per this thread:
https://github.com/electron/electron/issues/16521

And the big note is: you have to call it before creating the BrowserWindow! Or it will not work!

const {app, BrowserWindow, Menu} = require('electron')

Menu.setApplicationMenu(null);

const browserWindow = new BrowserWindow({/*...*/});

UPDATE (Setting autoHideMenuBar on BrowserWindow construction)

As by @kcpr comment! We can set the property and many on the constructor

That's available on the latest stable version of electron by now which is 8.3!
But too in old versions i checked for v1, v2, v3, v4!
It's there in all versions!

As per this link
https://github.com/electron/electron/blob/1-3-x/docs/api/browser-window.md

And for the v8.3
https://github.com/electron/electron/blob/v8.3.0/docs/api/browser-window.md#new-browserwindowoptions

The doc link
https://www.electronjs.org/docs/api/browser-window#new-browserwindowoptions

From the doc for the option:

autoHideMenuBar Boolean (optional) - Auto hide the menu bar unless the Alt key is pressed. Default is false.

Here a snippet to illustrate it:


let browserWindow = new BrowserWindow({
    width: 800,
    height: 600,
    autoHideMenuBar: true // <<< here
})

Java equivalent of unsigned long long?

No, there isn't. The designers of Java are on record as saying they didn't like unsigned ints. Use a BigInteger instead. See this question for details.