Programs & Examples On #Wikimapia

How to change the pop-up position of the jQuery DatePicker control

The accepted answer for this question is actually not for the jQuery UI Datepicker. To change the position of the jQuery UI Datepicker just modify .ui-datepicker in the css file. The size of the Datepicker can also be changed in this way, just adjust the font size.

Declaring a xsl variable and assigning value to it

No, unlike in a lot of other languages, XSLT variables cannot change their values after they are created. You can however, avoid extraneous code with a technique like this:

<xsl:stylesheet version="1.0" xmlns:xsl="http://www.w3.org/1999/XSL/Transform">
  <xsl:output method="xml" indent="yes" omit-xml-declaration="yes"/>

  <xsl:variable name="mapping">
    <item key="1" v1="A" v2="B" />
    <item key="2" v1="X" v2="Y" />
  </xsl:variable>
  <xsl:variable name="mappingNode"
                select="document('')//xsl:variable[@name = 'mapping']" />

  <xsl:template match="....">
    <xsl:variable name="testVariable" select="'1'" />

    <xsl:variable name="values" select="$mappingNode/item[@key = $testVariable]" />

    <xsl:variable name="variable1" select="$values/@v1" />
    <xsl:variable name="variable2" select="$values/@v2" />
  </xsl:template>
</xsl:stylesheet>

In fact, once you've got the values variable, you may not even need separate variable1 and variable2 variables. You could just use $values/@v1 and $values/@v2 instead.

How to obtain Certificate Signing Request

Follow these steps to create CSR (Code Signing Identity):

  1. On your Mac, go to the folder 'Applications' ? 'Utilities' and open 'Keychain Access.'

    enter image description here

  2. Go to 'Keychain Access' ? Certificate Assistant ? Request a Certificate from a Certificate Authority. ?

    enter image description here

  3. Fill out the information in the Certificate Information window as specified below and click "Continue."
    • In the User Email Address field, enter the email address to identify with this certificate
    • In the Common Name field, enter your name
    • In the Request group, click the "Saved to disk" option ?

    enter image description here

  4. Save the file to your hard drive.

    enter image description here


Use this CSR (.certSigningRequest) file to create project/application certificates and profiles, in Apple developer account.

SQL Switch/Case in 'where' clause

Try this query. Its very easy to understand:

CREATE TABLE PersonsDetail(FirstName nvarchar(20), LastName nvarchar(20), GenderID int);
GO

INSERT INTO PersonsDetail VALUES(N'Gourav', N'Bhatia', 2),
              (N'Ramesh', N'Kumar', 1),
              (N'Ram', N'Lal', 2),
              (N'Sunil', N'Kumar', 3),
              (N'Sunny', N'Sehgal', 1),
              (N'Malkeet', N'Shaoul', 3),
              (N'Jassy', N'Sohal', 2);
GO

SELECT FirstName, LastName, Gender =
    CASE GenderID
    WHEN 1 THEN 'Male'
    WHEN 2 THEN 'Female'
    ELSE 'Unknown'
    END
FROM PersonsDetail

Dynamically add child components in React

First, I wouldn't use document.body. Instead add an empty container:

index.html:

<html>
    <head></head>
    <body>
        <div id="app"></div>
    </body>
</html>

Then opt to only render your <App /> element:

main.js:

var App = require('./App.js');
ReactDOM.render(<App />, document.getElementById('app'));

Within App.js you can import your other components and ignore your DOM render code completely:

App.js:

var SampleComponent = require('./SampleComponent.js');

var App = React.createClass({
    render: function() {
        return (
            <div>
                <h1>App main component!</h1>
                <SampleComponent name="SomeName" />
            </div>
        );
    }
});

SampleComponent.js:

var SampleComponent = React.createClass({
    render: function() {
        return (
            <div>
                <h1>Sample Component!</h1>
            </div>
        );
    }
});

Then you can programmatically interact with any number of components by importing them into the necessary component files using require.

How can I get a resource content from a static context?

I am using API level 27 and found a best solution after struggling for around two days. If you want to read a xml file from a class which doesn't derive from Activity or Application then do the following.

  1. Put the testdata.xml file inside the assets directory.

  2. Write the following code to get the testdata document parsed.

        InputStream inputStream = this.getClass().getResourceAsStream("/assets/testdata.xml");
    
        // create a new DocumentBuilderFactory
        DocumentBuilderFactory factory = DocumentBuilderFactory.newInstance();
        // use the factory to create a documentbuilder
        DocumentBuilder builder = factory.newDocumentBuilder();
        // create a new document from input stream
        Document doc = builder.parse(inputStream);
    

Adb over wireless without usb cable at all for not rooted phones

This might help:

If the adb connection is ever lost:

Make sure that your host is still connected to the same Wi-Fi network your Android device is. Reconnect by executing the "adb connect IP" step. (IP is obviously different when you change location.) Or if that doesn't work, reset your adb host: adb kill-server and then start over from the beginning.

Most efficient T-SQL way to pad a varchar on the left to a certain length?

How about this:

