Programs & Examples On #Url.action

Url.Action parameters?

The following is the correct overload (in your example you are missing a closing } to the routeValues anonymous object so your code will throw an exception):

<a href="<%: Url.Action("GetByList", "Listing", new { name = "John", contact = "calgary, vancouver" }) %>">
    <span>People</span>
</a>

Assuming you are using the default routes this should generate the following markup:

<a href="/Listing/GetByList?name=John&amp;contact=calgary%2C%20vancouver">
    <span>People</span>
</a>

which will successfully invoke the GetByList controller action passing the two parameters:

public ActionResult GetByList(string name, string contact) 
{
    ...
}

TypeScript sorting an array

let numericArray: number[] = [2, 3, 4, 1, 5, 8, 11];

let sortFn = (n1 , n2) => number { return n1 - n2; }

const sortedArray: number[] = numericArray.sort(sortFn);

Sort by some field:

let arr:{key:number}[] = [{key : 2}, {key : 3}, {key : 4}, {key : 1}, {key : 5}, {key : 8}, {key : 11}];

let sortFn2 = (obj1 , obj2) => {key:number} { return obj1.key - obj2.key; }

const sortedArray2:{key:number}[] = arr.sort(sortFn2);

document.getElementById('btnid').disabled is not working in firefox and chrome

Try setting the disabled attribute directly:

if ( someCondition == true ) {
   document.getElementById('btn1').setAttribute('disabled', 'disabled');
} else {
   document.getElementById('btn1').removeAttribute('disabled');
}

How to get IP address of the device from code?

You do not need to add permissions like what is the case with the solutions provided so far. Download this website as a string:

http://www.ip-api.com/json

or

http://www.telize.com/geoip

Downloading a website as a string can be done with java code:

http://www.itcuties.com/java/read-url-to-string/

Parse the JSON object like this:

https://stackoverflow.com/a/18998203/1987258

The json attribute "query" or "ip" contains the IP address.

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

Very simple just do this:

<button ng-click="hideShow=(hideShow ? false : true)">Toggle</button>

<div ng-if="hideShow">hide and show content ...</div>

Twitter-Bootstrap-2 logo image on top of navbar

You have to also add the "navbar-brand" class to your image a container, also you have to include it inside the .navbar-inner container, like so:

 <div class="navbar navbar-fixed-top">
   <div class="navbar-inner">
     <div class="container">
        <a class="navbar-brand" href="index.html"> <img src="images/57x57x300.jpg"></a>
     </div>
   </div>
 </div>

How to open a web page from my application?

Microsoft explains it in the KB305703 article on How to start the default Internet browser programmatically by using Visual C#.

Don't forget to check the Troubleshooting section.

Connect to SQL Server Database from PowerShell

Assuming you can use integrated security, you can remove the user id and pass:

$SqlConnection.ConnectionString = "Server = $SQLServer; Database = $SQLDBName; Integrated Security = True;"

Adding a module (Specifically pymorph) to Spyder (Python IDE)

just use '!' before the pip command in spyder terminal and it will be fine

Eg:

!pip install imutils

Easy way to turn JavaScript array into comma-separated list?

Or (more efficiently):

var arr = new Array(3);
arr[0] = "Zero";
arr[1] = "One";
arr[2] = "Two";

document.write(arr); // same as document.write(arr.toString()) in this context

The toString method of an array when called returns exactly what you need - comma-separated list.

Failed to execute removeChild on Node

The direct parent of your child is markerDiv, so you should call remove from markerDiv as so:

markerDiv.removeChild(myCoolDiv);

Alternatively, you may want to remove markerNode. Since that node was appended directly to videoContainer, it can be removed with:

document.getElementById("playerContainer").removeChild(markerDiv);

Now, the easiest general way to remove a node, if you are absolutely confident that you did insert it into the DOM, is this:

markerDiv.parentNode.removeChild(markerDiv);

This works for any node (just replace markerDiv with a different node), and finds the parent of the node directly in order to call remove from it. If you are unsure if you added it, double check if the parentNode is non-null before calling removeChild.

Python Pandas: How to read only first n rows of CSV files in?

If you only want to read the first 999,999 (non-header) rows:

read_csv(..., nrows=999999)

If you only want to read rows 1,000,000 ... 1,999,999

read_csv(..., skiprows=1000000, nrows=999999)

nrows : int, default None Number of rows of file to read. Useful for reading pieces of large files*

skiprows : list-like or integer Row numbers to skip (0-indexed) or number of rows to skip (int) at the start of the file

and for large files, you'll probably also want to use chunksize:

chunksize : int, default None Return TextFileReader object for iteration

pandas.io.parsers.read_csv documentation

How to open Android Device Monitor in latest Android Studio 3.1

You still can run it from File explorer on Windows 10 with the proper path. You just need to go to C:\Users\user\AppData\Local\Android\Sdk\tools\lib\monitor-x86_64 and double click the file monitor.

If you want to use in the cmd just the 'monitor' command you have to add this folder (in my case with android studio 3.4.1 and win10) to your Environment variables. So, press the start button and then type Edit the system environment variabes click it and System properties window should open. Then go to

Environment variables => System variables => path

press the Edit button for path and add the new value

C:\Users\user\AppData\Local\Android\Sdk\tools\lib\monitor-x86_64

click 'Ok', 'Ok' and 'Ok' and restart the cmd window if you had it opened and type 'monitor' and it should open the monitor as well.

Hope it helps!

PD: This answer was based on this answer https://stackoverflow.com/a/55077068/5360905 from Tiago Martins Peres

How to get device make and model on iOS?

Below Function Perfectly Working on iOS7 or later version in Swift

func DeviceName()-> String {

        var myDeviceName : String = String()

        var systemInfo = [UInt8](count: sizeof(utsname), repeatedValue: 0)

        let model = systemInfo.withUnsafeMutableBufferPointer { (inout body: UnsafeMutableBufferPointer<UInt8>) -> String? in

            if uname(UnsafeMutablePointer(body.baseAddress)) != 0 {
                return nil
            }

            return String.fromCString(UnsafePointer(body.baseAddress.advancedBy(Int(_SYS_NAMELEN * 4))))
        }

        let deviceNamesByCode : [String: String] = ["iPod1,1":"iPod Touch 1",
                                                    "iPod2,1":"iPod Touch 2",
                                                    "iPod3,1":"iPod Touch 3",
                                                    "iPod4,1":"iPod Touch 4",
                                                    "iPod5,1":"iPod Touch 5",
                                                    "iPod7,1":"iPod Touch 6",
                                                    "iPhone1,1":"iPhone",
                                                    "iPhone1,2":"iPhone ",
                                                    "iPhone2,1":"iPhone ",
                                                    "iPhone3,1":"iPhone 4",
                                                    "iPhone3,2":"iPhone 4",
                                                    "iPhone3,3":"iPhone 4",
                                                    "iPhone4,1":"iPhone 4s",
                                                    "iPhone5,1":"iPhone 5",
                                                    "iPhone5,2":"iPhone 5",
                                                    "iPhone5,3":"iPhone 5c",
                                                    "iPhone5,4":"iPhone 5c",
                                                    "iPhone6,1":"iPhone 5s",
                                                    "iPhone6,2":"iPhone 5s",
                                                    "iPhone7,2":"iPhone 6",
                                                    "iPhone7,1":"iPhone 6 Plus",
                                                    "iPhone8,1":"iPhone 6s",
                                                    "iPhone8,2":"iPhone 6s Plus",
                                                    "iPhone8,4":"iPhone SE",
                                                    "iPad2,1":"iPad 2",
                                                    "iPad2,2":"iPad 2",
                                                    "iPad2,3":"iPad 2",
                                                    "iPad2,4":"iPad 2",
                                                    "iPad3,1":"iPad 3",
                                                    "iPad3,2":"iPad 3",
                                                    "iPad3,3":"iPad 3",
                                                    "iPad3,4":"iPad 4",
                                                    "iPad3,5":"iPad 4",
                                                    "iPad3,6":"iPad 4",
                                                    "iPad4,1":"iPad Air",
                                                    "iPad4,2":"iPad Air",
                                                    "iPad4,3":"iPad Air",
                                                    "iPad5,3":"iPad Air 2",
                                                    "iPad5,4":"iPad Air 2",
                                                    "iPad2,5":"iPad Mini",
                                                    "iPad2,6":"iPad Mini",
                                                    "iPad2,7":"iPad Mini",
                                                    "iPad4,4":"iPad Mini 2",
                                                    "iPad4,5":"iPad Mini 2",
                                                    "iPad4,6":"iPad Mini 2",
                                                    "iPad4,7":"iPad Mini 3",
                                                    "iPad4,8":"iPad Mini 3",
                                                    "iPad4,9":"iPad Mini 3",
                                                    "iPad5,1":"iPad Mini 4",
                                                    "iPad5,2":"iPad Mini 4",
                                                    "iPad6,3":"iPad Pro",
                                                    "iPad6,4":"iPad Pro",
                                                    "iPad6,7":"iPad Pro",
                                                    "iPad6,8":"iPad Pro",
                                                    "AppleTV5,3":"Apple TV",
                                                    "i386":"Simulator",
                                                    "x86_64":"Simulator"

        ]

        if model!.characters.count > 0 {
            myDeviceName = deviceNamesByCode[model!]!
        }else{
            myDeviceName = UIDevice.currentDevice().model
        }

        print("myDeviceName==\(myDeviceName)")
        return myDeviceName

    }

Fatal error: Call to undefined function imap_open() in PHP

On Mac OS X with Homebrew, as obviously, PHP is already installed due to provided error we cannot run:

Update: Tha latest version brew instal php --with-imap will not work any more!!!

$ brew install php72 --with-imap
Warning: homebrew/php/php72 7.2.xxx is already installed

Also, installing module only, here will not work:

$ brew install php72-imap
Error: No available formula with the name "php72-imap"

So, we must reinstall it:

$ brew reinstall php72 --with-imap

It will take a while :-) (built in 8 minutes 17 seconds)

Closing database connections in Java

Actually, it is best if you use a try-with-resources block and Java will close all of the connections for you when you exit the try block.

You should do this with any object that implements AutoClosable.