replace((space(3 - len(MyField))

3 is the number of zeros to pad

How to prettyprint a JSON file?

It's far from perfect, but it does the job.

data = data.replace(',"',',\n"')

you can improve it, add indenting and so on, but if you just want to be able to read a cleaner json, this is the way to go.

Hide text within HTML?

You said that you can’t use HTML comments because the CMS filters them out. So I assume that you really want to hide this content and you don’t need to display it ever.

In that case, you shouldn’t use CSS (only), as you’d only play on the presentation level, not affecting the content level. Your content should also be hidden for user-agents ignoring the CSS (people using text browsers, feed readers, screen readers; bots; etc.).

In HTML5 there is the global hidden attribute:

When specified on an element, it indicates that the element is not yet, or is no longer, directly relevant to the page's current state, or that it is being used to declare content to be reused by other parts of the page as opposed to being directly accessed by the user. User agents should not render elements that have the hidden attribute specified.

Example (using the small element here, because it’s an "attribution"):

<small hidden>Thanks to John Doe for this idea.</small>

As a fallback (for user-agents that don’t know the hidden attribute), you can specify in your CSS:

[hidden] {display:none;}

An general element for plain text could be the script element used as "data block":

<script type="text/plain" hidden>
Thanks to John Doe for this idea.
</script>

Alternatively, you could also use data-* attributes on existing elements (resp. on new div elements if you want to group some elements for the attribution):

<p data-attribution="Thanks to John Doe for this idea!">This is some visible example content …</p>

What are the differences between JSON and JSONP?

Basically, you're not allowed to request JSON data from another domain via AJAX due to same-origin policy. AJAX allows you to fetch data after a page has already loaded, and then execute some code/call a function once it returns. We can't use AJAX but we are allowed to inject <script> tags into our own page and those are allowed to reference scripts hosted at other domains.

Usually you would use this to include libraries from a CDN such as jQuery. However, we can abuse this and use it to fetch data instead! JSON is already valid JavaScript (for the most part), but we can't just return JSON in our script file, because we have no way of knowing when the script/data has finished loading and we have no way of accessing it unless it's assigned to a variable or passed to a function. So what we do instead is tell the web service to call a function on our behalf when it's ready.

For example, we might request some data from a stock exchange API, and along with our usual API parameters, we give it a callback, like ?callback=callThisWhenReady. The web service then wraps the data with our function and returns it like this: callThisWhenReady({...data...}). Now as soon as the script loads, your browser will try to execute it (as normal), which in turns calls our arbitrary function and feeds us the data we wanted.

It works much like a normal AJAX request except instead of calling an anonymous function, we have to use named functions.

jQuery actually supports this seamlessly for you by creating a uniquely named function for you and passing that off, which will then in turn run the code you wanted.

How do you loop in a Windows batch file?

Conditionally perform a command several times.

  • syntax-FOR-Files

    FOR %%parameter IN (set) DO command 
    
  • syntax-FOR-Files-Rooted at Path

    FOR /R [[drive:]path] %%parameter IN (set) DO command 
    
  • syntax-FOR-Folders

    FOR /D %%parameter IN (folder_set) DO command 
    
  • syntax-FOR-List of numbers

    FOR /L %%parameter IN (start,step,end) DO command 
    
  • syntax-FOR-File contents

    FOR /F ["options"] %%parameter IN (filenameset) DO command 
    

    or

    FOR /F ["options"] %%parameter IN ("Text string to process") DO command
    
  • syntax-FOR-Command Results

    FOR /F ["options"] %%parameter IN ('command to process') DO command
    

It

  • Take a set of data
  • Make a FOR Parameter %%G equal to some part of that data
  • Perform a command (optionally using the parameter as part of the command).
  • --> Repeat for each item of data

If you are using the FOR command at the command line rather than in a batch program, use just one percent sign: %G instead of %%G.

FOR Parameters

  • The first parameter has to be defined using a single character, for example the letter G.

  • FOR %%G IN ...

    In each iteration of a FOR loop, the IN ( ....) clause is evaluated and %%G set to a different value

    If this clause results in a single value then %%G is set equal to that value and the command is performed.

    If the clause results in a multiple values then extra parameters are implicitly defined to hold each. These are automatically assigned in alphabetical order %%H %%I %%J ...(implicit parameter definition)

    If the parameter refers to a file, then enhanced variable reference can be used to extract the filename/path/date/size.

    You can of course pick any letter of the alphabet other than %%G. but it is a good choice because it does not conflict with any of the pathname format letters (a, d, f, n, p, s, t, x) and provides the longest run of non-conflicting letters for use as implicit parameters.

How to install trusted CA certificate on Android device?

What I did to beable to use startssl certificates was quite easy. (on my rooted phone)

I copied /system/etc/security/cacerts.bks to my sdcard

Downloaded http://www.startssl.com/certs/ca.crt and http://www.startssl.com/certs/sub.class1.server.ca.crt

Went to portecle.sourceforge.net and ran portecle directly from the webpage.

Opened my cacerts.bks file from my sdcard (entered nothing when asked for a password)

Choose import in portacle and opened sub.class1.server.ca.crt, im my case it allready had the ca.crt but maybe you need to install that too.

Saved the keystore and copied it baxck to /system/etc/security/cacerts.bks (I made a backup of that file first just in case)

Rebooted my phone and now I can vist my site thats using a startssl certificate without errors.

Correctly Parsing JSON in Swift 3

The problem is with the API interaction method. The JSON parsing is changed only in syntax. The main problem is with the way of fetching data. What you are using is a synchronous way of getting data. This doesn't work in every case. What you should be using is an asynchronous way to fetch data. In this way, you have to request data through the API and wait for it to respond with data. You can achieve this with URL session and third party libraries like Alamofire. Below is the code for URL Session method.

let urlString = "https://api.forecast.io/forecast/apiKey/37.5673776,122.048951"
let url = URL.init(string: urlString)
URLSession.shared.dataTask(with:url!) { (data, response, error) in
    guard error == nil else {
        print(error)
    }
    do {
        let Data = try JSONSerialization.jsonObject(with: data!) as! [String:Any]
        // Note if your data is coming in Array you should be using [Any]()
        //Now your data is parsed in Data variable and you can use it normally
        let currentConditions = Data["currently"] as! [String:Any]
        print(currentConditions)
        let currentTemperatureF = currentConditions["temperature"] as! Double
        print(currentTemperatureF)
    } catch let error as NSError {
        print(error)
    }
}.resume()

What is the meaning of ImagePullBackOff status on a Kubernetes pod?

I too had this problem, when I checked I image that I was pulling from a private registry was removed If we describe pod it will show pulling event and the image it's trying to pull

kubectl describe pod <POD_NAME>

Events:
 Type     Reason   Age                  From              Message
 ----     ------   ----                 ----              -------
 Normal   Pulling  18h (x35 over 20h)   kubelet, gsk-kub  Pulling image "registeryName:tag"
 Normal   BackOff  11m (x822 over 20h)  kubelet, gsk-kub  Back-off pulling image "registeryName:tag"
 Warning  Failed   91s (x858 over 20h)  kubelet, gsk-kub  Error: ImagePullBackOff

How do I change an HTML selected option using JavaScript?

It's an old post, but if anyone is still looking for solution to this kind of problem, here is what I came up with:

<script>
  document.addEventListener("DOMContentLoaded", function(e) {
    document.forms['AddAndEdit'].elements['list'].value = 11;
  });
</script>

How to use SortedMap interface in Java?

TreeMap, which is an implementation of the SortedMap interface, would work.

How do I use it ?

Map<Float, MyObject> map = new TreeMap<Float, MyObject>();

Embed Google Map code in HTML with marker

I would suggest this way, one line iframe. no javascript needed at all. In query ?q=,

_x000D_
_x000D_
<iframe src="http://maps.google.com/maps?q=12.927923,77.627108&z=15&output=embed"></iframe>
_x000D_
_x000D_
_x000D_

Hide options in a select list using jQuery

It CAN be done cross browser; it just takes some custom programming. Please see my fiddle at http://jsfiddle.net/sablefoste/YVMzt/6/. It was tested to work in Chrome, Firefox, Internet Explorer, and Safari.

In short, I have a hidden field, #optionstore, which stores the array sequentially (since you can't have Associative Arrays in JavaScript). Then when you change the category, it parses the existing options (first time through only) writes them to #optionstore, erases everything, and puts back only the ones associated with the category.

NOTE: I created this to allow different option values from the text displayed to the user, so it is highly flexible.

The HTML:

<p id="choosetype">
    <div>
        Food Category:
    </div>
    <select name="category" id="category" title="OPTIONAL - Choose a Category to Limit Food Types" size="1">
        <option value="">All Food</option>
        <option value="Food1">Fruit</option>
        <option value="Food2">Veggies</option>
        <option value="Food3">Meat</option>
        <option value="Food4">Dairy</option>
        <option value="Food5">Bread</option>
    </select>
    <div>
        Food Selection
    </div>
    <select name="foodType" id="foodType" size="1">
        <option value="Fruit1" class="sub-Food1">Apples</option>
        <option value="Fruit2" class="sub-Food1">Pears</option>
        <option value="Fruit3" class="sub-Food1">Bananas</option>
        <option value="Fruit4" class="sub-Food1">Oranges</option>
        <option value="Veg1" class="sub-Food2">Peas</option>
        <option value="Veg2" class="sub-Food2">Carrots</option>
        <option value="Veg3" class="sub-Food2">Broccoli</option>
        <option value="Veg4" class="sub-Food2">Lettuce</option>
        <option value="Meat1" class="sub-Food3">Steak</option>
        <option value="Meat2" class="sub-Food3">Chicken</option>
        <option value="Meat3" class="sub-Food3">Salmon</option>
        <option value="Meat4" class="sub-Food3">Shrimp</option>
        <option value="Meat5" class="sub-Food3">Tuna</option>
        <option value="Meat6" class="sub-Food3">Pork</option>
        <option value="Dairy1" class="sub-Food4">Milk</option>
        <option value="Dairy2" class="sub-Food4">Cheese</option>
        <option value="Dairy3" class="sub-Food4">Ice Cream</option>
        <option value="Dairy4" class="sub-Food4">Yogurt</option>
        <option value="Bread1" class="sub-Food5">White Bread</option>
        <option value="Bread2" class="sub-Food5">Panini</option>
    </select>
    <span id="optionstore" style="display:none;"></span>
</p>

The JavaScript/jQuery:

$(document).ready(function() {
    $('#category').on("change", function() {
        var cattype = $(this).val();
        optionswitch(cattype);
    });
});

function optionswitch(myfilter) {
    //Populate the optionstore if the first time through
    if ($('#optionstore').text() == "") {
        $('option[class^="sub-"]').each(function() {
            var optvalue = $(this).val();
            var optclass = $(this).prop('class');
            var opttext = $(this).text();
            optionlist = $('#optionstore').text() + "@%" + optvalue + "@%" + optclass + "@%" + opttext;
            $('#optionstore').text(optionlist);
        });
    }

    //Delete everything
    $('option[class^="sub-"]').remove();

    // Put the filtered stuff back
    populateoption = rewriteoption(myfilter);
    $('#foodType').html(populateoption);
}

function rewriteoption(myfilter) {
    //Rewrite only the filtered stuff back into the option
    var options = $('#optionstore').text().split('@%');
    var resultgood = false;
    var myfilterclass = "sub-" + myfilter;
    var optionlisting = "";

    myfilterclass = (myfilter != "")?myfilterclass:"all";

    //First variable is always the value, second is always the class, third is always the text
    for (var i = 3; i < options.length; i = i + 3) {
        if (options[i - 1] == myfilterclass || myfilterclass == "all") {
            optionlisting = optionlisting + '<option value="' + options[i - 2] + '" class="' + options[i - 1] + '">' + options[i] + '</option>';
            resultgood = true;
        }
    }
    if (resultgood) {
        return optionlisting;
    }
}

NameError: global name 'xrange' is not defined in Python 3

in python 2.x, xrange is used to return a generator while range is used to return a list. In python 3.x , xrange has been removed and range returns a generator just like xrange in python 2.x. Therefore, in python 3.x you need to use range rather than xrange.

What bitrate is used for each of the youtube video qualities (360p - 1080p), in regards to flowplayer?

Looking at this official google link: Youtube Live encoder settings, bitrates and resolutions they have this table:

                   240p       360p        480p        720p        1080p
Resolution      426 x 240   640 x 360   854x480     1280x720    1920x1080
Video Bitrates                   
Maximum         700 Kbps    1000 Kbps   2000 Kbps   4000 Kbps   6000 Kbps
Recommended     400 Kbps    750 Kbps    1000 Kbps   2500 Kbps   4500 Kbps
Minimum         300 Kbps    400 Kbps    500 Kbps    1500 Kbps   3000 Kbps

It would appear as though this is the case, although the numbers dont sync up to the google table above:

// the bitrates, video width and file names for this clip
      bitrates: [
        { url: "bbb-800.mp4", width: 480, bitrate: 800 }, //360p video
        { url: "bbb-1200.mp4", width: 720, bitrate: 1200 }, //480p video
        { url: "bbb-1600.mp4", width: 1080, bitrate: 1600 } //720p video
      ],

Extract values in Pandas value_counts()

Try this:

dataframe[column].value_counts().index.tolist()
['apple', 'sausage', 'banana', 'cheese']

How to change maven logging level to display only warning and errors?

Linux:

mvn validate clean install | egrep -v "(^\[INFO\])"

or

mvn validate clean install | egrep -v "(^\[INFO\]|^\[DEBUG\])"

Windows:

mvn validate clean install | findstr /V /R "^\[INFO\] ^\[DEBUG\]"

Change image source with JavaScript

 <script type="text/javascript">
        function changeImage(a) {
    var picName=a.substring(1,a.length-1);
            document.getElementById("image").src=picName;
        }
 </script>

 <div id="main_img">
     <img id="image" src="app.jpg">
 </div>

 <div id="thumb_img">
     <img src='app.jpg'  onclick="changeImage('+5steps.jpg+');">
     <img src='5steps.jpg'  onclick="changeImage('+award.png+');">
     <img src='award.png'  onclick="changeImage('+app.jpg+');">
 </div>

Use the above code by placing this html file and pics(take care in namings, beacause I have given the above code with my pic names) in same folder you will get...

PivotTable to show values, not sum of values

I fear this might turn out to BE the long way round but could depend on how big your data set is – presumably more than four months for example.

Assuming your data is in ColumnA:C and has column labels in Row 1, also that Month is formatted mmm(this last for ease of sorting):

  1. Sort the data by Name then Month
  2. Enter in D2 =IF(AND(A2=A1,C2=C1),D1+1,1) (One way to deal with what is the tricky issue of multiple entries for the same person for the same month).
  3. Create a pivot table from A1:D(last occupied row no.)
  4. Say insert in F1.
  5. Layout as in screenshot.

SO12803305 example

I’m hoping this would be adequate for your needs because pivot table should automatically update (provided range is appropriate) in response to additional data with refresh. If not (you hard taskmaster), continue but beware that the following steps would need to be repeated each time the source data changes.

  1. Copy pivot table and Paste Special/Values to, say, L1.
  2. Delete top row of copied range with shift cells up.
  3. Insert new cell at L1 and shift down.
  4. Key 'Name' into L1.
  5. Filter copied range and for ColumnL, select Row Labels and numeric values.
  6. Delete contents of L2:L(last selected cell)
  7. Delete blank rows in copied range with shift cells up (may best via adding a column that counts all 12 months). Hopefully result should be as highlighted in yellow.

Happy to explain further/try again (I've not really tested this) if does not suit.

EDIT (To avoid second block of steps above and facilitate updating for source data changes)

.0. Before first step 2. add a blank row at the very top and move A2:D2 up.
.2. Adjust cell references accordingly (in D3 =IF(AND(A3=A2,C3=C2),D2+1,1).
.3. Create pivot table from A:D

.6. Overwrite Row Labels with Name.
.7. PivotTable Tools, Design, Report Layout, Show in Tabular Form and sort rows and columns A>Z.
.8. Hide Row1, ColumnG and rows and columns that show (blank).

additional example

Steps .0. and .2. in the edit are not required if the pivot table is in a different sheet from the source data (recommended).

Step .3. in the edit is a change to simplify the consequences of expanding the source data set. However introduces (blank) into pivot table that if to be hidden may need adjustment on refresh. So may be better to adjust source data range each time that changes instead: PivotTable Tools, Options, Change Data Source, Change Data Source, Select a table or range). In which case copy rather than move in .0.

Android : difference between invisible and gone?

View.GONE = The view will not show and the rest of the views will not take its existence into consideration

View.INVISIBLE = The view will not show, but it will take its assigned space in the layout

Suppress InsecureRequestWarning: Unverified HTTPS request is being made in Python2.6

You can disable any Python warnings via the PYTHONWARNINGS environment variable. In this case, you want:

export PYTHONWARNINGS="ignore:Unverified HTTPS request"

To disable using Python code (requests >= 2.16.0):

import urllib3
urllib3.disable_warnings(urllib3.exceptions.InsecureRequestWarning)

For requests < 2.16.0, see original answer below.

Original answer

The reason doing urllib3.disable_warnings() didn't work for you is because it looks like you're using a separate instance of urllib3 vendored inside of requests.

I gather this based on the path here: /usr/lib/python2.6/site-packages/requests/packages/urllib3/connectionpool.py

To disable warnings in requests' vendored urllib3, you'll need to import that specific instance of the module:

import requests
from requests.packages.urllib3.exceptions import InsecureRequestWarning

requests.packages.urllib3.disable_warnings(InsecureRequestWarning)

Download a file by jQuery.Ajax

1. Framework agnostic: Servlet downloading file as attachment

<!-- with JS -->
<a href="javascript:window.location='downloadServlet?param1=value1'">
    download
</a>

<!-- without JS -->
<a href="downloadServlet?param1=value1" >download</a>

2. Struts2 Framework: Action downloading file as attachment

<!-- with JS -->
<a href="javascript:window.location='downloadAction.action?param1=value1'">
    download
</a>

<!-- without JS -->
<a href="downloadAction.action?param1=value1" >download</a>

It would be better to use <s:a> tag pointing with OGNL to an URL created with <s:url> tag:

<!-- without JS, with Struts tags: THE RIGHT WAY -->    
<s:url action="downloadAction.action" var="url">
    <s:param name="param1">value1</s:param>
</s:ulr>
<s:a href="%{url}" >download</s:a>

In the above cases, you need to write the Content-Disposition header to the response, specifying that the file needs to be downloaded (attachment) and not opened by the browser (inline). You need to specify the Content Type too, and you may want to add the file name and length (to help the browser drawing a realistic progressbar).

For example, when downloading a ZIP:

response.setContentType("application/zip");
response.addHeader("Content-Disposition", 
                   "attachment; filename=\"name of my file.zip\"");
response.setHeader("Content-Length", myFile.length()); // or myByte[].length...

With Struts2 (unless you are using the Action as a Servlet, an hack for direct streaming, for example), you don't need to directly write anything to the response; simply using the Stream result type and configuring it in struts.xml will work: EXAMPLE

<result name="success" type="stream">
   <param name="contentType">application/zip</param>
   <param name="contentDisposition">attachment;filename="${fileName}"</param>
   <param name="contentLength">${fileLength}</param>
</result>

3. Framework agnostic (/ Struts2 framework): Servlet(/Action) opening file inside the browser

If you want to open the file inside the browser, instead of downloading it, the Content-disposition must be set to inline, but the target can't be the current window location; you must target a new window created by javascript, an <iframe> in the page, or a new window created on-the-fly with the "discussed" target="_blank":

<!-- From a parent page into an IFrame without javascript -->   
<a href="downloadServlet?param1=value1" target="iFrameName">
    download
</a>

<!-- In a new window without javascript --> 
<a href="downloadServlet?param1=value1" target="_blank">
    download
</a>

<!-- In a new window with javascript -->    
<a href="javascript:window.open('downloadServlet?param1=value1');" >
    download
</a>

C: scanf to array

int main()
{
  int array[11];
  printf("Write down your ID number!\n");
  for(int i=0;i<id_length;i++)
  scanf("%d", &array[i]);
  if (array[0]==1)
  {
    printf("\nThis person is a male.");
  }
  else if (array[0]==2)
  {
    printf("\nThis person is a female.");
  }
  return 0;
}

AngularJS - add HTML element to dom in directive without jQuery

In angularJS, you can use angular.element which is the lite version of jQuery. You can do pretty much everything with it, so you don't need to include jQuery.

So basically, you can rewrite your code to something like this:

link: function (scope, iElement, iAttrs) {
  var svgTag = angular.element('<svg width="600" height="100" class="svg"></svg>');
  angular.element(svgTag).appendTo(iElement[0]);
  //...
}

MVC ajax json post to controller action method

Below is how I got this working.

The Key point was: I needed to use the ViewModel associated with the view in order for the runtime to be able to resolve the object in the request.

[I know that that there is a way to bind an object other than the default ViewModel object but ended up simply populating the necessary properties for my needs as I could not get it to work]

[HttpPost]  
  public ActionResult GetDataForInvoiceNumber(MyViewModel myViewModel)  
  {            
     var invoiceNumberQueryResult = _viewModelBuilder.HydrateMyViewModelGivenInvoiceDetail(myViewModel.InvoiceNumber, myViewModel.SelectedCompanyCode);
     return Json(invoiceNumberQueryResult, JsonRequestBehavior.DenyGet);
  }

The JQuery script used to call this action method:

var requestData = {
         InvoiceNumber: $.trim(this.value),
         SelectedCompanyCode: $.trim($('#SelectedCompanyCode').val())
      };


      $.ajax({
         url: '/en/myController/GetDataForInvoiceNumber',
         type: 'POST',
         data: JSON.stringify(requestData),
         dataType: 'json',
         contentType: 'application/json; charset=utf-8',
         error: function (xhr) {
            alert('Error: ' + xhr.statusText);
         },
         success: function (result) {
            CheckIfInvoiceFound(result);
         },
         async: true,
         processData: false
      });

how to create a cookie and add to http response from inside my service layer?

In Spring MVC you get the HtppServletResponce object by default .

   @RequestMapping("/myPath.htm")
    public ModelAndView add(HttpServletRequest request,
         HttpServletResponse response) throws Exception{
            //Do service call passing the response
    return new ModelAndView("CustomerAddView");
    }

//Service code
Cookie myCookie =
  new Cookie("name", "val");
  response.addCookie(myCookie);

Simulate low network connectivity for Android

Or on an actual device you can go to Settings -> Mobile Networks -> Preferred network types and chose the slowest available... Of course this is very limited, but for some test- purposes it might be enough.

What is a 'workspace' in Visual Studio Code?

So, yet again the lesson of not polluting the source tree of a project with artifacts that aren't directly related to that project is being ignored.

There is zero reason for a Visual Studio Code workspace file (workspaces.json) or directory (.vscode) or whatever to be placed in the source tree. It could just as easily have been placed under your user settings.

I thought we figured this out about 20+ years ago, but it seems that some lessons are doomed to be repeated.

Python Remove last 3 characters of a string

You might have misunderstood rstrip slightly, it strips not a string but any character in the string you specify.

Like this:

>>> text = "xxxxcbaabc"
>>> text.rstrip("abc")
'xxxx'

So instead, just use

text = text[:-3] 

(after replacing whitespace with nothing)

Restoring MySQL database from physical files

I ran into this trying to revive an accidentally deleted Docker Container (oraclelinux's MySQL) from a luckily-not-removed docker volume that had the DB data in physical files.

So, all I wanted to do was to turn the data from physical files into a .sql importable file to recreate the container with the DB and the data.

I tried biolin's solution, but ran into some [InnoDB] Multiple files found for the same tablespace ID errors, after restart. I realized that doing open hurt surgery on certain folders/files there is quite trickey.

The solution that worked for me was temporarily changing the datadir= in my.cnf to the available folder and restarting the MySQL server. It did the job perfectly!

Remove property for all objects in array

With ES6, you may deconstruct each object to create new one without named attributes:

const newArray = array.map(({dropAttr1, dropAttr2, ...keepAttrs}) => keepAttrs)

Fastest way to copy a file in Node.js

benweet's solution, but also checking the visibility of the file before copy:

function copy(from, to) {
    return new Promise(function (resolve, reject) {
        fs.access(from, fs.F_OK, function (error) {
            if (error) {
                reject(error);
            } else {
                var inputStream = fs.createReadStream(from);
                var outputStream = fs.createWriteStream(to);

                function rejectCleanup(error) {
                    inputStream.destroy();
                    outputStream.end();
                    reject(error);
                }

                inputStream.on('error', rejectCleanup);
                outputStream.on('error', rejectCleanup);

                outputStream.on('finish', resolve);

                inputStream.pipe(outputStream);
            }
        });
    });
}

PHP float with 2 decimal places: .00

You can use this simple function. number_format ()

    $num = 2214.56;

    // default english notation
    $english_format = number_format($num);
    // 2,215

    // French notation
    $format_francais = number_format($num, 2, ',', ' ');
    // 2 214,56

    $num1 = 2234.5688;

   // English notation with thousands separator
    $english_format_number = number_format($num1,2);
    // 2,234.57

    // english notation without thousands separator
    $english_format_number2 = number_format($num1, 2, '.', '');
    // 2234.57

How to use __doPostBack()

I'd just like to add something to this post for asp:button. I've tried clientId and it doesn't seem to work for me:

__doPostBack('<%= btn.ClientID%>', '');

However, getting the UniqueId seems to post back to the server, like below:

__doPostBack('<%= btn.UniqueID%>', '');

This might help someone else in future, hence posting this.

How to fix broken paste clipboard in VNC on Windows

You likely need to re-start VNC on both ends. i.e. when you say "restarted VNC", you probably just mean the client. But what about the other end? You likely need to re-start that end too. The root cause is likely a conflict. Many apps spy on the clipboard when they shouldn't. And many apps are not forgiving when they go to open the clipboard and can't. Robust ones will retry, others will simply not anticipate a failure and then they get fouled up and need to be restarted. Could be VNC, or it could be another app that's "listening" to the clipboard viewer chain, where it is obligated to pass along notifications to the other apps in the chain. If the notifications aren't sent, then VNC may not even know that there has been a clipboard update.

Load content of a div on another page

Yes, see "Loading Page Fragments" on http://api.jquery.com/load/.

In short, you add the selector after the URL. For example:

$('#result').load('ajax/test.html #container');

Press TAB and then ENTER key in Selenium WebDriver

Be sure to include the Key in the imports...

const {Builder, By, logging, until, Key} = require('selenium-webdriver');

searchInput.sendKeys(Key.ENTER) worked great for me

Export to CSV using jQuery and html

 <a id="export" role='button'>
        Click Here To Download Below Report
    </a>
    <table id="testbed_results" style="table-layout:fixed">
        <thead>
            <tr width="100%" style="color:white" bgcolor="#3195A9" id="tblHeader">
                <th>Name</th>
                <th>Date</th>
                <th>Speed</th>
                <th>Column2</th>
                <th>Interface</th>
                <th>Interface2</th>
                <th>Sub</th>
                <th>COmpany result</th>
                <th>company2</th>
                <th>Gen</th>
            </tr>
        </thead>
        <tbody>
            <tr id="samplerow">
                <td>hello</td>
                <td>100</td>
                <td>200</td>
                <td>300</td>
                <td>html2svc</td>
                <td>ajax</td>
                <td>200</td>
                <td>7</td>
                <td>8</td>
                <td>9</td>
            </tr>
            <tr>
                <td>hello</td>
                <td>100</td>
                <td>200</td>
                <td>300</td>
                <td>html2svc</td>
                <td>ajax</td>
                <td>200</td>
                <td>7</td>
                <td>8</td>
                <td>9</td>
            </tr>
        </tbody>
    </table>

    $(document).ready(function () {
        Html2CSV('testbed_results', 'myfilename','export');
    });



    function Html2CSV(tableId, filename,alinkButtonId) {
        var array = [];
        var headers = [];
        var arrayItem = [];
        var csvData = new Array();
        $('#' + tableId + ' th').each(function (index, item) {
            headers[index] = '"' + $(item).html() + '"';
        });
        csvData.push(headers);
        $('#' + tableId + ' tr').has('td').each(function () {

            $('td', $(this)).each(function (index, item) {
                arrayItem[index] = '"' + $(item).html() + '"';
            });
            array.push(arrayItem);
            csvData.push(arrayItem);
        });




        var fileName = filename + '.csv';
        var buffer = csvData.join("\n");
        var blob = new Blob([buffer], {
            "type": "text/csv;charset=utf8;"
        });
        var link = document.getElementById(alinkButton);

        if (link.download !== undefined) { // feature detection
            // Browsers that support HTML5 download attribute
            link.setAttribute("href", window.URL.createObjectURL(blob));
            link.setAttribute("download", fileName);
        }
        else if (navigator.msSaveBlob) { // IE 10+
            link.setAttribute("href", "#");
            link.addEventListener("click", function (event) {
                navigator.msSaveBlob(blob, fileName);
            }, false);
        }
        else {
            // it needs to implement server side export
            link.setAttribute("href", "http://www.example.com/export");
        }
    }

</script>

Add a duration to a moment (moment.js)

For people having a startTime (like 12h:30:30) and a duration (value in minutes like 120), you can guess the endTime like so:

const startTime = '12:30:00';
const durationInMinutes = '120';

const endTime = moment(startTime, 'HH:mm:ss').add(durationInMinutes, 'minutes').format('HH:mm');

// endTime is equal to "14:30"

How to add an existing folder with files to SVN?

Let's say I have code in the directory ~/local_dir/myNewApp, and I want to put it under 'https://svn.host/existing_path/myNewApp' (while being able to ignore some binaries, vendor libraries, etc.).

  1. Create an empty folder in the repository svn mkdir https://svn.host/existing_path/myNewApp
  2. Go to the parent directory of the project, cd ~/local_dir
  3. Check out the empty directory over your local folder. Don't be afraid - the files you have locally will not be deleted. svn co https://svn.host/existing_path/myNewApp. If your folder has a different name locally than in the repository, you must specify it as an additional argument.
  4. You can see that svn st will now show all your files as ?, which means that they are not currently under revision control
  5. Perform svn add on files you want to add to the repository, and add others to svn:ignore. You may find some useful options with svn help add, for example --parents or --depth empty, when you want selectively add only some files/folders.
  6. Commit with svn ci

Class file has wrong version 52.0, should be 50.0

Select "File" -> "Project Structure".

Under "Project Settings" select "Project"

From there you can select the "Project SDK".

The type initializer for 'CrystalDecisions.CrystalReports.Engine.ReportDocument' threw an exception

Project Properties -> Compile -> Target CPU -> Any CPU And uncheck Prefer 32 bit

Done

What is console.log?

Places you can view the console! Just to have them all in one answer.

Firefox

http://getfirebug.com/

(you can also now use Firefox's built in developer tools Ctrl+Shift+J (Tools > Web Developer > Error Console), but Firebug is much better; use Firebug)

Safari and Chrome

Basically the same.

https://developers.google.com/chrome-developer-tools/docs/overview

https://developer.apple.com/technologies/safari/developer-tools.html

Internet Explorer

Don't forget you can use compatibility modes to debug IE7 and IE8 in IE9 or IE10

http://msdn.microsoft.com/en-us/library/ie/gg589507(v=vs.85).aspx

http://msdn.microsoft.com/en-us/library/dd565628(v=vs.85).aspx

If you must access the console in IE6 for IE7 use the Firebug Lite bookmarklet

http://getfirebug.com/firebuglite/ look for stable bookmarklet

http://en.wikipedia.org/wiki/Bookmarklet

Opera

http://www.opera.com/dragonfly/

iOS

Works for all iPhones, iPod touch and iPads.

http://developer.apple.com/library/ios/ipad/#DOCUMENTATION/AppleApplications/Reference/SafariWebContent/DebuggingSafarioniPhoneContent/DebuggingSafarioniPhoneContent.html

Now with iOS 6 you can view the console through Safari in OS X if you plug in your device. Or you can do so with the emulator, simply open a Safari browser window and go to the "Develop" tab. There you will find options to get the Safari inspector to communicate with your device.

Windows Phone, Android

Both of these have no console built in and no bookmarklet ability. So we use http://jsconsole.com/ type :listen and it will give you a script tag to place in your HTML. From then on you can view your console inside the jsconsole website.

iOS and Android

You can also use http://html.adobe.com/edge/inspect/ to access web inspector tools and the console on any device using their convenient browser plugin.


Older browser problems

Lastly older versions of IE will crash if you use console.log in your code and not have the developer tools open at the same time. Luckily it's an easy fix. Use the below code snippet at the top of your code:

 if(!window.console){ window.console = {log: function(){} }; } 

This checks to see if the console is present, and if not it sets it to an object with a blank function called log. This way window.console and window.console.log is never truly undefined.

Correct way to find max in an Array in Swift

Updated for Swift 3/4:

Use below simple lines of code to find the max from array;

var num = [11, 2, 7, 5, 21]
var result = num.sorted(){
    $0 > $1
}
print("max from result: \(result[0])") // 21

Printing Python version in output

import sys  

expanded version

sys.version_info  
sys.version_info(major=3, minor=2, micro=2, releaselevel='final', serial=0)

specific

maj_ver = sys.version_info.major  
repr(maj_ver) 
'3'  

or

print(sys.version_info.major)
'3'

or

version = ".".join(map(str, sys.version_info[:3]))
print(version)
'3.2.2'

Difference between View and Request scope in managed beans

A @ViewScoped bean lives exactly as long as a JSF view. It usually starts with a fresh new GET request, or with a navigation action, and will then live as long as the enduser submits any POST form in the view to an action method which returns null or void (and thus navigates back to the same view). Once you refresh the page, or return a non-null string (even an empty string!) navigation outcome, then the view scope will end.

A @RequestScoped bean lives exactly as long a HTTP request. It will thus be garbaged by end of every request and recreated on every new request, hereby losing all changed properties.

A @ViewScoped bean is thus particularly more useful in rich Ajax-enabled views which needs to remember the (changed) view state across Ajax requests. A @RequestScoped one would be recreated on every Ajax request and thus fail to remember all changed view state. Note that a @ViewScoped bean does not share any data among different browser tabs/windows in the same session like as a @SessionScoped bean. Every view has its own unique @ViewScoped bean.

See also:

Pandas: Convert Timestamp to datetime.date

As of pandas 0.20.3, use .to_pydatetime() to convert any pandas.DateTimeIndex instances to Python datetime.datetime.

To show a new Form on click of a button in C#

This is the code that I needed. A defined user control's .show() function doesn't actually show anything. It must first be wrapped into a form like so:

CustomControl customControl = new CustomControl();
Form newForm = new Form();
newForm.Controls.Add(customControl);
newForm.ShowDialog();

Elasticsearch query to return all records

curl -XGET '{{IP/localhost}}:9200/{{Index name}}/{{type}}/_search?scroll=10m&pretty' -d '{
"query": {
"filtered": {
"query": {
"match_all": {}
}}'

Evenly distributing n points on a sphere

# create uniform spiral grid
numOfPoints = varargin[0]
vxyz = zeros((numOfPoints,3),dtype=float)
sq0 = 0.00033333333**2
sq2 = 0.9999998**2
sumsq = 2*sq0 + sq2
vxyz[numOfPoints -1] = array([(sqrt(sq0/sumsq)), 
                              (sqrt(sq0/sumsq)), 
                              (-sqrt(sq2/sumsq))])
vxyz[0] = -vxyz[numOfPoints -1] 
phi2 = sqrt(5)*0.5 + 2.5
rootCnt = sqrt(numOfPoints)
prevLongitude = 0
for index in arange(1, (numOfPoints -1), 1, dtype=float):
  zInc = (2*index)/(numOfPoints) -1
  radius = sqrt(1-zInc**2)

  longitude = phi2/(rootCnt*radius)
  longitude = longitude + prevLongitude
  while (longitude > 2*pi): 
    longitude = longitude - 2*pi

  prevLongitude = longitude
  if (longitude > pi):
    longitude = longitude - 2*pi

  latitude = arccos(zInc) - pi/2
  vxyz[index] = array([ (cos(latitude) * cos(longitude)) ,
                        (cos(latitude) * sin(longitude)), 
                        sin(latitude)])

creating array without declaring the size - java

I think what you really want is an ArrayList or Vector. Arrays in Java are not like those in Javascript.

angularjs - using {{}} binding inside ng-src but ng-src doesn't load

We can use ng-src but when ng-src's value became null, '' or undefined, ng-src will not work. So just use ng-if for this case:

http://jsfiddle.net/Hx7B9/299/

<div ng-app>
    <div ng-controller="AppCtrl"> 
        <a href='#'><img ng-src="{{link}}" ng-if="!!link"/></a>
        <button ng-click="changeLink()">Change Image</button>
    </div>
</div>

How can I execute Shell script in Jenkinsfile?

If you see your error message it says

Building in workspace /var/lib/jenkins/workspace/AutoScript

and as per your comments you have put urltest.sh in

/var/lib/jenkins

Hence Jenkins is not able to find the file. In your build step do this thing, it will work

cd             # which will point to /var/lib/jenkins
./urltest.sh   # it will run your script

If it still fails try to chown the file as jenkin user may not have file permission, but I think if you do above step you will be able to run.

Including all the jars in a directory within the Java classpath

macOS, current folder

For Java 13 on macOS Mojave

If all your .jar files are in the same folder, use cd to make that your current working directory. Verify with pwd.

For the -classpath you must first list the JAR file for your app. Using a colon character : as a delimiter, append an asterisk * to get all other JAR files within the same folder. Lastly, pass the full package name of the class with your main method.

For example, for an app in a JAR file named my_app.jar with a main method in a class named App in a package named com.example, alongside some needed jars in the same folder:

java -classpath my_app.jar:* com.example.App

How to pass IEnumerable list to controller in MVC including checkbox state?

Use a list instead and replace your foreach loop with a for loop:

@model IList<BlockedIPViewModel>

@using (Html.BeginForm()) 
{ 
    @Html.AntiForgeryToken()

    @for (var i = 0; i < Model.Count; i++) 
    {
        <tr>
            <td>
                @Html.HiddenFor(x => x[i].IP)           
                @Html.CheckBoxFor(x => x[i].Checked)
            </td>
            <td>
                @Html.DisplayFor(x => x[i].IP)
            </td>
        </tr>
    }
    <div>
        <input type="submit" value="Unblock IPs" />
    </div>
}

Alternatively you could use an editor template:

@model IEnumerable<BlockedIPViewModel>

@using (Html.BeginForm()) 
{ 
    @Html.AntiForgeryToken()
    @Html.EditorForModel()   
    <div>
        <input type="submit" value="Unblock IPs" />
    </div>
}

and then define the template ~/Views/Shared/EditorTemplates/BlockedIPViewModel.cshtml which will automatically be rendered for each element of the collection:

@model BlockedIPViewModel
<tr>
    <td>
        @Html.HiddenFor(x => x.IP)
        @Html.CheckBoxFor(x => x.Checked)
    </td>
    <td>
        @Html.DisplayFor(x => x.IP)
    </td>
</tr>

The reason you were getting null in your controller is because you didn't respect the naming convention for your input fields that the default model binder expects to successfully bind to a list. I invite you to read the following article.

Once you have read it, look at the generated HTML (and more specifically the names of the input fields) with my example and yours. Then compare and you will understand why yours doesn't work.

Merge two array of objects based on a key

You could use an arbitrary count of arrays and map on the same index new objects.

_x000D_
_x000D_
var array1 = [{ id: "abdc4051", date: "2017-01-24" }, { id: "abdc4052", date: "2017-01-22" }],_x000D_
    array2 = [{ id: "abdc4051", name: "ab" }, { id: "abdc4052", name: "abc" }],_x000D_
    result = [array1, array2].reduce((a, b) => a.map((c, i) => Object.assign({}, c, b[i])));_x000D_
    _x000D_
console.log(result);
_x000D_
.as-console-wrapper { max-height: 100% !important; top: 0; }
_x000D_
_x000D_
_x000D_

Avoid dropdown menu close on click inside

Bootstrap has solved this problem themselves in their support for <form> tags in dropdowns. Their solution is quite graspable and you can read it here: https://github.com/twbs/bootstrap/blob/v4-dev/js/src/dropdown.js

It boils down to preventing propagation at the document element and doing so only for events of type 'click.bs.dropdown.data-api' that match the selector '.dropdown .your-custom-class-for-keep-open-on-click-elements'.

Or in code

$(document).on('click.bs.dropdown.data-api', '.dropdown .keep-open-on-click', (event) => {
    event.stopPropagation();
});

java.io.StreamCorruptedException: invalid stream header: 54657374

You can't expect ObjectInputStream to automagically convert text into objects. The hexadecimal 54657374 is "Test" as text. You must be sending it directly as bytes.

Width of input type=text element

The visible width of an element is width + padding + border + outline, so it seems that you are forgetting about the border on the input element. That is, to say, that the default border width for an input element on most (some?) browsers is actually calculated as 2px, not one. Hence your input is appearing as 2px wider. Try explicitly setting the border-width on the input, or making your div wider.

MySQL WHERE IN ()

Your query translates to

SELECT * FROM table WHERE id='1' or id='2' or id='3' or id='4';

It will only return the results that match it.


One way of solving it avoiding the complexity would be, chaning the datatype to SET. Then you could use, FIND_IN_SET

SELECT * FROM table WHERE FIND_IN_SET('1', id);

How can I pretty-print JSON using node.js?

what about this?

console.table(object)

sample

Opacity CSS not working in IE8

No idea if this still applies to 8, but historically IE doesn't apply several styles to elements that don't "have layout."

see: http://www.satzansatz.de/cssd/onhavinglayout.html

How to draw a filled triangle in android canvas?

private void drawArrows(Point[] point, Canvas canvas, Paint paint) {

    float [] points  = new float[8];             
    points[0] = point[0].x;      
    points[1] = point[0].y;      
    points[2] = point[1].x;      
    points[3] = point[1].y;         
    points[4] = point[2].x;      
    points[5] = point[2].y;              
    points[6] = point[0].x;      
    points[7] = point[0].y;

    canvas.drawVertices(VertexMode.TRIANGLES, 8, points, 0, null, 0, null, 0, null, 0, 0, paint);
    Path path = new Path();
    path.moveTo(point[0].x , point[0].y);
    path.lineTo(point[1].x,point[1].y);
    path.lineTo(point[2].x,point[2].y);
    canvas.drawPath(path,paint);

}

How do I force Robocopy to overwrite files?

This is really weird, why nobody is mentioning the /IM switch ?! I've been using it for a long time in backup jobs. But I tried googling just now and I couldn't land on a single web page that says anything about it even on MS website !!! Also found so many user posts complaining about the same issue!!

Anyway.. to use Robocopy to overwrite EVERYTHING what ever size or time in source or distination you must include these three switches in your command (/IS /IT /IM)

/IS :: Include Same files. (Includes same size files)
/IT :: Include Tweaked files. (Includes same files with different Attributes)
/IM :: Include Modified files (Includes same files with different times).

This is the exact command I use to transfer few TeraBytes of mostly 1GB+ files (ISOs - Disk Images - 4K Videos):

robocopy B:\Source D:\Destination /E /J /COPYALL /MT:1 /DCOPY:DATE /IS /IT /IM /X /V /NP /LOG:A:\ROBOCOPY.LOG

I did a small test for you .. and here is the result:

               Total    Copied   Skipped  Mismatch    FAILED    Extras
    Dirs :      1028      1028         0         0         0       169
   Files :      8053      8053         0         0         0         1
   Bytes : 649.666 g 649.666 g         0         0         0   1.707 g
   Times :   2:46:53   0:41:43                       0:00:00   0:41:44


   Speed :           278653398 Bytes/sec.
   Speed :           15944.675 MegaBytes/min.
   Ended : Friday, August 21, 2020 7:34:33 AM

Dest, Disk: WD Gold 6TB (Compare the write speed with my result)

Even with those "Extras", that's for reporting only because of the "/X" switch. As you can see nothing was Skipped and Total number and size of all files are equal to the Copied. Sometimes It will show small number of skipped files when I abuse it and cancel it multiple times during operation but even with that the values in the first 2 columns are always Equal. I also confirmed that once before by running a PowerShell script that scans all files in destination and generate a report of all time-stamps.

Some performance tips from my history with it and so many tests & troubles!:

. Despite of what most users online advise to use maximum threads "/MT:128" like it's a general trick to get the best performance ... PLEASE DON'T USE "/MT:128" WITH VERY LARGE FILES ... that's a big mistake and it will decrease your drive performance dramatically after several runs .. it will create very high fragmentation or even cause the files system to fail in some cases and you end up spending valuable time trying to recover a RAW partition and all that nonsense. And above all that, It will perform 4-6 times slower!!

For very large files:

  1. Use Only "One" thread "/MT:1" | Impact: BIG
  2. Must use "/J" to disable buffering. | Impact: High
  3. Use "/NP" with "/LOG:file" and Don't output to the console by "/TEE" | Impact: Medium.
  4. Put the "/LOG:file" on a separate drive from the source or destination | Impact: Low.

For regular big files:

  1. Use multi threads, I would not exceed "/MT:4" | Impact: BIG
  2. IF destination disk has low Cache specs use "/J" to disable buffering | Impact: High
  3. & 4 same as above.

For thousands of tiny files:

  1. Go nuts :) with Multi threads, at first I would start with 16 and multibly by 2 while monitoring the disk performance. Once it starts dropping I'll fall back to the prevouse value and stik with it | Impact: BIG
  2. Don't use "/J" | Impact: High
  3. Use "/NP" with "/LOG:file" and Don't output to the console by "/TEE" | Impact: HIGH.
  4. Put the "/LOG:file" on a separate drive from the source or destination | Impact: HIGH.

Adding Jar files to IntellijIdea classpath

On the Mac version I was getting the error when trying to run JSON-Clojure.json.clj, which is the script to export a database table to JSON. To get it to work I had to download the latest Clojure JAR from http://clojure.org/ and then right-click on PHPStorm app in the Finder and "Show Package Contents". Then go to Contents in there. Then open the lib folder, and see a bunch of .jar files. Copy the clojure-1.8.0.jar file from the unzipped archive I downloaded from clojure.org into the aforementioned lib folder inside the PHPStorm.app/Contents/lib. Restart the app. Now it freaking works.

EDIT: You also have to put the JSR-223 script engine into PHPStorm.app/Contents/lib. It can be built from https://github.com/ato/clojure-jsr223 or downloaded from https://www.dropbox.com/s/jg7s0c41t5ceu7o/clojure-jsr223-1.5.1.jar?dl=0 .

OraOLEDB.Oracle provider is not registered on the local machine

It only worked for me after I changed the 'Platform target' to 'x64' (considering I'm using Oracle 12c 64 bits)

To do that, I did:

  1. Right click on the project name (at the Solution Explorer panel locate, in general, at the left)

  2. Clicked on 'Build' (in the new opened window)

  3. Changed the 'Platform target' from 'Any CPU' to 'x64'

That solved the problem.

Creating for loop until list.length

You could learn about Python loops here: http://en.wikibooks.org/wiki/Python_Programming/Loops

You have to know that Python doesn't have { and } for start and end of loop, instead it depends on tab chars you enter in first of line, I mean line indents.

So you can do loop inside loop with double tab (indent)

An example of double loop is like this:

onetoten = range(1,11)
tentotwenty = range(10,21)
for count in onetoten:
    for count2 in tentotwenty
        print(count2)

Converting String Array to an Integer Array

Line by line

int [] v = Stream.of(line.split(",\\s+"))
  .mapToInt(Integer::parseInt)
  .toArray();

How to check if memcache or memcached is installed for PHP?

It may be relevant to see if it's running in PHP via command line as well-

<path-to-php-binary>php -i | grep memcache

How to do a FULL OUTER JOIN in MySQL?

Answer:

SELECT * FROM t1 FULL OUTER JOIN t2 ON t1.id = t2.id;

Can be recreated as follows:

 SELECT t1.*, t2.* 
 FROM (SELECT * FROM t1 UNION SELECT name FROM t2) tmp
 LEFT JOIN t1 ON t1.id = tmp.id
 LEFT JOIN t2 ON t2.id = tmp.id;

Using a UNION or UNION ALL answer does not cover the edge case where the base tables have duplicated entries.

Explanation:

There is an edge case that a UNION or UNION ALL cannot cover. We cannot test this on mysql as it doesn't support FULL OUTER JOINs, but we can illustrate this on a database that does support it:

 WITH cte_t1 AS
 (
       SELECT 1 AS id1
       UNION ALL SELECT 2
       UNION ALL SELECT 5
       UNION ALL SELECT 6
       UNION ALL SELECT 6
 ),
cte_t2 AS
(
      SELECT 3 AS id2
      UNION ALL SELECT 4
      UNION ALL SELECT 5
      UNION ALL SELECT 6
      UNION ALL SELECT 6
)
SELECT  *  FROM  cte_t1 t1 FULL OUTER JOIN cte_t2 t2 ON t1.id1 = t2.id2;

This gives us this answer:

id1  id2
1  NULL
2  NULL
NULL  3
NULL  4
5  5
6  6
6  6
6  6
6  6

The UNION solution:

SELECT  * FROM  cte_t1 t1 LEFT OUTER JOIN cte_t2 t2 ON t1.id1 = t2.id2
UNION    
SELECT  * FROM cte_t1 t1 RIGHT OUTER JOIN cte_t2 t2 ON t1.id1 = t2.id2

Gives an incorrect answer:

 id1  id2
NULL  3
NULL  4
1  NULL
2  NULL
5  5
6  6

The UNION ALL solution:

SELECT  * FROM cte_t1 t1 LEFT OUTER join cte_t2 t2 ON t1.id1 = t2.id2
UNION ALL
SELECT  * FROM  cte_t1 t1 RIGHT OUTER JOIN cte_t2 t2 ON t1.id1 = t2.id2

Is also incorrect.

id1  id2
1  NULL
2  NULL
5  5
6  6
6  6
6  6
6  6
NULL  3
NULL  4
5  5
6  6
6  6
6  6
6  6

Whereas this query:

SELECT t1.*, t2.*
FROM (SELECT * FROM t1 UNION SELECT name FROM t2) tmp 
LEFT JOIN t1 ON t1.id = tmp.id 
LEFT JOIN t2 ON t2.id = tmp.id;

Gives the following:

id1  id2
1  NULL
2  NULL
NULL  3
NULL  4
5  5
6  6
6  6
6  6
6  6

The order is different, but otherwise matches the correct answer.

How to do a background for a label will be without color?

this.label1.BackColor = System.Drawing.Color.Transparent;

2 column div layout: right column with fixed width, left fluid

Remove the float on the left column.

At the HTML code, the right column needs to come before the left one.

If the right has a float (and a width), and if the left column doesn't have a width and no float, it will be flexible :)

Also apply an overflow: hidden and some height (can be auto) to the outer div, so that it surrounds both inner divs.

Finally, at the left column, add a width: auto and overflow: hidden, this makes the left column independent from the right one (for example, if you resized the browser window, and the right column touched the left one, without these properties, the left column would run arround the right one, with this properties it remains in its space).

Example HTML:

<div class="container">
    <div class="right">
        right content fixed width
    </div>
    <div class="left">
        left content flexible width
    </div>
</div>

CSS:

.container {
   height: auto;
   overflow: hidden;
}

.right {
    width: 180px;
    float: right;
    background: #aafed6;
}

.left {
    float: none; /* not needed, just for clarification */
    background: #e8f6fe;
    /* the next props are meant to keep this block independent from the other floated one */
    width: auto;
    overflow: hidden;
}??

Example here: http://jsfiddle.net/jackJoe/fxWg7/

How to compile multiple java source files in command line

OR you could just use javac file1.java and then also use javac file2.java afterwards.

Nginx subdomain configuration

You could move the common parts to another configuration file and include from both server contexts. This should work:

server {
  listen 80;
  server_name server1.example;
  ...
  include /etc/nginx/include.d/your-common-stuff.conf;
}

server {
  listen 80;
  server_name another-one.example;
  ...
  include /etc/nginx/include.d/your-common-stuff.conf;
}

Edit: Here's an example that's actually copied from my running server. I configure my basic server settings in /etc/nginx/sites-enabled (normal stuff for nginx on Ubuntu/Debian). For example, my main server bunkus.org's configuration file is /etc/nginx/sites-enabled and it looks like this:

server {
  listen   80 default_server;
  listen   [2a01:4f8:120:3105::101:1]:80 default_server;

  include /etc/nginx/include.d/all-common;
  include /etc/nginx/include.d/bunkus.org-common;
  include /etc/nginx/include.d/bunkus.org-80;
}

server {
  listen   443 default_server;
  listen   [2a01:4f8:120:3105::101:1]:443 default_server;

  include /etc/nginx/include.d/all-common;
  include /etc/nginx/include.d/ssl-common;
  include /etc/nginx/include.d/bunkus.org-common;
  include /etc/nginx/include.d/bunkus.org-443;
}

As an example here's the /etc/nginx/include.d/all-common file that's included from both server contexts:

index index.html index.htm index.php .dirindex.php;
try_files $uri $uri/ =404;

location ~ /\.ht {
  deny all;
}

location = /favicon.ico {
  log_not_found off;
  access_log off;
}

location ~ /(README|ChangeLog)$ {
  types { }
  default_type text/plain;
}

Performing a Stress Test on Web Application?

One more note, for our web application, I found that we had huge performance issues due to contention between threads over locks... so the moral was to think over the locking scheme very carefully. We ended up having worker threads to throttle too many requests using an asynchronous http handler, otherwise the application would just get overwhelmed and crash and burn. It meant a huge backlog could pile up, but at least the site would stay up.

How do I include a JavaScript file in another JavaScript file?

Don't forget to check out LAB.js!

<script type="text/javascript">
       $LAB
       .script("jquery-1.8.3.js").wait()
       .script("scripts/clientscript.js");      
</script>

Resolving instances with ASP.NET Core DI from within ConfigureServices

I know this is an old question but I'm astonished that a rather obvious and disgusting hack isn't here.

You can exploit the ability to define your own ctor function to grab necessary values out of your services as you define them... obviously this would be ran every time the service was requested unless you explicitly remove/clear and re-add the definition of this service within the first construction of the exploiting ctor.

This method has the advantage of not requiring you to build the service tree, or use it, during the configuration of the service. You are still defining how services will be configured.

public void ConfigureServices(IServiceCollection services)
{
    //Prey this doesn't get GC'd or promote to a static class var
    string? somevalue = null;

    services.AddSingleton<IServiceINeedToUse, ServiceINeedToUse>(scope => {
         //create service you need
         var service = new ServiceINeedToUse(scope.GetService<IDependantService>())
         //get the values you need
         somevalue = somevalue ?? service.MyDirtyHack();
         //return the instance
         return service;
    });
    services.AddTransient<IOtherService, OtherService>(scope => {
         //Explicitly ensuring the ctor function above is called, and also showcasing why this is an anti-pattern.
         scope.GetService<IServiceINeedToUse>();
         //TODO: Clean up both the IServiceINeedToUse and IOtherService configuration here, then somehow rebuild the service tree.
         //Wow!
         return new OtherService(somevalue);
    });
}

The way to fix this pattern would be to give OtherService an explicit dependency on IServiceINeedToUse, rather than either implicitly depending on it or its method's return value... or resolving that dependency explicitly in some other fashion.

Why does the JFrame setSize() method not set the size correctly?

On OS X, you need to take into account existing window decorations. They add 22 pixels to the height. So on a JFrame, you need to tell the program this:

frame.setSize(width, height + 22);

What is difference between sjlj vs dwarf vs seh?

There's a short overview at MinGW-w64 Wiki:

Why doesn't mingw-w64 gcc support Dwarf-2 Exception Handling?

The Dwarf-2 EH implementation for Windows is not designed at all to work under 64-bit Windows applications. In win32 mode, the exception unwind handler cannot propagate through non-dw2 aware code, this means that any exception going through any non-dw2 aware "foreign frames" code will fail, including Windows system DLLs and DLLs built with Visual Studio. Dwarf-2 unwinding code in gcc inspects the x86 unwinding assembly and is unable to proceed without other dwarf-2 unwind information.

The SetJump LongJump method of exception handling works for most cases on both win32 and win64, except for general protection faults. Structured exception handling support in gcc is being developed to overcome the weaknesses of dw2 and sjlj. On win64, the unwind-information are placed in xdata-section and there is the .pdata (function descriptor table) instead of the stack. For win32, the chain of handlers are on stack and need to be saved/restored by real executed code.

GCC GNU about Exception Handling:

GCC supports two methods for exception handling (EH):

  • DWARF-2 (DW2) EH, which requires the use of DWARF-2 (or DWARF-3) debugging information. DW-2 EH can cause executables to be slightly bloated because large call stack unwinding tables have to be included in th executables.
  • A method based on setjmp/longjmp (SJLJ). SJLJ-based EH is much slower than DW2 EH (penalising even normal execution when no exceptions are thrown), but can work across code that has not been compiled with GCC or that does not have call-stack unwinding information.

[...]

Structured Exception Handling (SEH)

Windows uses its own exception handling mechanism known as Structured Exception Handling (SEH). [...] Unfortunately, GCC does not support SEH yet. [...]

See also:

How can I remove a pytz timezone from a datetime object?

To remove a timezone (tzinfo) from a datetime object:

# dt_tz is a datetime.datetime object
dt = dt_tz.replace(tzinfo=None)

If you are using a library like arrow, then you can remove timezone by simply converting an arrow object to to a datetime object, then doing the same thing as the example above.

# <Arrow [2014-10-09T10:56:09.347444-07:00]>
arrowObj = arrow.get('2014-10-09T10:56:09.347444-07:00')

# datetime.datetime(2014, 10, 9, 10, 56, 9, 347444, tzinfo=tzoffset(None, -25200))
tmpDatetime = arrowObj.datetime

# datetime.datetime(2014, 10, 9, 10, 56, 9, 347444)
tmpDatetime = tmpDatetime.replace(tzinfo=None)

Why would you do this? One example is that mysql does not support timezones with its DATETIME type. So using ORM's like sqlalchemy will simply remove the timezone when you give it a datetime.datetime object to insert into the database. The solution is to convert your datetime.datetime object to UTC (so everything in your database is UTC since it can't specify timezone) then either insert it into the database (where the timezone is removed anyway) or remove it yourself. Also note that you cannot compare datetime.datetime objects where one is timezone aware and another is timezone naive.

##############################################################################
# MySQL example! where MySQL doesn't support timezones with its DATETIME type!
##############################################################################

arrowObj = arrow.get('2014-10-09T10:56:09.347444-07:00')

arrowDt = arrowObj.to("utc").datetime

# inserts datetime.datetime(2014, 10, 9, 17, 56, 9, 347444, tzinfo=tzutc())
insertIntoMysqlDatabase(arrowDt)

# returns datetime.datetime(2014, 10, 9, 17, 56, 9, 347444)
dbDatetimeNoTz = getFromMysqlDatabase()

# cannot compare timzeone aware and timezone naive
dbDatetimeNoTz == arrowDt # False, or TypeError on python versions before 3.3

# compare datetimes that are both aware or both naive work however
dbDatetimeNoTz == arrowDt.replace(tzinfo=None) # True

How many characters in varchar(max)

For future readers who need this answer quickly:

2^31-1 = 2.147.483.647 characters

How to convert this var string to URL in Swift

In Swift3:
let fileUrl = Foundation.URL(string: filePath)

How to properly ignore exceptions

When you just want to do a try catch without handling the exception, how do you do it in Python?

This will help you to print what the exception is:( i.e. try catch without handling the exception and print the exception.)

import sys
try:
    doSomething()
except:
    print "Unexpected error:", sys.exc_info()[0]

Why is using "for...in" for array iteration a bad idea?

The reason is that one construct:

_x000D_
_x000D_
var a = []; // Create a new empty array._x000D_
a[5] = 5;   // Perfectly legal JavaScript that resizes the array._x000D_
_x000D_
for (var i = 0; i < a.length; i++) {_x000D_
    // Iterate over numeric indexes from 0 to 5, as everyone expects._x000D_
    console.log(a[i]);_x000D_
}_x000D_
_x000D_
/* Will display:_x000D_
   undefined_x000D_
   undefined_x000D_
   undefined_x000D_
   undefined_x000D_
   undefined_x000D_
   5_x000D_
*/
_x000D_
_x000D_
_x000D_

can sometimes be totally different from the other:

_x000D_
_x000D_
var a = [];_x000D_
a[5] = 5;_x000D_
for (var x in a) {_x000D_
    // Shows only the explicitly set index of "5", and ignores 0-4_x000D_
    console.log(x);_x000D_
}_x000D_
_x000D_
/* Will display:_x000D_
   5_x000D_
*/
_x000D_
_x000D_
_x000D_

Also consider that JavaScript libraries might do things like this, which will affect any array you create:

_x000D_
_x000D_
// Somewhere deep in your JavaScript library..._x000D_
Array.prototype.foo = 1;_x000D_
_x000D_
// Now you have no idea what the below code will do._x000D_
var a = [1, 2, 3, 4, 5];_x000D_
for (var x in a){_x000D_
    // Now foo is a part of EVERY array and _x000D_
    // will show up here as a value of 'x'._x000D_
    console.log(x);_x000D_
}_x000D_
_x000D_
/* Will display:_x000D_
   0_x000D_
   1_x000D_
   2_x000D_
   3_x000D_
   4_x000D_
   foo_x000D_
*/
_x000D_
_x000D_
_x000D_

Can a WSDL indicate the SOAP version (1.1 or 1.2) of the web service?

Found transport-attribute in binding-element which tells us that this is the WSDL 1.1 binding for the SOAP 1.1 HTTP binding.

ex.

<wsdlsoap:binding style="document" transport="http://schemas.xmlsoap.org/soap/http"/>

Styling a disabled input with css only

Use this CSS (jsFiddle example):

input:disabled.btn:hover,
input:disabled.btn:active,
input:disabled.btn:focus {
  color: green
}

You have to write the most outer element on the left and the most inner element on the right.

.btn:hover input:disabled would select any disabled input elements contained in an element with a class btn which is currently hovered by the user.

I would prefer :disabled over [disabled], see this question for a discussion: Should I use CSS :disabled pseudo-class or [disabled] attribute selector or is it a matter of opinion?


By the way, Laravel (PHP) generates the HTML - not the browser.

Disable a Button

The button can be Disabled in Swift 4 by the code

@IBAction func yourButtonMethodname(sender: UIButon) {
 yourButton.isEnabled = false 
}

Reverse colormap in matplotlib

The solution is pretty straightforward. Suppose you want to use the "autumn" colormap scheme. The standard version:

cmap = matplotlib.cm.autumn

To reverse the colormap color spectrum, use get_cmap() function and append '_r' to the colormap title like this:

cmap_reversed = matplotlib.cm.get_cmap('autumn_r')

Draggable div without jQuery UI

Here's my contribution:

http://jsfiddle.net/g6m5t8co/1/

<!doctype html>
<html>
    <head>
        <style>
            #container {
                position:absolute;
                background-color: blue;
                }
            #elem{
                position: absolute;
                background-color: green;
                -webkit-user-select: none;
                -moz-user-select: none;
                -o-user-select: none;
                -ms-user-select: none;
                -khtml-user-select: none;     
                user-select: none;
            }
        </style>
        <script>
            var mydragg = function(){
                return {
                    move : function(divid,xpos,ypos){
                        divid.style.left = xpos + 'px';
                        divid.style.top = ypos + 'px';
                    },
                    startMoving : function(divid,container,evt){
                        evt = evt || window.event;
                        var posX = evt.clientX,
                            posY = evt.clientY,
                        divTop = divid.style.top,
                        divLeft = divid.style.left,
                        eWi = parseInt(divid.style.width),
                        eHe = parseInt(divid.style.height),
                        cWi = parseInt(document.getElementById(container).style.width),
                        cHe = parseInt(document.getElementById(container).style.height);
                        document.getElementById(container).style.cursor='move';
                        divTop = divTop.replace('px','');
                        divLeft = divLeft.replace('px','');
                        var diffX = posX - divLeft,
                            diffY = posY - divTop;
                        document.onmousemove = function(evt){
                            evt = evt || window.event;
                            var posX = evt.clientX,
                                posY = evt.clientY,
                                aX = posX - diffX,
                                aY = posY - diffY;
                                if (aX < 0) aX = 0;
                                if (aY < 0) aY = 0;
                                if (aX + eWi > cWi) aX = cWi - eWi;
                                if (aY + eHe > cHe) aY = cHe -eHe;
                            mydragg.move(divid,aX,aY);
                        }
                    },
                    stopMoving : function(container){
                        var a = document.createElement('script');
                        document.getElementById(container).style.cursor='default';
                        document.onmousemove = function(){}
                    },
                }
            }();

        </script>
    </head>
    <body>
        <div id='container' style="width: 600px;height: 400px;top:50px;left:50px;">     
            <div id="elem" onmousedown='mydragg.startMoving(this,"container",event);' onmouseup='mydragg.stopMoving("container");' style="width: 200px;height: 100px;">
                <div style='width:100%;height:100%;padding:10px'>
                <select id=test>
                    <option value=1>first
                    <option value=2>second
                </select>
                <INPUT TYPE=text value="123">
                </div>
            </div>
        </div>  
    </body>
</html>

Difference between Date(dateString) and new Date(dateString)

The following format works in all browsers:

new Date("2010/08/17 12:09:36");

So, to make a yyyy-mm-dd hh:mm:ss formatted date string fully browser compatible you would have to replace dashes with slashes:

var dateString = "2010-08-17 12:09:36";
new Date(dateString.replace(/-/g, "/"));

What's the difference between all the Selection Segues?

The document has moved here it seems: https://help.apple.com/xcode/mac/8.0/#/dev564169bb1

Can't copy the icons here, but here are the descriptions:

  • Show: Present the content in the detail or master area depending on the content of the screen.

    If the app is displaying a master and detail view, the content is pushed onto the detail area. If the app is only displaying the master or the detail, the content is pushed on top of the current view controller stack.

  • Show Detail: Present the content in the detail area.

    If the app is displaying a master and detail view, the new content replaces the current detail. If the app is only displaying the master or the detail, the content replaces the top of the current view controller stack.

  • Present Modally: Present the content modally.

  • Present as Popover: Present the content as a popover anchored to an existing view.

  • Custom: Create your own behaviors by using a custom segue.

How can I find the dimensions of a matrix in Python?

You simply can find a matrix dimension by using Numpy:

import numpy as np

x = np.arange(24).reshape((6, 4))
x.ndim

output will be:

2

It means this matrix is a 2 dimensional matrix.

x.shape

Will show you the size of each dimension. The shape for x is equal to:

(6, 4)

What are C++ functors and their uses?

To add on, I have used function objects to fit an existing legacy method to the command pattern; (only place where the beauty of OO paradigm true OCP I felt ); Also adding here the related function adapter pattern.

Suppose your method has the signature:

int CTask::ThreeParameterTask(int par1, int par2, int par3)

We will see how we can fit it for the Command pattern - for this, first, you have to write a member function adapter so that it can be called as a function object.

Note - this is ugly, and may be you can use the Boost bind helpers etc., but if you can't or don't want to, this is one way.

// a template class for converting a member function of the type int        function(int,int,int)
//to be called as a function object
template<typename _Ret,typename _Class,typename _arg1,typename _arg2,typename _arg3>
class mem_fun3_t
{
  public:
explicit mem_fun3_t(_Ret (_Class::*_Pm)(_arg1,_arg2,_arg3))
    :m_Ptr(_Pm) //okay here we store the member function pointer for later use
    {}

//this operator call comes from the bind method
_Ret operator()(_Class *_P, _arg1 arg1, _arg2 arg2, _arg3 arg3) const
{
    return ((_P->*m_Ptr)(arg1,arg2,arg3));
}
private:
_Ret (_Class::*m_Ptr)(_arg1,_arg2,_arg3);// method pointer signature
};

Also, we need a helper method mem_fun3 for the above class to aid in calling.

template<typename _Ret,typename _Class,typename _arg1,typename _arg2,typename _arg3>
mem_fun3_t<_Ret,_Class,_arg1,_arg2,_arg3> mem_fun3 ( _Ret (_Class::*_Pm)          (_arg1,_arg2,_arg3) )
{
  return (mem_fun3_t<_Ret,_Class,_arg1,_arg2,_arg3>(_Pm));
}

Now, in order to bind the parameters, we have to write a binder function. So, here it goes:

template<typename _Func,typename _Ptr,typename _arg1,typename _arg2,typename _arg3>
class binder3
{
public:
//This is the constructor that does the binding part
binder3(_Func fn,_Ptr ptr,_arg1 i,_arg2 j,_arg3 k)
    :m_ptr(ptr),m_fn(fn),m1(i),m2(j),m3(k){}

 //and this is the function object 
 void operator()() const
 {
        m_fn(m_ptr,m1,m2,m3);//that calls the operator
    }
private:
    _Ptr m_ptr;
    _Func m_fn;
    _arg1 m1; _arg2 m2; _arg3 m3;
};

And, a helper function to use the binder3 class - bind3:

//a helper function to call binder3
template <typename _Func, typename _P1,typename _arg1,typename _arg2,typename _arg3>
binder3<_Func, _P1, _arg1, _arg2, _arg3> bind3(_Func func, _P1 p1,_arg1 i,_arg2 j,_arg3 k)
{
    return binder3<_Func, _P1, _arg1, _arg2, _arg3> (func, p1,i,j,k);
}

Now, we have to use this with the Command class; use the following typedef:

typedef binder3<mem_fun3_t<int,T,int,int,int> ,T* ,int,int,int> F3;
//and change the signature of the ctor
//just to illustrate the usage with a method signature taking more than one parameter
explicit Command(T* pObj,F3* p_method,long timeout,const char* key,
long priority = PRIO_NORMAL ):
m_objptr(pObj),m_timeout(timeout),m_key(key),m_value(priority),method1(0),method0(0),
method(0)
{
    method3 = p_method;
}

Here is how you call it:

F3 f3 = PluginThreadPool::bind3( PluginThreadPool::mem_fun3( 
      &CTask::ThreeParameterTask), task1,2122,23 );

Note: f3(); will call the method task1->ThreeParameterTask(21,22,23);.

The full context of this pattern at the following link

Does Hive have a String split function?

There does exist a split function based on regular expressions. It's not listed in the tutorial, but it is listed on the language manual on the wiki:

split(string str, string pat)
   Split str around pat (pat is a regular expression) 

In your case, the delimiter "|" has a special meaning as a regular expression, so it should be referred to as "\\|".

Catching errors in Angular HttpClient

If you find yourself unable to catch errors with any of the solutions provided here, it may be that the server isn't handling CORS requests.

In that event, Javascript, much less Angular, can access the error information.

Look for warnings in your console that include CORB or Cross-Origin Read Blocking.

Also, the syntax has changed for handling errors (as described in every other answer). You now use pipe-able operators, like so:

this.service.requestsMyInfo(payload).pipe(
    catcheError(err => {
        // handle the error here.
    })
);

How can I compare two dates in PHP?

If you want a date ($date) to get expired in some interval for example a token expiration date when performing a password reset, here's how you can do:

$date = $row->expireDate;

$date->add(new DateInterval('PT24H')); // adds 24 hours

$now = new \DateTime();

if($now < $date) { /* expired after 24 hours */ }

But in your case you could do the comparison just as the following:

$today = new DateTime('Y-m-d');

$date = $row->expireDate;

if($today < $date) { /* do something */ }

python inserting variable string as file name

Even better are f-strings in python 3!

f = open(f'{name}.csv', 'wb')

Getting request doesn't pass access control check: No 'Access-Control-Allow-Origin' header is present on the requested resource

In case of Request to a REST Service:

You need to allow the CORS (cross origin sharing of resources) on the endpoint of your REST Service with Spring annotation:

@CrossOrigin(origins = "http://localhost:8080")

Very good tutorial: https://spring.io/guides/gs/rest-service-cors/

How to select date without time in SQL

First Convert the date to float (which displays the numeric), then ROUND the numeric to 0 decimal points, then convert that to datetime.

convert(datetime,round(convert(float,orderdate,101),0) ,101)

What do numbers using 0x notation mean?

In C and languages based on the C syntax, the prefix 0x means hexadecimal (base 16).

Thus, 0x400 = 4×(162) + 0×(161) + 0×(160) = 4×((24)2) = 22 × 28 = 210 = 1024, or one binary K.

And so 0x6400 = 0x4000 + 0x2400 = 0x19×0x400 = 25K

How to dynamically build a JSON object with Python?

All previous answers are correct, here is one more and easy way to do it. For example, create a Dict data structure to serialize and deserialize an object

(Notice None is Null in python and I'm intentionally using this to demonstrate how you can store null and convert it to json null)

import json
print('serialization')
myDictObj = { "name":"John", "age":30, "car":None }
##convert object to json
serialized= json.dumps(myDictObj, sort_keys=True, indent=3)
print(serialized)
## now we are gonna convert json to object
deserialization=json.loads(serialized)
print(deserialization)

enter image description here

Objective-C ARC: strong vs retain and weak vs assign

To understand Strong and Weak reference consider below example, suppose we have method named as displayLocalVariable.

 -(void)displayLocalVariable
  {
     NSString myName = @"ABC";
     NSLog(@"My name is = %@", myName);
  }

In above method scope of myName variable is limited to displayLocalVariable method, once the method gets finished myName variable which is holding the string "ABC" will get deallocated from the memory.

Now what if we want to hold the myName variable value throughout our view controller life cycle. For this we can create the property named as username which will have Strong reference to the variable myName(see self.username = myName; in below code), as below,

@interface LoginViewController ()

@property(nonatomic,strong) NSString* username;
@property(nonatomic,weak) NSString* dummyName;

- (void)displayLocalVariable;

@end

@implementation LoginViewController

- (void)viewDidLoad
{
    [super viewDidLoad];

}

-(void)viewWillAppear:(BOOL)animated
{
     [self displayLocalVariable];
}

- (void)displayLocalVariable
{
   NSString myName = @"ABC";
   NSLog(@"My name is = %@", myName);
   self.username = myName;
}

- (void)didReceiveMemoryWarning
{
    [super didReceiveMemoryWarning];
}


@end

Now in above code you can see myName has been assigned to self.username and self.username is having a strong reference(as we declared in interface using @property) to myName(indirectly it's having Strong reference to "ABC" string). Hence String myName will not get deallocated from memory till self.username is alive.

  • Weak reference

Now consider assigning myName to dummyName which is a Weak reference, self.dummyName = myName; Unlike Strong reference Weak will hold the myName only till there is Strong reference to myName. See below code to understand Weak reference,

-(void)displayLocalVariable
  {
     NSString myName = @"ABC";
     NSLog(@"My name is = %@", myName);
     self.dummyName = myName;
  }

In above code there is Weak reference to myName(i.e. self.dummyName is having Weak reference to myName) but there is no Strong reference to myName, hence self.dummyName will not be able to hold the myName value.

Now again consider the below code,

-(void)displayLocalVariable
      {
         NSString myName = @"ABC";
         NSLog(@"My name is = %@", myName);
         self.username = myName;
         self.dummyName = myName;
      } 

In above code self.username has a Strong reference to myName, hence self.dummyName will now have a value of myName even after method ends since myName has a Strong reference associated with it.

Now whenever we make a Strong reference to a variable it's retain count get increased by one and the variable will not get deallocated retain count reaches to 0.

Hope this helps.

How to prevent SIGPIPEs (or handle them properly)

Under a modern POSIX system (i.e. Linux), you can use the sigprocmask() function.

#include <signal.h>

void block_signal(int signal_to_block /* i.e. SIGPIPE */ )
{
    sigset_t set;
    sigset_t old_state;

    // get the current state
    //
    sigprocmask(SIG_BLOCK, NULL, &old_state);

    // add signal_to_block to that existing state
    //
    set = old_state;
    sigaddset(&set, signal_to_block);

    // block that signal also
    //
    sigprocmask(SIG_BLOCK, &set, NULL);

    // ... deal with old_state if required ...
}

If you want to restore the previous state later, make sure to save the old_state somewhere safe. If you call that function multiple times, you need to either use a stack or only save the first or last old_state... or maybe have a function which removes a specific blocked signal.

For more info read the man page.

How can I shuffle the lines of a text file on the Unix command line or in a shell script?

I use a tiny perl script, which I call "unsort":

#!/usr/bin/perl
use List::Util 'shuffle';
@list = <STDIN>;
print shuffle(@list);

I've also got a NULL-delimited version, called "unsort0" ... handy for use with find -print0 and so on.

PS: Voted up 'shuf' too, I had no idea that was there in coreutils these days ... the above may still be useful if your systems doesn't have 'shuf'.

C++ pointer to objects

if you want the object on the stack, try this:

MyClass myclass;
myclass.DoSomething();

If you need a pointer to that object:

MyClass* myclassptr = &myclass;
myclassptr->DoSomething();

Base64 encoding and decoding in client-side Javascript

I'd rather use the bas64 encode/decode methods from CryptoJS, the most popular library for standard and secure cryptographic algorithms implemented in JavaScript using best practices and patterns.

How to get to a particular element in a List in java?

CSVReader reader = new CSVReader(new FileReader(
                "myfile.csv"));
        try {
            List<String[]> myEntries = reader.readAll();
            for (String[] s : myEntries) {
               for(String ss : s) {
                   System.out.print(", " + ss);
               }

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

A SQL Query to select a string between two known strings

I had a similar need to parse out a set of parameters stored within an IIS logs' csUriQuery field, which looked like this: id=3598308&user=AD\user&parameter=1&listing=No needed in this format.

I ended up creating a User-defined function to accomplish a string between, with the following assumptions:

  1. If the starting occurrence is not found, a NULL is returned, and
  2. If the ending occurrence is not found, the rest of the string is returned

Here's the code:

CREATE FUNCTION dbo.str_between(@col varchar(max), @start varchar(50), @end varchar(50))  
  RETURNS varchar(max)  
  WITH EXECUTE AS CALLER  
AS  
BEGIN  
  RETURN substring(@col, charindex(@start, @col) + len(@start), 
         isnull(nullif(charindex(@end, stuff(@col, 1, charindex(@start, @col)-1, '')),0),
         len(stuff(@col, 1, charindex(@start, @col)-1, ''))+1) - len(@start)-1);
END;  
GO

For the above question, the usage is as follows:

DECLARE @a VARCHAR(MAX) = 'All I knew was that the dog had been very bad and required harsh punishment immediately regardless of what anyone else thought.'
SELECT dbo.str_between(@a, 'the dog', 'immediately')
-- Yields' had been very bad and required harsh punishment '

How do I get a class instance of generic type T?

A standard approach/workaround/solution is to add a class object to the constructor(s), like:

 public class Foo<T> {

    private Class<T> type;
    public Foo(Class<T> type) {
      this.type = type;
    }

    public Class<T> getType() {
      return type;
    }

    public T newInstance() {
      return type.newInstance();
    }
 }

How do I empty an array in JavaScript?

If you use constants then you have no choice:

const numbers = [1, 2, 3]

You can not reasign:

numbers = []

You can only truncate:

numbers.length = 0

Escape Character in SQL Server

You can escape quotation like this:

select 'it''s escaped'

result will be

it's escaped

Import CSV to mysql table

Here's a simple PHP command line script that will do what you need:

<?php

$host = 'localhost';
$user = 'root';
$pass = '';
$database = 'database';

$db = mysql_connect($host, $user, $pass);
mysql_query("use $database", $db);

/********************************************************************************/
// Parameters: filename.csv table_name

$argv = $_SERVER[argv];

if($argv[1]) { $file = $argv[1]; }
else {
    echo "Please provide a file name\n"; exit; 
}
if($argv[2]) { $table = $argv[2]; }
else {
    $table = pathinfo($file);
    $table = $table['filename'];
}

/********************************************************************************/
// Get the first row to create the column headings

$fp = fopen($file, 'r');
$frow = fgetcsv($fp);

foreach($frow as $column) {
    if($columns) $columns .= ', ';
    $columns .= "`$column` varchar(250)";
}

$create = "create table if not exists $table ($columns);";
mysql_query($create, $db);

/********************************************************************************/
// Import the data into the newly created table.

$file = $_SERVER['PWD'].'/'.$file;
$q = "load data infile '$file' into table $table fields terminated by ',' ignore 1 lines";
mysql_query($q, $db);

?>

It will create a table based on the first row and import the remaining rows into it. Here is the command line syntax:

php csv_import.php csv_file.csv table_name

How can I make a link from a <td> table cell

Here is my solution:

<td>
   <a href="/yourURL"></a>
   <div class="item-container">
      <img class="icon" src="/iconURL" />
      <p class="name">
         SomeText
      </p>
   </div>
</td>

(LESS)

td {
  padding: 1%;
  vertical-align: bottom;
  position:relative;

     a {
        height: 100%;
        display: block;
        position: absolute;
        top:0;
        bottom:0;
        right:0;
        left:0;
       }

     .item-container {
         /*...*/
     }
}

Like this you can still benefit from some table cell properties like vertical-align. (Tested on Chrome)

How to get the text of the selected value of a dropdown list?

The easiest way is through css3 $("select option:selected") and then use the .text() or .html() function. depending on what you want to have.

The opposite of Intersect()

This code enumerates each sequence only once and uses Select(x => x) to hide the result to get a clean Linq-style extension method. Since it uses HashSet<T> its runtime is O(n + m) if the hashes are well distributed. Duplicate elements in either list are omitted.

public static IEnumerable<T> SymmetricExcept<T>(this IEnumerable<T> seq1,
    IEnumerable<T> seq2)
{
    HashSet<T> hashSet = new HashSet<T>(seq1);
    hashSet.SymmetricExceptWith(seq2);
    return hashSet.Select(x => x);
}

How to clamp an integer to some range?

If your code seems too unwieldy, a function might help:

def clamp(minvalue, value, maxvalue):
    return max(minvalue, min(value, maxvalue))

new_index = clamp(0, new_index, len(mylist)-1)

Reset input value in angular 2

If you want to clear the input by using the HTML ONLY, then you can do something like this:

<input type="text"
       (keyup)="0"
       #searchCollectorInput
       class="search-metrics"
       placeholder="Find">

Notice the importance of (keyup)=0 and the reference to the input of course.

Then reset it like this:

<span *ngIf="searchCollectorInput.value.length > 0"
      (click)="searchCollectorInput.value = ''"
      class="fa fa-close" ></span>

Is there a label/goto in Python?

Labels for break and continue were proposed in PEP 3136 back in 2007, but it was rejected. The Motivation section of the proposal illustrates several common (if inelegant) methods for imitating labeled break in Python.

How can I display a messagebox in ASP.NET?

you can use clientscript. MSDN : Clientscript

String scriptText = 
        "alert('sdsd');";
    ClientScript.RegisterOnSubmitStatement(this.GetType(), 
        "ConfirmSubmit", scriptText);

try this

ClientScript.RegisterStartupScript(this.GetType(), "JSScript", scriptText); 



ClientScript.RegisterClientScriptBlock(this.GetType(), "alert", scriptText); //use this 

codes for ADD,EDIT,DELETE,SEARCH in vb2010

A good resource start off point would be MSDN as your looking into a microsoft product

HTML: How to create a DIV with only vertical scroll-bars for long paragraphs?

This is my mix:

overflow-y: scroll;
height: 13em; // Initial height.
resize: vertical; // Allow user to change the vertical size.
max-height: 31em; // If you want to constrain the max size.

MySQL: ERROR 1227 (42000): Access denied - Cannot CREATE USER

First thing to do is run this:

SHOW GRANTS;

You will quickly see you were assigned the anonymous user to authenticate into mysql.

Instead of logging into mysql with

mysql

login like this:

mysql -uroot

By default, root@localhost has all rights and no password.

If you cannot login as root without a password, do the following:

Step 01) Add the two options in the mysqld section of my.ini:

[mysqld]
skip-grant-tables
skip-networking

Step 02) Restart mysql

net stop mysql
<wait 10 seconds>
net start mysql

Step 03) Connect to mysql

mysql

Step 04) Create a password from root@localhost

UPDATE mysql.user SET password=password('whateverpasswordyoulike')
WHERE user='root' AND host='localhost';
exit

Step 05) Restart mysql

net stop mysql
<wait 10 seconds>
net start mysql

Step 06) Login as root with password

mysql -u root -p

You should be good from there.

CAVEAT: Please remove anonymous users !!!

Render Partial View Using jQuery in ASP.NET MVC

Using standard Ajax call to achieve same result

        $.ajax({
            url: '@Url.Action("_SearchStudents")?NationalId=' + $('#NationalId').val(),
            type: 'GET',
            error: function (xhr) {
                alert('Error: ' + xhr.statusText);

            },
            success: function (result) {

                $('#divSearchResult').html(result);
            }
        });




public ActionResult _SearchStudents(string NationalId)
        {

           //.......

            return PartialView("_SearchStudents", model);
        }

How can I show a combobox in Android?

Here is an example of custom combobox in android:

package myWidgets;
import android.content.Context;
import android.database.Cursor;
import android.text.InputType;
import android.util.AttributeSet;
import android.view.View;
import android.widget.AutoCompleteTextView;
import android.widget.ImageButton;
import android.widget.LinearLayout;
import android.widget.SimpleCursorAdapter;

public class ComboBox extends LinearLayout {

   private AutoCompleteTextView _text;
   private ImageButton _button;

   public ComboBox(Context context) {
       super(context);
       this.createChildControls(context);
   }

   public ComboBox(Context context, AttributeSet attrs) {
       super(context, attrs);
       this.createChildControls(context);
}

 private void createChildControls(Context context) {
    this.setOrientation(HORIZONTAL);
    this.setLayoutParams(new LayoutParams(LayoutParams.FILL_PARENT,
                   LayoutParams.WRAP_CONTENT));

   _text = new AutoCompleteTextView(context);
   _text.setSingleLine();
   _text.setInputType(InputType.TYPE_CLASS_TEXT
                   | InputType.TYPE_TEXT_VARIATION_NORMAL
                   | InputType.TYPE_TEXT_FLAG_CAP_SENTENCES
                   | InputType.TYPE_TEXT_FLAG_AUTO_COMPLETE
                   | InputType.TYPE_TEXT_FLAG_AUTO_CORRECT);
   _text.setRawInputType(InputType.TYPE_TEXT_VARIATION_PASSWORD);
   this.addView(_text, new LayoutParams(LayoutParams.WRAP_CONTENT,
                   LayoutParams.WRAP_CONTENT, 1));

   _button = new ImageButton(context);
   _button.setImageResource(android.R.drawable.arrow_down_float);
   _button.setOnClickListener(new OnClickListener() {
           @Override
           public void onClick(View v) {
                   _text.showDropDown();
           }
   });
   this.addView(_button, new LayoutParams(LayoutParams.WRAP_CONTENT,
                   LayoutParams.WRAP_CONTENT));
 }

/**
    * Sets the source for DDLB suggestions.
    * Cursor MUST be managed by supplier!!
    * @param source Source of suggestions.
    * @param column Which column from source to show.
    */
 public void setSuggestionSource(Cursor source, String column) {
    String[] from = new String[] { column };
    int[] to = new int[] { android.R.id.text1 };
    SimpleCursorAdapter cursorAdapter = new SimpleCursorAdapter(this.getContext(),
                   android.R.layout.simple_dropdown_item_1line, source, from, to);
    // this is to ensure that when suggestion is selected
    // it provides the value to the textbox
    cursorAdapter.setStringConversionColumn(source.getColumnIndex(column));
    _text.setAdapter(cursorAdapter);
 }

/**
    * Gets the text in the combo box.
    *
    * @return Text.
    */
public String getText() {
    return _text.getText().toString();
 }

/**
    * Sets the text in combo box.
    */
public void setText(String text) {
    _text.setText(text);
   }
}

Hope it helps!!

WorksheetFunction.CountA - not working post upgrade to Office 2010

This answer from another forum solved the problem.

(substitute your own range for the "I:I" shown here)

Re: CountA not working in VBA

Should be:

Nonblank = Application.WorksheetFunction.CountA(Range("I:I"))

You have to refer to ranges in the vba format, not the in-excel format.

What does the "More Columns than Column Names" error mean?

For the Germans:

you have to change your decimal commas into a Full stop in your csv-file (in Excel:File -> Options -> Advanced -> "Decimal seperator") , then the error is solved.

JSON Parse File Path

var request = new XMLHttpRequest();
request.open("GET","<path_to_file>", false);
request.send(null);
var jsonData = JSON.parse(request.responseText);

This code worked for me.

PHP upload image

You need to add two new file one is index.html, copy and paste the below code and other is imageup.php which will upload your image

 <form action="imageup.php" method="post" enctype="multipart/form-data">
 <input type="file" name="banner" >
 <input type="submit" value="submit">
 </form>

 imageup.php
 <?php
 $banner=$_FILES['banner']['name']; 
 $expbanner=explode('.',$banner);
 $bannerexptype=$expbanner[1];
 date_default_timezone_set('Australia/Melbourne');
 $date = date('m/d/Yh:i:sa', time());
 $rand=rand(10000,99999);
 $encname=$date.$rand;
 $bannername=md5($encname).'.'.$bannerexptype;
 $bannerpath="uploads/banners/".$bannername;
 move_uploaded_file($_FILES["banner"]["tmp_name"],$bannerpath);
 ?>

The above code will upload your image with encrypted name

Getting the base url of the website and globally passing it to twig in Symfony 2

For current Symfony version (as of writing this answer it's Symfony 4.1) do not directly access the service container as done in some of the other answers.

Instead (unless you don't use the standard services configuration), inject the request object by type-hinting.

<?php

namespace App\Service;

use Symfony\Component\HttpFoundation\RequestStack;

/**
 * The YourService class provides a method for retrieving the base URL.
 *
 * @package App\Service
 */
class YourService
{

    /**
     * @var string
     */
    protected $baseUrl;

    /**
     * YourService constructor.
     *
     * @param \Symfony\Component\HttpFoundation\RequestStack $requestStack
     */
    public function __construct(RequestStack $requestStack)
    {
        $this->baseUrl = $requestStack->getCurrentRequest()->getSchemeAndHttpHost();
    }

    /**
     * Returns the current base URL.
     *
     * @return string
     */
    public function getBaseUrl(): string
    {
        return $this->baseUrl;
    }
}

See also official Symfony docs about how to retrieve the current request object.

Update span tag value with JQuery

Tag ids must be unique. You are updating the span with ID 'ItemCostSpan' of which there are two. Give the span a class and get it using find.

    $("legend").each(function() {
        var SoftwareItem = $(this).text();
        itemCost = GetItemCost(SoftwareItem);
        $("input:checked").each(function() {               
            var Component = $(this).next("label").text();
            itemCost += GetItemCost(Component);
        });            
        $(this).find(".ItemCostSpan").text("Item Cost = $ " + itemCost);
    });

How to find integer array size in java

Array's has

array.length

whereas List has

list.size()

Replace array.size() to array.length

How Can I Override Style Info from a CSS Class in the Body of a Page?

Eli, it is important to remember that in css specificity goes a long way. If your inline css is using the !important and isn't overriding the imported stylesheet rules then closely observe the code using a tool such as 'firebug' for firefox. It will show you the css being applied to your element. If there is a syntax error firebug will show you in the warning panel that it has thrown out the declaration.

Also remember that in general an id is more specific than a class is more specific than an element.

Hope that helps.

-Rick

Error:Cause: unable to find valid certification path to requested target

change dependencies from compile to Implementation in build.gradle file

Parsing CSV files in C#, with header

A CSV parser is now a part of .NET Framework.

Add a reference to Microsoft.VisualBasic.dll (works fine in C#, don't mind the name)

using (TextFieldParser parser = new TextFieldParser(@"c:\temp\test.csv"))
{
    parser.TextFieldType = FieldType.Delimited;
    parser.SetDelimiters(",");
    while (!parser.EndOfData)
    {
        //Process row
        string[] fields = parser.ReadFields();
        foreach (string field in fields)
        {
            //TODO: Process field
        }
    }
}

The docs are here - TextFieldParser Class

P.S. If you need a CSV exporter, try CsvExport (discl: I'm one of the contributors)

'JSON' is undefined error in JavaScript in Internet Explorer

<!DOCTYPE html>

Otherwise IE8 is not acting right. Also you should use:

<meta http-equiv="X-UA-Compatible" content="IE=EDGE" />

Regular expression: find spaces (tabs/space) but not newlines

Note: For those dealing with CJK text (Chinese, Japanese, and Korean), the double-byte space (Unicode \u3000) is not included in \s for any implementation I've tried so far (Perl, .NET, PCRE, Python). You'll need to either normalize your strings first (such as by replacing all \u3000 with \u0020), or you'll have to use a character set that includes this codepoint in addition to whatever other whitespace you're targeting, such as [ \t\u3000].

If you're using Perl or PCRE, you have the option of using the \h shorthand for horizontal whitespace, which appears to include the single-byte space, double-byte space, and tab, among others. See the Match whitespace but not newlines (Perl) thread for more detail.

However, this \h shorthand has not been implemented for .NET and C#, as best I've been able to tell.

How to remove duplicate white spaces in string using Java?

Though it is too late, I have found a better solution (that works for me) that will replace all consecutive same type white spaces with one white space of its type. That is:

   Hello!\n\n\nMy    World  

will be

 Hello!\nMy World 

Notice there are still leading and trailing white spaces. So my complete solution is:

str = str.trim().replaceAll("(\\s)+", "$1"));

Here, trim() replaces all leading and trailing white space strings with "". (\\s) is for capturing \\s (that is white spaces such as ' ', '\n', '\t') in group #1. + sign is for matching 1 or more preceding token. So (\\s)+ can be consecutive characters (1 or more) among any single white space characters (' ', '\n' or '\t'). $1 is for replacing the matching strings with the group #1 string (which only contains 1 white space character) of the matching type (that is the single white space character which has matched). The above solution will change like this:

   Hello!\n\n\nMy    World  

will be

Hello!\nMy World

I have not found my above solution here so I have posted it.

Using HTML data-attribute to set CSS background-image url

It is not best practise to mix up content with style, but a solution could be

<div class="thumb" style="background-image: url('images/img.jpg')"></div>

how to make a jquery "$.post" request synchronous

From the Jquery docs: you specify the async option to be false to get a synchronous Ajax request. Then your callback can set some data before your mother function proceeds.

Here's what your code would look like if changed as suggested:

beforecreate: function(node,targetNode,type,to) {
    jQuery.ajax({
         url:    url,
         success: function(result) {
                      if(result.isOk == false)
                          alert(result.message);
                  },
         async:   false
    });          
}

this is because $.ajax is the only request type that you can set the asynchronousity for

How to replace a whole line with sed?

sed -i.bak 's/\(aaa=\).*/\1"xxx"/g' your_file

How to fix a Div to top of page with CSS only

You can simply make the top div fixed:

#top { position: fixed; top: 20px; left: 20px; }

Bootstrap tab activation with JQuery

This one is quite straightforward from w3schools: https://www.w3schools.com/bootstrap/bootstrap_ref_js_tab.asp

// Select tab by name
$('.nav-tabs a[href="#home"]').tab('show')

// Select first tab
$('.nav-tabs a:first').tab('show') 

// Select last tab
$('.nav-tabs a:last').tab('show') 

// Select fourth tab (zero-based)
$('.nav-tabs li:eq(3) a').tab('show')

Regular expression to match non-ASCII characters?

All Unicode-enabled Regex flavours should have a special character class like \w that match any Unicode letter. Take a look at your specific flavour here.

How do you overcome the svn 'out of date' error?

Perform the move directly in the repository.

Linq filter List<string> where it contains a string value from another List<string>

its even easier:

fileList.Where(item => filterList.Contains(item))

in case you want to filter not for an exact match but for a "contains" you can use this expression:

var t = fileList.Where(file => filterList.Any(folder => file.ToUpperInvariant().Contains(folder.ToUpperInvariant())));

What's the difference between unit, functional, acceptance, and integration tests?

unit test: testing of individual module or independent component in an application is known to be unit testing , the unit testing will be done by developer.

integration test: combining all the modules and testing the application to verify the communication and the data flow between the modules are working properly or not , this testing also performed by developers.

funcional test checking the individual functionality of an application is mean to be functional testing

acceptance testing this testing is done by end user or customer whether the build application is according to the customer requirement , and customer specification this is known to be acceptance testing

Convert pandas Series to DataFrame

probably graded as a non-pythonic way to do this but this'll give the result you want in a line:

new_df = pd.DataFrame(zip(email,list))

Result:

               email               list
0   [email protected]    [1.0, 0.0, 0.0]
1   [email protected]    [2.0, 0.0, 0.0]
2   [email protected]    [1.0, 0.0, 0.0]
3   [email protected]    [4.0, 0.0, 3.0]
4   [email protected]    [1.0, 5.0, 0.0]

Make an Android button change background on click through XML

In the latest version of the SDK, you would use the setBackgroundResource method.

public void onClick(View v) {
   if(v == ButtonName) {
     ButtonName.setBackgroundResource(R.drawable.ImageResource);
   }
}

SQL Server 2008: TOP 10 and distinct together

select top 10 p.id from(select distinct p.id  from tablename)tablename

How to get complete month name from DateTime

If you receive "MMMM" as a response, probably you are getting the month and then converting it to a string of defined format.

DateTime.Now.Month.ToString("MMMM") 

will output "MMMM"

DateTime.Now.ToString("MMMM") 

will output the month name

Turn on IncludeExceptionDetailInFaults (either from ServiceBehaviorAttribute or from the <serviceDebug> configuration behavior) on the server

I was also getting the same error, the WCF was working properly for me when i was using it in the Dev Environment with my credentials, but when someone else was using it in TEST, it was throwing the same error. I did a lot of research, and then instead of doing config updates, handled an exception in the WCF method with the help of fault exception. Also the identity for the WCF needs to be set with the same credentials which are having access in the database, someone might have changed your authority. Please find below the code for the same:

 [ServiceContract]
public interface IService1
{
    [OperationContract]
    [FaultContract(typeof(ServiceData))]
    ForDataset GetCCDBdata();

    [OperationContract]
    [FaultContract(typeof(ServiceData))]
    string GetCCDBdataasXMLstring();


    //[OperationContract]
    //string GetData(int value);

    //[OperationContract]
    //CompositeType GetDataUsingDataContract(CompositeType composite);

    // TODO: Add your service operations here
}

  [DataContract]
public class ServiceData
{
    [DataMember]
    public bool Result { get; set; }
    [DataMember]
    public string ErrorMessage { get; set; }
    [DataMember]
    public string ErrorDetails { get; set; }
}

in your service1.svc.cs you can use this in the catch block:

 catch (Exception ex)
        {
            myServiceData.Result = false;
            myServiceData.ErrorMessage = "unforeseen error occured. Please try later.";
            myServiceData.ErrorDetails = ex.ToString();
            throw new FaultException<ServiceData>(myServiceData, ex.ToString());
        }

And use this in the Client application like below code:

  ConsoleApplicationWCFClient.CCDB_HIG_service.ForDataset ds = obj.GetCCDBdata();

            string str = obj.GetCCDBdataasXMLstring();

        }

        catch (FaultException<ConsoleApplicationWCFClient.CCDB_HIG_service.ServiceData> Fex)
      {
          Console.WriteLine("ErrorMessage::" + Fex.Detail.ErrorMessage + Environment.NewLine);
          Console.WriteLine("ErrorDetails::" + Environment.NewLine + Fex.Detail.ErrorDetails);
          Console.ReadLine();
      }

Just try this, it will help for sure to get the exact issue.

How to inspect Javascript Objects

There are few methods :

 1. typeof tells you which one of the 6 javascript types is the object. 
 2. instanceof tells you if the object is an instance of another object.
 3. List properties with for(var k in obj)
 4. Object.getOwnPropertyNames( anObjectToInspect ) 
 5. Object.getPrototypeOf( anObject )
 6. anObject.hasOwnProperty(aProperty) 

In a console context, sometimes the .constructor or .prototype maybe useful:

console.log(anObject.constructor ); 
console.log(anObject.prototype ) ; 

How to get ID of the last updated row in MySQL?

Query :

$sqlQuery = "UPDATE 
            update_table 
        SET 
            set_name = 'value' 
        WHERE 
            where_name = 'name'
        LIMIT 1;";

PHP function:

function updateAndGetId($sqlQuery)
{
    mysql_query(str_replace("SET", "SET id = LAST_INSERT_ID(id),", $sqlQuery));
    return mysql_insert_id();
}

It's work for me ;)

How to change password using TortoiseSVN?

You can't change your password through TortoiseSVN. Authentication to the SVN server has to be changed within the SVN server itself.

How you actually achieve this depends on which SVN Server is housing the repository and how the SVN Server was laid out on your computer.

n a Windows environment, credentials are typically stored in <yoursvnroot>\conf\passwd.

In a Linux environment it could be as above, or a myriad of other ways depending on how it's hosted.

JavaScript: client-side vs. server-side validation

The benefit of doing server side validation over client side validation is that client side validation can be bypassed/manipulated:

  • The end user could have javascript switched off
  • The data could be sent directly to your server by someone who's not even using your site, with a custom app designed to do so
  • A Javascript error on your page (caused by any number of things) could result in some, but not all, of your validation running

In short - always, always validate server-side and then consider client-side validation as an added "extra" to enhance the end user experience.

TypeError: p.easing[this.easing] is not a function

use the latest one for bootstrap 4 and above, this won't affect your UI

Cannot resolve symbol HttpGet,HttpClient,HttpResponce in Android Studio

please add these codes to your dependencies. It will work.

implementation 'org.jbundle.util.osgi.wrapped:org.jbundle.util.osgi.wrapped.org.apache.http.client:4.1.2'
dependencies {
    implementation fileTree(dir: 'libs', include: ['*.jar'])
    testCompile 'junit:junit:4.12'
    implementation 'com.android.support:appcompat-v7:23.1.0'
    implementation 'com.android.support:design:23.1.0'
    implementation 'com.android.support:cardview-v7:23.1.0'
    implementation 'com.android.support:recyclerview-v7:23.1.0'

    implementation 'org.jbundle.util.osgi.wrapped:org.jbundle.util.osgi.wrapped.org.apache.http.client:4.1.2'
}

Print string and variable contents on the same line in R

The {glue} package offers string interpolation. In the example, {wd} is substituted with the contents of the variable. Complex expressions are also supported.

library(glue)

wd <- getwd()
glue("Current working dir: {wd}")
#> Current working dir: /tmp/RtmpteMv88/reprex46156826ee8c

Created on 2019-05-13 by the reprex package (v0.2.1)

Note how the printed output doesn't contain the [1] artifacts and the " quotes, for which other answers use cat().

How to Export Private / Secret ASC Key to Decrypt GPG Files

Similar to @Wolfram J's answer, here is a method to encrypt your private key with a passphrase:

gpg --output - --armor --export $KEYID | \
    gpg --output private_key.asc --armor --symmetric --cipher-algo AES256

And a corresponding method to decrypt:

gpg private_key.asc

Git merge develop into feature branch outputs "Already up-to-date" while it's not

You should first pull the changes from the develop branch and only then merge them to your branch:

git checkout develop 
git pull 
git checkout branch-x
git rebase develop

Or, when on branch-x:

git fetch && git rebase origin/develop

I have an alias that saves me a lot of time. Add to your ~/.gitconfig:

[alias]
    fr = "!f() { git fetch && git rebase origin/"$1"; }; f"

Now, all that you have to do is:

git fr develop

Returning value that was passed into a method

The generic Returns<T> method can handle this situation nicely.

_mock.Setup(x => x.DoSomething(It.IsAny<string>())).Returns<string>(x => x);

Or if the method requires multiple inputs, specify them like so:

_mock.Setup(x => x.DoSomething(It.IsAny<string>(), It.IsAny<int>())).Returns((string x, int y) => x);

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

Remove Windows Service via Registry

Its very easy to remove a service from registry if you know the right path. Here is how I did that:

  1. Run Regedit or Regedt32

  2. Go to the registry entry "HKEY_LOCAL_MACHINE/SYSTEM/CurrentControlSet/Services"

  3. Look for the service that you want delete and delete it. You can look at the keys to know what files the service was using and delete them as well (if necessary).

Delete Windows Service via Command Window

Alternatively, you can also use command prompt and delete a service using following command:

sc delete

You can also create service by using following command

sc create "MorganTechService" binpath= "C:\Program Files\MorganTechSPace\myservice.exe"

Note: You may have to reboot the system to get the list updated in service manager.

IntelliJ Organize Imports

In IntelliJ 14, the path to the settings for Auto Import has changed. The path is

IntelliJ IDEA->Preferences->Editor->General->Auto Import

then follow the instructions above, clicking Add unambiguous imports on the fly

I can't imagine why this wouldn't be set by default.

VSCode Change Default Terminal

If you want to select the type of console, you can write this in the file "keybinding.json" (this file can be found in the following path "File-> Preferences-> Keyboard Shortcuts") `

//with this you can select what type of console you want
{
    "key": "ctrl+shift+t",
    "command": "shellLauncher.launch"
},

//and this will help you quickly change console
{ 
    "key": "ctrl+shift+j", 
    "command": "workbench.action.terminal.focusNext" 
},
{
    "key": "ctrl+shift+k", 
    "command": "workbench.action.terminal.focusPrevious" 
}`

Circle line-segment collision detection algorithm?

Circle is really a bad guy :) So a good way is to avoid true circle, if you can. If you are doing collision check for games you can go with some simplifications and have just 3 dot products, and a few comparisons.

I call this "fat point" or "thin circle". its kind of a ellipse with zero radius in a direction parallel to a segment. but full radius in a direction perpendicular to a segment

First, i would consider renaming and switching coordinate system to avoid excessive data:

s0s1 = B-A;
s0qp = C-A;
rSqr = r*r;

Second, index h in hvec2f means than vector must favor horisontal operations, like dot()/det(). Which means its components are to be placed in a separate xmm registers, to avoid shuffling/hadd'ing/hsub'ing. And here we go, with most performant version of simpliest collision detection for 2D game:

bool fat_point_collides_segment(const hvec2f& s0qp, const hvec2f& s0s1, const float& rSqr) {
    auto a = dot(s0s1, s0s1);
    //if( a != 0 ) // if you haven't zero-length segments omit this, as it would save you 1 _mm_comineq_ss() instruction and 1 memory fetch
    {
        auto b = dot(s0s1, s0qp);
        auto t = b / a; // length of projection of s0qp onto s0s1
        //std::cout << "t = " << t << "\n";
        if ((t >= 0) && (t <= 1)) // 
        {
            auto c = dot(s0qp, s0qp);
            auto r2 = c - a * t * t;
            return (r2 <= rSqr); // true if collides
        }
    }   
    return false;
}

I doubt you can optimize it any further. I am using it for neural-network driven car racing collision detection, to process millions of millions iteration steps.

$.ajax( type: "POST" POST method to php

You need to use data: {title: title} to POST it correctly.

In the PHP code you need to echo the value instead of returning it.

How to generate the JPA entity Metamodel?

Please take a look at jpa-metamodels-with-maven-example.

Hibernate

  • We need org.hibernate.org:hibernate-jpamodelgen.
  • The processor class is org.hibernate.jpamodelgen.JPAMetaModelEntityProcessor.

Hibernate as a dependency

    <dependency>
      <groupId>org.hibernate.orm</groupId>
      <artifactId>hibernate-jpamodelgen</artifactId>
      <version>${version.hibernate-jpamodelgen}</version>
      <scope>provided</scope>
    </dependency>

Hibernate as a processor

      <plugin>
        <groupId>org.bsc.maven</groupId>
        <artifactId>maven-processor-plugin</artifactId>
        <executions>
          <execution>
            <goals>
              <goal>process</goal>
            </goals>
            <phase>generate-sources</phase>
            <configuration>
              <compilerArguments>-AaddGeneratedAnnotation=false</compilerArguments> <!-- suppress java.annotation -->
              <processors>
                <processor>org.hibernate.jpamodelgen.JPAMetaModelEntityProcessor</processor>
              </processors>
            </configuration>
          </execution>
        </executions>
        <dependencies>
          <dependency>
            <groupId>org.hibernate.orm</groupId>
            <artifactId>hibernate-jpamodelgen</artifactId>
            <version>${version.hibernate-jpamodelgen}</version>
          </dependency>
        </dependencies>
      </plugin>

OpenJPA

  • We need org.apache.openjpa:openjpa.
  • The processor class is org.apache.openjpa.persistence.meta.AnnotationProcessor6.
  • OpenJPA seems require additional element <openjpa.metamodel>true<openjpa.metamodel>.

OpenJPA as a dependency

  <dependencies>
    <dependency>
      <groupId>org.apache.openjpa</groupId>
      <artifactId>openjpa</artifactId>
      <scope>provided</scope>
    </dependency>
  </dependencies>
  <build>
    <plugins>
      <plugin>
        <groupId>org.apache.maven.plugins</groupId>
        <artifactId>maven-compiler-plugin</artifactId>
        <configuration>
          <compilerArgs>
            <arg>-Aopenjpa.metamodel=true</arg>
          </compilerArgs>
        </configuration>
      </plugin>
    </plugins>
  </build>

OpenJPA as a processor

      <plugin>
        <groupId>org.bsc.maven</groupId>
        <artifactId>maven-processor-plugin</artifactId>
        <executions>
          <execution>
            <id>process</id>
            <goals>
              <goal>process</goal>
            </goals>
            <phase>generate-sources</phase>
            <configuration>
              <processors>
                <processor>org.apache.openjpa.persistence.meta.AnnotationProcessor6</processor>
              </processors>
              <optionMap>
                <openjpa.metamodel>true</openjpa.metamodel>
              </optionMap>
            </configuration>
          </execution>
        </executions>
        <dependencies>
          <dependency>
            <groupId>org.apache.openjpa</groupId>
            <artifactId>openjpa</artifactId>
            <version>${version.openjpa}</version>
          </dependency>
        </dependencies>
      </plugin>

EclipseLink

  • We need org.eclipse.persistence:org.eclipse.persistence.jpa.modelgen.processor.
  • The processor class is org.eclipse.persistence.internal.jpa.modelgen.CanonicalModelProcessor.
  • EclipseLink requires persistence.xml.

EclipseLink as a dependency

  <dependencies>
    <dependency>
      <groupId>org.eclipse.persistence</groupId>
      <artifactId>org.eclipse.persistence.jpa.modelgen.processor</artifactId>
      <scope>provided</scope>
    </dependency>

EclipseLink as a processor

    <plugins>
      <plugin>
        <groupId>org.bsc.maven</groupId>
        <artifactId>maven-processor-plugin</artifactId>
        <executions>
          <execution>
            <goals>
              <goal>process</goal>
            </goals>
            <phase>generate-sources</phase>
            <configuration>
              <processors>
                <processor>org.eclipse.persistence.internal.jpa.modelgen.CanonicalModelProcessor</processor>
              </processors>
              <compilerArguments>-Aeclipselink.persistencexml=src/main/resources-${environment.id}/META-INF/persistence.xml</compilerArguments>
            </configuration>
          </execution>
        </executions>
        <dependencies>
          <dependency>
            <groupId>org.eclipse.persistence</groupId>
            <artifactId>org.eclipse.persistence.jpa.modelgen.processor</artifactId>
            <version>${version.eclipselink}</version>
          </dependency>
        </dependencies>
      </plugin>

DataNucleus

  • We need org.datanucleus:datanucleus-jpa-query.
  • The processor class is org.datanucleus.jpa.query.JPACriteriaProcessor.

DataNucleus as a dependency

  <dependencies>
    <dependency>
      <groupId>org.datanucleus</groupId>
      <artifactId>datanucleus-jpa-query</artifactId>
      <scope>provided</scope>
    </dependency>
  </dependencies>

DataNucleus as a processor

      <plugin>
        <groupId>org.bsc.maven</groupId>
        <artifactId>maven-processor-plugin</artifactId>
        <executions>
          <execution>
            <id>process</id>
            <goals>
              <goal>process</goal>
            </goals>
            <phase>generate-sources</phase>
            <configuration>
              <processors>
                <processor>org.datanucleus.jpa.query.JPACriteriaProcessor</processor>
              </processors>
            </configuration>
          </execution>
        </executions>
        <dependencies>
          <dependency>
            <groupId>org.datanucleus</groupId>
            <artifactId>datanucleus-jpa-query</artifactId>
            <version>${version.datanucleus}</version>
          </dependency>
        </dependencies>
      </plugin>

How can Bash execute a command in a different directory context?

Use cd in a subshell; the shorthand way to use this kind of subshell is parentheses.

(cd wherever; mycommand ...)

That said, if your command has an environment that it requires, it should really ensure that environment itself instead of putting the onus on anything that might want to use it (unless it's an internal command used in very specific circumstances in the context of a well defined larger system, such that any caller already needs to ensure the environment it requires). Usually this would be some kind of shell script wrapper.

JavaScript: undefined !== undefined?

It turns out that you can set window.undefined to whatever you want, and so get object.x !== undefined when object.x is the real undefined. In my case I inadvertently set undefined to null.

The easiest way to see this happen is:

window.undefined = null;
alert(window.xyzw === undefined); // shows false

Of course, this is not likely to happen. In my case the bug was a little more subtle, and was equivalent to the following scenario.

var n = window.someName; // someName expected to be set but is actually undefined
window[n]=null; // I thought I was clearing the old value but was actually changing window.undefined to null
alert(window.xyzw === undefined); // shows false

Parse XML document in C#

Try this:

XmlDocument doc = new XmlDocument();
doc.Load(@"C:\Path\To\Xml\File.xml");

Or alternatively if you have the XML in a string use the LoadXml method.

Once you have it loaded, you can use SelectNodes and SelectSingleNode to query specific values, for example:

XmlNode node = doc.SelectSingleNode("//Company/Email/text()");
// node.Value contains "[email protected]"

Finally, note that your XML is invalid as it doesn't contain a single root node. It must be something like this:

<Data>
    <Employee>
        <Name>Test</Name>
        <ID>123</ID>
    </Employee>
    <Company>
        <Name>ABC</Name>
        <Email>[email protected]</Email>
    </Company>
</Data>

Finding even or odd ID values

For finding the even number we should use

select num from table where ( num % 2 ) = 0

How can I detect keydown or keypress event in angular.js?

Update:

ngKeypress, ngKeydown and ngKeyup are now part of AngularJS.

<!-- you can, for example, specify an expression to evaluate -->
<input ng-keypress="count = count + 1" ng-init="count=0">

<!-- or call a controller/directive method and pass $event as parameter.
     With access to $event you can now do stuff like 
     finding which key was pressed -->
<input ng-keypress="changed($event)">

Read more here:

https://docs.angularjs.org/api/ng/directive/ngKeypress https://docs.angularjs.org/api/ng/directive/ngKeydown https://docs.angularjs.org/api/ng/directive/ngKeyup

Earlier solutions:

Solution 1: Use ng-change with ng-model

<input type="text" placeholder="+639178983214" ng-model="mobileNumber" 
ng-controller="RegisterDataController" ng-change="keydown()">

JS:

function RegisterDataController($scope) {       
   $scope.keydown = function() {
        /* validate $scope.mobileNumber here*/
   };
}

Solution 2. Use $watch

<input type="text" placeholder="+639178983214" ng-model="mobileNumber" 
ng-controller="RegisterDataController">
    

JS:

$scope.$watch("mobileNumber", function(newValue, oldValue) {
    /* change noticed */
});

Splitting String and put it on int array

List<String> stringList = new ArrayList<String>(Arrays.asList(arr.split(",")));
List<Integer> intList = new ArrayList<Integer>();
for (String s : stringList) 
   intList.add(Integer.valueOf(s));

Check for false

If you want it to check explicit for it to not be false (boolean value) you have to use

if(borrar() !== false)

But in JavaScript we usually use falsy and truthy and you could use

if(!borrar())

but then values 0, '', null, undefined, null and NaN would not generate the alert.

The following values are always falsy:

false,
,0 (zero)
,'' or "" (empty string)
,null
,undefined
,NaN

Everything else is truthy. That includes:

'0' (a string containing a single zero)
,'false' (a string containing the text “false”)
,[] (an empty array)
,{} (an empty object)
,function(){} (an “empty” function)

Source: https://www.sitepoint.com/javascript-truthy-falsy/

As an extra perk to convert any value to true or false (boolean type), use double exclamation mark:

!![] === true
!!'false' === true
!!false === false
!!undefined === false

React Hook Warnings for async function in useEffect: useEffect function must return a cleanup function or nothing

try

_x000D_
_x000D_
const MyFunctionnalComponent: React.FC = props => {_x000D_
  useEffect(() => {_x000D_
    // Using an IIFE_x000D_
    (async function anyNameFunction() {_x000D_
      await loadContent();_x000D_
    })();_x000D_
  }, []);_x000D_
  return <div></div>;_x000D_
};
_x000D_
_x000D_
_x000D_

What's the difference between isset() and array_key_exists()?

Answer to an old question as no answer here seem to address the 'warning' problem (explanation follows)

Basically, in this case of checking if a key exists in an array, isset

  • tells if the expression (array) is defined, and the key is set
  • no warning or error if the var is not defined, not an array ...
  • but returns false if the value for that key is null

and array_key_exists

  • tells if a key exists in an array as the name implies
  • but gives a warning if the array parameter is not an array

So how do we check if a key exists which value may be null in a variable

  • that may or may not be an array
  • (or similarly is a multidimensional array for which the key check happens at dim 2 and dim 1 value may not be an array for the 1st dim (etc...))

without getting a warning, without missing the existing key when its value is null (what were the PHP devs thinking would also be an interesting question, but certainly not relevant on SO). And of course we don't want to use @

isset($var[$key]);            // silent but misses null values
array_key_exists($key, $var); // works but warning if $var not defined/array

It seems is_array should be involved in the equation, but it gives a warning if $var is not defined, so that could be a solution:

if (isset($var[$key]) || 
    isset($var) && is_array($var) && array_key_exists($key, $var)) ...

which is likely to be faster if the tests are mainly on non-null values. Otherwise for an array with mostly null values

if (isset($var) && is_array($var) && array_key_exists($key, $var)) ...

will do the work.

How to remove non UTF-8 characters from text file

This command:

iconv -f utf-8 -t utf-8 -c file.txt

will clean up your UTF-8 file, skipping all the invalid characters.

-f is the source format
-t the target format
-c skips any invalid sequence

html5 - canvas element - Multiple layers

I was having this same problem too, I while multiple canvas elements with position:absolute does the job, if you want to save the output into an image, that's not going to work.

So I went ahead and did a simple layering "system" to code as if each layer had its own code, but it all gets rendered into the same element.

https://github.com/federicojacobi/layeredCanvas

I intend to add extra capabilities, but for now it will do.

You can do multiple functions and call them in order to "fake" layers.

how to realize countifs function (excel) in R

Easy peasy. Your data frame will look like this:

df <- data.frame(sex=c('M','F','M'),
                 occupation=c('Student','Analyst','Analyst'))

You can then do the equivalent of a COUNTIF by first specifying the IF part, like so:

df$sex == 'M'

This will give you a boolean vector, i.e. a vector of TRUE and FALSE. What you want is to count the observations for which the condition is TRUE. Since in R TRUE and FALSE double as 1 and 0 you can simply sum() over the boolean vector. The equivalent of COUNTIF(sex='M') is therefore

sum(df$sex == 'M')

Should there be rows in which the sex is not specified the above will give back NA. In that case, if you just want to ignore the missing observations use

sum(df$sex == 'M', na.rm=TRUE)

Converting a double to an int in C#

ToInt32 rounds. Casting to int just throws away the non-integer component.

3 column layout HTML/CSS

CSS:

     .container div{
 width: 33.33%;
 float: left;
 height: 100px ;} 

Clear floats after the columns

 .container:after {
 content: "";
 display: table;
 clear: both;}

Close window automatically after printing dialog closes

This is what worked for me (2018/02). I needed a seperate request because my print wansn't yet on screen. Based on some of the excellent responses above, for which i thank you all, i noticed:

  • w.onload must not be set before w.document.write(data).
    It seems strange because you would want to set the hook beforehand. My guess: the hook is fired already when opening the window without content. Since it's fired, it won't fire again. But, when there is still processing going on with a new document.write() then the hook will be called when processing has finished.
  • w.document.close() still is required. Otherwise nothing happens.

I've tested this in Chrome 64.0, IE11 (11.248), Edge 41.16299 (edgeHTML 16.16299), FF 58.0.1 . They will complain about popups, but it prints.

function on_request_print() {
  $.get('/some/page.html')
    .done(function(data) {
      console.log('data ready ' + data.length);
      var w = window.open();
      w.document.write(data);
      w.onload = function() {
        console.log('on.load fired')
        w.focus();
        w.print();
        w.close();
      }
      console.log('written data')
      //this seems to be the thing doing the trick
      w.document.close();
      console.log('document closed')
    })
}
<script src="https://ajax.googleapis.com/ajax/libs/jquery/2.1.1/jquery.min.js">
</script>
<a onclick="on_request_print();">Print rapportage</a>

Merge r brings error "'by' must specify uniquely valid columns"

Rather give names of the column on which you want to merge:

exporttab <- merge(x=dwd_nogap, y=dwd_gap, by.x='x1', by.y='x2', fill=-9999)

FormsAuthentication.SignOut() does not log the user out

Using two of the above postings by x64igor and Phil Haselden solved this:

1. x64igor gave the example to do the Logout:

  • You first need to Clear the Authentication Cookie and Session Cookie by passing back empty cookies in the Response to the Logout.

    public ActionResult LogOff()
    {
        FormsAuthentication.SignOut();
        Session.Clear();  // This may not be needed -- but can't hurt
        Session.Abandon();
    
        // Clear authentication cookie
        HttpCookie rFormsCookie = new HttpCookie( FormsAuthentication.FormsCookieName, "" );
        rFormsCookie.Expires = DateTime.Now.AddYears( -1 );
        Response.Cookies.Add( rFormsCookie );
    
        // Clear session cookie 
        HttpCookie rSessionCookie = new HttpCookie( "ASP.NET_SessionId", "" );
        rSessionCookie.Expires = DateTime.Now.AddYears( -1 );
        Response.Cookies.Add( rSessionCookie );
    

2. Phil Haselden gave the example above of how to prevent caching after logout:

  • You need to Invalidate the Cache on the Client Side via the Response.

        // Invalidate the Cache on the Client Side
        Response.Cache.SetCacheability( HttpCacheability.NoCache );
        Response.Cache.SetNoStore();
    
        // Redirect to the Home Page (that should be intercepted and redirected to the Login Page first)
        return RedirectToAction( "Index", "Home" ); 
    }
    

String to HtmlDocument

Using Html Agility Pack as suggested by SLaks, this becomes very easy:

string html = webClient.DownloadString(url);
var doc = new HtmlDocument();
doc.LoadHtml(html);

HtmlNode specificNode = doc.GetElementById("nodeId");
HtmlNodeCollection nodesMatchingXPath = doc.DocumentNode.SelectNodes("x/path/nodes");

How to export a CSV to Excel using Powershell

Why would you bother? Load your CSV into Excel like this:

$csv = Join-Path $env:TEMP "process.csv"
$xls = Join-Path $env:TEMP "process.xlsx"

$xl = New-Object -COM "Excel.Application"
$xl.Visible = $true

$wb = $xl.Workbooks.OpenText($csv)

$wb.SaveAs($xls, 51)

You just need to make sure that the CSV export uses the delimiter defined in your regional settings. Override with -Delimiter if need be.


Edit: A more general solution that should preserve the values from the CSV as plain text. Code for iterating over the CSV columns taken from here.

$csv = Join-Path $env:TEMP "input.csv"
$xls = Join-Path $env:TEMP "output.xlsx"

$xl = New-Object -COM "Excel.Application"
$xl.Visible = $true

$wb = $xl.Workbooks.Add()
$ws = $wb.Sheets.Item(1)

$ws.Cells.NumberFormat = "@"

$i = 1
Import-Csv $csv | ForEach-Object {
  $j = 1
  foreach ($prop in $_.PSObject.Properties) {
    if ($i -eq 1) {
      $ws.Cells.Item($i, $j++).Value = $prop.Name
    } else {
      $ws.Cells.Item($i, $j++).Value = $prop.Value
    }
  }
  $i++
}

$wb.SaveAs($xls, 51)
$wb.Close()

$xl.Quit()
[System.Runtime.Interopservices.Marshal]::ReleaseComObject($xl)

Obviously this second approach won't perform too well, because it's processing each cell individually.

How can I execute PHP code from the command line?

If you're going to do PHP in the command line, I recommend you install phpsh, a decent PHP shell. It's a lot more fun.

Anyway, the php command offers two switches to execute code from the command line:

-r <code>        Run PHP <code> without using script tags <?..?>
-R <code>        Run PHP <code> for every input line

You can use php's -r switch as such:

php -r 'echo function_exists("foo") ? "yes" : "no";'

The above PHP command above should output no and returns 0 as you can see:

>>> php -r 'echo function_exists("foo") ? "yes" : "no";'
no
>>> echo $? # print the return value of the previous command
0

Another funny switch is php -a:

-a               Run as interactive shell

It's sort of lame compared to phpsh, but if you don't want to install the awesome interactive shell for PHP made by Facebook to get tab completion, history, and so on, then use -a as such:

>>> php -a
Interactive shell

php > echo function_exists("foo") ? "yes" : "no";
no
php >

If it doesn't work on your box like on my boxes (tested on Ubuntu and Arch Linux), then probably your PHP setup is fuzzy or broken. If you run this command:

php -i | grep 'API'

You should see:

Server API => Command Line Interface

If you don't, this means that maybe another command will provides the CLI SAPI. Try php-cli; maybe it's a package or a command available in your OS.

If you do see that your php command uses the CLI (command-line interface) SAPI (Server API), then run php -h | grep code to find out which crazy switch - as this hasn't changed for year- allows to run code in your version/setup.

Another couple of examples, just to make sure it works on my boxes:

>>> php -r 'echo function_exists("sg_load") ? "yes" : "no";'
no
>>> php -r 'echo function_exists("print_r") ? "yes" : "no";'
yes

Also, note that it is possible that an extension is loaded in the CLI and not in the CGI or Apache SAPI. It is likely that several PHP SAPIs use different php.ini files, e.g., /etc/php/cli/php.ini vs. /etc/php/cgi/php.ini vs. /etc/php/apache/php.ini on a Gentoo Linux box. Find out which ini file is used with php -i | grep ini.

How to export JSON from MongoDB using Robomongo

I don't think robomongo have such a feature. So you better use mongodb function as mongoexport for a specific Collection.

http://docs.mongodb.org/manual/reference/program/mongoexport/#export-in-json-format

But if you are looking for a backup solution is better to use

mongodump / mongorestore

Can I load a UIImage from a URL?

You can try SDWebImage, it provides:

  1. Asynchronous loading
  2. Caching for offline use
  3. Place holder image to appear while loading
  4. Works well with UITableView

Quick example:

    [cell.imageView setImageWithURL:[NSURL URLWithString:@"http://www.domain.com/path/to/image.jpg"] placeholderImage:[UIImage imageNamed:@"placeholder.png"]];

What do the terms "CPU bound" and "I/O bound" mean?

Another way to phrase the same idea:

  • If speeding up the CPU doesn't speed up your program, it may be I/O bound.

  • If speeding up the I/O (e.g. using a faster disk) doesn't help, your program may be CPU bound.

(I used "may be" because you need to take other resources into account. Memory is one example.)

How to use mongoimport to import csv

All these answers above are great. And the way to go on a full featured application.

But if you want to prototype fast, want flexibility as the collection still changes as well as to minimize your early code base, there is a much simpler way that is not much discussed.

You can basically forego mongoimport by now. I could have saved 3 hours if it was mentioned here on this question. So let me share for others:

Mongodb has a GUI called Mongo Compass has both csv and json import features out of the box in a matter of clicks. It is an official part of the Mongo ecosytem. At the time of writing it is free and it works very well for my use case. https://www.mongodb.com/products/compass

  1. You simply get MongoDB compass running on your machine by following the simple installation. A couple of fields for DB connection and authentication directly in the GUI.
  2. Import the csv/json file. It took less than a second on a 30KB file to be parsed before user (me) validates.
  3. Validate the "type" of each property. Great feature, I could directly mention the property types such as booleans, integers, etc. In my experience, they seem all default to string. You can update before importing. Dates were more finicky and needed special attention on the coding side.
  4. One click further the csv is a collection in your mongo db local or on the cloud. Voila!