try (Connection connection = getDatabaseConnection(); Statement statement = connection.createStatement()) {
    String sqlToExecute = "SELECT * FROM persons";
    try (ResultSet resultSet = statement.execute(sqlToExecute)) {
        if (resultSet.next()) {
            System.out.println(resultSet.getString("name");
        }
    }
} catch (SQLException e) {
    System.out.println("Failed to select persons.");
}

The call to getDatabaseConnection is just made up. Replace it with a call that gets you a JDBC SQL connection or a connection from a pool.

Draw path between two points using Google Maps Android API v2

in below code midpointsList is an ArrayList of waypoints

private String getMapsApiDirectionsUrl(GoogleMap googleMap, LatLng startLatLng, LatLng endLatLng, ArrayList<LatLng> midpointsList) {
    String origin = "origin=" + startLatLng.latitude + "," + startLatLng.longitude;

    String midpoints = "";
    for (int mid = 0; mid < midpointsList.size(); mid++) {
        midpoints += "|" + midpointsList.get(mid).latitude + "," + midpointsList.get(mid).longitude;
    }

    String waypoints = "waypoints=optimize:true" + midpoints + "|";

    String destination = "destination=" + endLatLng.latitude + "," + endLatLng.longitude;
    String key = "key=AIzaSyCV1sOa_7vASRBs6S3S6t1KofFvDhjohvI";

    String sensor = "sensor=false";
    String params = origin + "&" + waypoints + "&" + destination + "&" + sensor + "&" + key;
    String output = "json";
    String url = "https://maps.googleapis.com/maps/api/directions/" + output + "?" + params;


    Log.e("url", url);
    parseDirectionApidata(url, googleMap);
    return url;
}

Then copy and paste this url in your browser to check And the below code is to parse the url

    private void parseDirectionApidata(String url, final GoogleMap googleMap) {

    final JSONObject jsonObject = new JSONObject();

    try {

        AppUtill.getJsonWithHTTPPost(ViewMapActivity.this, 1, new ServiceCallBack() {
            @Override
            public void serviceCallBack(int id, JSONObject jsonResult) throws JSONException {

                if (jsonResult != null) {

                    Log.e("jsonRes", jsonResult.toString());

                    String status = jsonResult.optString("status");

                    if (status.equalsIgnoreCase("ok")) {
                        drawPath(jsonResult, googleMap);
                    }

                } else {

                    Toast.makeText(ViewMapActivity.this, "Unable to parse Directions Data", Toast.LENGTH_LONG).show();
                }

            }
        }, url, jsonObject);

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

    }
}

And then pass the result to the drawPath method

    public void drawPath(JSONObject jObject, GoogleMap googleMap) {

    List<List<HashMap<String, String>>> routes = new ArrayList<List<HashMap<String, String>>>();
    JSONArray jRoutes = null;
    JSONArray jLegs = null;
    JSONArray jSteps = null;
    List<LatLng> list = null;
    try {

        Toast.makeText(ViewMapActivity.this, "Drawing Path...", Toast.LENGTH_SHORT).show();
        jRoutes = jObject.getJSONArray("routes");

        /** Traversing all routes */
        for (int i = 0; i < jRoutes.length(); i++) {
            jLegs = ((JSONObject) jRoutes.get(i)).getJSONArray("legs");
            List path = new ArrayList<HashMap<String, String>>();

            /** Traversing all legs */
            for (int j = 0; j < jLegs.length(); j++) {
                jSteps = ((JSONObject) jLegs.get(j)).getJSONArray("steps");

                /** Traversing all steps */
                for (int k = 0; k < jSteps.length(); k++) {
                    String polyline = "";
                    polyline = (String) ((JSONObject) ((JSONObject) jSteps.get(k)).get("polyline")).get("points");
                    list = decodePoly(polyline);
                }
                Log.e("list", list.toString());
                routes.add(path);
                Log.e("routes", routes.toString());
                if (list != null) {
                    Polyline line = googleMap.addPolyline(new PolylineOptions()
                            .addAll(list)
                            .width(12)
                            .color(Color.parseColor("#FF0000"))//Google maps blue color #05b1fb
                            .geodesic(true)
                    );
                }
            }
        }
    } catch (JSONException e) {
        e.printStackTrace();
    }

}

  private List<LatLng> decodePoly(String encoded) {

    List<LatLng> poly = new ArrayList<LatLng>();
    int index = 0, len = encoded.length();
    int lat = 0, lng = 0;

    while (index < len) {
        int b, shift = 0, result = 0;
        do {
            b = encoded.charAt(index++) - 63;
            result |= (b & 0x1f) << shift;
            shift += 5;
        } while (b >= 0x20);
        int dlat = ((result & 1) != 0 ? ~(result >> 1) : (result >> 1));
        lat += dlat;

        shift = 0;
        result = 0;
        do {
            b = encoded.charAt(index++) - 63;
            result |= (b & 0x1f) << shift;
            shift += 5;
        } while (b >= 0x20);
        int dlng = ((result & 1) != 0 ? ~(result >> 1) : (result >> 1));
        lng += dlng;

        LatLng p = new LatLng((((double) lat / 1E5)),
                (((double) lng / 1E5)));
        poly.add(p);
    }

    return poly;
}

decode poly function is to decode the points(lat and long) provided by Directions API in encoded form

Java enum - why use toString instead of name

While most people blindly follow the advice of the javadoc, there are very specific situations where you want to actually avoid toString(). For example, I'm using enums in my Java code, but they need to be serialized to a database, and back again. If I used toString() then I would technically be subject to getting the overridden behavior as others have pointed out.

Additionally one can also de-serialize from the database, for example, this should always work in Java:

MyEnum taco = MyEnum.valueOf(MyEnum.TACO.name());

Whereas this is not guaranteed:

MyEnum taco = MyEnum.valueOf(MyEnum.TACO.toString());

By the way, I find it very odd for the Javadoc to explicitly say "most programmers should". I find very little use-case in the toString of an enum, if people are using that for a "friendly name" that's clearly a poor use-case as they should be using something more compatible with i18n, which would, in most cases, use the name() method.

android TextView: setting the background color dynamically doesn't work

I had a similar issue where I was creating a numeric color without considering the leading alpha channel. ie. mytext.setTextColor(0xFF0000) (thinking this would be red ). While this is a red color it is also 100% transparent as it = 0x00FF0000; The correct 100% opaque value is 0xFFFF0000 or mytext.setTextcolor(0xFFFF0000).

angularjs: allows only numbers to be typed into a text box

HTML

 <input type="text" name="number" only-digits>

// Just type 123

  .directive('onlyDigits', function () {
    return {
      require: 'ngModel',
      restrict: 'A',
      link: function (scope, element, attr, ctrl) {
        function inputValue(val) {
          if (val) {
            var digits = val.replace(/[^0-9]/g, '');

            if (digits !== val) {
              ctrl.$setViewValue(digits);
              ctrl.$render();
            }
            return parseInt(digits,10);
          }
          return undefined;
        }            
        ctrl.$parsers.push(inputValue);
      }
    };
});

// type: 123 or 123.45

 .directive('onlyDigits', function () {
    return {
      require: 'ngModel',
      restrict: 'A',
      link: function (scope, element, attr, ctrl) {
        function inputValue(val) {
          if (val) {
            var digits = val.replace(/[^0-9.]/g, '');

            if (digits.split('.').length > 2) {
              digits = digits.substring(0, digits.length - 1);
            }

            if (digits !== val) {
              ctrl.$setViewValue(digits);
              ctrl.$render();
            }
            return parseFloat(digits);
          }
          return undefined;
        }            
        ctrl.$parsers.push(inputValue);
      }
    };
 });

check if jquery has been loaded, then load it if false

Maybe something like this:

<script>
if(!window.jQuery)
{
   var script = document.createElement('script');
   script.type = "text/javascript";
   script.src = "path/to/jQuery";
   document.getElementsByTagName('head')[0].appendChild(script);
}
</script>

Edit and replay XHR chrome/firefox etc?

My two suggestions:

  1. Chrome's Postman plugin + the Postman Interceptor Plugin. More Info: Postman Capturing Requests Docs

  2. If you're on Windows then Telerik's Fiddler is an option. It has a composer option to replay http requests, and it's free.

How can I change column types in Spark SQL's DataFrame?

Why not just do as described under http://spark.apache.org/docs/latest/api/python/pyspark.sql.html#pyspark.sql.Column.cast

df.select(df.year.cast("int"),"make","model","comment","blank")

Split an integer into digits to compute an ISBN checksum

while number:
    digit = number % 10

    # do whatever with digit

    # remove last digit from number (as integer)
    number //= 10

On each iteration of the loop, it removes the last digit from number, assigning it to digit. It's in reverse, starts from the last digit, finishes with the first

Make absolute positioned div expand parent div height

I had a similar problem. To solve this (instead of calculate the iframe's height using the body, document or window) I created a div that wraps the whole page content (a div with an id="page" for example) and then I used its height.

data type not understood

Try:

mmatrix = np.zeros((nrows, ncols))

Since the shape parameter has to be an int or sequence of ints

http://docs.scipy.org/doc/numpy/reference/generated/numpy.zeros.html

Otherwise you are passing ncols to np.zeros as the dtype.

Can I run javascript before the whole page is loaded?

Not only can you, but you have to make a special effort not to if you don't want to. :-)

When the browser encounters a classic script tag when parsing the HTML, it stops parsing and hands over to the JavaScript interpreter, which runs the script. The parser doesn't continue until the script execution is complete (because the script might do document.write calls to output markup that the parser should handle).

That's the default behavior, but you have a few options for delaying script execution:

  1. Use JavaScript modules. A type="module" script is deferred until the HTML has been fully parsed and the initial DOM created. This isn't the primary reason to use modules, but it's one of the reasons:

    <script type="module" src="./my-code.js"></script>
    <!-- Or -->
    <script type="module">
    // Your code here
    </script>
    

    The code will be fetched (if it's separate) and parsed in parallel with the HTML parsing, but won't be run until the HTML parsing is done. (If your module code is inline rather than in its own file, it is also deferred until HTML parsing is complete.)

    This wasn't available when I first wrote this answer in 2010, but here in 2020, all major modern browsers support modules natively, and if you need to support older browsers, you can use bundlers like Webpack and Rollup.js.

  2. Use the defer attribute on a classic script tag:

    <script defer src="./my-code.js"></script>
    

    As with the module, the code in my-code.js will be fetched and parsed in parallel with the HTML parsing, but won't be run until the HTML parsing is done. But, defer doesn't work with inline script content, only with external files referenced via src.

  3. I don't think it's what you want, but you can use the async attribute to tell the browser to fetch the JavaScript code in parallel with the HTML parsing, but then run it as soon as possible, even if the HTML parsing isn't complete. You can put it on a type="module" tag, or use it instead of defer on a classic script tag.

  4. Put the script tag at the end of the document, just prior to the closing </body> tag:

    <!doctype html>
    <html>
    <!-- ... -->
    <body>
    <!-- The document's HTML goes here -->
    <script type="module" src="./my-code.js"></script><!-- Or inline script -->
    </body>
    </html>
    

    That way, even though the code is run as soon as its encountered, all of the elements defined by the HTML above it exist and are ready to be used.

    It used to be that this caused an additional delay on some browsers because they wouldn't start fetching the code until the script tag was encountered, but modern browsers scan ahead and start prefetching. Still, this is very much the third choice at this point, both modules and defer are better options.

The spec has a useful diagram showing a raw script tag, defer, async, type="module", and type="module" async and the timing of when the JavaScript code is fetched and run:

enter image description here

Here's an example of the default behavior, a raw script tag:

_x000D_
_x000D_
.found {_x000D_
    color: green;_x000D_
}
_x000D_
<p>Paragraph 1</p>_x000D_
<script>_x000D_
    if (typeof NodeList !== "undefined" && !NodeList.prototype.forEach) {_x000D_
        NodeList.prototype.forEach = Array.prototype.forEach;_x000D_
    }_x000D_
    document.querySelectorAll("p").forEach(p => {_x000D_
        p.classList.add("found");_x000D_
    });_x000D_
</script>_x000D_
<p>Paragraph 2</p>
_x000D_
_x000D_
_x000D_

(See my answer here for details around that NodeList code.)

When you run that, you see "Paragraph 1" in green but "Paragraph 2" is black, because the script ran synchronously with the HTML parsing, and so it only found the first paragraph, not the second.

In contrast, here's a type="module" script:

_x000D_
_x000D_
.found {_x000D_
    color: green;_x000D_
}
_x000D_
<p>Paragraph 1</p>_x000D_
<script type="module">_x000D_
    document.querySelectorAll("p").forEach(p => {_x000D_
        p.classList.add("found");_x000D_
    });_x000D_
</script>_x000D_
<p>Paragraph 2</p>
_x000D_
_x000D_
_x000D_

Notice how they're both green now; the code didn't run until HTML parsing was complete. That would also be true with a defer script with external content (but not inline content).

(There was no need for the NodeList check there because any modern browser supporting modules already has forEach on NodeList.)

In this modern world, there's no real value to the DOMContentLoaded event of the "ready" feature that PrototypeJS, jQuery, ExtJS, Dojo, and most others provided back in the day (and still provide); just use modules or defer. Even back in the day, there wasn't much reason for using them (and they were often used incorrectly, holding up page presentation while the entire jQuery library was loaded because the script was in the head instead of after the document), something some developers at Google flagged up early on. This was also part of the reason for the YUI recommendation to put scripts at the end of the body, again back in the day.

phpmailer - The following SMTP Error: Data not accepted

Interestingly, I had the same exact issue and for me the problem was that my connection was timing out. To be able to see more details on my connections, I added $mail->SMTPDebug = 4; to my phpmailer (look up how to capture the debug since the default output function is echo).

Here's the result:

SMTP -> get_lines(): $data was ""
SMTP -> get_lines(): $str is ""
SMTP -> get_lines(): $data is ""
SMTP -> get_lines(): timed-out (10 seconds)
SMTP -> FROM SERVER:
SMTP -> ERROR: DATA not accepted from server: 

The default timeout is set to 10 seconds. If your app can support more, add this line to your phpmailer:

$mail->Timeout = 20;

error LNK2005: xxx already defined in MSVCRT.lib(MSVCR100.dll) C:\something\LIBCMT.lib(setlocal.obj)

Getting this error, I changed the

c/C++ > Code Generation > Runtime Library to Multi-threaded library (DLL) /MD

for both code project and associated Google Test project. This solved the issue.

Note: all components of the project must have the same definition in c/C++ > Code Generation > Runtime Library. Either DLL or not DLL, but identical.

The remote end hung up unexpectedly while git cloning

SOLVED WITH WIFI Router Setting :

I got same issue when I am in wifi with Settings PPPoE(auto login by wifi router).

Git download speed is very slow 15kb.

packet_write_wait: Connection to 17.121.133.16 port 22: Broken pipe fatal: The remote end hung up unexpectedly fatal: early EOF fatal: index-pack failed

Solution : 1. Changed setting to Dynamic IP, reboot wifi router. 2. From web browser login to Internet service provider portal (do not configure PPPoE , auto login from the wifi router).

After changing Git download speed is 1.7MiB.

Using BeautifulSoup to extract text without tags

Just loop through all the <strong> tags and use next_sibling to get what you want. Like this:

for strong_tag in soup.find_all('strong'):
    print(strong_tag.text, strong_tag.next_sibling)

Demo:

from bs4 import BeautifulSoup

html = '''
<p>
  <strong class="offender">YOB:</strong> 1987<br />
  <strong class="offender">RACE:</strong> WHITE<br />
  <strong class="offender">GENDER:</strong> FEMALE<br />
  <strong class="offender">HEIGHT:</strong> 5'05''<br />
  <strong class="offender">WEIGHT:</strong> 118<br />
  <strong class="offender">EYE COLOR:</strong> GREEN<br />
  <strong class="offender">HAIR COLOR:</strong> BROWN<br />
</p>
'''

soup = BeautifulSoup(html)

for strong_tag in soup.find_all('strong'):
    print(strong_tag.text, strong_tag.next_sibling)

This gives you:

YOB:  1987
RACE:  WHITE
GENDER:  FEMALE
HEIGHT:  5'05''
WEIGHT:  118
EYE COLOR:  GREEN
HAIR COLOR:  BROWN

Remove an element from a Bash array

If anyone finds themselves in a position where they need to remember set -e or set -x values and be able to restore them, please check out this gist which uses the first array deletion solution to manage it's own stack:

https://gist.github.com/kigster/94799325e39d2a227ef89676eed44cc6

Is it possible to insert multiple rows at a time in an SQLite database?

update

As BrianCampbell points out here, SQLite 3.7.11 and above now supports the simpler syntax of the original post. However, the approach shown is still appropriate if you want maximum compatibility across legacy databases.

original answer

If I had privileges, I would bump river's reply: You can insert multiple rows in SQLite, you just need different syntax. To make it perfectly clear, the OPs MySQL example:

INSERT INTO 'tablename' ('column1', 'column2') VALUES
  ('data1', 'data2'),
  ('data1', 'data2'),
  ('data1', 'data2'),
  ('data1', 'data2');

This can be recast into SQLite as:

     INSERT INTO 'tablename'
          SELECT 'data1' AS 'column1', 'data2' AS 'column2'
UNION ALL SELECT 'data1', 'data2'
UNION ALL SELECT 'data1', 'data2'
UNION ALL SELECT 'data1', 'data2'

a note on performance

I originally used this technique to efficiently load large datasets from Ruby on Rails. However, as Jaime Cook points out, it's not clear this is any faster wrapping individual INSERTs within a single transaction:

BEGIN TRANSACTION;
INSERT INTO 'tablename' table VALUES ('data1', 'data2');
INSERT INTO 'tablename' table VALUES ('data3', 'data4');
...
COMMIT;

If efficiency is your goal, you should try this first.

a note on UNION vs UNION ALL

As several people commented, if you use UNION ALL (as shown above), all rows will be inserted, so in this case, you'd get four rows of data1, data2. If you omit the ALL, then duplicate rows will be eliminated (and the operation will presumably be a bit slower). We're using UNION ALL since it more closely matches the semantics of the original post.

in closing

P.S.: Please +1 river's reply, as it presented the solution first.

How do I set the driver's python version in spark?

I am using the following environment

? python --version; ipython --version; jupyter --version
Python 3.5.2+
5.3.0
5.0.0

and the following aliases work well for me

alias pyspark="PYSPARK_PYTHON=/usr/local/bin/python3 PYSPARK_DRIVER_PYTHON=ipython ~/spark-2.1.1-bin-hadoop2.7/bin/pyspark --packages graphframes:graphframes:0.5.0-spark2.1-s_2.11"    
alias pysparknotebook="PYSPARK_PYTHON=/usr/bin/python3 PYSPARK_DRIVER_PYTHON=jupyter PYSPARK_DRIVER_PYTHON_OPTS='notebook' ~/spark-2.1.1-bin-hadoop2.7/bin/pyspark --packages graphframes:graphframes:0.5.0-spark2.1-s_2.11"

In the notebook, I set up the environment as follows

from pyspark.context import SparkContext
sc = SparkContext.getOrCreate()

Squash the first two commits in Git?

I've reworked VonC's script to do everything automatically and not ask me for anything. You give it two commit SHA1s and it will squash everything between them into one commit named "squashed history":

#!/bin/sh
# Go back to the last commit that we want
# to form the initial commit (detach HEAD)
git checkout $2

# reset the branch pointer to the initial commit (= $1),
# but leaving the index and working tree intact.
git reset --soft $1

# amend the initial tree using the tree from $2
git commit --amend -m "squashed history"

# remember the new commit sha1
TARGET=`git rev-list HEAD --max-count=1`

# go back to the original branch (assume master for this example)
git checkout master

# Replay all the commits after $2 onto the new initial commit
git rebase --onto $TARGET $2

How to run 'sudo' command in windows

There is no sudo command in case of windows and also there is no need to put any $. For installing Angular CLI through node.js command prompt in windows, I just wrote npm install -g @angular/cli and then pressed Enter. It worked fine.

React-router v4 this.props.history.push(...) not working

It seems things have changed around a bit in the latest version of react router. You can now access history via the context. this.context.history.push('/path')

Also see the replies to the this github issue: https://github.com/ReactTraining/react-router/issues/4059

Verilog: How to instantiate a module

This is all generally covered by Section 23.3.2 of SystemVerilog IEEE Std 1800-2012.

The simplest way is to instantiate in the main section of top, creating a named instance and wiring the ports up in order:

module top(
   input        clk,
   input        rst_n,
   input        enable,
   input  [9:0] data_rx_1,
   input  [9:0] data_rx_2,
   output [9:0] data_tx_2
);

subcomponent subcomponent_instance_name (
  clk, rst_n, data_rx_1, data_tx ); 

endmodule

This is described in Section 23.3.2.1 of SystemVerilog IEEE Std 1800-2012.

This has a few draw backs especially regarding the port order of the subcomponent code. simple refactoring here can break connectivity or change behaviour. for example if some one else fixs a bug and reorders the ports for some reason, switching the clk and reset order. There will be no connectivity issue from your compiler but will not work as intended.

module subcomponent(
  input        rst_n,       
  input        clk,
  ...

It is therefore recommended to connect using named ports, this also helps tracing connectivity of wires in the code.

module top(
   input        clk,
   input        rst_n,
   input        enable,
   input  [9:0] data_rx_1,
   input  [9:0] data_rx_2,
   output [9:0] data_tx_2
);

subcomponent subcomponent_instance_name (
  .clk(clk), .rst_n(rst_n), .data_rx(data_rx_1), .data_tx(data_tx) ); 

endmodule

This is described in Section 23.3.2.2 of SystemVerilog IEEE Std 1800-2012.

Giving each port its own line and indenting correctly adds to the readability and code quality.

subcomponent subcomponent_instance_name (
  .clk      ( clk       ), // input
  .rst_n    ( rst_n     ), // input
  .data_rx  ( data_rx_1 ), // input  [9:0]
  .data_tx  ( data_tx   )  // output [9:0]
);

So far all the connections that have been made have reused inputs and output to the sub module and no connectivity wires have been created. What happens if we are to take outputs from one component to another:

clk_gen( 
  .clk      ( clk_sub   ), // output
  .en       ( enable    )  // input

subcomponent subcomponent_instance_name (
  .clk      ( clk_sub   ), // input
  .rst_n    ( rst_n     ), // input 
  .data_rx  ( data_rx_1 ), // input  [9:0]
  .data_tx  ( data_tx   )  // output [9:0]
);

This nominally works as a wire for clk_sub is automatically created, there is a danger to relying on this. it will only ever create a 1 bit wire by default. An example where this is a problem would be for the data:

Note that the instance name for the second component has been changed

subcomponent subcomponent_instance_name (
  .clk      ( clk_sub   ), // input
  .rst_n    ( rst_n     ), // input 
  .data_rx  ( data_rx_1 ), // input  [9:0]
  .data_tx  ( data_temp )  // output [9:0]
);
subcomponent subcomponent_instance_name2 (
  .clk      ( clk_sub   ), // input
  .rst_n    ( rst_n     ), // input 
  .data_rx  ( data_temp ), // input  [9:0]
  .data_tx  ( data_tx   )  // output [9:0]
);

The issue with the above code is that data_temp is only 1 bit wide, there would be a compile warning about port width mismatch. The connectivity wire needs to be created and a width specified. I would recommend that all connectivity wires be explicitly written out.

wire [9:0] data_temp
subcomponent subcomponent_instance_name (
  .clk      ( clk_sub   ), // input
  .rst_n    ( rst_n     ), // input 
  .data_rx  ( data_rx_1 ), // input  [9:0]
  .data_tx  ( data_temp )  // output [9:0]
);
subcomponent subcomponent_instance_name2 (
  .clk      ( clk_sub   ), // input
  .rst_n    ( rst_n     ), // input 
  .data_rx  ( data_temp ), // input  [9:0]
  .data_tx  ( data_tx   )  // output [9:0]
);

Moving to SystemVerilog there are a few tricks available that save typing a handful of characters. I believe that they hinder the code readability and can make it harder to find bugs.

Use .port with no brackets to connect to a wire/reg of the same name. This can look neat especially with lots of clk and resets but at some levels you may generate different clocks or resets or you actually do not want to connect to the signal of the same name but a modified one and this can lead to wiring bugs that are not obvious to the eye.

module top(
   input        clk,
   input        rst_n,
   input        enable,
   input  [9:0] data_rx_1,
   input  [9:0] data_rx_2,
   output [9:0] data_tx_2
);

subcomponent subcomponent_instance_name (
  .clk,                    // input **Auto connect**
  .rst_n,                  // input **Auto connect**
  .data_rx  ( data_rx_1 ), // input  [9:0]
  .data_tx  ( data_tx   )  // output [9:0]
);

endmodule

This is described in Section 23.3.2.3 of SystemVerilog IEEE Std 1800-2012.

Another trick that I think is even worse than the one above is .* which connects unmentioned ports to signals of the same wire. I consider this to be quite dangerous in production code. It is not obvious when new ports have been added and are missing or that they might accidentally get connected if the new port name had a counter part in the instancing level, they get auto connected and no warning would be generated.

subcomponent subcomponent_instance_name (
  .*,                      // **Auto connect**
  .data_rx  ( data_rx_1 ), // input  [9:0]
  .data_tx  ( data_tx   )  // output [9:0]
);

This is described in Section 23.3.2.4 of SystemVerilog IEEE Std 1800-2012.

Insert multiple rows WITHOUT repeating the "INSERT INTO ..." part of the statement?

Corresponding to INSERT (Transact-SQL) (SQL Server 2005) you can't omit INSERT INTO dbo.Blah and have to specify it every time or use another syntax/approach,

POSTing JsonObject With HttpClient From Web API

I don't have enough reputation to add a comment on the answer from pomber so I'm posting another answer. Using pomber's approach I kept receiving a "400 Bad Request" response from an API I was POSTing my JSON request to (Visual Studio 2017, .NET 4.6.2). Eventually the problem was traced to the "Content-Type" header produced by StringContent() being incorrect (see https://github.com/dotnet/corefx/issues/7864).

tl;dr

Use pomber's answer with an extra line to correctly set the header on the request:

var content = new StringContent(jsonObject.ToString(), Encoding.UTF8, "application/json");
content.Headers.ContentType = new MediaTypeHeaderValue("application/json");
var result = client.PostAsync(url, content).Result;

What does `set -x` do?

set -x

Prints a trace of simple commands, for commands, case commands, select commands, and arithmetic for commands and their arguments or associated word lists after they are expanded and before they are executed. The value of the PS4 variable is expanded and the resultant value is printed before the command and its expanded arguments.

[source]

Example

set -x
echo `expr 10 + 20 `
+ expr 10 + 20
+ echo 30
30

set +x
echo `expr 10 + 20 `
30

Above example illustrates the usage of set -x. When it is used, above arithmetic expression has been expanded. We could see how a singe line has been evaluated step by step.

  • First step expr has been evaluated.
  • Second step echo has been evaluated.

To know more about set ? visit this link

when it comes to your shell script,

[ "$DEBUG" == 'true' ] && set -x

Your script might have been printing some additional lines of information when the execution mode selected as DEBUG. Traditionally people used to enable debug mode when a script called with optional argument such as -d

What is the equivalent of Java's final in C#?

What everyone here is missing is Java's guarantee of definite assignment for final member variables.

For a class C with final member variable V, every possible execution path through every constructor of C must assign V exactly once - failing to assign V or assigning V two or more times will result in an error.

C#'s readonly keyword has no such guarantee - the compiler is more than happy to leave readonly members unassigned or allow you to assign them multiple times within a constructor.

So, final and readonly (at least with respect to member variables) are definitely not equivalent - final is much more strict.

Pandas split column of lists into multiple columns

Much simpler solution:

pd.DataFrame(df2["teams"].to_list(), columns=['team1', 'team2'])

Yields,

  team1 team2
-------------
0    SF   NYG
1    SF   NYG
2    SF   NYG
3    SF   NYG
4    SF   NYG
5    SF   NYG
6    SF   NYG
7    SF   NYG

If you wanted to split a column of delimited strings rather than lists, you could similarly do:

pd.DataFrame(df["teams"].str.split('<delim>', expand=True).values,
             columns=['team1', 'team2'])

Setting width as a percentage using jQuery

Using the width function:

$('div#somediv').width('70%');

will turn:

<div id="somediv" />

into:

<div id="somediv" style="width: 70%;"/>

Webpack "OTS parsing error" loading fonts

As of 2018,

use MiniCssExtractPlugin

for Webpack(> 4.0) will solve this problem.

https://github.com/webpack-contrib/mini-css-extract-plugin

Using extract-text-webpack-plugin in the accepted answer is NOT recommended for Webpack 4.0+.

Center the content inside a column in Bootstrap 4

<div class="container">
    <div class="row justify-content-center">
        <div class="col-3 text-center">
            Center text goes here
        </div>
    </div>
</div>

I have used justify-content-center class instead of mx-auto as in this answer.

check at https://jsfiddle.net/sarfarazk/4fsp4ywh/

Google Chrome Full Black Screen

i have resolved this by following steps.

1) Go to customise icon in the top right corner chrome.
2) click on more tools option.
3) Click task manager.
4) Kill/end process GPU process

This has resolved my issue of black screen in chrome.

javascript close current window

Should be

<input type="button" class="btn btn-success"
                       style="font-weight: bold;display: inline;"
                       value="Close"
                       onclick="closeMe()">
<script>
function closeMe()
{
    window.opener = self;
    window.close();
}
</script>

differences between using wmode="transparent", "opaque", or "window" for an embedded object on a webpage

One bizarre thing is that in Chrome + Firefox, the MOUSE_LEAVE event isn't dispatched for OPAQUE and TRANSPARENT.

With WINDOW it works fine. That one took some time to find out! grr...

(note: jediericb mentioned this bug - which is similar but doesn't mention MOUSE_LEAVE)

Xcode - iPhone - profile doesn't match any valid certificate-/private-key pair in the default keychain

To generate a certificate on the Apple provisioning profile website, firstly you have to generate keys on your mac, then upload the public key. Apple will generate your certificates with this key. When you download your certificates, tu be able to use them you need to have the private key.

The error "XCode could not find a valid private-key/certificate pair for this profile in your keychain." means you don't have the private key.

Maybe because your Mac was reinstalled, maybe because this key was generated on another Mac. So to be able to use your certificates, you need to find this key and install it on the keychain.

If you can not find it you can generate new keys restart this process on the provisioning profile website and get new certificates you will able to use.

sql server #region

BEGIN...END works, you just have to add a commented section. The easiest way to do this is to add a section name! Another route is to add a comment block. See below:

BEGIN  -- Section Name
/* 
Comment block some stuff  --end comment should be on next line
*/

 --Very long query
SELECT * FROM FOO
SELECT * FROM BAR
END

C++, copy set to vector

set<T> s;
//....
vector<T> v;
v.assign(s.begin(), s.end());

Why is quicksort better than mergesort?

Quicksort is the fastest sorting algorithm in practice but has a number of pathological cases that can make it perform as badly as O(n2).

Heapsort is guaranteed to run in O(n*ln(n)) and requires only finite additional storage. But there are many citations of real world tests which show that heapsort is significantly slower than quicksort on average.

Regular expression to find two strings anywhere in input

If you absolutely need to only use one regex then

/(?=.*?(string1))(?=.*?(string2))/is

i modifier = case-insensitive

.*? Lazy evaluation for any character (matches as few as possible)

?= for Positive LookAhead it has to match somewhere

s modifier = .(period) also accepts line breaks

More than one file was found with OS independent path 'META-INF/LICENSE'

I was wired, but my project was already migrated to AndroidX, but after migrating to androidX again, it refactored some part of my project and the problem solved.

Error in plot.new() : figure margins too large in R

The problem is that the small figure region 2 created by your layout() call is not sufficiently large enough to contain just the default margins, let alone a plot.

More generally, you get this error if the size of the plotting region on the device is not large enough to actually do any plotting. For the OP's case the issue was having too small a plotting device to contain all the subplots and their margins and leave a large enough plotting region to draw in.

RStudio users can encounter this error if the Plot tab is too small to leave enough room to contain the margins, plotting region etc. This is because the physical size of that pane is the size of the graphics device. These are not independent issues; the plot pane in RStudio is just another plotting device, like png(), pdf(), windows(), and X11().

Solutions include:

  1. reducing the size of the margins; this might help especially if you are trying, as in the case of the OP, to draw several plots on the same device.

  2. increasing the physical dimensions of the device, either in the call to the device (e.g. png(), pdf(), etc) or by resizing the window / pane containing the device

  3. reducing the size of text on the plot as that can control the size of margins etc.

Reduce the size of the margins

Before the line causing the problem try:

par(mar = rep(2, 4))

then plot the second image

image(as.matrix(leg),col=cx,axes=T)

You'll need to play around with the size of the margins on the par() call I show to get this right.

Increase the size of the device

You may also need to increase the size of the actual device onto which you are plotting.

A final tip, save the par() defaults before changing them, so change your existing par() call to:

op <- par(oma=c(5,7,1,1))

then at the end of plotting do

par(op)

How to reset (clear) form through JavaScript?

Pure JS solution is as follows:

function clearForm(myFormElement) {

  var elements = myFormElement.elements;

  myFormElement.reset();

  for(i=0; i<elements.length; i++) {

  field_type = elements[i].type.toLowerCase();

  switch(field_type) {

    case "text":
    case "password":
    case "textarea":
          case "hidden":

      elements[i].value = "";
      break;

    case "radio":
    case "checkbox":
        if (elements[i].checked) {
          elements[i].checked = false;
      }
      break;

    case "select-one":
    case "select-multi":
                elements[i].selectedIndex = -1;
      break;

    default:
      break;
  }
    }
}

Returning a regex match in VBA (excel)

You need to access the matches in order to get at the SDI number. Here is a function that will do it (assuming there is only 1 SDI number per cell).

For the regex, I used "sdi followed by a space and one or more numbers". You had "sdi followed by a space and zero or more numbers". You can simply change the + to * in my pattern to go back to what you had.

Function ExtractSDI(ByVal text As String) As String

Dim result As String
Dim allMatches As Object
Dim RE As Object
Set RE = CreateObject("vbscript.regexp")

RE.pattern = "(sdi \d+)"
RE.Global = True
RE.IgnoreCase = True
Set allMatches = RE.Execute(text)

If allMatches.count <> 0 Then
    result = allMatches.Item(0).submatches.Item(0)
End If

ExtractSDI = result

End Function

If a cell may have more than one SDI number you want to extract, here is my RegexExtract function. You can pass in a third paramter to seperate each match (like comma-seperate them), and you manually enter the pattern in the actual function call:

Ex) =RegexExtract(A1, "(sdi \d+)", ", ")

Here is:

Function RegexExtract(ByVal text As String, _
                      ByVal extract_what As String, _
                      Optional seperator As String = "") As String

Dim i As Long, j As Long
Dim result As String
Dim allMatches As Object
Dim RE As Object
Set RE = CreateObject("vbscript.regexp")

RE.pattern = extract_what
RE.Global = True
Set allMatches = RE.Execute(text)

For i = 0 To allMatches.count - 1
    For j = 0 To allMatches.Item(i).submatches.count - 1
        result = result & seperator & allMatches.Item(i).submatches.Item(j)
    Next
Next

If Len(result) <> 0 Then
    result = Right(result, Len(result) - Len(seperator))
End If

RegexExtract = result

End Function

*Please note that I have taken "RE.IgnoreCase = True" out of my RegexExtract, but you could add it back in, or even add it as an optional 4th parameter if you like.

How to append to New Line in Node.js

Use the os.EOL constant instead.

var os = require("os");

function processInput ( text ) 
{     
  fs.open('H://log.txt', 'a', 666, function( e, id ) {
   fs.write( id, text + os.EOL, null, 'utf8', function(){
    fs.close(id, function(){
     console.log('file is updated');
    });
   });
  });
 }

jQuery same click event for multiple elements

$('.class1, .class2').on('click', some_function);

Or:

$('.class1').add('.class2').on('click', some_function);

This also works with existing objects:

const $class1 = $('.class1');
const $class2 = $('.class2');
$class1.add($class2).on('click', some_function);

How to debug (only) JavaScript in Visual Studio?

For debugging JavaScript code in VS2015, there is no need for

  1. Enabling script debugging in IE Options -> Advanced tab
  2. Writing debugger statement in JavaScript code

Attaching IE didn't work, but here is a workaround.

Select IE

enter image description here

and press F5. This will attach both worker process and IE as shown here- enter image description here

If you are not interested in debugging server code, detach it from Processes window. enter image description here

You will still face the slowness when you press F5 and all your server code compiles and loads up in VS. Note that you can detach and attach again the IE instance launched from VS. JavaScript breakpoints are hit the same way they are in server side code.

Do I use <img>, <object>, or <embed> for SVG files?

In most circumstances, I recommend using the <object> tag to display SVG images. It feels a little unnatural, but it's the most reliable method if you want to provide dynamic effects.

For images without interaction, the <img> tag or a CSS background can be used.

Inline SVGs or iframes are possible options for some projects, but it's best to avoid <embed>

But if you want to play with SVG stuff like

  • Changing colors
  • Resize path
  • rotate svg

Go with the embedded one

<svg>
    <g> 
        <path> </path>
    </g>
</svg>

Iterate over each line in a string in PHP

preg_split the variable containing the text, and iterate over the returned array:

foreach(preg_split("/((\r?\n)|(\r\n?))/", $subject) as $line){
    // do stuff with $line
} 

Create a root password for PHPMyAdmin

  • Go tohttp://localhost/security/index.php
  • Select language, it redirects to http://localhost/security/xamppsecurity.php
  • You will find an option to change the password here

Changing text color of menu item in navigation drawer

 <android.support.design.widget.NavigationView
        android:id="@+id/navigation_view"
        android:background="#000"
        android:layout_height="match_parent"
        android:layout_width="match_parent"
        android:layout_gravity="start"
        app:headerLayout="@layout/header"
        app:itemTextColor="your color"
        app:menu="@menu/drawer" />

How do I change the font size and color in an Excel Drop Down List?

Try making the whole sheet font size smaller. Then zoom and save. Make a practice sheet first because it really screws everything up.

Python "TypeError: unhashable type: 'slice'" for encoding categorical data

Try by changing X[:,3] to X.iloc[:,3] in label encoder

Signed versus Unsigned Integers

Everything except for point 2 is correct. There are many different notations for signed ints, some implementations use the first, others use the last and yet others use something completely different. That all depends on the platform you're working with.

Using grep to search for a string that has a dot in it

Escape dot. Sample command will be.

grep '0\.00'

There is an error in XML document (1, 41)

First check the variables declared using proper Datatypes. I had a same problem then I have checked, by mistake I declared SAPUser as int datatype so that the error occurred. One more thing XML file stores its data using concept like array but its first index starts having +1. e.g. if error is in(7,2) then check for 6th line always.....

Ruby on Rails form_for select field with class

You can see in here: http://apidock.com/rails/ActionView/Helpers/FormBuilder/select

Or here: http://apidock.com/rails/ActionView/Helpers/FormOptionsHelper/select

Select tag has maximun 4 agrument, and last agrument is html option, it mean you can put class, require, selection option in here.

= f.select :sms_category_id, @sms_category_collect, {}, {class: 'form-control', required: true, selected: @set}

What does jQuery.fn mean?

jQuery.fn is defined shorthand for jQuery.prototype. From the source code:

jQuery.fn = jQuery.prototype = {
    // ...
}

That means jQuery.fn.jquery is an alias for jQuery.prototype.jquery, which returns the current jQuery version. Again from the source code:

// The current version of jQuery being used
jquery: "@VERSION",

How to post JSON to PHP with curl

Jordans analysis of why the $_POST-array isn't populated is correct. However, you can use

$data = file_get_contents("php://input");

to just retrieve the http body and handle it yourself. See PHP input/output streams.

From a protocol perspective this is actually more correct, since you're not really processing http multipart form data anyway. Also, use application/json as content-type when posting your request.

ERROR 1044 (42000): Access denied for user ''@'localhost' to database 'db'

Most Developers log-in to server(I assume you r having user-name and password for mysql database) then from Bash they switch to mysql> prompt then use the command below(which doesn’t work

mysql -h localhost -u root -p

What needs to be done is use the above command in the bash prompt--> on doing so it will ask for password if given it will take directly to mysql prompt and

then database, table can be created one by one

I faced similar deadlock so sharing the experience

I can pass a variable from a JSP scriptlet to JSTL but not from JSTL to a JSP scriptlet without an error

@skaffman nailed it down. They live each in its own context. However, I wouldn't consider using scriptlets as the solution. You'd like to avoid them. If all you want is to concatenate strings in EL and you discovered that the + operator fails for strings in EL (which is correct), then just do:

<c:out value="abc${test}" />

Or if abc is to obtained from another scoped variable named ${resp}, then do:

<c:out value="${resp}${test}" />

Query-string encoding of a Javascript Object

While there are limits to query-string lengths that should be considered (for sending JSON data in HTTP/s GET calls versus using POST) ...

JSON.stringify(yourJSON) will create a String from your JSON object.

Then just hex-encode it (link below).

That will work ALWAYS versus various possible problems with base64 type URL encoding, UTF-8 characters, nested JSON objects and such.

https://developer.mozilla.org/en-US/docs/Web/JavaScript/Reference/Global_Objects/JSON/stringify

Encode String to HEX

Getting the count of unique values in a column in bash

To see a frequency count for column two (for example):

awk -F '\t' '{print $2}' * | sort | uniq -c | sort -nr

fileA.txt

z    z    a
a    b    c
w    d    e

fileB.txt

t    r    e
z    d    a
a    g    c

fileC.txt

z    r    a
v    d    c
a    m    c

Result:

  3 d
  2 r
  1 z
  1 m
  1 g
  1 b

How can I transition height: 0; to height: auto; using CSS?

You should use scaleY instead.

_x000D_
_x000D_
ul {_x000D_
  background-color: #eee;_x000D_
  transform: scaleY(0);    _x000D_
  transform-origin: top;_x000D_
  transition: transform 0.26s ease;_x000D_
}_x000D_
p:hover ~ ul {_x000D_
  transform: scaleY(1);_x000D_
}
_x000D_
<p>Hover This</p>_x000D_
<ul>_x000D_
  <li>Coffee</li>_x000D_
  <li>Tea</li>_x000D_
  <li>Milk</li>_x000D_
</ul>
_x000D_
_x000D_
_x000D_

I've made a vendor prefixed version of the above code on jsfiddle, and changed your jsfiddle to use scaleY instead of height.

Python map object is not subscriptable

In Python 3, map returns an iterable object of type map, and not a subscriptible list, which would allow you to write map[i]. To force a list result, write

payIntList = list(map(int,payList))

However, in many cases, you can write out your code way nicer by not using indices. For example, with list comprehensions:

payIntList = [pi + 1000 for pi in payList]
for pi in payIntList:
    print(pi)

Markdown and image alignment

I have an alternative to the methods above that used the ALT tag and a CSS selector on the alt tag... Instead, add a URL hash like this:

First your Markdown image code:

![my image](/img/myImage.jpg#left)
![my image](/img/myImage.jpg#right)
![my image](/img/myImage.jpg#center)

Note the added URL hash #center.

Now add this rule in CSS using CSS 3 attribute selectors to select images with a certain path.

img[src*='#left'] {
    float: left;
}
img[src*='#right'] {
    float: right;
}
img[src*='#center'] {
    display: block;
    margin: auto;
}

You should be able to use a URL hash like this almost like defining a class name and it isn't a misuse of the ALT tag like some people had commented about for that solution. It also won't require any additional extensions. Do one for float right and left as well or any other styles you might want.

How do I return clean JSON from a WCF Service?

If you want nice json without hardcoding attributes into your service classes,

use <webHttp defaultOutgoingResponseFormat="Json"/> in your behavior config

How To Add An "a href" Link To A "div"?

In this case, it doesn't matter as there is no content between the two divs.

Either one will get the browser to scroll down to it.

The a element will look like:

<a href="mypageName.html#buttonOne">buttonOne</a>

Or:

<a href="mypageName.html#linkedinB">linkedinB</a>

Google Maps v2 - set both my location and zoom in

You also could set both parameters like,

mMap.moveCamera( CameraUpdateFactory.newLatLngZoom(new LatLng(21.000000, -101.400000) ,4) );

This locates your map on a specific position and zoom. I use this on the setting up my map.

Error retrieving parent for item: No resource found that matches the given name after upgrading to AppCompat v23

As pointed out by Tanis.7x, the support library version (23) does not match the targetSdkVersion (22)

You can fix this by doing the following:

In the build.grade file of your app module, change the following line of code

compile 'com.android.support:appcompat-v7:23.0.0'

To

compile 'com.android.support:appcompat-v7:22.+'

This will use the latest version of the appcompat version that is compatible with SdkVersion 22.

UILabel is not auto-shrinking text to fit label size

Two years on, and this issue is still around...

In iOS 8 / XCode 6.1, I was sometimes finding that my UILabel (created in a UITableViewCell, with AutoLayout turned on, and flexible constraints so it had plenty of space) wouldn't resize itself to fit the text string.

The solution, as in previous years, was to set the text, and then call sizeToFit.

-(UITableViewCell *)tableView:(UITableView *)tableView cellForRowAtIndexPath:(NSIndexPath *)indexPath
{
    . . .
    cell.lblCreatedAt.text = [note getCreatedDateAsString];
    [cell.lblCreatedAt sizeToFit];
}

(Sigh.)

How to find list intersection?

Here's some Python 2 / Python 3 code that generates timing information for both list-based and set-based methods of finding the intersection of two lists.

The pure list comprehension algorithms are O(n^2), since in on a list is a linear search. The set-based algorithms are O(n), since set search is O(1), and set creation is O(n) (and converting a set to a list is also O(n)). So for sufficiently large n the set-based algorithms are faster, but for small n the overheads of creating the set(s) make them slower than the pure list comp algorithms.

#!/usr/bin/env python

''' Time list- vs set-based list intersection
    See http://stackoverflow.com/q/3697432/4014959
    Written by PM 2Ring 2015.10.16
'''

from __future__ import print_function, division
from timeit import Timer

setup = 'from __main__ import a, b'
cmd_lista = '[u for u in a if u in b]'
cmd_listb = '[u for u in b if u in a]'

cmd_lcsa = 'sa=set(a);[u for u in b if u in sa]'

cmd_seta = 'list(set(a).intersection(b))'
cmd_setb = 'list(set(b).intersection(a))'

reps = 3
loops = 50000

def do_timing(heading, cmd, setup):
    t = Timer(cmd, setup)
    r = t.repeat(reps, loops)
    r.sort()
    print(heading, r)
    return r[0]

m = 10
nums = list(range(6 * m))

for n in range(1, m + 1):
    a = nums[:6*n:2]
    b = nums[:6*n:3]
    print('\nn =', n, len(a), len(b))
    #print('\nn = %d\n%s %d\n%s %d' % (n, a, len(a), b, len(b)))
    la = do_timing('lista', cmd_lista, setup) 
    lb = do_timing('listb', cmd_listb, setup) 
    lc = do_timing('lcsa ', cmd_lcsa, setup)
    sa = do_timing('seta ', cmd_seta, setup)
    sb = do_timing('setb ', cmd_setb, setup)
    print(la/sa, lb/sa, lc/sa, la/sb, lb/sb, lc/sb)

output

n = 1 3 2
lista [0.082171916961669922, 0.082588911056518555, 0.0898590087890625]
listb [0.069530963897705078, 0.070394992828369141, 0.075379848480224609]
lcsa  [0.11858987808227539, 0.1188349723815918, 0.12825107574462891]
seta  [0.26900982856750488, 0.26902294158935547, 0.27298116683959961]
setb  [0.27218389511108398, 0.27459001541137695, 0.34307217597961426]
0.305460649521 0.258469975867 0.440838458259 0.301898526833 0.255455833892 0.435697630214

n = 2 6 4
lista [0.15915989875793457, 0.16000485420227051, 0.16551494598388672]
listb [0.13000702857971191, 0.13060092926025391, 0.13543915748596191]
lcsa  [0.18650484085083008, 0.18742108345031738, 0.19513416290283203]
seta  [0.33592700958251953, 0.34001994132995605, 0.34146714210510254]
setb  [0.29436492919921875, 0.2953648567199707, 0.30039691925048828]
0.473793098554 0.387009751735 0.555194537893 0.540689066428 0.441652573672 0.633583767462

n = 3 9 6
lista [0.27657914161682129, 0.28098297119140625, 0.28311991691589355]
listb [0.21585917472839355, 0.21679902076721191, 0.22272896766662598]
lcsa  [0.22559309005737305, 0.2271728515625, 0.2323150634765625]
seta  [0.36382699012756348, 0.36453008651733398, 0.36750602722167969]
setb  [0.34979605674743652, 0.35533690452575684, 0.36164689064025879]
0.760194128313 0.59330170819 0.62005595016 0.790686848184 0.61710008036 0.644927481902

n = 4 12 8
lista [0.39616990089416504, 0.39746403694152832, 0.41129183769226074]
listb [0.33485794067382812, 0.33914685249328613, 0.37850618362426758]
lcsa  [0.27405810356140137, 0.2745978832244873, 0.28249192237854004]
seta  [0.39211201667785645, 0.39234519004821777, 0.39317893981933594]
setb  [0.36988520622253418, 0.37011313438415527, 0.37571001052856445]
1.01034878821 0.85398540833 0.698928091731 1.07106176249 0.905302334456 0.740927452493

n = 5 15 10
lista [0.56792402267456055, 0.57422614097595215, 0.57740211486816406]
listb [0.47309303283691406, 0.47619009017944336, 0.47628307342529297]
lcsa  [0.32805585861206055, 0.32813096046447754, 0.3349759578704834]
seta  [0.40036201477050781, 0.40322518348693848, 0.40548801422119141]
setb  [0.39103078842163086, 0.39722800254821777, 0.43811702728271484]
1.41852623806 1.18166313332 0.819398061028 1.45237674242 1.20986133789 0.838951479847

n = 6 18 12
lista [0.77897095680236816, 0.78187918663024902, 0.78467702865600586]
listb [0.629547119140625, 0.63210701942443848, 0.63321495056152344]
lcsa  [0.36563992500305176, 0.36638498306274414, 0.38175487518310547]
seta  [0.46695613861083984, 0.46992206573486328, 0.47583580017089844]
setb  [0.47616910934448242, 0.47661614418029785, 0.4850609302520752]
1.66818870637 1.34819326075 0.783028414812 1.63591241329 1.32210827369 0.767878297495

n = 7 21 14
lista [0.9703209400177002, 0.9734041690826416, 1.0182771682739258]
listb [0.82394003868103027, 0.82625699043273926, 0.82796716690063477]
lcsa  [0.40975093841552734, 0.41210508346557617, 0.42286920547485352]
seta  [0.5086359977722168, 0.50968098640441895, 0.51014018058776855]
setb  [0.48688101768493652, 0.4879908561706543, 0.49204087257385254]
1.90769222837 1.61990115188 0.805587768483 1.99293236904 1.69228211566 0.841583309951

n = 8 24 16
lista [1.204819917678833, 1.2206029891967773, 1.258256196975708]
listb [1.014998197555542, 1.0206191539764404, 1.0343101024627686]
lcsa  [0.50966787338256836, 0.51018595695495605, 0.51319599151611328]
seta  [0.50310111045837402, 0.50556015968322754, 0.51335406303405762]
setb  [0.51472997665405273, 0.51948785781860352, 0.52113485336303711]
2.39478683834 2.01748351664 1.01305257092 2.34068341135 1.97190418975 0.990165516871

n = 9 27 18
lista [1.511646032333374, 1.5133969783782959, 1.5639569759368896]
listb [1.2461750507354736, 1.254518985748291, 1.2613379955291748]
lcsa  [0.5565330982208252, 0.56119203567504883, 0.56451296806335449]
seta  [0.5966339111328125, 0.60275578498840332, 0.64791703224182129]
setb  [0.54694414138793945, 0.5508568286895752, 0.55375313758850098]
2.53362406013 2.08867620074 0.932788243907 2.76380331728 2.27843203069 1.01753187594

n = 10 30 20
lista [1.7777848243713379, 2.1453688144683838, 2.4085969924926758]
listb [1.5070111751556396, 1.5202279090881348, 1.5779800415039062]
lcsa  [0.5954139232635498, 0.59703707695007324, 0.60746097564697266]
seta  [0.61563014984130859, 0.62125110626220703, 0.62354087829589844]
setb  [0.56723213195800781, 0.57257509231567383, 0.57460403442382812]
2.88774814689 2.44791645689 0.967161734066 3.13413984189 2.6567803378 1.04968299523

Generated using a 2GHz single core machine with 2GB of RAM running Python 2.6.6 on a Debian flavour of Linux (with Firefox running in the background).

These figures are only a rough guide, since the actual speeds of the various algorithms are affected differently by the proportion of elements that are in both source lists.

Asyncio.gather vs asyncio.wait

A very important distinction, which is easy to miss, is the default bheavior of these two functions, when it comes to exceptions.


I'll use this example to simulate a coroutine that will raise exceptions, sometimes -

import asyncio
import random


async def a_flaky_tsk(i):
    await asyncio.sleep(i)  # bit of fuzz to simulate a real-world example

    if i % 2 == 0:
        print(i, "ok")
    else:
        print(i, "crashed!")
        raise ValueError

coros = [a_flaky_tsk(i) for i in range(10)]

await asyncio.gather(*coros) outputs -

0 ok
1 crashed!
Traceback (most recent call last):
  File "/Users/dev/PycharmProjects/trading/xxx.py", line 20, in <module>
    asyncio.run(main())
  File "/Users/dev/.pyenv/versions/3.8.2/lib/python3.8/asyncio/runners.py", line 43, in run
    return loop.run_until_complete(main)
  File "/Users/dev/.pyenv/versions/3.8.2/lib/python3.8/asyncio/base_events.py", line 616, in run_until_complete
    return future.result()
  File "/Users/dev/PycharmProjects/trading/xxx.py", line 17, in main
    await asyncio.gather(*coros)
  File "/Users/dev/PycharmProjects/trading/xxx.py", line 12, in a_flaky_tsk
    raise ValueError
ValueError

As you can see, the coros after index 1 never got to execute.


But await asyncio.wait(coros) continues to execute tasks, even if some of them fail -

0 ok
1 crashed!
2 ok
3 crashed!
4 ok
5 crashed!
6 ok
7 crashed!
8 ok
9 crashed!
Task exception was never retrieved
future: <Task finished name='Task-10' coro=<a_flaky_tsk() done, defined at /Users/dev/PycharmProjects/trading/xxx.py:6> exception=ValueError()>
Traceback (most recent call last):
  File "/Users/dev/PycharmProjects/trading/xxx.py", line 12, in a_flaky_tsk
    raise ValueError
ValueError
Task exception was never retrieved
future: <Task finished name='Task-8' coro=<a_flaky_tsk() done, defined at /Users/dev/PycharmProjects/trading/xxx.py:6> exception=ValueError()>
Traceback (most recent call last):
  File "/Users/dev/PycharmProjects/trading/xxx.py", line 12, in a_flaky_tsk
    raise ValueError
ValueError
Task exception was never retrieved
future: <Task finished name='Task-2' coro=<a_flaky_tsk() done, defined at /Users/dev/PycharmProjects/trading/xxx.py:6> exception=ValueError()>
Traceback (most recent call last):
  File "/Users/dev/PycharmProjects/trading/xxx.py", line 12, in a_flaky_tsk
    raise ValueError
ValueError
Task exception was never retrieved
future: <Task finished name='Task-9' coro=<a_flaky_tsk() done, defined at /Users/dev/PycharmProjects/trading/xxx.py:6> exception=ValueError()>
Traceback (most recent call last):
  File "/Users/dev/PycharmProjects/trading/xxx.py", line 12, in a_flaky_tsk
    raise ValueError
ValueError
Task exception was never retrieved
future: <Task finished name='Task-3' coro=<a_flaky_tsk() done, defined at /Users/dev/PycharmProjects/trading/xxx.py:6> exception=ValueError()>
Traceback (most recent call last):
  File "/Users/dev/PycharmProjects/trading/xxx.py", line 12, in a_flaky_tsk
    raise ValueError
ValueError

Ofcourse, this behavior can be changed for both by using -

asyncio.gather(..., return_exceptions=True)

or,

asyncio.wait([...], return_when=asyncio.FIRST_EXCEPTION)


But it doesn't end here!

Notice: Task exception was never retrieved in the logs above.

asyncio.wait() won't re-raise exceptions from the child tasks until you await them individually. (The stacktrace in the logs are just messages, they cannot be caught!)

done, pending = await asyncio.wait(coros)
for tsk in done:
    try:
        await tsk
    except Exception as e:
        print("I caught:", repr(e))

Output -

0 ok
1 crashed!
2 ok
3 crashed!
4 ok
5 crashed!
6 ok
7 crashed!
8 ok
9 crashed!
I caught: ValueError()
I caught: ValueError()
I caught: ValueError()
I caught: ValueError()
I caught: ValueError()

On the other hand, to catch exceptions with asyncio.gather(), you must -

results = await asyncio.gather(*coros, return_exceptions=True)
for result_or_exc in results:
    if isinstance(result_or_exc, Exception):
        print("I caught:", repr(result_or_exc))

(Same output as before)

Build .NET Core console application to output an EXE

Here's my hacky workaround - generate a console application (.NET Framework) that reads its own name and arguments, and then calls dotnet [nameOfExe].dll [args].

Of course this assumes that .NET is installed on the target machine.

Here's the code. Feel free to copy!

using System;
using System.Diagnostics;
using System.Text;

namespace dotNetLauncher
{
    class Program
    {
        /*
            If you make .NET Core applications, they have to be launched like .NET blah.dll args here
            This is a convenience EXE file that launches .NET Core applications via name.exe
            Just rename the output exe to the name of the .NET Core DLL file you wish to launch
        */
        static void Main(string[] args)
        {
            var exePath = AppDomain.CurrentDomain.BaseDirectory;
            var exeName = AppDomain.CurrentDomain.FriendlyName;
            var assemblyName = exeName.Substring(0, exeName.Length - 4);
            StringBuilder passInArgs = new StringBuilder();
            foreach(var arg in args)
            {
                bool needsSurroundingQuotes = false;
                if (arg.Contains(" ") || arg.Contains("\""))
                {
                    passInArgs.Append("\"");
                    needsSurroundingQuotes = true;
                }
                passInArgs.Append(arg.Replace("\"","\"\""));
                if (needsSurroundingQuotes)
                {
                    passInArgs.Append("\"");
                }

                passInArgs.Append(" ");
            }
            string callingArgs = $"\"{exePath}{assemblyName}.dll\" {passInArgs.ToString().Trim()}";

            var p = new Process
            {
                StartInfo = new ProcessStartInfo("dotnet", callingArgs)
                {
                    UseShellExecute = false
                }
            };

            p.Start();
            p.WaitForExit();
        }
    }
}

C# Double - ToString() formatting with two decimal places but no rounding

I suggest you truncate first, and then format:

double a = 123.4567;
double aTruncated = Math.Truncate(a * 100) / 100;
CultureInfo ci = new CultureInfo("de-DE");
string s = string.Format(ci, "{0:0.00}%", aTruncated);

Use the constant 100 for 2 digits truncate; use a 1 followed by as many zeros as digits after the decimal point you would like. Use the culture name you need to adjust the formatting result.

how to open a page in new tab on button click in asp.net?

Use JavaScript for the main form / Button click event. An example is:

Context.Response.Write("<script language='javascript'>window.open('AccountsStmt.aspx?showledger=" & sledgerGrp & "','_newtab');</script>")

Why doesn't height: 100% work to expand divs to the screen height?

Try to play around also with the calc and overflow functions

.myClassName {
    overflow: auto;
    height: calc(100% - 1.5em);
}

How to update Xcode from command line

Hello I solved it like this:

Install Application> Xcode.app> Contents> Resources> Packages> XcodeSystemResources.pkg.

Set and Get Methods in java?

just because the OOP rule: Data Hiding and Encapsulation. It is a very bad practice to declare a object's as public and change it on the fly in most situations. Also there are many other reasons , but the root is Encapsulation in OOP. and "buy a book or go read on Object Oriented Programming ", you will understand everything on this after you read any book on OOP.

matplotlib error - no module named tkinter

Sometimes (for example in osgeo4w distribution) tkinter is removed.

Try changing matplotlib backend editing matplotlibrc file located in [python install dir]/matplotlib/mpl-data/matplotlibrc changing The backend parameter from backend: TkAgg to something other like backend: Qt4Aggas described here: http://matplotlib.org/faq/usage_faq.html#what-is-a-backend

C# version of java's synchronized keyword?

You can use the lock statement instead. I think this can only replace the second version. Also, remember that both synchronized and lock need to operate on an object.

Default keystore file does not exist?

go to ~/.android if there is no debug.keystore copy it from your project and paste it here then run command again.

How to properly express JPQL "join fetch" with "where" clause as JPA 2 CriteriaQuery?

I will show visually the problem, using the great example from James answer and adding the alternative solution.

When you do the follow query, without the FETCH:

Select e from Employee e 
join e.phones p 
where p.areaCode = '613'

You will have the follow results from Employee as you expected:

EmployeeId EmployeeName PhoneId PhoneAreaCode
1 James 5 613
1 James 6 416

But when you add the FETCH word on JOIN, this is what happens:

EmployeeId EmployeeName PhoneId PhoneAreaCode
1 James 5 613

The generated SQL is the same for the two queries, but the Hibernate removes on memory the 416 register when you use WHERE on the FETCH join.

So, to bring all phones and apply the WHERE correctly, you need to have two JOINs: one for the WHERE and another for the FETCH. Like:

Select e from Employee e 
join e.phones p 
join fetch e.phones      //no alias, to not commit the mistake
where p.areaCode = '613'

Android replace the current fragment with another fragment

Then provided your button is showing and the click event is being fired you can call the following in your click event:

final FragmentTransaction ft = getFragmentManager().beginTransaction(); 
ft.replace(R.id.details, new NewFragmentToReplace(), "NewFragmentTag"); 
ft.commit(); 

and if you want to go back to the DetailsFragment on clicking back ensure you add the above transaction to the back stack, i.e.

ft.addToBackStack(null);

Or am I missing something? Alternatively some people suggest that your activity gets the click event for the button and it has responsibility for replacing the fragments in your details pane.

Mongodb find() query : return only unique values (no duplicates)

I think you can use db.collection.distinct(fields,query)

You will be able to get the distinct values in your case for NetworkID.

It should be something like this :

Db.collection.distinct('NetworkID')

Shell script to delete directories older than n days

I was struggling to get this right using the scripts provided above and some other scripts especially when files and folder names had newline or spaces.

Finally stumbled on tmpreaper and it has been worked pretty well for us so far.

tmpreaper -t 5d ~/Downloads


tmpreaper  --protect '*.c' -t 5h ~/my_prg

Original Source link

Has features like test, which checks the directories recursively and lists them. Ability to delete symlinks, files or directories and also the protection mode for a certain pattern while deleting

How does the "final" keyword in Java work? (I can still modify an object.)

The final keyword indicates that a variable may only be initialized once. In your code you are only performing one initialization of final so the terms are satisfied. This statement performs the lone initialization of foo. Note that final != immutable, it only means that the reference cannot change.

foo = new ArrayList();

When you declare foo as static final the variable must be initialized when the class is loaded and cannot rely on instantiation (aka call to constructor) to initialize foo since static fields must be available without an instance of a class. There is no guarantee that the constructor will have been called prior to using the static field.

When you execute your method under the static final scenario the Test class is loaded prior to instantiating t at this time there is no instantiation of foo meaning it has not been initialized so foo is set to the default for all objects which is null. At this point I assume your code throws a NullPointerException when you attempt to add an item to the list.

Long press on UITableView

Answer in Swift 5 (Continuation of Ricky's answer in Swift)

Add the UIGestureRecognizerDelegate to your ViewController

 override func viewDidLoad() {
    super.viewDidLoad()

    //Long Press
    let longPressGesture = UILongPressGestureRecognizer(target: self, action: #selector(handleLongPress))
    longPressGesture.minimumPressDuration = 0.5
    self.tableView.addGestureRecognizer(longPressGesture)
 }

And the function:

@objc func handleLongPress(longPressGesture: UILongPressGestureRecognizer) {
    let p = longPressGesture.location(in: self.tableView)
    let indexPath = self.tableView.indexPathForRow(at: p)
    if indexPath == nil {
        print("Long press on table view, not row.")
    } else if longPressGesture.state == UIGestureRecognizer.State.began {
        print("Long press on row, at \(indexPath!.row)")
    }
}

git rebase: "error: cannot stat 'file': Permission denied"

I have just had this under Win 7.

$ git stash pop error: cannot stat 'parentFolder/subfolder': Permission denied error: cannot stat 'parentFolder/subfolder': Permission denied

Diagnosis:

1>I went to the subfolder and it's there and I couldn't delete it !

2>Use "process explorer" -> Find -> Find handles and Dlls -> put the "subfolder" name there and search.

Result: It turns out it's XMLSpy has opened one of the xml there, close XML Spy and try stash pop again, it's working now.

Opposite of append in jquery

Opposite up is children(), but opposite in position is prepend(). Here a very good tutorial.

In Perl, how can I concisely check if a $variable is defined and contains a non zero length string?

if ($name )
{
    #since undef and '' both evaluate to false 
    #this should work only when string is defined and non-empty...
    #unless you're expecting someting like $name="0" which is false.
    #notice though that $name="00" is not false
}

How can I remove an element from a list?

Using lapply and grep:

lst <- list(a = 1:4, b = 4:8, c = 8:10)
# say you want to remove a and c
toremove<-c("a","c")
lstnew<-lst[-unlist(lapply(toremove, function(x) grep(x, names(lst)) ) ) ]
#or
pattern<-"a|c"
lstnew<-lst[-grep(pattern, names(lst))]

How do I make a checkbox required on an ASP.NET form?

Non-javascript way . . aspx page:

 <form id="form1" runat="server">
<div>
    <asp:CheckBox ID="CheckBox1" runat="server" />
    <asp:CustomValidator ID="CustomValidator1"
        runat="server" ErrorMessage="CustomValidator" ControlToValidate="CheckBox1"></asp:CustomValidator>
</div>
</form>

Code Behind:

Protected Sub CustomValidator1_ServerValidate(ByVal source As Object, ByVal args As System.Web.UI.WebControls.ServerValidateEventArgs) Handles CustomValidator1.ServerValidate
    If Not CheckBox1.Checked Then
        args.IsValid = False
    End If
End Sub

For any actions you might need (business Rules):

If Page.IsValid Then
   'do logic
End If 

Sorry for the VB code . . . you can convert it to C# if that is your pleasure. The company I am working for right now requires VB :(

Most concise way to test string equality (not object equality) for Ruby strings or symbols?

Your code sample didn't expand on part of your topic, namely symbols, and so that part of the question went unanswered.

If you have two strings, foo and bar, and both can be either a string or a symbol, you can test equality with

foo.to_s == bar.to_s

It's a little more efficient to skip the string conversions on operands with known type. So if foo is always a string

foo == bar.to_s

But the efficiency gain is almost certainly not worth demanding any extra work on behalf of the caller.

Prior to Ruby 2.2, avoid interning uncontrolled input strings for the purpose of comparison (with strings or symbols), because symbols are not garbage collected, and so you can open yourself to denial of service through resource exhaustion. Limit your use of symbols to values you control, i.e. literals in your code, and trusted configuration properties.

Ruby 2.2 introduced garbage collection of symbols.

DBCC CHECKIDENT Sets Identity to 0

Change statement to

  DBCC CHECKIDENT('TableName', RESEED, 1)

This will start from 2 (or 1 when you recreate table), but it will never be 0.

Best solution to protect PHP code without encryption

Obfuscating things can only inconvenience your legitimate, law-abiding customers, while the people who would would rip you off are not your target paying customers anyway. (edited out other thoughts about obfuscation)

Another suggestion for protecting your software: create a business model in which the code is an incomplete part of the value of your offering. For example, sell product licenses along with access to some data you manage on your site, or license the product on a subscription model or with customer support.

Designing a EULA is a legal matter, not a coding matter. You can start by reading some EULA text for products and websites you use. You might find some interesting details!

Creating a proprietary license is is highly flexible, and probably a subject beyond the intended scope of StackOverflow, since it's not strictly about coding.

Some parts of a EULA that come to mind:

  • Limiting your liability if the product has bugs or causes damage.
  • Spelling out how the customer can use their licensed software, for how long, on how many machines, with or without redistribution rights, etc.
  • Giving you rights to audit their site, so you can enforce the licenses.
  • What happens if they violate the EULA, e.g. they lose their privilege to use your software.

You should consult a legal professional to prepare a commercial EULA.

edit: If this project can't justify the expense of a lawyer, check out these resources:

How do I make a <div> move up and down when I'm scrolling the page?

You want to apply the fixed property to the position style of the element.

position: fixed;

What browser are you working with? Not all browsers support the fixed property. Read more about who supports it, who doesn't and some work around here

http://webreflection.blogspot.com/2009/09/css-position-fixed-solution.html

How to implement custom JsonConverter in JSON.NET to deserialize a List of base class objects?

Here's another solution that avoids the use of jObject.CreateReader(), and instead creates a new JsonTextReader (which is the behavior used by the default JsonCreate.Deserialze method:

public abstract class JsonCreationConverter<T> : JsonConverter
{
    protected abstract T Create(Type objectType, JObject jObject);

    public override bool CanConvert(Type objectType)
    {
        return typeof(T).IsAssignableFrom(objectType);
    }

    public override object ReadJson(JsonReader reader, Type objectType, object existingValue, JsonSerializer serializer)
    {
        if (reader.TokenType == JsonToken.Null)
            return null;

        // Load JObject from stream
        JObject jObject = JObject.Load(reader);

        // Create target object based on JObject
        T target = Create(objectType, jObject);

        // Populate the object properties
        StringWriter writer = new StringWriter();
        serializer.Serialize(writer, jObject);
        using (JsonTextReader newReader = new JsonTextReader(new StringReader(writer.ToString())))
        { 
            newReader.Culture = reader.Culture;
            newReader.DateParseHandling = reader.DateParseHandling;
            newReader.DateTimeZoneHandling = reader.DateTimeZoneHandling;
            newReader.FloatParseHandling = reader.FloatParseHandling;
            serializer.Populate(newReader, target);
        }

        return target;
    }

    public override void WriteJson(JsonWriter writer, object value, JsonSerializer serializer)
    {
        serializer.Serialize(writer, value);
    }
}

HTML5 tag for horizontal line break

You can make a div that has the same attributes as the <hr> tag. This way it is fully able to be customized. Here is some sample code:

The HTML:

<h3>This is a header.</h3>
<div class="customHr">.</div>

<p>Here is some sample paragraph text.<br>
This demonstrates what could go below a custom hr.</p>

The CSS:

.customHr {
    width: 95%
    font-size: 1px;
    color: rgba(0, 0, 0, 0);
    line-height: 1px;

    background-color: grey;
    margin-top: -6px;
    margin-bottom: 10px;
}

To see how the project turns out, here is a JSFiddle for the above code: http://jsfiddle.net/SplashHero/qmccsc06/1/

Placeholder in IE9

If you want to do it without using jquery or modenizer you can use the code below:

(function(){

     "use strict";

     //shim for String's trim function..
     function trim(string){
         return string.trim ? string.trim() : string.replace(/^\s+|\s+$/g, "");
     }

     //returns whether the given element has the given class name..
     function hasClassName(element, className){ 
         //refactoring of Prototype's function..
         var elClassName = element.className;
         if(!elClassName)
             return false;
         var regex = new RegExp("(^|\\s)" + className + "(\\s|$)");
         return regex.test(element.className);
     }

     function removeClassName(element, className){
         //refactoring of Prototype's function..
         var elClassName = element.className;
         if(!elClassName)
             return;
         element.className = elClassName.replace(
             new RegExp("(^|\\s+)" + className + "(\\s+|$)"), ' ');
     }

     function addClassName(element, className){
         var elClassName = element.className;
         if(elClassName)
             element.className += " " + className;
         else
             element.className = className;
     }

     //strings to make event attachment x-browser.. 
     var addEvent = document.addEventListener ?
            'addEventListener' : 'attachEvent';
     var eventPrefix = document.addEventListener ? '' : 'on';

     //the class which is added when the placeholder is being used..
     var placeHolderClassName = 'usingPlaceHolder';

     //allows the given textField to use it's placeholder attribute
     //as if it's functionality is supported natively..
     window.placeHolder = function(textField){

         //don't do anything if you get it for free..
         if('placeholder' in document.createElement('input'))
             return;

         //don't do anything if the place holder attribute is not
         //defined or is blank..
         var placeHolder = textField.getAttribute('placeholder');        
         if(!placeHolder)
             return;

         //if it's just the empty string do nothing..
         placeHolder = trim(placeHolder);
         if(placeHolder === '')
             return;

         //called on blur - sets the value to the place holder if it's empty..
         var onBlur = function(){
             if(textField.value !== '') //a space is a valid input..
                 return;
             textField.value = placeHolder;
             addClassName(textField, placeHolderClassName);
         };

         //the blur event..
         textField[addEvent](eventPrefix + 'blur', onBlur, false);

         //the focus event - removes the place holder if required..
         textField[addEvent](eventPrefix + 'focus', function(){
             if(hasClassName(textField, placeHolderClassName)){
                removeClassName(textField, placeHolderClassName);
                textField.value = "";
             }
         }, false);

         //the submit event on the form to which it's associated - if the
         //placeholder is attached set the value to be empty..
         var form = textField.form;
         if(form){
             form[addEvent](eventPrefix + 'submit', function(){
                 if(hasClassName(textField, placeHolderClassName))
                     textField.value = '';
            }, false);
         }

         onBlur(); //call the onBlur to set it initially..
    };

}());

For each text field you want to use it for you need to run placeHolder(HTMLInputElement), but I guess you can just change that to suit! Also, doing it this way, rather than just on load means that you can make it work for inputs which aren't in the DOM when the page loads.

Note, that this works by applying the class: usingPlaceHolder to the input element, so you can use this to style it (e.g. add the rule .usingPlaceHolder { color: #999; font-style: italic; } to make it look better).

Change value of input and submit form in JavaScript

My problem turned out to be that I was assigning as document.getElementById("myinput").Value = '1';

Notice the capital V in Value? Once I changed it to small case, i.e., value, the data started posting. Odd as it was not giving any JavaScript errors either.

How to use default Android drawables

To use the default android drawable resource, no need copy anything.. you can just import it first with..

import android.R;

but i will make your own resources will have an error if you want to use it. The error will be something like:

R. cannot be resolved

So, I prefer not to import android.R but import *my.own.package*.R;

then when I can normally use my own resource with R.drawable.*something* without error, and put android.R.*something_default* to use the default android resources.

When to use CouchDB over MongoDB and vice versa

The answers above all over complicate the story.

  1. If you plan to have a mobile component, or need desktop users to work offline and then sync their work to a server you need CouchDB.
  2. If your code will run only on the server then go with MongoDB

That's it. Unless you need CouchDB's (awesome) ability to replicate to mobile and desktop devices, MongoDB has the performance, community and tooling advantage at present.

Convert String to Float in Swift

In swift 4

let Totalname = "10.0" //Now it is in string

let floatVal  = (Totalname as NSString).floatValue //Now converted to float

Netbeans how to set command line arguments in Java

  1. Create the Java code that can receive an argument as a command line argument.

    class TestCode{
        public static void main(String args[]){
            System.out.println("first argument is: "+args[0]);
        }
    }
    
  2. Run the program without arguments (press F6).

  3. In the Output window, at the bottom, click the double yellow arrow (or the yellow button) to open a Run dialog.

  4. If the argument you need to pass is testArgument, then here in this window pass the argument as application.args=testArgument.

This will give the output as follows in the same Output window:

first argument is: testArgument

For Maven, the instructions are similar, but change the exec.args property instead:

exec.args=-classpath %classpath package.ClassName PARAM1 PARAM2 PARAM3

Note: Use single quotes for string parameters that contain spaces.

Sending email in .NET through Gmail

Be sure to use System.Net.Mail, not the deprecated System.Web.Mail. Doing SSL with System.Web.Mail is a gross mess of hacky extensions.

using System.Net;
using System.Net.Mail;

var fromAddress = new MailAddress("[email protected]", "From Name");
var toAddress = new MailAddress("[email protected]", "To Name");
const string fromPassword = "fromPassword";
const string subject = "Subject";
const string body = "Body";

var smtp = new SmtpClient
{
    Host = "smtp.gmail.com",
    Port = 587,
    EnableSsl = true,
    DeliveryMethod = SmtpDeliveryMethod.Network,
    UseDefaultCredentials = false,
    Credentials = new NetworkCredential(fromAddress.Address, fromPassword)
};
using (var message = new MailMessage(fromAddress, toAddress)
{
    Subject = subject,
    Body = body
})
{
    smtp.Send(message);
}

Create a custom event in Java

There are 3 different ways you may wish to set this up:

  1. Thrower inside of Catcher
  2. Catcher inside of Thrower
  3. Thrower and Catcher inside of another class in this example Test

THE WORKING GITHUB EXAMPLE I AM CITING Defaults to Option 3, to try the others simply uncomment the "Optional" code block of the class you want to be main, and set that class as the ${Main-Class} variable in the build.xml file:

4 Things needed on throwing side code:

import java.util.*;//import of java.util.event

//Declaration of the event's interface type, OR import of the interface,
//OR declared somewhere else in the package
interface ThrowListener {
    public void Catch();
}
/*_____________________________________________________________*/class Thrower {
//list of catchers & corresponding function to add/remove them in the list
    List<ThrowListener> listeners = new ArrayList<ThrowListener>();
    public void addThrowListener(ThrowListener toAdd){ listeners.add(toAdd); }
    //Set of functions that Throw Events.
        public void Throw(){ for (ThrowListener hl : listeners) hl.Catch();
            System.out.println("Something thrown");
        }
////Optional: 2 things to send events to a class that is a member of the current class
. . . go to github link to see this code . . .
}

2 Things needed in a class file to receive events from a class

/*_______________________________________________________________*/class Catcher
implements ThrowListener {//implement added to class
//Set of @Override functions that Catch Events
    @Override public void Catch() {
        System.out.println("I caught something!!");
    }
////Optional: 2 things to receive events from a class that is a member of the current class
. . . go to github link to see this code . . .
}

How to extract table as text from the PDF using Python?

  • I would suggest you to extract the table using tabula.
  • Pass your pdf as an argument to the tabula api and it will return you the table in the form of dataframe.
  • Each table in your pdf is returned as one dataframe.
  • The table will be returned in a list of dataframea, for working with dataframe you need pandas.

This is my code for extracting pdf.

import pandas as pd
import tabula
file = "filename.pdf"
path = 'enter your directory path here'  + file
df = tabula.read_pdf(path, pages = '1', multiple_tables = True)
print(df)

Please refer to this repo of mine for more details.

How do I specify "not equals to" when comparing strings in an XSLT <xsl:if>?

If you want to compare to a string literal you need to put it in (single) quotes:

<xsl:if test="Count != 'N/A'">

LINQ to SQL - How to select specific columns and return strongly typed list

Make a call to the DB searching with myid (Id of the row) and get back specific columns:

var columns = db.Notifications
                .Where(x => x.Id == myid)
                .Select(n => new { n.NotificationTitle, 
                                   n.NotificationDescription, 
                                   n.NotificationOrder });

Jenkins returned status code 128 with github

I changed the permission of my .ssh/id_rsa (private key) to 604. chmod 700 id_rsa

How to get a variable from a file to another file in Node.js

File FileOne.js:

module.exports = { ClientIDUnsplash : 'SuperSecretKey' };

File FileTwo.js:

var { ClientIDUnsplash } = require('./FileOne');

This example works best for React.

How can I count the number of matches for a regex?

This should work for matches that might overlap:

public static void main(String[] args) {
    String input = "aaaaaaaa";
    String regex = "aa";
    Pattern pattern = Pattern.compile(regex);
    Matcher matcher = pattern.matcher(input);
    int from = 0;
    int count = 0;
    while(matcher.find(from)) {
        count++;
        from = matcher.start() + 1;
    }
    System.out.println(count);
}

Printing Batch file results to a text file

Have you tried moving DEL %FILE%.txt% to after @echo %FILE% deleted. >> results.txt so that it looks like this?

@echo %FILE% deleted. >> results.txt
DEL %FILE%.txt

Java file path in Linux

Looks like you are missing a leading slash. Perhaps try:

Scanner s = new Scanner(new File("/home/me/java/ex.txt"));

(as to where it looks for files by default, it is where the JVM is run from for relative paths like the one you have in your question)

Ignore 'Security Warning' running script from command line

For those who want to access a file from an already loaded PowerShell session, either use Unblock-File to mark the file as safe (though you already need to have set a relaxed execution policy like Unrestricted for this to work), or change the execution policy just for the current PowerShell session:

Set-ExecutionPolicy -ExecutionPolicy Bypass -Scope Process

Sort a list of lists with a custom compare function

>>> l = [list(range(i, i+4)) for i in range(10,1,-1)]
>>> l
[[10, 11, 12, 13], [9, 10, 11, 12], [8, 9, 10, 11], [7, 8, 9, 10], [6, 7, 8, 9], [5, 6, 7, 8], [4, 5, 6, 7], [3, 4, 5, 6], [2, 3, 4, 5]]
>>> sorted(l, key=sum)
[[2, 3, 4, 5], [3, 4, 5, 6], [4, 5, 6, 7], [5, 6, 7, 8], [6, 7, 8, 9], [7, 8, 9, 10], [8, 9, 10, 11], [9, 10, 11, 12], [10, 11, 12, 13]]

The above works. Are you doing something different?

Notice that your key function is just sum; there's no need to write it explicitly.

How to open Atom editor from command line in OS X?

I had the same issue which I resolved by first moving Atom.app from downloads to Applications. Then under Atom's menu options, I selected "Install Shell Commands".

"A lambda expression with a statement body cannot be converted to an expression tree"

Is Arr a base type of Obj? Does the Obj class exist? Your code would work only if Arr is a base type of Obj. You can try this instead:

Obj[] myArray = objects.Select(o =>
{
    var someLocalVar = o.someVar;

    return new Obj() 
    { 
       Var1 = someLocalVar,
       Var2 = o.var2 
    };
}).ToArray();

How to make image hover in css?

Here are some easy to folow steps and a great on hover tutorial its the examples that you can "play" with and test live.

http://fivera.net/simple-cool-live-examples-image-hover-css-effect/

c - warning: implicit declaration of function ‘printf’

the warning or error of kind IMPLICIT DECLARATION is that the compiler is expecting a Function Declaration/Prototype..

It might either be a header file or your own function Declaration..

A potentially dangerous Request.Form value was detected from the client

If you're using framework 4.0 then the entry in the web.config (<pages validateRequest="false" />)

<configuration>
    <system.web>
        <pages validateRequest="false" />
    </system.web>
</configuration>

If you're using framework 4.5 then the entry in the web.config (requestValidationMode="2.0")

<system.web>
    <compilation debug="true" targetFramework="4.5" />
    <httpRuntime targetFramework="4.5" requestValidationMode="2.0"/>
</system.web>

If you want for only single page then, In you aspx file you should put the first line as this :

<%@ Page EnableEventValidation="false" %>

if you already have something like <%@ Page so just add the rest => EnableEventValidation="false" %>

I recommend not to do it.

Identify duplicate values in a list in Python

It looks like you want the indices of the duplicates. Here is some short code that will find those in O(n) time, without using any packages:

dups = {}
[dups.setdefault(v, []).append(i) for i, v in enumerate(mylist)]
dups = {k: v for k, v in dups.items() if len(v) > 1}
# dups now has keys for all the duplicate values
# and a list of matching indices for each

# The second line produces an unused list. 
# It could be replaced with this:
for i, v in enumerate(mylist):
    dups.setdefault(v, []).append(i)

How to use JavaScript source maps (.map files)?

The .map files are for js and css (and now ts too) files that have been minified. They are called SourceMaps. When you minify a file, like the angular.js file, it takes thousands of lines of pretty code and turns it into only a few lines of ugly code. Hopefully, when you are shipping your code to production, you are using the minified code instead of the full, unminified version. When your app is in production, and has an error, the sourcemap will help take your ugly file, and will allow you to see the original version of the code. If you didn't have the sourcemap, then any error would seem cryptic at best.

Same for CSS files. Once you take a SASS or LESS file and compile it to CSS, it looks nothing like its original form. If you enable sourcemaps, then you can see the original state of the file, instead of the modified state.

So, to answer you questions in order:

  • What is it for? To de-reference uglified code
  • How can a developer use it? You use it for debugging a production app. In development mode you can use the full version of Angular. In production, you would use the minified version.
  • Should I care about creating a js.map file? If you care about being able to debug production code easier, then yes, you should do it.
  • How does it get created? It is created at build time. There are build tools that can build your .map file for you as it does other files. https://github.com/gruntjs/grunt-contrib-uglify/issues/71

I hope this makes sense.

Xcode 12, building for iOS Simulator, but linking in object file built for iOS, for architecture arm64

I solve problem by adding "arm64" in "Excluded Architectures" for both project target and pod target.

Xcode -> Target Project -> Build Setting -> Excluded Architectures > "arm64"

Xcode -> Pod Target -> Build Setting -> Excluded Architectures > "arm64"

Disable single warning error

Instead of putting it on top of the file (or even a header file), just wrap the code in question with #pragma warning (push), #pragma warning (disable) and a matching #pragma warning (pop), as shown here.

Although there are some other options, including #pramga warning (once).

Is div inside list allowed?

I see you would want to do this if you wanted to make, say, the whole box of a menu item clickable. I used to insert an 'li' tag in 'a' tags to do this but this seems more valid.

C split a char array into different variables

One option is strtok

example:

char name[20];
//pretend name is set to the value "My name"

You want to split it at the space between the two words

split=strtok(name," ");

while(split != NULL)
{
    word=split;
    split=strtok(NULL," ");
}

What's the difference between deadlock and livelock?

Maybe these two examples illustrate you the difference between a deadlock and a livelock:


Java-Example for a deadlock:

import java.util.concurrent.locks.Lock;
import java.util.concurrent.locks.ReentrantLock;

public class DeadlockSample {

    private static final Lock lock1 = new ReentrantLock(true);
    private static final Lock lock2 = new ReentrantLock(true);

    public static void main(String[] args) {
        Thread threadA = new Thread(DeadlockSample::doA,"Thread A");
        Thread threadB = new Thread(DeadlockSample::doB,"Thread B");
        threadA.start();
        threadB.start();
    }

    public static void doA() {
        System.out.println(Thread.currentThread().getName() + " : waits for lock 1");
        lock1.lock();
        System.out.println(Thread.currentThread().getName() + " : holds lock 1");

        try {
            System.out.println(Thread.currentThread().getName() + " : waits for lock 2");
            lock2.lock();
            System.out.println(Thread.currentThread().getName() + " : holds lock 2");

            try {
                System.out.println(Thread.currentThread().getName() + " : critical section of doA()");
            } finally {
                lock2.unlock();
                System.out.println(Thread.currentThread().getName() + " : does not hold lock 2 any longer");
            }
        } finally {
            lock1.unlock();
            System.out.println(Thread.currentThread().getName() + " : does not hold lock 1 any longer");
        }
    }

    public static void doB() {
        System.out.println(Thread.currentThread().getName() + " : waits for lock 2");
        lock2.lock();
        System.out.println(Thread.currentThread().getName() + " : holds lock 2");

        try {
            System.out.println(Thread.currentThread().getName() + " : waits for lock 1");
            lock1.lock();
            System.out.println(Thread.currentThread().getName() + " : holds lock 1");

            try {
                System.out.println(Thread.currentThread().getName() + " : critical section of doB()");
            } finally {
                lock1.unlock();
                System.out.println(Thread.currentThread().getName() + " : does not hold lock 1 any longer");
            }
        } finally {
            lock2.unlock();
            System.out.println(Thread.currentThread().getName() + " : does not hold lock 2 any longer");
        }
    }
}

Sample output:

Thread A : waits for lock 1
Thread B : waits for lock 2
Thread A : holds lock 1
Thread B : holds lock 2
Thread B : waits for lock 1
Thread A : waits for lock 2

Java-Example for a livelock:


import java.util.concurrent.locks.Lock;
import java.util.concurrent.locks.ReentrantLock;

public class LivelockSample {

    private static final Lock lock1 = new ReentrantLock(true);
    private static final Lock lock2 = new ReentrantLock(true);

    public static void main(String[] args) {
        Thread threadA = new Thread(LivelockSample::doA, "Thread A");
        Thread threadB = new Thread(LivelockSample::doB, "Thread B");
        threadA.start();
        threadB.start();
    }

    public static void doA() {
        try {
            while (!lock1.tryLock()) {
                System.out.println(Thread.currentThread().getName() + " : waits for lock 1");
                Thread.sleep(100);
            }
            System.out.println(Thread.currentThread().getName() + " : holds lock 1");

            try {
                while (!lock2.tryLock()) {
                    System.out.println(Thread.currentThread().getName() + " : waits for lock 2");
                    Thread.sleep(100);
                }
                System.out.println(Thread.currentThread().getName() + " : holds lock 2");

                try {
                    System.out.println(Thread.currentThread().getName() + " : critical section of doA()");
                } finally {
                    lock2.unlock();
                    System.out.println(Thread.currentThread().getName() + " : does not hold lock 2 any longer");
                }
            } finally {
                lock1.unlock();
                System.out.println(Thread.currentThread().getName() + " : does not hold lock 1 any longer");
            }
        } catch (InterruptedException e) {
            // can be ignored here for this sample
        }
    }

    public static void doB() {
        try {
            while (!lock2.tryLock()) {
                System.out.println(Thread.currentThread().getName() + " : waits for lock 2");
                Thread.sleep(100);
            }
            System.out.println(Thread.currentThread().getName() + " : holds lock 2");

            try {
                while (!lock1.tryLock()) {
                    System.out.println(Thread.currentThread().getName() + " : waits for lock 1");
                    Thread.sleep(100);
                }
                System.out.println(Thread.currentThread().getName() + " : holds lock 1");

                try {
                    System.out.println(Thread.currentThread().getName() + " : critical section of doB()");
                } finally {
                    lock1.unlock();
                    System.out.println(Thread.currentThread().getName() + " : does not hold lock 1 any longer");
                }
            } finally {
                lock2.unlock();
                System.out.println(Thread.currentThread().getName() + " : does not hold lock 2 any longer");
            }
        } catch (InterruptedException e) {
            // can be ignored here for this sample
        }
    }
}

Sample output:

Thread B : holds lock 2
Thread A : holds lock 1
Thread A : waits for lock 2
Thread B : waits for lock 1
Thread B : waits for lock 1
Thread A : waits for lock 2
Thread A : waits for lock 2
Thread B : waits for lock 1
Thread B : waits for lock 1
Thread A : waits for lock 2
Thread A : waits for lock 2
Thread B : waits for lock 1
...

Both examples force the threads to aquire the locks in different orders. While the deadlock waits for the other lock, the livelock does not really wait - it desperately tries to acquire the lock without the chance of getting it. Every try consumes CPU cycles.

Select * from subquery

You can select every column from that sub-query by aliasing it and adding the alias before the *:

SELECT t.*, a+b AS total_sum
FROM
(
   SELECT SUM(column1) AS a, SUM(column2) AS b
   FROM table
) t

How to turn off page breaks in Google Docs?

If You want to REMOVE page break from document

use Edit / Find-Replace \f with regex

If You want to TURN OFF (as You asked)

uncheck "Print Layout" from the "View" menu, but dotted lines will remain indicating page breaks

What is the best way to get the count/length/size of an iterator?

There is no more efficient way, if all you have is the iterator. And if the iterator can only be used once, then getting the count before you get the iterator's contents is ... problematic.

The solution is either to change your application so that it doesn't need the count, or to obtain the count by some other means. (For example, pass a Collection rather than Iterator ...)

Can a java file have more than one class?

There can only be one public class top level class in a file. The class name of that public class should be the name of the file. It can have many public inner classes.

You can have many classes in a single file. The limits for various levels of class visibility in a file are as follows:

Top level classes:
1 public class
0 private class
any number of default/protected classes

Inner classes:
any number of inner classes with any visibility (default, private, protected, public)

Please correct me if I am wrong.

Background thread with QThread in PyQt

PySide2 Solution:

Unlike in PyQt5, in PySide2 the QThread.started signal is received/handled on the original thread, not the worker thread! Luckily it still receives all other signals on the worker thread.

In order to match PyQt5's behavior, you have to create the started signal yourself.

Here is an easy solution:

# Use this class instead of QThread
class QThread2(QThread):
    # Use this signal instead of "started"
    started2 = Signal()

    def __init__(self):
        QThread.__init__(self)
        self.started.connect(self.onStarted)

    def onStarted(self):
        self.started2.emit()

Is it possible to refresh a single UITableViewCell in a UITableView?

If you are using custom TableViewCells, the generic

[self.tableView reloadData];    

does not effectively answer this question unless you leave the current view and come back. Neither does the first answer.

To successfully reload your first table view cell without switching views, use the following code:

//For iOS 5 and later
- (void)reloadTopCell {
    NSIndexPath *indexPath = [NSIndexPath indexPathForRow:0 inSection:0];
    NSArray *indexPaths = [[NSArray alloc] initWithObjects:indexPath, nil];
    [self.tableView reloadRowsAtIndexPaths:indexPaths withRowAnimation:UITableViewRowAnimationNone];
}

Insert the following refresh method which calls to the above method so you can custom reload only the top cell (or the entire table view if you wish):

- (void)refresh:(UIRefreshControl *)refreshControl {
    //call to the method which will perform the function
    [self reloadTopCell];

    //finish refreshing 
    [refreshControl endRefreshing];
}

Now that you have that sorted, inside of your viewDidLoad add the following:

//refresh table view
UIRefreshControl *refreshControl = [[UIRefreshControl alloc] init];

[refreshControl addTarget:self action:@selector(refresh:) forControlEvents:UIControlEventValueChanged];

[self.tableView addSubview:refreshControl];

You now have a custom refresh table feature that will reload the top cell. To reload the entire table, add the

[self.tableView reloadData]; to your new refresh method.

If you wish to reload the data every time you switch views, implement the method:

//ensure that it reloads the table view data when switching to this view
- (void) viewWillAppear:(BOOL)animated {
    [self.tableView reloadData];
}

Collision Detection between two images in Java

I think your problem is that you are not using good OO design for your player and enemies. Create two classes:

public class Player
{
    int X;
    int Y;
    int Width;
    int Height;

    // Getters and Setters
}

public class Enemy
{
    int X;
    int Y;
    int Width;
    int Height;

    // Getters and Setters
}

Your Player should have X,Y,Width,and Height variables.

Your enemies should as well.

In your game loop, do something like this (C#):

foreach (Enemy e in EnemyCollection)
{
    Rectangle r = new Rectangle(e.X,e.Y,e.Width,e.Height);
    Rectangle p = new Rectangle(player.X,player.Y,player.Width,player.Height);

    // Assuming there is an intersect method, otherwise just handcompare the values
    if (r.Intersects(p))
    {
       // A Collision!
       // we know which enemy (e), so we can call e.DoCollision();
       e.DoCollision();
    }
}

To speed things up, don't bother checking if the enemies coords are offscreen.

What does the @Valid annotation indicate in Spring?

Just adding to the above answer, In a web application @valid is used where the bean to be validated is also annotated with validation annotations e.g. @NotNull, @Email(hibernate annotation) so when while getting input from user the values can be validated and binding result will have the validation results. bindingResult.hasErrors() will tell if any validation failed.

Validating URL in Java

Are you sure you're using the correct proxy as system properties?

Also if you are using 1.5 or 1.6 you could pass a java.net.Proxy instance to the openConnection() method. This is more elegant imo:

//Proxy instance, proxy ip = 10.0.0.1 with port 8080
Proxy proxy = new Proxy(Proxy.Type.HTTP, new InetSocketAddress("10.0.0.1", 8080));
conn = new URL(urlString).openConnection(proxy);

Navigation Controller Push View Controller

If you are using Swift:

let controller = self.storyboard!.instantiateViewControllerWithIdentifier("controllerID")
self.navigationController!.pushViewController(controller, animated: true)

Implode an array with JavaScript?

Array.join is what you need, but if you like, the friendly people at phpjs.org have created implode for you.

Then some slightly off topic ranting. As @jon_darkstar alreadt pointed out, jQuery is JavaScript and not vice versa. You don't need to know JavaScript to be able to understand how to use jQuery, but it certainly doesn't hurt and once you begin to appreciate reusability or start looking at the bigger picture you absolutely need to learn it.

Call a VBA Function into a Sub Procedure

Calling a Sub Procedure – 3 Way technique

Once you have a procedure, whether you created it or it is part of the Visual Basic language, you can use it. Using a procedure is also referred to as calling it.

Before calling a procedure, you should first locate the section of code in which you want to use it. To call a simple procedure, type its name. Here is an example:

Sub CreateCustomer()
    Dim strFullName As String

    strFullName = "Paul Bertrand Yamaguchi"

msgbox strFullName
End Sub

Sub Exercise()
    CreateCustomer
End Sub

Besides using the name of a procedure to call it, you can also precede it with the Call keyword. Here is an example:

Sub CreateCustomer()
    Dim strFullName As String

    strFullName = "Paul Bertrand Yamaguchi"
End Sub

Sub Exercise()
    Call CreateCustomer
End Sub

When calling a procedure, without or without the Call keyword, you can optionally type an opening and a closing parentheses on the right side of its name. Here is an example:

Sub CreateCustomer()
    Dim strFullName As String

    strFullName = "Paul Bertrand Yamaguchi"
End Sub

Sub Exercise()
    CreateCustomer()
End Sub

Procedures and Access Levels

Like a variable access, the access to a procedure can be controlled by an access level. A procedure can be made private or public. To specify the access level of a procedure, precede it with the Private or the Public keyword. Here is an example:

Private Sub CreateCustomer()
    Dim strFullName As String

    strFullName = "Paul Bertrand Yamaguchi"
End Sub

The rules that were applied to global variables are the same:

Private: If a procedure is made private, it can be called by other procedures of the same module. Procedures of outside modules cannot access such a procedure.

Also, when a procedure is private, its name does not appear in the Macros dialog box

Public: A procedure created as public can be called by procedures of the same module and by procedures of other modules.

Also, if a procedure was created as public, when you access the Macros dialog box, its name appears and you can run it from there

How to animate the change of image in an UIImageView?

Why not try this.

NSArray *animationFrames = [NSArray arrayWithObjects:
  [UIImage imageWithName:@"image1.png"],
  [UIImage imageWithName:@"image2.png"], 
  nil];

UIImageView *animatedImageView = [[UIImageView alloc] init];
animatedImageView.animationImages = animationsFrame;
[animatedImageView setAnimationRepeatCount:1];
[animatedImageView startAnimating];

A swift version:

let animationsFrames = [UIImage(named: "image1.png"), UIImage(named: "image2.png")]
let animatedImageView = UIImageView()
animatedImageView.animationImages = animationsFrames
animatedImageView.animationRepeatCount = 1
animatedImageView.startAnimating()

An explicit value for the identity column in table can only be specified when a column list is used and IDENTITY_INSERT is ON SQL Server

SET IDENTITY_INSERT tableA ON

INSERT Into tableA ([id], [c2], [c3], [c4], [c5] ) 
SELECT [id], [c2], [c3], [c4], [c5] FROM tableB

Not like this

INSERT INTO tableA
SELECT * FROM tableB

SET IDENTITY_INSERT tableA OFF

Error: Cannot invoke an expression whose type lacks a call signature

Add a type to your variable and then return.

Eg:

const myVariable : string [] = ['hello', 'there'];

const result = myVaraible.map(x=> {
  return
  {
    x.id
  }
});

=> Important part is adding the string[] type etc:

Convert a row of a data frame to vector

If you don't want to change to numeric you can try this.

> as.vector(t(df)[,1])
[1] 1.0 2.0 2.6

Import / Export database with SQL Server Server Management Studio

for Microsoft SQL Server Management Studio 2012,2008.. First Copy your database file .mdf and log file .ldf & Paste in your sql server install file in Programs Files->Microsoft SQL Server->MSSQL10.SQLEXPRESS->MSSQL->DATA. Then open Microsoft Sql Server . Right Click on Databases -> Select Attach...option.

Reading a text file and splitting it into single words in python

As supplementary, if you are reading a vvvvery large file, and you don't want read all of the content into memory at once, you might consider using a buffer, then return each word by yield:

def read_words(inputfile):
    with open(inputfile, 'r') as f:
        while True:
            buf = f.read(10240)
            if not buf:
                break

            # make sure we end on a space (word boundary)
            while not str.isspace(buf[-1]):
                ch = f.read(1)
                if not ch:
                    break
                buf += ch

            words = buf.split()
            for word in words:
                yield word
        yield '' #handle the scene that the file is empty

if __name__ == "__main__":
    for word in read_words('./very_large_file.txt'):
        process(word)

LEFT INNER JOIN vs. LEFT OUTER JOIN - Why does the OUTER take longer?

The fact that the same number of rows is returned is an after fact, the query optimizer cannot know in advance that every row in Accepts has a matching row in Marker, can it?

If you join two tables A and B, say A has 1 million rows and B has 1 row. If you say A LEFT INNER JOIN B it means only rows that match both A and B can result, so the query plan is free to scan B first, then use an index to do a range scan in A, and perhaps return 10 rows. But if you say A LEFT OUTER JOIN B then at least all rows in A have to be returned, so the plan must scan everything in A no matter what it finds in B. By using an OUTER join you are eliminating one possible optimization.

If you do know that every row in Accepts will have a match in Marker, then why not declare a foreign key to enforce this? The optimizer will see the constraint, and if is trusted, will take it into account in the plan.

jQuery UI " $("#datepicker").datepicker is not a function"

I just had this issue, and moving the JS references and code towards the bottom of the page before the </body> tag fixed it for me.

How to convert uint8 Array to base64 Encoded String?

Use the following to convert uint8 array to base64 encoded string

function arrayBufferToBase64(buffer) {
            var binary = '';
            var bytes = [].slice.call(new Uint8Array(buffer));
            bytes.forEach((b) => binary += String.fromCharCode(b));
            return window.btoa(binary);
        };

How do I create ColorStateList programmatically?

Unfortunately none of the solutions works for me.

  1. If you don't set pressed state at first it won't detect it.
  2. If you set it, then you need to define empty state to add default color
ColorStateList themeColorStateList = new ColorStateList(
        new int[][]{
                new int[]{android.R.attr.state_pressed},
                new int[]{android.R.attr.state_enabled},
                new int[]{android.R.attr.state_focused, android.R.attr.state_pressed},
                new int[]{-android.R.attr.state_enabled},
                new int[]{} // this should be empty to make default color as we want
        },
        new int[]{
                pressedFontColor,
                defaultFontColor,
                pressedFontColor,
                disabledFontColor,
                defaultFontColor
        }
);

This is constructor from source code:

/**
 * Creates a ColorStateList that returns the specified mapping from
 * states to colors.
 */
public ColorStateList(int[][] states, int[] colors) {
    mStateSpecs = states;
    mColors = colors;

    if (states.length > 0) {
        mDefaultColor = colors[0];

        for (int i = 0; i < states.length; i++) {
            if (states[i].length == 0) {
                mDefaultColor = colors[i];
            }
        }
    }
}

How to create Haar Cascade (.xml file) to use in OpenCV?

How to create CascadeClassifier :

  1. Open this link : https://github.com/opencv/opencv/tree/master/data/haarcascades
  2. Right click on where you find "haarcascade_frontalface_default.xml"
  3. Click on "Save link as"
  4. Save it into the same folder in which your file is.
  5. Include this line in your file face_cascade = cv2.CascadeClassifier(cv2.data.haarcascades + "haarcascade_frontalface_default.xml")

What was the strangest coding standard rule that you were forced to follow?

In a large group at my company, we use C++ almost exclusively. Passing by non-const reference is forbidden.

If you want to modify a parameter to a function, you must pass it by pointer.

We have an internal flame war over the pros (easier to identify function calls that can modify variables) and cons (ridiculousness; having to deal with possible NULL pointers when you want a parameter to be required) about once a year.

Java: splitting the filename into a base and extension

I know others have mentioned String.split, but here is a variant that only yields two tokens (the base and the extension):

String[] tokens = fileName.split("\\.(?=[^\\.]+$)");

For example:

"test.cool.awesome.txt".split("\\.(?=[^\\.]+$)");

Yields:

["test.cool.awesome", "txt"]

The regular expression tells Java to split on any period that is followed by any number of non-periods, followed by the end of input. There is only one period that matches this definition (namely, the last period).

Technically Regexically speaking, this technique is called zero-width positive lookahead.


BTW, if you want to split a path and get the full filename including but not limited to the dot extension, using a path with forward slashes,

    String[] tokens = dir.split(".+?/(?=[^/]+$)");

For example:

    String dir = "/foo/bar/bam/boozled"; 
    String[] tokens = dir.split(".+?/(?=[^/]+$)");
    // [ "/foo/bar/bam/" "boozled" ] 

What is the difference between atomic / volatile / synchronized?

A volatile + synchronization is a fool proof solution for an operation(statement) to be fully atomic which includes multiple instructions to the CPU.

Say for eg:volatile int i = 2; i++, which is nothing but i = i + 1; which makes i as the value 3 in the memory after the execution of this statement. This includes reading the existing value from memory for i(which is 2), load into the CPU accumulator register and do with the calculation by increment the existing value with one(2 + 1 = 3 in accumulator) and then write back that incremented value back to the memory. These operations are not atomic enough though the value is of i is volatile. i being volatile guarantees only that a SINGLE read/write from memory is atomic and not with MULTIPLE. Hence, we need to have synchronized also around i++ to keep it to be fool proof atomic statement. Remember the fact that a statement includes multiple statements.

Hope the explanation is clear enough.

Error: could not find function ... in R

If this occurs while you check your package (R CMD check), take a look at your NAMESPACE.

You can solve this by adding the following statement to the NAMESPACE:

exportPattern("^[^\\\\.]")

This exports everything that doesn't start with a dot ("."). This allows you to have your hidden functions, starting with a dot:

.myHiddenFunction <- function(x) cat("my hidden function")

Java associative-array

Java doesn't have associative arrays, the closest thing you can get is the Map interface

Here's a sample from that page.

import java.util.*;

public class Freq {
    public static void main(String[] args) {
        Map<String, Integer> m = new HashMap<String, Integer>();

        // Initialize frequency table from command line
        for (String a : args) {
            Integer freq = m.get(a);
            m.put(a, (freq == null) ? 1 : freq + 1);
        }

        System.out.println(m.size() + " distinct words:");
        System.out.println(m);
    }
}

If run with:

java Freq if it is to be it is up to me to delegate

You'll get:

8 distinct words:
{to=3, delegate=1, be=1, it=2, up=1, if=1, me=1, is=2}

Is there a WebSocket client implemented for Python?

web2py has comet_messaging.py, which uses Tornado for websockets look at an example here: http://vimeo.com/18399381 and here vimeo . com / 18232653

Regex Email validation

I think @"^([\w\.\-]+)@([\w\-]+)((\.(\w){2,3})+)$" should work.
You need to write it like

string email = txtemail.Text;
Regex regex = new Regex(@"^([\w\.\-]+)@([\w\-]+)((\.(\w){2,3})+)$");
Match match = regex.Match(email);
if (match.Success)
    Response.Write(email + " is correct");
else
    Response.Write(email + " is incorrect");

Be warned that this will fail if:

  1. There is a subdomain after the @ symbol.

  2. You use a TLD with a length greater than 3, such as .info

utf-8 special characters not displaying

If all the other answers didn't work for you, try disabling HTTP input encoding translation.

This is a setting related to PHP extension mbstring. This was the problem in my case. This setting was enabled by default in my server.

How to customize message box

MessageBox::Show uses function from user32.dll, and its style is dependent on Windows, so you cannot change it like that, you have to create your own form

outline on only one border

I know this is old. But yeah. I prefer much shorter solution, than Giona answer

[contenteditable] {
    border-bottom: 1px solid transparent;
    &:focus {outline: none; border-bottom: 1px dashed #000;}
}

Plotting with C#

I started using the new ASP.NET Chart control a few days ago, and it's absolutely amazing in its capabilities.

Here is the link.

EDIT: This is obviously only if you are using ASP.NET. Not sure about WinForms.

How to know Hive and Hadoop versions from command prompt?

hive -e "set hive.hwi.war.file;" | cut -d'-' -f3

PHP: How to remove specific element from an array?

Use array_search to get the key and remove it with unset if found:

if (($key = array_search('strawberry', $array)) !== false) {
    unset($array[$key]);
}

array_search returns false (null until PHP 4.2.0) if no item has been found.

And if there can be multiple items with the same value, you can use array_keys to get the keys to all items:

foreach (array_keys($array, 'strawberry') as $key) {
    unset($array[$key]);
}

Generating Random Number In Each Row In Oracle Query

Something like?

select t.*, round(dbms_random.value() * 8) + 1 from foo t;

Edit: David has pointed out this gives uneven distribution for 1 and 9.

As he points out, the following gives a better distribution:

select t.*, floor(dbms_random.value(1, 10)) from foo t;

SQL Server 2008 Windows Auth Login Error: The login is from an untrusted domain

You need to enable the sa account first and log in to your SQL management studio with the sa account (please chose SQl Server authentication).

After you logged in with the sa account, go to security, right-click on logins, select new login, select SQL Server authentication, create a user name (no / or any other special characters, just a name), then give it a password, confirm the password and at the bottom of that page select your default Database.

Go to logins, right-click on the user you created and click on properties.

Go to Server Roles and select the roles you want to give to the user you created.

Click OK and go back to login properties, click on User Mapping, double-click on the database you want to map this user to and select the database role membership for that database in the bottom window.

How to markdown nested list items in Bitbucket?

Even a single space works

...Just open this answer for edit to see it.

Nested lists, deeper levels: ---- leave here an empty row * first level A item - no space in front the bullet character * second level Aa item - 1 space is enough * third level Aaa item - 5 spaces min * second level Ab item - 4 spaces possible too * first level B item

Nested lists, deeper levels:

  • first level A item - no space in front the bullet character
    • second level Aa item - 1 space is enough
      • third level Aaa item - 5 spaces min
    • second level Ab item - 4 spaces possible too
  • first level B item

    Nested lists, deeper levels:
     ...Skip a line and indent eight spaces. (as said in the editor-help, just on this page)
    * first level A item - no space in front the bullet character
     * second level Aa item - 1 space is enough
         * third level Aaa item - 5 spaces min
        * second level Ab item - 4 spaces possible too
    * first level B item
    

How to know the version of pip itself

For windows:

import pip

help(pip) 

shows the version at the end of the help file.

log4j logging hierarchy order

Hierarchy order

  1. ALL
  2. TRACE
  3. DEBUG
  4. INFO
  5. WARN
  6. ERROR
  7. FATAL
  8. OFF

Run git pull over all subdirectories

Original answer 2010:

If all of those directories are separate git repo, you should reference them as submodules.

That means your "origin" would be that remote repo 'plugins' which only contains references to subrepos 'cms', 'admin', 'chart'.

A git pull followed by a git submodule update would achieve what your are looking for.


Update January 2016:

With Git 2.8 (Q1 2016), you will be able to fetch submodules in parallel (!) with git fetch --recurse-submodules -j2.
See "How to speed up / parallelize downloads of git submodules using git clone --recursive?"

Postgresql, update if row with some unique value exists, else insert

This has been asked many times. A possible solution can be found here: https://stackoverflow.com/a/6527838/552671

This solution requires both an UPDATE and INSERT.

UPDATE table SET field='C', field2='Z' WHERE id=3;
INSERT INTO table (id, field, field2)
       SELECT 3, 'C', 'Z'
       WHERE NOT EXISTS (SELECT 1 FROM table WHERE id=3);

With Postgres 9.1 it is possible to do it with one query: https://stackoverflow.com/a/1109198/2873507

Split text with '\r\n'

Reading the file is easier done with the static File class:

// First read all the text into a single string.
string text = File.ReadAllText(FileName);

// Then split the lines at "\r\n".   
string[] stringSeparators = new string[] { "\r\n" };
string[] lines = text.Split(stringSeparators, StringSplitOptions.None);

// Finally replace lonely '\r' and '\n' by  whitespaces in each line.
foreach (string s in lines) {
    Console.WriteLine(s.Replace('\r', ' ').Replace('\n', ' '));
}

Note: The text might also contain vertical tabulators \v. Those are used by Microsoft Word as manual linebreaks.

In order to catch any possible kind of breaks, you could use regex for the replacement

Console.WriteLine(Regex.Replace(s, @"[\f\n\r\t\v]", " "));

Parsing JSON using Json.net

I don't know about JSON.NET, but it works fine with JavaScriptSerializer from System.Web.Extensions.dll (.NET 3.5 SP1):

using System.Collections.Generic;
using System.Web.Script.Serialization;
public class NameTypePair
{
    public string OBJECT_NAME { get; set; }
    public string OBJECT_TYPE { get; set; }
}
public enum PositionType { none, point }
public class Ref
{
    public int id { get; set; }
}
public class SubObject
{
    public NameTypePair attributes { get; set; }
    public Position position { get; set; }
}
public class Position
{
    public int x { get; set; }
    public int y { get; set; }
}
public class Foo
{
    public Foo() { objects = new List<SubObject>(); }
    public string displayFieldName { get; set; }
    public NameTypePair fieldAliases { get; set; }
    public PositionType positionType { get; set; }
    public Ref reference { get; set; }
    public List<SubObject> objects { get; set; }
}
static class Program
{

    const string json = @"{
  ""displayFieldName"" : ""OBJECT_NAME"", 
  ""fieldAliases"" : {
    ""OBJECT_NAME"" : ""OBJECT_NAME"", 
    ""OBJECT_TYPE"" : ""OBJECT_TYPE""
  }, 
  ""positionType"" : ""point"", 
  ""reference"" : {
    ""id"" : 1111
  }, 
  ""objects"" : [
    {
      ""attributes"" : {
        ""OBJECT_NAME"" : ""test name"", 
        ""OBJECT_TYPE"" : ""test type""
      }, 
      ""position"" : 
      {
        ""x"" : 5, 
        ""y"" : 7
      }
    }
  ]
}";


    static void Main()
    {
        JavaScriptSerializer ser = new JavaScriptSerializer();
        Foo foo = ser.Deserialize<Foo>(json);
    }


}

Edit:

Json.NET works using the same JSON and classes.

Foo foo = JsonConvert.DeserializeObject<Foo>(json);

Link: Serializing and Deserializing JSON with Json.NET

Convert pyspark string to date format

from datetime import datetime
from pyspark.sql.functions import col, udf
from pyspark.sql.types import DateType



# Creation of a dummy dataframe:
df1 = sqlContext.createDataFrame([("11/25/1991","11/24/1991","11/30/1991"), 
                            ("11/25/1391","11/24/1992","11/30/1992")], schema=['first', 'second', 'third'])

# Setting an user define function:
# This function converts the string cell into a date:
func =  udf (lambda x: datetime.strptime(x, '%m/%d/%Y'), DateType())

df = df1.withColumn('test', func(col('first')))

df.show()

df.printSchema()

Here is the output:

+----------+----------+----------+----------+
|     first|    second|     third|      test|
+----------+----------+----------+----------+
|11/25/1991|11/24/1991|11/30/1991|1991-01-25|
|11/25/1391|11/24/1992|11/30/1992|1391-01-17|
+----------+----------+----------+----------+

root
 |-- first: string (nullable = true)
 |-- second: string (nullable = true)
 |-- third: string (nullable = true)
 |-- test: date (nullable = true)

SQL update from one Table to another based on a ID match

For PostgreSQL:

UPDATE Sales_Import SI
SET AccountNumber = RAN.AccountNumber
FROM RetrieveAccountNumber RAN
WHERE RAN.LeadID = SI.LeadID; 

How to manually include external aar package using new Gradle Android Build System

There is 1 more way to do this.

Usually the .aar file is not supposed to be directly used like we use a .jar and hence the solutions mentioned above to mention it in libs folder and declaring in gradle can be avoided.

Step 1: Unpack the .aar file (You can do this by renaming its extension from ".aar" to ".zip")

Step 2: You will most probably find the .jar file in the folder after extraction. Copy this .jar file and paste it in your module/libs folder

Step 3: That's it, now sync your project and you should be able to access all classes/methods/ properties from that .jar . You don't need to mention about it's path/name/existence in any gradle file, this is because the gradle build system always looks out for files existing in libs folder while building the project

How to remove unused C/C++ symbols with GCC and ld?

Programming habits could help too; e.g. add static to functions that are not accessed outside a specific file; use shorter names for symbols (can help a bit, likely not too much); use const char x[] where possible; ... this paper, though it talks about dynamic shared objects, can contain suggestions that, if followed, can help to make your final binary output size smaller (if your target is ELF).

round value to 2 decimals javascript

If you want it visually formatted to two decimals as a string (for output) use toFixed():

var priceString = someValue.toFixed(2);

The answer by @David has two problems:

  1. It leaves the result as a floating point number, and consequently holds the possibility of displaying a particular result with many decimal places, e.g. 134.1999999999 instead of "134.20".

  2. If your value is an integer or rounds to one tenth, you will not see the additional decimal value:

    var n = 1.099;
    (Math.round( n * 100 )/100 ).toString() //-> "1.1"
    n.toFixed(2)                            //-> "1.10"
    
    var n = 3;
    (Math.round( n * 100 )/100 ).toString() //-> "3"
    n.toFixed(2)                            //-> "3.00"
    

And, as you can see above, using toFixed() is also far easier to type. ;)

Check if MySQL table exists or not

Updated mysqli version:

if ($result = $mysqli->query("SHOW TABLES LIKE '".$table."'")) {
    if($result->num_rows == 1) {
        echo "Table exists";
    }
}
else {
    echo "Table does not exist";
}

Original mysql version:

if(mysql_num_rows(mysql_query("SHOW TABLES LIKE '".$table."'"))==1) 
    echo "Table exists";
else echo "Table does not exist";

Referenced from the PHP docs.

Nth word in a string variable

A file containing some statements :

cat test.txt

Result :

This is the 1st Statement
This is the 2nd Statement
This is the 3rd Statement
This is the 4th Statement
This is the 5th Statement

So, to print the 4th word of this statement type :

cat test.txt |awk '{print $4}'

Output :

1st
2nd
3rd
4th
5th

jQuery validation plugin: accept only alphabetical characters?

 $('.AlphabetsOnly').keypress(function (e) {
        var regex = new RegExp(/^[a-zA-Z\s]+$/);
        var str = String.fromCharCode(!e.charCode ? e.which : e.charCode);
        if (regex.test(str)) {
            return true;
        }
        else {
            e.preventDefault();
            return false;
        }
    });

Breaking out of a nested loop

Don't quote me on this, but you could use goto as suggested in the MSDN. There are other solutions, as including a flag that is checked in each iteration of both loops. Finally you could use an exception as a really heavyweight solution to your problem.

GOTO:

for ( int i = 0; i < 10; ++i ) {
   for ( int j = 0; j < 10; ++j ) {
      // code
      if ( break_condition ) goto End;
      // more code
   }
}
End: ;

Condition:

bool exit = false;
for ( int i = 0; i < 10 && !exit; ++i ) {
   for ( int j = 0; j < 10 && !exit; ++j ) {
      // code
      if ( break_condition ) {
         exit = true;
         break; // or continue
      }
      // more code
   }
}

Exception:

try {
    for ( int i = 0; i < 10 && !exit; ++i ) {
       for ( int j = 0; j < 10 && !exit; ++j ) {
          // code
          if ( break_condition ) {
             throw new Exception()
          }
          // more code
       }
    }
catch ( Exception e ) {}